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 debounced_delay;
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 debounced_delay::DebouncedDelay;
62use display_map::*;
63pub use display_map::{DisplayPoint, FoldPlaceholder};
64pub use editor_settings::{
65 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
66};
67pub use editor_settings_controls::*;
68use element::LineWithInvisibles;
69pub use element::{
70 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
71};
72use futures::{future, FutureExt};
73use fuzzy::{StringMatch, StringMatchCandidate};
74use git::blame::GitBlame;
75use gpui::{
76 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
77 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
78 ClipboardItem, Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent,
79 FocusableView, FontId, FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext,
80 ListSizingBehavior, Model, ModelContext, MouseButton, PaintQuad, ParentElement, Pixels, Render,
81 ScrollStrategy, SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task,
82 TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, View,
83 ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle, WeakView, WindowContext,
84};
85use highlight_matching_bracket::refresh_matching_bracket_highlights;
86use hover_popover::{hide_hover, HoverState};
87pub(crate) use hunk_diff::HoveredHunk;
88use hunk_diff::{diff_hunk_to_display, DiffMap, DiffMapSnapshot};
89use indent_guides::ActiveIndentGuidesState;
90use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
91pub use inline_completion::Direction;
92use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
93pub use items::MAX_TAB_TITLE_LEN;
94use itertools::Itertools;
95use language::{
96 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
97 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
98 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
99 Point, Selection, SelectionGoal, TransactionId,
100};
101use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
102use linked_editing_ranges::refresh_linked_ranges;
103pub use proposed_changes_editor::{
104 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
105};
106use similar::{ChangeTag, TextDiff};
107use std::iter::Peekable;
108use task::{ResolvedTask, TaskTemplate, TaskVariables};
109
110use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
111pub use lsp::CompletionContext;
112use lsp::{
113 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
114 LanguageServerId, LanguageServerName,
115};
116use mouse_context_menu::MouseContextMenu;
117use movement::TextLayoutDetails;
118pub use multi_buffer::{
119 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
120 ToPoint,
121};
122use multi_buffer::{
123 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
124};
125use ordered_float::OrderedFloat;
126use parking_lot::{Mutex, RwLock};
127use project::{
128 lsp_store::{FormatTarget, FormatTrigger},
129 project_settings::{GitGutterSetting, ProjectSettings},
130 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
131 Project, ProjectItem, ProjectTransaction, TaskSourceKind,
132};
133use rand::prelude::*;
134use rpc::{proto::*, ErrorExt};
135use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
136use selections_collection::{
137 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
138};
139use serde::{Deserialize, Serialize};
140use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
141use smallvec::SmallVec;
142use snippet::Snippet;
143use std::{
144 any::TypeId,
145 borrow::Cow,
146 cell::{Cell, RefCell},
147 cmp::{self, Ordering, Reverse},
148 mem,
149 num::NonZeroU32,
150 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
151 path::{Path, PathBuf},
152 rc::Rc,
153 sync::Arc,
154 time::{Duration, Instant},
155};
156pub use sum_tree::Bias;
157use sum_tree::TreeMap;
158use text::{BufferId, OffsetUtf16, Rope};
159use theme::{
160 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
161 ThemeColors, ThemeSettings,
162};
163use ui::{
164 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
165 ListItem, Popover, PopoverMenuHandle, Tooltip,
166};
167use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
168use workspace::item::{ItemHandle, PreviewTabsSettings};
169use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
170use workspace::{
171 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
172};
173use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
174
175use crate::hover_links::find_url;
176use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
177
178pub const FILE_HEADER_HEIGHT: u32 = 2;
179pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
180pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
181pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
182const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
183const MAX_LINE_LEN: usize = 1024;
184const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
185const MAX_SELECTION_HISTORY_LEN: usize = 1024;
186pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
187#[doc(hidden)]
188pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
189#[doc(hidden)]
190pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
191
192pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
193pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
194
195pub fn render_parsed_markdown(
196 element_id: impl Into<ElementId>,
197 parsed: &language::ParsedMarkdown,
198 editor_style: &EditorStyle,
199 workspace: Option<WeakView<Workspace>>,
200 cx: &mut WindowContext,
201) -> InteractiveText {
202 let code_span_background_color = cx
203 .theme()
204 .colors()
205 .editor_document_highlight_read_background;
206
207 let highlights = gpui::combine_highlights(
208 parsed.highlights.iter().filter_map(|(range, highlight)| {
209 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
210 Some((range.clone(), highlight))
211 }),
212 parsed
213 .regions
214 .iter()
215 .zip(&parsed.region_ranges)
216 .filter_map(|(region, range)| {
217 if region.code {
218 Some((
219 range.clone(),
220 HighlightStyle {
221 background_color: Some(code_span_background_color),
222 ..Default::default()
223 },
224 ))
225 } else {
226 None
227 }
228 }),
229 );
230
231 let mut links = Vec::new();
232 let mut link_ranges = Vec::new();
233 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
234 if let Some(link) = region.link.clone() {
235 links.push(link);
236 link_ranges.push(range.clone());
237 }
238 }
239
240 InteractiveText::new(
241 element_id,
242 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
243 )
244 .on_click(link_ranges, move |clicked_range_ix, cx| {
245 match &links[clicked_range_ix] {
246 markdown::Link::Web { url } => cx.open_url(url),
247 markdown::Link::Path { path } => {
248 if let Some(workspace) = &workspace {
249 _ = workspace.update(cx, |workspace, cx| {
250 workspace.open_abs_path(path.clone(), false, cx).detach();
251 });
252 }
253 }
254 }
255 })
256}
257
258#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
259pub(crate) enum InlayId {
260 Suggestion(usize),
261 Hint(usize),
262}
263
264impl InlayId {
265 fn id(&self) -> usize {
266 match self {
267 Self::Suggestion(id) => *id,
268 Self::Hint(id) => *id,
269 }
270 }
271}
272
273enum DiffRowHighlight {}
274enum DocumentHighlightRead {}
275enum DocumentHighlightWrite {}
276enum InputComposition {}
277
278#[derive(Debug, Copy, Clone, PartialEq, Eq)]
279pub enum Navigated {
280 Yes,
281 No,
282}
283
284impl Navigated {
285 pub fn from_bool(yes: bool) -> Navigated {
286 if yes {
287 Navigated::Yes
288 } else {
289 Navigated::No
290 }
291 }
292}
293
294pub fn init_settings(cx: &mut AppContext) {
295 EditorSettings::register(cx);
296}
297
298pub fn init(cx: &mut AppContext) {
299 init_settings(cx);
300
301 workspace::register_project_item::<Editor>(cx);
302 workspace::FollowableViewRegistry::register::<Editor>(cx);
303 workspace::register_serializable_item::<Editor>(cx);
304
305 cx.observe_new_views(
306 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
307 workspace.register_action(Editor::new_file);
308 workspace.register_action(Editor::new_file_vertical);
309 workspace.register_action(Editor::new_file_horizontal);
310 },
311 )
312 .detach();
313
314 cx.on_action(move |_: &workspace::NewFile, cx| {
315 let app_state = workspace::AppState::global(cx);
316 if let Some(app_state) = app_state.upgrade() {
317 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
318 Editor::new_file(workspace, &Default::default(), cx)
319 })
320 .detach();
321 }
322 });
323 cx.on_action(move |_: &workspace::NewWindow, cx| {
324 let app_state = workspace::AppState::global(cx);
325 if let Some(app_state) = app_state.upgrade() {
326 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
327 Editor::new_file(workspace, &Default::default(), cx)
328 })
329 .detach();
330 }
331 });
332 git::project_diff::init(cx);
333}
334
335pub struct SearchWithinRange;
336
337trait InvalidationRegion {
338 fn ranges(&self) -> &[Range<Anchor>];
339}
340
341#[derive(Clone, Debug, PartialEq)]
342pub enum SelectPhase {
343 Begin {
344 position: DisplayPoint,
345 add: bool,
346 click_count: usize,
347 },
348 BeginColumnar {
349 position: DisplayPoint,
350 reset: bool,
351 goal_column: u32,
352 },
353 Extend {
354 position: DisplayPoint,
355 click_count: usize,
356 },
357 Update {
358 position: DisplayPoint,
359 goal_column: u32,
360 scroll_delta: gpui::Point<f32>,
361 },
362 End,
363}
364
365#[derive(Clone, Debug)]
366pub enum SelectMode {
367 Character,
368 Word(Range<Anchor>),
369 Line(Range<Anchor>),
370 All,
371}
372
373#[derive(Copy, Clone, PartialEq, Eq, Debug)]
374pub enum EditorMode {
375 SingleLine { auto_width: bool },
376 AutoHeight { max_lines: usize },
377 Full,
378}
379
380#[derive(Copy, Clone, Debug)]
381pub enum SoftWrap {
382 /// Prefer not to wrap at all.
383 ///
384 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
385 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
386 GitDiff,
387 /// Prefer a single line generally, unless an overly long line is encountered.
388 None,
389 /// Soft wrap lines that exceed the editor width.
390 EditorWidth,
391 /// Soft wrap lines at the preferred line length.
392 Column(u32),
393 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
394 Bounded(u32),
395}
396
397#[derive(Clone)]
398pub struct EditorStyle {
399 pub background: Hsla,
400 pub local_player: PlayerColor,
401 pub text: TextStyle,
402 pub scrollbar_width: Pixels,
403 pub syntax: Arc<SyntaxTheme>,
404 pub status: StatusColors,
405 pub inlay_hints_style: HighlightStyle,
406 pub suggestions_style: HighlightStyle,
407 pub unnecessary_code_fade: f32,
408}
409
410impl Default for EditorStyle {
411 fn default() -> Self {
412 Self {
413 background: Hsla::default(),
414 local_player: PlayerColor::default(),
415 text: TextStyle::default(),
416 scrollbar_width: Pixels::default(),
417 syntax: Default::default(),
418 // HACK: Status colors don't have a real default.
419 // We should look into removing the status colors from the editor
420 // style and retrieve them directly from the theme.
421 status: StatusColors::dark(),
422 inlay_hints_style: HighlightStyle::default(),
423 suggestions_style: HighlightStyle::default(),
424 unnecessary_code_fade: Default::default(),
425 }
426 }
427}
428
429pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
430 let show_background = language_settings::language_settings(None, None, cx)
431 .inlay_hints
432 .show_background;
433
434 HighlightStyle {
435 color: Some(cx.theme().status().hint),
436 background_color: show_background.then(|| cx.theme().status().hint_background),
437 ..HighlightStyle::default()
438 }
439}
440
441type CompletionId = usize;
442
443enum InlineCompletion {
444 Edit(Vec<(Range<Anchor>, String)>),
445 Move(Anchor),
446}
447
448struct InlineCompletionState {
449 inlay_ids: Vec<InlayId>,
450 completion: InlineCompletion,
451 invalidation_range: Range<Anchor>,
452}
453
454enum InlineCompletionHighlight {}
455
456#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
457struct EditorActionId(usize);
458
459impl EditorActionId {
460 pub fn post_inc(&mut self) -> Self {
461 let answer = self.0;
462
463 *self = Self(answer + 1);
464
465 Self(answer)
466 }
467}
468
469// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
470// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
471
472type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
473type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
474
475#[derive(Default)]
476struct ScrollbarMarkerState {
477 scrollbar_size: Size<Pixels>,
478 dirty: bool,
479 markers: Arc<[PaintQuad]>,
480 pending_refresh: Option<Task<Result<()>>>,
481}
482
483impl ScrollbarMarkerState {
484 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
485 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
486 }
487}
488
489#[derive(Clone, Debug)]
490struct RunnableTasks {
491 templates: Vec<(TaskSourceKind, TaskTemplate)>,
492 offset: MultiBufferOffset,
493 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
494 column: u32,
495 // Values of all named captures, including those starting with '_'
496 extra_variables: HashMap<String, String>,
497 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
498 context_range: Range<BufferOffset>,
499}
500
501impl RunnableTasks {
502 fn resolve<'a>(
503 &'a self,
504 cx: &'a task::TaskContext,
505 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
506 self.templates.iter().filter_map(|(kind, template)| {
507 template
508 .resolve_task(&kind.to_id_base(), cx)
509 .map(|task| (kind.clone(), task))
510 })
511 }
512}
513
514#[derive(Clone)]
515struct ResolvedTasks {
516 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
517 position: Anchor,
518}
519#[derive(Copy, Clone, Debug)]
520struct MultiBufferOffset(usize);
521#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
522struct BufferOffset(usize);
523
524// Addons allow storing per-editor state in other crates (e.g. Vim)
525pub trait Addon: 'static {
526 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
527
528 fn to_any(&self) -> &dyn std::any::Any;
529}
530
531#[derive(Debug, Copy, Clone, PartialEq, Eq)]
532pub enum IsVimMode {
533 Yes,
534 No,
535}
536
537/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
538///
539/// See the [module level documentation](self) for more information.
540pub struct Editor {
541 focus_handle: FocusHandle,
542 last_focused_descendant: Option<WeakFocusHandle>,
543 /// The text buffer being edited
544 buffer: Model<MultiBuffer>,
545 /// Map of how text in the buffer should be displayed.
546 /// Handles soft wraps, folds, fake inlay text insertions, etc.
547 pub display_map: Model<DisplayMap>,
548 pub selections: SelectionsCollection,
549 pub scroll_manager: ScrollManager,
550 /// When inline assist editors are linked, they all render cursors because
551 /// typing enters text into each of them, even the ones that aren't focused.
552 pub(crate) show_cursor_when_unfocused: bool,
553 columnar_selection_tail: Option<Anchor>,
554 add_selections_state: Option<AddSelectionsState>,
555 select_next_state: Option<SelectNextState>,
556 select_prev_state: Option<SelectNextState>,
557 selection_history: SelectionHistory,
558 autoclose_regions: Vec<AutocloseRegion>,
559 snippet_stack: InvalidationStack<SnippetState>,
560 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
561 ime_transaction: Option<TransactionId>,
562 active_diagnostics: Option<ActiveDiagnosticGroup>,
563 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
564
565 project: Option<Model<Project>>,
566 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
567 completion_provider: Option<Box<dyn CompletionProvider>>,
568 collaboration_hub: Option<Box<dyn CollaborationHub>>,
569 blink_manager: Model<BlinkManager>,
570 show_cursor_names: bool,
571 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
572 pub show_local_selections: bool,
573 mode: EditorMode,
574 show_breadcrumbs: bool,
575 show_gutter: bool,
576 show_line_numbers: Option<bool>,
577 use_relative_line_numbers: Option<bool>,
578 show_git_diff_gutter: Option<bool>,
579 show_code_actions: Option<bool>,
580 show_runnables: Option<bool>,
581 show_wrap_guides: Option<bool>,
582 show_indent_guides: Option<bool>,
583 placeholder_text: Option<Arc<str>>,
584 highlight_order: usize,
585 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
586 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
587 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
588 scrollbar_marker_state: ScrollbarMarkerState,
589 active_indent_guides_state: ActiveIndentGuidesState,
590 nav_history: Option<ItemNavHistory>,
591 context_menu: RwLock<Option<ContextMenu>>,
592 mouse_context_menu: Option<MouseContextMenu>,
593 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
594 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
595 signature_help_state: SignatureHelpState,
596 auto_signature_help: Option<bool>,
597 find_all_references_task_sources: Vec<Anchor>,
598 next_completion_id: CompletionId,
599 available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
600 code_actions_task: Option<Task<Result<()>>>,
601 document_highlights_task: Option<Task<()>>,
602 linked_editing_range_task: Option<Task<Option<()>>>,
603 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
604 pending_rename: Option<RenameState>,
605 searchable: bool,
606 cursor_shape: CursorShape,
607 current_line_highlight: Option<CurrentLineHighlight>,
608 collapse_matches: bool,
609 autoindent_mode: Option<AutoindentMode>,
610 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
611 input_enabled: bool,
612 use_modal_editing: bool,
613 read_only: bool,
614 leader_peer_id: Option<PeerId>,
615 remote_id: Option<ViewId>,
616 hover_state: HoverState,
617 gutter_hovered: bool,
618 hovered_link_state: Option<HoveredLinkState>,
619 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
620 code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
621 active_inline_completion: Option<InlineCompletionState>,
622 // enable_inline_completions is a switch that Vim can use to disable
623 // inline completions based on its mode.
624 enable_inline_completions: bool,
625 show_inline_completions_override: Option<bool>,
626 inlay_hint_cache: InlayHintCache,
627 diff_map: DiffMap,
628 next_inlay_id: usize,
629 _subscriptions: Vec<Subscription>,
630 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
631 gutter_dimensions: GutterDimensions,
632 style: Option<EditorStyle>,
633 text_style_refinement: Option<TextStyleRefinement>,
634 next_editor_action_id: EditorActionId,
635 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
636 use_autoclose: bool,
637 use_auto_surround: bool,
638 auto_replace_emoji_shortcode: bool,
639 show_git_blame_gutter: bool,
640 show_git_blame_inline: bool,
641 show_git_blame_inline_delay_task: Option<Task<()>>,
642 git_blame_inline_enabled: bool,
643 serialize_dirty_buffers: bool,
644 show_selection_menu: Option<bool>,
645 blame: Option<Model<GitBlame>>,
646 blame_subscription: Option<Subscription>,
647 custom_context_menu: Option<
648 Box<
649 dyn 'static
650 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
651 >,
652 >,
653 last_bounds: Option<Bounds<Pixels>>,
654 expect_bounds_change: Option<Bounds<Pixels>>,
655 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
656 tasks_update_task: Option<Task<()>>,
657 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
658 breadcrumb_header: Option<String>,
659 focused_block: Option<FocusedBlock>,
660 next_scroll_position: NextScrollCursorCenterTopBottom,
661 addons: HashMap<TypeId, Box<dyn Addon>>,
662 _scroll_cursor_center_top_bottom_task: Task<()>,
663}
664
665#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
666enum NextScrollCursorCenterTopBottom {
667 #[default]
668 Center,
669 Top,
670 Bottom,
671}
672
673impl NextScrollCursorCenterTopBottom {
674 fn next(&self) -> Self {
675 match self {
676 Self::Center => Self::Top,
677 Self::Top => Self::Bottom,
678 Self::Bottom => Self::Center,
679 }
680 }
681}
682
683#[derive(Clone)]
684pub struct EditorSnapshot {
685 pub mode: EditorMode,
686 show_gutter: bool,
687 show_line_numbers: Option<bool>,
688 show_git_diff_gutter: Option<bool>,
689 show_code_actions: Option<bool>,
690 show_runnables: Option<bool>,
691 git_blame_gutter_max_author_length: Option<usize>,
692 pub display_snapshot: DisplaySnapshot,
693 pub placeholder_text: Option<Arc<str>>,
694 diff_map: DiffMapSnapshot,
695 is_focused: bool,
696 scroll_anchor: ScrollAnchor,
697 ongoing_scroll: OngoingScroll,
698 current_line_highlight: CurrentLineHighlight,
699 gutter_hovered: bool,
700}
701
702const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
703
704#[derive(Default, Debug, Clone, Copy)]
705pub struct GutterDimensions {
706 pub left_padding: Pixels,
707 pub right_padding: Pixels,
708 pub width: Pixels,
709 pub margin: Pixels,
710 pub git_blame_entries_width: Option<Pixels>,
711}
712
713impl GutterDimensions {
714 /// The full width of the space taken up by the gutter.
715 pub fn full_width(&self) -> Pixels {
716 self.margin + self.width
717 }
718
719 /// The width of the space reserved for the fold indicators,
720 /// use alongside 'justify_end' and `gutter_width` to
721 /// right align content with the line numbers
722 pub fn fold_area_width(&self) -> Pixels {
723 self.margin + self.right_padding
724 }
725}
726
727#[derive(Debug)]
728pub struct RemoteSelection {
729 pub replica_id: ReplicaId,
730 pub selection: Selection<Anchor>,
731 pub cursor_shape: CursorShape,
732 pub peer_id: PeerId,
733 pub line_mode: bool,
734 pub participant_index: Option<ParticipantIndex>,
735 pub user_name: Option<SharedString>,
736}
737
738#[derive(Clone, Debug)]
739struct SelectionHistoryEntry {
740 selections: Arc<[Selection<Anchor>]>,
741 select_next_state: Option<SelectNextState>,
742 select_prev_state: Option<SelectNextState>,
743 add_selections_state: Option<AddSelectionsState>,
744}
745
746enum SelectionHistoryMode {
747 Normal,
748 Undoing,
749 Redoing,
750}
751
752#[derive(Clone, PartialEq, Eq, Hash)]
753struct HoveredCursor {
754 replica_id: u16,
755 selection_id: usize,
756}
757
758impl Default for SelectionHistoryMode {
759 fn default() -> Self {
760 Self::Normal
761 }
762}
763
764#[derive(Default)]
765struct SelectionHistory {
766 #[allow(clippy::type_complexity)]
767 selections_by_transaction:
768 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
769 mode: SelectionHistoryMode,
770 undo_stack: VecDeque<SelectionHistoryEntry>,
771 redo_stack: VecDeque<SelectionHistoryEntry>,
772}
773
774impl SelectionHistory {
775 fn insert_transaction(
776 &mut self,
777 transaction_id: TransactionId,
778 selections: Arc<[Selection<Anchor>]>,
779 ) {
780 self.selections_by_transaction
781 .insert(transaction_id, (selections, None));
782 }
783
784 #[allow(clippy::type_complexity)]
785 fn transaction(
786 &self,
787 transaction_id: TransactionId,
788 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
789 self.selections_by_transaction.get(&transaction_id)
790 }
791
792 #[allow(clippy::type_complexity)]
793 fn transaction_mut(
794 &mut self,
795 transaction_id: TransactionId,
796 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
797 self.selections_by_transaction.get_mut(&transaction_id)
798 }
799
800 fn push(&mut self, entry: SelectionHistoryEntry) {
801 if !entry.selections.is_empty() {
802 match self.mode {
803 SelectionHistoryMode::Normal => {
804 self.push_undo(entry);
805 self.redo_stack.clear();
806 }
807 SelectionHistoryMode::Undoing => self.push_redo(entry),
808 SelectionHistoryMode::Redoing => self.push_undo(entry),
809 }
810 }
811 }
812
813 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
814 if self
815 .undo_stack
816 .back()
817 .map_or(true, |e| e.selections != entry.selections)
818 {
819 self.undo_stack.push_back(entry);
820 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
821 self.undo_stack.pop_front();
822 }
823 }
824 }
825
826 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
827 if self
828 .redo_stack
829 .back()
830 .map_or(true, |e| e.selections != entry.selections)
831 {
832 self.redo_stack.push_back(entry);
833 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
834 self.redo_stack.pop_front();
835 }
836 }
837 }
838}
839
840struct RowHighlight {
841 index: usize,
842 range: Range<Anchor>,
843 color: Hsla,
844 should_autoscroll: bool,
845}
846
847#[derive(Clone, Debug)]
848struct AddSelectionsState {
849 above: bool,
850 stack: Vec<usize>,
851}
852
853#[derive(Clone)]
854struct SelectNextState {
855 query: AhoCorasick,
856 wordwise: bool,
857 done: bool,
858}
859
860impl std::fmt::Debug for SelectNextState {
861 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
862 f.debug_struct(std::any::type_name::<Self>())
863 .field("wordwise", &self.wordwise)
864 .field("done", &self.done)
865 .finish()
866 }
867}
868
869#[derive(Debug)]
870struct AutocloseRegion {
871 selection_id: usize,
872 range: Range<Anchor>,
873 pair: BracketPair,
874}
875
876#[derive(Debug)]
877struct SnippetState {
878 ranges: Vec<Vec<Range<Anchor>>>,
879 active_index: usize,
880 choices: Vec<Option<Vec<String>>>,
881}
882
883#[doc(hidden)]
884pub struct RenameState {
885 pub range: Range<Anchor>,
886 pub old_name: Arc<str>,
887 pub editor: View<Editor>,
888 block_id: CustomBlockId,
889}
890
891struct InvalidationStack<T>(Vec<T>);
892
893struct RegisteredInlineCompletionProvider {
894 provider: Arc<dyn InlineCompletionProviderHandle>,
895 _subscription: Subscription,
896}
897
898enum ContextMenu {
899 Completions(CompletionsMenu),
900 CodeActions(CodeActionsMenu),
901}
902
903impl ContextMenu {
904 fn select_first(
905 &mut self,
906 provider: Option<&dyn CompletionProvider>,
907 cx: &mut ViewContext<Editor>,
908 ) -> bool {
909 if self.visible() {
910 match self {
911 ContextMenu::Completions(menu) => menu.select_first(provider, cx),
912 ContextMenu::CodeActions(menu) => menu.select_first(cx),
913 }
914 true
915 } else {
916 false
917 }
918 }
919
920 fn select_prev(
921 &mut self,
922 provider: Option<&dyn CompletionProvider>,
923 cx: &mut ViewContext<Editor>,
924 ) -> bool {
925 if self.visible() {
926 match self {
927 ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
928 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
929 }
930 true
931 } else {
932 false
933 }
934 }
935
936 fn select_next(
937 &mut self,
938 provider: Option<&dyn CompletionProvider>,
939 cx: &mut ViewContext<Editor>,
940 ) -> bool {
941 if self.visible() {
942 match self {
943 ContextMenu::Completions(menu) => menu.select_next(provider, cx),
944 ContextMenu::CodeActions(menu) => menu.select_next(cx),
945 }
946 true
947 } else {
948 false
949 }
950 }
951
952 fn select_last(
953 &mut self,
954 provider: Option<&dyn CompletionProvider>,
955 cx: &mut ViewContext<Editor>,
956 ) -> bool {
957 if self.visible() {
958 match self {
959 ContextMenu::Completions(menu) => menu.select_last(provider, cx),
960 ContextMenu::CodeActions(menu) => menu.select_last(cx),
961 }
962 true
963 } else {
964 false
965 }
966 }
967
968 fn visible(&self) -> bool {
969 match self {
970 ContextMenu::Completions(menu) => menu.visible(),
971 ContextMenu::CodeActions(menu) => menu.visible(),
972 }
973 }
974
975 fn render(
976 &self,
977 cursor_position: DisplayPoint,
978 style: &EditorStyle,
979 max_height: Pixels,
980 workspace: Option<WeakView<Workspace>>,
981 cx: &mut ViewContext<Editor>,
982 ) -> (ContextMenuOrigin, AnyElement) {
983 match self {
984 ContextMenu::Completions(menu) => (
985 ContextMenuOrigin::EditorPoint(cursor_position),
986 menu.render(style, max_height, workspace, cx),
987 ),
988 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
989 }
990 }
991}
992
993enum ContextMenuOrigin {
994 EditorPoint(DisplayPoint),
995 GutterIndicator(DisplayRow),
996}
997
998#[derive(Clone, Debug)]
999struct CompletionsMenu {
1000 id: CompletionId,
1001 sort_completions: bool,
1002 initial_position: Anchor,
1003 buffer: Model<Buffer>,
1004 completions: Arc<RwLock<Box<[Completion]>>>,
1005 match_candidates: Arc<[StringMatchCandidate]>,
1006 matches: Arc<[StringMatch]>,
1007 selected_item: usize,
1008 scroll_handle: UniformListScrollHandle,
1009 selected_completion_resolve_debounce: Option<Arc<Mutex<DebouncedDelay>>>,
1010 aside_was_displayed: Cell<bool>,
1011}
1012
1013impl CompletionsMenu {
1014 fn new(
1015 id: CompletionId,
1016 sort_completions: bool,
1017 initial_position: Anchor,
1018 buffer: Model<Buffer>,
1019 completions: Box<[Completion]>,
1020 ) -> Self {
1021 let match_candidates = completions
1022 .iter()
1023 .enumerate()
1024 .map(|(id, completion)| {
1025 StringMatchCandidate::new(
1026 id,
1027 completion.label.text[completion.label.filter_range.clone()].into(),
1028 )
1029 })
1030 .collect();
1031
1032 Self {
1033 id,
1034 sort_completions,
1035 initial_position,
1036 buffer,
1037 completions: Arc::new(RwLock::new(completions)),
1038 match_candidates,
1039 matches: Vec::new().into(),
1040 selected_item: 0,
1041 scroll_handle: UniformListScrollHandle::new(),
1042 selected_completion_resolve_debounce: Some(Arc::new(Mutex::new(DebouncedDelay::new()))),
1043 aside_was_displayed: Cell::new(false),
1044 }
1045 }
1046
1047 fn new_snippet_choices(
1048 id: CompletionId,
1049 sort_completions: bool,
1050 choices: &Vec<String>,
1051 selection: Range<Anchor>,
1052 buffer: Model<Buffer>,
1053 ) -> Self {
1054 let completions = choices
1055 .iter()
1056 .map(|choice| Completion {
1057 old_range: selection.start.text_anchor..selection.end.text_anchor,
1058 new_text: choice.to_string(),
1059 label: CodeLabel {
1060 text: choice.to_string(),
1061 runs: Default::default(),
1062 filter_range: Default::default(),
1063 },
1064 server_id: LanguageServerId(usize::MAX),
1065 documentation: None,
1066 lsp_completion: Default::default(),
1067 confirm: None,
1068 })
1069 .collect();
1070
1071 let match_candidates = choices
1072 .iter()
1073 .enumerate()
1074 .map(|(id, completion)| StringMatchCandidate::new(id, completion.to_string()))
1075 .collect();
1076 let matches = choices
1077 .iter()
1078 .enumerate()
1079 .map(|(id, completion)| StringMatch {
1080 candidate_id: id,
1081 score: 1.,
1082 positions: vec![],
1083 string: completion.clone(),
1084 })
1085 .collect();
1086 Self {
1087 id,
1088 sort_completions,
1089 initial_position: selection.start,
1090 buffer,
1091 completions: Arc::new(RwLock::new(completions)),
1092 match_candidates,
1093 matches,
1094 selected_item: 0,
1095 scroll_handle: UniformListScrollHandle::new(),
1096 selected_completion_resolve_debounce: Some(Arc::new(Mutex::new(DebouncedDelay::new()))),
1097 aside_was_displayed: Cell::new(false),
1098 }
1099 }
1100
1101 fn suppress_documentation_resolution(mut self) -> Self {
1102 self.selected_completion_resolve_debounce.take();
1103 self
1104 }
1105
1106 fn select_first(
1107 &mut self,
1108 provider: Option<&dyn CompletionProvider>,
1109 cx: &mut ViewContext<Editor>,
1110 ) {
1111 self.selected_item = 0;
1112 self.scroll_handle
1113 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1114 self.resolve_selected_completion(provider, cx);
1115 cx.notify();
1116 }
1117
1118 fn select_prev(
1119 &mut self,
1120 provider: Option<&dyn CompletionProvider>,
1121 cx: &mut ViewContext<Editor>,
1122 ) {
1123 if self.selected_item > 0 {
1124 self.selected_item -= 1;
1125 } else {
1126 self.selected_item = self.matches.len() - 1;
1127 }
1128 self.scroll_handle
1129 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1130 self.resolve_selected_completion(provider, cx);
1131 cx.notify();
1132 }
1133
1134 fn select_next(
1135 &mut self,
1136 provider: Option<&dyn CompletionProvider>,
1137 cx: &mut ViewContext<Editor>,
1138 ) {
1139 if self.selected_item + 1 < self.matches.len() {
1140 self.selected_item += 1;
1141 } else {
1142 self.selected_item = 0;
1143 }
1144 self.scroll_handle
1145 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1146 self.resolve_selected_completion(provider, cx);
1147 cx.notify();
1148 }
1149
1150 fn select_last(
1151 &mut self,
1152 provider: Option<&dyn CompletionProvider>,
1153 cx: &mut ViewContext<Editor>,
1154 ) {
1155 self.selected_item = self.matches.len() - 1;
1156 self.scroll_handle
1157 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1158 self.resolve_selected_completion(provider, cx);
1159 cx.notify();
1160 }
1161
1162 fn resolve_selected_completion(
1163 &mut self,
1164 provider: Option<&dyn CompletionProvider>,
1165 cx: &mut ViewContext<Editor>,
1166 ) {
1167 let completion_index = self.matches[self.selected_item].candidate_id;
1168 let Some(provider) = provider else {
1169 return;
1170 };
1171 let Some(completion_resolve) = self.selected_completion_resolve_debounce.as_ref() else {
1172 return;
1173 };
1174
1175 let resolve_task = provider.resolve_completions(
1176 self.buffer.clone(),
1177 vec![completion_index],
1178 self.completions.clone(),
1179 cx,
1180 );
1181
1182 let delay_ms =
1183 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1184 let delay = Duration::from_millis(delay_ms);
1185
1186 completion_resolve.lock().fire_new(delay, cx, |_, cx| {
1187 cx.spawn(move |editor, mut cx| async move {
1188 if let Some(true) = resolve_task.await.log_err() {
1189 editor.update(&mut cx, |_, cx| cx.notify()).ok();
1190 }
1191 })
1192 });
1193 }
1194
1195 fn visible(&self) -> bool {
1196 !self.matches.is_empty()
1197 }
1198
1199 fn render(
1200 &self,
1201 style: &EditorStyle,
1202 max_height: Pixels,
1203 workspace: Option<WeakView<Workspace>>,
1204 cx: &mut ViewContext<Editor>,
1205 ) -> AnyElement {
1206 let settings = EditorSettings::get_global(cx);
1207 let show_completion_documentation = settings.show_completion_documentation;
1208
1209 let widest_completion_ix = self
1210 .matches
1211 .iter()
1212 .enumerate()
1213 .max_by_key(|(_, mat)| {
1214 let completions = self.completions.read();
1215 let completion = &completions[mat.candidate_id];
1216 let documentation = &completion.documentation;
1217
1218 let mut len = completion.label.text.chars().count();
1219 if let Some(Documentation::SingleLine(text)) = documentation {
1220 if show_completion_documentation {
1221 len += text.chars().count();
1222 }
1223 }
1224
1225 len
1226 })
1227 .map(|(ix, _)| ix);
1228
1229 let completions = self.completions.clone();
1230 let matches = self.matches.clone();
1231 let selected_item = self.selected_item;
1232 let style = style.clone();
1233
1234 let multiline_docs = if show_completion_documentation {
1235 let mat = &self.matches[selected_item];
1236 match &self.completions.read()[mat.candidate_id].documentation {
1237 Some(Documentation::MultiLinePlainText(text)) => {
1238 Some(div().child(SharedString::from(text.clone())))
1239 }
1240 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1241 Some(div().child(render_parsed_markdown(
1242 "completions_markdown",
1243 parsed,
1244 &style,
1245 workspace,
1246 cx,
1247 )))
1248 }
1249 Some(Documentation::Undocumented) if self.aside_was_displayed.get() => {
1250 Some(div().child("No documentation"))
1251 }
1252 _ => None,
1253 }
1254 } else {
1255 None
1256 };
1257
1258 let aside_contents = if let Some(multiline_docs) = multiline_docs {
1259 Some(multiline_docs)
1260 } else if self.aside_was_displayed.get() {
1261 Some(div().child("Fetching documentation..."))
1262 } else {
1263 None
1264 };
1265 self.aside_was_displayed.set(aside_contents.is_some());
1266
1267 let aside_contents = aside_contents.map(|div| {
1268 div.id("multiline_docs")
1269 .max_h(max_height)
1270 .flex_1()
1271 .px_1p5()
1272 .py_1()
1273 .min_w(px(260.))
1274 .max_w(px(640.))
1275 .w(px(500.))
1276 .overflow_y_scroll()
1277 .occlude()
1278 });
1279
1280 let list = uniform_list(
1281 cx.view().clone(),
1282 "completions",
1283 matches.len(),
1284 move |_editor, range, cx| {
1285 let start_ix = range.start;
1286 let completions_guard = completions.read();
1287
1288 matches[range]
1289 .iter()
1290 .enumerate()
1291 .map(|(ix, mat)| {
1292 let item_ix = start_ix + ix;
1293 let candidate_id = mat.candidate_id;
1294 let completion = &completions_guard[candidate_id];
1295
1296 let documentation = if show_completion_documentation {
1297 &completion.documentation
1298 } else {
1299 &None
1300 };
1301
1302 let highlights = gpui::combine_highlights(
1303 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1304 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1305 |(range, mut highlight)| {
1306 // Ignore font weight for syntax highlighting, as we'll use it
1307 // for fuzzy matches.
1308 highlight.font_weight = None;
1309
1310 if completion.lsp_completion.deprecated.unwrap_or(false) {
1311 highlight.strikethrough = Some(StrikethroughStyle {
1312 thickness: 1.0.into(),
1313 ..Default::default()
1314 });
1315 highlight.color = Some(cx.theme().colors().text_muted);
1316 }
1317
1318 (range, highlight)
1319 },
1320 ),
1321 );
1322 let completion_label = StyledText::new(completion.label.text.clone())
1323 .with_highlights(&style.text, highlights);
1324 let documentation_label =
1325 if let Some(Documentation::SingleLine(text)) = documentation {
1326 if text.trim().is_empty() {
1327 None
1328 } else {
1329 Some(
1330 Label::new(text.clone())
1331 .ml_4()
1332 .size(LabelSize::Small)
1333 .color(Color::Muted),
1334 )
1335 }
1336 } else {
1337 None
1338 };
1339
1340 let color_swatch = completion
1341 .color()
1342 .map(|color| div().size_4().bg(color).rounded_sm());
1343
1344 div().min_w(px(220.)).max_w(px(540.)).child(
1345 ListItem::new(mat.candidate_id)
1346 .inset(true)
1347 .selected(item_ix == selected_item)
1348 .on_click(cx.listener(move |editor, _event, cx| {
1349 cx.stop_propagation();
1350 if let Some(task) = editor.confirm_completion(
1351 &ConfirmCompletion {
1352 item_ix: Some(item_ix),
1353 },
1354 cx,
1355 ) {
1356 task.detach_and_log_err(cx)
1357 }
1358 }))
1359 .start_slot::<Div>(color_swatch)
1360 .child(h_flex().overflow_hidden().child(completion_label))
1361 .end_slot::<Label>(documentation_label),
1362 )
1363 })
1364 .collect()
1365 },
1366 )
1367 .occlude()
1368 .max_h(max_height)
1369 .track_scroll(self.scroll_handle.clone())
1370 .with_width_from_item(widest_completion_ix)
1371 .with_sizing_behavior(ListSizingBehavior::Infer);
1372
1373 Popover::new()
1374 .child(list)
1375 .when_some(aside_contents, |popover, aside_contents| {
1376 popover.aside(aside_contents)
1377 })
1378 .into_any_element()
1379 }
1380
1381 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1382 let mut matches = if let Some(query) = query {
1383 fuzzy::match_strings(
1384 &self.match_candidates,
1385 query,
1386 query.chars().any(|c| c.is_uppercase()),
1387 100,
1388 &Default::default(),
1389 executor,
1390 )
1391 .await
1392 } else {
1393 self.match_candidates
1394 .iter()
1395 .enumerate()
1396 .map(|(candidate_id, candidate)| StringMatch {
1397 candidate_id,
1398 score: Default::default(),
1399 positions: Default::default(),
1400 string: candidate.string.clone(),
1401 })
1402 .collect()
1403 };
1404
1405 // Remove all candidates where the query's start does not match the start of any word in the candidate
1406 if let Some(query) = query {
1407 if let Some(query_start) = query.chars().next() {
1408 matches.retain(|string_match| {
1409 split_words(&string_match.string).any(|word| {
1410 // Check that the first codepoint of the word as lowercase matches the first
1411 // codepoint of the query as lowercase
1412 word.chars()
1413 .flat_map(|codepoint| codepoint.to_lowercase())
1414 .zip(query_start.to_lowercase())
1415 .all(|(word_cp, query_cp)| word_cp == query_cp)
1416 })
1417 });
1418 }
1419 }
1420
1421 let completions = self.completions.read();
1422 if self.sort_completions {
1423 matches.sort_unstable_by_key(|mat| {
1424 // We do want to strike a balance here between what the language server tells us
1425 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1426 // `Creat` and there is a local variable called `CreateComponent`).
1427 // So what we do is: we bucket all matches into two buckets
1428 // - Strong matches
1429 // - Weak matches
1430 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1431 // and the Weak matches are the rest.
1432 //
1433 // For the strong matches, we sort by our fuzzy-finder score first and for the weak
1434 // matches, we prefer language-server sort_text first.
1435 //
1436 // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
1437 // Rest of the matches(weak) can be sorted as language-server expects.
1438
1439 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1440 enum MatchScore<'a> {
1441 Strong {
1442 score: Reverse<OrderedFloat<f64>>,
1443 sort_text: Option<&'a str>,
1444 sort_key: (usize, &'a str),
1445 },
1446 Weak {
1447 sort_text: Option<&'a str>,
1448 score: Reverse<OrderedFloat<f64>>,
1449 sort_key: (usize, &'a str),
1450 },
1451 }
1452
1453 let completion = &completions[mat.candidate_id];
1454 let sort_key = completion.sort_key();
1455 let sort_text = completion.lsp_completion.sort_text.as_deref();
1456 let score = Reverse(OrderedFloat(mat.score));
1457
1458 if mat.score >= 0.2 {
1459 MatchScore::Strong {
1460 score,
1461 sort_text,
1462 sort_key,
1463 }
1464 } else {
1465 MatchScore::Weak {
1466 sort_text,
1467 score,
1468 sort_key,
1469 }
1470 }
1471 });
1472 }
1473
1474 for mat in &mut matches {
1475 let completion = &completions[mat.candidate_id];
1476 mat.string.clone_from(&completion.label.text);
1477 for position in &mut mat.positions {
1478 *position += completion.label.filter_range.start;
1479 }
1480 }
1481 drop(completions);
1482
1483 self.matches = matches.into();
1484 self.selected_item = 0;
1485 }
1486}
1487
1488#[derive(Clone)]
1489struct AvailableCodeAction {
1490 excerpt_id: ExcerptId,
1491 action: CodeAction,
1492 provider: Arc<dyn CodeActionProvider>,
1493}
1494
1495#[derive(Clone)]
1496struct CodeActionContents {
1497 tasks: Option<Arc<ResolvedTasks>>,
1498 actions: Option<Arc<[AvailableCodeAction]>>,
1499}
1500
1501impl CodeActionContents {
1502 fn len(&self) -> usize {
1503 match (&self.tasks, &self.actions) {
1504 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1505 (Some(tasks), None) => tasks.templates.len(),
1506 (None, Some(actions)) => actions.len(),
1507 (None, None) => 0,
1508 }
1509 }
1510
1511 fn is_empty(&self) -> bool {
1512 match (&self.tasks, &self.actions) {
1513 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1514 (Some(tasks), None) => tasks.templates.is_empty(),
1515 (None, Some(actions)) => actions.is_empty(),
1516 (None, None) => true,
1517 }
1518 }
1519
1520 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1521 self.tasks
1522 .iter()
1523 .flat_map(|tasks| {
1524 tasks
1525 .templates
1526 .iter()
1527 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1528 })
1529 .chain(self.actions.iter().flat_map(|actions| {
1530 actions.iter().map(|available| CodeActionsItem::CodeAction {
1531 excerpt_id: available.excerpt_id,
1532 action: available.action.clone(),
1533 provider: available.provider.clone(),
1534 })
1535 }))
1536 }
1537 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1538 match (&self.tasks, &self.actions) {
1539 (Some(tasks), Some(actions)) => {
1540 if index < tasks.templates.len() {
1541 tasks
1542 .templates
1543 .get(index)
1544 .cloned()
1545 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1546 } else {
1547 actions.get(index - tasks.templates.len()).map(|available| {
1548 CodeActionsItem::CodeAction {
1549 excerpt_id: available.excerpt_id,
1550 action: available.action.clone(),
1551 provider: available.provider.clone(),
1552 }
1553 })
1554 }
1555 }
1556 (Some(tasks), None) => tasks
1557 .templates
1558 .get(index)
1559 .cloned()
1560 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1561 (None, Some(actions)) => {
1562 actions
1563 .get(index)
1564 .map(|available| CodeActionsItem::CodeAction {
1565 excerpt_id: available.excerpt_id,
1566 action: available.action.clone(),
1567 provider: available.provider.clone(),
1568 })
1569 }
1570 (None, None) => None,
1571 }
1572 }
1573}
1574
1575#[allow(clippy::large_enum_variant)]
1576#[derive(Clone)]
1577enum CodeActionsItem {
1578 Task(TaskSourceKind, ResolvedTask),
1579 CodeAction {
1580 excerpt_id: ExcerptId,
1581 action: CodeAction,
1582 provider: Arc<dyn CodeActionProvider>,
1583 },
1584}
1585
1586impl CodeActionsItem {
1587 fn as_task(&self) -> Option<&ResolvedTask> {
1588 let Self::Task(_, task) = self else {
1589 return None;
1590 };
1591 Some(task)
1592 }
1593 fn as_code_action(&self) -> Option<&CodeAction> {
1594 let Self::CodeAction { action, .. } = self else {
1595 return None;
1596 };
1597 Some(action)
1598 }
1599 fn label(&self) -> String {
1600 match self {
1601 Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
1602 Self::Task(_, task) => task.resolved_label.clone(),
1603 }
1604 }
1605}
1606
1607struct CodeActionsMenu {
1608 actions: CodeActionContents,
1609 buffer: Model<Buffer>,
1610 selected_item: usize,
1611 scroll_handle: UniformListScrollHandle,
1612 deployed_from_indicator: Option<DisplayRow>,
1613}
1614
1615impl CodeActionsMenu {
1616 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1617 self.selected_item = 0;
1618 self.scroll_handle
1619 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1620 cx.notify()
1621 }
1622
1623 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1624 if self.selected_item > 0 {
1625 self.selected_item -= 1;
1626 } else {
1627 self.selected_item = self.actions.len() - 1;
1628 }
1629 self.scroll_handle
1630 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1631 cx.notify();
1632 }
1633
1634 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1635 if self.selected_item + 1 < self.actions.len() {
1636 self.selected_item += 1;
1637 } else {
1638 self.selected_item = 0;
1639 }
1640 self.scroll_handle
1641 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1642 cx.notify();
1643 }
1644
1645 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1646 self.selected_item = self.actions.len() - 1;
1647 self.scroll_handle
1648 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1649 cx.notify()
1650 }
1651
1652 fn visible(&self) -> bool {
1653 !self.actions.is_empty()
1654 }
1655
1656 fn render(
1657 &self,
1658 cursor_position: DisplayPoint,
1659 _style: &EditorStyle,
1660 max_height: Pixels,
1661 cx: &mut ViewContext<Editor>,
1662 ) -> (ContextMenuOrigin, AnyElement) {
1663 let actions = self.actions.clone();
1664 let selected_item = self.selected_item;
1665 let element = uniform_list(
1666 cx.view().clone(),
1667 "code_actions_menu",
1668 self.actions.len(),
1669 move |_this, range, cx| {
1670 actions
1671 .iter()
1672 .skip(range.start)
1673 .take(range.end - range.start)
1674 .enumerate()
1675 .map(|(ix, action)| {
1676 let item_ix = range.start + ix;
1677 let selected = selected_item == item_ix;
1678 let colors = cx.theme().colors();
1679 div()
1680 .px_1()
1681 .rounded_md()
1682 .text_color(colors.text)
1683 .when(selected, |style| {
1684 style
1685 .bg(colors.element_active)
1686 .text_color(colors.text_accent)
1687 })
1688 .hover(|style| {
1689 style
1690 .bg(colors.element_hover)
1691 .text_color(colors.text_accent)
1692 })
1693 .whitespace_nowrap()
1694 .when_some(action.as_code_action(), |this, action| {
1695 this.on_mouse_down(
1696 MouseButton::Left,
1697 cx.listener(move |editor, _, cx| {
1698 cx.stop_propagation();
1699 if let Some(task) = editor.confirm_code_action(
1700 &ConfirmCodeAction {
1701 item_ix: Some(item_ix),
1702 },
1703 cx,
1704 ) {
1705 task.detach_and_log_err(cx)
1706 }
1707 }),
1708 )
1709 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1710 .child(SharedString::from(
1711 action.lsp_action.title.replace("\n", ""),
1712 ))
1713 })
1714 .when_some(action.as_task(), |this, task| {
1715 this.on_mouse_down(
1716 MouseButton::Left,
1717 cx.listener(move |editor, _, cx| {
1718 cx.stop_propagation();
1719 if let Some(task) = editor.confirm_code_action(
1720 &ConfirmCodeAction {
1721 item_ix: Some(item_ix),
1722 },
1723 cx,
1724 ) {
1725 task.detach_and_log_err(cx)
1726 }
1727 }),
1728 )
1729 .child(SharedString::from(task.resolved_label.replace("\n", "")))
1730 })
1731 })
1732 .collect()
1733 },
1734 )
1735 .elevation_1(cx)
1736 .p_1()
1737 .max_h(max_height)
1738 .occlude()
1739 .track_scroll(self.scroll_handle.clone())
1740 .with_width_from_item(
1741 self.actions
1742 .iter()
1743 .enumerate()
1744 .max_by_key(|(_, action)| match action {
1745 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1746 CodeActionsItem::CodeAction { action, .. } => {
1747 action.lsp_action.title.chars().count()
1748 }
1749 })
1750 .map(|(ix, _)| ix),
1751 )
1752 .with_sizing_behavior(ListSizingBehavior::Infer)
1753 .into_any_element();
1754
1755 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1756 ContextMenuOrigin::GutterIndicator(row)
1757 } else {
1758 ContextMenuOrigin::EditorPoint(cursor_position)
1759 };
1760
1761 (cursor_position, element)
1762 }
1763}
1764
1765#[derive(Debug)]
1766struct ActiveDiagnosticGroup {
1767 primary_range: Range<Anchor>,
1768 primary_message: String,
1769 group_id: usize,
1770 blocks: HashMap<CustomBlockId, Diagnostic>,
1771 is_valid: bool,
1772}
1773
1774#[derive(Serialize, Deserialize, Clone, Debug)]
1775pub struct ClipboardSelection {
1776 pub len: usize,
1777 pub is_entire_line: bool,
1778 pub first_line_indent: u32,
1779}
1780
1781#[derive(Debug)]
1782pub(crate) struct NavigationData {
1783 cursor_anchor: Anchor,
1784 cursor_position: Point,
1785 scroll_anchor: ScrollAnchor,
1786 scroll_top_row: u32,
1787}
1788
1789#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1790pub enum GotoDefinitionKind {
1791 Symbol,
1792 Declaration,
1793 Type,
1794 Implementation,
1795}
1796
1797#[derive(Debug, Clone)]
1798enum InlayHintRefreshReason {
1799 Toggle(bool),
1800 SettingsChange(InlayHintSettings),
1801 NewLinesShown,
1802 BufferEdited(HashSet<Arc<Language>>),
1803 RefreshRequested,
1804 ExcerptsRemoved(Vec<ExcerptId>),
1805}
1806
1807impl InlayHintRefreshReason {
1808 fn description(&self) -> &'static str {
1809 match self {
1810 Self::Toggle(_) => "toggle",
1811 Self::SettingsChange(_) => "settings change",
1812 Self::NewLinesShown => "new lines shown",
1813 Self::BufferEdited(_) => "buffer edited",
1814 Self::RefreshRequested => "refresh requested",
1815 Self::ExcerptsRemoved(_) => "excerpts removed",
1816 }
1817 }
1818}
1819
1820pub(crate) struct FocusedBlock {
1821 id: BlockId,
1822 focus_handle: WeakFocusHandle,
1823}
1824
1825#[derive(Clone)]
1826struct JumpData {
1827 excerpt_id: ExcerptId,
1828 position: Point,
1829 anchor: text::Anchor,
1830 path: Option<project::ProjectPath>,
1831 line_offset_from_top: u32,
1832}
1833
1834impl Editor {
1835 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1836 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1837 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1838 Self::new(
1839 EditorMode::SingleLine { auto_width: false },
1840 buffer,
1841 None,
1842 false,
1843 cx,
1844 )
1845 }
1846
1847 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1848 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1849 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1850 Self::new(EditorMode::Full, buffer, None, false, cx)
1851 }
1852
1853 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1854 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1855 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1856 Self::new(
1857 EditorMode::SingleLine { auto_width: true },
1858 buffer,
1859 None,
1860 false,
1861 cx,
1862 )
1863 }
1864
1865 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1866 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1867 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1868 Self::new(
1869 EditorMode::AutoHeight { max_lines },
1870 buffer,
1871 None,
1872 false,
1873 cx,
1874 )
1875 }
1876
1877 pub fn for_buffer(
1878 buffer: Model<Buffer>,
1879 project: Option<Model<Project>>,
1880 cx: &mut ViewContext<Self>,
1881 ) -> Self {
1882 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1883 Self::new(EditorMode::Full, buffer, project, false, cx)
1884 }
1885
1886 pub fn for_multibuffer(
1887 buffer: Model<MultiBuffer>,
1888 project: Option<Model<Project>>,
1889 show_excerpt_controls: bool,
1890 cx: &mut ViewContext<Self>,
1891 ) -> Self {
1892 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1893 }
1894
1895 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1896 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1897 let mut clone = Self::new(
1898 self.mode,
1899 self.buffer.clone(),
1900 self.project.clone(),
1901 show_excerpt_controls,
1902 cx,
1903 );
1904 self.display_map.update(cx, |display_map, cx| {
1905 let snapshot = display_map.snapshot(cx);
1906 clone.display_map.update(cx, |display_map, cx| {
1907 display_map.set_state(&snapshot, cx);
1908 });
1909 });
1910 clone.selections.clone_state(&self.selections);
1911 clone.scroll_manager.clone_state(&self.scroll_manager);
1912 clone.searchable = self.searchable;
1913 clone
1914 }
1915
1916 pub fn new(
1917 mode: EditorMode,
1918 buffer: Model<MultiBuffer>,
1919 project: Option<Model<Project>>,
1920 show_excerpt_controls: bool,
1921 cx: &mut ViewContext<Self>,
1922 ) -> Self {
1923 let style = cx.text_style();
1924 let font_size = style.font_size.to_pixels(cx.rem_size());
1925 let editor = cx.view().downgrade();
1926 let fold_placeholder = FoldPlaceholder {
1927 constrain_width: true,
1928 render: Arc::new(move |fold_id, fold_range, cx| {
1929 let editor = editor.clone();
1930 div()
1931 .id(fold_id)
1932 .bg(cx.theme().colors().ghost_element_background)
1933 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1934 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1935 .rounded_sm()
1936 .size_full()
1937 .cursor_pointer()
1938 .child("⋯")
1939 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1940 .on_click(move |_, cx| {
1941 editor
1942 .update(cx, |editor, cx| {
1943 editor.unfold_ranges(
1944 &[fold_range.start..fold_range.end],
1945 true,
1946 false,
1947 cx,
1948 );
1949 cx.stop_propagation();
1950 })
1951 .ok();
1952 })
1953 .into_any()
1954 }),
1955 merge_adjacent: true,
1956 ..Default::default()
1957 };
1958 let display_map = cx.new_model(|cx| {
1959 DisplayMap::new(
1960 buffer.clone(),
1961 style.font(),
1962 font_size,
1963 None,
1964 show_excerpt_controls,
1965 FILE_HEADER_HEIGHT,
1966 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1967 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1968 fold_placeholder,
1969 cx,
1970 )
1971 });
1972
1973 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1974
1975 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1976
1977 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1978 .then(|| language_settings::SoftWrap::None);
1979
1980 let mut project_subscriptions = Vec::new();
1981 if mode == EditorMode::Full {
1982 if let Some(project) = project.as_ref() {
1983 if buffer.read(cx).is_singleton() {
1984 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1985 cx.emit(EditorEvent::TitleChanged);
1986 }));
1987 }
1988 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1989 if let project::Event::RefreshInlayHints = event {
1990 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1991 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1992 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1993 let focus_handle = editor.focus_handle(cx);
1994 if focus_handle.is_focused(cx) {
1995 let snapshot = buffer.read(cx).snapshot();
1996 for (range, snippet) in snippet_edits {
1997 let editor_range =
1998 language::range_from_lsp(*range).to_offset(&snapshot);
1999 editor
2000 .insert_snippet(&[editor_range], snippet.clone(), cx)
2001 .ok();
2002 }
2003 }
2004 }
2005 }
2006 }));
2007 if let Some(task_inventory) = project
2008 .read(cx)
2009 .task_store()
2010 .read(cx)
2011 .task_inventory()
2012 .cloned()
2013 {
2014 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
2015 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
2016 }));
2017 }
2018 }
2019 }
2020
2021 let buffer_snapshot = buffer.read(cx).snapshot(cx);
2022
2023 let inlay_hint_settings =
2024 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
2025 let focus_handle = cx.focus_handle();
2026 cx.on_focus(&focus_handle, Self::handle_focus).detach();
2027 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
2028 .detach();
2029 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
2030 .detach();
2031 cx.on_blur(&focus_handle, Self::handle_blur).detach();
2032
2033 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
2034 Some(false)
2035 } else {
2036 None
2037 };
2038
2039 let mut code_action_providers = Vec::new();
2040 if let Some(project) = project.clone() {
2041 get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
2042 code_action_providers.push(Arc::new(project) as Arc<_>);
2043 }
2044
2045 let mut this = Self {
2046 focus_handle,
2047 show_cursor_when_unfocused: false,
2048 last_focused_descendant: None,
2049 buffer: buffer.clone(),
2050 display_map: display_map.clone(),
2051 selections,
2052 scroll_manager: ScrollManager::new(cx),
2053 columnar_selection_tail: None,
2054 add_selections_state: None,
2055 select_next_state: None,
2056 select_prev_state: None,
2057 selection_history: Default::default(),
2058 autoclose_regions: Default::default(),
2059 snippet_stack: Default::default(),
2060 select_larger_syntax_node_stack: Vec::new(),
2061 ime_transaction: Default::default(),
2062 active_diagnostics: None,
2063 soft_wrap_mode_override,
2064 completion_provider: project.clone().map(|project| Box::new(project) as _),
2065 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
2066 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
2067 project,
2068 blink_manager: blink_manager.clone(),
2069 show_local_selections: true,
2070 mode,
2071 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
2072 show_gutter: mode == EditorMode::Full,
2073 show_line_numbers: None,
2074 use_relative_line_numbers: None,
2075 show_git_diff_gutter: None,
2076 show_code_actions: None,
2077 show_runnables: None,
2078 show_wrap_guides: None,
2079 show_indent_guides,
2080 placeholder_text: None,
2081 highlight_order: 0,
2082 highlighted_rows: HashMap::default(),
2083 background_highlights: Default::default(),
2084 gutter_highlights: TreeMap::default(),
2085 scrollbar_marker_state: ScrollbarMarkerState::default(),
2086 active_indent_guides_state: ActiveIndentGuidesState::default(),
2087 nav_history: None,
2088 context_menu: RwLock::new(None),
2089 mouse_context_menu: None,
2090 hunk_controls_menu_handle: PopoverMenuHandle::default(),
2091 completion_tasks: Default::default(),
2092 signature_help_state: SignatureHelpState::default(),
2093 auto_signature_help: None,
2094 find_all_references_task_sources: Vec::new(),
2095 next_completion_id: 0,
2096 next_inlay_id: 0,
2097 code_action_providers,
2098 available_code_actions: Default::default(),
2099 code_actions_task: Default::default(),
2100 document_highlights_task: Default::default(),
2101 linked_editing_range_task: Default::default(),
2102 pending_rename: Default::default(),
2103 searchable: true,
2104 cursor_shape: EditorSettings::get_global(cx)
2105 .cursor_shape
2106 .unwrap_or_default(),
2107 current_line_highlight: None,
2108 autoindent_mode: Some(AutoindentMode::EachLine),
2109 collapse_matches: false,
2110 workspace: None,
2111 input_enabled: true,
2112 use_modal_editing: mode == EditorMode::Full,
2113 read_only: false,
2114 use_autoclose: true,
2115 use_auto_surround: true,
2116 auto_replace_emoji_shortcode: false,
2117 leader_peer_id: None,
2118 remote_id: None,
2119 hover_state: Default::default(),
2120 hovered_link_state: Default::default(),
2121 inline_completion_provider: None,
2122 active_inline_completion: None,
2123 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
2124 diff_map: DiffMap::default(),
2125 gutter_hovered: false,
2126 pixel_position_of_newest_cursor: None,
2127 last_bounds: None,
2128 expect_bounds_change: None,
2129 gutter_dimensions: GutterDimensions::default(),
2130 style: None,
2131 show_cursor_names: false,
2132 hovered_cursors: Default::default(),
2133 next_editor_action_id: EditorActionId::default(),
2134 editor_actions: Rc::default(),
2135 show_inline_completions_override: None,
2136 enable_inline_completions: true,
2137 custom_context_menu: None,
2138 show_git_blame_gutter: false,
2139 show_git_blame_inline: false,
2140 show_selection_menu: None,
2141 show_git_blame_inline_delay_task: None,
2142 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
2143 serialize_dirty_buffers: ProjectSettings::get_global(cx)
2144 .session
2145 .restore_unsaved_buffers,
2146 blame: None,
2147 blame_subscription: None,
2148 tasks: Default::default(),
2149 _subscriptions: vec![
2150 cx.observe(&buffer, Self::on_buffer_changed),
2151 cx.subscribe(&buffer, Self::on_buffer_event),
2152 cx.observe(&display_map, Self::on_display_map_changed),
2153 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
2154 cx.observe_global::<SettingsStore>(Self::settings_changed),
2155 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
2156 cx.observe_window_activation(|editor, cx| {
2157 let active = cx.is_window_active();
2158 editor.blink_manager.update(cx, |blink_manager, cx| {
2159 if active {
2160 blink_manager.enable(cx);
2161 } else {
2162 blink_manager.disable(cx);
2163 }
2164 });
2165 }),
2166 ],
2167 tasks_update_task: None,
2168 linked_edit_ranges: Default::default(),
2169 previous_search_ranges: None,
2170 breadcrumb_header: None,
2171 focused_block: None,
2172 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
2173 addons: HashMap::default(),
2174 _scroll_cursor_center_top_bottom_task: Task::ready(()),
2175 text_style_refinement: None,
2176 };
2177 this.tasks_update_task = Some(this.refresh_runnables(cx));
2178 this._subscriptions.extend(project_subscriptions);
2179
2180 this.end_selection(cx);
2181 this.scroll_manager.show_scrollbar(cx);
2182
2183 if mode == EditorMode::Full {
2184 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
2185 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2186
2187 if this.git_blame_inline_enabled {
2188 this.git_blame_inline_enabled = true;
2189 this.start_git_blame_inline(false, cx);
2190 }
2191 }
2192
2193 this.report_editor_event("open", None, cx);
2194 this
2195 }
2196
2197 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
2198 self.mouse_context_menu
2199 .as_ref()
2200 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
2201 }
2202
2203 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
2204 let mut key_context = KeyContext::new_with_defaults();
2205 key_context.add("Editor");
2206 let mode = match self.mode {
2207 EditorMode::SingleLine { .. } => "single_line",
2208 EditorMode::AutoHeight { .. } => "auto_height",
2209 EditorMode::Full => "full",
2210 };
2211
2212 if EditorSettings::jupyter_enabled(cx) {
2213 key_context.add("jupyter");
2214 }
2215
2216 key_context.set("mode", mode);
2217 if self.pending_rename.is_some() {
2218 key_context.add("renaming");
2219 }
2220 if self.context_menu_visible() {
2221 match self.context_menu.read().as_ref() {
2222 Some(ContextMenu::Completions(_)) => {
2223 key_context.add("menu");
2224 key_context.add("showing_completions")
2225 }
2226 Some(ContextMenu::CodeActions(_)) => {
2227 key_context.add("menu");
2228 key_context.add("showing_code_actions")
2229 }
2230 None => {}
2231 }
2232 }
2233
2234 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2235 if !self.focus_handle(cx).contains_focused(cx)
2236 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2237 {
2238 for addon in self.addons.values() {
2239 addon.extend_key_context(&mut key_context, cx)
2240 }
2241 }
2242
2243 if let Some(extension) = self
2244 .buffer
2245 .read(cx)
2246 .as_singleton()
2247 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2248 {
2249 key_context.set("extension", extension.to_string());
2250 }
2251
2252 if self.has_active_inline_completion() {
2253 key_context.add("copilot_suggestion");
2254 key_context.add("inline_completion");
2255 }
2256
2257 key_context
2258 }
2259
2260 pub fn new_file(
2261 workspace: &mut Workspace,
2262 _: &workspace::NewFile,
2263 cx: &mut ViewContext<Workspace>,
2264 ) {
2265 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2266 "Failed to create buffer",
2267 cx,
2268 |e, _| match e.error_code() {
2269 ErrorCode::RemoteUpgradeRequired => Some(format!(
2270 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2271 e.error_tag("required").unwrap_or("the latest version")
2272 )),
2273 _ => None,
2274 },
2275 );
2276 }
2277
2278 pub fn new_in_workspace(
2279 workspace: &mut Workspace,
2280 cx: &mut ViewContext<Workspace>,
2281 ) -> Task<Result<View<Editor>>> {
2282 let project = workspace.project().clone();
2283 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2284
2285 cx.spawn(|workspace, mut cx| async move {
2286 let buffer = create.await?;
2287 workspace.update(&mut cx, |workspace, cx| {
2288 let editor =
2289 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2290 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2291 editor
2292 })
2293 })
2294 }
2295
2296 fn new_file_vertical(
2297 workspace: &mut Workspace,
2298 _: &workspace::NewFileSplitVertical,
2299 cx: &mut ViewContext<Workspace>,
2300 ) {
2301 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2302 }
2303
2304 fn new_file_horizontal(
2305 workspace: &mut Workspace,
2306 _: &workspace::NewFileSplitHorizontal,
2307 cx: &mut ViewContext<Workspace>,
2308 ) {
2309 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2310 }
2311
2312 fn new_file_in_direction(
2313 workspace: &mut Workspace,
2314 direction: SplitDirection,
2315 cx: &mut ViewContext<Workspace>,
2316 ) {
2317 let project = workspace.project().clone();
2318 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2319
2320 cx.spawn(|workspace, mut cx| async move {
2321 let buffer = create.await?;
2322 workspace.update(&mut cx, move |workspace, cx| {
2323 workspace.split_item(
2324 direction,
2325 Box::new(
2326 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2327 ),
2328 cx,
2329 )
2330 })?;
2331 anyhow::Ok(())
2332 })
2333 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2334 ErrorCode::RemoteUpgradeRequired => Some(format!(
2335 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2336 e.error_tag("required").unwrap_or("the latest version")
2337 )),
2338 _ => None,
2339 });
2340 }
2341
2342 pub fn leader_peer_id(&self) -> Option<PeerId> {
2343 self.leader_peer_id
2344 }
2345
2346 pub fn buffer(&self) -> &Model<MultiBuffer> {
2347 &self.buffer
2348 }
2349
2350 pub fn workspace(&self) -> Option<View<Workspace>> {
2351 self.workspace.as_ref()?.0.upgrade()
2352 }
2353
2354 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2355 self.buffer().read(cx).title(cx)
2356 }
2357
2358 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2359 let git_blame_gutter_max_author_length = self
2360 .render_git_blame_gutter(cx)
2361 .then(|| {
2362 if let Some(blame) = self.blame.as_ref() {
2363 let max_author_length =
2364 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2365 Some(max_author_length)
2366 } else {
2367 None
2368 }
2369 })
2370 .flatten();
2371
2372 EditorSnapshot {
2373 mode: self.mode,
2374 show_gutter: self.show_gutter,
2375 show_line_numbers: self.show_line_numbers,
2376 show_git_diff_gutter: self.show_git_diff_gutter,
2377 show_code_actions: self.show_code_actions,
2378 show_runnables: self.show_runnables,
2379 git_blame_gutter_max_author_length,
2380 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2381 scroll_anchor: self.scroll_manager.anchor(),
2382 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2383 placeholder_text: self.placeholder_text.clone(),
2384 diff_map: self.diff_map.snapshot(),
2385 is_focused: self.focus_handle.is_focused(cx),
2386 current_line_highlight: self
2387 .current_line_highlight
2388 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2389 gutter_hovered: self.gutter_hovered,
2390 }
2391 }
2392
2393 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2394 self.buffer.read(cx).language_at(point, cx)
2395 }
2396
2397 pub fn file_at<T: ToOffset>(
2398 &self,
2399 point: T,
2400 cx: &AppContext,
2401 ) -> Option<Arc<dyn language::File>> {
2402 self.buffer.read(cx).read(cx).file_at(point).cloned()
2403 }
2404
2405 pub fn active_excerpt(
2406 &self,
2407 cx: &AppContext,
2408 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2409 self.buffer
2410 .read(cx)
2411 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2412 }
2413
2414 pub fn mode(&self) -> EditorMode {
2415 self.mode
2416 }
2417
2418 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2419 self.collaboration_hub.as_deref()
2420 }
2421
2422 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2423 self.collaboration_hub = Some(hub);
2424 }
2425
2426 pub fn set_custom_context_menu(
2427 &mut self,
2428 f: impl 'static
2429 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2430 ) {
2431 self.custom_context_menu = Some(Box::new(f))
2432 }
2433
2434 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2435 self.completion_provider = provider;
2436 }
2437
2438 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2439 self.semantics_provider.clone()
2440 }
2441
2442 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2443 self.semantics_provider = provider;
2444 }
2445
2446 pub fn set_inline_completion_provider<T>(
2447 &mut self,
2448 provider: Option<Model<T>>,
2449 cx: &mut ViewContext<Self>,
2450 ) where
2451 T: InlineCompletionProvider,
2452 {
2453 self.inline_completion_provider =
2454 provider.map(|provider| RegisteredInlineCompletionProvider {
2455 _subscription: cx.observe(&provider, |this, _, cx| {
2456 if this.focus_handle.is_focused(cx) {
2457 this.update_visible_inline_completion(cx);
2458 }
2459 }),
2460 provider: Arc::new(provider),
2461 });
2462 self.refresh_inline_completion(false, false, cx);
2463 }
2464
2465 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2466 self.placeholder_text.as_deref()
2467 }
2468
2469 pub fn set_placeholder_text(
2470 &mut self,
2471 placeholder_text: impl Into<Arc<str>>,
2472 cx: &mut ViewContext<Self>,
2473 ) {
2474 let placeholder_text = Some(placeholder_text.into());
2475 if self.placeholder_text != placeholder_text {
2476 self.placeholder_text = placeholder_text;
2477 cx.notify();
2478 }
2479 }
2480
2481 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2482 self.cursor_shape = cursor_shape;
2483
2484 // Disrupt blink for immediate user feedback that the cursor shape has changed
2485 self.blink_manager.update(cx, BlinkManager::show_cursor);
2486
2487 cx.notify();
2488 }
2489
2490 pub fn set_current_line_highlight(
2491 &mut self,
2492 current_line_highlight: Option<CurrentLineHighlight>,
2493 ) {
2494 self.current_line_highlight = current_line_highlight;
2495 }
2496
2497 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2498 self.collapse_matches = collapse_matches;
2499 }
2500
2501 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2502 if self.collapse_matches {
2503 return range.start..range.start;
2504 }
2505 range.clone()
2506 }
2507
2508 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2509 if self.display_map.read(cx).clip_at_line_ends != clip {
2510 self.display_map
2511 .update(cx, |map, _| map.clip_at_line_ends = clip);
2512 }
2513 }
2514
2515 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2516 self.input_enabled = input_enabled;
2517 }
2518
2519 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2520 self.enable_inline_completions = enabled;
2521 }
2522
2523 pub fn set_autoindent(&mut self, autoindent: bool) {
2524 if autoindent {
2525 self.autoindent_mode = Some(AutoindentMode::EachLine);
2526 } else {
2527 self.autoindent_mode = None;
2528 }
2529 }
2530
2531 pub fn read_only(&self, cx: &AppContext) -> bool {
2532 self.read_only || self.buffer.read(cx).read_only()
2533 }
2534
2535 pub fn set_read_only(&mut self, read_only: bool) {
2536 self.read_only = read_only;
2537 }
2538
2539 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2540 self.use_autoclose = autoclose;
2541 }
2542
2543 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2544 self.use_auto_surround = auto_surround;
2545 }
2546
2547 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2548 self.auto_replace_emoji_shortcode = auto_replace;
2549 }
2550
2551 pub fn toggle_inline_completions(
2552 &mut self,
2553 _: &ToggleInlineCompletions,
2554 cx: &mut ViewContext<Self>,
2555 ) {
2556 if self.show_inline_completions_override.is_some() {
2557 self.set_show_inline_completions(None, cx);
2558 } else {
2559 let cursor = self.selections.newest_anchor().head();
2560 if let Some((buffer, cursor_buffer_position)) =
2561 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2562 {
2563 let show_inline_completions =
2564 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2565 self.set_show_inline_completions(Some(show_inline_completions), cx);
2566 }
2567 }
2568 }
2569
2570 pub fn set_show_inline_completions(
2571 &mut self,
2572 show_inline_completions: Option<bool>,
2573 cx: &mut ViewContext<Self>,
2574 ) {
2575 self.show_inline_completions_override = show_inline_completions;
2576 self.refresh_inline_completion(false, true, cx);
2577 }
2578
2579 fn should_show_inline_completions(
2580 &self,
2581 buffer: &Model<Buffer>,
2582 buffer_position: language::Anchor,
2583 cx: &AppContext,
2584 ) -> bool {
2585 if !self.snippet_stack.is_empty() {
2586 return false;
2587 }
2588
2589 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
2590 return false;
2591 }
2592
2593 if let Some(provider) = self.inline_completion_provider() {
2594 if let Some(show_inline_completions) = self.show_inline_completions_override {
2595 show_inline_completions
2596 } else {
2597 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2598 }
2599 } else {
2600 false
2601 }
2602 }
2603
2604 fn inline_completions_disabled_in_scope(
2605 &self,
2606 buffer: &Model<Buffer>,
2607 buffer_position: language::Anchor,
2608 cx: &AppContext,
2609 ) -> bool {
2610 let snapshot = buffer.read(cx).snapshot();
2611 let settings = snapshot.settings_at(buffer_position, cx);
2612
2613 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2614 return false;
2615 };
2616
2617 scope.override_name().map_or(false, |scope_name| {
2618 settings
2619 .inline_completions_disabled_in
2620 .iter()
2621 .any(|s| s == scope_name)
2622 })
2623 }
2624
2625 pub fn set_use_modal_editing(&mut self, to: bool) {
2626 self.use_modal_editing = to;
2627 }
2628
2629 pub fn use_modal_editing(&self) -> bool {
2630 self.use_modal_editing
2631 }
2632
2633 fn selections_did_change(
2634 &mut self,
2635 local: bool,
2636 old_cursor_position: &Anchor,
2637 show_completions: bool,
2638 cx: &mut ViewContext<Self>,
2639 ) {
2640 cx.invalidate_character_coordinates();
2641
2642 // Copy selections to primary selection buffer
2643 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2644 if local {
2645 let selections = self.selections.all::<usize>(cx);
2646 let buffer_handle = self.buffer.read(cx).read(cx);
2647
2648 let mut text = String::new();
2649 for (index, selection) in selections.iter().enumerate() {
2650 let text_for_selection = buffer_handle
2651 .text_for_range(selection.start..selection.end)
2652 .collect::<String>();
2653
2654 text.push_str(&text_for_selection);
2655 if index != selections.len() - 1 {
2656 text.push('\n');
2657 }
2658 }
2659
2660 if !text.is_empty() {
2661 cx.write_to_primary(ClipboardItem::new_string(text));
2662 }
2663 }
2664
2665 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2666 self.buffer.update(cx, |buffer, cx| {
2667 buffer.set_active_selections(
2668 &self.selections.disjoint_anchors(),
2669 self.selections.line_mode,
2670 self.cursor_shape,
2671 cx,
2672 )
2673 });
2674 }
2675 let display_map = self
2676 .display_map
2677 .update(cx, |display_map, cx| display_map.snapshot(cx));
2678 let buffer = &display_map.buffer_snapshot;
2679 self.add_selections_state = None;
2680 self.select_next_state = None;
2681 self.select_prev_state = None;
2682 self.select_larger_syntax_node_stack.clear();
2683 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2684 self.snippet_stack
2685 .invalidate(&self.selections.disjoint_anchors(), buffer);
2686 self.take_rename(false, cx);
2687
2688 let new_cursor_position = self.selections.newest_anchor().head();
2689
2690 self.push_to_nav_history(
2691 *old_cursor_position,
2692 Some(new_cursor_position.to_point(buffer)),
2693 cx,
2694 );
2695
2696 if local {
2697 let new_cursor_position = self.selections.newest_anchor().head();
2698 let mut context_menu = self.context_menu.write();
2699 let completion_menu = match context_menu.as_ref() {
2700 Some(ContextMenu::Completions(menu)) => Some(menu),
2701
2702 _ => {
2703 *context_menu = None;
2704 None
2705 }
2706 };
2707
2708 if let Some(completion_menu) = completion_menu {
2709 let cursor_position = new_cursor_position.to_offset(buffer);
2710 let (word_range, kind) =
2711 buffer.surrounding_word(completion_menu.initial_position, true);
2712 if kind == Some(CharKind::Word)
2713 && word_range.to_inclusive().contains(&cursor_position)
2714 {
2715 let mut completion_menu = completion_menu.clone();
2716 drop(context_menu);
2717
2718 let query = Self::completion_query(buffer, cursor_position);
2719 cx.spawn(move |this, mut cx| async move {
2720 completion_menu
2721 .filter(query.as_deref(), cx.background_executor().clone())
2722 .await;
2723
2724 this.update(&mut cx, |this, cx| {
2725 let mut context_menu = this.context_menu.write();
2726 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2727 return;
2728 };
2729
2730 if menu.id > completion_menu.id {
2731 return;
2732 }
2733
2734 *context_menu = Some(ContextMenu::Completions(completion_menu));
2735 drop(context_menu);
2736 cx.notify();
2737 })
2738 })
2739 .detach();
2740
2741 if show_completions {
2742 self.show_completions(&ShowCompletions { trigger: None }, cx);
2743 }
2744 } else {
2745 drop(context_menu);
2746 self.hide_context_menu(cx);
2747 }
2748 } else {
2749 drop(context_menu);
2750 }
2751
2752 hide_hover(self, cx);
2753
2754 if old_cursor_position.to_display_point(&display_map).row()
2755 != new_cursor_position.to_display_point(&display_map).row()
2756 {
2757 self.available_code_actions.take();
2758 }
2759 self.refresh_code_actions(cx);
2760 self.refresh_document_highlights(cx);
2761 refresh_matching_bracket_highlights(self, cx);
2762 self.update_visible_inline_completion(cx);
2763 linked_editing_ranges::refresh_linked_ranges(self, cx);
2764 if self.git_blame_inline_enabled {
2765 self.start_inline_blame_timer(cx);
2766 }
2767 }
2768
2769 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2770 cx.emit(EditorEvent::SelectionsChanged { local });
2771
2772 if self.selections.disjoint_anchors().len() == 1 {
2773 cx.emit(SearchEvent::ActiveMatchChanged)
2774 }
2775 cx.notify();
2776 }
2777
2778 pub fn change_selections<R>(
2779 &mut self,
2780 autoscroll: Option<Autoscroll>,
2781 cx: &mut ViewContext<Self>,
2782 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2783 ) -> R {
2784 self.change_selections_inner(autoscroll, true, cx, change)
2785 }
2786
2787 pub fn change_selections_inner<R>(
2788 &mut self,
2789 autoscroll: Option<Autoscroll>,
2790 request_completions: bool,
2791 cx: &mut ViewContext<Self>,
2792 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2793 ) -> R {
2794 let old_cursor_position = self.selections.newest_anchor().head();
2795 self.push_to_selection_history();
2796
2797 let (changed, result) = self.selections.change_with(cx, change);
2798
2799 if changed {
2800 if let Some(autoscroll) = autoscroll {
2801 self.request_autoscroll(autoscroll, cx);
2802 }
2803 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2804
2805 if self.should_open_signature_help_automatically(
2806 &old_cursor_position,
2807 self.signature_help_state.backspace_pressed(),
2808 cx,
2809 ) {
2810 self.show_signature_help(&ShowSignatureHelp, cx);
2811 }
2812 self.signature_help_state.set_backspace_pressed(false);
2813 }
2814
2815 result
2816 }
2817
2818 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2819 where
2820 I: IntoIterator<Item = (Range<S>, T)>,
2821 S: ToOffset,
2822 T: Into<Arc<str>>,
2823 {
2824 if self.read_only(cx) {
2825 return;
2826 }
2827
2828 self.buffer
2829 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2830 }
2831
2832 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2833 where
2834 I: IntoIterator<Item = (Range<S>, T)>,
2835 S: ToOffset,
2836 T: Into<Arc<str>>,
2837 {
2838 if self.read_only(cx) {
2839 return;
2840 }
2841
2842 self.buffer.update(cx, |buffer, cx| {
2843 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2844 });
2845 }
2846
2847 pub fn edit_with_block_indent<I, S, T>(
2848 &mut self,
2849 edits: I,
2850 original_indent_columns: Vec<u32>,
2851 cx: &mut ViewContext<Self>,
2852 ) where
2853 I: IntoIterator<Item = (Range<S>, T)>,
2854 S: ToOffset,
2855 T: Into<Arc<str>>,
2856 {
2857 if self.read_only(cx) {
2858 return;
2859 }
2860
2861 self.buffer.update(cx, |buffer, cx| {
2862 buffer.edit(
2863 edits,
2864 Some(AutoindentMode::Block {
2865 original_indent_columns,
2866 }),
2867 cx,
2868 )
2869 });
2870 }
2871
2872 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2873 self.hide_context_menu(cx);
2874
2875 match phase {
2876 SelectPhase::Begin {
2877 position,
2878 add,
2879 click_count,
2880 } => self.begin_selection(position, add, click_count, cx),
2881 SelectPhase::BeginColumnar {
2882 position,
2883 goal_column,
2884 reset,
2885 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2886 SelectPhase::Extend {
2887 position,
2888 click_count,
2889 } => self.extend_selection(position, click_count, cx),
2890 SelectPhase::Update {
2891 position,
2892 goal_column,
2893 scroll_delta,
2894 } => self.update_selection(position, goal_column, scroll_delta, cx),
2895 SelectPhase::End => self.end_selection(cx),
2896 }
2897 }
2898
2899 fn extend_selection(
2900 &mut self,
2901 position: DisplayPoint,
2902 click_count: usize,
2903 cx: &mut ViewContext<Self>,
2904 ) {
2905 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2906 let tail = self.selections.newest::<usize>(cx).tail();
2907 self.begin_selection(position, false, click_count, cx);
2908
2909 let position = position.to_offset(&display_map, Bias::Left);
2910 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2911
2912 let mut pending_selection = self
2913 .selections
2914 .pending_anchor()
2915 .expect("extend_selection not called with pending selection");
2916 if position >= tail {
2917 pending_selection.start = tail_anchor;
2918 } else {
2919 pending_selection.end = tail_anchor;
2920 pending_selection.reversed = true;
2921 }
2922
2923 let mut pending_mode = self.selections.pending_mode().unwrap();
2924 match &mut pending_mode {
2925 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2926 _ => {}
2927 }
2928
2929 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2930 s.set_pending(pending_selection, pending_mode)
2931 });
2932 }
2933
2934 fn begin_selection(
2935 &mut self,
2936 position: DisplayPoint,
2937 add: bool,
2938 click_count: usize,
2939 cx: &mut ViewContext<Self>,
2940 ) {
2941 if !self.focus_handle.is_focused(cx) {
2942 self.last_focused_descendant = None;
2943 cx.focus(&self.focus_handle);
2944 }
2945
2946 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2947 let buffer = &display_map.buffer_snapshot;
2948 let newest_selection = self.selections.newest_anchor().clone();
2949 let position = display_map.clip_point(position, Bias::Left);
2950
2951 let start;
2952 let end;
2953 let mode;
2954 let mut auto_scroll;
2955 match click_count {
2956 1 => {
2957 start = buffer.anchor_before(position.to_point(&display_map));
2958 end = start;
2959 mode = SelectMode::Character;
2960 auto_scroll = true;
2961 }
2962 2 => {
2963 let range = movement::surrounding_word(&display_map, position);
2964 start = buffer.anchor_before(range.start.to_point(&display_map));
2965 end = buffer.anchor_before(range.end.to_point(&display_map));
2966 mode = SelectMode::Word(start..end);
2967 auto_scroll = true;
2968 }
2969 3 => {
2970 let position = display_map
2971 .clip_point(position, Bias::Left)
2972 .to_point(&display_map);
2973 let line_start = display_map.prev_line_boundary(position).0;
2974 let next_line_start = buffer.clip_point(
2975 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2976 Bias::Left,
2977 );
2978 start = buffer.anchor_before(line_start);
2979 end = buffer.anchor_before(next_line_start);
2980 mode = SelectMode::Line(start..end);
2981 auto_scroll = true;
2982 }
2983 _ => {
2984 start = buffer.anchor_before(0);
2985 end = buffer.anchor_before(buffer.len());
2986 mode = SelectMode::All;
2987 auto_scroll = false;
2988 }
2989 }
2990 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2991
2992 let point_to_delete: Option<usize> = {
2993 let selected_points: Vec<Selection<Point>> =
2994 self.selections.disjoint_in_range(start..end, cx);
2995
2996 if !add || click_count > 1 {
2997 None
2998 } else if !selected_points.is_empty() {
2999 Some(selected_points[0].id)
3000 } else {
3001 let clicked_point_already_selected =
3002 self.selections.disjoint.iter().find(|selection| {
3003 selection.start.to_point(buffer) == start.to_point(buffer)
3004 || selection.end.to_point(buffer) == end.to_point(buffer)
3005 });
3006
3007 clicked_point_already_selected.map(|selection| selection.id)
3008 }
3009 };
3010
3011 let selections_count = self.selections.count();
3012
3013 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
3014 if let Some(point_to_delete) = point_to_delete {
3015 s.delete(point_to_delete);
3016
3017 if selections_count == 1 {
3018 s.set_pending_anchor_range(start..end, mode);
3019 }
3020 } else {
3021 if !add {
3022 s.clear_disjoint();
3023 } else if click_count > 1 {
3024 s.delete(newest_selection.id)
3025 }
3026
3027 s.set_pending_anchor_range(start..end, mode);
3028 }
3029 });
3030 }
3031
3032 fn begin_columnar_selection(
3033 &mut self,
3034 position: DisplayPoint,
3035 goal_column: u32,
3036 reset: bool,
3037 cx: &mut ViewContext<Self>,
3038 ) {
3039 if !self.focus_handle.is_focused(cx) {
3040 self.last_focused_descendant = None;
3041 cx.focus(&self.focus_handle);
3042 }
3043
3044 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3045
3046 if reset {
3047 let pointer_position = display_map
3048 .buffer_snapshot
3049 .anchor_before(position.to_point(&display_map));
3050
3051 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
3052 s.clear_disjoint();
3053 s.set_pending_anchor_range(
3054 pointer_position..pointer_position,
3055 SelectMode::Character,
3056 );
3057 });
3058 }
3059
3060 let tail = self.selections.newest::<Point>(cx).tail();
3061 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
3062
3063 if !reset {
3064 self.select_columns(
3065 tail.to_display_point(&display_map),
3066 position,
3067 goal_column,
3068 &display_map,
3069 cx,
3070 );
3071 }
3072 }
3073
3074 fn update_selection(
3075 &mut self,
3076 position: DisplayPoint,
3077 goal_column: u32,
3078 scroll_delta: gpui::Point<f32>,
3079 cx: &mut ViewContext<Self>,
3080 ) {
3081 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3082
3083 if let Some(tail) = self.columnar_selection_tail.as_ref() {
3084 let tail = tail.to_display_point(&display_map);
3085 self.select_columns(tail, position, goal_column, &display_map, cx);
3086 } else if let Some(mut pending) = self.selections.pending_anchor() {
3087 let buffer = self.buffer.read(cx).snapshot(cx);
3088 let head;
3089 let tail;
3090 let mode = self.selections.pending_mode().unwrap();
3091 match &mode {
3092 SelectMode::Character => {
3093 head = position.to_point(&display_map);
3094 tail = pending.tail().to_point(&buffer);
3095 }
3096 SelectMode::Word(original_range) => {
3097 let original_display_range = original_range.start.to_display_point(&display_map)
3098 ..original_range.end.to_display_point(&display_map);
3099 let original_buffer_range = original_display_range.start.to_point(&display_map)
3100 ..original_display_range.end.to_point(&display_map);
3101 if movement::is_inside_word(&display_map, position)
3102 || original_display_range.contains(&position)
3103 {
3104 let word_range = movement::surrounding_word(&display_map, position);
3105 if word_range.start < original_display_range.start {
3106 head = word_range.start.to_point(&display_map);
3107 } else {
3108 head = word_range.end.to_point(&display_map);
3109 }
3110 } else {
3111 head = position.to_point(&display_map);
3112 }
3113
3114 if head <= original_buffer_range.start {
3115 tail = original_buffer_range.end;
3116 } else {
3117 tail = original_buffer_range.start;
3118 }
3119 }
3120 SelectMode::Line(original_range) => {
3121 let original_range = original_range.to_point(&display_map.buffer_snapshot);
3122
3123 let position = display_map
3124 .clip_point(position, Bias::Left)
3125 .to_point(&display_map);
3126 let line_start = display_map.prev_line_boundary(position).0;
3127 let next_line_start = buffer.clip_point(
3128 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3129 Bias::Left,
3130 );
3131
3132 if line_start < original_range.start {
3133 head = line_start
3134 } else {
3135 head = next_line_start
3136 }
3137
3138 if head <= original_range.start {
3139 tail = original_range.end;
3140 } else {
3141 tail = original_range.start;
3142 }
3143 }
3144 SelectMode::All => {
3145 return;
3146 }
3147 };
3148
3149 if head < tail {
3150 pending.start = buffer.anchor_before(head);
3151 pending.end = buffer.anchor_before(tail);
3152 pending.reversed = true;
3153 } else {
3154 pending.start = buffer.anchor_before(tail);
3155 pending.end = buffer.anchor_before(head);
3156 pending.reversed = false;
3157 }
3158
3159 self.change_selections(None, cx, |s| {
3160 s.set_pending(pending, mode);
3161 });
3162 } else {
3163 log::error!("update_selection dispatched with no pending selection");
3164 return;
3165 }
3166
3167 self.apply_scroll_delta(scroll_delta, cx);
3168 cx.notify();
3169 }
3170
3171 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
3172 self.columnar_selection_tail.take();
3173 if self.selections.pending_anchor().is_some() {
3174 let selections = self.selections.all::<usize>(cx);
3175 self.change_selections(None, cx, |s| {
3176 s.select(selections);
3177 s.clear_pending();
3178 });
3179 }
3180 }
3181
3182 fn select_columns(
3183 &mut self,
3184 tail: DisplayPoint,
3185 head: DisplayPoint,
3186 goal_column: u32,
3187 display_map: &DisplaySnapshot,
3188 cx: &mut ViewContext<Self>,
3189 ) {
3190 let start_row = cmp::min(tail.row(), head.row());
3191 let end_row = cmp::max(tail.row(), head.row());
3192 let start_column = cmp::min(tail.column(), goal_column);
3193 let end_column = cmp::max(tail.column(), goal_column);
3194 let reversed = start_column < tail.column();
3195
3196 let selection_ranges = (start_row.0..=end_row.0)
3197 .map(DisplayRow)
3198 .filter_map(|row| {
3199 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3200 let start = display_map
3201 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3202 .to_point(display_map);
3203 let end = display_map
3204 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3205 .to_point(display_map);
3206 if reversed {
3207 Some(end..start)
3208 } else {
3209 Some(start..end)
3210 }
3211 } else {
3212 None
3213 }
3214 })
3215 .collect::<Vec<_>>();
3216
3217 self.change_selections(None, cx, |s| {
3218 s.select_ranges(selection_ranges);
3219 });
3220 cx.notify();
3221 }
3222
3223 pub fn has_pending_nonempty_selection(&self) -> bool {
3224 let pending_nonempty_selection = match self.selections.pending_anchor() {
3225 Some(Selection { start, end, .. }) => start != end,
3226 None => false,
3227 };
3228
3229 pending_nonempty_selection
3230 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3231 }
3232
3233 pub fn has_pending_selection(&self) -> bool {
3234 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3235 }
3236
3237 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
3238 if self.clear_expanded_diff_hunks(cx) {
3239 cx.notify();
3240 return;
3241 }
3242 if self.dismiss_menus_and_popups(true, cx) {
3243 return;
3244 }
3245
3246 if self.mode == EditorMode::Full
3247 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
3248 {
3249 return;
3250 }
3251
3252 cx.propagate();
3253 }
3254
3255 pub fn dismiss_menus_and_popups(
3256 &mut self,
3257 should_report_inline_completion_event: bool,
3258 cx: &mut ViewContext<Self>,
3259 ) -> bool {
3260 if self.take_rename(false, cx).is_some() {
3261 return true;
3262 }
3263
3264 if hide_hover(self, cx) {
3265 return true;
3266 }
3267
3268 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3269 return true;
3270 }
3271
3272 if self.hide_context_menu(cx).is_some() {
3273 return true;
3274 }
3275
3276 if self.mouse_context_menu.take().is_some() {
3277 return true;
3278 }
3279
3280 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3281 return true;
3282 }
3283
3284 if self.snippet_stack.pop().is_some() {
3285 return true;
3286 }
3287
3288 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3289 self.dismiss_diagnostics(cx);
3290 return true;
3291 }
3292
3293 false
3294 }
3295
3296 fn linked_editing_ranges_for(
3297 &self,
3298 selection: Range<text::Anchor>,
3299 cx: &AppContext,
3300 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3301 if self.linked_edit_ranges.is_empty() {
3302 return None;
3303 }
3304 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3305 selection.end.buffer_id.and_then(|end_buffer_id| {
3306 if selection.start.buffer_id != Some(end_buffer_id) {
3307 return None;
3308 }
3309 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3310 let snapshot = buffer.read(cx).snapshot();
3311 self.linked_edit_ranges
3312 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3313 .map(|ranges| (ranges, snapshot, buffer))
3314 })?;
3315 use text::ToOffset as TO;
3316 // find offset from the start of current range to current cursor position
3317 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3318
3319 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3320 let start_difference = start_offset - start_byte_offset;
3321 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3322 let end_difference = end_offset - start_byte_offset;
3323 // Current range has associated linked ranges.
3324 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3325 for range in linked_ranges.iter() {
3326 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3327 let end_offset = start_offset + end_difference;
3328 let start_offset = start_offset + start_difference;
3329 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3330 continue;
3331 }
3332 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3333 if s.start.buffer_id != selection.start.buffer_id
3334 || s.end.buffer_id != selection.end.buffer_id
3335 {
3336 return false;
3337 }
3338 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3339 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3340 }) {
3341 continue;
3342 }
3343 let start = buffer_snapshot.anchor_after(start_offset);
3344 let end = buffer_snapshot.anchor_after(end_offset);
3345 linked_edits
3346 .entry(buffer.clone())
3347 .or_default()
3348 .push(start..end);
3349 }
3350 Some(linked_edits)
3351 }
3352
3353 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3354 let text: Arc<str> = text.into();
3355
3356 if self.read_only(cx) {
3357 return;
3358 }
3359
3360 let selections = self.selections.all_adjusted(cx);
3361 let mut bracket_inserted = false;
3362 let mut edits = Vec::new();
3363 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3364 let mut new_selections = Vec::with_capacity(selections.len());
3365 let mut new_autoclose_regions = Vec::new();
3366 let snapshot = self.buffer.read(cx).read(cx);
3367
3368 for (selection, autoclose_region) in
3369 self.selections_with_autoclose_regions(selections, &snapshot)
3370 {
3371 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3372 // Determine if the inserted text matches the opening or closing
3373 // bracket of any of this language's bracket pairs.
3374 let mut bracket_pair = None;
3375 let mut is_bracket_pair_start = false;
3376 let mut is_bracket_pair_end = false;
3377 if !text.is_empty() {
3378 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3379 // and they are removing the character that triggered IME popup.
3380 for (pair, enabled) in scope.brackets() {
3381 if !pair.close && !pair.surround {
3382 continue;
3383 }
3384
3385 if enabled && pair.start.ends_with(text.as_ref()) {
3386 let prefix_len = pair.start.len() - text.len();
3387 let preceding_text_matches_prefix = prefix_len == 0
3388 || (selection.start.column >= (prefix_len as u32)
3389 && snapshot.contains_str_at(
3390 Point::new(
3391 selection.start.row,
3392 selection.start.column - (prefix_len as u32),
3393 ),
3394 &pair.start[..prefix_len],
3395 ));
3396 if preceding_text_matches_prefix {
3397 bracket_pair = Some(pair.clone());
3398 is_bracket_pair_start = true;
3399 break;
3400 }
3401 }
3402 if pair.end.as_str() == text.as_ref() {
3403 bracket_pair = Some(pair.clone());
3404 is_bracket_pair_end = true;
3405 break;
3406 }
3407 }
3408 }
3409
3410 if let Some(bracket_pair) = bracket_pair {
3411 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3412 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3413 let auto_surround =
3414 self.use_auto_surround && snapshot_settings.use_auto_surround;
3415 if selection.is_empty() {
3416 if is_bracket_pair_start {
3417 // If the inserted text is a suffix of an opening bracket and the
3418 // selection is preceded by the rest of the opening bracket, then
3419 // insert the closing bracket.
3420 let following_text_allows_autoclose = snapshot
3421 .chars_at(selection.start)
3422 .next()
3423 .map_or(true, |c| scope.should_autoclose_before(c));
3424
3425 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3426 && bracket_pair.start.len() == 1
3427 {
3428 let target = bracket_pair.start.chars().next().unwrap();
3429 let current_line_count = snapshot
3430 .reversed_chars_at(selection.start)
3431 .take_while(|&c| c != '\n')
3432 .filter(|&c| c == target)
3433 .count();
3434 current_line_count % 2 == 1
3435 } else {
3436 false
3437 };
3438
3439 if autoclose
3440 && bracket_pair.close
3441 && following_text_allows_autoclose
3442 && !is_closing_quote
3443 {
3444 let anchor = snapshot.anchor_before(selection.end);
3445 new_selections.push((selection.map(|_| anchor), text.len()));
3446 new_autoclose_regions.push((
3447 anchor,
3448 text.len(),
3449 selection.id,
3450 bracket_pair.clone(),
3451 ));
3452 edits.push((
3453 selection.range(),
3454 format!("{}{}", text, bracket_pair.end).into(),
3455 ));
3456 bracket_inserted = true;
3457 continue;
3458 }
3459 }
3460
3461 if let Some(region) = autoclose_region {
3462 // If the selection is followed by an auto-inserted closing bracket,
3463 // then don't insert that closing bracket again; just move the selection
3464 // past the closing bracket.
3465 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3466 && text.as_ref() == region.pair.end.as_str();
3467 if should_skip {
3468 let anchor = snapshot.anchor_after(selection.end);
3469 new_selections
3470 .push((selection.map(|_| anchor), region.pair.end.len()));
3471 continue;
3472 }
3473 }
3474
3475 let always_treat_brackets_as_autoclosed = snapshot
3476 .settings_at(selection.start, cx)
3477 .always_treat_brackets_as_autoclosed;
3478 if always_treat_brackets_as_autoclosed
3479 && is_bracket_pair_end
3480 && snapshot.contains_str_at(selection.end, text.as_ref())
3481 {
3482 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3483 // and the inserted text is a closing bracket and the selection is followed
3484 // by the closing bracket then move the selection past the closing bracket.
3485 let anchor = snapshot.anchor_after(selection.end);
3486 new_selections.push((selection.map(|_| anchor), text.len()));
3487 continue;
3488 }
3489 }
3490 // If an opening bracket is 1 character long and is typed while
3491 // text is selected, then surround that text with the bracket pair.
3492 else if auto_surround
3493 && bracket_pair.surround
3494 && is_bracket_pair_start
3495 && bracket_pair.start.chars().count() == 1
3496 {
3497 edits.push((selection.start..selection.start, text.clone()));
3498 edits.push((
3499 selection.end..selection.end,
3500 bracket_pair.end.as_str().into(),
3501 ));
3502 bracket_inserted = true;
3503 new_selections.push((
3504 Selection {
3505 id: selection.id,
3506 start: snapshot.anchor_after(selection.start),
3507 end: snapshot.anchor_before(selection.end),
3508 reversed: selection.reversed,
3509 goal: selection.goal,
3510 },
3511 0,
3512 ));
3513 continue;
3514 }
3515 }
3516 }
3517
3518 if self.auto_replace_emoji_shortcode
3519 && selection.is_empty()
3520 && text.as_ref().ends_with(':')
3521 {
3522 if let Some(possible_emoji_short_code) =
3523 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3524 {
3525 if !possible_emoji_short_code.is_empty() {
3526 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3527 let emoji_shortcode_start = Point::new(
3528 selection.start.row,
3529 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3530 );
3531
3532 // Remove shortcode from buffer
3533 edits.push((
3534 emoji_shortcode_start..selection.start,
3535 "".to_string().into(),
3536 ));
3537 new_selections.push((
3538 Selection {
3539 id: selection.id,
3540 start: snapshot.anchor_after(emoji_shortcode_start),
3541 end: snapshot.anchor_before(selection.start),
3542 reversed: selection.reversed,
3543 goal: selection.goal,
3544 },
3545 0,
3546 ));
3547
3548 // Insert emoji
3549 let selection_start_anchor = snapshot.anchor_after(selection.start);
3550 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3551 edits.push((selection.start..selection.end, emoji.to_string().into()));
3552
3553 continue;
3554 }
3555 }
3556 }
3557 }
3558
3559 // If not handling any auto-close operation, then just replace the selected
3560 // text with the given input and move the selection to the end of the
3561 // newly inserted text.
3562 let anchor = snapshot.anchor_after(selection.end);
3563 if !self.linked_edit_ranges.is_empty() {
3564 let start_anchor = snapshot.anchor_before(selection.start);
3565
3566 let is_word_char = text.chars().next().map_or(true, |char| {
3567 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3568 classifier.is_word(char)
3569 });
3570
3571 if is_word_char {
3572 if let Some(ranges) = self
3573 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3574 {
3575 for (buffer, edits) in ranges {
3576 linked_edits
3577 .entry(buffer.clone())
3578 .or_default()
3579 .extend(edits.into_iter().map(|range| (range, text.clone())));
3580 }
3581 }
3582 }
3583 }
3584
3585 new_selections.push((selection.map(|_| anchor), 0));
3586 edits.push((selection.start..selection.end, text.clone()));
3587 }
3588
3589 drop(snapshot);
3590
3591 self.transact(cx, |this, cx| {
3592 this.buffer.update(cx, |buffer, cx| {
3593 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3594 });
3595 for (buffer, edits) in linked_edits {
3596 buffer.update(cx, |buffer, cx| {
3597 let snapshot = buffer.snapshot();
3598 let edits = edits
3599 .into_iter()
3600 .map(|(range, text)| {
3601 use text::ToPoint as TP;
3602 let end_point = TP::to_point(&range.end, &snapshot);
3603 let start_point = TP::to_point(&range.start, &snapshot);
3604 (start_point..end_point, text)
3605 })
3606 .sorted_by_key(|(range, _)| range.start)
3607 .collect::<Vec<_>>();
3608 buffer.edit(edits, None, cx);
3609 })
3610 }
3611 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3612 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3613 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3614 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3615 .zip(new_selection_deltas)
3616 .map(|(selection, delta)| Selection {
3617 id: selection.id,
3618 start: selection.start + delta,
3619 end: selection.end + delta,
3620 reversed: selection.reversed,
3621 goal: SelectionGoal::None,
3622 })
3623 .collect::<Vec<_>>();
3624
3625 let mut i = 0;
3626 for (position, delta, selection_id, pair) in new_autoclose_regions {
3627 let position = position.to_offset(&map.buffer_snapshot) + delta;
3628 let start = map.buffer_snapshot.anchor_before(position);
3629 let end = map.buffer_snapshot.anchor_after(position);
3630 while let Some(existing_state) = this.autoclose_regions.get(i) {
3631 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3632 Ordering::Less => i += 1,
3633 Ordering::Greater => break,
3634 Ordering::Equal => {
3635 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3636 Ordering::Less => i += 1,
3637 Ordering::Equal => break,
3638 Ordering::Greater => break,
3639 }
3640 }
3641 }
3642 }
3643 this.autoclose_regions.insert(
3644 i,
3645 AutocloseRegion {
3646 selection_id,
3647 range: start..end,
3648 pair,
3649 },
3650 );
3651 }
3652
3653 let had_active_inline_completion = this.has_active_inline_completion();
3654 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3655 s.select(new_selections)
3656 });
3657
3658 if !bracket_inserted {
3659 if let Some(on_type_format_task) =
3660 this.trigger_on_type_formatting(text.to_string(), cx)
3661 {
3662 on_type_format_task.detach_and_log_err(cx);
3663 }
3664 }
3665
3666 let editor_settings = EditorSettings::get_global(cx);
3667 if bracket_inserted
3668 && (editor_settings.auto_signature_help
3669 || editor_settings.show_signature_help_after_edits)
3670 {
3671 this.show_signature_help(&ShowSignatureHelp, cx);
3672 }
3673
3674 let trigger_in_words = !had_active_inline_completion;
3675 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3676 linked_editing_ranges::refresh_linked_ranges(this, cx);
3677 this.refresh_inline_completion(true, false, cx);
3678 });
3679 }
3680
3681 fn find_possible_emoji_shortcode_at_position(
3682 snapshot: &MultiBufferSnapshot,
3683 position: Point,
3684 ) -> Option<String> {
3685 let mut chars = Vec::new();
3686 let mut found_colon = false;
3687 for char in snapshot.reversed_chars_at(position).take(100) {
3688 // Found a possible emoji shortcode in the middle of the buffer
3689 if found_colon {
3690 if char.is_whitespace() {
3691 chars.reverse();
3692 return Some(chars.iter().collect());
3693 }
3694 // If the previous character is not a whitespace, we are in the middle of a word
3695 // and we only want to complete the shortcode if the word is made up of other emojis
3696 let mut containing_word = String::new();
3697 for ch in snapshot
3698 .reversed_chars_at(position)
3699 .skip(chars.len() + 1)
3700 .take(100)
3701 {
3702 if ch.is_whitespace() {
3703 break;
3704 }
3705 containing_word.push(ch);
3706 }
3707 let containing_word = containing_word.chars().rev().collect::<String>();
3708 if util::word_consists_of_emojis(containing_word.as_str()) {
3709 chars.reverse();
3710 return Some(chars.iter().collect());
3711 }
3712 }
3713
3714 if char.is_whitespace() || !char.is_ascii() {
3715 return None;
3716 }
3717 if char == ':' {
3718 found_colon = true;
3719 } else {
3720 chars.push(char);
3721 }
3722 }
3723 // Found a possible emoji shortcode at the beginning of the buffer
3724 chars.reverse();
3725 Some(chars.iter().collect())
3726 }
3727
3728 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3729 self.transact(cx, |this, cx| {
3730 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3731 let selections = this.selections.all::<usize>(cx);
3732 let multi_buffer = this.buffer.read(cx);
3733 let buffer = multi_buffer.snapshot(cx);
3734 selections
3735 .iter()
3736 .map(|selection| {
3737 let start_point = selection.start.to_point(&buffer);
3738 let mut indent =
3739 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3740 indent.len = cmp::min(indent.len, start_point.column);
3741 let start = selection.start;
3742 let end = selection.end;
3743 let selection_is_empty = start == end;
3744 let language_scope = buffer.language_scope_at(start);
3745 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3746 &language_scope
3747 {
3748 let leading_whitespace_len = buffer
3749 .reversed_chars_at(start)
3750 .take_while(|c| c.is_whitespace() && *c != '\n')
3751 .map(|c| c.len_utf8())
3752 .sum::<usize>();
3753
3754 let trailing_whitespace_len = buffer
3755 .chars_at(end)
3756 .take_while(|c| c.is_whitespace() && *c != '\n')
3757 .map(|c| c.len_utf8())
3758 .sum::<usize>();
3759
3760 let insert_extra_newline =
3761 language.brackets().any(|(pair, enabled)| {
3762 let pair_start = pair.start.trim_end();
3763 let pair_end = pair.end.trim_start();
3764
3765 enabled
3766 && pair.newline
3767 && buffer.contains_str_at(
3768 end + trailing_whitespace_len,
3769 pair_end,
3770 )
3771 && buffer.contains_str_at(
3772 (start - leading_whitespace_len)
3773 .saturating_sub(pair_start.len()),
3774 pair_start,
3775 )
3776 });
3777
3778 // Comment extension on newline is allowed only for cursor selections
3779 let comment_delimiter = maybe!({
3780 if !selection_is_empty {
3781 return None;
3782 }
3783
3784 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3785 return None;
3786 }
3787
3788 let delimiters = language.line_comment_prefixes();
3789 let max_len_of_delimiter =
3790 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3791 let (snapshot, range) =
3792 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3793
3794 let mut index_of_first_non_whitespace = 0;
3795 let comment_candidate = snapshot
3796 .chars_for_range(range)
3797 .skip_while(|c| {
3798 let should_skip = c.is_whitespace();
3799 if should_skip {
3800 index_of_first_non_whitespace += 1;
3801 }
3802 should_skip
3803 })
3804 .take(max_len_of_delimiter)
3805 .collect::<String>();
3806 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3807 comment_candidate.starts_with(comment_prefix.as_ref())
3808 })?;
3809 let cursor_is_placed_after_comment_marker =
3810 index_of_first_non_whitespace + comment_prefix.len()
3811 <= start_point.column as usize;
3812 if cursor_is_placed_after_comment_marker {
3813 Some(comment_prefix.clone())
3814 } else {
3815 None
3816 }
3817 });
3818 (comment_delimiter, insert_extra_newline)
3819 } else {
3820 (None, false)
3821 };
3822
3823 let capacity_for_delimiter = comment_delimiter
3824 .as_deref()
3825 .map(str::len)
3826 .unwrap_or_default();
3827 let mut new_text =
3828 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3829 new_text.push('\n');
3830 new_text.extend(indent.chars());
3831 if let Some(delimiter) = &comment_delimiter {
3832 new_text.push_str(delimiter);
3833 }
3834 if insert_extra_newline {
3835 new_text = new_text.repeat(2);
3836 }
3837
3838 let anchor = buffer.anchor_after(end);
3839 let new_selection = selection.map(|_| anchor);
3840 (
3841 (start..end, new_text),
3842 (insert_extra_newline, new_selection),
3843 )
3844 })
3845 .unzip()
3846 };
3847
3848 this.edit_with_autoindent(edits, cx);
3849 let buffer = this.buffer.read(cx).snapshot(cx);
3850 let new_selections = selection_fixup_info
3851 .into_iter()
3852 .map(|(extra_newline_inserted, new_selection)| {
3853 let mut cursor = new_selection.end.to_point(&buffer);
3854 if extra_newline_inserted {
3855 cursor.row -= 1;
3856 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3857 }
3858 new_selection.map(|_| cursor)
3859 })
3860 .collect();
3861
3862 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3863 this.refresh_inline_completion(true, false, cx);
3864 });
3865 }
3866
3867 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3868 let buffer = self.buffer.read(cx);
3869 let snapshot = buffer.snapshot(cx);
3870
3871 let mut edits = Vec::new();
3872 let mut rows = Vec::new();
3873
3874 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3875 let cursor = selection.head();
3876 let row = cursor.row;
3877
3878 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3879
3880 let newline = "\n".to_string();
3881 edits.push((start_of_line..start_of_line, newline));
3882
3883 rows.push(row + rows_inserted as u32);
3884 }
3885
3886 self.transact(cx, |editor, cx| {
3887 editor.edit(edits, cx);
3888
3889 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3890 let mut index = 0;
3891 s.move_cursors_with(|map, _, _| {
3892 let row = rows[index];
3893 index += 1;
3894
3895 let point = Point::new(row, 0);
3896 let boundary = map.next_line_boundary(point).1;
3897 let clipped = map.clip_point(boundary, Bias::Left);
3898
3899 (clipped, SelectionGoal::None)
3900 });
3901 });
3902
3903 let mut indent_edits = Vec::new();
3904 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3905 for row in rows {
3906 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3907 for (row, indent) in indents {
3908 if indent.len == 0 {
3909 continue;
3910 }
3911
3912 let text = match indent.kind {
3913 IndentKind::Space => " ".repeat(indent.len as usize),
3914 IndentKind::Tab => "\t".repeat(indent.len as usize),
3915 };
3916 let point = Point::new(row.0, 0);
3917 indent_edits.push((point..point, text));
3918 }
3919 }
3920 editor.edit(indent_edits, cx);
3921 });
3922 }
3923
3924 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3925 let buffer = self.buffer.read(cx);
3926 let snapshot = buffer.snapshot(cx);
3927
3928 let mut edits = Vec::new();
3929 let mut rows = Vec::new();
3930 let mut rows_inserted = 0;
3931
3932 for selection in self.selections.all_adjusted(cx) {
3933 let cursor = selection.head();
3934 let row = cursor.row;
3935
3936 let point = Point::new(row + 1, 0);
3937 let start_of_line = snapshot.clip_point(point, Bias::Left);
3938
3939 let newline = "\n".to_string();
3940 edits.push((start_of_line..start_of_line, newline));
3941
3942 rows_inserted += 1;
3943 rows.push(row + rows_inserted);
3944 }
3945
3946 self.transact(cx, |editor, cx| {
3947 editor.edit(edits, cx);
3948
3949 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3950 let mut index = 0;
3951 s.move_cursors_with(|map, _, _| {
3952 let row = rows[index];
3953 index += 1;
3954
3955 let point = Point::new(row, 0);
3956 let boundary = map.next_line_boundary(point).1;
3957 let clipped = map.clip_point(boundary, Bias::Left);
3958
3959 (clipped, SelectionGoal::None)
3960 });
3961 });
3962
3963 let mut indent_edits = Vec::new();
3964 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3965 for row in rows {
3966 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3967 for (row, indent) in indents {
3968 if indent.len == 0 {
3969 continue;
3970 }
3971
3972 let text = match indent.kind {
3973 IndentKind::Space => " ".repeat(indent.len as usize),
3974 IndentKind::Tab => "\t".repeat(indent.len as usize),
3975 };
3976 let point = Point::new(row.0, 0);
3977 indent_edits.push((point..point, text));
3978 }
3979 }
3980 editor.edit(indent_edits, cx);
3981 });
3982 }
3983
3984 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3985 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3986 original_indent_columns: Vec::new(),
3987 });
3988 self.insert_with_autoindent_mode(text, autoindent, cx);
3989 }
3990
3991 fn insert_with_autoindent_mode(
3992 &mut self,
3993 text: &str,
3994 autoindent_mode: Option<AutoindentMode>,
3995 cx: &mut ViewContext<Self>,
3996 ) {
3997 if self.read_only(cx) {
3998 return;
3999 }
4000
4001 let text: Arc<str> = text.into();
4002 self.transact(cx, |this, cx| {
4003 let old_selections = this.selections.all_adjusted(cx);
4004 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
4005 let anchors = {
4006 let snapshot = buffer.read(cx);
4007 old_selections
4008 .iter()
4009 .map(|s| {
4010 let anchor = snapshot.anchor_after(s.head());
4011 s.map(|_| anchor)
4012 })
4013 .collect::<Vec<_>>()
4014 };
4015 buffer.edit(
4016 old_selections
4017 .iter()
4018 .map(|s| (s.start..s.end, text.clone())),
4019 autoindent_mode,
4020 cx,
4021 );
4022 anchors
4023 });
4024
4025 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
4026 s.select_anchors(selection_anchors);
4027 })
4028 });
4029 }
4030
4031 fn trigger_completion_on_input(
4032 &mut self,
4033 text: &str,
4034 trigger_in_words: bool,
4035 cx: &mut ViewContext<Self>,
4036 ) {
4037 if self.is_completion_trigger(text, trigger_in_words, cx) {
4038 self.show_completions(
4039 &ShowCompletions {
4040 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
4041 },
4042 cx,
4043 );
4044 } else {
4045 self.hide_context_menu(cx);
4046 }
4047 }
4048
4049 fn is_completion_trigger(
4050 &self,
4051 text: &str,
4052 trigger_in_words: bool,
4053 cx: &mut ViewContext<Self>,
4054 ) -> bool {
4055 let position = self.selections.newest_anchor().head();
4056 let multibuffer = self.buffer.read(cx);
4057 let Some(buffer) = position
4058 .buffer_id
4059 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
4060 else {
4061 return false;
4062 };
4063
4064 if let Some(completion_provider) = &self.completion_provider {
4065 completion_provider.is_completion_trigger(
4066 &buffer,
4067 position.text_anchor,
4068 text,
4069 trigger_in_words,
4070 cx,
4071 )
4072 } else {
4073 false
4074 }
4075 }
4076
4077 /// If any empty selections is touching the start of its innermost containing autoclose
4078 /// region, expand it to select the brackets.
4079 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
4080 let selections = self.selections.all::<usize>(cx);
4081 let buffer = self.buffer.read(cx).read(cx);
4082 let new_selections = self
4083 .selections_with_autoclose_regions(selections, &buffer)
4084 .map(|(mut selection, region)| {
4085 if !selection.is_empty() {
4086 return selection;
4087 }
4088
4089 if let Some(region) = region {
4090 let mut range = region.range.to_offset(&buffer);
4091 if selection.start == range.start && range.start >= region.pair.start.len() {
4092 range.start -= region.pair.start.len();
4093 if buffer.contains_str_at(range.start, ®ion.pair.start)
4094 && buffer.contains_str_at(range.end, ®ion.pair.end)
4095 {
4096 range.end += region.pair.end.len();
4097 selection.start = range.start;
4098 selection.end = range.end;
4099
4100 return selection;
4101 }
4102 }
4103 }
4104
4105 let always_treat_brackets_as_autoclosed = buffer
4106 .settings_at(selection.start, cx)
4107 .always_treat_brackets_as_autoclosed;
4108
4109 if !always_treat_brackets_as_autoclosed {
4110 return selection;
4111 }
4112
4113 if let Some(scope) = buffer.language_scope_at(selection.start) {
4114 for (pair, enabled) in scope.brackets() {
4115 if !enabled || !pair.close {
4116 continue;
4117 }
4118
4119 if buffer.contains_str_at(selection.start, &pair.end) {
4120 let pair_start_len = pair.start.len();
4121 if buffer.contains_str_at(
4122 selection.start.saturating_sub(pair_start_len),
4123 &pair.start,
4124 ) {
4125 selection.start -= pair_start_len;
4126 selection.end += pair.end.len();
4127
4128 return selection;
4129 }
4130 }
4131 }
4132 }
4133
4134 selection
4135 })
4136 .collect();
4137
4138 drop(buffer);
4139 self.change_selections(None, cx, |selections| selections.select(new_selections));
4140 }
4141
4142 /// Iterate the given selections, and for each one, find the smallest surrounding
4143 /// autoclose region. This uses the ordering of the selections and the autoclose
4144 /// regions to avoid repeated comparisons.
4145 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4146 &'a self,
4147 selections: impl IntoIterator<Item = Selection<D>>,
4148 buffer: &'a MultiBufferSnapshot,
4149 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4150 let mut i = 0;
4151 let mut regions = self.autoclose_regions.as_slice();
4152 selections.into_iter().map(move |selection| {
4153 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4154
4155 let mut enclosing = None;
4156 while let Some(pair_state) = regions.get(i) {
4157 if pair_state.range.end.to_offset(buffer) < range.start {
4158 regions = ®ions[i + 1..];
4159 i = 0;
4160 } else if pair_state.range.start.to_offset(buffer) > range.end {
4161 break;
4162 } else {
4163 if pair_state.selection_id == selection.id {
4164 enclosing = Some(pair_state);
4165 }
4166 i += 1;
4167 }
4168 }
4169
4170 (selection, enclosing)
4171 })
4172 }
4173
4174 /// Remove any autoclose regions that no longer contain their selection.
4175 fn invalidate_autoclose_regions(
4176 &mut self,
4177 mut selections: &[Selection<Anchor>],
4178 buffer: &MultiBufferSnapshot,
4179 ) {
4180 self.autoclose_regions.retain(|state| {
4181 let mut i = 0;
4182 while let Some(selection) = selections.get(i) {
4183 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4184 selections = &selections[1..];
4185 continue;
4186 }
4187 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4188 break;
4189 }
4190 if selection.id == state.selection_id {
4191 return true;
4192 } else {
4193 i += 1;
4194 }
4195 }
4196 false
4197 });
4198 }
4199
4200 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4201 let offset = position.to_offset(buffer);
4202 let (word_range, kind) = buffer.surrounding_word(offset, true);
4203 if offset > word_range.start && kind == Some(CharKind::Word) {
4204 Some(
4205 buffer
4206 .text_for_range(word_range.start..offset)
4207 .collect::<String>(),
4208 )
4209 } else {
4210 None
4211 }
4212 }
4213
4214 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
4215 self.refresh_inlay_hints(
4216 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
4217 cx,
4218 );
4219 }
4220
4221 pub fn inlay_hints_enabled(&self) -> bool {
4222 self.inlay_hint_cache.enabled
4223 }
4224
4225 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
4226 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
4227 return;
4228 }
4229
4230 let reason_description = reason.description();
4231 let ignore_debounce = matches!(
4232 reason,
4233 InlayHintRefreshReason::SettingsChange(_)
4234 | InlayHintRefreshReason::Toggle(_)
4235 | InlayHintRefreshReason::ExcerptsRemoved(_)
4236 );
4237 let (invalidate_cache, required_languages) = match reason {
4238 InlayHintRefreshReason::Toggle(enabled) => {
4239 self.inlay_hint_cache.enabled = enabled;
4240 if enabled {
4241 (InvalidationStrategy::RefreshRequested, None)
4242 } else {
4243 self.inlay_hint_cache.clear();
4244 self.splice_inlays(
4245 self.visible_inlay_hints(cx)
4246 .iter()
4247 .map(|inlay| inlay.id)
4248 .collect(),
4249 Vec::new(),
4250 cx,
4251 );
4252 return;
4253 }
4254 }
4255 InlayHintRefreshReason::SettingsChange(new_settings) => {
4256 match self.inlay_hint_cache.update_settings(
4257 &self.buffer,
4258 new_settings,
4259 self.visible_inlay_hints(cx),
4260 cx,
4261 ) {
4262 ControlFlow::Break(Some(InlaySplice {
4263 to_remove,
4264 to_insert,
4265 })) => {
4266 self.splice_inlays(to_remove, to_insert, cx);
4267 return;
4268 }
4269 ControlFlow::Break(None) => return,
4270 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4271 }
4272 }
4273 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4274 if let Some(InlaySplice {
4275 to_remove,
4276 to_insert,
4277 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4278 {
4279 self.splice_inlays(to_remove, to_insert, cx);
4280 }
4281 return;
4282 }
4283 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4284 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4285 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4286 }
4287 InlayHintRefreshReason::RefreshRequested => {
4288 (InvalidationStrategy::RefreshRequested, None)
4289 }
4290 };
4291
4292 if let Some(InlaySplice {
4293 to_remove,
4294 to_insert,
4295 }) = self.inlay_hint_cache.spawn_hint_refresh(
4296 reason_description,
4297 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4298 invalidate_cache,
4299 ignore_debounce,
4300 cx,
4301 ) {
4302 self.splice_inlays(to_remove, to_insert, cx);
4303 }
4304 }
4305
4306 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4307 self.display_map
4308 .read(cx)
4309 .current_inlays()
4310 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4311 .cloned()
4312 .collect()
4313 }
4314
4315 pub fn excerpts_for_inlay_hints_query(
4316 &self,
4317 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4318 cx: &mut ViewContext<Editor>,
4319 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4320 let Some(project) = self.project.as_ref() else {
4321 return HashMap::default();
4322 };
4323 let project = project.read(cx);
4324 let multi_buffer = self.buffer().read(cx);
4325 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4326 let multi_buffer_visible_start = self
4327 .scroll_manager
4328 .anchor()
4329 .anchor
4330 .to_point(&multi_buffer_snapshot);
4331 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4332 multi_buffer_visible_start
4333 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4334 Bias::Left,
4335 );
4336 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4337 multi_buffer
4338 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4339 .into_iter()
4340 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4341 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4342 let buffer = buffer_handle.read(cx);
4343 let buffer_file = project::File::from_dyn(buffer.file())?;
4344 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4345 let worktree_entry = buffer_worktree
4346 .read(cx)
4347 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4348 if worktree_entry.is_ignored {
4349 return None;
4350 }
4351
4352 let language = buffer.language()?;
4353 if let Some(restrict_to_languages) = restrict_to_languages {
4354 if !restrict_to_languages.contains(language) {
4355 return None;
4356 }
4357 }
4358 Some((
4359 excerpt_id,
4360 (
4361 buffer_handle,
4362 buffer.version().clone(),
4363 excerpt_visible_range,
4364 ),
4365 ))
4366 })
4367 .collect()
4368 }
4369
4370 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4371 TextLayoutDetails {
4372 text_system: cx.text_system().clone(),
4373 editor_style: self.style.clone().unwrap(),
4374 rem_size: cx.rem_size(),
4375 scroll_anchor: self.scroll_manager.anchor(),
4376 visible_rows: self.visible_line_count(),
4377 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4378 }
4379 }
4380
4381 fn splice_inlays(
4382 &self,
4383 to_remove: Vec<InlayId>,
4384 to_insert: Vec<Inlay>,
4385 cx: &mut ViewContext<Self>,
4386 ) {
4387 self.display_map.update(cx, |display_map, cx| {
4388 display_map.splice_inlays(to_remove, to_insert, cx)
4389 });
4390 cx.notify();
4391 }
4392
4393 fn trigger_on_type_formatting(
4394 &self,
4395 input: String,
4396 cx: &mut ViewContext<Self>,
4397 ) -> Option<Task<Result<()>>> {
4398 if input.len() != 1 {
4399 return None;
4400 }
4401
4402 let project = self.project.as_ref()?;
4403 let position = self.selections.newest_anchor().head();
4404 let (buffer, buffer_position) = self
4405 .buffer
4406 .read(cx)
4407 .text_anchor_for_position(position, cx)?;
4408
4409 let settings = language_settings::language_settings(
4410 buffer
4411 .read(cx)
4412 .language_at(buffer_position)
4413 .map(|l| l.name()),
4414 buffer.read(cx).file(),
4415 cx,
4416 );
4417 if !settings.use_on_type_format {
4418 return None;
4419 }
4420
4421 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4422 // hence we do LSP request & edit on host side only — add formats to host's history.
4423 let push_to_lsp_host_history = true;
4424 // If this is not the host, append its history with new edits.
4425 let push_to_client_history = project.read(cx).is_via_collab();
4426
4427 let on_type_formatting = project.update(cx, |project, cx| {
4428 project.on_type_format(
4429 buffer.clone(),
4430 buffer_position,
4431 input,
4432 push_to_lsp_host_history,
4433 cx,
4434 )
4435 });
4436 Some(cx.spawn(|editor, mut cx| async move {
4437 if let Some(transaction) = on_type_formatting.await? {
4438 if push_to_client_history {
4439 buffer
4440 .update(&mut cx, |buffer, _| {
4441 buffer.push_transaction(transaction, Instant::now());
4442 })
4443 .ok();
4444 }
4445 editor.update(&mut cx, |editor, cx| {
4446 editor.refresh_document_highlights(cx);
4447 })?;
4448 }
4449 Ok(())
4450 }))
4451 }
4452
4453 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4454 if self.pending_rename.is_some() {
4455 return;
4456 }
4457
4458 let Some(provider) = self.completion_provider.as_ref() else {
4459 return;
4460 };
4461
4462 if !self.snippet_stack.is_empty() && self.context_menu.read().as_ref().is_some() {
4463 return;
4464 }
4465
4466 let position = self.selections.newest_anchor().head();
4467 let (buffer, buffer_position) =
4468 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4469 output
4470 } else {
4471 return;
4472 };
4473
4474 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4475 let is_followup_invoke = {
4476 let context_menu_state = self.context_menu.read();
4477 matches!(
4478 context_menu_state.deref(),
4479 Some(ContextMenu::Completions(_))
4480 )
4481 };
4482 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4483 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4484 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
4485 CompletionTriggerKind::TRIGGER_CHARACTER
4486 }
4487
4488 _ => CompletionTriggerKind::INVOKED,
4489 };
4490 let completion_context = CompletionContext {
4491 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4492 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4493 Some(String::from(trigger))
4494 } else {
4495 None
4496 }
4497 }),
4498 trigger_kind,
4499 };
4500 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4501 let sort_completions = provider.sort_completions();
4502
4503 let id = post_inc(&mut self.next_completion_id);
4504 let task = cx.spawn(|editor, mut cx| {
4505 async move {
4506 editor.update(&mut cx, |this, _| {
4507 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4508 })?;
4509 let completions = completions.await.log_err();
4510 let menu = if let Some(completions) = completions {
4511 let mut menu = CompletionsMenu::new(
4512 id,
4513 sort_completions,
4514 position,
4515 buffer.clone(),
4516 completions.into(),
4517 );
4518 menu.filter(query.as_deref(), cx.background_executor().clone())
4519 .await;
4520
4521 if menu.matches.is_empty() {
4522 None
4523 } else {
4524 Some(menu)
4525 }
4526 } else {
4527 None
4528 };
4529
4530 editor.update(&mut cx, |editor, cx| {
4531 let mut context_menu = editor.context_menu.write();
4532 match context_menu.as_ref() {
4533 None => {}
4534
4535 Some(ContextMenu::Completions(prev_menu)) => {
4536 if prev_menu.id > id {
4537 return;
4538 }
4539 }
4540
4541 _ => return,
4542 }
4543
4544 if editor.focus_handle.is_focused(cx) && menu.is_some() {
4545 let mut menu = menu.unwrap();
4546 menu.resolve_selected_completion(editor.completion_provider.as_deref(), cx);
4547 *context_menu = Some(ContextMenu::Completions(menu));
4548 drop(context_menu);
4549 editor.discard_inline_completion(false, cx);
4550 cx.notify();
4551 } else if editor.completion_tasks.len() <= 1 {
4552 // If there are no more completion tasks and the last menu was
4553 // empty, we should hide it. If it was already hidden, we should
4554 // also show the copilot completion when available.
4555 drop(context_menu);
4556 if editor.hide_context_menu(cx).is_none() {
4557 editor.update_visible_inline_completion(cx);
4558 }
4559 }
4560 })?;
4561
4562 Ok::<_, anyhow::Error>(())
4563 }
4564 .log_err()
4565 });
4566
4567 self.completion_tasks.push((id, task));
4568 }
4569
4570 pub fn confirm_completion(
4571 &mut self,
4572 action: &ConfirmCompletion,
4573 cx: &mut ViewContext<Self>,
4574 ) -> Option<Task<Result<()>>> {
4575 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4576 }
4577
4578 pub fn compose_completion(
4579 &mut self,
4580 action: &ComposeCompletion,
4581 cx: &mut ViewContext<Self>,
4582 ) -> Option<Task<Result<()>>> {
4583 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4584 }
4585
4586 fn do_completion(
4587 &mut self,
4588 item_ix: Option<usize>,
4589 intent: CompletionIntent,
4590 cx: &mut ViewContext<Editor>,
4591 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4592 use language::ToOffset as _;
4593
4594 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4595 menu
4596 } else {
4597 return None;
4598 };
4599
4600 let mat = completions_menu
4601 .matches
4602 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4603 let buffer_handle = completions_menu.buffer;
4604 let completions = completions_menu.completions.read();
4605 let completion = completions.get(mat.candidate_id)?;
4606 cx.stop_propagation();
4607
4608 let snippet;
4609 let text;
4610
4611 if completion.is_snippet() {
4612 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4613 text = snippet.as_ref().unwrap().text.clone();
4614 } else {
4615 snippet = None;
4616 text = completion.new_text.clone();
4617 };
4618 let selections = self.selections.all::<usize>(cx);
4619 let buffer = buffer_handle.read(cx);
4620 let old_range = completion.old_range.to_offset(buffer);
4621 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4622
4623 let newest_selection = self.selections.newest_anchor();
4624 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4625 return None;
4626 }
4627
4628 let lookbehind = newest_selection
4629 .start
4630 .text_anchor
4631 .to_offset(buffer)
4632 .saturating_sub(old_range.start);
4633 let lookahead = old_range
4634 .end
4635 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4636 let mut common_prefix_len = old_text
4637 .bytes()
4638 .zip(text.bytes())
4639 .take_while(|(a, b)| a == b)
4640 .count();
4641
4642 let snapshot = self.buffer.read(cx).snapshot(cx);
4643 let mut range_to_replace: Option<Range<isize>> = None;
4644 let mut ranges = Vec::new();
4645 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4646 for selection in &selections {
4647 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4648 let start = selection.start.saturating_sub(lookbehind);
4649 let end = selection.end + lookahead;
4650 if selection.id == newest_selection.id {
4651 range_to_replace = Some(
4652 ((start + common_prefix_len) as isize - selection.start as isize)
4653 ..(end as isize - selection.start as isize),
4654 );
4655 }
4656 ranges.push(start + common_prefix_len..end);
4657 } else {
4658 common_prefix_len = 0;
4659 ranges.clear();
4660 ranges.extend(selections.iter().map(|s| {
4661 if s.id == newest_selection.id {
4662 range_to_replace = Some(
4663 old_range.start.to_offset_utf16(&snapshot).0 as isize
4664 - selection.start as isize
4665 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4666 - selection.start as isize,
4667 );
4668 old_range.clone()
4669 } else {
4670 s.start..s.end
4671 }
4672 }));
4673 break;
4674 }
4675 if !self.linked_edit_ranges.is_empty() {
4676 let start_anchor = snapshot.anchor_before(selection.head());
4677 let end_anchor = snapshot.anchor_after(selection.tail());
4678 if let Some(ranges) = self
4679 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4680 {
4681 for (buffer, edits) in ranges {
4682 linked_edits.entry(buffer.clone()).or_default().extend(
4683 edits
4684 .into_iter()
4685 .map(|range| (range, text[common_prefix_len..].to_owned())),
4686 );
4687 }
4688 }
4689 }
4690 }
4691 let text = &text[common_prefix_len..];
4692
4693 cx.emit(EditorEvent::InputHandled {
4694 utf16_range_to_replace: range_to_replace,
4695 text: text.into(),
4696 });
4697
4698 self.transact(cx, |this, cx| {
4699 if let Some(mut snippet) = snippet {
4700 snippet.text = text.to_string();
4701 for tabstop in snippet
4702 .tabstops
4703 .iter_mut()
4704 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4705 {
4706 tabstop.start -= common_prefix_len as isize;
4707 tabstop.end -= common_prefix_len as isize;
4708 }
4709
4710 this.insert_snippet(&ranges, snippet, cx).log_err();
4711 } else {
4712 this.buffer.update(cx, |buffer, cx| {
4713 buffer.edit(
4714 ranges.iter().map(|range| (range.clone(), text)),
4715 this.autoindent_mode.clone(),
4716 cx,
4717 );
4718 });
4719 }
4720 for (buffer, edits) in linked_edits {
4721 buffer.update(cx, |buffer, cx| {
4722 let snapshot = buffer.snapshot();
4723 let edits = edits
4724 .into_iter()
4725 .map(|(range, text)| {
4726 use text::ToPoint as TP;
4727 let end_point = TP::to_point(&range.end, &snapshot);
4728 let start_point = TP::to_point(&range.start, &snapshot);
4729 (start_point..end_point, text)
4730 })
4731 .sorted_by_key(|(range, _)| range.start)
4732 .collect::<Vec<_>>();
4733 buffer.edit(edits, None, cx);
4734 })
4735 }
4736
4737 this.refresh_inline_completion(true, false, cx);
4738 });
4739
4740 let show_new_completions_on_confirm = completion
4741 .confirm
4742 .as_ref()
4743 .map_or(false, |confirm| confirm(intent, cx));
4744 if show_new_completions_on_confirm {
4745 self.show_completions(&ShowCompletions { trigger: None }, cx);
4746 }
4747
4748 let provider = self.completion_provider.as_ref()?;
4749 let apply_edits = provider.apply_additional_edits_for_completion(
4750 buffer_handle,
4751 completion.clone(),
4752 true,
4753 cx,
4754 );
4755
4756 let editor_settings = EditorSettings::get_global(cx);
4757 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4758 // After the code completion is finished, users often want to know what signatures are needed.
4759 // so we should automatically call signature_help
4760 self.show_signature_help(&ShowSignatureHelp, cx);
4761 }
4762
4763 Some(cx.foreground_executor().spawn(async move {
4764 apply_edits.await?;
4765 Ok(())
4766 }))
4767 }
4768
4769 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4770 let mut context_menu = self.context_menu.write();
4771 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4772 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4773 // Toggle if we're selecting the same one
4774 *context_menu = None;
4775 cx.notify();
4776 return;
4777 } else {
4778 // Otherwise, clear it and start a new one
4779 *context_menu = None;
4780 cx.notify();
4781 }
4782 }
4783 drop(context_menu);
4784 let snapshot = self.snapshot(cx);
4785 let deployed_from_indicator = action.deployed_from_indicator;
4786 let mut task = self.code_actions_task.take();
4787 let action = action.clone();
4788 cx.spawn(|editor, mut cx| async move {
4789 while let Some(prev_task) = task {
4790 prev_task.await.log_err();
4791 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4792 }
4793
4794 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4795 if editor.focus_handle.is_focused(cx) {
4796 let multibuffer_point = action
4797 .deployed_from_indicator
4798 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4799 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4800 let (buffer, buffer_row) = snapshot
4801 .buffer_snapshot
4802 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4803 .and_then(|(buffer_snapshot, range)| {
4804 editor
4805 .buffer
4806 .read(cx)
4807 .buffer(buffer_snapshot.remote_id())
4808 .map(|buffer| (buffer, range.start.row))
4809 })?;
4810 let (_, code_actions) = editor
4811 .available_code_actions
4812 .clone()
4813 .and_then(|(location, code_actions)| {
4814 let snapshot = location.buffer.read(cx).snapshot();
4815 let point_range = location.range.to_point(&snapshot);
4816 let point_range = point_range.start.row..=point_range.end.row;
4817 if point_range.contains(&buffer_row) {
4818 Some((location, code_actions))
4819 } else {
4820 None
4821 }
4822 })
4823 .unzip();
4824 let buffer_id = buffer.read(cx).remote_id();
4825 let tasks = editor
4826 .tasks
4827 .get(&(buffer_id, buffer_row))
4828 .map(|t| Arc::new(t.to_owned()));
4829 if tasks.is_none() && code_actions.is_none() {
4830 return None;
4831 }
4832
4833 editor.completion_tasks.clear();
4834 editor.discard_inline_completion(false, cx);
4835 let task_context =
4836 tasks
4837 .as_ref()
4838 .zip(editor.project.clone())
4839 .map(|(tasks, project)| {
4840 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4841 });
4842
4843 Some(cx.spawn(|editor, mut cx| async move {
4844 let task_context = match task_context {
4845 Some(task_context) => task_context.await,
4846 None => None,
4847 };
4848 let resolved_tasks =
4849 tasks.zip(task_context).map(|(tasks, task_context)| {
4850 Arc::new(ResolvedTasks {
4851 templates: tasks.resolve(&task_context).collect(),
4852 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4853 multibuffer_point.row,
4854 tasks.column,
4855 )),
4856 })
4857 });
4858 let spawn_straight_away = resolved_tasks
4859 .as_ref()
4860 .map_or(false, |tasks| tasks.templates.len() == 1)
4861 && code_actions
4862 .as_ref()
4863 .map_or(true, |actions| actions.is_empty());
4864 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4865 *editor.context_menu.write() =
4866 Some(ContextMenu::CodeActions(CodeActionsMenu {
4867 buffer,
4868 actions: CodeActionContents {
4869 tasks: resolved_tasks,
4870 actions: code_actions,
4871 },
4872 selected_item: Default::default(),
4873 scroll_handle: UniformListScrollHandle::default(),
4874 deployed_from_indicator,
4875 }));
4876 if spawn_straight_away {
4877 if let Some(task) = editor.confirm_code_action(
4878 &ConfirmCodeAction { item_ix: Some(0) },
4879 cx,
4880 ) {
4881 cx.notify();
4882 return task;
4883 }
4884 }
4885 cx.notify();
4886 Task::ready(Ok(()))
4887 }) {
4888 task.await
4889 } else {
4890 Ok(())
4891 }
4892 }))
4893 } else {
4894 Some(Task::ready(Ok(())))
4895 }
4896 })?;
4897 if let Some(task) = spawned_test_task {
4898 task.await?;
4899 }
4900
4901 Ok::<_, anyhow::Error>(())
4902 })
4903 .detach_and_log_err(cx);
4904 }
4905
4906 pub fn confirm_code_action(
4907 &mut self,
4908 action: &ConfirmCodeAction,
4909 cx: &mut ViewContext<Self>,
4910 ) -> Option<Task<Result<()>>> {
4911 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4912 menu
4913 } else {
4914 return None;
4915 };
4916 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4917 let action = actions_menu.actions.get(action_ix)?;
4918 let title = action.label();
4919 let buffer = actions_menu.buffer;
4920 let workspace = self.workspace()?;
4921
4922 match action {
4923 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4924 workspace.update(cx, |workspace, cx| {
4925 workspace::tasks::schedule_resolved_task(
4926 workspace,
4927 task_source_kind,
4928 resolved_task,
4929 false,
4930 cx,
4931 );
4932
4933 Some(Task::ready(Ok(())))
4934 })
4935 }
4936 CodeActionsItem::CodeAction {
4937 excerpt_id,
4938 action,
4939 provider,
4940 } => {
4941 let apply_code_action =
4942 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4943 let workspace = workspace.downgrade();
4944 Some(cx.spawn(|editor, cx| async move {
4945 let project_transaction = apply_code_action.await?;
4946 Self::open_project_transaction(
4947 &editor,
4948 workspace,
4949 project_transaction,
4950 title,
4951 cx,
4952 )
4953 .await
4954 }))
4955 }
4956 }
4957 }
4958
4959 pub async fn open_project_transaction(
4960 this: &WeakView<Editor>,
4961 workspace: WeakView<Workspace>,
4962 transaction: ProjectTransaction,
4963 title: String,
4964 mut cx: AsyncWindowContext,
4965 ) -> Result<()> {
4966 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4967 cx.update(|cx| {
4968 entries.sort_unstable_by_key(|(buffer, _)| {
4969 buffer.read(cx).file().map(|f| f.path().clone())
4970 });
4971 })?;
4972
4973 // If the project transaction's edits are all contained within this editor, then
4974 // avoid opening a new editor to display them.
4975
4976 if let Some((buffer, transaction)) = entries.first() {
4977 if entries.len() == 1 {
4978 let excerpt = this.update(&mut cx, |editor, cx| {
4979 editor
4980 .buffer()
4981 .read(cx)
4982 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4983 })?;
4984 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4985 if excerpted_buffer == *buffer {
4986 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4987 let excerpt_range = excerpt_range.to_offset(buffer);
4988 buffer
4989 .edited_ranges_for_transaction::<usize>(transaction)
4990 .all(|range| {
4991 excerpt_range.start <= range.start
4992 && excerpt_range.end >= range.end
4993 })
4994 })?;
4995
4996 if all_edits_within_excerpt {
4997 return Ok(());
4998 }
4999 }
5000 }
5001 }
5002 } else {
5003 return Ok(());
5004 }
5005
5006 let mut ranges_to_highlight = Vec::new();
5007 let excerpt_buffer = cx.new_model(|cx| {
5008 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5009 for (buffer_handle, transaction) in &entries {
5010 let buffer = buffer_handle.read(cx);
5011 ranges_to_highlight.extend(
5012 multibuffer.push_excerpts_with_context_lines(
5013 buffer_handle.clone(),
5014 buffer
5015 .edited_ranges_for_transaction::<usize>(transaction)
5016 .collect(),
5017 DEFAULT_MULTIBUFFER_CONTEXT,
5018 cx,
5019 ),
5020 );
5021 }
5022 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5023 multibuffer
5024 })?;
5025
5026 workspace.update(&mut cx, |workspace, cx| {
5027 let project = workspace.project().clone();
5028 let editor =
5029 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
5030 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
5031 editor.update(cx, |editor, cx| {
5032 editor.highlight_background::<Self>(
5033 &ranges_to_highlight,
5034 |theme| theme.editor_highlighted_line_background,
5035 cx,
5036 );
5037 });
5038 })?;
5039
5040 Ok(())
5041 }
5042
5043 pub fn clear_code_action_providers(&mut self) {
5044 self.code_action_providers.clear();
5045 self.available_code_actions.take();
5046 }
5047
5048 pub fn push_code_action_provider(
5049 &mut self,
5050 provider: Arc<dyn CodeActionProvider>,
5051 cx: &mut ViewContext<Self>,
5052 ) {
5053 self.code_action_providers.push(provider);
5054 self.refresh_code_actions(cx);
5055 }
5056
5057 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5058 let buffer = self.buffer.read(cx);
5059 let newest_selection = self.selections.newest_anchor().clone();
5060 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
5061 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
5062 if start_buffer != end_buffer {
5063 return None;
5064 }
5065
5066 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
5067 cx.background_executor()
5068 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5069 .await;
5070
5071 let (providers, tasks) = this.update(&mut cx, |this, cx| {
5072 let providers = this.code_action_providers.clone();
5073 let tasks = this
5074 .code_action_providers
5075 .iter()
5076 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
5077 .collect::<Vec<_>>();
5078 (providers, tasks)
5079 })?;
5080
5081 let mut actions = Vec::new();
5082 for (provider, provider_actions) in
5083 providers.into_iter().zip(future::join_all(tasks).await)
5084 {
5085 if let Some(provider_actions) = provider_actions.log_err() {
5086 actions.extend(provider_actions.into_iter().map(|action| {
5087 AvailableCodeAction {
5088 excerpt_id: newest_selection.start.excerpt_id,
5089 action,
5090 provider: provider.clone(),
5091 }
5092 }));
5093 }
5094 }
5095
5096 this.update(&mut cx, |this, cx| {
5097 this.available_code_actions = if actions.is_empty() {
5098 None
5099 } else {
5100 Some((
5101 Location {
5102 buffer: start_buffer,
5103 range: start..end,
5104 },
5105 actions.into(),
5106 ))
5107 };
5108 cx.notify();
5109 })
5110 }));
5111 None
5112 }
5113
5114 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
5115 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5116 self.show_git_blame_inline = false;
5117
5118 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
5119 cx.background_executor().timer(delay).await;
5120
5121 this.update(&mut cx, |this, cx| {
5122 this.show_git_blame_inline = true;
5123 cx.notify();
5124 })
5125 .log_err();
5126 }));
5127 }
5128 }
5129
5130 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5131 if self.pending_rename.is_some() {
5132 return None;
5133 }
5134
5135 let provider = self.semantics_provider.clone()?;
5136 let buffer = self.buffer.read(cx);
5137 let newest_selection = self.selections.newest_anchor().clone();
5138 let cursor_position = newest_selection.head();
5139 let (cursor_buffer, cursor_buffer_position) =
5140 buffer.text_anchor_for_position(cursor_position, cx)?;
5141 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5142 if cursor_buffer != tail_buffer {
5143 return None;
5144 }
5145
5146 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
5147 cx.background_executor()
5148 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
5149 .await;
5150
5151 let highlights = if let Some(highlights) = cx
5152 .update(|cx| {
5153 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5154 })
5155 .ok()
5156 .flatten()
5157 {
5158 highlights.await.log_err()
5159 } else {
5160 None
5161 };
5162
5163 if let Some(highlights) = highlights {
5164 this.update(&mut cx, |this, cx| {
5165 if this.pending_rename.is_some() {
5166 return;
5167 }
5168
5169 let buffer_id = cursor_position.buffer_id;
5170 let buffer = this.buffer.read(cx);
5171 if !buffer
5172 .text_anchor_for_position(cursor_position, cx)
5173 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5174 {
5175 return;
5176 }
5177
5178 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5179 let mut write_ranges = Vec::new();
5180 let mut read_ranges = Vec::new();
5181 for highlight in highlights {
5182 for (excerpt_id, excerpt_range) in
5183 buffer.excerpts_for_buffer(&cursor_buffer, cx)
5184 {
5185 let start = highlight
5186 .range
5187 .start
5188 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5189 let end = highlight
5190 .range
5191 .end
5192 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5193 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5194 continue;
5195 }
5196
5197 let range = Anchor {
5198 buffer_id,
5199 excerpt_id,
5200 text_anchor: start,
5201 }..Anchor {
5202 buffer_id,
5203 excerpt_id,
5204 text_anchor: end,
5205 };
5206 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5207 write_ranges.push(range);
5208 } else {
5209 read_ranges.push(range);
5210 }
5211 }
5212 }
5213
5214 this.highlight_background::<DocumentHighlightRead>(
5215 &read_ranges,
5216 |theme| theme.editor_document_highlight_read_background,
5217 cx,
5218 );
5219 this.highlight_background::<DocumentHighlightWrite>(
5220 &write_ranges,
5221 |theme| theme.editor_document_highlight_write_background,
5222 cx,
5223 );
5224 cx.notify();
5225 })
5226 .log_err();
5227 }
5228 }));
5229 None
5230 }
5231
5232 pub fn refresh_inline_completion(
5233 &mut self,
5234 debounce: bool,
5235 user_requested: bool,
5236 cx: &mut ViewContext<Self>,
5237 ) -> Option<()> {
5238 let provider = self.inline_completion_provider()?;
5239 let cursor = self.selections.newest_anchor().head();
5240 let (buffer, cursor_buffer_position) =
5241 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5242
5243 if !user_requested
5244 && (!self.enable_inline_completions
5245 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5246 || !self.is_focused(cx))
5247 {
5248 self.discard_inline_completion(false, cx);
5249 return None;
5250 }
5251
5252 self.update_visible_inline_completion(cx);
5253 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
5254 Some(())
5255 }
5256
5257 fn cycle_inline_completion(
5258 &mut self,
5259 direction: Direction,
5260 cx: &mut ViewContext<Self>,
5261 ) -> Option<()> {
5262 let provider = self.inline_completion_provider()?;
5263 let cursor = self.selections.newest_anchor().head();
5264 let (buffer, cursor_buffer_position) =
5265 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5266 if !self.enable_inline_completions
5267 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5268 {
5269 return None;
5270 }
5271
5272 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5273 self.update_visible_inline_completion(cx);
5274
5275 Some(())
5276 }
5277
5278 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5279 if !self.has_active_inline_completion() {
5280 self.refresh_inline_completion(false, true, cx);
5281 return;
5282 }
5283
5284 self.update_visible_inline_completion(cx);
5285 }
5286
5287 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5288 self.show_cursor_names(cx);
5289 }
5290
5291 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5292 self.show_cursor_names = true;
5293 cx.notify();
5294 cx.spawn(|this, mut cx| async move {
5295 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5296 this.update(&mut cx, |this, cx| {
5297 this.show_cursor_names = false;
5298 cx.notify()
5299 })
5300 .ok()
5301 })
5302 .detach();
5303 }
5304
5305 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5306 if self.has_active_inline_completion() {
5307 self.cycle_inline_completion(Direction::Next, cx);
5308 } else {
5309 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5310 if is_copilot_disabled {
5311 cx.propagate();
5312 }
5313 }
5314 }
5315
5316 pub fn previous_inline_completion(
5317 &mut self,
5318 _: &PreviousInlineCompletion,
5319 cx: &mut ViewContext<Self>,
5320 ) {
5321 if self.has_active_inline_completion() {
5322 self.cycle_inline_completion(Direction::Prev, cx);
5323 } else {
5324 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5325 if is_copilot_disabled {
5326 cx.propagate();
5327 }
5328 }
5329 }
5330
5331 pub fn accept_inline_completion(
5332 &mut self,
5333 _: &AcceptInlineCompletion,
5334 cx: &mut ViewContext<Self>,
5335 ) {
5336 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5337 return;
5338 };
5339
5340 self.report_inline_completion_event(true, cx);
5341
5342 match &active_inline_completion.completion {
5343 InlineCompletion::Move(position) => {
5344 let position = *position;
5345 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
5346 selections.select_anchor_ranges([position..position]);
5347 });
5348 }
5349 InlineCompletion::Edit(edits) => {
5350 if let Some(provider) = self.inline_completion_provider() {
5351 provider.accept(cx);
5352 }
5353
5354 let snapshot = self.buffer.read(cx).snapshot(cx);
5355 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5356
5357 self.buffer.update(cx, |buffer, cx| {
5358 buffer.edit(edits.iter().cloned(), None, cx)
5359 });
5360
5361 self.change_selections(None, cx, |s| {
5362 s.select_anchor_ranges([last_edit_end..last_edit_end])
5363 });
5364
5365 self.update_visible_inline_completion(cx);
5366 if self.active_inline_completion.is_none() {
5367 self.refresh_inline_completion(true, true, cx);
5368 }
5369
5370 cx.notify();
5371 }
5372 }
5373 }
5374
5375 pub fn accept_partial_inline_completion(
5376 &mut self,
5377 _: &AcceptPartialInlineCompletion,
5378 cx: &mut ViewContext<Self>,
5379 ) {
5380 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5381 return;
5382 };
5383 if self.selections.count() != 1 {
5384 return;
5385 }
5386
5387 self.report_inline_completion_event(true, cx);
5388
5389 match &active_inline_completion.completion {
5390 InlineCompletion::Move(position) => {
5391 let position = *position;
5392 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
5393 selections.select_anchor_ranges([position..position]);
5394 });
5395 }
5396 InlineCompletion::Edit(edits) => {
5397 if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
5398 let text = edits[0].1.as_str();
5399 let mut partial_completion = text
5400 .chars()
5401 .by_ref()
5402 .take_while(|c| c.is_alphabetic())
5403 .collect::<String>();
5404 if partial_completion.is_empty() {
5405 partial_completion = text
5406 .chars()
5407 .by_ref()
5408 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5409 .collect::<String>();
5410 }
5411
5412 cx.emit(EditorEvent::InputHandled {
5413 utf16_range_to_replace: None,
5414 text: partial_completion.clone().into(),
5415 });
5416
5417 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5418
5419 self.refresh_inline_completion(true, true, cx);
5420 cx.notify();
5421 }
5422 }
5423 }
5424 }
5425
5426 fn discard_inline_completion(
5427 &mut self,
5428 should_report_inline_completion_event: bool,
5429 cx: &mut ViewContext<Self>,
5430 ) -> bool {
5431 if should_report_inline_completion_event {
5432 self.report_inline_completion_event(false, cx);
5433 }
5434
5435 if let Some(provider) = self.inline_completion_provider() {
5436 provider.discard(cx);
5437 }
5438
5439 self.take_active_inline_completion(cx).is_some()
5440 }
5441
5442 fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
5443 let Some(provider) = self.inline_completion_provider() else {
5444 return;
5445 };
5446 let Some(project) = self.project.as_ref() else {
5447 return;
5448 };
5449 let Some((_, buffer, _)) = self
5450 .buffer
5451 .read(cx)
5452 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5453 else {
5454 return;
5455 };
5456
5457 let project = project.read(cx);
5458 let extension = buffer
5459 .read(cx)
5460 .file()
5461 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5462 project.client().telemetry().report_inline_completion_event(
5463 provider.name().into(),
5464 accepted,
5465 extension,
5466 );
5467 }
5468
5469 pub fn has_active_inline_completion(&self) -> bool {
5470 self.active_inline_completion.is_some()
5471 }
5472
5473 fn take_active_inline_completion(
5474 &mut self,
5475 cx: &mut ViewContext<Self>,
5476 ) -> Option<InlineCompletion> {
5477 let active_inline_completion = self.active_inline_completion.take()?;
5478 self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
5479 self.clear_highlights::<InlineCompletionHighlight>(cx);
5480 Some(active_inline_completion.completion)
5481 }
5482
5483 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5484 let selection = self.selections.newest_anchor();
5485 let cursor = selection.head();
5486 let multibuffer = self.buffer.read(cx).snapshot(cx);
5487 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5488 let excerpt_id = cursor.excerpt_id;
5489
5490 if self.context_menu.read().is_some()
5491 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion())
5492 || !offset_selection.is_empty()
5493 || self
5494 .active_inline_completion
5495 .as_ref()
5496 .map_or(false, |completion| {
5497 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5498 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5499 !invalidation_range.contains(&offset_selection.head())
5500 })
5501 {
5502 self.discard_inline_completion(false, cx);
5503 return None;
5504 }
5505
5506 self.take_active_inline_completion(cx);
5507 let provider = self.inline_completion_provider()?;
5508
5509 let (buffer, cursor_buffer_position) =
5510 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5511
5512 let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5513 let edits = completion
5514 .edits
5515 .into_iter()
5516 .map(|(range, new_text)| {
5517 (
5518 multibuffer
5519 .anchor_in_excerpt(excerpt_id, range.start)
5520 .unwrap()
5521 ..multibuffer
5522 .anchor_in_excerpt(excerpt_id, range.end)
5523 .unwrap(),
5524 new_text,
5525 )
5526 })
5527 .collect::<Vec<_>>();
5528 if edits.is_empty() {
5529 return None;
5530 }
5531
5532 let first_edit_start = edits.first().unwrap().0.start;
5533 let edit_start_row = first_edit_start
5534 .to_point(&multibuffer)
5535 .row
5536 .saturating_sub(2);
5537
5538 let last_edit_end = edits.last().unwrap().0.end;
5539 let edit_end_row = cmp::min(
5540 multibuffer.max_point().row,
5541 last_edit_end.to_point(&multibuffer).row + 2,
5542 );
5543
5544 let cursor_row = cursor.to_point(&multibuffer).row;
5545
5546 let mut inlay_ids = Vec::new();
5547 let invalidation_row_range;
5548 let completion;
5549 if cursor_row < edit_start_row {
5550 invalidation_row_range = cursor_row..edit_end_row;
5551 completion = InlineCompletion::Move(first_edit_start);
5552 } else if cursor_row > edit_end_row {
5553 invalidation_row_range = edit_start_row..cursor_row;
5554 completion = InlineCompletion::Move(first_edit_start);
5555 } else {
5556 if edits
5557 .iter()
5558 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5559 {
5560 let mut inlays = Vec::new();
5561 for (range, new_text) in &edits {
5562 let inlay = Inlay::suggestion(
5563 post_inc(&mut self.next_inlay_id),
5564 range.start,
5565 new_text.as_str(),
5566 );
5567 inlay_ids.push(inlay.id);
5568 inlays.push(inlay);
5569 }
5570
5571 self.splice_inlays(vec![], inlays, cx);
5572 } else {
5573 let background_color = cx.theme().status().deleted_background;
5574 self.highlight_text::<InlineCompletionHighlight>(
5575 edits.iter().map(|(range, _)| range.clone()).collect(),
5576 HighlightStyle {
5577 background_color: Some(background_color),
5578 ..Default::default()
5579 },
5580 cx,
5581 );
5582 }
5583
5584 invalidation_row_range = edit_start_row..edit_end_row;
5585 completion = InlineCompletion::Edit(edits);
5586 };
5587
5588 let invalidation_range = multibuffer
5589 .anchor_before(Point::new(invalidation_row_range.start, 0))
5590 ..multibuffer.anchor_after(Point::new(
5591 invalidation_row_range.end,
5592 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5593 ));
5594
5595 self.active_inline_completion = Some(InlineCompletionState {
5596 inlay_ids,
5597 completion,
5598 invalidation_range,
5599 });
5600 cx.notify();
5601
5602 Some(())
5603 }
5604
5605 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5606 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5607 }
5608
5609 fn render_code_actions_indicator(
5610 &self,
5611 _style: &EditorStyle,
5612 row: DisplayRow,
5613 is_active: bool,
5614 cx: &mut ViewContext<Self>,
5615 ) -> Option<IconButton> {
5616 if self.available_code_actions.is_some() {
5617 Some(
5618 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5619 .shape(ui::IconButtonShape::Square)
5620 .icon_size(IconSize::XSmall)
5621 .icon_color(Color::Muted)
5622 .selected(is_active)
5623 .tooltip({
5624 let focus_handle = self.focus_handle.clone();
5625 move |cx| {
5626 Tooltip::for_action_in(
5627 "Toggle Code Actions",
5628 &ToggleCodeActions {
5629 deployed_from_indicator: None,
5630 },
5631 &focus_handle,
5632 cx,
5633 )
5634 }
5635 })
5636 .on_click(cx.listener(move |editor, _e, cx| {
5637 editor.focus(cx);
5638 editor.toggle_code_actions(
5639 &ToggleCodeActions {
5640 deployed_from_indicator: Some(row),
5641 },
5642 cx,
5643 );
5644 })),
5645 )
5646 } else {
5647 None
5648 }
5649 }
5650
5651 fn clear_tasks(&mut self) {
5652 self.tasks.clear()
5653 }
5654
5655 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5656 if self.tasks.insert(key, value).is_some() {
5657 // This case should hopefully be rare, but just in case...
5658 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5659 }
5660 }
5661
5662 fn build_tasks_context(
5663 project: &Model<Project>,
5664 buffer: &Model<Buffer>,
5665 buffer_row: u32,
5666 tasks: &Arc<RunnableTasks>,
5667 cx: &mut ViewContext<Self>,
5668 ) -> Task<Option<task::TaskContext>> {
5669 let position = Point::new(buffer_row, tasks.column);
5670 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5671 let location = Location {
5672 buffer: buffer.clone(),
5673 range: range_start..range_start,
5674 };
5675 // Fill in the environmental variables from the tree-sitter captures
5676 let mut captured_task_variables = TaskVariables::default();
5677 for (capture_name, value) in tasks.extra_variables.clone() {
5678 captured_task_variables.insert(
5679 task::VariableName::Custom(capture_name.into()),
5680 value.clone(),
5681 );
5682 }
5683 project.update(cx, |project, cx| {
5684 project.task_store().update(cx, |task_store, cx| {
5685 task_store.task_context_for_location(captured_task_variables, location, cx)
5686 })
5687 })
5688 }
5689
5690 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
5691 let Some((workspace, _)) = self.workspace.clone() else {
5692 return;
5693 };
5694 let Some(project) = self.project.clone() else {
5695 return;
5696 };
5697
5698 // Try to find a closest, enclosing node using tree-sitter that has a
5699 // task
5700 let Some((buffer, buffer_row, tasks)) = self
5701 .find_enclosing_node_task(cx)
5702 // Or find the task that's closest in row-distance.
5703 .or_else(|| self.find_closest_task(cx))
5704 else {
5705 return;
5706 };
5707
5708 let reveal_strategy = action.reveal;
5709 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5710 cx.spawn(|_, mut cx| async move {
5711 let context = task_context.await?;
5712 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5713
5714 let resolved = resolved_task.resolved.as_mut()?;
5715 resolved.reveal = reveal_strategy;
5716
5717 workspace
5718 .update(&mut cx, |workspace, cx| {
5719 workspace::tasks::schedule_resolved_task(
5720 workspace,
5721 task_source_kind,
5722 resolved_task,
5723 false,
5724 cx,
5725 );
5726 })
5727 .ok()
5728 })
5729 .detach();
5730 }
5731
5732 fn find_closest_task(
5733 &mut self,
5734 cx: &mut ViewContext<Self>,
5735 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5736 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5737
5738 let ((buffer_id, row), tasks) = self
5739 .tasks
5740 .iter()
5741 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5742
5743 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5744 let tasks = Arc::new(tasks.to_owned());
5745 Some((buffer, *row, tasks))
5746 }
5747
5748 fn find_enclosing_node_task(
5749 &mut self,
5750 cx: &mut ViewContext<Self>,
5751 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5752 let snapshot = self.buffer.read(cx).snapshot(cx);
5753 let offset = self.selections.newest::<usize>(cx).head();
5754 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5755 let buffer_id = excerpt.buffer().remote_id();
5756
5757 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5758 let mut cursor = layer.node().walk();
5759
5760 while cursor.goto_first_child_for_byte(offset).is_some() {
5761 if cursor.node().end_byte() == offset {
5762 cursor.goto_next_sibling();
5763 }
5764 }
5765
5766 // Ascend to the smallest ancestor that contains the range and has a task.
5767 loop {
5768 let node = cursor.node();
5769 let node_range = node.byte_range();
5770 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5771
5772 // Check if this node contains our offset
5773 if node_range.start <= offset && node_range.end >= offset {
5774 // If it contains offset, check for task
5775 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5776 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5777 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5778 }
5779 }
5780
5781 if !cursor.goto_parent() {
5782 break;
5783 }
5784 }
5785 None
5786 }
5787
5788 fn render_run_indicator(
5789 &self,
5790 _style: &EditorStyle,
5791 is_active: bool,
5792 row: DisplayRow,
5793 cx: &mut ViewContext<Self>,
5794 ) -> IconButton {
5795 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5796 .shape(ui::IconButtonShape::Square)
5797 .icon_size(IconSize::XSmall)
5798 .icon_color(Color::Muted)
5799 .selected(is_active)
5800 .on_click(cx.listener(move |editor, _e, cx| {
5801 editor.focus(cx);
5802 editor.toggle_code_actions(
5803 &ToggleCodeActions {
5804 deployed_from_indicator: Some(row),
5805 },
5806 cx,
5807 );
5808 }))
5809 }
5810
5811 pub fn context_menu_visible(&self) -> bool {
5812 self.context_menu
5813 .read()
5814 .as_ref()
5815 .map_or(false, |menu| menu.visible())
5816 }
5817
5818 fn render_context_menu(
5819 &self,
5820 cursor_position: DisplayPoint,
5821 style: &EditorStyle,
5822 max_height: Pixels,
5823 cx: &mut ViewContext<Editor>,
5824 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5825 self.context_menu.read().as_ref().map(|menu| {
5826 menu.render(
5827 cursor_position,
5828 style,
5829 max_height,
5830 self.workspace.as_ref().map(|(w, _)| w.clone()),
5831 cx,
5832 )
5833 })
5834 }
5835
5836 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5837 cx.notify();
5838 self.completion_tasks.clear();
5839 let context_menu = self.context_menu.write().take();
5840 if context_menu.is_some() {
5841 self.update_visible_inline_completion(cx);
5842 }
5843 context_menu
5844 }
5845
5846 fn show_snippet_choices(
5847 &mut self,
5848 choices: &Vec<String>,
5849 selection: Range<Anchor>,
5850 cx: &mut ViewContext<Self>,
5851 ) {
5852 if selection.start.buffer_id.is_none() {
5853 return;
5854 }
5855 let buffer_id = selection.start.buffer_id.unwrap();
5856 let buffer = self.buffer().read(cx).buffer(buffer_id);
5857 let id = post_inc(&mut self.next_completion_id);
5858
5859 if let Some(buffer) = buffer {
5860 *self.context_menu.write() = Some(ContextMenu::Completions(
5861 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer)
5862 .suppress_documentation_resolution(),
5863 ));
5864 }
5865 }
5866
5867 pub fn insert_snippet(
5868 &mut self,
5869 insertion_ranges: &[Range<usize>],
5870 snippet: Snippet,
5871 cx: &mut ViewContext<Self>,
5872 ) -> Result<()> {
5873 struct Tabstop<T> {
5874 is_end_tabstop: bool,
5875 ranges: Vec<Range<T>>,
5876 choices: Option<Vec<String>>,
5877 }
5878
5879 let tabstops = self.buffer.update(cx, |buffer, cx| {
5880 let snippet_text: Arc<str> = snippet.text.clone().into();
5881 buffer.edit(
5882 insertion_ranges
5883 .iter()
5884 .cloned()
5885 .map(|range| (range, snippet_text.clone())),
5886 Some(AutoindentMode::EachLine),
5887 cx,
5888 );
5889
5890 let snapshot = &*buffer.read(cx);
5891 let snippet = &snippet;
5892 snippet
5893 .tabstops
5894 .iter()
5895 .map(|tabstop| {
5896 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5897 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5898 });
5899 let mut tabstop_ranges = tabstop
5900 .ranges
5901 .iter()
5902 .flat_map(|tabstop_range| {
5903 let mut delta = 0_isize;
5904 insertion_ranges.iter().map(move |insertion_range| {
5905 let insertion_start = insertion_range.start as isize + delta;
5906 delta +=
5907 snippet.text.len() as isize - insertion_range.len() as isize;
5908
5909 let start = ((insertion_start + tabstop_range.start) as usize)
5910 .min(snapshot.len());
5911 let end = ((insertion_start + tabstop_range.end) as usize)
5912 .min(snapshot.len());
5913 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5914 })
5915 })
5916 .collect::<Vec<_>>();
5917 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5918
5919 Tabstop {
5920 is_end_tabstop,
5921 ranges: tabstop_ranges,
5922 choices: tabstop.choices.clone(),
5923 }
5924 })
5925 .collect::<Vec<_>>()
5926 });
5927 if let Some(tabstop) = tabstops.first() {
5928 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5929 s.select_ranges(tabstop.ranges.iter().cloned());
5930 });
5931
5932 if let Some(choices) = &tabstop.choices {
5933 if let Some(selection) = tabstop.ranges.first() {
5934 self.show_snippet_choices(choices, selection.clone(), cx)
5935 }
5936 }
5937
5938 // If we're already at the last tabstop and it's at the end of the snippet,
5939 // we're done, we don't need to keep the state around.
5940 if !tabstop.is_end_tabstop {
5941 let choices = tabstops
5942 .iter()
5943 .map(|tabstop| tabstop.choices.clone())
5944 .collect();
5945
5946 let ranges = tabstops
5947 .into_iter()
5948 .map(|tabstop| tabstop.ranges)
5949 .collect::<Vec<_>>();
5950
5951 self.snippet_stack.push(SnippetState {
5952 active_index: 0,
5953 ranges,
5954 choices,
5955 });
5956 }
5957
5958 // Check whether the just-entered snippet ends with an auto-closable bracket.
5959 if self.autoclose_regions.is_empty() {
5960 let snapshot = self.buffer.read(cx).snapshot(cx);
5961 for selection in &mut self.selections.all::<Point>(cx) {
5962 let selection_head = selection.head();
5963 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5964 continue;
5965 };
5966
5967 let mut bracket_pair = None;
5968 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5969 let prev_chars = snapshot
5970 .reversed_chars_at(selection_head)
5971 .collect::<String>();
5972 for (pair, enabled) in scope.brackets() {
5973 if enabled
5974 && pair.close
5975 && prev_chars.starts_with(pair.start.as_str())
5976 && next_chars.starts_with(pair.end.as_str())
5977 {
5978 bracket_pair = Some(pair.clone());
5979 break;
5980 }
5981 }
5982 if let Some(pair) = bracket_pair {
5983 let start = snapshot.anchor_after(selection_head);
5984 let end = snapshot.anchor_after(selection_head);
5985 self.autoclose_regions.push(AutocloseRegion {
5986 selection_id: selection.id,
5987 range: start..end,
5988 pair,
5989 });
5990 }
5991 }
5992 }
5993 }
5994 Ok(())
5995 }
5996
5997 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5998 self.move_to_snippet_tabstop(Bias::Right, cx)
5999 }
6000
6001 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
6002 self.move_to_snippet_tabstop(Bias::Left, cx)
6003 }
6004
6005 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
6006 if let Some(mut snippet) = self.snippet_stack.pop() {
6007 match bias {
6008 Bias::Left => {
6009 if snippet.active_index > 0 {
6010 snippet.active_index -= 1;
6011 } else {
6012 self.snippet_stack.push(snippet);
6013 return false;
6014 }
6015 }
6016 Bias::Right => {
6017 if snippet.active_index + 1 < snippet.ranges.len() {
6018 snippet.active_index += 1;
6019 } else {
6020 self.snippet_stack.push(snippet);
6021 return false;
6022 }
6023 }
6024 }
6025 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6026 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6027 s.select_anchor_ranges(current_ranges.iter().cloned())
6028 });
6029
6030 if let Some(choices) = &snippet.choices[snippet.active_index] {
6031 if let Some(selection) = current_ranges.first() {
6032 self.show_snippet_choices(&choices, selection.clone(), cx);
6033 }
6034 }
6035
6036 // If snippet state is not at the last tabstop, push it back on the stack
6037 if snippet.active_index + 1 < snippet.ranges.len() {
6038 self.snippet_stack.push(snippet);
6039 }
6040 return true;
6041 }
6042 }
6043
6044 false
6045 }
6046
6047 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
6048 self.transact(cx, |this, cx| {
6049 this.select_all(&SelectAll, cx);
6050 this.insert("", cx);
6051 });
6052 }
6053
6054 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
6055 self.transact(cx, |this, cx| {
6056 this.select_autoclose_pair(cx);
6057 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6058 if !this.linked_edit_ranges.is_empty() {
6059 let selections = this.selections.all::<MultiBufferPoint>(cx);
6060 let snapshot = this.buffer.read(cx).snapshot(cx);
6061
6062 for selection in selections.iter() {
6063 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6064 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6065 if selection_start.buffer_id != selection_end.buffer_id {
6066 continue;
6067 }
6068 if let Some(ranges) =
6069 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6070 {
6071 for (buffer, entries) in ranges {
6072 linked_ranges.entry(buffer).or_default().extend(entries);
6073 }
6074 }
6075 }
6076 }
6077
6078 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6079 if !this.selections.line_mode {
6080 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6081 for selection in &mut selections {
6082 if selection.is_empty() {
6083 let old_head = selection.head();
6084 let mut new_head =
6085 movement::left(&display_map, old_head.to_display_point(&display_map))
6086 .to_point(&display_map);
6087 if let Some((buffer, line_buffer_range)) = display_map
6088 .buffer_snapshot
6089 .buffer_line_for_row(MultiBufferRow(old_head.row))
6090 {
6091 let indent_size =
6092 buffer.indent_size_for_line(line_buffer_range.start.row);
6093 let indent_len = match indent_size.kind {
6094 IndentKind::Space => {
6095 buffer.settings_at(line_buffer_range.start, cx).tab_size
6096 }
6097 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6098 };
6099 if old_head.column <= indent_size.len && old_head.column > 0 {
6100 let indent_len = indent_len.get();
6101 new_head = cmp::min(
6102 new_head,
6103 MultiBufferPoint::new(
6104 old_head.row,
6105 ((old_head.column - 1) / indent_len) * indent_len,
6106 ),
6107 );
6108 }
6109 }
6110
6111 selection.set_head(new_head, SelectionGoal::None);
6112 }
6113 }
6114 }
6115
6116 this.signature_help_state.set_backspace_pressed(true);
6117 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6118 this.insert("", cx);
6119 let empty_str: Arc<str> = Arc::from("");
6120 for (buffer, edits) in linked_ranges {
6121 let snapshot = buffer.read(cx).snapshot();
6122 use text::ToPoint as TP;
6123
6124 let edits = edits
6125 .into_iter()
6126 .map(|range| {
6127 let end_point = TP::to_point(&range.end, &snapshot);
6128 let mut start_point = TP::to_point(&range.start, &snapshot);
6129
6130 if end_point == start_point {
6131 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6132 .saturating_sub(1);
6133 start_point = TP::to_point(&offset, &snapshot);
6134 };
6135
6136 (start_point..end_point, empty_str.clone())
6137 })
6138 .sorted_by_key(|(range, _)| range.start)
6139 .collect::<Vec<_>>();
6140 buffer.update(cx, |this, cx| {
6141 this.edit(edits, None, cx);
6142 })
6143 }
6144 this.refresh_inline_completion(true, false, cx);
6145 linked_editing_ranges::refresh_linked_ranges(this, cx);
6146 });
6147 }
6148
6149 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
6150 self.transact(cx, |this, cx| {
6151 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6152 let line_mode = s.line_mode;
6153 s.move_with(|map, selection| {
6154 if selection.is_empty() && !line_mode {
6155 let cursor = movement::right(map, selection.head());
6156 selection.end = cursor;
6157 selection.reversed = true;
6158 selection.goal = SelectionGoal::None;
6159 }
6160 })
6161 });
6162 this.insert("", cx);
6163 this.refresh_inline_completion(true, false, cx);
6164 });
6165 }
6166
6167 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
6168 if self.move_to_prev_snippet_tabstop(cx) {
6169 return;
6170 }
6171
6172 self.outdent(&Outdent, cx);
6173 }
6174
6175 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
6176 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
6177 return;
6178 }
6179
6180 let mut selections = self.selections.all_adjusted(cx);
6181 let buffer = self.buffer.read(cx);
6182 let snapshot = buffer.snapshot(cx);
6183 let rows_iter = selections.iter().map(|s| s.head().row);
6184 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6185
6186 let mut edits = Vec::new();
6187 let mut prev_edited_row = 0;
6188 let mut row_delta = 0;
6189 for selection in &mut selections {
6190 if selection.start.row != prev_edited_row {
6191 row_delta = 0;
6192 }
6193 prev_edited_row = selection.end.row;
6194
6195 // If the selection is non-empty, then increase the indentation of the selected lines.
6196 if !selection.is_empty() {
6197 row_delta =
6198 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6199 continue;
6200 }
6201
6202 // If the selection is empty and the cursor is in the leading whitespace before the
6203 // suggested indentation, then auto-indent the line.
6204 let cursor = selection.head();
6205 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6206 if let Some(suggested_indent) =
6207 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6208 {
6209 if cursor.column < suggested_indent.len
6210 && cursor.column <= current_indent.len
6211 && current_indent.len <= suggested_indent.len
6212 {
6213 selection.start = Point::new(cursor.row, suggested_indent.len);
6214 selection.end = selection.start;
6215 if row_delta == 0 {
6216 edits.extend(Buffer::edit_for_indent_size_adjustment(
6217 cursor.row,
6218 current_indent,
6219 suggested_indent,
6220 ));
6221 row_delta = suggested_indent.len - current_indent.len;
6222 }
6223 continue;
6224 }
6225 }
6226
6227 // Otherwise, insert a hard or soft tab.
6228 let settings = buffer.settings_at(cursor, cx);
6229 let tab_size = if settings.hard_tabs {
6230 IndentSize::tab()
6231 } else {
6232 let tab_size = settings.tab_size.get();
6233 let char_column = snapshot
6234 .text_for_range(Point::new(cursor.row, 0)..cursor)
6235 .flat_map(str::chars)
6236 .count()
6237 + row_delta as usize;
6238 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6239 IndentSize::spaces(chars_to_next_tab_stop)
6240 };
6241 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6242 selection.end = selection.start;
6243 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6244 row_delta += tab_size.len;
6245 }
6246
6247 self.transact(cx, |this, cx| {
6248 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6249 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6250 this.refresh_inline_completion(true, false, cx);
6251 });
6252 }
6253
6254 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
6255 if self.read_only(cx) {
6256 return;
6257 }
6258 let mut selections = self.selections.all::<Point>(cx);
6259 let mut prev_edited_row = 0;
6260 let mut row_delta = 0;
6261 let mut edits = Vec::new();
6262 let buffer = self.buffer.read(cx);
6263 let snapshot = buffer.snapshot(cx);
6264 for selection in &mut selections {
6265 if selection.start.row != prev_edited_row {
6266 row_delta = 0;
6267 }
6268 prev_edited_row = selection.end.row;
6269
6270 row_delta =
6271 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6272 }
6273
6274 self.transact(cx, |this, cx| {
6275 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6276 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6277 });
6278 }
6279
6280 fn indent_selection(
6281 buffer: &MultiBuffer,
6282 snapshot: &MultiBufferSnapshot,
6283 selection: &mut Selection<Point>,
6284 edits: &mut Vec<(Range<Point>, String)>,
6285 delta_for_start_row: u32,
6286 cx: &AppContext,
6287 ) -> u32 {
6288 let settings = buffer.settings_at(selection.start, cx);
6289 let tab_size = settings.tab_size.get();
6290 let indent_kind = if settings.hard_tabs {
6291 IndentKind::Tab
6292 } else {
6293 IndentKind::Space
6294 };
6295 let mut start_row = selection.start.row;
6296 let mut end_row = selection.end.row + 1;
6297
6298 // If a selection ends at the beginning of a line, don't indent
6299 // that last line.
6300 if selection.end.column == 0 && selection.end.row > selection.start.row {
6301 end_row -= 1;
6302 }
6303
6304 // Avoid re-indenting a row that has already been indented by a
6305 // previous selection, but still update this selection's column
6306 // to reflect that indentation.
6307 if delta_for_start_row > 0 {
6308 start_row += 1;
6309 selection.start.column += delta_for_start_row;
6310 if selection.end.row == selection.start.row {
6311 selection.end.column += delta_for_start_row;
6312 }
6313 }
6314
6315 let mut delta_for_end_row = 0;
6316 let has_multiple_rows = start_row + 1 != end_row;
6317 for row in start_row..end_row {
6318 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6319 let indent_delta = match (current_indent.kind, indent_kind) {
6320 (IndentKind::Space, IndentKind::Space) => {
6321 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6322 IndentSize::spaces(columns_to_next_tab_stop)
6323 }
6324 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6325 (_, IndentKind::Tab) => IndentSize::tab(),
6326 };
6327
6328 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6329 0
6330 } else {
6331 selection.start.column
6332 };
6333 let row_start = Point::new(row, start);
6334 edits.push((
6335 row_start..row_start,
6336 indent_delta.chars().collect::<String>(),
6337 ));
6338
6339 // Update this selection's endpoints to reflect the indentation.
6340 if row == selection.start.row {
6341 selection.start.column += indent_delta.len;
6342 }
6343 if row == selection.end.row {
6344 selection.end.column += indent_delta.len;
6345 delta_for_end_row = indent_delta.len;
6346 }
6347 }
6348
6349 if selection.start.row == selection.end.row {
6350 delta_for_start_row + delta_for_end_row
6351 } else {
6352 delta_for_end_row
6353 }
6354 }
6355
6356 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
6357 if self.read_only(cx) {
6358 return;
6359 }
6360 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6361 let selections = self.selections.all::<Point>(cx);
6362 let mut deletion_ranges = Vec::new();
6363 let mut last_outdent = None;
6364 {
6365 let buffer = self.buffer.read(cx);
6366 let snapshot = buffer.snapshot(cx);
6367 for selection in &selections {
6368 let settings = buffer.settings_at(selection.start, cx);
6369 let tab_size = settings.tab_size.get();
6370 let mut rows = selection.spanned_rows(false, &display_map);
6371
6372 // Avoid re-outdenting a row that has already been outdented by a
6373 // previous selection.
6374 if let Some(last_row) = last_outdent {
6375 if last_row == rows.start {
6376 rows.start = rows.start.next_row();
6377 }
6378 }
6379 let has_multiple_rows = rows.len() > 1;
6380 for row in rows.iter_rows() {
6381 let indent_size = snapshot.indent_size_for_line(row);
6382 if indent_size.len > 0 {
6383 let deletion_len = match indent_size.kind {
6384 IndentKind::Space => {
6385 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6386 if columns_to_prev_tab_stop == 0 {
6387 tab_size
6388 } else {
6389 columns_to_prev_tab_stop
6390 }
6391 }
6392 IndentKind::Tab => 1,
6393 };
6394 let start = if has_multiple_rows
6395 || deletion_len > selection.start.column
6396 || indent_size.len < selection.start.column
6397 {
6398 0
6399 } else {
6400 selection.start.column - deletion_len
6401 };
6402 deletion_ranges.push(
6403 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6404 );
6405 last_outdent = Some(row);
6406 }
6407 }
6408 }
6409 }
6410
6411 self.transact(cx, |this, cx| {
6412 this.buffer.update(cx, |buffer, cx| {
6413 let empty_str: Arc<str> = Arc::default();
6414 buffer.edit(
6415 deletion_ranges
6416 .into_iter()
6417 .map(|range| (range, empty_str.clone())),
6418 None,
6419 cx,
6420 );
6421 });
6422 let selections = this.selections.all::<usize>(cx);
6423 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6424 });
6425 }
6426
6427 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
6428 if self.read_only(cx) {
6429 return;
6430 }
6431 let selections = self
6432 .selections
6433 .all::<usize>(cx)
6434 .into_iter()
6435 .map(|s| s.range());
6436
6437 self.transact(cx, |this, cx| {
6438 this.buffer.update(cx, |buffer, cx| {
6439 buffer.autoindent_ranges(selections, cx);
6440 });
6441 let selections = this.selections.all::<usize>(cx);
6442 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6443 });
6444 }
6445
6446 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
6447 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6448 let selections = self.selections.all::<Point>(cx);
6449
6450 let mut new_cursors = Vec::new();
6451 let mut edit_ranges = Vec::new();
6452 let mut selections = selections.iter().peekable();
6453 while let Some(selection) = selections.next() {
6454 let mut rows = selection.spanned_rows(false, &display_map);
6455 let goal_display_column = selection.head().to_display_point(&display_map).column();
6456
6457 // Accumulate contiguous regions of rows that we want to delete.
6458 while let Some(next_selection) = selections.peek() {
6459 let next_rows = next_selection.spanned_rows(false, &display_map);
6460 if next_rows.start <= rows.end {
6461 rows.end = next_rows.end;
6462 selections.next().unwrap();
6463 } else {
6464 break;
6465 }
6466 }
6467
6468 let buffer = &display_map.buffer_snapshot;
6469 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6470 let edit_end;
6471 let cursor_buffer_row;
6472 if buffer.max_point().row >= rows.end.0 {
6473 // If there's a line after the range, delete the \n from the end of the row range
6474 // and position the cursor on the next line.
6475 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6476 cursor_buffer_row = rows.end;
6477 } else {
6478 // If there isn't a line after the range, delete the \n from the line before the
6479 // start of the row range and position the cursor there.
6480 edit_start = edit_start.saturating_sub(1);
6481 edit_end = buffer.len();
6482 cursor_buffer_row = rows.start.previous_row();
6483 }
6484
6485 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6486 *cursor.column_mut() =
6487 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6488
6489 new_cursors.push((
6490 selection.id,
6491 buffer.anchor_after(cursor.to_point(&display_map)),
6492 ));
6493 edit_ranges.push(edit_start..edit_end);
6494 }
6495
6496 self.transact(cx, |this, cx| {
6497 let buffer = this.buffer.update(cx, |buffer, cx| {
6498 let empty_str: Arc<str> = Arc::default();
6499 buffer.edit(
6500 edit_ranges
6501 .into_iter()
6502 .map(|range| (range, empty_str.clone())),
6503 None,
6504 cx,
6505 );
6506 buffer.snapshot(cx)
6507 });
6508 let new_selections = new_cursors
6509 .into_iter()
6510 .map(|(id, cursor)| {
6511 let cursor = cursor.to_point(&buffer);
6512 Selection {
6513 id,
6514 start: cursor,
6515 end: cursor,
6516 reversed: false,
6517 goal: SelectionGoal::None,
6518 }
6519 })
6520 .collect();
6521
6522 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6523 s.select(new_selections);
6524 });
6525 });
6526 }
6527
6528 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6529 if self.read_only(cx) {
6530 return;
6531 }
6532 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6533 for selection in self.selections.all::<Point>(cx) {
6534 let start = MultiBufferRow(selection.start.row);
6535 // Treat single line selections as if they include the next line. Otherwise this action
6536 // would do nothing for single line selections individual cursors.
6537 let end = if selection.start.row == selection.end.row {
6538 MultiBufferRow(selection.start.row + 1)
6539 } else {
6540 MultiBufferRow(selection.end.row)
6541 };
6542
6543 if let Some(last_row_range) = row_ranges.last_mut() {
6544 if start <= last_row_range.end {
6545 last_row_range.end = end;
6546 continue;
6547 }
6548 }
6549 row_ranges.push(start..end);
6550 }
6551
6552 let snapshot = self.buffer.read(cx).snapshot(cx);
6553 let mut cursor_positions = Vec::new();
6554 for row_range in &row_ranges {
6555 let anchor = snapshot.anchor_before(Point::new(
6556 row_range.end.previous_row().0,
6557 snapshot.line_len(row_range.end.previous_row()),
6558 ));
6559 cursor_positions.push(anchor..anchor);
6560 }
6561
6562 self.transact(cx, |this, cx| {
6563 for row_range in row_ranges.into_iter().rev() {
6564 for row in row_range.iter_rows().rev() {
6565 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6566 let next_line_row = row.next_row();
6567 let indent = snapshot.indent_size_for_line(next_line_row);
6568 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6569
6570 let replace = if snapshot.line_len(next_line_row) > indent.len {
6571 " "
6572 } else {
6573 ""
6574 };
6575
6576 this.buffer.update(cx, |buffer, cx| {
6577 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6578 });
6579 }
6580 }
6581
6582 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6583 s.select_anchor_ranges(cursor_positions)
6584 });
6585 });
6586 }
6587
6588 pub fn sort_lines_case_sensitive(
6589 &mut self,
6590 _: &SortLinesCaseSensitive,
6591 cx: &mut ViewContext<Self>,
6592 ) {
6593 self.manipulate_lines(cx, |lines| lines.sort())
6594 }
6595
6596 pub fn sort_lines_case_insensitive(
6597 &mut self,
6598 _: &SortLinesCaseInsensitive,
6599 cx: &mut ViewContext<Self>,
6600 ) {
6601 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6602 }
6603
6604 pub fn unique_lines_case_insensitive(
6605 &mut self,
6606 _: &UniqueLinesCaseInsensitive,
6607 cx: &mut ViewContext<Self>,
6608 ) {
6609 self.manipulate_lines(cx, |lines| {
6610 let mut seen = HashSet::default();
6611 lines.retain(|line| seen.insert(line.to_lowercase()));
6612 })
6613 }
6614
6615 pub fn unique_lines_case_sensitive(
6616 &mut self,
6617 _: &UniqueLinesCaseSensitive,
6618 cx: &mut ViewContext<Self>,
6619 ) {
6620 self.manipulate_lines(cx, |lines| {
6621 let mut seen = HashSet::default();
6622 lines.retain(|line| seen.insert(*line));
6623 })
6624 }
6625
6626 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6627 let mut revert_changes = HashMap::default();
6628 let snapshot = self.snapshot(cx);
6629 for hunk in hunks_for_ranges(
6630 Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
6631 &snapshot,
6632 ) {
6633 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6634 }
6635 if !revert_changes.is_empty() {
6636 self.transact(cx, |editor, cx| {
6637 editor.revert(revert_changes, cx);
6638 });
6639 }
6640 }
6641
6642 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6643 let Some(project) = self.project.clone() else {
6644 return;
6645 };
6646 self.reload(project, cx).detach_and_notify_err(cx);
6647 }
6648
6649 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6650 let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
6651 if !revert_changes.is_empty() {
6652 self.transact(cx, |editor, cx| {
6653 editor.revert(revert_changes, cx);
6654 });
6655 }
6656 }
6657
6658 fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
6659 let snapshot = self.buffer.read(cx).read(cx);
6660 if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
6661 drop(snapshot);
6662 let mut revert_changes = HashMap::default();
6663 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6664 if !revert_changes.is_empty() {
6665 self.revert(revert_changes, cx)
6666 }
6667 }
6668 }
6669
6670 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6671 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6672 let project_path = buffer.read(cx).project_path(cx)?;
6673 let project = self.project.as_ref()?.read(cx);
6674 let entry = project.entry_for_path(&project_path, cx)?;
6675 let parent = match &entry.canonical_path {
6676 Some(canonical_path) => canonical_path.to_path_buf(),
6677 None => project.absolute_path(&project_path, cx)?,
6678 }
6679 .parent()?
6680 .to_path_buf();
6681 Some(parent)
6682 }) {
6683 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6684 }
6685 }
6686
6687 fn gather_revert_changes(
6688 &mut self,
6689 selections: &[Selection<Point>],
6690 cx: &mut ViewContext<'_, Editor>,
6691 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6692 let mut revert_changes = HashMap::default();
6693 let snapshot = self.snapshot(cx);
6694 for hunk in hunks_for_selections(&snapshot, selections) {
6695 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6696 }
6697 revert_changes
6698 }
6699
6700 pub fn prepare_revert_change(
6701 &mut self,
6702 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6703 hunk: &MultiBufferDiffHunk,
6704 cx: &AppContext,
6705 ) -> Option<()> {
6706 let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
6707 let buffer = buffer.read(cx);
6708 let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
6709 let original_text = change_set
6710 .read(cx)
6711 .base_text
6712 .as_ref()?
6713 .read(cx)
6714 .as_rope()
6715 .slice(hunk.diff_base_byte_range.clone());
6716 let buffer_snapshot = buffer.snapshot();
6717 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6718 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6719 probe
6720 .0
6721 .start
6722 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6723 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6724 }) {
6725 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6726 Some(())
6727 } else {
6728 None
6729 }
6730 }
6731
6732 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6733 self.manipulate_lines(cx, |lines| lines.reverse())
6734 }
6735
6736 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6737 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6738 }
6739
6740 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6741 where
6742 Fn: FnMut(&mut Vec<&str>),
6743 {
6744 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6745 let buffer = self.buffer.read(cx).snapshot(cx);
6746
6747 let mut edits = Vec::new();
6748
6749 let selections = self.selections.all::<Point>(cx);
6750 let mut selections = selections.iter().peekable();
6751 let mut contiguous_row_selections = Vec::new();
6752 let mut new_selections = Vec::new();
6753 let mut added_lines = 0;
6754 let mut removed_lines = 0;
6755
6756 while let Some(selection) = selections.next() {
6757 let (start_row, end_row) = consume_contiguous_rows(
6758 &mut contiguous_row_selections,
6759 selection,
6760 &display_map,
6761 &mut selections,
6762 );
6763
6764 let start_point = Point::new(start_row.0, 0);
6765 let end_point = Point::new(
6766 end_row.previous_row().0,
6767 buffer.line_len(end_row.previous_row()),
6768 );
6769 let text = buffer
6770 .text_for_range(start_point..end_point)
6771 .collect::<String>();
6772
6773 let mut lines = text.split('\n').collect_vec();
6774
6775 let lines_before = lines.len();
6776 callback(&mut lines);
6777 let lines_after = lines.len();
6778
6779 edits.push((start_point..end_point, lines.join("\n")));
6780
6781 // Selections must change based on added and removed line count
6782 let start_row =
6783 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6784 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6785 new_selections.push(Selection {
6786 id: selection.id,
6787 start: start_row,
6788 end: end_row,
6789 goal: SelectionGoal::None,
6790 reversed: selection.reversed,
6791 });
6792
6793 if lines_after > lines_before {
6794 added_lines += lines_after - lines_before;
6795 } else if lines_before > lines_after {
6796 removed_lines += lines_before - lines_after;
6797 }
6798 }
6799
6800 self.transact(cx, |this, cx| {
6801 let buffer = this.buffer.update(cx, |buffer, cx| {
6802 buffer.edit(edits, None, cx);
6803 buffer.snapshot(cx)
6804 });
6805
6806 // Recalculate offsets on newly edited buffer
6807 let new_selections = new_selections
6808 .iter()
6809 .map(|s| {
6810 let start_point = Point::new(s.start.0, 0);
6811 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6812 Selection {
6813 id: s.id,
6814 start: buffer.point_to_offset(start_point),
6815 end: buffer.point_to_offset(end_point),
6816 goal: s.goal,
6817 reversed: s.reversed,
6818 }
6819 })
6820 .collect();
6821
6822 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6823 s.select(new_selections);
6824 });
6825
6826 this.request_autoscroll(Autoscroll::fit(), cx);
6827 });
6828 }
6829
6830 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6831 self.manipulate_text(cx, |text| text.to_uppercase())
6832 }
6833
6834 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6835 self.manipulate_text(cx, |text| text.to_lowercase())
6836 }
6837
6838 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6839 self.manipulate_text(cx, |text| {
6840 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6841 // https://github.com/rutrum/convert-case/issues/16
6842 text.split('\n')
6843 .map(|line| line.to_case(Case::Title))
6844 .join("\n")
6845 })
6846 }
6847
6848 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6849 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6850 }
6851
6852 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6853 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6854 }
6855
6856 pub fn convert_to_upper_camel_case(
6857 &mut self,
6858 _: &ConvertToUpperCamelCase,
6859 cx: &mut ViewContext<Self>,
6860 ) {
6861 self.manipulate_text(cx, |text| {
6862 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6863 // https://github.com/rutrum/convert-case/issues/16
6864 text.split('\n')
6865 .map(|line| line.to_case(Case::UpperCamel))
6866 .join("\n")
6867 })
6868 }
6869
6870 pub fn convert_to_lower_camel_case(
6871 &mut self,
6872 _: &ConvertToLowerCamelCase,
6873 cx: &mut ViewContext<Self>,
6874 ) {
6875 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6876 }
6877
6878 pub fn convert_to_opposite_case(
6879 &mut self,
6880 _: &ConvertToOppositeCase,
6881 cx: &mut ViewContext<Self>,
6882 ) {
6883 self.manipulate_text(cx, |text| {
6884 text.chars()
6885 .fold(String::with_capacity(text.len()), |mut t, c| {
6886 if c.is_uppercase() {
6887 t.extend(c.to_lowercase());
6888 } else {
6889 t.extend(c.to_uppercase());
6890 }
6891 t
6892 })
6893 })
6894 }
6895
6896 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6897 where
6898 Fn: FnMut(&str) -> String,
6899 {
6900 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6901 let buffer = self.buffer.read(cx).snapshot(cx);
6902
6903 let mut new_selections = Vec::new();
6904 let mut edits = Vec::new();
6905 let mut selection_adjustment = 0i32;
6906
6907 for selection in self.selections.all::<usize>(cx) {
6908 let selection_is_empty = selection.is_empty();
6909
6910 let (start, end) = if selection_is_empty {
6911 let word_range = movement::surrounding_word(
6912 &display_map,
6913 selection.start.to_display_point(&display_map),
6914 );
6915 let start = word_range.start.to_offset(&display_map, Bias::Left);
6916 let end = word_range.end.to_offset(&display_map, Bias::Left);
6917 (start, end)
6918 } else {
6919 (selection.start, selection.end)
6920 };
6921
6922 let text = buffer.text_for_range(start..end).collect::<String>();
6923 let old_length = text.len() as i32;
6924 let text = callback(&text);
6925
6926 new_selections.push(Selection {
6927 start: (start as i32 - selection_adjustment) as usize,
6928 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6929 goal: SelectionGoal::None,
6930 ..selection
6931 });
6932
6933 selection_adjustment += old_length - text.len() as i32;
6934
6935 edits.push((start..end, text));
6936 }
6937
6938 self.transact(cx, |this, cx| {
6939 this.buffer.update(cx, |buffer, cx| {
6940 buffer.edit(edits, None, cx);
6941 });
6942
6943 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6944 s.select(new_selections);
6945 });
6946
6947 this.request_autoscroll(Autoscroll::fit(), cx);
6948 });
6949 }
6950
6951 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6952 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6953 let buffer = &display_map.buffer_snapshot;
6954 let selections = self.selections.all::<Point>(cx);
6955
6956 let mut edits = Vec::new();
6957 let mut selections_iter = selections.iter().peekable();
6958 while let Some(selection) = selections_iter.next() {
6959 // Avoid duplicating the same lines twice.
6960 let mut rows = selection.spanned_rows(false, &display_map);
6961
6962 while let Some(next_selection) = selections_iter.peek() {
6963 let next_rows = next_selection.spanned_rows(false, &display_map);
6964 if next_rows.start < rows.end {
6965 rows.end = next_rows.end;
6966 selections_iter.next().unwrap();
6967 } else {
6968 break;
6969 }
6970 }
6971
6972 // Copy the text from the selected row region and splice it either at the start
6973 // or end of the region.
6974 let start = Point::new(rows.start.0, 0);
6975 let end = Point::new(
6976 rows.end.previous_row().0,
6977 buffer.line_len(rows.end.previous_row()),
6978 );
6979 let text = buffer
6980 .text_for_range(start..end)
6981 .chain(Some("\n"))
6982 .collect::<String>();
6983 let insert_location = if upwards {
6984 Point::new(rows.end.0, 0)
6985 } else {
6986 start
6987 };
6988 edits.push((insert_location..insert_location, text));
6989 }
6990
6991 self.transact(cx, |this, cx| {
6992 this.buffer.update(cx, |buffer, cx| {
6993 buffer.edit(edits, None, cx);
6994 });
6995
6996 this.request_autoscroll(Autoscroll::fit(), cx);
6997 });
6998 }
6999
7000 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
7001 self.duplicate_line(true, cx);
7002 }
7003
7004 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
7005 self.duplicate_line(false, cx);
7006 }
7007
7008 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
7009 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7010 let buffer = self.buffer.read(cx).snapshot(cx);
7011
7012 let mut edits = Vec::new();
7013 let mut unfold_ranges = Vec::new();
7014 let mut refold_creases = Vec::new();
7015
7016 let selections = self.selections.all::<Point>(cx);
7017 let mut selections = selections.iter().peekable();
7018 let mut contiguous_row_selections = Vec::new();
7019 let mut new_selections = Vec::new();
7020
7021 while let Some(selection) = selections.next() {
7022 // Find all the selections that span a contiguous row range
7023 let (start_row, end_row) = consume_contiguous_rows(
7024 &mut contiguous_row_selections,
7025 selection,
7026 &display_map,
7027 &mut selections,
7028 );
7029
7030 // Move the text spanned by the row range to be before the line preceding the row range
7031 if start_row.0 > 0 {
7032 let range_to_move = Point::new(
7033 start_row.previous_row().0,
7034 buffer.line_len(start_row.previous_row()),
7035 )
7036 ..Point::new(
7037 end_row.previous_row().0,
7038 buffer.line_len(end_row.previous_row()),
7039 );
7040 let insertion_point = display_map
7041 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7042 .0;
7043
7044 // Don't move lines across excerpts
7045 if buffer
7046 .excerpt_boundaries_in_range((
7047 Bound::Excluded(insertion_point),
7048 Bound::Included(range_to_move.end),
7049 ))
7050 .next()
7051 .is_none()
7052 {
7053 let text = buffer
7054 .text_for_range(range_to_move.clone())
7055 .flat_map(|s| s.chars())
7056 .skip(1)
7057 .chain(['\n'])
7058 .collect::<String>();
7059
7060 edits.push((
7061 buffer.anchor_after(range_to_move.start)
7062 ..buffer.anchor_before(range_to_move.end),
7063 String::new(),
7064 ));
7065 let insertion_anchor = buffer.anchor_after(insertion_point);
7066 edits.push((insertion_anchor..insertion_anchor, text));
7067
7068 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7069
7070 // Move selections up
7071 new_selections.extend(contiguous_row_selections.drain(..).map(
7072 |mut selection| {
7073 selection.start.row -= row_delta;
7074 selection.end.row -= row_delta;
7075 selection
7076 },
7077 ));
7078
7079 // Move folds up
7080 unfold_ranges.push(range_to_move.clone());
7081 for fold in display_map.folds_in_range(
7082 buffer.anchor_before(range_to_move.start)
7083 ..buffer.anchor_after(range_to_move.end),
7084 ) {
7085 let mut start = fold.range.start.to_point(&buffer);
7086 let mut end = fold.range.end.to_point(&buffer);
7087 start.row -= row_delta;
7088 end.row -= row_delta;
7089 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7090 }
7091 }
7092 }
7093
7094 // If we didn't move line(s), preserve the existing selections
7095 new_selections.append(&mut contiguous_row_selections);
7096 }
7097
7098 self.transact(cx, |this, cx| {
7099 this.unfold_ranges(&unfold_ranges, true, true, cx);
7100 this.buffer.update(cx, |buffer, cx| {
7101 for (range, text) in edits {
7102 buffer.edit([(range, text)], None, cx);
7103 }
7104 });
7105 this.fold_creases(refold_creases, true, cx);
7106 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7107 s.select(new_selections);
7108 })
7109 });
7110 }
7111
7112 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
7113 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7114 let buffer = self.buffer.read(cx).snapshot(cx);
7115
7116 let mut edits = Vec::new();
7117 let mut unfold_ranges = Vec::new();
7118 let mut refold_creases = Vec::new();
7119
7120 let selections = self.selections.all::<Point>(cx);
7121 let mut selections = selections.iter().peekable();
7122 let mut contiguous_row_selections = Vec::new();
7123 let mut new_selections = Vec::new();
7124
7125 while let Some(selection) = selections.next() {
7126 // Find all the selections that span a contiguous row range
7127 let (start_row, end_row) = consume_contiguous_rows(
7128 &mut contiguous_row_selections,
7129 selection,
7130 &display_map,
7131 &mut selections,
7132 );
7133
7134 // Move the text spanned by the row range to be after the last line of the row range
7135 if end_row.0 <= buffer.max_point().row {
7136 let range_to_move =
7137 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7138 let insertion_point = display_map
7139 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7140 .0;
7141
7142 // Don't move lines across excerpt boundaries
7143 if buffer
7144 .excerpt_boundaries_in_range((
7145 Bound::Excluded(range_to_move.start),
7146 Bound::Included(insertion_point),
7147 ))
7148 .next()
7149 .is_none()
7150 {
7151 let mut text = String::from("\n");
7152 text.extend(buffer.text_for_range(range_to_move.clone()));
7153 text.pop(); // Drop trailing newline
7154 edits.push((
7155 buffer.anchor_after(range_to_move.start)
7156 ..buffer.anchor_before(range_to_move.end),
7157 String::new(),
7158 ));
7159 let insertion_anchor = buffer.anchor_after(insertion_point);
7160 edits.push((insertion_anchor..insertion_anchor, text));
7161
7162 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7163
7164 // Move selections down
7165 new_selections.extend(contiguous_row_selections.drain(..).map(
7166 |mut selection| {
7167 selection.start.row += row_delta;
7168 selection.end.row += row_delta;
7169 selection
7170 },
7171 ));
7172
7173 // Move folds down
7174 unfold_ranges.push(range_to_move.clone());
7175 for fold in display_map.folds_in_range(
7176 buffer.anchor_before(range_to_move.start)
7177 ..buffer.anchor_after(range_to_move.end),
7178 ) {
7179 let mut start = fold.range.start.to_point(&buffer);
7180 let mut end = fold.range.end.to_point(&buffer);
7181 start.row += row_delta;
7182 end.row += row_delta;
7183 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7184 }
7185 }
7186 }
7187
7188 // If we didn't move line(s), preserve the existing selections
7189 new_selections.append(&mut contiguous_row_selections);
7190 }
7191
7192 self.transact(cx, |this, cx| {
7193 this.unfold_ranges(&unfold_ranges, true, true, cx);
7194 this.buffer.update(cx, |buffer, cx| {
7195 for (range, text) in edits {
7196 buffer.edit([(range, text)], None, cx);
7197 }
7198 });
7199 this.fold_creases(refold_creases, true, cx);
7200 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
7201 });
7202 }
7203
7204 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
7205 let text_layout_details = &self.text_layout_details(cx);
7206 self.transact(cx, |this, cx| {
7207 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7208 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7209 let line_mode = s.line_mode;
7210 s.move_with(|display_map, selection| {
7211 if !selection.is_empty() || line_mode {
7212 return;
7213 }
7214
7215 let mut head = selection.head();
7216 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7217 if head.column() == display_map.line_len(head.row()) {
7218 transpose_offset = display_map
7219 .buffer_snapshot
7220 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7221 }
7222
7223 if transpose_offset == 0 {
7224 return;
7225 }
7226
7227 *head.column_mut() += 1;
7228 head = display_map.clip_point(head, Bias::Right);
7229 let goal = SelectionGoal::HorizontalPosition(
7230 display_map
7231 .x_for_display_point(head, text_layout_details)
7232 .into(),
7233 );
7234 selection.collapse_to(head, goal);
7235
7236 let transpose_start = display_map
7237 .buffer_snapshot
7238 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7239 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7240 let transpose_end = display_map
7241 .buffer_snapshot
7242 .clip_offset(transpose_offset + 1, Bias::Right);
7243 if let Some(ch) =
7244 display_map.buffer_snapshot.chars_at(transpose_start).next()
7245 {
7246 edits.push((transpose_start..transpose_offset, String::new()));
7247 edits.push((transpose_end..transpose_end, ch.to_string()));
7248 }
7249 }
7250 });
7251 edits
7252 });
7253 this.buffer
7254 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7255 let selections = this.selections.all::<usize>(cx);
7256 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7257 s.select(selections);
7258 });
7259 });
7260 }
7261
7262 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
7263 self.rewrap_impl(IsVimMode::No, cx)
7264 }
7265
7266 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
7267 let buffer = self.buffer.read(cx).snapshot(cx);
7268 let selections = self.selections.all::<Point>(cx);
7269 let mut selections = selections.iter().peekable();
7270
7271 let mut edits = Vec::new();
7272 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7273
7274 while let Some(selection) = selections.next() {
7275 let mut start_row = selection.start.row;
7276 let mut end_row = selection.end.row;
7277
7278 // Skip selections that overlap with a range that has already been rewrapped.
7279 let selection_range = start_row..end_row;
7280 if rewrapped_row_ranges
7281 .iter()
7282 .any(|range| range.overlaps(&selection_range))
7283 {
7284 continue;
7285 }
7286
7287 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7288
7289 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7290 match language_scope.language_name().0.as_ref() {
7291 "Markdown" | "Plain Text" => {
7292 should_rewrap = true;
7293 }
7294 _ => {}
7295 }
7296 }
7297
7298 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7299
7300 // Since not all lines in the selection may be at the same indent
7301 // level, choose the indent size that is the most common between all
7302 // of the lines.
7303 //
7304 // If there is a tie, we use the deepest indent.
7305 let (indent_size, indent_end) = {
7306 let mut indent_size_occurrences = HashMap::default();
7307 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7308
7309 for row in start_row..=end_row {
7310 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7311 rows_by_indent_size.entry(indent).or_default().push(row);
7312 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7313 }
7314
7315 let indent_size = indent_size_occurrences
7316 .into_iter()
7317 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7318 .map(|(indent, _)| indent)
7319 .unwrap_or_default();
7320 let row = rows_by_indent_size[&indent_size][0];
7321 let indent_end = Point::new(row, indent_size.len);
7322
7323 (indent_size, indent_end)
7324 };
7325
7326 let mut line_prefix = indent_size.chars().collect::<String>();
7327
7328 if let Some(comment_prefix) =
7329 buffer
7330 .language_scope_at(selection.head())
7331 .and_then(|language| {
7332 language
7333 .line_comment_prefixes()
7334 .iter()
7335 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7336 .cloned()
7337 })
7338 {
7339 line_prefix.push_str(&comment_prefix);
7340 should_rewrap = true;
7341 }
7342
7343 if !should_rewrap {
7344 continue;
7345 }
7346
7347 if selection.is_empty() {
7348 'expand_upwards: while start_row > 0 {
7349 let prev_row = start_row - 1;
7350 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7351 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7352 {
7353 start_row = prev_row;
7354 } else {
7355 break 'expand_upwards;
7356 }
7357 }
7358
7359 'expand_downwards: while end_row < buffer.max_point().row {
7360 let next_row = end_row + 1;
7361 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7362 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7363 {
7364 end_row = next_row;
7365 } else {
7366 break 'expand_downwards;
7367 }
7368 }
7369 }
7370
7371 let start = Point::new(start_row, 0);
7372 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7373 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7374 let Some(lines_without_prefixes) = selection_text
7375 .lines()
7376 .map(|line| {
7377 line.strip_prefix(&line_prefix)
7378 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7379 .ok_or_else(|| {
7380 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7381 })
7382 })
7383 .collect::<Result<Vec<_>, _>>()
7384 .log_err()
7385 else {
7386 continue;
7387 };
7388
7389 let wrap_column = buffer
7390 .settings_at(Point::new(start_row, 0), cx)
7391 .preferred_line_length as usize;
7392 let wrapped_text = wrap_with_prefix(
7393 line_prefix,
7394 lines_without_prefixes.join(" "),
7395 wrap_column,
7396 tab_size,
7397 );
7398
7399 // TODO: should always use char-based diff while still supporting cursor behavior that
7400 // matches vim.
7401 let diff = match is_vim_mode {
7402 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7403 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7404 };
7405 let mut offset = start.to_offset(&buffer);
7406 let mut moved_since_edit = true;
7407
7408 for change in diff.iter_all_changes() {
7409 let value = change.value();
7410 match change.tag() {
7411 ChangeTag::Equal => {
7412 offset += value.len();
7413 moved_since_edit = true;
7414 }
7415 ChangeTag::Delete => {
7416 let start = buffer.anchor_after(offset);
7417 let end = buffer.anchor_before(offset + value.len());
7418
7419 if moved_since_edit {
7420 edits.push((start..end, String::new()));
7421 } else {
7422 edits.last_mut().unwrap().0.end = end;
7423 }
7424
7425 offset += value.len();
7426 moved_since_edit = false;
7427 }
7428 ChangeTag::Insert => {
7429 if moved_since_edit {
7430 let anchor = buffer.anchor_after(offset);
7431 edits.push((anchor..anchor, value.to_string()));
7432 } else {
7433 edits.last_mut().unwrap().1.push_str(value);
7434 }
7435
7436 moved_since_edit = false;
7437 }
7438 }
7439 }
7440
7441 rewrapped_row_ranges.push(start_row..=end_row);
7442 }
7443
7444 self.buffer
7445 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7446 }
7447
7448 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
7449 let mut text = String::new();
7450 let buffer = self.buffer.read(cx).snapshot(cx);
7451 let mut selections = self.selections.all::<Point>(cx);
7452 let mut clipboard_selections = Vec::with_capacity(selections.len());
7453 {
7454 let max_point = buffer.max_point();
7455 let mut is_first = true;
7456 for selection in &mut selections {
7457 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7458 if is_entire_line {
7459 selection.start = Point::new(selection.start.row, 0);
7460 if !selection.is_empty() && selection.end.column == 0 {
7461 selection.end = cmp::min(max_point, selection.end);
7462 } else {
7463 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7464 }
7465 selection.goal = SelectionGoal::None;
7466 }
7467 if is_first {
7468 is_first = false;
7469 } else {
7470 text += "\n";
7471 }
7472 let mut len = 0;
7473 for chunk in buffer.text_for_range(selection.start..selection.end) {
7474 text.push_str(chunk);
7475 len += chunk.len();
7476 }
7477 clipboard_selections.push(ClipboardSelection {
7478 len,
7479 is_entire_line,
7480 first_line_indent: buffer
7481 .indent_size_for_line(MultiBufferRow(selection.start.row))
7482 .len,
7483 });
7484 }
7485 }
7486
7487 self.transact(cx, |this, cx| {
7488 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7489 s.select(selections);
7490 });
7491 this.insert("", cx);
7492 });
7493 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7494 }
7495
7496 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
7497 let item = self.cut_common(cx);
7498 cx.write_to_clipboard(item);
7499 }
7500
7501 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
7502 self.change_selections(None, cx, |s| {
7503 s.move_with(|snapshot, sel| {
7504 if sel.is_empty() {
7505 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7506 }
7507 });
7508 });
7509 let item = self.cut_common(cx);
7510 cx.set_global(KillRing(item))
7511 }
7512
7513 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
7514 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7515 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7516 (kill_ring.text().to_string(), kill_ring.metadata_json())
7517 } else {
7518 return;
7519 }
7520 } else {
7521 return;
7522 };
7523 self.do_paste(&text, metadata, false, cx);
7524 }
7525
7526 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
7527 let selections = self.selections.all::<Point>(cx);
7528 let buffer = self.buffer.read(cx).read(cx);
7529 let mut text = String::new();
7530
7531 let mut clipboard_selections = Vec::with_capacity(selections.len());
7532 {
7533 let max_point = buffer.max_point();
7534 let mut is_first = true;
7535 for selection in selections.iter() {
7536 let mut start = selection.start;
7537 let mut end = selection.end;
7538 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7539 if is_entire_line {
7540 start = Point::new(start.row, 0);
7541 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7542 }
7543 if is_first {
7544 is_first = false;
7545 } else {
7546 text += "\n";
7547 }
7548 let mut len = 0;
7549 for chunk in buffer.text_for_range(start..end) {
7550 text.push_str(chunk);
7551 len += chunk.len();
7552 }
7553 clipboard_selections.push(ClipboardSelection {
7554 len,
7555 is_entire_line,
7556 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7557 });
7558 }
7559 }
7560
7561 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7562 text,
7563 clipboard_selections,
7564 ));
7565 }
7566
7567 pub fn do_paste(
7568 &mut self,
7569 text: &String,
7570 clipboard_selections: Option<Vec<ClipboardSelection>>,
7571 handle_entire_lines: bool,
7572 cx: &mut ViewContext<Self>,
7573 ) {
7574 if self.read_only(cx) {
7575 return;
7576 }
7577
7578 let clipboard_text = Cow::Borrowed(text);
7579
7580 self.transact(cx, |this, cx| {
7581 if let Some(mut clipboard_selections) = clipboard_selections {
7582 let old_selections = this.selections.all::<usize>(cx);
7583 let all_selections_were_entire_line =
7584 clipboard_selections.iter().all(|s| s.is_entire_line);
7585 let first_selection_indent_column =
7586 clipboard_selections.first().map(|s| s.first_line_indent);
7587 if clipboard_selections.len() != old_selections.len() {
7588 clipboard_selections.drain(..);
7589 }
7590 let cursor_offset = this.selections.last::<usize>(cx).head();
7591 let mut auto_indent_on_paste = true;
7592
7593 this.buffer.update(cx, |buffer, cx| {
7594 let snapshot = buffer.read(cx);
7595 auto_indent_on_paste =
7596 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7597
7598 let mut start_offset = 0;
7599 let mut edits = Vec::new();
7600 let mut original_indent_columns = Vec::new();
7601 for (ix, selection) in old_selections.iter().enumerate() {
7602 let to_insert;
7603 let entire_line;
7604 let original_indent_column;
7605 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7606 let end_offset = start_offset + clipboard_selection.len;
7607 to_insert = &clipboard_text[start_offset..end_offset];
7608 entire_line = clipboard_selection.is_entire_line;
7609 start_offset = end_offset + 1;
7610 original_indent_column = Some(clipboard_selection.first_line_indent);
7611 } else {
7612 to_insert = clipboard_text.as_str();
7613 entire_line = all_selections_were_entire_line;
7614 original_indent_column = first_selection_indent_column
7615 }
7616
7617 // If the corresponding selection was empty when this slice of the
7618 // clipboard text was written, then the entire line containing the
7619 // selection was copied. If this selection is also currently empty,
7620 // then paste the line before the current line of the buffer.
7621 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7622 let column = selection.start.to_point(&snapshot).column as usize;
7623 let line_start = selection.start - column;
7624 line_start..line_start
7625 } else {
7626 selection.range()
7627 };
7628
7629 edits.push((range, to_insert));
7630 original_indent_columns.extend(original_indent_column);
7631 }
7632 drop(snapshot);
7633
7634 buffer.edit(
7635 edits,
7636 if auto_indent_on_paste {
7637 Some(AutoindentMode::Block {
7638 original_indent_columns,
7639 })
7640 } else {
7641 None
7642 },
7643 cx,
7644 );
7645 });
7646
7647 let selections = this.selections.all::<usize>(cx);
7648 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7649 } else {
7650 this.insert(&clipboard_text, cx);
7651 }
7652 });
7653 }
7654
7655 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7656 if let Some(item) = cx.read_from_clipboard() {
7657 let entries = item.entries();
7658
7659 match entries.first() {
7660 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7661 // of all the pasted entries.
7662 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7663 .do_paste(
7664 clipboard_string.text(),
7665 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7666 true,
7667 cx,
7668 ),
7669 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7670 }
7671 }
7672 }
7673
7674 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7675 if self.read_only(cx) {
7676 return;
7677 }
7678
7679 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7680 if let Some((selections, _)) =
7681 self.selection_history.transaction(transaction_id).cloned()
7682 {
7683 self.change_selections(None, cx, |s| {
7684 s.select_anchors(selections.to_vec());
7685 });
7686 }
7687 self.request_autoscroll(Autoscroll::fit(), cx);
7688 self.unmark_text(cx);
7689 self.refresh_inline_completion(true, false, cx);
7690 cx.emit(EditorEvent::Edited { transaction_id });
7691 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7692 }
7693 }
7694
7695 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7696 if self.read_only(cx) {
7697 return;
7698 }
7699
7700 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7701 if let Some((_, Some(selections))) =
7702 self.selection_history.transaction(transaction_id).cloned()
7703 {
7704 self.change_selections(None, cx, |s| {
7705 s.select_anchors(selections.to_vec());
7706 });
7707 }
7708 self.request_autoscroll(Autoscroll::fit(), cx);
7709 self.unmark_text(cx);
7710 self.refresh_inline_completion(true, false, cx);
7711 cx.emit(EditorEvent::Edited { transaction_id });
7712 }
7713 }
7714
7715 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7716 self.buffer
7717 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7718 }
7719
7720 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7721 self.buffer
7722 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7723 }
7724
7725 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7726 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7727 let line_mode = s.line_mode;
7728 s.move_with(|map, selection| {
7729 let cursor = if selection.is_empty() && !line_mode {
7730 movement::left(map, selection.start)
7731 } else {
7732 selection.start
7733 };
7734 selection.collapse_to(cursor, SelectionGoal::None);
7735 });
7736 })
7737 }
7738
7739 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7740 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7741 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7742 })
7743 }
7744
7745 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7746 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7747 let line_mode = s.line_mode;
7748 s.move_with(|map, selection| {
7749 let cursor = if selection.is_empty() && !line_mode {
7750 movement::right(map, selection.end)
7751 } else {
7752 selection.end
7753 };
7754 selection.collapse_to(cursor, SelectionGoal::None)
7755 });
7756 })
7757 }
7758
7759 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7760 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7761 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7762 })
7763 }
7764
7765 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7766 if self.take_rename(true, cx).is_some() {
7767 return;
7768 }
7769
7770 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7771 cx.propagate();
7772 return;
7773 }
7774
7775 let text_layout_details = &self.text_layout_details(cx);
7776 let selection_count = self.selections.count();
7777 let first_selection = self.selections.first_anchor();
7778
7779 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7780 let line_mode = s.line_mode;
7781 s.move_with(|map, selection| {
7782 if !selection.is_empty() && !line_mode {
7783 selection.goal = SelectionGoal::None;
7784 }
7785 let (cursor, goal) = movement::up(
7786 map,
7787 selection.start,
7788 selection.goal,
7789 false,
7790 text_layout_details,
7791 );
7792 selection.collapse_to(cursor, goal);
7793 });
7794 });
7795
7796 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7797 {
7798 cx.propagate();
7799 }
7800 }
7801
7802 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7803 if self.take_rename(true, cx).is_some() {
7804 return;
7805 }
7806
7807 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7808 cx.propagate();
7809 return;
7810 }
7811
7812 let text_layout_details = &self.text_layout_details(cx);
7813
7814 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7815 let line_mode = s.line_mode;
7816 s.move_with(|map, selection| {
7817 if !selection.is_empty() && !line_mode {
7818 selection.goal = SelectionGoal::None;
7819 }
7820 let (cursor, goal) = movement::up_by_rows(
7821 map,
7822 selection.start,
7823 action.lines,
7824 selection.goal,
7825 false,
7826 text_layout_details,
7827 );
7828 selection.collapse_to(cursor, goal);
7829 });
7830 })
7831 }
7832
7833 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7834 if self.take_rename(true, cx).is_some() {
7835 return;
7836 }
7837
7838 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7839 cx.propagate();
7840 return;
7841 }
7842
7843 let text_layout_details = &self.text_layout_details(cx);
7844
7845 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7846 let line_mode = s.line_mode;
7847 s.move_with(|map, selection| {
7848 if !selection.is_empty() && !line_mode {
7849 selection.goal = SelectionGoal::None;
7850 }
7851 let (cursor, goal) = movement::down_by_rows(
7852 map,
7853 selection.start,
7854 action.lines,
7855 selection.goal,
7856 false,
7857 text_layout_details,
7858 );
7859 selection.collapse_to(cursor, goal);
7860 });
7861 })
7862 }
7863
7864 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7865 let text_layout_details = &self.text_layout_details(cx);
7866 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7867 s.move_heads_with(|map, head, goal| {
7868 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7869 })
7870 })
7871 }
7872
7873 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7874 let text_layout_details = &self.text_layout_details(cx);
7875 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7876 s.move_heads_with(|map, head, goal| {
7877 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7878 })
7879 })
7880 }
7881
7882 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7883 let Some(row_count) = self.visible_row_count() else {
7884 return;
7885 };
7886
7887 let text_layout_details = &self.text_layout_details(cx);
7888
7889 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7890 s.move_heads_with(|map, head, goal| {
7891 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7892 })
7893 })
7894 }
7895
7896 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7897 if self.take_rename(true, cx).is_some() {
7898 return;
7899 }
7900
7901 if self
7902 .context_menu
7903 .write()
7904 .as_mut()
7905 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7906 .unwrap_or(false)
7907 {
7908 return;
7909 }
7910
7911 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7912 cx.propagate();
7913 return;
7914 }
7915
7916 let Some(row_count) = self.visible_row_count() else {
7917 return;
7918 };
7919
7920 let autoscroll = if action.center_cursor {
7921 Autoscroll::center()
7922 } else {
7923 Autoscroll::fit()
7924 };
7925
7926 let text_layout_details = &self.text_layout_details(cx);
7927
7928 self.change_selections(Some(autoscroll), cx, |s| {
7929 let line_mode = s.line_mode;
7930 s.move_with(|map, selection| {
7931 if !selection.is_empty() && !line_mode {
7932 selection.goal = SelectionGoal::None;
7933 }
7934 let (cursor, goal) = movement::up_by_rows(
7935 map,
7936 selection.end,
7937 row_count,
7938 selection.goal,
7939 false,
7940 text_layout_details,
7941 );
7942 selection.collapse_to(cursor, goal);
7943 });
7944 });
7945 }
7946
7947 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7948 let text_layout_details = &self.text_layout_details(cx);
7949 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7950 s.move_heads_with(|map, head, goal| {
7951 movement::up(map, head, goal, false, text_layout_details)
7952 })
7953 })
7954 }
7955
7956 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7957 self.take_rename(true, cx);
7958
7959 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7960 cx.propagate();
7961 return;
7962 }
7963
7964 let text_layout_details = &self.text_layout_details(cx);
7965 let selection_count = self.selections.count();
7966 let first_selection = self.selections.first_anchor();
7967
7968 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7969 let line_mode = s.line_mode;
7970 s.move_with(|map, selection| {
7971 if !selection.is_empty() && !line_mode {
7972 selection.goal = SelectionGoal::None;
7973 }
7974 let (cursor, goal) = movement::down(
7975 map,
7976 selection.end,
7977 selection.goal,
7978 false,
7979 text_layout_details,
7980 );
7981 selection.collapse_to(cursor, goal);
7982 });
7983 });
7984
7985 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7986 {
7987 cx.propagate();
7988 }
7989 }
7990
7991 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7992 let Some(row_count) = self.visible_row_count() else {
7993 return;
7994 };
7995
7996 let text_layout_details = &self.text_layout_details(cx);
7997
7998 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7999 s.move_heads_with(|map, head, goal| {
8000 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8001 })
8002 })
8003 }
8004
8005 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
8006 if self.take_rename(true, cx).is_some() {
8007 return;
8008 }
8009
8010 if self
8011 .context_menu
8012 .write()
8013 .as_mut()
8014 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8015 .unwrap_or(false)
8016 {
8017 return;
8018 }
8019
8020 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8021 cx.propagate();
8022 return;
8023 }
8024
8025 let Some(row_count) = self.visible_row_count() else {
8026 return;
8027 };
8028
8029 let autoscroll = if action.center_cursor {
8030 Autoscroll::center()
8031 } else {
8032 Autoscroll::fit()
8033 };
8034
8035 let text_layout_details = &self.text_layout_details(cx);
8036 self.change_selections(Some(autoscroll), cx, |s| {
8037 let line_mode = s.line_mode;
8038 s.move_with(|map, selection| {
8039 if !selection.is_empty() && !line_mode {
8040 selection.goal = SelectionGoal::None;
8041 }
8042 let (cursor, goal) = movement::down_by_rows(
8043 map,
8044 selection.end,
8045 row_count,
8046 selection.goal,
8047 false,
8048 text_layout_details,
8049 );
8050 selection.collapse_to(cursor, goal);
8051 });
8052 });
8053 }
8054
8055 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
8056 let text_layout_details = &self.text_layout_details(cx);
8057 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8058 s.move_heads_with(|map, head, goal| {
8059 movement::down(map, head, goal, false, text_layout_details)
8060 })
8061 });
8062 }
8063
8064 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
8065 if let Some(context_menu) = self.context_menu.write().as_mut() {
8066 context_menu.select_first(self.completion_provider.as_deref(), cx);
8067 }
8068 }
8069
8070 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
8071 if let Some(context_menu) = self.context_menu.write().as_mut() {
8072 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8073 }
8074 }
8075
8076 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
8077 if let Some(context_menu) = self.context_menu.write().as_mut() {
8078 context_menu.select_next(self.completion_provider.as_deref(), cx);
8079 }
8080 }
8081
8082 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
8083 if let Some(context_menu) = self.context_menu.write().as_mut() {
8084 context_menu.select_last(self.completion_provider.as_deref(), cx);
8085 }
8086 }
8087
8088 pub fn move_to_previous_word_start(
8089 &mut self,
8090 _: &MoveToPreviousWordStart,
8091 cx: &mut ViewContext<Self>,
8092 ) {
8093 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8094 s.move_cursors_with(|map, head, _| {
8095 (
8096 movement::previous_word_start(map, head),
8097 SelectionGoal::None,
8098 )
8099 });
8100 })
8101 }
8102
8103 pub fn move_to_previous_subword_start(
8104 &mut self,
8105 _: &MoveToPreviousSubwordStart,
8106 cx: &mut ViewContext<Self>,
8107 ) {
8108 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8109 s.move_cursors_with(|map, head, _| {
8110 (
8111 movement::previous_subword_start(map, head),
8112 SelectionGoal::None,
8113 )
8114 });
8115 })
8116 }
8117
8118 pub fn select_to_previous_word_start(
8119 &mut self,
8120 _: &SelectToPreviousWordStart,
8121 cx: &mut ViewContext<Self>,
8122 ) {
8123 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8124 s.move_heads_with(|map, head, _| {
8125 (
8126 movement::previous_word_start(map, head),
8127 SelectionGoal::None,
8128 )
8129 });
8130 })
8131 }
8132
8133 pub fn select_to_previous_subword_start(
8134 &mut self,
8135 _: &SelectToPreviousSubwordStart,
8136 cx: &mut ViewContext<Self>,
8137 ) {
8138 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8139 s.move_heads_with(|map, head, _| {
8140 (
8141 movement::previous_subword_start(map, head),
8142 SelectionGoal::None,
8143 )
8144 });
8145 })
8146 }
8147
8148 pub fn delete_to_previous_word_start(
8149 &mut self,
8150 action: &DeleteToPreviousWordStart,
8151 cx: &mut ViewContext<Self>,
8152 ) {
8153 self.transact(cx, |this, cx| {
8154 this.select_autoclose_pair(cx);
8155 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8156 let line_mode = s.line_mode;
8157 s.move_with(|map, selection| {
8158 if selection.is_empty() && !line_mode {
8159 let cursor = if action.ignore_newlines {
8160 movement::previous_word_start(map, selection.head())
8161 } else {
8162 movement::previous_word_start_or_newline(map, selection.head())
8163 };
8164 selection.set_head(cursor, SelectionGoal::None);
8165 }
8166 });
8167 });
8168 this.insert("", cx);
8169 });
8170 }
8171
8172 pub fn delete_to_previous_subword_start(
8173 &mut self,
8174 _: &DeleteToPreviousSubwordStart,
8175 cx: &mut ViewContext<Self>,
8176 ) {
8177 self.transact(cx, |this, cx| {
8178 this.select_autoclose_pair(cx);
8179 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8180 let line_mode = s.line_mode;
8181 s.move_with(|map, selection| {
8182 if selection.is_empty() && !line_mode {
8183 let cursor = movement::previous_subword_start(map, selection.head());
8184 selection.set_head(cursor, SelectionGoal::None);
8185 }
8186 });
8187 });
8188 this.insert("", cx);
8189 });
8190 }
8191
8192 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
8193 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8194 s.move_cursors_with(|map, head, _| {
8195 (movement::next_word_end(map, head), SelectionGoal::None)
8196 });
8197 })
8198 }
8199
8200 pub fn move_to_next_subword_end(
8201 &mut self,
8202 _: &MoveToNextSubwordEnd,
8203 cx: &mut ViewContext<Self>,
8204 ) {
8205 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8206 s.move_cursors_with(|map, head, _| {
8207 (movement::next_subword_end(map, head), SelectionGoal::None)
8208 });
8209 })
8210 }
8211
8212 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
8213 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8214 s.move_heads_with(|map, head, _| {
8215 (movement::next_word_end(map, head), SelectionGoal::None)
8216 });
8217 })
8218 }
8219
8220 pub fn select_to_next_subword_end(
8221 &mut self,
8222 _: &SelectToNextSubwordEnd,
8223 cx: &mut ViewContext<Self>,
8224 ) {
8225 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8226 s.move_heads_with(|map, head, _| {
8227 (movement::next_subword_end(map, head), SelectionGoal::None)
8228 });
8229 })
8230 }
8231
8232 pub fn delete_to_next_word_end(
8233 &mut self,
8234 action: &DeleteToNextWordEnd,
8235 cx: &mut ViewContext<Self>,
8236 ) {
8237 self.transact(cx, |this, cx| {
8238 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8239 let line_mode = s.line_mode;
8240 s.move_with(|map, selection| {
8241 if selection.is_empty() && !line_mode {
8242 let cursor = if action.ignore_newlines {
8243 movement::next_word_end(map, selection.head())
8244 } else {
8245 movement::next_word_end_or_newline(map, selection.head())
8246 };
8247 selection.set_head(cursor, SelectionGoal::None);
8248 }
8249 });
8250 });
8251 this.insert("", cx);
8252 });
8253 }
8254
8255 pub fn delete_to_next_subword_end(
8256 &mut self,
8257 _: &DeleteToNextSubwordEnd,
8258 cx: &mut ViewContext<Self>,
8259 ) {
8260 self.transact(cx, |this, cx| {
8261 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8262 s.move_with(|map, selection| {
8263 if selection.is_empty() {
8264 let cursor = movement::next_subword_end(map, selection.head());
8265 selection.set_head(cursor, SelectionGoal::None);
8266 }
8267 });
8268 });
8269 this.insert("", cx);
8270 });
8271 }
8272
8273 pub fn move_to_beginning_of_line(
8274 &mut self,
8275 action: &MoveToBeginningOfLine,
8276 cx: &mut ViewContext<Self>,
8277 ) {
8278 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8279 s.move_cursors_with(|map, head, _| {
8280 (
8281 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8282 SelectionGoal::None,
8283 )
8284 });
8285 })
8286 }
8287
8288 pub fn select_to_beginning_of_line(
8289 &mut self,
8290 action: &SelectToBeginningOfLine,
8291 cx: &mut ViewContext<Self>,
8292 ) {
8293 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8294 s.move_heads_with(|map, head, _| {
8295 (
8296 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8297 SelectionGoal::None,
8298 )
8299 });
8300 });
8301 }
8302
8303 pub fn delete_to_beginning_of_line(
8304 &mut self,
8305 _: &DeleteToBeginningOfLine,
8306 cx: &mut ViewContext<Self>,
8307 ) {
8308 self.transact(cx, |this, cx| {
8309 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8310 s.move_with(|_, selection| {
8311 selection.reversed = true;
8312 });
8313 });
8314
8315 this.select_to_beginning_of_line(
8316 &SelectToBeginningOfLine {
8317 stop_at_soft_wraps: false,
8318 },
8319 cx,
8320 );
8321 this.backspace(&Backspace, cx);
8322 });
8323 }
8324
8325 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
8326 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8327 s.move_cursors_with(|map, head, _| {
8328 (
8329 movement::line_end(map, head, action.stop_at_soft_wraps),
8330 SelectionGoal::None,
8331 )
8332 });
8333 })
8334 }
8335
8336 pub fn select_to_end_of_line(
8337 &mut self,
8338 action: &SelectToEndOfLine,
8339 cx: &mut ViewContext<Self>,
8340 ) {
8341 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8342 s.move_heads_with(|map, head, _| {
8343 (
8344 movement::line_end(map, head, action.stop_at_soft_wraps),
8345 SelectionGoal::None,
8346 )
8347 });
8348 })
8349 }
8350
8351 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
8352 self.transact(cx, |this, cx| {
8353 this.select_to_end_of_line(
8354 &SelectToEndOfLine {
8355 stop_at_soft_wraps: false,
8356 },
8357 cx,
8358 );
8359 this.delete(&Delete, cx);
8360 });
8361 }
8362
8363 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
8364 self.transact(cx, |this, cx| {
8365 this.select_to_end_of_line(
8366 &SelectToEndOfLine {
8367 stop_at_soft_wraps: false,
8368 },
8369 cx,
8370 );
8371 this.cut(&Cut, cx);
8372 });
8373 }
8374
8375 pub fn move_to_start_of_paragraph(
8376 &mut self,
8377 _: &MoveToStartOfParagraph,
8378 cx: &mut ViewContext<Self>,
8379 ) {
8380 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8381 cx.propagate();
8382 return;
8383 }
8384
8385 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8386 s.move_with(|map, selection| {
8387 selection.collapse_to(
8388 movement::start_of_paragraph(map, selection.head(), 1),
8389 SelectionGoal::None,
8390 )
8391 });
8392 })
8393 }
8394
8395 pub fn move_to_end_of_paragraph(
8396 &mut self,
8397 _: &MoveToEndOfParagraph,
8398 cx: &mut ViewContext<Self>,
8399 ) {
8400 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8401 cx.propagate();
8402 return;
8403 }
8404
8405 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8406 s.move_with(|map, selection| {
8407 selection.collapse_to(
8408 movement::end_of_paragraph(map, selection.head(), 1),
8409 SelectionGoal::None,
8410 )
8411 });
8412 })
8413 }
8414
8415 pub fn select_to_start_of_paragraph(
8416 &mut self,
8417 _: &SelectToStartOfParagraph,
8418 cx: &mut ViewContext<Self>,
8419 ) {
8420 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8421 cx.propagate();
8422 return;
8423 }
8424
8425 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8426 s.move_heads_with(|map, head, _| {
8427 (
8428 movement::start_of_paragraph(map, head, 1),
8429 SelectionGoal::None,
8430 )
8431 });
8432 })
8433 }
8434
8435 pub fn select_to_end_of_paragraph(
8436 &mut self,
8437 _: &SelectToEndOfParagraph,
8438 cx: &mut ViewContext<Self>,
8439 ) {
8440 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8441 cx.propagate();
8442 return;
8443 }
8444
8445 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8446 s.move_heads_with(|map, head, _| {
8447 (
8448 movement::end_of_paragraph(map, head, 1),
8449 SelectionGoal::None,
8450 )
8451 });
8452 })
8453 }
8454
8455 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
8456 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8457 cx.propagate();
8458 return;
8459 }
8460
8461 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8462 s.select_ranges(vec![0..0]);
8463 });
8464 }
8465
8466 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
8467 let mut selection = self.selections.last::<Point>(cx);
8468 selection.set_head(Point::zero(), SelectionGoal::None);
8469
8470 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8471 s.select(vec![selection]);
8472 });
8473 }
8474
8475 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
8476 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8477 cx.propagate();
8478 return;
8479 }
8480
8481 let cursor = self.buffer.read(cx).read(cx).len();
8482 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8483 s.select_ranges(vec![cursor..cursor])
8484 });
8485 }
8486
8487 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8488 self.nav_history = nav_history;
8489 }
8490
8491 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8492 self.nav_history.as_ref()
8493 }
8494
8495 fn push_to_nav_history(
8496 &mut self,
8497 cursor_anchor: Anchor,
8498 new_position: Option<Point>,
8499 cx: &mut ViewContext<Self>,
8500 ) {
8501 if let Some(nav_history) = self.nav_history.as_mut() {
8502 let buffer = self.buffer.read(cx).read(cx);
8503 let cursor_position = cursor_anchor.to_point(&buffer);
8504 let scroll_state = self.scroll_manager.anchor();
8505 let scroll_top_row = scroll_state.top_row(&buffer);
8506 drop(buffer);
8507
8508 if let Some(new_position) = new_position {
8509 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8510 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8511 return;
8512 }
8513 }
8514
8515 nav_history.push(
8516 Some(NavigationData {
8517 cursor_anchor,
8518 cursor_position,
8519 scroll_anchor: scroll_state,
8520 scroll_top_row,
8521 }),
8522 cx,
8523 );
8524 }
8525 }
8526
8527 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
8528 let buffer = self.buffer.read(cx).snapshot(cx);
8529 let mut selection = self.selections.first::<usize>(cx);
8530 selection.set_head(buffer.len(), SelectionGoal::None);
8531 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8532 s.select(vec![selection]);
8533 });
8534 }
8535
8536 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
8537 let end = self.buffer.read(cx).read(cx).len();
8538 self.change_selections(None, cx, |s| {
8539 s.select_ranges(vec![0..end]);
8540 });
8541 }
8542
8543 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8544 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8545 let mut selections = self.selections.all::<Point>(cx);
8546 let max_point = display_map.buffer_snapshot.max_point();
8547 for selection in &mut selections {
8548 let rows = selection.spanned_rows(true, &display_map);
8549 selection.start = Point::new(rows.start.0, 0);
8550 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8551 selection.reversed = false;
8552 }
8553 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8554 s.select(selections);
8555 });
8556 }
8557
8558 pub fn split_selection_into_lines(
8559 &mut self,
8560 _: &SplitSelectionIntoLines,
8561 cx: &mut ViewContext<Self>,
8562 ) {
8563 let mut to_unfold = Vec::new();
8564 let mut new_selection_ranges = Vec::new();
8565 {
8566 let selections = self.selections.all::<Point>(cx);
8567 let buffer = self.buffer.read(cx).read(cx);
8568 for selection in selections {
8569 for row in selection.start.row..selection.end.row {
8570 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8571 new_selection_ranges.push(cursor..cursor);
8572 }
8573 new_selection_ranges.push(selection.end..selection.end);
8574 to_unfold.push(selection.start..selection.end);
8575 }
8576 }
8577 self.unfold_ranges(&to_unfold, true, true, cx);
8578 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8579 s.select_ranges(new_selection_ranges);
8580 });
8581 }
8582
8583 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8584 self.add_selection(true, cx);
8585 }
8586
8587 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8588 self.add_selection(false, cx);
8589 }
8590
8591 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8592 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8593 let mut selections = self.selections.all::<Point>(cx);
8594 let text_layout_details = self.text_layout_details(cx);
8595 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8596 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8597 let range = oldest_selection.display_range(&display_map).sorted();
8598
8599 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8600 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8601 let positions = start_x.min(end_x)..start_x.max(end_x);
8602
8603 selections.clear();
8604 let mut stack = Vec::new();
8605 for row in range.start.row().0..=range.end.row().0 {
8606 if let Some(selection) = self.selections.build_columnar_selection(
8607 &display_map,
8608 DisplayRow(row),
8609 &positions,
8610 oldest_selection.reversed,
8611 &text_layout_details,
8612 ) {
8613 stack.push(selection.id);
8614 selections.push(selection);
8615 }
8616 }
8617
8618 if above {
8619 stack.reverse();
8620 }
8621
8622 AddSelectionsState { above, stack }
8623 });
8624
8625 let last_added_selection = *state.stack.last().unwrap();
8626 let mut new_selections = Vec::new();
8627 if above == state.above {
8628 let end_row = if above {
8629 DisplayRow(0)
8630 } else {
8631 display_map.max_point().row()
8632 };
8633
8634 'outer: for selection in selections {
8635 if selection.id == last_added_selection {
8636 let range = selection.display_range(&display_map).sorted();
8637 debug_assert_eq!(range.start.row(), range.end.row());
8638 let mut row = range.start.row();
8639 let positions =
8640 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8641 px(start)..px(end)
8642 } else {
8643 let start_x =
8644 display_map.x_for_display_point(range.start, &text_layout_details);
8645 let end_x =
8646 display_map.x_for_display_point(range.end, &text_layout_details);
8647 start_x.min(end_x)..start_x.max(end_x)
8648 };
8649
8650 while row != end_row {
8651 if above {
8652 row.0 -= 1;
8653 } else {
8654 row.0 += 1;
8655 }
8656
8657 if let Some(new_selection) = self.selections.build_columnar_selection(
8658 &display_map,
8659 row,
8660 &positions,
8661 selection.reversed,
8662 &text_layout_details,
8663 ) {
8664 state.stack.push(new_selection.id);
8665 if above {
8666 new_selections.push(new_selection);
8667 new_selections.push(selection);
8668 } else {
8669 new_selections.push(selection);
8670 new_selections.push(new_selection);
8671 }
8672
8673 continue 'outer;
8674 }
8675 }
8676 }
8677
8678 new_selections.push(selection);
8679 }
8680 } else {
8681 new_selections = selections;
8682 new_selections.retain(|s| s.id != last_added_selection);
8683 state.stack.pop();
8684 }
8685
8686 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8687 s.select(new_selections);
8688 });
8689 if state.stack.len() > 1 {
8690 self.add_selections_state = Some(state);
8691 }
8692 }
8693
8694 pub fn select_next_match_internal(
8695 &mut self,
8696 display_map: &DisplaySnapshot,
8697 replace_newest: bool,
8698 autoscroll: Option<Autoscroll>,
8699 cx: &mut ViewContext<Self>,
8700 ) -> Result<()> {
8701 fn select_next_match_ranges(
8702 this: &mut Editor,
8703 range: Range<usize>,
8704 replace_newest: bool,
8705 auto_scroll: Option<Autoscroll>,
8706 cx: &mut ViewContext<Editor>,
8707 ) {
8708 this.unfold_ranges(&[range.clone()], false, true, cx);
8709 this.change_selections(auto_scroll, cx, |s| {
8710 if replace_newest {
8711 s.delete(s.newest_anchor().id);
8712 }
8713 s.insert_range(range.clone());
8714 });
8715 }
8716
8717 let buffer = &display_map.buffer_snapshot;
8718 let mut selections = self.selections.all::<usize>(cx);
8719 if let Some(mut select_next_state) = self.select_next_state.take() {
8720 let query = &select_next_state.query;
8721 if !select_next_state.done {
8722 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8723 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8724 let mut next_selected_range = None;
8725
8726 let bytes_after_last_selection =
8727 buffer.bytes_in_range(last_selection.end..buffer.len());
8728 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8729 let query_matches = query
8730 .stream_find_iter(bytes_after_last_selection)
8731 .map(|result| (last_selection.end, result))
8732 .chain(
8733 query
8734 .stream_find_iter(bytes_before_first_selection)
8735 .map(|result| (0, result)),
8736 );
8737
8738 for (start_offset, query_match) in query_matches {
8739 let query_match = query_match.unwrap(); // can only fail due to I/O
8740 let offset_range =
8741 start_offset + query_match.start()..start_offset + query_match.end();
8742 let display_range = offset_range.start.to_display_point(display_map)
8743 ..offset_range.end.to_display_point(display_map);
8744
8745 if !select_next_state.wordwise
8746 || (!movement::is_inside_word(display_map, display_range.start)
8747 && !movement::is_inside_word(display_map, display_range.end))
8748 {
8749 // TODO: This is n^2, because we might check all the selections
8750 if !selections
8751 .iter()
8752 .any(|selection| selection.range().overlaps(&offset_range))
8753 {
8754 next_selected_range = Some(offset_range);
8755 break;
8756 }
8757 }
8758 }
8759
8760 if let Some(next_selected_range) = next_selected_range {
8761 select_next_match_ranges(
8762 self,
8763 next_selected_range,
8764 replace_newest,
8765 autoscroll,
8766 cx,
8767 );
8768 } else {
8769 select_next_state.done = true;
8770 }
8771 }
8772
8773 self.select_next_state = Some(select_next_state);
8774 } else {
8775 let mut only_carets = true;
8776 let mut same_text_selected = true;
8777 let mut selected_text = None;
8778
8779 let mut selections_iter = selections.iter().peekable();
8780 while let Some(selection) = selections_iter.next() {
8781 if selection.start != selection.end {
8782 only_carets = false;
8783 }
8784
8785 if same_text_selected {
8786 if selected_text.is_none() {
8787 selected_text =
8788 Some(buffer.text_for_range(selection.range()).collect::<String>());
8789 }
8790
8791 if let Some(next_selection) = selections_iter.peek() {
8792 if next_selection.range().len() == selection.range().len() {
8793 let next_selected_text = buffer
8794 .text_for_range(next_selection.range())
8795 .collect::<String>();
8796 if Some(next_selected_text) != selected_text {
8797 same_text_selected = false;
8798 selected_text = None;
8799 }
8800 } else {
8801 same_text_selected = false;
8802 selected_text = None;
8803 }
8804 }
8805 }
8806 }
8807
8808 if only_carets {
8809 for selection in &mut selections {
8810 let word_range = movement::surrounding_word(
8811 display_map,
8812 selection.start.to_display_point(display_map),
8813 );
8814 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8815 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8816 selection.goal = SelectionGoal::None;
8817 selection.reversed = false;
8818 select_next_match_ranges(
8819 self,
8820 selection.start..selection.end,
8821 replace_newest,
8822 autoscroll,
8823 cx,
8824 );
8825 }
8826
8827 if selections.len() == 1 {
8828 let selection = selections
8829 .last()
8830 .expect("ensured that there's only one selection");
8831 let query = buffer
8832 .text_for_range(selection.start..selection.end)
8833 .collect::<String>();
8834 let is_empty = query.is_empty();
8835 let select_state = SelectNextState {
8836 query: AhoCorasick::new(&[query])?,
8837 wordwise: true,
8838 done: is_empty,
8839 };
8840 self.select_next_state = Some(select_state);
8841 } else {
8842 self.select_next_state = None;
8843 }
8844 } else if let Some(selected_text) = selected_text {
8845 self.select_next_state = Some(SelectNextState {
8846 query: AhoCorasick::new(&[selected_text])?,
8847 wordwise: false,
8848 done: false,
8849 });
8850 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8851 }
8852 }
8853 Ok(())
8854 }
8855
8856 pub fn select_all_matches(
8857 &mut self,
8858 _action: &SelectAllMatches,
8859 cx: &mut ViewContext<Self>,
8860 ) -> Result<()> {
8861 self.push_to_selection_history();
8862 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8863
8864 self.select_next_match_internal(&display_map, false, None, cx)?;
8865 let Some(select_next_state) = self.select_next_state.as_mut() else {
8866 return Ok(());
8867 };
8868 if select_next_state.done {
8869 return Ok(());
8870 }
8871
8872 let mut new_selections = self.selections.all::<usize>(cx);
8873
8874 let buffer = &display_map.buffer_snapshot;
8875 let query_matches = select_next_state
8876 .query
8877 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8878
8879 for query_match in query_matches {
8880 let query_match = query_match.unwrap(); // can only fail due to I/O
8881 let offset_range = query_match.start()..query_match.end();
8882 let display_range = offset_range.start.to_display_point(&display_map)
8883 ..offset_range.end.to_display_point(&display_map);
8884
8885 if !select_next_state.wordwise
8886 || (!movement::is_inside_word(&display_map, display_range.start)
8887 && !movement::is_inside_word(&display_map, display_range.end))
8888 {
8889 self.selections.change_with(cx, |selections| {
8890 new_selections.push(Selection {
8891 id: selections.new_selection_id(),
8892 start: offset_range.start,
8893 end: offset_range.end,
8894 reversed: false,
8895 goal: SelectionGoal::None,
8896 });
8897 });
8898 }
8899 }
8900
8901 new_selections.sort_by_key(|selection| selection.start);
8902 let mut ix = 0;
8903 while ix + 1 < new_selections.len() {
8904 let current_selection = &new_selections[ix];
8905 let next_selection = &new_selections[ix + 1];
8906 if current_selection.range().overlaps(&next_selection.range()) {
8907 if current_selection.id < next_selection.id {
8908 new_selections.remove(ix + 1);
8909 } else {
8910 new_selections.remove(ix);
8911 }
8912 } else {
8913 ix += 1;
8914 }
8915 }
8916
8917 select_next_state.done = true;
8918 self.unfold_ranges(
8919 &new_selections
8920 .iter()
8921 .map(|selection| selection.range())
8922 .collect::<Vec<_>>(),
8923 false,
8924 false,
8925 cx,
8926 );
8927 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8928 selections.select(new_selections)
8929 });
8930
8931 Ok(())
8932 }
8933
8934 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8935 self.push_to_selection_history();
8936 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8937 self.select_next_match_internal(
8938 &display_map,
8939 action.replace_newest,
8940 Some(Autoscroll::newest()),
8941 cx,
8942 )?;
8943 Ok(())
8944 }
8945
8946 pub fn select_previous(
8947 &mut self,
8948 action: &SelectPrevious,
8949 cx: &mut ViewContext<Self>,
8950 ) -> Result<()> {
8951 self.push_to_selection_history();
8952 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8953 let buffer = &display_map.buffer_snapshot;
8954 let mut selections = self.selections.all::<usize>(cx);
8955 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8956 let query = &select_prev_state.query;
8957 if !select_prev_state.done {
8958 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8959 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8960 let mut next_selected_range = None;
8961 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8962 let bytes_before_last_selection =
8963 buffer.reversed_bytes_in_range(0..last_selection.start);
8964 let bytes_after_first_selection =
8965 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8966 let query_matches = query
8967 .stream_find_iter(bytes_before_last_selection)
8968 .map(|result| (last_selection.start, result))
8969 .chain(
8970 query
8971 .stream_find_iter(bytes_after_first_selection)
8972 .map(|result| (buffer.len(), result)),
8973 );
8974 for (end_offset, query_match) in query_matches {
8975 let query_match = query_match.unwrap(); // can only fail due to I/O
8976 let offset_range =
8977 end_offset - query_match.end()..end_offset - query_match.start();
8978 let display_range = offset_range.start.to_display_point(&display_map)
8979 ..offset_range.end.to_display_point(&display_map);
8980
8981 if !select_prev_state.wordwise
8982 || (!movement::is_inside_word(&display_map, display_range.start)
8983 && !movement::is_inside_word(&display_map, display_range.end))
8984 {
8985 next_selected_range = Some(offset_range);
8986 break;
8987 }
8988 }
8989
8990 if let Some(next_selected_range) = next_selected_range {
8991 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8992 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8993 if action.replace_newest {
8994 s.delete(s.newest_anchor().id);
8995 }
8996 s.insert_range(next_selected_range);
8997 });
8998 } else {
8999 select_prev_state.done = true;
9000 }
9001 }
9002
9003 self.select_prev_state = Some(select_prev_state);
9004 } else {
9005 let mut only_carets = true;
9006 let mut same_text_selected = true;
9007 let mut selected_text = None;
9008
9009 let mut selections_iter = selections.iter().peekable();
9010 while let Some(selection) = selections_iter.next() {
9011 if selection.start != selection.end {
9012 only_carets = false;
9013 }
9014
9015 if same_text_selected {
9016 if selected_text.is_none() {
9017 selected_text =
9018 Some(buffer.text_for_range(selection.range()).collect::<String>());
9019 }
9020
9021 if let Some(next_selection) = selections_iter.peek() {
9022 if next_selection.range().len() == selection.range().len() {
9023 let next_selected_text = buffer
9024 .text_for_range(next_selection.range())
9025 .collect::<String>();
9026 if Some(next_selected_text) != selected_text {
9027 same_text_selected = false;
9028 selected_text = None;
9029 }
9030 } else {
9031 same_text_selected = false;
9032 selected_text = None;
9033 }
9034 }
9035 }
9036 }
9037
9038 if only_carets {
9039 for selection in &mut selections {
9040 let word_range = movement::surrounding_word(
9041 &display_map,
9042 selection.start.to_display_point(&display_map),
9043 );
9044 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9045 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9046 selection.goal = SelectionGoal::None;
9047 selection.reversed = false;
9048 }
9049 if selections.len() == 1 {
9050 let selection = selections
9051 .last()
9052 .expect("ensured that there's only one selection");
9053 let query = buffer
9054 .text_for_range(selection.start..selection.end)
9055 .collect::<String>();
9056 let is_empty = query.is_empty();
9057 let select_state = SelectNextState {
9058 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9059 wordwise: true,
9060 done: is_empty,
9061 };
9062 self.select_prev_state = Some(select_state);
9063 } else {
9064 self.select_prev_state = None;
9065 }
9066
9067 self.unfold_ranges(
9068 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9069 false,
9070 true,
9071 cx,
9072 );
9073 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
9074 s.select(selections);
9075 });
9076 } else if let Some(selected_text) = selected_text {
9077 self.select_prev_state = Some(SelectNextState {
9078 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9079 wordwise: false,
9080 done: false,
9081 });
9082 self.select_previous(action, cx)?;
9083 }
9084 }
9085 Ok(())
9086 }
9087
9088 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
9089 if self.read_only(cx) {
9090 return;
9091 }
9092 let text_layout_details = &self.text_layout_details(cx);
9093 self.transact(cx, |this, cx| {
9094 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9095 let mut edits = Vec::new();
9096 let mut selection_edit_ranges = Vec::new();
9097 let mut last_toggled_row = None;
9098 let snapshot = this.buffer.read(cx).read(cx);
9099 let empty_str: Arc<str> = Arc::default();
9100 let mut suffixes_inserted = Vec::new();
9101 let ignore_indent = action.ignore_indent;
9102
9103 fn comment_prefix_range(
9104 snapshot: &MultiBufferSnapshot,
9105 row: MultiBufferRow,
9106 comment_prefix: &str,
9107 comment_prefix_whitespace: &str,
9108 ignore_indent: bool,
9109 ) -> Range<Point> {
9110 let indent_size = if ignore_indent {
9111 0
9112 } else {
9113 snapshot.indent_size_for_line(row).len
9114 };
9115
9116 let start = Point::new(row.0, indent_size);
9117
9118 let mut line_bytes = snapshot
9119 .bytes_in_range(start..snapshot.max_point())
9120 .flatten()
9121 .copied();
9122
9123 // If this line currently begins with the line comment prefix, then record
9124 // the range containing the prefix.
9125 if line_bytes
9126 .by_ref()
9127 .take(comment_prefix.len())
9128 .eq(comment_prefix.bytes())
9129 {
9130 // Include any whitespace that matches the comment prefix.
9131 let matching_whitespace_len = line_bytes
9132 .zip(comment_prefix_whitespace.bytes())
9133 .take_while(|(a, b)| a == b)
9134 .count() as u32;
9135 let end = Point::new(
9136 start.row,
9137 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9138 );
9139 start..end
9140 } else {
9141 start..start
9142 }
9143 }
9144
9145 fn comment_suffix_range(
9146 snapshot: &MultiBufferSnapshot,
9147 row: MultiBufferRow,
9148 comment_suffix: &str,
9149 comment_suffix_has_leading_space: bool,
9150 ) -> Range<Point> {
9151 let end = Point::new(row.0, snapshot.line_len(row));
9152 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9153
9154 let mut line_end_bytes = snapshot
9155 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9156 .flatten()
9157 .copied();
9158
9159 let leading_space_len = if suffix_start_column > 0
9160 && line_end_bytes.next() == Some(b' ')
9161 && comment_suffix_has_leading_space
9162 {
9163 1
9164 } else {
9165 0
9166 };
9167
9168 // If this line currently begins with the line comment prefix, then record
9169 // the range containing the prefix.
9170 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9171 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9172 start..end
9173 } else {
9174 end..end
9175 }
9176 }
9177
9178 // TODO: Handle selections that cross excerpts
9179 for selection in &mut selections {
9180 let start_column = snapshot
9181 .indent_size_for_line(MultiBufferRow(selection.start.row))
9182 .len;
9183 let language = if let Some(language) =
9184 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9185 {
9186 language
9187 } else {
9188 continue;
9189 };
9190
9191 selection_edit_ranges.clear();
9192
9193 // If multiple selections contain a given row, avoid processing that
9194 // row more than once.
9195 let mut start_row = MultiBufferRow(selection.start.row);
9196 if last_toggled_row == Some(start_row) {
9197 start_row = start_row.next_row();
9198 }
9199 let end_row =
9200 if selection.end.row > selection.start.row && selection.end.column == 0 {
9201 MultiBufferRow(selection.end.row - 1)
9202 } else {
9203 MultiBufferRow(selection.end.row)
9204 };
9205 last_toggled_row = Some(end_row);
9206
9207 if start_row > end_row {
9208 continue;
9209 }
9210
9211 // If the language has line comments, toggle those.
9212 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9213
9214 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9215 if ignore_indent {
9216 full_comment_prefixes = full_comment_prefixes
9217 .into_iter()
9218 .map(|s| Arc::from(s.trim_end()))
9219 .collect();
9220 }
9221
9222 if !full_comment_prefixes.is_empty() {
9223 let first_prefix = full_comment_prefixes
9224 .first()
9225 .expect("prefixes is non-empty");
9226 let prefix_trimmed_lengths = full_comment_prefixes
9227 .iter()
9228 .map(|p| p.trim_end_matches(' ').len())
9229 .collect::<SmallVec<[usize; 4]>>();
9230
9231 let mut all_selection_lines_are_comments = true;
9232
9233 for row in start_row.0..=end_row.0 {
9234 let row = MultiBufferRow(row);
9235 if start_row < end_row && snapshot.is_line_blank(row) {
9236 continue;
9237 }
9238
9239 let prefix_range = full_comment_prefixes
9240 .iter()
9241 .zip(prefix_trimmed_lengths.iter().copied())
9242 .map(|(prefix, trimmed_prefix_len)| {
9243 comment_prefix_range(
9244 snapshot.deref(),
9245 row,
9246 &prefix[..trimmed_prefix_len],
9247 &prefix[trimmed_prefix_len..],
9248 ignore_indent,
9249 )
9250 })
9251 .max_by_key(|range| range.end.column - range.start.column)
9252 .expect("prefixes is non-empty");
9253
9254 if prefix_range.is_empty() {
9255 all_selection_lines_are_comments = false;
9256 }
9257
9258 selection_edit_ranges.push(prefix_range);
9259 }
9260
9261 if all_selection_lines_are_comments {
9262 edits.extend(
9263 selection_edit_ranges
9264 .iter()
9265 .cloned()
9266 .map(|range| (range, empty_str.clone())),
9267 );
9268 } else {
9269 let min_column = selection_edit_ranges
9270 .iter()
9271 .map(|range| range.start.column)
9272 .min()
9273 .unwrap_or(0);
9274 edits.extend(selection_edit_ranges.iter().map(|range| {
9275 let position = Point::new(range.start.row, min_column);
9276 (position..position, first_prefix.clone())
9277 }));
9278 }
9279 } else if let Some((full_comment_prefix, comment_suffix)) =
9280 language.block_comment_delimiters()
9281 {
9282 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9283 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9284 let prefix_range = comment_prefix_range(
9285 snapshot.deref(),
9286 start_row,
9287 comment_prefix,
9288 comment_prefix_whitespace,
9289 ignore_indent,
9290 );
9291 let suffix_range = comment_suffix_range(
9292 snapshot.deref(),
9293 end_row,
9294 comment_suffix.trim_start_matches(' '),
9295 comment_suffix.starts_with(' '),
9296 );
9297
9298 if prefix_range.is_empty() || suffix_range.is_empty() {
9299 edits.push((
9300 prefix_range.start..prefix_range.start,
9301 full_comment_prefix.clone(),
9302 ));
9303 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9304 suffixes_inserted.push((end_row, comment_suffix.len()));
9305 } else {
9306 edits.push((prefix_range, empty_str.clone()));
9307 edits.push((suffix_range, empty_str.clone()));
9308 }
9309 } else {
9310 continue;
9311 }
9312 }
9313
9314 drop(snapshot);
9315 this.buffer.update(cx, |buffer, cx| {
9316 buffer.edit(edits, None, cx);
9317 });
9318
9319 // Adjust selections so that they end before any comment suffixes that
9320 // were inserted.
9321 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9322 let mut selections = this.selections.all::<Point>(cx);
9323 let snapshot = this.buffer.read(cx).read(cx);
9324 for selection in &mut selections {
9325 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9326 match row.cmp(&MultiBufferRow(selection.end.row)) {
9327 Ordering::Less => {
9328 suffixes_inserted.next();
9329 continue;
9330 }
9331 Ordering::Greater => break,
9332 Ordering::Equal => {
9333 if selection.end.column == snapshot.line_len(row) {
9334 if selection.is_empty() {
9335 selection.start.column -= suffix_len as u32;
9336 }
9337 selection.end.column -= suffix_len as u32;
9338 }
9339 break;
9340 }
9341 }
9342 }
9343 }
9344
9345 drop(snapshot);
9346 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
9347
9348 let selections = this.selections.all::<Point>(cx);
9349 let selections_on_single_row = selections.windows(2).all(|selections| {
9350 selections[0].start.row == selections[1].start.row
9351 && selections[0].end.row == selections[1].end.row
9352 && selections[0].start.row == selections[0].end.row
9353 });
9354 let selections_selecting = selections
9355 .iter()
9356 .any(|selection| selection.start != selection.end);
9357 let advance_downwards = action.advance_downwards
9358 && selections_on_single_row
9359 && !selections_selecting
9360 && !matches!(this.mode, EditorMode::SingleLine { .. });
9361
9362 if advance_downwards {
9363 let snapshot = this.buffer.read(cx).snapshot(cx);
9364
9365 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
9366 s.move_cursors_with(|display_snapshot, display_point, _| {
9367 let mut point = display_point.to_point(display_snapshot);
9368 point.row += 1;
9369 point = snapshot.clip_point(point, Bias::Left);
9370 let display_point = point.to_display_point(display_snapshot);
9371 let goal = SelectionGoal::HorizontalPosition(
9372 display_snapshot
9373 .x_for_display_point(display_point, text_layout_details)
9374 .into(),
9375 );
9376 (display_point, goal)
9377 })
9378 });
9379 }
9380 });
9381 }
9382
9383 pub fn select_enclosing_symbol(
9384 &mut self,
9385 _: &SelectEnclosingSymbol,
9386 cx: &mut ViewContext<Self>,
9387 ) {
9388 let buffer = self.buffer.read(cx).snapshot(cx);
9389 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9390
9391 fn update_selection(
9392 selection: &Selection<usize>,
9393 buffer_snap: &MultiBufferSnapshot,
9394 ) -> Option<Selection<usize>> {
9395 let cursor = selection.head();
9396 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9397 for symbol in symbols.iter().rev() {
9398 let start = symbol.range.start.to_offset(buffer_snap);
9399 let end = symbol.range.end.to_offset(buffer_snap);
9400 let new_range = start..end;
9401 if start < selection.start || end > selection.end {
9402 return Some(Selection {
9403 id: selection.id,
9404 start: new_range.start,
9405 end: new_range.end,
9406 goal: SelectionGoal::None,
9407 reversed: selection.reversed,
9408 });
9409 }
9410 }
9411 None
9412 }
9413
9414 let mut selected_larger_symbol = false;
9415 let new_selections = old_selections
9416 .iter()
9417 .map(|selection| match update_selection(selection, &buffer) {
9418 Some(new_selection) => {
9419 if new_selection.range() != selection.range() {
9420 selected_larger_symbol = true;
9421 }
9422 new_selection
9423 }
9424 None => selection.clone(),
9425 })
9426 .collect::<Vec<_>>();
9427
9428 if selected_larger_symbol {
9429 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9430 s.select(new_selections);
9431 });
9432 }
9433 }
9434
9435 pub fn select_larger_syntax_node(
9436 &mut self,
9437 _: &SelectLargerSyntaxNode,
9438 cx: &mut ViewContext<Self>,
9439 ) {
9440 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9441 let buffer = self.buffer.read(cx).snapshot(cx);
9442 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9443
9444 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9445 let mut selected_larger_node = false;
9446 let new_selections = old_selections
9447 .iter()
9448 .map(|selection| {
9449 let old_range = selection.start..selection.end;
9450 let mut new_range = old_range.clone();
9451 while let Some(containing_range) =
9452 buffer.range_for_syntax_ancestor(new_range.clone())
9453 {
9454 new_range = containing_range;
9455 if !display_map.intersects_fold(new_range.start)
9456 && !display_map.intersects_fold(new_range.end)
9457 {
9458 break;
9459 }
9460 }
9461
9462 selected_larger_node |= new_range != old_range;
9463 Selection {
9464 id: selection.id,
9465 start: new_range.start,
9466 end: new_range.end,
9467 goal: SelectionGoal::None,
9468 reversed: selection.reversed,
9469 }
9470 })
9471 .collect::<Vec<_>>();
9472
9473 if selected_larger_node {
9474 stack.push(old_selections);
9475 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9476 s.select(new_selections);
9477 });
9478 }
9479 self.select_larger_syntax_node_stack = stack;
9480 }
9481
9482 pub fn select_smaller_syntax_node(
9483 &mut self,
9484 _: &SelectSmallerSyntaxNode,
9485 cx: &mut ViewContext<Self>,
9486 ) {
9487 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9488 if let Some(selections) = stack.pop() {
9489 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9490 s.select(selections.to_vec());
9491 });
9492 }
9493 self.select_larger_syntax_node_stack = stack;
9494 }
9495
9496 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
9497 if !EditorSettings::get_global(cx).gutter.runnables {
9498 self.clear_tasks();
9499 return Task::ready(());
9500 }
9501 let project = self.project.as_ref().map(Model::downgrade);
9502 cx.spawn(|this, mut cx| async move {
9503 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
9504 let Some(project) = project.and_then(|p| p.upgrade()) else {
9505 return;
9506 };
9507 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9508 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9509 }) else {
9510 return;
9511 };
9512
9513 let hide_runnables = project
9514 .update(&mut cx, |project, cx| {
9515 // Do not display any test indicators in non-dev server remote projects.
9516 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9517 })
9518 .unwrap_or(true);
9519 if hide_runnables {
9520 return;
9521 }
9522 let new_rows =
9523 cx.background_executor()
9524 .spawn({
9525 let snapshot = display_snapshot.clone();
9526 async move {
9527 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9528 }
9529 })
9530 .await;
9531 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9532
9533 this.update(&mut cx, |this, _| {
9534 this.clear_tasks();
9535 for (key, value) in rows {
9536 this.insert_tasks(key, value);
9537 }
9538 })
9539 .ok();
9540 })
9541 }
9542 fn fetch_runnable_ranges(
9543 snapshot: &DisplaySnapshot,
9544 range: Range<Anchor>,
9545 ) -> Vec<language::RunnableRange> {
9546 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9547 }
9548
9549 fn runnable_rows(
9550 project: Model<Project>,
9551 snapshot: DisplaySnapshot,
9552 runnable_ranges: Vec<RunnableRange>,
9553 mut cx: AsyncWindowContext,
9554 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9555 runnable_ranges
9556 .into_iter()
9557 .filter_map(|mut runnable| {
9558 let tasks = cx
9559 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9560 .ok()?;
9561 if tasks.is_empty() {
9562 return None;
9563 }
9564
9565 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9566
9567 let row = snapshot
9568 .buffer_snapshot
9569 .buffer_line_for_row(MultiBufferRow(point.row))?
9570 .1
9571 .start
9572 .row;
9573
9574 let context_range =
9575 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9576 Some((
9577 (runnable.buffer_id, row),
9578 RunnableTasks {
9579 templates: tasks,
9580 offset: MultiBufferOffset(runnable.run_range.start),
9581 context_range,
9582 column: point.column,
9583 extra_variables: runnable.extra_captures,
9584 },
9585 ))
9586 })
9587 .collect()
9588 }
9589
9590 fn templates_with_tags(
9591 project: &Model<Project>,
9592 runnable: &mut Runnable,
9593 cx: &WindowContext<'_>,
9594 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9595 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9596 let (worktree_id, file) = project
9597 .buffer_for_id(runnable.buffer, cx)
9598 .and_then(|buffer| buffer.read(cx).file())
9599 .map(|file| (file.worktree_id(cx), file.clone()))
9600 .unzip();
9601
9602 (
9603 project.task_store().read(cx).task_inventory().cloned(),
9604 worktree_id,
9605 file,
9606 )
9607 });
9608
9609 let tags = mem::take(&mut runnable.tags);
9610 let mut tags: Vec<_> = tags
9611 .into_iter()
9612 .flat_map(|tag| {
9613 let tag = tag.0.clone();
9614 inventory
9615 .as_ref()
9616 .into_iter()
9617 .flat_map(|inventory| {
9618 inventory.read(cx).list_tasks(
9619 file.clone(),
9620 Some(runnable.language.clone()),
9621 worktree_id,
9622 cx,
9623 )
9624 })
9625 .filter(move |(_, template)| {
9626 template.tags.iter().any(|source_tag| source_tag == &tag)
9627 })
9628 })
9629 .sorted_by_key(|(kind, _)| kind.to_owned())
9630 .collect();
9631 if let Some((leading_tag_source, _)) = tags.first() {
9632 // Strongest source wins; if we have worktree tag binding, prefer that to
9633 // global and language bindings;
9634 // if we have a global binding, prefer that to language binding.
9635 let first_mismatch = tags
9636 .iter()
9637 .position(|(tag_source, _)| tag_source != leading_tag_source);
9638 if let Some(index) = first_mismatch {
9639 tags.truncate(index);
9640 }
9641 }
9642
9643 tags
9644 }
9645
9646 pub fn move_to_enclosing_bracket(
9647 &mut self,
9648 _: &MoveToEnclosingBracket,
9649 cx: &mut ViewContext<Self>,
9650 ) {
9651 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9652 s.move_offsets_with(|snapshot, selection| {
9653 let Some(enclosing_bracket_ranges) =
9654 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9655 else {
9656 return;
9657 };
9658
9659 let mut best_length = usize::MAX;
9660 let mut best_inside = false;
9661 let mut best_in_bracket_range = false;
9662 let mut best_destination = None;
9663 for (open, close) in enclosing_bracket_ranges {
9664 let close = close.to_inclusive();
9665 let length = close.end() - open.start;
9666 let inside = selection.start >= open.end && selection.end <= *close.start();
9667 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9668 || close.contains(&selection.head());
9669
9670 // If best is next to a bracket and current isn't, skip
9671 if !in_bracket_range && best_in_bracket_range {
9672 continue;
9673 }
9674
9675 // Prefer smaller lengths unless best is inside and current isn't
9676 if length > best_length && (best_inside || !inside) {
9677 continue;
9678 }
9679
9680 best_length = length;
9681 best_inside = inside;
9682 best_in_bracket_range = in_bracket_range;
9683 best_destination = Some(
9684 if close.contains(&selection.start) && close.contains(&selection.end) {
9685 if inside {
9686 open.end
9687 } else {
9688 open.start
9689 }
9690 } else if inside {
9691 *close.start()
9692 } else {
9693 *close.end()
9694 },
9695 );
9696 }
9697
9698 if let Some(destination) = best_destination {
9699 selection.collapse_to(destination, SelectionGoal::None);
9700 }
9701 })
9702 });
9703 }
9704
9705 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9706 self.end_selection(cx);
9707 self.selection_history.mode = SelectionHistoryMode::Undoing;
9708 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9709 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9710 self.select_next_state = entry.select_next_state;
9711 self.select_prev_state = entry.select_prev_state;
9712 self.add_selections_state = entry.add_selections_state;
9713 self.request_autoscroll(Autoscroll::newest(), cx);
9714 }
9715 self.selection_history.mode = SelectionHistoryMode::Normal;
9716 }
9717
9718 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9719 self.end_selection(cx);
9720 self.selection_history.mode = SelectionHistoryMode::Redoing;
9721 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9722 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9723 self.select_next_state = entry.select_next_state;
9724 self.select_prev_state = entry.select_prev_state;
9725 self.add_selections_state = entry.add_selections_state;
9726 self.request_autoscroll(Autoscroll::newest(), cx);
9727 }
9728 self.selection_history.mode = SelectionHistoryMode::Normal;
9729 }
9730
9731 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9732 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9733 }
9734
9735 pub fn expand_excerpts_down(
9736 &mut self,
9737 action: &ExpandExcerptsDown,
9738 cx: &mut ViewContext<Self>,
9739 ) {
9740 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9741 }
9742
9743 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9744 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9745 }
9746
9747 pub fn expand_excerpts_for_direction(
9748 &mut self,
9749 lines: u32,
9750 direction: ExpandExcerptDirection,
9751 cx: &mut ViewContext<Self>,
9752 ) {
9753 let selections = self.selections.disjoint_anchors();
9754
9755 let lines = if lines == 0 {
9756 EditorSettings::get_global(cx).expand_excerpt_lines
9757 } else {
9758 lines
9759 };
9760
9761 self.buffer.update(cx, |buffer, cx| {
9762 buffer.expand_excerpts(
9763 selections
9764 .iter()
9765 .map(|selection| selection.head().excerpt_id)
9766 .dedup(),
9767 lines,
9768 direction,
9769 cx,
9770 )
9771 })
9772 }
9773
9774 pub fn expand_excerpt(
9775 &mut self,
9776 excerpt: ExcerptId,
9777 direction: ExpandExcerptDirection,
9778 cx: &mut ViewContext<Self>,
9779 ) {
9780 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9781 self.buffer.update(cx, |buffer, cx| {
9782 buffer.expand_excerpts([excerpt], lines, direction, cx)
9783 })
9784 }
9785
9786 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9787 self.go_to_diagnostic_impl(Direction::Next, cx)
9788 }
9789
9790 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9791 self.go_to_diagnostic_impl(Direction::Prev, cx)
9792 }
9793
9794 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9795 let buffer = self.buffer.read(cx).snapshot(cx);
9796 let selection = self.selections.newest::<usize>(cx);
9797
9798 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9799 if direction == Direction::Next {
9800 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9801 let (group_id, jump_to) = popover.activation_info();
9802 if self.activate_diagnostics(group_id, cx) {
9803 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9804 let mut new_selection = s.newest_anchor().clone();
9805 new_selection.collapse_to(jump_to, SelectionGoal::None);
9806 s.select_anchors(vec![new_selection.clone()]);
9807 });
9808 }
9809 return;
9810 }
9811 }
9812
9813 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9814 active_diagnostics
9815 .primary_range
9816 .to_offset(&buffer)
9817 .to_inclusive()
9818 });
9819 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9820 if active_primary_range.contains(&selection.head()) {
9821 *active_primary_range.start()
9822 } else {
9823 selection.head()
9824 }
9825 } else {
9826 selection.head()
9827 };
9828 let snapshot = self.snapshot(cx);
9829 loop {
9830 let diagnostics = if direction == Direction::Prev {
9831 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9832 } else {
9833 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9834 }
9835 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9836 let group = diagnostics
9837 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9838 // be sorted in a stable way
9839 // skip until we are at current active diagnostic, if it exists
9840 .skip_while(|entry| {
9841 (match direction {
9842 Direction::Prev => entry.range.start >= search_start,
9843 Direction::Next => entry.range.start <= search_start,
9844 }) && self
9845 .active_diagnostics
9846 .as_ref()
9847 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9848 })
9849 .find_map(|entry| {
9850 if entry.diagnostic.is_primary
9851 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9852 && !entry.range.is_empty()
9853 // if we match with the active diagnostic, skip it
9854 && Some(entry.diagnostic.group_id)
9855 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9856 {
9857 Some((entry.range, entry.diagnostic.group_id))
9858 } else {
9859 None
9860 }
9861 });
9862
9863 if let Some((primary_range, group_id)) = group {
9864 if self.activate_diagnostics(group_id, cx) {
9865 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9866 s.select(vec![Selection {
9867 id: selection.id,
9868 start: primary_range.start,
9869 end: primary_range.start,
9870 reversed: false,
9871 goal: SelectionGoal::None,
9872 }]);
9873 });
9874 }
9875 break;
9876 } else {
9877 // Cycle around to the start of the buffer, potentially moving back to the start of
9878 // the currently active diagnostic.
9879 active_primary_range.take();
9880 if direction == Direction::Prev {
9881 if search_start == buffer.len() {
9882 break;
9883 } else {
9884 search_start = buffer.len();
9885 }
9886 } else if search_start == 0 {
9887 break;
9888 } else {
9889 search_start = 0;
9890 }
9891 }
9892 }
9893 }
9894
9895 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9896 let snapshot = self.snapshot(cx);
9897 let selection = self.selections.newest::<Point>(cx);
9898 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9899 }
9900
9901 fn go_to_hunk_after_position(
9902 &mut self,
9903 snapshot: &EditorSnapshot,
9904 position: Point,
9905 cx: &mut ViewContext<'_, Editor>,
9906 ) -> Option<MultiBufferDiffHunk> {
9907 for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
9908 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9909 snapshot,
9910 position,
9911 ix > 0,
9912 snapshot.diff_map.diff_hunks_in_range(
9913 position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
9914 &snapshot.buffer_snapshot,
9915 ),
9916 cx,
9917 ) {
9918 return Some(hunk);
9919 }
9920 }
9921 None
9922 }
9923
9924 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9925 let snapshot = self.snapshot(cx);
9926 let selection = self.selections.newest::<Point>(cx);
9927 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9928 }
9929
9930 fn go_to_hunk_before_position(
9931 &mut self,
9932 snapshot: &EditorSnapshot,
9933 position: Point,
9934 cx: &mut ViewContext<'_, Editor>,
9935 ) -> Option<MultiBufferDiffHunk> {
9936 for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
9937 .into_iter()
9938 .enumerate()
9939 {
9940 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9941 snapshot,
9942 position,
9943 ix > 0,
9944 snapshot
9945 .diff_map
9946 .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
9947 cx,
9948 ) {
9949 return Some(hunk);
9950 }
9951 }
9952 None
9953 }
9954
9955 fn go_to_next_hunk_in_direction(
9956 &mut self,
9957 snapshot: &DisplaySnapshot,
9958 initial_point: Point,
9959 is_wrapped: bool,
9960 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9961 cx: &mut ViewContext<Editor>,
9962 ) -> Option<MultiBufferDiffHunk> {
9963 let display_point = initial_point.to_display_point(snapshot);
9964 let mut hunks = hunks
9965 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9966 .filter(|(display_hunk, _)| {
9967 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9968 })
9969 .dedup();
9970
9971 if let Some((display_hunk, hunk)) = hunks.next() {
9972 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9973 let row = display_hunk.start_display_row();
9974 let point = DisplayPoint::new(row, 0);
9975 s.select_display_ranges([point..point]);
9976 });
9977
9978 Some(hunk)
9979 } else {
9980 None
9981 }
9982 }
9983
9984 pub fn go_to_definition(
9985 &mut self,
9986 _: &GoToDefinition,
9987 cx: &mut ViewContext<Self>,
9988 ) -> Task<Result<Navigated>> {
9989 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9990 cx.spawn(|editor, mut cx| async move {
9991 if definition.await? == Navigated::Yes {
9992 return Ok(Navigated::Yes);
9993 }
9994 match editor.update(&mut cx, |editor, cx| {
9995 editor.find_all_references(&FindAllReferences, cx)
9996 })? {
9997 Some(references) => references.await,
9998 None => Ok(Navigated::No),
9999 }
10000 })
10001 }
10002
10003 pub fn go_to_declaration(
10004 &mut self,
10005 _: &GoToDeclaration,
10006 cx: &mut ViewContext<Self>,
10007 ) -> Task<Result<Navigated>> {
10008 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
10009 }
10010
10011 pub fn go_to_declaration_split(
10012 &mut self,
10013 _: &GoToDeclaration,
10014 cx: &mut ViewContext<Self>,
10015 ) -> Task<Result<Navigated>> {
10016 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
10017 }
10018
10019 pub fn go_to_implementation(
10020 &mut self,
10021 _: &GoToImplementation,
10022 cx: &mut ViewContext<Self>,
10023 ) -> Task<Result<Navigated>> {
10024 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
10025 }
10026
10027 pub fn go_to_implementation_split(
10028 &mut self,
10029 _: &GoToImplementationSplit,
10030 cx: &mut ViewContext<Self>,
10031 ) -> Task<Result<Navigated>> {
10032 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
10033 }
10034
10035 pub fn go_to_type_definition(
10036 &mut self,
10037 _: &GoToTypeDefinition,
10038 cx: &mut ViewContext<Self>,
10039 ) -> Task<Result<Navigated>> {
10040 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
10041 }
10042
10043 pub fn go_to_definition_split(
10044 &mut self,
10045 _: &GoToDefinitionSplit,
10046 cx: &mut ViewContext<Self>,
10047 ) -> Task<Result<Navigated>> {
10048 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
10049 }
10050
10051 pub fn go_to_type_definition_split(
10052 &mut self,
10053 _: &GoToTypeDefinitionSplit,
10054 cx: &mut ViewContext<Self>,
10055 ) -> Task<Result<Navigated>> {
10056 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
10057 }
10058
10059 fn go_to_definition_of_kind(
10060 &mut self,
10061 kind: GotoDefinitionKind,
10062 split: bool,
10063 cx: &mut ViewContext<Self>,
10064 ) -> Task<Result<Navigated>> {
10065 let Some(provider) = self.semantics_provider.clone() else {
10066 return Task::ready(Ok(Navigated::No));
10067 };
10068 let head = self.selections.newest::<usize>(cx).head();
10069 let buffer = self.buffer.read(cx);
10070 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10071 text_anchor
10072 } else {
10073 return Task::ready(Ok(Navigated::No));
10074 };
10075
10076 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10077 return Task::ready(Ok(Navigated::No));
10078 };
10079
10080 cx.spawn(|editor, mut cx| async move {
10081 let definitions = definitions.await?;
10082 let navigated = editor
10083 .update(&mut cx, |editor, cx| {
10084 editor.navigate_to_hover_links(
10085 Some(kind),
10086 definitions
10087 .into_iter()
10088 .filter(|location| {
10089 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10090 })
10091 .map(HoverLink::Text)
10092 .collect::<Vec<_>>(),
10093 split,
10094 cx,
10095 )
10096 })?
10097 .await?;
10098 anyhow::Ok(navigated)
10099 })
10100 }
10101
10102 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
10103 let position = self.selections.newest_anchor().head();
10104 let Some((buffer, buffer_position)) =
10105 self.buffer.read(cx).text_anchor_for_position(position, cx)
10106 else {
10107 return;
10108 };
10109
10110 cx.spawn(|editor, mut cx| async move {
10111 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
10112 editor.update(&mut cx, |_, cx| {
10113 cx.open_url(&url);
10114 })
10115 } else {
10116 Ok(())
10117 }
10118 })
10119 .detach();
10120 }
10121
10122 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
10123 let Some(workspace) = self.workspace() else {
10124 return;
10125 };
10126
10127 let position = self.selections.newest_anchor().head();
10128
10129 let Some((buffer, buffer_position)) =
10130 self.buffer.read(cx).text_anchor_for_position(position, cx)
10131 else {
10132 return;
10133 };
10134
10135 let project = self.project.clone();
10136
10137 cx.spawn(|_, mut cx| async move {
10138 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10139
10140 if let Some((_, path)) = result {
10141 workspace
10142 .update(&mut cx, |workspace, cx| {
10143 workspace.open_resolved_path(path, cx)
10144 })?
10145 .await?;
10146 }
10147 anyhow::Ok(())
10148 })
10149 .detach();
10150 }
10151
10152 pub(crate) fn navigate_to_hover_links(
10153 &mut self,
10154 kind: Option<GotoDefinitionKind>,
10155 mut definitions: Vec<HoverLink>,
10156 split: bool,
10157 cx: &mut ViewContext<Editor>,
10158 ) -> Task<Result<Navigated>> {
10159 // If there is one definition, just open it directly
10160 if definitions.len() == 1 {
10161 let definition = definitions.pop().unwrap();
10162
10163 enum TargetTaskResult {
10164 Location(Option<Location>),
10165 AlreadyNavigated,
10166 }
10167
10168 let target_task = match definition {
10169 HoverLink::Text(link) => {
10170 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10171 }
10172 HoverLink::InlayHint(lsp_location, server_id) => {
10173 let computation = self.compute_target_location(lsp_location, server_id, cx);
10174 cx.background_executor().spawn(async move {
10175 let location = computation.await?;
10176 Ok(TargetTaskResult::Location(location))
10177 })
10178 }
10179 HoverLink::Url(url) => {
10180 cx.open_url(&url);
10181 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10182 }
10183 HoverLink::File(path) => {
10184 if let Some(workspace) = self.workspace() {
10185 cx.spawn(|_, mut cx| async move {
10186 workspace
10187 .update(&mut cx, |workspace, cx| {
10188 workspace.open_resolved_path(path, cx)
10189 })?
10190 .await
10191 .map(|_| TargetTaskResult::AlreadyNavigated)
10192 })
10193 } else {
10194 Task::ready(Ok(TargetTaskResult::Location(None)))
10195 }
10196 }
10197 };
10198 cx.spawn(|editor, mut cx| async move {
10199 let target = match target_task.await.context("target resolution task")? {
10200 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10201 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10202 TargetTaskResult::Location(Some(target)) => target,
10203 };
10204
10205 editor.update(&mut cx, |editor, cx| {
10206 let Some(workspace) = editor.workspace() else {
10207 return Navigated::No;
10208 };
10209 let pane = workspace.read(cx).active_pane().clone();
10210
10211 let range = target.range.to_offset(target.buffer.read(cx));
10212 let range = editor.range_for_match(&range);
10213
10214 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10215 let buffer = target.buffer.read(cx);
10216 let range = check_multiline_range(buffer, range);
10217 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10218 s.select_ranges([range]);
10219 });
10220 } else {
10221 cx.window_context().defer(move |cx| {
10222 let target_editor: View<Self> =
10223 workspace.update(cx, |workspace, cx| {
10224 let pane = if split {
10225 workspace.adjacent_pane(cx)
10226 } else {
10227 workspace.active_pane().clone()
10228 };
10229
10230 workspace.open_project_item(
10231 pane,
10232 target.buffer.clone(),
10233 true,
10234 true,
10235 cx,
10236 )
10237 });
10238 target_editor.update(cx, |target_editor, cx| {
10239 // When selecting a definition in a different buffer, disable the nav history
10240 // to avoid creating a history entry at the previous cursor location.
10241 pane.update(cx, |pane, _| pane.disable_history());
10242 let buffer = target.buffer.read(cx);
10243 let range = check_multiline_range(buffer, range);
10244 target_editor.change_selections(
10245 Some(Autoscroll::focused()),
10246 cx,
10247 |s| {
10248 s.select_ranges([range]);
10249 },
10250 );
10251 pane.update(cx, |pane, _| pane.enable_history());
10252 });
10253 });
10254 }
10255 Navigated::Yes
10256 })
10257 })
10258 } else if !definitions.is_empty() {
10259 cx.spawn(|editor, mut cx| async move {
10260 let (title, location_tasks, workspace) = editor
10261 .update(&mut cx, |editor, cx| {
10262 let tab_kind = match kind {
10263 Some(GotoDefinitionKind::Implementation) => "Implementations",
10264 _ => "Definitions",
10265 };
10266 let title = definitions
10267 .iter()
10268 .find_map(|definition| match definition {
10269 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10270 let buffer = origin.buffer.read(cx);
10271 format!(
10272 "{} for {}",
10273 tab_kind,
10274 buffer
10275 .text_for_range(origin.range.clone())
10276 .collect::<String>()
10277 )
10278 }),
10279 HoverLink::InlayHint(_, _) => None,
10280 HoverLink::Url(_) => None,
10281 HoverLink::File(_) => None,
10282 })
10283 .unwrap_or(tab_kind.to_string());
10284 let location_tasks = definitions
10285 .into_iter()
10286 .map(|definition| match definition {
10287 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
10288 HoverLink::InlayHint(lsp_location, server_id) => {
10289 editor.compute_target_location(lsp_location, server_id, cx)
10290 }
10291 HoverLink::Url(_) => Task::ready(Ok(None)),
10292 HoverLink::File(_) => Task::ready(Ok(None)),
10293 })
10294 .collect::<Vec<_>>();
10295 (title, location_tasks, editor.workspace().clone())
10296 })
10297 .context("location tasks preparation")?;
10298
10299 let locations = future::join_all(location_tasks)
10300 .await
10301 .into_iter()
10302 .filter_map(|location| location.transpose())
10303 .collect::<Result<_>>()
10304 .context("location tasks")?;
10305
10306 let Some(workspace) = workspace else {
10307 return Ok(Navigated::No);
10308 };
10309 let opened = workspace
10310 .update(&mut cx, |workspace, cx| {
10311 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10312 })
10313 .ok();
10314
10315 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10316 })
10317 } else {
10318 Task::ready(Ok(Navigated::No))
10319 }
10320 }
10321
10322 fn compute_target_location(
10323 &self,
10324 lsp_location: lsp::Location,
10325 server_id: LanguageServerId,
10326 cx: &mut ViewContext<Self>,
10327 ) -> Task<anyhow::Result<Option<Location>>> {
10328 let Some(project) = self.project.clone() else {
10329 return Task::Ready(Some(Ok(None)));
10330 };
10331
10332 cx.spawn(move |editor, mut cx| async move {
10333 let location_task = editor.update(&mut cx, |_, cx| {
10334 project.update(cx, |project, cx| {
10335 let language_server_name = project
10336 .language_server_statuses(cx)
10337 .find(|(id, _)| server_id == *id)
10338 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10339 language_server_name.map(|language_server_name| {
10340 project.open_local_buffer_via_lsp(
10341 lsp_location.uri.clone(),
10342 server_id,
10343 language_server_name,
10344 cx,
10345 )
10346 })
10347 })
10348 })?;
10349 let location = match location_task {
10350 Some(task) => Some({
10351 let target_buffer_handle = task.await.context("open local buffer")?;
10352 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10353 let target_start = target_buffer
10354 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10355 let target_end = target_buffer
10356 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10357 target_buffer.anchor_after(target_start)
10358 ..target_buffer.anchor_before(target_end)
10359 })?;
10360 Location {
10361 buffer: target_buffer_handle,
10362 range,
10363 }
10364 }),
10365 None => None,
10366 };
10367 Ok(location)
10368 })
10369 }
10370
10371 pub fn find_all_references(
10372 &mut self,
10373 _: &FindAllReferences,
10374 cx: &mut ViewContext<Self>,
10375 ) -> Option<Task<Result<Navigated>>> {
10376 let selection = self.selections.newest::<usize>(cx);
10377 let multi_buffer = self.buffer.read(cx);
10378 let head = selection.head();
10379
10380 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10381 let head_anchor = multi_buffer_snapshot.anchor_at(
10382 head,
10383 if head < selection.tail() {
10384 Bias::Right
10385 } else {
10386 Bias::Left
10387 },
10388 );
10389
10390 match self
10391 .find_all_references_task_sources
10392 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10393 {
10394 Ok(_) => {
10395 log::info!(
10396 "Ignoring repeated FindAllReferences invocation with the position of already running task"
10397 );
10398 return None;
10399 }
10400 Err(i) => {
10401 self.find_all_references_task_sources.insert(i, head_anchor);
10402 }
10403 }
10404
10405 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10406 let workspace = self.workspace()?;
10407 let project = workspace.read(cx).project().clone();
10408 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10409 Some(cx.spawn(|editor, mut cx| async move {
10410 let _cleanup = defer({
10411 let mut cx = cx.clone();
10412 move || {
10413 let _ = editor.update(&mut cx, |editor, _| {
10414 if let Ok(i) =
10415 editor
10416 .find_all_references_task_sources
10417 .binary_search_by(|anchor| {
10418 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10419 })
10420 {
10421 editor.find_all_references_task_sources.remove(i);
10422 }
10423 });
10424 }
10425 });
10426
10427 let locations = references.await?;
10428 if locations.is_empty() {
10429 return anyhow::Ok(Navigated::No);
10430 }
10431
10432 workspace.update(&mut cx, |workspace, cx| {
10433 let title = locations
10434 .first()
10435 .as_ref()
10436 .map(|location| {
10437 let buffer = location.buffer.read(cx);
10438 format!(
10439 "References to `{}`",
10440 buffer
10441 .text_for_range(location.range.clone())
10442 .collect::<String>()
10443 )
10444 })
10445 .unwrap();
10446 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10447 Navigated::Yes
10448 })
10449 }))
10450 }
10451
10452 /// Opens a multibuffer with the given project locations in it
10453 pub fn open_locations_in_multibuffer(
10454 workspace: &mut Workspace,
10455 mut locations: Vec<Location>,
10456 title: String,
10457 split: bool,
10458 cx: &mut ViewContext<Workspace>,
10459 ) {
10460 // If there are multiple definitions, open them in a multibuffer
10461 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10462 let mut locations = locations.into_iter().peekable();
10463 let mut ranges_to_highlight = Vec::new();
10464 let capability = workspace.project().read(cx).capability();
10465
10466 let excerpt_buffer = cx.new_model(|cx| {
10467 let mut multibuffer = MultiBuffer::new(capability);
10468 while let Some(location) = locations.next() {
10469 let buffer = location.buffer.read(cx);
10470 let mut ranges_for_buffer = Vec::new();
10471 let range = location.range.to_offset(buffer);
10472 ranges_for_buffer.push(range.clone());
10473
10474 while let Some(next_location) = locations.peek() {
10475 if next_location.buffer == location.buffer {
10476 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10477 locations.next();
10478 } else {
10479 break;
10480 }
10481 }
10482
10483 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10484 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10485 location.buffer.clone(),
10486 ranges_for_buffer,
10487 DEFAULT_MULTIBUFFER_CONTEXT,
10488 cx,
10489 ))
10490 }
10491
10492 multibuffer.with_title(title)
10493 });
10494
10495 let editor = cx.new_view(|cx| {
10496 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10497 });
10498 editor.update(cx, |editor, cx| {
10499 if let Some(first_range) = ranges_to_highlight.first() {
10500 editor.change_selections(None, cx, |selections| {
10501 selections.clear_disjoint();
10502 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10503 });
10504 }
10505 editor.highlight_background::<Self>(
10506 &ranges_to_highlight,
10507 |theme| theme.editor_highlighted_line_background,
10508 cx,
10509 );
10510 });
10511
10512 let item = Box::new(editor);
10513 let item_id = item.item_id();
10514
10515 if split {
10516 workspace.split_item(SplitDirection::Right, item.clone(), cx);
10517 } else {
10518 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10519 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10520 pane.close_current_preview_item(cx)
10521 } else {
10522 None
10523 }
10524 });
10525 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10526 }
10527 workspace.active_pane().update(cx, |pane, cx| {
10528 pane.set_preview_item_id(Some(item_id), cx);
10529 });
10530 }
10531
10532 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10533 use language::ToOffset as _;
10534
10535 let provider = self.semantics_provider.clone()?;
10536 let selection = self.selections.newest_anchor().clone();
10537 let (cursor_buffer, cursor_buffer_position) = self
10538 .buffer
10539 .read(cx)
10540 .text_anchor_for_position(selection.head(), cx)?;
10541 let (tail_buffer, cursor_buffer_position_end) = self
10542 .buffer
10543 .read(cx)
10544 .text_anchor_for_position(selection.tail(), cx)?;
10545 if tail_buffer != cursor_buffer {
10546 return None;
10547 }
10548
10549 let snapshot = cursor_buffer.read(cx).snapshot();
10550 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10551 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10552 let prepare_rename = provider
10553 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10554 .unwrap_or_else(|| Task::ready(Ok(None)));
10555 drop(snapshot);
10556
10557 Some(cx.spawn(|this, mut cx| async move {
10558 let rename_range = if let Some(range) = prepare_rename.await? {
10559 Some(range)
10560 } else {
10561 this.update(&mut cx, |this, cx| {
10562 let buffer = this.buffer.read(cx).snapshot(cx);
10563 let mut buffer_highlights = this
10564 .document_highlights_for_position(selection.head(), &buffer)
10565 .filter(|highlight| {
10566 highlight.start.excerpt_id == selection.head().excerpt_id
10567 && highlight.end.excerpt_id == selection.head().excerpt_id
10568 });
10569 buffer_highlights
10570 .next()
10571 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10572 })?
10573 };
10574 if let Some(rename_range) = rename_range {
10575 this.update(&mut cx, |this, cx| {
10576 let snapshot = cursor_buffer.read(cx).snapshot();
10577 let rename_buffer_range = rename_range.to_offset(&snapshot);
10578 let cursor_offset_in_rename_range =
10579 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10580 let cursor_offset_in_rename_range_end =
10581 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10582
10583 this.take_rename(false, cx);
10584 let buffer = this.buffer.read(cx).read(cx);
10585 let cursor_offset = selection.head().to_offset(&buffer);
10586 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10587 let rename_end = rename_start + rename_buffer_range.len();
10588 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10589 let mut old_highlight_id = None;
10590 let old_name: Arc<str> = buffer
10591 .chunks(rename_start..rename_end, true)
10592 .map(|chunk| {
10593 if old_highlight_id.is_none() {
10594 old_highlight_id = chunk.syntax_highlight_id;
10595 }
10596 chunk.text
10597 })
10598 .collect::<String>()
10599 .into();
10600
10601 drop(buffer);
10602
10603 // Position the selection in the rename editor so that it matches the current selection.
10604 this.show_local_selections = false;
10605 let rename_editor = cx.new_view(|cx| {
10606 let mut editor = Editor::single_line(cx);
10607 editor.buffer.update(cx, |buffer, cx| {
10608 buffer.edit([(0..0, old_name.clone())], None, cx)
10609 });
10610 let rename_selection_range = match cursor_offset_in_rename_range
10611 .cmp(&cursor_offset_in_rename_range_end)
10612 {
10613 Ordering::Equal => {
10614 editor.select_all(&SelectAll, cx);
10615 return editor;
10616 }
10617 Ordering::Less => {
10618 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10619 }
10620 Ordering::Greater => {
10621 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10622 }
10623 };
10624 if rename_selection_range.end > old_name.len() {
10625 editor.select_all(&SelectAll, cx);
10626 } else {
10627 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10628 s.select_ranges([rename_selection_range]);
10629 });
10630 }
10631 editor
10632 });
10633 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10634 if e == &EditorEvent::Focused {
10635 cx.emit(EditorEvent::FocusedIn)
10636 }
10637 })
10638 .detach();
10639
10640 let write_highlights =
10641 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10642 let read_highlights =
10643 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10644 let ranges = write_highlights
10645 .iter()
10646 .flat_map(|(_, ranges)| ranges.iter())
10647 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10648 .cloned()
10649 .collect();
10650
10651 this.highlight_text::<Rename>(
10652 ranges,
10653 HighlightStyle {
10654 fade_out: Some(0.6),
10655 ..Default::default()
10656 },
10657 cx,
10658 );
10659 let rename_focus_handle = rename_editor.focus_handle(cx);
10660 cx.focus(&rename_focus_handle);
10661 let block_id = this.insert_blocks(
10662 [BlockProperties {
10663 style: BlockStyle::Flex,
10664 placement: BlockPlacement::Below(range.start),
10665 height: 1,
10666 render: Arc::new({
10667 let rename_editor = rename_editor.clone();
10668 move |cx: &mut BlockContext| {
10669 let mut text_style = cx.editor_style.text.clone();
10670 if let Some(highlight_style) = old_highlight_id
10671 .and_then(|h| h.style(&cx.editor_style.syntax))
10672 {
10673 text_style = text_style.highlight(highlight_style);
10674 }
10675 div()
10676 .block_mouse_down()
10677 .pl(cx.anchor_x)
10678 .child(EditorElement::new(
10679 &rename_editor,
10680 EditorStyle {
10681 background: cx.theme().system().transparent,
10682 local_player: cx.editor_style.local_player,
10683 text: text_style,
10684 scrollbar_width: cx.editor_style.scrollbar_width,
10685 syntax: cx.editor_style.syntax.clone(),
10686 status: cx.editor_style.status.clone(),
10687 inlay_hints_style: HighlightStyle {
10688 font_weight: Some(FontWeight::BOLD),
10689 ..make_inlay_hints_style(cx)
10690 },
10691 suggestions_style: HighlightStyle {
10692 color: Some(cx.theme().status().predictive),
10693 ..HighlightStyle::default()
10694 },
10695 ..EditorStyle::default()
10696 },
10697 ))
10698 .into_any_element()
10699 }
10700 }),
10701 priority: 0,
10702 }],
10703 Some(Autoscroll::fit()),
10704 cx,
10705 )[0];
10706 this.pending_rename = Some(RenameState {
10707 range,
10708 old_name,
10709 editor: rename_editor,
10710 block_id,
10711 });
10712 })?;
10713 }
10714
10715 Ok(())
10716 }))
10717 }
10718
10719 pub fn confirm_rename(
10720 &mut self,
10721 _: &ConfirmRename,
10722 cx: &mut ViewContext<Self>,
10723 ) -> Option<Task<Result<()>>> {
10724 let rename = self.take_rename(false, cx)?;
10725 let workspace = self.workspace()?.downgrade();
10726 let (buffer, start) = self
10727 .buffer
10728 .read(cx)
10729 .text_anchor_for_position(rename.range.start, cx)?;
10730 let (end_buffer, _) = self
10731 .buffer
10732 .read(cx)
10733 .text_anchor_for_position(rename.range.end, cx)?;
10734 if buffer != end_buffer {
10735 return None;
10736 }
10737
10738 let old_name = rename.old_name;
10739 let new_name = rename.editor.read(cx).text(cx);
10740
10741 let rename = self.semantics_provider.as_ref()?.perform_rename(
10742 &buffer,
10743 start,
10744 new_name.clone(),
10745 cx,
10746 )?;
10747
10748 Some(cx.spawn(|editor, mut cx| async move {
10749 let project_transaction = rename.await?;
10750 Self::open_project_transaction(
10751 &editor,
10752 workspace,
10753 project_transaction,
10754 format!("Rename: {} → {}", old_name, new_name),
10755 cx.clone(),
10756 )
10757 .await?;
10758
10759 editor.update(&mut cx, |editor, cx| {
10760 editor.refresh_document_highlights(cx);
10761 })?;
10762 Ok(())
10763 }))
10764 }
10765
10766 fn take_rename(
10767 &mut self,
10768 moving_cursor: bool,
10769 cx: &mut ViewContext<Self>,
10770 ) -> Option<RenameState> {
10771 let rename = self.pending_rename.take()?;
10772 if rename.editor.focus_handle(cx).is_focused(cx) {
10773 cx.focus(&self.focus_handle);
10774 }
10775
10776 self.remove_blocks(
10777 [rename.block_id].into_iter().collect(),
10778 Some(Autoscroll::fit()),
10779 cx,
10780 );
10781 self.clear_highlights::<Rename>(cx);
10782 self.show_local_selections = true;
10783
10784 if moving_cursor {
10785 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10786 editor.selections.newest::<usize>(cx).head()
10787 });
10788
10789 // Update the selection to match the position of the selection inside
10790 // the rename editor.
10791 let snapshot = self.buffer.read(cx).read(cx);
10792 let rename_range = rename.range.to_offset(&snapshot);
10793 let cursor_in_editor = snapshot
10794 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10795 .min(rename_range.end);
10796 drop(snapshot);
10797
10798 self.change_selections(None, cx, |s| {
10799 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10800 });
10801 } else {
10802 self.refresh_document_highlights(cx);
10803 }
10804
10805 Some(rename)
10806 }
10807
10808 pub fn pending_rename(&self) -> Option<&RenameState> {
10809 self.pending_rename.as_ref()
10810 }
10811
10812 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10813 let project = match &self.project {
10814 Some(project) => project.clone(),
10815 None => return None,
10816 };
10817
10818 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10819 }
10820
10821 fn format_selections(
10822 &mut self,
10823 _: &FormatSelections,
10824 cx: &mut ViewContext<Self>,
10825 ) -> Option<Task<Result<()>>> {
10826 let project = match &self.project {
10827 Some(project) => project.clone(),
10828 None => return None,
10829 };
10830
10831 let selections = self
10832 .selections
10833 .all_adjusted(cx)
10834 .into_iter()
10835 .filter(|s| !s.is_empty())
10836 .collect_vec();
10837
10838 Some(self.perform_format(
10839 project,
10840 FormatTrigger::Manual,
10841 FormatTarget::Ranges(selections),
10842 cx,
10843 ))
10844 }
10845
10846 fn perform_format(
10847 &mut self,
10848 project: Model<Project>,
10849 trigger: FormatTrigger,
10850 target: FormatTarget,
10851 cx: &mut ViewContext<Self>,
10852 ) -> Task<Result<()>> {
10853 let buffer = self.buffer().clone();
10854 let mut buffers = buffer.read(cx).all_buffers();
10855 if trigger == FormatTrigger::Save {
10856 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10857 }
10858
10859 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10860 let format = project.update(cx, |project, cx| {
10861 project.format(buffers, true, trigger, target, cx)
10862 });
10863
10864 cx.spawn(|_, mut cx| async move {
10865 let transaction = futures::select_biased! {
10866 () = timeout => {
10867 log::warn!("timed out waiting for formatting");
10868 None
10869 }
10870 transaction = format.log_err().fuse() => transaction,
10871 };
10872
10873 buffer
10874 .update(&mut cx, |buffer, cx| {
10875 if let Some(transaction) = transaction {
10876 if !buffer.is_singleton() {
10877 buffer.push_transaction(&transaction.0, cx);
10878 }
10879 }
10880
10881 cx.notify();
10882 })
10883 .ok();
10884
10885 Ok(())
10886 })
10887 }
10888
10889 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10890 if let Some(project) = self.project.clone() {
10891 self.buffer.update(cx, |multi_buffer, cx| {
10892 project.update(cx, |project, cx| {
10893 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10894 });
10895 })
10896 }
10897 }
10898
10899 fn cancel_language_server_work(
10900 &mut self,
10901 _: &actions::CancelLanguageServerWork,
10902 cx: &mut ViewContext<Self>,
10903 ) {
10904 if let Some(project) = self.project.clone() {
10905 self.buffer.update(cx, |multi_buffer, cx| {
10906 project.update(cx, |project, cx| {
10907 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10908 });
10909 })
10910 }
10911 }
10912
10913 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10914 cx.show_character_palette();
10915 }
10916
10917 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10918 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10919 let buffer = self.buffer.read(cx).snapshot(cx);
10920 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10921 let is_valid = buffer
10922 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10923 .any(|entry| {
10924 entry.diagnostic.is_primary
10925 && !entry.range.is_empty()
10926 && entry.range.start == primary_range_start
10927 && entry.diagnostic.message == active_diagnostics.primary_message
10928 });
10929
10930 if is_valid != active_diagnostics.is_valid {
10931 active_diagnostics.is_valid = is_valid;
10932 let mut new_styles = HashMap::default();
10933 for (block_id, diagnostic) in &active_diagnostics.blocks {
10934 new_styles.insert(
10935 *block_id,
10936 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10937 );
10938 }
10939 self.display_map.update(cx, |display_map, _cx| {
10940 display_map.replace_blocks(new_styles)
10941 });
10942 }
10943 }
10944 }
10945
10946 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10947 self.dismiss_diagnostics(cx);
10948 let snapshot = self.snapshot(cx);
10949 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10950 let buffer = self.buffer.read(cx).snapshot(cx);
10951
10952 let mut primary_range = None;
10953 let mut primary_message = None;
10954 let mut group_end = Point::zero();
10955 let diagnostic_group = buffer
10956 .diagnostic_group::<MultiBufferPoint>(group_id)
10957 .filter_map(|entry| {
10958 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10959 && (entry.range.start.row == entry.range.end.row
10960 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10961 {
10962 return None;
10963 }
10964 if entry.range.end > group_end {
10965 group_end = entry.range.end;
10966 }
10967 if entry.diagnostic.is_primary {
10968 primary_range = Some(entry.range.clone());
10969 primary_message = Some(entry.diagnostic.message.clone());
10970 }
10971 Some(entry)
10972 })
10973 .collect::<Vec<_>>();
10974 let primary_range = primary_range?;
10975 let primary_message = primary_message?;
10976 let primary_range =
10977 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10978
10979 let blocks = display_map
10980 .insert_blocks(
10981 diagnostic_group.iter().map(|entry| {
10982 let diagnostic = entry.diagnostic.clone();
10983 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10984 BlockProperties {
10985 style: BlockStyle::Fixed,
10986 placement: BlockPlacement::Below(
10987 buffer.anchor_after(entry.range.start),
10988 ),
10989 height: message_height,
10990 render: diagnostic_block_renderer(diagnostic, None, true, true),
10991 priority: 0,
10992 }
10993 }),
10994 cx,
10995 )
10996 .into_iter()
10997 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10998 .collect();
10999
11000 Some(ActiveDiagnosticGroup {
11001 primary_range,
11002 primary_message,
11003 group_id,
11004 blocks,
11005 is_valid: true,
11006 })
11007 });
11008 self.active_diagnostics.is_some()
11009 }
11010
11011 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
11012 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11013 self.display_map.update(cx, |display_map, cx| {
11014 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11015 });
11016 cx.notify();
11017 }
11018 }
11019
11020 pub fn set_selections_from_remote(
11021 &mut self,
11022 selections: Vec<Selection<Anchor>>,
11023 pending_selection: Option<Selection<Anchor>>,
11024 cx: &mut ViewContext<Self>,
11025 ) {
11026 let old_cursor_position = self.selections.newest_anchor().head();
11027 self.selections.change_with(cx, |s| {
11028 s.select_anchors(selections);
11029 if let Some(pending_selection) = pending_selection {
11030 s.set_pending(pending_selection, SelectMode::Character);
11031 } else {
11032 s.clear_pending();
11033 }
11034 });
11035 self.selections_did_change(false, &old_cursor_position, true, cx);
11036 }
11037
11038 fn push_to_selection_history(&mut self) {
11039 self.selection_history.push(SelectionHistoryEntry {
11040 selections: self.selections.disjoint_anchors(),
11041 select_next_state: self.select_next_state.clone(),
11042 select_prev_state: self.select_prev_state.clone(),
11043 add_selections_state: self.add_selections_state.clone(),
11044 });
11045 }
11046
11047 pub fn transact(
11048 &mut self,
11049 cx: &mut ViewContext<Self>,
11050 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
11051 ) -> Option<TransactionId> {
11052 self.start_transaction_at(Instant::now(), cx);
11053 update(self, cx);
11054 self.end_transaction_at(Instant::now(), cx)
11055 }
11056
11057 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
11058 self.end_selection(cx);
11059 if let Some(tx_id) = self
11060 .buffer
11061 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11062 {
11063 self.selection_history
11064 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11065 cx.emit(EditorEvent::TransactionBegun {
11066 transaction_id: tx_id,
11067 })
11068 }
11069 }
11070
11071 fn end_transaction_at(
11072 &mut self,
11073 now: Instant,
11074 cx: &mut ViewContext<Self>,
11075 ) -> Option<TransactionId> {
11076 if let Some(transaction_id) = self
11077 .buffer
11078 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11079 {
11080 if let Some((_, end_selections)) =
11081 self.selection_history.transaction_mut(transaction_id)
11082 {
11083 *end_selections = Some(self.selections.disjoint_anchors());
11084 } else {
11085 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11086 }
11087
11088 cx.emit(EditorEvent::Edited { transaction_id });
11089 Some(transaction_id)
11090 } else {
11091 None
11092 }
11093 }
11094
11095 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
11096 let selection = self.selections.newest::<Point>(cx);
11097
11098 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11099 let range = if selection.is_empty() {
11100 let point = selection.head().to_display_point(&display_map);
11101 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11102 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11103 .to_point(&display_map);
11104 start..end
11105 } else {
11106 selection.range()
11107 };
11108 if display_map.folds_in_range(range).next().is_some() {
11109 self.unfold_lines(&Default::default(), cx)
11110 } else {
11111 self.fold(&Default::default(), cx)
11112 }
11113 }
11114
11115 pub fn toggle_fold_recursive(
11116 &mut self,
11117 _: &actions::ToggleFoldRecursive,
11118 cx: &mut ViewContext<Self>,
11119 ) {
11120 let selection = self.selections.newest::<Point>(cx);
11121
11122 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11123 let range = if selection.is_empty() {
11124 let point = selection.head().to_display_point(&display_map);
11125 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11126 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11127 .to_point(&display_map);
11128 start..end
11129 } else {
11130 selection.range()
11131 };
11132 if display_map.folds_in_range(range).next().is_some() {
11133 self.unfold_recursive(&Default::default(), cx)
11134 } else {
11135 self.fold_recursive(&Default::default(), cx)
11136 }
11137 }
11138
11139 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
11140 let mut to_fold = Vec::new();
11141 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11142 let selections = self.selections.all_adjusted(cx);
11143
11144 for selection in selections {
11145 let range = selection.range().sorted();
11146 let buffer_start_row = range.start.row;
11147
11148 if range.start.row != range.end.row {
11149 let mut found = false;
11150 let mut row = range.start.row;
11151 while row <= range.end.row {
11152 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11153 found = true;
11154 row = crease.range().end.row + 1;
11155 to_fold.push(crease);
11156 } else {
11157 row += 1
11158 }
11159 }
11160 if found {
11161 continue;
11162 }
11163 }
11164
11165 for row in (0..=range.start.row).rev() {
11166 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11167 if crease.range().end.row >= buffer_start_row {
11168 to_fold.push(crease);
11169 if row <= range.start.row {
11170 break;
11171 }
11172 }
11173 }
11174 }
11175 }
11176
11177 self.fold_creases(to_fold, true, cx);
11178 }
11179
11180 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
11181 if !self.buffer.read(cx).is_singleton() {
11182 return;
11183 }
11184
11185 let fold_at_level = fold_at.level;
11186 let snapshot = self.buffer.read(cx).snapshot(cx);
11187 let mut to_fold = Vec::new();
11188 let mut stack = vec![(0, snapshot.max_row().0, 1)];
11189
11190 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11191 while start_row < end_row {
11192 match self
11193 .snapshot(cx)
11194 .crease_for_buffer_row(MultiBufferRow(start_row))
11195 {
11196 Some(crease) => {
11197 let nested_start_row = crease.range().start.row + 1;
11198 let nested_end_row = crease.range().end.row;
11199
11200 if current_level < fold_at_level {
11201 stack.push((nested_start_row, nested_end_row, current_level + 1));
11202 } else if current_level == fold_at_level {
11203 to_fold.push(crease);
11204 }
11205
11206 start_row = nested_end_row + 1;
11207 }
11208 None => start_row += 1,
11209 }
11210 }
11211 }
11212
11213 self.fold_creases(to_fold, true, cx);
11214 }
11215
11216 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
11217 if !self.buffer.read(cx).is_singleton() {
11218 return;
11219 }
11220
11221 let mut fold_ranges = Vec::new();
11222 let snapshot = self.buffer.read(cx).snapshot(cx);
11223
11224 for row in 0..snapshot.max_row().0 {
11225 if let Some(foldable_range) =
11226 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
11227 {
11228 fold_ranges.push(foldable_range);
11229 }
11230 }
11231
11232 self.fold_creases(fold_ranges, true, cx);
11233 }
11234
11235 pub fn fold_function_bodies(
11236 &mut self,
11237 _: &actions::FoldFunctionBodies,
11238 cx: &mut ViewContext<Self>,
11239 ) {
11240 let snapshot = self.buffer.read(cx).snapshot(cx);
11241 let Some((_, _, buffer)) = snapshot.as_singleton() else {
11242 return;
11243 };
11244 let creases = buffer
11245 .function_body_fold_ranges(0..buffer.len())
11246 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11247 .collect();
11248
11249 self.fold_creases(creases, true, cx);
11250 }
11251
11252 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
11253 let mut to_fold = Vec::new();
11254 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11255 let selections = self.selections.all_adjusted(cx);
11256
11257 for selection in selections {
11258 let range = selection.range().sorted();
11259 let buffer_start_row = range.start.row;
11260
11261 if range.start.row != range.end.row {
11262 let mut found = false;
11263 for row in range.start.row..=range.end.row {
11264 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11265 found = true;
11266 to_fold.push(crease);
11267 }
11268 }
11269 if found {
11270 continue;
11271 }
11272 }
11273
11274 for row in (0..=range.start.row).rev() {
11275 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11276 if crease.range().end.row >= buffer_start_row {
11277 to_fold.push(crease);
11278 } else {
11279 break;
11280 }
11281 }
11282 }
11283 }
11284
11285 self.fold_creases(to_fold, true, cx);
11286 }
11287
11288 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
11289 let buffer_row = fold_at.buffer_row;
11290 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11291
11292 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11293 let autoscroll = self
11294 .selections
11295 .all::<Point>(cx)
11296 .iter()
11297 .any(|selection| crease.range().overlaps(&selection.range()));
11298
11299 self.fold_creases(vec![crease], autoscroll, cx);
11300 }
11301 }
11302
11303 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
11304 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11305 let buffer = &display_map.buffer_snapshot;
11306 let selections = self.selections.all::<Point>(cx);
11307 let ranges = selections
11308 .iter()
11309 .map(|s| {
11310 let range = s.display_range(&display_map).sorted();
11311 let mut start = range.start.to_point(&display_map);
11312 let mut end = range.end.to_point(&display_map);
11313 start.column = 0;
11314 end.column = buffer.line_len(MultiBufferRow(end.row));
11315 start..end
11316 })
11317 .collect::<Vec<_>>();
11318
11319 self.unfold_ranges(&ranges, true, true, cx);
11320 }
11321
11322 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11323 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11324 let selections = self.selections.all::<Point>(cx);
11325 let ranges = selections
11326 .iter()
11327 .map(|s| {
11328 let mut range = s.display_range(&display_map).sorted();
11329 *range.start.column_mut() = 0;
11330 *range.end.column_mut() = display_map.line_len(range.end.row());
11331 let start = range.start.to_point(&display_map);
11332 let end = range.end.to_point(&display_map);
11333 start..end
11334 })
11335 .collect::<Vec<_>>();
11336
11337 self.unfold_ranges(&ranges, true, true, cx);
11338 }
11339
11340 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11341 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11342
11343 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11344 ..Point::new(
11345 unfold_at.buffer_row.0,
11346 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11347 );
11348
11349 let autoscroll = self
11350 .selections
11351 .all::<Point>(cx)
11352 .iter()
11353 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11354
11355 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11356 }
11357
11358 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11359 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11360 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11361 }
11362
11363 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11364 let selections = self.selections.all::<Point>(cx);
11365 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11366 let line_mode = self.selections.line_mode;
11367 let ranges = selections
11368 .into_iter()
11369 .map(|s| {
11370 if line_mode {
11371 let start = Point::new(s.start.row, 0);
11372 let end = Point::new(
11373 s.end.row,
11374 display_map
11375 .buffer_snapshot
11376 .line_len(MultiBufferRow(s.end.row)),
11377 );
11378 Crease::simple(start..end, display_map.fold_placeholder.clone())
11379 } else {
11380 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11381 }
11382 })
11383 .collect::<Vec<_>>();
11384 self.fold_creases(ranges, true, cx);
11385 }
11386
11387 pub fn fold_creases<T: ToOffset + Clone>(
11388 &mut self,
11389 creases: Vec<Crease<T>>,
11390 auto_scroll: bool,
11391 cx: &mut ViewContext<Self>,
11392 ) {
11393 if creases.is_empty() {
11394 return;
11395 }
11396
11397 let mut buffers_affected = HashSet::default();
11398 let multi_buffer = self.buffer().read(cx);
11399 for crease in &creases {
11400 if let Some((_, buffer, _)) =
11401 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11402 {
11403 buffers_affected.insert(buffer.read(cx).remote_id());
11404 };
11405 }
11406
11407 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11408
11409 if auto_scroll {
11410 self.request_autoscroll(Autoscroll::fit(), cx);
11411 }
11412
11413 for buffer_id in buffers_affected {
11414 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11415 }
11416
11417 cx.notify();
11418
11419 if let Some(active_diagnostics) = self.active_diagnostics.take() {
11420 // Clear diagnostics block when folding a range that contains it.
11421 let snapshot = self.snapshot(cx);
11422 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11423 drop(snapshot);
11424 self.active_diagnostics = Some(active_diagnostics);
11425 self.dismiss_diagnostics(cx);
11426 } else {
11427 self.active_diagnostics = Some(active_diagnostics);
11428 }
11429 }
11430
11431 self.scrollbar_marker_state.dirty = true;
11432 }
11433
11434 /// Removes any folds whose ranges intersect any of the given ranges.
11435 pub fn unfold_ranges<T: ToOffset + Clone>(
11436 &mut self,
11437 ranges: &[Range<T>],
11438 inclusive: bool,
11439 auto_scroll: bool,
11440 cx: &mut ViewContext<Self>,
11441 ) {
11442 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11443 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11444 });
11445 }
11446
11447 /// Removes any folds with the given ranges.
11448 pub fn remove_folds_with_type<T: ToOffset + Clone>(
11449 &mut self,
11450 ranges: &[Range<T>],
11451 type_id: TypeId,
11452 auto_scroll: bool,
11453 cx: &mut ViewContext<Self>,
11454 ) {
11455 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11456 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11457 });
11458 }
11459
11460 fn remove_folds_with<T: ToOffset + Clone>(
11461 &mut self,
11462 ranges: &[Range<T>],
11463 auto_scroll: bool,
11464 cx: &mut ViewContext<Self>,
11465 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11466 ) {
11467 if ranges.is_empty() {
11468 return;
11469 }
11470
11471 let mut buffers_affected = HashSet::default();
11472 let multi_buffer = self.buffer().read(cx);
11473 for range in ranges {
11474 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11475 buffers_affected.insert(buffer.read(cx).remote_id());
11476 };
11477 }
11478
11479 self.display_map.update(cx, update);
11480
11481 if auto_scroll {
11482 self.request_autoscroll(Autoscroll::fit(), cx);
11483 }
11484
11485 for buffer_id in buffers_affected {
11486 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11487 }
11488
11489 cx.notify();
11490 self.scrollbar_marker_state.dirty = true;
11491 self.active_indent_guides_state.dirty = true;
11492 }
11493
11494 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11495 self.display_map.read(cx).fold_placeholder.clone()
11496 }
11497
11498 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11499 if hovered != self.gutter_hovered {
11500 self.gutter_hovered = hovered;
11501 cx.notify();
11502 }
11503 }
11504
11505 pub fn insert_blocks(
11506 &mut self,
11507 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11508 autoscroll: Option<Autoscroll>,
11509 cx: &mut ViewContext<Self>,
11510 ) -> Vec<CustomBlockId> {
11511 let blocks = self
11512 .display_map
11513 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11514 if let Some(autoscroll) = autoscroll {
11515 self.request_autoscroll(autoscroll, cx);
11516 }
11517 cx.notify();
11518 blocks
11519 }
11520
11521 pub fn resize_blocks(
11522 &mut self,
11523 heights: HashMap<CustomBlockId, u32>,
11524 autoscroll: Option<Autoscroll>,
11525 cx: &mut ViewContext<Self>,
11526 ) {
11527 self.display_map
11528 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11529 if let Some(autoscroll) = autoscroll {
11530 self.request_autoscroll(autoscroll, cx);
11531 }
11532 cx.notify();
11533 }
11534
11535 pub fn replace_blocks(
11536 &mut self,
11537 renderers: HashMap<CustomBlockId, RenderBlock>,
11538 autoscroll: Option<Autoscroll>,
11539 cx: &mut ViewContext<Self>,
11540 ) {
11541 self.display_map
11542 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11543 if let Some(autoscroll) = autoscroll {
11544 self.request_autoscroll(autoscroll, cx);
11545 }
11546 cx.notify();
11547 }
11548
11549 pub fn remove_blocks(
11550 &mut self,
11551 block_ids: HashSet<CustomBlockId>,
11552 autoscroll: Option<Autoscroll>,
11553 cx: &mut ViewContext<Self>,
11554 ) {
11555 self.display_map.update(cx, |display_map, cx| {
11556 display_map.remove_blocks(block_ids, cx)
11557 });
11558 if let Some(autoscroll) = autoscroll {
11559 self.request_autoscroll(autoscroll, cx);
11560 }
11561 cx.notify();
11562 }
11563
11564 pub fn row_for_block(
11565 &self,
11566 block_id: CustomBlockId,
11567 cx: &mut ViewContext<Self>,
11568 ) -> Option<DisplayRow> {
11569 self.display_map
11570 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11571 }
11572
11573 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11574 self.focused_block = Some(focused_block);
11575 }
11576
11577 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11578 self.focused_block.take()
11579 }
11580
11581 pub fn insert_creases(
11582 &mut self,
11583 creases: impl IntoIterator<Item = Crease<Anchor>>,
11584 cx: &mut ViewContext<Self>,
11585 ) -> Vec<CreaseId> {
11586 self.display_map
11587 .update(cx, |map, cx| map.insert_creases(creases, cx))
11588 }
11589
11590 pub fn remove_creases(
11591 &mut self,
11592 ids: impl IntoIterator<Item = CreaseId>,
11593 cx: &mut ViewContext<Self>,
11594 ) {
11595 self.display_map
11596 .update(cx, |map, cx| map.remove_creases(ids, cx));
11597 }
11598
11599 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11600 self.display_map
11601 .update(cx, |map, cx| map.snapshot(cx))
11602 .longest_row()
11603 }
11604
11605 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11606 self.display_map
11607 .update(cx, |map, cx| map.snapshot(cx))
11608 .max_point()
11609 }
11610
11611 pub fn text(&self, cx: &AppContext) -> String {
11612 self.buffer.read(cx).read(cx).text()
11613 }
11614
11615 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11616 let text = self.text(cx);
11617 let text = text.trim();
11618
11619 if text.is_empty() {
11620 return None;
11621 }
11622
11623 Some(text.to_string())
11624 }
11625
11626 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11627 self.transact(cx, |this, cx| {
11628 this.buffer
11629 .read(cx)
11630 .as_singleton()
11631 .expect("you can only call set_text on editors for singleton buffers")
11632 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11633 });
11634 }
11635
11636 pub fn display_text(&self, cx: &mut AppContext) -> String {
11637 self.display_map
11638 .update(cx, |map, cx| map.snapshot(cx))
11639 .text()
11640 }
11641
11642 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11643 let mut wrap_guides = smallvec::smallvec![];
11644
11645 if self.show_wrap_guides == Some(false) {
11646 return wrap_guides;
11647 }
11648
11649 let settings = self.buffer.read(cx).settings_at(0, cx);
11650 if settings.show_wrap_guides {
11651 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11652 wrap_guides.push((soft_wrap as usize, true));
11653 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11654 wrap_guides.push((soft_wrap as usize, true));
11655 }
11656 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11657 }
11658
11659 wrap_guides
11660 }
11661
11662 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11663 let settings = self.buffer.read(cx).settings_at(0, cx);
11664 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11665 match mode {
11666 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11667 SoftWrap::None
11668 }
11669 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11670 language_settings::SoftWrap::PreferredLineLength => {
11671 SoftWrap::Column(settings.preferred_line_length)
11672 }
11673 language_settings::SoftWrap::Bounded => {
11674 SoftWrap::Bounded(settings.preferred_line_length)
11675 }
11676 }
11677 }
11678
11679 pub fn set_soft_wrap_mode(
11680 &mut self,
11681 mode: language_settings::SoftWrap,
11682 cx: &mut ViewContext<Self>,
11683 ) {
11684 self.soft_wrap_mode_override = Some(mode);
11685 cx.notify();
11686 }
11687
11688 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11689 self.text_style_refinement = Some(style);
11690 }
11691
11692 /// called by the Element so we know what style we were most recently rendered with.
11693 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11694 let rem_size = cx.rem_size();
11695 self.display_map.update(cx, |map, cx| {
11696 map.set_font(
11697 style.text.font(),
11698 style.text.font_size.to_pixels(rem_size),
11699 cx,
11700 )
11701 });
11702 self.style = Some(style);
11703 }
11704
11705 pub fn style(&self) -> Option<&EditorStyle> {
11706 self.style.as_ref()
11707 }
11708
11709 // Called by the element. This method is not designed to be called outside of the editor
11710 // element's layout code because it does not notify when rewrapping is computed synchronously.
11711 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11712 self.display_map
11713 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11714 }
11715
11716 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11717 if self.soft_wrap_mode_override.is_some() {
11718 self.soft_wrap_mode_override.take();
11719 } else {
11720 let soft_wrap = match self.soft_wrap_mode(cx) {
11721 SoftWrap::GitDiff => return,
11722 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11723 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11724 language_settings::SoftWrap::None
11725 }
11726 };
11727 self.soft_wrap_mode_override = Some(soft_wrap);
11728 }
11729 cx.notify();
11730 }
11731
11732 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11733 let Some(workspace) = self.workspace() else {
11734 return;
11735 };
11736 let fs = workspace.read(cx).app_state().fs.clone();
11737 let current_show = TabBarSettings::get_global(cx).show;
11738 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11739 setting.show = Some(!current_show);
11740 });
11741 }
11742
11743 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11744 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11745 self.buffer
11746 .read(cx)
11747 .settings_at(0, cx)
11748 .indent_guides
11749 .enabled
11750 });
11751 self.show_indent_guides = Some(!currently_enabled);
11752 cx.notify();
11753 }
11754
11755 fn should_show_indent_guides(&self) -> Option<bool> {
11756 self.show_indent_guides
11757 }
11758
11759 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11760 let mut editor_settings = EditorSettings::get_global(cx).clone();
11761 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11762 EditorSettings::override_global(editor_settings, cx);
11763 }
11764
11765 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11766 self.use_relative_line_numbers
11767 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11768 }
11769
11770 pub fn toggle_relative_line_numbers(
11771 &mut self,
11772 _: &ToggleRelativeLineNumbers,
11773 cx: &mut ViewContext<Self>,
11774 ) {
11775 let is_relative = self.should_use_relative_line_numbers(cx);
11776 self.set_relative_line_number(Some(!is_relative), cx)
11777 }
11778
11779 pub fn set_relative_line_number(
11780 &mut self,
11781 is_relative: Option<bool>,
11782 cx: &mut ViewContext<Self>,
11783 ) {
11784 self.use_relative_line_numbers = is_relative;
11785 cx.notify();
11786 }
11787
11788 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11789 self.show_gutter = show_gutter;
11790 cx.notify();
11791 }
11792
11793 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11794 self.show_line_numbers = Some(show_line_numbers);
11795 cx.notify();
11796 }
11797
11798 pub fn set_show_git_diff_gutter(
11799 &mut self,
11800 show_git_diff_gutter: bool,
11801 cx: &mut ViewContext<Self>,
11802 ) {
11803 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11804 cx.notify();
11805 }
11806
11807 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11808 self.show_code_actions = Some(show_code_actions);
11809 cx.notify();
11810 }
11811
11812 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11813 self.show_runnables = Some(show_runnables);
11814 cx.notify();
11815 }
11816
11817 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11818 if self.display_map.read(cx).masked != masked {
11819 self.display_map.update(cx, |map, _| map.masked = masked);
11820 }
11821 cx.notify()
11822 }
11823
11824 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11825 self.show_wrap_guides = Some(show_wrap_guides);
11826 cx.notify();
11827 }
11828
11829 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11830 self.show_indent_guides = Some(show_indent_guides);
11831 cx.notify();
11832 }
11833
11834 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11835 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11836 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11837 if let Some(dir) = file.abs_path(cx).parent() {
11838 return Some(dir.to_owned());
11839 }
11840 }
11841
11842 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11843 return Some(project_path.path.to_path_buf());
11844 }
11845 }
11846
11847 None
11848 }
11849
11850 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11851 self.active_excerpt(cx)?
11852 .1
11853 .read(cx)
11854 .file()
11855 .and_then(|f| f.as_local())
11856 }
11857
11858 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11859 if let Some(target) = self.target_file(cx) {
11860 cx.reveal_path(&target.abs_path(cx));
11861 }
11862 }
11863
11864 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11865 if let Some(file) = self.target_file(cx) {
11866 if let Some(path) = file.abs_path(cx).to_str() {
11867 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11868 }
11869 }
11870 }
11871
11872 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11873 if let Some(file) = self.target_file(cx) {
11874 if let Some(path) = file.path().to_str() {
11875 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11876 }
11877 }
11878 }
11879
11880 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11881 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11882
11883 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11884 self.start_git_blame(true, cx);
11885 }
11886
11887 cx.notify();
11888 }
11889
11890 pub fn toggle_git_blame_inline(
11891 &mut self,
11892 _: &ToggleGitBlameInline,
11893 cx: &mut ViewContext<Self>,
11894 ) {
11895 self.toggle_git_blame_inline_internal(true, cx);
11896 cx.notify();
11897 }
11898
11899 pub fn git_blame_inline_enabled(&self) -> bool {
11900 self.git_blame_inline_enabled
11901 }
11902
11903 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11904 self.show_selection_menu = self
11905 .show_selection_menu
11906 .map(|show_selections_menu| !show_selections_menu)
11907 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11908
11909 cx.notify();
11910 }
11911
11912 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11913 self.show_selection_menu
11914 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11915 }
11916
11917 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11918 if let Some(project) = self.project.as_ref() {
11919 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11920 return;
11921 };
11922
11923 if buffer.read(cx).file().is_none() {
11924 return;
11925 }
11926
11927 let focused = self.focus_handle(cx).contains_focused(cx);
11928
11929 let project = project.clone();
11930 let blame =
11931 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11932 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11933 self.blame = Some(blame);
11934 }
11935 }
11936
11937 fn toggle_git_blame_inline_internal(
11938 &mut self,
11939 user_triggered: bool,
11940 cx: &mut ViewContext<Self>,
11941 ) {
11942 if self.git_blame_inline_enabled {
11943 self.git_blame_inline_enabled = false;
11944 self.show_git_blame_inline = false;
11945 self.show_git_blame_inline_delay_task.take();
11946 } else {
11947 self.git_blame_inline_enabled = true;
11948 self.start_git_blame_inline(user_triggered, cx);
11949 }
11950
11951 cx.notify();
11952 }
11953
11954 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11955 self.start_git_blame(user_triggered, cx);
11956
11957 if ProjectSettings::get_global(cx)
11958 .git
11959 .inline_blame_delay()
11960 .is_some()
11961 {
11962 self.start_inline_blame_timer(cx);
11963 } else {
11964 self.show_git_blame_inline = true
11965 }
11966 }
11967
11968 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11969 self.blame.as_ref()
11970 }
11971
11972 pub fn show_git_blame_gutter(&self) -> bool {
11973 self.show_git_blame_gutter
11974 }
11975
11976 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11977 self.show_git_blame_gutter && self.has_blame_entries(cx)
11978 }
11979
11980 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11981 self.show_git_blame_inline
11982 && self.focus_handle.is_focused(cx)
11983 && !self.newest_selection_head_on_empty_line(cx)
11984 && self.has_blame_entries(cx)
11985 }
11986
11987 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11988 self.blame()
11989 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11990 }
11991
11992 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11993 let cursor_anchor = self.selections.newest_anchor().head();
11994
11995 let snapshot = self.buffer.read(cx).snapshot(cx);
11996 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11997
11998 snapshot.line_len(buffer_row) == 0
11999 }
12000
12001 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
12002 let buffer_and_selection = maybe!({
12003 let selection = self.selections.newest::<Point>(cx);
12004 let selection_range = selection.range();
12005
12006 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12007 (buffer, selection_range.start.row..selection_range.end.row)
12008 } else {
12009 let buffer_ranges = self
12010 .buffer()
12011 .read(cx)
12012 .range_to_buffer_ranges(selection_range, cx);
12013
12014 let (buffer, range, _) = if selection.reversed {
12015 buffer_ranges.first()
12016 } else {
12017 buffer_ranges.last()
12018 }?;
12019
12020 let snapshot = buffer.read(cx).snapshot();
12021 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
12022 ..text::ToPoint::to_point(&range.end, &snapshot).row;
12023 (buffer.clone(), selection)
12024 };
12025
12026 Some((buffer, selection))
12027 });
12028
12029 let Some((buffer, selection)) = buffer_and_selection else {
12030 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12031 };
12032
12033 let Some(project) = self.project.as_ref() else {
12034 return Task::ready(Err(anyhow!("editor does not have project")));
12035 };
12036
12037 project.update(cx, |project, cx| {
12038 project.get_permalink_to_line(&buffer, selection, cx)
12039 })
12040 }
12041
12042 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
12043 let permalink_task = self.get_permalink_to_line(cx);
12044 let workspace = self.workspace();
12045
12046 cx.spawn(|_, mut cx| async move {
12047 match permalink_task.await {
12048 Ok(permalink) => {
12049 cx.update(|cx| {
12050 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12051 })
12052 .ok();
12053 }
12054 Err(err) => {
12055 let message = format!("Failed to copy permalink: {err}");
12056
12057 Err::<(), anyhow::Error>(err).log_err();
12058
12059 if let Some(workspace) = workspace {
12060 workspace
12061 .update(&mut cx, |workspace, cx| {
12062 struct CopyPermalinkToLine;
12063
12064 workspace.show_toast(
12065 Toast::new(
12066 NotificationId::unique::<CopyPermalinkToLine>(),
12067 message,
12068 ),
12069 cx,
12070 )
12071 })
12072 .ok();
12073 }
12074 }
12075 }
12076 })
12077 .detach();
12078 }
12079
12080 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
12081 let selection = self.selections.newest::<Point>(cx).start.row + 1;
12082 if let Some(file) = self.target_file(cx) {
12083 if let Some(path) = file.path().to_str() {
12084 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
12085 }
12086 }
12087 }
12088
12089 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
12090 let permalink_task = self.get_permalink_to_line(cx);
12091 let workspace = self.workspace();
12092
12093 cx.spawn(|_, mut cx| async move {
12094 match permalink_task.await {
12095 Ok(permalink) => {
12096 cx.update(|cx| {
12097 cx.open_url(permalink.as_ref());
12098 })
12099 .ok();
12100 }
12101 Err(err) => {
12102 let message = format!("Failed to open permalink: {err}");
12103
12104 Err::<(), anyhow::Error>(err).log_err();
12105
12106 if let Some(workspace) = workspace {
12107 workspace
12108 .update(&mut cx, |workspace, cx| {
12109 struct OpenPermalinkToLine;
12110
12111 workspace.show_toast(
12112 Toast::new(
12113 NotificationId::unique::<OpenPermalinkToLine>(),
12114 message,
12115 ),
12116 cx,
12117 )
12118 })
12119 .ok();
12120 }
12121 }
12122 }
12123 })
12124 .detach();
12125 }
12126
12127 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
12128 self.insert_uuid(UuidVersion::V4, cx);
12129 }
12130
12131 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
12132 self.insert_uuid(UuidVersion::V7, cx);
12133 }
12134
12135 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
12136 self.transact(cx, |this, cx| {
12137 let edits = this
12138 .selections
12139 .all::<Point>(cx)
12140 .into_iter()
12141 .map(|selection| {
12142 let uuid = match version {
12143 UuidVersion::V4 => uuid::Uuid::new_v4(),
12144 UuidVersion::V7 => uuid::Uuid::now_v7(),
12145 };
12146
12147 (selection.range(), uuid.to_string())
12148 });
12149 this.edit(edits, cx);
12150 this.refresh_inline_completion(true, false, cx);
12151 });
12152 }
12153
12154 /// Adds a row highlight for the given range. If a row has multiple highlights, the
12155 /// last highlight added will be used.
12156 ///
12157 /// If the range ends at the beginning of a line, then that line will not be highlighted.
12158 pub fn highlight_rows<T: 'static>(
12159 &mut self,
12160 range: Range<Anchor>,
12161 color: Hsla,
12162 should_autoscroll: bool,
12163 cx: &mut ViewContext<Self>,
12164 ) {
12165 let snapshot = self.buffer().read(cx).snapshot(cx);
12166 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12167 let ix = row_highlights.binary_search_by(|highlight| {
12168 Ordering::Equal
12169 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
12170 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
12171 });
12172
12173 if let Err(mut ix) = ix {
12174 let index = post_inc(&mut self.highlight_order);
12175
12176 // If this range intersects with the preceding highlight, then merge it with
12177 // the preceding highlight. Otherwise insert a new highlight.
12178 let mut merged = false;
12179 if ix > 0 {
12180 let prev_highlight = &mut row_highlights[ix - 1];
12181 if prev_highlight
12182 .range
12183 .end
12184 .cmp(&range.start, &snapshot)
12185 .is_ge()
12186 {
12187 ix -= 1;
12188 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12189 prev_highlight.range.end = range.end;
12190 }
12191 merged = true;
12192 prev_highlight.index = index;
12193 prev_highlight.color = color;
12194 prev_highlight.should_autoscroll = should_autoscroll;
12195 }
12196 }
12197
12198 if !merged {
12199 row_highlights.insert(
12200 ix,
12201 RowHighlight {
12202 range: range.clone(),
12203 index,
12204 color,
12205 should_autoscroll,
12206 },
12207 );
12208 }
12209
12210 // If any of the following highlights intersect with this one, merge them.
12211 while let Some(next_highlight) = row_highlights.get(ix + 1) {
12212 let highlight = &row_highlights[ix];
12213 if next_highlight
12214 .range
12215 .start
12216 .cmp(&highlight.range.end, &snapshot)
12217 .is_le()
12218 {
12219 if next_highlight
12220 .range
12221 .end
12222 .cmp(&highlight.range.end, &snapshot)
12223 .is_gt()
12224 {
12225 row_highlights[ix].range.end = next_highlight.range.end;
12226 }
12227 row_highlights.remove(ix + 1);
12228 } else {
12229 break;
12230 }
12231 }
12232 }
12233 }
12234
12235 /// Remove any highlighted row ranges of the given type that intersect the
12236 /// given ranges.
12237 pub fn remove_highlighted_rows<T: 'static>(
12238 &mut self,
12239 ranges_to_remove: Vec<Range<Anchor>>,
12240 cx: &mut ViewContext<Self>,
12241 ) {
12242 let snapshot = self.buffer().read(cx).snapshot(cx);
12243 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12244 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12245 row_highlights.retain(|highlight| {
12246 while let Some(range_to_remove) = ranges_to_remove.peek() {
12247 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12248 Ordering::Less | Ordering::Equal => {
12249 ranges_to_remove.next();
12250 }
12251 Ordering::Greater => {
12252 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12253 Ordering::Less | Ordering::Equal => {
12254 return false;
12255 }
12256 Ordering::Greater => break,
12257 }
12258 }
12259 }
12260 }
12261
12262 true
12263 })
12264 }
12265
12266 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12267 pub fn clear_row_highlights<T: 'static>(&mut self) {
12268 self.highlighted_rows.remove(&TypeId::of::<T>());
12269 }
12270
12271 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12272 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12273 self.highlighted_rows
12274 .get(&TypeId::of::<T>())
12275 .map_or(&[] as &[_], |vec| vec.as_slice())
12276 .iter()
12277 .map(|highlight| (highlight.range.clone(), highlight.color))
12278 }
12279
12280 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12281 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
12282 /// Allows to ignore certain kinds of highlights.
12283 pub fn highlighted_display_rows(
12284 &mut self,
12285 cx: &mut WindowContext,
12286 ) -> BTreeMap<DisplayRow, Hsla> {
12287 let snapshot = self.snapshot(cx);
12288 let mut used_highlight_orders = HashMap::default();
12289 self.highlighted_rows
12290 .iter()
12291 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12292 .fold(
12293 BTreeMap::<DisplayRow, Hsla>::new(),
12294 |mut unique_rows, highlight| {
12295 let start = highlight.range.start.to_display_point(&snapshot);
12296 let end = highlight.range.end.to_display_point(&snapshot);
12297 let start_row = start.row().0;
12298 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12299 && end.column() == 0
12300 {
12301 end.row().0.saturating_sub(1)
12302 } else {
12303 end.row().0
12304 };
12305 for row in start_row..=end_row {
12306 let used_index =
12307 used_highlight_orders.entry(row).or_insert(highlight.index);
12308 if highlight.index >= *used_index {
12309 *used_index = highlight.index;
12310 unique_rows.insert(DisplayRow(row), highlight.color);
12311 }
12312 }
12313 unique_rows
12314 },
12315 )
12316 }
12317
12318 pub fn highlighted_display_row_for_autoscroll(
12319 &self,
12320 snapshot: &DisplaySnapshot,
12321 ) -> Option<DisplayRow> {
12322 self.highlighted_rows
12323 .values()
12324 .flat_map(|highlighted_rows| highlighted_rows.iter())
12325 .filter_map(|highlight| {
12326 if highlight.should_autoscroll {
12327 Some(highlight.range.start.to_display_point(snapshot).row())
12328 } else {
12329 None
12330 }
12331 })
12332 .min()
12333 }
12334
12335 pub fn set_search_within_ranges(
12336 &mut self,
12337 ranges: &[Range<Anchor>],
12338 cx: &mut ViewContext<Self>,
12339 ) {
12340 self.highlight_background::<SearchWithinRange>(
12341 ranges,
12342 |colors| colors.editor_document_highlight_read_background,
12343 cx,
12344 )
12345 }
12346
12347 pub fn set_breadcrumb_header(&mut self, new_header: String) {
12348 self.breadcrumb_header = Some(new_header);
12349 }
12350
12351 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12352 self.clear_background_highlights::<SearchWithinRange>(cx);
12353 }
12354
12355 pub fn highlight_background<T: 'static>(
12356 &mut self,
12357 ranges: &[Range<Anchor>],
12358 color_fetcher: fn(&ThemeColors) -> Hsla,
12359 cx: &mut ViewContext<Self>,
12360 ) {
12361 self.background_highlights
12362 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12363 self.scrollbar_marker_state.dirty = true;
12364 cx.notify();
12365 }
12366
12367 pub fn clear_background_highlights<T: 'static>(
12368 &mut self,
12369 cx: &mut ViewContext<Self>,
12370 ) -> Option<BackgroundHighlight> {
12371 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12372 if !text_highlights.1.is_empty() {
12373 self.scrollbar_marker_state.dirty = true;
12374 cx.notify();
12375 }
12376 Some(text_highlights)
12377 }
12378
12379 pub fn highlight_gutter<T: 'static>(
12380 &mut self,
12381 ranges: &[Range<Anchor>],
12382 color_fetcher: fn(&AppContext) -> Hsla,
12383 cx: &mut ViewContext<Self>,
12384 ) {
12385 self.gutter_highlights
12386 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12387 cx.notify();
12388 }
12389
12390 pub fn clear_gutter_highlights<T: 'static>(
12391 &mut self,
12392 cx: &mut ViewContext<Self>,
12393 ) -> Option<GutterHighlight> {
12394 cx.notify();
12395 self.gutter_highlights.remove(&TypeId::of::<T>())
12396 }
12397
12398 #[cfg(feature = "test-support")]
12399 pub fn all_text_background_highlights(
12400 &mut self,
12401 cx: &mut ViewContext<Self>,
12402 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12403 let snapshot = self.snapshot(cx);
12404 let buffer = &snapshot.buffer_snapshot;
12405 let start = buffer.anchor_before(0);
12406 let end = buffer.anchor_after(buffer.len());
12407 let theme = cx.theme().colors();
12408 self.background_highlights_in_range(start..end, &snapshot, theme)
12409 }
12410
12411 #[cfg(feature = "test-support")]
12412 pub fn search_background_highlights(
12413 &mut self,
12414 cx: &mut ViewContext<Self>,
12415 ) -> Vec<Range<Point>> {
12416 let snapshot = self.buffer().read(cx).snapshot(cx);
12417
12418 let highlights = self
12419 .background_highlights
12420 .get(&TypeId::of::<items::BufferSearchHighlights>());
12421
12422 if let Some((_color, ranges)) = highlights {
12423 ranges
12424 .iter()
12425 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12426 .collect_vec()
12427 } else {
12428 vec![]
12429 }
12430 }
12431
12432 fn document_highlights_for_position<'a>(
12433 &'a self,
12434 position: Anchor,
12435 buffer: &'a MultiBufferSnapshot,
12436 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12437 let read_highlights = self
12438 .background_highlights
12439 .get(&TypeId::of::<DocumentHighlightRead>())
12440 .map(|h| &h.1);
12441 let write_highlights = self
12442 .background_highlights
12443 .get(&TypeId::of::<DocumentHighlightWrite>())
12444 .map(|h| &h.1);
12445 let left_position = position.bias_left(buffer);
12446 let right_position = position.bias_right(buffer);
12447 read_highlights
12448 .into_iter()
12449 .chain(write_highlights)
12450 .flat_map(move |ranges| {
12451 let start_ix = match ranges.binary_search_by(|probe| {
12452 let cmp = probe.end.cmp(&left_position, buffer);
12453 if cmp.is_ge() {
12454 Ordering::Greater
12455 } else {
12456 Ordering::Less
12457 }
12458 }) {
12459 Ok(i) | Err(i) => i,
12460 };
12461
12462 ranges[start_ix..]
12463 .iter()
12464 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12465 })
12466 }
12467
12468 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12469 self.background_highlights
12470 .get(&TypeId::of::<T>())
12471 .map_or(false, |(_, highlights)| !highlights.is_empty())
12472 }
12473
12474 pub fn background_highlights_in_range(
12475 &self,
12476 search_range: Range<Anchor>,
12477 display_snapshot: &DisplaySnapshot,
12478 theme: &ThemeColors,
12479 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12480 let mut results = Vec::new();
12481 for (color_fetcher, ranges) in self.background_highlights.values() {
12482 let color = color_fetcher(theme);
12483 let start_ix = match ranges.binary_search_by(|probe| {
12484 let cmp = probe
12485 .end
12486 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12487 if cmp.is_gt() {
12488 Ordering::Greater
12489 } else {
12490 Ordering::Less
12491 }
12492 }) {
12493 Ok(i) | Err(i) => i,
12494 };
12495 for range in &ranges[start_ix..] {
12496 if range
12497 .start
12498 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12499 .is_ge()
12500 {
12501 break;
12502 }
12503
12504 let start = range.start.to_display_point(display_snapshot);
12505 let end = range.end.to_display_point(display_snapshot);
12506 results.push((start..end, color))
12507 }
12508 }
12509 results
12510 }
12511
12512 pub fn background_highlight_row_ranges<T: 'static>(
12513 &self,
12514 search_range: Range<Anchor>,
12515 display_snapshot: &DisplaySnapshot,
12516 count: usize,
12517 ) -> Vec<RangeInclusive<DisplayPoint>> {
12518 let mut results = Vec::new();
12519 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12520 return vec![];
12521 };
12522
12523 let start_ix = match ranges.binary_search_by(|probe| {
12524 let cmp = probe
12525 .end
12526 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12527 if cmp.is_gt() {
12528 Ordering::Greater
12529 } else {
12530 Ordering::Less
12531 }
12532 }) {
12533 Ok(i) | Err(i) => i,
12534 };
12535 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12536 if let (Some(start_display), Some(end_display)) = (start, end) {
12537 results.push(
12538 start_display.to_display_point(display_snapshot)
12539 ..=end_display.to_display_point(display_snapshot),
12540 );
12541 }
12542 };
12543 let mut start_row: Option<Point> = None;
12544 let mut end_row: Option<Point> = None;
12545 if ranges.len() > count {
12546 return Vec::new();
12547 }
12548 for range in &ranges[start_ix..] {
12549 if range
12550 .start
12551 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12552 .is_ge()
12553 {
12554 break;
12555 }
12556 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12557 if let Some(current_row) = &end_row {
12558 if end.row == current_row.row {
12559 continue;
12560 }
12561 }
12562 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12563 if start_row.is_none() {
12564 assert_eq!(end_row, None);
12565 start_row = Some(start);
12566 end_row = Some(end);
12567 continue;
12568 }
12569 if let Some(current_end) = end_row.as_mut() {
12570 if start.row > current_end.row + 1 {
12571 push_region(start_row, end_row);
12572 start_row = Some(start);
12573 end_row = Some(end);
12574 } else {
12575 // Merge two hunks.
12576 *current_end = end;
12577 }
12578 } else {
12579 unreachable!();
12580 }
12581 }
12582 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12583 push_region(start_row, end_row);
12584 results
12585 }
12586
12587 pub fn gutter_highlights_in_range(
12588 &self,
12589 search_range: Range<Anchor>,
12590 display_snapshot: &DisplaySnapshot,
12591 cx: &AppContext,
12592 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12593 let mut results = Vec::new();
12594 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12595 let color = color_fetcher(cx);
12596 let start_ix = match ranges.binary_search_by(|probe| {
12597 let cmp = probe
12598 .end
12599 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12600 if cmp.is_gt() {
12601 Ordering::Greater
12602 } else {
12603 Ordering::Less
12604 }
12605 }) {
12606 Ok(i) | Err(i) => i,
12607 };
12608 for range in &ranges[start_ix..] {
12609 if range
12610 .start
12611 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12612 .is_ge()
12613 {
12614 break;
12615 }
12616
12617 let start = range.start.to_display_point(display_snapshot);
12618 let end = range.end.to_display_point(display_snapshot);
12619 results.push((start..end, color))
12620 }
12621 }
12622 results
12623 }
12624
12625 /// Get the text ranges corresponding to the redaction query
12626 pub fn redacted_ranges(
12627 &self,
12628 search_range: Range<Anchor>,
12629 display_snapshot: &DisplaySnapshot,
12630 cx: &WindowContext,
12631 ) -> Vec<Range<DisplayPoint>> {
12632 display_snapshot
12633 .buffer_snapshot
12634 .redacted_ranges(search_range, |file| {
12635 if let Some(file) = file {
12636 file.is_private()
12637 && EditorSettings::get(
12638 Some(SettingsLocation {
12639 worktree_id: file.worktree_id(cx),
12640 path: file.path().as_ref(),
12641 }),
12642 cx,
12643 )
12644 .redact_private_values
12645 } else {
12646 false
12647 }
12648 })
12649 .map(|range| {
12650 range.start.to_display_point(display_snapshot)
12651 ..range.end.to_display_point(display_snapshot)
12652 })
12653 .collect()
12654 }
12655
12656 pub fn highlight_text<T: 'static>(
12657 &mut self,
12658 ranges: Vec<Range<Anchor>>,
12659 style: HighlightStyle,
12660 cx: &mut ViewContext<Self>,
12661 ) {
12662 self.display_map.update(cx, |map, _| {
12663 map.highlight_text(TypeId::of::<T>(), ranges, style)
12664 });
12665 cx.notify();
12666 }
12667
12668 pub(crate) fn highlight_inlays<T: 'static>(
12669 &mut self,
12670 highlights: Vec<InlayHighlight>,
12671 style: HighlightStyle,
12672 cx: &mut ViewContext<Self>,
12673 ) {
12674 self.display_map.update(cx, |map, _| {
12675 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12676 });
12677 cx.notify();
12678 }
12679
12680 pub fn text_highlights<'a, T: 'static>(
12681 &'a self,
12682 cx: &'a AppContext,
12683 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12684 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12685 }
12686
12687 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12688 let cleared = self
12689 .display_map
12690 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12691 if cleared {
12692 cx.notify();
12693 }
12694 }
12695
12696 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12697 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12698 && self.focus_handle.is_focused(cx)
12699 }
12700
12701 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12702 self.show_cursor_when_unfocused = is_enabled;
12703 cx.notify();
12704 }
12705
12706 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12707 cx.notify();
12708 }
12709
12710 fn on_buffer_event(
12711 &mut self,
12712 multibuffer: Model<MultiBuffer>,
12713 event: &multi_buffer::Event,
12714 cx: &mut ViewContext<Self>,
12715 ) {
12716 match event {
12717 multi_buffer::Event::Edited {
12718 singleton_buffer_edited,
12719 } => {
12720 self.scrollbar_marker_state.dirty = true;
12721 self.active_indent_guides_state.dirty = true;
12722 self.refresh_active_diagnostics(cx);
12723 self.refresh_code_actions(cx);
12724 if self.has_active_inline_completion() {
12725 self.update_visible_inline_completion(cx);
12726 }
12727 cx.emit(EditorEvent::BufferEdited);
12728 cx.emit(SearchEvent::MatchesInvalidated);
12729 if *singleton_buffer_edited {
12730 if let Some(project) = &self.project {
12731 let project = project.read(cx);
12732 #[allow(clippy::mutable_key_type)]
12733 let languages_affected = multibuffer
12734 .read(cx)
12735 .all_buffers()
12736 .into_iter()
12737 .filter_map(|buffer| {
12738 let buffer = buffer.read(cx);
12739 let language = buffer.language()?;
12740 if project.is_local()
12741 && project.language_servers_for_buffer(buffer, cx).count() == 0
12742 {
12743 None
12744 } else {
12745 Some(language)
12746 }
12747 })
12748 .cloned()
12749 .collect::<HashSet<_>>();
12750 if !languages_affected.is_empty() {
12751 self.refresh_inlay_hints(
12752 InlayHintRefreshReason::BufferEdited(languages_affected),
12753 cx,
12754 );
12755 }
12756 }
12757 }
12758
12759 let Some(project) = &self.project else { return };
12760 let (telemetry, is_via_ssh) = {
12761 let project = project.read(cx);
12762 let telemetry = project.client().telemetry().clone();
12763 let is_via_ssh = project.is_via_ssh();
12764 (telemetry, is_via_ssh)
12765 };
12766 refresh_linked_ranges(self, cx);
12767 telemetry.log_edit_event("editor", is_via_ssh);
12768 }
12769 multi_buffer::Event::ExcerptsAdded {
12770 buffer,
12771 predecessor,
12772 excerpts,
12773 } => {
12774 self.tasks_update_task = Some(self.refresh_runnables(cx));
12775 let buffer_id = buffer.read(cx).remote_id();
12776 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12777 if let Some(project) = &self.project {
12778 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12779 }
12780 }
12781 cx.emit(EditorEvent::ExcerptsAdded {
12782 buffer: buffer.clone(),
12783 predecessor: *predecessor,
12784 excerpts: excerpts.clone(),
12785 });
12786 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12787 }
12788 multi_buffer::Event::ExcerptsRemoved { ids } => {
12789 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12790 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12791 }
12792 multi_buffer::Event::ExcerptsEdited { ids } => {
12793 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12794 }
12795 multi_buffer::Event::ExcerptsExpanded { ids } => {
12796 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12797 }
12798 multi_buffer::Event::Reparsed(buffer_id) => {
12799 self.tasks_update_task = Some(self.refresh_runnables(cx));
12800
12801 cx.emit(EditorEvent::Reparsed(*buffer_id));
12802 }
12803 multi_buffer::Event::LanguageChanged(buffer_id) => {
12804 linked_editing_ranges::refresh_linked_ranges(self, cx);
12805 cx.emit(EditorEvent::Reparsed(*buffer_id));
12806 cx.notify();
12807 }
12808 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12809 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12810 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12811 cx.emit(EditorEvent::TitleChanged)
12812 }
12813 // multi_buffer::Event::DiffBaseChanged => {
12814 // self.scrollbar_marker_state.dirty = true;
12815 // cx.emit(EditorEvent::DiffBaseChanged);
12816 // cx.notify();
12817 // }
12818 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12819 multi_buffer::Event::DiagnosticsUpdated => {
12820 self.refresh_active_diagnostics(cx);
12821 self.scrollbar_marker_state.dirty = true;
12822 cx.notify();
12823 }
12824 _ => {}
12825 };
12826 }
12827
12828 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12829 cx.notify();
12830 }
12831
12832 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12833 self.tasks_update_task = Some(self.refresh_runnables(cx));
12834 self.refresh_inline_completion(true, false, cx);
12835 self.refresh_inlay_hints(
12836 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12837 self.selections.newest_anchor().head(),
12838 &self.buffer.read(cx).snapshot(cx),
12839 cx,
12840 )),
12841 cx,
12842 );
12843
12844 let old_cursor_shape = self.cursor_shape;
12845
12846 {
12847 let editor_settings = EditorSettings::get_global(cx);
12848 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12849 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12850 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12851 }
12852
12853 if old_cursor_shape != self.cursor_shape {
12854 cx.emit(EditorEvent::CursorShapeChanged);
12855 }
12856
12857 let project_settings = ProjectSettings::get_global(cx);
12858 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12859
12860 if self.mode == EditorMode::Full {
12861 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12862 if self.git_blame_inline_enabled != inline_blame_enabled {
12863 self.toggle_git_blame_inline_internal(false, cx);
12864 }
12865 }
12866
12867 cx.notify();
12868 }
12869
12870 pub fn set_searchable(&mut self, searchable: bool) {
12871 self.searchable = searchable;
12872 }
12873
12874 pub fn searchable(&self) -> bool {
12875 self.searchable
12876 }
12877
12878 fn open_proposed_changes_editor(
12879 &mut self,
12880 _: &OpenProposedChangesEditor,
12881 cx: &mut ViewContext<Self>,
12882 ) {
12883 let Some(workspace) = self.workspace() else {
12884 cx.propagate();
12885 return;
12886 };
12887
12888 let selections = self.selections.all::<usize>(cx);
12889 let buffer = self.buffer.read(cx);
12890 let mut new_selections_by_buffer = HashMap::default();
12891 for selection in selections {
12892 for (buffer, range, _) in
12893 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12894 {
12895 let mut range = range.to_point(buffer.read(cx));
12896 range.start.column = 0;
12897 range.end.column = buffer.read(cx).line_len(range.end.row);
12898 new_selections_by_buffer
12899 .entry(buffer)
12900 .or_insert(Vec::new())
12901 .push(range)
12902 }
12903 }
12904
12905 let proposed_changes_buffers = new_selections_by_buffer
12906 .into_iter()
12907 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12908 .collect::<Vec<_>>();
12909 let proposed_changes_editor = cx.new_view(|cx| {
12910 ProposedChangesEditor::new(
12911 "Proposed changes",
12912 proposed_changes_buffers,
12913 self.project.clone(),
12914 cx,
12915 )
12916 });
12917
12918 cx.window_context().defer(move |cx| {
12919 workspace.update(cx, |workspace, cx| {
12920 workspace.active_pane().update(cx, |pane, cx| {
12921 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12922 });
12923 });
12924 });
12925 }
12926
12927 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12928 self.open_excerpts_common(None, true, cx)
12929 }
12930
12931 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12932 self.open_excerpts_common(None, false, cx)
12933 }
12934
12935 fn open_excerpts_common(
12936 &mut self,
12937 jump_data: Option<JumpData>,
12938 split: bool,
12939 cx: &mut ViewContext<Self>,
12940 ) {
12941 let Some(workspace) = self.workspace() else {
12942 cx.propagate();
12943 return;
12944 };
12945
12946 if self.buffer.read(cx).is_singleton() {
12947 cx.propagate();
12948 return;
12949 }
12950
12951 let mut new_selections_by_buffer = HashMap::default();
12952 match &jump_data {
12953 Some(jump_data) => {
12954 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12955 if let Some(buffer) = multi_buffer_snapshot
12956 .buffer_id_for_excerpt(jump_data.excerpt_id)
12957 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12958 {
12959 let buffer_snapshot = buffer.read(cx).snapshot();
12960 let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12961 language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12962 } else {
12963 buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12964 };
12965 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12966 new_selections_by_buffer.insert(
12967 buffer,
12968 (
12969 vec![jump_to_offset..jump_to_offset],
12970 Some(jump_data.line_offset_from_top),
12971 ),
12972 );
12973 }
12974 }
12975 None => {
12976 let selections = self.selections.all::<usize>(cx);
12977 let buffer = self.buffer.read(cx);
12978 for selection in selections {
12979 for (mut buffer_handle, mut range, _) in
12980 buffer.range_to_buffer_ranges(selection.range(), cx)
12981 {
12982 // When editing branch buffers, jump to the corresponding location
12983 // in their base buffer.
12984 let buffer = buffer_handle.read(cx);
12985 if let Some(base_buffer) = buffer.base_buffer() {
12986 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12987 buffer_handle = base_buffer;
12988 }
12989
12990 if selection.reversed {
12991 mem::swap(&mut range.start, &mut range.end);
12992 }
12993 new_selections_by_buffer
12994 .entry(buffer_handle)
12995 .or_insert((Vec::new(), None))
12996 .0
12997 .push(range)
12998 }
12999 }
13000 }
13001 }
13002
13003 if new_selections_by_buffer.is_empty() {
13004 return;
13005 }
13006
13007 // We defer the pane interaction because we ourselves are a workspace item
13008 // and activating a new item causes the pane to call a method on us reentrantly,
13009 // which panics if we're on the stack.
13010 cx.window_context().defer(move |cx| {
13011 workspace.update(cx, |workspace, cx| {
13012 let pane = if split {
13013 workspace.adjacent_pane(cx)
13014 } else {
13015 workspace.active_pane().clone()
13016 };
13017
13018 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
13019 let editor = buffer
13020 .read(cx)
13021 .file()
13022 .is_none()
13023 .then(|| {
13024 // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
13025 // so `workspace.open_project_item` will never find them, always opening a new editor.
13026 // Instead, we try to activate the existing editor in the pane first.
13027 let (editor, pane_item_index) =
13028 pane.read(cx).items().enumerate().find_map(|(i, item)| {
13029 let editor = item.downcast::<Editor>()?;
13030 let singleton_buffer =
13031 editor.read(cx).buffer().read(cx).as_singleton()?;
13032 if singleton_buffer == buffer {
13033 Some((editor, i))
13034 } else {
13035 None
13036 }
13037 })?;
13038 pane.update(cx, |pane, cx| {
13039 pane.activate_item(pane_item_index, true, true, cx)
13040 });
13041 Some(editor)
13042 })
13043 .flatten()
13044 .unwrap_or_else(|| {
13045 workspace.open_project_item::<Self>(
13046 pane.clone(),
13047 buffer,
13048 true,
13049 true,
13050 cx,
13051 )
13052 });
13053
13054 editor.update(cx, |editor, cx| {
13055 let autoscroll = match scroll_offset {
13056 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
13057 None => Autoscroll::newest(),
13058 };
13059 let nav_history = editor.nav_history.take();
13060 editor.change_selections(Some(autoscroll), cx, |s| {
13061 s.select_ranges(ranges);
13062 });
13063 editor.nav_history = nav_history;
13064 });
13065 }
13066 })
13067 });
13068 }
13069
13070 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
13071 let snapshot = self.buffer.read(cx).read(cx);
13072 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
13073 Some(
13074 ranges
13075 .iter()
13076 .map(move |range| {
13077 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
13078 })
13079 .collect(),
13080 )
13081 }
13082
13083 fn selection_replacement_ranges(
13084 &self,
13085 range: Range<OffsetUtf16>,
13086 cx: &mut AppContext,
13087 ) -> Vec<Range<OffsetUtf16>> {
13088 let selections = self.selections.all::<OffsetUtf16>(cx);
13089 let newest_selection = selections
13090 .iter()
13091 .max_by_key(|selection| selection.id)
13092 .unwrap();
13093 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
13094 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
13095 let snapshot = self.buffer.read(cx).read(cx);
13096 selections
13097 .into_iter()
13098 .map(|mut selection| {
13099 selection.start.0 =
13100 (selection.start.0 as isize).saturating_add(start_delta) as usize;
13101 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
13102 snapshot.clip_offset_utf16(selection.start, Bias::Left)
13103 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
13104 })
13105 .collect()
13106 }
13107
13108 fn report_editor_event(
13109 &self,
13110 operation: &'static str,
13111 file_extension: Option<String>,
13112 cx: &AppContext,
13113 ) {
13114 if cfg!(any(test, feature = "test-support")) {
13115 return;
13116 }
13117
13118 let Some(project) = &self.project else { return };
13119
13120 // If None, we are in a file without an extension
13121 let file = self
13122 .buffer
13123 .read(cx)
13124 .as_singleton()
13125 .and_then(|b| b.read(cx).file());
13126 let file_extension = file_extension.or(file
13127 .as_ref()
13128 .and_then(|file| Path::new(file.file_name(cx)).extension())
13129 .and_then(|e| e.to_str())
13130 .map(|a| a.to_string()));
13131
13132 let vim_mode = cx
13133 .global::<SettingsStore>()
13134 .raw_user_settings()
13135 .get("vim_mode")
13136 == Some(&serde_json::Value::Bool(true));
13137
13138 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
13139 == language::language_settings::InlineCompletionProvider::Copilot;
13140 let copilot_enabled_for_language = self
13141 .buffer
13142 .read(cx)
13143 .settings_at(0, cx)
13144 .show_inline_completions;
13145
13146 let project = project.read(cx);
13147 let telemetry = project.client().telemetry().clone();
13148 telemetry.report_editor_event(
13149 file_extension,
13150 vim_mode,
13151 operation,
13152 copilot_enabled,
13153 copilot_enabled_for_language,
13154 project.is_via_ssh(),
13155 )
13156 }
13157
13158 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
13159 /// with each line being an array of {text, highlight} objects.
13160 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
13161 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
13162 return;
13163 };
13164
13165 #[derive(Serialize)]
13166 struct Chunk<'a> {
13167 text: String,
13168 highlight: Option<&'a str>,
13169 }
13170
13171 let snapshot = buffer.read(cx).snapshot();
13172 let range = self
13173 .selected_text_range(false, cx)
13174 .and_then(|selection| {
13175 if selection.range.is_empty() {
13176 None
13177 } else {
13178 Some(selection.range)
13179 }
13180 })
13181 .unwrap_or_else(|| 0..snapshot.len());
13182
13183 let chunks = snapshot.chunks(range, true);
13184 let mut lines = Vec::new();
13185 let mut line: VecDeque<Chunk> = VecDeque::new();
13186
13187 let Some(style) = self.style.as_ref() else {
13188 return;
13189 };
13190
13191 for chunk in chunks {
13192 let highlight = chunk
13193 .syntax_highlight_id
13194 .and_then(|id| id.name(&style.syntax));
13195 let mut chunk_lines = chunk.text.split('\n').peekable();
13196 while let Some(text) = chunk_lines.next() {
13197 let mut merged_with_last_token = false;
13198 if let Some(last_token) = line.back_mut() {
13199 if last_token.highlight == highlight {
13200 last_token.text.push_str(text);
13201 merged_with_last_token = true;
13202 }
13203 }
13204
13205 if !merged_with_last_token {
13206 line.push_back(Chunk {
13207 text: text.into(),
13208 highlight,
13209 });
13210 }
13211
13212 if chunk_lines.peek().is_some() {
13213 if line.len() > 1 && line.front().unwrap().text.is_empty() {
13214 line.pop_front();
13215 }
13216 if line.len() > 1 && line.back().unwrap().text.is_empty() {
13217 line.pop_back();
13218 }
13219
13220 lines.push(mem::take(&mut line));
13221 }
13222 }
13223 }
13224
13225 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13226 return;
13227 };
13228 cx.write_to_clipboard(ClipboardItem::new_string(lines));
13229 }
13230
13231 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
13232 self.request_autoscroll(Autoscroll::newest(), cx);
13233 let position = self.selections.newest_display(cx).start;
13234 mouse_context_menu::deploy_context_menu(self, None, position, cx);
13235 }
13236
13237 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13238 &self.inlay_hint_cache
13239 }
13240
13241 pub fn replay_insert_event(
13242 &mut self,
13243 text: &str,
13244 relative_utf16_range: Option<Range<isize>>,
13245 cx: &mut ViewContext<Self>,
13246 ) {
13247 if !self.input_enabled {
13248 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13249 return;
13250 }
13251 if let Some(relative_utf16_range) = relative_utf16_range {
13252 let selections = self.selections.all::<OffsetUtf16>(cx);
13253 self.change_selections(None, cx, |s| {
13254 let new_ranges = selections.into_iter().map(|range| {
13255 let start = OffsetUtf16(
13256 range
13257 .head()
13258 .0
13259 .saturating_add_signed(relative_utf16_range.start),
13260 );
13261 let end = OffsetUtf16(
13262 range
13263 .head()
13264 .0
13265 .saturating_add_signed(relative_utf16_range.end),
13266 );
13267 start..end
13268 });
13269 s.select_ranges(new_ranges);
13270 });
13271 }
13272
13273 self.handle_input(text, cx);
13274 }
13275
13276 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
13277 let Some(provider) = self.semantics_provider.as_ref() else {
13278 return false;
13279 };
13280
13281 let mut supports = false;
13282 self.buffer().read(cx).for_each_buffer(|buffer| {
13283 supports |= provider.supports_inlay_hints(buffer, cx);
13284 });
13285 supports
13286 }
13287
13288 pub fn focus(&self, cx: &mut WindowContext) {
13289 cx.focus(&self.focus_handle)
13290 }
13291
13292 pub fn is_focused(&self, cx: &WindowContext) -> bool {
13293 self.focus_handle.is_focused(cx)
13294 }
13295
13296 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13297 cx.emit(EditorEvent::Focused);
13298
13299 if let Some(descendant) = self
13300 .last_focused_descendant
13301 .take()
13302 .and_then(|descendant| descendant.upgrade())
13303 {
13304 cx.focus(&descendant);
13305 } else {
13306 if let Some(blame) = self.blame.as_ref() {
13307 blame.update(cx, GitBlame::focus)
13308 }
13309
13310 self.blink_manager.update(cx, BlinkManager::enable);
13311 self.show_cursor_names(cx);
13312 self.buffer.update(cx, |buffer, cx| {
13313 buffer.finalize_last_transaction(cx);
13314 if self.leader_peer_id.is_none() {
13315 buffer.set_active_selections(
13316 &self.selections.disjoint_anchors(),
13317 self.selections.line_mode,
13318 self.cursor_shape,
13319 cx,
13320 );
13321 }
13322 });
13323 }
13324 }
13325
13326 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13327 cx.emit(EditorEvent::FocusedIn)
13328 }
13329
13330 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13331 if event.blurred != self.focus_handle {
13332 self.last_focused_descendant = Some(event.blurred);
13333 }
13334 }
13335
13336 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13337 self.blink_manager.update(cx, BlinkManager::disable);
13338 self.buffer
13339 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13340
13341 if let Some(blame) = self.blame.as_ref() {
13342 blame.update(cx, GitBlame::blur)
13343 }
13344 if !self.hover_state.focused(cx) {
13345 hide_hover(self, cx);
13346 }
13347
13348 self.hide_context_menu(cx);
13349 cx.emit(EditorEvent::Blurred);
13350 cx.notify();
13351 }
13352
13353 pub fn register_action<A: Action>(
13354 &mut self,
13355 listener: impl Fn(&A, &mut WindowContext) + 'static,
13356 ) -> Subscription {
13357 let id = self.next_editor_action_id.post_inc();
13358 let listener = Arc::new(listener);
13359 self.editor_actions.borrow_mut().insert(
13360 id,
13361 Box::new(move |cx| {
13362 let cx = cx.window_context();
13363 let listener = listener.clone();
13364 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13365 let action = action.downcast_ref().unwrap();
13366 if phase == DispatchPhase::Bubble {
13367 listener(action, cx)
13368 }
13369 })
13370 }),
13371 );
13372
13373 let editor_actions = self.editor_actions.clone();
13374 Subscription::new(move || {
13375 editor_actions.borrow_mut().remove(&id);
13376 })
13377 }
13378
13379 pub fn file_header_size(&self) -> u32 {
13380 FILE_HEADER_HEIGHT
13381 }
13382
13383 pub fn revert(
13384 &mut self,
13385 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13386 cx: &mut ViewContext<Self>,
13387 ) {
13388 self.buffer().update(cx, |multi_buffer, cx| {
13389 for (buffer_id, changes) in revert_changes {
13390 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13391 buffer.update(cx, |buffer, cx| {
13392 buffer.edit(
13393 changes.into_iter().map(|(range, text)| {
13394 (range, text.to_string().map(Arc::<str>::from))
13395 }),
13396 None,
13397 cx,
13398 );
13399 });
13400 }
13401 }
13402 });
13403 self.change_selections(None, cx, |selections| selections.refresh());
13404 }
13405
13406 pub fn to_pixel_point(
13407 &mut self,
13408 source: multi_buffer::Anchor,
13409 editor_snapshot: &EditorSnapshot,
13410 cx: &mut ViewContext<Self>,
13411 ) -> Option<gpui::Point<Pixels>> {
13412 let source_point = source.to_display_point(editor_snapshot);
13413 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13414 }
13415
13416 pub fn display_to_pixel_point(
13417 &self,
13418 source: DisplayPoint,
13419 editor_snapshot: &EditorSnapshot,
13420 cx: &WindowContext,
13421 ) -> Option<gpui::Point<Pixels>> {
13422 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13423 let text_layout_details = self.text_layout_details(cx);
13424 let scroll_top = text_layout_details
13425 .scroll_anchor
13426 .scroll_position(editor_snapshot)
13427 .y;
13428
13429 if source.row().as_f32() < scroll_top.floor() {
13430 return None;
13431 }
13432 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13433 let source_y = line_height * (source.row().as_f32() - scroll_top);
13434 Some(gpui::Point::new(source_x, source_y))
13435 }
13436
13437 pub fn has_active_completions_menu(&self) -> bool {
13438 self.context_menu.read().as_ref().map_or(false, |menu| {
13439 menu.visible() && matches!(menu, ContextMenu::Completions(_))
13440 })
13441 }
13442
13443 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13444 self.addons
13445 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13446 }
13447
13448 pub fn unregister_addon<T: Addon>(&mut self) {
13449 self.addons.remove(&std::any::TypeId::of::<T>());
13450 }
13451
13452 pub fn addon<T: Addon>(&self) -> Option<&T> {
13453 let type_id = std::any::TypeId::of::<T>();
13454 self.addons
13455 .get(&type_id)
13456 .and_then(|item| item.to_any().downcast_ref::<T>())
13457 }
13458
13459 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13460 let text_layout_details = self.text_layout_details(cx);
13461 let style = &text_layout_details.editor_style;
13462 let font_id = cx.text_system().resolve_font(&style.text.font());
13463 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13464 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13465
13466 let em_width = cx
13467 .text_system()
13468 .typographic_bounds(font_id, font_size, 'm')
13469 .unwrap()
13470 .size
13471 .width;
13472
13473 gpui::Point::new(em_width, line_height)
13474 }
13475}
13476
13477fn get_unstaged_changes_for_buffers(
13478 project: &Model<Project>,
13479 buffers: impl IntoIterator<Item = Model<Buffer>>,
13480 cx: &mut ViewContext<Editor>,
13481) {
13482 let mut tasks = Vec::new();
13483 project.update(cx, |project, cx| {
13484 for buffer in buffers {
13485 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13486 }
13487 });
13488 cx.spawn(|this, mut cx| async move {
13489 let change_sets = futures::future::join_all(tasks).await;
13490 this.update(&mut cx, |this, cx| {
13491 for change_set in change_sets {
13492 if let Some(change_set) = change_set.log_err() {
13493 this.diff_map.add_change_set(change_set, cx);
13494 }
13495 }
13496 })
13497 .ok();
13498 })
13499 .detach();
13500}
13501
13502fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13503 let tab_size = tab_size.get() as usize;
13504 let mut width = offset;
13505
13506 for ch in text.chars() {
13507 width += if ch == '\t' {
13508 tab_size - (width % tab_size)
13509 } else {
13510 1
13511 };
13512 }
13513
13514 width - offset
13515}
13516
13517#[cfg(test)]
13518mod tests {
13519 use super::*;
13520
13521 #[test]
13522 fn test_string_size_with_expanded_tabs() {
13523 let nz = |val| NonZeroU32::new(val).unwrap();
13524 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13525 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13526 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13527 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13528 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13529 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13530 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13531 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13532 }
13533}
13534
13535/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13536struct WordBreakingTokenizer<'a> {
13537 input: &'a str,
13538}
13539
13540impl<'a> WordBreakingTokenizer<'a> {
13541 fn new(input: &'a str) -> Self {
13542 Self { input }
13543 }
13544}
13545
13546fn is_char_ideographic(ch: char) -> bool {
13547 use unicode_script::Script::*;
13548 use unicode_script::UnicodeScript;
13549 matches!(ch.script(), Han | Tangut | Yi)
13550}
13551
13552fn is_grapheme_ideographic(text: &str) -> bool {
13553 text.chars().any(is_char_ideographic)
13554}
13555
13556fn is_grapheme_whitespace(text: &str) -> bool {
13557 text.chars().any(|x| x.is_whitespace())
13558}
13559
13560fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13561 text.chars().next().map_or(false, |ch| {
13562 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13563 })
13564}
13565
13566#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13567struct WordBreakToken<'a> {
13568 token: &'a str,
13569 grapheme_len: usize,
13570 is_whitespace: bool,
13571}
13572
13573impl<'a> Iterator for WordBreakingTokenizer<'a> {
13574 /// Yields a span, the count of graphemes in the token, and whether it was
13575 /// whitespace. Note that it also breaks at word boundaries.
13576 type Item = WordBreakToken<'a>;
13577
13578 fn next(&mut self) -> Option<Self::Item> {
13579 use unicode_segmentation::UnicodeSegmentation;
13580 if self.input.is_empty() {
13581 return None;
13582 }
13583
13584 let mut iter = self.input.graphemes(true).peekable();
13585 let mut offset = 0;
13586 let mut graphemes = 0;
13587 if let Some(first_grapheme) = iter.next() {
13588 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13589 offset += first_grapheme.len();
13590 graphemes += 1;
13591 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13592 if let Some(grapheme) = iter.peek().copied() {
13593 if should_stay_with_preceding_ideograph(grapheme) {
13594 offset += grapheme.len();
13595 graphemes += 1;
13596 }
13597 }
13598 } else {
13599 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13600 let mut next_word_bound = words.peek().copied();
13601 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13602 next_word_bound = words.next();
13603 }
13604 while let Some(grapheme) = iter.peek().copied() {
13605 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13606 break;
13607 };
13608 if is_grapheme_whitespace(grapheme) != is_whitespace {
13609 break;
13610 };
13611 offset += grapheme.len();
13612 graphemes += 1;
13613 iter.next();
13614 }
13615 }
13616 let token = &self.input[..offset];
13617 self.input = &self.input[offset..];
13618 if is_whitespace {
13619 Some(WordBreakToken {
13620 token: " ",
13621 grapheme_len: 1,
13622 is_whitespace: true,
13623 })
13624 } else {
13625 Some(WordBreakToken {
13626 token,
13627 grapheme_len: graphemes,
13628 is_whitespace: false,
13629 })
13630 }
13631 } else {
13632 None
13633 }
13634 }
13635}
13636
13637#[test]
13638fn test_word_breaking_tokenizer() {
13639 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13640 ("", &[]),
13641 (" ", &[(" ", 1, true)]),
13642 ("Ʒ", &[("Ʒ", 1, false)]),
13643 ("Ǽ", &[("Ǽ", 1, false)]),
13644 ("⋑", &[("⋑", 1, false)]),
13645 ("⋑⋑", &[("⋑⋑", 2, false)]),
13646 (
13647 "原理,进而",
13648 &[
13649 ("原", 1, false),
13650 ("理,", 2, false),
13651 ("进", 1, false),
13652 ("而", 1, false),
13653 ],
13654 ),
13655 (
13656 "hello world",
13657 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13658 ),
13659 (
13660 "hello, world",
13661 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13662 ),
13663 (
13664 " hello world",
13665 &[
13666 (" ", 1, true),
13667 ("hello", 5, false),
13668 (" ", 1, true),
13669 ("world", 5, false),
13670 ],
13671 ),
13672 (
13673 "这是什么 \n 钢笔",
13674 &[
13675 ("这", 1, false),
13676 ("是", 1, false),
13677 ("什", 1, false),
13678 ("么", 1, false),
13679 (" ", 1, true),
13680 ("钢", 1, false),
13681 ("笔", 1, false),
13682 ],
13683 ),
13684 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13685 ];
13686
13687 for (input, result) in tests {
13688 assert_eq!(
13689 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13690 result
13691 .iter()
13692 .copied()
13693 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13694 token,
13695 grapheme_len,
13696 is_whitespace,
13697 })
13698 .collect::<Vec<_>>()
13699 );
13700 }
13701}
13702
13703fn wrap_with_prefix(
13704 line_prefix: String,
13705 unwrapped_text: String,
13706 wrap_column: usize,
13707 tab_size: NonZeroU32,
13708) -> String {
13709 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13710 let mut wrapped_text = String::new();
13711 let mut current_line = line_prefix.clone();
13712
13713 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13714 let mut current_line_len = line_prefix_len;
13715 for WordBreakToken {
13716 token,
13717 grapheme_len,
13718 is_whitespace,
13719 } in tokenizer
13720 {
13721 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13722 wrapped_text.push_str(current_line.trim_end());
13723 wrapped_text.push('\n');
13724 current_line.truncate(line_prefix.len());
13725 current_line_len = line_prefix_len;
13726 if !is_whitespace {
13727 current_line.push_str(token);
13728 current_line_len += grapheme_len;
13729 }
13730 } else if !is_whitespace {
13731 current_line.push_str(token);
13732 current_line_len += grapheme_len;
13733 } else if current_line_len != line_prefix_len {
13734 current_line.push(' ');
13735 current_line_len += 1;
13736 }
13737 }
13738
13739 if !current_line.is_empty() {
13740 wrapped_text.push_str(¤t_line);
13741 }
13742 wrapped_text
13743}
13744
13745#[test]
13746fn test_wrap_with_prefix() {
13747 assert_eq!(
13748 wrap_with_prefix(
13749 "# ".to_string(),
13750 "abcdefg".to_string(),
13751 4,
13752 NonZeroU32::new(4).unwrap()
13753 ),
13754 "# abcdefg"
13755 );
13756 assert_eq!(
13757 wrap_with_prefix(
13758 "".to_string(),
13759 "\thello world".to_string(),
13760 8,
13761 NonZeroU32::new(4).unwrap()
13762 ),
13763 "hello\nworld"
13764 );
13765 assert_eq!(
13766 wrap_with_prefix(
13767 "// ".to_string(),
13768 "xx \nyy zz aa bb cc".to_string(),
13769 12,
13770 NonZeroU32::new(4).unwrap()
13771 ),
13772 "// xx yy zz\n// aa bb cc"
13773 );
13774 assert_eq!(
13775 wrap_with_prefix(
13776 String::new(),
13777 "这是什么 \n 钢笔".to_string(),
13778 3,
13779 NonZeroU32::new(4).unwrap()
13780 ),
13781 "这是什\n么 钢\n笔"
13782 );
13783}
13784
13785fn hunks_for_selections(
13786 snapshot: &EditorSnapshot,
13787 selections: &[Selection<Point>],
13788) -> Vec<MultiBufferDiffHunk> {
13789 hunks_for_ranges(
13790 selections.iter().map(|selection| selection.range()),
13791 snapshot,
13792 )
13793}
13794
13795pub fn hunks_for_ranges(
13796 ranges: impl Iterator<Item = Range<Point>>,
13797 snapshot: &EditorSnapshot,
13798) -> Vec<MultiBufferDiffHunk> {
13799 let mut hunks = Vec::new();
13800 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13801 HashMap::default();
13802 for query_range in ranges {
13803 let query_rows =
13804 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13805 for hunk in snapshot.diff_map.diff_hunks_in_range(
13806 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13807 &snapshot.buffer_snapshot,
13808 ) {
13809 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13810 // when the caret is just above or just below the deleted hunk.
13811 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13812 let related_to_selection = if allow_adjacent {
13813 hunk.row_range.overlaps(&query_rows)
13814 || hunk.row_range.start == query_rows.end
13815 || hunk.row_range.end == query_rows.start
13816 } else {
13817 hunk.row_range.overlaps(&query_rows)
13818 };
13819 if related_to_selection {
13820 if !processed_buffer_rows
13821 .entry(hunk.buffer_id)
13822 .or_default()
13823 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13824 {
13825 continue;
13826 }
13827 hunks.push(hunk);
13828 }
13829 }
13830 }
13831
13832 hunks
13833}
13834
13835pub trait CollaborationHub {
13836 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13837 fn user_participant_indices<'a>(
13838 &self,
13839 cx: &'a AppContext,
13840 ) -> &'a HashMap<u64, ParticipantIndex>;
13841 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13842}
13843
13844impl CollaborationHub for Model<Project> {
13845 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13846 self.read(cx).collaborators()
13847 }
13848
13849 fn user_participant_indices<'a>(
13850 &self,
13851 cx: &'a AppContext,
13852 ) -> &'a HashMap<u64, ParticipantIndex> {
13853 self.read(cx).user_store().read(cx).participant_indices()
13854 }
13855
13856 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13857 let this = self.read(cx);
13858 let user_ids = this.collaborators().values().map(|c| c.user_id);
13859 this.user_store().read_with(cx, |user_store, cx| {
13860 user_store.participant_names(user_ids, cx)
13861 })
13862 }
13863}
13864
13865pub trait SemanticsProvider {
13866 fn hover(
13867 &self,
13868 buffer: &Model<Buffer>,
13869 position: text::Anchor,
13870 cx: &mut AppContext,
13871 ) -> Option<Task<Vec<project::Hover>>>;
13872
13873 fn inlay_hints(
13874 &self,
13875 buffer_handle: Model<Buffer>,
13876 range: Range<text::Anchor>,
13877 cx: &mut AppContext,
13878 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13879
13880 fn resolve_inlay_hint(
13881 &self,
13882 hint: InlayHint,
13883 buffer_handle: Model<Buffer>,
13884 server_id: LanguageServerId,
13885 cx: &mut AppContext,
13886 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13887
13888 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13889
13890 fn document_highlights(
13891 &self,
13892 buffer: &Model<Buffer>,
13893 position: text::Anchor,
13894 cx: &mut AppContext,
13895 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13896
13897 fn definitions(
13898 &self,
13899 buffer: &Model<Buffer>,
13900 position: text::Anchor,
13901 kind: GotoDefinitionKind,
13902 cx: &mut AppContext,
13903 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13904
13905 fn range_for_rename(
13906 &self,
13907 buffer: &Model<Buffer>,
13908 position: text::Anchor,
13909 cx: &mut AppContext,
13910 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13911
13912 fn perform_rename(
13913 &self,
13914 buffer: &Model<Buffer>,
13915 position: text::Anchor,
13916 new_name: String,
13917 cx: &mut AppContext,
13918 ) -> Option<Task<Result<ProjectTransaction>>>;
13919}
13920
13921pub trait CompletionProvider {
13922 fn completions(
13923 &self,
13924 buffer: &Model<Buffer>,
13925 buffer_position: text::Anchor,
13926 trigger: CompletionContext,
13927 cx: &mut ViewContext<Editor>,
13928 ) -> Task<Result<Vec<Completion>>>;
13929
13930 fn resolve_completions(
13931 &self,
13932 buffer: Model<Buffer>,
13933 completion_indices: Vec<usize>,
13934 completions: Arc<RwLock<Box<[Completion]>>>,
13935 cx: &mut ViewContext<Editor>,
13936 ) -> Task<Result<bool>>;
13937
13938 fn apply_additional_edits_for_completion(
13939 &self,
13940 buffer: Model<Buffer>,
13941 completion: Completion,
13942 push_to_history: bool,
13943 cx: &mut ViewContext<Editor>,
13944 ) -> Task<Result<Option<language::Transaction>>>;
13945
13946 fn is_completion_trigger(
13947 &self,
13948 buffer: &Model<Buffer>,
13949 position: language::Anchor,
13950 text: &str,
13951 trigger_in_words: bool,
13952 cx: &mut ViewContext<Editor>,
13953 ) -> bool;
13954
13955 fn sort_completions(&self) -> bool {
13956 true
13957 }
13958}
13959
13960pub trait CodeActionProvider {
13961 fn code_actions(
13962 &self,
13963 buffer: &Model<Buffer>,
13964 range: Range<text::Anchor>,
13965 cx: &mut WindowContext,
13966 ) -> Task<Result<Vec<CodeAction>>>;
13967
13968 fn apply_code_action(
13969 &self,
13970 buffer_handle: Model<Buffer>,
13971 action: CodeAction,
13972 excerpt_id: ExcerptId,
13973 push_to_history: bool,
13974 cx: &mut WindowContext,
13975 ) -> Task<Result<ProjectTransaction>>;
13976}
13977
13978impl CodeActionProvider for Model<Project> {
13979 fn code_actions(
13980 &self,
13981 buffer: &Model<Buffer>,
13982 range: Range<text::Anchor>,
13983 cx: &mut WindowContext,
13984 ) -> Task<Result<Vec<CodeAction>>> {
13985 self.update(cx, |project, cx| {
13986 project.code_actions(buffer, range, None, cx)
13987 })
13988 }
13989
13990 fn apply_code_action(
13991 &self,
13992 buffer_handle: Model<Buffer>,
13993 action: CodeAction,
13994 _excerpt_id: ExcerptId,
13995 push_to_history: bool,
13996 cx: &mut WindowContext,
13997 ) -> Task<Result<ProjectTransaction>> {
13998 self.update(cx, |project, cx| {
13999 project.apply_code_action(buffer_handle, action, push_to_history, cx)
14000 })
14001 }
14002}
14003
14004fn snippet_completions(
14005 project: &Project,
14006 buffer: &Model<Buffer>,
14007 buffer_position: text::Anchor,
14008 cx: &mut AppContext,
14009) -> Task<Result<Vec<Completion>>> {
14010 let language = buffer.read(cx).language_at(buffer_position);
14011 let language_name = language.as_ref().map(|language| language.lsp_id());
14012 let snippet_store = project.snippets().read(cx);
14013 let snippets = snippet_store.snippets_for(language_name, cx);
14014
14015 if snippets.is_empty() {
14016 return Task::ready(Ok(vec![]));
14017 }
14018 let snapshot = buffer.read(cx).text_snapshot();
14019 let chars: String = snapshot
14020 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
14021 .collect();
14022
14023 let scope = language.map(|language| language.default_scope());
14024 let executor = cx.background_executor().clone();
14025
14026 cx.background_executor().spawn(async move {
14027 let classifier = CharClassifier::new(scope).for_completion(true);
14028 let mut last_word = chars
14029 .chars()
14030 .take_while(|c| classifier.is_word(*c))
14031 .collect::<String>();
14032 last_word = last_word.chars().rev().collect();
14033
14034 if last_word.is_empty() {
14035 return Ok(vec![]);
14036 }
14037
14038 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
14039 let to_lsp = |point: &text::Anchor| {
14040 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
14041 point_to_lsp(end)
14042 };
14043 let lsp_end = to_lsp(&buffer_position);
14044
14045 let candidates = snippets
14046 .iter()
14047 .enumerate()
14048 .flat_map(|(ix, snippet)| {
14049 snippet
14050 .prefix
14051 .iter()
14052 .map(move |prefix| StringMatchCandidate::new(ix, prefix.clone()))
14053 })
14054 .collect::<Vec<StringMatchCandidate>>();
14055
14056 let mut matches = fuzzy::match_strings(
14057 &candidates,
14058 &last_word,
14059 last_word.chars().any(|c| c.is_uppercase()),
14060 100,
14061 &Default::default(),
14062 executor,
14063 )
14064 .await;
14065
14066 // Remove all candidates where the query's start does not match the start of any word in the candidate
14067 if let Some(query_start) = last_word.chars().next() {
14068 matches.retain(|string_match| {
14069 split_words(&string_match.string).any(|word| {
14070 // Check that the first codepoint of the word as lowercase matches the first
14071 // codepoint of the query as lowercase
14072 word.chars()
14073 .flat_map(|codepoint| codepoint.to_lowercase())
14074 .zip(query_start.to_lowercase())
14075 .all(|(word_cp, query_cp)| word_cp == query_cp)
14076 })
14077 });
14078 }
14079
14080 let matched_strings = matches
14081 .into_iter()
14082 .map(|m| m.string)
14083 .collect::<HashSet<_>>();
14084
14085 let result: Vec<Completion> = snippets
14086 .into_iter()
14087 .filter_map(|snippet| {
14088 let matching_prefix = snippet
14089 .prefix
14090 .iter()
14091 .find(|prefix| matched_strings.contains(*prefix))?;
14092 let start = as_offset - last_word.len();
14093 let start = snapshot.anchor_before(start);
14094 let range = start..buffer_position;
14095 let lsp_start = to_lsp(&start);
14096 let lsp_range = lsp::Range {
14097 start: lsp_start,
14098 end: lsp_end,
14099 };
14100 Some(Completion {
14101 old_range: range,
14102 new_text: snippet.body.clone(),
14103 label: CodeLabel {
14104 text: matching_prefix.clone(),
14105 runs: vec![],
14106 filter_range: 0..matching_prefix.len(),
14107 },
14108 server_id: LanguageServerId(usize::MAX),
14109 documentation: snippet.description.clone().map(Documentation::SingleLine),
14110 lsp_completion: lsp::CompletionItem {
14111 label: snippet.prefix.first().unwrap().clone(),
14112 kind: Some(CompletionItemKind::SNIPPET),
14113 label_details: snippet.description.as_ref().map(|description| {
14114 lsp::CompletionItemLabelDetails {
14115 detail: Some(description.clone()),
14116 description: None,
14117 }
14118 }),
14119 insert_text_format: Some(InsertTextFormat::SNIPPET),
14120 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
14121 lsp::InsertReplaceEdit {
14122 new_text: snippet.body.clone(),
14123 insert: lsp_range,
14124 replace: lsp_range,
14125 },
14126 )),
14127 filter_text: Some(snippet.body.clone()),
14128 sort_text: Some(char::MAX.to_string()),
14129 ..Default::default()
14130 },
14131 confirm: None,
14132 })
14133 })
14134 .collect();
14135
14136 Ok(result)
14137 })
14138}
14139
14140impl CompletionProvider for Model<Project> {
14141 fn completions(
14142 &self,
14143 buffer: &Model<Buffer>,
14144 buffer_position: text::Anchor,
14145 options: CompletionContext,
14146 cx: &mut ViewContext<Editor>,
14147 ) -> Task<Result<Vec<Completion>>> {
14148 self.update(cx, |project, cx| {
14149 let snippets = snippet_completions(project, buffer, buffer_position, cx);
14150 let project_completions = project.completions(buffer, buffer_position, options, cx);
14151 cx.background_executor().spawn(async move {
14152 let mut completions = project_completions.await?;
14153 let snippets_completions = snippets.await?;
14154 completions.extend(snippets_completions);
14155 Ok(completions)
14156 })
14157 })
14158 }
14159
14160 fn resolve_completions(
14161 &self,
14162 buffer: Model<Buffer>,
14163 completion_indices: Vec<usize>,
14164 completions: Arc<RwLock<Box<[Completion]>>>,
14165 cx: &mut ViewContext<Editor>,
14166 ) -> Task<Result<bool>> {
14167 self.update(cx, |project, cx| {
14168 project.resolve_completions(buffer, completion_indices, completions, cx)
14169 })
14170 }
14171
14172 fn apply_additional_edits_for_completion(
14173 &self,
14174 buffer: Model<Buffer>,
14175 completion: Completion,
14176 push_to_history: bool,
14177 cx: &mut ViewContext<Editor>,
14178 ) -> Task<Result<Option<language::Transaction>>> {
14179 self.update(cx, |project, cx| {
14180 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
14181 })
14182 }
14183
14184 fn is_completion_trigger(
14185 &self,
14186 buffer: &Model<Buffer>,
14187 position: language::Anchor,
14188 text: &str,
14189 trigger_in_words: bool,
14190 cx: &mut ViewContext<Editor>,
14191 ) -> bool {
14192 if !EditorSettings::get_global(cx).show_completions_on_input {
14193 return false;
14194 }
14195
14196 let mut chars = text.chars();
14197 let char = if let Some(char) = chars.next() {
14198 char
14199 } else {
14200 return false;
14201 };
14202 if chars.next().is_some() {
14203 return false;
14204 }
14205
14206 let buffer = buffer.read(cx);
14207 let classifier = buffer
14208 .snapshot()
14209 .char_classifier_at(position)
14210 .for_completion(true);
14211 if trigger_in_words && classifier.is_word(char) {
14212 return true;
14213 }
14214
14215 buffer.completion_triggers().contains(text)
14216 }
14217}
14218
14219impl SemanticsProvider for Model<Project> {
14220 fn hover(
14221 &self,
14222 buffer: &Model<Buffer>,
14223 position: text::Anchor,
14224 cx: &mut AppContext,
14225 ) -> Option<Task<Vec<project::Hover>>> {
14226 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
14227 }
14228
14229 fn document_highlights(
14230 &self,
14231 buffer: &Model<Buffer>,
14232 position: text::Anchor,
14233 cx: &mut AppContext,
14234 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
14235 Some(self.update(cx, |project, cx| {
14236 project.document_highlights(buffer, position, cx)
14237 }))
14238 }
14239
14240 fn definitions(
14241 &self,
14242 buffer: &Model<Buffer>,
14243 position: text::Anchor,
14244 kind: GotoDefinitionKind,
14245 cx: &mut AppContext,
14246 ) -> Option<Task<Result<Vec<LocationLink>>>> {
14247 Some(self.update(cx, |project, cx| match kind {
14248 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
14249 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
14250 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
14251 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
14252 }))
14253 }
14254
14255 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
14256 // TODO: make this work for remote projects
14257 self.read(cx)
14258 .language_servers_for_buffer(buffer.read(cx), cx)
14259 .any(
14260 |(_, server)| match server.capabilities().inlay_hint_provider {
14261 Some(lsp::OneOf::Left(enabled)) => enabled,
14262 Some(lsp::OneOf::Right(_)) => true,
14263 None => false,
14264 },
14265 )
14266 }
14267
14268 fn inlay_hints(
14269 &self,
14270 buffer_handle: Model<Buffer>,
14271 range: Range<text::Anchor>,
14272 cx: &mut AppContext,
14273 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14274 Some(self.update(cx, |project, cx| {
14275 project.inlay_hints(buffer_handle, range, cx)
14276 }))
14277 }
14278
14279 fn resolve_inlay_hint(
14280 &self,
14281 hint: InlayHint,
14282 buffer_handle: Model<Buffer>,
14283 server_id: LanguageServerId,
14284 cx: &mut AppContext,
14285 ) -> Option<Task<anyhow::Result<InlayHint>>> {
14286 Some(self.update(cx, |project, cx| {
14287 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14288 }))
14289 }
14290
14291 fn range_for_rename(
14292 &self,
14293 buffer: &Model<Buffer>,
14294 position: text::Anchor,
14295 cx: &mut AppContext,
14296 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14297 Some(self.update(cx, |project, cx| {
14298 project.prepare_rename(buffer.clone(), position, cx)
14299 }))
14300 }
14301
14302 fn perform_rename(
14303 &self,
14304 buffer: &Model<Buffer>,
14305 position: text::Anchor,
14306 new_name: String,
14307 cx: &mut AppContext,
14308 ) -> Option<Task<Result<ProjectTransaction>>> {
14309 Some(self.update(cx, |project, cx| {
14310 project.perform_rename(buffer.clone(), position, new_name, cx)
14311 }))
14312 }
14313}
14314
14315fn inlay_hint_settings(
14316 location: Anchor,
14317 snapshot: &MultiBufferSnapshot,
14318 cx: &mut ViewContext<'_, Editor>,
14319) -> InlayHintSettings {
14320 let file = snapshot.file_at(location);
14321 let language = snapshot.language_at(location).map(|l| l.name());
14322 language_settings(language, file, cx).inlay_hints
14323}
14324
14325fn consume_contiguous_rows(
14326 contiguous_row_selections: &mut Vec<Selection<Point>>,
14327 selection: &Selection<Point>,
14328 display_map: &DisplaySnapshot,
14329 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14330) -> (MultiBufferRow, MultiBufferRow) {
14331 contiguous_row_selections.push(selection.clone());
14332 let start_row = MultiBufferRow(selection.start.row);
14333 let mut end_row = ending_row(selection, display_map);
14334
14335 while let Some(next_selection) = selections.peek() {
14336 if next_selection.start.row <= end_row.0 {
14337 end_row = ending_row(next_selection, display_map);
14338 contiguous_row_selections.push(selections.next().unwrap().clone());
14339 } else {
14340 break;
14341 }
14342 }
14343 (start_row, end_row)
14344}
14345
14346fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14347 if next_selection.end.column > 0 || next_selection.is_empty() {
14348 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14349 } else {
14350 MultiBufferRow(next_selection.end.row)
14351 }
14352}
14353
14354impl EditorSnapshot {
14355 pub fn remote_selections_in_range<'a>(
14356 &'a self,
14357 range: &'a Range<Anchor>,
14358 collaboration_hub: &dyn CollaborationHub,
14359 cx: &'a AppContext,
14360 ) -> impl 'a + Iterator<Item = RemoteSelection> {
14361 let participant_names = collaboration_hub.user_names(cx);
14362 let participant_indices = collaboration_hub.user_participant_indices(cx);
14363 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14364 let collaborators_by_replica_id = collaborators_by_peer_id
14365 .iter()
14366 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14367 .collect::<HashMap<_, _>>();
14368 self.buffer_snapshot
14369 .selections_in_range(range, false)
14370 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14371 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14372 let participant_index = participant_indices.get(&collaborator.user_id).copied();
14373 let user_name = participant_names.get(&collaborator.user_id).cloned();
14374 Some(RemoteSelection {
14375 replica_id,
14376 selection,
14377 cursor_shape,
14378 line_mode,
14379 participant_index,
14380 peer_id: collaborator.peer_id,
14381 user_name,
14382 })
14383 })
14384 }
14385
14386 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14387 self.display_snapshot.buffer_snapshot.language_at(position)
14388 }
14389
14390 pub fn is_focused(&self) -> bool {
14391 self.is_focused
14392 }
14393
14394 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14395 self.placeholder_text.as_ref()
14396 }
14397
14398 pub fn scroll_position(&self) -> gpui::Point<f32> {
14399 self.scroll_anchor.scroll_position(&self.display_snapshot)
14400 }
14401
14402 fn gutter_dimensions(
14403 &self,
14404 font_id: FontId,
14405 font_size: Pixels,
14406 em_width: Pixels,
14407 em_advance: Pixels,
14408 max_line_number_width: Pixels,
14409 cx: &AppContext,
14410 ) -> GutterDimensions {
14411 if !self.show_gutter {
14412 return GutterDimensions::default();
14413 }
14414 let descent = cx.text_system().descent(font_id, font_size);
14415
14416 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14417 matches!(
14418 ProjectSettings::get_global(cx).git.git_gutter,
14419 Some(GitGutterSetting::TrackedFiles)
14420 )
14421 });
14422 let gutter_settings = EditorSettings::get_global(cx).gutter;
14423 let show_line_numbers = self
14424 .show_line_numbers
14425 .unwrap_or(gutter_settings.line_numbers);
14426 let line_gutter_width = if show_line_numbers {
14427 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14428 let min_width_for_number_on_gutter = em_advance * 4.0;
14429 max_line_number_width.max(min_width_for_number_on_gutter)
14430 } else {
14431 0.0.into()
14432 };
14433
14434 let show_code_actions = self
14435 .show_code_actions
14436 .unwrap_or(gutter_settings.code_actions);
14437
14438 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14439
14440 let git_blame_entries_width =
14441 self.git_blame_gutter_max_author_length
14442 .map(|max_author_length| {
14443 // Length of the author name, but also space for the commit hash,
14444 // the spacing and the timestamp.
14445 let max_char_count = max_author_length
14446 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14447 + 7 // length of commit sha
14448 + 14 // length of max relative timestamp ("60 minutes ago")
14449 + 4; // gaps and margins
14450
14451 em_advance * max_char_count
14452 });
14453
14454 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14455 left_padding += if show_code_actions || show_runnables {
14456 em_width * 3.0
14457 } else if show_git_gutter && show_line_numbers {
14458 em_width * 2.0
14459 } else if show_git_gutter || show_line_numbers {
14460 em_width
14461 } else {
14462 px(0.)
14463 };
14464
14465 let right_padding = if gutter_settings.folds && show_line_numbers {
14466 em_width * 4.0
14467 } else if gutter_settings.folds {
14468 em_width * 3.0
14469 } else if show_line_numbers {
14470 em_width
14471 } else {
14472 px(0.)
14473 };
14474
14475 GutterDimensions {
14476 left_padding,
14477 right_padding,
14478 width: line_gutter_width + left_padding + right_padding,
14479 margin: -descent,
14480 git_blame_entries_width,
14481 }
14482 }
14483
14484 pub fn render_crease_toggle(
14485 &self,
14486 buffer_row: MultiBufferRow,
14487 row_contains_cursor: bool,
14488 editor: View<Editor>,
14489 cx: &mut WindowContext,
14490 ) -> Option<AnyElement> {
14491 let folded = self.is_line_folded(buffer_row);
14492 let mut is_foldable = false;
14493
14494 if let Some(crease) = self
14495 .crease_snapshot
14496 .query_row(buffer_row, &self.buffer_snapshot)
14497 {
14498 is_foldable = true;
14499 match crease {
14500 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14501 if let Some(render_toggle) = render_toggle {
14502 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14503 if folded {
14504 editor.update(cx, |editor, cx| {
14505 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14506 });
14507 } else {
14508 editor.update(cx, |editor, cx| {
14509 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14510 });
14511 }
14512 });
14513 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14514 }
14515 }
14516 }
14517 }
14518
14519 is_foldable |= self.starts_indent(buffer_row);
14520
14521 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14522 Some(
14523 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14524 .selected(folded)
14525 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14526 if folded {
14527 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14528 } else {
14529 this.fold_at(&FoldAt { buffer_row }, cx);
14530 }
14531 }))
14532 .into_any_element(),
14533 )
14534 } else {
14535 None
14536 }
14537 }
14538
14539 pub fn render_crease_trailer(
14540 &self,
14541 buffer_row: MultiBufferRow,
14542 cx: &mut WindowContext,
14543 ) -> Option<AnyElement> {
14544 let folded = self.is_line_folded(buffer_row);
14545 if let Crease::Inline { render_trailer, .. } = self
14546 .crease_snapshot
14547 .query_row(buffer_row, &self.buffer_snapshot)?
14548 {
14549 let render_trailer = render_trailer.as_ref()?;
14550 Some(render_trailer(buffer_row, folded, cx))
14551 } else {
14552 None
14553 }
14554 }
14555}
14556
14557impl Deref for EditorSnapshot {
14558 type Target = DisplaySnapshot;
14559
14560 fn deref(&self) -> &Self::Target {
14561 &self.display_snapshot
14562 }
14563}
14564
14565#[derive(Clone, Debug, PartialEq, Eq)]
14566pub enum EditorEvent {
14567 InputIgnored {
14568 text: Arc<str>,
14569 },
14570 InputHandled {
14571 utf16_range_to_replace: Option<Range<isize>>,
14572 text: Arc<str>,
14573 },
14574 ExcerptsAdded {
14575 buffer: Model<Buffer>,
14576 predecessor: ExcerptId,
14577 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14578 },
14579 ExcerptsRemoved {
14580 ids: Vec<ExcerptId>,
14581 },
14582 ExcerptsEdited {
14583 ids: Vec<ExcerptId>,
14584 },
14585 ExcerptsExpanded {
14586 ids: Vec<ExcerptId>,
14587 },
14588 BufferEdited,
14589 Edited {
14590 transaction_id: clock::Lamport,
14591 },
14592 Reparsed(BufferId),
14593 Focused,
14594 FocusedIn,
14595 Blurred,
14596 DirtyChanged,
14597 Saved,
14598 TitleChanged,
14599 DiffBaseChanged,
14600 SelectionsChanged {
14601 local: bool,
14602 },
14603 ScrollPositionChanged {
14604 local: bool,
14605 autoscroll: bool,
14606 },
14607 Closed,
14608 TransactionUndone {
14609 transaction_id: clock::Lamport,
14610 },
14611 TransactionBegun {
14612 transaction_id: clock::Lamport,
14613 },
14614 Reloaded,
14615 CursorShapeChanged,
14616}
14617
14618impl EventEmitter<EditorEvent> for Editor {}
14619
14620impl FocusableView for Editor {
14621 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14622 self.focus_handle.clone()
14623 }
14624}
14625
14626impl Render for Editor {
14627 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14628 let settings = ThemeSettings::get_global(cx);
14629
14630 let mut text_style = match self.mode {
14631 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14632 color: cx.theme().colors().editor_foreground,
14633 font_family: settings.ui_font.family.clone(),
14634 font_features: settings.ui_font.features.clone(),
14635 font_fallbacks: settings.ui_font.fallbacks.clone(),
14636 font_size: rems(0.875).into(),
14637 font_weight: settings.ui_font.weight,
14638 line_height: relative(settings.buffer_line_height.value()),
14639 ..Default::default()
14640 },
14641 EditorMode::Full => TextStyle {
14642 color: cx.theme().colors().editor_foreground,
14643 font_family: settings.buffer_font.family.clone(),
14644 font_features: settings.buffer_font.features.clone(),
14645 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14646 font_size: settings.buffer_font_size(cx).into(),
14647 font_weight: settings.buffer_font.weight,
14648 line_height: relative(settings.buffer_line_height.value()),
14649 ..Default::default()
14650 },
14651 };
14652 if let Some(text_style_refinement) = &self.text_style_refinement {
14653 text_style.refine(text_style_refinement)
14654 }
14655
14656 let background = match self.mode {
14657 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14658 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14659 EditorMode::Full => cx.theme().colors().editor_background,
14660 };
14661
14662 EditorElement::new(
14663 cx.view(),
14664 EditorStyle {
14665 background,
14666 local_player: cx.theme().players().local(),
14667 text: text_style,
14668 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14669 syntax: cx.theme().syntax().clone(),
14670 status: cx.theme().status().clone(),
14671 inlay_hints_style: make_inlay_hints_style(cx),
14672 suggestions_style: HighlightStyle {
14673 color: Some(cx.theme().status().predictive),
14674 ..HighlightStyle::default()
14675 },
14676 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14677 },
14678 )
14679 }
14680}
14681
14682impl ViewInputHandler for Editor {
14683 fn text_for_range(
14684 &mut self,
14685 range_utf16: Range<usize>,
14686 adjusted_range: &mut Option<Range<usize>>,
14687 cx: &mut ViewContext<Self>,
14688 ) -> Option<String> {
14689 let snapshot = self.buffer.read(cx).read(cx);
14690 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14691 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14692 if (start.0..end.0) != range_utf16 {
14693 adjusted_range.replace(start.0..end.0);
14694 }
14695 Some(snapshot.text_for_range(start..end).collect())
14696 }
14697
14698 fn selected_text_range(
14699 &mut self,
14700 ignore_disabled_input: bool,
14701 cx: &mut ViewContext<Self>,
14702 ) -> Option<UTF16Selection> {
14703 // Prevent the IME menu from appearing when holding down an alphabetic key
14704 // while input is disabled.
14705 if !ignore_disabled_input && !self.input_enabled {
14706 return None;
14707 }
14708
14709 let selection = self.selections.newest::<OffsetUtf16>(cx);
14710 let range = selection.range();
14711
14712 Some(UTF16Selection {
14713 range: range.start.0..range.end.0,
14714 reversed: selection.reversed,
14715 })
14716 }
14717
14718 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14719 let snapshot = self.buffer.read(cx).read(cx);
14720 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14721 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14722 }
14723
14724 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14725 self.clear_highlights::<InputComposition>(cx);
14726 self.ime_transaction.take();
14727 }
14728
14729 fn replace_text_in_range(
14730 &mut self,
14731 range_utf16: Option<Range<usize>>,
14732 text: &str,
14733 cx: &mut ViewContext<Self>,
14734 ) {
14735 if !self.input_enabled {
14736 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14737 return;
14738 }
14739
14740 self.transact(cx, |this, cx| {
14741 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14742 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14743 Some(this.selection_replacement_ranges(range_utf16, cx))
14744 } else {
14745 this.marked_text_ranges(cx)
14746 };
14747
14748 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14749 let newest_selection_id = this.selections.newest_anchor().id;
14750 this.selections
14751 .all::<OffsetUtf16>(cx)
14752 .iter()
14753 .zip(ranges_to_replace.iter())
14754 .find_map(|(selection, range)| {
14755 if selection.id == newest_selection_id {
14756 Some(
14757 (range.start.0 as isize - selection.head().0 as isize)
14758 ..(range.end.0 as isize - selection.head().0 as isize),
14759 )
14760 } else {
14761 None
14762 }
14763 })
14764 });
14765
14766 cx.emit(EditorEvent::InputHandled {
14767 utf16_range_to_replace: range_to_replace,
14768 text: text.into(),
14769 });
14770
14771 if let Some(new_selected_ranges) = new_selected_ranges {
14772 this.change_selections(None, cx, |selections| {
14773 selections.select_ranges(new_selected_ranges)
14774 });
14775 this.backspace(&Default::default(), cx);
14776 }
14777
14778 this.handle_input(text, cx);
14779 });
14780
14781 if let Some(transaction) = self.ime_transaction {
14782 self.buffer.update(cx, |buffer, cx| {
14783 buffer.group_until_transaction(transaction, cx);
14784 });
14785 }
14786
14787 self.unmark_text(cx);
14788 }
14789
14790 fn replace_and_mark_text_in_range(
14791 &mut self,
14792 range_utf16: Option<Range<usize>>,
14793 text: &str,
14794 new_selected_range_utf16: Option<Range<usize>>,
14795 cx: &mut ViewContext<Self>,
14796 ) {
14797 if !self.input_enabled {
14798 return;
14799 }
14800
14801 let transaction = self.transact(cx, |this, cx| {
14802 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14803 let snapshot = this.buffer.read(cx).read(cx);
14804 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14805 for marked_range in &mut marked_ranges {
14806 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14807 marked_range.start.0 += relative_range_utf16.start;
14808 marked_range.start =
14809 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14810 marked_range.end =
14811 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14812 }
14813 }
14814 Some(marked_ranges)
14815 } else if let Some(range_utf16) = range_utf16 {
14816 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14817 Some(this.selection_replacement_ranges(range_utf16, cx))
14818 } else {
14819 None
14820 };
14821
14822 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14823 let newest_selection_id = this.selections.newest_anchor().id;
14824 this.selections
14825 .all::<OffsetUtf16>(cx)
14826 .iter()
14827 .zip(ranges_to_replace.iter())
14828 .find_map(|(selection, range)| {
14829 if selection.id == newest_selection_id {
14830 Some(
14831 (range.start.0 as isize - selection.head().0 as isize)
14832 ..(range.end.0 as isize - selection.head().0 as isize),
14833 )
14834 } else {
14835 None
14836 }
14837 })
14838 });
14839
14840 cx.emit(EditorEvent::InputHandled {
14841 utf16_range_to_replace: range_to_replace,
14842 text: text.into(),
14843 });
14844
14845 if let Some(ranges) = ranges_to_replace {
14846 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14847 }
14848
14849 let marked_ranges = {
14850 let snapshot = this.buffer.read(cx).read(cx);
14851 this.selections
14852 .disjoint_anchors()
14853 .iter()
14854 .map(|selection| {
14855 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14856 })
14857 .collect::<Vec<_>>()
14858 };
14859
14860 if text.is_empty() {
14861 this.unmark_text(cx);
14862 } else {
14863 this.highlight_text::<InputComposition>(
14864 marked_ranges.clone(),
14865 HighlightStyle {
14866 underline: Some(UnderlineStyle {
14867 thickness: px(1.),
14868 color: None,
14869 wavy: false,
14870 }),
14871 ..Default::default()
14872 },
14873 cx,
14874 );
14875 }
14876
14877 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14878 let use_autoclose = this.use_autoclose;
14879 let use_auto_surround = this.use_auto_surround;
14880 this.set_use_autoclose(false);
14881 this.set_use_auto_surround(false);
14882 this.handle_input(text, cx);
14883 this.set_use_autoclose(use_autoclose);
14884 this.set_use_auto_surround(use_auto_surround);
14885
14886 if let Some(new_selected_range) = new_selected_range_utf16 {
14887 let snapshot = this.buffer.read(cx).read(cx);
14888 let new_selected_ranges = marked_ranges
14889 .into_iter()
14890 .map(|marked_range| {
14891 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14892 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14893 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14894 snapshot.clip_offset_utf16(new_start, Bias::Left)
14895 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14896 })
14897 .collect::<Vec<_>>();
14898
14899 drop(snapshot);
14900 this.change_selections(None, cx, |selections| {
14901 selections.select_ranges(new_selected_ranges)
14902 });
14903 }
14904 });
14905
14906 self.ime_transaction = self.ime_transaction.or(transaction);
14907 if let Some(transaction) = self.ime_transaction {
14908 self.buffer.update(cx, |buffer, cx| {
14909 buffer.group_until_transaction(transaction, cx);
14910 });
14911 }
14912
14913 if self.text_highlights::<InputComposition>(cx).is_none() {
14914 self.ime_transaction.take();
14915 }
14916 }
14917
14918 fn bounds_for_range(
14919 &mut self,
14920 range_utf16: Range<usize>,
14921 element_bounds: gpui::Bounds<Pixels>,
14922 cx: &mut ViewContext<Self>,
14923 ) -> Option<gpui::Bounds<Pixels>> {
14924 let text_layout_details = self.text_layout_details(cx);
14925 let gpui::Point {
14926 x: em_width,
14927 y: line_height,
14928 } = self.character_size(cx);
14929
14930 let snapshot = self.snapshot(cx);
14931 let scroll_position = snapshot.scroll_position();
14932 let scroll_left = scroll_position.x * em_width;
14933
14934 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14935 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14936 + self.gutter_dimensions.width
14937 + self.gutter_dimensions.margin;
14938 let y = line_height * (start.row().as_f32() - scroll_position.y);
14939
14940 Some(Bounds {
14941 origin: element_bounds.origin + point(x, y),
14942 size: size(em_width, line_height),
14943 })
14944 }
14945}
14946
14947trait SelectionExt {
14948 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14949 fn spanned_rows(
14950 &self,
14951 include_end_if_at_line_start: bool,
14952 map: &DisplaySnapshot,
14953 ) -> Range<MultiBufferRow>;
14954}
14955
14956impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14957 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14958 let start = self
14959 .start
14960 .to_point(&map.buffer_snapshot)
14961 .to_display_point(map);
14962 let end = self
14963 .end
14964 .to_point(&map.buffer_snapshot)
14965 .to_display_point(map);
14966 if self.reversed {
14967 end..start
14968 } else {
14969 start..end
14970 }
14971 }
14972
14973 fn spanned_rows(
14974 &self,
14975 include_end_if_at_line_start: bool,
14976 map: &DisplaySnapshot,
14977 ) -> Range<MultiBufferRow> {
14978 let start = self.start.to_point(&map.buffer_snapshot);
14979 let mut end = self.end.to_point(&map.buffer_snapshot);
14980 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14981 end.row -= 1;
14982 }
14983
14984 let buffer_start = map.prev_line_boundary(start).0;
14985 let buffer_end = map.next_line_boundary(end).0;
14986 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14987 }
14988}
14989
14990impl<T: InvalidationRegion> InvalidationStack<T> {
14991 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14992 where
14993 S: Clone + ToOffset,
14994 {
14995 while let Some(region) = self.last() {
14996 let all_selections_inside_invalidation_ranges =
14997 if selections.len() == region.ranges().len() {
14998 selections
14999 .iter()
15000 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
15001 .all(|(selection, invalidation_range)| {
15002 let head = selection.head().to_offset(buffer);
15003 invalidation_range.start <= head && invalidation_range.end >= head
15004 })
15005 } else {
15006 false
15007 };
15008
15009 if all_selections_inside_invalidation_ranges {
15010 break;
15011 } else {
15012 self.pop();
15013 }
15014 }
15015 }
15016}
15017
15018impl<T> Default for InvalidationStack<T> {
15019 fn default() -> Self {
15020 Self(Default::default())
15021 }
15022}
15023
15024impl<T> Deref for InvalidationStack<T> {
15025 type Target = Vec<T>;
15026
15027 fn deref(&self) -> &Self::Target {
15028 &self.0
15029 }
15030}
15031
15032impl<T> DerefMut for InvalidationStack<T> {
15033 fn deref_mut(&mut self) -> &mut Self::Target {
15034 &mut self.0
15035 }
15036}
15037
15038impl InvalidationRegion for SnippetState {
15039 fn ranges(&self) -> &[Range<Anchor>] {
15040 &self.ranges[self.active_index]
15041 }
15042}
15043
15044pub fn diagnostic_block_renderer(
15045 diagnostic: Diagnostic,
15046 max_message_rows: Option<u8>,
15047 allow_closing: bool,
15048 _is_valid: bool,
15049) -> RenderBlock {
15050 let (text_without_backticks, code_ranges) =
15051 highlight_diagnostic_message(&diagnostic, max_message_rows);
15052
15053 Arc::new(move |cx: &mut BlockContext| {
15054 let group_id: SharedString = cx.block_id.to_string().into();
15055
15056 let mut text_style = cx.text_style().clone();
15057 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
15058 let theme_settings = ThemeSettings::get_global(cx);
15059 text_style.font_family = theme_settings.buffer_font.family.clone();
15060 text_style.font_style = theme_settings.buffer_font.style;
15061 text_style.font_features = theme_settings.buffer_font.features.clone();
15062 text_style.font_weight = theme_settings.buffer_font.weight;
15063
15064 let multi_line_diagnostic = diagnostic.message.contains('\n');
15065
15066 let buttons = |diagnostic: &Diagnostic| {
15067 if multi_line_diagnostic {
15068 v_flex()
15069 } else {
15070 h_flex()
15071 }
15072 .when(allow_closing, |div| {
15073 div.children(diagnostic.is_primary.then(|| {
15074 IconButton::new("close-block", IconName::XCircle)
15075 .icon_color(Color::Muted)
15076 .size(ButtonSize::Compact)
15077 .style(ButtonStyle::Transparent)
15078 .visible_on_hover(group_id.clone())
15079 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
15080 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
15081 }))
15082 })
15083 .child(
15084 IconButton::new("copy-block", IconName::Copy)
15085 .icon_color(Color::Muted)
15086 .size(ButtonSize::Compact)
15087 .style(ButtonStyle::Transparent)
15088 .visible_on_hover(group_id.clone())
15089 .on_click({
15090 let message = diagnostic.message.clone();
15091 move |_click, cx| {
15092 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
15093 }
15094 })
15095 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
15096 )
15097 };
15098
15099 let icon_size = buttons(&diagnostic)
15100 .into_any_element()
15101 .layout_as_root(AvailableSpace::min_size(), cx);
15102
15103 h_flex()
15104 .id(cx.block_id)
15105 .group(group_id.clone())
15106 .relative()
15107 .size_full()
15108 .block_mouse_down()
15109 .pl(cx.gutter_dimensions.width)
15110 .w(cx.max_width - cx.gutter_dimensions.full_width())
15111 .child(
15112 div()
15113 .flex()
15114 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
15115 .flex_shrink(),
15116 )
15117 .child(buttons(&diagnostic))
15118 .child(div().flex().flex_shrink_0().child(
15119 StyledText::new(text_without_backticks.clone()).with_highlights(
15120 &text_style,
15121 code_ranges.iter().map(|range| {
15122 (
15123 range.clone(),
15124 HighlightStyle {
15125 font_weight: Some(FontWeight::BOLD),
15126 ..Default::default()
15127 },
15128 )
15129 }),
15130 ),
15131 ))
15132 .into_any_element()
15133 })
15134}
15135
15136pub fn highlight_diagnostic_message(
15137 diagnostic: &Diagnostic,
15138 mut max_message_rows: Option<u8>,
15139) -> (SharedString, Vec<Range<usize>>) {
15140 let mut text_without_backticks = String::new();
15141 let mut code_ranges = Vec::new();
15142
15143 if let Some(source) = &diagnostic.source {
15144 text_without_backticks.push_str(source);
15145 code_ranges.push(0..source.len());
15146 text_without_backticks.push_str(": ");
15147 }
15148
15149 let mut prev_offset = 0;
15150 let mut in_code_block = false;
15151 let has_row_limit = max_message_rows.is_some();
15152 let mut newline_indices = diagnostic
15153 .message
15154 .match_indices('\n')
15155 .filter(|_| has_row_limit)
15156 .map(|(ix, _)| ix)
15157 .fuse()
15158 .peekable();
15159
15160 for (quote_ix, _) in diagnostic
15161 .message
15162 .match_indices('`')
15163 .chain([(diagnostic.message.len(), "")])
15164 {
15165 let mut first_newline_ix = None;
15166 let mut last_newline_ix = None;
15167 while let Some(newline_ix) = newline_indices.peek() {
15168 if *newline_ix < quote_ix {
15169 if first_newline_ix.is_none() {
15170 first_newline_ix = Some(*newline_ix);
15171 }
15172 last_newline_ix = Some(*newline_ix);
15173
15174 if let Some(rows_left) = &mut max_message_rows {
15175 if *rows_left == 0 {
15176 break;
15177 } else {
15178 *rows_left -= 1;
15179 }
15180 }
15181 let _ = newline_indices.next();
15182 } else {
15183 break;
15184 }
15185 }
15186 let prev_len = text_without_backticks.len();
15187 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
15188 text_without_backticks.push_str(new_text);
15189 if in_code_block {
15190 code_ranges.push(prev_len..text_without_backticks.len());
15191 }
15192 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
15193 in_code_block = !in_code_block;
15194 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
15195 text_without_backticks.push_str("...");
15196 break;
15197 }
15198 }
15199
15200 (text_without_backticks.into(), code_ranges)
15201}
15202
15203fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
15204 match severity {
15205 DiagnosticSeverity::ERROR => colors.error,
15206 DiagnosticSeverity::WARNING => colors.warning,
15207 DiagnosticSeverity::INFORMATION => colors.info,
15208 DiagnosticSeverity::HINT => colors.info,
15209 _ => colors.ignored,
15210 }
15211}
15212
15213pub fn styled_runs_for_code_label<'a>(
15214 label: &'a CodeLabel,
15215 syntax_theme: &'a theme::SyntaxTheme,
15216) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15217 let fade_out = HighlightStyle {
15218 fade_out: Some(0.35),
15219 ..Default::default()
15220 };
15221
15222 let mut prev_end = label.filter_range.end;
15223 label
15224 .runs
15225 .iter()
15226 .enumerate()
15227 .flat_map(move |(ix, (range, highlight_id))| {
15228 let style = if let Some(style) = highlight_id.style(syntax_theme) {
15229 style
15230 } else {
15231 return Default::default();
15232 };
15233 let mut muted_style = style;
15234 muted_style.highlight(fade_out);
15235
15236 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15237 if range.start >= label.filter_range.end {
15238 if range.start > prev_end {
15239 runs.push((prev_end..range.start, fade_out));
15240 }
15241 runs.push((range.clone(), muted_style));
15242 } else if range.end <= label.filter_range.end {
15243 runs.push((range.clone(), style));
15244 } else {
15245 runs.push((range.start..label.filter_range.end, style));
15246 runs.push((label.filter_range.end..range.end, muted_style));
15247 }
15248 prev_end = cmp::max(prev_end, range.end);
15249
15250 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15251 runs.push((prev_end..label.text.len(), fade_out));
15252 }
15253
15254 runs
15255 })
15256}
15257
15258pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15259 let mut prev_index = 0;
15260 let mut prev_codepoint: Option<char> = None;
15261 text.char_indices()
15262 .chain([(text.len(), '\0')])
15263 .filter_map(move |(index, codepoint)| {
15264 let prev_codepoint = prev_codepoint.replace(codepoint)?;
15265 let is_boundary = index == text.len()
15266 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15267 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15268 if is_boundary {
15269 let chunk = &text[prev_index..index];
15270 prev_index = index;
15271 Some(chunk)
15272 } else {
15273 None
15274 }
15275 })
15276}
15277
15278pub trait RangeToAnchorExt: Sized {
15279 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15280
15281 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15282 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15283 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15284 }
15285}
15286
15287impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15288 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15289 let start_offset = self.start.to_offset(snapshot);
15290 let end_offset = self.end.to_offset(snapshot);
15291 if start_offset == end_offset {
15292 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15293 } else {
15294 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15295 }
15296 }
15297}
15298
15299pub trait RowExt {
15300 fn as_f32(&self) -> f32;
15301
15302 fn next_row(&self) -> Self;
15303
15304 fn previous_row(&self) -> Self;
15305
15306 fn minus(&self, other: Self) -> u32;
15307}
15308
15309impl RowExt for DisplayRow {
15310 fn as_f32(&self) -> f32 {
15311 self.0 as f32
15312 }
15313
15314 fn next_row(&self) -> Self {
15315 Self(self.0 + 1)
15316 }
15317
15318 fn previous_row(&self) -> Self {
15319 Self(self.0.saturating_sub(1))
15320 }
15321
15322 fn minus(&self, other: Self) -> u32 {
15323 self.0 - other.0
15324 }
15325}
15326
15327impl RowExt for MultiBufferRow {
15328 fn as_f32(&self) -> f32 {
15329 self.0 as f32
15330 }
15331
15332 fn next_row(&self) -> Self {
15333 Self(self.0 + 1)
15334 }
15335
15336 fn previous_row(&self) -> Self {
15337 Self(self.0.saturating_sub(1))
15338 }
15339
15340 fn minus(&self, other: Self) -> u32 {
15341 self.0 - other.0
15342 }
15343}
15344
15345trait RowRangeExt {
15346 type Row;
15347
15348 fn len(&self) -> usize;
15349
15350 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15351}
15352
15353impl RowRangeExt for Range<MultiBufferRow> {
15354 type Row = MultiBufferRow;
15355
15356 fn len(&self) -> usize {
15357 (self.end.0 - self.start.0) as usize
15358 }
15359
15360 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15361 (self.start.0..self.end.0).map(MultiBufferRow)
15362 }
15363}
15364
15365impl RowRangeExt for Range<DisplayRow> {
15366 type Row = DisplayRow;
15367
15368 fn len(&self) -> usize {
15369 (self.end.0 - self.start.0) as usize
15370 }
15371
15372 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15373 (self.start.0..self.end.0).map(DisplayRow)
15374 }
15375}
15376
15377fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15378 if hunk.diff_base_byte_range.is_empty() {
15379 DiffHunkStatus::Added
15380 } else if hunk.row_range.is_empty() {
15381 DiffHunkStatus::Removed
15382 } else {
15383 DiffHunkStatus::Modified
15384 }
15385}
15386
15387/// If select range has more than one line, we
15388/// just point the cursor to range.start.
15389fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15390 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15391 range
15392 } else {
15393 range.start..range.start
15394 }
15395}
15396
15397pub struct KillRing(ClipboardItem);
15398impl Global for KillRing {}
15399
15400const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);