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;
19pub mod display_map;
20mod editor_settings;
21mod editor_settings_controls;
22mod element;
23mod git;
24mod highlight_matching_bracket;
25mod hover_links;
26mod hover_popover;
27mod hunk_diff;
28mod indent_guides;
29mod inlay_hint_cache;
30pub mod items;
31mod linked_editing_ranges;
32mod lsp_ext;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod proposed_changes_editor;
37mod rust_analyzer_ext;
38pub mod scroll;
39mod selections_collection;
40pub mod tasks;
41
42#[cfg(test)]
43mod editor_tests;
44#[cfg(test)]
45mod inline_completion_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50use ::git::diff::DiffHunkStatus;
51pub(crate) use actions::*;
52pub use actions::{OpenExcerpts, OpenExcerptsSplit};
53use aho_corasick::AhoCorasick;
54use anyhow::{anyhow, Context as _, Result};
55use blink_manager::BlinkManager;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{
63 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
64};
65pub use editor_settings_controls::*;
66use element::LineWithInvisibles;
67pub use element::{
68 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
69};
70use futures::{future, FutureExt};
71use fuzzy::{StringMatch, StringMatchCandidate};
72use git::blame::GitBlame;
73use gpui::{
74 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
75 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
76 ClipboardItem, Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent,
77 FocusableView, FontId, FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext,
78 ListSizingBehavior, Model, ModelContext, MouseButton, PaintQuad, ParentElement, Pixels, Render,
79 ScrollStrategy, SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task,
80 TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, View,
81 ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle, WeakView, WindowContext,
82};
83use highlight_matching_bracket::refresh_matching_bracket_highlights;
84use hover_popover::{hide_hover, HoverState};
85pub(crate) use hunk_diff::HoveredHunk;
86use hunk_diff::{diff_hunk_to_display, DiffMap, DiffMapSnapshot};
87use indent_guides::ActiveIndentGuidesState;
88use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
89pub use inline_completion::Direction;
90use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
91pub use items::MAX_TAB_TITLE_LEN;
92use itertools::Itertools;
93use language::{
94 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
95 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
96 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
97 Point, Selection, SelectionGoal, TransactionId,
98};
99use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
100use linked_editing_ranges::refresh_linked_ranges;
101pub use proposed_changes_editor::{
102 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
103};
104use similar::{ChangeTag, TextDiff};
105use std::iter::Peekable;
106use task::{ResolvedTask, TaskTemplate, TaskVariables};
107
108use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
109pub use lsp::CompletionContext;
110use lsp::{
111 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
112 LanguageServerId, LanguageServerName,
113};
114use mouse_context_menu::MouseContextMenu;
115use movement::TextLayoutDetails;
116pub use multi_buffer::{
117 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
118 ToPoint,
119};
120use multi_buffer::{
121 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
122};
123use ordered_float::OrderedFloat;
124use parking_lot::RwLock;
125use project::{
126 lsp_store::{FormatTarget, FormatTrigger},
127 project_settings::{GitGutterSetting, ProjectSettings},
128 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
129 Project, ProjectItem, ProjectTransaction, TaskSourceKind,
130};
131use rand::prelude::*;
132use rpc::{proto::*, ErrorExt};
133use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
134use selections_collection::{
135 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
136};
137use serde::{Deserialize, Serialize};
138use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
139use smallvec::SmallVec;
140use snippet::Snippet;
141use std::{
142 any::TypeId,
143 borrow::Cow,
144 cell::{Cell, RefCell},
145 cmp::{self, Ordering, Reverse},
146 mem,
147 num::NonZeroU32,
148 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
149 path::{Path, PathBuf},
150 rc::Rc,
151 sync::Arc,
152 time::{Duration, Instant},
153};
154pub use sum_tree::Bias;
155use sum_tree::TreeMap;
156use text::{BufferId, OffsetUtf16, Rope};
157use theme::{
158 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
159 ThemeColors, ThemeSettings,
160};
161use ui::{
162 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
163 ListItem, Popover, PopoverMenuHandle, Tooltip,
164};
165use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
166use workspace::item::{ItemHandle, PreviewTabsSettings};
167use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
168use workspace::{
169 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
170};
171use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
172
173use crate::hover_links::find_url;
174use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
175
176pub const FILE_HEADER_HEIGHT: u32 = 2;
177pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
178pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
179pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
180const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
181const MAX_LINE_LEN: usize = 1024;
182const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
183const MAX_SELECTION_HISTORY_LEN: usize = 1024;
184pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
185#[doc(hidden)]
186pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
187#[doc(hidden)]
188pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
189
190pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
191pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
192
193pub fn render_parsed_markdown(
194 element_id: impl Into<ElementId>,
195 parsed: &language::ParsedMarkdown,
196 editor_style: &EditorStyle,
197 workspace: Option<WeakView<Workspace>>,
198 cx: &mut WindowContext,
199) -> InteractiveText {
200 let code_span_background_color = cx
201 .theme()
202 .colors()
203 .editor_document_highlight_read_background;
204
205 let highlights = gpui::combine_highlights(
206 parsed.highlights.iter().filter_map(|(range, highlight)| {
207 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
208 Some((range.clone(), highlight))
209 }),
210 parsed
211 .regions
212 .iter()
213 .zip(&parsed.region_ranges)
214 .filter_map(|(region, range)| {
215 if region.code {
216 Some((
217 range.clone(),
218 HighlightStyle {
219 background_color: Some(code_span_background_color),
220 ..Default::default()
221 },
222 ))
223 } else {
224 None
225 }
226 }),
227 );
228
229 let mut links = Vec::new();
230 let mut link_ranges = Vec::new();
231 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
232 if let Some(link) = region.link.clone() {
233 links.push(link);
234 link_ranges.push(range.clone());
235 }
236 }
237
238 InteractiveText::new(
239 element_id,
240 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
241 )
242 .on_click(link_ranges, move |clicked_range_ix, cx| {
243 match &links[clicked_range_ix] {
244 markdown::Link::Web { url } => cx.open_url(url),
245 markdown::Link::Path { path } => {
246 if let Some(workspace) = &workspace {
247 _ = workspace.update(cx, |workspace, cx| {
248 workspace.open_abs_path(path.clone(), false, cx).detach();
249 });
250 }
251 }
252 }
253 })
254}
255
256#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
257pub(crate) enum InlayId {
258 Suggestion(usize),
259 Hint(usize),
260}
261
262impl InlayId {
263 fn id(&self) -> usize {
264 match self {
265 Self::Suggestion(id) => *id,
266 Self::Hint(id) => *id,
267 }
268 }
269}
270
271enum DiffRowHighlight {}
272enum DocumentHighlightRead {}
273enum DocumentHighlightWrite {}
274enum InputComposition {}
275
276#[derive(Debug, Copy, Clone, PartialEq, Eq)]
277pub enum Navigated {
278 Yes,
279 No,
280}
281
282impl Navigated {
283 pub fn from_bool(yes: bool) -> Navigated {
284 if yes {
285 Navigated::Yes
286 } else {
287 Navigated::No
288 }
289 }
290}
291
292pub fn init_settings(cx: &mut AppContext) {
293 EditorSettings::register(cx);
294}
295
296pub fn init(cx: &mut AppContext) {
297 init_settings(cx);
298
299 workspace::register_project_item::<Editor>(cx);
300 workspace::FollowableViewRegistry::register::<Editor>(cx);
301 workspace::register_serializable_item::<Editor>(cx);
302
303 cx.observe_new_views(
304 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
305 workspace.register_action(Editor::new_file);
306 workspace.register_action(Editor::new_file_vertical);
307 workspace.register_action(Editor::new_file_horizontal);
308 },
309 )
310 .detach();
311
312 cx.on_action(move |_: &workspace::NewFile, cx| {
313 let app_state = workspace::AppState::global(cx);
314 if let Some(app_state) = app_state.upgrade() {
315 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
316 Editor::new_file(workspace, &Default::default(), cx)
317 })
318 .detach();
319 }
320 });
321 cx.on_action(move |_: &workspace::NewWindow, cx| {
322 let app_state = workspace::AppState::global(cx);
323 if let Some(app_state) = app_state.upgrade() {
324 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
325 Editor::new_file(workspace, &Default::default(), cx)
326 })
327 .detach();
328 }
329 });
330 git::project_diff::init(cx);
331}
332
333pub struct SearchWithinRange;
334
335trait InvalidationRegion {
336 fn ranges(&self) -> &[Range<Anchor>];
337}
338
339#[derive(Clone, Debug, PartialEq)]
340pub enum SelectPhase {
341 Begin {
342 position: DisplayPoint,
343 add: bool,
344 click_count: usize,
345 },
346 BeginColumnar {
347 position: DisplayPoint,
348 reset: bool,
349 goal_column: u32,
350 },
351 Extend {
352 position: DisplayPoint,
353 click_count: usize,
354 },
355 Update {
356 position: DisplayPoint,
357 goal_column: u32,
358 scroll_delta: gpui::Point<f32>,
359 },
360 End,
361}
362
363#[derive(Clone, Debug)]
364pub enum SelectMode {
365 Character,
366 Word(Range<Anchor>),
367 Line(Range<Anchor>),
368 All,
369}
370
371#[derive(Copy, Clone, PartialEq, Eq, Debug)]
372pub enum EditorMode {
373 SingleLine { auto_width: bool },
374 AutoHeight { max_lines: usize },
375 Full,
376}
377
378#[derive(Copy, Clone, Debug)]
379pub enum SoftWrap {
380 /// Prefer not to wrap at all.
381 ///
382 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
383 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
384 GitDiff,
385 /// Prefer a single line generally, unless an overly long line is encountered.
386 None,
387 /// Soft wrap lines that exceed the editor width.
388 EditorWidth,
389 /// Soft wrap lines at the preferred line length.
390 Column(u32),
391 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
392 Bounded(u32),
393}
394
395#[derive(Clone)]
396pub struct EditorStyle {
397 pub background: Hsla,
398 pub local_player: PlayerColor,
399 pub text: TextStyle,
400 pub scrollbar_width: Pixels,
401 pub syntax: Arc<SyntaxTheme>,
402 pub status: StatusColors,
403 pub inlay_hints_style: HighlightStyle,
404 pub suggestions_style: HighlightStyle,
405 pub unnecessary_code_fade: f32,
406}
407
408impl Default for EditorStyle {
409 fn default() -> Self {
410 Self {
411 background: Hsla::default(),
412 local_player: PlayerColor::default(),
413 text: TextStyle::default(),
414 scrollbar_width: Pixels::default(),
415 syntax: Default::default(),
416 // HACK: Status colors don't have a real default.
417 // We should look into removing the status colors from the editor
418 // style and retrieve them directly from the theme.
419 status: StatusColors::dark(),
420 inlay_hints_style: HighlightStyle::default(),
421 suggestions_style: HighlightStyle::default(),
422 unnecessary_code_fade: Default::default(),
423 }
424 }
425}
426
427pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
428 let show_background = language_settings::language_settings(None, None, cx)
429 .inlay_hints
430 .show_background;
431
432 HighlightStyle {
433 color: Some(cx.theme().status().hint),
434 background_color: show_background.then(|| cx.theme().status().hint_background),
435 ..HighlightStyle::default()
436 }
437}
438
439type CompletionId = usize;
440
441enum InlineCompletion {
442 Edit(Vec<(Range<Anchor>, String)>),
443 Move(Anchor),
444}
445
446struct InlineCompletionState {
447 inlay_ids: Vec<InlayId>,
448 completion: InlineCompletion,
449 invalidation_range: Range<Anchor>,
450}
451
452enum InlineCompletionHighlight {}
453
454#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
455struct EditorActionId(usize);
456
457impl EditorActionId {
458 pub fn post_inc(&mut self) -> Self {
459 let answer = self.0;
460
461 *self = Self(answer + 1);
462
463 Self(answer)
464 }
465}
466
467// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
468// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
469
470type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
471type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
472
473#[derive(Default)]
474struct ScrollbarMarkerState {
475 scrollbar_size: Size<Pixels>,
476 dirty: bool,
477 markers: Arc<[PaintQuad]>,
478 pending_refresh: Option<Task<Result<()>>>,
479}
480
481impl ScrollbarMarkerState {
482 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
483 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
484 }
485}
486
487#[derive(Clone, Debug)]
488struct RunnableTasks {
489 templates: Vec<(TaskSourceKind, TaskTemplate)>,
490 offset: MultiBufferOffset,
491 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
492 column: u32,
493 // Values of all named captures, including those starting with '_'
494 extra_variables: HashMap<String, String>,
495 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
496 context_range: Range<BufferOffset>,
497}
498
499impl RunnableTasks {
500 fn resolve<'a>(
501 &'a self,
502 cx: &'a task::TaskContext,
503 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
504 self.templates.iter().filter_map(|(kind, template)| {
505 template
506 .resolve_task(&kind.to_id_base(), cx)
507 .map(|task| (kind.clone(), task))
508 })
509 }
510}
511
512#[derive(Clone)]
513struct ResolvedTasks {
514 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
515 position: Anchor,
516}
517#[derive(Copy, Clone, Debug)]
518struct MultiBufferOffset(usize);
519#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
520struct BufferOffset(usize);
521
522// Addons allow storing per-editor state in other crates (e.g. Vim)
523pub trait Addon: 'static {
524 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
525
526 fn to_any(&self) -> &dyn std::any::Any;
527}
528
529#[derive(Debug, Copy, Clone, PartialEq, Eq)]
530pub enum IsVimMode {
531 Yes,
532 No,
533}
534
535/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
536///
537/// See the [module level documentation](self) for more information.
538pub struct Editor {
539 focus_handle: FocusHandle,
540 last_focused_descendant: Option<WeakFocusHandle>,
541 /// The text buffer being edited
542 buffer: Model<MultiBuffer>,
543 /// Map of how text in the buffer should be displayed.
544 /// Handles soft wraps, folds, fake inlay text insertions, etc.
545 pub display_map: Model<DisplayMap>,
546 pub selections: SelectionsCollection,
547 pub scroll_manager: ScrollManager,
548 /// When inline assist editors are linked, they all render cursors because
549 /// typing enters text into each of them, even the ones that aren't focused.
550 pub(crate) show_cursor_when_unfocused: bool,
551 columnar_selection_tail: Option<Anchor>,
552 add_selections_state: Option<AddSelectionsState>,
553 select_next_state: Option<SelectNextState>,
554 select_prev_state: Option<SelectNextState>,
555 selection_history: SelectionHistory,
556 autoclose_regions: Vec<AutocloseRegion>,
557 snippet_stack: InvalidationStack<SnippetState>,
558 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
559 ime_transaction: Option<TransactionId>,
560 active_diagnostics: Option<ActiveDiagnosticGroup>,
561 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
562
563 project: Option<Model<Project>>,
564 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
565 completion_provider: Option<Box<dyn CompletionProvider>>,
566 collaboration_hub: Option<Box<dyn CollaborationHub>>,
567 blink_manager: Model<BlinkManager>,
568 show_cursor_names: bool,
569 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
570 pub show_local_selections: bool,
571 mode: EditorMode,
572 show_breadcrumbs: bool,
573 show_gutter: bool,
574 show_line_numbers: Option<bool>,
575 use_relative_line_numbers: Option<bool>,
576 show_git_diff_gutter: Option<bool>,
577 show_code_actions: Option<bool>,
578 show_runnables: Option<bool>,
579 show_wrap_guides: Option<bool>,
580 show_indent_guides: Option<bool>,
581 placeholder_text: Option<Arc<str>>,
582 highlight_order: usize,
583 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
584 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
585 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
586 scrollbar_marker_state: ScrollbarMarkerState,
587 active_indent_guides_state: ActiveIndentGuidesState,
588 nav_history: Option<ItemNavHistory>,
589 context_menu: RwLock<Option<ContextMenu>>,
590 mouse_context_menu: Option<MouseContextMenu>,
591 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
592 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
593 signature_help_state: SignatureHelpState,
594 auto_signature_help: Option<bool>,
595 find_all_references_task_sources: Vec<Anchor>,
596 next_completion_id: CompletionId,
597 available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
598 code_actions_task: Option<Task<Result<()>>>,
599 document_highlights_task: Option<Task<()>>,
600 linked_editing_range_task: Option<Task<Option<()>>>,
601 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
602 pending_rename: Option<RenameState>,
603 searchable: bool,
604 cursor_shape: CursorShape,
605 current_line_highlight: Option<CurrentLineHighlight>,
606 collapse_matches: bool,
607 autoindent_mode: Option<AutoindentMode>,
608 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
609 input_enabled: bool,
610 use_modal_editing: bool,
611 read_only: bool,
612 leader_peer_id: Option<PeerId>,
613 remote_id: Option<ViewId>,
614 hover_state: HoverState,
615 gutter_hovered: bool,
616 hovered_link_state: Option<HoveredLinkState>,
617 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
618 code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
619 active_inline_completion: Option<InlineCompletionState>,
620 // enable_inline_completions is a switch that Vim can use to disable
621 // inline completions based on its mode.
622 enable_inline_completions: bool,
623 show_inline_completions_override: Option<bool>,
624 inlay_hint_cache: InlayHintCache,
625 diff_map: DiffMap,
626 next_inlay_id: usize,
627 _subscriptions: Vec<Subscription>,
628 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
629 gutter_dimensions: GutterDimensions,
630 style: Option<EditorStyle>,
631 text_style_refinement: Option<TextStyleRefinement>,
632 next_editor_action_id: EditorActionId,
633 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
634 use_autoclose: bool,
635 use_auto_surround: bool,
636 auto_replace_emoji_shortcode: bool,
637 show_git_blame_gutter: bool,
638 show_git_blame_inline: bool,
639 show_git_blame_inline_delay_task: Option<Task<()>>,
640 git_blame_inline_enabled: bool,
641 serialize_dirty_buffers: bool,
642 show_selection_menu: Option<bool>,
643 blame: Option<Model<GitBlame>>,
644 blame_subscription: Option<Subscription>,
645 custom_context_menu: Option<
646 Box<
647 dyn 'static
648 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
649 >,
650 >,
651 last_bounds: Option<Bounds<Pixels>>,
652 expect_bounds_change: Option<Bounds<Pixels>>,
653 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
654 tasks_update_task: Option<Task<()>>,
655 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
656 breadcrumb_header: Option<String>,
657 focused_block: Option<FocusedBlock>,
658 next_scroll_position: NextScrollCursorCenterTopBottom,
659 addons: HashMap<TypeId, Box<dyn Addon>>,
660 _scroll_cursor_center_top_bottom_task: Task<()>,
661}
662
663#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
664enum NextScrollCursorCenterTopBottom {
665 #[default]
666 Center,
667 Top,
668 Bottom,
669}
670
671impl NextScrollCursorCenterTopBottom {
672 fn next(&self) -> Self {
673 match self {
674 Self::Center => Self::Top,
675 Self::Top => Self::Bottom,
676 Self::Bottom => Self::Center,
677 }
678 }
679}
680
681#[derive(Clone)]
682pub struct EditorSnapshot {
683 pub mode: EditorMode,
684 show_gutter: bool,
685 show_line_numbers: Option<bool>,
686 show_git_diff_gutter: Option<bool>,
687 show_code_actions: Option<bool>,
688 show_runnables: Option<bool>,
689 git_blame_gutter_max_author_length: Option<usize>,
690 pub display_snapshot: DisplaySnapshot,
691 pub placeholder_text: Option<Arc<str>>,
692 diff_map: DiffMapSnapshot,
693 is_focused: bool,
694 scroll_anchor: ScrollAnchor,
695 ongoing_scroll: OngoingScroll,
696 current_line_highlight: CurrentLineHighlight,
697 gutter_hovered: bool,
698}
699
700const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
701
702#[derive(Default, Debug, Clone, Copy)]
703pub struct GutterDimensions {
704 pub left_padding: Pixels,
705 pub right_padding: Pixels,
706 pub width: Pixels,
707 pub margin: Pixels,
708 pub git_blame_entries_width: Option<Pixels>,
709}
710
711impl GutterDimensions {
712 /// The full width of the space taken up by the gutter.
713 pub fn full_width(&self) -> Pixels {
714 self.margin + self.width
715 }
716
717 /// The width of the space reserved for the fold indicators,
718 /// use alongside 'justify_end' and `gutter_width` to
719 /// right align content with the line numbers
720 pub fn fold_area_width(&self) -> Pixels {
721 self.margin + self.right_padding
722 }
723}
724
725#[derive(Debug)]
726pub struct RemoteSelection {
727 pub replica_id: ReplicaId,
728 pub selection: Selection<Anchor>,
729 pub cursor_shape: CursorShape,
730 pub peer_id: PeerId,
731 pub line_mode: bool,
732 pub participant_index: Option<ParticipantIndex>,
733 pub user_name: Option<SharedString>,
734}
735
736#[derive(Clone, Debug)]
737struct SelectionHistoryEntry {
738 selections: Arc<[Selection<Anchor>]>,
739 select_next_state: Option<SelectNextState>,
740 select_prev_state: Option<SelectNextState>,
741 add_selections_state: Option<AddSelectionsState>,
742}
743
744enum SelectionHistoryMode {
745 Normal,
746 Undoing,
747 Redoing,
748}
749
750#[derive(Clone, PartialEq, Eq, Hash)]
751struct HoveredCursor {
752 replica_id: u16,
753 selection_id: usize,
754}
755
756impl Default for SelectionHistoryMode {
757 fn default() -> Self {
758 Self::Normal
759 }
760}
761
762#[derive(Default)]
763struct SelectionHistory {
764 #[allow(clippy::type_complexity)]
765 selections_by_transaction:
766 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
767 mode: SelectionHistoryMode,
768 undo_stack: VecDeque<SelectionHistoryEntry>,
769 redo_stack: VecDeque<SelectionHistoryEntry>,
770}
771
772impl SelectionHistory {
773 fn insert_transaction(
774 &mut self,
775 transaction_id: TransactionId,
776 selections: Arc<[Selection<Anchor>]>,
777 ) {
778 self.selections_by_transaction
779 .insert(transaction_id, (selections, None));
780 }
781
782 #[allow(clippy::type_complexity)]
783 fn transaction(
784 &self,
785 transaction_id: TransactionId,
786 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
787 self.selections_by_transaction.get(&transaction_id)
788 }
789
790 #[allow(clippy::type_complexity)]
791 fn transaction_mut(
792 &mut self,
793 transaction_id: TransactionId,
794 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
795 self.selections_by_transaction.get_mut(&transaction_id)
796 }
797
798 fn push(&mut self, entry: SelectionHistoryEntry) {
799 if !entry.selections.is_empty() {
800 match self.mode {
801 SelectionHistoryMode::Normal => {
802 self.push_undo(entry);
803 self.redo_stack.clear();
804 }
805 SelectionHistoryMode::Undoing => self.push_redo(entry),
806 SelectionHistoryMode::Redoing => self.push_undo(entry),
807 }
808 }
809 }
810
811 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
812 if self
813 .undo_stack
814 .back()
815 .map_or(true, |e| e.selections != entry.selections)
816 {
817 self.undo_stack.push_back(entry);
818 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
819 self.undo_stack.pop_front();
820 }
821 }
822 }
823
824 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
825 if self
826 .redo_stack
827 .back()
828 .map_or(true, |e| e.selections != entry.selections)
829 {
830 self.redo_stack.push_back(entry);
831 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
832 self.redo_stack.pop_front();
833 }
834 }
835 }
836}
837
838struct RowHighlight {
839 index: usize,
840 range: Range<Anchor>,
841 color: Hsla,
842 should_autoscroll: bool,
843}
844
845#[derive(Clone, Debug)]
846struct AddSelectionsState {
847 above: bool,
848 stack: Vec<usize>,
849}
850
851#[derive(Clone)]
852struct SelectNextState {
853 query: AhoCorasick,
854 wordwise: bool,
855 done: bool,
856}
857
858impl std::fmt::Debug for SelectNextState {
859 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
860 f.debug_struct(std::any::type_name::<Self>())
861 .field("wordwise", &self.wordwise)
862 .field("done", &self.done)
863 .finish()
864 }
865}
866
867#[derive(Debug)]
868struct AutocloseRegion {
869 selection_id: usize,
870 range: Range<Anchor>,
871 pair: BracketPair,
872}
873
874#[derive(Debug)]
875struct SnippetState {
876 ranges: Vec<Vec<Range<Anchor>>>,
877 active_index: usize,
878 choices: Vec<Option<Vec<String>>>,
879}
880
881#[doc(hidden)]
882pub struct RenameState {
883 pub range: Range<Anchor>,
884 pub old_name: Arc<str>,
885 pub editor: View<Editor>,
886 block_id: CustomBlockId,
887}
888
889struct InvalidationStack<T>(Vec<T>);
890
891struct RegisteredInlineCompletionProvider {
892 provider: Arc<dyn InlineCompletionProviderHandle>,
893 _subscription: Subscription,
894}
895
896enum ContextMenu {
897 Completions(CompletionsMenu),
898 CodeActions(CodeActionsMenu),
899}
900
901impl ContextMenu {
902 fn select_first(
903 &mut self,
904 provider: Option<&dyn CompletionProvider>,
905 cx: &mut ViewContext<Editor>,
906 ) -> bool {
907 if self.visible() {
908 match self {
909 ContextMenu::Completions(menu) => menu.select_first(provider, cx),
910 ContextMenu::CodeActions(menu) => menu.select_first(cx),
911 }
912 true
913 } else {
914 false
915 }
916 }
917
918 fn select_prev(
919 &mut self,
920 provider: Option<&dyn CompletionProvider>,
921 cx: &mut ViewContext<Editor>,
922 ) -> bool {
923 if self.visible() {
924 match self {
925 ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
926 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
927 }
928 true
929 } else {
930 false
931 }
932 }
933
934 fn select_next(
935 &mut self,
936 provider: Option<&dyn CompletionProvider>,
937 cx: &mut ViewContext<Editor>,
938 ) -> bool {
939 if self.visible() {
940 match self {
941 ContextMenu::Completions(menu) => menu.select_next(provider, cx),
942 ContextMenu::CodeActions(menu) => menu.select_next(cx),
943 }
944 true
945 } else {
946 false
947 }
948 }
949
950 fn select_last(
951 &mut self,
952 provider: Option<&dyn CompletionProvider>,
953 cx: &mut ViewContext<Editor>,
954 ) -> bool {
955 if self.visible() {
956 match self {
957 ContextMenu::Completions(menu) => menu.select_last(provider, cx),
958 ContextMenu::CodeActions(menu) => menu.select_last(cx),
959 }
960 true
961 } else {
962 false
963 }
964 }
965
966 fn visible(&self) -> bool {
967 match self {
968 ContextMenu::Completions(menu) => menu.visible(),
969 ContextMenu::CodeActions(menu) => menu.visible(),
970 }
971 }
972
973 fn render(
974 &self,
975 cursor_position: DisplayPoint,
976 style: &EditorStyle,
977 max_height: Pixels,
978 workspace: Option<WeakView<Workspace>>,
979 cx: &mut ViewContext<Editor>,
980 ) -> (ContextMenuOrigin, AnyElement) {
981 match self {
982 ContextMenu::Completions(menu) => (
983 ContextMenuOrigin::EditorPoint(cursor_position),
984 menu.render(style, max_height, workspace, cx),
985 ),
986 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
987 }
988 }
989}
990
991enum ContextMenuOrigin {
992 EditorPoint(DisplayPoint),
993 GutterIndicator(DisplayRow),
994}
995
996#[derive(Clone, Debug)]
997struct CompletionsMenu {
998 id: CompletionId,
999 sort_completions: bool,
1000 initial_position: Anchor,
1001 buffer: Model<Buffer>,
1002 completions: Arc<RwLock<Box<[Completion]>>>,
1003 match_candidates: Arc<[StringMatchCandidate]>,
1004 matches: Arc<[StringMatch]>,
1005 selected_item: usize,
1006 scroll_handle: UniformListScrollHandle,
1007 resolve_completions: bool,
1008 aside_was_displayed: Cell<bool>,
1009 show_completion_documentation: bool,
1010}
1011
1012impl CompletionsMenu {
1013 fn new(
1014 id: CompletionId,
1015 sort_completions: bool,
1016 show_completion_documentation: bool,
1017 initial_position: Anchor,
1018 buffer: Model<Buffer>,
1019 completions: Box<[Completion]>,
1020 aside_was_displayed: bool,
1021 ) -> Self {
1022 let match_candidates = completions
1023 .iter()
1024 .enumerate()
1025 .map(|(id, completion)| {
1026 StringMatchCandidate::new(
1027 id,
1028 completion.label.text[completion.label.filter_range.clone()].into(),
1029 )
1030 })
1031 .collect();
1032
1033 Self {
1034 id,
1035 sort_completions,
1036 initial_position,
1037 buffer,
1038 completions: Arc::new(RwLock::new(completions)),
1039 match_candidates,
1040 matches: Vec::new().into(),
1041 selected_item: 0,
1042 scroll_handle: UniformListScrollHandle::new(),
1043 resolve_completions: true,
1044 aside_was_displayed: Cell::new(aside_was_displayed),
1045 show_completion_documentation: show_completion_documentation,
1046 }
1047 }
1048
1049 fn new_snippet_choices(
1050 id: CompletionId,
1051 sort_completions: bool,
1052 choices: &Vec<String>,
1053 selection: Range<Anchor>,
1054 buffer: Model<Buffer>,
1055 ) -> Self {
1056 let completions = choices
1057 .iter()
1058 .map(|choice| Completion {
1059 old_range: selection.start.text_anchor..selection.end.text_anchor,
1060 new_text: choice.to_string(),
1061 label: CodeLabel {
1062 text: choice.to_string(),
1063 runs: Default::default(),
1064 filter_range: Default::default(),
1065 },
1066 server_id: LanguageServerId(usize::MAX),
1067 documentation: None,
1068 lsp_completion: Default::default(),
1069 confirm: None,
1070 })
1071 .collect();
1072
1073 let match_candidates = choices
1074 .iter()
1075 .enumerate()
1076 .map(|(id, completion)| StringMatchCandidate::new(id, completion.to_string()))
1077 .collect();
1078 let matches = choices
1079 .iter()
1080 .enumerate()
1081 .map(|(id, completion)| StringMatch {
1082 candidate_id: id,
1083 score: 1.,
1084 positions: vec![],
1085 string: completion.clone(),
1086 })
1087 .collect();
1088 Self {
1089 id,
1090 sort_completions,
1091 initial_position: selection.start,
1092 buffer,
1093 completions: Arc::new(RwLock::new(completions)),
1094 match_candidates,
1095 matches,
1096 selected_item: 0,
1097 scroll_handle: UniformListScrollHandle::new(),
1098 resolve_completions: false,
1099 aside_was_displayed: Cell::new(false),
1100 show_completion_documentation: false,
1101 }
1102 }
1103
1104 fn select_first(
1105 &mut self,
1106 provider: Option<&dyn CompletionProvider>,
1107 cx: &mut ViewContext<Editor>,
1108 ) {
1109 self.selected_item = 0;
1110 self.scroll_handle
1111 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1112 self.resolve_selected_completion(provider, cx);
1113 cx.notify();
1114 }
1115
1116 fn select_prev(
1117 &mut self,
1118 provider: Option<&dyn CompletionProvider>,
1119 cx: &mut ViewContext<Editor>,
1120 ) {
1121 if self.selected_item > 0 {
1122 self.selected_item -= 1;
1123 } else {
1124 self.selected_item = self.matches.len() - 1;
1125 }
1126 self.scroll_handle
1127 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1128 self.resolve_selected_completion(provider, cx);
1129 cx.notify();
1130 }
1131
1132 fn select_next(
1133 &mut self,
1134 provider: Option<&dyn CompletionProvider>,
1135 cx: &mut ViewContext<Editor>,
1136 ) {
1137 if self.selected_item + 1 < self.matches.len() {
1138 self.selected_item += 1;
1139 } else {
1140 self.selected_item = 0;
1141 }
1142 self.scroll_handle
1143 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1144 self.resolve_selected_completion(provider, cx);
1145 cx.notify();
1146 }
1147
1148 fn select_last(
1149 &mut self,
1150 provider: Option<&dyn CompletionProvider>,
1151 cx: &mut ViewContext<Editor>,
1152 ) {
1153 self.selected_item = self.matches.len() - 1;
1154 self.scroll_handle
1155 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1156 self.resolve_selected_completion(provider, cx);
1157 cx.notify();
1158 }
1159
1160 fn resolve_selected_completion(
1161 &mut self,
1162 provider: Option<&dyn CompletionProvider>,
1163 cx: &mut ViewContext<Editor>,
1164 ) {
1165 if !self.resolve_completions {
1166 return;
1167 }
1168 let Some(provider) = provider else {
1169 return;
1170 };
1171
1172 let completion_index = self.matches[self.selected_item].candidate_id;
1173 let resolve_task = provider.resolve_completions(
1174 self.buffer.clone(),
1175 vec![completion_index],
1176 self.completions.clone(),
1177 cx,
1178 );
1179
1180 cx.spawn(move |editor, mut cx| async move {
1181 if let Some(true) = resolve_task.await.log_err() {
1182 editor.update(&mut cx, |_, cx| cx.notify()).ok();
1183 }
1184 })
1185 .detach();
1186 }
1187
1188 fn visible(&self) -> bool {
1189 !self.matches.is_empty()
1190 }
1191
1192 fn render(
1193 &self,
1194 style: &EditorStyle,
1195 max_height: Pixels,
1196 workspace: Option<WeakView<Workspace>>,
1197 cx: &mut ViewContext<Editor>,
1198 ) -> AnyElement {
1199 let show_completion_documentation = self.show_completion_documentation;
1200 let widest_completion_ix = self
1201 .matches
1202 .iter()
1203 .enumerate()
1204 .max_by_key(|(_, mat)| {
1205 let completions = self.completions.read();
1206 let completion = &completions[mat.candidate_id];
1207 let documentation = &completion.documentation;
1208
1209 let mut len = completion.label.text.chars().count();
1210 if let Some(Documentation::SingleLine(text)) = documentation {
1211 if show_completion_documentation {
1212 len += text.chars().count();
1213 }
1214 }
1215
1216 len
1217 })
1218 .map(|(ix, _)| ix);
1219
1220 let completions = self.completions.clone();
1221 let matches = self.matches.clone();
1222 let selected_item = self.selected_item;
1223 let style = style.clone();
1224
1225 let multiline_docs = if show_completion_documentation {
1226 let mat = &self.matches[selected_item];
1227 match &self.completions.read()[mat.candidate_id].documentation {
1228 Some(Documentation::MultiLinePlainText(text)) => {
1229 Some(div().child(SharedString::from(text.clone())))
1230 }
1231 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1232 Some(div().child(render_parsed_markdown(
1233 "completions_markdown",
1234 parsed,
1235 &style,
1236 workspace,
1237 cx,
1238 )))
1239 }
1240 Some(Documentation::Undocumented) if self.aside_was_displayed.get() => {
1241 Some(div().child("No documentation"))
1242 }
1243 _ => None,
1244 }
1245 } else {
1246 None
1247 };
1248
1249 let aside_contents = if let Some(multiline_docs) = multiline_docs {
1250 Some(multiline_docs)
1251 } else if self.aside_was_displayed.get() {
1252 Some(div().child("Fetching documentation..."))
1253 } else {
1254 None
1255 };
1256 self.aside_was_displayed.set(aside_contents.is_some());
1257
1258 let aside_contents = aside_contents.map(|div| {
1259 div.id("multiline_docs")
1260 .max_h(max_height)
1261 .flex_1()
1262 .px_1p5()
1263 .py_1()
1264 .min_w(px(260.))
1265 .max_w(px(640.))
1266 .w(px(500.))
1267 .overflow_y_scroll()
1268 .occlude()
1269 });
1270
1271 let list = uniform_list(
1272 cx.view().clone(),
1273 "completions",
1274 matches.len(),
1275 move |_editor, range, cx| {
1276 let start_ix = range.start;
1277 let completions_guard = completions.read();
1278
1279 matches[range]
1280 .iter()
1281 .enumerate()
1282 .map(|(ix, mat)| {
1283 let item_ix = start_ix + ix;
1284 let candidate_id = mat.candidate_id;
1285 let completion = &completions_guard[candidate_id];
1286
1287 let documentation = if show_completion_documentation {
1288 &completion.documentation
1289 } else {
1290 &None
1291 };
1292
1293 let highlights = gpui::combine_highlights(
1294 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1295 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1296 |(range, mut highlight)| {
1297 // Ignore font weight for syntax highlighting, as we'll use it
1298 // for fuzzy matches.
1299 highlight.font_weight = None;
1300
1301 if completion.lsp_completion.deprecated.unwrap_or(false) {
1302 highlight.strikethrough = Some(StrikethroughStyle {
1303 thickness: 1.0.into(),
1304 ..Default::default()
1305 });
1306 highlight.color = Some(cx.theme().colors().text_muted);
1307 }
1308
1309 (range, highlight)
1310 },
1311 ),
1312 );
1313 let completion_label = StyledText::new(completion.label.text.clone())
1314 .with_highlights(&style.text, highlights);
1315 let documentation_label =
1316 if let Some(Documentation::SingleLine(text)) = documentation {
1317 if text.trim().is_empty() {
1318 None
1319 } else {
1320 Some(
1321 Label::new(text.clone())
1322 .ml_4()
1323 .size(LabelSize::Small)
1324 .color(Color::Muted),
1325 )
1326 }
1327 } else {
1328 None
1329 };
1330
1331 let color_swatch = completion
1332 .color()
1333 .map(|color| div().size_4().bg(color).rounded_sm());
1334
1335 div().min_w(px(220.)).max_w(px(540.)).child(
1336 ListItem::new(mat.candidate_id)
1337 .inset(true)
1338 .selected(item_ix == selected_item)
1339 .on_click(cx.listener(move |editor, _event, cx| {
1340 cx.stop_propagation();
1341 if let Some(task) = editor.confirm_completion(
1342 &ConfirmCompletion {
1343 item_ix: Some(item_ix),
1344 },
1345 cx,
1346 ) {
1347 task.detach_and_log_err(cx)
1348 }
1349 }))
1350 .start_slot::<Div>(color_swatch)
1351 .child(h_flex().overflow_hidden().child(completion_label))
1352 .end_slot::<Label>(documentation_label),
1353 )
1354 })
1355 .collect()
1356 },
1357 )
1358 .occlude()
1359 .max_h(max_height)
1360 .track_scroll(self.scroll_handle.clone())
1361 .with_width_from_item(widest_completion_ix)
1362 .with_sizing_behavior(ListSizingBehavior::Infer);
1363
1364 Popover::new()
1365 .child(list)
1366 .when_some(aside_contents, |popover, aside_contents| {
1367 popover.aside(aside_contents)
1368 })
1369 .into_any_element()
1370 }
1371
1372 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1373 let mut matches = if let Some(query) = query {
1374 fuzzy::match_strings(
1375 &self.match_candidates,
1376 query,
1377 query.chars().any(|c| c.is_uppercase()),
1378 100,
1379 &Default::default(),
1380 executor,
1381 )
1382 .await
1383 } else {
1384 self.match_candidates
1385 .iter()
1386 .enumerate()
1387 .map(|(candidate_id, candidate)| StringMatch {
1388 candidate_id,
1389 score: Default::default(),
1390 positions: Default::default(),
1391 string: candidate.string.clone(),
1392 })
1393 .collect()
1394 };
1395
1396 // Remove all candidates where the query's start does not match the start of any word in the candidate
1397 if let Some(query) = query {
1398 if let Some(query_start) = query.chars().next() {
1399 matches.retain(|string_match| {
1400 split_words(&string_match.string).any(|word| {
1401 // Check that the first codepoint of the word as lowercase matches the first
1402 // codepoint of the query as lowercase
1403 word.chars()
1404 .flat_map(|codepoint| codepoint.to_lowercase())
1405 .zip(query_start.to_lowercase())
1406 .all(|(word_cp, query_cp)| word_cp == query_cp)
1407 })
1408 });
1409 }
1410 }
1411
1412 let completions = self.completions.read();
1413 if self.sort_completions {
1414 matches.sort_unstable_by_key(|mat| {
1415 // We do want to strike a balance here between what the language server tells us
1416 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1417 // `Creat` and there is a local variable called `CreateComponent`).
1418 // So what we do is: we bucket all matches into two buckets
1419 // - Strong matches
1420 // - Weak matches
1421 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1422 // and the Weak matches are the rest.
1423 //
1424 // For the strong matches, we sort by our fuzzy-finder score first and for the weak
1425 // matches, we prefer language-server sort_text first.
1426 //
1427 // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
1428 // Rest of the matches(weak) can be sorted as language-server expects.
1429
1430 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1431 enum MatchScore<'a> {
1432 Strong {
1433 score: Reverse<OrderedFloat<f64>>,
1434 sort_text: Option<&'a str>,
1435 sort_key: (usize, &'a str),
1436 },
1437 Weak {
1438 sort_text: Option<&'a str>,
1439 score: Reverse<OrderedFloat<f64>>,
1440 sort_key: (usize, &'a str),
1441 },
1442 }
1443
1444 let completion = &completions[mat.candidate_id];
1445 let sort_key = completion.sort_key();
1446 let sort_text = completion.lsp_completion.sort_text.as_deref();
1447 let score = Reverse(OrderedFloat(mat.score));
1448
1449 if mat.score >= 0.2 {
1450 MatchScore::Strong {
1451 score,
1452 sort_text,
1453 sort_key,
1454 }
1455 } else {
1456 MatchScore::Weak {
1457 sort_text,
1458 score,
1459 sort_key,
1460 }
1461 }
1462 });
1463 }
1464
1465 for mat in &mut matches {
1466 let completion = &completions[mat.candidate_id];
1467 mat.string.clone_from(&completion.label.text);
1468 for position in &mut mat.positions {
1469 *position += completion.label.filter_range.start;
1470 }
1471 }
1472 drop(completions);
1473
1474 self.matches = matches.into();
1475 self.selected_item = 0;
1476 }
1477}
1478
1479#[derive(Clone)]
1480struct AvailableCodeAction {
1481 excerpt_id: ExcerptId,
1482 action: CodeAction,
1483 provider: Arc<dyn CodeActionProvider>,
1484}
1485
1486#[derive(Clone)]
1487struct CodeActionContents {
1488 tasks: Option<Arc<ResolvedTasks>>,
1489 actions: Option<Arc<[AvailableCodeAction]>>,
1490}
1491
1492impl CodeActionContents {
1493 fn len(&self) -> usize {
1494 match (&self.tasks, &self.actions) {
1495 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1496 (Some(tasks), None) => tasks.templates.len(),
1497 (None, Some(actions)) => actions.len(),
1498 (None, None) => 0,
1499 }
1500 }
1501
1502 fn is_empty(&self) -> bool {
1503 match (&self.tasks, &self.actions) {
1504 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1505 (Some(tasks), None) => tasks.templates.is_empty(),
1506 (None, Some(actions)) => actions.is_empty(),
1507 (None, None) => true,
1508 }
1509 }
1510
1511 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1512 self.tasks
1513 .iter()
1514 .flat_map(|tasks| {
1515 tasks
1516 .templates
1517 .iter()
1518 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1519 })
1520 .chain(self.actions.iter().flat_map(|actions| {
1521 actions.iter().map(|available| CodeActionsItem::CodeAction {
1522 excerpt_id: available.excerpt_id,
1523 action: available.action.clone(),
1524 provider: available.provider.clone(),
1525 })
1526 }))
1527 }
1528 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1529 match (&self.tasks, &self.actions) {
1530 (Some(tasks), Some(actions)) => {
1531 if index < tasks.templates.len() {
1532 tasks
1533 .templates
1534 .get(index)
1535 .cloned()
1536 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1537 } else {
1538 actions.get(index - tasks.templates.len()).map(|available| {
1539 CodeActionsItem::CodeAction {
1540 excerpt_id: available.excerpt_id,
1541 action: available.action.clone(),
1542 provider: available.provider.clone(),
1543 }
1544 })
1545 }
1546 }
1547 (Some(tasks), None) => tasks
1548 .templates
1549 .get(index)
1550 .cloned()
1551 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1552 (None, Some(actions)) => {
1553 actions
1554 .get(index)
1555 .map(|available| CodeActionsItem::CodeAction {
1556 excerpt_id: available.excerpt_id,
1557 action: available.action.clone(),
1558 provider: available.provider.clone(),
1559 })
1560 }
1561 (None, None) => None,
1562 }
1563 }
1564}
1565
1566#[allow(clippy::large_enum_variant)]
1567#[derive(Clone)]
1568enum CodeActionsItem {
1569 Task(TaskSourceKind, ResolvedTask),
1570 CodeAction {
1571 excerpt_id: ExcerptId,
1572 action: CodeAction,
1573 provider: Arc<dyn CodeActionProvider>,
1574 },
1575}
1576
1577impl CodeActionsItem {
1578 fn as_task(&self) -> Option<&ResolvedTask> {
1579 let Self::Task(_, task) = self else {
1580 return None;
1581 };
1582 Some(task)
1583 }
1584 fn as_code_action(&self) -> Option<&CodeAction> {
1585 let Self::CodeAction { action, .. } = self else {
1586 return None;
1587 };
1588 Some(action)
1589 }
1590 fn label(&self) -> String {
1591 match self {
1592 Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
1593 Self::Task(_, task) => task.resolved_label.clone(),
1594 }
1595 }
1596}
1597
1598struct CodeActionsMenu {
1599 actions: CodeActionContents,
1600 buffer: Model<Buffer>,
1601 selected_item: usize,
1602 scroll_handle: UniformListScrollHandle,
1603 deployed_from_indicator: Option<DisplayRow>,
1604}
1605
1606impl CodeActionsMenu {
1607 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1608 self.selected_item = 0;
1609 self.scroll_handle
1610 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1611 cx.notify()
1612 }
1613
1614 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1615 if self.selected_item > 0 {
1616 self.selected_item -= 1;
1617 } else {
1618 self.selected_item = self.actions.len() - 1;
1619 }
1620 self.scroll_handle
1621 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1622 cx.notify();
1623 }
1624
1625 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1626 if self.selected_item + 1 < self.actions.len() {
1627 self.selected_item += 1;
1628 } else {
1629 self.selected_item = 0;
1630 }
1631 self.scroll_handle
1632 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1633 cx.notify();
1634 }
1635
1636 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1637 self.selected_item = self.actions.len() - 1;
1638 self.scroll_handle
1639 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1640 cx.notify()
1641 }
1642
1643 fn visible(&self) -> bool {
1644 !self.actions.is_empty()
1645 }
1646
1647 fn render(
1648 &self,
1649 cursor_position: DisplayPoint,
1650 _style: &EditorStyle,
1651 max_height: Pixels,
1652 cx: &mut ViewContext<Editor>,
1653 ) -> (ContextMenuOrigin, AnyElement) {
1654 let actions = self.actions.clone();
1655 let selected_item = self.selected_item;
1656 let element = uniform_list(
1657 cx.view().clone(),
1658 "code_actions_menu",
1659 self.actions.len(),
1660 move |_this, range, cx| {
1661 actions
1662 .iter()
1663 .skip(range.start)
1664 .take(range.end - range.start)
1665 .enumerate()
1666 .map(|(ix, action)| {
1667 let item_ix = range.start + ix;
1668 let selected = selected_item == item_ix;
1669 let colors = cx.theme().colors();
1670 div()
1671 .px_1()
1672 .rounded_md()
1673 .text_color(colors.text)
1674 .when(selected, |style| {
1675 style
1676 .bg(colors.element_active)
1677 .text_color(colors.text_accent)
1678 })
1679 .hover(|style| {
1680 style
1681 .bg(colors.element_hover)
1682 .text_color(colors.text_accent)
1683 })
1684 .whitespace_nowrap()
1685 .when_some(action.as_code_action(), |this, action| {
1686 this.on_mouse_down(
1687 MouseButton::Left,
1688 cx.listener(move |editor, _, cx| {
1689 cx.stop_propagation();
1690 if let Some(task) = editor.confirm_code_action(
1691 &ConfirmCodeAction {
1692 item_ix: Some(item_ix),
1693 },
1694 cx,
1695 ) {
1696 task.detach_and_log_err(cx)
1697 }
1698 }),
1699 )
1700 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1701 .child(SharedString::from(
1702 action.lsp_action.title.replace("\n", ""),
1703 ))
1704 })
1705 .when_some(action.as_task(), |this, task| {
1706 this.on_mouse_down(
1707 MouseButton::Left,
1708 cx.listener(move |editor, _, cx| {
1709 cx.stop_propagation();
1710 if let Some(task) = editor.confirm_code_action(
1711 &ConfirmCodeAction {
1712 item_ix: Some(item_ix),
1713 },
1714 cx,
1715 ) {
1716 task.detach_and_log_err(cx)
1717 }
1718 }),
1719 )
1720 .child(SharedString::from(task.resolved_label.replace("\n", "")))
1721 })
1722 })
1723 .collect()
1724 },
1725 )
1726 .elevation_1(cx)
1727 .p_1()
1728 .max_h(max_height)
1729 .occlude()
1730 .track_scroll(self.scroll_handle.clone())
1731 .with_width_from_item(
1732 self.actions
1733 .iter()
1734 .enumerate()
1735 .max_by_key(|(_, action)| match action {
1736 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1737 CodeActionsItem::CodeAction { action, .. } => {
1738 action.lsp_action.title.chars().count()
1739 }
1740 })
1741 .map(|(ix, _)| ix),
1742 )
1743 .with_sizing_behavior(ListSizingBehavior::Infer)
1744 .into_any_element();
1745
1746 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1747 ContextMenuOrigin::GutterIndicator(row)
1748 } else {
1749 ContextMenuOrigin::EditorPoint(cursor_position)
1750 };
1751
1752 (cursor_position, element)
1753 }
1754}
1755
1756#[derive(Debug)]
1757struct ActiveDiagnosticGroup {
1758 primary_range: Range<Anchor>,
1759 primary_message: String,
1760 group_id: usize,
1761 blocks: HashMap<CustomBlockId, Diagnostic>,
1762 is_valid: bool,
1763}
1764
1765#[derive(Serialize, Deserialize, Clone, Debug)]
1766pub struct ClipboardSelection {
1767 pub len: usize,
1768 pub is_entire_line: bool,
1769 pub first_line_indent: u32,
1770}
1771
1772#[derive(Debug)]
1773pub(crate) struct NavigationData {
1774 cursor_anchor: Anchor,
1775 cursor_position: Point,
1776 scroll_anchor: ScrollAnchor,
1777 scroll_top_row: u32,
1778}
1779
1780#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1781pub enum GotoDefinitionKind {
1782 Symbol,
1783 Declaration,
1784 Type,
1785 Implementation,
1786}
1787
1788#[derive(Debug, Clone)]
1789enum InlayHintRefreshReason {
1790 Toggle(bool),
1791 SettingsChange(InlayHintSettings),
1792 NewLinesShown,
1793 BufferEdited(HashSet<Arc<Language>>),
1794 RefreshRequested,
1795 ExcerptsRemoved(Vec<ExcerptId>),
1796}
1797
1798impl InlayHintRefreshReason {
1799 fn description(&self) -> &'static str {
1800 match self {
1801 Self::Toggle(_) => "toggle",
1802 Self::SettingsChange(_) => "settings change",
1803 Self::NewLinesShown => "new lines shown",
1804 Self::BufferEdited(_) => "buffer edited",
1805 Self::RefreshRequested => "refresh requested",
1806 Self::ExcerptsRemoved(_) => "excerpts removed",
1807 }
1808 }
1809}
1810
1811pub(crate) struct FocusedBlock {
1812 id: BlockId,
1813 focus_handle: WeakFocusHandle,
1814}
1815
1816#[derive(Clone)]
1817struct JumpData {
1818 excerpt_id: ExcerptId,
1819 position: Point,
1820 anchor: text::Anchor,
1821 path: Option<project::ProjectPath>,
1822 line_offset_from_top: u32,
1823}
1824
1825impl Editor {
1826 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1827 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1828 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1829 Self::new(
1830 EditorMode::SingleLine { auto_width: false },
1831 buffer,
1832 None,
1833 false,
1834 cx,
1835 )
1836 }
1837
1838 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1839 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1840 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1841 Self::new(EditorMode::Full, buffer, None, false, cx)
1842 }
1843
1844 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1845 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1846 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1847 Self::new(
1848 EditorMode::SingleLine { auto_width: true },
1849 buffer,
1850 None,
1851 false,
1852 cx,
1853 )
1854 }
1855
1856 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1857 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1858 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1859 Self::new(
1860 EditorMode::AutoHeight { max_lines },
1861 buffer,
1862 None,
1863 false,
1864 cx,
1865 )
1866 }
1867
1868 pub fn for_buffer(
1869 buffer: Model<Buffer>,
1870 project: Option<Model<Project>>,
1871 cx: &mut ViewContext<Self>,
1872 ) -> Self {
1873 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1874 Self::new(EditorMode::Full, buffer, project, false, cx)
1875 }
1876
1877 pub fn for_multibuffer(
1878 buffer: Model<MultiBuffer>,
1879 project: Option<Model<Project>>,
1880 show_excerpt_controls: bool,
1881 cx: &mut ViewContext<Self>,
1882 ) -> Self {
1883 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1884 }
1885
1886 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1887 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1888 let mut clone = Self::new(
1889 self.mode,
1890 self.buffer.clone(),
1891 self.project.clone(),
1892 show_excerpt_controls,
1893 cx,
1894 );
1895 self.display_map.update(cx, |display_map, cx| {
1896 let snapshot = display_map.snapshot(cx);
1897 clone.display_map.update(cx, |display_map, cx| {
1898 display_map.set_state(&snapshot, cx);
1899 });
1900 });
1901 clone.selections.clone_state(&self.selections);
1902 clone.scroll_manager.clone_state(&self.scroll_manager);
1903 clone.searchable = self.searchable;
1904 clone
1905 }
1906
1907 pub fn new(
1908 mode: EditorMode,
1909 buffer: Model<MultiBuffer>,
1910 project: Option<Model<Project>>,
1911 show_excerpt_controls: bool,
1912 cx: &mut ViewContext<Self>,
1913 ) -> Self {
1914 let style = cx.text_style();
1915 let font_size = style.font_size.to_pixels(cx.rem_size());
1916 let editor = cx.view().downgrade();
1917 let fold_placeholder = FoldPlaceholder {
1918 constrain_width: true,
1919 render: Arc::new(move |fold_id, fold_range, cx| {
1920 let editor = editor.clone();
1921 div()
1922 .id(fold_id)
1923 .bg(cx.theme().colors().ghost_element_background)
1924 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1925 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1926 .rounded_sm()
1927 .size_full()
1928 .cursor_pointer()
1929 .child("⋯")
1930 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1931 .on_click(move |_, cx| {
1932 editor
1933 .update(cx, |editor, cx| {
1934 editor.unfold_ranges(
1935 &[fold_range.start..fold_range.end],
1936 true,
1937 false,
1938 cx,
1939 );
1940 cx.stop_propagation();
1941 })
1942 .ok();
1943 })
1944 .into_any()
1945 }),
1946 merge_adjacent: true,
1947 ..Default::default()
1948 };
1949 let display_map = cx.new_model(|cx| {
1950 DisplayMap::new(
1951 buffer.clone(),
1952 style.font(),
1953 font_size,
1954 None,
1955 show_excerpt_controls,
1956 FILE_HEADER_HEIGHT,
1957 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1958 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1959 fold_placeholder,
1960 cx,
1961 )
1962 });
1963
1964 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1965
1966 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1967
1968 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1969 .then(|| language_settings::SoftWrap::None);
1970
1971 let mut project_subscriptions = Vec::new();
1972 if mode == EditorMode::Full {
1973 if let Some(project) = project.as_ref() {
1974 if buffer.read(cx).is_singleton() {
1975 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1976 cx.emit(EditorEvent::TitleChanged);
1977 }));
1978 }
1979 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1980 if let project::Event::RefreshInlayHints = event {
1981 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1982 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1983 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1984 let focus_handle = editor.focus_handle(cx);
1985 if focus_handle.is_focused(cx) {
1986 let snapshot = buffer.read(cx).snapshot();
1987 for (range, snippet) in snippet_edits {
1988 let editor_range =
1989 language::range_from_lsp(*range).to_offset(&snapshot);
1990 editor
1991 .insert_snippet(&[editor_range], snippet.clone(), cx)
1992 .ok();
1993 }
1994 }
1995 }
1996 }
1997 }));
1998 if let Some(task_inventory) = project
1999 .read(cx)
2000 .task_store()
2001 .read(cx)
2002 .task_inventory()
2003 .cloned()
2004 {
2005 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
2006 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
2007 }));
2008 }
2009 }
2010 }
2011
2012 let buffer_snapshot = buffer.read(cx).snapshot(cx);
2013
2014 let inlay_hint_settings =
2015 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
2016 let focus_handle = cx.focus_handle();
2017 cx.on_focus(&focus_handle, Self::handle_focus).detach();
2018 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
2019 .detach();
2020 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
2021 .detach();
2022 cx.on_blur(&focus_handle, Self::handle_blur).detach();
2023
2024 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
2025 Some(false)
2026 } else {
2027 None
2028 };
2029
2030 let mut code_action_providers = Vec::new();
2031 if let Some(project) = project.clone() {
2032 get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
2033 code_action_providers.push(Arc::new(project) as Arc<_>);
2034 }
2035
2036 let mut this = Self {
2037 focus_handle,
2038 show_cursor_when_unfocused: false,
2039 last_focused_descendant: None,
2040 buffer: buffer.clone(),
2041 display_map: display_map.clone(),
2042 selections,
2043 scroll_manager: ScrollManager::new(cx),
2044 columnar_selection_tail: None,
2045 add_selections_state: None,
2046 select_next_state: None,
2047 select_prev_state: None,
2048 selection_history: Default::default(),
2049 autoclose_regions: Default::default(),
2050 snippet_stack: Default::default(),
2051 select_larger_syntax_node_stack: Vec::new(),
2052 ime_transaction: Default::default(),
2053 active_diagnostics: None,
2054 soft_wrap_mode_override,
2055 completion_provider: project.clone().map(|project| Box::new(project) as _),
2056 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
2057 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
2058 project,
2059 blink_manager: blink_manager.clone(),
2060 show_local_selections: true,
2061 mode,
2062 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
2063 show_gutter: mode == EditorMode::Full,
2064 show_line_numbers: None,
2065 use_relative_line_numbers: None,
2066 show_git_diff_gutter: None,
2067 show_code_actions: None,
2068 show_runnables: None,
2069 show_wrap_guides: None,
2070 show_indent_guides,
2071 placeholder_text: None,
2072 highlight_order: 0,
2073 highlighted_rows: HashMap::default(),
2074 background_highlights: Default::default(),
2075 gutter_highlights: TreeMap::default(),
2076 scrollbar_marker_state: ScrollbarMarkerState::default(),
2077 active_indent_guides_state: ActiveIndentGuidesState::default(),
2078 nav_history: None,
2079 context_menu: RwLock::new(None),
2080 mouse_context_menu: None,
2081 hunk_controls_menu_handle: PopoverMenuHandle::default(),
2082 completion_tasks: Default::default(),
2083 signature_help_state: SignatureHelpState::default(),
2084 auto_signature_help: None,
2085 find_all_references_task_sources: Vec::new(),
2086 next_completion_id: 0,
2087 next_inlay_id: 0,
2088 code_action_providers,
2089 available_code_actions: Default::default(),
2090 code_actions_task: Default::default(),
2091 document_highlights_task: Default::default(),
2092 linked_editing_range_task: Default::default(),
2093 pending_rename: Default::default(),
2094 searchable: true,
2095 cursor_shape: EditorSettings::get_global(cx)
2096 .cursor_shape
2097 .unwrap_or_default(),
2098 current_line_highlight: None,
2099 autoindent_mode: Some(AutoindentMode::EachLine),
2100 collapse_matches: false,
2101 workspace: None,
2102 input_enabled: true,
2103 use_modal_editing: mode == EditorMode::Full,
2104 read_only: false,
2105 use_autoclose: true,
2106 use_auto_surround: true,
2107 auto_replace_emoji_shortcode: false,
2108 leader_peer_id: None,
2109 remote_id: None,
2110 hover_state: Default::default(),
2111 hovered_link_state: Default::default(),
2112 inline_completion_provider: None,
2113 active_inline_completion: None,
2114 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
2115 diff_map: DiffMap::default(),
2116 gutter_hovered: false,
2117 pixel_position_of_newest_cursor: None,
2118 last_bounds: None,
2119 expect_bounds_change: None,
2120 gutter_dimensions: GutterDimensions::default(),
2121 style: None,
2122 show_cursor_names: false,
2123 hovered_cursors: Default::default(),
2124 next_editor_action_id: EditorActionId::default(),
2125 editor_actions: Rc::default(),
2126 show_inline_completions_override: None,
2127 enable_inline_completions: true,
2128 custom_context_menu: None,
2129 show_git_blame_gutter: false,
2130 show_git_blame_inline: false,
2131 show_selection_menu: None,
2132 show_git_blame_inline_delay_task: None,
2133 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
2134 serialize_dirty_buffers: ProjectSettings::get_global(cx)
2135 .session
2136 .restore_unsaved_buffers,
2137 blame: None,
2138 blame_subscription: None,
2139 tasks: Default::default(),
2140 _subscriptions: vec![
2141 cx.observe(&buffer, Self::on_buffer_changed),
2142 cx.subscribe(&buffer, Self::on_buffer_event),
2143 cx.observe(&display_map, Self::on_display_map_changed),
2144 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
2145 cx.observe_global::<SettingsStore>(Self::settings_changed),
2146 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
2147 cx.observe_window_activation(|editor, cx| {
2148 let active = cx.is_window_active();
2149 editor.blink_manager.update(cx, |blink_manager, cx| {
2150 if active {
2151 blink_manager.enable(cx);
2152 } else {
2153 blink_manager.disable(cx);
2154 }
2155 });
2156 }),
2157 ],
2158 tasks_update_task: None,
2159 linked_edit_ranges: Default::default(),
2160 previous_search_ranges: None,
2161 breadcrumb_header: None,
2162 focused_block: None,
2163 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
2164 addons: HashMap::default(),
2165 _scroll_cursor_center_top_bottom_task: Task::ready(()),
2166 text_style_refinement: None,
2167 };
2168 this.tasks_update_task = Some(this.refresh_runnables(cx));
2169 this._subscriptions.extend(project_subscriptions);
2170
2171 this.end_selection(cx);
2172 this.scroll_manager.show_scrollbar(cx);
2173
2174 if mode == EditorMode::Full {
2175 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
2176 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2177
2178 if this.git_blame_inline_enabled {
2179 this.git_blame_inline_enabled = true;
2180 this.start_git_blame_inline(false, cx);
2181 }
2182 }
2183
2184 this.report_editor_event("open", None, cx);
2185 this
2186 }
2187
2188 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
2189 self.mouse_context_menu
2190 .as_ref()
2191 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
2192 }
2193
2194 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
2195 let mut key_context = KeyContext::new_with_defaults();
2196 key_context.add("Editor");
2197 let mode = match self.mode {
2198 EditorMode::SingleLine { .. } => "single_line",
2199 EditorMode::AutoHeight { .. } => "auto_height",
2200 EditorMode::Full => "full",
2201 };
2202
2203 if EditorSettings::jupyter_enabled(cx) {
2204 key_context.add("jupyter");
2205 }
2206
2207 key_context.set("mode", mode);
2208 if self.pending_rename.is_some() {
2209 key_context.add("renaming");
2210 }
2211 if self.context_menu_visible() {
2212 match self.context_menu.read().as_ref() {
2213 Some(ContextMenu::Completions(_)) => {
2214 key_context.add("menu");
2215 key_context.add("showing_completions")
2216 }
2217 Some(ContextMenu::CodeActions(_)) => {
2218 key_context.add("menu");
2219 key_context.add("showing_code_actions")
2220 }
2221 None => {}
2222 }
2223 }
2224
2225 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2226 if !self.focus_handle(cx).contains_focused(cx)
2227 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2228 {
2229 for addon in self.addons.values() {
2230 addon.extend_key_context(&mut key_context, cx)
2231 }
2232 }
2233
2234 if let Some(extension) = self
2235 .buffer
2236 .read(cx)
2237 .as_singleton()
2238 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2239 {
2240 key_context.set("extension", extension.to_string());
2241 }
2242
2243 if self.has_active_inline_completion() {
2244 key_context.add("copilot_suggestion");
2245 key_context.add("inline_completion");
2246 }
2247
2248 key_context
2249 }
2250
2251 pub fn new_file(
2252 workspace: &mut Workspace,
2253 _: &workspace::NewFile,
2254 cx: &mut ViewContext<Workspace>,
2255 ) {
2256 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2257 "Failed to create buffer",
2258 cx,
2259 |e, _| match e.error_code() {
2260 ErrorCode::RemoteUpgradeRequired => Some(format!(
2261 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2262 e.error_tag("required").unwrap_or("the latest version")
2263 )),
2264 _ => None,
2265 },
2266 );
2267 }
2268
2269 pub fn new_in_workspace(
2270 workspace: &mut Workspace,
2271 cx: &mut ViewContext<Workspace>,
2272 ) -> Task<Result<View<Editor>>> {
2273 let project = workspace.project().clone();
2274 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2275
2276 cx.spawn(|workspace, mut cx| async move {
2277 let buffer = create.await?;
2278 workspace.update(&mut cx, |workspace, cx| {
2279 let editor =
2280 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2281 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2282 editor
2283 })
2284 })
2285 }
2286
2287 fn new_file_vertical(
2288 workspace: &mut Workspace,
2289 _: &workspace::NewFileSplitVertical,
2290 cx: &mut ViewContext<Workspace>,
2291 ) {
2292 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2293 }
2294
2295 fn new_file_horizontal(
2296 workspace: &mut Workspace,
2297 _: &workspace::NewFileSplitHorizontal,
2298 cx: &mut ViewContext<Workspace>,
2299 ) {
2300 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2301 }
2302
2303 fn new_file_in_direction(
2304 workspace: &mut Workspace,
2305 direction: SplitDirection,
2306 cx: &mut ViewContext<Workspace>,
2307 ) {
2308 let project = workspace.project().clone();
2309 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2310
2311 cx.spawn(|workspace, mut cx| async move {
2312 let buffer = create.await?;
2313 workspace.update(&mut cx, move |workspace, cx| {
2314 workspace.split_item(
2315 direction,
2316 Box::new(
2317 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2318 ),
2319 cx,
2320 )
2321 })?;
2322 anyhow::Ok(())
2323 })
2324 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2325 ErrorCode::RemoteUpgradeRequired => Some(format!(
2326 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2327 e.error_tag("required").unwrap_or("the latest version")
2328 )),
2329 _ => None,
2330 });
2331 }
2332
2333 pub fn leader_peer_id(&self) -> Option<PeerId> {
2334 self.leader_peer_id
2335 }
2336
2337 pub fn buffer(&self) -> &Model<MultiBuffer> {
2338 &self.buffer
2339 }
2340
2341 pub fn workspace(&self) -> Option<View<Workspace>> {
2342 self.workspace.as_ref()?.0.upgrade()
2343 }
2344
2345 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2346 self.buffer().read(cx).title(cx)
2347 }
2348
2349 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2350 let git_blame_gutter_max_author_length = self
2351 .render_git_blame_gutter(cx)
2352 .then(|| {
2353 if let Some(blame) = self.blame.as_ref() {
2354 let max_author_length =
2355 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2356 Some(max_author_length)
2357 } else {
2358 None
2359 }
2360 })
2361 .flatten();
2362
2363 EditorSnapshot {
2364 mode: self.mode,
2365 show_gutter: self.show_gutter,
2366 show_line_numbers: self.show_line_numbers,
2367 show_git_diff_gutter: self.show_git_diff_gutter,
2368 show_code_actions: self.show_code_actions,
2369 show_runnables: self.show_runnables,
2370 git_blame_gutter_max_author_length,
2371 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2372 scroll_anchor: self.scroll_manager.anchor(),
2373 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2374 placeholder_text: self.placeholder_text.clone(),
2375 diff_map: self.diff_map.snapshot(),
2376 is_focused: self.focus_handle.is_focused(cx),
2377 current_line_highlight: self
2378 .current_line_highlight
2379 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2380 gutter_hovered: self.gutter_hovered,
2381 }
2382 }
2383
2384 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2385 self.buffer.read(cx).language_at(point, cx)
2386 }
2387
2388 pub fn file_at<T: ToOffset>(
2389 &self,
2390 point: T,
2391 cx: &AppContext,
2392 ) -> Option<Arc<dyn language::File>> {
2393 self.buffer.read(cx).read(cx).file_at(point).cloned()
2394 }
2395
2396 pub fn active_excerpt(
2397 &self,
2398 cx: &AppContext,
2399 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2400 self.buffer
2401 .read(cx)
2402 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2403 }
2404
2405 pub fn mode(&self) -> EditorMode {
2406 self.mode
2407 }
2408
2409 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2410 self.collaboration_hub.as_deref()
2411 }
2412
2413 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2414 self.collaboration_hub = Some(hub);
2415 }
2416
2417 pub fn set_custom_context_menu(
2418 &mut self,
2419 f: impl 'static
2420 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2421 ) {
2422 self.custom_context_menu = Some(Box::new(f))
2423 }
2424
2425 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2426 self.completion_provider = provider;
2427 }
2428
2429 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2430 self.semantics_provider.clone()
2431 }
2432
2433 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2434 self.semantics_provider = provider;
2435 }
2436
2437 pub fn set_inline_completion_provider<T>(
2438 &mut self,
2439 provider: Option<Model<T>>,
2440 cx: &mut ViewContext<Self>,
2441 ) where
2442 T: InlineCompletionProvider,
2443 {
2444 self.inline_completion_provider =
2445 provider.map(|provider| RegisteredInlineCompletionProvider {
2446 _subscription: cx.observe(&provider, |this, _, cx| {
2447 if this.focus_handle.is_focused(cx) {
2448 this.update_visible_inline_completion(cx);
2449 }
2450 }),
2451 provider: Arc::new(provider),
2452 });
2453 self.refresh_inline_completion(false, false, cx);
2454 }
2455
2456 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2457 self.placeholder_text.as_deref()
2458 }
2459
2460 pub fn set_placeholder_text(
2461 &mut self,
2462 placeholder_text: impl Into<Arc<str>>,
2463 cx: &mut ViewContext<Self>,
2464 ) {
2465 let placeholder_text = Some(placeholder_text.into());
2466 if self.placeholder_text != placeholder_text {
2467 self.placeholder_text = placeholder_text;
2468 cx.notify();
2469 }
2470 }
2471
2472 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2473 self.cursor_shape = cursor_shape;
2474
2475 // Disrupt blink for immediate user feedback that the cursor shape has changed
2476 self.blink_manager.update(cx, BlinkManager::show_cursor);
2477
2478 cx.notify();
2479 }
2480
2481 pub fn set_current_line_highlight(
2482 &mut self,
2483 current_line_highlight: Option<CurrentLineHighlight>,
2484 ) {
2485 self.current_line_highlight = current_line_highlight;
2486 }
2487
2488 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2489 self.collapse_matches = collapse_matches;
2490 }
2491
2492 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2493 if self.collapse_matches {
2494 return range.start..range.start;
2495 }
2496 range.clone()
2497 }
2498
2499 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2500 if self.display_map.read(cx).clip_at_line_ends != clip {
2501 self.display_map
2502 .update(cx, |map, _| map.clip_at_line_ends = clip);
2503 }
2504 }
2505
2506 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2507 self.input_enabled = input_enabled;
2508 }
2509
2510 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2511 self.enable_inline_completions = enabled;
2512 }
2513
2514 pub fn set_autoindent(&mut self, autoindent: bool) {
2515 if autoindent {
2516 self.autoindent_mode = Some(AutoindentMode::EachLine);
2517 } else {
2518 self.autoindent_mode = None;
2519 }
2520 }
2521
2522 pub fn read_only(&self, cx: &AppContext) -> bool {
2523 self.read_only || self.buffer.read(cx).read_only()
2524 }
2525
2526 pub fn set_read_only(&mut self, read_only: bool) {
2527 self.read_only = read_only;
2528 }
2529
2530 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2531 self.use_autoclose = autoclose;
2532 }
2533
2534 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2535 self.use_auto_surround = auto_surround;
2536 }
2537
2538 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2539 self.auto_replace_emoji_shortcode = auto_replace;
2540 }
2541
2542 pub fn toggle_inline_completions(
2543 &mut self,
2544 _: &ToggleInlineCompletions,
2545 cx: &mut ViewContext<Self>,
2546 ) {
2547 if self.show_inline_completions_override.is_some() {
2548 self.set_show_inline_completions(None, cx);
2549 } else {
2550 let cursor = self.selections.newest_anchor().head();
2551 if let Some((buffer, cursor_buffer_position)) =
2552 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2553 {
2554 let show_inline_completions =
2555 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2556 self.set_show_inline_completions(Some(show_inline_completions), cx);
2557 }
2558 }
2559 }
2560
2561 pub fn set_show_inline_completions(
2562 &mut self,
2563 show_inline_completions: Option<bool>,
2564 cx: &mut ViewContext<Self>,
2565 ) {
2566 self.show_inline_completions_override = show_inline_completions;
2567 self.refresh_inline_completion(false, true, cx);
2568 }
2569
2570 fn should_show_inline_completions(
2571 &self,
2572 buffer: &Model<Buffer>,
2573 buffer_position: language::Anchor,
2574 cx: &AppContext,
2575 ) -> bool {
2576 if !self.snippet_stack.is_empty() {
2577 return false;
2578 }
2579
2580 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
2581 return false;
2582 }
2583
2584 if let Some(provider) = self.inline_completion_provider() {
2585 if let Some(show_inline_completions) = self.show_inline_completions_override {
2586 show_inline_completions
2587 } else {
2588 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2589 }
2590 } else {
2591 false
2592 }
2593 }
2594
2595 fn inline_completions_disabled_in_scope(
2596 &self,
2597 buffer: &Model<Buffer>,
2598 buffer_position: language::Anchor,
2599 cx: &AppContext,
2600 ) -> bool {
2601 let snapshot = buffer.read(cx).snapshot();
2602 let settings = snapshot.settings_at(buffer_position, cx);
2603
2604 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2605 return false;
2606 };
2607
2608 scope.override_name().map_or(false, |scope_name| {
2609 settings
2610 .inline_completions_disabled_in
2611 .iter()
2612 .any(|s| s == scope_name)
2613 })
2614 }
2615
2616 pub fn set_use_modal_editing(&mut self, to: bool) {
2617 self.use_modal_editing = to;
2618 }
2619
2620 pub fn use_modal_editing(&self) -> bool {
2621 self.use_modal_editing
2622 }
2623
2624 fn selections_did_change(
2625 &mut self,
2626 local: bool,
2627 old_cursor_position: &Anchor,
2628 show_completions: bool,
2629 cx: &mut ViewContext<Self>,
2630 ) {
2631 cx.invalidate_character_coordinates();
2632
2633 // Copy selections to primary selection buffer
2634 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2635 if local {
2636 let selections = self.selections.all::<usize>(cx);
2637 let buffer_handle = self.buffer.read(cx).read(cx);
2638
2639 let mut text = String::new();
2640 for (index, selection) in selections.iter().enumerate() {
2641 let text_for_selection = buffer_handle
2642 .text_for_range(selection.start..selection.end)
2643 .collect::<String>();
2644
2645 text.push_str(&text_for_selection);
2646 if index != selections.len() - 1 {
2647 text.push('\n');
2648 }
2649 }
2650
2651 if !text.is_empty() {
2652 cx.write_to_primary(ClipboardItem::new_string(text));
2653 }
2654 }
2655
2656 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2657 self.buffer.update(cx, |buffer, cx| {
2658 buffer.set_active_selections(
2659 &self.selections.disjoint_anchors(),
2660 self.selections.line_mode,
2661 self.cursor_shape,
2662 cx,
2663 )
2664 });
2665 }
2666 let display_map = self
2667 .display_map
2668 .update(cx, |display_map, cx| display_map.snapshot(cx));
2669 let buffer = &display_map.buffer_snapshot;
2670 self.add_selections_state = None;
2671 self.select_next_state = None;
2672 self.select_prev_state = None;
2673 self.select_larger_syntax_node_stack.clear();
2674 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2675 self.snippet_stack
2676 .invalidate(&self.selections.disjoint_anchors(), buffer);
2677 self.take_rename(false, cx);
2678
2679 let new_cursor_position = self.selections.newest_anchor().head();
2680
2681 self.push_to_nav_history(
2682 *old_cursor_position,
2683 Some(new_cursor_position.to_point(buffer)),
2684 cx,
2685 );
2686
2687 if local {
2688 let new_cursor_position = self.selections.newest_anchor().head();
2689 let mut context_menu = self.context_menu.write();
2690 let completion_menu = match context_menu.as_ref() {
2691 Some(ContextMenu::Completions(menu)) => Some(menu),
2692
2693 _ => {
2694 *context_menu = None;
2695 None
2696 }
2697 };
2698
2699 if let Some(completion_menu) = completion_menu {
2700 let cursor_position = new_cursor_position.to_offset(buffer);
2701 let (word_range, kind) =
2702 buffer.surrounding_word(completion_menu.initial_position, true);
2703 if kind == Some(CharKind::Word)
2704 && word_range.to_inclusive().contains(&cursor_position)
2705 {
2706 let mut completion_menu = completion_menu.clone();
2707 drop(context_menu);
2708
2709 let query = Self::completion_query(buffer, cursor_position);
2710 cx.spawn(move |this, mut cx| async move {
2711 completion_menu
2712 .filter(query.as_deref(), cx.background_executor().clone())
2713 .await;
2714
2715 this.update(&mut cx, |this, cx| {
2716 let mut context_menu = this.context_menu.write();
2717 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2718 return;
2719 };
2720
2721 if menu.id > completion_menu.id {
2722 return;
2723 }
2724
2725 *context_menu = Some(ContextMenu::Completions(completion_menu));
2726 drop(context_menu);
2727 cx.notify();
2728 })
2729 })
2730 .detach();
2731
2732 if show_completions {
2733 self.show_completions(&ShowCompletions { trigger: None }, cx);
2734 }
2735 } else {
2736 drop(context_menu);
2737 self.hide_context_menu(cx);
2738 }
2739 } else {
2740 drop(context_menu);
2741 }
2742
2743 hide_hover(self, cx);
2744
2745 if old_cursor_position.to_display_point(&display_map).row()
2746 != new_cursor_position.to_display_point(&display_map).row()
2747 {
2748 self.available_code_actions.take();
2749 }
2750 self.refresh_code_actions(cx);
2751 self.refresh_document_highlights(cx);
2752 refresh_matching_bracket_highlights(self, cx);
2753 self.update_visible_inline_completion(cx);
2754 linked_editing_ranges::refresh_linked_ranges(self, cx);
2755 if self.git_blame_inline_enabled {
2756 self.start_inline_blame_timer(cx);
2757 }
2758 }
2759
2760 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2761 cx.emit(EditorEvent::SelectionsChanged { local });
2762
2763 if self.selections.disjoint_anchors().len() == 1 {
2764 cx.emit(SearchEvent::ActiveMatchChanged)
2765 }
2766 cx.notify();
2767 }
2768
2769 pub fn change_selections<R>(
2770 &mut self,
2771 autoscroll: Option<Autoscroll>,
2772 cx: &mut ViewContext<Self>,
2773 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2774 ) -> R {
2775 self.change_selections_inner(autoscroll, true, cx, change)
2776 }
2777
2778 pub fn change_selections_inner<R>(
2779 &mut self,
2780 autoscroll: Option<Autoscroll>,
2781 request_completions: bool,
2782 cx: &mut ViewContext<Self>,
2783 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2784 ) -> R {
2785 let old_cursor_position = self.selections.newest_anchor().head();
2786 self.push_to_selection_history();
2787
2788 let (changed, result) = self.selections.change_with(cx, change);
2789
2790 if changed {
2791 if let Some(autoscroll) = autoscroll {
2792 self.request_autoscroll(autoscroll, cx);
2793 }
2794 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2795
2796 if self.should_open_signature_help_automatically(
2797 &old_cursor_position,
2798 self.signature_help_state.backspace_pressed(),
2799 cx,
2800 ) {
2801 self.show_signature_help(&ShowSignatureHelp, cx);
2802 }
2803 self.signature_help_state.set_backspace_pressed(false);
2804 }
2805
2806 result
2807 }
2808
2809 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2810 where
2811 I: IntoIterator<Item = (Range<S>, T)>,
2812 S: ToOffset,
2813 T: Into<Arc<str>>,
2814 {
2815 if self.read_only(cx) {
2816 return;
2817 }
2818
2819 self.buffer
2820 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2821 }
2822
2823 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2824 where
2825 I: IntoIterator<Item = (Range<S>, T)>,
2826 S: ToOffset,
2827 T: Into<Arc<str>>,
2828 {
2829 if self.read_only(cx) {
2830 return;
2831 }
2832
2833 self.buffer.update(cx, |buffer, cx| {
2834 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2835 });
2836 }
2837
2838 pub fn edit_with_block_indent<I, S, T>(
2839 &mut self,
2840 edits: I,
2841 original_indent_columns: Vec<u32>,
2842 cx: &mut ViewContext<Self>,
2843 ) where
2844 I: IntoIterator<Item = (Range<S>, T)>,
2845 S: ToOffset,
2846 T: Into<Arc<str>>,
2847 {
2848 if self.read_only(cx) {
2849 return;
2850 }
2851
2852 self.buffer.update(cx, |buffer, cx| {
2853 buffer.edit(
2854 edits,
2855 Some(AutoindentMode::Block {
2856 original_indent_columns,
2857 }),
2858 cx,
2859 )
2860 });
2861 }
2862
2863 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2864 self.hide_context_menu(cx);
2865
2866 match phase {
2867 SelectPhase::Begin {
2868 position,
2869 add,
2870 click_count,
2871 } => self.begin_selection(position, add, click_count, cx),
2872 SelectPhase::BeginColumnar {
2873 position,
2874 goal_column,
2875 reset,
2876 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2877 SelectPhase::Extend {
2878 position,
2879 click_count,
2880 } => self.extend_selection(position, click_count, cx),
2881 SelectPhase::Update {
2882 position,
2883 goal_column,
2884 scroll_delta,
2885 } => self.update_selection(position, goal_column, scroll_delta, cx),
2886 SelectPhase::End => self.end_selection(cx),
2887 }
2888 }
2889
2890 fn extend_selection(
2891 &mut self,
2892 position: DisplayPoint,
2893 click_count: usize,
2894 cx: &mut ViewContext<Self>,
2895 ) {
2896 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2897 let tail = self.selections.newest::<usize>(cx).tail();
2898 self.begin_selection(position, false, click_count, cx);
2899
2900 let position = position.to_offset(&display_map, Bias::Left);
2901 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2902
2903 let mut pending_selection = self
2904 .selections
2905 .pending_anchor()
2906 .expect("extend_selection not called with pending selection");
2907 if position >= tail {
2908 pending_selection.start = tail_anchor;
2909 } else {
2910 pending_selection.end = tail_anchor;
2911 pending_selection.reversed = true;
2912 }
2913
2914 let mut pending_mode = self.selections.pending_mode().unwrap();
2915 match &mut pending_mode {
2916 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2917 _ => {}
2918 }
2919
2920 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2921 s.set_pending(pending_selection, pending_mode)
2922 });
2923 }
2924
2925 fn begin_selection(
2926 &mut self,
2927 position: DisplayPoint,
2928 add: bool,
2929 click_count: usize,
2930 cx: &mut ViewContext<Self>,
2931 ) {
2932 if !self.focus_handle.is_focused(cx) {
2933 self.last_focused_descendant = None;
2934 cx.focus(&self.focus_handle);
2935 }
2936
2937 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2938 let buffer = &display_map.buffer_snapshot;
2939 let newest_selection = self.selections.newest_anchor().clone();
2940 let position = display_map.clip_point(position, Bias::Left);
2941
2942 let start;
2943 let end;
2944 let mode;
2945 let mut auto_scroll;
2946 match click_count {
2947 1 => {
2948 start = buffer.anchor_before(position.to_point(&display_map));
2949 end = start;
2950 mode = SelectMode::Character;
2951 auto_scroll = true;
2952 }
2953 2 => {
2954 let range = movement::surrounding_word(&display_map, position);
2955 start = buffer.anchor_before(range.start.to_point(&display_map));
2956 end = buffer.anchor_before(range.end.to_point(&display_map));
2957 mode = SelectMode::Word(start..end);
2958 auto_scroll = true;
2959 }
2960 3 => {
2961 let position = display_map
2962 .clip_point(position, Bias::Left)
2963 .to_point(&display_map);
2964 let line_start = display_map.prev_line_boundary(position).0;
2965 let next_line_start = buffer.clip_point(
2966 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2967 Bias::Left,
2968 );
2969 start = buffer.anchor_before(line_start);
2970 end = buffer.anchor_before(next_line_start);
2971 mode = SelectMode::Line(start..end);
2972 auto_scroll = true;
2973 }
2974 _ => {
2975 start = buffer.anchor_before(0);
2976 end = buffer.anchor_before(buffer.len());
2977 mode = SelectMode::All;
2978 auto_scroll = false;
2979 }
2980 }
2981 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2982
2983 let point_to_delete: Option<usize> = {
2984 let selected_points: Vec<Selection<Point>> =
2985 self.selections.disjoint_in_range(start..end, cx);
2986
2987 if !add || click_count > 1 {
2988 None
2989 } else if !selected_points.is_empty() {
2990 Some(selected_points[0].id)
2991 } else {
2992 let clicked_point_already_selected =
2993 self.selections.disjoint.iter().find(|selection| {
2994 selection.start.to_point(buffer) == start.to_point(buffer)
2995 || selection.end.to_point(buffer) == end.to_point(buffer)
2996 });
2997
2998 clicked_point_already_selected.map(|selection| selection.id)
2999 }
3000 };
3001
3002 let selections_count = self.selections.count();
3003
3004 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
3005 if let Some(point_to_delete) = point_to_delete {
3006 s.delete(point_to_delete);
3007
3008 if selections_count == 1 {
3009 s.set_pending_anchor_range(start..end, mode);
3010 }
3011 } else {
3012 if !add {
3013 s.clear_disjoint();
3014 } else if click_count > 1 {
3015 s.delete(newest_selection.id)
3016 }
3017
3018 s.set_pending_anchor_range(start..end, mode);
3019 }
3020 });
3021 }
3022
3023 fn begin_columnar_selection(
3024 &mut self,
3025 position: DisplayPoint,
3026 goal_column: u32,
3027 reset: bool,
3028 cx: &mut ViewContext<Self>,
3029 ) {
3030 if !self.focus_handle.is_focused(cx) {
3031 self.last_focused_descendant = None;
3032 cx.focus(&self.focus_handle);
3033 }
3034
3035 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3036
3037 if reset {
3038 let pointer_position = display_map
3039 .buffer_snapshot
3040 .anchor_before(position.to_point(&display_map));
3041
3042 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
3043 s.clear_disjoint();
3044 s.set_pending_anchor_range(
3045 pointer_position..pointer_position,
3046 SelectMode::Character,
3047 );
3048 });
3049 }
3050
3051 let tail = self.selections.newest::<Point>(cx).tail();
3052 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
3053
3054 if !reset {
3055 self.select_columns(
3056 tail.to_display_point(&display_map),
3057 position,
3058 goal_column,
3059 &display_map,
3060 cx,
3061 );
3062 }
3063 }
3064
3065 fn update_selection(
3066 &mut self,
3067 position: DisplayPoint,
3068 goal_column: u32,
3069 scroll_delta: gpui::Point<f32>,
3070 cx: &mut ViewContext<Self>,
3071 ) {
3072 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3073
3074 if let Some(tail) = self.columnar_selection_tail.as_ref() {
3075 let tail = tail.to_display_point(&display_map);
3076 self.select_columns(tail, position, goal_column, &display_map, cx);
3077 } else if let Some(mut pending) = self.selections.pending_anchor() {
3078 let buffer = self.buffer.read(cx).snapshot(cx);
3079 let head;
3080 let tail;
3081 let mode = self.selections.pending_mode().unwrap();
3082 match &mode {
3083 SelectMode::Character => {
3084 head = position.to_point(&display_map);
3085 tail = pending.tail().to_point(&buffer);
3086 }
3087 SelectMode::Word(original_range) => {
3088 let original_display_range = original_range.start.to_display_point(&display_map)
3089 ..original_range.end.to_display_point(&display_map);
3090 let original_buffer_range = original_display_range.start.to_point(&display_map)
3091 ..original_display_range.end.to_point(&display_map);
3092 if movement::is_inside_word(&display_map, position)
3093 || original_display_range.contains(&position)
3094 {
3095 let word_range = movement::surrounding_word(&display_map, position);
3096 if word_range.start < original_display_range.start {
3097 head = word_range.start.to_point(&display_map);
3098 } else {
3099 head = word_range.end.to_point(&display_map);
3100 }
3101 } else {
3102 head = position.to_point(&display_map);
3103 }
3104
3105 if head <= original_buffer_range.start {
3106 tail = original_buffer_range.end;
3107 } else {
3108 tail = original_buffer_range.start;
3109 }
3110 }
3111 SelectMode::Line(original_range) => {
3112 let original_range = original_range.to_point(&display_map.buffer_snapshot);
3113
3114 let position = display_map
3115 .clip_point(position, Bias::Left)
3116 .to_point(&display_map);
3117 let line_start = display_map.prev_line_boundary(position).0;
3118 let next_line_start = buffer.clip_point(
3119 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3120 Bias::Left,
3121 );
3122
3123 if line_start < original_range.start {
3124 head = line_start
3125 } else {
3126 head = next_line_start
3127 }
3128
3129 if head <= original_range.start {
3130 tail = original_range.end;
3131 } else {
3132 tail = original_range.start;
3133 }
3134 }
3135 SelectMode::All => {
3136 return;
3137 }
3138 };
3139
3140 if head < tail {
3141 pending.start = buffer.anchor_before(head);
3142 pending.end = buffer.anchor_before(tail);
3143 pending.reversed = true;
3144 } else {
3145 pending.start = buffer.anchor_before(tail);
3146 pending.end = buffer.anchor_before(head);
3147 pending.reversed = false;
3148 }
3149
3150 self.change_selections(None, cx, |s| {
3151 s.set_pending(pending, mode);
3152 });
3153 } else {
3154 log::error!("update_selection dispatched with no pending selection");
3155 return;
3156 }
3157
3158 self.apply_scroll_delta(scroll_delta, cx);
3159 cx.notify();
3160 }
3161
3162 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
3163 self.columnar_selection_tail.take();
3164 if self.selections.pending_anchor().is_some() {
3165 let selections = self.selections.all::<usize>(cx);
3166 self.change_selections(None, cx, |s| {
3167 s.select(selections);
3168 s.clear_pending();
3169 });
3170 }
3171 }
3172
3173 fn select_columns(
3174 &mut self,
3175 tail: DisplayPoint,
3176 head: DisplayPoint,
3177 goal_column: u32,
3178 display_map: &DisplaySnapshot,
3179 cx: &mut ViewContext<Self>,
3180 ) {
3181 let start_row = cmp::min(tail.row(), head.row());
3182 let end_row = cmp::max(tail.row(), head.row());
3183 let start_column = cmp::min(tail.column(), goal_column);
3184 let end_column = cmp::max(tail.column(), goal_column);
3185 let reversed = start_column < tail.column();
3186
3187 let selection_ranges = (start_row.0..=end_row.0)
3188 .map(DisplayRow)
3189 .filter_map(|row| {
3190 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3191 let start = display_map
3192 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3193 .to_point(display_map);
3194 let end = display_map
3195 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3196 .to_point(display_map);
3197 if reversed {
3198 Some(end..start)
3199 } else {
3200 Some(start..end)
3201 }
3202 } else {
3203 None
3204 }
3205 })
3206 .collect::<Vec<_>>();
3207
3208 self.change_selections(None, cx, |s| {
3209 s.select_ranges(selection_ranges);
3210 });
3211 cx.notify();
3212 }
3213
3214 pub fn has_pending_nonempty_selection(&self) -> bool {
3215 let pending_nonempty_selection = match self.selections.pending_anchor() {
3216 Some(Selection { start, end, .. }) => start != end,
3217 None => false,
3218 };
3219
3220 pending_nonempty_selection
3221 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3222 }
3223
3224 pub fn has_pending_selection(&self) -> bool {
3225 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3226 }
3227
3228 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
3229 if self.clear_expanded_diff_hunks(cx) {
3230 cx.notify();
3231 return;
3232 }
3233 if self.dismiss_menus_and_popups(true, cx) {
3234 return;
3235 }
3236
3237 if self.mode == EditorMode::Full
3238 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
3239 {
3240 return;
3241 }
3242
3243 cx.propagate();
3244 }
3245
3246 pub fn dismiss_menus_and_popups(
3247 &mut self,
3248 should_report_inline_completion_event: bool,
3249 cx: &mut ViewContext<Self>,
3250 ) -> bool {
3251 if self.take_rename(false, cx).is_some() {
3252 return true;
3253 }
3254
3255 if hide_hover(self, cx) {
3256 return true;
3257 }
3258
3259 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3260 return true;
3261 }
3262
3263 if self.hide_context_menu(cx).is_some() {
3264 return true;
3265 }
3266
3267 if self.mouse_context_menu.take().is_some() {
3268 return true;
3269 }
3270
3271 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3272 return true;
3273 }
3274
3275 if self.snippet_stack.pop().is_some() {
3276 return true;
3277 }
3278
3279 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3280 self.dismiss_diagnostics(cx);
3281 return true;
3282 }
3283
3284 false
3285 }
3286
3287 fn linked_editing_ranges_for(
3288 &self,
3289 selection: Range<text::Anchor>,
3290 cx: &AppContext,
3291 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3292 if self.linked_edit_ranges.is_empty() {
3293 return None;
3294 }
3295 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3296 selection.end.buffer_id.and_then(|end_buffer_id| {
3297 if selection.start.buffer_id != Some(end_buffer_id) {
3298 return None;
3299 }
3300 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3301 let snapshot = buffer.read(cx).snapshot();
3302 self.linked_edit_ranges
3303 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3304 .map(|ranges| (ranges, snapshot, buffer))
3305 })?;
3306 use text::ToOffset as TO;
3307 // find offset from the start of current range to current cursor position
3308 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3309
3310 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3311 let start_difference = start_offset - start_byte_offset;
3312 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3313 let end_difference = end_offset - start_byte_offset;
3314 // Current range has associated linked ranges.
3315 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3316 for range in linked_ranges.iter() {
3317 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3318 let end_offset = start_offset + end_difference;
3319 let start_offset = start_offset + start_difference;
3320 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3321 continue;
3322 }
3323 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3324 if s.start.buffer_id != selection.start.buffer_id
3325 || s.end.buffer_id != selection.end.buffer_id
3326 {
3327 return false;
3328 }
3329 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3330 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3331 }) {
3332 continue;
3333 }
3334 let start = buffer_snapshot.anchor_after(start_offset);
3335 let end = buffer_snapshot.anchor_after(end_offset);
3336 linked_edits
3337 .entry(buffer.clone())
3338 .or_default()
3339 .push(start..end);
3340 }
3341 Some(linked_edits)
3342 }
3343
3344 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3345 let text: Arc<str> = text.into();
3346
3347 if self.read_only(cx) {
3348 return;
3349 }
3350
3351 let selections = self.selections.all_adjusted(cx);
3352 let mut bracket_inserted = false;
3353 let mut edits = Vec::new();
3354 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3355 let mut new_selections = Vec::with_capacity(selections.len());
3356 let mut new_autoclose_regions = Vec::new();
3357 let snapshot = self.buffer.read(cx).read(cx);
3358
3359 for (selection, autoclose_region) in
3360 self.selections_with_autoclose_regions(selections, &snapshot)
3361 {
3362 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3363 // Determine if the inserted text matches the opening or closing
3364 // bracket of any of this language's bracket pairs.
3365 let mut bracket_pair = None;
3366 let mut is_bracket_pair_start = false;
3367 let mut is_bracket_pair_end = false;
3368 if !text.is_empty() {
3369 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3370 // and they are removing the character that triggered IME popup.
3371 for (pair, enabled) in scope.brackets() {
3372 if !pair.close && !pair.surround {
3373 continue;
3374 }
3375
3376 if enabled && pair.start.ends_with(text.as_ref()) {
3377 let prefix_len = pair.start.len() - text.len();
3378 let preceding_text_matches_prefix = prefix_len == 0
3379 || (selection.start.column >= (prefix_len as u32)
3380 && snapshot.contains_str_at(
3381 Point::new(
3382 selection.start.row,
3383 selection.start.column - (prefix_len as u32),
3384 ),
3385 &pair.start[..prefix_len],
3386 ));
3387 if preceding_text_matches_prefix {
3388 bracket_pair = Some(pair.clone());
3389 is_bracket_pair_start = true;
3390 break;
3391 }
3392 }
3393 if pair.end.as_str() == text.as_ref() {
3394 bracket_pair = Some(pair.clone());
3395 is_bracket_pair_end = true;
3396 break;
3397 }
3398 }
3399 }
3400
3401 if let Some(bracket_pair) = bracket_pair {
3402 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3403 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3404 let auto_surround =
3405 self.use_auto_surround && snapshot_settings.use_auto_surround;
3406 if selection.is_empty() {
3407 if is_bracket_pair_start {
3408 // If the inserted text is a suffix of an opening bracket and the
3409 // selection is preceded by the rest of the opening bracket, then
3410 // insert the closing bracket.
3411 let following_text_allows_autoclose = snapshot
3412 .chars_at(selection.start)
3413 .next()
3414 .map_or(true, |c| scope.should_autoclose_before(c));
3415
3416 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3417 && bracket_pair.start.len() == 1
3418 {
3419 let target = bracket_pair.start.chars().next().unwrap();
3420 let current_line_count = snapshot
3421 .reversed_chars_at(selection.start)
3422 .take_while(|&c| c != '\n')
3423 .filter(|&c| c == target)
3424 .count();
3425 current_line_count % 2 == 1
3426 } else {
3427 false
3428 };
3429
3430 if autoclose
3431 && bracket_pair.close
3432 && following_text_allows_autoclose
3433 && !is_closing_quote
3434 {
3435 let anchor = snapshot.anchor_before(selection.end);
3436 new_selections.push((selection.map(|_| anchor), text.len()));
3437 new_autoclose_regions.push((
3438 anchor,
3439 text.len(),
3440 selection.id,
3441 bracket_pair.clone(),
3442 ));
3443 edits.push((
3444 selection.range(),
3445 format!("{}{}", text, bracket_pair.end).into(),
3446 ));
3447 bracket_inserted = true;
3448 continue;
3449 }
3450 }
3451
3452 if let Some(region) = autoclose_region {
3453 // If the selection is followed by an auto-inserted closing bracket,
3454 // then don't insert that closing bracket again; just move the selection
3455 // past the closing bracket.
3456 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3457 && text.as_ref() == region.pair.end.as_str();
3458 if should_skip {
3459 let anchor = snapshot.anchor_after(selection.end);
3460 new_selections
3461 .push((selection.map(|_| anchor), region.pair.end.len()));
3462 continue;
3463 }
3464 }
3465
3466 let always_treat_brackets_as_autoclosed = snapshot
3467 .settings_at(selection.start, cx)
3468 .always_treat_brackets_as_autoclosed;
3469 if always_treat_brackets_as_autoclosed
3470 && is_bracket_pair_end
3471 && snapshot.contains_str_at(selection.end, text.as_ref())
3472 {
3473 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3474 // and the inserted text is a closing bracket and the selection is followed
3475 // by the closing bracket then move the selection past the closing bracket.
3476 let anchor = snapshot.anchor_after(selection.end);
3477 new_selections.push((selection.map(|_| anchor), text.len()));
3478 continue;
3479 }
3480 }
3481 // If an opening bracket is 1 character long and is typed while
3482 // text is selected, then surround that text with the bracket pair.
3483 else if auto_surround
3484 && bracket_pair.surround
3485 && is_bracket_pair_start
3486 && bracket_pair.start.chars().count() == 1
3487 {
3488 edits.push((selection.start..selection.start, text.clone()));
3489 edits.push((
3490 selection.end..selection.end,
3491 bracket_pair.end.as_str().into(),
3492 ));
3493 bracket_inserted = true;
3494 new_selections.push((
3495 Selection {
3496 id: selection.id,
3497 start: snapshot.anchor_after(selection.start),
3498 end: snapshot.anchor_before(selection.end),
3499 reversed: selection.reversed,
3500 goal: selection.goal,
3501 },
3502 0,
3503 ));
3504 continue;
3505 }
3506 }
3507 }
3508
3509 if self.auto_replace_emoji_shortcode
3510 && selection.is_empty()
3511 && text.as_ref().ends_with(':')
3512 {
3513 if let Some(possible_emoji_short_code) =
3514 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3515 {
3516 if !possible_emoji_short_code.is_empty() {
3517 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3518 let emoji_shortcode_start = Point::new(
3519 selection.start.row,
3520 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3521 );
3522
3523 // Remove shortcode from buffer
3524 edits.push((
3525 emoji_shortcode_start..selection.start,
3526 "".to_string().into(),
3527 ));
3528 new_selections.push((
3529 Selection {
3530 id: selection.id,
3531 start: snapshot.anchor_after(emoji_shortcode_start),
3532 end: snapshot.anchor_before(selection.start),
3533 reversed: selection.reversed,
3534 goal: selection.goal,
3535 },
3536 0,
3537 ));
3538
3539 // Insert emoji
3540 let selection_start_anchor = snapshot.anchor_after(selection.start);
3541 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3542 edits.push((selection.start..selection.end, emoji.to_string().into()));
3543
3544 continue;
3545 }
3546 }
3547 }
3548 }
3549
3550 // If not handling any auto-close operation, then just replace the selected
3551 // text with the given input and move the selection to the end of the
3552 // newly inserted text.
3553 let anchor = snapshot.anchor_after(selection.end);
3554 if !self.linked_edit_ranges.is_empty() {
3555 let start_anchor = snapshot.anchor_before(selection.start);
3556
3557 let is_word_char = text.chars().next().map_or(true, |char| {
3558 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3559 classifier.is_word(char)
3560 });
3561
3562 if is_word_char {
3563 if let Some(ranges) = self
3564 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3565 {
3566 for (buffer, edits) in ranges {
3567 linked_edits
3568 .entry(buffer.clone())
3569 .or_default()
3570 .extend(edits.into_iter().map(|range| (range, text.clone())));
3571 }
3572 }
3573 }
3574 }
3575
3576 new_selections.push((selection.map(|_| anchor), 0));
3577 edits.push((selection.start..selection.end, text.clone()));
3578 }
3579
3580 drop(snapshot);
3581
3582 self.transact(cx, |this, cx| {
3583 this.buffer.update(cx, |buffer, cx| {
3584 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3585 });
3586 for (buffer, edits) in linked_edits {
3587 buffer.update(cx, |buffer, cx| {
3588 let snapshot = buffer.snapshot();
3589 let edits = edits
3590 .into_iter()
3591 .map(|(range, text)| {
3592 use text::ToPoint as TP;
3593 let end_point = TP::to_point(&range.end, &snapshot);
3594 let start_point = TP::to_point(&range.start, &snapshot);
3595 (start_point..end_point, text)
3596 })
3597 .sorted_by_key(|(range, _)| range.start)
3598 .collect::<Vec<_>>();
3599 buffer.edit(edits, None, cx);
3600 })
3601 }
3602 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3603 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3604 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3605 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3606 .zip(new_selection_deltas)
3607 .map(|(selection, delta)| Selection {
3608 id: selection.id,
3609 start: selection.start + delta,
3610 end: selection.end + delta,
3611 reversed: selection.reversed,
3612 goal: SelectionGoal::None,
3613 })
3614 .collect::<Vec<_>>();
3615
3616 let mut i = 0;
3617 for (position, delta, selection_id, pair) in new_autoclose_regions {
3618 let position = position.to_offset(&map.buffer_snapshot) + delta;
3619 let start = map.buffer_snapshot.anchor_before(position);
3620 let end = map.buffer_snapshot.anchor_after(position);
3621 while let Some(existing_state) = this.autoclose_regions.get(i) {
3622 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3623 Ordering::Less => i += 1,
3624 Ordering::Greater => break,
3625 Ordering::Equal => {
3626 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3627 Ordering::Less => i += 1,
3628 Ordering::Equal => break,
3629 Ordering::Greater => break,
3630 }
3631 }
3632 }
3633 }
3634 this.autoclose_regions.insert(
3635 i,
3636 AutocloseRegion {
3637 selection_id,
3638 range: start..end,
3639 pair,
3640 },
3641 );
3642 }
3643
3644 let had_active_inline_completion = this.has_active_inline_completion();
3645 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3646 s.select(new_selections)
3647 });
3648
3649 if !bracket_inserted {
3650 if let Some(on_type_format_task) =
3651 this.trigger_on_type_formatting(text.to_string(), cx)
3652 {
3653 on_type_format_task.detach_and_log_err(cx);
3654 }
3655 }
3656
3657 let editor_settings = EditorSettings::get_global(cx);
3658 if bracket_inserted
3659 && (editor_settings.auto_signature_help
3660 || editor_settings.show_signature_help_after_edits)
3661 {
3662 this.show_signature_help(&ShowSignatureHelp, cx);
3663 }
3664
3665 let trigger_in_words = !had_active_inline_completion;
3666 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3667 linked_editing_ranges::refresh_linked_ranges(this, cx);
3668 this.refresh_inline_completion(true, false, cx);
3669 });
3670 }
3671
3672 fn find_possible_emoji_shortcode_at_position(
3673 snapshot: &MultiBufferSnapshot,
3674 position: Point,
3675 ) -> Option<String> {
3676 let mut chars = Vec::new();
3677 let mut found_colon = false;
3678 for char in snapshot.reversed_chars_at(position).take(100) {
3679 // Found a possible emoji shortcode in the middle of the buffer
3680 if found_colon {
3681 if char.is_whitespace() {
3682 chars.reverse();
3683 return Some(chars.iter().collect());
3684 }
3685 // If the previous character is not a whitespace, we are in the middle of a word
3686 // and we only want to complete the shortcode if the word is made up of other emojis
3687 let mut containing_word = String::new();
3688 for ch in snapshot
3689 .reversed_chars_at(position)
3690 .skip(chars.len() + 1)
3691 .take(100)
3692 {
3693 if ch.is_whitespace() {
3694 break;
3695 }
3696 containing_word.push(ch);
3697 }
3698 let containing_word = containing_word.chars().rev().collect::<String>();
3699 if util::word_consists_of_emojis(containing_word.as_str()) {
3700 chars.reverse();
3701 return Some(chars.iter().collect());
3702 }
3703 }
3704
3705 if char.is_whitespace() || !char.is_ascii() {
3706 return None;
3707 }
3708 if char == ':' {
3709 found_colon = true;
3710 } else {
3711 chars.push(char);
3712 }
3713 }
3714 // Found a possible emoji shortcode at the beginning of the buffer
3715 chars.reverse();
3716 Some(chars.iter().collect())
3717 }
3718
3719 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3720 self.transact(cx, |this, cx| {
3721 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3722 let selections = this.selections.all::<usize>(cx);
3723 let multi_buffer = this.buffer.read(cx);
3724 let buffer = multi_buffer.snapshot(cx);
3725 selections
3726 .iter()
3727 .map(|selection| {
3728 let start_point = selection.start.to_point(&buffer);
3729 let mut indent =
3730 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3731 indent.len = cmp::min(indent.len, start_point.column);
3732 let start = selection.start;
3733 let end = selection.end;
3734 let selection_is_empty = start == end;
3735 let language_scope = buffer.language_scope_at(start);
3736 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3737 &language_scope
3738 {
3739 let leading_whitespace_len = buffer
3740 .reversed_chars_at(start)
3741 .take_while(|c| c.is_whitespace() && *c != '\n')
3742 .map(|c| c.len_utf8())
3743 .sum::<usize>();
3744
3745 let trailing_whitespace_len = buffer
3746 .chars_at(end)
3747 .take_while(|c| c.is_whitespace() && *c != '\n')
3748 .map(|c| c.len_utf8())
3749 .sum::<usize>();
3750
3751 let insert_extra_newline =
3752 language.brackets().any(|(pair, enabled)| {
3753 let pair_start = pair.start.trim_end();
3754 let pair_end = pair.end.trim_start();
3755
3756 enabled
3757 && pair.newline
3758 && buffer.contains_str_at(
3759 end + trailing_whitespace_len,
3760 pair_end,
3761 )
3762 && buffer.contains_str_at(
3763 (start - leading_whitespace_len)
3764 .saturating_sub(pair_start.len()),
3765 pair_start,
3766 )
3767 });
3768
3769 // Comment extension on newline is allowed only for cursor selections
3770 let comment_delimiter = maybe!({
3771 if !selection_is_empty {
3772 return None;
3773 }
3774
3775 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3776 return None;
3777 }
3778
3779 let delimiters = language.line_comment_prefixes();
3780 let max_len_of_delimiter =
3781 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3782 let (snapshot, range) =
3783 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3784
3785 let mut index_of_first_non_whitespace = 0;
3786 let comment_candidate = snapshot
3787 .chars_for_range(range)
3788 .skip_while(|c| {
3789 let should_skip = c.is_whitespace();
3790 if should_skip {
3791 index_of_first_non_whitespace += 1;
3792 }
3793 should_skip
3794 })
3795 .take(max_len_of_delimiter)
3796 .collect::<String>();
3797 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3798 comment_candidate.starts_with(comment_prefix.as_ref())
3799 })?;
3800 let cursor_is_placed_after_comment_marker =
3801 index_of_first_non_whitespace + comment_prefix.len()
3802 <= start_point.column as usize;
3803 if cursor_is_placed_after_comment_marker {
3804 Some(comment_prefix.clone())
3805 } else {
3806 None
3807 }
3808 });
3809 (comment_delimiter, insert_extra_newline)
3810 } else {
3811 (None, false)
3812 };
3813
3814 let capacity_for_delimiter = comment_delimiter
3815 .as_deref()
3816 .map(str::len)
3817 .unwrap_or_default();
3818 let mut new_text =
3819 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3820 new_text.push('\n');
3821 new_text.extend(indent.chars());
3822 if let Some(delimiter) = &comment_delimiter {
3823 new_text.push_str(delimiter);
3824 }
3825 if insert_extra_newline {
3826 new_text = new_text.repeat(2);
3827 }
3828
3829 let anchor = buffer.anchor_after(end);
3830 let new_selection = selection.map(|_| anchor);
3831 (
3832 (start..end, new_text),
3833 (insert_extra_newline, new_selection),
3834 )
3835 })
3836 .unzip()
3837 };
3838
3839 this.edit_with_autoindent(edits, cx);
3840 let buffer = this.buffer.read(cx).snapshot(cx);
3841 let new_selections = selection_fixup_info
3842 .into_iter()
3843 .map(|(extra_newline_inserted, new_selection)| {
3844 let mut cursor = new_selection.end.to_point(&buffer);
3845 if extra_newline_inserted {
3846 cursor.row -= 1;
3847 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3848 }
3849 new_selection.map(|_| cursor)
3850 })
3851 .collect();
3852
3853 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3854 this.refresh_inline_completion(true, false, cx);
3855 });
3856 }
3857
3858 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3859 let buffer = self.buffer.read(cx);
3860 let snapshot = buffer.snapshot(cx);
3861
3862 let mut edits = Vec::new();
3863 let mut rows = Vec::new();
3864
3865 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3866 let cursor = selection.head();
3867 let row = cursor.row;
3868
3869 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3870
3871 let newline = "\n".to_string();
3872 edits.push((start_of_line..start_of_line, newline));
3873
3874 rows.push(row + rows_inserted as u32);
3875 }
3876
3877 self.transact(cx, |editor, cx| {
3878 editor.edit(edits, cx);
3879
3880 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3881 let mut index = 0;
3882 s.move_cursors_with(|map, _, _| {
3883 let row = rows[index];
3884 index += 1;
3885
3886 let point = Point::new(row, 0);
3887 let boundary = map.next_line_boundary(point).1;
3888 let clipped = map.clip_point(boundary, Bias::Left);
3889
3890 (clipped, SelectionGoal::None)
3891 });
3892 });
3893
3894 let mut indent_edits = Vec::new();
3895 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3896 for row in rows {
3897 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3898 for (row, indent) in indents {
3899 if indent.len == 0 {
3900 continue;
3901 }
3902
3903 let text = match indent.kind {
3904 IndentKind::Space => " ".repeat(indent.len as usize),
3905 IndentKind::Tab => "\t".repeat(indent.len as usize),
3906 };
3907 let point = Point::new(row.0, 0);
3908 indent_edits.push((point..point, text));
3909 }
3910 }
3911 editor.edit(indent_edits, cx);
3912 });
3913 }
3914
3915 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3916 let buffer = self.buffer.read(cx);
3917 let snapshot = buffer.snapshot(cx);
3918
3919 let mut edits = Vec::new();
3920 let mut rows = Vec::new();
3921 let mut rows_inserted = 0;
3922
3923 for selection in self.selections.all_adjusted(cx) {
3924 let cursor = selection.head();
3925 let row = cursor.row;
3926
3927 let point = Point::new(row + 1, 0);
3928 let start_of_line = snapshot.clip_point(point, Bias::Left);
3929
3930 let newline = "\n".to_string();
3931 edits.push((start_of_line..start_of_line, newline));
3932
3933 rows_inserted += 1;
3934 rows.push(row + rows_inserted);
3935 }
3936
3937 self.transact(cx, |editor, cx| {
3938 editor.edit(edits, cx);
3939
3940 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3941 let mut index = 0;
3942 s.move_cursors_with(|map, _, _| {
3943 let row = rows[index];
3944 index += 1;
3945
3946 let point = Point::new(row, 0);
3947 let boundary = map.next_line_boundary(point).1;
3948 let clipped = map.clip_point(boundary, Bias::Left);
3949
3950 (clipped, SelectionGoal::None)
3951 });
3952 });
3953
3954 let mut indent_edits = Vec::new();
3955 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3956 for row in rows {
3957 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3958 for (row, indent) in indents {
3959 if indent.len == 0 {
3960 continue;
3961 }
3962
3963 let text = match indent.kind {
3964 IndentKind::Space => " ".repeat(indent.len as usize),
3965 IndentKind::Tab => "\t".repeat(indent.len as usize),
3966 };
3967 let point = Point::new(row.0, 0);
3968 indent_edits.push((point..point, text));
3969 }
3970 }
3971 editor.edit(indent_edits, cx);
3972 });
3973 }
3974
3975 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3976 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3977 original_indent_columns: Vec::new(),
3978 });
3979 self.insert_with_autoindent_mode(text, autoindent, cx);
3980 }
3981
3982 fn insert_with_autoindent_mode(
3983 &mut self,
3984 text: &str,
3985 autoindent_mode: Option<AutoindentMode>,
3986 cx: &mut ViewContext<Self>,
3987 ) {
3988 if self.read_only(cx) {
3989 return;
3990 }
3991
3992 let text: Arc<str> = text.into();
3993 self.transact(cx, |this, cx| {
3994 let old_selections = this.selections.all_adjusted(cx);
3995 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3996 let anchors = {
3997 let snapshot = buffer.read(cx);
3998 old_selections
3999 .iter()
4000 .map(|s| {
4001 let anchor = snapshot.anchor_after(s.head());
4002 s.map(|_| anchor)
4003 })
4004 .collect::<Vec<_>>()
4005 };
4006 buffer.edit(
4007 old_selections
4008 .iter()
4009 .map(|s| (s.start..s.end, text.clone())),
4010 autoindent_mode,
4011 cx,
4012 );
4013 anchors
4014 });
4015
4016 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
4017 s.select_anchors(selection_anchors);
4018 })
4019 });
4020 }
4021
4022 fn trigger_completion_on_input(
4023 &mut self,
4024 text: &str,
4025 trigger_in_words: bool,
4026 cx: &mut ViewContext<Self>,
4027 ) {
4028 if self.is_completion_trigger(text, trigger_in_words, cx) {
4029 self.show_completions(
4030 &ShowCompletions {
4031 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
4032 },
4033 cx,
4034 );
4035 } else {
4036 self.hide_context_menu(cx);
4037 }
4038 }
4039
4040 fn is_completion_trigger(
4041 &self,
4042 text: &str,
4043 trigger_in_words: bool,
4044 cx: &mut ViewContext<Self>,
4045 ) -> bool {
4046 let position = self.selections.newest_anchor().head();
4047 let multibuffer = self.buffer.read(cx);
4048 let Some(buffer) = position
4049 .buffer_id
4050 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
4051 else {
4052 return false;
4053 };
4054
4055 if let Some(completion_provider) = &self.completion_provider {
4056 completion_provider.is_completion_trigger(
4057 &buffer,
4058 position.text_anchor,
4059 text,
4060 trigger_in_words,
4061 cx,
4062 )
4063 } else {
4064 false
4065 }
4066 }
4067
4068 /// If any empty selections is touching the start of its innermost containing autoclose
4069 /// region, expand it to select the brackets.
4070 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
4071 let selections = self.selections.all::<usize>(cx);
4072 let buffer = self.buffer.read(cx).read(cx);
4073 let new_selections = self
4074 .selections_with_autoclose_regions(selections, &buffer)
4075 .map(|(mut selection, region)| {
4076 if !selection.is_empty() {
4077 return selection;
4078 }
4079
4080 if let Some(region) = region {
4081 let mut range = region.range.to_offset(&buffer);
4082 if selection.start == range.start && range.start >= region.pair.start.len() {
4083 range.start -= region.pair.start.len();
4084 if buffer.contains_str_at(range.start, ®ion.pair.start)
4085 && buffer.contains_str_at(range.end, ®ion.pair.end)
4086 {
4087 range.end += region.pair.end.len();
4088 selection.start = range.start;
4089 selection.end = range.end;
4090
4091 return selection;
4092 }
4093 }
4094 }
4095
4096 let always_treat_brackets_as_autoclosed = buffer
4097 .settings_at(selection.start, cx)
4098 .always_treat_brackets_as_autoclosed;
4099
4100 if !always_treat_brackets_as_autoclosed {
4101 return selection;
4102 }
4103
4104 if let Some(scope) = buffer.language_scope_at(selection.start) {
4105 for (pair, enabled) in scope.brackets() {
4106 if !enabled || !pair.close {
4107 continue;
4108 }
4109
4110 if buffer.contains_str_at(selection.start, &pair.end) {
4111 let pair_start_len = pair.start.len();
4112 if buffer.contains_str_at(
4113 selection.start.saturating_sub(pair_start_len),
4114 &pair.start,
4115 ) {
4116 selection.start -= pair_start_len;
4117 selection.end += pair.end.len();
4118
4119 return selection;
4120 }
4121 }
4122 }
4123 }
4124
4125 selection
4126 })
4127 .collect();
4128
4129 drop(buffer);
4130 self.change_selections(None, cx, |selections| selections.select(new_selections));
4131 }
4132
4133 /// Iterate the given selections, and for each one, find the smallest surrounding
4134 /// autoclose region. This uses the ordering of the selections and the autoclose
4135 /// regions to avoid repeated comparisons.
4136 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4137 &'a self,
4138 selections: impl IntoIterator<Item = Selection<D>>,
4139 buffer: &'a MultiBufferSnapshot,
4140 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4141 let mut i = 0;
4142 let mut regions = self.autoclose_regions.as_slice();
4143 selections.into_iter().map(move |selection| {
4144 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4145
4146 let mut enclosing = None;
4147 while let Some(pair_state) = regions.get(i) {
4148 if pair_state.range.end.to_offset(buffer) < range.start {
4149 regions = ®ions[i + 1..];
4150 i = 0;
4151 } else if pair_state.range.start.to_offset(buffer) > range.end {
4152 break;
4153 } else {
4154 if pair_state.selection_id == selection.id {
4155 enclosing = Some(pair_state);
4156 }
4157 i += 1;
4158 }
4159 }
4160
4161 (selection, enclosing)
4162 })
4163 }
4164
4165 /// Remove any autoclose regions that no longer contain their selection.
4166 fn invalidate_autoclose_regions(
4167 &mut self,
4168 mut selections: &[Selection<Anchor>],
4169 buffer: &MultiBufferSnapshot,
4170 ) {
4171 self.autoclose_regions.retain(|state| {
4172 let mut i = 0;
4173 while let Some(selection) = selections.get(i) {
4174 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4175 selections = &selections[1..];
4176 continue;
4177 }
4178 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4179 break;
4180 }
4181 if selection.id == state.selection_id {
4182 return true;
4183 } else {
4184 i += 1;
4185 }
4186 }
4187 false
4188 });
4189 }
4190
4191 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4192 let offset = position.to_offset(buffer);
4193 let (word_range, kind) = buffer.surrounding_word(offset, true);
4194 if offset > word_range.start && kind == Some(CharKind::Word) {
4195 Some(
4196 buffer
4197 .text_for_range(word_range.start..offset)
4198 .collect::<String>(),
4199 )
4200 } else {
4201 None
4202 }
4203 }
4204
4205 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
4206 self.refresh_inlay_hints(
4207 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
4208 cx,
4209 );
4210 }
4211
4212 pub fn inlay_hints_enabled(&self) -> bool {
4213 self.inlay_hint_cache.enabled
4214 }
4215
4216 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
4217 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
4218 return;
4219 }
4220
4221 let reason_description = reason.description();
4222 let ignore_debounce = matches!(
4223 reason,
4224 InlayHintRefreshReason::SettingsChange(_)
4225 | InlayHintRefreshReason::Toggle(_)
4226 | InlayHintRefreshReason::ExcerptsRemoved(_)
4227 );
4228 let (invalidate_cache, required_languages) = match reason {
4229 InlayHintRefreshReason::Toggle(enabled) => {
4230 self.inlay_hint_cache.enabled = enabled;
4231 if enabled {
4232 (InvalidationStrategy::RefreshRequested, None)
4233 } else {
4234 self.inlay_hint_cache.clear();
4235 self.splice_inlays(
4236 self.visible_inlay_hints(cx)
4237 .iter()
4238 .map(|inlay| inlay.id)
4239 .collect(),
4240 Vec::new(),
4241 cx,
4242 );
4243 return;
4244 }
4245 }
4246 InlayHintRefreshReason::SettingsChange(new_settings) => {
4247 match self.inlay_hint_cache.update_settings(
4248 &self.buffer,
4249 new_settings,
4250 self.visible_inlay_hints(cx),
4251 cx,
4252 ) {
4253 ControlFlow::Break(Some(InlaySplice {
4254 to_remove,
4255 to_insert,
4256 })) => {
4257 self.splice_inlays(to_remove, to_insert, cx);
4258 return;
4259 }
4260 ControlFlow::Break(None) => return,
4261 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4262 }
4263 }
4264 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4265 if let Some(InlaySplice {
4266 to_remove,
4267 to_insert,
4268 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4269 {
4270 self.splice_inlays(to_remove, to_insert, cx);
4271 }
4272 return;
4273 }
4274 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4275 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4276 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4277 }
4278 InlayHintRefreshReason::RefreshRequested => {
4279 (InvalidationStrategy::RefreshRequested, None)
4280 }
4281 };
4282
4283 if let Some(InlaySplice {
4284 to_remove,
4285 to_insert,
4286 }) = self.inlay_hint_cache.spawn_hint_refresh(
4287 reason_description,
4288 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4289 invalidate_cache,
4290 ignore_debounce,
4291 cx,
4292 ) {
4293 self.splice_inlays(to_remove, to_insert, cx);
4294 }
4295 }
4296
4297 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4298 self.display_map
4299 .read(cx)
4300 .current_inlays()
4301 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4302 .cloned()
4303 .collect()
4304 }
4305
4306 pub fn excerpts_for_inlay_hints_query(
4307 &self,
4308 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4309 cx: &mut ViewContext<Editor>,
4310 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4311 let Some(project) = self.project.as_ref() else {
4312 return HashMap::default();
4313 };
4314 let project = project.read(cx);
4315 let multi_buffer = self.buffer().read(cx);
4316 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4317 let multi_buffer_visible_start = self
4318 .scroll_manager
4319 .anchor()
4320 .anchor
4321 .to_point(&multi_buffer_snapshot);
4322 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4323 multi_buffer_visible_start
4324 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4325 Bias::Left,
4326 );
4327 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4328 multi_buffer
4329 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4330 .into_iter()
4331 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4332 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4333 let buffer = buffer_handle.read(cx);
4334 let buffer_file = project::File::from_dyn(buffer.file())?;
4335 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4336 let worktree_entry = buffer_worktree
4337 .read(cx)
4338 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4339 if worktree_entry.is_ignored {
4340 return None;
4341 }
4342
4343 let language = buffer.language()?;
4344 if let Some(restrict_to_languages) = restrict_to_languages {
4345 if !restrict_to_languages.contains(language) {
4346 return None;
4347 }
4348 }
4349 Some((
4350 excerpt_id,
4351 (
4352 buffer_handle,
4353 buffer.version().clone(),
4354 excerpt_visible_range,
4355 ),
4356 ))
4357 })
4358 .collect()
4359 }
4360
4361 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4362 TextLayoutDetails {
4363 text_system: cx.text_system().clone(),
4364 editor_style: self.style.clone().unwrap(),
4365 rem_size: cx.rem_size(),
4366 scroll_anchor: self.scroll_manager.anchor(),
4367 visible_rows: self.visible_line_count(),
4368 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4369 }
4370 }
4371
4372 fn splice_inlays(
4373 &self,
4374 to_remove: Vec<InlayId>,
4375 to_insert: Vec<Inlay>,
4376 cx: &mut ViewContext<Self>,
4377 ) {
4378 self.display_map.update(cx, |display_map, cx| {
4379 display_map.splice_inlays(to_remove, to_insert, cx)
4380 });
4381 cx.notify();
4382 }
4383
4384 fn trigger_on_type_formatting(
4385 &self,
4386 input: String,
4387 cx: &mut ViewContext<Self>,
4388 ) -> Option<Task<Result<()>>> {
4389 if input.len() != 1 {
4390 return None;
4391 }
4392
4393 let project = self.project.as_ref()?;
4394 let position = self.selections.newest_anchor().head();
4395 let (buffer, buffer_position) = self
4396 .buffer
4397 .read(cx)
4398 .text_anchor_for_position(position, cx)?;
4399
4400 let settings = language_settings::language_settings(
4401 buffer
4402 .read(cx)
4403 .language_at(buffer_position)
4404 .map(|l| l.name()),
4405 buffer.read(cx).file(),
4406 cx,
4407 );
4408 if !settings.use_on_type_format {
4409 return None;
4410 }
4411
4412 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4413 // hence we do LSP request & edit on host side only — add formats to host's history.
4414 let push_to_lsp_host_history = true;
4415 // If this is not the host, append its history with new edits.
4416 let push_to_client_history = project.read(cx).is_via_collab();
4417
4418 let on_type_formatting = project.update(cx, |project, cx| {
4419 project.on_type_format(
4420 buffer.clone(),
4421 buffer_position,
4422 input,
4423 push_to_lsp_host_history,
4424 cx,
4425 )
4426 });
4427 Some(cx.spawn(|editor, mut cx| async move {
4428 if let Some(transaction) = on_type_formatting.await? {
4429 if push_to_client_history {
4430 buffer
4431 .update(&mut cx, |buffer, _| {
4432 buffer.push_transaction(transaction, Instant::now());
4433 })
4434 .ok();
4435 }
4436 editor.update(&mut cx, |editor, cx| {
4437 editor.refresh_document_highlights(cx);
4438 })?;
4439 }
4440 Ok(())
4441 }))
4442 }
4443
4444 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4445 if self.pending_rename.is_some() {
4446 return;
4447 }
4448
4449 let Some(provider) = self.completion_provider.as_ref() else {
4450 return;
4451 };
4452
4453 if !self.snippet_stack.is_empty() && self.context_menu.read().as_ref().is_some() {
4454 return;
4455 }
4456
4457 let position = self.selections.newest_anchor().head();
4458 let (buffer, buffer_position) =
4459 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4460 output
4461 } else {
4462 return;
4463 };
4464 let show_completion_documentation = buffer
4465 .read(cx)
4466 .snapshot()
4467 .settings_at(buffer_position, cx)
4468 .show_completion_documentation;
4469
4470 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4471
4472 let aside_was_displayed = match self.context_menu.read().deref() {
4473 Some(ContextMenu::Completions(menu)) => menu.aside_was_displayed.get(),
4474 _ => false,
4475 };
4476 let trigger_kind = match &options.trigger {
4477 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4478 CompletionTriggerKind::TRIGGER_CHARACTER
4479 }
4480 _ => CompletionTriggerKind::INVOKED,
4481 };
4482 let completion_context = CompletionContext {
4483 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4484 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4485 Some(String::from(trigger))
4486 } else {
4487 None
4488 }
4489 }),
4490 trigger_kind,
4491 };
4492 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4493 let sort_completions = provider.sort_completions();
4494
4495 let id = post_inc(&mut self.next_completion_id);
4496 let task = cx.spawn(|editor, mut cx| {
4497 async move {
4498 editor.update(&mut cx, |this, _| {
4499 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4500 })?;
4501 let completions = completions.await.log_err();
4502 let menu = if let Some(completions) = completions {
4503 let mut menu = CompletionsMenu::new(
4504 id,
4505 sort_completions,
4506 show_completion_documentation,
4507 position,
4508 buffer.clone(),
4509 completions.into(),
4510 aside_was_displayed,
4511 );
4512 menu.filter(query.as_deref(), cx.background_executor().clone())
4513 .await;
4514
4515 if menu.matches.is_empty() {
4516 None
4517 } else {
4518 Some(menu)
4519 }
4520 } else {
4521 None
4522 };
4523
4524 editor.update(&mut cx, |editor, cx| {
4525 let mut context_menu = editor.context_menu.write();
4526 match context_menu.as_ref() {
4527 None => {}
4528
4529 Some(ContextMenu::Completions(prev_menu)) => {
4530 if prev_menu.id > id {
4531 return;
4532 }
4533 }
4534
4535 _ => return,
4536 }
4537
4538 if editor.focus_handle.is_focused(cx) && menu.is_some() {
4539 let mut menu = menu.unwrap();
4540 menu.resolve_selected_completion(editor.completion_provider.as_deref(), cx);
4541 *context_menu = Some(ContextMenu::Completions(menu));
4542 drop(context_menu);
4543 editor.discard_inline_completion(false, cx);
4544 cx.notify();
4545 } else if editor.completion_tasks.len() <= 1 {
4546 // If there are no more completion tasks and the last menu was
4547 // empty, we should hide it. If it was already hidden, we should
4548 // also show the copilot completion when available.
4549 drop(context_menu);
4550 if editor.hide_context_menu(cx).is_none() {
4551 editor.update_visible_inline_completion(cx);
4552 }
4553 }
4554 })?;
4555
4556 Ok::<_, anyhow::Error>(())
4557 }
4558 .log_err()
4559 });
4560
4561 self.completion_tasks.push((id, task));
4562 }
4563
4564 pub fn confirm_completion(
4565 &mut self,
4566 action: &ConfirmCompletion,
4567 cx: &mut ViewContext<Self>,
4568 ) -> Option<Task<Result<()>>> {
4569 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4570 }
4571
4572 pub fn compose_completion(
4573 &mut self,
4574 action: &ComposeCompletion,
4575 cx: &mut ViewContext<Self>,
4576 ) -> Option<Task<Result<()>>> {
4577 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4578 }
4579
4580 fn do_completion(
4581 &mut self,
4582 item_ix: Option<usize>,
4583 intent: CompletionIntent,
4584 cx: &mut ViewContext<Editor>,
4585 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4586 use language::ToOffset as _;
4587
4588 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4589 menu
4590 } else {
4591 return None;
4592 };
4593
4594 let mat = completions_menu
4595 .matches
4596 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4597 let buffer_handle = completions_menu.buffer;
4598 let completions = completions_menu.completions.read();
4599 let completion = completions.get(mat.candidate_id)?;
4600 cx.stop_propagation();
4601
4602 let snippet;
4603 let text;
4604
4605 if completion.is_snippet() {
4606 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4607 text = snippet.as_ref().unwrap().text.clone();
4608 } else {
4609 snippet = None;
4610 text = completion.new_text.clone();
4611 };
4612 let selections = self.selections.all::<usize>(cx);
4613 let buffer = buffer_handle.read(cx);
4614 let old_range = completion.old_range.to_offset(buffer);
4615 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4616
4617 let newest_selection = self.selections.newest_anchor();
4618 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4619 return None;
4620 }
4621
4622 let lookbehind = newest_selection
4623 .start
4624 .text_anchor
4625 .to_offset(buffer)
4626 .saturating_sub(old_range.start);
4627 let lookahead = old_range
4628 .end
4629 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4630 let mut common_prefix_len = old_text
4631 .bytes()
4632 .zip(text.bytes())
4633 .take_while(|(a, b)| a == b)
4634 .count();
4635
4636 let snapshot = self.buffer.read(cx).snapshot(cx);
4637 let mut range_to_replace: Option<Range<isize>> = None;
4638 let mut ranges = Vec::new();
4639 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4640 for selection in &selections {
4641 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4642 let start = selection.start.saturating_sub(lookbehind);
4643 let end = selection.end + lookahead;
4644 if selection.id == newest_selection.id {
4645 range_to_replace = Some(
4646 ((start + common_prefix_len) as isize - selection.start as isize)
4647 ..(end as isize - selection.start as isize),
4648 );
4649 }
4650 ranges.push(start + common_prefix_len..end);
4651 } else {
4652 common_prefix_len = 0;
4653 ranges.clear();
4654 ranges.extend(selections.iter().map(|s| {
4655 if s.id == newest_selection.id {
4656 range_to_replace = Some(
4657 old_range.start.to_offset_utf16(&snapshot).0 as isize
4658 - selection.start as isize
4659 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4660 - selection.start as isize,
4661 );
4662 old_range.clone()
4663 } else {
4664 s.start..s.end
4665 }
4666 }));
4667 break;
4668 }
4669 if !self.linked_edit_ranges.is_empty() {
4670 let start_anchor = snapshot.anchor_before(selection.head());
4671 let end_anchor = snapshot.anchor_after(selection.tail());
4672 if let Some(ranges) = self
4673 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4674 {
4675 for (buffer, edits) in ranges {
4676 linked_edits.entry(buffer.clone()).or_default().extend(
4677 edits
4678 .into_iter()
4679 .map(|range| (range, text[common_prefix_len..].to_owned())),
4680 );
4681 }
4682 }
4683 }
4684 }
4685 let text = &text[common_prefix_len..];
4686
4687 cx.emit(EditorEvent::InputHandled {
4688 utf16_range_to_replace: range_to_replace,
4689 text: text.into(),
4690 });
4691
4692 self.transact(cx, |this, cx| {
4693 if let Some(mut snippet) = snippet {
4694 snippet.text = text.to_string();
4695 for tabstop in snippet
4696 .tabstops
4697 .iter_mut()
4698 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4699 {
4700 tabstop.start -= common_prefix_len as isize;
4701 tabstop.end -= common_prefix_len as isize;
4702 }
4703
4704 this.insert_snippet(&ranges, snippet, cx).log_err();
4705 } else {
4706 this.buffer.update(cx, |buffer, cx| {
4707 buffer.edit(
4708 ranges.iter().map(|range| (range.clone(), text)),
4709 this.autoindent_mode.clone(),
4710 cx,
4711 );
4712 });
4713 }
4714 for (buffer, edits) in linked_edits {
4715 buffer.update(cx, |buffer, cx| {
4716 let snapshot = buffer.snapshot();
4717 let edits = edits
4718 .into_iter()
4719 .map(|(range, text)| {
4720 use text::ToPoint as TP;
4721 let end_point = TP::to_point(&range.end, &snapshot);
4722 let start_point = TP::to_point(&range.start, &snapshot);
4723 (start_point..end_point, text)
4724 })
4725 .sorted_by_key(|(range, _)| range.start)
4726 .collect::<Vec<_>>();
4727 buffer.edit(edits, None, cx);
4728 })
4729 }
4730
4731 this.refresh_inline_completion(true, false, cx);
4732 });
4733
4734 let show_new_completions_on_confirm = completion
4735 .confirm
4736 .as_ref()
4737 .map_or(false, |confirm| confirm(intent, cx));
4738 if show_new_completions_on_confirm {
4739 self.show_completions(&ShowCompletions { trigger: None }, cx);
4740 }
4741
4742 let provider = self.completion_provider.as_ref()?;
4743 let apply_edits = provider.apply_additional_edits_for_completion(
4744 buffer_handle,
4745 completion.clone(),
4746 true,
4747 cx,
4748 );
4749
4750 let editor_settings = EditorSettings::get_global(cx);
4751 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4752 // After the code completion is finished, users often want to know what signatures are needed.
4753 // so we should automatically call signature_help
4754 self.show_signature_help(&ShowSignatureHelp, cx);
4755 }
4756
4757 Some(cx.foreground_executor().spawn(async move {
4758 apply_edits.await?;
4759 Ok(())
4760 }))
4761 }
4762
4763 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4764 let mut context_menu = self.context_menu.write();
4765 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4766 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4767 // Toggle if we're selecting the same one
4768 *context_menu = None;
4769 cx.notify();
4770 return;
4771 } else {
4772 // Otherwise, clear it and start a new one
4773 *context_menu = None;
4774 cx.notify();
4775 }
4776 }
4777 drop(context_menu);
4778 let snapshot = self.snapshot(cx);
4779 let deployed_from_indicator = action.deployed_from_indicator;
4780 let mut task = self.code_actions_task.take();
4781 let action = action.clone();
4782 cx.spawn(|editor, mut cx| async move {
4783 while let Some(prev_task) = task {
4784 prev_task.await.log_err();
4785 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4786 }
4787
4788 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4789 if editor.focus_handle.is_focused(cx) {
4790 let multibuffer_point = action
4791 .deployed_from_indicator
4792 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4793 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4794 let (buffer, buffer_row) = snapshot
4795 .buffer_snapshot
4796 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4797 .and_then(|(buffer_snapshot, range)| {
4798 editor
4799 .buffer
4800 .read(cx)
4801 .buffer(buffer_snapshot.remote_id())
4802 .map(|buffer| (buffer, range.start.row))
4803 })?;
4804 let (_, code_actions) = editor
4805 .available_code_actions
4806 .clone()
4807 .and_then(|(location, code_actions)| {
4808 let snapshot = location.buffer.read(cx).snapshot();
4809 let point_range = location.range.to_point(&snapshot);
4810 let point_range = point_range.start.row..=point_range.end.row;
4811 if point_range.contains(&buffer_row) {
4812 Some((location, code_actions))
4813 } else {
4814 None
4815 }
4816 })
4817 .unzip();
4818 let buffer_id = buffer.read(cx).remote_id();
4819 let tasks = editor
4820 .tasks
4821 .get(&(buffer_id, buffer_row))
4822 .map(|t| Arc::new(t.to_owned()));
4823 if tasks.is_none() && code_actions.is_none() {
4824 return None;
4825 }
4826
4827 editor.completion_tasks.clear();
4828 editor.discard_inline_completion(false, cx);
4829 let task_context =
4830 tasks
4831 .as_ref()
4832 .zip(editor.project.clone())
4833 .map(|(tasks, project)| {
4834 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4835 });
4836
4837 Some(cx.spawn(|editor, mut cx| async move {
4838 let task_context = match task_context {
4839 Some(task_context) => task_context.await,
4840 None => None,
4841 };
4842 let resolved_tasks =
4843 tasks.zip(task_context).map(|(tasks, task_context)| {
4844 Arc::new(ResolvedTasks {
4845 templates: tasks.resolve(&task_context).collect(),
4846 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4847 multibuffer_point.row,
4848 tasks.column,
4849 )),
4850 })
4851 });
4852 let spawn_straight_away = resolved_tasks
4853 .as_ref()
4854 .map_or(false, |tasks| tasks.templates.len() == 1)
4855 && code_actions
4856 .as_ref()
4857 .map_or(true, |actions| actions.is_empty());
4858 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4859 *editor.context_menu.write() =
4860 Some(ContextMenu::CodeActions(CodeActionsMenu {
4861 buffer,
4862 actions: CodeActionContents {
4863 tasks: resolved_tasks,
4864 actions: code_actions,
4865 },
4866 selected_item: Default::default(),
4867 scroll_handle: UniformListScrollHandle::default(),
4868 deployed_from_indicator,
4869 }));
4870 if spawn_straight_away {
4871 if let Some(task) = editor.confirm_code_action(
4872 &ConfirmCodeAction { item_ix: Some(0) },
4873 cx,
4874 ) {
4875 cx.notify();
4876 return task;
4877 }
4878 }
4879 cx.notify();
4880 Task::ready(Ok(()))
4881 }) {
4882 task.await
4883 } else {
4884 Ok(())
4885 }
4886 }))
4887 } else {
4888 Some(Task::ready(Ok(())))
4889 }
4890 })?;
4891 if let Some(task) = spawned_test_task {
4892 task.await?;
4893 }
4894
4895 Ok::<_, anyhow::Error>(())
4896 })
4897 .detach_and_log_err(cx);
4898 }
4899
4900 pub fn confirm_code_action(
4901 &mut self,
4902 action: &ConfirmCodeAction,
4903 cx: &mut ViewContext<Self>,
4904 ) -> Option<Task<Result<()>>> {
4905 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4906 menu
4907 } else {
4908 return None;
4909 };
4910 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4911 let action = actions_menu.actions.get(action_ix)?;
4912 let title = action.label();
4913 let buffer = actions_menu.buffer;
4914 let workspace = self.workspace()?;
4915
4916 match action {
4917 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4918 workspace.update(cx, |workspace, cx| {
4919 workspace::tasks::schedule_resolved_task(
4920 workspace,
4921 task_source_kind,
4922 resolved_task,
4923 false,
4924 cx,
4925 );
4926
4927 Some(Task::ready(Ok(())))
4928 })
4929 }
4930 CodeActionsItem::CodeAction {
4931 excerpt_id,
4932 action,
4933 provider,
4934 } => {
4935 let apply_code_action =
4936 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4937 let workspace = workspace.downgrade();
4938 Some(cx.spawn(|editor, cx| async move {
4939 let project_transaction = apply_code_action.await?;
4940 Self::open_project_transaction(
4941 &editor,
4942 workspace,
4943 project_transaction,
4944 title,
4945 cx,
4946 )
4947 .await
4948 }))
4949 }
4950 }
4951 }
4952
4953 pub async fn open_project_transaction(
4954 this: &WeakView<Editor>,
4955 workspace: WeakView<Workspace>,
4956 transaction: ProjectTransaction,
4957 title: String,
4958 mut cx: AsyncWindowContext,
4959 ) -> Result<()> {
4960 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4961 cx.update(|cx| {
4962 entries.sort_unstable_by_key(|(buffer, _)| {
4963 buffer.read(cx).file().map(|f| f.path().clone())
4964 });
4965 })?;
4966
4967 // If the project transaction's edits are all contained within this editor, then
4968 // avoid opening a new editor to display them.
4969
4970 if let Some((buffer, transaction)) = entries.first() {
4971 if entries.len() == 1 {
4972 let excerpt = this.update(&mut cx, |editor, cx| {
4973 editor
4974 .buffer()
4975 .read(cx)
4976 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4977 })?;
4978 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4979 if excerpted_buffer == *buffer {
4980 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4981 let excerpt_range = excerpt_range.to_offset(buffer);
4982 buffer
4983 .edited_ranges_for_transaction::<usize>(transaction)
4984 .all(|range| {
4985 excerpt_range.start <= range.start
4986 && excerpt_range.end >= range.end
4987 })
4988 })?;
4989
4990 if all_edits_within_excerpt {
4991 return Ok(());
4992 }
4993 }
4994 }
4995 }
4996 } else {
4997 return Ok(());
4998 }
4999
5000 let mut ranges_to_highlight = Vec::new();
5001 let excerpt_buffer = cx.new_model(|cx| {
5002 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5003 for (buffer_handle, transaction) in &entries {
5004 let buffer = buffer_handle.read(cx);
5005 ranges_to_highlight.extend(
5006 multibuffer.push_excerpts_with_context_lines(
5007 buffer_handle.clone(),
5008 buffer
5009 .edited_ranges_for_transaction::<usize>(transaction)
5010 .collect(),
5011 DEFAULT_MULTIBUFFER_CONTEXT,
5012 cx,
5013 ),
5014 );
5015 }
5016 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5017 multibuffer
5018 })?;
5019
5020 workspace.update(&mut cx, |workspace, cx| {
5021 let project = workspace.project().clone();
5022 let editor =
5023 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
5024 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
5025 editor.update(cx, |editor, cx| {
5026 editor.highlight_background::<Self>(
5027 &ranges_to_highlight,
5028 |theme| theme.editor_highlighted_line_background,
5029 cx,
5030 );
5031 });
5032 })?;
5033
5034 Ok(())
5035 }
5036
5037 pub fn clear_code_action_providers(&mut self) {
5038 self.code_action_providers.clear();
5039 self.available_code_actions.take();
5040 }
5041
5042 pub fn push_code_action_provider(
5043 &mut self,
5044 provider: Arc<dyn CodeActionProvider>,
5045 cx: &mut ViewContext<Self>,
5046 ) {
5047 self.code_action_providers.push(provider);
5048 self.refresh_code_actions(cx);
5049 }
5050
5051 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5052 let buffer = self.buffer.read(cx);
5053 let newest_selection = self.selections.newest_anchor().clone();
5054 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
5055 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
5056 if start_buffer != end_buffer {
5057 return None;
5058 }
5059
5060 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
5061 cx.background_executor()
5062 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5063 .await;
5064
5065 let (providers, tasks) = this.update(&mut cx, |this, cx| {
5066 let providers = this.code_action_providers.clone();
5067 let tasks = this
5068 .code_action_providers
5069 .iter()
5070 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
5071 .collect::<Vec<_>>();
5072 (providers, tasks)
5073 })?;
5074
5075 let mut actions = Vec::new();
5076 for (provider, provider_actions) in
5077 providers.into_iter().zip(future::join_all(tasks).await)
5078 {
5079 if let Some(provider_actions) = provider_actions.log_err() {
5080 actions.extend(provider_actions.into_iter().map(|action| {
5081 AvailableCodeAction {
5082 excerpt_id: newest_selection.start.excerpt_id,
5083 action,
5084 provider: provider.clone(),
5085 }
5086 }));
5087 }
5088 }
5089
5090 this.update(&mut cx, |this, cx| {
5091 this.available_code_actions = if actions.is_empty() {
5092 None
5093 } else {
5094 Some((
5095 Location {
5096 buffer: start_buffer,
5097 range: start..end,
5098 },
5099 actions.into(),
5100 ))
5101 };
5102 cx.notify();
5103 })
5104 }));
5105 None
5106 }
5107
5108 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
5109 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5110 self.show_git_blame_inline = false;
5111
5112 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
5113 cx.background_executor().timer(delay).await;
5114
5115 this.update(&mut cx, |this, cx| {
5116 this.show_git_blame_inline = true;
5117 cx.notify();
5118 })
5119 .log_err();
5120 }));
5121 }
5122 }
5123
5124 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5125 if self.pending_rename.is_some() {
5126 return None;
5127 }
5128
5129 let provider = self.semantics_provider.clone()?;
5130 let buffer = self.buffer.read(cx);
5131 let newest_selection = self.selections.newest_anchor().clone();
5132 let cursor_position = newest_selection.head();
5133 let (cursor_buffer, cursor_buffer_position) =
5134 buffer.text_anchor_for_position(cursor_position, cx)?;
5135 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5136 if cursor_buffer != tail_buffer {
5137 return None;
5138 }
5139
5140 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
5141 cx.background_executor()
5142 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
5143 .await;
5144
5145 let highlights = if let Some(highlights) = cx
5146 .update(|cx| {
5147 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5148 })
5149 .ok()
5150 .flatten()
5151 {
5152 highlights.await.log_err()
5153 } else {
5154 None
5155 };
5156
5157 if let Some(highlights) = highlights {
5158 this.update(&mut cx, |this, cx| {
5159 if this.pending_rename.is_some() {
5160 return;
5161 }
5162
5163 let buffer_id = cursor_position.buffer_id;
5164 let buffer = this.buffer.read(cx);
5165 if !buffer
5166 .text_anchor_for_position(cursor_position, cx)
5167 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5168 {
5169 return;
5170 }
5171
5172 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5173 let mut write_ranges = Vec::new();
5174 let mut read_ranges = Vec::new();
5175 for highlight in highlights {
5176 for (excerpt_id, excerpt_range) in
5177 buffer.excerpts_for_buffer(&cursor_buffer, cx)
5178 {
5179 let start = highlight
5180 .range
5181 .start
5182 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5183 let end = highlight
5184 .range
5185 .end
5186 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5187 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5188 continue;
5189 }
5190
5191 let range = Anchor {
5192 buffer_id,
5193 excerpt_id,
5194 text_anchor: start,
5195 }..Anchor {
5196 buffer_id,
5197 excerpt_id,
5198 text_anchor: end,
5199 };
5200 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5201 write_ranges.push(range);
5202 } else {
5203 read_ranges.push(range);
5204 }
5205 }
5206 }
5207
5208 this.highlight_background::<DocumentHighlightRead>(
5209 &read_ranges,
5210 |theme| theme.editor_document_highlight_read_background,
5211 cx,
5212 );
5213 this.highlight_background::<DocumentHighlightWrite>(
5214 &write_ranges,
5215 |theme| theme.editor_document_highlight_write_background,
5216 cx,
5217 );
5218 cx.notify();
5219 })
5220 .log_err();
5221 }
5222 }));
5223 None
5224 }
5225
5226 pub fn refresh_inline_completion(
5227 &mut self,
5228 debounce: bool,
5229 user_requested: bool,
5230 cx: &mut ViewContext<Self>,
5231 ) -> Option<()> {
5232 let provider = self.inline_completion_provider()?;
5233 let cursor = self.selections.newest_anchor().head();
5234 let (buffer, cursor_buffer_position) =
5235 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5236
5237 if !user_requested
5238 && (!self.enable_inline_completions
5239 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5240 || !self.is_focused(cx))
5241 {
5242 self.discard_inline_completion(false, cx);
5243 return None;
5244 }
5245
5246 self.update_visible_inline_completion(cx);
5247 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
5248 Some(())
5249 }
5250
5251 fn cycle_inline_completion(
5252 &mut self,
5253 direction: Direction,
5254 cx: &mut ViewContext<Self>,
5255 ) -> Option<()> {
5256 let provider = self.inline_completion_provider()?;
5257 let cursor = self.selections.newest_anchor().head();
5258 let (buffer, cursor_buffer_position) =
5259 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5260 if !self.enable_inline_completions
5261 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5262 {
5263 return None;
5264 }
5265
5266 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5267 self.update_visible_inline_completion(cx);
5268
5269 Some(())
5270 }
5271
5272 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5273 if !self.has_active_inline_completion() {
5274 self.refresh_inline_completion(false, true, cx);
5275 return;
5276 }
5277
5278 self.update_visible_inline_completion(cx);
5279 }
5280
5281 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5282 self.show_cursor_names(cx);
5283 }
5284
5285 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5286 self.show_cursor_names = true;
5287 cx.notify();
5288 cx.spawn(|this, mut cx| async move {
5289 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5290 this.update(&mut cx, |this, cx| {
5291 this.show_cursor_names = false;
5292 cx.notify()
5293 })
5294 .ok()
5295 })
5296 .detach();
5297 }
5298
5299 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5300 if self.has_active_inline_completion() {
5301 self.cycle_inline_completion(Direction::Next, cx);
5302 } else {
5303 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5304 if is_copilot_disabled {
5305 cx.propagate();
5306 }
5307 }
5308 }
5309
5310 pub fn previous_inline_completion(
5311 &mut self,
5312 _: &PreviousInlineCompletion,
5313 cx: &mut ViewContext<Self>,
5314 ) {
5315 if self.has_active_inline_completion() {
5316 self.cycle_inline_completion(Direction::Prev, cx);
5317 } else {
5318 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5319 if is_copilot_disabled {
5320 cx.propagate();
5321 }
5322 }
5323 }
5324
5325 pub fn accept_inline_completion(
5326 &mut self,
5327 _: &AcceptInlineCompletion,
5328 cx: &mut ViewContext<Self>,
5329 ) {
5330 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5331 return;
5332 };
5333
5334 self.report_inline_completion_event(true, cx);
5335
5336 match &active_inline_completion.completion {
5337 InlineCompletion::Move(position) => {
5338 let position = *position;
5339 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
5340 selections.select_anchor_ranges([position..position]);
5341 });
5342 }
5343 InlineCompletion::Edit(edits) => {
5344 if let Some(provider) = self.inline_completion_provider() {
5345 provider.accept(cx);
5346 }
5347
5348 let snapshot = self.buffer.read(cx).snapshot(cx);
5349 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5350
5351 self.buffer.update(cx, |buffer, cx| {
5352 buffer.edit(edits.iter().cloned(), None, cx)
5353 });
5354
5355 self.change_selections(None, cx, |s| {
5356 s.select_anchor_ranges([last_edit_end..last_edit_end])
5357 });
5358
5359 self.update_visible_inline_completion(cx);
5360 if self.active_inline_completion.is_none() {
5361 self.refresh_inline_completion(true, true, cx);
5362 }
5363
5364 cx.notify();
5365 }
5366 }
5367 }
5368
5369 pub fn accept_partial_inline_completion(
5370 &mut self,
5371 _: &AcceptPartialInlineCompletion,
5372 cx: &mut ViewContext<Self>,
5373 ) {
5374 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5375 return;
5376 };
5377 if self.selections.count() != 1 {
5378 return;
5379 }
5380
5381 self.report_inline_completion_event(true, cx);
5382
5383 match &active_inline_completion.completion {
5384 InlineCompletion::Move(position) => {
5385 let position = *position;
5386 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
5387 selections.select_anchor_ranges([position..position]);
5388 });
5389 }
5390 InlineCompletion::Edit(edits) => {
5391 if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
5392 let text = edits[0].1.as_str();
5393 let mut partial_completion = text
5394 .chars()
5395 .by_ref()
5396 .take_while(|c| c.is_alphabetic())
5397 .collect::<String>();
5398 if partial_completion.is_empty() {
5399 partial_completion = text
5400 .chars()
5401 .by_ref()
5402 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5403 .collect::<String>();
5404 }
5405
5406 cx.emit(EditorEvent::InputHandled {
5407 utf16_range_to_replace: None,
5408 text: partial_completion.clone().into(),
5409 });
5410
5411 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5412
5413 self.refresh_inline_completion(true, true, cx);
5414 cx.notify();
5415 }
5416 }
5417 }
5418 }
5419
5420 fn discard_inline_completion(
5421 &mut self,
5422 should_report_inline_completion_event: bool,
5423 cx: &mut ViewContext<Self>,
5424 ) -> bool {
5425 if should_report_inline_completion_event {
5426 self.report_inline_completion_event(false, cx);
5427 }
5428
5429 if let Some(provider) = self.inline_completion_provider() {
5430 provider.discard(cx);
5431 }
5432
5433 self.take_active_inline_completion(cx).is_some()
5434 }
5435
5436 fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
5437 let Some(provider) = self.inline_completion_provider() else {
5438 return;
5439 };
5440 let Some(project) = self.project.as_ref() else {
5441 return;
5442 };
5443 let Some((_, buffer, _)) = self
5444 .buffer
5445 .read(cx)
5446 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5447 else {
5448 return;
5449 };
5450
5451 let project = project.read(cx);
5452 let extension = buffer
5453 .read(cx)
5454 .file()
5455 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5456 project.client().telemetry().report_inline_completion_event(
5457 provider.name().into(),
5458 accepted,
5459 extension,
5460 );
5461 }
5462
5463 pub fn has_active_inline_completion(&self) -> bool {
5464 self.active_inline_completion.is_some()
5465 }
5466
5467 fn take_active_inline_completion(
5468 &mut self,
5469 cx: &mut ViewContext<Self>,
5470 ) -> Option<InlineCompletion> {
5471 let active_inline_completion = self.active_inline_completion.take()?;
5472 self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
5473 self.clear_highlights::<InlineCompletionHighlight>(cx);
5474 Some(active_inline_completion.completion)
5475 }
5476
5477 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5478 let selection = self.selections.newest_anchor();
5479 let cursor = selection.head();
5480 let multibuffer = self.buffer.read(cx).snapshot(cx);
5481 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5482 let excerpt_id = cursor.excerpt_id;
5483
5484 if self.context_menu.read().is_some()
5485 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion())
5486 || !offset_selection.is_empty()
5487 || self
5488 .active_inline_completion
5489 .as_ref()
5490 .map_or(false, |completion| {
5491 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5492 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5493 !invalidation_range.contains(&offset_selection.head())
5494 })
5495 {
5496 self.discard_inline_completion(false, cx);
5497 return None;
5498 }
5499
5500 self.take_active_inline_completion(cx);
5501 let provider = self.inline_completion_provider()?;
5502
5503 let (buffer, cursor_buffer_position) =
5504 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5505
5506 let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5507 let edits = completion
5508 .edits
5509 .into_iter()
5510 .map(|(range, new_text)| {
5511 (
5512 multibuffer
5513 .anchor_in_excerpt(excerpt_id, range.start)
5514 .unwrap()
5515 ..multibuffer
5516 .anchor_in_excerpt(excerpt_id, range.end)
5517 .unwrap(),
5518 new_text,
5519 )
5520 })
5521 .collect::<Vec<_>>();
5522 if edits.is_empty() {
5523 return None;
5524 }
5525
5526 let first_edit_start = edits.first().unwrap().0.start;
5527 let edit_start_row = first_edit_start
5528 .to_point(&multibuffer)
5529 .row
5530 .saturating_sub(2);
5531
5532 let last_edit_end = edits.last().unwrap().0.end;
5533 let edit_end_row = cmp::min(
5534 multibuffer.max_point().row,
5535 last_edit_end.to_point(&multibuffer).row + 2,
5536 );
5537
5538 let cursor_row = cursor.to_point(&multibuffer).row;
5539
5540 let mut inlay_ids = Vec::new();
5541 let invalidation_row_range;
5542 let completion;
5543 if cursor_row < edit_start_row {
5544 invalidation_row_range = cursor_row..edit_end_row;
5545 completion = InlineCompletion::Move(first_edit_start);
5546 } else if cursor_row > edit_end_row {
5547 invalidation_row_range = edit_start_row..cursor_row;
5548 completion = InlineCompletion::Move(first_edit_start);
5549 } else {
5550 if edits
5551 .iter()
5552 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5553 {
5554 let mut inlays = Vec::new();
5555 for (range, new_text) in &edits {
5556 let inlay = Inlay::suggestion(
5557 post_inc(&mut self.next_inlay_id),
5558 range.start,
5559 new_text.as_str(),
5560 );
5561 inlay_ids.push(inlay.id);
5562 inlays.push(inlay);
5563 }
5564
5565 self.splice_inlays(vec![], inlays, cx);
5566 } else {
5567 let background_color = cx.theme().status().deleted_background;
5568 self.highlight_text::<InlineCompletionHighlight>(
5569 edits.iter().map(|(range, _)| range.clone()).collect(),
5570 HighlightStyle {
5571 background_color: Some(background_color),
5572 ..Default::default()
5573 },
5574 cx,
5575 );
5576 }
5577
5578 invalidation_row_range = edit_start_row..edit_end_row;
5579 completion = InlineCompletion::Edit(edits);
5580 };
5581
5582 let invalidation_range = multibuffer
5583 .anchor_before(Point::new(invalidation_row_range.start, 0))
5584 ..multibuffer.anchor_after(Point::new(
5585 invalidation_row_range.end,
5586 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5587 ));
5588
5589 self.active_inline_completion = Some(InlineCompletionState {
5590 inlay_ids,
5591 completion,
5592 invalidation_range,
5593 });
5594 cx.notify();
5595
5596 Some(())
5597 }
5598
5599 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5600 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5601 }
5602
5603 fn render_code_actions_indicator(
5604 &self,
5605 _style: &EditorStyle,
5606 row: DisplayRow,
5607 is_active: bool,
5608 cx: &mut ViewContext<Self>,
5609 ) -> Option<IconButton> {
5610 if self.available_code_actions.is_some() {
5611 Some(
5612 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5613 .shape(ui::IconButtonShape::Square)
5614 .icon_size(IconSize::XSmall)
5615 .icon_color(Color::Muted)
5616 .selected(is_active)
5617 .tooltip({
5618 let focus_handle = self.focus_handle.clone();
5619 move |cx| {
5620 Tooltip::for_action_in(
5621 "Toggle Code Actions",
5622 &ToggleCodeActions {
5623 deployed_from_indicator: None,
5624 },
5625 &focus_handle,
5626 cx,
5627 )
5628 }
5629 })
5630 .on_click(cx.listener(move |editor, _e, cx| {
5631 editor.focus(cx);
5632 editor.toggle_code_actions(
5633 &ToggleCodeActions {
5634 deployed_from_indicator: Some(row),
5635 },
5636 cx,
5637 );
5638 })),
5639 )
5640 } else {
5641 None
5642 }
5643 }
5644
5645 fn clear_tasks(&mut self) {
5646 self.tasks.clear()
5647 }
5648
5649 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5650 if self.tasks.insert(key, value).is_some() {
5651 // This case should hopefully be rare, but just in case...
5652 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5653 }
5654 }
5655
5656 fn build_tasks_context(
5657 project: &Model<Project>,
5658 buffer: &Model<Buffer>,
5659 buffer_row: u32,
5660 tasks: &Arc<RunnableTasks>,
5661 cx: &mut ViewContext<Self>,
5662 ) -> Task<Option<task::TaskContext>> {
5663 let position = Point::new(buffer_row, tasks.column);
5664 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5665 let location = Location {
5666 buffer: buffer.clone(),
5667 range: range_start..range_start,
5668 };
5669 // Fill in the environmental variables from the tree-sitter captures
5670 let mut captured_task_variables = TaskVariables::default();
5671 for (capture_name, value) in tasks.extra_variables.clone() {
5672 captured_task_variables.insert(
5673 task::VariableName::Custom(capture_name.into()),
5674 value.clone(),
5675 );
5676 }
5677 project.update(cx, |project, cx| {
5678 project.task_store().update(cx, |task_store, cx| {
5679 task_store.task_context_for_location(captured_task_variables, location, cx)
5680 })
5681 })
5682 }
5683
5684 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
5685 let Some((workspace, _)) = self.workspace.clone() else {
5686 return;
5687 };
5688 let Some(project) = self.project.clone() else {
5689 return;
5690 };
5691
5692 // Try to find a closest, enclosing node using tree-sitter that has a
5693 // task
5694 let Some((buffer, buffer_row, tasks)) = self
5695 .find_enclosing_node_task(cx)
5696 // Or find the task that's closest in row-distance.
5697 .or_else(|| self.find_closest_task(cx))
5698 else {
5699 return;
5700 };
5701
5702 let reveal_strategy = action.reveal;
5703 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5704 cx.spawn(|_, mut cx| async move {
5705 let context = task_context.await?;
5706 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5707
5708 let resolved = resolved_task.resolved.as_mut()?;
5709 resolved.reveal = reveal_strategy;
5710
5711 workspace
5712 .update(&mut cx, |workspace, cx| {
5713 workspace::tasks::schedule_resolved_task(
5714 workspace,
5715 task_source_kind,
5716 resolved_task,
5717 false,
5718 cx,
5719 );
5720 })
5721 .ok()
5722 })
5723 .detach();
5724 }
5725
5726 fn find_closest_task(
5727 &mut self,
5728 cx: &mut ViewContext<Self>,
5729 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5730 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5731
5732 let ((buffer_id, row), tasks) = self
5733 .tasks
5734 .iter()
5735 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5736
5737 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5738 let tasks = Arc::new(tasks.to_owned());
5739 Some((buffer, *row, tasks))
5740 }
5741
5742 fn find_enclosing_node_task(
5743 &mut self,
5744 cx: &mut ViewContext<Self>,
5745 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5746 let snapshot = self.buffer.read(cx).snapshot(cx);
5747 let offset = self.selections.newest::<usize>(cx).head();
5748 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5749 let buffer_id = excerpt.buffer().remote_id();
5750
5751 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5752 let mut cursor = layer.node().walk();
5753
5754 while cursor.goto_first_child_for_byte(offset).is_some() {
5755 if cursor.node().end_byte() == offset {
5756 cursor.goto_next_sibling();
5757 }
5758 }
5759
5760 // Ascend to the smallest ancestor that contains the range and has a task.
5761 loop {
5762 let node = cursor.node();
5763 let node_range = node.byte_range();
5764 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5765
5766 // Check if this node contains our offset
5767 if node_range.start <= offset && node_range.end >= offset {
5768 // If it contains offset, check for task
5769 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5770 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5771 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5772 }
5773 }
5774
5775 if !cursor.goto_parent() {
5776 break;
5777 }
5778 }
5779 None
5780 }
5781
5782 fn render_run_indicator(
5783 &self,
5784 _style: &EditorStyle,
5785 is_active: bool,
5786 row: DisplayRow,
5787 cx: &mut ViewContext<Self>,
5788 ) -> IconButton {
5789 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5790 .shape(ui::IconButtonShape::Square)
5791 .icon_size(IconSize::XSmall)
5792 .icon_color(Color::Muted)
5793 .selected(is_active)
5794 .on_click(cx.listener(move |editor, _e, cx| {
5795 editor.focus(cx);
5796 editor.toggle_code_actions(
5797 &ToggleCodeActions {
5798 deployed_from_indicator: Some(row),
5799 },
5800 cx,
5801 );
5802 }))
5803 }
5804
5805 pub fn context_menu_visible(&self) -> bool {
5806 self.context_menu
5807 .read()
5808 .as_ref()
5809 .map_or(false, |menu| menu.visible())
5810 }
5811
5812 fn render_context_menu(
5813 &self,
5814 cursor_position: DisplayPoint,
5815 style: &EditorStyle,
5816 max_height: Pixels,
5817 cx: &mut ViewContext<Editor>,
5818 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5819 self.context_menu.read().as_ref().map(|menu| {
5820 menu.render(
5821 cursor_position,
5822 style,
5823 max_height,
5824 self.workspace.as_ref().map(|(w, _)| w.clone()),
5825 cx,
5826 )
5827 })
5828 }
5829
5830 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5831 cx.notify();
5832 self.completion_tasks.clear();
5833 let context_menu = self.context_menu.write().take();
5834 if context_menu.is_some() {
5835 self.update_visible_inline_completion(cx);
5836 }
5837 context_menu
5838 }
5839
5840 fn show_snippet_choices(
5841 &mut self,
5842 choices: &Vec<String>,
5843 selection: Range<Anchor>,
5844 cx: &mut ViewContext<Self>,
5845 ) {
5846 if selection.start.buffer_id.is_none() {
5847 return;
5848 }
5849 let buffer_id = selection.start.buffer_id.unwrap();
5850 let buffer = self.buffer().read(cx).buffer(buffer_id);
5851 let id = post_inc(&mut self.next_completion_id);
5852
5853 if let Some(buffer) = buffer {
5854 *self.context_menu.write() = Some(ContextMenu::Completions(
5855 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5856 ));
5857 }
5858 }
5859
5860 pub fn insert_snippet(
5861 &mut self,
5862 insertion_ranges: &[Range<usize>],
5863 snippet: Snippet,
5864 cx: &mut ViewContext<Self>,
5865 ) -> Result<()> {
5866 struct Tabstop<T> {
5867 is_end_tabstop: bool,
5868 ranges: Vec<Range<T>>,
5869 choices: Option<Vec<String>>,
5870 }
5871
5872 let tabstops = self.buffer.update(cx, |buffer, cx| {
5873 let snippet_text: Arc<str> = snippet.text.clone().into();
5874 buffer.edit(
5875 insertion_ranges
5876 .iter()
5877 .cloned()
5878 .map(|range| (range, snippet_text.clone())),
5879 Some(AutoindentMode::EachLine),
5880 cx,
5881 );
5882
5883 let snapshot = &*buffer.read(cx);
5884 let snippet = &snippet;
5885 snippet
5886 .tabstops
5887 .iter()
5888 .map(|tabstop| {
5889 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5890 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5891 });
5892 let mut tabstop_ranges = tabstop
5893 .ranges
5894 .iter()
5895 .flat_map(|tabstop_range| {
5896 let mut delta = 0_isize;
5897 insertion_ranges.iter().map(move |insertion_range| {
5898 let insertion_start = insertion_range.start as isize + delta;
5899 delta +=
5900 snippet.text.len() as isize - insertion_range.len() as isize;
5901
5902 let start = ((insertion_start + tabstop_range.start) as usize)
5903 .min(snapshot.len());
5904 let end = ((insertion_start + tabstop_range.end) as usize)
5905 .min(snapshot.len());
5906 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5907 })
5908 })
5909 .collect::<Vec<_>>();
5910 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5911
5912 Tabstop {
5913 is_end_tabstop,
5914 ranges: tabstop_ranges,
5915 choices: tabstop.choices.clone(),
5916 }
5917 })
5918 .collect::<Vec<_>>()
5919 });
5920 if let Some(tabstop) = tabstops.first() {
5921 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5922 s.select_ranges(tabstop.ranges.iter().cloned());
5923 });
5924
5925 if let Some(choices) = &tabstop.choices {
5926 if let Some(selection) = tabstop.ranges.first() {
5927 self.show_snippet_choices(choices, selection.clone(), cx)
5928 }
5929 }
5930
5931 // If we're already at the last tabstop and it's at the end of the snippet,
5932 // we're done, we don't need to keep the state around.
5933 if !tabstop.is_end_tabstop {
5934 let choices = tabstops
5935 .iter()
5936 .map(|tabstop| tabstop.choices.clone())
5937 .collect();
5938
5939 let ranges = tabstops
5940 .into_iter()
5941 .map(|tabstop| tabstop.ranges)
5942 .collect::<Vec<_>>();
5943
5944 self.snippet_stack.push(SnippetState {
5945 active_index: 0,
5946 ranges,
5947 choices,
5948 });
5949 }
5950
5951 // Check whether the just-entered snippet ends with an auto-closable bracket.
5952 if self.autoclose_regions.is_empty() {
5953 let snapshot = self.buffer.read(cx).snapshot(cx);
5954 for selection in &mut self.selections.all::<Point>(cx) {
5955 let selection_head = selection.head();
5956 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5957 continue;
5958 };
5959
5960 let mut bracket_pair = None;
5961 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5962 let prev_chars = snapshot
5963 .reversed_chars_at(selection_head)
5964 .collect::<String>();
5965 for (pair, enabled) in scope.brackets() {
5966 if enabled
5967 && pair.close
5968 && prev_chars.starts_with(pair.start.as_str())
5969 && next_chars.starts_with(pair.end.as_str())
5970 {
5971 bracket_pair = Some(pair.clone());
5972 break;
5973 }
5974 }
5975 if let Some(pair) = bracket_pair {
5976 let start = snapshot.anchor_after(selection_head);
5977 let end = snapshot.anchor_after(selection_head);
5978 self.autoclose_regions.push(AutocloseRegion {
5979 selection_id: selection.id,
5980 range: start..end,
5981 pair,
5982 });
5983 }
5984 }
5985 }
5986 }
5987 Ok(())
5988 }
5989
5990 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5991 self.move_to_snippet_tabstop(Bias::Right, cx)
5992 }
5993
5994 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5995 self.move_to_snippet_tabstop(Bias::Left, cx)
5996 }
5997
5998 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5999 if let Some(mut snippet) = self.snippet_stack.pop() {
6000 match bias {
6001 Bias::Left => {
6002 if snippet.active_index > 0 {
6003 snippet.active_index -= 1;
6004 } else {
6005 self.snippet_stack.push(snippet);
6006 return false;
6007 }
6008 }
6009 Bias::Right => {
6010 if snippet.active_index + 1 < snippet.ranges.len() {
6011 snippet.active_index += 1;
6012 } else {
6013 self.snippet_stack.push(snippet);
6014 return false;
6015 }
6016 }
6017 }
6018 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6019 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6020 s.select_anchor_ranges(current_ranges.iter().cloned())
6021 });
6022
6023 if let Some(choices) = &snippet.choices[snippet.active_index] {
6024 if let Some(selection) = current_ranges.first() {
6025 self.show_snippet_choices(&choices, selection.clone(), cx);
6026 }
6027 }
6028
6029 // If snippet state is not at the last tabstop, push it back on the stack
6030 if snippet.active_index + 1 < snippet.ranges.len() {
6031 self.snippet_stack.push(snippet);
6032 }
6033 return true;
6034 }
6035 }
6036
6037 false
6038 }
6039
6040 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
6041 self.transact(cx, |this, cx| {
6042 this.select_all(&SelectAll, cx);
6043 this.insert("", cx);
6044 });
6045 }
6046
6047 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
6048 self.transact(cx, |this, cx| {
6049 this.select_autoclose_pair(cx);
6050 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6051 if !this.linked_edit_ranges.is_empty() {
6052 let selections = this.selections.all::<MultiBufferPoint>(cx);
6053 let snapshot = this.buffer.read(cx).snapshot(cx);
6054
6055 for selection in selections.iter() {
6056 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6057 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6058 if selection_start.buffer_id != selection_end.buffer_id {
6059 continue;
6060 }
6061 if let Some(ranges) =
6062 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6063 {
6064 for (buffer, entries) in ranges {
6065 linked_ranges.entry(buffer).or_default().extend(entries);
6066 }
6067 }
6068 }
6069 }
6070
6071 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6072 if !this.selections.line_mode {
6073 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6074 for selection in &mut selections {
6075 if selection.is_empty() {
6076 let old_head = selection.head();
6077 let mut new_head =
6078 movement::left(&display_map, old_head.to_display_point(&display_map))
6079 .to_point(&display_map);
6080 if let Some((buffer, line_buffer_range)) = display_map
6081 .buffer_snapshot
6082 .buffer_line_for_row(MultiBufferRow(old_head.row))
6083 {
6084 let indent_size =
6085 buffer.indent_size_for_line(line_buffer_range.start.row);
6086 let indent_len = match indent_size.kind {
6087 IndentKind::Space => {
6088 buffer.settings_at(line_buffer_range.start, cx).tab_size
6089 }
6090 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6091 };
6092 if old_head.column <= indent_size.len && old_head.column > 0 {
6093 let indent_len = indent_len.get();
6094 new_head = cmp::min(
6095 new_head,
6096 MultiBufferPoint::new(
6097 old_head.row,
6098 ((old_head.column - 1) / indent_len) * indent_len,
6099 ),
6100 );
6101 }
6102 }
6103
6104 selection.set_head(new_head, SelectionGoal::None);
6105 }
6106 }
6107 }
6108
6109 this.signature_help_state.set_backspace_pressed(true);
6110 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6111 this.insert("", cx);
6112 let empty_str: Arc<str> = Arc::from("");
6113 for (buffer, edits) in linked_ranges {
6114 let snapshot = buffer.read(cx).snapshot();
6115 use text::ToPoint as TP;
6116
6117 let edits = edits
6118 .into_iter()
6119 .map(|range| {
6120 let end_point = TP::to_point(&range.end, &snapshot);
6121 let mut start_point = TP::to_point(&range.start, &snapshot);
6122
6123 if end_point == start_point {
6124 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6125 .saturating_sub(1);
6126 start_point = TP::to_point(&offset, &snapshot);
6127 };
6128
6129 (start_point..end_point, empty_str.clone())
6130 })
6131 .sorted_by_key(|(range, _)| range.start)
6132 .collect::<Vec<_>>();
6133 buffer.update(cx, |this, cx| {
6134 this.edit(edits, None, cx);
6135 })
6136 }
6137 this.refresh_inline_completion(true, false, cx);
6138 linked_editing_ranges::refresh_linked_ranges(this, cx);
6139 });
6140 }
6141
6142 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
6143 self.transact(cx, |this, cx| {
6144 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6145 let line_mode = s.line_mode;
6146 s.move_with(|map, selection| {
6147 if selection.is_empty() && !line_mode {
6148 let cursor = movement::right(map, selection.head());
6149 selection.end = cursor;
6150 selection.reversed = true;
6151 selection.goal = SelectionGoal::None;
6152 }
6153 })
6154 });
6155 this.insert("", cx);
6156 this.refresh_inline_completion(true, false, cx);
6157 });
6158 }
6159
6160 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
6161 if self.move_to_prev_snippet_tabstop(cx) {
6162 return;
6163 }
6164
6165 self.outdent(&Outdent, cx);
6166 }
6167
6168 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
6169 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
6170 return;
6171 }
6172
6173 let mut selections = self.selections.all_adjusted(cx);
6174 let buffer = self.buffer.read(cx);
6175 let snapshot = buffer.snapshot(cx);
6176 let rows_iter = selections.iter().map(|s| s.head().row);
6177 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6178
6179 let mut edits = Vec::new();
6180 let mut prev_edited_row = 0;
6181 let mut row_delta = 0;
6182 for selection in &mut selections {
6183 if selection.start.row != prev_edited_row {
6184 row_delta = 0;
6185 }
6186 prev_edited_row = selection.end.row;
6187
6188 // If the selection is non-empty, then increase the indentation of the selected lines.
6189 if !selection.is_empty() {
6190 row_delta =
6191 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6192 continue;
6193 }
6194
6195 // If the selection is empty and the cursor is in the leading whitespace before the
6196 // suggested indentation, then auto-indent the line.
6197 let cursor = selection.head();
6198 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6199 if let Some(suggested_indent) =
6200 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6201 {
6202 if cursor.column < suggested_indent.len
6203 && cursor.column <= current_indent.len
6204 && current_indent.len <= suggested_indent.len
6205 {
6206 selection.start = Point::new(cursor.row, suggested_indent.len);
6207 selection.end = selection.start;
6208 if row_delta == 0 {
6209 edits.extend(Buffer::edit_for_indent_size_adjustment(
6210 cursor.row,
6211 current_indent,
6212 suggested_indent,
6213 ));
6214 row_delta = suggested_indent.len - current_indent.len;
6215 }
6216 continue;
6217 }
6218 }
6219
6220 // Otherwise, insert a hard or soft tab.
6221 let settings = buffer.settings_at(cursor, cx);
6222 let tab_size = if settings.hard_tabs {
6223 IndentSize::tab()
6224 } else {
6225 let tab_size = settings.tab_size.get();
6226 let char_column = snapshot
6227 .text_for_range(Point::new(cursor.row, 0)..cursor)
6228 .flat_map(str::chars)
6229 .count()
6230 + row_delta as usize;
6231 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6232 IndentSize::spaces(chars_to_next_tab_stop)
6233 };
6234 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6235 selection.end = selection.start;
6236 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6237 row_delta += tab_size.len;
6238 }
6239
6240 self.transact(cx, |this, cx| {
6241 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6242 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6243 this.refresh_inline_completion(true, false, cx);
6244 });
6245 }
6246
6247 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
6248 if self.read_only(cx) {
6249 return;
6250 }
6251 let mut selections = self.selections.all::<Point>(cx);
6252 let mut prev_edited_row = 0;
6253 let mut row_delta = 0;
6254 let mut edits = Vec::new();
6255 let buffer = self.buffer.read(cx);
6256 let snapshot = buffer.snapshot(cx);
6257 for selection in &mut selections {
6258 if selection.start.row != prev_edited_row {
6259 row_delta = 0;
6260 }
6261 prev_edited_row = selection.end.row;
6262
6263 row_delta =
6264 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6265 }
6266
6267 self.transact(cx, |this, cx| {
6268 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6269 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6270 });
6271 }
6272
6273 fn indent_selection(
6274 buffer: &MultiBuffer,
6275 snapshot: &MultiBufferSnapshot,
6276 selection: &mut Selection<Point>,
6277 edits: &mut Vec<(Range<Point>, String)>,
6278 delta_for_start_row: u32,
6279 cx: &AppContext,
6280 ) -> u32 {
6281 let settings = buffer.settings_at(selection.start, cx);
6282 let tab_size = settings.tab_size.get();
6283 let indent_kind = if settings.hard_tabs {
6284 IndentKind::Tab
6285 } else {
6286 IndentKind::Space
6287 };
6288 let mut start_row = selection.start.row;
6289 let mut end_row = selection.end.row + 1;
6290
6291 // If a selection ends at the beginning of a line, don't indent
6292 // that last line.
6293 if selection.end.column == 0 && selection.end.row > selection.start.row {
6294 end_row -= 1;
6295 }
6296
6297 // Avoid re-indenting a row that has already been indented by a
6298 // previous selection, but still update this selection's column
6299 // to reflect that indentation.
6300 if delta_for_start_row > 0 {
6301 start_row += 1;
6302 selection.start.column += delta_for_start_row;
6303 if selection.end.row == selection.start.row {
6304 selection.end.column += delta_for_start_row;
6305 }
6306 }
6307
6308 let mut delta_for_end_row = 0;
6309 let has_multiple_rows = start_row + 1 != end_row;
6310 for row in start_row..end_row {
6311 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6312 let indent_delta = match (current_indent.kind, indent_kind) {
6313 (IndentKind::Space, IndentKind::Space) => {
6314 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6315 IndentSize::spaces(columns_to_next_tab_stop)
6316 }
6317 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6318 (_, IndentKind::Tab) => IndentSize::tab(),
6319 };
6320
6321 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6322 0
6323 } else {
6324 selection.start.column
6325 };
6326 let row_start = Point::new(row, start);
6327 edits.push((
6328 row_start..row_start,
6329 indent_delta.chars().collect::<String>(),
6330 ));
6331
6332 // Update this selection's endpoints to reflect the indentation.
6333 if row == selection.start.row {
6334 selection.start.column += indent_delta.len;
6335 }
6336 if row == selection.end.row {
6337 selection.end.column += indent_delta.len;
6338 delta_for_end_row = indent_delta.len;
6339 }
6340 }
6341
6342 if selection.start.row == selection.end.row {
6343 delta_for_start_row + delta_for_end_row
6344 } else {
6345 delta_for_end_row
6346 }
6347 }
6348
6349 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
6350 if self.read_only(cx) {
6351 return;
6352 }
6353 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6354 let selections = self.selections.all::<Point>(cx);
6355 let mut deletion_ranges = Vec::new();
6356 let mut last_outdent = None;
6357 {
6358 let buffer = self.buffer.read(cx);
6359 let snapshot = buffer.snapshot(cx);
6360 for selection in &selections {
6361 let settings = buffer.settings_at(selection.start, cx);
6362 let tab_size = settings.tab_size.get();
6363 let mut rows = selection.spanned_rows(false, &display_map);
6364
6365 // Avoid re-outdenting a row that has already been outdented by a
6366 // previous selection.
6367 if let Some(last_row) = last_outdent {
6368 if last_row == rows.start {
6369 rows.start = rows.start.next_row();
6370 }
6371 }
6372 let has_multiple_rows = rows.len() > 1;
6373 for row in rows.iter_rows() {
6374 let indent_size = snapshot.indent_size_for_line(row);
6375 if indent_size.len > 0 {
6376 let deletion_len = match indent_size.kind {
6377 IndentKind::Space => {
6378 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6379 if columns_to_prev_tab_stop == 0 {
6380 tab_size
6381 } else {
6382 columns_to_prev_tab_stop
6383 }
6384 }
6385 IndentKind::Tab => 1,
6386 };
6387 let start = if has_multiple_rows
6388 || deletion_len > selection.start.column
6389 || indent_size.len < selection.start.column
6390 {
6391 0
6392 } else {
6393 selection.start.column - deletion_len
6394 };
6395 deletion_ranges.push(
6396 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6397 );
6398 last_outdent = Some(row);
6399 }
6400 }
6401 }
6402 }
6403
6404 self.transact(cx, |this, cx| {
6405 this.buffer.update(cx, |buffer, cx| {
6406 let empty_str: Arc<str> = Arc::default();
6407 buffer.edit(
6408 deletion_ranges
6409 .into_iter()
6410 .map(|range| (range, empty_str.clone())),
6411 None,
6412 cx,
6413 );
6414 });
6415 let selections = this.selections.all::<usize>(cx);
6416 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6417 });
6418 }
6419
6420 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
6421 if self.read_only(cx) {
6422 return;
6423 }
6424 let selections = self
6425 .selections
6426 .all::<usize>(cx)
6427 .into_iter()
6428 .map(|s| s.range());
6429
6430 self.transact(cx, |this, cx| {
6431 this.buffer.update(cx, |buffer, cx| {
6432 buffer.autoindent_ranges(selections, cx);
6433 });
6434 let selections = this.selections.all::<usize>(cx);
6435 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6436 });
6437 }
6438
6439 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
6440 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6441 let selections = self.selections.all::<Point>(cx);
6442
6443 let mut new_cursors = Vec::new();
6444 let mut edit_ranges = Vec::new();
6445 let mut selections = selections.iter().peekable();
6446 while let Some(selection) = selections.next() {
6447 let mut rows = selection.spanned_rows(false, &display_map);
6448 let goal_display_column = selection.head().to_display_point(&display_map).column();
6449
6450 // Accumulate contiguous regions of rows that we want to delete.
6451 while let Some(next_selection) = selections.peek() {
6452 let next_rows = next_selection.spanned_rows(false, &display_map);
6453 if next_rows.start <= rows.end {
6454 rows.end = next_rows.end;
6455 selections.next().unwrap();
6456 } else {
6457 break;
6458 }
6459 }
6460
6461 let buffer = &display_map.buffer_snapshot;
6462 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6463 let edit_end;
6464 let cursor_buffer_row;
6465 if buffer.max_point().row >= rows.end.0 {
6466 // If there's a line after the range, delete the \n from the end of the row range
6467 // and position the cursor on the next line.
6468 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6469 cursor_buffer_row = rows.end;
6470 } else {
6471 // If there isn't a line after the range, delete the \n from the line before the
6472 // start of the row range and position the cursor there.
6473 edit_start = edit_start.saturating_sub(1);
6474 edit_end = buffer.len();
6475 cursor_buffer_row = rows.start.previous_row();
6476 }
6477
6478 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6479 *cursor.column_mut() =
6480 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6481
6482 new_cursors.push((
6483 selection.id,
6484 buffer.anchor_after(cursor.to_point(&display_map)),
6485 ));
6486 edit_ranges.push(edit_start..edit_end);
6487 }
6488
6489 self.transact(cx, |this, cx| {
6490 let buffer = this.buffer.update(cx, |buffer, cx| {
6491 let empty_str: Arc<str> = Arc::default();
6492 buffer.edit(
6493 edit_ranges
6494 .into_iter()
6495 .map(|range| (range, empty_str.clone())),
6496 None,
6497 cx,
6498 );
6499 buffer.snapshot(cx)
6500 });
6501 let new_selections = new_cursors
6502 .into_iter()
6503 .map(|(id, cursor)| {
6504 let cursor = cursor.to_point(&buffer);
6505 Selection {
6506 id,
6507 start: cursor,
6508 end: cursor,
6509 reversed: false,
6510 goal: SelectionGoal::None,
6511 }
6512 })
6513 .collect();
6514
6515 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6516 s.select(new_selections);
6517 });
6518 });
6519 }
6520
6521 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6522 if self.read_only(cx) {
6523 return;
6524 }
6525 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6526 for selection in self.selections.all::<Point>(cx) {
6527 let start = MultiBufferRow(selection.start.row);
6528 // Treat single line selections as if they include the next line. Otherwise this action
6529 // would do nothing for single line selections individual cursors.
6530 let end = if selection.start.row == selection.end.row {
6531 MultiBufferRow(selection.start.row + 1)
6532 } else {
6533 MultiBufferRow(selection.end.row)
6534 };
6535
6536 if let Some(last_row_range) = row_ranges.last_mut() {
6537 if start <= last_row_range.end {
6538 last_row_range.end = end;
6539 continue;
6540 }
6541 }
6542 row_ranges.push(start..end);
6543 }
6544
6545 let snapshot = self.buffer.read(cx).snapshot(cx);
6546 let mut cursor_positions = Vec::new();
6547 for row_range in &row_ranges {
6548 let anchor = snapshot.anchor_before(Point::new(
6549 row_range.end.previous_row().0,
6550 snapshot.line_len(row_range.end.previous_row()),
6551 ));
6552 cursor_positions.push(anchor..anchor);
6553 }
6554
6555 self.transact(cx, |this, cx| {
6556 for row_range in row_ranges.into_iter().rev() {
6557 for row in row_range.iter_rows().rev() {
6558 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6559 let next_line_row = row.next_row();
6560 let indent = snapshot.indent_size_for_line(next_line_row);
6561 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6562
6563 let replace = if snapshot.line_len(next_line_row) > indent.len {
6564 " "
6565 } else {
6566 ""
6567 };
6568
6569 this.buffer.update(cx, |buffer, cx| {
6570 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6571 });
6572 }
6573 }
6574
6575 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6576 s.select_anchor_ranges(cursor_positions)
6577 });
6578 });
6579 }
6580
6581 pub fn sort_lines_case_sensitive(
6582 &mut self,
6583 _: &SortLinesCaseSensitive,
6584 cx: &mut ViewContext<Self>,
6585 ) {
6586 self.manipulate_lines(cx, |lines| lines.sort())
6587 }
6588
6589 pub fn sort_lines_case_insensitive(
6590 &mut self,
6591 _: &SortLinesCaseInsensitive,
6592 cx: &mut ViewContext<Self>,
6593 ) {
6594 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6595 }
6596
6597 pub fn unique_lines_case_insensitive(
6598 &mut self,
6599 _: &UniqueLinesCaseInsensitive,
6600 cx: &mut ViewContext<Self>,
6601 ) {
6602 self.manipulate_lines(cx, |lines| {
6603 let mut seen = HashSet::default();
6604 lines.retain(|line| seen.insert(line.to_lowercase()));
6605 })
6606 }
6607
6608 pub fn unique_lines_case_sensitive(
6609 &mut self,
6610 _: &UniqueLinesCaseSensitive,
6611 cx: &mut ViewContext<Self>,
6612 ) {
6613 self.manipulate_lines(cx, |lines| {
6614 let mut seen = HashSet::default();
6615 lines.retain(|line| seen.insert(*line));
6616 })
6617 }
6618
6619 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6620 let mut revert_changes = HashMap::default();
6621 let snapshot = self.snapshot(cx);
6622 for hunk in hunks_for_ranges(
6623 Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
6624 &snapshot,
6625 ) {
6626 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6627 }
6628 if !revert_changes.is_empty() {
6629 self.transact(cx, |editor, cx| {
6630 editor.revert(revert_changes, cx);
6631 });
6632 }
6633 }
6634
6635 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6636 let Some(project) = self.project.clone() else {
6637 return;
6638 };
6639 self.reload(project, cx).detach_and_notify_err(cx);
6640 }
6641
6642 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6643 let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
6644 if !revert_changes.is_empty() {
6645 self.transact(cx, |editor, cx| {
6646 editor.revert(revert_changes, cx);
6647 });
6648 }
6649 }
6650
6651 fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
6652 let snapshot = self.buffer.read(cx).read(cx);
6653 if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
6654 drop(snapshot);
6655 let mut revert_changes = HashMap::default();
6656 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6657 if !revert_changes.is_empty() {
6658 self.revert(revert_changes, cx)
6659 }
6660 }
6661 }
6662
6663 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6664 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6665 let project_path = buffer.read(cx).project_path(cx)?;
6666 let project = self.project.as_ref()?.read(cx);
6667 let entry = project.entry_for_path(&project_path, cx)?;
6668 let parent = match &entry.canonical_path {
6669 Some(canonical_path) => canonical_path.to_path_buf(),
6670 None => project.absolute_path(&project_path, cx)?,
6671 }
6672 .parent()?
6673 .to_path_buf();
6674 Some(parent)
6675 }) {
6676 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6677 }
6678 }
6679
6680 fn gather_revert_changes(
6681 &mut self,
6682 selections: &[Selection<Point>],
6683 cx: &mut ViewContext<'_, Editor>,
6684 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6685 let mut revert_changes = HashMap::default();
6686 let snapshot = self.snapshot(cx);
6687 for hunk in hunks_for_selections(&snapshot, selections) {
6688 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6689 }
6690 revert_changes
6691 }
6692
6693 pub fn prepare_revert_change(
6694 &mut self,
6695 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6696 hunk: &MultiBufferDiffHunk,
6697 cx: &AppContext,
6698 ) -> Option<()> {
6699 let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
6700 let buffer = buffer.read(cx);
6701 let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
6702 let original_text = change_set
6703 .read(cx)
6704 .base_text
6705 .as_ref()?
6706 .read(cx)
6707 .as_rope()
6708 .slice(hunk.diff_base_byte_range.clone());
6709 let buffer_snapshot = buffer.snapshot();
6710 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6711 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6712 probe
6713 .0
6714 .start
6715 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6716 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6717 }) {
6718 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6719 Some(())
6720 } else {
6721 None
6722 }
6723 }
6724
6725 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6726 self.manipulate_lines(cx, |lines| lines.reverse())
6727 }
6728
6729 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6730 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6731 }
6732
6733 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6734 where
6735 Fn: FnMut(&mut Vec<&str>),
6736 {
6737 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6738 let buffer = self.buffer.read(cx).snapshot(cx);
6739
6740 let mut edits = Vec::new();
6741
6742 let selections = self.selections.all::<Point>(cx);
6743 let mut selections = selections.iter().peekable();
6744 let mut contiguous_row_selections = Vec::new();
6745 let mut new_selections = Vec::new();
6746 let mut added_lines = 0;
6747 let mut removed_lines = 0;
6748
6749 while let Some(selection) = selections.next() {
6750 let (start_row, end_row) = consume_contiguous_rows(
6751 &mut contiguous_row_selections,
6752 selection,
6753 &display_map,
6754 &mut selections,
6755 );
6756
6757 let start_point = Point::new(start_row.0, 0);
6758 let end_point = Point::new(
6759 end_row.previous_row().0,
6760 buffer.line_len(end_row.previous_row()),
6761 );
6762 let text = buffer
6763 .text_for_range(start_point..end_point)
6764 .collect::<String>();
6765
6766 let mut lines = text.split('\n').collect_vec();
6767
6768 let lines_before = lines.len();
6769 callback(&mut lines);
6770 let lines_after = lines.len();
6771
6772 edits.push((start_point..end_point, lines.join("\n")));
6773
6774 // Selections must change based on added and removed line count
6775 let start_row =
6776 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6777 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6778 new_selections.push(Selection {
6779 id: selection.id,
6780 start: start_row,
6781 end: end_row,
6782 goal: SelectionGoal::None,
6783 reversed: selection.reversed,
6784 });
6785
6786 if lines_after > lines_before {
6787 added_lines += lines_after - lines_before;
6788 } else if lines_before > lines_after {
6789 removed_lines += lines_before - lines_after;
6790 }
6791 }
6792
6793 self.transact(cx, |this, cx| {
6794 let buffer = this.buffer.update(cx, |buffer, cx| {
6795 buffer.edit(edits, None, cx);
6796 buffer.snapshot(cx)
6797 });
6798
6799 // Recalculate offsets on newly edited buffer
6800 let new_selections = new_selections
6801 .iter()
6802 .map(|s| {
6803 let start_point = Point::new(s.start.0, 0);
6804 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6805 Selection {
6806 id: s.id,
6807 start: buffer.point_to_offset(start_point),
6808 end: buffer.point_to_offset(end_point),
6809 goal: s.goal,
6810 reversed: s.reversed,
6811 }
6812 })
6813 .collect();
6814
6815 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6816 s.select(new_selections);
6817 });
6818
6819 this.request_autoscroll(Autoscroll::fit(), cx);
6820 });
6821 }
6822
6823 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6824 self.manipulate_text(cx, |text| text.to_uppercase())
6825 }
6826
6827 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6828 self.manipulate_text(cx, |text| text.to_lowercase())
6829 }
6830
6831 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6832 self.manipulate_text(cx, |text| {
6833 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6834 // https://github.com/rutrum/convert-case/issues/16
6835 text.split('\n')
6836 .map(|line| line.to_case(Case::Title))
6837 .join("\n")
6838 })
6839 }
6840
6841 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6842 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6843 }
6844
6845 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6846 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6847 }
6848
6849 pub fn convert_to_upper_camel_case(
6850 &mut self,
6851 _: &ConvertToUpperCamelCase,
6852 cx: &mut ViewContext<Self>,
6853 ) {
6854 self.manipulate_text(cx, |text| {
6855 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6856 // https://github.com/rutrum/convert-case/issues/16
6857 text.split('\n')
6858 .map(|line| line.to_case(Case::UpperCamel))
6859 .join("\n")
6860 })
6861 }
6862
6863 pub fn convert_to_lower_camel_case(
6864 &mut self,
6865 _: &ConvertToLowerCamelCase,
6866 cx: &mut ViewContext<Self>,
6867 ) {
6868 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6869 }
6870
6871 pub fn convert_to_opposite_case(
6872 &mut self,
6873 _: &ConvertToOppositeCase,
6874 cx: &mut ViewContext<Self>,
6875 ) {
6876 self.manipulate_text(cx, |text| {
6877 text.chars()
6878 .fold(String::with_capacity(text.len()), |mut t, c| {
6879 if c.is_uppercase() {
6880 t.extend(c.to_lowercase());
6881 } else {
6882 t.extend(c.to_uppercase());
6883 }
6884 t
6885 })
6886 })
6887 }
6888
6889 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6890 where
6891 Fn: FnMut(&str) -> String,
6892 {
6893 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6894 let buffer = self.buffer.read(cx).snapshot(cx);
6895
6896 let mut new_selections = Vec::new();
6897 let mut edits = Vec::new();
6898 let mut selection_adjustment = 0i32;
6899
6900 for selection in self.selections.all::<usize>(cx) {
6901 let selection_is_empty = selection.is_empty();
6902
6903 let (start, end) = if selection_is_empty {
6904 let word_range = movement::surrounding_word(
6905 &display_map,
6906 selection.start.to_display_point(&display_map),
6907 );
6908 let start = word_range.start.to_offset(&display_map, Bias::Left);
6909 let end = word_range.end.to_offset(&display_map, Bias::Left);
6910 (start, end)
6911 } else {
6912 (selection.start, selection.end)
6913 };
6914
6915 let text = buffer.text_for_range(start..end).collect::<String>();
6916 let old_length = text.len() as i32;
6917 let text = callback(&text);
6918
6919 new_selections.push(Selection {
6920 start: (start as i32 - selection_adjustment) as usize,
6921 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6922 goal: SelectionGoal::None,
6923 ..selection
6924 });
6925
6926 selection_adjustment += old_length - text.len() as i32;
6927
6928 edits.push((start..end, text));
6929 }
6930
6931 self.transact(cx, |this, cx| {
6932 this.buffer.update(cx, |buffer, cx| {
6933 buffer.edit(edits, None, cx);
6934 });
6935
6936 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6937 s.select(new_selections);
6938 });
6939
6940 this.request_autoscroll(Autoscroll::fit(), cx);
6941 });
6942 }
6943
6944 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6945 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6946 let buffer = &display_map.buffer_snapshot;
6947 let selections = self.selections.all::<Point>(cx);
6948
6949 let mut edits = Vec::new();
6950 let mut selections_iter = selections.iter().peekable();
6951 while let Some(selection) = selections_iter.next() {
6952 // Avoid duplicating the same lines twice.
6953 let mut rows = selection.spanned_rows(false, &display_map);
6954
6955 while let Some(next_selection) = selections_iter.peek() {
6956 let next_rows = next_selection.spanned_rows(false, &display_map);
6957 if next_rows.start < rows.end {
6958 rows.end = next_rows.end;
6959 selections_iter.next().unwrap();
6960 } else {
6961 break;
6962 }
6963 }
6964
6965 // Copy the text from the selected row region and splice it either at the start
6966 // or end of the region.
6967 let start = Point::new(rows.start.0, 0);
6968 let end = Point::new(
6969 rows.end.previous_row().0,
6970 buffer.line_len(rows.end.previous_row()),
6971 );
6972 let text = buffer
6973 .text_for_range(start..end)
6974 .chain(Some("\n"))
6975 .collect::<String>();
6976 let insert_location = if upwards {
6977 Point::new(rows.end.0, 0)
6978 } else {
6979 start
6980 };
6981 edits.push((insert_location..insert_location, text));
6982 }
6983
6984 self.transact(cx, |this, cx| {
6985 this.buffer.update(cx, |buffer, cx| {
6986 buffer.edit(edits, None, cx);
6987 });
6988
6989 this.request_autoscroll(Autoscroll::fit(), cx);
6990 });
6991 }
6992
6993 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6994 self.duplicate_line(true, cx);
6995 }
6996
6997 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6998 self.duplicate_line(false, cx);
6999 }
7000
7001 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
7002 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7003 let buffer = self.buffer.read(cx).snapshot(cx);
7004
7005 let mut edits = Vec::new();
7006 let mut unfold_ranges = Vec::new();
7007 let mut refold_creases = Vec::new();
7008
7009 let selections = self.selections.all::<Point>(cx);
7010 let mut selections = selections.iter().peekable();
7011 let mut contiguous_row_selections = Vec::new();
7012 let mut new_selections = Vec::new();
7013
7014 while let Some(selection) = selections.next() {
7015 // Find all the selections that span a contiguous row range
7016 let (start_row, end_row) = consume_contiguous_rows(
7017 &mut contiguous_row_selections,
7018 selection,
7019 &display_map,
7020 &mut selections,
7021 );
7022
7023 // Move the text spanned by the row range to be before the line preceding the row range
7024 if start_row.0 > 0 {
7025 let range_to_move = Point::new(
7026 start_row.previous_row().0,
7027 buffer.line_len(start_row.previous_row()),
7028 )
7029 ..Point::new(
7030 end_row.previous_row().0,
7031 buffer.line_len(end_row.previous_row()),
7032 );
7033 let insertion_point = display_map
7034 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7035 .0;
7036
7037 // Don't move lines across excerpts
7038 if buffer
7039 .excerpt_boundaries_in_range((
7040 Bound::Excluded(insertion_point),
7041 Bound::Included(range_to_move.end),
7042 ))
7043 .next()
7044 .is_none()
7045 {
7046 let text = buffer
7047 .text_for_range(range_to_move.clone())
7048 .flat_map(|s| s.chars())
7049 .skip(1)
7050 .chain(['\n'])
7051 .collect::<String>();
7052
7053 edits.push((
7054 buffer.anchor_after(range_to_move.start)
7055 ..buffer.anchor_before(range_to_move.end),
7056 String::new(),
7057 ));
7058 let insertion_anchor = buffer.anchor_after(insertion_point);
7059 edits.push((insertion_anchor..insertion_anchor, text));
7060
7061 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7062
7063 // Move selections up
7064 new_selections.extend(contiguous_row_selections.drain(..).map(
7065 |mut selection| {
7066 selection.start.row -= row_delta;
7067 selection.end.row -= row_delta;
7068 selection
7069 },
7070 ));
7071
7072 // Move folds up
7073 unfold_ranges.push(range_to_move.clone());
7074 for fold in display_map.folds_in_range(
7075 buffer.anchor_before(range_to_move.start)
7076 ..buffer.anchor_after(range_to_move.end),
7077 ) {
7078 let mut start = fold.range.start.to_point(&buffer);
7079 let mut end = fold.range.end.to_point(&buffer);
7080 start.row -= row_delta;
7081 end.row -= row_delta;
7082 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7083 }
7084 }
7085 }
7086
7087 // If we didn't move line(s), preserve the existing selections
7088 new_selections.append(&mut contiguous_row_selections);
7089 }
7090
7091 self.transact(cx, |this, cx| {
7092 this.unfold_ranges(&unfold_ranges, true, true, cx);
7093 this.buffer.update(cx, |buffer, cx| {
7094 for (range, text) in edits {
7095 buffer.edit([(range, text)], None, cx);
7096 }
7097 });
7098 this.fold_creases(refold_creases, true, cx);
7099 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7100 s.select(new_selections);
7101 })
7102 });
7103 }
7104
7105 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
7106 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7107 let buffer = self.buffer.read(cx).snapshot(cx);
7108
7109 let mut edits = Vec::new();
7110 let mut unfold_ranges = Vec::new();
7111 let mut refold_creases = Vec::new();
7112
7113 let selections = self.selections.all::<Point>(cx);
7114 let mut selections = selections.iter().peekable();
7115 let mut contiguous_row_selections = Vec::new();
7116 let mut new_selections = Vec::new();
7117
7118 while let Some(selection) = selections.next() {
7119 // Find all the selections that span a contiguous row range
7120 let (start_row, end_row) = consume_contiguous_rows(
7121 &mut contiguous_row_selections,
7122 selection,
7123 &display_map,
7124 &mut selections,
7125 );
7126
7127 // Move the text spanned by the row range to be after the last line of the row range
7128 if end_row.0 <= buffer.max_point().row {
7129 let range_to_move =
7130 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7131 let insertion_point = display_map
7132 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7133 .0;
7134
7135 // Don't move lines across excerpt boundaries
7136 if buffer
7137 .excerpt_boundaries_in_range((
7138 Bound::Excluded(range_to_move.start),
7139 Bound::Included(insertion_point),
7140 ))
7141 .next()
7142 .is_none()
7143 {
7144 let mut text = String::from("\n");
7145 text.extend(buffer.text_for_range(range_to_move.clone()));
7146 text.pop(); // Drop trailing newline
7147 edits.push((
7148 buffer.anchor_after(range_to_move.start)
7149 ..buffer.anchor_before(range_to_move.end),
7150 String::new(),
7151 ));
7152 let insertion_anchor = buffer.anchor_after(insertion_point);
7153 edits.push((insertion_anchor..insertion_anchor, text));
7154
7155 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7156
7157 // Move selections down
7158 new_selections.extend(contiguous_row_selections.drain(..).map(
7159 |mut selection| {
7160 selection.start.row += row_delta;
7161 selection.end.row += row_delta;
7162 selection
7163 },
7164 ));
7165
7166 // Move folds down
7167 unfold_ranges.push(range_to_move.clone());
7168 for fold in display_map.folds_in_range(
7169 buffer.anchor_before(range_to_move.start)
7170 ..buffer.anchor_after(range_to_move.end),
7171 ) {
7172 let mut start = fold.range.start.to_point(&buffer);
7173 let mut end = fold.range.end.to_point(&buffer);
7174 start.row += row_delta;
7175 end.row += row_delta;
7176 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7177 }
7178 }
7179 }
7180
7181 // If we didn't move line(s), preserve the existing selections
7182 new_selections.append(&mut contiguous_row_selections);
7183 }
7184
7185 self.transact(cx, |this, cx| {
7186 this.unfold_ranges(&unfold_ranges, true, true, cx);
7187 this.buffer.update(cx, |buffer, cx| {
7188 for (range, text) in edits {
7189 buffer.edit([(range, text)], None, cx);
7190 }
7191 });
7192 this.fold_creases(refold_creases, true, cx);
7193 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
7194 });
7195 }
7196
7197 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
7198 let text_layout_details = &self.text_layout_details(cx);
7199 self.transact(cx, |this, cx| {
7200 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7201 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7202 let line_mode = s.line_mode;
7203 s.move_with(|display_map, selection| {
7204 if !selection.is_empty() || line_mode {
7205 return;
7206 }
7207
7208 let mut head = selection.head();
7209 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7210 if head.column() == display_map.line_len(head.row()) {
7211 transpose_offset = display_map
7212 .buffer_snapshot
7213 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7214 }
7215
7216 if transpose_offset == 0 {
7217 return;
7218 }
7219
7220 *head.column_mut() += 1;
7221 head = display_map.clip_point(head, Bias::Right);
7222 let goal = SelectionGoal::HorizontalPosition(
7223 display_map
7224 .x_for_display_point(head, text_layout_details)
7225 .into(),
7226 );
7227 selection.collapse_to(head, goal);
7228
7229 let transpose_start = display_map
7230 .buffer_snapshot
7231 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7232 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7233 let transpose_end = display_map
7234 .buffer_snapshot
7235 .clip_offset(transpose_offset + 1, Bias::Right);
7236 if let Some(ch) =
7237 display_map.buffer_snapshot.chars_at(transpose_start).next()
7238 {
7239 edits.push((transpose_start..transpose_offset, String::new()));
7240 edits.push((transpose_end..transpose_end, ch.to_string()));
7241 }
7242 }
7243 });
7244 edits
7245 });
7246 this.buffer
7247 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7248 let selections = this.selections.all::<usize>(cx);
7249 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7250 s.select(selections);
7251 });
7252 });
7253 }
7254
7255 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
7256 self.rewrap_impl(IsVimMode::No, cx)
7257 }
7258
7259 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
7260 let buffer = self.buffer.read(cx).snapshot(cx);
7261 let selections = self.selections.all::<Point>(cx);
7262 let mut selections = selections.iter().peekable();
7263
7264 let mut edits = Vec::new();
7265 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7266
7267 while let Some(selection) = selections.next() {
7268 let mut start_row = selection.start.row;
7269 let mut end_row = selection.end.row;
7270
7271 // Skip selections that overlap with a range that has already been rewrapped.
7272 let selection_range = start_row..end_row;
7273 if rewrapped_row_ranges
7274 .iter()
7275 .any(|range| range.overlaps(&selection_range))
7276 {
7277 continue;
7278 }
7279
7280 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7281
7282 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7283 match language_scope.language_name().0.as_ref() {
7284 "Markdown" | "Plain Text" => {
7285 should_rewrap = true;
7286 }
7287 _ => {}
7288 }
7289 }
7290
7291 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7292
7293 // Since not all lines in the selection may be at the same indent
7294 // level, choose the indent size that is the most common between all
7295 // of the lines.
7296 //
7297 // If there is a tie, we use the deepest indent.
7298 let (indent_size, indent_end) = {
7299 let mut indent_size_occurrences = HashMap::default();
7300 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7301
7302 for row in start_row..=end_row {
7303 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7304 rows_by_indent_size.entry(indent).or_default().push(row);
7305 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7306 }
7307
7308 let indent_size = indent_size_occurrences
7309 .into_iter()
7310 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7311 .map(|(indent, _)| indent)
7312 .unwrap_or_default();
7313 let row = rows_by_indent_size[&indent_size][0];
7314 let indent_end = Point::new(row, indent_size.len);
7315
7316 (indent_size, indent_end)
7317 };
7318
7319 let mut line_prefix = indent_size.chars().collect::<String>();
7320
7321 if let Some(comment_prefix) =
7322 buffer
7323 .language_scope_at(selection.head())
7324 .and_then(|language| {
7325 language
7326 .line_comment_prefixes()
7327 .iter()
7328 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7329 .cloned()
7330 })
7331 {
7332 line_prefix.push_str(&comment_prefix);
7333 should_rewrap = true;
7334 }
7335
7336 if !should_rewrap {
7337 continue;
7338 }
7339
7340 if selection.is_empty() {
7341 'expand_upwards: while start_row > 0 {
7342 let prev_row = start_row - 1;
7343 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7344 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7345 {
7346 start_row = prev_row;
7347 } else {
7348 break 'expand_upwards;
7349 }
7350 }
7351
7352 'expand_downwards: while end_row < buffer.max_point().row {
7353 let next_row = end_row + 1;
7354 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7355 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7356 {
7357 end_row = next_row;
7358 } else {
7359 break 'expand_downwards;
7360 }
7361 }
7362 }
7363
7364 let start = Point::new(start_row, 0);
7365 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7366 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7367 let Some(lines_without_prefixes) = selection_text
7368 .lines()
7369 .map(|line| {
7370 line.strip_prefix(&line_prefix)
7371 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7372 .ok_or_else(|| {
7373 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7374 })
7375 })
7376 .collect::<Result<Vec<_>, _>>()
7377 .log_err()
7378 else {
7379 continue;
7380 };
7381
7382 let wrap_column = buffer
7383 .settings_at(Point::new(start_row, 0), cx)
7384 .preferred_line_length as usize;
7385 let wrapped_text = wrap_with_prefix(
7386 line_prefix,
7387 lines_without_prefixes.join(" "),
7388 wrap_column,
7389 tab_size,
7390 );
7391
7392 // TODO: should always use char-based diff while still supporting cursor behavior that
7393 // matches vim.
7394 let diff = match is_vim_mode {
7395 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7396 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7397 };
7398 let mut offset = start.to_offset(&buffer);
7399 let mut moved_since_edit = true;
7400
7401 for change in diff.iter_all_changes() {
7402 let value = change.value();
7403 match change.tag() {
7404 ChangeTag::Equal => {
7405 offset += value.len();
7406 moved_since_edit = true;
7407 }
7408 ChangeTag::Delete => {
7409 let start = buffer.anchor_after(offset);
7410 let end = buffer.anchor_before(offset + value.len());
7411
7412 if moved_since_edit {
7413 edits.push((start..end, String::new()));
7414 } else {
7415 edits.last_mut().unwrap().0.end = end;
7416 }
7417
7418 offset += value.len();
7419 moved_since_edit = false;
7420 }
7421 ChangeTag::Insert => {
7422 if moved_since_edit {
7423 let anchor = buffer.anchor_after(offset);
7424 edits.push((anchor..anchor, value.to_string()));
7425 } else {
7426 edits.last_mut().unwrap().1.push_str(value);
7427 }
7428
7429 moved_since_edit = false;
7430 }
7431 }
7432 }
7433
7434 rewrapped_row_ranges.push(start_row..=end_row);
7435 }
7436
7437 self.buffer
7438 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7439 }
7440
7441 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
7442 let mut text = String::new();
7443 let buffer = self.buffer.read(cx).snapshot(cx);
7444 let mut selections = self.selections.all::<Point>(cx);
7445 let mut clipboard_selections = Vec::with_capacity(selections.len());
7446 {
7447 let max_point = buffer.max_point();
7448 let mut is_first = true;
7449 for selection in &mut selections {
7450 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7451 if is_entire_line {
7452 selection.start = Point::new(selection.start.row, 0);
7453 if !selection.is_empty() && selection.end.column == 0 {
7454 selection.end = cmp::min(max_point, selection.end);
7455 } else {
7456 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7457 }
7458 selection.goal = SelectionGoal::None;
7459 }
7460 if is_first {
7461 is_first = false;
7462 } else {
7463 text += "\n";
7464 }
7465 let mut len = 0;
7466 for chunk in buffer.text_for_range(selection.start..selection.end) {
7467 text.push_str(chunk);
7468 len += chunk.len();
7469 }
7470 clipboard_selections.push(ClipboardSelection {
7471 len,
7472 is_entire_line,
7473 first_line_indent: buffer
7474 .indent_size_for_line(MultiBufferRow(selection.start.row))
7475 .len,
7476 });
7477 }
7478 }
7479
7480 self.transact(cx, |this, cx| {
7481 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7482 s.select(selections);
7483 });
7484 this.insert("", cx);
7485 });
7486 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7487 }
7488
7489 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
7490 let item = self.cut_common(cx);
7491 cx.write_to_clipboard(item);
7492 }
7493
7494 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
7495 self.change_selections(None, cx, |s| {
7496 s.move_with(|snapshot, sel| {
7497 if sel.is_empty() {
7498 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7499 }
7500 });
7501 });
7502 let item = self.cut_common(cx);
7503 cx.set_global(KillRing(item))
7504 }
7505
7506 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
7507 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7508 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7509 (kill_ring.text().to_string(), kill_ring.metadata_json())
7510 } else {
7511 return;
7512 }
7513 } else {
7514 return;
7515 };
7516 self.do_paste(&text, metadata, false, cx);
7517 }
7518
7519 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
7520 let selections = self.selections.all::<Point>(cx);
7521 let buffer = self.buffer.read(cx).read(cx);
7522 let mut text = String::new();
7523
7524 let mut clipboard_selections = Vec::with_capacity(selections.len());
7525 {
7526 let max_point = buffer.max_point();
7527 let mut is_first = true;
7528 for selection in selections.iter() {
7529 let mut start = selection.start;
7530 let mut end = selection.end;
7531 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7532 if is_entire_line {
7533 start = Point::new(start.row, 0);
7534 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7535 }
7536 if is_first {
7537 is_first = false;
7538 } else {
7539 text += "\n";
7540 }
7541 let mut len = 0;
7542 for chunk in buffer.text_for_range(start..end) {
7543 text.push_str(chunk);
7544 len += chunk.len();
7545 }
7546 clipboard_selections.push(ClipboardSelection {
7547 len,
7548 is_entire_line,
7549 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7550 });
7551 }
7552 }
7553
7554 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7555 text,
7556 clipboard_selections,
7557 ));
7558 }
7559
7560 pub fn do_paste(
7561 &mut self,
7562 text: &String,
7563 clipboard_selections: Option<Vec<ClipboardSelection>>,
7564 handle_entire_lines: bool,
7565 cx: &mut ViewContext<Self>,
7566 ) {
7567 if self.read_only(cx) {
7568 return;
7569 }
7570
7571 let clipboard_text = Cow::Borrowed(text);
7572
7573 self.transact(cx, |this, cx| {
7574 if let Some(mut clipboard_selections) = clipboard_selections {
7575 let old_selections = this.selections.all::<usize>(cx);
7576 let all_selections_were_entire_line =
7577 clipboard_selections.iter().all(|s| s.is_entire_line);
7578 let first_selection_indent_column =
7579 clipboard_selections.first().map(|s| s.first_line_indent);
7580 if clipboard_selections.len() != old_selections.len() {
7581 clipboard_selections.drain(..);
7582 }
7583 let cursor_offset = this.selections.last::<usize>(cx).head();
7584 let mut auto_indent_on_paste = true;
7585
7586 this.buffer.update(cx, |buffer, cx| {
7587 let snapshot = buffer.read(cx);
7588 auto_indent_on_paste =
7589 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7590
7591 let mut start_offset = 0;
7592 let mut edits = Vec::new();
7593 let mut original_indent_columns = Vec::new();
7594 for (ix, selection) in old_selections.iter().enumerate() {
7595 let to_insert;
7596 let entire_line;
7597 let original_indent_column;
7598 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7599 let end_offset = start_offset + clipboard_selection.len;
7600 to_insert = &clipboard_text[start_offset..end_offset];
7601 entire_line = clipboard_selection.is_entire_line;
7602 start_offset = end_offset + 1;
7603 original_indent_column = Some(clipboard_selection.first_line_indent);
7604 } else {
7605 to_insert = clipboard_text.as_str();
7606 entire_line = all_selections_were_entire_line;
7607 original_indent_column = first_selection_indent_column
7608 }
7609
7610 // If the corresponding selection was empty when this slice of the
7611 // clipboard text was written, then the entire line containing the
7612 // selection was copied. If this selection is also currently empty,
7613 // then paste the line before the current line of the buffer.
7614 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7615 let column = selection.start.to_point(&snapshot).column as usize;
7616 let line_start = selection.start - column;
7617 line_start..line_start
7618 } else {
7619 selection.range()
7620 };
7621
7622 edits.push((range, to_insert));
7623 original_indent_columns.extend(original_indent_column);
7624 }
7625 drop(snapshot);
7626
7627 buffer.edit(
7628 edits,
7629 if auto_indent_on_paste {
7630 Some(AutoindentMode::Block {
7631 original_indent_columns,
7632 })
7633 } else {
7634 None
7635 },
7636 cx,
7637 );
7638 });
7639
7640 let selections = this.selections.all::<usize>(cx);
7641 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7642 } else {
7643 this.insert(&clipboard_text, cx);
7644 }
7645 });
7646 }
7647
7648 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7649 if let Some(item) = cx.read_from_clipboard() {
7650 let entries = item.entries();
7651
7652 match entries.first() {
7653 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7654 // of all the pasted entries.
7655 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7656 .do_paste(
7657 clipboard_string.text(),
7658 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7659 true,
7660 cx,
7661 ),
7662 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7663 }
7664 }
7665 }
7666
7667 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7668 if self.read_only(cx) {
7669 return;
7670 }
7671
7672 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7673 if let Some((selections, _)) =
7674 self.selection_history.transaction(transaction_id).cloned()
7675 {
7676 self.change_selections(None, cx, |s| {
7677 s.select_anchors(selections.to_vec());
7678 });
7679 }
7680 self.request_autoscroll(Autoscroll::fit(), cx);
7681 self.unmark_text(cx);
7682 self.refresh_inline_completion(true, false, cx);
7683 cx.emit(EditorEvent::Edited { transaction_id });
7684 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7685 }
7686 }
7687
7688 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7689 if self.read_only(cx) {
7690 return;
7691 }
7692
7693 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7694 if let Some((_, Some(selections))) =
7695 self.selection_history.transaction(transaction_id).cloned()
7696 {
7697 self.change_selections(None, cx, |s| {
7698 s.select_anchors(selections.to_vec());
7699 });
7700 }
7701 self.request_autoscroll(Autoscroll::fit(), cx);
7702 self.unmark_text(cx);
7703 self.refresh_inline_completion(true, false, cx);
7704 cx.emit(EditorEvent::Edited { transaction_id });
7705 }
7706 }
7707
7708 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7709 self.buffer
7710 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7711 }
7712
7713 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7714 self.buffer
7715 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7716 }
7717
7718 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7719 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7720 let line_mode = s.line_mode;
7721 s.move_with(|map, selection| {
7722 let cursor = if selection.is_empty() && !line_mode {
7723 movement::left(map, selection.start)
7724 } else {
7725 selection.start
7726 };
7727 selection.collapse_to(cursor, SelectionGoal::None);
7728 });
7729 })
7730 }
7731
7732 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7733 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7734 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7735 })
7736 }
7737
7738 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7739 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7740 let line_mode = s.line_mode;
7741 s.move_with(|map, selection| {
7742 let cursor = if selection.is_empty() && !line_mode {
7743 movement::right(map, selection.end)
7744 } else {
7745 selection.end
7746 };
7747 selection.collapse_to(cursor, SelectionGoal::None)
7748 });
7749 })
7750 }
7751
7752 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7753 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7754 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7755 })
7756 }
7757
7758 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7759 if self.take_rename(true, cx).is_some() {
7760 return;
7761 }
7762
7763 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7764 cx.propagate();
7765 return;
7766 }
7767
7768 let text_layout_details = &self.text_layout_details(cx);
7769 let selection_count = self.selections.count();
7770 let first_selection = self.selections.first_anchor();
7771
7772 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7773 let line_mode = s.line_mode;
7774 s.move_with(|map, selection| {
7775 if !selection.is_empty() && !line_mode {
7776 selection.goal = SelectionGoal::None;
7777 }
7778 let (cursor, goal) = movement::up(
7779 map,
7780 selection.start,
7781 selection.goal,
7782 false,
7783 text_layout_details,
7784 );
7785 selection.collapse_to(cursor, goal);
7786 });
7787 });
7788
7789 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7790 {
7791 cx.propagate();
7792 }
7793 }
7794
7795 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7796 if self.take_rename(true, cx).is_some() {
7797 return;
7798 }
7799
7800 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7801 cx.propagate();
7802 return;
7803 }
7804
7805 let text_layout_details = &self.text_layout_details(cx);
7806
7807 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7808 let line_mode = s.line_mode;
7809 s.move_with(|map, selection| {
7810 if !selection.is_empty() && !line_mode {
7811 selection.goal = SelectionGoal::None;
7812 }
7813 let (cursor, goal) = movement::up_by_rows(
7814 map,
7815 selection.start,
7816 action.lines,
7817 selection.goal,
7818 false,
7819 text_layout_details,
7820 );
7821 selection.collapse_to(cursor, goal);
7822 });
7823 })
7824 }
7825
7826 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7827 if self.take_rename(true, cx).is_some() {
7828 return;
7829 }
7830
7831 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7832 cx.propagate();
7833 return;
7834 }
7835
7836 let text_layout_details = &self.text_layout_details(cx);
7837
7838 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7839 let line_mode = s.line_mode;
7840 s.move_with(|map, selection| {
7841 if !selection.is_empty() && !line_mode {
7842 selection.goal = SelectionGoal::None;
7843 }
7844 let (cursor, goal) = movement::down_by_rows(
7845 map,
7846 selection.start,
7847 action.lines,
7848 selection.goal,
7849 false,
7850 text_layout_details,
7851 );
7852 selection.collapse_to(cursor, goal);
7853 });
7854 })
7855 }
7856
7857 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7858 let text_layout_details = &self.text_layout_details(cx);
7859 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7860 s.move_heads_with(|map, head, goal| {
7861 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7862 })
7863 })
7864 }
7865
7866 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7867 let text_layout_details = &self.text_layout_details(cx);
7868 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7869 s.move_heads_with(|map, head, goal| {
7870 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7871 })
7872 })
7873 }
7874
7875 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7876 let Some(row_count) = self.visible_row_count() else {
7877 return;
7878 };
7879
7880 let text_layout_details = &self.text_layout_details(cx);
7881
7882 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7883 s.move_heads_with(|map, head, goal| {
7884 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7885 })
7886 })
7887 }
7888
7889 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7890 if self.take_rename(true, cx).is_some() {
7891 return;
7892 }
7893
7894 if self
7895 .context_menu
7896 .write()
7897 .as_mut()
7898 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7899 .unwrap_or(false)
7900 {
7901 return;
7902 }
7903
7904 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7905 cx.propagate();
7906 return;
7907 }
7908
7909 let Some(row_count) = self.visible_row_count() else {
7910 return;
7911 };
7912
7913 let autoscroll = if action.center_cursor {
7914 Autoscroll::center()
7915 } else {
7916 Autoscroll::fit()
7917 };
7918
7919 let text_layout_details = &self.text_layout_details(cx);
7920
7921 self.change_selections(Some(autoscroll), cx, |s| {
7922 let line_mode = s.line_mode;
7923 s.move_with(|map, selection| {
7924 if !selection.is_empty() && !line_mode {
7925 selection.goal = SelectionGoal::None;
7926 }
7927 let (cursor, goal) = movement::up_by_rows(
7928 map,
7929 selection.end,
7930 row_count,
7931 selection.goal,
7932 false,
7933 text_layout_details,
7934 );
7935 selection.collapse_to(cursor, goal);
7936 });
7937 });
7938 }
7939
7940 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7941 let text_layout_details = &self.text_layout_details(cx);
7942 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7943 s.move_heads_with(|map, head, goal| {
7944 movement::up(map, head, goal, false, text_layout_details)
7945 })
7946 })
7947 }
7948
7949 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7950 self.take_rename(true, cx);
7951
7952 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7953 cx.propagate();
7954 return;
7955 }
7956
7957 let text_layout_details = &self.text_layout_details(cx);
7958 let selection_count = self.selections.count();
7959 let first_selection = self.selections.first_anchor();
7960
7961 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7962 let line_mode = s.line_mode;
7963 s.move_with(|map, selection| {
7964 if !selection.is_empty() && !line_mode {
7965 selection.goal = SelectionGoal::None;
7966 }
7967 let (cursor, goal) = movement::down(
7968 map,
7969 selection.end,
7970 selection.goal,
7971 false,
7972 text_layout_details,
7973 );
7974 selection.collapse_to(cursor, goal);
7975 });
7976 });
7977
7978 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7979 {
7980 cx.propagate();
7981 }
7982 }
7983
7984 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7985 let Some(row_count) = self.visible_row_count() else {
7986 return;
7987 };
7988
7989 let text_layout_details = &self.text_layout_details(cx);
7990
7991 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7992 s.move_heads_with(|map, head, goal| {
7993 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7994 })
7995 })
7996 }
7997
7998 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7999 if self.take_rename(true, cx).is_some() {
8000 return;
8001 }
8002
8003 if self
8004 .context_menu
8005 .write()
8006 .as_mut()
8007 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8008 .unwrap_or(false)
8009 {
8010 return;
8011 }
8012
8013 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8014 cx.propagate();
8015 return;
8016 }
8017
8018 let Some(row_count) = self.visible_row_count() else {
8019 return;
8020 };
8021
8022 let autoscroll = if action.center_cursor {
8023 Autoscroll::center()
8024 } else {
8025 Autoscroll::fit()
8026 };
8027
8028 let text_layout_details = &self.text_layout_details(cx);
8029 self.change_selections(Some(autoscroll), cx, |s| {
8030 let line_mode = s.line_mode;
8031 s.move_with(|map, selection| {
8032 if !selection.is_empty() && !line_mode {
8033 selection.goal = SelectionGoal::None;
8034 }
8035 let (cursor, goal) = movement::down_by_rows(
8036 map,
8037 selection.end,
8038 row_count,
8039 selection.goal,
8040 false,
8041 text_layout_details,
8042 );
8043 selection.collapse_to(cursor, goal);
8044 });
8045 });
8046 }
8047
8048 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
8049 let text_layout_details = &self.text_layout_details(cx);
8050 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8051 s.move_heads_with(|map, head, goal| {
8052 movement::down(map, head, goal, false, text_layout_details)
8053 })
8054 });
8055 }
8056
8057 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
8058 if let Some(context_menu) = self.context_menu.write().as_mut() {
8059 context_menu.select_first(self.completion_provider.as_deref(), cx);
8060 }
8061 }
8062
8063 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
8064 if let Some(context_menu) = self.context_menu.write().as_mut() {
8065 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8066 }
8067 }
8068
8069 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
8070 if let Some(context_menu) = self.context_menu.write().as_mut() {
8071 context_menu.select_next(self.completion_provider.as_deref(), cx);
8072 }
8073 }
8074
8075 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
8076 if let Some(context_menu) = self.context_menu.write().as_mut() {
8077 context_menu.select_last(self.completion_provider.as_deref(), cx);
8078 }
8079 }
8080
8081 pub fn move_to_previous_word_start(
8082 &mut self,
8083 _: &MoveToPreviousWordStart,
8084 cx: &mut ViewContext<Self>,
8085 ) {
8086 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8087 s.move_cursors_with(|map, head, _| {
8088 (
8089 movement::previous_word_start(map, head),
8090 SelectionGoal::None,
8091 )
8092 });
8093 })
8094 }
8095
8096 pub fn move_to_previous_subword_start(
8097 &mut self,
8098 _: &MoveToPreviousSubwordStart,
8099 cx: &mut ViewContext<Self>,
8100 ) {
8101 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8102 s.move_cursors_with(|map, head, _| {
8103 (
8104 movement::previous_subword_start(map, head),
8105 SelectionGoal::None,
8106 )
8107 });
8108 })
8109 }
8110
8111 pub fn select_to_previous_word_start(
8112 &mut self,
8113 _: &SelectToPreviousWordStart,
8114 cx: &mut ViewContext<Self>,
8115 ) {
8116 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8117 s.move_heads_with(|map, head, _| {
8118 (
8119 movement::previous_word_start(map, head),
8120 SelectionGoal::None,
8121 )
8122 });
8123 })
8124 }
8125
8126 pub fn select_to_previous_subword_start(
8127 &mut self,
8128 _: &SelectToPreviousSubwordStart,
8129 cx: &mut ViewContext<Self>,
8130 ) {
8131 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8132 s.move_heads_with(|map, head, _| {
8133 (
8134 movement::previous_subword_start(map, head),
8135 SelectionGoal::None,
8136 )
8137 });
8138 })
8139 }
8140
8141 pub fn delete_to_previous_word_start(
8142 &mut self,
8143 action: &DeleteToPreviousWordStart,
8144 cx: &mut ViewContext<Self>,
8145 ) {
8146 self.transact(cx, |this, cx| {
8147 this.select_autoclose_pair(cx);
8148 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8149 let line_mode = s.line_mode;
8150 s.move_with(|map, selection| {
8151 if selection.is_empty() && !line_mode {
8152 let cursor = if action.ignore_newlines {
8153 movement::previous_word_start(map, selection.head())
8154 } else {
8155 movement::previous_word_start_or_newline(map, selection.head())
8156 };
8157 selection.set_head(cursor, SelectionGoal::None);
8158 }
8159 });
8160 });
8161 this.insert("", cx);
8162 });
8163 }
8164
8165 pub fn delete_to_previous_subword_start(
8166 &mut self,
8167 _: &DeleteToPreviousSubwordStart,
8168 cx: &mut ViewContext<Self>,
8169 ) {
8170 self.transact(cx, |this, cx| {
8171 this.select_autoclose_pair(cx);
8172 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8173 let line_mode = s.line_mode;
8174 s.move_with(|map, selection| {
8175 if selection.is_empty() && !line_mode {
8176 let cursor = movement::previous_subword_start(map, selection.head());
8177 selection.set_head(cursor, SelectionGoal::None);
8178 }
8179 });
8180 });
8181 this.insert("", cx);
8182 });
8183 }
8184
8185 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
8186 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8187 s.move_cursors_with(|map, head, _| {
8188 (movement::next_word_end(map, head), SelectionGoal::None)
8189 });
8190 })
8191 }
8192
8193 pub fn move_to_next_subword_end(
8194 &mut self,
8195 _: &MoveToNextSubwordEnd,
8196 cx: &mut ViewContext<Self>,
8197 ) {
8198 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8199 s.move_cursors_with(|map, head, _| {
8200 (movement::next_subword_end(map, head), SelectionGoal::None)
8201 });
8202 })
8203 }
8204
8205 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
8206 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8207 s.move_heads_with(|map, head, _| {
8208 (movement::next_word_end(map, head), SelectionGoal::None)
8209 });
8210 })
8211 }
8212
8213 pub fn select_to_next_subword_end(
8214 &mut self,
8215 _: &SelectToNextSubwordEnd,
8216 cx: &mut ViewContext<Self>,
8217 ) {
8218 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8219 s.move_heads_with(|map, head, _| {
8220 (movement::next_subword_end(map, head), SelectionGoal::None)
8221 });
8222 })
8223 }
8224
8225 pub fn delete_to_next_word_end(
8226 &mut self,
8227 action: &DeleteToNextWordEnd,
8228 cx: &mut ViewContext<Self>,
8229 ) {
8230 self.transact(cx, |this, cx| {
8231 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8232 let line_mode = s.line_mode;
8233 s.move_with(|map, selection| {
8234 if selection.is_empty() && !line_mode {
8235 let cursor = if action.ignore_newlines {
8236 movement::next_word_end(map, selection.head())
8237 } else {
8238 movement::next_word_end_or_newline(map, selection.head())
8239 };
8240 selection.set_head(cursor, SelectionGoal::None);
8241 }
8242 });
8243 });
8244 this.insert("", cx);
8245 });
8246 }
8247
8248 pub fn delete_to_next_subword_end(
8249 &mut self,
8250 _: &DeleteToNextSubwordEnd,
8251 cx: &mut ViewContext<Self>,
8252 ) {
8253 self.transact(cx, |this, cx| {
8254 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8255 s.move_with(|map, selection| {
8256 if selection.is_empty() {
8257 let cursor = movement::next_subword_end(map, selection.head());
8258 selection.set_head(cursor, SelectionGoal::None);
8259 }
8260 });
8261 });
8262 this.insert("", cx);
8263 });
8264 }
8265
8266 pub fn move_to_beginning_of_line(
8267 &mut self,
8268 action: &MoveToBeginningOfLine,
8269 cx: &mut ViewContext<Self>,
8270 ) {
8271 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8272 s.move_cursors_with(|map, head, _| {
8273 (
8274 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8275 SelectionGoal::None,
8276 )
8277 });
8278 })
8279 }
8280
8281 pub fn select_to_beginning_of_line(
8282 &mut self,
8283 action: &SelectToBeginningOfLine,
8284 cx: &mut ViewContext<Self>,
8285 ) {
8286 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8287 s.move_heads_with(|map, head, _| {
8288 (
8289 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8290 SelectionGoal::None,
8291 )
8292 });
8293 });
8294 }
8295
8296 pub fn delete_to_beginning_of_line(
8297 &mut self,
8298 _: &DeleteToBeginningOfLine,
8299 cx: &mut ViewContext<Self>,
8300 ) {
8301 self.transact(cx, |this, cx| {
8302 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8303 s.move_with(|_, selection| {
8304 selection.reversed = true;
8305 });
8306 });
8307
8308 this.select_to_beginning_of_line(
8309 &SelectToBeginningOfLine {
8310 stop_at_soft_wraps: false,
8311 },
8312 cx,
8313 );
8314 this.backspace(&Backspace, cx);
8315 });
8316 }
8317
8318 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
8319 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8320 s.move_cursors_with(|map, head, _| {
8321 (
8322 movement::line_end(map, head, action.stop_at_soft_wraps),
8323 SelectionGoal::None,
8324 )
8325 });
8326 })
8327 }
8328
8329 pub fn select_to_end_of_line(
8330 &mut self,
8331 action: &SelectToEndOfLine,
8332 cx: &mut ViewContext<Self>,
8333 ) {
8334 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8335 s.move_heads_with(|map, head, _| {
8336 (
8337 movement::line_end(map, head, action.stop_at_soft_wraps),
8338 SelectionGoal::None,
8339 )
8340 });
8341 })
8342 }
8343
8344 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
8345 self.transact(cx, |this, cx| {
8346 this.select_to_end_of_line(
8347 &SelectToEndOfLine {
8348 stop_at_soft_wraps: false,
8349 },
8350 cx,
8351 );
8352 this.delete(&Delete, cx);
8353 });
8354 }
8355
8356 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
8357 self.transact(cx, |this, cx| {
8358 this.select_to_end_of_line(
8359 &SelectToEndOfLine {
8360 stop_at_soft_wraps: false,
8361 },
8362 cx,
8363 );
8364 this.cut(&Cut, cx);
8365 });
8366 }
8367
8368 pub fn move_to_start_of_paragraph(
8369 &mut self,
8370 _: &MoveToStartOfParagraph,
8371 cx: &mut ViewContext<Self>,
8372 ) {
8373 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8374 cx.propagate();
8375 return;
8376 }
8377
8378 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8379 s.move_with(|map, selection| {
8380 selection.collapse_to(
8381 movement::start_of_paragraph(map, selection.head(), 1),
8382 SelectionGoal::None,
8383 )
8384 });
8385 })
8386 }
8387
8388 pub fn move_to_end_of_paragraph(
8389 &mut self,
8390 _: &MoveToEndOfParagraph,
8391 cx: &mut ViewContext<Self>,
8392 ) {
8393 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8394 cx.propagate();
8395 return;
8396 }
8397
8398 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8399 s.move_with(|map, selection| {
8400 selection.collapse_to(
8401 movement::end_of_paragraph(map, selection.head(), 1),
8402 SelectionGoal::None,
8403 )
8404 });
8405 })
8406 }
8407
8408 pub fn select_to_start_of_paragraph(
8409 &mut self,
8410 _: &SelectToStartOfParagraph,
8411 cx: &mut ViewContext<Self>,
8412 ) {
8413 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8414 cx.propagate();
8415 return;
8416 }
8417
8418 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8419 s.move_heads_with(|map, head, _| {
8420 (
8421 movement::start_of_paragraph(map, head, 1),
8422 SelectionGoal::None,
8423 )
8424 });
8425 })
8426 }
8427
8428 pub fn select_to_end_of_paragraph(
8429 &mut self,
8430 _: &SelectToEndOfParagraph,
8431 cx: &mut ViewContext<Self>,
8432 ) {
8433 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8434 cx.propagate();
8435 return;
8436 }
8437
8438 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8439 s.move_heads_with(|map, head, _| {
8440 (
8441 movement::end_of_paragraph(map, head, 1),
8442 SelectionGoal::None,
8443 )
8444 });
8445 })
8446 }
8447
8448 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
8449 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8450 cx.propagate();
8451 return;
8452 }
8453
8454 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8455 s.select_ranges(vec![0..0]);
8456 });
8457 }
8458
8459 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
8460 let mut selection = self.selections.last::<Point>(cx);
8461 selection.set_head(Point::zero(), SelectionGoal::None);
8462
8463 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8464 s.select(vec![selection]);
8465 });
8466 }
8467
8468 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
8469 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8470 cx.propagate();
8471 return;
8472 }
8473
8474 let cursor = self.buffer.read(cx).read(cx).len();
8475 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8476 s.select_ranges(vec![cursor..cursor])
8477 });
8478 }
8479
8480 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8481 self.nav_history = nav_history;
8482 }
8483
8484 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8485 self.nav_history.as_ref()
8486 }
8487
8488 fn push_to_nav_history(
8489 &mut self,
8490 cursor_anchor: Anchor,
8491 new_position: Option<Point>,
8492 cx: &mut ViewContext<Self>,
8493 ) {
8494 if let Some(nav_history) = self.nav_history.as_mut() {
8495 let buffer = self.buffer.read(cx).read(cx);
8496 let cursor_position = cursor_anchor.to_point(&buffer);
8497 let scroll_state = self.scroll_manager.anchor();
8498 let scroll_top_row = scroll_state.top_row(&buffer);
8499 drop(buffer);
8500
8501 if let Some(new_position) = new_position {
8502 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8503 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8504 return;
8505 }
8506 }
8507
8508 nav_history.push(
8509 Some(NavigationData {
8510 cursor_anchor,
8511 cursor_position,
8512 scroll_anchor: scroll_state,
8513 scroll_top_row,
8514 }),
8515 cx,
8516 );
8517 }
8518 }
8519
8520 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
8521 let buffer = self.buffer.read(cx).snapshot(cx);
8522 let mut selection = self.selections.first::<usize>(cx);
8523 selection.set_head(buffer.len(), SelectionGoal::None);
8524 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8525 s.select(vec![selection]);
8526 });
8527 }
8528
8529 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
8530 let end = self.buffer.read(cx).read(cx).len();
8531 self.change_selections(None, cx, |s| {
8532 s.select_ranges(vec![0..end]);
8533 });
8534 }
8535
8536 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8537 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8538 let mut selections = self.selections.all::<Point>(cx);
8539 let max_point = display_map.buffer_snapshot.max_point();
8540 for selection in &mut selections {
8541 let rows = selection.spanned_rows(true, &display_map);
8542 selection.start = Point::new(rows.start.0, 0);
8543 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8544 selection.reversed = false;
8545 }
8546 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8547 s.select(selections);
8548 });
8549 }
8550
8551 pub fn split_selection_into_lines(
8552 &mut self,
8553 _: &SplitSelectionIntoLines,
8554 cx: &mut ViewContext<Self>,
8555 ) {
8556 let mut to_unfold = Vec::new();
8557 let mut new_selection_ranges = Vec::new();
8558 {
8559 let selections = self.selections.all::<Point>(cx);
8560 let buffer = self.buffer.read(cx).read(cx);
8561 for selection in selections {
8562 for row in selection.start.row..selection.end.row {
8563 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8564 new_selection_ranges.push(cursor..cursor);
8565 }
8566 new_selection_ranges.push(selection.end..selection.end);
8567 to_unfold.push(selection.start..selection.end);
8568 }
8569 }
8570 self.unfold_ranges(&to_unfold, true, true, cx);
8571 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8572 s.select_ranges(new_selection_ranges);
8573 });
8574 }
8575
8576 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8577 self.add_selection(true, cx);
8578 }
8579
8580 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8581 self.add_selection(false, cx);
8582 }
8583
8584 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8585 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8586 let mut selections = self.selections.all::<Point>(cx);
8587 let text_layout_details = self.text_layout_details(cx);
8588 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8589 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8590 let range = oldest_selection.display_range(&display_map).sorted();
8591
8592 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8593 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8594 let positions = start_x.min(end_x)..start_x.max(end_x);
8595
8596 selections.clear();
8597 let mut stack = Vec::new();
8598 for row in range.start.row().0..=range.end.row().0 {
8599 if let Some(selection) = self.selections.build_columnar_selection(
8600 &display_map,
8601 DisplayRow(row),
8602 &positions,
8603 oldest_selection.reversed,
8604 &text_layout_details,
8605 ) {
8606 stack.push(selection.id);
8607 selections.push(selection);
8608 }
8609 }
8610
8611 if above {
8612 stack.reverse();
8613 }
8614
8615 AddSelectionsState { above, stack }
8616 });
8617
8618 let last_added_selection = *state.stack.last().unwrap();
8619 let mut new_selections = Vec::new();
8620 if above == state.above {
8621 let end_row = if above {
8622 DisplayRow(0)
8623 } else {
8624 display_map.max_point().row()
8625 };
8626
8627 'outer: for selection in selections {
8628 if selection.id == last_added_selection {
8629 let range = selection.display_range(&display_map).sorted();
8630 debug_assert_eq!(range.start.row(), range.end.row());
8631 let mut row = range.start.row();
8632 let positions =
8633 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8634 px(start)..px(end)
8635 } else {
8636 let start_x =
8637 display_map.x_for_display_point(range.start, &text_layout_details);
8638 let end_x =
8639 display_map.x_for_display_point(range.end, &text_layout_details);
8640 start_x.min(end_x)..start_x.max(end_x)
8641 };
8642
8643 while row != end_row {
8644 if above {
8645 row.0 -= 1;
8646 } else {
8647 row.0 += 1;
8648 }
8649
8650 if let Some(new_selection) = self.selections.build_columnar_selection(
8651 &display_map,
8652 row,
8653 &positions,
8654 selection.reversed,
8655 &text_layout_details,
8656 ) {
8657 state.stack.push(new_selection.id);
8658 if above {
8659 new_selections.push(new_selection);
8660 new_selections.push(selection);
8661 } else {
8662 new_selections.push(selection);
8663 new_selections.push(new_selection);
8664 }
8665
8666 continue 'outer;
8667 }
8668 }
8669 }
8670
8671 new_selections.push(selection);
8672 }
8673 } else {
8674 new_selections = selections;
8675 new_selections.retain(|s| s.id != last_added_selection);
8676 state.stack.pop();
8677 }
8678
8679 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8680 s.select(new_selections);
8681 });
8682 if state.stack.len() > 1 {
8683 self.add_selections_state = Some(state);
8684 }
8685 }
8686
8687 pub fn select_next_match_internal(
8688 &mut self,
8689 display_map: &DisplaySnapshot,
8690 replace_newest: bool,
8691 autoscroll: Option<Autoscroll>,
8692 cx: &mut ViewContext<Self>,
8693 ) -> Result<()> {
8694 fn select_next_match_ranges(
8695 this: &mut Editor,
8696 range: Range<usize>,
8697 replace_newest: bool,
8698 auto_scroll: Option<Autoscroll>,
8699 cx: &mut ViewContext<Editor>,
8700 ) {
8701 this.unfold_ranges(&[range.clone()], false, true, cx);
8702 this.change_selections(auto_scroll, cx, |s| {
8703 if replace_newest {
8704 s.delete(s.newest_anchor().id);
8705 }
8706 s.insert_range(range.clone());
8707 });
8708 }
8709
8710 let buffer = &display_map.buffer_snapshot;
8711 let mut selections = self.selections.all::<usize>(cx);
8712 if let Some(mut select_next_state) = self.select_next_state.take() {
8713 let query = &select_next_state.query;
8714 if !select_next_state.done {
8715 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8716 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8717 let mut next_selected_range = None;
8718
8719 let bytes_after_last_selection =
8720 buffer.bytes_in_range(last_selection.end..buffer.len());
8721 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8722 let query_matches = query
8723 .stream_find_iter(bytes_after_last_selection)
8724 .map(|result| (last_selection.end, result))
8725 .chain(
8726 query
8727 .stream_find_iter(bytes_before_first_selection)
8728 .map(|result| (0, result)),
8729 );
8730
8731 for (start_offset, query_match) in query_matches {
8732 let query_match = query_match.unwrap(); // can only fail due to I/O
8733 let offset_range =
8734 start_offset + query_match.start()..start_offset + query_match.end();
8735 let display_range = offset_range.start.to_display_point(display_map)
8736 ..offset_range.end.to_display_point(display_map);
8737
8738 if !select_next_state.wordwise
8739 || (!movement::is_inside_word(display_map, display_range.start)
8740 && !movement::is_inside_word(display_map, display_range.end))
8741 {
8742 // TODO: This is n^2, because we might check all the selections
8743 if !selections
8744 .iter()
8745 .any(|selection| selection.range().overlaps(&offset_range))
8746 {
8747 next_selected_range = Some(offset_range);
8748 break;
8749 }
8750 }
8751 }
8752
8753 if let Some(next_selected_range) = next_selected_range {
8754 select_next_match_ranges(
8755 self,
8756 next_selected_range,
8757 replace_newest,
8758 autoscroll,
8759 cx,
8760 );
8761 } else {
8762 select_next_state.done = true;
8763 }
8764 }
8765
8766 self.select_next_state = Some(select_next_state);
8767 } else {
8768 let mut only_carets = true;
8769 let mut same_text_selected = true;
8770 let mut selected_text = None;
8771
8772 let mut selections_iter = selections.iter().peekable();
8773 while let Some(selection) = selections_iter.next() {
8774 if selection.start != selection.end {
8775 only_carets = false;
8776 }
8777
8778 if same_text_selected {
8779 if selected_text.is_none() {
8780 selected_text =
8781 Some(buffer.text_for_range(selection.range()).collect::<String>());
8782 }
8783
8784 if let Some(next_selection) = selections_iter.peek() {
8785 if next_selection.range().len() == selection.range().len() {
8786 let next_selected_text = buffer
8787 .text_for_range(next_selection.range())
8788 .collect::<String>();
8789 if Some(next_selected_text) != selected_text {
8790 same_text_selected = false;
8791 selected_text = None;
8792 }
8793 } else {
8794 same_text_selected = false;
8795 selected_text = None;
8796 }
8797 }
8798 }
8799 }
8800
8801 if only_carets {
8802 for selection in &mut selections {
8803 let word_range = movement::surrounding_word(
8804 display_map,
8805 selection.start.to_display_point(display_map),
8806 );
8807 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8808 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8809 selection.goal = SelectionGoal::None;
8810 selection.reversed = false;
8811 select_next_match_ranges(
8812 self,
8813 selection.start..selection.end,
8814 replace_newest,
8815 autoscroll,
8816 cx,
8817 );
8818 }
8819
8820 if selections.len() == 1 {
8821 let selection = selections
8822 .last()
8823 .expect("ensured that there's only one selection");
8824 let query = buffer
8825 .text_for_range(selection.start..selection.end)
8826 .collect::<String>();
8827 let is_empty = query.is_empty();
8828 let select_state = SelectNextState {
8829 query: AhoCorasick::new(&[query])?,
8830 wordwise: true,
8831 done: is_empty,
8832 };
8833 self.select_next_state = Some(select_state);
8834 } else {
8835 self.select_next_state = None;
8836 }
8837 } else if let Some(selected_text) = selected_text {
8838 self.select_next_state = Some(SelectNextState {
8839 query: AhoCorasick::new(&[selected_text])?,
8840 wordwise: false,
8841 done: false,
8842 });
8843 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8844 }
8845 }
8846 Ok(())
8847 }
8848
8849 pub fn select_all_matches(
8850 &mut self,
8851 _action: &SelectAllMatches,
8852 cx: &mut ViewContext<Self>,
8853 ) -> Result<()> {
8854 self.push_to_selection_history();
8855 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8856
8857 self.select_next_match_internal(&display_map, false, None, cx)?;
8858 let Some(select_next_state) = self.select_next_state.as_mut() else {
8859 return Ok(());
8860 };
8861 if select_next_state.done {
8862 return Ok(());
8863 }
8864
8865 let mut new_selections = self.selections.all::<usize>(cx);
8866
8867 let buffer = &display_map.buffer_snapshot;
8868 let query_matches = select_next_state
8869 .query
8870 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8871
8872 for query_match in query_matches {
8873 let query_match = query_match.unwrap(); // can only fail due to I/O
8874 let offset_range = query_match.start()..query_match.end();
8875 let display_range = offset_range.start.to_display_point(&display_map)
8876 ..offset_range.end.to_display_point(&display_map);
8877
8878 if !select_next_state.wordwise
8879 || (!movement::is_inside_word(&display_map, display_range.start)
8880 && !movement::is_inside_word(&display_map, display_range.end))
8881 {
8882 self.selections.change_with(cx, |selections| {
8883 new_selections.push(Selection {
8884 id: selections.new_selection_id(),
8885 start: offset_range.start,
8886 end: offset_range.end,
8887 reversed: false,
8888 goal: SelectionGoal::None,
8889 });
8890 });
8891 }
8892 }
8893
8894 new_selections.sort_by_key(|selection| selection.start);
8895 let mut ix = 0;
8896 while ix + 1 < new_selections.len() {
8897 let current_selection = &new_selections[ix];
8898 let next_selection = &new_selections[ix + 1];
8899 if current_selection.range().overlaps(&next_selection.range()) {
8900 if current_selection.id < next_selection.id {
8901 new_selections.remove(ix + 1);
8902 } else {
8903 new_selections.remove(ix);
8904 }
8905 } else {
8906 ix += 1;
8907 }
8908 }
8909
8910 select_next_state.done = true;
8911 self.unfold_ranges(
8912 &new_selections
8913 .iter()
8914 .map(|selection| selection.range())
8915 .collect::<Vec<_>>(),
8916 false,
8917 false,
8918 cx,
8919 );
8920 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8921 selections.select(new_selections)
8922 });
8923
8924 Ok(())
8925 }
8926
8927 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8928 self.push_to_selection_history();
8929 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8930 self.select_next_match_internal(
8931 &display_map,
8932 action.replace_newest,
8933 Some(Autoscroll::newest()),
8934 cx,
8935 )?;
8936 Ok(())
8937 }
8938
8939 pub fn select_previous(
8940 &mut self,
8941 action: &SelectPrevious,
8942 cx: &mut ViewContext<Self>,
8943 ) -> Result<()> {
8944 self.push_to_selection_history();
8945 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8946 let buffer = &display_map.buffer_snapshot;
8947 let mut selections = self.selections.all::<usize>(cx);
8948 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8949 let query = &select_prev_state.query;
8950 if !select_prev_state.done {
8951 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8952 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8953 let mut next_selected_range = None;
8954 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8955 let bytes_before_last_selection =
8956 buffer.reversed_bytes_in_range(0..last_selection.start);
8957 let bytes_after_first_selection =
8958 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8959 let query_matches = query
8960 .stream_find_iter(bytes_before_last_selection)
8961 .map(|result| (last_selection.start, result))
8962 .chain(
8963 query
8964 .stream_find_iter(bytes_after_first_selection)
8965 .map(|result| (buffer.len(), result)),
8966 );
8967 for (end_offset, query_match) in query_matches {
8968 let query_match = query_match.unwrap(); // can only fail due to I/O
8969 let offset_range =
8970 end_offset - query_match.end()..end_offset - query_match.start();
8971 let display_range = offset_range.start.to_display_point(&display_map)
8972 ..offset_range.end.to_display_point(&display_map);
8973
8974 if !select_prev_state.wordwise
8975 || (!movement::is_inside_word(&display_map, display_range.start)
8976 && !movement::is_inside_word(&display_map, display_range.end))
8977 {
8978 next_selected_range = Some(offset_range);
8979 break;
8980 }
8981 }
8982
8983 if let Some(next_selected_range) = next_selected_range {
8984 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8985 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8986 if action.replace_newest {
8987 s.delete(s.newest_anchor().id);
8988 }
8989 s.insert_range(next_selected_range);
8990 });
8991 } else {
8992 select_prev_state.done = true;
8993 }
8994 }
8995
8996 self.select_prev_state = Some(select_prev_state);
8997 } else {
8998 let mut only_carets = true;
8999 let mut same_text_selected = true;
9000 let mut selected_text = None;
9001
9002 let mut selections_iter = selections.iter().peekable();
9003 while let Some(selection) = selections_iter.next() {
9004 if selection.start != selection.end {
9005 only_carets = false;
9006 }
9007
9008 if same_text_selected {
9009 if selected_text.is_none() {
9010 selected_text =
9011 Some(buffer.text_for_range(selection.range()).collect::<String>());
9012 }
9013
9014 if let Some(next_selection) = selections_iter.peek() {
9015 if next_selection.range().len() == selection.range().len() {
9016 let next_selected_text = buffer
9017 .text_for_range(next_selection.range())
9018 .collect::<String>();
9019 if Some(next_selected_text) != selected_text {
9020 same_text_selected = false;
9021 selected_text = None;
9022 }
9023 } else {
9024 same_text_selected = false;
9025 selected_text = None;
9026 }
9027 }
9028 }
9029 }
9030
9031 if only_carets {
9032 for selection in &mut selections {
9033 let word_range = movement::surrounding_word(
9034 &display_map,
9035 selection.start.to_display_point(&display_map),
9036 );
9037 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9038 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9039 selection.goal = SelectionGoal::None;
9040 selection.reversed = false;
9041 }
9042 if selections.len() == 1 {
9043 let selection = selections
9044 .last()
9045 .expect("ensured that there's only one selection");
9046 let query = buffer
9047 .text_for_range(selection.start..selection.end)
9048 .collect::<String>();
9049 let is_empty = query.is_empty();
9050 let select_state = SelectNextState {
9051 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9052 wordwise: true,
9053 done: is_empty,
9054 };
9055 self.select_prev_state = Some(select_state);
9056 } else {
9057 self.select_prev_state = None;
9058 }
9059
9060 self.unfold_ranges(
9061 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9062 false,
9063 true,
9064 cx,
9065 );
9066 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
9067 s.select(selections);
9068 });
9069 } else if let Some(selected_text) = selected_text {
9070 self.select_prev_state = Some(SelectNextState {
9071 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9072 wordwise: false,
9073 done: false,
9074 });
9075 self.select_previous(action, cx)?;
9076 }
9077 }
9078 Ok(())
9079 }
9080
9081 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
9082 if self.read_only(cx) {
9083 return;
9084 }
9085 let text_layout_details = &self.text_layout_details(cx);
9086 self.transact(cx, |this, cx| {
9087 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9088 let mut edits = Vec::new();
9089 let mut selection_edit_ranges = Vec::new();
9090 let mut last_toggled_row = None;
9091 let snapshot = this.buffer.read(cx).read(cx);
9092 let empty_str: Arc<str> = Arc::default();
9093 let mut suffixes_inserted = Vec::new();
9094 let ignore_indent = action.ignore_indent;
9095
9096 fn comment_prefix_range(
9097 snapshot: &MultiBufferSnapshot,
9098 row: MultiBufferRow,
9099 comment_prefix: &str,
9100 comment_prefix_whitespace: &str,
9101 ignore_indent: bool,
9102 ) -> Range<Point> {
9103 let indent_size = if ignore_indent {
9104 0
9105 } else {
9106 snapshot.indent_size_for_line(row).len
9107 };
9108
9109 let start = Point::new(row.0, indent_size);
9110
9111 let mut line_bytes = snapshot
9112 .bytes_in_range(start..snapshot.max_point())
9113 .flatten()
9114 .copied();
9115
9116 // If this line currently begins with the line comment prefix, then record
9117 // the range containing the prefix.
9118 if line_bytes
9119 .by_ref()
9120 .take(comment_prefix.len())
9121 .eq(comment_prefix.bytes())
9122 {
9123 // Include any whitespace that matches the comment prefix.
9124 let matching_whitespace_len = line_bytes
9125 .zip(comment_prefix_whitespace.bytes())
9126 .take_while(|(a, b)| a == b)
9127 .count() as u32;
9128 let end = Point::new(
9129 start.row,
9130 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9131 );
9132 start..end
9133 } else {
9134 start..start
9135 }
9136 }
9137
9138 fn comment_suffix_range(
9139 snapshot: &MultiBufferSnapshot,
9140 row: MultiBufferRow,
9141 comment_suffix: &str,
9142 comment_suffix_has_leading_space: bool,
9143 ) -> Range<Point> {
9144 let end = Point::new(row.0, snapshot.line_len(row));
9145 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9146
9147 let mut line_end_bytes = snapshot
9148 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9149 .flatten()
9150 .copied();
9151
9152 let leading_space_len = if suffix_start_column > 0
9153 && line_end_bytes.next() == Some(b' ')
9154 && comment_suffix_has_leading_space
9155 {
9156 1
9157 } else {
9158 0
9159 };
9160
9161 // If this line currently begins with the line comment prefix, then record
9162 // the range containing the prefix.
9163 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9164 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9165 start..end
9166 } else {
9167 end..end
9168 }
9169 }
9170
9171 // TODO: Handle selections that cross excerpts
9172 for selection in &mut selections {
9173 let start_column = snapshot
9174 .indent_size_for_line(MultiBufferRow(selection.start.row))
9175 .len;
9176 let language = if let Some(language) =
9177 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9178 {
9179 language
9180 } else {
9181 continue;
9182 };
9183
9184 selection_edit_ranges.clear();
9185
9186 // If multiple selections contain a given row, avoid processing that
9187 // row more than once.
9188 let mut start_row = MultiBufferRow(selection.start.row);
9189 if last_toggled_row == Some(start_row) {
9190 start_row = start_row.next_row();
9191 }
9192 let end_row =
9193 if selection.end.row > selection.start.row && selection.end.column == 0 {
9194 MultiBufferRow(selection.end.row - 1)
9195 } else {
9196 MultiBufferRow(selection.end.row)
9197 };
9198 last_toggled_row = Some(end_row);
9199
9200 if start_row > end_row {
9201 continue;
9202 }
9203
9204 // If the language has line comments, toggle those.
9205 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9206
9207 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9208 if ignore_indent {
9209 full_comment_prefixes = full_comment_prefixes
9210 .into_iter()
9211 .map(|s| Arc::from(s.trim_end()))
9212 .collect();
9213 }
9214
9215 if !full_comment_prefixes.is_empty() {
9216 let first_prefix = full_comment_prefixes
9217 .first()
9218 .expect("prefixes is non-empty");
9219 let prefix_trimmed_lengths = full_comment_prefixes
9220 .iter()
9221 .map(|p| p.trim_end_matches(' ').len())
9222 .collect::<SmallVec<[usize; 4]>>();
9223
9224 let mut all_selection_lines_are_comments = true;
9225
9226 for row in start_row.0..=end_row.0 {
9227 let row = MultiBufferRow(row);
9228 if start_row < end_row && snapshot.is_line_blank(row) {
9229 continue;
9230 }
9231
9232 let prefix_range = full_comment_prefixes
9233 .iter()
9234 .zip(prefix_trimmed_lengths.iter().copied())
9235 .map(|(prefix, trimmed_prefix_len)| {
9236 comment_prefix_range(
9237 snapshot.deref(),
9238 row,
9239 &prefix[..trimmed_prefix_len],
9240 &prefix[trimmed_prefix_len..],
9241 ignore_indent,
9242 )
9243 })
9244 .max_by_key(|range| range.end.column - range.start.column)
9245 .expect("prefixes is non-empty");
9246
9247 if prefix_range.is_empty() {
9248 all_selection_lines_are_comments = false;
9249 }
9250
9251 selection_edit_ranges.push(prefix_range);
9252 }
9253
9254 if all_selection_lines_are_comments {
9255 edits.extend(
9256 selection_edit_ranges
9257 .iter()
9258 .cloned()
9259 .map(|range| (range, empty_str.clone())),
9260 );
9261 } else {
9262 let min_column = selection_edit_ranges
9263 .iter()
9264 .map(|range| range.start.column)
9265 .min()
9266 .unwrap_or(0);
9267 edits.extend(selection_edit_ranges.iter().map(|range| {
9268 let position = Point::new(range.start.row, min_column);
9269 (position..position, first_prefix.clone())
9270 }));
9271 }
9272 } else if let Some((full_comment_prefix, comment_suffix)) =
9273 language.block_comment_delimiters()
9274 {
9275 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9276 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9277 let prefix_range = comment_prefix_range(
9278 snapshot.deref(),
9279 start_row,
9280 comment_prefix,
9281 comment_prefix_whitespace,
9282 ignore_indent,
9283 );
9284 let suffix_range = comment_suffix_range(
9285 snapshot.deref(),
9286 end_row,
9287 comment_suffix.trim_start_matches(' '),
9288 comment_suffix.starts_with(' '),
9289 );
9290
9291 if prefix_range.is_empty() || suffix_range.is_empty() {
9292 edits.push((
9293 prefix_range.start..prefix_range.start,
9294 full_comment_prefix.clone(),
9295 ));
9296 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9297 suffixes_inserted.push((end_row, comment_suffix.len()));
9298 } else {
9299 edits.push((prefix_range, empty_str.clone()));
9300 edits.push((suffix_range, empty_str.clone()));
9301 }
9302 } else {
9303 continue;
9304 }
9305 }
9306
9307 drop(snapshot);
9308 this.buffer.update(cx, |buffer, cx| {
9309 buffer.edit(edits, None, cx);
9310 });
9311
9312 // Adjust selections so that they end before any comment suffixes that
9313 // were inserted.
9314 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9315 let mut selections = this.selections.all::<Point>(cx);
9316 let snapshot = this.buffer.read(cx).read(cx);
9317 for selection in &mut selections {
9318 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9319 match row.cmp(&MultiBufferRow(selection.end.row)) {
9320 Ordering::Less => {
9321 suffixes_inserted.next();
9322 continue;
9323 }
9324 Ordering::Greater => break,
9325 Ordering::Equal => {
9326 if selection.end.column == snapshot.line_len(row) {
9327 if selection.is_empty() {
9328 selection.start.column -= suffix_len as u32;
9329 }
9330 selection.end.column -= suffix_len as u32;
9331 }
9332 break;
9333 }
9334 }
9335 }
9336 }
9337
9338 drop(snapshot);
9339 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
9340
9341 let selections = this.selections.all::<Point>(cx);
9342 let selections_on_single_row = selections.windows(2).all(|selections| {
9343 selections[0].start.row == selections[1].start.row
9344 && selections[0].end.row == selections[1].end.row
9345 && selections[0].start.row == selections[0].end.row
9346 });
9347 let selections_selecting = selections
9348 .iter()
9349 .any(|selection| selection.start != selection.end);
9350 let advance_downwards = action.advance_downwards
9351 && selections_on_single_row
9352 && !selections_selecting
9353 && !matches!(this.mode, EditorMode::SingleLine { .. });
9354
9355 if advance_downwards {
9356 let snapshot = this.buffer.read(cx).snapshot(cx);
9357
9358 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
9359 s.move_cursors_with(|display_snapshot, display_point, _| {
9360 let mut point = display_point.to_point(display_snapshot);
9361 point.row += 1;
9362 point = snapshot.clip_point(point, Bias::Left);
9363 let display_point = point.to_display_point(display_snapshot);
9364 let goal = SelectionGoal::HorizontalPosition(
9365 display_snapshot
9366 .x_for_display_point(display_point, text_layout_details)
9367 .into(),
9368 );
9369 (display_point, goal)
9370 })
9371 });
9372 }
9373 });
9374 }
9375
9376 pub fn select_enclosing_symbol(
9377 &mut self,
9378 _: &SelectEnclosingSymbol,
9379 cx: &mut ViewContext<Self>,
9380 ) {
9381 let buffer = self.buffer.read(cx).snapshot(cx);
9382 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9383
9384 fn update_selection(
9385 selection: &Selection<usize>,
9386 buffer_snap: &MultiBufferSnapshot,
9387 ) -> Option<Selection<usize>> {
9388 let cursor = selection.head();
9389 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9390 for symbol in symbols.iter().rev() {
9391 let start = symbol.range.start.to_offset(buffer_snap);
9392 let end = symbol.range.end.to_offset(buffer_snap);
9393 let new_range = start..end;
9394 if start < selection.start || end > selection.end {
9395 return Some(Selection {
9396 id: selection.id,
9397 start: new_range.start,
9398 end: new_range.end,
9399 goal: SelectionGoal::None,
9400 reversed: selection.reversed,
9401 });
9402 }
9403 }
9404 None
9405 }
9406
9407 let mut selected_larger_symbol = false;
9408 let new_selections = old_selections
9409 .iter()
9410 .map(|selection| match update_selection(selection, &buffer) {
9411 Some(new_selection) => {
9412 if new_selection.range() != selection.range() {
9413 selected_larger_symbol = true;
9414 }
9415 new_selection
9416 }
9417 None => selection.clone(),
9418 })
9419 .collect::<Vec<_>>();
9420
9421 if selected_larger_symbol {
9422 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9423 s.select(new_selections);
9424 });
9425 }
9426 }
9427
9428 pub fn select_larger_syntax_node(
9429 &mut self,
9430 _: &SelectLargerSyntaxNode,
9431 cx: &mut ViewContext<Self>,
9432 ) {
9433 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9434 let buffer = self.buffer.read(cx).snapshot(cx);
9435 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9436
9437 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9438 let mut selected_larger_node = false;
9439 let new_selections = old_selections
9440 .iter()
9441 .map(|selection| {
9442 let old_range = selection.start..selection.end;
9443 let mut new_range = old_range.clone();
9444 while let Some(containing_range) =
9445 buffer.range_for_syntax_ancestor(new_range.clone())
9446 {
9447 new_range = containing_range;
9448 if !display_map.intersects_fold(new_range.start)
9449 && !display_map.intersects_fold(new_range.end)
9450 {
9451 break;
9452 }
9453 }
9454
9455 selected_larger_node |= new_range != old_range;
9456 Selection {
9457 id: selection.id,
9458 start: new_range.start,
9459 end: new_range.end,
9460 goal: SelectionGoal::None,
9461 reversed: selection.reversed,
9462 }
9463 })
9464 .collect::<Vec<_>>();
9465
9466 if selected_larger_node {
9467 stack.push(old_selections);
9468 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9469 s.select(new_selections);
9470 });
9471 }
9472 self.select_larger_syntax_node_stack = stack;
9473 }
9474
9475 pub fn select_smaller_syntax_node(
9476 &mut self,
9477 _: &SelectSmallerSyntaxNode,
9478 cx: &mut ViewContext<Self>,
9479 ) {
9480 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9481 if let Some(selections) = stack.pop() {
9482 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9483 s.select(selections.to_vec());
9484 });
9485 }
9486 self.select_larger_syntax_node_stack = stack;
9487 }
9488
9489 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
9490 if !EditorSettings::get_global(cx).gutter.runnables {
9491 self.clear_tasks();
9492 return Task::ready(());
9493 }
9494 let project = self.project.as_ref().map(Model::downgrade);
9495 cx.spawn(|this, mut cx| async move {
9496 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
9497 let Some(project) = project.and_then(|p| p.upgrade()) else {
9498 return;
9499 };
9500 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9501 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9502 }) else {
9503 return;
9504 };
9505
9506 let hide_runnables = project
9507 .update(&mut cx, |project, cx| {
9508 // Do not display any test indicators in non-dev server remote projects.
9509 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9510 })
9511 .unwrap_or(true);
9512 if hide_runnables {
9513 return;
9514 }
9515 let new_rows =
9516 cx.background_executor()
9517 .spawn({
9518 let snapshot = display_snapshot.clone();
9519 async move {
9520 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9521 }
9522 })
9523 .await;
9524 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9525
9526 this.update(&mut cx, |this, _| {
9527 this.clear_tasks();
9528 for (key, value) in rows {
9529 this.insert_tasks(key, value);
9530 }
9531 })
9532 .ok();
9533 })
9534 }
9535 fn fetch_runnable_ranges(
9536 snapshot: &DisplaySnapshot,
9537 range: Range<Anchor>,
9538 ) -> Vec<language::RunnableRange> {
9539 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9540 }
9541
9542 fn runnable_rows(
9543 project: Model<Project>,
9544 snapshot: DisplaySnapshot,
9545 runnable_ranges: Vec<RunnableRange>,
9546 mut cx: AsyncWindowContext,
9547 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9548 runnable_ranges
9549 .into_iter()
9550 .filter_map(|mut runnable| {
9551 let tasks = cx
9552 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9553 .ok()?;
9554 if tasks.is_empty() {
9555 return None;
9556 }
9557
9558 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9559
9560 let row = snapshot
9561 .buffer_snapshot
9562 .buffer_line_for_row(MultiBufferRow(point.row))?
9563 .1
9564 .start
9565 .row;
9566
9567 let context_range =
9568 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9569 Some((
9570 (runnable.buffer_id, row),
9571 RunnableTasks {
9572 templates: tasks,
9573 offset: MultiBufferOffset(runnable.run_range.start),
9574 context_range,
9575 column: point.column,
9576 extra_variables: runnable.extra_captures,
9577 },
9578 ))
9579 })
9580 .collect()
9581 }
9582
9583 fn templates_with_tags(
9584 project: &Model<Project>,
9585 runnable: &mut Runnable,
9586 cx: &WindowContext<'_>,
9587 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9588 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9589 let (worktree_id, file) = project
9590 .buffer_for_id(runnable.buffer, cx)
9591 .and_then(|buffer| buffer.read(cx).file())
9592 .map(|file| (file.worktree_id(cx), file.clone()))
9593 .unzip();
9594
9595 (
9596 project.task_store().read(cx).task_inventory().cloned(),
9597 worktree_id,
9598 file,
9599 )
9600 });
9601
9602 let tags = mem::take(&mut runnable.tags);
9603 let mut tags: Vec<_> = tags
9604 .into_iter()
9605 .flat_map(|tag| {
9606 let tag = tag.0.clone();
9607 inventory
9608 .as_ref()
9609 .into_iter()
9610 .flat_map(|inventory| {
9611 inventory.read(cx).list_tasks(
9612 file.clone(),
9613 Some(runnable.language.clone()),
9614 worktree_id,
9615 cx,
9616 )
9617 })
9618 .filter(move |(_, template)| {
9619 template.tags.iter().any(|source_tag| source_tag == &tag)
9620 })
9621 })
9622 .sorted_by_key(|(kind, _)| kind.to_owned())
9623 .collect();
9624 if let Some((leading_tag_source, _)) = tags.first() {
9625 // Strongest source wins; if we have worktree tag binding, prefer that to
9626 // global and language bindings;
9627 // if we have a global binding, prefer that to language binding.
9628 let first_mismatch = tags
9629 .iter()
9630 .position(|(tag_source, _)| tag_source != leading_tag_source);
9631 if let Some(index) = first_mismatch {
9632 tags.truncate(index);
9633 }
9634 }
9635
9636 tags
9637 }
9638
9639 pub fn move_to_enclosing_bracket(
9640 &mut self,
9641 _: &MoveToEnclosingBracket,
9642 cx: &mut ViewContext<Self>,
9643 ) {
9644 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9645 s.move_offsets_with(|snapshot, selection| {
9646 let Some(enclosing_bracket_ranges) =
9647 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9648 else {
9649 return;
9650 };
9651
9652 let mut best_length = usize::MAX;
9653 let mut best_inside = false;
9654 let mut best_in_bracket_range = false;
9655 let mut best_destination = None;
9656 for (open, close) in enclosing_bracket_ranges {
9657 let close = close.to_inclusive();
9658 let length = close.end() - open.start;
9659 let inside = selection.start >= open.end && selection.end <= *close.start();
9660 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9661 || close.contains(&selection.head());
9662
9663 // If best is next to a bracket and current isn't, skip
9664 if !in_bracket_range && best_in_bracket_range {
9665 continue;
9666 }
9667
9668 // Prefer smaller lengths unless best is inside and current isn't
9669 if length > best_length && (best_inside || !inside) {
9670 continue;
9671 }
9672
9673 best_length = length;
9674 best_inside = inside;
9675 best_in_bracket_range = in_bracket_range;
9676 best_destination = Some(
9677 if close.contains(&selection.start) && close.contains(&selection.end) {
9678 if inside {
9679 open.end
9680 } else {
9681 open.start
9682 }
9683 } else if inside {
9684 *close.start()
9685 } else {
9686 *close.end()
9687 },
9688 );
9689 }
9690
9691 if let Some(destination) = best_destination {
9692 selection.collapse_to(destination, SelectionGoal::None);
9693 }
9694 })
9695 });
9696 }
9697
9698 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9699 self.end_selection(cx);
9700 self.selection_history.mode = SelectionHistoryMode::Undoing;
9701 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9702 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9703 self.select_next_state = entry.select_next_state;
9704 self.select_prev_state = entry.select_prev_state;
9705 self.add_selections_state = entry.add_selections_state;
9706 self.request_autoscroll(Autoscroll::newest(), cx);
9707 }
9708 self.selection_history.mode = SelectionHistoryMode::Normal;
9709 }
9710
9711 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9712 self.end_selection(cx);
9713 self.selection_history.mode = SelectionHistoryMode::Redoing;
9714 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9715 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9716 self.select_next_state = entry.select_next_state;
9717 self.select_prev_state = entry.select_prev_state;
9718 self.add_selections_state = entry.add_selections_state;
9719 self.request_autoscroll(Autoscroll::newest(), cx);
9720 }
9721 self.selection_history.mode = SelectionHistoryMode::Normal;
9722 }
9723
9724 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9725 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9726 }
9727
9728 pub fn expand_excerpts_down(
9729 &mut self,
9730 action: &ExpandExcerptsDown,
9731 cx: &mut ViewContext<Self>,
9732 ) {
9733 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9734 }
9735
9736 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9737 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9738 }
9739
9740 pub fn expand_excerpts_for_direction(
9741 &mut self,
9742 lines: u32,
9743 direction: ExpandExcerptDirection,
9744 cx: &mut ViewContext<Self>,
9745 ) {
9746 let selections = self.selections.disjoint_anchors();
9747
9748 let lines = if lines == 0 {
9749 EditorSettings::get_global(cx).expand_excerpt_lines
9750 } else {
9751 lines
9752 };
9753
9754 self.buffer.update(cx, |buffer, cx| {
9755 buffer.expand_excerpts(
9756 selections
9757 .iter()
9758 .map(|selection| selection.head().excerpt_id)
9759 .dedup(),
9760 lines,
9761 direction,
9762 cx,
9763 )
9764 })
9765 }
9766
9767 pub fn expand_excerpt(
9768 &mut self,
9769 excerpt: ExcerptId,
9770 direction: ExpandExcerptDirection,
9771 cx: &mut ViewContext<Self>,
9772 ) {
9773 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9774 self.buffer.update(cx, |buffer, cx| {
9775 buffer.expand_excerpts([excerpt], lines, direction, cx)
9776 })
9777 }
9778
9779 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9780 self.go_to_diagnostic_impl(Direction::Next, cx)
9781 }
9782
9783 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9784 self.go_to_diagnostic_impl(Direction::Prev, cx)
9785 }
9786
9787 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9788 let buffer = self.buffer.read(cx).snapshot(cx);
9789 let selection = self.selections.newest::<usize>(cx);
9790
9791 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9792 if direction == Direction::Next {
9793 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9794 let (group_id, jump_to) = popover.activation_info();
9795 if self.activate_diagnostics(group_id, cx) {
9796 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9797 let mut new_selection = s.newest_anchor().clone();
9798 new_selection.collapse_to(jump_to, SelectionGoal::None);
9799 s.select_anchors(vec![new_selection.clone()]);
9800 });
9801 }
9802 return;
9803 }
9804 }
9805
9806 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9807 active_diagnostics
9808 .primary_range
9809 .to_offset(&buffer)
9810 .to_inclusive()
9811 });
9812 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9813 if active_primary_range.contains(&selection.head()) {
9814 *active_primary_range.start()
9815 } else {
9816 selection.head()
9817 }
9818 } else {
9819 selection.head()
9820 };
9821 let snapshot = self.snapshot(cx);
9822 loop {
9823 let diagnostics = if direction == Direction::Prev {
9824 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9825 } else {
9826 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9827 }
9828 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9829 let group = diagnostics
9830 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9831 // be sorted in a stable way
9832 // skip until we are at current active diagnostic, if it exists
9833 .skip_while(|entry| {
9834 (match direction {
9835 Direction::Prev => entry.range.start >= search_start,
9836 Direction::Next => entry.range.start <= search_start,
9837 }) && self
9838 .active_diagnostics
9839 .as_ref()
9840 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9841 })
9842 .find_map(|entry| {
9843 if entry.diagnostic.is_primary
9844 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9845 && !entry.range.is_empty()
9846 // if we match with the active diagnostic, skip it
9847 && Some(entry.diagnostic.group_id)
9848 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9849 {
9850 Some((entry.range, entry.diagnostic.group_id))
9851 } else {
9852 None
9853 }
9854 });
9855
9856 if let Some((primary_range, group_id)) = group {
9857 if self.activate_diagnostics(group_id, cx) {
9858 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9859 s.select(vec![Selection {
9860 id: selection.id,
9861 start: primary_range.start,
9862 end: primary_range.start,
9863 reversed: false,
9864 goal: SelectionGoal::None,
9865 }]);
9866 });
9867 }
9868 break;
9869 } else {
9870 // Cycle around to the start of the buffer, potentially moving back to the start of
9871 // the currently active diagnostic.
9872 active_primary_range.take();
9873 if direction == Direction::Prev {
9874 if search_start == buffer.len() {
9875 break;
9876 } else {
9877 search_start = buffer.len();
9878 }
9879 } else if search_start == 0 {
9880 break;
9881 } else {
9882 search_start = 0;
9883 }
9884 }
9885 }
9886 }
9887
9888 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9889 let snapshot = self.snapshot(cx);
9890 let selection = self.selections.newest::<Point>(cx);
9891 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9892 }
9893
9894 fn go_to_hunk_after_position(
9895 &mut self,
9896 snapshot: &EditorSnapshot,
9897 position: Point,
9898 cx: &mut ViewContext<'_, Editor>,
9899 ) -> Option<MultiBufferDiffHunk> {
9900 for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
9901 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9902 snapshot,
9903 position,
9904 ix > 0,
9905 snapshot.diff_map.diff_hunks_in_range(
9906 position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
9907 &snapshot.buffer_snapshot,
9908 ),
9909 cx,
9910 ) {
9911 return Some(hunk);
9912 }
9913 }
9914 None
9915 }
9916
9917 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9918 let snapshot = self.snapshot(cx);
9919 let selection = self.selections.newest::<Point>(cx);
9920 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9921 }
9922
9923 fn go_to_hunk_before_position(
9924 &mut self,
9925 snapshot: &EditorSnapshot,
9926 position: Point,
9927 cx: &mut ViewContext<'_, Editor>,
9928 ) -> Option<MultiBufferDiffHunk> {
9929 for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
9930 .into_iter()
9931 .enumerate()
9932 {
9933 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9934 snapshot,
9935 position,
9936 ix > 0,
9937 snapshot
9938 .diff_map
9939 .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
9940 cx,
9941 ) {
9942 return Some(hunk);
9943 }
9944 }
9945 None
9946 }
9947
9948 fn go_to_next_hunk_in_direction(
9949 &mut self,
9950 snapshot: &DisplaySnapshot,
9951 initial_point: Point,
9952 is_wrapped: bool,
9953 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9954 cx: &mut ViewContext<Editor>,
9955 ) -> Option<MultiBufferDiffHunk> {
9956 let display_point = initial_point.to_display_point(snapshot);
9957 let mut hunks = hunks
9958 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9959 .filter(|(display_hunk, _)| {
9960 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9961 })
9962 .dedup();
9963
9964 if let Some((display_hunk, hunk)) = hunks.next() {
9965 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9966 let row = display_hunk.start_display_row();
9967 let point = DisplayPoint::new(row, 0);
9968 s.select_display_ranges([point..point]);
9969 });
9970
9971 Some(hunk)
9972 } else {
9973 None
9974 }
9975 }
9976
9977 pub fn go_to_definition(
9978 &mut self,
9979 _: &GoToDefinition,
9980 cx: &mut ViewContext<Self>,
9981 ) -> Task<Result<Navigated>> {
9982 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9983 cx.spawn(|editor, mut cx| async move {
9984 if definition.await? == Navigated::Yes {
9985 return Ok(Navigated::Yes);
9986 }
9987 match editor.update(&mut cx, |editor, cx| {
9988 editor.find_all_references(&FindAllReferences, cx)
9989 })? {
9990 Some(references) => references.await,
9991 None => Ok(Navigated::No),
9992 }
9993 })
9994 }
9995
9996 pub fn go_to_declaration(
9997 &mut self,
9998 _: &GoToDeclaration,
9999 cx: &mut ViewContext<Self>,
10000 ) -> Task<Result<Navigated>> {
10001 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
10002 }
10003
10004 pub fn go_to_declaration_split(
10005 &mut self,
10006 _: &GoToDeclaration,
10007 cx: &mut ViewContext<Self>,
10008 ) -> Task<Result<Navigated>> {
10009 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
10010 }
10011
10012 pub fn go_to_implementation(
10013 &mut self,
10014 _: &GoToImplementation,
10015 cx: &mut ViewContext<Self>,
10016 ) -> Task<Result<Navigated>> {
10017 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
10018 }
10019
10020 pub fn go_to_implementation_split(
10021 &mut self,
10022 _: &GoToImplementationSplit,
10023 cx: &mut ViewContext<Self>,
10024 ) -> Task<Result<Navigated>> {
10025 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
10026 }
10027
10028 pub fn go_to_type_definition(
10029 &mut self,
10030 _: &GoToTypeDefinition,
10031 cx: &mut ViewContext<Self>,
10032 ) -> Task<Result<Navigated>> {
10033 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
10034 }
10035
10036 pub fn go_to_definition_split(
10037 &mut self,
10038 _: &GoToDefinitionSplit,
10039 cx: &mut ViewContext<Self>,
10040 ) -> Task<Result<Navigated>> {
10041 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
10042 }
10043
10044 pub fn go_to_type_definition_split(
10045 &mut self,
10046 _: &GoToTypeDefinitionSplit,
10047 cx: &mut ViewContext<Self>,
10048 ) -> Task<Result<Navigated>> {
10049 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
10050 }
10051
10052 fn go_to_definition_of_kind(
10053 &mut self,
10054 kind: GotoDefinitionKind,
10055 split: bool,
10056 cx: &mut ViewContext<Self>,
10057 ) -> Task<Result<Navigated>> {
10058 let Some(provider) = self.semantics_provider.clone() else {
10059 return Task::ready(Ok(Navigated::No));
10060 };
10061 let head = self.selections.newest::<usize>(cx).head();
10062 let buffer = self.buffer.read(cx);
10063 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10064 text_anchor
10065 } else {
10066 return Task::ready(Ok(Navigated::No));
10067 };
10068
10069 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10070 return Task::ready(Ok(Navigated::No));
10071 };
10072
10073 cx.spawn(|editor, mut cx| async move {
10074 let definitions = definitions.await?;
10075 let navigated = editor
10076 .update(&mut cx, |editor, cx| {
10077 editor.navigate_to_hover_links(
10078 Some(kind),
10079 definitions
10080 .into_iter()
10081 .filter(|location| {
10082 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10083 })
10084 .map(HoverLink::Text)
10085 .collect::<Vec<_>>(),
10086 split,
10087 cx,
10088 )
10089 })?
10090 .await?;
10091 anyhow::Ok(navigated)
10092 })
10093 }
10094
10095 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
10096 let position = self.selections.newest_anchor().head();
10097 let Some((buffer, buffer_position)) =
10098 self.buffer.read(cx).text_anchor_for_position(position, cx)
10099 else {
10100 return;
10101 };
10102
10103 cx.spawn(|editor, mut cx| async move {
10104 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
10105 editor.update(&mut cx, |_, cx| {
10106 cx.open_url(&url);
10107 })
10108 } else {
10109 Ok(())
10110 }
10111 })
10112 .detach();
10113 }
10114
10115 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
10116 let Some(workspace) = self.workspace() else {
10117 return;
10118 };
10119
10120 let position = self.selections.newest_anchor().head();
10121
10122 let Some((buffer, buffer_position)) =
10123 self.buffer.read(cx).text_anchor_for_position(position, cx)
10124 else {
10125 return;
10126 };
10127
10128 let project = self.project.clone();
10129
10130 cx.spawn(|_, mut cx| async move {
10131 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10132
10133 if let Some((_, path)) = result {
10134 workspace
10135 .update(&mut cx, |workspace, cx| {
10136 workspace.open_resolved_path(path, cx)
10137 })?
10138 .await?;
10139 }
10140 anyhow::Ok(())
10141 })
10142 .detach();
10143 }
10144
10145 pub(crate) fn navigate_to_hover_links(
10146 &mut self,
10147 kind: Option<GotoDefinitionKind>,
10148 mut definitions: Vec<HoverLink>,
10149 split: bool,
10150 cx: &mut ViewContext<Editor>,
10151 ) -> Task<Result<Navigated>> {
10152 // If there is one definition, just open it directly
10153 if definitions.len() == 1 {
10154 let definition = definitions.pop().unwrap();
10155
10156 enum TargetTaskResult {
10157 Location(Option<Location>),
10158 AlreadyNavigated,
10159 }
10160
10161 let target_task = match definition {
10162 HoverLink::Text(link) => {
10163 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10164 }
10165 HoverLink::InlayHint(lsp_location, server_id) => {
10166 let computation = self.compute_target_location(lsp_location, server_id, cx);
10167 cx.background_executor().spawn(async move {
10168 let location = computation.await?;
10169 Ok(TargetTaskResult::Location(location))
10170 })
10171 }
10172 HoverLink::Url(url) => {
10173 cx.open_url(&url);
10174 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10175 }
10176 HoverLink::File(path) => {
10177 if let Some(workspace) = self.workspace() {
10178 cx.spawn(|_, mut cx| async move {
10179 workspace
10180 .update(&mut cx, |workspace, cx| {
10181 workspace.open_resolved_path(path, cx)
10182 })?
10183 .await
10184 .map(|_| TargetTaskResult::AlreadyNavigated)
10185 })
10186 } else {
10187 Task::ready(Ok(TargetTaskResult::Location(None)))
10188 }
10189 }
10190 };
10191 cx.spawn(|editor, mut cx| async move {
10192 let target = match target_task.await.context("target resolution task")? {
10193 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10194 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10195 TargetTaskResult::Location(Some(target)) => target,
10196 };
10197
10198 editor.update(&mut cx, |editor, cx| {
10199 let Some(workspace) = editor.workspace() else {
10200 return Navigated::No;
10201 };
10202 let pane = workspace.read(cx).active_pane().clone();
10203
10204 let range = target.range.to_offset(target.buffer.read(cx));
10205 let range = editor.range_for_match(&range);
10206
10207 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10208 let buffer = target.buffer.read(cx);
10209 let range = check_multiline_range(buffer, range);
10210 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10211 s.select_ranges([range]);
10212 });
10213 } else {
10214 cx.window_context().defer(move |cx| {
10215 let target_editor: View<Self> =
10216 workspace.update(cx, |workspace, cx| {
10217 let pane = if split {
10218 workspace.adjacent_pane(cx)
10219 } else {
10220 workspace.active_pane().clone()
10221 };
10222
10223 workspace.open_project_item(
10224 pane,
10225 target.buffer.clone(),
10226 true,
10227 true,
10228 cx,
10229 )
10230 });
10231 target_editor.update(cx, |target_editor, cx| {
10232 // When selecting a definition in a different buffer, disable the nav history
10233 // to avoid creating a history entry at the previous cursor location.
10234 pane.update(cx, |pane, _| pane.disable_history());
10235 let buffer = target.buffer.read(cx);
10236 let range = check_multiline_range(buffer, range);
10237 target_editor.change_selections(
10238 Some(Autoscroll::focused()),
10239 cx,
10240 |s| {
10241 s.select_ranges([range]);
10242 },
10243 );
10244 pane.update(cx, |pane, _| pane.enable_history());
10245 });
10246 });
10247 }
10248 Navigated::Yes
10249 })
10250 })
10251 } else if !definitions.is_empty() {
10252 cx.spawn(|editor, mut cx| async move {
10253 let (title, location_tasks, workspace) = editor
10254 .update(&mut cx, |editor, cx| {
10255 let tab_kind = match kind {
10256 Some(GotoDefinitionKind::Implementation) => "Implementations",
10257 _ => "Definitions",
10258 };
10259 let title = definitions
10260 .iter()
10261 .find_map(|definition| match definition {
10262 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10263 let buffer = origin.buffer.read(cx);
10264 format!(
10265 "{} for {}",
10266 tab_kind,
10267 buffer
10268 .text_for_range(origin.range.clone())
10269 .collect::<String>()
10270 )
10271 }),
10272 HoverLink::InlayHint(_, _) => None,
10273 HoverLink::Url(_) => None,
10274 HoverLink::File(_) => None,
10275 })
10276 .unwrap_or(tab_kind.to_string());
10277 let location_tasks = definitions
10278 .into_iter()
10279 .map(|definition| match definition {
10280 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
10281 HoverLink::InlayHint(lsp_location, server_id) => {
10282 editor.compute_target_location(lsp_location, server_id, cx)
10283 }
10284 HoverLink::Url(_) => Task::ready(Ok(None)),
10285 HoverLink::File(_) => Task::ready(Ok(None)),
10286 })
10287 .collect::<Vec<_>>();
10288 (title, location_tasks, editor.workspace().clone())
10289 })
10290 .context("location tasks preparation")?;
10291
10292 let locations = future::join_all(location_tasks)
10293 .await
10294 .into_iter()
10295 .filter_map(|location| location.transpose())
10296 .collect::<Result<_>>()
10297 .context("location tasks")?;
10298
10299 let Some(workspace) = workspace else {
10300 return Ok(Navigated::No);
10301 };
10302 let opened = workspace
10303 .update(&mut cx, |workspace, cx| {
10304 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10305 })
10306 .ok();
10307
10308 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10309 })
10310 } else {
10311 Task::ready(Ok(Navigated::No))
10312 }
10313 }
10314
10315 fn compute_target_location(
10316 &self,
10317 lsp_location: lsp::Location,
10318 server_id: LanguageServerId,
10319 cx: &mut ViewContext<Self>,
10320 ) -> Task<anyhow::Result<Option<Location>>> {
10321 let Some(project) = self.project.clone() else {
10322 return Task::Ready(Some(Ok(None)));
10323 };
10324
10325 cx.spawn(move |editor, mut cx| async move {
10326 let location_task = editor.update(&mut cx, |_, cx| {
10327 project.update(cx, |project, cx| {
10328 let language_server_name = project
10329 .language_server_statuses(cx)
10330 .find(|(id, _)| server_id == *id)
10331 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10332 language_server_name.map(|language_server_name| {
10333 project.open_local_buffer_via_lsp(
10334 lsp_location.uri.clone(),
10335 server_id,
10336 language_server_name,
10337 cx,
10338 )
10339 })
10340 })
10341 })?;
10342 let location = match location_task {
10343 Some(task) => Some({
10344 let target_buffer_handle = task.await.context("open local buffer")?;
10345 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10346 let target_start = target_buffer
10347 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10348 let target_end = target_buffer
10349 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10350 target_buffer.anchor_after(target_start)
10351 ..target_buffer.anchor_before(target_end)
10352 })?;
10353 Location {
10354 buffer: target_buffer_handle,
10355 range,
10356 }
10357 }),
10358 None => None,
10359 };
10360 Ok(location)
10361 })
10362 }
10363
10364 pub fn find_all_references(
10365 &mut self,
10366 _: &FindAllReferences,
10367 cx: &mut ViewContext<Self>,
10368 ) -> Option<Task<Result<Navigated>>> {
10369 let selection = self.selections.newest::<usize>(cx);
10370 let multi_buffer = self.buffer.read(cx);
10371 let head = selection.head();
10372
10373 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10374 let head_anchor = multi_buffer_snapshot.anchor_at(
10375 head,
10376 if head < selection.tail() {
10377 Bias::Right
10378 } else {
10379 Bias::Left
10380 },
10381 );
10382
10383 match self
10384 .find_all_references_task_sources
10385 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10386 {
10387 Ok(_) => {
10388 log::info!(
10389 "Ignoring repeated FindAllReferences invocation with the position of already running task"
10390 );
10391 return None;
10392 }
10393 Err(i) => {
10394 self.find_all_references_task_sources.insert(i, head_anchor);
10395 }
10396 }
10397
10398 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10399 let workspace = self.workspace()?;
10400 let project = workspace.read(cx).project().clone();
10401 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10402 Some(cx.spawn(|editor, mut cx| async move {
10403 let _cleanup = defer({
10404 let mut cx = cx.clone();
10405 move || {
10406 let _ = editor.update(&mut cx, |editor, _| {
10407 if let Ok(i) =
10408 editor
10409 .find_all_references_task_sources
10410 .binary_search_by(|anchor| {
10411 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10412 })
10413 {
10414 editor.find_all_references_task_sources.remove(i);
10415 }
10416 });
10417 }
10418 });
10419
10420 let locations = references.await?;
10421 if locations.is_empty() {
10422 return anyhow::Ok(Navigated::No);
10423 }
10424
10425 workspace.update(&mut cx, |workspace, cx| {
10426 let title = locations
10427 .first()
10428 .as_ref()
10429 .map(|location| {
10430 let buffer = location.buffer.read(cx);
10431 format!(
10432 "References to `{}`",
10433 buffer
10434 .text_for_range(location.range.clone())
10435 .collect::<String>()
10436 )
10437 })
10438 .unwrap();
10439 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10440 Navigated::Yes
10441 })
10442 }))
10443 }
10444
10445 /// Opens a multibuffer with the given project locations in it
10446 pub fn open_locations_in_multibuffer(
10447 workspace: &mut Workspace,
10448 mut locations: Vec<Location>,
10449 title: String,
10450 split: bool,
10451 cx: &mut ViewContext<Workspace>,
10452 ) {
10453 // If there are multiple definitions, open them in a multibuffer
10454 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10455 let mut locations = locations.into_iter().peekable();
10456 let mut ranges_to_highlight = Vec::new();
10457 let capability = workspace.project().read(cx).capability();
10458
10459 let excerpt_buffer = cx.new_model(|cx| {
10460 let mut multibuffer = MultiBuffer::new(capability);
10461 while let Some(location) = locations.next() {
10462 let buffer = location.buffer.read(cx);
10463 let mut ranges_for_buffer = Vec::new();
10464 let range = location.range.to_offset(buffer);
10465 ranges_for_buffer.push(range.clone());
10466
10467 while let Some(next_location) = locations.peek() {
10468 if next_location.buffer == location.buffer {
10469 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10470 locations.next();
10471 } else {
10472 break;
10473 }
10474 }
10475
10476 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10477 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10478 location.buffer.clone(),
10479 ranges_for_buffer,
10480 DEFAULT_MULTIBUFFER_CONTEXT,
10481 cx,
10482 ))
10483 }
10484
10485 multibuffer.with_title(title)
10486 });
10487
10488 let editor = cx.new_view(|cx| {
10489 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10490 });
10491 editor.update(cx, |editor, cx| {
10492 if let Some(first_range) = ranges_to_highlight.first() {
10493 editor.change_selections(None, cx, |selections| {
10494 selections.clear_disjoint();
10495 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10496 });
10497 }
10498 editor.highlight_background::<Self>(
10499 &ranges_to_highlight,
10500 |theme| theme.editor_highlighted_line_background,
10501 cx,
10502 );
10503 });
10504
10505 let item = Box::new(editor);
10506 let item_id = item.item_id();
10507
10508 if split {
10509 workspace.split_item(SplitDirection::Right, item.clone(), cx);
10510 } else {
10511 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10512 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10513 pane.close_current_preview_item(cx)
10514 } else {
10515 None
10516 }
10517 });
10518 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10519 }
10520 workspace.active_pane().update(cx, |pane, cx| {
10521 pane.set_preview_item_id(Some(item_id), cx);
10522 });
10523 }
10524
10525 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10526 use language::ToOffset as _;
10527
10528 let provider = self.semantics_provider.clone()?;
10529 let selection = self.selections.newest_anchor().clone();
10530 let (cursor_buffer, cursor_buffer_position) = self
10531 .buffer
10532 .read(cx)
10533 .text_anchor_for_position(selection.head(), cx)?;
10534 let (tail_buffer, cursor_buffer_position_end) = self
10535 .buffer
10536 .read(cx)
10537 .text_anchor_for_position(selection.tail(), cx)?;
10538 if tail_buffer != cursor_buffer {
10539 return None;
10540 }
10541
10542 let snapshot = cursor_buffer.read(cx).snapshot();
10543 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10544 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10545 let prepare_rename = provider
10546 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10547 .unwrap_or_else(|| Task::ready(Ok(None)));
10548 drop(snapshot);
10549
10550 Some(cx.spawn(|this, mut cx| async move {
10551 let rename_range = if let Some(range) = prepare_rename.await? {
10552 Some(range)
10553 } else {
10554 this.update(&mut cx, |this, cx| {
10555 let buffer = this.buffer.read(cx).snapshot(cx);
10556 let mut buffer_highlights = this
10557 .document_highlights_for_position(selection.head(), &buffer)
10558 .filter(|highlight| {
10559 highlight.start.excerpt_id == selection.head().excerpt_id
10560 && highlight.end.excerpt_id == selection.head().excerpt_id
10561 });
10562 buffer_highlights
10563 .next()
10564 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10565 })?
10566 };
10567 if let Some(rename_range) = rename_range {
10568 this.update(&mut cx, |this, cx| {
10569 let snapshot = cursor_buffer.read(cx).snapshot();
10570 let rename_buffer_range = rename_range.to_offset(&snapshot);
10571 let cursor_offset_in_rename_range =
10572 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10573 let cursor_offset_in_rename_range_end =
10574 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10575
10576 this.take_rename(false, cx);
10577 let buffer = this.buffer.read(cx).read(cx);
10578 let cursor_offset = selection.head().to_offset(&buffer);
10579 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10580 let rename_end = rename_start + rename_buffer_range.len();
10581 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10582 let mut old_highlight_id = None;
10583 let old_name: Arc<str> = buffer
10584 .chunks(rename_start..rename_end, true)
10585 .map(|chunk| {
10586 if old_highlight_id.is_none() {
10587 old_highlight_id = chunk.syntax_highlight_id;
10588 }
10589 chunk.text
10590 })
10591 .collect::<String>()
10592 .into();
10593
10594 drop(buffer);
10595
10596 // Position the selection in the rename editor so that it matches the current selection.
10597 this.show_local_selections = false;
10598 let rename_editor = cx.new_view(|cx| {
10599 let mut editor = Editor::single_line(cx);
10600 editor.buffer.update(cx, |buffer, cx| {
10601 buffer.edit([(0..0, old_name.clone())], None, cx)
10602 });
10603 let rename_selection_range = match cursor_offset_in_rename_range
10604 .cmp(&cursor_offset_in_rename_range_end)
10605 {
10606 Ordering::Equal => {
10607 editor.select_all(&SelectAll, cx);
10608 return editor;
10609 }
10610 Ordering::Less => {
10611 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10612 }
10613 Ordering::Greater => {
10614 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10615 }
10616 };
10617 if rename_selection_range.end > old_name.len() {
10618 editor.select_all(&SelectAll, cx);
10619 } else {
10620 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10621 s.select_ranges([rename_selection_range]);
10622 });
10623 }
10624 editor
10625 });
10626 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10627 if e == &EditorEvent::Focused {
10628 cx.emit(EditorEvent::FocusedIn)
10629 }
10630 })
10631 .detach();
10632
10633 let write_highlights =
10634 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10635 let read_highlights =
10636 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10637 let ranges = write_highlights
10638 .iter()
10639 .flat_map(|(_, ranges)| ranges.iter())
10640 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10641 .cloned()
10642 .collect();
10643
10644 this.highlight_text::<Rename>(
10645 ranges,
10646 HighlightStyle {
10647 fade_out: Some(0.6),
10648 ..Default::default()
10649 },
10650 cx,
10651 );
10652 let rename_focus_handle = rename_editor.focus_handle(cx);
10653 cx.focus(&rename_focus_handle);
10654 let block_id = this.insert_blocks(
10655 [BlockProperties {
10656 style: BlockStyle::Flex,
10657 placement: BlockPlacement::Below(range.start),
10658 height: 1,
10659 render: Arc::new({
10660 let rename_editor = rename_editor.clone();
10661 move |cx: &mut BlockContext| {
10662 let mut text_style = cx.editor_style.text.clone();
10663 if let Some(highlight_style) = old_highlight_id
10664 .and_then(|h| h.style(&cx.editor_style.syntax))
10665 {
10666 text_style = text_style.highlight(highlight_style);
10667 }
10668 div()
10669 .block_mouse_down()
10670 .pl(cx.anchor_x)
10671 .child(EditorElement::new(
10672 &rename_editor,
10673 EditorStyle {
10674 background: cx.theme().system().transparent,
10675 local_player: cx.editor_style.local_player,
10676 text: text_style,
10677 scrollbar_width: cx.editor_style.scrollbar_width,
10678 syntax: cx.editor_style.syntax.clone(),
10679 status: cx.editor_style.status.clone(),
10680 inlay_hints_style: HighlightStyle {
10681 font_weight: Some(FontWeight::BOLD),
10682 ..make_inlay_hints_style(cx)
10683 },
10684 suggestions_style: HighlightStyle {
10685 color: Some(cx.theme().status().predictive),
10686 ..HighlightStyle::default()
10687 },
10688 ..EditorStyle::default()
10689 },
10690 ))
10691 .into_any_element()
10692 }
10693 }),
10694 priority: 0,
10695 }],
10696 Some(Autoscroll::fit()),
10697 cx,
10698 )[0];
10699 this.pending_rename = Some(RenameState {
10700 range,
10701 old_name,
10702 editor: rename_editor,
10703 block_id,
10704 });
10705 })?;
10706 }
10707
10708 Ok(())
10709 }))
10710 }
10711
10712 pub fn confirm_rename(
10713 &mut self,
10714 _: &ConfirmRename,
10715 cx: &mut ViewContext<Self>,
10716 ) -> Option<Task<Result<()>>> {
10717 let rename = self.take_rename(false, cx)?;
10718 let workspace = self.workspace()?.downgrade();
10719 let (buffer, start) = self
10720 .buffer
10721 .read(cx)
10722 .text_anchor_for_position(rename.range.start, cx)?;
10723 let (end_buffer, _) = self
10724 .buffer
10725 .read(cx)
10726 .text_anchor_for_position(rename.range.end, cx)?;
10727 if buffer != end_buffer {
10728 return None;
10729 }
10730
10731 let old_name = rename.old_name;
10732 let new_name = rename.editor.read(cx).text(cx);
10733
10734 let rename = self.semantics_provider.as_ref()?.perform_rename(
10735 &buffer,
10736 start,
10737 new_name.clone(),
10738 cx,
10739 )?;
10740
10741 Some(cx.spawn(|editor, mut cx| async move {
10742 let project_transaction = rename.await?;
10743 Self::open_project_transaction(
10744 &editor,
10745 workspace,
10746 project_transaction,
10747 format!("Rename: {} → {}", old_name, new_name),
10748 cx.clone(),
10749 )
10750 .await?;
10751
10752 editor.update(&mut cx, |editor, cx| {
10753 editor.refresh_document_highlights(cx);
10754 })?;
10755 Ok(())
10756 }))
10757 }
10758
10759 fn take_rename(
10760 &mut self,
10761 moving_cursor: bool,
10762 cx: &mut ViewContext<Self>,
10763 ) -> Option<RenameState> {
10764 let rename = self.pending_rename.take()?;
10765 if rename.editor.focus_handle(cx).is_focused(cx) {
10766 cx.focus(&self.focus_handle);
10767 }
10768
10769 self.remove_blocks(
10770 [rename.block_id].into_iter().collect(),
10771 Some(Autoscroll::fit()),
10772 cx,
10773 );
10774 self.clear_highlights::<Rename>(cx);
10775 self.show_local_selections = true;
10776
10777 if moving_cursor {
10778 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10779 editor.selections.newest::<usize>(cx).head()
10780 });
10781
10782 // Update the selection to match the position of the selection inside
10783 // the rename editor.
10784 let snapshot = self.buffer.read(cx).read(cx);
10785 let rename_range = rename.range.to_offset(&snapshot);
10786 let cursor_in_editor = snapshot
10787 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10788 .min(rename_range.end);
10789 drop(snapshot);
10790
10791 self.change_selections(None, cx, |s| {
10792 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10793 });
10794 } else {
10795 self.refresh_document_highlights(cx);
10796 }
10797
10798 Some(rename)
10799 }
10800
10801 pub fn pending_rename(&self) -> Option<&RenameState> {
10802 self.pending_rename.as_ref()
10803 }
10804
10805 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10806 let project = match &self.project {
10807 Some(project) => project.clone(),
10808 None => return None,
10809 };
10810
10811 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10812 }
10813
10814 fn format_selections(
10815 &mut self,
10816 _: &FormatSelections,
10817 cx: &mut ViewContext<Self>,
10818 ) -> Option<Task<Result<()>>> {
10819 let project = match &self.project {
10820 Some(project) => project.clone(),
10821 None => return None,
10822 };
10823
10824 let selections = self
10825 .selections
10826 .all_adjusted(cx)
10827 .into_iter()
10828 .filter(|s| !s.is_empty())
10829 .collect_vec();
10830
10831 Some(self.perform_format(
10832 project,
10833 FormatTrigger::Manual,
10834 FormatTarget::Ranges(selections),
10835 cx,
10836 ))
10837 }
10838
10839 fn perform_format(
10840 &mut self,
10841 project: Model<Project>,
10842 trigger: FormatTrigger,
10843 target: FormatTarget,
10844 cx: &mut ViewContext<Self>,
10845 ) -> Task<Result<()>> {
10846 let buffer = self.buffer().clone();
10847 let mut buffers = buffer.read(cx).all_buffers();
10848 if trigger == FormatTrigger::Save {
10849 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10850 }
10851
10852 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10853 let format = project.update(cx, |project, cx| {
10854 project.format(buffers, true, trigger, target, cx)
10855 });
10856
10857 cx.spawn(|_, mut cx| async move {
10858 let transaction = futures::select_biased! {
10859 () = timeout => {
10860 log::warn!("timed out waiting for formatting");
10861 None
10862 }
10863 transaction = format.log_err().fuse() => transaction,
10864 };
10865
10866 buffer
10867 .update(&mut cx, |buffer, cx| {
10868 if let Some(transaction) = transaction {
10869 if !buffer.is_singleton() {
10870 buffer.push_transaction(&transaction.0, cx);
10871 }
10872 }
10873
10874 cx.notify();
10875 })
10876 .ok();
10877
10878 Ok(())
10879 })
10880 }
10881
10882 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10883 if let Some(project) = self.project.clone() {
10884 self.buffer.update(cx, |multi_buffer, cx| {
10885 project.update(cx, |project, cx| {
10886 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10887 });
10888 })
10889 }
10890 }
10891
10892 fn cancel_language_server_work(
10893 &mut self,
10894 _: &actions::CancelLanguageServerWork,
10895 cx: &mut ViewContext<Self>,
10896 ) {
10897 if let Some(project) = self.project.clone() {
10898 self.buffer.update(cx, |multi_buffer, cx| {
10899 project.update(cx, |project, cx| {
10900 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10901 });
10902 })
10903 }
10904 }
10905
10906 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10907 cx.show_character_palette();
10908 }
10909
10910 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10911 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10912 let buffer = self.buffer.read(cx).snapshot(cx);
10913 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10914 let is_valid = buffer
10915 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10916 .any(|entry| {
10917 entry.diagnostic.is_primary
10918 && !entry.range.is_empty()
10919 && entry.range.start == primary_range_start
10920 && entry.diagnostic.message == active_diagnostics.primary_message
10921 });
10922
10923 if is_valid != active_diagnostics.is_valid {
10924 active_diagnostics.is_valid = is_valid;
10925 let mut new_styles = HashMap::default();
10926 for (block_id, diagnostic) in &active_diagnostics.blocks {
10927 new_styles.insert(
10928 *block_id,
10929 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10930 );
10931 }
10932 self.display_map.update(cx, |display_map, _cx| {
10933 display_map.replace_blocks(new_styles)
10934 });
10935 }
10936 }
10937 }
10938
10939 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10940 self.dismiss_diagnostics(cx);
10941 let snapshot = self.snapshot(cx);
10942 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10943 let buffer = self.buffer.read(cx).snapshot(cx);
10944
10945 let mut primary_range = None;
10946 let mut primary_message = None;
10947 let mut group_end = Point::zero();
10948 let diagnostic_group = buffer
10949 .diagnostic_group::<MultiBufferPoint>(group_id)
10950 .filter_map(|entry| {
10951 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10952 && (entry.range.start.row == entry.range.end.row
10953 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10954 {
10955 return None;
10956 }
10957 if entry.range.end > group_end {
10958 group_end = entry.range.end;
10959 }
10960 if entry.diagnostic.is_primary {
10961 primary_range = Some(entry.range.clone());
10962 primary_message = Some(entry.diagnostic.message.clone());
10963 }
10964 Some(entry)
10965 })
10966 .collect::<Vec<_>>();
10967 let primary_range = primary_range?;
10968 let primary_message = primary_message?;
10969 let primary_range =
10970 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10971
10972 let blocks = display_map
10973 .insert_blocks(
10974 diagnostic_group.iter().map(|entry| {
10975 let diagnostic = entry.diagnostic.clone();
10976 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10977 BlockProperties {
10978 style: BlockStyle::Fixed,
10979 placement: BlockPlacement::Below(
10980 buffer.anchor_after(entry.range.start),
10981 ),
10982 height: message_height,
10983 render: diagnostic_block_renderer(diagnostic, None, true, true),
10984 priority: 0,
10985 }
10986 }),
10987 cx,
10988 )
10989 .into_iter()
10990 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10991 .collect();
10992
10993 Some(ActiveDiagnosticGroup {
10994 primary_range,
10995 primary_message,
10996 group_id,
10997 blocks,
10998 is_valid: true,
10999 })
11000 });
11001 self.active_diagnostics.is_some()
11002 }
11003
11004 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
11005 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11006 self.display_map.update(cx, |display_map, cx| {
11007 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11008 });
11009 cx.notify();
11010 }
11011 }
11012
11013 pub fn set_selections_from_remote(
11014 &mut self,
11015 selections: Vec<Selection<Anchor>>,
11016 pending_selection: Option<Selection<Anchor>>,
11017 cx: &mut ViewContext<Self>,
11018 ) {
11019 let old_cursor_position = self.selections.newest_anchor().head();
11020 self.selections.change_with(cx, |s| {
11021 s.select_anchors(selections);
11022 if let Some(pending_selection) = pending_selection {
11023 s.set_pending(pending_selection, SelectMode::Character);
11024 } else {
11025 s.clear_pending();
11026 }
11027 });
11028 self.selections_did_change(false, &old_cursor_position, true, cx);
11029 }
11030
11031 fn push_to_selection_history(&mut self) {
11032 self.selection_history.push(SelectionHistoryEntry {
11033 selections: self.selections.disjoint_anchors(),
11034 select_next_state: self.select_next_state.clone(),
11035 select_prev_state: self.select_prev_state.clone(),
11036 add_selections_state: self.add_selections_state.clone(),
11037 });
11038 }
11039
11040 pub fn transact(
11041 &mut self,
11042 cx: &mut ViewContext<Self>,
11043 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
11044 ) -> Option<TransactionId> {
11045 self.start_transaction_at(Instant::now(), cx);
11046 update(self, cx);
11047 self.end_transaction_at(Instant::now(), cx)
11048 }
11049
11050 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
11051 self.end_selection(cx);
11052 if let Some(tx_id) = self
11053 .buffer
11054 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11055 {
11056 self.selection_history
11057 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11058 cx.emit(EditorEvent::TransactionBegun {
11059 transaction_id: tx_id,
11060 })
11061 }
11062 }
11063
11064 fn end_transaction_at(
11065 &mut self,
11066 now: Instant,
11067 cx: &mut ViewContext<Self>,
11068 ) -> Option<TransactionId> {
11069 if let Some(transaction_id) = self
11070 .buffer
11071 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11072 {
11073 if let Some((_, end_selections)) =
11074 self.selection_history.transaction_mut(transaction_id)
11075 {
11076 *end_selections = Some(self.selections.disjoint_anchors());
11077 } else {
11078 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11079 }
11080
11081 cx.emit(EditorEvent::Edited { transaction_id });
11082 Some(transaction_id)
11083 } else {
11084 None
11085 }
11086 }
11087
11088 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
11089 let selection = self.selections.newest::<Point>(cx);
11090
11091 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11092 let range = if selection.is_empty() {
11093 let point = selection.head().to_display_point(&display_map);
11094 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11095 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11096 .to_point(&display_map);
11097 start..end
11098 } else {
11099 selection.range()
11100 };
11101 if display_map.folds_in_range(range).next().is_some() {
11102 self.unfold_lines(&Default::default(), cx)
11103 } else {
11104 self.fold(&Default::default(), cx)
11105 }
11106 }
11107
11108 pub fn toggle_fold_recursive(
11109 &mut self,
11110 _: &actions::ToggleFoldRecursive,
11111 cx: &mut ViewContext<Self>,
11112 ) {
11113 let selection = self.selections.newest::<Point>(cx);
11114
11115 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11116 let range = if selection.is_empty() {
11117 let point = selection.head().to_display_point(&display_map);
11118 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11119 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11120 .to_point(&display_map);
11121 start..end
11122 } else {
11123 selection.range()
11124 };
11125 if display_map.folds_in_range(range).next().is_some() {
11126 self.unfold_recursive(&Default::default(), cx)
11127 } else {
11128 self.fold_recursive(&Default::default(), cx)
11129 }
11130 }
11131
11132 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
11133 let mut to_fold = Vec::new();
11134 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11135 let selections = self.selections.all_adjusted(cx);
11136
11137 for selection in selections {
11138 let range = selection.range().sorted();
11139 let buffer_start_row = range.start.row;
11140
11141 if range.start.row != range.end.row {
11142 let mut found = false;
11143 let mut row = range.start.row;
11144 while row <= range.end.row {
11145 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11146 found = true;
11147 row = crease.range().end.row + 1;
11148 to_fold.push(crease);
11149 } else {
11150 row += 1
11151 }
11152 }
11153 if found {
11154 continue;
11155 }
11156 }
11157
11158 for row in (0..=range.start.row).rev() {
11159 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11160 if crease.range().end.row >= buffer_start_row {
11161 to_fold.push(crease);
11162 if row <= range.start.row {
11163 break;
11164 }
11165 }
11166 }
11167 }
11168 }
11169
11170 self.fold_creases(to_fold, true, cx);
11171 }
11172
11173 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
11174 if !self.buffer.read(cx).is_singleton() {
11175 return;
11176 }
11177
11178 let fold_at_level = fold_at.level;
11179 let snapshot = self.buffer.read(cx).snapshot(cx);
11180 let mut to_fold = Vec::new();
11181 let mut stack = vec![(0, snapshot.max_row().0, 1)];
11182
11183 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11184 while start_row < end_row {
11185 match self
11186 .snapshot(cx)
11187 .crease_for_buffer_row(MultiBufferRow(start_row))
11188 {
11189 Some(crease) => {
11190 let nested_start_row = crease.range().start.row + 1;
11191 let nested_end_row = crease.range().end.row;
11192
11193 if current_level < fold_at_level {
11194 stack.push((nested_start_row, nested_end_row, current_level + 1));
11195 } else if current_level == fold_at_level {
11196 to_fold.push(crease);
11197 }
11198
11199 start_row = nested_end_row + 1;
11200 }
11201 None => start_row += 1,
11202 }
11203 }
11204 }
11205
11206 self.fold_creases(to_fold, true, cx);
11207 }
11208
11209 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
11210 if !self.buffer.read(cx).is_singleton() {
11211 return;
11212 }
11213
11214 let mut fold_ranges = Vec::new();
11215 let snapshot = self.buffer.read(cx).snapshot(cx);
11216
11217 for row in 0..snapshot.max_row().0 {
11218 if let Some(foldable_range) =
11219 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
11220 {
11221 fold_ranges.push(foldable_range);
11222 }
11223 }
11224
11225 self.fold_creases(fold_ranges, true, cx);
11226 }
11227
11228 pub fn fold_function_bodies(
11229 &mut self,
11230 _: &actions::FoldFunctionBodies,
11231 cx: &mut ViewContext<Self>,
11232 ) {
11233 let snapshot = self.buffer.read(cx).snapshot(cx);
11234 let Some((_, _, buffer)) = snapshot.as_singleton() else {
11235 return;
11236 };
11237 let creases = buffer
11238 .function_body_fold_ranges(0..buffer.len())
11239 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11240 .collect();
11241
11242 self.fold_creases(creases, true, cx);
11243 }
11244
11245 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
11246 let mut to_fold = Vec::new();
11247 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11248 let selections = self.selections.all_adjusted(cx);
11249
11250 for selection in selections {
11251 let range = selection.range().sorted();
11252 let buffer_start_row = range.start.row;
11253
11254 if range.start.row != range.end.row {
11255 let mut found = false;
11256 for row in range.start.row..=range.end.row {
11257 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11258 found = true;
11259 to_fold.push(crease);
11260 }
11261 }
11262 if found {
11263 continue;
11264 }
11265 }
11266
11267 for row in (0..=range.start.row).rev() {
11268 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11269 if crease.range().end.row >= buffer_start_row {
11270 to_fold.push(crease);
11271 } else {
11272 break;
11273 }
11274 }
11275 }
11276 }
11277
11278 self.fold_creases(to_fold, true, cx);
11279 }
11280
11281 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
11282 let buffer_row = fold_at.buffer_row;
11283 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11284
11285 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11286 let autoscroll = self
11287 .selections
11288 .all::<Point>(cx)
11289 .iter()
11290 .any(|selection| crease.range().overlaps(&selection.range()));
11291
11292 self.fold_creases(vec![crease], autoscroll, cx);
11293 }
11294 }
11295
11296 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
11297 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11298 let buffer = &display_map.buffer_snapshot;
11299 let selections = self.selections.all::<Point>(cx);
11300 let ranges = selections
11301 .iter()
11302 .map(|s| {
11303 let range = s.display_range(&display_map).sorted();
11304 let mut start = range.start.to_point(&display_map);
11305 let mut end = range.end.to_point(&display_map);
11306 start.column = 0;
11307 end.column = buffer.line_len(MultiBufferRow(end.row));
11308 start..end
11309 })
11310 .collect::<Vec<_>>();
11311
11312 self.unfold_ranges(&ranges, true, true, cx);
11313 }
11314
11315 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11316 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11317 let selections = self.selections.all::<Point>(cx);
11318 let ranges = selections
11319 .iter()
11320 .map(|s| {
11321 let mut range = s.display_range(&display_map).sorted();
11322 *range.start.column_mut() = 0;
11323 *range.end.column_mut() = display_map.line_len(range.end.row());
11324 let start = range.start.to_point(&display_map);
11325 let end = range.end.to_point(&display_map);
11326 start..end
11327 })
11328 .collect::<Vec<_>>();
11329
11330 self.unfold_ranges(&ranges, true, true, cx);
11331 }
11332
11333 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11334 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11335
11336 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11337 ..Point::new(
11338 unfold_at.buffer_row.0,
11339 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11340 );
11341
11342 let autoscroll = self
11343 .selections
11344 .all::<Point>(cx)
11345 .iter()
11346 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11347
11348 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11349 }
11350
11351 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11352 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11353 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11354 }
11355
11356 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11357 let selections = self.selections.all::<Point>(cx);
11358 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11359 let line_mode = self.selections.line_mode;
11360 let ranges = selections
11361 .into_iter()
11362 .map(|s| {
11363 if line_mode {
11364 let start = Point::new(s.start.row, 0);
11365 let end = Point::new(
11366 s.end.row,
11367 display_map
11368 .buffer_snapshot
11369 .line_len(MultiBufferRow(s.end.row)),
11370 );
11371 Crease::simple(start..end, display_map.fold_placeholder.clone())
11372 } else {
11373 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11374 }
11375 })
11376 .collect::<Vec<_>>();
11377 self.fold_creases(ranges, true, cx);
11378 }
11379
11380 pub fn fold_creases<T: ToOffset + Clone>(
11381 &mut self,
11382 creases: Vec<Crease<T>>,
11383 auto_scroll: bool,
11384 cx: &mut ViewContext<Self>,
11385 ) {
11386 if creases.is_empty() {
11387 return;
11388 }
11389
11390 let mut buffers_affected = HashSet::default();
11391 let multi_buffer = self.buffer().read(cx);
11392 for crease in &creases {
11393 if let Some((_, buffer, _)) =
11394 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11395 {
11396 buffers_affected.insert(buffer.read(cx).remote_id());
11397 };
11398 }
11399
11400 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11401
11402 if auto_scroll {
11403 self.request_autoscroll(Autoscroll::fit(), cx);
11404 }
11405
11406 for buffer_id in buffers_affected {
11407 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11408 }
11409
11410 cx.notify();
11411
11412 if let Some(active_diagnostics) = self.active_diagnostics.take() {
11413 // Clear diagnostics block when folding a range that contains it.
11414 let snapshot = self.snapshot(cx);
11415 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11416 drop(snapshot);
11417 self.active_diagnostics = Some(active_diagnostics);
11418 self.dismiss_diagnostics(cx);
11419 } else {
11420 self.active_diagnostics = Some(active_diagnostics);
11421 }
11422 }
11423
11424 self.scrollbar_marker_state.dirty = true;
11425 }
11426
11427 /// Removes any folds whose ranges intersect any of the given ranges.
11428 pub fn unfold_ranges<T: ToOffset + Clone>(
11429 &mut self,
11430 ranges: &[Range<T>],
11431 inclusive: bool,
11432 auto_scroll: bool,
11433 cx: &mut ViewContext<Self>,
11434 ) {
11435 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11436 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11437 });
11438 }
11439
11440 /// Removes any folds with the given ranges.
11441 pub fn remove_folds_with_type<T: ToOffset + Clone>(
11442 &mut self,
11443 ranges: &[Range<T>],
11444 type_id: TypeId,
11445 auto_scroll: bool,
11446 cx: &mut ViewContext<Self>,
11447 ) {
11448 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11449 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11450 });
11451 }
11452
11453 fn remove_folds_with<T: ToOffset + Clone>(
11454 &mut self,
11455 ranges: &[Range<T>],
11456 auto_scroll: bool,
11457 cx: &mut ViewContext<Self>,
11458 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11459 ) {
11460 if ranges.is_empty() {
11461 return;
11462 }
11463
11464 let mut buffers_affected = HashSet::default();
11465 let multi_buffer = self.buffer().read(cx);
11466 for range in ranges {
11467 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11468 buffers_affected.insert(buffer.read(cx).remote_id());
11469 };
11470 }
11471
11472 self.display_map.update(cx, update);
11473
11474 if auto_scroll {
11475 self.request_autoscroll(Autoscroll::fit(), cx);
11476 }
11477
11478 for buffer_id in buffers_affected {
11479 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11480 }
11481
11482 cx.notify();
11483 self.scrollbar_marker_state.dirty = true;
11484 self.active_indent_guides_state.dirty = true;
11485 }
11486
11487 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11488 self.display_map.read(cx).fold_placeholder.clone()
11489 }
11490
11491 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11492 if hovered != self.gutter_hovered {
11493 self.gutter_hovered = hovered;
11494 cx.notify();
11495 }
11496 }
11497
11498 pub fn insert_blocks(
11499 &mut self,
11500 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11501 autoscroll: Option<Autoscroll>,
11502 cx: &mut ViewContext<Self>,
11503 ) -> Vec<CustomBlockId> {
11504 let blocks = self
11505 .display_map
11506 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11507 if let Some(autoscroll) = autoscroll {
11508 self.request_autoscroll(autoscroll, cx);
11509 }
11510 cx.notify();
11511 blocks
11512 }
11513
11514 pub fn resize_blocks(
11515 &mut self,
11516 heights: HashMap<CustomBlockId, u32>,
11517 autoscroll: Option<Autoscroll>,
11518 cx: &mut ViewContext<Self>,
11519 ) {
11520 self.display_map
11521 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11522 if let Some(autoscroll) = autoscroll {
11523 self.request_autoscroll(autoscroll, cx);
11524 }
11525 cx.notify();
11526 }
11527
11528 pub fn replace_blocks(
11529 &mut self,
11530 renderers: HashMap<CustomBlockId, RenderBlock>,
11531 autoscroll: Option<Autoscroll>,
11532 cx: &mut ViewContext<Self>,
11533 ) {
11534 self.display_map
11535 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11536 if let Some(autoscroll) = autoscroll {
11537 self.request_autoscroll(autoscroll, cx);
11538 }
11539 cx.notify();
11540 }
11541
11542 pub fn remove_blocks(
11543 &mut self,
11544 block_ids: HashSet<CustomBlockId>,
11545 autoscroll: Option<Autoscroll>,
11546 cx: &mut ViewContext<Self>,
11547 ) {
11548 self.display_map.update(cx, |display_map, cx| {
11549 display_map.remove_blocks(block_ids, cx)
11550 });
11551 if let Some(autoscroll) = autoscroll {
11552 self.request_autoscroll(autoscroll, cx);
11553 }
11554 cx.notify();
11555 }
11556
11557 pub fn row_for_block(
11558 &self,
11559 block_id: CustomBlockId,
11560 cx: &mut ViewContext<Self>,
11561 ) -> Option<DisplayRow> {
11562 self.display_map
11563 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11564 }
11565
11566 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11567 self.focused_block = Some(focused_block);
11568 }
11569
11570 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11571 self.focused_block.take()
11572 }
11573
11574 pub fn insert_creases(
11575 &mut self,
11576 creases: impl IntoIterator<Item = Crease<Anchor>>,
11577 cx: &mut ViewContext<Self>,
11578 ) -> Vec<CreaseId> {
11579 self.display_map
11580 .update(cx, |map, cx| map.insert_creases(creases, cx))
11581 }
11582
11583 pub fn remove_creases(
11584 &mut self,
11585 ids: impl IntoIterator<Item = CreaseId>,
11586 cx: &mut ViewContext<Self>,
11587 ) {
11588 self.display_map
11589 .update(cx, |map, cx| map.remove_creases(ids, cx));
11590 }
11591
11592 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11593 self.display_map
11594 .update(cx, |map, cx| map.snapshot(cx))
11595 .longest_row()
11596 }
11597
11598 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11599 self.display_map
11600 .update(cx, |map, cx| map.snapshot(cx))
11601 .max_point()
11602 }
11603
11604 pub fn text(&self, cx: &AppContext) -> String {
11605 self.buffer.read(cx).read(cx).text()
11606 }
11607
11608 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11609 let text = self.text(cx);
11610 let text = text.trim();
11611
11612 if text.is_empty() {
11613 return None;
11614 }
11615
11616 Some(text.to_string())
11617 }
11618
11619 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11620 self.transact(cx, |this, cx| {
11621 this.buffer
11622 .read(cx)
11623 .as_singleton()
11624 .expect("you can only call set_text on editors for singleton buffers")
11625 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11626 });
11627 }
11628
11629 pub fn display_text(&self, cx: &mut AppContext) -> String {
11630 self.display_map
11631 .update(cx, |map, cx| map.snapshot(cx))
11632 .text()
11633 }
11634
11635 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11636 let mut wrap_guides = smallvec::smallvec![];
11637
11638 if self.show_wrap_guides == Some(false) {
11639 return wrap_guides;
11640 }
11641
11642 let settings = self.buffer.read(cx).settings_at(0, cx);
11643 if settings.show_wrap_guides {
11644 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11645 wrap_guides.push((soft_wrap as usize, true));
11646 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11647 wrap_guides.push((soft_wrap as usize, true));
11648 }
11649 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11650 }
11651
11652 wrap_guides
11653 }
11654
11655 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11656 let settings = self.buffer.read(cx).settings_at(0, cx);
11657 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11658 match mode {
11659 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11660 SoftWrap::None
11661 }
11662 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11663 language_settings::SoftWrap::PreferredLineLength => {
11664 SoftWrap::Column(settings.preferred_line_length)
11665 }
11666 language_settings::SoftWrap::Bounded => {
11667 SoftWrap::Bounded(settings.preferred_line_length)
11668 }
11669 }
11670 }
11671
11672 pub fn set_soft_wrap_mode(
11673 &mut self,
11674 mode: language_settings::SoftWrap,
11675 cx: &mut ViewContext<Self>,
11676 ) {
11677 self.soft_wrap_mode_override = Some(mode);
11678 cx.notify();
11679 }
11680
11681 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11682 self.text_style_refinement = Some(style);
11683 }
11684
11685 /// called by the Element so we know what style we were most recently rendered with.
11686 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11687 let rem_size = cx.rem_size();
11688 self.display_map.update(cx, |map, cx| {
11689 map.set_font(
11690 style.text.font(),
11691 style.text.font_size.to_pixels(rem_size),
11692 cx,
11693 )
11694 });
11695 self.style = Some(style);
11696 }
11697
11698 pub fn style(&self) -> Option<&EditorStyle> {
11699 self.style.as_ref()
11700 }
11701
11702 // Called by the element. This method is not designed to be called outside of the editor
11703 // element's layout code because it does not notify when rewrapping is computed synchronously.
11704 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11705 self.display_map
11706 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11707 }
11708
11709 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11710 if self.soft_wrap_mode_override.is_some() {
11711 self.soft_wrap_mode_override.take();
11712 } else {
11713 let soft_wrap = match self.soft_wrap_mode(cx) {
11714 SoftWrap::GitDiff => return,
11715 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11716 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11717 language_settings::SoftWrap::None
11718 }
11719 };
11720 self.soft_wrap_mode_override = Some(soft_wrap);
11721 }
11722 cx.notify();
11723 }
11724
11725 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11726 let Some(workspace) = self.workspace() else {
11727 return;
11728 };
11729 let fs = workspace.read(cx).app_state().fs.clone();
11730 let current_show = TabBarSettings::get_global(cx).show;
11731 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11732 setting.show = Some(!current_show);
11733 });
11734 }
11735
11736 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11737 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11738 self.buffer
11739 .read(cx)
11740 .settings_at(0, cx)
11741 .indent_guides
11742 .enabled
11743 });
11744 self.show_indent_guides = Some(!currently_enabled);
11745 cx.notify();
11746 }
11747
11748 fn should_show_indent_guides(&self) -> Option<bool> {
11749 self.show_indent_guides
11750 }
11751
11752 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11753 let mut editor_settings = EditorSettings::get_global(cx).clone();
11754 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11755 EditorSettings::override_global(editor_settings, cx);
11756 }
11757
11758 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11759 self.use_relative_line_numbers
11760 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11761 }
11762
11763 pub fn toggle_relative_line_numbers(
11764 &mut self,
11765 _: &ToggleRelativeLineNumbers,
11766 cx: &mut ViewContext<Self>,
11767 ) {
11768 let is_relative = self.should_use_relative_line_numbers(cx);
11769 self.set_relative_line_number(Some(!is_relative), cx)
11770 }
11771
11772 pub fn set_relative_line_number(
11773 &mut self,
11774 is_relative: Option<bool>,
11775 cx: &mut ViewContext<Self>,
11776 ) {
11777 self.use_relative_line_numbers = is_relative;
11778 cx.notify();
11779 }
11780
11781 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11782 self.show_gutter = show_gutter;
11783 cx.notify();
11784 }
11785
11786 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11787 self.show_line_numbers = Some(show_line_numbers);
11788 cx.notify();
11789 }
11790
11791 pub fn set_show_git_diff_gutter(
11792 &mut self,
11793 show_git_diff_gutter: bool,
11794 cx: &mut ViewContext<Self>,
11795 ) {
11796 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11797 cx.notify();
11798 }
11799
11800 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11801 self.show_code_actions = Some(show_code_actions);
11802 cx.notify();
11803 }
11804
11805 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11806 self.show_runnables = Some(show_runnables);
11807 cx.notify();
11808 }
11809
11810 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11811 if self.display_map.read(cx).masked != masked {
11812 self.display_map.update(cx, |map, _| map.masked = masked);
11813 }
11814 cx.notify()
11815 }
11816
11817 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11818 self.show_wrap_guides = Some(show_wrap_guides);
11819 cx.notify();
11820 }
11821
11822 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11823 self.show_indent_guides = Some(show_indent_guides);
11824 cx.notify();
11825 }
11826
11827 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11828 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11829 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11830 if let Some(dir) = file.abs_path(cx).parent() {
11831 return Some(dir.to_owned());
11832 }
11833 }
11834
11835 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11836 return Some(project_path.path.to_path_buf());
11837 }
11838 }
11839
11840 None
11841 }
11842
11843 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11844 self.active_excerpt(cx)?
11845 .1
11846 .read(cx)
11847 .file()
11848 .and_then(|f| f.as_local())
11849 }
11850
11851 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11852 if let Some(target) = self.target_file(cx) {
11853 cx.reveal_path(&target.abs_path(cx));
11854 }
11855 }
11856
11857 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11858 if let Some(file) = self.target_file(cx) {
11859 if let Some(path) = file.abs_path(cx).to_str() {
11860 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11861 }
11862 }
11863 }
11864
11865 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11866 if let Some(file) = self.target_file(cx) {
11867 if let Some(path) = file.path().to_str() {
11868 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11869 }
11870 }
11871 }
11872
11873 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11874 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11875
11876 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11877 self.start_git_blame(true, cx);
11878 }
11879
11880 cx.notify();
11881 }
11882
11883 pub fn toggle_git_blame_inline(
11884 &mut self,
11885 _: &ToggleGitBlameInline,
11886 cx: &mut ViewContext<Self>,
11887 ) {
11888 self.toggle_git_blame_inline_internal(true, cx);
11889 cx.notify();
11890 }
11891
11892 pub fn git_blame_inline_enabled(&self) -> bool {
11893 self.git_blame_inline_enabled
11894 }
11895
11896 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11897 self.show_selection_menu = self
11898 .show_selection_menu
11899 .map(|show_selections_menu| !show_selections_menu)
11900 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11901
11902 cx.notify();
11903 }
11904
11905 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11906 self.show_selection_menu
11907 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11908 }
11909
11910 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11911 if let Some(project) = self.project.as_ref() {
11912 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11913 return;
11914 };
11915
11916 if buffer.read(cx).file().is_none() {
11917 return;
11918 }
11919
11920 let focused = self.focus_handle(cx).contains_focused(cx);
11921
11922 let project = project.clone();
11923 let blame =
11924 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11925 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11926 self.blame = Some(blame);
11927 }
11928 }
11929
11930 fn toggle_git_blame_inline_internal(
11931 &mut self,
11932 user_triggered: bool,
11933 cx: &mut ViewContext<Self>,
11934 ) {
11935 if self.git_blame_inline_enabled {
11936 self.git_blame_inline_enabled = false;
11937 self.show_git_blame_inline = false;
11938 self.show_git_blame_inline_delay_task.take();
11939 } else {
11940 self.git_blame_inline_enabled = true;
11941 self.start_git_blame_inline(user_triggered, cx);
11942 }
11943
11944 cx.notify();
11945 }
11946
11947 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11948 self.start_git_blame(user_triggered, cx);
11949
11950 if ProjectSettings::get_global(cx)
11951 .git
11952 .inline_blame_delay()
11953 .is_some()
11954 {
11955 self.start_inline_blame_timer(cx);
11956 } else {
11957 self.show_git_blame_inline = true
11958 }
11959 }
11960
11961 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11962 self.blame.as_ref()
11963 }
11964
11965 pub fn show_git_blame_gutter(&self) -> bool {
11966 self.show_git_blame_gutter
11967 }
11968
11969 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11970 self.show_git_blame_gutter && self.has_blame_entries(cx)
11971 }
11972
11973 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11974 self.show_git_blame_inline
11975 && self.focus_handle.is_focused(cx)
11976 && !self.newest_selection_head_on_empty_line(cx)
11977 && self.has_blame_entries(cx)
11978 }
11979
11980 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11981 self.blame()
11982 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11983 }
11984
11985 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11986 let cursor_anchor = self.selections.newest_anchor().head();
11987
11988 let snapshot = self.buffer.read(cx).snapshot(cx);
11989 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11990
11991 snapshot.line_len(buffer_row) == 0
11992 }
11993
11994 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11995 let buffer_and_selection = maybe!({
11996 let selection = self.selections.newest::<Point>(cx);
11997 let selection_range = selection.range();
11998
11999 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12000 (buffer, selection_range.start.row..selection_range.end.row)
12001 } else {
12002 let buffer_ranges = self
12003 .buffer()
12004 .read(cx)
12005 .range_to_buffer_ranges(selection_range, cx);
12006
12007 let (buffer, range, _) = if selection.reversed {
12008 buffer_ranges.first()
12009 } else {
12010 buffer_ranges.last()
12011 }?;
12012
12013 let snapshot = buffer.read(cx).snapshot();
12014 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
12015 ..text::ToPoint::to_point(&range.end, &snapshot).row;
12016 (buffer.clone(), selection)
12017 };
12018
12019 Some((buffer, selection))
12020 });
12021
12022 let Some((buffer, selection)) = buffer_and_selection else {
12023 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12024 };
12025
12026 let Some(project) = self.project.as_ref() else {
12027 return Task::ready(Err(anyhow!("editor does not have project")));
12028 };
12029
12030 project.update(cx, |project, cx| {
12031 project.get_permalink_to_line(&buffer, selection, cx)
12032 })
12033 }
12034
12035 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
12036 let permalink_task = self.get_permalink_to_line(cx);
12037 let workspace = self.workspace();
12038
12039 cx.spawn(|_, mut cx| async move {
12040 match permalink_task.await {
12041 Ok(permalink) => {
12042 cx.update(|cx| {
12043 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12044 })
12045 .ok();
12046 }
12047 Err(err) => {
12048 let message = format!("Failed to copy permalink: {err}");
12049
12050 Err::<(), anyhow::Error>(err).log_err();
12051
12052 if let Some(workspace) = workspace {
12053 workspace
12054 .update(&mut cx, |workspace, cx| {
12055 struct CopyPermalinkToLine;
12056
12057 workspace.show_toast(
12058 Toast::new(
12059 NotificationId::unique::<CopyPermalinkToLine>(),
12060 message,
12061 ),
12062 cx,
12063 )
12064 })
12065 .ok();
12066 }
12067 }
12068 }
12069 })
12070 .detach();
12071 }
12072
12073 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
12074 let selection = self.selections.newest::<Point>(cx).start.row + 1;
12075 if let Some(file) = self.target_file(cx) {
12076 if let Some(path) = file.path().to_str() {
12077 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
12078 }
12079 }
12080 }
12081
12082 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
12083 let permalink_task = self.get_permalink_to_line(cx);
12084 let workspace = self.workspace();
12085
12086 cx.spawn(|_, mut cx| async move {
12087 match permalink_task.await {
12088 Ok(permalink) => {
12089 cx.update(|cx| {
12090 cx.open_url(permalink.as_ref());
12091 })
12092 .ok();
12093 }
12094 Err(err) => {
12095 let message = format!("Failed to open permalink: {err}");
12096
12097 Err::<(), anyhow::Error>(err).log_err();
12098
12099 if let Some(workspace) = workspace {
12100 workspace
12101 .update(&mut cx, |workspace, cx| {
12102 struct OpenPermalinkToLine;
12103
12104 workspace.show_toast(
12105 Toast::new(
12106 NotificationId::unique::<OpenPermalinkToLine>(),
12107 message,
12108 ),
12109 cx,
12110 )
12111 })
12112 .ok();
12113 }
12114 }
12115 }
12116 })
12117 .detach();
12118 }
12119
12120 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
12121 self.insert_uuid(UuidVersion::V4, cx);
12122 }
12123
12124 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
12125 self.insert_uuid(UuidVersion::V7, cx);
12126 }
12127
12128 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
12129 self.transact(cx, |this, cx| {
12130 let edits = this
12131 .selections
12132 .all::<Point>(cx)
12133 .into_iter()
12134 .map(|selection| {
12135 let uuid = match version {
12136 UuidVersion::V4 => uuid::Uuid::new_v4(),
12137 UuidVersion::V7 => uuid::Uuid::now_v7(),
12138 };
12139
12140 (selection.range(), uuid.to_string())
12141 });
12142 this.edit(edits, cx);
12143 this.refresh_inline_completion(true, false, cx);
12144 });
12145 }
12146
12147 /// Adds a row highlight for the given range. If a row has multiple highlights, the
12148 /// last highlight added will be used.
12149 ///
12150 /// If the range ends at the beginning of a line, then that line will not be highlighted.
12151 pub fn highlight_rows<T: 'static>(
12152 &mut self,
12153 range: Range<Anchor>,
12154 color: Hsla,
12155 should_autoscroll: bool,
12156 cx: &mut ViewContext<Self>,
12157 ) {
12158 let snapshot = self.buffer().read(cx).snapshot(cx);
12159 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12160 let ix = row_highlights.binary_search_by(|highlight| {
12161 Ordering::Equal
12162 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
12163 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
12164 });
12165
12166 if let Err(mut ix) = ix {
12167 let index = post_inc(&mut self.highlight_order);
12168
12169 // If this range intersects with the preceding highlight, then merge it with
12170 // the preceding highlight. Otherwise insert a new highlight.
12171 let mut merged = false;
12172 if ix > 0 {
12173 let prev_highlight = &mut row_highlights[ix - 1];
12174 if prev_highlight
12175 .range
12176 .end
12177 .cmp(&range.start, &snapshot)
12178 .is_ge()
12179 {
12180 ix -= 1;
12181 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12182 prev_highlight.range.end = range.end;
12183 }
12184 merged = true;
12185 prev_highlight.index = index;
12186 prev_highlight.color = color;
12187 prev_highlight.should_autoscroll = should_autoscroll;
12188 }
12189 }
12190
12191 if !merged {
12192 row_highlights.insert(
12193 ix,
12194 RowHighlight {
12195 range: range.clone(),
12196 index,
12197 color,
12198 should_autoscroll,
12199 },
12200 );
12201 }
12202
12203 // If any of the following highlights intersect with this one, merge them.
12204 while let Some(next_highlight) = row_highlights.get(ix + 1) {
12205 let highlight = &row_highlights[ix];
12206 if next_highlight
12207 .range
12208 .start
12209 .cmp(&highlight.range.end, &snapshot)
12210 .is_le()
12211 {
12212 if next_highlight
12213 .range
12214 .end
12215 .cmp(&highlight.range.end, &snapshot)
12216 .is_gt()
12217 {
12218 row_highlights[ix].range.end = next_highlight.range.end;
12219 }
12220 row_highlights.remove(ix + 1);
12221 } else {
12222 break;
12223 }
12224 }
12225 }
12226 }
12227
12228 /// Remove any highlighted row ranges of the given type that intersect the
12229 /// given ranges.
12230 pub fn remove_highlighted_rows<T: 'static>(
12231 &mut self,
12232 ranges_to_remove: Vec<Range<Anchor>>,
12233 cx: &mut ViewContext<Self>,
12234 ) {
12235 let snapshot = self.buffer().read(cx).snapshot(cx);
12236 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12237 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12238 row_highlights.retain(|highlight| {
12239 while let Some(range_to_remove) = ranges_to_remove.peek() {
12240 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12241 Ordering::Less | Ordering::Equal => {
12242 ranges_to_remove.next();
12243 }
12244 Ordering::Greater => {
12245 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12246 Ordering::Less | Ordering::Equal => {
12247 return false;
12248 }
12249 Ordering::Greater => break,
12250 }
12251 }
12252 }
12253 }
12254
12255 true
12256 })
12257 }
12258
12259 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12260 pub fn clear_row_highlights<T: 'static>(&mut self) {
12261 self.highlighted_rows.remove(&TypeId::of::<T>());
12262 }
12263
12264 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12265 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12266 self.highlighted_rows
12267 .get(&TypeId::of::<T>())
12268 .map_or(&[] as &[_], |vec| vec.as_slice())
12269 .iter()
12270 .map(|highlight| (highlight.range.clone(), highlight.color))
12271 }
12272
12273 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12274 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
12275 /// Allows to ignore certain kinds of highlights.
12276 pub fn highlighted_display_rows(
12277 &mut self,
12278 cx: &mut WindowContext,
12279 ) -> BTreeMap<DisplayRow, Hsla> {
12280 let snapshot = self.snapshot(cx);
12281 let mut used_highlight_orders = HashMap::default();
12282 self.highlighted_rows
12283 .iter()
12284 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12285 .fold(
12286 BTreeMap::<DisplayRow, Hsla>::new(),
12287 |mut unique_rows, highlight| {
12288 let start = highlight.range.start.to_display_point(&snapshot);
12289 let end = highlight.range.end.to_display_point(&snapshot);
12290 let start_row = start.row().0;
12291 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12292 && end.column() == 0
12293 {
12294 end.row().0.saturating_sub(1)
12295 } else {
12296 end.row().0
12297 };
12298 for row in start_row..=end_row {
12299 let used_index =
12300 used_highlight_orders.entry(row).or_insert(highlight.index);
12301 if highlight.index >= *used_index {
12302 *used_index = highlight.index;
12303 unique_rows.insert(DisplayRow(row), highlight.color);
12304 }
12305 }
12306 unique_rows
12307 },
12308 )
12309 }
12310
12311 pub fn highlighted_display_row_for_autoscroll(
12312 &self,
12313 snapshot: &DisplaySnapshot,
12314 ) -> Option<DisplayRow> {
12315 self.highlighted_rows
12316 .values()
12317 .flat_map(|highlighted_rows| highlighted_rows.iter())
12318 .filter_map(|highlight| {
12319 if highlight.should_autoscroll {
12320 Some(highlight.range.start.to_display_point(snapshot).row())
12321 } else {
12322 None
12323 }
12324 })
12325 .min()
12326 }
12327
12328 pub fn set_search_within_ranges(
12329 &mut self,
12330 ranges: &[Range<Anchor>],
12331 cx: &mut ViewContext<Self>,
12332 ) {
12333 self.highlight_background::<SearchWithinRange>(
12334 ranges,
12335 |colors| colors.editor_document_highlight_read_background,
12336 cx,
12337 )
12338 }
12339
12340 pub fn set_breadcrumb_header(&mut self, new_header: String) {
12341 self.breadcrumb_header = Some(new_header);
12342 }
12343
12344 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12345 self.clear_background_highlights::<SearchWithinRange>(cx);
12346 }
12347
12348 pub fn highlight_background<T: 'static>(
12349 &mut self,
12350 ranges: &[Range<Anchor>],
12351 color_fetcher: fn(&ThemeColors) -> Hsla,
12352 cx: &mut ViewContext<Self>,
12353 ) {
12354 self.background_highlights
12355 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12356 self.scrollbar_marker_state.dirty = true;
12357 cx.notify();
12358 }
12359
12360 pub fn clear_background_highlights<T: 'static>(
12361 &mut self,
12362 cx: &mut ViewContext<Self>,
12363 ) -> Option<BackgroundHighlight> {
12364 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12365 if !text_highlights.1.is_empty() {
12366 self.scrollbar_marker_state.dirty = true;
12367 cx.notify();
12368 }
12369 Some(text_highlights)
12370 }
12371
12372 pub fn highlight_gutter<T: 'static>(
12373 &mut self,
12374 ranges: &[Range<Anchor>],
12375 color_fetcher: fn(&AppContext) -> Hsla,
12376 cx: &mut ViewContext<Self>,
12377 ) {
12378 self.gutter_highlights
12379 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12380 cx.notify();
12381 }
12382
12383 pub fn clear_gutter_highlights<T: 'static>(
12384 &mut self,
12385 cx: &mut ViewContext<Self>,
12386 ) -> Option<GutterHighlight> {
12387 cx.notify();
12388 self.gutter_highlights.remove(&TypeId::of::<T>())
12389 }
12390
12391 #[cfg(feature = "test-support")]
12392 pub fn all_text_background_highlights(
12393 &mut self,
12394 cx: &mut ViewContext<Self>,
12395 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12396 let snapshot = self.snapshot(cx);
12397 let buffer = &snapshot.buffer_snapshot;
12398 let start = buffer.anchor_before(0);
12399 let end = buffer.anchor_after(buffer.len());
12400 let theme = cx.theme().colors();
12401 self.background_highlights_in_range(start..end, &snapshot, theme)
12402 }
12403
12404 #[cfg(feature = "test-support")]
12405 pub fn search_background_highlights(
12406 &mut self,
12407 cx: &mut ViewContext<Self>,
12408 ) -> Vec<Range<Point>> {
12409 let snapshot = self.buffer().read(cx).snapshot(cx);
12410
12411 let highlights = self
12412 .background_highlights
12413 .get(&TypeId::of::<items::BufferSearchHighlights>());
12414
12415 if let Some((_color, ranges)) = highlights {
12416 ranges
12417 .iter()
12418 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12419 .collect_vec()
12420 } else {
12421 vec![]
12422 }
12423 }
12424
12425 fn document_highlights_for_position<'a>(
12426 &'a self,
12427 position: Anchor,
12428 buffer: &'a MultiBufferSnapshot,
12429 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12430 let read_highlights = self
12431 .background_highlights
12432 .get(&TypeId::of::<DocumentHighlightRead>())
12433 .map(|h| &h.1);
12434 let write_highlights = self
12435 .background_highlights
12436 .get(&TypeId::of::<DocumentHighlightWrite>())
12437 .map(|h| &h.1);
12438 let left_position = position.bias_left(buffer);
12439 let right_position = position.bias_right(buffer);
12440 read_highlights
12441 .into_iter()
12442 .chain(write_highlights)
12443 .flat_map(move |ranges| {
12444 let start_ix = match ranges.binary_search_by(|probe| {
12445 let cmp = probe.end.cmp(&left_position, buffer);
12446 if cmp.is_ge() {
12447 Ordering::Greater
12448 } else {
12449 Ordering::Less
12450 }
12451 }) {
12452 Ok(i) | Err(i) => i,
12453 };
12454
12455 ranges[start_ix..]
12456 .iter()
12457 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12458 })
12459 }
12460
12461 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12462 self.background_highlights
12463 .get(&TypeId::of::<T>())
12464 .map_or(false, |(_, highlights)| !highlights.is_empty())
12465 }
12466
12467 pub fn background_highlights_in_range(
12468 &self,
12469 search_range: Range<Anchor>,
12470 display_snapshot: &DisplaySnapshot,
12471 theme: &ThemeColors,
12472 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12473 let mut results = Vec::new();
12474 for (color_fetcher, ranges) in self.background_highlights.values() {
12475 let color = color_fetcher(theme);
12476 let start_ix = match ranges.binary_search_by(|probe| {
12477 let cmp = probe
12478 .end
12479 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12480 if cmp.is_gt() {
12481 Ordering::Greater
12482 } else {
12483 Ordering::Less
12484 }
12485 }) {
12486 Ok(i) | Err(i) => i,
12487 };
12488 for range in &ranges[start_ix..] {
12489 if range
12490 .start
12491 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12492 .is_ge()
12493 {
12494 break;
12495 }
12496
12497 let start = range.start.to_display_point(display_snapshot);
12498 let end = range.end.to_display_point(display_snapshot);
12499 results.push((start..end, color))
12500 }
12501 }
12502 results
12503 }
12504
12505 pub fn background_highlight_row_ranges<T: 'static>(
12506 &self,
12507 search_range: Range<Anchor>,
12508 display_snapshot: &DisplaySnapshot,
12509 count: usize,
12510 ) -> Vec<RangeInclusive<DisplayPoint>> {
12511 let mut results = Vec::new();
12512 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12513 return vec![];
12514 };
12515
12516 let start_ix = match ranges.binary_search_by(|probe| {
12517 let cmp = probe
12518 .end
12519 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12520 if cmp.is_gt() {
12521 Ordering::Greater
12522 } else {
12523 Ordering::Less
12524 }
12525 }) {
12526 Ok(i) | Err(i) => i,
12527 };
12528 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12529 if let (Some(start_display), Some(end_display)) = (start, end) {
12530 results.push(
12531 start_display.to_display_point(display_snapshot)
12532 ..=end_display.to_display_point(display_snapshot),
12533 );
12534 }
12535 };
12536 let mut start_row: Option<Point> = None;
12537 let mut end_row: Option<Point> = None;
12538 if ranges.len() > count {
12539 return Vec::new();
12540 }
12541 for range in &ranges[start_ix..] {
12542 if range
12543 .start
12544 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12545 .is_ge()
12546 {
12547 break;
12548 }
12549 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12550 if let Some(current_row) = &end_row {
12551 if end.row == current_row.row {
12552 continue;
12553 }
12554 }
12555 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12556 if start_row.is_none() {
12557 assert_eq!(end_row, None);
12558 start_row = Some(start);
12559 end_row = Some(end);
12560 continue;
12561 }
12562 if let Some(current_end) = end_row.as_mut() {
12563 if start.row > current_end.row + 1 {
12564 push_region(start_row, end_row);
12565 start_row = Some(start);
12566 end_row = Some(end);
12567 } else {
12568 // Merge two hunks.
12569 *current_end = end;
12570 }
12571 } else {
12572 unreachable!();
12573 }
12574 }
12575 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12576 push_region(start_row, end_row);
12577 results
12578 }
12579
12580 pub fn gutter_highlights_in_range(
12581 &self,
12582 search_range: Range<Anchor>,
12583 display_snapshot: &DisplaySnapshot,
12584 cx: &AppContext,
12585 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12586 let mut results = Vec::new();
12587 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12588 let color = color_fetcher(cx);
12589 let start_ix = match ranges.binary_search_by(|probe| {
12590 let cmp = probe
12591 .end
12592 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12593 if cmp.is_gt() {
12594 Ordering::Greater
12595 } else {
12596 Ordering::Less
12597 }
12598 }) {
12599 Ok(i) | Err(i) => i,
12600 };
12601 for range in &ranges[start_ix..] {
12602 if range
12603 .start
12604 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12605 .is_ge()
12606 {
12607 break;
12608 }
12609
12610 let start = range.start.to_display_point(display_snapshot);
12611 let end = range.end.to_display_point(display_snapshot);
12612 results.push((start..end, color))
12613 }
12614 }
12615 results
12616 }
12617
12618 /// Get the text ranges corresponding to the redaction query
12619 pub fn redacted_ranges(
12620 &self,
12621 search_range: Range<Anchor>,
12622 display_snapshot: &DisplaySnapshot,
12623 cx: &WindowContext,
12624 ) -> Vec<Range<DisplayPoint>> {
12625 display_snapshot
12626 .buffer_snapshot
12627 .redacted_ranges(search_range, |file| {
12628 if let Some(file) = file {
12629 file.is_private()
12630 && EditorSettings::get(
12631 Some(SettingsLocation {
12632 worktree_id: file.worktree_id(cx),
12633 path: file.path().as_ref(),
12634 }),
12635 cx,
12636 )
12637 .redact_private_values
12638 } else {
12639 false
12640 }
12641 })
12642 .map(|range| {
12643 range.start.to_display_point(display_snapshot)
12644 ..range.end.to_display_point(display_snapshot)
12645 })
12646 .collect()
12647 }
12648
12649 pub fn highlight_text<T: 'static>(
12650 &mut self,
12651 ranges: Vec<Range<Anchor>>,
12652 style: HighlightStyle,
12653 cx: &mut ViewContext<Self>,
12654 ) {
12655 self.display_map.update(cx, |map, _| {
12656 map.highlight_text(TypeId::of::<T>(), ranges, style)
12657 });
12658 cx.notify();
12659 }
12660
12661 pub(crate) fn highlight_inlays<T: 'static>(
12662 &mut self,
12663 highlights: Vec<InlayHighlight>,
12664 style: HighlightStyle,
12665 cx: &mut ViewContext<Self>,
12666 ) {
12667 self.display_map.update(cx, |map, _| {
12668 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12669 });
12670 cx.notify();
12671 }
12672
12673 pub fn text_highlights<'a, T: 'static>(
12674 &'a self,
12675 cx: &'a AppContext,
12676 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12677 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12678 }
12679
12680 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12681 let cleared = self
12682 .display_map
12683 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12684 if cleared {
12685 cx.notify();
12686 }
12687 }
12688
12689 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12690 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12691 && self.focus_handle.is_focused(cx)
12692 }
12693
12694 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12695 self.show_cursor_when_unfocused = is_enabled;
12696 cx.notify();
12697 }
12698
12699 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12700 cx.notify();
12701 }
12702
12703 fn on_buffer_event(
12704 &mut self,
12705 multibuffer: Model<MultiBuffer>,
12706 event: &multi_buffer::Event,
12707 cx: &mut ViewContext<Self>,
12708 ) {
12709 match event {
12710 multi_buffer::Event::Edited {
12711 singleton_buffer_edited,
12712 } => {
12713 self.scrollbar_marker_state.dirty = true;
12714 self.active_indent_guides_state.dirty = true;
12715 self.refresh_active_diagnostics(cx);
12716 self.refresh_code_actions(cx);
12717 if self.has_active_inline_completion() {
12718 self.update_visible_inline_completion(cx);
12719 }
12720 cx.emit(EditorEvent::BufferEdited);
12721 cx.emit(SearchEvent::MatchesInvalidated);
12722 if *singleton_buffer_edited {
12723 if let Some(project) = &self.project {
12724 let project = project.read(cx);
12725 #[allow(clippy::mutable_key_type)]
12726 let languages_affected = multibuffer
12727 .read(cx)
12728 .all_buffers()
12729 .into_iter()
12730 .filter_map(|buffer| {
12731 let buffer = buffer.read(cx);
12732 let language = buffer.language()?;
12733 if project.is_local()
12734 && project.language_servers_for_buffer(buffer, cx).count() == 0
12735 {
12736 None
12737 } else {
12738 Some(language)
12739 }
12740 })
12741 .cloned()
12742 .collect::<HashSet<_>>();
12743 if !languages_affected.is_empty() {
12744 self.refresh_inlay_hints(
12745 InlayHintRefreshReason::BufferEdited(languages_affected),
12746 cx,
12747 );
12748 }
12749 }
12750 }
12751
12752 let Some(project) = &self.project else { return };
12753 let (telemetry, is_via_ssh) = {
12754 let project = project.read(cx);
12755 let telemetry = project.client().telemetry().clone();
12756 let is_via_ssh = project.is_via_ssh();
12757 (telemetry, is_via_ssh)
12758 };
12759 refresh_linked_ranges(self, cx);
12760 telemetry.log_edit_event("editor", is_via_ssh);
12761 }
12762 multi_buffer::Event::ExcerptsAdded {
12763 buffer,
12764 predecessor,
12765 excerpts,
12766 } => {
12767 self.tasks_update_task = Some(self.refresh_runnables(cx));
12768 let buffer_id = buffer.read(cx).remote_id();
12769 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12770 if let Some(project) = &self.project {
12771 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12772 }
12773 }
12774 cx.emit(EditorEvent::ExcerptsAdded {
12775 buffer: buffer.clone(),
12776 predecessor: *predecessor,
12777 excerpts: excerpts.clone(),
12778 });
12779 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12780 }
12781 multi_buffer::Event::ExcerptsRemoved { ids } => {
12782 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12783 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12784 }
12785 multi_buffer::Event::ExcerptsEdited { ids } => {
12786 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12787 }
12788 multi_buffer::Event::ExcerptsExpanded { ids } => {
12789 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12790 }
12791 multi_buffer::Event::Reparsed(buffer_id) => {
12792 self.tasks_update_task = Some(self.refresh_runnables(cx));
12793
12794 cx.emit(EditorEvent::Reparsed(*buffer_id));
12795 }
12796 multi_buffer::Event::LanguageChanged(buffer_id) => {
12797 linked_editing_ranges::refresh_linked_ranges(self, cx);
12798 cx.emit(EditorEvent::Reparsed(*buffer_id));
12799 cx.notify();
12800 }
12801 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12802 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12803 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12804 cx.emit(EditorEvent::TitleChanged)
12805 }
12806 // multi_buffer::Event::DiffBaseChanged => {
12807 // self.scrollbar_marker_state.dirty = true;
12808 // cx.emit(EditorEvent::DiffBaseChanged);
12809 // cx.notify();
12810 // }
12811 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12812 multi_buffer::Event::DiagnosticsUpdated => {
12813 self.refresh_active_diagnostics(cx);
12814 self.scrollbar_marker_state.dirty = true;
12815 cx.notify();
12816 }
12817 _ => {}
12818 };
12819 }
12820
12821 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12822 cx.notify();
12823 }
12824
12825 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12826 self.tasks_update_task = Some(self.refresh_runnables(cx));
12827 self.refresh_inline_completion(true, false, cx);
12828 self.refresh_inlay_hints(
12829 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12830 self.selections.newest_anchor().head(),
12831 &self.buffer.read(cx).snapshot(cx),
12832 cx,
12833 )),
12834 cx,
12835 );
12836
12837 let old_cursor_shape = self.cursor_shape;
12838
12839 {
12840 let editor_settings = EditorSettings::get_global(cx);
12841 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12842 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12843 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12844 }
12845
12846 if old_cursor_shape != self.cursor_shape {
12847 cx.emit(EditorEvent::CursorShapeChanged);
12848 }
12849
12850 let project_settings = ProjectSettings::get_global(cx);
12851 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12852
12853 if self.mode == EditorMode::Full {
12854 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12855 if self.git_blame_inline_enabled != inline_blame_enabled {
12856 self.toggle_git_blame_inline_internal(false, cx);
12857 }
12858 }
12859
12860 cx.notify();
12861 }
12862
12863 pub fn set_searchable(&mut self, searchable: bool) {
12864 self.searchable = searchable;
12865 }
12866
12867 pub fn searchable(&self) -> bool {
12868 self.searchable
12869 }
12870
12871 fn open_proposed_changes_editor(
12872 &mut self,
12873 _: &OpenProposedChangesEditor,
12874 cx: &mut ViewContext<Self>,
12875 ) {
12876 let Some(workspace) = self.workspace() else {
12877 cx.propagate();
12878 return;
12879 };
12880
12881 let selections = self.selections.all::<usize>(cx);
12882 let buffer = self.buffer.read(cx);
12883 let mut new_selections_by_buffer = HashMap::default();
12884 for selection in selections {
12885 for (buffer, range, _) in
12886 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12887 {
12888 let mut range = range.to_point(buffer.read(cx));
12889 range.start.column = 0;
12890 range.end.column = buffer.read(cx).line_len(range.end.row);
12891 new_selections_by_buffer
12892 .entry(buffer)
12893 .or_insert(Vec::new())
12894 .push(range)
12895 }
12896 }
12897
12898 let proposed_changes_buffers = new_selections_by_buffer
12899 .into_iter()
12900 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12901 .collect::<Vec<_>>();
12902 let proposed_changes_editor = cx.new_view(|cx| {
12903 ProposedChangesEditor::new(
12904 "Proposed changes",
12905 proposed_changes_buffers,
12906 self.project.clone(),
12907 cx,
12908 )
12909 });
12910
12911 cx.window_context().defer(move |cx| {
12912 workspace.update(cx, |workspace, cx| {
12913 workspace.active_pane().update(cx, |pane, cx| {
12914 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12915 });
12916 });
12917 });
12918 }
12919
12920 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12921 self.open_excerpts_common(None, true, cx)
12922 }
12923
12924 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12925 self.open_excerpts_common(None, false, cx)
12926 }
12927
12928 fn open_excerpts_common(
12929 &mut self,
12930 jump_data: Option<JumpData>,
12931 split: bool,
12932 cx: &mut ViewContext<Self>,
12933 ) {
12934 let Some(workspace) = self.workspace() else {
12935 cx.propagate();
12936 return;
12937 };
12938
12939 if self.buffer.read(cx).is_singleton() {
12940 cx.propagate();
12941 return;
12942 }
12943
12944 let mut new_selections_by_buffer = HashMap::default();
12945 match &jump_data {
12946 Some(jump_data) => {
12947 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12948 if let Some(buffer) = multi_buffer_snapshot
12949 .buffer_id_for_excerpt(jump_data.excerpt_id)
12950 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12951 {
12952 let buffer_snapshot = buffer.read(cx).snapshot();
12953 let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12954 language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12955 } else {
12956 buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12957 };
12958 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12959 new_selections_by_buffer.insert(
12960 buffer,
12961 (
12962 vec![jump_to_offset..jump_to_offset],
12963 Some(jump_data.line_offset_from_top),
12964 ),
12965 );
12966 }
12967 }
12968 None => {
12969 let selections = self.selections.all::<usize>(cx);
12970 let buffer = self.buffer.read(cx);
12971 for selection in selections {
12972 for (mut buffer_handle, mut range, _) in
12973 buffer.range_to_buffer_ranges(selection.range(), cx)
12974 {
12975 // When editing branch buffers, jump to the corresponding location
12976 // in their base buffer.
12977 let buffer = buffer_handle.read(cx);
12978 if let Some(base_buffer) = buffer.base_buffer() {
12979 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12980 buffer_handle = base_buffer;
12981 }
12982
12983 if selection.reversed {
12984 mem::swap(&mut range.start, &mut range.end);
12985 }
12986 new_selections_by_buffer
12987 .entry(buffer_handle)
12988 .or_insert((Vec::new(), None))
12989 .0
12990 .push(range)
12991 }
12992 }
12993 }
12994 }
12995
12996 if new_selections_by_buffer.is_empty() {
12997 return;
12998 }
12999
13000 // We defer the pane interaction because we ourselves are a workspace item
13001 // and activating a new item causes the pane to call a method on us reentrantly,
13002 // which panics if we're on the stack.
13003 cx.window_context().defer(move |cx| {
13004 workspace.update(cx, |workspace, cx| {
13005 let pane = if split {
13006 workspace.adjacent_pane(cx)
13007 } else {
13008 workspace.active_pane().clone()
13009 };
13010
13011 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
13012 let editor = buffer
13013 .read(cx)
13014 .file()
13015 .is_none()
13016 .then(|| {
13017 // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
13018 // so `workspace.open_project_item` will never find them, always opening a new editor.
13019 // Instead, we try to activate the existing editor in the pane first.
13020 let (editor, pane_item_index) =
13021 pane.read(cx).items().enumerate().find_map(|(i, item)| {
13022 let editor = item.downcast::<Editor>()?;
13023 let singleton_buffer =
13024 editor.read(cx).buffer().read(cx).as_singleton()?;
13025 if singleton_buffer == buffer {
13026 Some((editor, i))
13027 } else {
13028 None
13029 }
13030 })?;
13031 pane.update(cx, |pane, cx| {
13032 pane.activate_item(pane_item_index, true, true, cx)
13033 });
13034 Some(editor)
13035 })
13036 .flatten()
13037 .unwrap_or_else(|| {
13038 workspace.open_project_item::<Self>(
13039 pane.clone(),
13040 buffer,
13041 true,
13042 true,
13043 cx,
13044 )
13045 });
13046
13047 editor.update(cx, |editor, cx| {
13048 let autoscroll = match scroll_offset {
13049 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
13050 None => Autoscroll::newest(),
13051 };
13052 let nav_history = editor.nav_history.take();
13053 editor.change_selections(Some(autoscroll), cx, |s| {
13054 s.select_ranges(ranges);
13055 });
13056 editor.nav_history = nav_history;
13057 });
13058 }
13059 })
13060 });
13061 }
13062
13063 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
13064 let snapshot = self.buffer.read(cx).read(cx);
13065 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
13066 Some(
13067 ranges
13068 .iter()
13069 .map(move |range| {
13070 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
13071 })
13072 .collect(),
13073 )
13074 }
13075
13076 fn selection_replacement_ranges(
13077 &self,
13078 range: Range<OffsetUtf16>,
13079 cx: &mut AppContext,
13080 ) -> Vec<Range<OffsetUtf16>> {
13081 let selections = self.selections.all::<OffsetUtf16>(cx);
13082 let newest_selection = selections
13083 .iter()
13084 .max_by_key(|selection| selection.id)
13085 .unwrap();
13086 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
13087 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
13088 let snapshot = self.buffer.read(cx).read(cx);
13089 selections
13090 .into_iter()
13091 .map(|mut selection| {
13092 selection.start.0 =
13093 (selection.start.0 as isize).saturating_add(start_delta) as usize;
13094 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
13095 snapshot.clip_offset_utf16(selection.start, Bias::Left)
13096 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
13097 })
13098 .collect()
13099 }
13100
13101 fn report_editor_event(
13102 &self,
13103 operation: &'static str,
13104 file_extension: Option<String>,
13105 cx: &AppContext,
13106 ) {
13107 if cfg!(any(test, feature = "test-support")) {
13108 return;
13109 }
13110
13111 let Some(project) = &self.project else { return };
13112
13113 // If None, we are in a file without an extension
13114 let file = self
13115 .buffer
13116 .read(cx)
13117 .as_singleton()
13118 .and_then(|b| b.read(cx).file());
13119 let file_extension = file_extension.or(file
13120 .as_ref()
13121 .and_then(|file| Path::new(file.file_name(cx)).extension())
13122 .and_then(|e| e.to_str())
13123 .map(|a| a.to_string()));
13124
13125 let vim_mode = cx
13126 .global::<SettingsStore>()
13127 .raw_user_settings()
13128 .get("vim_mode")
13129 == Some(&serde_json::Value::Bool(true));
13130
13131 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
13132 == language::language_settings::InlineCompletionProvider::Copilot;
13133 let copilot_enabled_for_language = self
13134 .buffer
13135 .read(cx)
13136 .settings_at(0, cx)
13137 .show_inline_completions;
13138
13139 let project = project.read(cx);
13140 let telemetry = project.client().telemetry().clone();
13141 telemetry.report_editor_event(
13142 file_extension,
13143 vim_mode,
13144 operation,
13145 copilot_enabled,
13146 copilot_enabled_for_language,
13147 project.is_via_ssh(),
13148 )
13149 }
13150
13151 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
13152 /// with each line being an array of {text, highlight} objects.
13153 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
13154 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
13155 return;
13156 };
13157
13158 #[derive(Serialize)]
13159 struct Chunk<'a> {
13160 text: String,
13161 highlight: Option<&'a str>,
13162 }
13163
13164 let snapshot = buffer.read(cx).snapshot();
13165 let range = self
13166 .selected_text_range(false, cx)
13167 .and_then(|selection| {
13168 if selection.range.is_empty() {
13169 None
13170 } else {
13171 Some(selection.range)
13172 }
13173 })
13174 .unwrap_or_else(|| 0..snapshot.len());
13175
13176 let chunks = snapshot.chunks(range, true);
13177 let mut lines = Vec::new();
13178 let mut line: VecDeque<Chunk> = VecDeque::new();
13179
13180 let Some(style) = self.style.as_ref() else {
13181 return;
13182 };
13183
13184 for chunk in chunks {
13185 let highlight = chunk
13186 .syntax_highlight_id
13187 .and_then(|id| id.name(&style.syntax));
13188 let mut chunk_lines = chunk.text.split('\n').peekable();
13189 while let Some(text) = chunk_lines.next() {
13190 let mut merged_with_last_token = false;
13191 if let Some(last_token) = line.back_mut() {
13192 if last_token.highlight == highlight {
13193 last_token.text.push_str(text);
13194 merged_with_last_token = true;
13195 }
13196 }
13197
13198 if !merged_with_last_token {
13199 line.push_back(Chunk {
13200 text: text.into(),
13201 highlight,
13202 });
13203 }
13204
13205 if chunk_lines.peek().is_some() {
13206 if line.len() > 1 && line.front().unwrap().text.is_empty() {
13207 line.pop_front();
13208 }
13209 if line.len() > 1 && line.back().unwrap().text.is_empty() {
13210 line.pop_back();
13211 }
13212
13213 lines.push(mem::take(&mut line));
13214 }
13215 }
13216 }
13217
13218 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13219 return;
13220 };
13221 cx.write_to_clipboard(ClipboardItem::new_string(lines));
13222 }
13223
13224 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
13225 self.request_autoscroll(Autoscroll::newest(), cx);
13226 let position = self.selections.newest_display(cx).start;
13227 mouse_context_menu::deploy_context_menu(self, None, position, cx);
13228 }
13229
13230 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13231 &self.inlay_hint_cache
13232 }
13233
13234 pub fn replay_insert_event(
13235 &mut self,
13236 text: &str,
13237 relative_utf16_range: Option<Range<isize>>,
13238 cx: &mut ViewContext<Self>,
13239 ) {
13240 if !self.input_enabled {
13241 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13242 return;
13243 }
13244 if let Some(relative_utf16_range) = relative_utf16_range {
13245 let selections = self.selections.all::<OffsetUtf16>(cx);
13246 self.change_selections(None, cx, |s| {
13247 let new_ranges = selections.into_iter().map(|range| {
13248 let start = OffsetUtf16(
13249 range
13250 .head()
13251 .0
13252 .saturating_add_signed(relative_utf16_range.start),
13253 );
13254 let end = OffsetUtf16(
13255 range
13256 .head()
13257 .0
13258 .saturating_add_signed(relative_utf16_range.end),
13259 );
13260 start..end
13261 });
13262 s.select_ranges(new_ranges);
13263 });
13264 }
13265
13266 self.handle_input(text, cx);
13267 }
13268
13269 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
13270 let Some(provider) = self.semantics_provider.as_ref() else {
13271 return false;
13272 };
13273
13274 let mut supports = false;
13275 self.buffer().read(cx).for_each_buffer(|buffer| {
13276 supports |= provider.supports_inlay_hints(buffer, cx);
13277 });
13278 supports
13279 }
13280
13281 pub fn focus(&self, cx: &mut WindowContext) {
13282 cx.focus(&self.focus_handle)
13283 }
13284
13285 pub fn is_focused(&self, cx: &WindowContext) -> bool {
13286 self.focus_handle.is_focused(cx)
13287 }
13288
13289 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13290 cx.emit(EditorEvent::Focused);
13291
13292 if let Some(descendant) = self
13293 .last_focused_descendant
13294 .take()
13295 .and_then(|descendant| descendant.upgrade())
13296 {
13297 cx.focus(&descendant);
13298 } else {
13299 if let Some(blame) = self.blame.as_ref() {
13300 blame.update(cx, GitBlame::focus)
13301 }
13302
13303 self.blink_manager.update(cx, BlinkManager::enable);
13304 self.show_cursor_names(cx);
13305 self.buffer.update(cx, |buffer, cx| {
13306 buffer.finalize_last_transaction(cx);
13307 if self.leader_peer_id.is_none() {
13308 buffer.set_active_selections(
13309 &self.selections.disjoint_anchors(),
13310 self.selections.line_mode,
13311 self.cursor_shape,
13312 cx,
13313 );
13314 }
13315 });
13316 }
13317 }
13318
13319 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13320 cx.emit(EditorEvent::FocusedIn)
13321 }
13322
13323 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13324 if event.blurred != self.focus_handle {
13325 self.last_focused_descendant = Some(event.blurred);
13326 }
13327 }
13328
13329 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13330 self.blink_manager.update(cx, BlinkManager::disable);
13331 self.buffer
13332 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13333
13334 if let Some(blame) = self.blame.as_ref() {
13335 blame.update(cx, GitBlame::blur)
13336 }
13337 if !self.hover_state.focused(cx) {
13338 hide_hover(self, cx);
13339 }
13340
13341 self.hide_context_menu(cx);
13342 cx.emit(EditorEvent::Blurred);
13343 cx.notify();
13344 }
13345
13346 pub fn register_action<A: Action>(
13347 &mut self,
13348 listener: impl Fn(&A, &mut WindowContext) + 'static,
13349 ) -> Subscription {
13350 let id = self.next_editor_action_id.post_inc();
13351 let listener = Arc::new(listener);
13352 self.editor_actions.borrow_mut().insert(
13353 id,
13354 Box::new(move |cx| {
13355 let cx = cx.window_context();
13356 let listener = listener.clone();
13357 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13358 let action = action.downcast_ref().unwrap();
13359 if phase == DispatchPhase::Bubble {
13360 listener(action, cx)
13361 }
13362 })
13363 }),
13364 );
13365
13366 let editor_actions = self.editor_actions.clone();
13367 Subscription::new(move || {
13368 editor_actions.borrow_mut().remove(&id);
13369 })
13370 }
13371
13372 pub fn file_header_size(&self) -> u32 {
13373 FILE_HEADER_HEIGHT
13374 }
13375
13376 pub fn revert(
13377 &mut self,
13378 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13379 cx: &mut ViewContext<Self>,
13380 ) {
13381 self.buffer().update(cx, |multi_buffer, cx| {
13382 for (buffer_id, changes) in revert_changes {
13383 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13384 buffer.update(cx, |buffer, cx| {
13385 buffer.edit(
13386 changes.into_iter().map(|(range, text)| {
13387 (range, text.to_string().map(Arc::<str>::from))
13388 }),
13389 None,
13390 cx,
13391 );
13392 });
13393 }
13394 }
13395 });
13396 self.change_selections(None, cx, |selections| selections.refresh());
13397 }
13398
13399 pub fn to_pixel_point(
13400 &mut self,
13401 source: multi_buffer::Anchor,
13402 editor_snapshot: &EditorSnapshot,
13403 cx: &mut ViewContext<Self>,
13404 ) -> Option<gpui::Point<Pixels>> {
13405 let source_point = source.to_display_point(editor_snapshot);
13406 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13407 }
13408
13409 pub fn display_to_pixel_point(
13410 &self,
13411 source: DisplayPoint,
13412 editor_snapshot: &EditorSnapshot,
13413 cx: &WindowContext,
13414 ) -> Option<gpui::Point<Pixels>> {
13415 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13416 let text_layout_details = self.text_layout_details(cx);
13417 let scroll_top = text_layout_details
13418 .scroll_anchor
13419 .scroll_position(editor_snapshot)
13420 .y;
13421
13422 if source.row().as_f32() < scroll_top.floor() {
13423 return None;
13424 }
13425 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13426 let source_y = line_height * (source.row().as_f32() - scroll_top);
13427 Some(gpui::Point::new(source_x, source_y))
13428 }
13429
13430 pub fn has_active_completions_menu(&self) -> bool {
13431 self.context_menu.read().as_ref().map_or(false, |menu| {
13432 menu.visible() && matches!(menu, ContextMenu::Completions(_))
13433 })
13434 }
13435
13436 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13437 self.addons
13438 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13439 }
13440
13441 pub fn unregister_addon<T: Addon>(&mut self) {
13442 self.addons.remove(&std::any::TypeId::of::<T>());
13443 }
13444
13445 pub fn addon<T: Addon>(&self) -> Option<&T> {
13446 let type_id = std::any::TypeId::of::<T>();
13447 self.addons
13448 .get(&type_id)
13449 .and_then(|item| item.to_any().downcast_ref::<T>())
13450 }
13451
13452 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13453 let text_layout_details = self.text_layout_details(cx);
13454 let style = &text_layout_details.editor_style;
13455 let font_id = cx.text_system().resolve_font(&style.text.font());
13456 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13457 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13458
13459 let em_width = cx
13460 .text_system()
13461 .typographic_bounds(font_id, font_size, 'm')
13462 .unwrap()
13463 .size
13464 .width;
13465
13466 gpui::Point::new(em_width, line_height)
13467 }
13468}
13469
13470fn get_unstaged_changes_for_buffers(
13471 project: &Model<Project>,
13472 buffers: impl IntoIterator<Item = Model<Buffer>>,
13473 cx: &mut ViewContext<Editor>,
13474) {
13475 let mut tasks = Vec::new();
13476 project.update(cx, |project, cx| {
13477 for buffer in buffers {
13478 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13479 }
13480 });
13481 cx.spawn(|this, mut cx| async move {
13482 let change_sets = futures::future::join_all(tasks).await;
13483 this.update(&mut cx, |this, cx| {
13484 for change_set in change_sets {
13485 if let Some(change_set) = change_set.log_err() {
13486 this.diff_map.add_change_set(change_set, cx);
13487 }
13488 }
13489 })
13490 .ok();
13491 })
13492 .detach();
13493}
13494
13495fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13496 let tab_size = tab_size.get() as usize;
13497 let mut width = offset;
13498
13499 for ch in text.chars() {
13500 width += if ch == '\t' {
13501 tab_size - (width % tab_size)
13502 } else {
13503 1
13504 };
13505 }
13506
13507 width - offset
13508}
13509
13510#[cfg(test)]
13511mod tests {
13512 use super::*;
13513
13514 #[test]
13515 fn test_string_size_with_expanded_tabs() {
13516 let nz = |val| NonZeroU32::new(val).unwrap();
13517 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13518 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13519 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13520 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13521 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13522 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13523 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13524 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13525 }
13526}
13527
13528/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13529struct WordBreakingTokenizer<'a> {
13530 input: &'a str,
13531}
13532
13533impl<'a> WordBreakingTokenizer<'a> {
13534 fn new(input: &'a str) -> Self {
13535 Self { input }
13536 }
13537}
13538
13539fn is_char_ideographic(ch: char) -> bool {
13540 use unicode_script::Script::*;
13541 use unicode_script::UnicodeScript;
13542 matches!(ch.script(), Han | Tangut | Yi)
13543}
13544
13545fn is_grapheme_ideographic(text: &str) -> bool {
13546 text.chars().any(is_char_ideographic)
13547}
13548
13549fn is_grapheme_whitespace(text: &str) -> bool {
13550 text.chars().any(|x| x.is_whitespace())
13551}
13552
13553fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13554 text.chars().next().map_or(false, |ch| {
13555 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13556 })
13557}
13558
13559#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13560struct WordBreakToken<'a> {
13561 token: &'a str,
13562 grapheme_len: usize,
13563 is_whitespace: bool,
13564}
13565
13566impl<'a> Iterator for WordBreakingTokenizer<'a> {
13567 /// Yields a span, the count of graphemes in the token, and whether it was
13568 /// whitespace. Note that it also breaks at word boundaries.
13569 type Item = WordBreakToken<'a>;
13570
13571 fn next(&mut self) -> Option<Self::Item> {
13572 use unicode_segmentation::UnicodeSegmentation;
13573 if self.input.is_empty() {
13574 return None;
13575 }
13576
13577 let mut iter = self.input.graphemes(true).peekable();
13578 let mut offset = 0;
13579 let mut graphemes = 0;
13580 if let Some(first_grapheme) = iter.next() {
13581 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13582 offset += first_grapheme.len();
13583 graphemes += 1;
13584 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13585 if let Some(grapheme) = iter.peek().copied() {
13586 if should_stay_with_preceding_ideograph(grapheme) {
13587 offset += grapheme.len();
13588 graphemes += 1;
13589 }
13590 }
13591 } else {
13592 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13593 let mut next_word_bound = words.peek().copied();
13594 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13595 next_word_bound = words.next();
13596 }
13597 while let Some(grapheme) = iter.peek().copied() {
13598 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13599 break;
13600 };
13601 if is_grapheme_whitespace(grapheme) != is_whitespace {
13602 break;
13603 };
13604 offset += grapheme.len();
13605 graphemes += 1;
13606 iter.next();
13607 }
13608 }
13609 let token = &self.input[..offset];
13610 self.input = &self.input[offset..];
13611 if is_whitespace {
13612 Some(WordBreakToken {
13613 token: " ",
13614 grapheme_len: 1,
13615 is_whitespace: true,
13616 })
13617 } else {
13618 Some(WordBreakToken {
13619 token,
13620 grapheme_len: graphemes,
13621 is_whitespace: false,
13622 })
13623 }
13624 } else {
13625 None
13626 }
13627 }
13628}
13629
13630#[test]
13631fn test_word_breaking_tokenizer() {
13632 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13633 ("", &[]),
13634 (" ", &[(" ", 1, true)]),
13635 ("Ʒ", &[("Ʒ", 1, false)]),
13636 ("Ǽ", &[("Ǽ", 1, false)]),
13637 ("⋑", &[("⋑", 1, false)]),
13638 ("⋑⋑", &[("⋑⋑", 2, false)]),
13639 (
13640 "原理,进而",
13641 &[
13642 ("原", 1, false),
13643 ("理,", 2, false),
13644 ("进", 1, false),
13645 ("而", 1, false),
13646 ],
13647 ),
13648 (
13649 "hello world",
13650 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13651 ),
13652 (
13653 "hello, world",
13654 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13655 ),
13656 (
13657 " hello world",
13658 &[
13659 (" ", 1, true),
13660 ("hello", 5, false),
13661 (" ", 1, true),
13662 ("world", 5, false),
13663 ],
13664 ),
13665 (
13666 "这是什么 \n 钢笔",
13667 &[
13668 ("这", 1, false),
13669 ("是", 1, false),
13670 ("什", 1, false),
13671 ("么", 1, false),
13672 (" ", 1, true),
13673 ("钢", 1, false),
13674 ("笔", 1, false),
13675 ],
13676 ),
13677 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13678 ];
13679
13680 for (input, result) in tests {
13681 assert_eq!(
13682 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13683 result
13684 .iter()
13685 .copied()
13686 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13687 token,
13688 grapheme_len,
13689 is_whitespace,
13690 })
13691 .collect::<Vec<_>>()
13692 );
13693 }
13694}
13695
13696fn wrap_with_prefix(
13697 line_prefix: String,
13698 unwrapped_text: String,
13699 wrap_column: usize,
13700 tab_size: NonZeroU32,
13701) -> String {
13702 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13703 let mut wrapped_text = String::new();
13704 let mut current_line = line_prefix.clone();
13705
13706 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13707 let mut current_line_len = line_prefix_len;
13708 for WordBreakToken {
13709 token,
13710 grapheme_len,
13711 is_whitespace,
13712 } in tokenizer
13713 {
13714 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13715 wrapped_text.push_str(current_line.trim_end());
13716 wrapped_text.push('\n');
13717 current_line.truncate(line_prefix.len());
13718 current_line_len = line_prefix_len;
13719 if !is_whitespace {
13720 current_line.push_str(token);
13721 current_line_len += grapheme_len;
13722 }
13723 } else if !is_whitespace {
13724 current_line.push_str(token);
13725 current_line_len += grapheme_len;
13726 } else if current_line_len != line_prefix_len {
13727 current_line.push(' ');
13728 current_line_len += 1;
13729 }
13730 }
13731
13732 if !current_line.is_empty() {
13733 wrapped_text.push_str(¤t_line);
13734 }
13735 wrapped_text
13736}
13737
13738#[test]
13739fn test_wrap_with_prefix() {
13740 assert_eq!(
13741 wrap_with_prefix(
13742 "# ".to_string(),
13743 "abcdefg".to_string(),
13744 4,
13745 NonZeroU32::new(4).unwrap()
13746 ),
13747 "# abcdefg"
13748 );
13749 assert_eq!(
13750 wrap_with_prefix(
13751 "".to_string(),
13752 "\thello world".to_string(),
13753 8,
13754 NonZeroU32::new(4).unwrap()
13755 ),
13756 "hello\nworld"
13757 );
13758 assert_eq!(
13759 wrap_with_prefix(
13760 "// ".to_string(),
13761 "xx \nyy zz aa bb cc".to_string(),
13762 12,
13763 NonZeroU32::new(4).unwrap()
13764 ),
13765 "// xx yy zz\n// aa bb cc"
13766 );
13767 assert_eq!(
13768 wrap_with_prefix(
13769 String::new(),
13770 "这是什么 \n 钢笔".to_string(),
13771 3,
13772 NonZeroU32::new(4).unwrap()
13773 ),
13774 "这是什\n么 钢\n笔"
13775 );
13776}
13777
13778fn hunks_for_selections(
13779 snapshot: &EditorSnapshot,
13780 selections: &[Selection<Point>],
13781) -> Vec<MultiBufferDiffHunk> {
13782 hunks_for_ranges(
13783 selections.iter().map(|selection| selection.range()),
13784 snapshot,
13785 )
13786}
13787
13788pub fn hunks_for_ranges(
13789 ranges: impl Iterator<Item = Range<Point>>,
13790 snapshot: &EditorSnapshot,
13791) -> Vec<MultiBufferDiffHunk> {
13792 let mut hunks = Vec::new();
13793 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13794 HashMap::default();
13795 for query_range in ranges {
13796 let query_rows =
13797 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13798 for hunk in snapshot.diff_map.diff_hunks_in_range(
13799 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13800 &snapshot.buffer_snapshot,
13801 ) {
13802 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13803 // when the caret is just above or just below the deleted hunk.
13804 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13805 let related_to_selection = if allow_adjacent {
13806 hunk.row_range.overlaps(&query_rows)
13807 || hunk.row_range.start == query_rows.end
13808 || hunk.row_range.end == query_rows.start
13809 } else {
13810 hunk.row_range.overlaps(&query_rows)
13811 };
13812 if related_to_selection {
13813 if !processed_buffer_rows
13814 .entry(hunk.buffer_id)
13815 .or_default()
13816 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13817 {
13818 continue;
13819 }
13820 hunks.push(hunk);
13821 }
13822 }
13823 }
13824
13825 hunks
13826}
13827
13828pub trait CollaborationHub {
13829 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13830 fn user_participant_indices<'a>(
13831 &self,
13832 cx: &'a AppContext,
13833 ) -> &'a HashMap<u64, ParticipantIndex>;
13834 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13835}
13836
13837impl CollaborationHub for Model<Project> {
13838 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13839 self.read(cx).collaborators()
13840 }
13841
13842 fn user_participant_indices<'a>(
13843 &self,
13844 cx: &'a AppContext,
13845 ) -> &'a HashMap<u64, ParticipantIndex> {
13846 self.read(cx).user_store().read(cx).participant_indices()
13847 }
13848
13849 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13850 let this = self.read(cx);
13851 let user_ids = this.collaborators().values().map(|c| c.user_id);
13852 this.user_store().read_with(cx, |user_store, cx| {
13853 user_store.participant_names(user_ids, cx)
13854 })
13855 }
13856}
13857
13858pub trait SemanticsProvider {
13859 fn hover(
13860 &self,
13861 buffer: &Model<Buffer>,
13862 position: text::Anchor,
13863 cx: &mut AppContext,
13864 ) -> Option<Task<Vec<project::Hover>>>;
13865
13866 fn inlay_hints(
13867 &self,
13868 buffer_handle: Model<Buffer>,
13869 range: Range<text::Anchor>,
13870 cx: &mut AppContext,
13871 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13872
13873 fn resolve_inlay_hint(
13874 &self,
13875 hint: InlayHint,
13876 buffer_handle: Model<Buffer>,
13877 server_id: LanguageServerId,
13878 cx: &mut AppContext,
13879 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13880
13881 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13882
13883 fn document_highlights(
13884 &self,
13885 buffer: &Model<Buffer>,
13886 position: text::Anchor,
13887 cx: &mut AppContext,
13888 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13889
13890 fn definitions(
13891 &self,
13892 buffer: &Model<Buffer>,
13893 position: text::Anchor,
13894 kind: GotoDefinitionKind,
13895 cx: &mut AppContext,
13896 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13897
13898 fn range_for_rename(
13899 &self,
13900 buffer: &Model<Buffer>,
13901 position: text::Anchor,
13902 cx: &mut AppContext,
13903 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13904
13905 fn perform_rename(
13906 &self,
13907 buffer: &Model<Buffer>,
13908 position: text::Anchor,
13909 new_name: String,
13910 cx: &mut AppContext,
13911 ) -> Option<Task<Result<ProjectTransaction>>>;
13912}
13913
13914pub trait CompletionProvider {
13915 fn completions(
13916 &self,
13917 buffer: &Model<Buffer>,
13918 buffer_position: text::Anchor,
13919 trigger: CompletionContext,
13920 cx: &mut ViewContext<Editor>,
13921 ) -> Task<Result<Vec<Completion>>>;
13922
13923 fn resolve_completions(
13924 &self,
13925 buffer: Model<Buffer>,
13926 completion_indices: Vec<usize>,
13927 completions: Arc<RwLock<Box<[Completion]>>>,
13928 cx: &mut ViewContext<Editor>,
13929 ) -> Task<Result<bool>>;
13930
13931 fn apply_additional_edits_for_completion(
13932 &self,
13933 buffer: Model<Buffer>,
13934 completion: Completion,
13935 push_to_history: bool,
13936 cx: &mut ViewContext<Editor>,
13937 ) -> Task<Result<Option<language::Transaction>>>;
13938
13939 fn is_completion_trigger(
13940 &self,
13941 buffer: &Model<Buffer>,
13942 position: language::Anchor,
13943 text: &str,
13944 trigger_in_words: bool,
13945 cx: &mut ViewContext<Editor>,
13946 ) -> bool;
13947
13948 fn sort_completions(&self) -> bool {
13949 true
13950 }
13951}
13952
13953pub trait CodeActionProvider {
13954 fn code_actions(
13955 &self,
13956 buffer: &Model<Buffer>,
13957 range: Range<text::Anchor>,
13958 cx: &mut WindowContext,
13959 ) -> Task<Result<Vec<CodeAction>>>;
13960
13961 fn apply_code_action(
13962 &self,
13963 buffer_handle: Model<Buffer>,
13964 action: CodeAction,
13965 excerpt_id: ExcerptId,
13966 push_to_history: bool,
13967 cx: &mut WindowContext,
13968 ) -> Task<Result<ProjectTransaction>>;
13969}
13970
13971impl CodeActionProvider for Model<Project> {
13972 fn code_actions(
13973 &self,
13974 buffer: &Model<Buffer>,
13975 range: Range<text::Anchor>,
13976 cx: &mut WindowContext,
13977 ) -> Task<Result<Vec<CodeAction>>> {
13978 self.update(cx, |project, cx| {
13979 project.code_actions(buffer, range, None, cx)
13980 })
13981 }
13982
13983 fn apply_code_action(
13984 &self,
13985 buffer_handle: Model<Buffer>,
13986 action: CodeAction,
13987 _excerpt_id: ExcerptId,
13988 push_to_history: bool,
13989 cx: &mut WindowContext,
13990 ) -> Task<Result<ProjectTransaction>> {
13991 self.update(cx, |project, cx| {
13992 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13993 })
13994 }
13995}
13996
13997fn snippet_completions(
13998 project: &Project,
13999 buffer: &Model<Buffer>,
14000 buffer_position: text::Anchor,
14001 cx: &mut AppContext,
14002) -> Task<Result<Vec<Completion>>> {
14003 let language = buffer.read(cx).language_at(buffer_position);
14004 let language_name = language.as_ref().map(|language| language.lsp_id());
14005 let snippet_store = project.snippets().read(cx);
14006 let snippets = snippet_store.snippets_for(language_name, cx);
14007
14008 if snippets.is_empty() {
14009 return Task::ready(Ok(vec![]));
14010 }
14011 let snapshot = buffer.read(cx).text_snapshot();
14012 let chars: String = snapshot
14013 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
14014 .collect();
14015
14016 let scope = language.map(|language| language.default_scope());
14017 let executor = cx.background_executor().clone();
14018
14019 cx.background_executor().spawn(async move {
14020 let classifier = CharClassifier::new(scope).for_completion(true);
14021 let mut last_word = chars
14022 .chars()
14023 .take_while(|c| classifier.is_word(*c))
14024 .collect::<String>();
14025 last_word = last_word.chars().rev().collect();
14026
14027 if last_word.is_empty() {
14028 return Ok(vec![]);
14029 }
14030
14031 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
14032 let to_lsp = |point: &text::Anchor| {
14033 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
14034 point_to_lsp(end)
14035 };
14036 let lsp_end = to_lsp(&buffer_position);
14037
14038 let candidates = snippets
14039 .iter()
14040 .enumerate()
14041 .flat_map(|(ix, snippet)| {
14042 snippet
14043 .prefix
14044 .iter()
14045 .map(move |prefix| StringMatchCandidate::new(ix, prefix.clone()))
14046 })
14047 .collect::<Vec<StringMatchCandidate>>();
14048
14049 let mut matches = fuzzy::match_strings(
14050 &candidates,
14051 &last_word,
14052 last_word.chars().any(|c| c.is_uppercase()),
14053 100,
14054 &Default::default(),
14055 executor,
14056 )
14057 .await;
14058
14059 // Remove all candidates where the query's start does not match the start of any word in the candidate
14060 if let Some(query_start) = last_word.chars().next() {
14061 matches.retain(|string_match| {
14062 split_words(&string_match.string).any(|word| {
14063 // Check that the first codepoint of the word as lowercase matches the first
14064 // codepoint of the query as lowercase
14065 word.chars()
14066 .flat_map(|codepoint| codepoint.to_lowercase())
14067 .zip(query_start.to_lowercase())
14068 .all(|(word_cp, query_cp)| word_cp == query_cp)
14069 })
14070 });
14071 }
14072
14073 let matched_strings = matches
14074 .into_iter()
14075 .map(|m| m.string)
14076 .collect::<HashSet<_>>();
14077
14078 let result: Vec<Completion> = snippets
14079 .into_iter()
14080 .filter_map(|snippet| {
14081 let matching_prefix = snippet
14082 .prefix
14083 .iter()
14084 .find(|prefix| matched_strings.contains(*prefix))?;
14085 let start = as_offset - last_word.len();
14086 let start = snapshot.anchor_before(start);
14087 let range = start..buffer_position;
14088 let lsp_start = to_lsp(&start);
14089 let lsp_range = lsp::Range {
14090 start: lsp_start,
14091 end: lsp_end,
14092 };
14093 Some(Completion {
14094 old_range: range,
14095 new_text: snippet.body.clone(),
14096 label: CodeLabel {
14097 text: matching_prefix.clone(),
14098 runs: vec![],
14099 filter_range: 0..matching_prefix.len(),
14100 },
14101 server_id: LanguageServerId(usize::MAX),
14102 documentation: snippet.description.clone().map(Documentation::SingleLine),
14103 lsp_completion: lsp::CompletionItem {
14104 label: snippet.prefix.first().unwrap().clone(),
14105 kind: Some(CompletionItemKind::SNIPPET),
14106 label_details: snippet.description.as_ref().map(|description| {
14107 lsp::CompletionItemLabelDetails {
14108 detail: Some(description.clone()),
14109 description: None,
14110 }
14111 }),
14112 insert_text_format: Some(InsertTextFormat::SNIPPET),
14113 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
14114 lsp::InsertReplaceEdit {
14115 new_text: snippet.body.clone(),
14116 insert: lsp_range,
14117 replace: lsp_range,
14118 },
14119 )),
14120 filter_text: Some(snippet.body.clone()),
14121 sort_text: Some(char::MAX.to_string()),
14122 ..Default::default()
14123 },
14124 confirm: None,
14125 })
14126 })
14127 .collect();
14128
14129 Ok(result)
14130 })
14131}
14132
14133impl CompletionProvider for Model<Project> {
14134 fn completions(
14135 &self,
14136 buffer: &Model<Buffer>,
14137 buffer_position: text::Anchor,
14138 options: CompletionContext,
14139 cx: &mut ViewContext<Editor>,
14140 ) -> Task<Result<Vec<Completion>>> {
14141 self.update(cx, |project, cx| {
14142 let snippets = snippet_completions(project, buffer, buffer_position, cx);
14143 let project_completions = project.completions(buffer, buffer_position, options, cx);
14144 cx.background_executor().spawn(async move {
14145 let mut completions = project_completions.await?;
14146 let snippets_completions = snippets.await?;
14147 completions.extend(snippets_completions);
14148 Ok(completions)
14149 })
14150 })
14151 }
14152
14153 fn resolve_completions(
14154 &self,
14155 buffer: Model<Buffer>,
14156 completion_indices: Vec<usize>,
14157 completions: Arc<RwLock<Box<[Completion]>>>,
14158 cx: &mut ViewContext<Editor>,
14159 ) -> Task<Result<bool>> {
14160 self.update(cx, |project, cx| {
14161 project.resolve_completions(buffer, completion_indices, completions, cx)
14162 })
14163 }
14164
14165 fn apply_additional_edits_for_completion(
14166 &self,
14167 buffer: Model<Buffer>,
14168 completion: Completion,
14169 push_to_history: bool,
14170 cx: &mut ViewContext<Editor>,
14171 ) -> Task<Result<Option<language::Transaction>>> {
14172 self.update(cx, |project, cx| {
14173 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
14174 })
14175 }
14176
14177 fn is_completion_trigger(
14178 &self,
14179 buffer: &Model<Buffer>,
14180 position: language::Anchor,
14181 text: &str,
14182 trigger_in_words: bool,
14183 cx: &mut ViewContext<Editor>,
14184 ) -> bool {
14185 let mut chars = text.chars();
14186 let char = if let Some(char) = chars.next() {
14187 char
14188 } else {
14189 return false;
14190 };
14191 if chars.next().is_some() {
14192 return false;
14193 }
14194
14195 let buffer = buffer.read(cx);
14196 let snapshot = buffer.snapshot();
14197 if !snapshot.settings_at(position, cx).show_completions_on_input {
14198 return false;
14199 }
14200 let classifier = snapshot.char_classifier_at(position).for_completion(true);
14201 if trigger_in_words && classifier.is_word(char) {
14202 return true;
14203 }
14204
14205 buffer.completion_triggers().contains(text)
14206 }
14207}
14208
14209impl SemanticsProvider for Model<Project> {
14210 fn hover(
14211 &self,
14212 buffer: &Model<Buffer>,
14213 position: text::Anchor,
14214 cx: &mut AppContext,
14215 ) -> Option<Task<Vec<project::Hover>>> {
14216 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
14217 }
14218
14219 fn document_highlights(
14220 &self,
14221 buffer: &Model<Buffer>,
14222 position: text::Anchor,
14223 cx: &mut AppContext,
14224 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
14225 Some(self.update(cx, |project, cx| {
14226 project.document_highlights(buffer, position, cx)
14227 }))
14228 }
14229
14230 fn definitions(
14231 &self,
14232 buffer: &Model<Buffer>,
14233 position: text::Anchor,
14234 kind: GotoDefinitionKind,
14235 cx: &mut AppContext,
14236 ) -> Option<Task<Result<Vec<LocationLink>>>> {
14237 Some(self.update(cx, |project, cx| match kind {
14238 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
14239 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
14240 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
14241 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
14242 }))
14243 }
14244
14245 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
14246 // TODO: make this work for remote projects
14247 self.read(cx)
14248 .language_servers_for_buffer(buffer.read(cx), cx)
14249 .any(
14250 |(_, server)| match server.capabilities().inlay_hint_provider {
14251 Some(lsp::OneOf::Left(enabled)) => enabled,
14252 Some(lsp::OneOf::Right(_)) => true,
14253 None => false,
14254 },
14255 )
14256 }
14257
14258 fn inlay_hints(
14259 &self,
14260 buffer_handle: Model<Buffer>,
14261 range: Range<text::Anchor>,
14262 cx: &mut AppContext,
14263 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14264 Some(self.update(cx, |project, cx| {
14265 project.inlay_hints(buffer_handle, range, cx)
14266 }))
14267 }
14268
14269 fn resolve_inlay_hint(
14270 &self,
14271 hint: InlayHint,
14272 buffer_handle: Model<Buffer>,
14273 server_id: LanguageServerId,
14274 cx: &mut AppContext,
14275 ) -> Option<Task<anyhow::Result<InlayHint>>> {
14276 Some(self.update(cx, |project, cx| {
14277 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14278 }))
14279 }
14280
14281 fn range_for_rename(
14282 &self,
14283 buffer: &Model<Buffer>,
14284 position: text::Anchor,
14285 cx: &mut AppContext,
14286 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14287 Some(self.update(cx, |project, cx| {
14288 project.prepare_rename(buffer.clone(), position, cx)
14289 }))
14290 }
14291
14292 fn perform_rename(
14293 &self,
14294 buffer: &Model<Buffer>,
14295 position: text::Anchor,
14296 new_name: String,
14297 cx: &mut AppContext,
14298 ) -> Option<Task<Result<ProjectTransaction>>> {
14299 Some(self.update(cx, |project, cx| {
14300 project.perform_rename(buffer.clone(), position, new_name, cx)
14301 }))
14302 }
14303}
14304
14305fn inlay_hint_settings(
14306 location: Anchor,
14307 snapshot: &MultiBufferSnapshot,
14308 cx: &mut ViewContext<'_, Editor>,
14309) -> InlayHintSettings {
14310 let file = snapshot.file_at(location);
14311 let language = snapshot.language_at(location).map(|l| l.name());
14312 language_settings(language, file, cx).inlay_hints
14313}
14314
14315fn consume_contiguous_rows(
14316 contiguous_row_selections: &mut Vec<Selection<Point>>,
14317 selection: &Selection<Point>,
14318 display_map: &DisplaySnapshot,
14319 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14320) -> (MultiBufferRow, MultiBufferRow) {
14321 contiguous_row_selections.push(selection.clone());
14322 let start_row = MultiBufferRow(selection.start.row);
14323 let mut end_row = ending_row(selection, display_map);
14324
14325 while let Some(next_selection) = selections.peek() {
14326 if next_selection.start.row <= end_row.0 {
14327 end_row = ending_row(next_selection, display_map);
14328 contiguous_row_selections.push(selections.next().unwrap().clone());
14329 } else {
14330 break;
14331 }
14332 }
14333 (start_row, end_row)
14334}
14335
14336fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14337 if next_selection.end.column > 0 || next_selection.is_empty() {
14338 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14339 } else {
14340 MultiBufferRow(next_selection.end.row)
14341 }
14342}
14343
14344impl EditorSnapshot {
14345 pub fn remote_selections_in_range<'a>(
14346 &'a self,
14347 range: &'a Range<Anchor>,
14348 collaboration_hub: &dyn CollaborationHub,
14349 cx: &'a AppContext,
14350 ) -> impl 'a + Iterator<Item = RemoteSelection> {
14351 let participant_names = collaboration_hub.user_names(cx);
14352 let participant_indices = collaboration_hub.user_participant_indices(cx);
14353 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14354 let collaborators_by_replica_id = collaborators_by_peer_id
14355 .iter()
14356 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14357 .collect::<HashMap<_, _>>();
14358 self.buffer_snapshot
14359 .selections_in_range(range, false)
14360 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14361 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14362 let participant_index = participant_indices.get(&collaborator.user_id).copied();
14363 let user_name = participant_names.get(&collaborator.user_id).cloned();
14364 Some(RemoteSelection {
14365 replica_id,
14366 selection,
14367 cursor_shape,
14368 line_mode,
14369 participant_index,
14370 peer_id: collaborator.peer_id,
14371 user_name,
14372 })
14373 })
14374 }
14375
14376 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14377 self.display_snapshot.buffer_snapshot.language_at(position)
14378 }
14379
14380 pub fn is_focused(&self) -> bool {
14381 self.is_focused
14382 }
14383
14384 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14385 self.placeholder_text.as_ref()
14386 }
14387
14388 pub fn scroll_position(&self) -> gpui::Point<f32> {
14389 self.scroll_anchor.scroll_position(&self.display_snapshot)
14390 }
14391
14392 fn gutter_dimensions(
14393 &self,
14394 font_id: FontId,
14395 font_size: Pixels,
14396 em_width: Pixels,
14397 em_advance: Pixels,
14398 max_line_number_width: Pixels,
14399 cx: &AppContext,
14400 ) -> GutterDimensions {
14401 if !self.show_gutter {
14402 return GutterDimensions::default();
14403 }
14404 let descent = cx.text_system().descent(font_id, font_size);
14405
14406 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14407 matches!(
14408 ProjectSettings::get_global(cx).git.git_gutter,
14409 Some(GitGutterSetting::TrackedFiles)
14410 )
14411 });
14412 let gutter_settings = EditorSettings::get_global(cx).gutter;
14413 let show_line_numbers = self
14414 .show_line_numbers
14415 .unwrap_or(gutter_settings.line_numbers);
14416 let line_gutter_width = if show_line_numbers {
14417 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14418 let min_width_for_number_on_gutter = em_advance * 4.0;
14419 max_line_number_width.max(min_width_for_number_on_gutter)
14420 } else {
14421 0.0.into()
14422 };
14423
14424 let show_code_actions = self
14425 .show_code_actions
14426 .unwrap_or(gutter_settings.code_actions);
14427
14428 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14429
14430 let git_blame_entries_width =
14431 self.git_blame_gutter_max_author_length
14432 .map(|max_author_length| {
14433 // Length of the author name, but also space for the commit hash,
14434 // the spacing and the timestamp.
14435 let max_char_count = max_author_length
14436 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14437 + 7 // length of commit sha
14438 + 14 // length of max relative timestamp ("60 minutes ago")
14439 + 4; // gaps and margins
14440
14441 em_advance * max_char_count
14442 });
14443
14444 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14445 left_padding += if show_code_actions || show_runnables {
14446 em_width * 3.0
14447 } else if show_git_gutter && show_line_numbers {
14448 em_width * 2.0
14449 } else if show_git_gutter || show_line_numbers {
14450 em_width
14451 } else {
14452 px(0.)
14453 };
14454
14455 let right_padding = if gutter_settings.folds && show_line_numbers {
14456 em_width * 4.0
14457 } else if gutter_settings.folds {
14458 em_width * 3.0
14459 } else if show_line_numbers {
14460 em_width
14461 } else {
14462 px(0.)
14463 };
14464
14465 GutterDimensions {
14466 left_padding,
14467 right_padding,
14468 width: line_gutter_width + left_padding + right_padding,
14469 margin: -descent,
14470 git_blame_entries_width,
14471 }
14472 }
14473
14474 pub fn render_crease_toggle(
14475 &self,
14476 buffer_row: MultiBufferRow,
14477 row_contains_cursor: bool,
14478 editor: View<Editor>,
14479 cx: &mut WindowContext,
14480 ) -> Option<AnyElement> {
14481 let folded = self.is_line_folded(buffer_row);
14482 let mut is_foldable = false;
14483
14484 if let Some(crease) = self
14485 .crease_snapshot
14486 .query_row(buffer_row, &self.buffer_snapshot)
14487 {
14488 is_foldable = true;
14489 match crease {
14490 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14491 if let Some(render_toggle) = render_toggle {
14492 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14493 if folded {
14494 editor.update(cx, |editor, cx| {
14495 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14496 });
14497 } else {
14498 editor.update(cx, |editor, cx| {
14499 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14500 });
14501 }
14502 });
14503 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14504 }
14505 }
14506 }
14507 }
14508
14509 is_foldable |= self.starts_indent(buffer_row);
14510
14511 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14512 Some(
14513 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14514 .selected(folded)
14515 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14516 if folded {
14517 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14518 } else {
14519 this.fold_at(&FoldAt { buffer_row }, cx);
14520 }
14521 }))
14522 .into_any_element(),
14523 )
14524 } else {
14525 None
14526 }
14527 }
14528
14529 pub fn render_crease_trailer(
14530 &self,
14531 buffer_row: MultiBufferRow,
14532 cx: &mut WindowContext,
14533 ) -> Option<AnyElement> {
14534 let folded = self.is_line_folded(buffer_row);
14535 if let Crease::Inline { render_trailer, .. } = self
14536 .crease_snapshot
14537 .query_row(buffer_row, &self.buffer_snapshot)?
14538 {
14539 let render_trailer = render_trailer.as_ref()?;
14540 Some(render_trailer(buffer_row, folded, cx))
14541 } else {
14542 None
14543 }
14544 }
14545}
14546
14547impl Deref for EditorSnapshot {
14548 type Target = DisplaySnapshot;
14549
14550 fn deref(&self) -> &Self::Target {
14551 &self.display_snapshot
14552 }
14553}
14554
14555#[derive(Clone, Debug, PartialEq, Eq)]
14556pub enum EditorEvent {
14557 InputIgnored {
14558 text: Arc<str>,
14559 },
14560 InputHandled {
14561 utf16_range_to_replace: Option<Range<isize>>,
14562 text: Arc<str>,
14563 },
14564 ExcerptsAdded {
14565 buffer: Model<Buffer>,
14566 predecessor: ExcerptId,
14567 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14568 },
14569 ExcerptsRemoved {
14570 ids: Vec<ExcerptId>,
14571 },
14572 ExcerptsEdited {
14573 ids: Vec<ExcerptId>,
14574 },
14575 ExcerptsExpanded {
14576 ids: Vec<ExcerptId>,
14577 },
14578 BufferEdited,
14579 Edited {
14580 transaction_id: clock::Lamport,
14581 },
14582 Reparsed(BufferId),
14583 Focused,
14584 FocusedIn,
14585 Blurred,
14586 DirtyChanged,
14587 Saved,
14588 TitleChanged,
14589 DiffBaseChanged,
14590 SelectionsChanged {
14591 local: bool,
14592 },
14593 ScrollPositionChanged {
14594 local: bool,
14595 autoscroll: bool,
14596 },
14597 Closed,
14598 TransactionUndone {
14599 transaction_id: clock::Lamport,
14600 },
14601 TransactionBegun {
14602 transaction_id: clock::Lamport,
14603 },
14604 Reloaded,
14605 CursorShapeChanged,
14606}
14607
14608impl EventEmitter<EditorEvent> for Editor {}
14609
14610impl FocusableView for Editor {
14611 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14612 self.focus_handle.clone()
14613 }
14614}
14615
14616impl Render for Editor {
14617 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14618 let settings = ThemeSettings::get_global(cx);
14619
14620 let mut text_style = match self.mode {
14621 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14622 color: cx.theme().colors().editor_foreground,
14623 font_family: settings.ui_font.family.clone(),
14624 font_features: settings.ui_font.features.clone(),
14625 font_fallbacks: settings.ui_font.fallbacks.clone(),
14626 font_size: rems(0.875).into(),
14627 font_weight: settings.ui_font.weight,
14628 line_height: relative(settings.buffer_line_height.value()),
14629 ..Default::default()
14630 },
14631 EditorMode::Full => TextStyle {
14632 color: cx.theme().colors().editor_foreground,
14633 font_family: settings.buffer_font.family.clone(),
14634 font_features: settings.buffer_font.features.clone(),
14635 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14636 font_size: settings.buffer_font_size(cx).into(),
14637 font_weight: settings.buffer_font.weight,
14638 line_height: relative(settings.buffer_line_height.value()),
14639 ..Default::default()
14640 },
14641 };
14642 if let Some(text_style_refinement) = &self.text_style_refinement {
14643 text_style.refine(text_style_refinement)
14644 }
14645
14646 let background = match self.mode {
14647 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14648 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14649 EditorMode::Full => cx.theme().colors().editor_background,
14650 };
14651
14652 EditorElement::new(
14653 cx.view(),
14654 EditorStyle {
14655 background,
14656 local_player: cx.theme().players().local(),
14657 text: text_style,
14658 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14659 syntax: cx.theme().syntax().clone(),
14660 status: cx.theme().status().clone(),
14661 inlay_hints_style: make_inlay_hints_style(cx),
14662 suggestions_style: HighlightStyle {
14663 color: Some(cx.theme().status().predictive),
14664 ..HighlightStyle::default()
14665 },
14666 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14667 },
14668 )
14669 }
14670}
14671
14672impl ViewInputHandler for Editor {
14673 fn text_for_range(
14674 &mut self,
14675 range_utf16: Range<usize>,
14676 adjusted_range: &mut Option<Range<usize>>,
14677 cx: &mut ViewContext<Self>,
14678 ) -> Option<String> {
14679 let snapshot = self.buffer.read(cx).read(cx);
14680 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14681 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14682 if (start.0..end.0) != range_utf16 {
14683 adjusted_range.replace(start.0..end.0);
14684 }
14685 Some(snapshot.text_for_range(start..end).collect())
14686 }
14687
14688 fn selected_text_range(
14689 &mut self,
14690 ignore_disabled_input: bool,
14691 cx: &mut ViewContext<Self>,
14692 ) -> Option<UTF16Selection> {
14693 // Prevent the IME menu from appearing when holding down an alphabetic key
14694 // while input is disabled.
14695 if !ignore_disabled_input && !self.input_enabled {
14696 return None;
14697 }
14698
14699 let selection = self.selections.newest::<OffsetUtf16>(cx);
14700 let range = selection.range();
14701
14702 Some(UTF16Selection {
14703 range: range.start.0..range.end.0,
14704 reversed: selection.reversed,
14705 })
14706 }
14707
14708 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14709 let snapshot = self.buffer.read(cx).read(cx);
14710 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14711 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14712 }
14713
14714 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14715 self.clear_highlights::<InputComposition>(cx);
14716 self.ime_transaction.take();
14717 }
14718
14719 fn replace_text_in_range(
14720 &mut self,
14721 range_utf16: Option<Range<usize>>,
14722 text: &str,
14723 cx: &mut ViewContext<Self>,
14724 ) {
14725 if !self.input_enabled {
14726 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14727 return;
14728 }
14729
14730 self.transact(cx, |this, cx| {
14731 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14732 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14733 Some(this.selection_replacement_ranges(range_utf16, cx))
14734 } else {
14735 this.marked_text_ranges(cx)
14736 };
14737
14738 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14739 let newest_selection_id = this.selections.newest_anchor().id;
14740 this.selections
14741 .all::<OffsetUtf16>(cx)
14742 .iter()
14743 .zip(ranges_to_replace.iter())
14744 .find_map(|(selection, range)| {
14745 if selection.id == newest_selection_id {
14746 Some(
14747 (range.start.0 as isize - selection.head().0 as isize)
14748 ..(range.end.0 as isize - selection.head().0 as isize),
14749 )
14750 } else {
14751 None
14752 }
14753 })
14754 });
14755
14756 cx.emit(EditorEvent::InputHandled {
14757 utf16_range_to_replace: range_to_replace,
14758 text: text.into(),
14759 });
14760
14761 if let Some(new_selected_ranges) = new_selected_ranges {
14762 this.change_selections(None, cx, |selections| {
14763 selections.select_ranges(new_selected_ranges)
14764 });
14765 this.backspace(&Default::default(), cx);
14766 }
14767
14768 this.handle_input(text, cx);
14769 });
14770
14771 if let Some(transaction) = self.ime_transaction {
14772 self.buffer.update(cx, |buffer, cx| {
14773 buffer.group_until_transaction(transaction, cx);
14774 });
14775 }
14776
14777 self.unmark_text(cx);
14778 }
14779
14780 fn replace_and_mark_text_in_range(
14781 &mut self,
14782 range_utf16: Option<Range<usize>>,
14783 text: &str,
14784 new_selected_range_utf16: Option<Range<usize>>,
14785 cx: &mut ViewContext<Self>,
14786 ) {
14787 if !self.input_enabled {
14788 return;
14789 }
14790
14791 let transaction = self.transact(cx, |this, cx| {
14792 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14793 let snapshot = this.buffer.read(cx).read(cx);
14794 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14795 for marked_range in &mut marked_ranges {
14796 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14797 marked_range.start.0 += relative_range_utf16.start;
14798 marked_range.start =
14799 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14800 marked_range.end =
14801 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14802 }
14803 }
14804 Some(marked_ranges)
14805 } else if let Some(range_utf16) = range_utf16 {
14806 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14807 Some(this.selection_replacement_ranges(range_utf16, cx))
14808 } else {
14809 None
14810 };
14811
14812 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14813 let newest_selection_id = this.selections.newest_anchor().id;
14814 this.selections
14815 .all::<OffsetUtf16>(cx)
14816 .iter()
14817 .zip(ranges_to_replace.iter())
14818 .find_map(|(selection, range)| {
14819 if selection.id == newest_selection_id {
14820 Some(
14821 (range.start.0 as isize - selection.head().0 as isize)
14822 ..(range.end.0 as isize - selection.head().0 as isize),
14823 )
14824 } else {
14825 None
14826 }
14827 })
14828 });
14829
14830 cx.emit(EditorEvent::InputHandled {
14831 utf16_range_to_replace: range_to_replace,
14832 text: text.into(),
14833 });
14834
14835 if let Some(ranges) = ranges_to_replace {
14836 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14837 }
14838
14839 let marked_ranges = {
14840 let snapshot = this.buffer.read(cx).read(cx);
14841 this.selections
14842 .disjoint_anchors()
14843 .iter()
14844 .map(|selection| {
14845 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14846 })
14847 .collect::<Vec<_>>()
14848 };
14849
14850 if text.is_empty() {
14851 this.unmark_text(cx);
14852 } else {
14853 this.highlight_text::<InputComposition>(
14854 marked_ranges.clone(),
14855 HighlightStyle {
14856 underline: Some(UnderlineStyle {
14857 thickness: px(1.),
14858 color: None,
14859 wavy: false,
14860 }),
14861 ..Default::default()
14862 },
14863 cx,
14864 );
14865 }
14866
14867 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14868 let use_autoclose = this.use_autoclose;
14869 let use_auto_surround = this.use_auto_surround;
14870 this.set_use_autoclose(false);
14871 this.set_use_auto_surround(false);
14872 this.handle_input(text, cx);
14873 this.set_use_autoclose(use_autoclose);
14874 this.set_use_auto_surround(use_auto_surround);
14875
14876 if let Some(new_selected_range) = new_selected_range_utf16 {
14877 let snapshot = this.buffer.read(cx).read(cx);
14878 let new_selected_ranges = marked_ranges
14879 .into_iter()
14880 .map(|marked_range| {
14881 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14882 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14883 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14884 snapshot.clip_offset_utf16(new_start, Bias::Left)
14885 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14886 })
14887 .collect::<Vec<_>>();
14888
14889 drop(snapshot);
14890 this.change_selections(None, cx, |selections| {
14891 selections.select_ranges(new_selected_ranges)
14892 });
14893 }
14894 });
14895
14896 self.ime_transaction = self.ime_transaction.or(transaction);
14897 if let Some(transaction) = self.ime_transaction {
14898 self.buffer.update(cx, |buffer, cx| {
14899 buffer.group_until_transaction(transaction, cx);
14900 });
14901 }
14902
14903 if self.text_highlights::<InputComposition>(cx).is_none() {
14904 self.ime_transaction.take();
14905 }
14906 }
14907
14908 fn bounds_for_range(
14909 &mut self,
14910 range_utf16: Range<usize>,
14911 element_bounds: gpui::Bounds<Pixels>,
14912 cx: &mut ViewContext<Self>,
14913 ) -> Option<gpui::Bounds<Pixels>> {
14914 let text_layout_details = self.text_layout_details(cx);
14915 let gpui::Point {
14916 x: em_width,
14917 y: line_height,
14918 } = self.character_size(cx);
14919
14920 let snapshot = self.snapshot(cx);
14921 let scroll_position = snapshot.scroll_position();
14922 let scroll_left = scroll_position.x * em_width;
14923
14924 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14925 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14926 + self.gutter_dimensions.width
14927 + self.gutter_dimensions.margin;
14928 let y = line_height * (start.row().as_f32() - scroll_position.y);
14929
14930 Some(Bounds {
14931 origin: element_bounds.origin + point(x, y),
14932 size: size(em_width, line_height),
14933 })
14934 }
14935}
14936
14937trait SelectionExt {
14938 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14939 fn spanned_rows(
14940 &self,
14941 include_end_if_at_line_start: bool,
14942 map: &DisplaySnapshot,
14943 ) -> Range<MultiBufferRow>;
14944}
14945
14946impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14947 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14948 let start = self
14949 .start
14950 .to_point(&map.buffer_snapshot)
14951 .to_display_point(map);
14952 let end = self
14953 .end
14954 .to_point(&map.buffer_snapshot)
14955 .to_display_point(map);
14956 if self.reversed {
14957 end..start
14958 } else {
14959 start..end
14960 }
14961 }
14962
14963 fn spanned_rows(
14964 &self,
14965 include_end_if_at_line_start: bool,
14966 map: &DisplaySnapshot,
14967 ) -> Range<MultiBufferRow> {
14968 let start = self.start.to_point(&map.buffer_snapshot);
14969 let mut end = self.end.to_point(&map.buffer_snapshot);
14970 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14971 end.row -= 1;
14972 }
14973
14974 let buffer_start = map.prev_line_boundary(start).0;
14975 let buffer_end = map.next_line_boundary(end).0;
14976 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14977 }
14978}
14979
14980impl<T: InvalidationRegion> InvalidationStack<T> {
14981 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14982 where
14983 S: Clone + ToOffset,
14984 {
14985 while let Some(region) = self.last() {
14986 let all_selections_inside_invalidation_ranges =
14987 if selections.len() == region.ranges().len() {
14988 selections
14989 .iter()
14990 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14991 .all(|(selection, invalidation_range)| {
14992 let head = selection.head().to_offset(buffer);
14993 invalidation_range.start <= head && invalidation_range.end >= head
14994 })
14995 } else {
14996 false
14997 };
14998
14999 if all_selections_inside_invalidation_ranges {
15000 break;
15001 } else {
15002 self.pop();
15003 }
15004 }
15005 }
15006}
15007
15008impl<T> Default for InvalidationStack<T> {
15009 fn default() -> Self {
15010 Self(Default::default())
15011 }
15012}
15013
15014impl<T> Deref for InvalidationStack<T> {
15015 type Target = Vec<T>;
15016
15017 fn deref(&self) -> &Self::Target {
15018 &self.0
15019 }
15020}
15021
15022impl<T> DerefMut for InvalidationStack<T> {
15023 fn deref_mut(&mut self) -> &mut Self::Target {
15024 &mut self.0
15025 }
15026}
15027
15028impl InvalidationRegion for SnippetState {
15029 fn ranges(&self) -> &[Range<Anchor>] {
15030 &self.ranges[self.active_index]
15031 }
15032}
15033
15034pub fn diagnostic_block_renderer(
15035 diagnostic: Diagnostic,
15036 max_message_rows: Option<u8>,
15037 allow_closing: bool,
15038 _is_valid: bool,
15039) -> RenderBlock {
15040 let (text_without_backticks, code_ranges) =
15041 highlight_diagnostic_message(&diagnostic, max_message_rows);
15042
15043 Arc::new(move |cx: &mut BlockContext| {
15044 let group_id: SharedString = cx.block_id.to_string().into();
15045
15046 let mut text_style = cx.text_style().clone();
15047 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
15048 let theme_settings = ThemeSettings::get_global(cx);
15049 text_style.font_family = theme_settings.buffer_font.family.clone();
15050 text_style.font_style = theme_settings.buffer_font.style;
15051 text_style.font_features = theme_settings.buffer_font.features.clone();
15052 text_style.font_weight = theme_settings.buffer_font.weight;
15053
15054 let multi_line_diagnostic = diagnostic.message.contains('\n');
15055
15056 let buttons = |diagnostic: &Diagnostic| {
15057 if multi_line_diagnostic {
15058 v_flex()
15059 } else {
15060 h_flex()
15061 }
15062 .when(allow_closing, |div| {
15063 div.children(diagnostic.is_primary.then(|| {
15064 IconButton::new("close-block", IconName::XCircle)
15065 .icon_color(Color::Muted)
15066 .size(ButtonSize::Compact)
15067 .style(ButtonStyle::Transparent)
15068 .visible_on_hover(group_id.clone())
15069 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
15070 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
15071 }))
15072 })
15073 .child(
15074 IconButton::new("copy-block", IconName::Copy)
15075 .icon_color(Color::Muted)
15076 .size(ButtonSize::Compact)
15077 .style(ButtonStyle::Transparent)
15078 .visible_on_hover(group_id.clone())
15079 .on_click({
15080 let message = diagnostic.message.clone();
15081 move |_click, cx| {
15082 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
15083 }
15084 })
15085 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
15086 )
15087 };
15088
15089 let icon_size = buttons(&diagnostic)
15090 .into_any_element()
15091 .layout_as_root(AvailableSpace::min_size(), cx);
15092
15093 h_flex()
15094 .id(cx.block_id)
15095 .group(group_id.clone())
15096 .relative()
15097 .size_full()
15098 .block_mouse_down()
15099 .pl(cx.gutter_dimensions.width)
15100 .w(cx.max_width - cx.gutter_dimensions.full_width())
15101 .child(
15102 div()
15103 .flex()
15104 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
15105 .flex_shrink(),
15106 )
15107 .child(buttons(&diagnostic))
15108 .child(div().flex().flex_shrink_0().child(
15109 StyledText::new(text_without_backticks.clone()).with_highlights(
15110 &text_style,
15111 code_ranges.iter().map(|range| {
15112 (
15113 range.clone(),
15114 HighlightStyle {
15115 font_weight: Some(FontWeight::BOLD),
15116 ..Default::default()
15117 },
15118 )
15119 }),
15120 ),
15121 ))
15122 .into_any_element()
15123 })
15124}
15125
15126pub fn highlight_diagnostic_message(
15127 diagnostic: &Diagnostic,
15128 mut max_message_rows: Option<u8>,
15129) -> (SharedString, Vec<Range<usize>>) {
15130 let mut text_without_backticks = String::new();
15131 let mut code_ranges = Vec::new();
15132
15133 if let Some(source) = &diagnostic.source {
15134 text_without_backticks.push_str(source);
15135 code_ranges.push(0..source.len());
15136 text_without_backticks.push_str(": ");
15137 }
15138
15139 let mut prev_offset = 0;
15140 let mut in_code_block = false;
15141 let has_row_limit = max_message_rows.is_some();
15142 let mut newline_indices = diagnostic
15143 .message
15144 .match_indices('\n')
15145 .filter(|_| has_row_limit)
15146 .map(|(ix, _)| ix)
15147 .fuse()
15148 .peekable();
15149
15150 for (quote_ix, _) in diagnostic
15151 .message
15152 .match_indices('`')
15153 .chain([(diagnostic.message.len(), "")])
15154 {
15155 let mut first_newline_ix = None;
15156 let mut last_newline_ix = None;
15157 while let Some(newline_ix) = newline_indices.peek() {
15158 if *newline_ix < quote_ix {
15159 if first_newline_ix.is_none() {
15160 first_newline_ix = Some(*newline_ix);
15161 }
15162 last_newline_ix = Some(*newline_ix);
15163
15164 if let Some(rows_left) = &mut max_message_rows {
15165 if *rows_left == 0 {
15166 break;
15167 } else {
15168 *rows_left -= 1;
15169 }
15170 }
15171 let _ = newline_indices.next();
15172 } else {
15173 break;
15174 }
15175 }
15176 let prev_len = text_without_backticks.len();
15177 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
15178 text_without_backticks.push_str(new_text);
15179 if in_code_block {
15180 code_ranges.push(prev_len..text_without_backticks.len());
15181 }
15182 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
15183 in_code_block = !in_code_block;
15184 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
15185 text_without_backticks.push_str("...");
15186 break;
15187 }
15188 }
15189
15190 (text_without_backticks.into(), code_ranges)
15191}
15192
15193fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
15194 match severity {
15195 DiagnosticSeverity::ERROR => colors.error,
15196 DiagnosticSeverity::WARNING => colors.warning,
15197 DiagnosticSeverity::INFORMATION => colors.info,
15198 DiagnosticSeverity::HINT => colors.info,
15199 _ => colors.ignored,
15200 }
15201}
15202
15203pub fn styled_runs_for_code_label<'a>(
15204 label: &'a CodeLabel,
15205 syntax_theme: &'a theme::SyntaxTheme,
15206) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15207 let fade_out = HighlightStyle {
15208 fade_out: Some(0.35),
15209 ..Default::default()
15210 };
15211
15212 let mut prev_end = label.filter_range.end;
15213 label
15214 .runs
15215 .iter()
15216 .enumerate()
15217 .flat_map(move |(ix, (range, highlight_id))| {
15218 let style = if let Some(style) = highlight_id.style(syntax_theme) {
15219 style
15220 } else {
15221 return Default::default();
15222 };
15223 let mut muted_style = style;
15224 muted_style.highlight(fade_out);
15225
15226 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15227 if range.start >= label.filter_range.end {
15228 if range.start > prev_end {
15229 runs.push((prev_end..range.start, fade_out));
15230 }
15231 runs.push((range.clone(), muted_style));
15232 } else if range.end <= label.filter_range.end {
15233 runs.push((range.clone(), style));
15234 } else {
15235 runs.push((range.start..label.filter_range.end, style));
15236 runs.push((label.filter_range.end..range.end, muted_style));
15237 }
15238 prev_end = cmp::max(prev_end, range.end);
15239
15240 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15241 runs.push((prev_end..label.text.len(), fade_out));
15242 }
15243
15244 runs
15245 })
15246}
15247
15248pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15249 let mut prev_index = 0;
15250 let mut prev_codepoint: Option<char> = None;
15251 text.char_indices()
15252 .chain([(text.len(), '\0')])
15253 .filter_map(move |(index, codepoint)| {
15254 let prev_codepoint = prev_codepoint.replace(codepoint)?;
15255 let is_boundary = index == text.len()
15256 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15257 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15258 if is_boundary {
15259 let chunk = &text[prev_index..index];
15260 prev_index = index;
15261 Some(chunk)
15262 } else {
15263 None
15264 }
15265 })
15266}
15267
15268pub trait RangeToAnchorExt: Sized {
15269 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15270
15271 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15272 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15273 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15274 }
15275}
15276
15277impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15278 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15279 let start_offset = self.start.to_offset(snapshot);
15280 let end_offset = self.end.to_offset(snapshot);
15281 if start_offset == end_offset {
15282 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15283 } else {
15284 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15285 }
15286 }
15287}
15288
15289pub trait RowExt {
15290 fn as_f32(&self) -> f32;
15291
15292 fn next_row(&self) -> Self;
15293
15294 fn previous_row(&self) -> Self;
15295
15296 fn minus(&self, other: Self) -> u32;
15297}
15298
15299impl RowExt for DisplayRow {
15300 fn as_f32(&self) -> f32 {
15301 self.0 as f32
15302 }
15303
15304 fn next_row(&self) -> Self {
15305 Self(self.0 + 1)
15306 }
15307
15308 fn previous_row(&self) -> Self {
15309 Self(self.0.saturating_sub(1))
15310 }
15311
15312 fn minus(&self, other: Self) -> u32 {
15313 self.0 - other.0
15314 }
15315}
15316
15317impl RowExt for MultiBufferRow {
15318 fn as_f32(&self) -> f32 {
15319 self.0 as f32
15320 }
15321
15322 fn next_row(&self) -> Self {
15323 Self(self.0 + 1)
15324 }
15325
15326 fn previous_row(&self) -> Self {
15327 Self(self.0.saturating_sub(1))
15328 }
15329
15330 fn minus(&self, other: Self) -> u32 {
15331 self.0 - other.0
15332 }
15333}
15334
15335trait RowRangeExt {
15336 type Row;
15337
15338 fn len(&self) -> usize;
15339
15340 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15341}
15342
15343impl RowRangeExt for Range<MultiBufferRow> {
15344 type Row = MultiBufferRow;
15345
15346 fn len(&self) -> usize {
15347 (self.end.0 - self.start.0) as usize
15348 }
15349
15350 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15351 (self.start.0..self.end.0).map(MultiBufferRow)
15352 }
15353}
15354
15355impl RowRangeExt for Range<DisplayRow> {
15356 type Row = DisplayRow;
15357
15358 fn len(&self) -> usize {
15359 (self.end.0 - self.start.0) as usize
15360 }
15361
15362 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15363 (self.start.0..self.end.0).map(DisplayRow)
15364 }
15365}
15366
15367fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15368 if hunk.diff_base_byte_range.is_empty() {
15369 DiffHunkStatus::Added
15370 } else if hunk.row_range.is_empty() {
15371 DiffHunkStatus::Removed
15372 } else {
15373 DiffHunkStatus::Modified
15374 }
15375}
15376
15377/// If select range has more than one line, we
15378/// just point the cursor to range.start.
15379fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15380 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15381 range
15382 } else {
15383 range.start..range.start
15384 }
15385}
15386
15387pub struct KillRing(ClipboardItem);
15388impl Global for KillRing {}
15389
15390const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);