1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod clangd_ext;
19mod code_context_menus;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod hunk_diff;
29mod indent_guides;
30mod inlay_hint_cache;
31pub mod items;
32mod linked_editing_ranges;
33mod lsp_ext;
34mod mouse_context_menu;
35pub mod movement;
36mod persistence;
37mod proposed_changes_editor;
38mod rust_analyzer_ext;
39pub mod scroll;
40mod selections_collection;
41pub mod tasks;
42
43#[cfg(test)]
44mod editor_tests;
45#[cfg(test)]
46mod inline_completion_tests;
47mod signature_help;
48#[cfg(any(test, feature = "test-support"))]
49pub mod test;
50
51use ::git::diff::DiffHunkStatus;
52pub(crate) use actions::*;
53pub use actions::{OpenExcerpts, OpenExcerptsSplit};
54use aho_corasick::AhoCorasick;
55use anyhow::{anyhow, Context as _, Result};
56use blink_manager::BlinkManager;
57use client::{Collaborator, ParticipantIndex};
58use clock::ReplicaId;
59use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
60use convert_case::{Case, Casing};
61use display_map::*;
62pub use display_map::{DisplayPoint, FoldPlaceholder};
63pub use editor_settings::{
64 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
65};
66pub use editor_settings_controls::*;
67use element::LineWithInvisibles;
68pub use element::{
69 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
70};
71use futures::{future, FutureExt};
72use fuzzy::StringMatchCandidate;
73
74use code_context_menus::{
75 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
76 CompletionsMenu, ContextMenuOrigin,
77};
78use git::blame::GitBlame;
79use gpui::{
80 div, impl_actions, point, prelude::*, px, relative, size, Action, AnyElement, AppContext,
81 AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context,
82 DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent, FocusableView, FontId,
83 FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Model, ModelContext,
84 MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText,
85 Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
86 UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
87 WeakView, WindowContext,
88};
89use highlight_matching_bracket::refresh_matching_bracket_highlights;
90use hover_popover::{hide_hover, HoverState};
91pub(crate) use hunk_diff::HoveredHunk;
92use hunk_diff::{diff_hunk_to_display, DiffMap, DiffMapSnapshot};
93use indent_guides::ActiveIndentGuidesState;
94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
95pub use inline_completion::Direction;
96use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
97pub use items::MAX_TAB_TITLE_LEN;
98use itertools::Itertools;
99use language::{
100 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
101 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
102 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
103 Point, Selection, SelectionGoal, TransactionId,
104};
105use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
106use linked_editing_ranges::refresh_linked_ranges;
107use mouse_context_menu::MouseContextMenu;
108pub use proposed_changes_editor::{
109 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
110};
111use similar::{ChangeTag, TextDiff};
112use std::iter::Peekable;
113use task::{ResolvedTask, TaskTemplate, TaskVariables};
114
115use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
116pub use lsp::CompletionContext;
117use lsp::{
118 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
119 LanguageServerId, LanguageServerName,
120};
121
122use movement::TextLayoutDetails;
123pub use multi_buffer::{
124 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
125 ToPoint,
126};
127use multi_buffer::{
128 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
129};
130use parking_lot::RwLock;
131use project::{
132 lsp_store::{FormatTarget, FormatTrigger},
133 project_settings::{GitGutterSetting, ProjectSettings},
134 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
135 Project, ProjectItem, ProjectTransaction, TaskSourceKind,
136};
137use rand::prelude::*;
138use rpc::{proto::*, ErrorExt};
139use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
140use selections_collection::{
141 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
142};
143use serde::{Deserialize, Serialize};
144use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
145use smallvec::SmallVec;
146use snippet::Snippet;
147use std::{
148 any::TypeId,
149 borrow::Cow,
150 cell::RefCell,
151 cmp::{self, Ordering, Reverse},
152 mem,
153 num::NonZeroU32,
154 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
155 path::{Path, PathBuf},
156 rc::Rc,
157 sync::Arc,
158 time::{Duration, Instant},
159};
160pub use sum_tree::Bias;
161use sum_tree::TreeMap;
162use text::{BufferId, OffsetUtf16, Rope};
163use theme::{
164 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
165 ThemeColors, ThemeSettings,
166};
167use ui::{
168 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
169 PopoverMenuHandle, Tooltip,
170};
171use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
172use workspace::item::{ItemHandle, PreviewTabsSettings};
173use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
174use workspace::{
175 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
176};
177use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
178
179use crate::hover_links::find_url;
180use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
181
182pub const FILE_HEADER_HEIGHT: u32 = 2;
183pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
184pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
185pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
186const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
187const MAX_LINE_LEN: usize = 1024;
188const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
189const MAX_SELECTION_HISTORY_LEN: usize = 1024;
190pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
191#[doc(hidden)]
192pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
193#[doc(hidden)]
194pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
195
196pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
197pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
198
199pub fn render_parsed_markdown(
200 element_id: impl Into<ElementId>,
201 parsed: &language::ParsedMarkdown,
202 editor_style: &EditorStyle,
203 workspace: Option<WeakView<Workspace>>,
204 cx: &mut WindowContext,
205) -> InteractiveText {
206 let code_span_background_color = cx
207 .theme()
208 .colors()
209 .editor_document_highlight_read_background;
210
211 let highlights = gpui::combine_highlights(
212 parsed.highlights.iter().filter_map(|(range, highlight)| {
213 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
214 Some((range.clone(), highlight))
215 }),
216 parsed
217 .regions
218 .iter()
219 .zip(&parsed.region_ranges)
220 .filter_map(|(region, range)| {
221 if region.code {
222 Some((
223 range.clone(),
224 HighlightStyle {
225 background_color: Some(code_span_background_color),
226 ..Default::default()
227 },
228 ))
229 } else {
230 None
231 }
232 }),
233 );
234
235 let mut links = Vec::new();
236 let mut link_ranges = Vec::new();
237 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
238 if let Some(link) = region.link.clone() {
239 links.push(link);
240 link_ranges.push(range.clone());
241 }
242 }
243
244 InteractiveText::new(
245 element_id,
246 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
247 )
248 .on_click(link_ranges, move |clicked_range_ix, cx| {
249 match &links[clicked_range_ix] {
250 markdown::Link::Web { url } => cx.open_url(url),
251 markdown::Link::Path { path } => {
252 if let Some(workspace) = &workspace {
253 _ = workspace.update(cx, |workspace, cx| {
254 workspace.open_abs_path(path.clone(), false, cx).detach();
255 });
256 }
257 }
258 }
259 })
260}
261
262#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
263pub(crate) enum InlayId {
264 Suggestion(usize),
265 Hint(usize),
266}
267
268impl InlayId {
269 fn id(&self) -> usize {
270 match self {
271 Self::Suggestion(id) => *id,
272 Self::Hint(id) => *id,
273 }
274 }
275}
276
277enum DiffRowHighlight {}
278enum DocumentHighlightRead {}
279enum DocumentHighlightWrite {}
280enum InputComposition {}
281
282#[derive(Debug, Copy, Clone, PartialEq, Eq)]
283pub enum Navigated {
284 Yes,
285 No,
286}
287
288impl Navigated {
289 pub fn from_bool(yes: bool) -> Navigated {
290 if yes {
291 Navigated::Yes
292 } else {
293 Navigated::No
294 }
295 }
296}
297
298pub fn init_settings(cx: &mut AppContext) {
299 EditorSettings::register(cx);
300}
301
302pub fn init(cx: &mut AppContext) {
303 init_settings(cx);
304
305 workspace::register_project_item::<Editor>(cx);
306 workspace::FollowableViewRegistry::register::<Editor>(cx);
307 workspace::register_serializable_item::<Editor>(cx);
308
309 cx.observe_new_views(
310 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
311 workspace.register_action(Editor::new_file);
312 workspace.register_action(Editor::new_file_vertical);
313 workspace.register_action(Editor::new_file_horizontal);
314 },
315 )
316 .detach();
317
318 cx.on_action(move |_: &workspace::NewFile, cx| {
319 let app_state = workspace::AppState::global(cx);
320 if let Some(app_state) = app_state.upgrade() {
321 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
322 Editor::new_file(workspace, &Default::default(), cx)
323 })
324 .detach();
325 }
326 });
327 cx.on_action(move |_: &workspace::NewWindow, cx| {
328 let app_state = workspace::AppState::global(cx);
329 if let Some(app_state) = app_state.upgrade() {
330 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
331 Editor::new_file(workspace, &Default::default(), cx)
332 })
333 .detach();
334 }
335 });
336 git::project_diff::init(cx);
337}
338
339pub struct SearchWithinRange;
340
341trait InvalidationRegion {
342 fn ranges(&self) -> &[Range<Anchor>];
343}
344
345#[derive(Clone, Debug, PartialEq)]
346pub enum SelectPhase {
347 Begin {
348 position: DisplayPoint,
349 add: bool,
350 click_count: usize,
351 },
352 BeginColumnar {
353 position: DisplayPoint,
354 reset: bool,
355 goal_column: u32,
356 },
357 Extend {
358 position: DisplayPoint,
359 click_count: usize,
360 },
361 Update {
362 position: DisplayPoint,
363 goal_column: u32,
364 scroll_delta: gpui::Point<f32>,
365 },
366 End,
367}
368
369#[derive(Clone, Debug)]
370pub enum SelectMode {
371 Character,
372 Word(Range<Anchor>),
373 Line(Range<Anchor>),
374 All,
375}
376
377#[derive(Copy, Clone, PartialEq, Eq, Debug)]
378pub enum EditorMode {
379 SingleLine { auto_width: bool },
380 AutoHeight { max_lines: usize },
381 Full,
382}
383
384#[derive(Copy, Clone, Debug)]
385pub enum SoftWrap {
386 /// Prefer not to wrap at all.
387 ///
388 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
389 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
390 GitDiff,
391 /// Prefer a single line generally, unless an overly long line is encountered.
392 None,
393 /// Soft wrap lines that exceed the editor width.
394 EditorWidth,
395 /// Soft wrap lines at the preferred line length.
396 Column(u32),
397 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
398 Bounded(u32),
399}
400
401#[derive(Clone)]
402pub struct EditorStyle {
403 pub background: Hsla,
404 pub local_player: PlayerColor,
405 pub text: TextStyle,
406 pub scrollbar_width: Pixels,
407 pub syntax: Arc<SyntaxTheme>,
408 pub status: StatusColors,
409 pub inlay_hints_style: HighlightStyle,
410 pub suggestions_style: HighlightStyle,
411 pub unnecessary_code_fade: f32,
412}
413
414impl Default for EditorStyle {
415 fn default() -> Self {
416 Self {
417 background: Hsla::default(),
418 local_player: PlayerColor::default(),
419 text: TextStyle::default(),
420 scrollbar_width: Pixels::default(),
421 syntax: Default::default(),
422 // HACK: Status colors don't have a real default.
423 // We should look into removing the status colors from the editor
424 // style and retrieve them directly from the theme.
425 status: StatusColors::dark(),
426 inlay_hints_style: HighlightStyle::default(),
427 suggestions_style: HighlightStyle::default(),
428 unnecessary_code_fade: Default::default(),
429 }
430 }
431}
432
433pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
434 let show_background = language_settings::language_settings(None, None, cx)
435 .inlay_hints
436 .show_background;
437
438 HighlightStyle {
439 color: Some(cx.theme().status().hint),
440 background_color: show_background.then(|| cx.theme().status().hint_background),
441 ..HighlightStyle::default()
442 }
443}
444
445type CompletionId = usize;
446
447enum InlineCompletion {
448 Edit(Vec<(Range<Anchor>, String)>),
449 Move(Anchor),
450}
451
452struct InlineCompletionState {
453 inlay_ids: Vec<InlayId>,
454 completion: InlineCompletion,
455 invalidation_range: Range<Anchor>,
456}
457
458enum InlineCompletionHighlight {}
459
460#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
461struct EditorActionId(usize);
462
463impl EditorActionId {
464 pub fn post_inc(&mut self) -> Self {
465 let answer = self.0;
466
467 *self = Self(answer + 1);
468
469 Self(answer)
470 }
471}
472
473// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
474// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
475
476type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
477type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
478
479#[derive(Default)]
480struct ScrollbarMarkerState {
481 scrollbar_size: Size<Pixels>,
482 dirty: bool,
483 markers: Arc<[PaintQuad]>,
484 pending_refresh: Option<Task<Result<()>>>,
485}
486
487impl ScrollbarMarkerState {
488 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
489 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
490 }
491}
492
493#[derive(Clone, Debug)]
494struct RunnableTasks {
495 templates: Vec<(TaskSourceKind, TaskTemplate)>,
496 offset: MultiBufferOffset,
497 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
498 column: u32,
499 // Values of all named captures, including those starting with '_'
500 extra_variables: HashMap<String, String>,
501 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
502 context_range: Range<BufferOffset>,
503}
504
505impl RunnableTasks {
506 fn resolve<'a>(
507 &'a self,
508 cx: &'a task::TaskContext,
509 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
510 self.templates.iter().filter_map(|(kind, template)| {
511 template
512 .resolve_task(&kind.to_id_base(), cx)
513 .map(|task| (kind.clone(), task))
514 })
515 }
516}
517
518#[derive(Clone)]
519struct ResolvedTasks {
520 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
521 position: Anchor,
522}
523#[derive(Copy, Clone, Debug)]
524struct MultiBufferOffset(usize);
525#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
526struct BufferOffset(usize);
527
528// Addons allow storing per-editor state in other crates (e.g. Vim)
529pub trait Addon: 'static {
530 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
531
532 fn to_any(&self) -> &dyn std::any::Any;
533}
534
535#[derive(Debug, Copy, Clone, PartialEq, Eq)]
536pub enum IsVimMode {
537 Yes,
538 No,
539}
540
541/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
542///
543/// See the [module level documentation](self) for more information.
544pub struct Editor {
545 focus_handle: FocusHandle,
546 last_focused_descendant: Option<WeakFocusHandle>,
547 /// The text buffer being edited
548 buffer: Model<MultiBuffer>,
549 /// Map of how text in the buffer should be displayed.
550 /// Handles soft wraps, folds, fake inlay text insertions, etc.
551 pub display_map: Model<DisplayMap>,
552 pub selections: SelectionsCollection,
553 pub scroll_manager: ScrollManager,
554 /// When inline assist editors are linked, they all render cursors because
555 /// typing enters text into each of them, even the ones that aren't focused.
556 pub(crate) show_cursor_when_unfocused: bool,
557 columnar_selection_tail: Option<Anchor>,
558 add_selections_state: Option<AddSelectionsState>,
559 select_next_state: Option<SelectNextState>,
560 select_prev_state: Option<SelectNextState>,
561 selection_history: SelectionHistory,
562 autoclose_regions: Vec<AutocloseRegion>,
563 snippet_stack: InvalidationStack<SnippetState>,
564 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
565 ime_transaction: Option<TransactionId>,
566 active_diagnostics: Option<ActiveDiagnosticGroup>,
567 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
568
569 project: Option<Model<Project>>,
570 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
571 completion_provider: Option<Box<dyn CompletionProvider>>,
572 collaboration_hub: Option<Box<dyn CollaborationHub>>,
573 blink_manager: Model<BlinkManager>,
574 show_cursor_names: bool,
575 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
576 pub show_local_selections: bool,
577 mode: EditorMode,
578 show_breadcrumbs: bool,
579 show_gutter: bool,
580 show_line_numbers: Option<bool>,
581 use_relative_line_numbers: Option<bool>,
582 show_git_diff_gutter: Option<bool>,
583 show_code_actions: Option<bool>,
584 show_runnables: Option<bool>,
585 show_wrap_guides: Option<bool>,
586 show_indent_guides: Option<bool>,
587 placeholder_text: Option<Arc<str>>,
588 highlight_order: usize,
589 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
590 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
591 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
592 scrollbar_marker_state: ScrollbarMarkerState,
593 active_indent_guides_state: ActiveIndentGuidesState,
594 nav_history: Option<ItemNavHistory>,
595 context_menu: RwLock<Option<CodeContextMenu>>,
596 mouse_context_menu: Option<MouseContextMenu>,
597 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
598 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
599 signature_help_state: SignatureHelpState,
600 auto_signature_help: Option<bool>,
601 find_all_references_task_sources: Vec<Anchor>,
602 next_completion_id: CompletionId,
603 available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
604 code_actions_task: Option<Task<Result<()>>>,
605 document_highlights_task: Option<Task<()>>,
606 linked_editing_range_task: Option<Task<Option<()>>>,
607 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
608 pending_rename: Option<RenameState>,
609 searchable: bool,
610 cursor_shape: CursorShape,
611 current_line_highlight: Option<CurrentLineHighlight>,
612 collapse_matches: bool,
613 autoindent_mode: Option<AutoindentMode>,
614 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
615 input_enabled: bool,
616 use_modal_editing: bool,
617 read_only: bool,
618 leader_peer_id: Option<PeerId>,
619 remote_id: Option<ViewId>,
620 hover_state: HoverState,
621 gutter_hovered: bool,
622 hovered_link_state: Option<HoveredLinkState>,
623 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
624 code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
625 active_inline_completion: Option<InlineCompletionState>,
626 // enable_inline_completions is a switch that Vim can use to disable
627 // inline completions based on its mode.
628 enable_inline_completions: bool,
629 show_inline_completions_override: Option<bool>,
630 inlay_hint_cache: InlayHintCache,
631 diff_map: DiffMap,
632 next_inlay_id: usize,
633 _subscriptions: Vec<Subscription>,
634 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
635 gutter_dimensions: GutterDimensions,
636 style: Option<EditorStyle>,
637 text_style_refinement: Option<TextStyleRefinement>,
638 next_editor_action_id: EditorActionId,
639 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
640 use_autoclose: bool,
641 use_auto_surround: bool,
642 auto_replace_emoji_shortcode: bool,
643 show_git_blame_gutter: bool,
644 show_git_blame_inline: bool,
645 show_git_blame_inline_delay_task: Option<Task<()>>,
646 git_blame_inline_enabled: bool,
647 serialize_dirty_buffers: bool,
648 show_selection_menu: Option<bool>,
649 blame: Option<Model<GitBlame>>,
650 blame_subscription: Option<Subscription>,
651 custom_context_menu: Option<
652 Box<
653 dyn 'static
654 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
655 >,
656 >,
657 last_bounds: Option<Bounds<Pixels>>,
658 expect_bounds_change: Option<Bounds<Pixels>>,
659 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
660 tasks_update_task: Option<Task<()>>,
661 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
662 breadcrumb_header: Option<String>,
663 focused_block: Option<FocusedBlock>,
664 next_scroll_position: NextScrollCursorCenterTopBottom,
665 addons: HashMap<TypeId, Box<dyn Addon>>,
666 _scroll_cursor_center_top_bottom_task: Task<()>,
667}
668
669#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
670enum NextScrollCursorCenterTopBottom {
671 #[default]
672 Center,
673 Top,
674 Bottom,
675}
676
677impl NextScrollCursorCenterTopBottom {
678 fn next(&self) -> Self {
679 match self {
680 Self::Center => Self::Top,
681 Self::Top => Self::Bottom,
682 Self::Bottom => Self::Center,
683 }
684 }
685}
686
687#[derive(Clone)]
688pub struct EditorSnapshot {
689 pub mode: EditorMode,
690 show_gutter: bool,
691 show_line_numbers: Option<bool>,
692 show_git_diff_gutter: Option<bool>,
693 show_code_actions: Option<bool>,
694 show_runnables: Option<bool>,
695 git_blame_gutter_max_author_length: Option<usize>,
696 pub display_snapshot: DisplaySnapshot,
697 pub placeholder_text: Option<Arc<str>>,
698 diff_map: DiffMapSnapshot,
699 is_focused: bool,
700 scroll_anchor: ScrollAnchor,
701 ongoing_scroll: OngoingScroll,
702 current_line_highlight: CurrentLineHighlight,
703 gutter_hovered: bool,
704}
705
706const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
707
708#[derive(Default, Debug, Clone, Copy)]
709pub struct GutterDimensions {
710 pub left_padding: Pixels,
711 pub right_padding: Pixels,
712 pub width: Pixels,
713 pub margin: Pixels,
714 pub git_blame_entries_width: Option<Pixels>,
715}
716
717impl GutterDimensions {
718 /// The full width of the space taken up by the gutter.
719 pub fn full_width(&self) -> Pixels {
720 self.margin + self.width
721 }
722
723 /// The width of the space reserved for the fold indicators,
724 /// use alongside 'justify_end' and `gutter_width` to
725 /// right align content with the line numbers
726 pub fn fold_area_width(&self) -> Pixels {
727 self.margin + self.right_padding
728 }
729}
730
731#[derive(Debug)]
732pub struct RemoteSelection {
733 pub replica_id: ReplicaId,
734 pub selection: Selection<Anchor>,
735 pub cursor_shape: CursorShape,
736 pub peer_id: PeerId,
737 pub line_mode: bool,
738 pub participant_index: Option<ParticipantIndex>,
739 pub user_name: Option<SharedString>,
740}
741
742#[derive(Clone, Debug)]
743struct SelectionHistoryEntry {
744 selections: Arc<[Selection<Anchor>]>,
745 select_next_state: Option<SelectNextState>,
746 select_prev_state: Option<SelectNextState>,
747 add_selections_state: Option<AddSelectionsState>,
748}
749
750enum SelectionHistoryMode {
751 Normal,
752 Undoing,
753 Redoing,
754}
755
756#[derive(Clone, PartialEq, Eq, Hash)]
757struct HoveredCursor {
758 replica_id: u16,
759 selection_id: usize,
760}
761
762impl Default for SelectionHistoryMode {
763 fn default() -> Self {
764 Self::Normal
765 }
766}
767
768#[derive(Default)]
769struct SelectionHistory {
770 #[allow(clippy::type_complexity)]
771 selections_by_transaction:
772 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
773 mode: SelectionHistoryMode,
774 undo_stack: VecDeque<SelectionHistoryEntry>,
775 redo_stack: VecDeque<SelectionHistoryEntry>,
776}
777
778impl SelectionHistory {
779 fn insert_transaction(
780 &mut self,
781 transaction_id: TransactionId,
782 selections: Arc<[Selection<Anchor>]>,
783 ) {
784 self.selections_by_transaction
785 .insert(transaction_id, (selections, None));
786 }
787
788 #[allow(clippy::type_complexity)]
789 fn transaction(
790 &self,
791 transaction_id: TransactionId,
792 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
793 self.selections_by_transaction.get(&transaction_id)
794 }
795
796 #[allow(clippy::type_complexity)]
797 fn transaction_mut(
798 &mut self,
799 transaction_id: TransactionId,
800 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
801 self.selections_by_transaction.get_mut(&transaction_id)
802 }
803
804 fn push(&mut self, entry: SelectionHistoryEntry) {
805 if !entry.selections.is_empty() {
806 match self.mode {
807 SelectionHistoryMode::Normal => {
808 self.push_undo(entry);
809 self.redo_stack.clear();
810 }
811 SelectionHistoryMode::Undoing => self.push_redo(entry),
812 SelectionHistoryMode::Redoing => self.push_undo(entry),
813 }
814 }
815 }
816
817 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
818 if self
819 .undo_stack
820 .back()
821 .map_or(true, |e| e.selections != entry.selections)
822 {
823 self.undo_stack.push_back(entry);
824 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
825 self.undo_stack.pop_front();
826 }
827 }
828 }
829
830 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
831 if self
832 .redo_stack
833 .back()
834 .map_or(true, |e| e.selections != entry.selections)
835 {
836 self.redo_stack.push_back(entry);
837 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
838 self.redo_stack.pop_front();
839 }
840 }
841 }
842}
843
844struct RowHighlight {
845 index: usize,
846 range: Range<Anchor>,
847 color: Hsla,
848 should_autoscroll: bool,
849}
850
851#[derive(Clone, Debug)]
852struct AddSelectionsState {
853 above: bool,
854 stack: Vec<usize>,
855}
856
857#[derive(Clone)]
858struct SelectNextState {
859 query: AhoCorasick,
860 wordwise: bool,
861 done: bool,
862}
863
864impl std::fmt::Debug for SelectNextState {
865 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
866 f.debug_struct(std::any::type_name::<Self>())
867 .field("wordwise", &self.wordwise)
868 .field("done", &self.done)
869 .finish()
870 }
871}
872
873#[derive(Debug)]
874struct AutocloseRegion {
875 selection_id: usize,
876 range: Range<Anchor>,
877 pair: BracketPair,
878}
879
880#[derive(Debug)]
881struct SnippetState {
882 ranges: Vec<Vec<Range<Anchor>>>,
883 active_index: usize,
884 choices: Vec<Option<Vec<String>>>,
885}
886
887#[doc(hidden)]
888pub struct RenameState {
889 pub range: Range<Anchor>,
890 pub old_name: Arc<str>,
891 pub editor: View<Editor>,
892 block_id: CustomBlockId,
893}
894
895struct InvalidationStack<T>(Vec<T>);
896
897struct RegisteredInlineCompletionProvider {
898 provider: Arc<dyn InlineCompletionProviderHandle>,
899 _subscription: Subscription,
900}
901
902#[derive(Debug)]
903struct ActiveDiagnosticGroup {
904 primary_range: Range<Anchor>,
905 primary_message: String,
906 group_id: usize,
907 blocks: HashMap<CustomBlockId, Diagnostic>,
908 is_valid: bool,
909}
910
911#[derive(Serialize, Deserialize, Clone, Debug)]
912pub struct ClipboardSelection {
913 pub len: usize,
914 pub is_entire_line: bool,
915 pub first_line_indent: u32,
916}
917
918#[derive(Debug)]
919pub(crate) struct NavigationData {
920 cursor_anchor: Anchor,
921 cursor_position: Point,
922 scroll_anchor: ScrollAnchor,
923 scroll_top_row: u32,
924}
925
926#[derive(Debug, Clone, Copy, PartialEq, Eq)]
927pub enum GotoDefinitionKind {
928 Symbol,
929 Declaration,
930 Type,
931 Implementation,
932}
933
934#[derive(Debug, Clone)]
935enum InlayHintRefreshReason {
936 Toggle(bool),
937 SettingsChange(InlayHintSettings),
938 NewLinesShown,
939 BufferEdited(HashSet<Arc<Language>>),
940 RefreshRequested,
941 ExcerptsRemoved(Vec<ExcerptId>),
942}
943
944impl InlayHintRefreshReason {
945 fn description(&self) -> &'static str {
946 match self {
947 Self::Toggle(_) => "toggle",
948 Self::SettingsChange(_) => "settings change",
949 Self::NewLinesShown => "new lines shown",
950 Self::BufferEdited(_) => "buffer edited",
951 Self::RefreshRequested => "refresh requested",
952 Self::ExcerptsRemoved(_) => "excerpts removed",
953 }
954 }
955}
956
957pub(crate) struct FocusedBlock {
958 id: BlockId,
959 focus_handle: WeakFocusHandle,
960}
961
962#[derive(Clone)]
963struct JumpData {
964 excerpt_id: ExcerptId,
965 position: Point,
966 anchor: text::Anchor,
967 path: Option<project::ProjectPath>,
968 line_offset_from_top: u32,
969}
970
971impl Editor {
972 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
973 let buffer = cx.new_model(|cx| Buffer::local("", cx));
974 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
975 Self::new(
976 EditorMode::SingleLine { auto_width: false },
977 buffer,
978 None,
979 false,
980 cx,
981 )
982 }
983
984 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
985 let buffer = cx.new_model(|cx| Buffer::local("", cx));
986 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
987 Self::new(EditorMode::Full, buffer, None, false, cx)
988 }
989
990 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
991 let buffer = cx.new_model(|cx| Buffer::local("", cx));
992 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
993 Self::new(
994 EditorMode::SingleLine { auto_width: true },
995 buffer,
996 None,
997 false,
998 cx,
999 )
1000 }
1001
1002 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1003 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1004 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1005 Self::new(
1006 EditorMode::AutoHeight { max_lines },
1007 buffer,
1008 None,
1009 false,
1010 cx,
1011 )
1012 }
1013
1014 pub fn for_buffer(
1015 buffer: Model<Buffer>,
1016 project: Option<Model<Project>>,
1017 cx: &mut ViewContext<Self>,
1018 ) -> Self {
1019 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1020 Self::new(EditorMode::Full, buffer, project, false, cx)
1021 }
1022
1023 pub fn for_multibuffer(
1024 buffer: Model<MultiBuffer>,
1025 project: Option<Model<Project>>,
1026 show_excerpt_controls: bool,
1027 cx: &mut ViewContext<Self>,
1028 ) -> Self {
1029 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1030 }
1031
1032 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1033 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1034 let mut clone = Self::new(
1035 self.mode,
1036 self.buffer.clone(),
1037 self.project.clone(),
1038 show_excerpt_controls,
1039 cx,
1040 );
1041 self.display_map.update(cx, |display_map, cx| {
1042 let snapshot = display_map.snapshot(cx);
1043 clone.display_map.update(cx, |display_map, cx| {
1044 display_map.set_state(&snapshot, cx);
1045 });
1046 });
1047 clone.selections.clone_state(&self.selections);
1048 clone.scroll_manager.clone_state(&self.scroll_manager);
1049 clone.searchable = self.searchable;
1050 clone
1051 }
1052
1053 pub fn new(
1054 mode: EditorMode,
1055 buffer: Model<MultiBuffer>,
1056 project: Option<Model<Project>>,
1057 show_excerpt_controls: bool,
1058 cx: &mut ViewContext<Self>,
1059 ) -> Self {
1060 let style = cx.text_style();
1061 let font_size = style.font_size.to_pixels(cx.rem_size());
1062 let editor = cx.view().downgrade();
1063 let fold_placeholder = FoldPlaceholder {
1064 constrain_width: true,
1065 render: Arc::new(move |fold_id, fold_range, cx| {
1066 let editor = editor.clone();
1067 div()
1068 .id(fold_id)
1069 .bg(cx.theme().colors().ghost_element_background)
1070 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1071 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1072 .rounded_sm()
1073 .size_full()
1074 .cursor_pointer()
1075 .child("⋯")
1076 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1077 .on_click(move |_, cx| {
1078 editor
1079 .update(cx, |editor, cx| {
1080 editor.unfold_ranges(
1081 &[fold_range.start..fold_range.end],
1082 true,
1083 false,
1084 cx,
1085 );
1086 cx.stop_propagation();
1087 })
1088 .ok();
1089 })
1090 .into_any()
1091 }),
1092 merge_adjacent: true,
1093 ..Default::default()
1094 };
1095 let display_map = cx.new_model(|cx| {
1096 DisplayMap::new(
1097 buffer.clone(),
1098 style.font(),
1099 font_size,
1100 None,
1101 show_excerpt_controls,
1102 FILE_HEADER_HEIGHT,
1103 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1104 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1105 fold_placeholder,
1106 cx,
1107 )
1108 });
1109
1110 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1111
1112 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1113
1114 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1115 .then(|| language_settings::SoftWrap::None);
1116
1117 let mut project_subscriptions = Vec::new();
1118 if mode == EditorMode::Full {
1119 if let Some(project) = project.as_ref() {
1120 if buffer.read(cx).is_singleton() {
1121 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1122 cx.emit(EditorEvent::TitleChanged);
1123 }));
1124 }
1125 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1126 if let project::Event::RefreshInlayHints = event {
1127 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1128 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1129 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1130 let focus_handle = editor.focus_handle(cx);
1131 if focus_handle.is_focused(cx) {
1132 let snapshot = buffer.read(cx).snapshot();
1133 for (range, snippet) in snippet_edits {
1134 let editor_range =
1135 language::range_from_lsp(*range).to_offset(&snapshot);
1136 editor
1137 .insert_snippet(&[editor_range], snippet.clone(), cx)
1138 .ok();
1139 }
1140 }
1141 }
1142 }
1143 }));
1144 if let Some(task_inventory) = project
1145 .read(cx)
1146 .task_store()
1147 .read(cx)
1148 .task_inventory()
1149 .cloned()
1150 {
1151 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1152 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1153 }));
1154 }
1155 }
1156 }
1157
1158 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1159
1160 let inlay_hint_settings =
1161 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1162 let focus_handle = cx.focus_handle();
1163 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1164 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1165 .detach();
1166 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1167 .detach();
1168 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1169
1170 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1171 Some(false)
1172 } else {
1173 None
1174 };
1175
1176 let mut code_action_providers = Vec::new();
1177 if let Some(project) = project.clone() {
1178 get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
1179 code_action_providers.push(Arc::new(project) as Arc<_>);
1180 }
1181
1182 let mut this = Self {
1183 focus_handle,
1184 show_cursor_when_unfocused: false,
1185 last_focused_descendant: None,
1186 buffer: buffer.clone(),
1187 display_map: display_map.clone(),
1188 selections,
1189 scroll_manager: ScrollManager::new(cx),
1190 columnar_selection_tail: None,
1191 add_selections_state: None,
1192 select_next_state: None,
1193 select_prev_state: None,
1194 selection_history: Default::default(),
1195 autoclose_regions: Default::default(),
1196 snippet_stack: Default::default(),
1197 select_larger_syntax_node_stack: Vec::new(),
1198 ime_transaction: Default::default(),
1199 active_diagnostics: None,
1200 soft_wrap_mode_override,
1201 completion_provider: project.clone().map(|project| Box::new(project) as _),
1202 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1203 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1204 project,
1205 blink_manager: blink_manager.clone(),
1206 show_local_selections: true,
1207 mode,
1208 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1209 show_gutter: mode == EditorMode::Full,
1210 show_line_numbers: None,
1211 use_relative_line_numbers: None,
1212 show_git_diff_gutter: None,
1213 show_code_actions: None,
1214 show_runnables: None,
1215 show_wrap_guides: None,
1216 show_indent_guides,
1217 placeholder_text: None,
1218 highlight_order: 0,
1219 highlighted_rows: HashMap::default(),
1220 background_highlights: Default::default(),
1221 gutter_highlights: TreeMap::default(),
1222 scrollbar_marker_state: ScrollbarMarkerState::default(),
1223 active_indent_guides_state: ActiveIndentGuidesState::default(),
1224 nav_history: None,
1225 context_menu: RwLock::new(None),
1226 mouse_context_menu: None,
1227 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1228 completion_tasks: Default::default(),
1229 signature_help_state: SignatureHelpState::default(),
1230 auto_signature_help: None,
1231 find_all_references_task_sources: Vec::new(),
1232 next_completion_id: 0,
1233 next_inlay_id: 0,
1234 code_action_providers,
1235 available_code_actions: Default::default(),
1236 code_actions_task: Default::default(),
1237 document_highlights_task: Default::default(),
1238 linked_editing_range_task: Default::default(),
1239 pending_rename: Default::default(),
1240 searchable: true,
1241 cursor_shape: EditorSettings::get_global(cx)
1242 .cursor_shape
1243 .unwrap_or_default(),
1244 current_line_highlight: None,
1245 autoindent_mode: Some(AutoindentMode::EachLine),
1246 collapse_matches: false,
1247 workspace: None,
1248 input_enabled: true,
1249 use_modal_editing: mode == EditorMode::Full,
1250 read_only: false,
1251 use_autoclose: true,
1252 use_auto_surround: true,
1253 auto_replace_emoji_shortcode: false,
1254 leader_peer_id: None,
1255 remote_id: None,
1256 hover_state: Default::default(),
1257 hovered_link_state: Default::default(),
1258 inline_completion_provider: None,
1259 active_inline_completion: None,
1260 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1261 diff_map: DiffMap::default(),
1262 gutter_hovered: false,
1263 pixel_position_of_newest_cursor: None,
1264 last_bounds: None,
1265 expect_bounds_change: None,
1266 gutter_dimensions: GutterDimensions::default(),
1267 style: None,
1268 show_cursor_names: false,
1269 hovered_cursors: Default::default(),
1270 next_editor_action_id: EditorActionId::default(),
1271 editor_actions: Rc::default(),
1272 show_inline_completions_override: None,
1273 enable_inline_completions: true,
1274 custom_context_menu: None,
1275 show_git_blame_gutter: false,
1276 show_git_blame_inline: false,
1277 show_selection_menu: None,
1278 show_git_blame_inline_delay_task: None,
1279 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1280 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1281 .session
1282 .restore_unsaved_buffers,
1283 blame: None,
1284 blame_subscription: None,
1285 tasks: Default::default(),
1286 _subscriptions: vec![
1287 cx.observe(&buffer, Self::on_buffer_changed),
1288 cx.subscribe(&buffer, Self::on_buffer_event),
1289 cx.observe(&display_map, Self::on_display_map_changed),
1290 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1291 cx.observe_global::<SettingsStore>(Self::settings_changed),
1292 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1293 cx.observe_window_activation(|editor, cx| {
1294 let active = cx.is_window_active();
1295 editor.blink_manager.update(cx, |blink_manager, cx| {
1296 if active {
1297 blink_manager.enable(cx);
1298 } else {
1299 blink_manager.disable(cx);
1300 }
1301 });
1302 }),
1303 ],
1304 tasks_update_task: None,
1305 linked_edit_ranges: Default::default(),
1306 previous_search_ranges: None,
1307 breadcrumb_header: None,
1308 focused_block: None,
1309 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1310 addons: HashMap::default(),
1311 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1312 text_style_refinement: None,
1313 };
1314 this.tasks_update_task = Some(this.refresh_runnables(cx));
1315 this._subscriptions.extend(project_subscriptions);
1316
1317 this.end_selection(cx);
1318 this.scroll_manager.show_scrollbar(cx);
1319
1320 if mode == EditorMode::Full {
1321 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1322 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1323
1324 if this.git_blame_inline_enabled {
1325 this.git_blame_inline_enabled = true;
1326 this.start_git_blame_inline(false, cx);
1327 }
1328 }
1329
1330 this.report_editor_event("open", None, cx);
1331 this
1332 }
1333
1334 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
1335 self.mouse_context_menu
1336 .as_ref()
1337 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1338 }
1339
1340 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
1341 let mut key_context = KeyContext::new_with_defaults();
1342 key_context.add("Editor");
1343 let mode = match self.mode {
1344 EditorMode::SingleLine { .. } => "single_line",
1345 EditorMode::AutoHeight { .. } => "auto_height",
1346 EditorMode::Full => "full",
1347 };
1348
1349 if EditorSettings::jupyter_enabled(cx) {
1350 key_context.add("jupyter");
1351 }
1352
1353 key_context.set("mode", mode);
1354 if self.pending_rename.is_some() {
1355 key_context.add("renaming");
1356 }
1357 if self.context_menu_visible() {
1358 match self.context_menu.read().as_ref() {
1359 Some(CodeContextMenu::Completions(_)) => {
1360 key_context.add("menu");
1361 key_context.add("showing_completions")
1362 }
1363 Some(CodeContextMenu::CodeActions(_)) => {
1364 key_context.add("menu");
1365 key_context.add("showing_code_actions")
1366 }
1367 None => {}
1368 }
1369 }
1370
1371 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1372 if !self.focus_handle(cx).contains_focused(cx)
1373 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
1374 {
1375 for addon in self.addons.values() {
1376 addon.extend_key_context(&mut key_context, cx)
1377 }
1378 }
1379
1380 if let Some(extension) = self
1381 .buffer
1382 .read(cx)
1383 .as_singleton()
1384 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1385 {
1386 key_context.set("extension", extension.to_string());
1387 }
1388
1389 if self.has_active_inline_completion() {
1390 key_context.add("copilot_suggestion");
1391 key_context.add("inline_completion");
1392 }
1393
1394 key_context
1395 }
1396
1397 pub fn new_file(
1398 workspace: &mut Workspace,
1399 _: &workspace::NewFile,
1400 cx: &mut ViewContext<Workspace>,
1401 ) {
1402 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
1403 "Failed to create buffer",
1404 cx,
1405 |e, _| match e.error_code() {
1406 ErrorCode::RemoteUpgradeRequired => Some(format!(
1407 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1408 e.error_tag("required").unwrap_or("the latest version")
1409 )),
1410 _ => None,
1411 },
1412 );
1413 }
1414
1415 pub fn new_in_workspace(
1416 workspace: &mut Workspace,
1417 cx: &mut ViewContext<Workspace>,
1418 ) -> Task<Result<View<Editor>>> {
1419 let project = workspace.project().clone();
1420 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1421
1422 cx.spawn(|workspace, mut cx| async move {
1423 let buffer = create.await?;
1424 workspace.update(&mut cx, |workspace, cx| {
1425 let editor =
1426 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
1427 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
1428 editor
1429 })
1430 })
1431 }
1432
1433 fn new_file_vertical(
1434 workspace: &mut Workspace,
1435 _: &workspace::NewFileSplitVertical,
1436 cx: &mut ViewContext<Workspace>,
1437 ) {
1438 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
1439 }
1440
1441 fn new_file_horizontal(
1442 workspace: &mut Workspace,
1443 _: &workspace::NewFileSplitHorizontal,
1444 cx: &mut ViewContext<Workspace>,
1445 ) {
1446 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
1447 }
1448
1449 fn new_file_in_direction(
1450 workspace: &mut Workspace,
1451 direction: SplitDirection,
1452 cx: &mut ViewContext<Workspace>,
1453 ) {
1454 let project = workspace.project().clone();
1455 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1456
1457 cx.spawn(|workspace, mut cx| async move {
1458 let buffer = create.await?;
1459 workspace.update(&mut cx, move |workspace, cx| {
1460 workspace.split_item(
1461 direction,
1462 Box::new(
1463 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
1464 ),
1465 cx,
1466 )
1467 })?;
1468 anyhow::Ok(())
1469 })
1470 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
1471 ErrorCode::RemoteUpgradeRequired => Some(format!(
1472 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1473 e.error_tag("required").unwrap_or("the latest version")
1474 )),
1475 _ => None,
1476 });
1477 }
1478
1479 pub fn leader_peer_id(&self) -> Option<PeerId> {
1480 self.leader_peer_id
1481 }
1482
1483 pub fn buffer(&self) -> &Model<MultiBuffer> {
1484 &self.buffer
1485 }
1486
1487 pub fn workspace(&self) -> Option<View<Workspace>> {
1488 self.workspace.as_ref()?.0.upgrade()
1489 }
1490
1491 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
1492 self.buffer().read(cx).title(cx)
1493 }
1494
1495 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
1496 let git_blame_gutter_max_author_length = self
1497 .render_git_blame_gutter(cx)
1498 .then(|| {
1499 if let Some(blame) = self.blame.as_ref() {
1500 let max_author_length =
1501 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1502 Some(max_author_length)
1503 } else {
1504 None
1505 }
1506 })
1507 .flatten();
1508
1509 EditorSnapshot {
1510 mode: self.mode,
1511 show_gutter: self.show_gutter,
1512 show_line_numbers: self.show_line_numbers,
1513 show_git_diff_gutter: self.show_git_diff_gutter,
1514 show_code_actions: self.show_code_actions,
1515 show_runnables: self.show_runnables,
1516 git_blame_gutter_max_author_length,
1517 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1518 scroll_anchor: self.scroll_manager.anchor(),
1519 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1520 placeholder_text: self.placeholder_text.clone(),
1521 diff_map: self.diff_map.snapshot(),
1522 is_focused: self.focus_handle.is_focused(cx),
1523 current_line_highlight: self
1524 .current_line_highlight
1525 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1526 gutter_hovered: self.gutter_hovered,
1527 }
1528 }
1529
1530 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
1531 self.buffer.read(cx).language_at(point, cx)
1532 }
1533
1534 pub fn file_at<T: ToOffset>(
1535 &self,
1536 point: T,
1537 cx: &AppContext,
1538 ) -> Option<Arc<dyn language::File>> {
1539 self.buffer.read(cx).read(cx).file_at(point).cloned()
1540 }
1541
1542 pub fn active_excerpt(
1543 &self,
1544 cx: &AppContext,
1545 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
1546 self.buffer
1547 .read(cx)
1548 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1549 }
1550
1551 pub fn mode(&self) -> EditorMode {
1552 self.mode
1553 }
1554
1555 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1556 self.collaboration_hub.as_deref()
1557 }
1558
1559 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1560 self.collaboration_hub = Some(hub);
1561 }
1562
1563 pub fn set_custom_context_menu(
1564 &mut self,
1565 f: impl 'static
1566 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
1567 ) {
1568 self.custom_context_menu = Some(Box::new(f))
1569 }
1570
1571 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1572 self.completion_provider = provider;
1573 }
1574
1575 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1576 self.semantics_provider.clone()
1577 }
1578
1579 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1580 self.semantics_provider = provider;
1581 }
1582
1583 pub fn set_inline_completion_provider<T>(
1584 &mut self,
1585 provider: Option<Model<T>>,
1586 cx: &mut ViewContext<Self>,
1587 ) where
1588 T: InlineCompletionProvider,
1589 {
1590 self.inline_completion_provider =
1591 provider.map(|provider| RegisteredInlineCompletionProvider {
1592 _subscription: cx.observe(&provider, |this, _, cx| {
1593 if this.focus_handle.is_focused(cx) {
1594 this.update_visible_inline_completion(cx);
1595 }
1596 }),
1597 provider: Arc::new(provider),
1598 });
1599 self.refresh_inline_completion(false, false, cx);
1600 }
1601
1602 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
1603 self.placeholder_text.as_deref()
1604 }
1605
1606 pub fn set_placeholder_text(
1607 &mut self,
1608 placeholder_text: impl Into<Arc<str>>,
1609 cx: &mut ViewContext<Self>,
1610 ) {
1611 let placeholder_text = Some(placeholder_text.into());
1612 if self.placeholder_text != placeholder_text {
1613 self.placeholder_text = placeholder_text;
1614 cx.notify();
1615 }
1616 }
1617
1618 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
1619 self.cursor_shape = cursor_shape;
1620
1621 // Disrupt blink for immediate user feedback that the cursor shape has changed
1622 self.blink_manager.update(cx, BlinkManager::show_cursor);
1623
1624 cx.notify();
1625 }
1626
1627 pub fn set_current_line_highlight(
1628 &mut self,
1629 current_line_highlight: Option<CurrentLineHighlight>,
1630 ) {
1631 self.current_line_highlight = current_line_highlight;
1632 }
1633
1634 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1635 self.collapse_matches = collapse_matches;
1636 }
1637
1638 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1639 if self.collapse_matches {
1640 return range.start..range.start;
1641 }
1642 range.clone()
1643 }
1644
1645 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
1646 if self.display_map.read(cx).clip_at_line_ends != clip {
1647 self.display_map
1648 .update(cx, |map, _| map.clip_at_line_ends = clip);
1649 }
1650 }
1651
1652 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1653 self.input_enabled = input_enabled;
1654 }
1655
1656 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
1657 self.enable_inline_completions = enabled;
1658 }
1659
1660 pub fn set_autoindent(&mut self, autoindent: bool) {
1661 if autoindent {
1662 self.autoindent_mode = Some(AutoindentMode::EachLine);
1663 } else {
1664 self.autoindent_mode = None;
1665 }
1666 }
1667
1668 pub fn read_only(&self, cx: &AppContext) -> bool {
1669 self.read_only || self.buffer.read(cx).read_only()
1670 }
1671
1672 pub fn set_read_only(&mut self, read_only: bool) {
1673 self.read_only = read_only;
1674 }
1675
1676 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1677 self.use_autoclose = autoclose;
1678 }
1679
1680 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1681 self.use_auto_surround = auto_surround;
1682 }
1683
1684 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1685 self.auto_replace_emoji_shortcode = auto_replace;
1686 }
1687
1688 pub fn toggle_inline_completions(
1689 &mut self,
1690 _: &ToggleInlineCompletions,
1691 cx: &mut ViewContext<Self>,
1692 ) {
1693 if self.show_inline_completions_override.is_some() {
1694 self.set_show_inline_completions(None, cx);
1695 } else {
1696 let cursor = self.selections.newest_anchor().head();
1697 if let Some((buffer, cursor_buffer_position)) =
1698 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1699 {
1700 let show_inline_completions =
1701 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
1702 self.set_show_inline_completions(Some(show_inline_completions), cx);
1703 }
1704 }
1705 }
1706
1707 pub fn set_show_inline_completions(
1708 &mut self,
1709 show_inline_completions: Option<bool>,
1710 cx: &mut ViewContext<Self>,
1711 ) {
1712 self.show_inline_completions_override = show_inline_completions;
1713 self.refresh_inline_completion(false, true, cx);
1714 }
1715
1716 fn should_show_inline_completions(
1717 &self,
1718 buffer: &Model<Buffer>,
1719 buffer_position: language::Anchor,
1720 cx: &AppContext,
1721 ) -> bool {
1722 if !self.snippet_stack.is_empty() {
1723 return false;
1724 }
1725
1726 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
1727 return false;
1728 }
1729
1730 if let Some(provider) = self.inline_completion_provider() {
1731 if let Some(show_inline_completions) = self.show_inline_completions_override {
1732 show_inline_completions
1733 } else {
1734 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
1735 }
1736 } else {
1737 false
1738 }
1739 }
1740
1741 fn inline_completions_disabled_in_scope(
1742 &self,
1743 buffer: &Model<Buffer>,
1744 buffer_position: language::Anchor,
1745 cx: &AppContext,
1746 ) -> bool {
1747 let snapshot = buffer.read(cx).snapshot();
1748 let settings = snapshot.settings_at(buffer_position, cx);
1749
1750 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1751 return false;
1752 };
1753
1754 scope.override_name().map_or(false, |scope_name| {
1755 settings
1756 .inline_completions_disabled_in
1757 .iter()
1758 .any(|s| s == scope_name)
1759 })
1760 }
1761
1762 pub fn set_use_modal_editing(&mut self, to: bool) {
1763 self.use_modal_editing = to;
1764 }
1765
1766 pub fn use_modal_editing(&self) -> bool {
1767 self.use_modal_editing
1768 }
1769
1770 fn selections_did_change(
1771 &mut self,
1772 local: bool,
1773 old_cursor_position: &Anchor,
1774 show_completions: bool,
1775 cx: &mut ViewContext<Self>,
1776 ) {
1777 cx.invalidate_character_coordinates();
1778
1779 // Copy selections to primary selection buffer
1780 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1781 if local {
1782 let selections = self.selections.all::<usize>(cx);
1783 let buffer_handle = self.buffer.read(cx).read(cx);
1784
1785 let mut text = String::new();
1786 for (index, selection) in selections.iter().enumerate() {
1787 let text_for_selection = buffer_handle
1788 .text_for_range(selection.start..selection.end)
1789 .collect::<String>();
1790
1791 text.push_str(&text_for_selection);
1792 if index != selections.len() - 1 {
1793 text.push('\n');
1794 }
1795 }
1796
1797 if !text.is_empty() {
1798 cx.write_to_primary(ClipboardItem::new_string(text));
1799 }
1800 }
1801
1802 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
1803 self.buffer.update(cx, |buffer, cx| {
1804 buffer.set_active_selections(
1805 &self.selections.disjoint_anchors(),
1806 self.selections.line_mode,
1807 self.cursor_shape,
1808 cx,
1809 )
1810 });
1811 }
1812 let display_map = self
1813 .display_map
1814 .update(cx, |display_map, cx| display_map.snapshot(cx));
1815 let buffer = &display_map.buffer_snapshot;
1816 self.add_selections_state = None;
1817 self.select_next_state = None;
1818 self.select_prev_state = None;
1819 self.select_larger_syntax_node_stack.clear();
1820 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1821 self.snippet_stack
1822 .invalidate(&self.selections.disjoint_anchors(), buffer);
1823 self.take_rename(false, cx);
1824
1825 let new_cursor_position = self.selections.newest_anchor().head();
1826
1827 self.push_to_nav_history(
1828 *old_cursor_position,
1829 Some(new_cursor_position.to_point(buffer)),
1830 cx,
1831 );
1832
1833 if local {
1834 let new_cursor_position = self.selections.newest_anchor().head();
1835 let mut context_menu = self.context_menu.write();
1836 let completion_menu = match context_menu.as_ref() {
1837 Some(CodeContextMenu::Completions(menu)) => Some(menu),
1838
1839 _ => {
1840 *context_menu = None;
1841 None
1842 }
1843 };
1844
1845 if let Some(completion_menu) = completion_menu {
1846 let cursor_position = new_cursor_position.to_offset(buffer);
1847 let (word_range, kind) =
1848 buffer.surrounding_word(completion_menu.initial_position, true);
1849 if kind == Some(CharKind::Word)
1850 && word_range.to_inclusive().contains(&cursor_position)
1851 {
1852 let mut completion_menu = completion_menu.clone();
1853 drop(context_menu);
1854
1855 let query = Self::completion_query(buffer, cursor_position);
1856 cx.spawn(move |this, mut cx| async move {
1857 completion_menu
1858 .filter(query.as_deref(), cx.background_executor().clone())
1859 .await;
1860
1861 this.update(&mut cx, |this, cx| {
1862 let mut context_menu = this.context_menu.write();
1863 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
1864 else {
1865 return;
1866 };
1867
1868 if menu.id > completion_menu.id {
1869 return;
1870 }
1871
1872 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
1873 drop(context_menu);
1874 cx.notify();
1875 })
1876 })
1877 .detach();
1878
1879 if show_completions {
1880 self.show_completions(&ShowCompletions { trigger: None }, cx);
1881 }
1882 } else {
1883 drop(context_menu);
1884 self.hide_context_menu(cx);
1885 }
1886 } else {
1887 drop(context_menu);
1888 }
1889
1890 hide_hover(self, cx);
1891
1892 if old_cursor_position.to_display_point(&display_map).row()
1893 != new_cursor_position.to_display_point(&display_map).row()
1894 {
1895 self.available_code_actions.take();
1896 }
1897 self.refresh_code_actions(cx);
1898 self.refresh_document_highlights(cx);
1899 refresh_matching_bracket_highlights(self, cx);
1900 self.update_visible_inline_completion(cx);
1901 linked_editing_ranges::refresh_linked_ranges(self, cx);
1902 if self.git_blame_inline_enabled {
1903 self.start_inline_blame_timer(cx);
1904 }
1905 }
1906
1907 self.blink_manager.update(cx, BlinkManager::pause_blinking);
1908 cx.emit(EditorEvent::SelectionsChanged { local });
1909
1910 if self.selections.disjoint_anchors().len() == 1 {
1911 cx.emit(SearchEvent::ActiveMatchChanged)
1912 }
1913 cx.notify();
1914 }
1915
1916 pub fn change_selections<R>(
1917 &mut self,
1918 autoscroll: Option<Autoscroll>,
1919 cx: &mut ViewContext<Self>,
1920 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
1921 ) -> R {
1922 self.change_selections_inner(autoscroll, true, cx, change)
1923 }
1924
1925 pub fn change_selections_inner<R>(
1926 &mut self,
1927 autoscroll: Option<Autoscroll>,
1928 request_completions: bool,
1929 cx: &mut ViewContext<Self>,
1930 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
1931 ) -> R {
1932 let old_cursor_position = self.selections.newest_anchor().head();
1933 self.push_to_selection_history();
1934
1935 let (changed, result) = self.selections.change_with(cx, change);
1936
1937 if changed {
1938 if let Some(autoscroll) = autoscroll {
1939 self.request_autoscroll(autoscroll, cx);
1940 }
1941 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
1942
1943 if self.should_open_signature_help_automatically(
1944 &old_cursor_position,
1945 self.signature_help_state.backspace_pressed(),
1946 cx,
1947 ) {
1948 self.show_signature_help(&ShowSignatureHelp, cx);
1949 }
1950 self.signature_help_state.set_backspace_pressed(false);
1951 }
1952
1953 result
1954 }
1955
1956 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
1957 where
1958 I: IntoIterator<Item = (Range<S>, T)>,
1959 S: ToOffset,
1960 T: Into<Arc<str>>,
1961 {
1962 if self.read_only(cx) {
1963 return;
1964 }
1965
1966 self.buffer
1967 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
1968 }
1969
1970 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
1971 where
1972 I: IntoIterator<Item = (Range<S>, T)>,
1973 S: ToOffset,
1974 T: Into<Arc<str>>,
1975 {
1976 if self.read_only(cx) {
1977 return;
1978 }
1979
1980 self.buffer.update(cx, |buffer, cx| {
1981 buffer.edit(edits, self.autoindent_mode.clone(), cx)
1982 });
1983 }
1984
1985 pub fn edit_with_block_indent<I, S, T>(
1986 &mut self,
1987 edits: I,
1988 original_indent_columns: Vec<u32>,
1989 cx: &mut ViewContext<Self>,
1990 ) where
1991 I: IntoIterator<Item = (Range<S>, T)>,
1992 S: ToOffset,
1993 T: Into<Arc<str>>,
1994 {
1995 if self.read_only(cx) {
1996 return;
1997 }
1998
1999 self.buffer.update(cx, |buffer, cx| {
2000 buffer.edit(
2001 edits,
2002 Some(AutoindentMode::Block {
2003 original_indent_columns,
2004 }),
2005 cx,
2006 )
2007 });
2008 }
2009
2010 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2011 self.hide_context_menu(cx);
2012
2013 match phase {
2014 SelectPhase::Begin {
2015 position,
2016 add,
2017 click_count,
2018 } => self.begin_selection(position, add, click_count, cx),
2019 SelectPhase::BeginColumnar {
2020 position,
2021 goal_column,
2022 reset,
2023 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2024 SelectPhase::Extend {
2025 position,
2026 click_count,
2027 } => self.extend_selection(position, click_count, cx),
2028 SelectPhase::Update {
2029 position,
2030 goal_column,
2031 scroll_delta,
2032 } => self.update_selection(position, goal_column, scroll_delta, cx),
2033 SelectPhase::End => self.end_selection(cx),
2034 }
2035 }
2036
2037 fn extend_selection(
2038 &mut self,
2039 position: DisplayPoint,
2040 click_count: usize,
2041 cx: &mut ViewContext<Self>,
2042 ) {
2043 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2044 let tail = self.selections.newest::<usize>(cx).tail();
2045 self.begin_selection(position, false, click_count, cx);
2046
2047 let position = position.to_offset(&display_map, Bias::Left);
2048 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2049
2050 let mut pending_selection = self
2051 .selections
2052 .pending_anchor()
2053 .expect("extend_selection not called with pending selection");
2054 if position >= tail {
2055 pending_selection.start = tail_anchor;
2056 } else {
2057 pending_selection.end = tail_anchor;
2058 pending_selection.reversed = true;
2059 }
2060
2061 let mut pending_mode = self.selections.pending_mode().unwrap();
2062 match &mut pending_mode {
2063 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2064 _ => {}
2065 }
2066
2067 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2068 s.set_pending(pending_selection, pending_mode)
2069 });
2070 }
2071
2072 fn begin_selection(
2073 &mut self,
2074 position: DisplayPoint,
2075 add: bool,
2076 click_count: usize,
2077 cx: &mut ViewContext<Self>,
2078 ) {
2079 if !self.focus_handle.is_focused(cx) {
2080 self.last_focused_descendant = None;
2081 cx.focus(&self.focus_handle);
2082 }
2083
2084 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2085 let buffer = &display_map.buffer_snapshot;
2086 let newest_selection = self.selections.newest_anchor().clone();
2087 let position = display_map.clip_point(position, Bias::Left);
2088
2089 let start;
2090 let end;
2091 let mode;
2092 let mut auto_scroll;
2093 match click_count {
2094 1 => {
2095 start = buffer.anchor_before(position.to_point(&display_map));
2096 end = start;
2097 mode = SelectMode::Character;
2098 auto_scroll = true;
2099 }
2100 2 => {
2101 let range = movement::surrounding_word(&display_map, position);
2102 start = buffer.anchor_before(range.start.to_point(&display_map));
2103 end = buffer.anchor_before(range.end.to_point(&display_map));
2104 mode = SelectMode::Word(start..end);
2105 auto_scroll = true;
2106 }
2107 3 => {
2108 let position = display_map
2109 .clip_point(position, Bias::Left)
2110 .to_point(&display_map);
2111 let line_start = display_map.prev_line_boundary(position).0;
2112 let next_line_start = buffer.clip_point(
2113 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2114 Bias::Left,
2115 );
2116 start = buffer.anchor_before(line_start);
2117 end = buffer.anchor_before(next_line_start);
2118 mode = SelectMode::Line(start..end);
2119 auto_scroll = true;
2120 }
2121 _ => {
2122 start = buffer.anchor_before(0);
2123 end = buffer.anchor_before(buffer.len());
2124 mode = SelectMode::All;
2125 auto_scroll = false;
2126 }
2127 }
2128 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2129
2130 let point_to_delete: Option<usize> = {
2131 let selected_points: Vec<Selection<Point>> =
2132 self.selections.disjoint_in_range(start..end, cx);
2133
2134 if !add || click_count > 1 {
2135 None
2136 } else if !selected_points.is_empty() {
2137 Some(selected_points[0].id)
2138 } else {
2139 let clicked_point_already_selected =
2140 self.selections.disjoint.iter().find(|selection| {
2141 selection.start.to_point(buffer) == start.to_point(buffer)
2142 || selection.end.to_point(buffer) == end.to_point(buffer)
2143 });
2144
2145 clicked_point_already_selected.map(|selection| selection.id)
2146 }
2147 };
2148
2149 let selections_count = self.selections.count();
2150
2151 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2152 if let Some(point_to_delete) = point_to_delete {
2153 s.delete(point_to_delete);
2154
2155 if selections_count == 1 {
2156 s.set_pending_anchor_range(start..end, mode);
2157 }
2158 } else {
2159 if !add {
2160 s.clear_disjoint();
2161 } else if click_count > 1 {
2162 s.delete(newest_selection.id)
2163 }
2164
2165 s.set_pending_anchor_range(start..end, mode);
2166 }
2167 });
2168 }
2169
2170 fn begin_columnar_selection(
2171 &mut self,
2172 position: DisplayPoint,
2173 goal_column: u32,
2174 reset: bool,
2175 cx: &mut ViewContext<Self>,
2176 ) {
2177 if !self.focus_handle.is_focused(cx) {
2178 self.last_focused_descendant = None;
2179 cx.focus(&self.focus_handle);
2180 }
2181
2182 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2183
2184 if reset {
2185 let pointer_position = display_map
2186 .buffer_snapshot
2187 .anchor_before(position.to_point(&display_map));
2188
2189 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2190 s.clear_disjoint();
2191 s.set_pending_anchor_range(
2192 pointer_position..pointer_position,
2193 SelectMode::Character,
2194 );
2195 });
2196 }
2197
2198 let tail = self.selections.newest::<Point>(cx).tail();
2199 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2200
2201 if !reset {
2202 self.select_columns(
2203 tail.to_display_point(&display_map),
2204 position,
2205 goal_column,
2206 &display_map,
2207 cx,
2208 );
2209 }
2210 }
2211
2212 fn update_selection(
2213 &mut self,
2214 position: DisplayPoint,
2215 goal_column: u32,
2216 scroll_delta: gpui::Point<f32>,
2217 cx: &mut ViewContext<Self>,
2218 ) {
2219 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2220
2221 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2222 let tail = tail.to_display_point(&display_map);
2223 self.select_columns(tail, position, goal_column, &display_map, cx);
2224 } else if let Some(mut pending) = self.selections.pending_anchor() {
2225 let buffer = self.buffer.read(cx).snapshot(cx);
2226 let head;
2227 let tail;
2228 let mode = self.selections.pending_mode().unwrap();
2229 match &mode {
2230 SelectMode::Character => {
2231 head = position.to_point(&display_map);
2232 tail = pending.tail().to_point(&buffer);
2233 }
2234 SelectMode::Word(original_range) => {
2235 let original_display_range = original_range.start.to_display_point(&display_map)
2236 ..original_range.end.to_display_point(&display_map);
2237 let original_buffer_range = original_display_range.start.to_point(&display_map)
2238 ..original_display_range.end.to_point(&display_map);
2239 if movement::is_inside_word(&display_map, position)
2240 || original_display_range.contains(&position)
2241 {
2242 let word_range = movement::surrounding_word(&display_map, position);
2243 if word_range.start < original_display_range.start {
2244 head = word_range.start.to_point(&display_map);
2245 } else {
2246 head = word_range.end.to_point(&display_map);
2247 }
2248 } else {
2249 head = position.to_point(&display_map);
2250 }
2251
2252 if head <= original_buffer_range.start {
2253 tail = original_buffer_range.end;
2254 } else {
2255 tail = original_buffer_range.start;
2256 }
2257 }
2258 SelectMode::Line(original_range) => {
2259 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2260
2261 let position = display_map
2262 .clip_point(position, Bias::Left)
2263 .to_point(&display_map);
2264 let line_start = display_map.prev_line_boundary(position).0;
2265 let next_line_start = buffer.clip_point(
2266 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2267 Bias::Left,
2268 );
2269
2270 if line_start < original_range.start {
2271 head = line_start
2272 } else {
2273 head = next_line_start
2274 }
2275
2276 if head <= original_range.start {
2277 tail = original_range.end;
2278 } else {
2279 tail = original_range.start;
2280 }
2281 }
2282 SelectMode::All => {
2283 return;
2284 }
2285 };
2286
2287 if head < tail {
2288 pending.start = buffer.anchor_before(head);
2289 pending.end = buffer.anchor_before(tail);
2290 pending.reversed = true;
2291 } else {
2292 pending.start = buffer.anchor_before(tail);
2293 pending.end = buffer.anchor_before(head);
2294 pending.reversed = false;
2295 }
2296
2297 self.change_selections(None, cx, |s| {
2298 s.set_pending(pending, mode);
2299 });
2300 } else {
2301 log::error!("update_selection dispatched with no pending selection");
2302 return;
2303 }
2304
2305 self.apply_scroll_delta(scroll_delta, cx);
2306 cx.notify();
2307 }
2308
2309 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2310 self.columnar_selection_tail.take();
2311 if self.selections.pending_anchor().is_some() {
2312 let selections = self.selections.all::<usize>(cx);
2313 self.change_selections(None, cx, |s| {
2314 s.select(selections);
2315 s.clear_pending();
2316 });
2317 }
2318 }
2319
2320 fn select_columns(
2321 &mut self,
2322 tail: DisplayPoint,
2323 head: DisplayPoint,
2324 goal_column: u32,
2325 display_map: &DisplaySnapshot,
2326 cx: &mut ViewContext<Self>,
2327 ) {
2328 let start_row = cmp::min(tail.row(), head.row());
2329 let end_row = cmp::max(tail.row(), head.row());
2330 let start_column = cmp::min(tail.column(), goal_column);
2331 let end_column = cmp::max(tail.column(), goal_column);
2332 let reversed = start_column < tail.column();
2333
2334 let selection_ranges = (start_row.0..=end_row.0)
2335 .map(DisplayRow)
2336 .filter_map(|row| {
2337 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2338 let start = display_map
2339 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2340 .to_point(display_map);
2341 let end = display_map
2342 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2343 .to_point(display_map);
2344 if reversed {
2345 Some(end..start)
2346 } else {
2347 Some(start..end)
2348 }
2349 } else {
2350 None
2351 }
2352 })
2353 .collect::<Vec<_>>();
2354
2355 self.change_selections(None, cx, |s| {
2356 s.select_ranges(selection_ranges);
2357 });
2358 cx.notify();
2359 }
2360
2361 pub fn has_pending_nonempty_selection(&self) -> bool {
2362 let pending_nonempty_selection = match self.selections.pending_anchor() {
2363 Some(Selection { start, end, .. }) => start != end,
2364 None => false,
2365 };
2366
2367 pending_nonempty_selection
2368 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2369 }
2370
2371 pub fn has_pending_selection(&self) -> bool {
2372 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2373 }
2374
2375 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2376 if self.clear_expanded_diff_hunks(cx) {
2377 cx.notify();
2378 return;
2379 }
2380 if self.dismiss_menus_and_popups(true, cx) {
2381 return;
2382 }
2383
2384 if self.mode == EditorMode::Full
2385 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
2386 {
2387 return;
2388 }
2389
2390 cx.propagate();
2391 }
2392
2393 pub fn dismiss_menus_and_popups(
2394 &mut self,
2395 should_report_inline_completion_event: bool,
2396 cx: &mut ViewContext<Self>,
2397 ) -> bool {
2398 if self.take_rename(false, cx).is_some() {
2399 return true;
2400 }
2401
2402 if hide_hover(self, cx) {
2403 return true;
2404 }
2405
2406 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2407 return true;
2408 }
2409
2410 if self.hide_context_menu(cx).is_some() {
2411 return true;
2412 }
2413
2414 if self.mouse_context_menu.take().is_some() {
2415 return true;
2416 }
2417
2418 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2419 return true;
2420 }
2421
2422 if self.snippet_stack.pop().is_some() {
2423 return true;
2424 }
2425
2426 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2427 self.dismiss_diagnostics(cx);
2428 return true;
2429 }
2430
2431 false
2432 }
2433
2434 fn linked_editing_ranges_for(
2435 &self,
2436 selection: Range<text::Anchor>,
2437 cx: &AppContext,
2438 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2439 if self.linked_edit_ranges.is_empty() {
2440 return None;
2441 }
2442 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2443 selection.end.buffer_id.and_then(|end_buffer_id| {
2444 if selection.start.buffer_id != Some(end_buffer_id) {
2445 return None;
2446 }
2447 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2448 let snapshot = buffer.read(cx).snapshot();
2449 self.linked_edit_ranges
2450 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2451 .map(|ranges| (ranges, snapshot, buffer))
2452 })?;
2453 use text::ToOffset as TO;
2454 // find offset from the start of current range to current cursor position
2455 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2456
2457 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2458 let start_difference = start_offset - start_byte_offset;
2459 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2460 let end_difference = end_offset - start_byte_offset;
2461 // Current range has associated linked ranges.
2462 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2463 for range in linked_ranges.iter() {
2464 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2465 let end_offset = start_offset + end_difference;
2466 let start_offset = start_offset + start_difference;
2467 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2468 continue;
2469 }
2470 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
2471 if s.start.buffer_id != selection.start.buffer_id
2472 || s.end.buffer_id != selection.end.buffer_id
2473 {
2474 return false;
2475 }
2476 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2477 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2478 }) {
2479 continue;
2480 }
2481 let start = buffer_snapshot.anchor_after(start_offset);
2482 let end = buffer_snapshot.anchor_after(end_offset);
2483 linked_edits
2484 .entry(buffer.clone())
2485 .or_default()
2486 .push(start..end);
2487 }
2488 Some(linked_edits)
2489 }
2490
2491 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2492 let text: Arc<str> = text.into();
2493
2494 if self.read_only(cx) {
2495 return;
2496 }
2497
2498 let selections = self.selections.all_adjusted(cx);
2499 let mut bracket_inserted = false;
2500 let mut edits = Vec::new();
2501 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2502 let mut new_selections = Vec::with_capacity(selections.len());
2503 let mut new_autoclose_regions = Vec::new();
2504 let snapshot = self.buffer.read(cx).read(cx);
2505
2506 for (selection, autoclose_region) in
2507 self.selections_with_autoclose_regions(selections, &snapshot)
2508 {
2509 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2510 // Determine if the inserted text matches the opening or closing
2511 // bracket of any of this language's bracket pairs.
2512 let mut bracket_pair = None;
2513 let mut is_bracket_pair_start = false;
2514 let mut is_bracket_pair_end = false;
2515 if !text.is_empty() {
2516 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2517 // and they are removing the character that triggered IME popup.
2518 for (pair, enabled) in scope.brackets() {
2519 if !pair.close && !pair.surround {
2520 continue;
2521 }
2522
2523 if enabled && pair.start.ends_with(text.as_ref()) {
2524 let prefix_len = pair.start.len() - text.len();
2525 let preceding_text_matches_prefix = prefix_len == 0
2526 || (selection.start.column >= (prefix_len as u32)
2527 && snapshot.contains_str_at(
2528 Point::new(
2529 selection.start.row,
2530 selection.start.column - (prefix_len as u32),
2531 ),
2532 &pair.start[..prefix_len],
2533 ));
2534 if preceding_text_matches_prefix {
2535 bracket_pair = Some(pair.clone());
2536 is_bracket_pair_start = true;
2537 break;
2538 }
2539 }
2540 if pair.end.as_str() == text.as_ref() {
2541 bracket_pair = Some(pair.clone());
2542 is_bracket_pair_end = true;
2543 break;
2544 }
2545 }
2546 }
2547
2548 if let Some(bracket_pair) = bracket_pair {
2549 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2550 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2551 let auto_surround =
2552 self.use_auto_surround && snapshot_settings.use_auto_surround;
2553 if selection.is_empty() {
2554 if is_bracket_pair_start {
2555 // If the inserted text is a suffix of an opening bracket and the
2556 // selection is preceded by the rest of the opening bracket, then
2557 // insert the closing bracket.
2558 let following_text_allows_autoclose = snapshot
2559 .chars_at(selection.start)
2560 .next()
2561 .map_or(true, |c| scope.should_autoclose_before(c));
2562
2563 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2564 && bracket_pair.start.len() == 1
2565 {
2566 let target = bracket_pair.start.chars().next().unwrap();
2567 let current_line_count = snapshot
2568 .reversed_chars_at(selection.start)
2569 .take_while(|&c| c != '\n')
2570 .filter(|&c| c == target)
2571 .count();
2572 current_line_count % 2 == 1
2573 } else {
2574 false
2575 };
2576
2577 if autoclose
2578 && bracket_pair.close
2579 && following_text_allows_autoclose
2580 && !is_closing_quote
2581 {
2582 let anchor = snapshot.anchor_before(selection.end);
2583 new_selections.push((selection.map(|_| anchor), text.len()));
2584 new_autoclose_regions.push((
2585 anchor,
2586 text.len(),
2587 selection.id,
2588 bracket_pair.clone(),
2589 ));
2590 edits.push((
2591 selection.range(),
2592 format!("{}{}", text, bracket_pair.end).into(),
2593 ));
2594 bracket_inserted = true;
2595 continue;
2596 }
2597 }
2598
2599 if let Some(region) = autoclose_region {
2600 // If the selection is followed by an auto-inserted closing bracket,
2601 // then don't insert that closing bracket again; just move the selection
2602 // past the closing bracket.
2603 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2604 && text.as_ref() == region.pair.end.as_str();
2605 if should_skip {
2606 let anchor = snapshot.anchor_after(selection.end);
2607 new_selections
2608 .push((selection.map(|_| anchor), region.pair.end.len()));
2609 continue;
2610 }
2611 }
2612
2613 let always_treat_brackets_as_autoclosed = snapshot
2614 .settings_at(selection.start, cx)
2615 .always_treat_brackets_as_autoclosed;
2616 if always_treat_brackets_as_autoclosed
2617 && is_bracket_pair_end
2618 && snapshot.contains_str_at(selection.end, text.as_ref())
2619 {
2620 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2621 // and the inserted text is a closing bracket and the selection is followed
2622 // by the closing bracket then move the selection past the closing bracket.
2623 let anchor = snapshot.anchor_after(selection.end);
2624 new_selections.push((selection.map(|_| anchor), text.len()));
2625 continue;
2626 }
2627 }
2628 // If an opening bracket is 1 character long and is typed while
2629 // text is selected, then surround that text with the bracket pair.
2630 else if auto_surround
2631 && bracket_pair.surround
2632 && is_bracket_pair_start
2633 && bracket_pair.start.chars().count() == 1
2634 {
2635 edits.push((selection.start..selection.start, text.clone()));
2636 edits.push((
2637 selection.end..selection.end,
2638 bracket_pair.end.as_str().into(),
2639 ));
2640 bracket_inserted = true;
2641 new_selections.push((
2642 Selection {
2643 id: selection.id,
2644 start: snapshot.anchor_after(selection.start),
2645 end: snapshot.anchor_before(selection.end),
2646 reversed: selection.reversed,
2647 goal: selection.goal,
2648 },
2649 0,
2650 ));
2651 continue;
2652 }
2653 }
2654 }
2655
2656 if self.auto_replace_emoji_shortcode
2657 && selection.is_empty()
2658 && text.as_ref().ends_with(':')
2659 {
2660 if let Some(possible_emoji_short_code) =
2661 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2662 {
2663 if !possible_emoji_short_code.is_empty() {
2664 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2665 let emoji_shortcode_start = Point::new(
2666 selection.start.row,
2667 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2668 );
2669
2670 // Remove shortcode from buffer
2671 edits.push((
2672 emoji_shortcode_start..selection.start,
2673 "".to_string().into(),
2674 ));
2675 new_selections.push((
2676 Selection {
2677 id: selection.id,
2678 start: snapshot.anchor_after(emoji_shortcode_start),
2679 end: snapshot.anchor_before(selection.start),
2680 reversed: selection.reversed,
2681 goal: selection.goal,
2682 },
2683 0,
2684 ));
2685
2686 // Insert emoji
2687 let selection_start_anchor = snapshot.anchor_after(selection.start);
2688 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2689 edits.push((selection.start..selection.end, emoji.to_string().into()));
2690
2691 continue;
2692 }
2693 }
2694 }
2695 }
2696
2697 // If not handling any auto-close operation, then just replace the selected
2698 // text with the given input and move the selection to the end of the
2699 // newly inserted text.
2700 let anchor = snapshot.anchor_after(selection.end);
2701 if !self.linked_edit_ranges.is_empty() {
2702 let start_anchor = snapshot.anchor_before(selection.start);
2703
2704 let is_word_char = text.chars().next().map_or(true, |char| {
2705 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2706 classifier.is_word(char)
2707 });
2708
2709 if is_word_char {
2710 if let Some(ranges) = self
2711 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2712 {
2713 for (buffer, edits) in ranges {
2714 linked_edits
2715 .entry(buffer.clone())
2716 .or_default()
2717 .extend(edits.into_iter().map(|range| (range, text.clone())));
2718 }
2719 }
2720 }
2721 }
2722
2723 new_selections.push((selection.map(|_| anchor), 0));
2724 edits.push((selection.start..selection.end, text.clone()));
2725 }
2726
2727 drop(snapshot);
2728
2729 self.transact(cx, |this, cx| {
2730 this.buffer.update(cx, |buffer, cx| {
2731 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2732 });
2733 for (buffer, edits) in linked_edits {
2734 buffer.update(cx, |buffer, cx| {
2735 let snapshot = buffer.snapshot();
2736 let edits = edits
2737 .into_iter()
2738 .map(|(range, text)| {
2739 use text::ToPoint as TP;
2740 let end_point = TP::to_point(&range.end, &snapshot);
2741 let start_point = TP::to_point(&range.start, &snapshot);
2742 (start_point..end_point, text)
2743 })
2744 .sorted_by_key(|(range, _)| range.start)
2745 .collect::<Vec<_>>();
2746 buffer.edit(edits, None, cx);
2747 })
2748 }
2749 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2750 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2751 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2752 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2753 .zip(new_selection_deltas)
2754 .map(|(selection, delta)| Selection {
2755 id: selection.id,
2756 start: selection.start + delta,
2757 end: selection.end + delta,
2758 reversed: selection.reversed,
2759 goal: SelectionGoal::None,
2760 })
2761 .collect::<Vec<_>>();
2762
2763 let mut i = 0;
2764 for (position, delta, selection_id, pair) in new_autoclose_regions {
2765 let position = position.to_offset(&map.buffer_snapshot) + delta;
2766 let start = map.buffer_snapshot.anchor_before(position);
2767 let end = map.buffer_snapshot.anchor_after(position);
2768 while let Some(existing_state) = this.autoclose_regions.get(i) {
2769 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2770 Ordering::Less => i += 1,
2771 Ordering::Greater => break,
2772 Ordering::Equal => {
2773 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2774 Ordering::Less => i += 1,
2775 Ordering::Equal => break,
2776 Ordering::Greater => break,
2777 }
2778 }
2779 }
2780 }
2781 this.autoclose_regions.insert(
2782 i,
2783 AutocloseRegion {
2784 selection_id,
2785 range: start..end,
2786 pair,
2787 },
2788 );
2789 }
2790
2791 let had_active_inline_completion = this.has_active_inline_completion();
2792 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
2793 s.select(new_selections)
2794 });
2795
2796 if !bracket_inserted {
2797 if let Some(on_type_format_task) =
2798 this.trigger_on_type_formatting(text.to_string(), cx)
2799 {
2800 on_type_format_task.detach_and_log_err(cx);
2801 }
2802 }
2803
2804 let editor_settings = EditorSettings::get_global(cx);
2805 if bracket_inserted
2806 && (editor_settings.auto_signature_help
2807 || editor_settings.show_signature_help_after_edits)
2808 {
2809 this.show_signature_help(&ShowSignatureHelp, cx);
2810 }
2811
2812 let trigger_in_words = !had_active_inline_completion;
2813 this.trigger_completion_on_input(&text, trigger_in_words, cx);
2814 linked_editing_ranges::refresh_linked_ranges(this, cx);
2815 this.refresh_inline_completion(true, false, cx);
2816 });
2817 }
2818
2819 fn find_possible_emoji_shortcode_at_position(
2820 snapshot: &MultiBufferSnapshot,
2821 position: Point,
2822 ) -> Option<String> {
2823 let mut chars = Vec::new();
2824 let mut found_colon = false;
2825 for char in snapshot.reversed_chars_at(position).take(100) {
2826 // Found a possible emoji shortcode in the middle of the buffer
2827 if found_colon {
2828 if char.is_whitespace() {
2829 chars.reverse();
2830 return Some(chars.iter().collect());
2831 }
2832 // If the previous character is not a whitespace, we are in the middle of a word
2833 // and we only want to complete the shortcode if the word is made up of other emojis
2834 let mut containing_word = String::new();
2835 for ch in snapshot
2836 .reversed_chars_at(position)
2837 .skip(chars.len() + 1)
2838 .take(100)
2839 {
2840 if ch.is_whitespace() {
2841 break;
2842 }
2843 containing_word.push(ch);
2844 }
2845 let containing_word = containing_word.chars().rev().collect::<String>();
2846 if util::word_consists_of_emojis(containing_word.as_str()) {
2847 chars.reverse();
2848 return Some(chars.iter().collect());
2849 }
2850 }
2851
2852 if char.is_whitespace() || !char.is_ascii() {
2853 return None;
2854 }
2855 if char == ':' {
2856 found_colon = true;
2857 } else {
2858 chars.push(char);
2859 }
2860 }
2861 // Found a possible emoji shortcode at the beginning of the buffer
2862 chars.reverse();
2863 Some(chars.iter().collect())
2864 }
2865
2866 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2867 self.transact(cx, |this, cx| {
2868 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2869 let selections = this.selections.all::<usize>(cx);
2870 let multi_buffer = this.buffer.read(cx);
2871 let buffer = multi_buffer.snapshot(cx);
2872 selections
2873 .iter()
2874 .map(|selection| {
2875 let start_point = selection.start.to_point(&buffer);
2876 let mut indent =
2877 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
2878 indent.len = cmp::min(indent.len, start_point.column);
2879 let start = selection.start;
2880 let end = selection.end;
2881 let selection_is_empty = start == end;
2882 let language_scope = buffer.language_scope_at(start);
2883 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
2884 &language_scope
2885 {
2886 let leading_whitespace_len = buffer
2887 .reversed_chars_at(start)
2888 .take_while(|c| c.is_whitespace() && *c != '\n')
2889 .map(|c| c.len_utf8())
2890 .sum::<usize>();
2891
2892 let trailing_whitespace_len = buffer
2893 .chars_at(end)
2894 .take_while(|c| c.is_whitespace() && *c != '\n')
2895 .map(|c| c.len_utf8())
2896 .sum::<usize>();
2897
2898 let insert_extra_newline =
2899 language.brackets().any(|(pair, enabled)| {
2900 let pair_start = pair.start.trim_end();
2901 let pair_end = pair.end.trim_start();
2902
2903 enabled
2904 && pair.newline
2905 && buffer.contains_str_at(
2906 end + trailing_whitespace_len,
2907 pair_end,
2908 )
2909 && buffer.contains_str_at(
2910 (start - leading_whitespace_len)
2911 .saturating_sub(pair_start.len()),
2912 pair_start,
2913 )
2914 });
2915
2916 // Comment extension on newline is allowed only for cursor selections
2917 let comment_delimiter = maybe!({
2918 if !selection_is_empty {
2919 return None;
2920 }
2921
2922 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
2923 return None;
2924 }
2925
2926 let delimiters = language.line_comment_prefixes();
2927 let max_len_of_delimiter =
2928 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
2929 let (snapshot, range) =
2930 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
2931
2932 let mut index_of_first_non_whitespace = 0;
2933 let comment_candidate = snapshot
2934 .chars_for_range(range)
2935 .skip_while(|c| {
2936 let should_skip = c.is_whitespace();
2937 if should_skip {
2938 index_of_first_non_whitespace += 1;
2939 }
2940 should_skip
2941 })
2942 .take(max_len_of_delimiter)
2943 .collect::<String>();
2944 let comment_prefix = delimiters.iter().find(|comment_prefix| {
2945 comment_candidate.starts_with(comment_prefix.as_ref())
2946 })?;
2947 let cursor_is_placed_after_comment_marker =
2948 index_of_first_non_whitespace + comment_prefix.len()
2949 <= start_point.column as usize;
2950 if cursor_is_placed_after_comment_marker {
2951 Some(comment_prefix.clone())
2952 } else {
2953 None
2954 }
2955 });
2956 (comment_delimiter, insert_extra_newline)
2957 } else {
2958 (None, false)
2959 };
2960
2961 let capacity_for_delimiter = comment_delimiter
2962 .as_deref()
2963 .map(str::len)
2964 .unwrap_or_default();
2965 let mut new_text =
2966 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
2967 new_text.push('\n');
2968 new_text.extend(indent.chars());
2969 if let Some(delimiter) = &comment_delimiter {
2970 new_text.push_str(delimiter);
2971 }
2972 if insert_extra_newline {
2973 new_text = new_text.repeat(2);
2974 }
2975
2976 let anchor = buffer.anchor_after(end);
2977 let new_selection = selection.map(|_| anchor);
2978 (
2979 (start..end, new_text),
2980 (insert_extra_newline, new_selection),
2981 )
2982 })
2983 .unzip()
2984 };
2985
2986 this.edit_with_autoindent(edits, cx);
2987 let buffer = this.buffer.read(cx).snapshot(cx);
2988 let new_selections = selection_fixup_info
2989 .into_iter()
2990 .map(|(extra_newline_inserted, new_selection)| {
2991 let mut cursor = new_selection.end.to_point(&buffer);
2992 if extra_newline_inserted {
2993 cursor.row -= 1;
2994 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
2995 }
2996 new_selection.map(|_| cursor)
2997 })
2998 .collect();
2999
3000 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3001 this.refresh_inline_completion(true, false, cx);
3002 });
3003 }
3004
3005 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3006 let buffer = self.buffer.read(cx);
3007 let snapshot = buffer.snapshot(cx);
3008
3009 let mut edits = Vec::new();
3010 let mut rows = Vec::new();
3011
3012 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3013 let cursor = selection.head();
3014 let row = cursor.row;
3015
3016 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3017
3018 let newline = "\n".to_string();
3019 edits.push((start_of_line..start_of_line, newline));
3020
3021 rows.push(row + rows_inserted as u32);
3022 }
3023
3024 self.transact(cx, |editor, cx| {
3025 editor.edit(edits, cx);
3026
3027 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3028 let mut index = 0;
3029 s.move_cursors_with(|map, _, _| {
3030 let row = rows[index];
3031 index += 1;
3032
3033 let point = Point::new(row, 0);
3034 let boundary = map.next_line_boundary(point).1;
3035 let clipped = map.clip_point(boundary, Bias::Left);
3036
3037 (clipped, SelectionGoal::None)
3038 });
3039 });
3040
3041 let mut indent_edits = Vec::new();
3042 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3043 for row in rows {
3044 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3045 for (row, indent) in indents {
3046 if indent.len == 0 {
3047 continue;
3048 }
3049
3050 let text = match indent.kind {
3051 IndentKind::Space => " ".repeat(indent.len as usize),
3052 IndentKind::Tab => "\t".repeat(indent.len as usize),
3053 };
3054 let point = Point::new(row.0, 0);
3055 indent_edits.push((point..point, text));
3056 }
3057 }
3058 editor.edit(indent_edits, cx);
3059 });
3060 }
3061
3062 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3063 let buffer = self.buffer.read(cx);
3064 let snapshot = buffer.snapshot(cx);
3065
3066 let mut edits = Vec::new();
3067 let mut rows = Vec::new();
3068 let mut rows_inserted = 0;
3069
3070 for selection in self.selections.all_adjusted(cx) {
3071 let cursor = selection.head();
3072 let row = cursor.row;
3073
3074 let point = Point::new(row + 1, 0);
3075 let start_of_line = snapshot.clip_point(point, Bias::Left);
3076
3077 let newline = "\n".to_string();
3078 edits.push((start_of_line..start_of_line, newline));
3079
3080 rows_inserted += 1;
3081 rows.push(row + rows_inserted);
3082 }
3083
3084 self.transact(cx, |editor, cx| {
3085 editor.edit(edits, cx);
3086
3087 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3088 let mut index = 0;
3089 s.move_cursors_with(|map, _, _| {
3090 let row = rows[index];
3091 index += 1;
3092
3093 let point = Point::new(row, 0);
3094 let boundary = map.next_line_boundary(point).1;
3095 let clipped = map.clip_point(boundary, Bias::Left);
3096
3097 (clipped, SelectionGoal::None)
3098 });
3099 });
3100
3101 let mut indent_edits = Vec::new();
3102 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3103 for row in rows {
3104 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3105 for (row, indent) in indents {
3106 if indent.len == 0 {
3107 continue;
3108 }
3109
3110 let text = match indent.kind {
3111 IndentKind::Space => " ".repeat(indent.len as usize),
3112 IndentKind::Tab => "\t".repeat(indent.len as usize),
3113 };
3114 let point = Point::new(row.0, 0);
3115 indent_edits.push((point..point, text));
3116 }
3117 }
3118 editor.edit(indent_edits, cx);
3119 });
3120 }
3121
3122 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3123 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3124 original_indent_columns: Vec::new(),
3125 });
3126 self.insert_with_autoindent_mode(text, autoindent, cx);
3127 }
3128
3129 fn insert_with_autoindent_mode(
3130 &mut self,
3131 text: &str,
3132 autoindent_mode: Option<AutoindentMode>,
3133 cx: &mut ViewContext<Self>,
3134 ) {
3135 if self.read_only(cx) {
3136 return;
3137 }
3138
3139 let text: Arc<str> = text.into();
3140 self.transact(cx, |this, cx| {
3141 let old_selections = this.selections.all_adjusted(cx);
3142 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3143 let anchors = {
3144 let snapshot = buffer.read(cx);
3145 old_selections
3146 .iter()
3147 .map(|s| {
3148 let anchor = snapshot.anchor_after(s.head());
3149 s.map(|_| anchor)
3150 })
3151 .collect::<Vec<_>>()
3152 };
3153 buffer.edit(
3154 old_selections
3155 .iter()
3156 .map(|s| (s.start..s.end, text.clone())),
3157 autoindent_mode,
3158 cx,
3159 );
3160 anchors
3161 });
3162
3163 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3164 s.select_anchors(selection_anchors);
3165 })
3166 });
3167 }
3168
3169 fn trigger_completion_on_input(
3170 &mut self,
3171 text: &str,
3172 trigger_in_words: bool,
3173 cx: &mut ViewContext<Self>,
3174 ) {
3175 if self.is_completion_trigger(text, trigger_in_words, cx) {
3176 self.show_completions(
3177 &ShowCompletions {
3178 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3179 },
3180 cx,
3181 );
3182 } else {
3183 self.hide_context_menu(cx);
3184 }
3185 }
3186
3187 fn is_completion_trigger(
3188 &self,
3189 text: &str,
3190 trigger_in_words: bool,
3191 cx: &mut ViewContext<Self>,
3192 ) -> bool {
3193 let position = self.selections.newest_anchor().head();
3194 let multibuffer = self.buffer.read(cx);
3195 let Some(buffer) = position
3196 .buffer_id
3197 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3198 else {
3199 return false;
3200 };
3201
3202 if let Some(completion_provider) = &self.completion_provider {
3203 completion_provider.is_completion_trigger(
3204 &buffer,
3205 position.text_anchor,
3206 text,
3207 trigger_in_words,
3208 cx,
3209 )
3210 } else {
3211 false
3212 }
3213 }
3214
3215 /// If any empty selections is touching the start of its innermost containing autoclose
3216 /// region, expand it to select the brackets.
3217 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3218 let selections = self.selections.all::<usize>(cx);
3219 let buffer = self.buffer.read(cx).read(cx);
3220 let new_selections = self
3221 .selections_with_autoclose_regions(selections, &buffer)
3222 .map(|(mut selection, region)| {
3223 if !selection.is_empty() {
3224 return selection;
3225 }
3226
3227 if let Some(region) = region {
3228 let mut range = region.range.to_offset(&buffer);
3229 if selection.start == range.start && range.start >= region.pair.start.len() {
3230 range.start -= region.pair.start.len();
3231 if buffer.contains_str_at(range.start, ®ion.pair.start)
3232 && buffer.contains_str_at(range.end, ®ion.pair.end)
3233 {
3234 range.end += region.pair.end.len();
3235 selection.start = range.start;
3236 selection.end = range.end;
3237
3238 return selection;
3239 }
3240 }
3241 }
3242
3243 let always_treat_brackets_as_autoclosed = buffer
3244 .settings_at(selection.start, cx)
3245 .always_treat_brackets_as_autoclosed;
3246
3247 if !always_treat_brackets_as_autoclosed {
3248 return selection;
3249 }
3250
3251 if let Some(scope) = buffer.language_scope_at(selection.start) {
3252 for (pair, enabled) in scope.brackets() {
3253 if !enabled || !pair.close {
3254 continue;
3255 }
3256
3257 if buffer.contains_str_at(selection.start, &pair.end) {
3258 let pair_start_len = pair.start.len();
3259 if buffer.contains_str_at(
3260 selection.start.saturating_sub(pair_start_len),
3261 &pair.start,
3262 ) {
3263 selection.start -= pair_start_len;
3264 selection.end += pair.end.len();
3265
3266 return selection;
3267 }
3268 }
3269 }
3270 }
3271
3272 selection
3273 })
3274 .collect();
3275
3276 drop(buffer);
3277 self.change_selections(None, cx, |selections| selections.select(new_selections));
3278 }
3279
3280 /// Iterate the given selections, and for each one, find the smallest surrounding
3281 /// autoclose region. This uses the ordering of the selections and the autoclose
3282 /// regions to avoid repeated comparisons.
3283 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3284 &'a self,
3285 selections: impl IntoIterator<Item = Selection<D>>,
3286 buffer: &'a MultiBufferSnapshot,
3287 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3288 let mut i = 0;
3289 let mut regions = self.autoclose_regions.as_slice();
3290 selections.into_iter().map(move |selection| {
3291 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3292
3293 let mut enclosing = None;
3294 while let Some(pair_state) = regions.get(i) {
3295 if pair_state.range.end.to_offset(buffer) < range.start {
3296 regions = ®ions[i + 1..];
3297 i = 0;
3298 } else if pair_state.range.start.to_offset(buffer) > range.end {
3299 break;
3300 } else {
3301 if pair_state.selection_id == selection.id {
3302 enclosing = Some(pair_state);
3303 }
3304 i += 1;
3305 }
3306 }
3307
3308 (selection, enclosing)
3309 })
3310 }
3311
3312 /// Remove any autoclose regions that no longer contain their selection.
3313 fn invalidate_autoclose_regions(
3314 &mut self,
3315 mut selections: &[Selection<Anchor>],
3316 buffer: &MultiBufferSnapshot,
3317 ) {
3318 self.autoclose_regions.retain(|state| {
3319 let mut i = 0;
3320 while let Some(selection) = selections.get(i) {
3321 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3322 selections = &selections[1..];
3323 continue;
3324 }
3325 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3326 break;
3327 }
3328 if selection.id == state.selection_id {
3329 return true;
3330 } else {
3331 i += 1;
3332 }
3333 }
3334 false
3335 });
3336 }
3337
3338 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3339 let offset = position.to_offset(buffer);
3340 let (word_range, kind) = buffer.surrounding_word(offset, true);
3341 if offset > word_range.start && kind == Some(CharKind::Word) {
3342 Some(
3343 buffer
3344 .text_for_range(word_range.start..offset)
3345 .collect::<String>(),
3346 )
3347 } else {
3348 None
3349 }
3350 }
3351
3352 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3353 self.refresh_inlay_hints(
3354 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3355 cx,
3356 );
3357 }
3358
3359 pub fn inlay_hints_enabled(&self) -> bool {
3360 self.inlay_hint_cache.enabled
3361 }
3362
3363 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3364 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3365 return;
3366 }
3367
3368 let reason_description = reason.description();
3369 let ignore_debounce = matches!(
3370 reason,
3371 InlayHintRefreshReason::SettingsChange(_)
3372 | InlayHintRefreshReason::Toggle(_)
3373 | InlayHintRefreshReason::ExcerptsRemoved(_)
3374 );
3375 let (invalidate_cache, required_languages) = match reason {
3376 InlayHintRefreshReason::Toggle(enabled) => {
3377 self.inlay_hint_cache.enabled = enabled;
3378 if enabled {
3379 (InvalidationStrategy::RefreshRequested, None)
3380 } else {
3381 self.inlay_hint_cache.clear();
3382 self.splice_inlays(
3383 self.visible_inlay_hints(cx)
3384 .iter()
3385 .map(|inlay| inlay.id)
3386 .collect(),
3387 Vec::new(),
3388 cx,
3389 );
3390 return;
3391 }
3392 }
3393 InlayHintRefreshReason::SettingsChange(new_settings) => {
3394 match self.inlay_hint_cache.update_settings(
3395 &self.buffer,
3396 new_settings,
3397 self.visible_inlay_hints(cx),
3398 cx,
3399 ) {
3400 ControlFlow::Break(Some(InlaySplice {
3401 to_remove,
3402 to_insert,
3403 })) => {
3404 self.splice_inlays(to_remove, to_insert, cx);
3405 return;
3406 }
3407 ControlFlow::Break(None) => return,
3408 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3409 }
3410 }
3411 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3412 if let Some(InlaySplice {
3413 to_remove,
3414 to_insert,
3415 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3416 {
3417 self.splice_inlays(to_remove, to_insert, cx);
3418 }
3419 return;
3420 }
3421 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3422 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3423 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3424 }
3425 InlayHintRefreshReason::RefreshRequested => {
3426 (InvalidationStrategy::RefreshRequested, None)
3427 }
3428 };
3429
3430 if let Some(InlaySplice {
3431 to_remove,
3432 to_insert,
3433 }) = self.inlay_hint_cache.spawn_hint_refresh(
3434 reason_description,
3435 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3436 invalidate_cache,
3437 ignore_debounce,
3438 cx,
3439 ) {
3440 self.splice_inlays(to_remove, to_insert, cx);
3441 }
3442 }
3443
3444 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
3445 self.display_map
3446 .read(cx)
3447 .current_inlays()
3448 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3449 .cloned()
3450 .collect()
3451 }
3452
3453 pub fn excerpts_for_inlay_hints_query(
3454 &self,
3455 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3456 cx: &mut ViewContext<Editor>,
3457 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3458 let Some(project) = self.project.as_ref() else {
3459 return HashMap::default();
3460 };
3461 let project = project.read(cx);
3462 let multi_buffer = self.buffer().read(cx);
3463 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3464 let multi_buffer_visible_start = self
3465 .scroll_manager
3466 .anchor()
3467 .anchor
3468 .to_point(&multi_buffer_snapshot);
3469 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3470 multi_buffer_visible_start
3471 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3472 Bias::Left,
3473 );
3474 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3475 multi_buffer
3476 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
3477 .into_iter()
3478 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3479 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
3480 let buffer = buffer_handle.read(cx);
3481 let buffer_file = project::File::from_dyn(buffer.file())?;
3482 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3483 let worktree_entry = buffer_worktree
3484 .read(cx)
3485 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3486 if worktree_entry.is_ignored {
3487 return None;
3488 }
3489
3490 let language = buffer.language()?;
3491 if let Some(restrict_to_languages) = restrict_to_languages {
3492 if !restrict_to_languages.contains(language) {
3493 return None;
3494 }
3495 }
3496 Some((
3497 excerpt_id,
3498 (
3499 buffer_handle,
3500 buffer.version().clone(),
3501 excerpt_visible_range,
3502 ),
3503 ))
3504 })
3505 .collect()
3506 }
3507
3508 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3509 TextLayoutDetails {
3510 text_system: cx.text_system().clone(),
3511 editor_style: self.style.clone().unwrap(),
3512 rem_size: cx.rem_size(),
3513 scroll_anchor: self.scroll_manager.anchor(),
3514 visible_rows: self.visible_line_count(),
3515 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3516 }
3517 }
3518
3519 fn splice_inlays(
3520 &self,
3521 to_remove: Vec<InlayId>,
3522 to_insert: Vec<Inlay>,
3523 cx: &mut ViewContext<Self>,
3524 ) {
3525 self.display_map.update(cx, |display_map, cx| {
3526 display_map.splice_inlays(to_remove, to_insert, cx)
3527 });
3528 cx.notify();
3529 }
3530
3531 fn trigger_on_type_formatting(
3532 &self,
3533 input: String,
3534 cx: &mut ViewContext<Self>,
3535 ) -> Option<Task<Result<()>>> {
3536 if input.len() != 1 {
3537 return None;
3538 }
3539
3540 let project = self.project.as_ref()?;
3541 let position = self.selections.newest_anchor().head();
3542 let (buffer, buffer_position) = self
3543 .buffer
3544 .read(cx)
3545 .text_anchor_for_position(position, cx)?;
3546
3547 let settings = language_settings::language_settings(
3548 buffer
3549 .read(cx)
3550 .language_at(buffer_position)
3551 .map(|l| l.name()),
3552 buffer.read(cx).file(),
3553 cx,
3554 );
3555 if !settings.use_on_type_format {
3556 return None;
3557 }
3558
3559 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3560 // hence we do LSP request & edit on host side only — add formats to host's history.
3561 let push_to_lsp_host_history = true;
3562 // If this is not the host, append its history with new edits.
3563 let push_to_client_history = project.read(cx).is_via_collab();
3564
3565 let on_type_formatting = project.update(cx, |project, cx| {
3566 project.on_type_format(
3567 buffer.clone(),
3568 buffer_position,
3569 input,
3570 push_to_lsp_host_history,
3571 cx,
3572 )
3573 });
3574 Some(cx.spawn(|editor, mut cx| async move {
3575 if let Some(transaction) = on_type_formatting.await? {
3576 if push_to_client_history {
3577 buffer
3578 .update(&mut cx, |buffer, _| {
3579 buffer.push_transaction(transaction, Instant::now());
3580 })
3581 .ok();
3582 }
3583 editor.update(&mut cx, |editor, cx| {
3584 editor.refresh_document_highlights(cx);
3585 })?;
3586 }
3587 Ok(())
3588 }))
3589 }
3590
3591 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
3592 if self.pending_rename.is_some() {
3593 return;
3594 }
3595
3596 let Some(provider) = self.completion_provider.as_ref() else {
3597 return;
3598 };
3599
3600 if !self.snippet_stack.is_empty() && self.context_menu.read().as_ref().is_some() {
3601 return;
3602 }
3603
3604 let position = self.selections.newest_anchor().head();
3605 let (buffer, buffer_position) =
3606 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3607 output
3608 } else {
3609 return;
3610 };
3611 let show_completion_documentation = buffer
3612 .read(cx)
3613 .snapshot()
3614 .settings_at(buffer_position, cx)
3615 .show_completion_documentation;
3616
3617 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3618
3619 let aside_was_displayed = match self.context_menu.read().deref() {
3620 Some(CodeContextMenu::Completions(menu)) => menu.aside_was_displayed.get(),
3621 _ => false,
3622 };
3623 let trigger_kind = match &options.trigger {
3624 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3625 CompletionTriggerKind::TRIGGER_CHARACTER
3626 }
3627 _ => CompletionTriggerKind::INVOKED,
3628 };
3629 let completion_context = CompletionContext {
3630 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3631 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3632 Some(String::from(trigger))
3633 } else {
3634 None
3635 }
3636 }),
3637 trigger_kind,
3638 };
3639 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
3640 let sort_completions = provider.sort_completions();
3641
3642 let id = post_inc(&mut self.next_completion_id);
3643 let task = cx.spawn(|editor, mut cx| {
3644 async move {
3645 editor.update(&mut cx, |this, _| {
3646 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3647 })?;
3648 let completions = completions.await.log_err();
3649 let menu = if let Some(completions) = completions {
3650 let mut menu = CompletionsMenu::new(
3651 id,
3652 sort_completions,
3653 show_completion_documentation,
3654 position,
3655 buffer.clone(),
3656 completions.into(),
3657 aside_was_displayed,
3658 );
3659 menu.filter(query.as_deref(), cx.background_executor().clone())
3660 .await;
3661
3662 if menu.matches.is_empty() {
3663 None
3664 } else {
3665 Some(menu)
3666 }
3667 } else {
3668 None
3669 };
3670
3671 editor.update(&mut cx, |editor, cx| {
3672 let mut context_menu = editor.context_menu.write();
3673 match context_menu.as_ref() {
3674 None => {}
3675
3676 Some(CodeContextMenu::Completions(prev_menu)) => {
3677 if prev_menu.id > id {
3678 return;
3679 }
3680 }
3681
3682 _ => return,
3683 }
3684
3685 if editor.focus_handle.is_focused(cx) && menu.is_some() {
3686 let mut menu = menu.unwrap();
3687 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3688 *context_menu = Some(CodeContextMenu::Completions(menu));
3689 drop(context_menu);
3690 cx.notify();
3691 } else if editor.completion_tasks.len() <= 1 {
3692 // If there are no more completion tasks and the last menu was
3693 // empty, we should hide it. If it was already hidden, we should
3694 // also show the copilot completion when available.
3695 drop(context_menu);
3696 editor.hide_context_menu(cx);
3697 }
3698 })?;
3699
3700 Ok::<_, anyhow::Error>(())
3701 }
3702 .log_err()
3703 });
3704
3705 self.completion_tasks.push((id, task));
3706 }
3707
3708 pub fn confirm_completion(
3709 &mut self,
3710 action: &ConfirmCompletion,
3711 cx: &mut ViewContext<Self>,
3712 ) -> Option<Task<Result<()>>> {
3713 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
3714 }
3715
3716 pub fn compose_completion(
3717 &mut self,
3718 action: &ComposeCompletion,
3719 cx: &mut ViewContext<Self>,
3720 ) -> Option<Task<Result<()>>> {
3721 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
3722 }
3723
3724 fn do_completion(
3725 &mut self,
3726 item_ix: Option<usize>,
3727 intent: CompletionIntent,
3728 cx: &mut ViewContext<Editor>,
3729 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3730 use language::ToOffset as _;
3731
3732 self.discard_inline_completion(true, cx);
3733 let completions_menu =
3734 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3735 menu
3736 } else {
3737 return None;
3738 };
3739
3740 let mat = completions_menu
3741 .matches
3742 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
3743 let buffer_handle = completions_menu.buffer;
3744 let completions = completions_menu.completions.read();
3745 let completion = completions.get(mat.candidate_id)?;
3746 cx.stop_propagation();
3747
3748 let snippet;
3749 let text;
3750
3751 if completion.is_snippet() {
3752 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3753 text = snippet.as_ref().unwrap().text.clone();
3754 } else {
3755 snippet = None;
3756 text = completion.new_text.clone();
3757 };
3758 let selections = self.selections.all::<usize>(cx);
3759 let buffer = buffer_handle.read(cx);
3760 let old_range = completion.old_range.to_offset(buffer);
3761 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3762
3763 let newest_selection = self.selections.newest_anchor();
3764 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3765 return None;
3766 }
3767
3768 let lookbehind = newest_selection
3769 .start
3770 .text_anchor
3771 .to_offset(buffer)
3772 .saturating_sub(old_range.start);
3773 let lookahead = old_range
3774 .end
3775 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3776 let mut common_prefix_len = old_text
3777 .bytes()
3778 .zip(text.bytes())
3779 .take_while(|(a, b)| a == b)
3780 .count();
3781
3782 let snapshot = self.buffer.read(cx).snapshot(cx);
3783 let mut range_to_replace: Option<Range<isize>> = None;
3784 let mut ranges = Vec::new();
3785 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3786 for selection in &selections {
3787 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3788 let start = selection.start.saturating_sub(lookbehind);
3789 let end = selection.end + lookahead;
3790 if selection.id == newest_selection.id {
3791 range_to_replace = Some(
3792 ((start + common_prefix_len) as isize - selection.start as isize)
3793 ..(end as isize - selection.start as isize),
3794 );
3795 }
3796 ranges.push(start + common_prefix_len..end);
3797 } else {
3798 common_prefix_len = 0;
3799 ranges.clear();
3800 ranges.extend(selections.iter().map(|s| {
3801 if s.id == newest_selection.id {
3802 range_to_replace = Some(
3803 old_range.start.to_offset_utf16(&snapshot).0 as isize
3804 - selection.start as isize
3805 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3806 - selection.start as isize,
3807 );
3808 old_range.clone()
3809 } else {
3810 s.start..s.end
3811 }
3812 }));
3813 break;
3814 }
3815 if !self.linked_edit_ranges.is_empty() {
3816 let start_anchor = snapshot.anchor_before(selection.head());
3817 let end_anchor = snapshot.anchor_after(selection.tail());
3818 if let Some(ranges) = self
3819 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
3820 {
3821 for (buffer, edits) in ranges {
3822 linked_edits.entry(buffer.clone()).or_default().extend(
3823 edits
3824 .into_iter()
3825 .map(|range| (range, text[common_prefix_len..].to_owned())),
3826 );
3827 }
3828 }
3829 }
3830 }
3831 let text = &text[common_prefix_len..];
3832
3833 cx.emit(EditorEvent::InputHandled {
3834 utf16_range_to_replace: range_to_replace,
3835 text: text.into(),
3836 });
3837
3838 self.transact(cx, |this, cx| {
3839 if let Some(mut snippet) = snippet {
3840 snippet.text = text.to_string();
3841 for tabstop in snippet
3842 .tabstops
3843 .iter_mut()
3844 .flat_map(|tabstop| tabstop.ranges.iter_mut())
3845 {
3846 tabstop.start -= common_prefix_len as isize;
3847 tabstop.end -= common_prefix_len as isize;
3848 }
3849
3850 this.insert_snippet(&ranges, snippet, cx).log_err();
3851 } else {
3852 this.buffer.update(cx, |buffer, cx| {
3853 buffer.edit(
3854 ranges.iter().map(|range| (range.clone(), text)),
3855 this.autoindent_mode.clone(),
3856 cx,
3857 );
3858 });
3859 }
3860 for (buffer, edits) in linked_edits {
3861 buffer.update(cx, |buffer, cx| {
3862 let snapshot = buffer.snapshot();
3863 let edits = edits
3864 .into_iter()
3865 .map(|(range, text)| {
3866 use text::ToPoint as TP;
3867 let end_point = TP::to_point(&range.end, &snapshot);
3868 let start_point = TP::to_point(&range.start, &snapshot);
3869 (start_point..end_point, text)
3870 })
3871 .sorted_by_key(|(range, _)| range.start)
3872 .collect::<Vec<_>>();
3873 buffer.edit(edits, None, cx);
3874 })
3875 }
3876
3877 this.refresh_inline_completion(true, false, cx);
3878 });
3879
3880 let show_new_completions_on_confirm = completion
3881 .confirm
3882 .as_ref()
3883 .map_or(false, |confirm| confirm(intent, cx));
3884 if show_new_completions_on_confirm {
3885 self.show_completions(&ShowCompletions { trigger: None }, cx);
3886 }
3887
3888 let provider = self.completion_provider.as_ref()?;
3889 let apply_edits = provider.apply_additional_edits_for_completion(
3890 buffer_handle,
3891 completion.clone(),
3892 true,
3893 cx,
3894 );
3895
3896 let editor_settings = EditorSettings::get_global(cx);
3897 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
3898 // After the code completion is finished, users often want to know what signatures are needed.
3899 // so we should automatically call signature_help
3900 self.show_signature_help(&ShowSignatureHelp, cx);
3901 }
3902
3903 Some(cx.foreground_executor().spawn(async move {
3904 apply_edits.await?;
3905 Ok(())
3906 }))
3907 }
3908
3909 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
3910 let mut context_menu = self.context_menu.write();
3911 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
3912 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
3913 // Toggle if we're selecting the same one
3914 *context_menu = None;
3915 cx.notify();
3916 return;
3917 } else {
3918 // Otherwise, clear it and start a new one
3919 *context_menu = None;
3920 cx.notify();
3921 }
3922 }
3923 drop(context_menu);
3924 let snapshot = self.snapshot(cx);
3925 let deployed_from_indicator = action.deployed_from_indicator;
3926 let mut task = self.code_actions_task.take();
3927 let action = action.clone();
3928 cx.spawn(|editor, mut cx| async move {
3929 while let Some(prev_task) = task {
3930 prev_task.await.log_err();
3931 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
3932 }
3933
3934 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
3935 if editor.focus_handle.is_focused(cx) {
3936 let multibuffer_point = action
3937 .deployed_from_indicator
3938 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
3939 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
3940 let (buffer, buffer_row) = snapshot
3941 .buffer_snapshot
3942 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
3943 .and_then(|(buffer_snapshot, range)| {
3944 editor
3945 .buffer
3946 .read(cx)
3947 .buffer(buffer_snapshot.remote_id())
3948 .map(|buffer| (buffer, range.start.row))
3949 })?;
3950 let (_, code_actions) = editor
3951 .available_code_actions
3952 .clone()
3953 .and_then(|(location, code_actions)| {
3954 let snapshot = location.buffer.read(cx).snapshot();
3955 let point_range = location.range.to_point(&snapshot);
3956 let point_range = point_range.start.row..=point_range.end.row;
3957 if point_range.contains(&buffer_row) {
3958 Some((location, code_actions))
3959 } else {
3960 None
3961 }
3962 })
3963 .unzip();
3964 let buffer_id = buffer.read(cx).remote_id();
3965 let tasks = editor
3966 .tasks
3967 .get(&(buffer_id, buffer_row))
3968 .map(|t| Arc::new(t.to_owned()));
3969 if tasks.is_none() && code_actions.is_none() {
3970 return None;
3971 }
3972
3973 editor.completion_tasks.clear();
3974 editor.discard_inline_completion(false, cx);
3975 let task_context =
3976 tasks
3977 .as_ref()
3978 .zip(editor.project.clone())
3979 .map(|(tasks, project)| {
3980 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
3981 });
3982
3983 Some(cx.spawn(|editor, mut cx| async move {
3984 let task_context = match task_context {
3985 Some(task_context) => task_context.await,
3986 None => None,
3987 };
3988 let resolved_tasks =
3989 tasks.zip(task_context).map(|(tasks, task_context)| {
3990 Arc::new(ResolvedTasks {
3991 templates: tasks.resolve(&task_context).collect(),
3992 position: snapshot.buffer_snapshot.anchor_before(Point::new(
3993 multibuffer_point.row,
3994 tasks.column,
3995 )),
3996 })
3997 });
3998 let spawn_straight_away = resolved_tasks
3999 .as_ref()
4000 .map_or(false, |tasks| tasks.templates.len() == 1)
4001 && code_actions
4002 .as_ref()
4003 .map_or(true, |actions| actions.is_empty());
4004 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4005 *editor.context_menu.write() =
4006 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4007 buffer,
4008 actions: CodeActionContents {
4009 tasks: resolved_tasks,
4010 actions: code_actions,
4011 },
4012 selected_item: Default::default(),
4013 scroll_handle: UniformListScrollHandle::default(),
4014 deployed_from_indicator,
4015 }));
4016 if spawn_straight_away {
4017 if let Some(task) = editor.confirm_code_action(
4018 &ConfirmCodeAction { item_ix: Some(0) },
4019 cx,
4020 ) {
4021 cx.notify();
4022 return task;
4023 }
4024 }
4025 cx.notify();
4026 Task::ready(Ok(()))
4027 }) {
4028 task.await
4029 } else {
4030 Ok(())
4031 }
4032 }))
4033 } else {
4034 Some(Task::ready(Ok(())))
4035 }
4036 })?;
4037 if let Some(task) = spawned_test_task {
4038 task.await?;
4039 }
4040
4041 Ok::<_, anyhow::Error>(())
4042 })
4043 .detach_and_log_err(cx);
4044 }
4045
4046 pub fn confirm_code_action(
4047 &mut self,
4048 action: &ConfirmCodeAction,
4049 cx: &mut ViewContext<Self>,
4050 ) -> Option<Task<Result<()>>> {
4051 let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4052 menu
4053 } else {
4054 return None;
4055 };
4056 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4057 let action = actions_menu.actions.get(action_ix)?;
4058 let title = action.label();
4059 let buffer = actions_menu.buffer;
4060 let workspace = self.workspace()?;
4061
4062 match action {
4063 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4064 workspace.update(cx, |workspace, cx| {
4065 workspace::tasks::schedule_resolved_task(
4066 workspace,
4067 task_source_kind,
4068 resolved_task,
4069 false,
4070 cx,
4071 );
4072
4073 Some(Task::ready(Ok(())))
4074 })
4075 }
4076 CodeActionsItem::CodeAction {
4077 excerpt_id,
4078 action,
4079 provider,
4080 } => {
4081 let apply_code_action =
4082 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4083 let workspace = workspace.downgrade();
4084 Some(cx.spawn(|editor, cx| async move {
4085 let project_transaction = apply_code_action.await?;
4086 Self::open_project_transaction(
4087 &editor,
4088 workspace,
4089 project_transaction,
4090 title,
4091 cx,
4092 )
4093 .await
4094 }))
4095 }
4096 }
4097 }
4098
4099 pub async fn open_project_transaction(
4100 this: &WeakView<Editor>,
4101 workspace: WeakView<Workspace>,
4102 transaction: ProjectTransaction,
4103 title: String,
4104 mut cx: AsyncWindowContext,
4105 ) -> Result<()> {
4106 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4107 cx.update(|cx| {
4108 entries.sort_unstable_by_key(|(buffer, _)| {
4109 buffer.read(cx).file().map(|f| f.path().clone())
4110 });
4111 })?;
4112
4113 // If the project transaction's edits are all contained within this editor, then
4114 // avoid opening a new editor to display them.
4115
4116 if let Some((buffer, transaction)) = entries.first() {
4117 if entries.len() == 1 {
4118 let excerpt = this.update(&mut cx, |editor, cx| {
4119 editor
4120 .buffer()
4121 .read(cx)
4122 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4123 })?;
4124 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4125 if excerpted_buffer == *buffer {
4126 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4127 let excerpt_range = excerpt_range.to_offset(buffer);
4128 buffer
4129 .edited_ranges_for_transaction::<usize>(transaction)
4130 .all(|range| {
4131 excerpt_range.start <= range.start
4132 && excerpt_range.end >= range.end
4133 })
4134 })?;
4135
4136 if all_edits_within_excerpt {
4137 return Ok(());
4138 }
4139 }
4140 }
4141 }
4142 } else {
4143 return Ok(());
4144 }
4145
4146 let mut ranges_to_highlight = Vec::new();
4147 let excerpt_buffer = cx.new_model(|cx| {
4148 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4149 for (buffer_handle, transaction) in &entries {
4150 let buffer = buffer_handle.read(cx);
4151 ranges_to_highlight.extend(
4152 multibuffer.push_excerpts_with_context_lines(
4153 buffer_handle.clone(),
4154 buffer
4155 .edited_ranges_for_transaction::<usize>(transaction)
4156 .collect(),
4157 DEFAULT_MULTIBUFFER_CONTEXT,
4158 cx,
4159 ),
4160 );
4161 }
4162 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4163 multibuffer
4164 })?;
4165
4166 workspace.update(&mut cx, |workspace, cx| {
4167 let project = workspace.project().clone();
4168 let editor =
4169 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4170 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4171 editor.update(cx, |editor, cx| {
4172 editor.highlight_background::<Self>(
4173 &ranges_to_highlight,
4174 |theme| theme.editor_highlighted_line_background,
4175 cx,
4176 );
4177 });
4178 })?;
4179
4180 Ok(())
4181 }
4182
4183 pub fn clear_code_action_providers(&mut self) {
4184 self.code_action_providers.clear();
4185 self.available_code_actions.take();
4186 }
4187
4188 pub fn push_code_action_provider(
4189 &mut self,
4190 provider: Arc<dyn CodeActionProvider>,
4191 cx: &mut ViewContext<Self>,
4192 ) {
4193 self.code_action_providers.push(provider);
4194 self.refresh_code_actions(cx);
4195 }
4196
4197 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4198 let buffer = self.buffer.read(cx);
4199 let newest_selection = self.selections.newest_anchor().clone();
4200 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4201 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4202 if start_buffer != end_buffer {
4203 return None;
4204 }
4205
4206 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4207 cx.background_executor()
4208 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4209 .await;
4210
4211 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4212 let providers = this.code_action_providers.clone();
4213 let tasks = this
4214 .code_action_providers
4215 .iter()
4216 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4217 .collect::<Vec<_>>();
4218 (providers, tasks)
4219 })?;
4220
4221 let mut actions = Vec::new();
4222 for (provider, provider_actions) in
4223 providers.into_iter().zip(future::join_all(tasks).await)
4224 {
4225 if let Some(provider_actions) = provider_actions.log_err() {
4226 actions.extend(provider_actions.into_iter().map(|action| {
4227 AvailableCodeAction {
4228 excerpt_id: newest_selection.start.excerpt_id,
4229 action,
4230 provider: provider.clone(),
4231 }
4232 }));
4233 }
4234 }
4235
4236 this.update(&mut cx, |this, cx| {
4237 this.available_code_actions = if actions.is_empty() {
4238 None
4239 } else {
4240 Some((
4241 Location {
4242 buffer: start_buffer,
4243 range: start..end,
4244 },
4245 actions.into(),
4246 ))
4247 };
4248 cx.notify();
4249 })
4250 }));
4251 None
4252 }
4253
4254 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4255 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4256 self.show_git_blame_inline = false;
4257
4258 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4259 cx.background_executor().timer(delay).await;
4260
4261 this.update(&mut cx, |this, cx| {
4262 this.show_git_blame_inline = true;
4263 cx.notify();
4264 })
4265 .log_err();
4266 }));
4267 }
4268 }
4269
4270 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4271 if self.pending_rename.is_some() {
4272 return None;
4273 }
4274
4275 let provider = self.semantics_provider.clone()?;
4276 let buffer = self.buffer.read(cx);
4277 let newest_selection = self.selections.newest_anchor().clone();
4278 let cursor_position = newest_selection.head();
4279 let (cursor_buffer, cursor_buffer_position) =
4280 buffer.text_anchor_for_position(cursor_position, cx)?;
4281 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4282 if cursor_buffer != tail_buffer {
4283 return None;
4284 }
4285
4286 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4287 cx.background_executor()
4288 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4289 .await;
4290
4291 let highlights = if let Some(highlights) = cx
4292 .update(|cx| {
4293 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4294 })
4295 .ok()
4296 .flatten()
4297 {
4298 highlights.await.log_err()
4299 } else {
4300 None
4301 };
4302
4303 if let Some(highlights) = highlights {
4304 this.update(&mut cx, |this, cx| {
4305 if this.pending_rename.is_some() {
4306 return;
4307 }
4308
4309 let buffer_id = cursor_position.buffer_id;
4310 let buffer = this.buffer.read(cx);
4311 if !buffer
4312 .text_anchor_for_position(cursor_position, cx)
4313 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4314 {
4315 return;
4316 }
4317
4318 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4319 let mut write_ranges = Vec::new();
4320 let mut read_ranges = Vec::new();
4321 for highlight in highlights {
4322 for (excerpt_id, excerpt_range) in
4323 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4324 {
4325 let start = highlight
4326 .range
4327 .start
4328 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4329 let end = highlight
4330 .range
4331 .end
4332 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4333 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4334 continue;
4335 }
4336
4337 let range = Anchor {
4338 buffer_id,
4339 excerpt_id,
4340 text_anchor: start,
4341 }..Anchor {
4342 buffer_id,
4343 excerpt_id,
4344 text_anchor: end,
4345 };
4346 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4347 write_ranges.push(range);
4348 } else {
4349 read_ranges.push(range);
4350 }
4351 }
4352 }
4353
4354 this.highlight_background::<DocumentHighlightRead>(
4355 &read_ranges,
4356 |theme| theme.editor_document_highlight_read_background,
4357 cx,
4358 );
4359 this.highlight_background::<DocumentHighlightWrite>(
4360 &write_ranges,
4361 |theme| theme.editor_document_highlight_write_background,
4362 cx,
4363 );
4364 cx.notify();
4365 })
4366 .log_err();
4367 }
4368 }));
4369 None
4370 }
4371
4372 pub fn refresh_inline_completion(
4373 &mut self,
4374 debounce: bool,
4375 user_requested: bool,
4376 cx: &mut ViewContext<Self>,
4377 ) -> Option<()> {
4378 let provider = self.inline_completion_provider()?;
4379 let cursor = self.selections.newest_anchor().head();
4380 let (buffer, cursor_buffer_position) =
4381 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4382
4383 if !user_requested
4384 && (!self.enable_inline_completions
4385 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4386 || !self.is_focused(cx))
4387 {
4388 self.discard_inline_completion(false, cx);
4389 return None;
4390 }
4391
4392 self.update_visible_inline_completion(cx);
4393 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4394 Some(())
4395 }
4396
4397 fn cycle_inline_completion(
4398 &mut self,
4399 direction: Direction,
4400 cx: &mut ViewContext<Self>,
4401 ) -> Option<()> {
4402 let provider = self.inline_completion_provider()?;
4403 let cursor = self.selections.newest_anchor().head();
4404 let (buffer, cursor_buffer_position) =
4405 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4406 if !self.enable_inline_completions
4407 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4408 {
4409 return None;
4410 }
4411
4412 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4413 self.update_visible_inline_completion(cx);
4414
4415 Some(())
4416 }
4417
4418 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4419 if !self.has_active_inline_completion() {
4420 self.refresh_inline_completion(false, true, cx);
4421 return;
4422 }
4423
4424 self.update_visible_inline_completion(cx);
4425 }
4426
4427 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4428 self.show_cursor_names(cx);
4429 }
4430
4431 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4432 self.show_cursor_names = true;
4433 cx.notify();
4434 cx.spawn(|this, mut cx| async move {
4435 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4436 this.update(&mut cx, |this, cx| {
4437 this.show_cursor_names = false;
4438 cx.notify()
4439 })
4440 .ok()
4441 })
4442 .detach();
4443 }
4444
4445 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4446 if self.has_active_inline_completion() {
4447 self.cycle_inline_completion(Direction::Next, cx);
4448 } else {
4449 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4450 if is_copilot_disabled {
4451 cx.propagate();
4452 }
4453 }
4454 }
4455
4456 pub fn previous_inline_completion(
4457 &mut self,
4458 _: &PreviousInlineCompletion,
4459 cx: &mut ViewContext<Self>,
4460 ) {
4461 if self.has_active_inline_completion() {
4462 self.cycle_inline_completion(Direction::Prev, cx);
4463 } else {
4464 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4465 if is_copilot_disabled {
4466 cx.propagate();
4467 }
4468 }
4469 }
4470
4471 pub fn accept_inline_completion(
4472 &mut self,
4473 _: &AcceptInlineCompletion,
4474 cx: &mut ViewContext<Self>,
4475 ) {
4476 self.hide_context_menu(cx);
4477
4478 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4479 return;
4480 };
4481
4482 self.report_inline_completion_event(true, cx);
4483
4484 match &active_inline_completion.completion {
4485 InlineCompletion::Move(position) => {
4486 let position = *position;
4487 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4488 selections.select_anchor_ranges([position..position]);
4489 });
4490 }
4491 InlineCompletion::Edit(edits) => {
4492 if let Some(provider) = self.inline_completion_provider() {
4493 provider.accept(cx);
4494 }
4495
4496 let snapshot = self.buffer.read(cx).snapshot(cx);
4497 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4498
4499 self.buffer.update(cx, |buffer, cx| {
4500 buffer.edit(edits.iter().cloned(), None, cx)
4501 });
4502
4503 self.change_selections(None, cx, |s| {
4504 s.select_anchor_ranges([last_edit_end..last_edit_end])
4505 });
4506
4507 self.update_visible_inline_completion(cx);
4508 if self.active_inline_completion.is_none() {
4509 self.refresh_inline_completion(true, true, cx);
4510 }
4511
4512 cx.notify();
4513 }
4514 }
4515 }
4516
4517 pub fn accept_partial_inline_completion(
4518 &mut self,
4519 _: &AcceptPartialInlineCompletion,
4520 cx: &mut ViewContext<Self>,
4521 ) {
4522 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4523 return;
4524 };
4525 if self.selections.count() != 1 {
4526 return;
4527 }
4528
4529 self.report_inline_completion_event(true, cx);
4530
4531 match &active_inline_completion.completion {
4532 InlineCompletion::Move(position) => {
4533 let position = *position;
4534 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4535 selections.select_anchor_ranges([position..position]);
4536 });
4537 }
4538 InlineCompletion::Edit(edits) => {
4539 if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
4540 let text = edits[0].1.as_str();
4541 let mut partial_completion = text
4542 .chars()
4543 .by_ref()
4544 .take_while(|c| c.is_alphabetic())
4545 .collect::<String>();
4546 if partial_completion.is_empty() {
4547 partial_completion = text
4548 .chars()
4549 .by_ref()
4550 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4551 .collect::<String>();
4552 }
4553
4554 cx.emit(EditorEvent::InputHandled {
4555 utf16_range_to_replace: None,
4556 text: partial_completion.clone().into(),
4557 });
4558
4559 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4560
4561 self.refresh_inline_completion(true, true, cx);
4562 cx.notify();
4563 }
4564 }
4565 }
4566 }
4567
4568 fn discard_inline_completion(
4569 &mut self,
4570 should_report_inline_completion_event: bool,
4571 cx: &mut ViewContext<Self>,
4572 ) -> bool {
4573 if should_report_inline_completion_event {
4574 self.report_inline_completion_event(false, cx);
4575 }
4576
4577 if let Some(provider) = self.inline_completion_provider() {
4578 provider.discard(cx);
4579 }
4580
4581 self.take_active_inline_completion(cx).is_some()
4582 }
4583
4584 fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
4585 let Some(provider) = self.inline_completion_provider() else {
4586 return;
4587 };
4588 let Some(project) = self.project.as_ref() else {
4589 return;
4590 };
4591 let Some((_, buffer, _)) = self
4592 .buffer
4593 .read(cx)
4594 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4595 else {
4596 return;
4597 };
4598
4599 let project = project.read(cx);
4600 let extension = buffer
4601 .read(cx)
4602 .file()
4603 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4604 project.client().telemetry().report_inline_completion_event(
4605 provider.name().into(),
4606 accepted,
4607 extension,
4608 );
4609 }
4610
4611 pub fn has_active_inline_completion(&self) -> bool {
4612 self.active_inline_completion.is_some()
4613 }
4614
4615 fn take_active_inline_completion(
4616 &mut self,
4617 cx: &mut ViewContext<Self>,
4618 ) -> Option<InlineCompletion> {
4619 let active_inline_completion = self.active_inline_completion.take()?;
4620 self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
4621 self.clear_highlights::<InlineCompletionHighlight>(cx);
4622 Some(active_inline_completion.completion)
4623 }
4624
4625 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4626 let selection = self.selections.newest_anchor();
4627 let cursor = selection.head();
4628 let multibuffer = self.buffer.read(cx).snapshot(cx);
4629 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
4630 let excerpt_id = cursor.excerpt_id;
4631
4632 if !offset_selection.is_empty()
4633 || self
4634 .active_inline_completion
4635 .as_ref()
4636 .map_or(false, |completion| {
4637 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
4638 let invalidation_range = invalidation_range.start..=invalidation_range.end;
4639 !invalidation_range.contains(&offset_selection.head())
4640 })
4641 {
4642 self.discard_inline_completion(false, cx);
4643 return None;
4644 }
4645
4646 self.take_active_inline_completion(cx);
4647 let provider = self.inline_completion_provider()?;
4648
4649 let (buffer, cursor_buffer_position) =
4650 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4651
4652 let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
4653 let edits = completion
4654 .edits
4655 .into_iter()
4656 .map(|(range, new_text)| {
4657 (
4658 multibuffer
4659 .anchor_in_excerpt(excerpt_id, range.start)
4660 .unwrap()
4661 ..multibuffer
4662 .anchor_in_excerpt(excerpt_id, range.end)
4663 .unwrap(),
4664 new_text,
4665 )
4666 })
4667 .collect::<Vec<_>>();
4668 if edits.is_empty() {
4669 return None;
4670 }
4671
4672 let first_edit_start = edits.first().unwrap().0.start;
4673 let edit_start_row = first_edit_start
4674 .to_point(&multibuffer)
4675 .row
4676 .saturating_sub(2);
4677
4678 let last_edit_end = edits.last().unwrap().0.end;
4679 let edit_end_row = cmp::min(
4680 multibuffer.max_point().row,
4681 last_edit_end.to_point(&multibuffer).row + 2,
4682 );
4683
4684 let cursor_row = cursor.to_point(&multibuffer).row;
4685
4686 let mut inlay_ids = Vec::new();
4687 let invalidation_row_range;
4688 let completion;
4689 if cursor_row < edit_start_row {
4690 invalidation_row_range = cursor_row..edit_end_row;
4691 completion = InlineCompletion::Move(first_edit_start);
4692 } else if cursor_row > edit_end_row {
4693 invalidation_row_range = edit_start_row..cursor_row;
4694 completion = InlineCompletion::Move(first_edit_start);
4695 } else {
4696 if edits
4697 .iter()
4698 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
4699 {
4700 let mut inlays = Vec::new();
4701 for (range, new_text) in &edits {
4702 let inlay = Inlay::suggestion(
4703 post_inc(&mut self.next_inlay_id),
4704 range.start,
4705 new_text.as_str(),
4706 );
4707 inlay_ids.push(inlay.id);
4708 inlays.push(inlay);
4709 }
4710
4711 self.splice_inlays(vec![], inlays, cx);
4712 } else {
4713 let background_color = cx.theme().status().deleted_background;
4714 self.highlight_text::<InlineCompletionHighlight>(
4715 edits.iter().map(|(range, _)| range.clone()).collect(),
4716 HighlightStyle {
4717 background_color: Some(background_color),
4718 ..Default::default()
4719 },
4720 cx,
4721 );
4722 }
4723
4724 invalidation_row_range = edit_start_row..edit_end_row;
4725 completion = InlineCompletion::Edit(edits);
4726 };
4727
4728 let invalidation_range = multibuffer
4729 .anchor_before(Point::new(invalidation_row_range.start, 0))
4730 ..multibuffer.anchor_after(Point::new(
4731 invalidation_row_range.end,
4732 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
4733 ));
4734
4735 self.active_inline_completion = Some(InlineCompletionState {
4736 inlay_ids,
4737 completion,
4738 invalidation_range,
4739 });
4740 cx.notify();
4741
4742 Some(())
4743 }
4744
4745 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
4746 Some(self.inline_completion_provider.as_ref()?.provider.clone())
4747 }
4748
4749 fn render_code_actions_indicator(
4750 &self,
4751 _style: &EditorStyle,
4752 row: DisplayRow,
4753 is_active: bool,
4754 cx: &mut ViewContext<Self>,
4755 ) -> Option<IconButton> {
4756 if self.available_code_actions.is_some() {
4757 Some(
4758 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
4759 .shape(ui::IconButtonShape::Square)
4760 .icon_size(IconSize::XSmall)
4761 .icon_color(Color::Muted)
4762 .selected(is_active)
4763 .tooltip({
4764 let focus_handle = self.focus_handle.clone();
4765 move |cx| {
4766 Tooltip::for_action_in(
4767 "Toggle Code Actions",
4768 &ToggleCodeActions {
4769 deployed_from_indicator: None,
4770 },
4771 &focus_handle,
4772 cx,
4773 )
4774 }
4775 })
4776 .on_click(cx.listener(move |editor, _e, cx| {
4777 editor.focus(cx);
4778 editor.toggle_code_actions(
4779 &ToggleCodeActions {
4780 deployed_from_indicator: Some(row),
4781 },
4782 cx,
4783 );
4784 })),
4785 )
4786 } else {
4787 None
4788 }
4789 }
4790
4791 fn clear_tasks(&mut self) {
4792 self.tasks.clear()
4793 }
4794
4795 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
4796 if self.tasks.insert(key, value).is_some() {
4797 // This case should hopefully be rare, but just in case...
4798 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
4799 }
4800 }
4801
4802 fn build_tasks_context(
4803 project: &Model<Project>,
4804 buffer: &Model<Buffer>,
4805 buffer_row: u32,
4806 tasks: &Arc<RunnableTasks>,
4807 cx: &mut ViewContext<Self>,
4808 ) -> Task<Option<task::TaskContext>> {
4809 let position = Point::new(buffer_row, tasks.column);
4810 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4811 let location = Location {
4812 buffer: buffer.clone(),
4813 range: range_start..range_start,
4814 };
4815 // Fill in the environmental variables from the tree-sitter captures
4816 let mut captured_task_variables = TaskVariables::default();
4817 for (capture_name, value) in tasks.extra_variables.clone() {
4818 captured_task_variables.insert(
4819 task::VariableName::Custom(capture_name.into()),
4820 value.clone(),
4821 );
4822 }
4823 project.update(cx, |project, cx| {
4824 project.task_store().update(cx, |task_store, cx| {
4825 task_store.task_context_for_location(captured_task_variables, location, cx)
4826 })
4827 })
4828 }
4829
4830 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
4831 let Some((workspace, _)) = self.workspace.clone() else {
4832 return;
4833 };
4834 let Some(project) = self.project.clone() else {
4835 return;
4836 };
4837
4838 // Try to find a closest, enclosing node using tree-sitter that has a
4839 // task
4840 let Some((buffer, buffer_row, tasks)) = self
4841 .find_enclosing_node_task(cx)
4842 // Or find the task that's closest in row-distance.
4843 .or_else(|| self.find_closest_task(cx))
4844 else {
4845 return;
4846 };
4847
4848 let reveal_strategy = action.reveal;
4849 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
4850 cx.spawn(|_, mut cx| async move {
4851 let context = task_context.await?;
4852 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
4853
4854 let resolved = resolved_task.resolved.as_mut()?;
4855 resolved.reveal = reveal_strategy;
4856
4857 workspace
4858 .update(&mut cx, |workspace, cx| {
4859 workspace::tasks::schedule_resolved_task(
4860 workspace,
4861 task_source_kind,
4862 resolved_task,
4863 false,
4864 cx,
4865 );
4866 })
4867 .ok()
4868 })
4869 .detach();
4870 }
4871
4872 fn find_closest_task(
4873 &mut self,
4874 cx: &mut ViewContext<Self>,
4875 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
4876 let cursor_row = self.selections.newest_adjusted(cx).head().row;
4877
4878 let ((buffer_id, row), tasks) = self
4879 .tasks
4880 .iter()
4881 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
4882
4883 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
4884 let tasks = Arc::new(tasks.to_owned());
4885 Some((buffer, *row, tasks))
4886 }
4887
4888 fn find_enclosing_node_task(
4889 &mut self,
4890 cx: &mut ViewContext<Self>,
4891 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
4892 let snapshot = self.buffer.read(cx).snapshot(cx);
4893 let offset = self.selections.newest::<usize>(cx).head();
4894 let excerpt = snapshot.excerpt_containing(offset..offset)?;
4895 let buffer_id = excerpt.buffer().remote_id();
4896
4897 let layer = excerpt.buffer().syntax_layer_at(offset)?;
4898 let mut cursor = layer.node().walk();
4899
4900 while cursor.goto_first_child_for_byte(offset).is_some() {
4901 if cursor.node().end_byte() == offset {
4902 cursor.goto_next_sibling();
4903 }
4904 }
4905
4906 // Ascend to the smallest ancestor that contains the range and has a task.
4907 loop {
4908 let node = cursor.node();
4909 let node_range = node.byte_range();
4910 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
4911
4912 // Check if this node contains our offset
4913 if node_range.start <= offset && node_range.end >= offset {
4914 // If it contains offset, check for task
4915 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
4916 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
4917 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
4918 }
4919 }
4920
4921 if !cursor.goto_parent() {
4922 break;
4923 }
4924 }
4925 None
4926 }
4927
4928 fn render_run_indicator(
4929 &self,
4930 _style: &EditorStyle,
4931 is_active: bool,
4932 row: DisplayRow,
4933 cx: &mut ViewContext<Self>,
4934 ) -> IconButton {
4935 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
4936 .shape(ui::IconButtonShape::Square)
4937 .icon_size(IconSize::XSmall)
4938 .icon_color(Color::Muted)
4939 .selected(is_active)
4940 .on_click(cx.listener(move |editor, _e, cx| {
4941 editor.focus(cx);
4942 editor.toggle_code_actions(
4943 &ToggleCodeActions {
4944 deployed_from_indicator: Some(row),
4945 },
4946 cx,
4947 );
4948 }))
4949 }
4950
4951 pub fn context_menu_visible(&self) -> bool {
4952 self.context_menu
4953 .read()
4954 .as_ref()
4955 .map_or(false, |menu| menu.visible())
4956 }
4957
4958 fn render_context_menu(
4959 &self,
4960 cursor_position: DisplayPoint,
4961 style: &EditorStyle,
4962 max_height: Pixels,
4963 cx: &mut ViewContext<Editor>,
4964 ) -> Option<(ContextMenuOrigin, AnyElement)> {
4965 self.context_menu.read().as_ref().map(|menu| {
4966 menu.render(
4967 cursor_position,
4968 style,
4969 max_height,
4970 self.workspace.as_ref().map(|(w, _)| w.clone()),
4971 cx,
4972 )
4973 })
4974 }
4975
4976 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
4977 cx.notify();
4978 self.completion_tasks.clear();
4979 self.context_menu.write().take()
4980 }
4981
4982 fn show_snippet_choices(
4983 &mut self,
4984 choices: &Vec<String>,
4985 selection: Range<Anchor>,
4986 cx: &mut ViewContext<Self>,
4987 ) {
4988 if selection.start.buffer_id.is_none() {
4989 return;
4990 }
4991 let buffer_id = selection.start.buffer_id.unwrap();
4992 let buffer = self.buffer().read(cx).buffer(buffer_id);
4993 let id = post_inc(&mut self.next_completion_id);
4994
4995 if let Some(buffer) = buffer {
4996 *self.context_menu.write() = Some(CodeContextMenu::Completions(
4997 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
4998 ));
4999 }
5000 }
5001
5002 pub fn insert_snippet(
5003 &mut self,
5004 insertion_ranges: &[Range<usize>],
5005 snippet: Snippet,
5006 cx: &mut ViewContext<Self>,
5007 ) -> Result<()> {
5008 struct Tabstop<T> {
5009 is_end_tabstop: bool,
5010 ranges: Vec<Range<T>>,
5011 choices: Option<Vec<String>>,
5012 }
5013
5014 let tabstops = self.buffer.update(cx, |buffer, cx| {
5015 let snippet_text: Arc<str> = snippet.text.clone().into();
5016 buffer.edit(
5017 insertion_ranges
5018 .iter()
5019 .cloned()
5020 .map(|range| (range, snippet_text.clone())),
5021 Some(AutoindentMode::EachLine),
5022 cx,
5023 );
5024
5025 let snapshot = &*buffer.read(cx);
5026 let snippet = &snippet;
5027 snippet
5028 .tabstops
5029 .iter()
5030 .map(|tabstop| {
5031 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5032 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5033 });
5034 let mut tabstop_ranges = tabstop
5035 .ranges
5036 .iter()
5037 .flat_map(|tabstop_range| {
5038 let mut delta = 0_isize;
5039 insertion_ranges.iter().map(move |insertion_range| {
5040 let insertion_start = insertion_range.start as isize + delta;
5041 delta +=
5042 snippet.text.len() as isize - insertion_range.len() as isize;
5043
5044 let start = ((insertion_start + tabstop_range.start) as usize)
5045 .min(snapshot.len());
5046 let end = ((insertion_start + tabstop_range.end) as usize)
5047 .min(snapshot.len());
5048 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5049 })
5050 })
5051 .collect::<Vec<_>>();
5052 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5053
5054 Tabstop {
5055 is_end_tabstop,
5056 ranges: tabstop_ranges,
5057 choices: tabstop.choices.clone(),
5058 }
5059 })
5060 .collect::<Vec<_>>()
5061 });
5062 if let Some(tabstop) = tabstops.first() {
5063 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5064 s.select_ranges(tabstop.ranges.iter().cloned());
5065 });
5066
5067 if let Some(choices) = &tabstop.choices {
5068 if let Some(selection) = tabstop.ranges.first() {
5069 self.show_snippet_choices(choices, selection.clone(), cx)
5070 }
5071 }
5072
5073 // If we're already at the last tabstop and it's at the end of the snippet,
5074 // we're done, we don't need to keep the state around.
5075 if !tabstop.is_end_tabstop {
5076 let choices = tabstops
5077 .iter()
5078 .map(|tabstop| tabstop.choices.clone())
5079 .collect();
5080
5081 let ranges = tabstops
5082 .into_iter()
5083 .map(|tabstop| tabstop.ranges)
5084 .collect::<Vec<_>>();
5085
5086 self.snippet_stack.push(SnippetState {
5087 active_index: 0,
5088 ranges,
5089 choices,
5090 });
5091 }
5092
5093 // Check whether the just-entered snippet ends with an auto-closable bracket.
5094 if self.autoclose_regions.is_empty() {
5095 let snapshot = self.buffer.read(cx).snapshot(cx);
5096 for selection in &mut self.selections.all::<Point>(cx) {
5097 let selection_head = selection.head();
5098 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5099 continue;
5100 };
5101
5102 let mut bracket_pair = None;
5103 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5104 let prev_chars = snapshot
5105 .reversed_chars_at(selection_head)
5106 .collect::<String>();
5107 for (pair, enabled) in scope.brackets() {
5108 if enabled
5109 && pair.close
5110 && prev_chars.starts_with(pair.start.as_str())
5111 && next_chars.starts_with(pair.end.as_str())
5112 {
5113 bracket_pair = Some(pair.clone());
5114 break;
5115 }
5116 }
5117 if let Some(pair) = bracket_pair {
5118 let start = snapshot.anchor_after(selection_head);
5119 let end = snapshot.anchor_after(selection_head);
5120 self.autoclose_regions.push(AutocloseRegion {
5121 selection_id: selection.id,
5122 range: start..end,
5123 pair,
5124 });
5125 }
5126 }
5127 }
5128 }
5129 Ok(())
5130 }
5131
5132 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5133 self.move_to_snippet_tabstop(Bias::Right, cx)
5134 }
5135
5136 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5137 self.move_to_snippet_tabstop(Bias::Left, cx)
5138 }
5139
5140 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5141 if let Some(mut snippet) = self.snippet_stack.pop() {
5142 match bias {
5143 Bias::Left => {
5144 if snippet.active_index > 0 {
5145 snippet.active_index -= 1;
5146 } else {
5147 self.snippet_stack.push(snippet);
5148 return false;
5149 }
5150 }
5151 Bias::Right => {
5152 if snippet.active_index + 1 < snippet.ranges.len() {
5153 snippet.active_index += 1;
5154 } else {
5155 self.snippet_stack.push(snippet);
5156 return false;
5157 }
5158 }
5159 }
5160 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5161 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5162 s.select_anchor_ranges(current_ranges.iter().cloned())
5163 });
5164
5165 if let Some(choices) = &snippet.choices[snippet.active_index] {
5166 if let Some(selection) = current_ranges.first() {
5167 self.show_snippet_choices(&choices, selection.clone(), cx);
5168 }
5169 }
5170
5171 // If snippet state is not at the last tabstop, push it back on the stack
5172 if snippet.active_index + 1 < snippet.ranges.len() {
5173 self.snippet_stack.push(snippet);
5174 }
5175 return true;
5176 }
5177 }
5178
5179 false
5180 }
5181
5182 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5183 self.transact(cx, |this, cx| {
5184 this.select_all(&SelectAll, cx);
5185 this.insert("", cx);
5186 });
5187 }
5188
5189 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5190 self.transact(cx, |this, cx| {
5191 this.select_autoclose_pair(cx);
5192 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5193 if !this.linked_edit_ranges.is_empty() {
5194 let selections = this.selections.all::<MultiBufferPoint>(cx);
5195 let snapshot = this.buffer.read(cx).snapshot(cx);
5196
5197 for selection in selections.iter() {
5198 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5199 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5200 if selection_start.buffer_id != selection_end.buffer_id {
5201 continue;
5202 }
5203 if let Some(ranges) =
5204 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5205 {
5206 for (buffer, entries) in ranges {
5207 linked_ranges.entry(buffer).or_default().extend(entries);
5208 }
5209 }
5210 }
5211 }
5212
5213 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5214 if !this.selections.line_mode {
5215 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5216 for selection in &mut selections {
5217 if selection.is_empty() {
5218 let old_head = selection.head();
5219 let mut new_head =
5220 movement::left(&display_map, old_head.to_display_point(&display_map))
5221 .to_point(&display_map);
5222 if let Some((buffer, line_buffer_range)) = display_map
5223 .buffer_snapshot
5224 .buffer_line_for_row(MultiBufferRow(old_head.row))
5225 {
5226 let indent_size =
5227 buffer.indent_size_for_line(line_buffer_range.start.row);
5228 let indent_len = match indent_size.kind {
5229 IndentKind::Space => {
5230 buffer.settings_at(line_buffer_range.start, cx).tab_size
5231 }
5232 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5233 };
5234 if old_head.column <= indent_size.len && old_head.column > 0 {
5235 let indent_len = indent_len.get();
5236 new_head = cmp::min(
5237 new_head,
5238 MultiBufferPoint::new(
5239 old_head.row,
5240 ((old_head.column - 1) / indent_len) * indent_len,
5241 ),
5242 );
5243 }
5244 }
5245
5246 selection.set_head(new_head, SelectionGoal::None);
5247 }
5248 }
5249 }
5250
5251 this.signature_help_state.set_backspace_pressed(true);
5252 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5253 this.insert("", cx);
5254 let empty_str: Arc<str> = Arc::from("");
5255 for (buffer, edits) in linked_ranges {
5256 let snapshot = buffer.read(cx).snapshot();
5257 use text::ToPoint as TP;
5258
5259 let edits = edits
5260 .into_iter()
5261 .map(|range| {
5262 let end_point = TP::to_point(&range.end, &snapshot);
5263 let mut start_point = TP::to_point(&range.start, &snapshot);
5264
5265 if end_point == start_point {
5266 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5267 .saturating_sub(1);
5268 start_point = TP::to_point(&offset, &snapshot);
5269 };
5270
5271 (start_point..end_point, empty_str.clone())
5272 })
5273 .sorted_by_key(|(range, _)| range.start)
5274 .collect::<Vec<_>>();
5275 buffer.update(cx, |this, cx| {
5276 this.edit(edits, None, cx);
5277 })
5278 }
5279 this.refresh_inline_completion(true, false, cx);
5280 linked_editing_ranges::refresh_linked_ranges(this, cx);
5281 });
5282 }
5283
5284 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5285 self.transact(cx, |this, cx| {
5286 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5287 let line_mode = s.line_mode;
5288 s.move_with(|map, selection| {
5289 if selection.is_empty() && !line_mode {
5290 let cursor = movement::right(map, selection.head());
5291 selection.end = cursor;
5292 selection.reversed = true;
5293 selection.goal = SelectionGoal::None;
5294 }
5295 })
5296 });
5297 this.insert("", cx);
5298 this.refresh_inline_completion(true, false, cx);
5299 });
5300 }
5301
5302 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5303 if self.move_to_prev_snippet_tabstop(cx) {
5304 return;
5305 }
5306
5307 self.outdent(&Outdent, cx);
5308 }
5309
5310 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5311 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5312 return;
5313 }
5314
5315 let mut selections = self.selections.all_adjusted(cx);
5316 let buffer = self.buffer.read(cx);
5317 let snapshot = buffer.snapshot(cx);
5318 let rows_iter = selections.iter().map(|s| s.head().row);
5319 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5320
5321 let mut edits = Vec::new();
5322 let mut prev_edited_row = 0;
5323 let mut row_delta = 0;
5324 for selection in &mut selections {
5325 if selection.start.row != prev_edited_row {
5326 row_delta = 0;
5327 }
5328 prev_edited_row = selection.end.row;
5329
5330 // If the selection is non-empty, then increase the indentation of the selected lines.
5331 if !selection.is_empty() {
5332 row_delta =
5333 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5334 continue;
5335 }
5336
5337 // If the selection is empty and the cursor is in the leading whitespace before the
5338 // suggested indentation, then auto-indent the line.
5339 let cursor = selection.head();
5340 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5341 if let Some(suggested_indent) =
5342 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5343 {
5344 if cursor.column < suggested_indent.len
5345 && cursor.column <= current_indent.len
5346 && current_indent.len <= suggested_indent.len
5347 {
5348 selection.start = Point::new(cursor.row, suggested_indent.len);
5349 selection.end = selection.start;
5350 if row_delta == 0 {
5351 edits.extend(Buffer::edit_for_indent_size_adjustment(
5352 cursor.row,
5353 current_indent,
5354 suggested_indent,
5355 ));
5356 row_delta = suggested_indent.len - current_indent.len;
5357 }
5358 continue;
5359 }
5360 }
5361
5362 // Otherwise, insert a hard or soft tab.
5363 let settings = buffer.settings_at(cursor, cx);
5364 let tab_size = if settings.hard_tabs {
5365 IndentSize::tab()
5366 } else {
5367 let tab_size = settings.tab_size.get();
5368 let char_column = snapshot
5369 .text_for_range(Point::new(cursor.row, 0)..cursor)
5370 .flat_map(str::chars)
5371 .count()
5372 + row_delta as usize;
5373 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5374 IndentSize::spaces(chars_to_next_tab_stop)
5375 };
5376 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5377 selection.end = selection.start;
5378 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5379 row_delta += tab_size.len;
5380 }
5381
5382 self.transact(cx, |this, cx| {
5383 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5384 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5385 this.refresh_inline_completion(true, false, cx);
5386 });
5387 }
5388
5389 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5390 if self.read_only(cx) {
5391 return;
5392 }
5393 let mut selections = self.selections.all::<Point>(cx);
5394 let mut prev_edited_row = 0;
5395 let mut row_delta = 0;
5396 let mut edits = Vec::new();
5397 let buffer = self.buffer.read(cx);
5398 let snapshot = buffer.snapshot(cx);
5399 for selection in &mut selections {
5400 if selection.start.row != prev_edited_row {
5401 row_delta = 0;
5402 }
5403 prev_edited_row = selection.end.row;
5404
5405 row_delta =
5406 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5407 }
5408
5409 self.transact(cx, |this, cx| {
5410 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5411 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5412 });
5413 }
5414
5415 fn indent_selection(
5416 buffer: &MultiBuffer,
5417 snapshot: &MultiBufferSnapshot,
5418 selection: &mut Selection<Point>,
5419 edits: &mut Vec<(Range<Point>, String)>,
5420 delta_for_start_row: u32,
5421 cx: &AppContext,
5422 ) -> u32 {
5423 let settings = buffer.settings_at(selection.start, cx);
5424 let tab_size = settings.tab_size.get();
5425 let indent_kind = if settings.hard_tabs {
5426 IndentKind::Tab
5427 } else {
5428 IndentKind::Space
5429 };
5430 let mut start_row = selection.start.row;
5431 let mut end_row = selection.end.row + 1;
5432
5433 // If a selection ends at the beginning of a line, don't indent
5434 // that last line.
5435 if selection.end.column == 0 && selection.end.row > selection.start.row {
5436 end_row -= 1;
5437 }
5438
5439 // Avoid re-indenting a row that has already been indented by a
5440 // previous selection, but still update this selection's column
5441 // to reflect that indentation.
5442 if delta_for_start_row > 0 {
5443 start_row += 1;
5444 selection.start.column += delta_for_start_row;
5445 if selection.end.row == selection.start.row {
5446 selection.end.column += delta_for_start_row;
5447 }
5448 }
5449
5450 let mut delta_for_end_row = 0;
5451 let has_multiple_rows = start_row + 1 != end_row;
5452 for row in start_row..end_row {
5453 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5454 let indent_delta = match (current_indent.kind, indent_kind) {
5455 (IndentKind::Space, IndentKind::Space) => {
5456 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5457 IndentSize::spaces(columns_to_next_tab_stop)
5458 }
5459 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5460 (_, IndentKind::Tab) => IndentSize::tab(),
5461 };
5462
5463 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5464 0
5465 } else {
5466 selection.start.column
5467 };
5468 let row_start = Point::new(row, start);
5469 edits.push((
5470 row_start..row_start,
5471 indent_delta.chars().collect::<String>(),
5472 ));
5473
5474 // Update this selection's endpoints to reflect the indentation.
5475 if row == selection.start.row {
5476 selection.start.column += indent_delta.len;
5477 }
5478 if row == selection.end.row {
5479 selection.end.column += indent_delta.len;
5480 delta_for_end_row = indent_delta.len;
5481 }
5482 }
5483
5484 if selection.start.row == selection.end.row {
5485 delta_for_start_row + delta_for_end_row
5486 } else {
5487 delta_for_end_row
5488 }
5489 }
5490
5491 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5492 if self.read_only(cx) {
5493 return;
5494 }
5495 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5496 let selections = self.selections.all::<Point>(cx);
5497 let mut deletion_ranges = Vec::new();
5498 let mut last_outdent = None;
5499 {
5500 let buffer = self.buffer.read(cx);
5501 let snapshot = buffer.snapshot(cx);
5502 for selection in &selections {
5503 let settings = buffer.settings_at(selection.start, cx);
5504 let tab_size = settings.tab_size.get();
5505 let mut rows = selection.spanned_rows(false, &display_map);
5506
5507 // Avoid re-outdenting a row that has already been outdented by a
5508 // previous selection.
5509 if let Some(last_row) = last_outdent {
5510 if last_row == rows.start {
5511 rows.start = rows.start.next_row();
5512 }
5513 }
5514 let has_multiple_rows = rows.len() > 1;
5515 for row in rows.iter_rows() {
5516 let indent_size = snapshot.indent_size_for_line(row);
5517 if indent_size.len > 0 {
5518 let deletion_len = match indent_size.kind {
5519 IndentKind::Space => {
5520 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5521 if columns_to_prev_tab_stop == 0 {
5522 tab_size
5523 } else {
5524 columns_to_prev_tab_stop
5525 }
5526 }
5527 IndentKind::Tab => 1,
5528 };
5529 let start = if has_multiple_rows
5530 || deletion_len > selection.start.column
5531 || indent_size.len < selection.start.column
5532 {
5533 0
5534 } else {
5535 selection.start.column - deletion_len
5536 };
5537 deletion_ranges.push(
5538 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5539 );
5540 last_outdent = Some(row);
5541 }
5542 }
5543 }
5544 }
5545
5546 self.transact(cx, |this, cx| {
5547 this.buffer.update(cx, |buffer, cx| {
5548 let empty_str: Arc<str> = Arc::default();
5549 buffer.edit(
5550 deletion_ranges
5551 .into_iter()
5552 .map(|range| (range, empty_str.clone())),
5553 None,
5554 cx,
5555 );
5556 });
5557 let selections = this.selections.all::<usize>(cx);
5558 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5559 });
5560 }
5561
5562 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
5563 if self.read_only(cx) {
5564 return;
5565 }
5566 let selections = self
5567 .selections
5568 .all::<usize>(cx)
5569 .into_iter()
5570 .map(|s| s.range());
5571
5572 self.transact(cx, |this, cx| {
5573 this.buffer.update(cx, |buffer, cx| {
5574 buffer.autoindent_ranges(selections, cx);
5575 });
5576 let selections = this.selections.all::<usize>(cx);
5577 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5578 });
5579 }
5580
5581 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5582 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5583 let selections = self.selections.all::<Point>(cx);
5584
5585 let mut new_cursors = Vec::new();
5586 let mut edit_ranges = Vec::new();
5587 let mut selections = selections.iter().peekable();
5588 while let Some(selection) = selections.next() {
5589 let mut rows = selection.spanned_rows(false, &display_map);
5590 let goal_display_column = selection.head().to_display_point(&display_map).column();
5591
5592 // Accumulate contiguous regions of rows that we want to delete.
5593 while let Some(next_selection) = selections.peek() {
5594 let next_rows = next_selection.spanned_rows(false, &display_map);
5595 if next_rows.start <= rows.end {
5596 rows.end = next_rows.end;
5597 selections.next().unwrap();
5598 } else {
5599 break;
5600 }
5601 }
5602
5603 let buffer = &display_map.buffer_snapshot;
5604 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5605 let edit_end;
5606 let cursor_buffer_row;
5607 if buffer.max_point().row >= rows.end.0 {
5608 // If there's a line after the range, delete the \n from the end of the row range
5609 // and position the cursor on the next line.
5610 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5611 cursor_buffer_row = rows.end;
5612 } else {
5613 // If there isn't a line after the range, delete the \n from the line before the
5614 // start of the row range and position the cursor there.
5615 edit_start = edit_start.saturating_sub(1);
5616 edit_end = buffer.len();
5617 cursor_buffer_row = rows.start.previous_row();
5618 }
5619
5620 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5621 *cursor.column_mut() =
5622 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5623
5624 new_cursors.push((
5625 selection.id,
5626 buffer.anchor_after(cursor.to_point(&display_map)),
5627 ));
5628 edit_ranges.push(edit_start..edit_end);
5629 }
5630
5631 self.transact(cx, |this, cx| {
5632 let buffer = this.buffer.update(cx, |buffer, cx| {
5633 let empty_str: Arc<str> = Arc::default();
5634 buffer.edit(
5635 edit_ranges
5636 .into_iter()
5637 .map(|range| (range, empty_str.clone())),
5638 None,
5639 cx,
5640 );
5641 buffer.snapshot(cx)
5642 });
5643 let new_selections = new_cursors
5644 .into_iter()
5645 .map(|(id, cursor)| {
5646 let cursor = cursor.to_point(&buffer);
5647 Selection {
5648 id,
5649 start: cursor,
5650 end: cursor,
5651 reversed: false,
5652 goal: SelectionGoal::None,
5653 }
5654 })
5655 .collect();
5656
5657 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5658 s.select(new_selections);
5659 });
5660 });
5661 }
5662
5663 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5664 if self.read_only(cx) {
5665 return;
5666 }
5667 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5668 for selection in self.selections.all::<Point>(cx) {
5669 let start = MultiBufferRow(selection.start.row);
5670 // Treat single line selections as if they include the next line. Otherwise this action
5671 // would do nothing for single line selections individual cursors.
5672 let end = if selection.start.row == selection.end.row {
5673 MultiBufferRow(selection.start.row + 1)
5674 } else {
5675 MultiBufferRow(selection.end.row)
5676 };
5677
5678 if let Some(last_row_range) = row_ranges.last_mut() {
5679 if start <= last_row_range.end {
5680 last_row_range.end = end;
5681 continue;
5682 }
5683 }
5684 row_ranges.push(start..end);
5685 }
5686
5687 let snapshot = self.buffer.read(cx).snapshot(cx);
5688 let mut cursor_positions = Vec::new();
5689 for row_range in &row_ranges {
5690 let anchor = snapshot.anchor_before(Point::new(
5691 row_range.end.previous_row().0,
5692 snapshot.line_len(row_range.end.previous_row()),
5693 ));
5694 cursor_positions.push(anchor..anchor);
5695 }
5696
5697 self.transact(cx, |this, cx| {
5698 for row_range in row_ranges.into_iter().rev() {
5699 for row in row_range.iter_rows().rev() {
5700 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5701 let next_line_row = row.next_row();
5702 let indent = snapshot.indent_size_for_line(next_line_row);
5703 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5704
5705 let replace = if snapshot.line_len(next_line_row) > indent.len {
5706 " "
5707 } else {
5708 ""
5709 };
5710
5711 this.buffer.update(cx, |buffer, cx| {
5712 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5713 });
5714 }
5715 }
5716
5717 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5718 s.select_anchor_ranges(cursor_positions)
5719 });
5720 });
5721 }
5722
5723 pub fn sort_lines_case_sensitive(
5724 &mut self,
5725 _: &SortLinesCaseSensitive,
5726 cx: &mut ViewContext<Self>,
5727 ) {
5728 self.manipulate_lines(cx, |lines| lines.sort())
5729 }
5730
5731 pub fn sort_lines_case_insensitive(
5732 &mut self,
5733 _: &SortLinesCaseInsensitive,
5734 cx: &mut ViewContext<Self>,
5735 ) {
5736 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5737 }
5738
5739 pub fn unique_lines_case_insensitive(
5740 &mut self,
5741 _: &UniqueLinesCaseInsensitive,
5742 cx: &mut ViewContext<Self>,
5743 ) {
5744 self.manipulate_lines(cx, |lines| {
5745 let mut seen = HashSet::default();
5746 lines.retain(|line| seen.insert(line.to_lowercase()));
5747 })
5748 }
5749
5750 pub fn unique_lines_case_sensitive(
5751 &mut self,
5752 _: &UniqueLinesCaseSensitive,
5753 cx: &mut ViewContext<Self>,
5754 ) {
5755 self.manipulate_lines(cx, |lines| {
5756 let mut seen = HashSet::default();
5757 lines.retain(|line| seen.insert(*line));
5758 })
5759 }
5760
5761 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
5762 let mut revert_changes = HashMap::default();
5763 let snapshot = self.snapshot(cx);
5764 for hunk in hunks_for_ranges(
5765 Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
5766 &snapshot,
5767 ) {
5768 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5769 }
5770 if !revert_changes.is_empty() {
5771 self.transact(cx, |editor, cx| {
5772 editor.revert(revert_changes, cx);
5773 });
5774 }
5775 }
5776
5777 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
5778 let Some(project) = self.project.clone() else {
5779 return;
5780 };
5781 self.reload(project, cx).detach_and_notify_err(cx);
5782 }
5783
5784 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
5785 let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
5786 if !revert_changes.is_empty() {
5787 self.transact(cx, |editor, cx| {
5788 editor.revert(revert_changes, cx);
5789 });
5790 }
5791 }
5792
5793 fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
5794 let snapshot = self.buffer.read(cx).read(cx);
5795 if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
5796 drop(snapshot);
5797 let mut revert_changes = HashMap::default();
5798 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5799 if !revert_changes.is_empty() {
5800 self.revert(revert_changes, cx)
5801 }
5802 }
5803 }
5804
5805 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
5806 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
5807 let project_path = buffer.read(cx).project_path(cx)?;
5808 let project = self.project.as_ref()?.read(cx);
5809 let entry = project.entry_for_path(&project_path, cx)?;
5810 let parent = match &entry.canonical_path {
5811 Some(canonical_path) => canonical_path.to_path_buf(),
5812 None => project.absolute_path(&project_path, cx)?,
5813 }
5814 .parent()?
5815 .to_path_buf();
5816 Some(parent)
5817 }) {
5818 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
5819 }
5820 }
5821
5822 fn gather_revert_changes(
5823 &mut self,
5824 selections: &[Selection<Point>],
5825 cx: &mut ViewContext<'_, Editor>,
5826 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
5827 let mut revert_changes = HashMap::default();
5828 let snapshot = self.snapshot(cx);
5829 for hunk in hunks_for_selections(&snapshot, selections) {
5830 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5831 }
5832 revert_changes
5833 }
5834
5835 pub fn prepare_revert_change(
5836 &mut self,
5837 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
5838 hunk: &MultiBufferDiffHunk,
5839 cx: &AppContext,
5840 ) -> Option<()> {
5841 let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
5842 let buffer = buffer.read(cx);
5843 let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
5844 let original_text = change_set
5845 .read(cx)
5846 .base_text
5847 .as_ref()?
5848 .read(cx)
5849 .as_rope()
5850 .slice(hunk.diff_base_byte_range.clone());
5851 let buffer_snapshot = buffer.snapshot();
5852 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
5853 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
5854 probe
5855 .0
5856 .start
5857 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
5858 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
5859 }) {
5860 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
5861 Some(())
5862 } else {
5863 None
5864 }
5865 }
5866
5867 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
5868 self.manipulate_lines(cx, |lines| lines.reverse())
5869 }
5870
5871 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
5872 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
5873 }
5874
5875 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
5876 where
5877 Fn: FnMut(&mut Vec<&str>),
5878 {
5879 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5880 let buffer = self.buffer.read(cx).snapshot(cx);
5881
5882 let mut edits = Vec::new();
5883
5884 let selections = self.selections.all::<Point>(cx);
5885 let mut selections = selections.iter().peekable();
5886 let mut contiguous_row_selections = Vec::new();
5887 let mut new_selections = Vec::new();
5888 let mut added_lines = 0;
5889 let mut removed_lines = 0;
5890
5891 while let Some(selection) = selections.next() {
5892 let (start_row, end_row) = consume_contiguous_rows(
5893 &mut contiguous_row_selections,
5894 selection,
5895 &display_map,
5896 &mut selections,
5897 );
5898
5899 let start_point = Point::new(start_row.0, 0);
5900 let end_point = Point::new(
5901 end_row.previous_row().0,
5902 buffer.line_len(end_row.previous_row()),
5903 );
5904 let text = buffer
5905 .text_for_range(start_point..end_point)
5906 .collect::<String>();
5907
5908 let mut lines = text.split('\n').collect_vec();
5909
5910 let lines_before = lines.len();
5911 callback(&mut lines);
5912 let lines_after = lines.len();
5913
5914 edits.push((start_point..end_point, lines.join("\n")));
5915
5916 // Selections must change based on added and removed line count
5917 let start_row =
5918 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
5919 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
5920 new_selections.push(Selection {
5921 id: selection.id,
5922 start: start_row,
5923 end: end_row,
5924 goal: SelectionGoal::None,
5925 reversed: selection.reversed,
5926 });
5927
5928 if lines_after > lines_before {
5929 added_lines += lines_after - lines_before;
5930 } else if lines_before > lines_after {
5931 removed_lines += lines_before - lines_after;
5932 }
5933 }
5934
5935 self.transact(cx, |this, cx| {
5936 let buffer = this.buffer.update(cx, |buffer, cx| {
5937 buffer.edit(edits, None, cx);
5938 buffer.snapshot(cx)
5939 });
5940
5941 // Recalculate offsets on newly edited buffer
5942 let new_selections = new_selections
5943 .iter()
5944 .map(|s| {
5945 let start_point = Point::new(s.start.0, 0);
5946 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
5947 Selection {
5948 id: s.id,
5949 start: buffer.point_to_offset(start_point),
5950 end: buffer.point_to_offset(end_point),
5951 goal: s.goal,
5952 reversed: s.reversed,
5953 }
5954 })
5955 .collect();
5956
5957 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5958 s.select(new_selections);
5959 });
5960
5961 this.request_autoscroll(Autoscroll::fit(), cx);
5962 });
5963 }
5964
5965 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
5966 self.manipulate_text(cx, |text| text.to_uppercase())
5967 }
5968
5969 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
5970 self.manipulate_text(cx, |text| text.to_lowercase())
5971 }
5972
5973 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
5974 self.manipulate_text(cx, |text| {
5975 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
5976 // https://github.com/rutrum/convert-case/issues/16
5977 text.split('\n')
5978 .map(|line| line.to_case(Case::Title))
5979 .join("\n")
5980 })
5981 }
5982
5983 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
5984 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
5985 }
5986
5987 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
5988 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
5989 }
5990
5991 pub fn convert_to_upper_camel_case(
5992 &mut self,
5993 _: &ConvertToUpperCamelCase,
5994 cx: &mut ViewContext<Self>,
5995 ) {
5996 self.manipulate_text(cx, |text| {
5997 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
5998 // https://github.com/rutrum/convert-case/issues/16
5999 text.split('\n')
6000 .map(|line| line.to_case(Case::UpperCamel))
6001 .join("\n")
6002 })
6003 }
6004
6005 pub fn convert_to_lower_camel_case(
6006 &mut self,
6007 _: &ConvertToLowerCamelCase,
6008 cx: &mut ViewContext<Self>,
6009 ) {
6010 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6011 }
6012
6013 pub fn convert_to_opposite_case(
6014 &mut self,
6015 _: &ConvertToOppositeCase,
6016 cx: &mut ViewContext<Self>,
6017 ) {
6018 self.manipulate_text(cx, |text| {
6019 text.chars()
6020 .fold(String::with_capacity(text.len()), |mut t, c| {
6021 if c.is_uppercase() {
6022 t.extend(c.to_lowercase());
6023 } else {
6024 t.extend(c.to_uppercase());
6025 }
6026 t
6027 })
6028 })
6029 }
6030
6031 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6032 where
6033 Fn: FnMut(&str) -> String,
6034 {
6035 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6036 let buffer = self.buffer.read(cx).snapshot(cx);
6037
6038 let mut new_selections = Vec::new();
6039 let mut edits = Vec::new();
6040 let mut selection_adjustment = 0i32;
6041
6042 for selection in self.selections.all::<usize>(cx) {
6043 let selection_is_empty = selection.is_empty();
6044
6045 let (start, end) = if selection_is_empty {
6046 let word_range = movement::surrounding_word(
6047 &display_map,
6048 selection.start.to_display_point(&display_map),
6049 );
6050 let start = word_range.start.to_offset(&display_map, Bias::Left);
6051 let end = word_range.end.to_offset(&display_map, Bias::Left);
6052 (start, end)
6053 } else {
6054 (selection.start, selection.end)
6055 };
6056
6057 let text = buffer.text_for_range(start..end).collect::<String>();
6058 let old_length = text.len() as i32;
6059 let text = callback(&text);
6060
6061 new_selections.push(Selection {
6062 start: (start as i32 - selection_adjustment) as usize,
6063 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6064 goal: SelectionGoal::None,
6065 ..selection
6066 });
6067
6068 selection_adjustment += old_length - text.len() as i32;
6069
6070 edits.push((start..end, text));
6071 }
6072
6073 self.transact(cx, |this, cx| {
6074 this.buffer.update(cx, |buffer, cx| {
6075 buffer.edit(edits, None, cx);
6076 });
6077
6078 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6079 s.select(new_selections);
6080 });
6081
6082 this.request_autoscroll(Autoscroll::fit(), cx);
6083 });
6084 }
6085
6086 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6087 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6088 let buffer = &display_map.buffer_snapshot;
6089 let selections = self.selections.all::<Point>(cx);
6090
6091 let mut edits = Vec::new();
6092 let mut selections_iter = selections.iter().peekable();
6093 while let Some(selection) = selections_iter.next() {
6094 // Avoid duplicating the same lines twice.
6095 let mut rows = selection.spanned_rows(false, &display_map);
6096
6097 while let Some(next_selection) = selections_iter.peek() {
6098 let next_rows = next_selection.spanned_rows(false, &display_map);
6099 if next_rows.start < rows.end {
6100 rows.end = next_rows.end;
6101 selections_iter.next().unwrap();
6102 } else {
6103 break;
6104 }
6105 }
6106
6107 // Copy the text from the selected row region and splice it either at the start
6108 // or end of the region.
6109 let start = Point::new(rows.start.0, 0);
6110 let end = Point::new(
6111 rows.end.previous_row().0,
6112 buffer.line_len(rows.end.previous_row()),
6113 );
6114 let text = buffer
6115 .text_for_range(start..end)
6116 .chain(Some("\n"))
6117 .collect::<String>();
6118 let insert_location = if upwards {
6119 Point::new(rows.end.0, 0)
6120 } else {
6121 start
6122 };
6123 edits.push((insert_location..insert_location, text));
6124 }
6125
6126 self.transact(cx, |this, cx| {
6127 this.buffer.update(cx, |buffer, cx| {
6128 buffer.edit(edits, None, cx);
6129 });
6130
6131 this.request_autoscroll(Autoscroll::fit(), cx);
6132 });
6133 }
6134
6135 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6136 self.duplicate_line(true, cx);
6137 }
6138
6139 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6140 self.duplicate_line(false, cx);
6141 }
6142
6143 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6144 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6145 let buffer = self.buffer.read(cx).snapshot(cx);
6146
6147 let mut edits = Vec::new();
6148 let mut unfold_ranges = Vec::new();
6149 let mut refold_creases = Vec::new();
6150
6151 let selections = self.selections.all::<Point>(cx);
6152 let mut selections = selections.iter().peekable();
6153 let mut contiguous_row_selections = Vec::new();
6154 let mut new_selections = Vec::new();
6155
6156 while let Some(selection) = selections.next() {
6157 // Find all the selections that span a contiguous row range
6158 let (start_row, end_row) = consume_contiguous_rows(
6159 &mut contiguous_row_selections,
6160 selection,
6161 &display_map,
6162 &mut selections,
6163 );
6164
6165 // Move the text spanned by the row range to be before the line preceding the row range
6166 if start_row.0 > 0 {
6167 let range_to_move = Point::new(
6168 start_row.previous_row().0,
6169 buffer.line_len(start_row.previous_row()),
6170 )
6171 ..Point::new(
6172 end_row.previous_row().0,
6173 buffer.line_len(end_row.previous_row()),
6174 );
6175 let insertion_point = display_map
6176 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6177 .0;
6178
6179 // Don't move lines across excerpts
6180 if buffer
6181 .excerpt_boundaries_in_range((
6182 Bound::Excluded(insertion_point),
6183 Bound::Included(range_to_move.end),
6184 ))
6185 .next()
6186 .is_none()
6187 {
6188 let text = buffer
6189 .text_for_range(range_to_move.clone())
6190 .flat_map(|s| s.chars())
6191 .skip(1)
6192 .chain(['\n'])
6193 .collect::<String>();
6194
6195 edits.push((
6196 buffer.anchor_after(range_to_move.start)
6197 ..buffer.anchor_before(range_to_move.end),
6198 String::new(),
6199 ));
6200 let insertion_anchor = buffer.anchor_after(insertion_point);
6201 edits.push((insertion_anchor..insertion_anchor, text));
6202
6203 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6204
6205 // Move selections up
6206 new_selections.extend(contiguous_row_selections.drain(..).map(
6207 |mut selection| {
6208 selection.start.row -= row_delta;
6209 selection.end.row -= row_delta;
6210 selection
6211 },
6212 ));
6213
6214 // Move folds up
6215 unfold_ranges.push(range_to_move.clone());
6216 for fold in display_map.folds_in_range(
6217 buffer.anchor_before(range_to_move.start)
6218 ..buffer.anchor_after(range_to_move.end),
6219 ) {
6220 let mut start = fold.range.start.to_point(&buffer);
6221 let mut end = fold.range.end.to_point(&buffer);
6222 start.row -= row_delta;
6223 end.row -= row_delta;
6224 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6225 }
6226 }
6227 }
6228
6229 // If we didn't move line(s), preserve the existing selections
6230 new_selections.append(&mut contiguous_row_selections);
6231 }
6232
6233 self.transact(cx, |this, cx| {
6234 this.unfold_ranges(&unfold_ranges, true, true, cx);
6235 this.buffer.update(cx, |buffer, cx| {
6236 for (range, text) in edits {
6237 buffer.edit([(range, text)], None, cx);
6238 }
6239 });
6240 this.fold_creases(refold_creases, true, cx);
6241 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6242 s.select(new_selections);
6243 })
6244 });
6245 }
6246
6247 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6248 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6249 let buffer = self.buffer.read(cx).snapshot(cx);
6250
6251 let mut edits = Vec::new();
6252 let mut unfold_ranges = Vec::new();
6253 let mut refold_creases = Vec::new();
6254
6255 let selections = self.selections.all::<Point>(cx);
6256 let mut selections = selections.iter().peekable();
6257 let mut contiguous_row_selections = Vec::new();
6258 let mut new_selections = Vec::new();
6259
6260 while let Some(selection) = selections.next() {
6261 // Find all the selections that span a contiguous row range
6262 let (start_row, end_row) = consume_contiguous_rows(
6263 &mut contiguous_row_selections,
6264 selection,
6265 &display_map,
6266 &mut selections,
6267 );
6268
6269 // Move the text spanned by the row range to be after the last line of the row range
6270 if end_row.0 <= buffer.max_point().row {
6271 let range_to_move =
6272 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6273 let insertion_point = display_map
6274 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6275 .0;
6276
6277 // Don't move lines across excerpt boundaries
6278 if buffer
6279 .excerpt_boundaries_in_range((
6280 Bound::Excluded(range_to_move.start),
6281 Bound::Included(insertion_point),
6282 ))
6283 .next()
6284 .is_none()
6285 {
6286 let mut text = String::from("\n");
6287 text.extend(buffer.text_for_range(range_to_move.clone()));
6288 text.pop(); // Drop trailing newline
6289 edits.push((
6290 buffer.anchor_after(range_to_move.start)
6291 ..buffer.anchor_before(range_to_move.end),
6292 String::new(),
6293 ));
6294 let insertion_anchor = buffer.anchor_after(insertion_point);
6295 edits.push((insertion_anchor..insertion_anchor, text));
6296
6297 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6298
6299 // Move selections down
6300 new_selections.extend(contiguous_row_selections.drain(..).map(
6301 |mut selection| {
6302 selection.start.row += row_delta;
6303 selection.end.row += row_delta;
6304 selection
6305 },
6306 ));
6307
6308 // Move folds down
6309 unfold_ranges.push(range_to_move.clone());
6310 for fold in display_map.folds_in_range(
6311 buffer.anchor_before(range_to_move.start)
6312 ..buffer.anchor_after(range_to_move.end),
6313 ) {
6314 let mut start = fold.range.start.to_point(&buffer);
6315 let mut end = fold.range.end.to_point(&buffer);
6316 start.row += row_delta;
6317 end.row += row_delta;
6318 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6319 }
6320 }
6321 }
6322
6323 // If we didn't move line(s), preserve the existing selections
6324 new_selections.append(&mut contiguous_row_selections);
6325 }
6326
6327 self.transact(cx, |this, cx| {
6328 this.unfold_ranges(&unfold_ranges, true, true, cx);
6329 this.buffer.update(cx, |buffer, cx| {
6330 for (range, text) in edits {
6331 buffer.edit([(range, text)], None, cx);
6332 }
6333 });
6334 this.fold_creases(refold_creases, true, cx);
6335 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6336 });
6337 }
6338
6339 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6340 let text_layout_details = &self.text_layout_details(cx);
6341 self.transact(cx, |this, cx| {
6342 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6343 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6344 let line_mode = s.line_mode;
6345 s.move_with(|display_map, selection| {
6346 if !selection.is_empty() || line_mode {
6347 return;
6348 }
6349
6350 let mut head = selection.head();
6351 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6352 if head.column() == display_map.line_len(head.row()) {
6353 transpose_offset = display_map
6354 .buffer_snapshot
6355 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6356 }
6357
6358 if transpose_offset == 0 {
6359 return;
6360 }
6361
6362 *head.column_mut() += 1;
6363 head = display_map.clip_point(head, Bias::Right);
6364 let goal = SelectionGoal::HorizontalPosition(
6365 display_map
6366 .x_for_display_point(head, text_layout_details)
6367 .into(),
6368 );
6369 selection.collapse_to(head, goal);
6370
6371 let transpose_start = display_map
6372 .buffer_snapshot
6373 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6374 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6375 let transpose_end = display_map
6376 .buffer_snapshot
6377 .clip_offset(transpose_offset + 1, Bias::Right);
6378 if let Some(ch) =
6379 display_map.buffer_snapshot.chars_at(transpose_start).next()
6380 {
6381 edits.push((transpose_start..transpose_offset, String::new()));
6382 edits.push((transpose_end..transpose_end, ch.to_string()));
6383 }
6384 }
6385 });
6386 edits
6387 });
6388 this.buffer
6389 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6390 let selections = this.selections.all::<usize>(cx);
6391 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6392 s.select(selections);
6393 });
6394 });
6395 }
6396
6397 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6398 self.rewrap_impl(IsVimMode::No, cx)
6399 }
6400
6401 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
6402 let buffer = self.buffer.read(cx).snapshot(cx);
6403 let selections = self.selections.all::<Point>(cx);
6404 let mut selections = selections.iter().peekable();
6405
6406 let mut edits = Vec::new();
6407 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6408
6409 while let Some(selection) = selections.next() {
6410 let mut start_row = selection.start.row;
6411 let mut end_row = selection.end.row;
6412
6413 // Skip selections that overlap with a range that has already been rewrapped.
6414 let selection_range = start_row..end_row;
6415 if rewrapped_row_ranges
6416 .iter()
6417 .any(|range| range.overlaps(&selection_range))
6418 {
6419 continue;
6420 }
6421
6422 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
6423
6424 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6425 match language_scope.language_name().0.as_ref() {
6426 "Markdown" | "Plain Text" => {
6427 should_rewrap = true;
6428 }
6429 _ => {}
6430 }
6431 }
6432
6433 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
6434
6435 // Since not all lines in the selection may be at the same indent
6436 // level, choose the indent size that is the most common between all
6437 // of the lines.
6438 //
6439 // If there is a tie, we use the deepest indent.
6440 let (indent_size, indent_end) = {
6441 let mut indent_size_occurrences = HashMap::default();
6442 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6443
6444 for row in start_row..=end_row {
6445 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6446 rows_by_indent_size.entry(indent).or_default().push(row);
6447 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6448 }
6449
6450 let indent_size = indent_size_occurrences
6451 .into_iter()
6452 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
6453 .map(|(indent, _)| indent)
6454 .unwrap_or_default();
6455 let row = rows_by_indent_size[&indent_size][0];
6456 let indent_end = Point::new(row, indent_size.len);
6457
6458 (indent_size, indent_end)
6459 };
6460
6461 let mut line_prefix = indent_size.chars().collect::<String>();
6462
6463 if let Some(comment_prefix) =
6464 buffer
6465 .language_scope_at(selection.head())
6466 .and_then(|language| {
6467 language
6468 .line_comment_prefixes()
6469 .iter()
6470 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6471 .cloned()
6472 })
6473 {
6474 line_prefix.push_str(&comment_prefix);
6475 should_rewrap = true;
6476 }
6477
6478 if !should_rewrap {
6479 continue;
6480 }
6481
6482 if selection.is_empty() {
6483 'expand_upwards: while start_row > 0 {
6484 let prev_row = start_row - 1;
6485 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6486 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6487 {
6488 start_row = prev_row;
6489 } else {
6490 break 'expand_upwards;
6491 }
6492 }
6493
6494 'expand_downwards: while end_row < buffer.max_point().row {
6495 let next_row = end_row + 1;
6496 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6497 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6498 {
6499 end_row = next_row;
6500 } else {
6501 break 'expand_downwards;
6502 }
6503 }
6504 }
6505
6506 let start = Point::new(start_row, 0);
6507 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6508 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6509 let Some(lines_without_prefixes) = selection_text
6510 .lines()
6511 .map(|line| {
6512 line.strip_prefix(&line_prefix)
6513 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6514 .ok_or_else(|| {
6515 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6516 })
6517 })
6518 .collect::<Result<Vec<_>, _>>()
6519 .log_err()
6520 else {
6521 continue;
6522 };
6523
6524 let wrap_column = buffer
6525 .settings_at(Point::new(start_row, 0), cx)
6526 .preferred_line_length as usize;
6527 let wrapped_text = wrap_with_prefix(
6528 line_prefix,
6529 lines_without_prefixes.join(" "),
6530 wrap_column,
6531 tab_size,
6532 );
6533
6534 // TODO: should always use char-based diff while still supporting cursor behavior that
6535 // matches vim.
6536 let diff = match is_vim_mode {
6537 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
6538 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
6539 };
6540 let mut offset = start.to_offset(&buffer);
6541 let mut moved_since_edit = true;
6542
6543 for change in diff.iter_all_changes() {
6544 let value = change.value();
6545 match change.tag() {
6546 ChangeTag::Equal => {
6547 offset += value.len();
6548 moved_since_edit = true;
6549 }
6550 ChangeTag::Delete => {
6551 let start = buffer.anchor_after(offset);
6552 let end = buffer.anchor_before(offset + value.len());
6553
6554 if moved_since_edit {
6555 edits.push((start..end, String::new()));
6556 } else {
6557 edits.last_mut().unwrap().0.end = end;
6558 }
6559
6560 offset += value.len();
6561 moved_since_edit = false;
6562 }
6563 ChangeTag::Insert => {
6564 if moved_since_edit {
6565 let anchor = buffer.anchor_after(offset);
6566 edits.push((anchor..anchor, value.to_string()));
6567 } else {
6568 edits.last_mut().unwrap().1.push_str(value);
6569 }
6570
6571 moved_since_edit = false;
6572 }
6573 }
6574 }
6575
6576 rewrapped_row_ranges.push(start_row..=end_row);
6577 }
6578
6579 self.buffer
6580 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6581 }
6582
6583 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
6584 let mut text = String::new();
6585 let buffer = self.buffer.read(cx).snapshot(cx);
6586 let mut selections = self.selections.all::<Point>(cx);
6587 let mut clipboard_selections = Vec::with_capacity(selections.len());
6588 {
6589 let max_point = buffer.max_point();
6590 let mut is_first = true;
6591 for selection in &mut selections {
6592 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6593 if is_entire_line {
6594 selection.start = Point::new(selection.start.row, 0);
6595 if !selection.is_empty() && selection.end.column == 0 {
6596 selection.end = cmp::min(max_point, selection.end);
6597 } else {
6598 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6599 }
6600 selection.goal = SelectionGoal::None;
6601 }
6602 if is_first {
6603 is_first = false;
6604 } else {
6605 text += "\n";
6606 }
6607 let mut len = 0;
6608 for chunk in buffer.text_for_range(selection.start..selection.end) {
6609 text.push_str(chunk);
6610 len += chunk.len();
6611 }
6612 clipboard_selections.push(ClipboardSelection {
6613 len,
6614 is_entire_line,
6615 first_line_indent: buffer
6616 .indent_size_for_line(MultiBufferRow(selection.start.row))
6617 .len,
6618 });
6619 }
6620 }
6621
6622 self.transact(cx, |this, cx| {
6623 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6624 s.select(selections);
6625 });
6626 this.insert("", cx);
6627 });
6628 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
6629 }
6630
6631 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6632 let item = self.cut_common(cx);
6633 cx.write_to_clipboard(item);
6634 }
6635
6636 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
6637 self.change_selections(None, cx, |s| {
6638 s.move_with(|snapshot, sel| {
6639 if sel.is_empty() {
6640 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
6641 }
6642 });
6643 });
6644 let item = self.cut_common(cx);
6645 cx.set_global(KillRing(item))
6646 }
6647
6648 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
6649 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
6650 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
6651 (kill_ring.text().to_string(), kill_ring.metadata_json())
6652 } else {
6653 return;
6654 }
6655 } else {
6656 return;
6657 };
6658 self.do_paste(&text, metadata, false, cx);
6659 }
6660
6661 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6662 let selections = self.selections.all::<Point>(cx);
6663 let buffer = self.buffer.read(cx).read(cx);
6664 let mut text = String::new();
6665
6666 let mut clipboard_selections = Vec::with_capacity(selections.len());
6667 {
6668 let max_point = buffer.max_point();
6669 let mut is_first = true;
6670 for selection in selections.iter() {
6671 let mut start = selection.start;
6672 let mut end = selection.end;
6673 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6674 if is_entire_line {
6675 start = Point::new(start.row, 0);
6676 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6677 }
6678 if is_first {
6679 is_first = false;
6680 } else {
6681 text += "\n";
6682 }
6683 let mut len = 0;
6684 for chunk in buffer.text_for_range(start..end) {
6685 text.push_str(chunk);
6686 len += chunk.len();
6687 }
6688 clipboard_selections.push(ClipboardSelection {
6689 len,
6690 is_entire_line,
6691 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6692 });
6693 }
6694 }
6695
6696 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6697 text,
6698 clipboard_selections,
6699 ));
6700 }
6701
6702 pub fn do_paste(
6703 &mut self,
6704 text: &String,
6705 clipboard_selections: Option<Vec<ClipboardSelection>>,
6706 handle_entire_lines: bool,
6707 cx: &mut ViewContext<Self>,
6708 ) {
6709 if self.read_only(cx) {
6710 return;
6711 }
6712
6713 let clipboard_text = Cow::Borrowed(text);
6714
6715 self.transact(cx, |this, cx| {
6716 if let Some(mut clipboard_selections) = clipboard_selections {
6717 let old_selections = this.selections.all::<usize>(cx);
6718 let all_selections_were_entire_line =
6719 clipboard_selections.iter().all(|s| s.is_entire_line);
6720 let first_selection_indent_column =
6721 clipboard_selections.first().map(|s| s.first_line_indent);
6722 if clipboard_selections.len() != old_selections.len() {
6723 clipboard_selections.drain(..);
6724 }
6725 let cursor_offset = this.selections.last::<usize>(cx).head();
6726 let mut auto_indent_on_paste = true;
6727
6728 this.buffer.update(cx, |buffer, cx| {
6729 let snapshot = buffer.read(cx);
6730 auto_indent_on_paste =
6731 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
6732
6733 let mut start_offset = 0;
6734 let mut edits = Vec::new();
6735 let mut original_indent_columns = Vec::new();
6736 for (ix, selection) in old_selections.iter().enumerate() {
6737 let to_insert;
6738 let entire_line;
6739 let original_indent_column;
6740 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6741 let end_offset = start_offset + clipboard_selection.len;
6742 to_insert = &clipboard_text[start_offset..end_offset];
6743 entire_line = clipboard_selection.is_entire_line;
6744 start_offset = end_offset + 1;
6745 original_indent_column = Some(clipboard_selection.first_line_indent);
6746 } else {
6747 to_insert = clipboard_text.as_str();
6748 entire_line = all_selections_were_entire_line;
6749 original_indent_column = first_selection_indent_column
6750 }
6751
6752 // If the corresponding selection was empty when this slice of the
6753 // clipboard text was written, then the entire line containing the
6754 // selection was copied. If this selection is also currently empty,
6755 // then paste the line before the current line of the buffer.
6756 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6757 let column = selection.start.to_point(&snapshot).column as usize;
6758 let line_start = selection.start - column;
6759 line_start..line_start
6760 } else {
6761 selection.range()
6762 };
6763
6764 edits.push((range, to_insert));
6765 original_indent_columns.extend(original_indent_column);
6766 }
6767 drop(snapshot);
6768
6769 buffer.edit(
6770 edits,
6771 if auto_indent_on_paste {
6772 Some(AutoindentMode::Block {
6773 original_indent_columns,
6774 })
6775 } else {
6776 None
6777 },
6778 cx,
6779 );
6780 });
6781
6782 let selections = this.selections.all::<usize>(cx);
6783 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6784 } else {
6785 this.insert(&clipboard_text, cx);
6786 }
6787 });
6788 }
6789
6790 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6791 if let Some(item) = cx.read_from_clipboard() {
6792 let entries = item.entries();
6793
6794 match entries.first() {
6795 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
6796 // of all the pasted entries.
6797 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
6798 .do_paste(
6799 clipboard_string.text(),
6800 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
6801 true,
6802 cx,
6803 ),
6804 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
6805 }
6806 }
6807 }
6808
6809 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
6810 if self.read_only(cx) {
6811 return;
6812 }
6813
6814 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
6815 if let Some((selections, _)) =
6816 self.selection_history.transaction(transaction_id).cloned()
6817 {
6818 self.change_selections(None, cx, |s| {
6819 s.select_anchors(selections.to_vec());
6820 });
6821 }
6822 self.request_autoscroll(Autoscroll::fit(), cx);
6823 self.unmark_text(cx);
6824 self.refresh_inline_completion(true, false, cx);
6825 cx.emit(EditorEvent::Edited { transaction_id });
6826 cx.emit(EditorEvent::TransactionUndone { transaction_id });
6827 }
6828 }
6829
6830 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
6831 if self.read_only(cx) {
6832 return;
6833 }
6834
6835 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
6836 if let Some((_, Some(selections))) =
6837 self.selection_history.transaction(transaction_id).cloned()
6838 {
6839 self.change_selections(None, cx, |s| {
6840 s.select_anchors(selections.to_vec());
6841 });
6842 }
6843 self.request_autoscroll(Autoscroll::fit(), cx);
6844 self.unmark_text(cx);
6845 self.refresh_inline_completion(true, false, cx);
6846 cx.emit(EditorEvent::Edited { transaction_id });
6847 }
6848 }
6849
6850 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
6851 self.buffer
6852 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
6853 }
6854
6855 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
6856 self.buffer
6857 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
6858 }
6859
6860 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
6861 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6862 let line_mode = s.line_mode;
6863 s.move_with(|map, selection| {
6864 let cursor = if selection.is_empty() && !line_mode {
6865 movement::left(map, selection.start)
6866 } else {
6867 selection.start
6868 };
6869 selection.collapse_to(cursor, SelectionGoal::None);
6870 });
6871 })
6872 }
6873
6874 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
6875 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6876 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
6877 })
6878 }
6879
6880 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
6881 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6882 let line_mode = s.line_mode;
6883 s.move_with(|map, selection| {
6884 let cursor = if selection.is_empty() && !line_mode {
6885 movement::right(map, selection.end)
6886 } else {
6887 selection.end
6888 };
6889 selection.collapse_to(cursor, SelectionGoal::None)
6890 });
6891 })
6892 }
6893
6894 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
6895 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6896 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
6897 })
6898 }
6899
6900 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
6901 if self.take_rename(true, cx).is_some() {
6902 return;
6903 }
6904
6905 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6906 cx.propagate();
6907 return;
6908 }
6909
6910 let text_layout_details = &self.text_layout_details(cx);
6911 let selection_count = self.selections.count();
6912 let first_selection = self.selections.first_anchor();
6913
6914 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6915 let line_mode = s.line_mode;
6916 s.move_with(|map, selection| {
6917 if !selection.is_empty() && !line_mode {
6918 selection.goal = SelectionGoal::None;
6919 }
6920 let (cursor, goal) = movement::up(
6921 map,
6922 selection.start,
6923 selection.goal,
6924 false,
6925 text_layout_details,
6926 );
6927 selection.collapse_to(cursor, goal);
6928 });
6929 });
6930
6931 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
6932 {
6933 cx.propagate();
6934 }
6935 }
6936
6937 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
6938 if self.take_rename(true, cx).is_some() {
6939 return;
6940 }
6941
6942 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6943 cx.propagate();
6944 return;
6945 }
6946
6947 let text_layout_details = &self.text_layout_details(cx);
6948
6949 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6950 let line_mode = s.line_mode;
6951 s.move_with(|map, selection| {
6952 if !selection.is_empty() && !line_mode {
6953 selection.goal = SelectionGoal::None;
6954 }
6955 let (cursor, goal) = movement::up_by_rows(
6956 map,
6957 selection.start,
6958 action.lines,
6959 selection.goal,
6960 false,
6961 text_layout_details,
6962 );
6963 selection.collapse_to(cursor, goal);
6964 });
6965 })
6966 }
6967
6968 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
6969 if self.take_rename(true, cx).is_some() {
6970 return;
6971 }
6972
6973 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6974 cx.propagate();
6975 return;
6976 }
6977
6978 let text_layout_details = &self.text_layout_details(cx);
6979
6980 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6981 let line_mode = s.line_mode;
6982 s.move_with(|map, selection| {
6983 if !selection.is_empty() && !line_mode {
6984 selection.goal = SelectionGoal::None;
6985 }
6986 let (cursor, goal) = movement::down_by_rows(
6987 map,
6988 selection.start,
6989 action.lines,
6990 selection.goal,
6991 false,
6992 text_layout_details,
6993 );
6994 selection.collapse_to(cursor, goal);
6995 });
6996 })
6997 }
6998
6999 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7000 let text_layout_details = &self.text_layout_details(cx);
7001 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7002 s.move_heads_with(|map, head, goal| {
7003 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7004 })
7005 })
7006 }
7007
7008 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7009 let text_layout_details = &self.text_layout_details(cx);
7010 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7011 s.move_heads_with(|map, head, goal| {
7012 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7013 })
7014 })
7015 }
7016
7017 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7018 let Some(row_count) = self.visible_row_count() else {
7019 return;
7020 };
7021
7022 let text_layout_details = &self.text_layout_details(cx);
7023
7024 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7025 s.move_heads_with(|map, head, goal| {
7026 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7027 })
7028 })
7029 }
7030
7031 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7032 if self.take_rename(true, cx).is_some() {
7033 return;
7034 }
7035
7036 if self
7037 .context_menu
7038 .write()
7039 .as_mut()
7040 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7041 .unwrap_or(false)
7042 {
7043 return;
7044 }
7045
7046 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7047 cx.propagate();
7048 return;
7049 }
7050
7051 let Some(row_count) = self.visible_row_count() else {
7052 return;
7053 };
7054
7055 let autoscroll = if action.center_cursor {
7056 Autoscroll::center()
7057 } else {
7058 Autoscroll::fit()
7059 };
7060
7061 let text_layout_details = &self.text_layout_details(cx);
7062
7063 self.change_selections(Some(autoscroll), cx, |s| {
7064 let line_mode = s.line_mode;
7065 s.move_with(|map, selection| {
7066 if !selection.is_empty() && !line_mode {
7067 selection.goal = SelectionGoal::None;
7068 }
7069 let (cursor, goal) = movement::up_by_rows(
7070 map,
7071 selection.end,
7072 row_count,
7073 selection.goal,
7074 false,
7075 text_layout_details,
7076 );
7077 selection.collapse_to(cursor, goal);
7078 });
7079 });
7080 }
7081
7082 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7083 let text_layout_details = &self.text_layout_details(cx);
7084 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7085 s.move_heads_with(|map, head, goal| {
7086 movement::up(map, head, goal, false, text_layout_details)
7087 })
7088 })
7089 }
7090
7091 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7092 self.take_rename(true, cx);
7093
7094 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7095 cx.propagate();
7096 return;
7097 }
7098
7099 let text_layout_details = &self.text_layout_details(cx);
7100 let selection_count = self.selections.count();
7101 let first_selection = self.selections.first_anchor();
7102
7103 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7104 let line_mode = s.line_mode;
7105 s.move_with(|map, selection| {
7106 if !selection.is_empty() && !line_mode {
7107 selection.goal = SelectionGoal::None;
7108 }
7109 let (cursor, goal) = movement::down(
7110 map,
7111 selection.end,
7112 selection.goal,
7113 false,
7114 text_layout_details,
7115 );
7116 selection.collapse_to(cursor, goal);
7117 });
7118 });
7119
7120 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7121 {
7122 cx.propagate();
7123 }
7124 }
7125
7126 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7127 let Some(row_count) = self.visible_row_count() else {
7128 return;
7129 };
7130
7131 let text_layout_details = &self.text_layout_details(cx);
7132
7133 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7134 s.move_heads_with(|map, head, goal| {
7135 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7136 })
7137 })
7138 }
7139
7140 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7141 if self.take_rename(true, cx).is_some() {
7142 return;
7143 }
7144
7145 if self
7146 .context_menu
7147 .write()
7148 .as_mut()
7149 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7150 .unwrap_or(false)
7151 {
7152 return;
7153 }
7154
7155 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7156 cx.propagate();
7157 return;
7158 }
7159
7160 let Some(row_count) = self.visible_row_count() else {
7161 return;
7162 };
7163
7164 let autoscroll = if action.center_cursor {
7165 Autoscroll::center()
7166 } else {
7167 Autoscroll::fit()
7168 };
7169
7170 let text_layout_details = &self.text_layout_details(cx);
7171 self.change_selections(Some(autoscroll), cx, |s| {
7172 let line_mode = s.line_mode;
7173 s.move_with(|map, selection| {
7174 if !selection.is_empty() && !line_mode {
7175 selection.goal = SelectionGoal::None;
7176 }
7177 let (cursor, goal) = movement::down_by_rows(
7178 map,
7179 selection.end,
7180 row_count,
7181 selection.goal,
7182 false,
7183 text_layout_details,
7184 );
7185 selection.collapse_to(cursor, goal);
7186 });
7187 });
7188 }
7189
7190 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7191 let text_layout_details = &self.text_layout_details(cx);
7192 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7193 s.move_heads_with(|map, head, goal| {
7194 movement::down(map, head, goal, false, text_layout_details)
7195 })
7196 });
7197 }
7198
7199 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7200 if let Some(context_menu) = self.context_menu.write().as_mut() {
7201 context_menu.select_first(self.completion_provider.as_deref(), cx);
7202 }
7203 }
7204
7205 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7206 if let Some(context_menu) = self.context_menu.write().as_mut() {
7207 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7208 }
7209 }
7210
7211 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7212 if let Some(context_menu) = self.context_menu.write().as_mut() {
7213 context_menu.select_next(self.completion_provider.as_deref(), cx);
7214 }
7215 }
7216
7217 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7218 if let Some(context_menu) = self.context_menu.write().as_mut() {
7219 context_menu.select_last(self.completion_provider.as_deref(), cx);
7220 }
7221 }
7222
7223 pub fn move_to_previous_word_start(
7224 &mut self,
7225 _: &MoveToPreviousWordStart,
7226 cx: &mut ViewContext<Self>,
7227 ) {
7228 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7229 s.move_cursors_with(|map, head, _| {
7230 (
7231 movement::previous_word_start(map, head),
7232 SelectionGoal::None,
7233 )
7234 });
7235 })
7236 }
7237
7238 pub fn move_to_previous_subword_start(
7239 &mut self,
7240 _: &MoveToPreviousSubwordStart,
7241 cx: &mut ViewContext<Self>,
7242 ) {
7243 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7244 s.move_cursors_with(|map, head, _| {
7245 (
7246 movement::previous_subword_start(map, head),
7247 SelectionGoal::None,
7248 )
7249 });
7250 })
7251 }
7252
7253 pub fn select_to_previous_word_start(
7254 &mut self,
7255 _: &SelectToPreviousWordStart,
7256 cx: &mut ViewContext<Self>,
7257 ) {
7258 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7259 s.move_heads_with(|map, head, _| {
7260 (
7261 movement::previous_word_start(map, head),
7262 SelectionGoal::None,
7263 )
7264 });
7265 })
7266 }
7267
7268 pub fn select_to_previous_subword_start(
7269 &mut self,
7270 _: &SelectToPreviousSubwordStart,
7271 cx: &mut ViewContext<Self>,
7272 ) {
7273 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7274 s.move_heads_with(|map, head, _| {
7275 (
7276 movement::previous_subword_start(map, head),
7277 SelectionGoal::None,
7278 )
7279 });
7280 })
7281 }
7282
7283 pub fn delete_to_previous_word_start(
7284 &mut self,
7285 action: &DeleteToPreviousWordStart,
7286 cx: &mut ViewContext<Self>,
7287 ) {
7288 self.transact(cx, |this, cx| {
7289 this.select_autoclose_pair(cx);
7290 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7291 let line_mode = s.line_mode;
7292 s.move_with(|map, selection| {
7293 if selection.is_empty() && !line_mode {
7294 let cursor = if action.ignore_newlines {
7295 movement::previous_word_start(map, selection.head())
7296 } else {
7297 movement::previous_word_start_or_newline(map, selection.head())
7298 };
7299 selection.set_head(cursor, SelectionGoal::None);
7300 }
7301 });
7302 });
7303 this.insert("", cx);
7304 });
7305 }
7306
7307 pub fn delete_to_previous_subword_start(
7308 &mut self,
7309 _: &DeleteToPreviousSubwordStart,
7310 cx: &mut ViewContext<Self>,
7311 ) {
7312 self.transact(cx, |this, cx| {
7313 this.select_autoclose_pair(cx);
7314 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7315 let line_mode = s.line_mode;
7316 s.move_with(|map, selection| {
7317 if selection.is_empty() && !line_mode {
7318 let cursor = movement::previous_subword_start(map, selection.head());
7319 selection.set_head(cursor, SelectionGoal::None);
7320 }
7321 });
7322 });
7323 this.insert("", cx);
7324 });
7325 }
7326
7327 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7328 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7329 s.move_cursors_with(|map, head, _| {
7330 (movement::next_word_end(map, head), SelectionGoal::None)
7331 });
7332 })
7333 }
7334
7335 pub fn move_to_next_subword_end(
7336 &mut self,
7337 _: &MoveToNextSubwordEnd,
7338 cx: &mut ViewContext<Self>,
7339 ) {
7340 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7341 s.move_cursors_with(|map, head, _| {
7342 (movement::next_subword_end(map, head), SelectionGoal::None)
7343 });
7344 })
7345 }
7346
7347 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7348 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7349 s.move_heads_with(|map, head, _| {
7350 (movement::next_word_end(map, head), SelectionGoal::None)
7351 });
7352 })
7353 }
7354
7355 pub fn select_to_next_subword_end(
7356 &mut self,
7357 _: &SelectToNextSubwordEnd,
7358 cx: &mut ViewContext<Self>,
7359 ) {
7360 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7361 s.move_heads_with(|map, head, _| {
7362 (movement::next_subword_end(map, head), SelectionGoal::None)
7363 });
7364 })
7365 }
7366
7367 pub fn delete_to_next_word_end(
7368 &mut self,
7369 action: &DeleteToNextWordEnd,
7370 cx: &mut ViewContext<Self>,
7371 ) {
7372 self.transact(cx, |this, cx| {
7373 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7374 let line_mode = s.line_mode;
7375 s.move_with(|map, selection| {
7376 if selection.is_empty() && !line_mode {
7377 let cursor = if action.ignore_newlines {
7378 movement::next_word_end(map, selection.head())
7379 } else {
7380 movement::next_word_end_or_newline(map, selection.head())
7381 };
7382 selection.set_head(cursor, SelectionGoal::None);
7383 }
7384 });
7385 });
7386 this.insert("", cx);
7387 });
7388 }
7389
7390 pub fn delete_to_next_subword_end(
7391 &mut self,
7392 _: &DeleteToNextSubwordEnd,
7393 cx: &mut ViewContext<Self>,
7394 ) {
7395 self.transact(cx, |this, cx| {
7396 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7397 s.move_with(|map, selection| {
7398 if selection.is_empty() {
7399 let cursor = movement::next_subword_end(map, selection.head());
7400 selection.set_head(cursor, SelectionGoal::None);
7401 }
7402 });
7403 });
7404 this.insert("", cx);
7405 });
7406 }
7407
7408 pub fn move_to_beginning_of_line(
7409 &mut self,
7410 action: &MoveToBeginningOfLine,
7411 cx: &mut ViewContext<Self>,
7412 ) {
7413 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7414 s.move_cursors_with(|map, head, _| {
7415 (
7416 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7417 SelectionGoal::None,
7418 )
7419 });
7420 })
7421 }
7422
7423 pub fn select_to_beginning_of_line(
7424 &mut self,
7425 action: &SelectToBeginningOfLine,
7426 cx: &mut ViewContext<Self>,
7427 ) {
7428 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7429 s.move_heads_with(|map, head, _| {
7430 (
7431 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7432 SelectionGoal::None,
7433 )
7434 });
7435 });
7436 }
7437
7438 pub fn delete_to_beginning_of_line(
7439 &mut self,
7440 _: &DeleteToBeginningOfLine,
7441 cx: &mut ViewContext<Self>,
7442 ) {
7443 self.transact(cx, |this, cx| {
7444 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7445 s.move_with(|_, selection| {
7446 selection.reversed = true;
7447 });
7448 });
7449
7450 this.select_to_beginning_of_line(
7451 &SelectToBeginningOfLine {
7452 stop_at_soft_wraps: false,
7453 },
7454 cx,
7455 );
7456 this.backspace(&Backspace, cx);
7457 });
7458 }
7459
7460 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7461 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7462 s.move_cursors_with(|map, head, _| {
7463 (
7464 movement::line_end(map, head, action.stop_at_soft_wraps),
7465 SelectionGoal::None,
7466 )
7467 });
7468 })
7469 }
7470
7471 pub fn select_to_end_of_line(
7472 &mut self,
7473 action: &SelectToEndOfLine,
7474 cx: &mut ViewContext<Self>,
7475 ) {
7476 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7477 s.move_heads_with(|map, head, _| {
7478 (
7479 movement::line_end(map, head, action.stop_at_soft_wraps),
7480 SelectionGoal::None,
7481 )
7482 });
7483 })
7484 }
7485
7486 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7487 self.transact(cx, |this, cx| {
7488 this.select_to_end_of_line(
7489 &SelectToEndOfLine {
7490 stop_at_soft_wraps: false,
7491 },
7492 cx,
7493 );
7494 this.delete(&Delete, cx);
7495 });
7496 }
7497
7498 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7499 self.transact(cx, |this, cx| {
7500 this.select_to_end_of_line(
7501 &SelectToEndOfLine {
7502 stop_at_soft_wraps: false,
7503 },
7504 cx,
7505 );
7506 this.cut(&Cut, cx);
7507 });
7508 }
7509
7510 pub fn move_to_start_of_paragraph(
7511 &mut self,
7512 _: &MoveToStartOfParagraph,
7513 cx: &mut ViewContext<Self>,
7514 ) {
7515 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7516 cx.propagate();
7517 return;
7518 }
7519
7520 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7521 s.move_with(|map, selection| {
7522 selection.collapse_to(
7523 movement::start_of_paragraph(map, selection.head(), 1),
7524 SelectionGoal::None,
7525 )
7526 });
7527 })
7528 }
7529
7530 pub fn move_to_end_of_paragraph(
7531 &mut self,
7532 _: &MoveToEndOfParagraph,
7533 cx: &mut ViewContext<Self>,
7534 ) {
7535 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7536 cx.propagate();
7537 return;
7538 }
7539
7540 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7541 s.move_with(|map, selection| {
7542 selection.collapse_to(
7543 movement::end_of_paragraph(map, selection.head(), 1),
7544 SelectionGoal::None,
7545 )
7546 });
7547 })
7548 }
7549
7550 pub fn select_to_start_of_paragraph(
7551 &mut self,
7552 _: &SelectToStartOfParagraph,
7553 cx: &mut ViewContext<Self>,
7554 ) {
7555 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7556 cx.propagate();
7557 return;
7558 }
7559
7560 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7561 s.move_heads_with(|map, head, _| {
7562 (
7563 movement::start_of_paragraph(map, head, 1),
7564 SelectionGoal::None,
7565 )
7566 });
7567 })
7568 }
7569
7570 pub fn select_to_end_of_paragraph(
7571 &mut self,
7572 _: &SelectToEndOfParagraph,
7573 cx: &mut ViewContext<Self>,
7574 ) {
7575 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7576 cx.propagate();
7577 return;
7578 }
7579
7580 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7581 s.move_heads_with(|map, head, _| {
7582 (
7583 movement::end_of_paragraph(map, head, 1),
7584 SelectionGoal::None,
7585 )
7586 });
7587 })
7588 }
7589
7590 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7591 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7592 cx.propagate();
7593 return;
7594 }
7595
7596 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7597 s.select_ranges(vec![0..0]);
7598 });
7599 }
7600
7601 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7602 let mut selection = self.selections.last::<Point>(cx);
7603 selection.set_head(Point::zero(), SelectionGoal::None);
7604
7605 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7606 s.select(vec![selection]);
7607 });
7608 }
7609
7610 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7611 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7612 cx.propagate();
7613 return;
7614 }
7615
7616 let cursor = self.buffer.read(cx).read(cx).len();
7617 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7618 s.select_ranges(vec![cursor..cursor])
7619 });
7620 }
7621
7622 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7623 self.nav_history = nav_history;
7624 }
7625
7626 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7627 self.nav_history.as_ref()
7628 }
7629
7630 fn push_to_nav_history(
7631 &mut self,
7632 cursor_anchor: Anchor,
7633 new_position: Option<Point>,
7634 cx: &mut ViewContext<Self>,
7635 ) {
7636 if let Some(nav_history) = self.nav_history.as_mut() {
7637 let buffer = self.buffer.read(cx).read(cx);
7638 let cursor_position = cursor_anchor.to_point(&buffer);
7639 let scroll_state = self.scroll_manager.anchor();
7640 let scroll_top_row = scroll_state.top_row(&buffer);
7641 drop(buffer);
7642
7643 if let Some(new_position) = new_position {
7644 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7645 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7646 return;
7647 }
7648 }
7649
7650 nav_history.push(
7651 Some(NavigationData {
7652 cursor_anchor,
7653 cursor_position,
7654 scroll_anchor: scroll_state,
7655 scroll_top_row,
7656 }),
7657 cx,
7658 );
7659 }
7660 }
7661
7662 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7663 let buffer = self.buffer.read(cx).snapshot(cx);
7664 let mut selection = self.selections.first::<usize>(cx);
7665 selection.set_head(buffer.len(), SelectionGoal::None);
7666 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7667 s.select(vec![selection]);
7668 });
7669 }
7670
7671 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7672 let end = self.buffer.read(cx).read(cx).len();
7673 self.change_selections(None, cx, |s| {
7674 s.select_ranges(vec![0..end]);
7675 });
7676 }
7677
7678 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7679 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7680 let mut selections = self.selections.all::<Point>(cx);
7681 let max_point = display_map.buffer_snapshot.max_point();
7682 for selection in &mut selections {
7683 let rows = selection.spanned_rows(true, &display_map);
7684 selection.start = Point::new(rows.start.0, 0);
7685 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7686 selection.reversed = false;
7687 }
7688 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7689 s.select(selections);
7690 });
7691 }
7692
7693 pub fn split_selection_into_lines(
7694 &mut self,
7695 _: &SplitSelectionIntoLines,
7696 cx: &mut ViewContext<Self>,
7697 ) {
7698 let mut to_unfold = Vec::new();
7699 let mut new_selection_ranges = Vec::new();
7700 {
7701 let selections = self.selections.all::<Point>(cx);
7702 let buffer = self.buffer.read(cx).read(cx);
7703 for selection in selections {
7704 for row in selection.start.row..selection.end.row {
7705 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7706 new_selection_ranges.push(cursor..cursor);
7707 }
7708 new_selection_ranges.push(selection.end..selection.end);
7709 to_unfold.push(selection.start..selection.end);
7710 }
7711 }
7712 self.unfold_ranges(&to_unfold, true, true, cx);
7713 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7714 s.select_ranges(new_selection_ranges);
7715 });
7716 }
7717
7718 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7719 self.add_selection(true, cx);
7720 }
7721
7722 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7723 self.add_selection(false, cx);
7724 }
7725
7726 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7727 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7728 let mut selections = self.selections.all::<Point>(cx);
7729 let text_layout_details = self.text_layout_details(cx);
7730 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7731 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7732 let range = oldest_selection.display_range(&display_map).sorted();
7733
7734 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7735 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7736 let positions = start_x.min(end_x)..start_x.max(end_x);
7737
7738 selections.clear();
7739 let mut stack = Vec::new();
7740 for row in range.start.row().0..=range.end.row().0 {
7741 if let Some(selection) = self.selections.build_columnar_selection(
7742 &display_map,
7743 DisplayRow(row),
7744 &positions,
7745 oldest_selection.reversed,
7746 &text_layout_details,
7747 ) {
7748 stack.push(selection.id);
7749 selections.push(selection);
7750 }
7751 }
7752
7753 if above {
7754 stack.reverse();
7755 }
7756
7757 AddSelectionsState { above, stack }
7758 });
7759
7760 let last_added_selection = *state.stack.last().unwrap();
7761 let mut new_selections = Vec::new();
7762 if above == state.above {
7763 let end_row = if above {
7764 DisplayRow(0)
7765 } else {
7766 display_map.max_point().row()
7767 };
7768
7769 'outer: for selection in selections {
7770 if selection.id == last_added_selection {
7771 let range = selection.display_range(&display_map).sorted();
7772 debug_assert_eq!(range.start.row(), range.end.row());
7773 let mut row = range.start.row();
7774 let positions =
7775 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7776 px(start)..px(end)
7777 } else {
7778 let start_x =
7779 display_map.x_for_display_point(range.start, &text_layout_details);
7780 let end_x =
7781 display_map.x_for_display_point(range.end, &text_layout_details);
7782 start_x.min(end_x)..start_x.max(end_x)
7783 };
7784
7785 while row != end_row {
7786 if above {
7787 row.0 -= 1;
7788 } else {
7789 row.0 += 1;
7790 }
7791
7792 if let Some(new_selection) = self.selections.build_columnar_selection(
7793 &display_map,
7794 row,
7795 &positions,
7796 selection.reversed,
7797 &text_layout_details,
7798 ) {
7799 state.stack.push(new_selection.id);
7800 if above {
7801 new_selections.push(new_selection);
7802 new_selections.push(selection);
7803 } else {
7804 new_selections.push(selection);
7805 new_selections.push(new_selection);
7806 }
7807
7808 continue 'outer;
7809 }
7810 }
7811 }
7812
7813 new_selections.push(selection);
7814 }
7815 } else {
7816 new_selections = selections;
7817 new_selections.retain(|s| s.id != last_added_selection);
7818 state.stack.pop();
7819 }
7820
7821 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7822 s.select(new_selections);
7823 });
7824 if state.stack.len() > 1 {
7825 self.add_selections_state = Some(state);
7826 }
7827 }
7828
7829 pub fn select_next_match_internal(
7830 &mut self,
7831 display_map: &DisplaySnapshot,
7832 replace_newest: bool,
7833 autoscroll: Option<Autoscroll>,
7834 cx: &mut ViewContext<Self>,
7835 ) -> Result<()> {
7836 fn select_next_match_ranges(
7837 this: &mut Editor,
7838 range: Range<usize>,
7839 replace_newest: bool,
7840 auto_scroll: Option<Autoscroll>,
7841 cx: &mut ViewContext<Editor>,
7842 ) {
7843 this.unfold_ranges(&[range.clone()], false, true, cx);
7844 this.change_selections(auto_scroll, cx, |s| {
7845 if replace_newest {
7846 s.delete(s.newest_anchor().id);
7847 }
7848 s.insert_range(range.clone());
7849 });
7850 }
7851
7852 let buffer = &display_map.buffer_snapshot;
7853 let mut selections = self.selections.all::<usize>(cx);
7854 if let Some(mut select_next_state) = self.select_next_state.take() {
7855 let query = &select_next_state.query;
7856 if !select_next_state.done {
7857 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7858 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7859 let mut next_selected_range = None;
7860
7861 let bytes_after_last_selection =
7862 buffer.bytes_in_range(last_selection.end..buffer.len());
7863 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
7864 let query_matches = query
7865 .stream_find_iter(bytes_after_last_selection)
7866 .map(|result| (last_selection.end, result))
7867 .chain(
7868 query
7869 .stream_find_iter(bytes_before_first_selection)
7870 .map(|result| (0, result)),
7871 );
7872
7873 for (start_offset, query_match) in query_matches {
7874 let query_match = query_match.unwrap(); // can only fail due to I/O
7875 let offset_range =
7876 start_offset + query_match.start()..start_offset + query_match.end();
7877 let display_range = offset_range.start.to_display_point(display_map)
7878 ..offset_range.end.to_display_point(display_map);
7879
7880 if !select_next_state.wordwise
7881 || (!movement::is_inside_word(display_map, display_range.start)
7882 && !movement::is_inside_word(display_map, display_range.end))
7883 {
7884 // TODO: This is n^2, because we might check all the selections
7885 if !selections
7886 .iter()
7887 .any(|selection| selection.range().overlaps(&offset_range))
7888 {
7889 next_selected_range = Some(offset_range);
7890 break;
7891 }
7892 }
7893 }
7894
7895 if let Some(next_selected_range) = next_selected_range {
7896 select_next_match_ranges(
7897 self,
7898 next_selected_range,
7899 replace_newest,
7900 autoscroll,
7901 cx,
7902 );
7903 } else {
7904 select_next_state.done = true;
7905 }
7906 }
7907
7908 self.select_next_state = Some(select_next_state);
7909 } else {
7910 let mut only_carets = true;
7911 let mut same_text_selected = true;
7912 let mut selected_text = None;
7913
7914 let mut selections_iter = selections.iter().peekable();
7915 while let Some(selection) = selections_iter.next() {
7916 if selection.start != selection.end {
7917 only_carets = false;
7918 }
7919
7920 if same_text_selected {
7921 if selected_text.is_none() {
7922 selected_text =
7923 Some(buffer.text_for_range(selection.range()).collect::<String>());
7924 }
7925
7926 if let Some(next_selection) = selections_iter.peek() {
7927 if next_selection.range().len() == selection.range().len() {
7928 let next_selected_text = buffer
7929 .text_for_range(next_selection.range())
7930 .collect::<String>();
7931 if Some(next_selected_text) != selected_text {
7932 same_text_selected = false;
7933 selected_text = None;
7934 }
7935 } else {
7936 same_text_selected = false;
7937 selected_text = None;
7938 }
7939 }
7940 }
7941 }
7942
7943 if only_carets {
7944 for selection in &mut selections {
7945 let word_range = movement::surrounding_word(
7946 display_map,
7947 selection.start.to_display_point(display_map),
7948 );
7949 selection.start = word_range.start.to_offset(display_map, Bias::Left);
7950 selection.end = word_range.end.to_offset(display_map, Bias::Left);
7951 selection.goal = SelectionGoal::None;
7952 selection.reversed = false;
7953 select_next_match_ranges(
7954 self,
7955 selection.start..selection.end,
7956 replace_newest,
7957 autoscroll,
7958 cx,
7959 );
7960 }
7961
7962 if selections.len() == 1 {
7963 let selection = selections
7964 .last()
7965 .expect("ensured that there's only one selection");
7966 let query = buffer
7967 .text_for_range(selection.start..selection.end)
7968 .collect::<String>();
7969 let is_empty = query.is_empty();
7970 let select_state = SelectNextState {
7971 query: AhoCorasick::new(&[query])?,
7972 wordwise: true,
7973 done: is_empty,
7974 };
7975 self.select_next_state = Some(select_state);
7976 } else {
7977 self.select_next_state = None;
7978 }
7979 } else if let Some(selected_text) = selected_text {
7980 self.select_next_state = Some(SelectNextState {
7981 query: AhoCorasick::new(&[selected_text])?,
7982 wordwise: false,
7983 done: false,
7984 });
7985 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
7986 }
7987 }
7988 Ok(())
7989 }
7990
7991 pub fn select_all_matches(
7992 &mut self,
7993 _action: &SelectAllMatches,
7994 cx: &mut ViewContext<Self>,
7995 ) -> Result<()> {
7996 self.push_to_selection_history();
7997 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7998
7999 self.select_next_match_internal(&display_map, false, None, cx)?;
8000 let Some(select_next_state) = self.select_next_state.as_mut() else {
8001 return Ok(());
8002 };
8003 if select_next_state.done {
8004 return Ok(());
8005 }
8006
8007 let mut new_selections = self.selections.all::<usize>(cx);
8008
8009 let buffer = &display_map.buffer_snapshot;
8010 let query_matches = select_next_state
8011 .query
8012 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8013
8014 for query_match in query_matches {
8015 let query_match = query_match.unwrap(); // can only fail due to I/O
8016 let offset_range = query_match.start()..query_match.end();
8017 let display_range = offset_range.start.to_display_point(&display_map)
8018 ..offset_range.end.to_display_point(&display_map);
8019
8020 if !select_next_state.wordwise
8021 || (!movement::is_inside_word(&display_map, display_range.start)
8022 && !movement::is_inside_word(&display_map, display_range.end))
8023 {
8024 self.selections.change_with(cx, |selections| {
8025 new_selections.push(Selection {
8026 id: selections.new_selection_id(),
8027 start: offset_range.start,
8028 end: offset_range.end,
8029 reversed: false,
8030 goal: SelectionGoal::None,
8031 });
8032 });
8033 }
8034 }
8035
8036 new_selections.sort_by_key(|selection| selection.start);
8037 let mut ix = 0;
8038 while ix + 1 < new_selections.len() {
8039 let current_selection = &new_selections[ix];
8040 let next_selection = &new_selections[ix + 1];
8041 if current_selection.range().overlaps(&next_selection.range()) {
8042 if current_selection.id < next_selection.id {
8043 new_selections.remove(ix + 1);
8044 } else {
8045 new_selections.remove(ix);
8046 }
8047 } else {
8048 ix += 1;
8049 }
8050 }
8051
8052 select_next_state.done = true;
8053 self.unfold_ranges(
8054 &new_selections
8055 .iter()
8056 .map(|selection| selection.range())
8057 .collect::<Vec<_>>(),
8058 false,
8059 false,
8060 cx,
8061 );
8062 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8063 selections.select(new_selections)
8064 });
8065
8066 Ok(())
8067 }
8068
8069 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8070 self.push_to_selection_history();
8071 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8072 self.select_next_match_internal(
8073 &display_map,
8074 action.replace_newest,
8075 Some(Autoscroll::newest()),
8076 cx,
8077 )?;
8078 Ok(())
8079 }
8080
8081 pub fn select_previous(
8082 &mut self,
8083 action: &SelectPrevious,
8084 cx: &mut ViewContext<Self>,
8085 ) -> Result<()> {
8086 self.push_to_selection_history();
8087 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8088 let buffer = &display_map.buffer_snapshot;
8089 let mut selections = self.selections.all::<usize>(cx);
8090 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8091 let query = &select_prev_state.query;
8092 if !select_prev_state.done {
8093 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8094 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8095 let mut next_selected_range = None;
8096 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8097 let bytes_before_last_selection =
8098 buffer.reversed_bytes_in_range(0..last_selection.start);
8099 let bytes_after_first_selection =
8100 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8101 let query_matches = query
8102 .stream_find_iter(bytes_before_last_selection)
8103 .map(|result| (last_selection.start, result))
8104 .chain(
8105 query
8106 .stream_find_iter(bytes_after_first_selection)
8107 .map(|result| (buffer.len(), result)),
8108 );
8109 for (end_offset, query_match) in query_matches {
8110 let query_match = query_match.unwrap(); // can only fail due to I/O
8111 let offset_range =
8112 end_offset - query_match.end()..end_offset - query_match.start();
8113 let display_range = offset_range.start.to_display_point(&display_map)
8114 ..offset_range.end.to_display_point(&display_map);
8115
8116 if !select_prev_state.wordwise
8117 || (!movement::is_inside_word(&display_map, display_range.start)
8118 && !movement::is_inside_word(&display_map, display_range.end))
8119 {
8120 next_selected_range = Some(offset_range);
8121 break;
8122 }
8123 }
8124
8125 if let Some(next_selected_range) = next_selected_range {
8126 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8127 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8128 if action.replace_newest {
8129 s.delete(s.newest_anchor().id);
8130 }
8131 s.insert_range(next_selected_range);
8132 });
8133 } else {
8134 select_prev_state.done = true;
8135 }
8136 }
8137
8138 self.select_prev_state = Some(select_prev_state);
8139 } else {
8140 let mut only_carets = true;
8141 let mut same_text_selected = true;
8142 let mut selected_text = None;
8143
8144 let mut selections_iter = selections.iter().peekable();
8145 while let Some(selection) = selections_iter.next() {
8146 if selection.start != selection.end {
8147 only_carets = false;
8148 }
8149
8150 if same_text_selected {
8151 if selected_text.is_none() {
8152 selected_text =
8153 Some(buffer.text_for_range(selection.range()).collect::<String>());
8154 }
8155
8156 if let Some(next_selection) = selections_iter.peek() {
8157 if next_selection.range().len() == selection.range().len() {
8158 let next_selected_text = buffer
8159 .text_for_range(next_selection.range())
8160 .collect::<String>();
8161 if Some(next_selected_text) != selected_text {
8162 same_text_selected = false;
8163 selected_text = None;
8164 }
8165 } else {
8166 same_text_selected = false;
8167 selected_text = None;
8168 }
8169 }
8170 }
8171 }
8172
8173 if only_carets {
8174 for selection in &mut selections {
8175 let word_range = movement::surrounding_word(
8176 &display_map,
8177 selection.start.to_display_point(&display_map),
8178 );
8179 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8180 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8181 selection.goal = SelectionGoal::None;
8182 selection.reversed = false;
8183 }
8184 if selections.len() == 1 {
8185 let selection = selections
8186 .last()
8187 .expect("ensured that there's only one selection");
8188 let query = buffer
8189 .text_for_range(selection.start..selection.end)
8190 .collect::<String>();
8191 let is_empty = query.is_empty();
8192 let select_state = SelectNextState {
8193 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8194 wordwise: true,
8195 done: is_empty,
8196 };
8197 self.select_prev_state = Some(select_state);
8198 } else {
8199 self.select_prev_state = None;
8200 }
8201
8202 self.unfold_ranges(
8203 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8204 false,
8205 true,
8206 cx,
8207 );
8208 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8209 s.select(selections);
8210 });
8211 } else if let Some(selected_text) = selected_text {
8212 self.select_prev_state = Some(SelectNextState {
8213 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8214 wordwise: false,
8215 done: false,
8216 });
8217 self.select_previous(action, cx)?;
8218 }
8219 }
8220 Ok(())
8221 }
8222
8223 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8224 if self.read_only(cx) {
8225 return;
8226 }
8227 let text_layout_details = &self.text_layout_details(cx);
8228 self.transact(cx, |this, cx| {
8229 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8230 let mut edits = Vec::new();
8231 let mut selection_edit_ranges = Vec::new();
8232 let mut last_toggled_row = None;
8233 let snapshot = this.buffer.read(cx).read(cx);
8234 let empty_str: Arc<str> = Arc::default();
8235 let mut suffixes_inserted = Vec::new();
8236 let ignore_indent = action.ignore_indent;
8237
8238 fn comment_prefix_range(
8239 snapshot: &MultiBufferSnapshot,
8240 row: MultiBufferRow,
8241 comment_prefix: &str,
8242 comment_prefix_whitespace: &str,
8243 ignore_indent: bool,
8244 ) -> Range<Point> {
8245 let indent_size = if ignore_indent {
8246 0
8247 } else {
8248 snapshot.indent_size_for_line(row).len
8249 };
8250
8251 let start = Point::new(row.0, indent_size);
8252
8253 let mut line_bytes = snapshot
8254 .bytes_in_range(start..snapshot.max_point())
8255 .flatten()
8256 .copied();
8257
8258 // If this line currently begins with the line comment prefix, then record
8259 // the range containing the prefix.
8260 if line_bytes
8261 .by_ref()
8262 .take(comment_prefix.len())
8263 .eq(comment_prefix.bytes())
8264 {
8265 // Include any whitespace that matches the comment prefix.
8266 let matching_whitespace_len = line_bytes
8267 .zip(comment_prefix_whitespace.bytes())
8268 .take_while(|(a, b)| a == b)
8269 .count() as u32;
8270 let end = Point::new(
8271 start.row,
8272 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8273 );
8274 start..end
8275 } else {
8276 start..start
8277 }
8278 }
8279
8280 fn comment_suffix_range(
8281 snapshot: &MultiBufferSnapshot,
8282 row: MultiBufferRow,
8283 comment_suffix: &str,
8284 comment_suffix_has_leading_space: bool,
8285 ) -> Range<Point> {
8286 let end = Point::new(row.0, snapshot.line_len(row));
8287 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8288
8289 let mut line_end_bytes = snapshot
8290 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8291 .flatten()
8292 .copied();
8293
8294 let leading_space_len = if suffix_start_column > 0
8295 && line_end_bytes.next() == Some(b' ')
8296 && comment_suffix_has_leading_space
8297 {
8298 1
8299 } else {
8300 0
8301 };
8302
8303 // If this line currently begins with the line comment prefix, then record
8304 // the range containing the prefix.
8305 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8306 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8307 start..end
8308 } else {
8309 end..end
8310 }
8311 }
8312
8313 // TODO: Handle selections that cross excerpts
8314 for selection in &mut selections {
8315 let start_column = snapshot
8316 .indent_size_for_line(MultiBufferRow(selection.start.row))
8317 .len;
8318 let language = if let Some(language) =
8319 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8320 {
8321 language
8322 } else {
8323 continue;
8324 };
8325
8326 selection_edit_ranges.clear();
8327
8328 // If multiple selections contain a given row, avoid processing that
8329 // row more than once.
8330 let mut start_row = MultiBufferRow(selection.start.row);
8331 if last_toggled_row == Some(start_row) {
8332 start_row = start_row.next_row();
8333 }
8334 let end_row =
8335 if selection.end.row > selection.start.row && selection.end.column == 0 {
8336 MultiBufferRow(selection.end.row - 1)
8337 } else {
8338 MultiBufferRow(selection.end.row)
8339 };
8340 last_toggled_row = Some(end_row);
8341
8342 if start_row > end_row {
8343 continue;
8344 }
8345
8346 // If the language has line comments, toggle those.
8347 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8348
8349 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8350 if ignore_indent {
8351 full_comment_prefixes = full_comment_prefixes
8352 .into_iter()
8353 .map(|s| Arc::from(s.trim_end()))
8354 .collect();
8355 }
8356
8357 if !full_comment_prefixes.is_empty() {
8358 let first_prefix = full_comment_prefixes
8359 .first()
8360 .expect("prefixes is non-empty");
8361 let prefix_trimmed_lengths = full_comment_prefixes
8362 .iter()
8363 .map(|p| p.trim_end_matches(' ').len())
8364 .collect::<SmallVec<[usize; 4]>>();
8365
8366 let mut all_selection_lines_are_comments = true;
8367
8368 for row in start_row.0..=end_row.0 {
8369 let row = MultiBufferRow(row);
8370 if start_row < end_row && snapshot.is_line_blank(row) {
8371 continue;
8372 }
8373
8374 let prefix_range = full_comment_prefixes
8375 .iter()
8376 .zip(prefix_trimmed_lengths.iter().copied())
8377 .map(|(prefix, trimmed_prefix_len)| {
8378 comment_prefix_range(
8379 snapshot.deref(),
8380 row,
8381 &prefix[..trimmed_prefix_len],
8382 &prefix[trimmed_prefix_len..],
8383 ignore_indent,
8384 )
8385 })
8386 .max_by_key(|range| range.end.column - range.start.column)
8387 .expect("prefixes is non-empty");
8388
8389 if prefix_range.is_empty() {
8390 all_selection_lines_are_comments = false;
8391 }
8392
8393 selection_edit_ranges.push(prefix_range);
8394 }
8395
8396 if all_selection_lines_are_comments {
8397 edits.extend(
8398 selection_edit_ranges
8399 .iter()
8400 .cloned()
8401 .map(|range| (range, empty_str.clone())),
8402 );
8403 } else {
8404 let min_column = selection_edit_ranges
8405 .iter()
8406 .map(|range| range.start.column)
8407 .min()
8408 .unwrap_or(0);
8409 edits.extend(selection_edit_ranges.iter().map(|range| {
8410 let position = Point::new(range.start.row, min_column);
8411 (position..position, first_prefix.clone())
8412 }));
8413 }
8414 } else if let Some((full_comment_prefix, comment_suffix)) =
8415 language.block_comment_delimiters()
8416 {
8417 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8418 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8419 let prefix_range = comment_prefix_range(
8420 snapshot.deref(),
8421 start_row,
8422 comment_prefix,
8423 comment_prefix_whitespace,
8424 ignore_indent,
8425 );
8426 let suffix_range = comment_suffix_range(
8427 snapshot.deref(),
8428 end_row,
8429 comment_suffix.trim_start_matches(' '),
8430 comment_suffix.starts_with(' '),
8431 );
8432
8433 if prefix_range.is_empty() || suffix_range.is_empty() {
8434 edits.push((
8435 prefix_range.start..prefix_range.start,
8436 full_comment_prefix.clone(),
8437 ));
8438 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8439 suffixes_inserted.push((end_row, comment_suffix.len()));
8440 } else {
8441 edits.push((prefix_range, empty_str.clone()));
8442 edits.push((suffix_range, empty_str.clone()));
8443 }
8444 } else {
8445 continue;
8446 }
8447 }
8448
8449 drop(snapshot);
8450 this.buffer.update(cx, |buffer, cx| {
8451 buffer.edit(edits, None, cx);
8452 });
8453
8454 // Adjust selections so that they end before any comment suffixes that
8455 // were inserted.
8456 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8457 let mut selections = this.selections.all::<Point>(cx);
8458 let snapshot = this.buffer.read(cx).read(cx);
8459 for selection in &mut selections {
8460 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8461 match row.cmp(&MultiBufferRow(selection.end.row)) {
8462 Ordering::Less => {
8463 suffixes_inserted.next();
8464 continue;
8465 }
8466 Ordering::Greater => break,
8467 Ordering::Equal => {
8468 if selection.end.column == snapshot.line_len(row) {
8469 if selection.is_empty() {
8470 selection.start.column -= suffix_len as u32;
8471 }
8472 selection.end.column -= suffix_len as u32;
8473 }
8474 break;
8475 }
8476 }
8477 }
8478 }
8479
8480 drop(snapshot);
8481 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8482
8483 let selections = this.selections.all::<Point>(cx);
8484 let selections_on_single_row = selections.windows(2).all(|selections| {
8485 selections[0].start.row == selections[1].start.row
8486 && selections[0].end.row == selections[1].end.row
8487 && selections[0].start.row == selections[0].end.row
8488 });
8489 let selections_selecting = selections
8490 .iter()
8491 .any(|selection| selection.start != selection.end);
8492 let advance_downwards = action.advance_downwards
8493 && selections_on_single_row
8494 && !selections_selecting
8495 && !matches!(this.mode, EditorMode::SingleLine { .. });
8496
8497 if advance_downwards {
8498 let snapshot = this.buffer.read(cx).snapshot(cx);
8499
8500 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8501 s.move_cursors_with(|display_snapshot, display_point, _| {
8502 let mut point = display_point.to_point(display_snapshot);
8503 point.row += 1;
8504 point = snapshot.clip_point(point, Bias::Left);
8505 let display_point = point.to_display_point(display_snapshot);
8506 let goal = SelectionGoal::HorizontalPosition(
8507 display_snapshot
8508 .x_for_display_point(display_point, text_layout_details)
8509 .into(),
8510 );
8511 (display_point, goal)
8512 })
8513 });
8514 }
8515 });
8516 }
8517
8518 pub fn select_enclosing_symbol(
8519 &mut self,
8520 _: &SelectEnclosingSymbol,
8521 cx: &mut ViewContext<Self>,
8522 ) {
8523 let buffer = self.buffer.read(cx).snapshot(cx);
8524 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8525
8526 fn update_selection(
8527 selection: &Selection<usize>,
8528 buffer_snap: &MultiBufferSnapshot,
8529 ) -> Option<Selection<usize>> {
8530 let cursor = selection.head();
8531 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8532 for symbol in symbols.iter().rev() {
8533 let start = symbol.range.start.to_offset(buffer_snap);
8534 let end = symbol.range.end.to_offset(buffer_snap);
8535 let new_range = start..end;
8536 if start < selection.start || end > selection.end {
8537 return Some(Selection {
8538 id: selection.id,
8539 start: new_range.start,
8540 end: new_range.end,
8541 goal: SelectionGoal::None,
8542 reversed: selection.reversed,
8543 });
8544 }
8545 }
8546 None
8547 }
8548
8549 let mut selected_larger_symbol = false;
8550 let new_selections = old_selections
8551 .iter()
8552 .map(|selection| match update_selection(selection, &buffer) {
8553 Some(new_selection) => {
8554 if new_selection.range() != selection.range() {
8555 selected_larger_symbol = true;
8556 }
8557 new_selection
8558 }
8559 None => selection.clone(),
8560 })
8561 .collect::<Vec<_>>();
8562
8563 if selected_larger_symbol {
8564 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8565 s.select(new_selections);
8566 });
8567 }
8568 }
8569
8570 pub fn select_larger_syntax_node(
8571 &mut self,
8572 _: &SelectLargerSyntaxNode,
8573 cx: &mut ViewContext<Self>,
8574 ) {
8575 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8576 let buffer = self.buffer.read(cx).snapshot(cx);
8577 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8578
8579 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8580 let mut selected_larger_node = false;
8581 let new_selections = old_selections
8582 .iter()
8583 .map(|selection| {
8584 let old_range = selection.start..selection.end;
8585 let mut new_range = old_range.clone();
8586 while let Some(containing_range) =
8587 buffer.range_for_syntax_ancestor(new_range.clone())
8588 {
8589 new_range = containing_range;
8590 if !display_map.intersects_fold(new_range.start)
8591 && !display_map.intersects_fold(new_range.end)
8592 {
8593 break;
8594 }
8595 }
8596
8597 selected_larger_node |= new_range != old_range;
8598 Selection {
8599 id: selection.id,
8600 start: new_range.start,
8601 end: new_range.end,
8602 goal: SelectionGoal::None,
8603 reversed: selection.reversed,
8604 }
8605 })
8606 .collect::<Vec<_>>();
8607
8608 if selected_larger_node {
8609 stack.push(old_selections);
8610 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8611 s.select(new_selections);
8612 });
8613 }
8614 self.select_larger_syntax_node_stack = stack;
8615 }
8616
8617 pub fn select_smaller_syntax_node(
8618 &mut self,
8619 _: &SelectSmallerSyntaxNode,
8620 cx: &mut ViewContext<Self>,
8621 ) {
8622 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8623 if let Some(selections) = stack.pop() {
8624 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8625 s.select(selections.to_vec());
8626 });
8627 }
8628 self.select_larger_syntax_node_stack = stack;
8629 }
8630
8631 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8632 if !EditorSettings::get_global(cx).gutter.runnables {
8633 self.clear_tasks();
8634 return Task::ready(());
8635 }
8636 let project = self.project.as_ref().map(Model::downgrade);
8637 cx.spawn(|this, mut cx| async move {
8638 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
8639 let Some(project) = project.and_then(|p| p.upgrade()) else {
8640 return;
8641 };
8642 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8643 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8644 }) else {
8645 return;
8646 };
8647
8648 let hide_runnables = project
8649 .update(&mut cx, |project, cx| {
8650 // Do not display any test indicators in non-dev server remote projects.
8651 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8652 })
8653 .unwrap_or(true);
8654 if hide_runnables {
8655 return;
8656 }
8657 let new_rows =
8658 cx.background_executor()
8659 .spawn({
8660 let snapshot = display_snapshot.clone();
8661 async move {
8662 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8663 }
8664 })
8665 .await;
8666 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8667
8668 this.update(&mut cx, |this, _| {
8669 this.clear_tasks();
8670 for (key, value) in rows {
8671 this.insert_tasks(key, value);
8672 }
8673 })
8674 .ok();
8675 })
8676 }
8677 fn fetch_runnable_ranges(
8678 snapshot: &DisplaySnapshot,
8679 range: Range<Anchor>,
8680 ) -> Vec<language::RunnableRange> {
8681 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8682 }
8683
8684 fn runnable_rows(
8685 project: Model<Project>,
8686 snapshot: DisplaySnapshot,
8687 runnable_ranges: Vec<RunnableRange>,
8688 mut cx: AsyncWindowContext,
8689 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8690 runnable_ranges
8691 .into_iter()
8692 .filter_map(|mut runnable| {
8693 let tasks = cx
8694 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8695 .ok()?;
8696 if tasks.is_empty() {
8697 return None;
8698 }
8699
8700 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8701
8702 let row = snapshot
8703 .buffer_snapshot
8704 .buffer_line_for_row(MultiBufferRow(point.row))?
8705 .1
8706 .start
8707 .row;
8708
8709 let context_range =
8710 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8711 Some((
8712 (runnable.buffer_id, row),
8713 RunnableTasks {
8714 templates: tasks,
8715 offset: MultiBufferOffset(runnable.run_range.start),
8716 context_range,
8717 column: point.column,
8718 extra_variables: runnable.extra_captures,
8719 },
8720 ))
8721 })
8722 .collect()
8723 }
8724
8725 fn templates_with_tags(
8726 project: &Model<Project>,
8727 runnable: &mut Runnable,
8728 cx: &WindowContext<'_>,
8729 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8730 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8731 let (worktree_id, file) = project
8732 .buffer_for_id(runnable.buffer, cx)
8733 .and_then(|buffer| buffer.read(cx).file())
8734 .map(|file| (file.worktree_id(cx), file.clone()))
8735 .unzip();
8736
8737 (
8738 project.task_store().read(cx).task_inventory().cloned(),
8739 worktree_id,
8740 file,
8741 )
8742 });
8743
8744 let tags = mem::take(&mut runnable.tags);
8745 let mut tags: Vec<_> = tags
8746 .into_iter()
8747 .flat_map(|tag| {
8748 let tag = tag.0.clone();
8749 inventory
8750 .as_ref()
8751 .into_iter()
8752 .flat_map(|inventory| {
8753 inventory.read(cx).list_tasks(
8754 file.clone(),
8755 Some(runnable.language.clone()),
8756 worktree_id,
8757 cx,
8758 )
8759 })
8760 .filter(move |(_, template)| {
8761 template.tags.iter().any(|source_tag| source_tag == &tag)
8762 })
8763 })
8764 .sorted_by_key(|(kind, _)| kind.to_owned())
8765 .collect();
8766 if let Some((leading_tag_source, _)) = tags.first() {
8767 // Strongest source wins; if we have worktree tag binding, prefer that to
8768 // global and language bindings;
8769 // if we have a global binding, prefer that to language binding.
8770 let first_mismatch = tags
8771 .iter()
8772 .position(|(tag_source, _)| tag_source != leading_tag_source);
8773 if let Some(index) = first_mismatch {
8774 tags.truncate(index);
8775 }
8776 }
8777
8778 tags
8779 }
8780
8781 pub fn move_to_enclosing_bracket(
8782 &mut self,
8783 _: &MoveToEnclosingBracket,
8784 cx: &mut ViewContext<Self>,
8785 ) {
8786 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8787 s.move_offsets_with(|snapshot, selection| {
8788 let Some(enclosing_bracket_ranges) =
8789 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8790 else {
8791 return;
8792 };
8793
8794 let mut best_length = usize::MAX;
8795 let mut best_inside = false;
8796 let mut best_in_bracket_range = false;
8797 let mut best_destination = None;
8798 for (open, close) in enclosing_bracket_ranges {
8799 let close = close.to_inclusive();
8800 let length = close.end() - open.start;
8801 let inside = selection.start >= open.end && selection.end <= *close.start();
8802 let in_bracket_range = open.to_inclusive().contains(&selection.head())
8803 || close.contains(&selection.head());
8804
8805 // If best is next to a bracket and current isn't, skip
8806 if !in_bracket_range && best_in_bracket_range {
8807 continue;
8808 }
8809
8810 // Prefer smaller lengths unless best is inside and current isn't
8811 if length > best_length && (best_inside || !inside) {
8812 continue;
8813 }
8814
8815 best_length = length;
8816 best_inside = inside;
8817 best_in_bracket_range = in_bracket_range;
8818 best_destination = Some(
8819 if close.contains(&selection.start) && close.contains(&selection.end) {
8820 if inside {
8821 open.end
8822 } else {
8823 open.start
8824 }
8825 } else if inside {
8826 *close.start()
8827 } else {
8828 *close.end()
8829 },
8830 );
8831 }
8832
8833 if let Some(destination) = best_destination {
8834 selection.collapse_to(destination, SelectionGoal::None);
8835 }
8836 })
8837 });
8838 }
8839
8840 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
8841 self.end_selection(cx);
8842 self.selection_history.mode = SelectionHistoryMode::Undoing;
8843 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
8844 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8845 self.select_next_state = entry.select_next_state;
8846 self.select_prev_state = entry.select_prev_state;
8847 self.add_selections_state = entry.add_selections_state;
8848 self.request_autoscroll(Autoscroll::newest(), cx);
8849 }
8850 self.selection_history.mode = SelectionHistoryMode::Normal;
8851 }
8852
8853 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
8854 self.end_selection(cx);
8855 self.selection_history.mode = SelectionHistoryMode::Redoing;
8856 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
8857 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8858 self.select_next_state = entry.select_next_state;
8859 self.select_prev_state = entry.select_prev_state;
8860 self.add_selections_state = entry.add_selections_state;
8861 self.request_autoscroll(Autoscroll::newest(), cx);
8862 }
8863 self.selection_history.mode = SelectionHistoryMode::Normal;
8864 }
8865
8866 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
8867 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
8868 }
8869
8870 pub fn expand_excerpts_down(
8871 &mut self,
8872 action: &ExpandExcerptsDown,
8873 cx: &mut ViewContext<Self>,
8874 ) {
8875 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
8876 }
8877
8878 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
8879 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
8880 }
8881
8882 pub fn expand_excerpts_for_direction(
8883 &mut self,
8884 lines: u32,
8885 direction: ExpandExcerptDirection,
8886 cx: &mut ViewContext<Self>,
8887 ) {
8888 let selections = self.selections.disjoint_anchors();
8889
8890 let lines = if lines == 0 {
8891 EditorSettings::get_global(cx).expand_excerpt_lines
8892 } else {
8893 lines
8894 };
8895
8896 self.buffer.update(cx, |buffer, cx| {
8897 buffer.expand_excerpts(
8898 selections
8899 .iter()
8900 .map(|selection| selection.head().excerpt_id)
8901 .dedup(),
8902 lines,
8903 direction,
8904 cx,
8905 )
8906 })
8907 }
8908
8909 pub fn expand_excerpt(
8910 &mut self,
8911 excerpt: ExcerptId,
8912 direction: ExpandExcerptDirection,
8913 cx: &mut ViewContext<Self>,
8914 ) {
8915 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
8916 self.buffer.update(cx, |buffer, cx| {
8917 buffer.expand_excerpts([excerpt], lines, direction, cx)
8918 })
8919 }
8920
8921 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
8922 self.go_to_diagnostic_impl(Direction::Next, cx)
8923 }
8924
8925 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
8926 self.go_to_diagnostic_impl(Direction::Prev, cx)
8927 }
8928
8929 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
8930 let buffer = self.buffer.read(cx).snapshot(cx);
8931 let selection = self.selections.newest::<usize>(cx);
8932
8933 // If there is an active Diagnostic Popover jump to its diagnostic instead.
8934 if direction == Direction::Next {
8935 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
8936 let (group_id, jump_to) = popover.activation_info();
8937 if self.activate_diagnostics(group_id, cx) {
8938 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8939 let mut new_selection = s.newest_anchor().clone();
8940 new_selection.collapse_to(jump_to, SelectionGoal::None);
8941 s.select_anchors(vec![new_selection.clone()]);
8942 });
8943 }
8944 return;
8945 }
8946 }
8947
8948 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
8949 active_diagnostics
8950 .primary_range
8951 .to_offset(&buffer)
8952 .to_inclusive()
8953 });
8954 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
8955 if active_primary_range.contains(&selection.head()) {
8956 *active_primary_range.start()
8957 } else {
8958 selection.head()
8959 }
8960 } else {
8961 selection.head()
8962 };
8963 let snapshot = self.snapshot(cx);
8964 loop {
8965 let diagnostics = if direction == Direction::Prev {
8966 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
8967 } else {
8968 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
8969 }
8970 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
8971 let group = diagnostics
8972 // relies on diagnostics_in_range to return diagnostics with the same starting range to
8973 // be sorted in a stable way
8974 // skip until we are at current active diagnostic, if it exists
8975 .skip_while(|entry| {
8976 (match direction {
8977 Direction::Prev => entry.range.start >= search_start,
8978 Direction::Next => entry.range.start <= search_start,
8979 }) && self
8980 .active_diagnostics
8981 .as_ref()
8982 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
8983 })
8984 .find_map(|entry| {
8985 if entry.diagnostic.is_primary
8986 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
8987 && !entry.range.is_empty()
8988 // if we match with the active diagnostic, skip it
8989 && Some(entry.diagnostic.group_id)
8990 != self.active_diagnostics.as_ref().map(|d| d.group_id)
8991 {
8992 Some((entry.range, entry.diagnostic.group_id))
8993 } else {
8994 None
8995 }
8996 });
8997
8998 if let Some((primary_range, group_id)) = group {
8999 if self.activate_diagnostics(group_id, cx) {
9000 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9001 s.select(vec![Selection {
9002 id: selection.id,
9003 start: primary_range.start,
9004 end: primary_range.start,
9005 reversed: false,
9006 goal: SelectionGoal::None,
9007 }]);
9008 });
9009 }
9010 break;
9011 } else {
9012 // Cycle around to the start of the buffer, potentially moving back to the start of
9013 // the currently active diagnostic.
9014 active_primary_range.take();
9015 if direction == Direction::Prev {
9016 if search_start == buffer.len() {
9017 break;
9018 } else {
9019 search_start = buffer.len();
9020 }
9021 } else if search_start == 0 {
9022 break;
9023 } else {
9024 search_start = 0;
9025 }
9026 }
9027 }
9028 }
9029
9030 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9031 let snapshot = self.snapshot(cx);
9032 let selection = self.selections.newest::<Point>(cx);
9033 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9034 }
9035
9036 fn go_to_hunk_after_position(
9037 &mut self,
9038 snapshot: &EditorSnapshot,
9039 position: Point,
9040 cx: &mut ViewContext<'_, Editor>,
9041 ) -> Option<MultiBufferDiffHunk> {
9042 for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
9043 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9044 snapshot,
9045 position,
9046 ix > 0,
9047 snapshot.diff_map.diff_hunks_in_range(
9048 position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
9049 &snapshot.buffer_snapshot,
9050 ),
9051 cx,
9052 ) {
9053 return Some(hunk);
9054 }
9055 }
9056 None
9057 }
9058
9059 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9060 let snapshot = self.snapshot(cx);
9061 let selection = self.selections.newest::<Point>(cx);
9062 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9063 }
9064
9065 fn go_to_hunk_before_position(
9066 &mut self,
9067 snapshot: &EditorSnapshot,
9068 position: Point,
9069 cx: &mut ViewContext<'_, Editor>,
9070 ) -> Option<MultiBufferDiffHunk> {
9071 for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
9072 .into_iter()
9073 .enumerate()
9074 {
9075 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9076 snapshot,
9077 position,
9078 ix > 0,
9079 snapshot
9080 .diff_map
9081 .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
9082 cx,
9083 ) {
9084 return Some(hunk);
9085 }
9086 }
9087 None
9088 }
9089
9090 fn go_to_next_hunk_in_direction(
9091 &mut self,
9092 snapshot: &DisplaySnapshot,
9093 initial_point: Point,
9094 is_wrapped: bool,
9095 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9096 cx: &mut ViewContext<Editor>,
9097 ) -> Option<MultiBufferDiffHunk> {
9098 let display_point = initial_point.to_display_point(snapshot);
9099 let mut hunks = hunks
9100 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9101 .filter(|(display_hunk, _)| {
9102 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9103 })
9104 .dedup();
9105
9106 if let Some((display_hunk, hunk)) = hunks.next() {
9107 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9108 let row = display_hunk.start_display_row();
9109 let point = DisplayPoint::new(row, 0);
9110 s.select_display_ranges([point..point]);
9111 });
9112
9113 Some(hunk)
9114 } else {
9115 None
9116 }
9117 }
9118
9119 pub fn go_to_definition(
9120 &mut self,
9121 _: &GoToDefinition,
9122 cx: &mut ViewContext<Self>,
9123 ) -> Task<Result<Navigated>> {
9124 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9125 cx.spawn(|editor, mut cx| async move {
9126 if definition.await? == Navigated::Yes {
9127 return Ok(Navigated::Yes);
9128 }
9129 match editor.update(&mut cx, |editor, cx| {
9130 editor.find_all_references(&FindAllReferences, cx)
9131 })? {
9132 Some(references) => references.await,
9133 None => Ok(Navigated::No),
9134 }
9135 })
9136 }
9137
9138 pub fn go_to_declaration(
9139 &mut self,
9140 _: &GoToDeclaration,
9141 cx: &mut ViewContext<Self>,
9142 ) -> Task<Result<Navigated>> {
9143 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9144 }
9145
9146 pub fn go_to_declaration_split(
9147 &mut self,
9148 _: &GoToDeclaration,
9149 cx: &mut ViewContext<Self>,
9150 ) -> Task<Result<Navigated>> {
9151 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9152 }
9153
9154 pub fn go_to_implementation(
9155 &mut self,
9156 _: &GoToImplementation,
9157 cx: &mut ViewContext<Self>,
9158 ) -> Task<Result<Navigated>> {
9159 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9160 }
9161
9162 pub fn go_to_implementation_split(
9163 &mut self,
9164 _: &GoToImplementationSplit,
9165 cx: &mut ViewContext<Self>,
9166 ) -> Task<Result<Navigated>> {
9167 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9168 }
9169
9170 pub fn go_to_type_definition(
9171 &mut self,
9172 _: &GoToTypeDefinition,
9173 cx: &mut ViewContext<Self>,
9174 ) -> Task<Result<Navigated>> {
9175 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9176 }
9177
9178 pub fn go_to_definition_split(
9179 &mut self,
9180 _: &GoToDefinitionSplit,
9181 cx: &mut ViewContext<Self>,
9182 ) -> Task<Result<Navigated>> {
9183 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9184 }
9185
9186 pub fn go_to_type_definition_split(
9187 &mut self,
9188 _: &GoToTypeDefinitionSplit,
9189 cx: &mut ViewContext<Self>,
9190 ) -> Task<Result<Navigated>> {
9191 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9192 }
9193
9194 fn go_to_definition_of_kind(
9195 &mut self,
9196 kind: GotoDefinitionKind,
9197 split: bool,
9198 cx: &mut ViewContext<Self>,
9199 ) -> Task<Result<Navigated>> {
9200 let Some(provider) = self.semantics_provider.clone() else {
9201 return Task::ready(Ok(Navigated::No));
9202 };
9203 let head = self.selections.newest::<usize>(cx).head();
9204 let buffer = self.buffer.read(cx);
9205 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9206 text_anchor
9207 } else {
9208 return Task::ready(Ok(Navigated::No));
9209 };
9210
9211 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9212 return Task::ready(Ok(Navigated::No));
9213 };
9214
9215 cx.spawn(|editor, mut cx| async move {
9216 let definitions = definitions.await?;
9217 let navigated = editor
9218 .update(&mut cx, |editor, cx| {
9219 editor.navigate_to_hover_links(
9220 Some(kind),
9221 definitions
9222 .into_iter()
9223 .filter(|location| {
9224 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9225 })
9226 .map(HoverLink::Text)
9227 .collect::<Vec<_>>(),
9228 split,
9229 cx,
9230 )
9231 })?
9232 .await?;
9233 anyhow::Ok(navigated)
9234 })
9235 }
9236
9237 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9238 let position = self.selections.newest_anchor().head();
9239 let Some((buffer, buffer_position)) =
9240 self.buffer.read(cx).text_anchor_for_position(position, cx)
9241 else {
9242 return;
9243 };
9244
9245 cx.spawn(|editor, mut cx| async move {
9246 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9247 editor.update(&mut cx, |_, cx| {
9248 cx.open_url(&url);
9249 })
9250 } else {
9251 Ok(())
9252 }
9253 })
9254 .detach();
9255 }
9256
9257 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9258 let Some(workspace) = self.workspace() else {
9259 return;
9260 };
9261
9262 let position = self.selections.newest_anchor().head();
9263
9264 let Some((buffer, buffer_position)) =
9265 self.buffer.read(cx).text_anchor_for_position(position, cx)
9266 else {
9267 return;
9268 };
9269
9270 let project = self.project.clone();
9271
9272 cx.spawn(|_, mut cx| async move {
9273 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9274
9275 if let Some((_, path)) = result {
9276 workspace
9277 .update(&mut cx, |workspace, cx| {
9278 workspace.open_resolved_path(path, cx)
9279 })?
9280 .await?;
9281 }
9282 anyhow::Ok(())
9283 })
9284 .detach();
9285 }
9286
9287 pub(crate) fn navigate_to_hover_links(
9288 &mut self,
9289 kind: Option<GotoDefinitionKind>,
9290 mut definitions: Vec<HoverLink>,
9291 split: bool,
9292 cx: &mut ViewContext<Editor>,
9293 ) -> Task<Result<Navigated>> {
9294 // If there is one definition, just open it directly
9295 if definitions.len() == 1 {
9296 let definition = definitions.pop().unwrap();
9297
9298 enum TargetTaskResult {
9299 Location(Option<Location>),
9300 AlreadyNavigated,
9301 }
9302
9303 let target_task = match definition {
9304 HoverLink::Text(link) => {
9305 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9306 }
9307 HoverLink::InlayHint(lsp_location, server_id) => {
9308 let computation = self.compute_target_location(lsp_location, server_id, cx);
9309 cx.background_executor().spawn(async move {
9310 let location = computation.await?;
9311 Ok(TargetTaskResult::Location(location))
9312 })
9313 }
9314 HoverLink::Url(url) => {
9315 cx.open_url(&url);
9316 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9317 }
9318 HoverLink::File(path) => {
9319 if let Some(workspace) = self.workspace() {
9320 cx.spawn(|_, mut cx| async move {
9321 workspace
9322 .update(&mut cx, |workspace, cx| {
9323 workspace.open_resolved_path(path, cx)
9324 })?
9325 .await
9326 .map(|_| TargetTaskResult::AlreadyNavigated)
9327 })
9328 } else {
9329 Task::ready(Ok(TargetTaskResult::Location(None)))
9330 }
9331 }
9332 };
9333 cx.spawn(|editor, mut cx| async move {
9334 let target = match target_task.await.context("target resolution task")? {
9335 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9336 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9337 TargetTaskResult::Location(Some(target)) => target,
9338 };
9339
9340 editor.update(&mut cx, |editor, cx| {
9341 let Some(workspace) = editor.workspace() else {
9342 return Navigated::No;
9343 };
9344 let pane = workspace.read(cx).active_pane().clone();
9345
9346 let range = target.range.to_offset(target.buffer.read(cx));
9347 let range = editor.range_for_match(&range);
9348
9349 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9350 let buffer = target.buffer.read(cx);
9351 let range = check_multiline_range(buffer, range);
9352 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9353 s.select_ranges([range]);
9354 });
9355 } else {
9356 cx.window_context().defer(move |cx| {
9357 let target_editor: View<Self> =
9358 workspace.update(cx, |workspace, cx| {
9359 let pane = if split {
9360 workspace.adjacent_pane(cx)
9361 } else {
9362 workspace.active_pane().clone()
9363 };
9364
9365 workspace.open_project_item(
9366 pane,
9367 target.buffer.clone(),
9368 true,
9369 true,
9370 cx,
9371 )
9372 });
9373 target_editor.update(cx, |target_editor, cx| {
9374 // When selecting a definition in a different buffer, disable the nav history
9375 // to avoid creating a history entry at the previous cursor location.
9376 pane.update(cx, |pane, _| pane.disable_history());
9377 let buffer = target.buffer.read(cx);
9378 let range = check_multiline_range(buffer, range);
9379 target_editor.change_selections(
9380 Some(Autoscroll::focused()),
9381 cx,
9382 |s| {
9383 s.select_ranges([range]);
9384 },
9385 );
9386 pane.update(cx, |pane, _| pane.enable_history());
9387 });
9388 });
9389 }
9390 Navigated::Yes
9391 })
9392 })
9393 } else if !definitions.is_empty() {
9394 cx.spawn(|editor, mut cx| async move {
9395 let (title, location_tasks, workspace) = editor
9396 .update(&mut cx, |editor, cx| {
9397 let tab_kind = match kind {
9398 Some(GotoDefinitionKind::Implementation) => "Implementations",
9399 _ => "Definitions",
9400 };
9401 let title = definitions
9402 .iter()
9403 .find_map(|definition| match definition {
9404 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9405 let buffer = origin.buffer.read(cx);
9406 format!(
9407 "{} for {}",
9408 tab_kind,
9409 buffer
9410 .text_for_range(origin.range.clone())
9411 .collect::<String>()
9412 )
9413 }),
9414 HoverLink::InlayHint(_, _) => None,
9415 HoverLink::Url(_) => None,
9416 HoverLink::File(_) => None,
9417 })
9418 .unwrap_or(tab_kind.to_string());
9419 let location_tasks = definitions
9420 .into_iter()
9421 .map(|definition| match definition {
9422 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9423 HoverLink::InlayHint(lsp_location, server_id) => {
9424 editor.compute_target_location(lsp_location, server_id, cx)
9425 }
9426 HoverLink::Url(_) => Task::ready(Ok(None)),
9427 HoverLink::File(_) => Task::ready(Ok(None)),
9428 })
9429 .collect::<Vec<_>>();
9430 (title, location_tasks, editor.workspace().clone())
9431 })
9432 .context("location tasks preparation")?;
9433
9434 let locations = future::join_all(location_tasks)
9435 .await
9436 .into_iter()
9437 .filter_map(|location| location.transpose())
9438 .collect::<Result<_>>()
9439 .context("location tasks")?;
9440
9441 let Some(workspace) = workspace else {
9442 return Ok(Navigated::No);
9443 };
9444 let opened = workspace
9445 .update(&mut cx, |workspace, cx| {
9446 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9447 })
9448 .ok();
9449
9450 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9451 })
9452 } else {
9453 Task::ready(Ok(Navigated::No))
9454 }
9455 }
9456
9457 fn compute_target_location(
9458 &self,
9459 lsp_location: lsp::Location,
9460 server_id: LanguageServerId,
9461 cx: &mut ViewContext<Self>,
9462 ) -> Task<anyhow::Result<Option<Location>>> {
9463 let Some(project) = self.project.clone() else {
9464 return Task::Ready(Some(Ok(None)));
9465 };
9466
9467 cx.spawn(move |editor, mut cx| async move {
9468 let location_task = editor.update(&mut cx, |_, cx| {
9469 project.update(cx, |project, cx| {
9470 let language_server_name = project
9471 .language_server_statuses(cx)
9472 .find(|(id, _)| server_id == *id)
9473 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9474 language_server_name.map(|language_server_name| {
9475 project.open_local_buffer_via_lsp(
9476 lsp_location.uri.clone(),
9477 server_id,
9478 language_server_name,
9479 cx,
9480 )
9481 })
9482 })
9483 })?;
9484 let location = match location_task {
9485 Some(task) => Some({
9486 let target_buffer_handle = task.await.context("open local buffer")?;
9487 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9488 let target_start = target_buffer
9489 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9490 let target_end = target_buffer
9491 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9492 target_buffer.anchor_after(target_start)
9493 ..target_buffer.anchor_before(target_end)
9494 })?;
9495 Location {
9496 buffer: target_buffer_handle,
9497 range,
9498 }
9499 }),
9500 None => None,
9501 };
9502 Ok(location)
9503 })
9504 }
9505
9506 pub fn find_all_references(
9507 &mut self,
9508 _: &FindAllReferences,
9509 cx: &mut ViewContext<Self>,
9510 ) -> Option<Task<Result<Navigated>>> {
9511 let selection = self.selections.newest::<usize>(cx);
9512 let multi_buffer = self.buffer.read(cx);
9513 let head = selection.head();
9514
9515 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9516 let head_anchor = multi_buffer_snapshot.anchor_at(
9517 head,
9518 if head < selection.tail() {
9519 Bias::Right
9520 } else {
9521 Bias::Left
9522 },
9523 );
9524
9525 match self
9526 .find_all_references_task_sources
9527 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9528 {
9529 Ok(_) => {
9530 log::info!(
9531 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9532 );
9533 return None;
9534 }
9535 Err(i) => {
9536 self.find_all_references_task_sources.insert(i, head_anchor);
9537 }
9538 }
9539
9540 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9541 let workspace = self.workspace()?;
9542 let project = workspace.read(cx).project().clone();
9543 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9544 Some(cx.spawn(|editor, mut cx| async move {
9545 let _cleanup = defer({
9546 let mut cx = cx.clone();
9547 move || {
9548 let _ = editor.update(&mut cx, |editor, _| {
9549 if let Ok(i) =
9550 editor
9551 .find_all_references_task_sources
9552 .binary_search_by(|anchor| {
9553 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9554 })
9555 {
9556 editor.find_all_references_task_sources.remove(i);
9557 }
9558 });
9559 }
9560 });
9561
9562 let locations = references.await?;
9563 if locations.is_empty() {
9564 return anyhow::Ok(Navigated::No);
9565 }
9566
9567 workspace.update(&mut cx, |workspace, cx| {
9568 let title = locations
9569 .first()
9570 .as_ref()
9571 .map(|location| {
9572 let buffer = location.buffer.read(cx);
9573 format!(
9574 "References to `{}`",
9575 buffer
9576 .text_for_range(location.range.clone())
9577 .collect::<String>()
9578 )
9579 })
9580 .unwrap();
9581 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9582 Navigated::Yes
9583 })
9584 }))
9585 }
9586
9587 /// Opens a multibuffer with the given project locations in it
9588 pub fn open_locations_in_multibuffer(
9589 workspace: &mut Workspace,
9590 mut locations: Vec<Location>,
9591 title: String,
9592 split: bool,
9593 cx: &mut ViewContext<Workspace>,
9594 ) {
9595 // If there are multiple definitions, open them in a multibuffer
9596 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9597 let mut locations = locations.into_iter().peekable();
9598 let mut ranges_to_highlight = Vec::new();
9599 let capability = workspace.project().read(cx).capability();
9600
9601 let excerpt_buffer = cx.new_model(|cx| {
9602 let mut multibuffer = MultiBuffer::new(capability);
9603 while let Some(location) = locations.next() {
9604 let buffer = location.buffer.read(cx);
9605 let mut ranges_for_buffer = Vec::new();
9606 let range = location.range.to_offset(buffer);
9607 ranges_for_buffer.push(range.clone());
9608
9609 while let Some(next_location) = locations.peek() {
9610 if next_location.buffer == location.buffer {
9611 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9612 locations.next();
9613 } else {
9614 break;
9615 }
9616 }
9617
9618 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9619 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9620 location.buffer.clone(),
9621 ranges_for_buffer,
9622 DEFAULT_MULTIBUFFER_CONTEXT,
9623 cx,
9624 ))
9625 }
9626
9627 multibuffer.with_title(title)
9628 });
9629
9630 let editor = cx.new_view(|cx| {
9631 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9632 });
9633 editor.update(cx, |editor, cx| {
9634 if let Some(first_range) = ranges_to_highlight.first() {
9635 editor.change_selections(None, cx, |selections| {
9636 selections.clear_disjoint();
9637 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9638 });
9639 }
9640 editor.highlight_background::<Self>(
9641 &ranges_to_highlight,
9642 |theme| theme.editor_highlighted_line_background,
9643 cx,
9644 );
9645 });
9646
9647 let item = Box::new(editor);
9648 let item_id = item.item_id();
9649
9650 if split {
9651 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9652 } else {
9653 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9654 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9655 pane.close_current_preview_item(cx)
9656 } else {
9657 None
9658 }
9659 });
9660 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9661 }
9662 workspace.active_pane().update(cx, |pane, cx| {
9663 pane.set_preview_item_id(Some(item_id), cx);
9664 });
9665 }
9666
9667 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9668 use language::ToOffset as _;
9669
9670 let provider = self.semantics_provider.clone()?;
9671 let selection = self.selections.newest_anchor().clone();
9672 let (cursor_buffer, cursor_buffer_position) = self
9673 .buffer
9674 .read(cx)
9675 .text_anchor_for_position(selection.head(), cx)?;
9676 let (tail_buffer, cursor_buffer_position_end) = self
9677 .buffer
9678 .read(cx)
9679 .text_anchor_for_position(selection.tail(), cx)?;
9680 if tail_buffer != cursor_buffer {
9681 return None;
9682 }
9683
9684 let snapshot = cursor_buffer.read(cx).snapshot();
9685 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9686 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9687 let prepare_rename = provider
9688 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
9689 .unwrap_or_else(|| Task::ready(Ok(None)));
9690 drop(snapshot);
9691
9692 Some(cx.spawn(|this, mut cx| async move {
9693 let rename_range = if let Some(range) = prepare_rename.await? {
9694 Some(range)
9695 } else {
9696 this.update(&mut cx, |this, cx| {
9697 let buffer = this.buffer.read(cx).snapshot(cx);
9698 let mut buffer_highlights = this
9699 .document_highlights_for_position(selection.head(), &buffer)
9700 .filter(|highlight| {
9701 highlight.start.excerpt_id == selection.head().excerpt_id
9702 && highlight.end.excerpt_id == selection.head().excerpt_id
9703 });
9704 buffer_highlights
9705 .next()
9706 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9707 })?
9708 };
9709 if let Some(rename_range) = rename_range {
9710 this.update(&mut cx, |this, cx| {
9711 let snapshot = cursor_buffer.read(cx).snapshot();
9712 let rename_buffer_range = rename_range.to_offset(&snapshot);
9713 let cursor_offset_in_rename_range =
9714 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9715 let cursor_offset_in_rename_range_end =
9716 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9717
9718 this.take_rename(false, cx);
9719 let buffer = this.buffer.read(cx).read(cx);
9720 let cursor_offset = selection.head().to_offset(&buffer);
9721 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9722 let rename_end = rename_start + rename_buffer_range.len();
9723 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9724 let mut old_highlight_id = None;
9725 let old_name: Arc<str> = buffer
9726 .chunks(rename_start..rename_end, true)
9727 .map(|chunk| {
9728 if old_highlight_id.is_none() {
9729 old_highlight_id = chunk.syntax_highlight_id;
9730 }
9731 chunk.text
9732 })
9733 .collect::<String>()
9734 .into();
9735
9736 drop(buffer);
9737
9738 // Position the selection in the rename editor so that it matches the current selection.
9739 this.show_local_selections = false;
9740 let rename_editor = cx.new_view(|cx| {
9741 let mut editor = Editor::single_line(cx);
9742 editor.buffer.update(cx, |buffer, cx| {
9743 buffer.edit([(0..0, old_name.clone())], None, cx)
9744 });
9745 let rename_selection_range = match cursor_offset_in_rename_range
9746 .cmp(&cursor_offset_in_rename_range_end)
9747 {
9748 Ordering::Equal => {
9749 editor.select_all(&SelectAll, cx);
9750 return editor;
9751 }
9752 Ordering::Less => {
9753 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9754 }
9755 Ordering::Greater => {
9756 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9757 }
9758 };
9759 if rename_selection_range.end > old_name.len() {
9760 editor.select_all(&SelectAll, cx);
9761 } else {
9762 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9763 s.select_ranges([rename_selection_range]);
9764 });
9765 }
9766 editor
9767 });
9768 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
9769 if e == &EditorEvent::Focused {
9770 cx.emit(EditorEvent::FocusedIn)
9771 }
9772 })
9773 .detach();
9774
9775 let write_highlights =
9776 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9777 let read_highlights =
9778 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9779 let ranges = write_highlights
9780 .iter()
9781 .flat_map(|(_, ranges)| ranges.iter())
9782 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9783 .cloned()
9784 .collect();
9785
9786 this.highlight_text::<Rename>(
9787 ranges,
9788 HighlightStyle {
9789 fade_out: Some(0.6),
9790 ..Default::default()
9791 },
9792 cx,
9793 );
9794 let rename_focus_handle = rename_editor.focus_handle(cx);
9795 cx.focus(&rename_focus_handle);
9796 let block_id = this.insert_blocks(
9797 [BlockProperties {
9798 style: BlockStyle::Flex,
9799 placement: BlockPlacement::Below(range.start),
9800 height: 1,
9801 render: Arc::new({
9802 let rename_editor = rename_editor.clone();
9803 move |cx: &mut BlockContext| {
9804 let mut text_style = cx.editor_style.text.clone();
9805 if let Some(highlight_style) = old_highlight_id
9806 .and_then(|h| h.style(&cx.editor_style.syntax))
9807 {
9808 text_style = text_style.highlight(highlight_style);
9809 }
9810 div()
9811 .block_mouse_down()
9812 .pl(cx.anchor_x)
9813 .child(EditorElement::new(
9814 &rename_editor,
9815 EditorStyle {
9816 background: cx.theme().system().transparent,
9817 local_player: cx.editor_style.local_player,
9818 text: text_style,
9819 scrollbar_width: cx.editor_style.scrollbar_width,
9820 syntax: cx.editor_style.syntax.clone(),
9821 status: cx.editor_style.status.clone(),
9822 inlay_hints_style: HighlightStyle {
9823 font_weight: Some(FontWeight::BOLD),
9824 ..make_inlay_hints_style(cx)
9825 },
9826 suggestions_style: HighlightStyle {
9827 color: Some(cx.theme().status().predictive),
9828 ..HighlightStyle::default()
9829 },
9830 ..EditorStyle::default()
9831 },
9832 ))
9833 .into_any_element()
9834 }
9835 }),
9836 priority: 0,
9837 }],
9838 Some(Autoscroll::fit()),
9839 cx,
9840 )[0];
9841 this.pending_rename = Some(RenameState {
9842 range,
9843 old_name,
9844 editor: rename_editor,
9845 block_id,
9846 });
9847 })?;
9848 }
9849
9850 Ok(())
9851 }))
9852 }
9853
9854 pub fn confirm_rename(
9855 &mut self,
9856 _: &ConfirmRename,
9857 cx: &mut ViewContext<Self>,
9858 ) -> Option<Task<Result<()>>> {
9859 let rename = self.take_rename(false, cx)?;
9860 let workspace = self.workspace()?.downgrade();
9861 let (buffer, start) = self
9862 .buffer
9863 .read(cx)
9864 .text_anchor_for_position(rename.range.start, cx)?;
9865 let (end_buffer, _) = self
9866 .buffer
9867 .read(cx)
9868 .text_anchor_for_position(rename.range.end, cx)?;
9869 if buffer != end_buffer {
9870 return None;
9871 }
9872
9873 let old_name = rename.old_name;
9874 let new_name = rename.editor.read(cx).text(cx);
9875
9876 let rename = self.semantics_provider.as_ref()?.perform_rename(
9877 &buffer,
9878 start,
9879 new_name.clone(),
9880 cx,
9881 )?;
9882
9883 Some(cx.spawn(|editor, mut cx| async move {
9884 let project_transaction = rename.await?;
9885 Self::open_project_transaction(
9886 &editor,
9887 workspace,
9888 project_transaction,
9889 format!("Rename: {} → {}", old_name, new_name),
9890 cx.clone(),
9891 )
9892 .await?;
9893
9894 editor.update(&mut cx, |editor, cx| {
9895 editor.refresh_document_highlights(cx);
9896 })?;
9897 Ok(())
9898 }))
9899 }
9900
9901 fn take_rename(
9902 &mut self,
9903 moving_cursor: bool,
9904 cx: &mut ViewContext<Self>,
9905 ) -> Option<RenameState> {
9906 let rename = self.pending_rename.take()?;
9907 if rename.editor.focus_handle(cx).is_focused(cx) {
9908 cx.focus(&self.focus_handle);
9909 }
9910
9911 self.remove_blocks(
9912 [rename.block_id].into_iter().collect(),
9913 Some(Autoscroll::fit()),
9914 cx,
9915 );
9916 self.clear_highlights::<Rename>(cx);
9917 self.show_local_selections = true;
9918
9919 if moving_cursor {
9920 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
9921 editor.selections.newest::<usize>(cx).head()
9922 });
9923
9924 // Update the selection to match the position of the selection inside
9925 // the rename editor.
9926 let snapshot = self.buffer.read(cx).read(cx);
9927 let rename_range = rename.range.to_offset(&snapshot);
9928 let cursor_in_editor = snapshot
9929 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
9930 .min(rename_range.end);
9931 drop(snapshot);
9932
9933 self.change_selections(None, cx, |s| {
9934 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
9935 });
9936 } else {
9937 self.refresh_document_highlights(cx);
9938 }
9939
9940 Some(rename)
9941 }
9942
9943 pub fn pending_rename(&self) -> Option<&RenameState> {
9944 self.pending_rename.as_ref()
9945 }
9946
9947 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9948 let project = match &self.project {
9949 Some(project) => project.clone(),
9950 None => return None,
9951 };
9952
9953 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
9954 }
9955
9956 fn format_selections(
9957 &mut self,
9958 _: &FormatSelections,
9959 cx: &mut ViewContext<Self>,
9960 ) -> Option<Task<Result<()>>> {
9961 let project = match &self.project {
9962 Some(project) => project.clone(),
9963 None => return None,
9964 };
9965
9966 let selections = self
9967 .selections
9968 .all_adjusted(cx)
9969 .into_iter()
9970 .filter(|s| !s.is_empty())
9971 .collect_vec();
9972
9973 Some(self.perform_format(
9974 project,
9975 FormatTrigger::Manual,
9976 FormatTarget::Ranges(selections),
9977 cx,
9978 ))
9979 }
9980
9981 fn perform_format(
9982 &mut self,
9983 project: Model<Project>,
9984 trigger: FormatTrigger,
9985 target: FormatTarget,
9986 cx: &mut ViewContext<Self>,
9987 ) -> Task<Result<()>> {
9988 let buffer = self.buffer().clone();
9989 let mut buffers = buffer.read(cx).all_buffers();
9990 if trigger == FormatTrigger::Save {
9991 buffers.retain(|buffer| buffer.read(cx).is_dirty());
9992 }
9993
9994 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
9995 let format = project.update(cx, |project, cx| {
9996 project.format(buffers, true, trigger, target, cx)
9997 });
9998
9999 cx.spawn(|_, mut cx| async move {
10000 let transaction = futures::select_biased! {
10001 () = timeout => {
10002 log::warn!("timed out waiting for formatting");
10003 None
10004 }
10005 transaction = format.log_err().fuse() => transaction,
10006 };
10007
10008 buffer
10009 .update(&mut cx, |buffer, cx| {
10010 if let Some(transaction) = transaction {
10011 if !buffer.is_singleton() {
10012 buffer.push_transaction(&transaction.0, cx);
10013 }
10014 }
10015
10016 cx.notify();
10017 })
10018 .ok();
10019
10020 Ok(())
10021 })
10022 }
10023
10024 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10025 if let Some(project) = self.project.clone() {
10026 self.buffer.update(cx, |multi_buffer, cx| {
10027 project.update(cx, |project, cx| {
10028 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10029 });
10030 })
10031 }
10032 }
10033
10034 fn cancel_language_server_work(
10035 &mut self,
10036 _: &actions::CancelLanguageServerWork,
10037 cx: &mut ViewContext<Self>,
10038 ) {
10039 if let Some(project) = self.project.clone() {
10040 self.buffer.update(cx, |multi_buffer, cx| {
10041 project.update(cx, |project, cx| {
10042 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10043 });
10044 })
10045 }
10046 }
10047
10048 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10049 cx.show_character_palette();
10050 }
10051
10052 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10053 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10054 let buffer = self.buffer.read(cx).snapshot(cx);
10055 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10056 let is_valid = buffer
10057 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10058 .any(|entry| {
10059 entry.diagnostic.is_primary
10060 && !entry.range.is_empty()
10061 && entry.range.start == primary_range_start
10062 && entry.diagnostic.message == active_diagnostics.primary_message
10063 });
10064
10065 if is_valid != active_diagnostics.is_valid {
10066 active_diagnostics.is_valid = is_valid;
10067 let mut new_styles = HashMap::default();
10068 for (block_id, diagnostic) in &active_diagnostics.blocks {
10069 new_styles.insert(
10070 *block_id,
10071 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10072 );
10073 }
10074 self.display_map.update(cx, |display_map, _cx| {
10075 display_map.replace_blocks(new_styles)
10076 });
10077 }
10078 }
10079 }
10080
10081 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10082 self.dismiss_diagnostics(cx);
10083 let snapshot = self.snapshot(cx);
10084 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10085 let buffer = self.buffer.read(cx).snapshot(cx);
10086
10087 let mut primary_range = None;
10088 let mut primary_message = None;
10089 let mut group_end = Point::zero();
10090 let diagnostic_group = buffer
10091 .diagnostic_group::<MultiBufferPoint>(group_id)
10092 .filter_map(|entry| {
10093 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10094 && (entry.range.start.row == entry.range.end.row
10095 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10096 {
10097 return None;
10098 }
10099 if entry.range.end > group_end {
10100 group_end = entry.range.end;
10101 }
10102 if entry.diagnostic.is_primary {
10103 primary_range = Some(entry.range.clone());
10104 primary_message = Some(entry.diagnostic.message.clone());
10105 }
10106 Some(entry)
10107 })
10108 .collect::<Vec<_>>();
10109 let primary_range = primary_range?;
10110 let primary_message = primary_message?;
10111 let primary_range =
10112 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10113
10114 let blocks = display_map
10115 .insert_blocks(
10116 diagnostic_group.iter().map(|entry| {
10117 let diagnostic = entry.diagnostic.clone();
10118 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10119 BlockProperties {
10120 style: BlockStyle::Fixed,
10121 placement: BlockPlacement::Below(
10122 buffer.anchor_after(entry.range.start),
10123 ),
10124 height: message_height,
10125 render: diagnostic_block_renderer(diagnostic, None, true, true),
10126 priority: 0,
10127 }
10128 }),
10129 cx,
10130 )
10131 .into_iter()
10132 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10133 .collect();
10134
10135 Some(ActiveDiagnosticGroup {
10136 primary_range,
10137 primary_message,
10138 group_id,
10139 blocks,
10140 is_valid: true,
10141 })
10142 });
10143 self.active_diagnostics.is_some()
10144 }
10145
10146 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10147 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10148 self.display_map.update(cx, |display_map, cx| {
10149 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10150 });
10151 cx.notify();
10152 }
10153 }
10154
10155 pub fn set_selections_from_remote(
10156 &mut self,
10157 selections: Vec<Selection<Anchor>>,
10158 pending_selection: Option<Selection<Anchor>>,
10159 cx: &mut ViewContext<Self>,
10160 ) {
10161 let old_cursor_position = self.selections.newest_anchor().head();
10162 self.selections.change_with(cx, |s| {
10163 s.select_anchors(selections);
10164 if let Some(pending_selection) = pending_selection {
10165 s.set_pending(pending_selection, SelectMode::Character);
10166 } else {
10167 s.clear_pending();
10168 }
10169 });
10170 self.selections_did_change(false, &old_cursor_position, true, cx);
10171 }
10172
10173 fn push_to_selection_history(&mut self) {
10174 self.selection_history.push(SelectionHistoryEntry {
10175 selections: self.selections.disjoint_anchors(),
10176 select_next_state: self.select_next_state.clone(),
10177 select_prev_state: self.select_prev_state.clone(),
10178 add_selections_state: self.add_selections_state.clone(),
10179 });
10180 }
10181
10182 pub fn transact(
10183 &mut self,
10184 cx: &mut ViewContext<Self>,
10185 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10186 ) -> Option<TransactionId> {
10187 self.start_transaction_at(Instant::now(), cx);
10188 update(self, cx);
10189 self.end_transaction_at(Instant::now(), cx)
10190 }
10191
10192 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10193 self.end_selection(cx);
10194 if let Some(tx_id) = self
10195 .buffer
10196 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10197 {
10198 self.selection_history
10199 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10200 cx.emit(EditorEvent::TransactionBegun {
10201 transaction_id: tx_id,
10202 })
10203 }
10204 }
10205
10206 fn end_transaction_at(
10207 &mut self,
10208 now: Instant,
10209 cx: &mut ViewContext<Self>,
10210 ) -> Option<TransactionId> {
10211 if let Some(transaction_id) = self
10212 .buffer
10213 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10214 {
10215 if let Some((_, end_selections)) =
10216 self.selection_history.transaction_mut(transaction_id)
10217 {
10218 *end_selections = Some(self.selections.disjoint_anchors());
10219 } else {
10220 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10221 }
10222
10223 cx.emit(EditorEvent::Edited { transaction_id });
10224 Some(transaction_id)
10225 } else {
10226 None
10227 }
10228 }
10229
10230 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10231 let selection = self.selections.newest::<Point>(cx);
10232
10233 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10234 let range = if selection.is_empty() {
10235 let point = selection.head().to_display_point(&display_map);
10236 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10237 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10238 .to_point(&display_map);
10239 start..end
10240 } else {
10241 selection.range()
10242 };
10243 if display_map.folds_in_range(range).next().is_some() {
10244 self.unfold_lines(&Default::default(), cx)
10245 } else {
10246 self.fold(&Default::default(), cx)
10247 }
10248 }
10249
10250 pub fn toggle_fold_recursive(
10251 &mut self,
10252 _: &actions::ToggleFoldRecursive,
10253 cx: &mut ViewContext<Self>,
10254 ) {
10255 let selection = self.selections.newest::<Point>(cx);
10256
10257 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10258 let range = if selection.is_empty() {
10259 let point = selection.head().to_display_point(&display_map);
10260 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10261 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10262 .to_point(&display_map);
10263 start..end
10264 } else {
10265 selection.range()
10266 };
10267 if display_map.folds_in_range(range).next().is_some() {
10268 self.unfold_recursive(&Default::default(), cx)
10269 } else {
10270 self.fold_recursive(&Default::default(), cx)
10271 }
10272 }
10273
10274 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10275 let mut to_fold = Vec::new();
10276 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10277 let selections = self.selections.all_adjusted(cx);
10278
10279 for selection in selections {
10280 let range = selection.range().sorted();
10281 let buffer_start_row = range.start.row;
10282
10283 if range.start.row != range.end.row {
10284 let mut found = false;
10285 let mut row = range.start.row;
10286 while row <= range.end.row {
10287 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10288 found = true;
10289 row = crease.range().end.row + 1;
10290 to_fold.push(crease);
10291 } else {
10292 row += 1
10293 }
10294 }
10295 if found {
10296 continue;
10297 }
10298 }
10299
10300 for row in (0..=range.start.row).rev() {
10301 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10302 if crease.range().end.row >= buffer_start_row {
10303 to_fold.push(crease);
10304 if row <= range.start.row {
10305 break;
10306 }
10307 }
10308 }
10309 }
10310 }
10311
10312 self.fold_creases(to_fold, true, cx);
10313 }
10314
10315 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10316 if !self.buffer.read(cx).is_singleton() {
10317 return;
10318 }
10319
10320 let fold_at_level = fold_at.level;
10321 let snapshot = self.buffer.read(cx).snapshot(cx);
10322 let mut to_fold = Vec::new();
10323 let mut stack = vec![(0, snapshot.max_row().0, 1)];
10324
10325 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10326 while start_row < end_row {
10327 match self
10328 .snapshot(cx)
10329 .crease_for_buffer_row(MultiBufferRow(start_row))
10330 {
10331 Some(crease) => {
10332 let nested_start_row = crease.range().start.row + 1;
10333 let nested_end_row = crease.range().end.row;
10334
10335 if current_level < fold_at_level {
10336 stack.push((nested_start_row, nested_end_row, current_level + 1));
10337 } else if current_level == fold_at_level {
10338 to_fold.push(crease);
10339 }
10340
10341 start_row = nested_end_row + 1;
10342 }
10343 None => start_row += 1,
10344 }
10345 }
10346 }
10347
10348 self.fold_creases(to_fold, true, cx);
10349 }
10350
10351 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10352 if !self.buffer.read(cx).is_singleton() {
10353 return;
10354 }
10355
10356 let mut fold_ranges = Vec::new();
10357 let snapshot = self.buffer.read(cx).snapshot(cx);
10358
10359 for row in 0..snapshot.max_row().0 {
10360 if let Some(foldable_range) =
10361 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10362 {
10363 fold_ranges.push(foldable_range);
10364 }
10365 }
10366
10367 self.fold_creases(fold_ranges, true, cx);
10368 }
10369
10370 pub fn fold_function_bodies(
10371 &mut self,
10372 _: &actions::FoldFunctionBodies,
10373 cx: &mut ViewContext<Self>,
10374 ) {
10375 let snapshot = self.buffer.read(cx).snapshot(cx);
10376 let Some((_, _, buffer)) = snapshot.as_singleton() else {
10377 return;
10378 };
10379 let creases = buffer
10380 .function_body_fold_ranges(0..buffer.len())
10381 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10382 .collect();
10383
10384 self.fold_creases(creases, true, cx);
10385 }
10386
10387 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10388 let mut to_fold = Vec::new();
10389 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10390 let selections = self.selections.all_adjusted(cx);
10391
10392 for selection in selections {
10393 let range = selection.range().sorted();
10394 let buffer_start_row = range.start.row;
10395
10396 if range.start.row != range.end.row {
10397 let mut found = false;
10398 for row in range.start.row..=range.end.row {
10399 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10400 found = true;
10401 to_fold.push(crease);
10402 }
10403 }
10404 if found {
10405 continue;
10406 }
10407 }
10408
10409 for row in (0..=range.start.row).rev() {
10410 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10411 if crease.range().end.row >= buffer_start_row {
10412 to_fold.push(crease);
10413 } else {
10414 break;
10415 }
10416 }
10417 }
10418 }
10419
10420 self.fold_creases(to_fold, true, cx);
10421 }
10422
10423 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10424 let buffer_row = fold_at.buffer_row;
10425 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10426
10427 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10428 let autoscroll = self
10429 .selections
10430 .all::<Point>(cx)
10431 .iter()
10432 .any(|selection| crease.range().overlaps(&selection.range()));
10433
10434 self.fold_creases(vec![crease], autoscroll, cx);
10435 }
10436 }
10437
10438 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10439 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10440 let buffer = &display_map.buffer_snapshot;
10441 let selections = self.selections.all::<Point>(cx);
10442 let ranges = selections
10443 .iter()
10444 .map(|s| {
10445 let range = s.display_range(&display_map).sorted();
10446 let mut start = range.start.to_point(&display_map);
10447 let mut end = range.end.to_point(&display_map);
10448 start.column = 0;
10449 end.column = buffer.line_len(MultiBufferRow(end.row));
10450 start..end
10451 })
10452 .collect::<Vec<_>>();
10453
10454 self.unfold_ranges(&ranges, true, true, cx);
10455 }
10456
10457 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10458 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10459 let selections = self.selections.all::<Point>(cx);
10460 let ranges = selections
10461 .iter()
10462 .map(|s| {
10463 let mut range = s.display_range(&display_map).sorted();
10464 *range.start.column_mut() = 0;
10465 *range.end.column_mut() = display_map.line_len(range.end.row());
10466 let start = range.start.to_point(&display_map);
10467 let end = range.end.to_point(&display_map);
10468 start..end
10469 })
10470 .collect::<Vec<_>>();
10471
10472 self.unfold_ranges(&ranges, true, true, cx);
10473 }
10474
10475 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10476 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10477
10478 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10479 ..Point::new(
10480 unfold_at.buffer_row.0,
10481 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10482 );
10483
10484 let autoscroll = self
10485 .selections
10486 .all::<Point>(cx)
10487 .iter()
10488 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10489
10490 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10491 }
10492
10493 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10494 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10495 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10496 }
10497
10498 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10499 let selections = self.selections.all::<Point>(cx);
10500 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10501 let line_mode = self.selections.line_mode;
10502 let ranges = selections
10503 .into_iter()
10504 .map(|s| {
10505 if line_mode {
10506 let start = Point::new(s.start.row, 0);
10507 let end = Point::new(
10508 s.end.row,
10509 display_map
10510 .buffer_snapshot
10511 .line_len(MultiBufferRow(s.end.row)),
10512 );
10513 Crease::simple(start..end, display_map.fold_placeholder.clone())
10514 } else {
10515 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10516 }
10517 })
10518 .collect::<Vec<_>>();
10519 self.fold_creases(ranges, true, cx);
10520 }
10521
10522 pub fn fold_creases<T: ToOffset + Clone>(
10523 &mut self,
10524 creases: Vec<Crease<T>>,
10525 auto_scroll: bool,
10526 cx: &mut ViewContext<Self>,
10527 ) {
10528 if creases.is_empty() {
10529 return;
10530 }
10531
10532 let mut buffers_affected = HashSet::default();
10533 let multi_buffer = self.buffer().read(cx);
10534 for crease in &creases {
10535 if let Some((_, buffer, _)) =
10536 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10537 {
10538 buffers_affected.insert(buffer.read(cx).remote_id());
10539 };
10540 }
10541
10542 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10543
10544 if auto_scroll {
10545 self.request_autoscroll(Autoscroll::fit(), cx);
10546 }
10547
10548 for buffer_id in buffers_affected {
10549 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10550 }
10551
10552 cx.notify();
10553
10554 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10555 // Clear diagnostics block when folding a range that contains it.
10556 let snapshot = self.snapshot(cx);
10557 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10558 drop(snapshot);
10559 self.active_diagnostics = Some(active_diagnostics);
10560 self.dismiss_diagnostics(cx);
10561 } else {
10562 self.active_diagnostics = Some(active_diagnostics);
10563 }
10564 }
10565
10566 self.scrollbar_marker_state.dirty = true;
10567 }
10568
10569 /// Removes any folds whose ranges intersect any of the given ranges.
10570 pub fn unfold_ranges<T: ToOffset + Clone>(
10571 &mut self,
10572 ranges: &[Range<T>],
10573 inclusive: bool,
10574 auto_scroll: bool,
10575 cx: &mut ViewContext<Self>,
10576 ) {
10577 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10578 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10579 });
10580 }
10581
10582 /// Removes any folds with the given ranges.
10583 pub fn remove_folds_with_type<T: ToOffset + Clone>(
10584 &mut self,
10585 ranges: &[Range<T>],
10586 type_id: TypeId,
10587 auto_scroll: bool,
10588 cx: &mut ViewContext<Self>,
10589 ) {
10590 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10591 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
10592 });
10593 }
10594
10595 fn remove_folds_with<T: ToOffset + Clone>(
10596 &mut self,
10597 ranges: &[Range<T>],
10598 auto_scroll: bool,
10599 cx: &mut ViewContext<Self>,
10600 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
10601 ) {
10602 if ranges.is_empty() {
10603 return;
10604 }
10605
10606 let mut buffers_affected = HashSet::default();
10607 let multi_buffer = self.buffer().read(cx);
10608 for range in ranges {
10609 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10610 buffers_affected.insert(buffer.read(cx).remote_id());
10611 };
10612 }
10613
10614 self.display_map.update(cx, update);
10615
10616 if auto_scroll {
10617 self.request_autoscroll(Autoscroll::fit(), cx);
10618 }
10619
10620 for buffer_id in buffers_affected {
10621 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10622 }
10623
10624 cx.notify();
10625 self.scrollbar_marker_state.dirty = true;
10626 self.active_indent_guides_state.dirty = true;
10627 }
10628
10629 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10630 self.display_map.read(cx).fold_placeholder.clone()
10631 }
10632
10633 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10634 if hovered != self.gutter_hovered {
10635 self.gutter_hovered = hovered;
10636 cx.notify();
10637 }
10638 }
10639
10640 pub fn insert_blocks(
10641 &mut self,
10642 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10643 autoscroll: Option<Autoscroll>,
10644 cx: &mut ViewContext<Self>,
10645 ) -> Vec<CustomBlockId> {
10646 let blocks = self
10647 .display_map
10648 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10649 if let Some(autoscroll) = autoscroll {
10650 self.request_autoscroll(autoscroll, cx);
10651 }
10652 cx.notify();
10653 blocks
10654 }
10655
10656 pub fn resize_blocks(
10657 &mut self,
10658 heights: HashMap<CustomBlockId, u32>,
10659 autoscroll: Option<Autoscroll>,
10660 cx: &mut ViewContext<Self>,
10661 ) {
10662 self.display_map
10663 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10664 if let Some(autoscroll) = autoscroll {
10665 self.request_autoscroll(autoscroll, cx);
10666 }
10667 cx.notify();
10668 }
10669
10670 pub fn replace_blocks(
10671 &mut self,
10672 renderers: HashMap<CustomBlockId, RenderBlock>,
10673 autoscroll: Option<Autoscroll>,
10674 cx: &mut ViewContext<Self>,
10675 ) {
10676 self.display_map
10677 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10678 if let Some(autoscroll) = autoscroll {
10679 self.request_autoscroll(autoscroll, cx);
10680 }
10681 cx.notify();
10682 }
10683
10684 pub fn remove_blocks(
10685 &mut self,
10686 block_ids: HashSet<CustomBlockId>,
10687 autoscroll: Option<Autoscroll>,
10688 cx: &mut ViewContext<Self>,
10689 ) {
10690 self.display_map.update(cx, |display_map, cx| {
10691 display_map.remove_blocks(block_ids, cx)
10692 });
10693 if let Some(autoscroll) = autoscroll {
10694 self.request_autoscroll(autoscroll, cx);
10695 }
10696 cx.notify();
10697 }
10698
10699 pub fn row_for_block(
10700 &self,
10701 block_id: CustomBlockId,
10702 cx: &mut ViewContext<Self>,
10703 ) -> Option<DisplayRow> {
10704 self.display_map
10705 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10706 }
10707
10708 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10709 self.focused_block = Some(focused_block);
10710 }
10711
10712 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10713 self.focused_block.take()
10714 }
10715
10716 pub fn insert_creases(
10717 &mut self,
10718 creases: impl IntoIterator<Item = Crease<Anchor>>,
10719 cx: &mut ViewContext<Self>,
10720 ) -> Vec<CreaseId> {
10721 self.display_map
10722 .update(cx, |map, cx| map.insert_creases(creases, cx))
10723 }
10724
10725 pub fn remove_creases(
10726 &mut self,
10727 ids: impl IntoIterator<Item = CreaseId>,
10728 cx: &mut ViewContext<Self>,
10729 ) {
10730 self.display_map
10731 .update(cx, |map, cx| map.remove_creases(ids, cx));
10732 }
10733
10734 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10735 self.display_map
10736 .update(cx, |map, cx| map.snapshot(cx))
10737 .longest_row()
10738 }
10739
10740 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10741 self.display_map
10742 .update(cx, |map, cx| map.snapshot(cx))
10743 .max_point()
10744 }
10745
10746 pub fn text(&self, cx: &AppContext) -> String {
10747 self.buffer.read(cx).read(cx).text()
10748 }
10749
10750 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10751 let text = self.text(cx);
10752 let text = text.trim();
10753
10754 if text.is_empty() {
10755 return None;
10756 }
10757
10758 Some(text.to_string())
10759 }
10760
10761 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10762 self.transact(cx, |this, cx| {
10763 this.buffer
10764 .read(cx)
10765 .as_singleton()
10766 .expect("you can only call set_text on editors for singleton buffers")
10767 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10768 });
10769 }
10770
10771 pub fn display_text(&self, cx: &mut AppContext) -> String {
10772 self.display_map
10773 .update(cx, |map, cx| map.snapshot(cx))
10774 .text()
10775 }
10776
10777 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10778 let mut wrap_guides = smallvec::smallvec![];
10779
10780 if self.show_wrap_guides == Some(false) {
10781 return wrap_guides;
10782 }
10783
10784 let settings = self.buffer.read(cx).settings_at(0, cx);
10785 if settings.show_wrap_guides {
10786 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10787 wrap_guides.push((soft_wrap as usize, true));
10788 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10789 wrap_guides.push((soft_wrap as usize, true));
10790 }
10791 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10792 }
10793
10794 wrap_guides
10795 }
10796
10797 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10798 let settings = self.buffer.read(cx).settings_at(0, cx);
10799 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
10800 match mode {
10801 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
10802 SoftWrap::None
10803 }
10804 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10805 language_settings::SoftWrap::PreferredLineLength => {
10806 SoftWrap::Column(settings.preferred_line_length)
10807 }
10808 language_settings::SoftWrap::Bounded => {
10809 SoftWrap::Bounded(settings.preferred_line_length)
10810 }
10811 }
10812 }
10813
10814 pub fn set_soft_wrap_mode(
10815 &mut self,
10816 mode: language_settings::SoftWrap,
10817 cx: &mut ViewContext<Self>,
10818 ) {
10819 self.soft_wrap_mode_override = Some(mode);
10820 cx.notify();
10821 }
10822
10823 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
10824 self.text_style_refinement = Some(style);
10825 }
10826
10827 /// called by the Element so we know what style we were most recently rendered with.
10828 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10829 let rem_size = cx.rem_size();
10830 self.display_map.update(cx, |map, cx| {
10831 map.set_font(
10832 style.text.font(),
10833 style.text.font_size.to_pixels(rem_size),
10834 cx,
10835 )
10836 });
10837 self.style = Some(style);
10838 }
10839
10840 pub fn style(&self) -> Option<&EditorStyle> {
10841 self.style.as_ref()
10842 }
10843
10844 // Called by the element. This method is not designed to be called outside of the editor
10845 // element's layout code because it does not notify when rewrapping is computed synchronously.
10846 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10847 self.display_map
10848 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10849 }
10850
10851 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10852 if self.soft_wrap_mode_override.is_some() {
10853 self.soft_wrap_mode_override.take();
10854 } else {
10855 let soft_wrap = match self.soft_wrap_mode(cx) {
10856 SoftWrap::GitDiff => return,
10857 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
10858 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
10859 language_settings::SoftWrap::None
10860 }
10861 };
10862 self.soft_wrap_mode_override = Some(soft_wrap);
10863 }
10864 cx.notify();
10865 }
10866
10867 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10868 let Some(workspace) = self.workspace() else {
10869 return;
10870 };
10871 let fs = workspace.read(cx).app_state().fs.clone();
10872 let current_show = TabBarSettings::get_global(cx).show;
10873 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10874 setting.show = Some(!current_show);
10875 });
10876 }
10877
10878 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10879 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10880 self.buffer
10881 .read(cx)
10882 .settings_at(0, cx)
10883 .indent_guides
10884 .enabled
10885 });
10886 self.show_indent_guides = Some(!currently_enabled);
10887 cx.notify();
10888 }
10889
10890 fn should_show_indent_guides(&self) -> Option<bool> {
10891 self.show_indent_guides
10892 }
10893
10894 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10895 let mut editor_settings = EditorSettings::get_global(cx).clone();
10896 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10897 EditorSettings::override_global(editor_settings, cx);
10898 }
10899
10900 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
10901 self.use_relative_line_numbers
10902 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
10903 }
10904
10905 pub fn toggle_relative_line_numbers(
10906 &mut self,
10907 _: &ToggleRelativeLineNumbers,
10908 cx: &mut ViewContext<Self>,
10909 ) {
10910 let is_relative = self.should_use_relative_line_numbers(cx);
10911 self.set_relative_line_number(Some(!is_relative), cx)
10912 }
10913
10914 pub fn set_relative_line_number(
10915 &mut self,
10916 is_relative: Option<bool>,
10917 cx: &mut ViewContext<Self>,
10918 ) {
10919 self.use_relative_line_numbers = is_relative;
10920 cx.notify();
10921 }
10922
10923 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10924 self.show_gutter = show_gutter;
10925 cx.notify();
10926 }
10927
10928 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10929 self.show_line_numbers = Some(show_line_numbers);
10930 cx.notify();
10931 }
10932
10933 pub fn set_show_git_diff_gutter(
10934 &mut self,
10935 show_git_diff_gutter: bool,
10936 cx: &mut ViewContext<Self>,
10937 ) {
10938 self.show_git_diff_gutter = Some(show_git_diff_gutter);
10939 cx.notify();
10940 }
10941
10942 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10943 self.show_code_actions = Some(show_code_actions);
10944 cx.notify();
10945 }
10946
10947 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10948 self.show_runnables = Some(show_runnables);
10949 cx.notify();
10950 }
10951
10952 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10953 if self.display_map.read(cx).masked != masked {
10954 self.display_map.update(cx, |map, _| map.masked = masked);
10955 }
10956 cx.notify()
10957 }
10958
10959 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10960 self.show_wrap_guides = Some(show_wrap_guides);
10961 cx.notify();
10962 }
10963
10964 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10965 self.show_indent_guides = Some(show_indent_guides);
10966 cx.notify();
10967 }
10968
10969 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10970 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10971 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10972 if let Some(dir) = file.abs_path(cx).parent() {
10973 return Some(dir.to_owned());
10974 }
10975 }
10976
10977 if let Some(project_path) = buffer.read(cx).project_path(cx) {
10978 return Some(project_path.path.to_path_buf());
10979 }
10980 }
10981
10982 None
10983 }
10984
10985 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
10986 self.active_excerpt(cx)?
10987 .1
10988 .read(cx)
10989 .file()
10990 .and_then(|f| f.as_local())
10991 }
10992
10993 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10994 if let Some(target) = self.target_file(cx) {
10995 cx.reveal_path(&target.abs_path(cx));
10996 }
10997 }
10998
10999 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11000 if let Some(file) = self.target_file(cx) {
11001 if let Some(path) = file.abs_path(cx).to_str() {
11002 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11003 }
11004 }
11005 }
11006
11007 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11008 if let Some(file) = self.target_file(cx) {
11009 if let Some(path) = file.path().to_str() {
11010 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11011 }
11012 }
11013 }
11014
11015 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11016 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11017
11018 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11019 self.start_git_blame(true, cx);
11020 }
11021
11022 cx.notify();
11023 }
11024
11025 pub fn toggle_git_blame_inline(
11026 &mut self,
11027 _: &ToggleGitBlameInline,
11028 cx: &mut ViewContext<Self>,
11029 ) {
11030 self.toggle_git_blame_inline_internal(true, cx);
11031 cx.notify();
11032 }
11033
11034 pub fn git_blame_inline_enabled(&self) -> bool {
11035 self.git_blame_inline_enabled
11036 }
11037
11038 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11039 self.show_selection_menu = self
11040 .show_selection_menu
11041 .map(|show_selections_menu| !show_selections_menu)
11042 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11043
11044 cx.notify();
11045 }
11046
11047 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11048 self.show_selection_menu
11049 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11050 }
11051
11052 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11053 if let Some(project) = self.project.as_ref() {
11054 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11055 return;
11056 };
11057
11058 if buffer.read(cx).file().is_none() {
11059 return;
11060 }
11061
11062 let focused = self.focus_handle(cx).contains_focused(cx);
11063
11064 let project = project.clone();
11065 let blame =
11066 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11067 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11068 self.blame = Some(blame);
11069 }
11070 }
11071
11072 fn toggle_git_blame_inline_internal(
11073 &mut self,
11074 user_triggered: bool,
11075 cx: &mut ViewContext<Self>,
11076 ) {
11077 if self.git_blame_inline_enabled {
11078 self.git_blame_inline_enabled = false;
11079 self.show_git_blame_inline = false;
11080 self.show_git_blame_inline_delay_task.take();
11081 } else {
11082 self.git_blame_inline_enabled = true;
11083 self.start_git_blame_inline(user_triggered, cx);
11084 }
11085
11086 cx.notify();
11087 }
11088
11089 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11090 self.start_git_blame(user_triggered, cx);
11091
11092 if ProjectSettings::get_global(cx)
11093 .git
11094 .inline_blame_delay()
11095 .is_some()
11096 {
11097 self.start_inline_blame_timer(cx);
11098 } else {
11099 self.show_git_blame_inline = true
11100 }
11101 }
11102
11103 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11104 self.blame.as_ref()
11105 }
11106
11107 pub fn show_git_blame_gutter(&self) -> bool {
11108 self.show_git_blame_gutter
11109 }
11110
11111 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11112 self.show_git_blame_gutter && self.has_blame_entries(cx)
11113 }
11114
11115 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11116 self.show_git_blame_inline
11117 && self.focus_handle.is_focused(cx)
11118 && !self.newest_selection_head_on_empty_line(cx)
11119 && self.has_blame_entries(cx)
11120 }
11121
11122 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11123 self.blame()
11124 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11125 }
11126
11127 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11128 let cursor_anchor = self.selections.newest_anchor().head();
11129
11130 let snapshot = self.buffer.read(cx).snapshot(cx);
11131 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11132
11133 snapshot.line_len(buffer_row) == 0
11134 }
11135
11136 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11137 let buffer_and_selection = maybe!({
11138 let selection = self.selections.newest::<Point>(cx);
11139 let selection_range = selection.range();
11140
11141 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11142 (buffer, selection_range.start.row..selection_range.end.row)
11143 } else {
11144 let buffer_ranges = self
11145 .buffer()
11146 .read(cx)
11147 .range_to_buffer_ranges(selection_range, cx);
11148
11149 let (buffer, range, _) = if selection.reversed {
11150 buffer_ranges.first()
11151 } else {
11152 buffer_ranges.last()
11153 }?;
11154
11155 let snapshot = buffer.read(cx).snapshot();
11156 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11157 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11158 (buffer.clone(), selection)
11159 };
11160
11161 Some((buffer, selection))
11162 });
11163
11164 let Some((buffer, selection)) = buffer_and_selection else {
11165 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11166 };
11167
11168 let Some(project) = self.project.as_ref() else {
11169 return Task::ready(Err(anyhow!("editor does not have project")));
11170 };
11171
11172 project.update(cx, |project, cx| {
11173 project.get_permalink_to_line(&buffer, selection, cx)
11174 })
11175 }
11176
11177 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11178 let permalink_task = self.get_permalink_to_line(cx);
11179 let workspace = self.workspace();
11180
11181 cx.spawn(|_, mut cx| async move {
11182 match permalink_task.await {
11183 Ok(permalink) => {
11184 cx.update(|cx| {
11185 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11186 })
11187 .ok();
11188 }
11189 Err(err) => {
11190 let message = format!("Failed to copy permalink: {err}");
11191
11192 Err::<(), anyhow::Error>(err).log_err();
11193
11194 if let Some(workspace) = workspace {
11195 workspace
11196 .update(&mut cx, |workspace, cx| {
11197 struct CopyPermalinkToLine;
11198
11199 workspace.show_toast(
11200 Toast::new(
11201 NotificationId::unique::<CopyPermalinkToLine>(),
11202 message,
11203 ),
11204 cx,
11205 )
11206 })
11207 .ok();
11208 }
11209 }
11210 }
11211 })
11212 .detach();
11213 }
11214
11215 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11216 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11217 if let Some(file) = self.target_file(cx) {
11218 if let Some(path) = file.path().to_str() {
11219 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11220 }
11221 }
11222 }
11223
11224 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11225 let permalink_task = self.get_permalink_to_line(cx);
11226 let workspace = self.workspace();
11227
11228 cx.spawn(|_, mut cx| async move {
11229 match permalink_task.await {
11230 Ok(permalink) => {
11231 cx.update(|cx| {
11232 cx.open_url(permalink.as_ref());
11233 })
11234 .ok();
11235 }
11236 Err(err) => {
11237 let message = format!("Failed to open permalink: {err}");
11238
11239 Err::<(), anyhow::Error>(err).log_err();
11240
11241 if let Some(workspace) = workspace {
11242 workspace
11243 .update(&mut cx, |workspace, cx| {
11244 struct OpenPermalinkToLine;
11245
11246 workspace.show_toast(
11247 Toast::new(
11248 NotificationId::unique::<OpenPermalinkToLine>(),
11249 message,
11250 ),
11251 cx,
11252 )
11253 })
11254 .ok();
11255 }
11256 }
11257 }
11258 })
11259 .detach();
11260 }
11261
11262 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11263 self.insert_uuid(UuidVersion::V4, cx);
11264 }
11265
11266 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11267 self.insert_uuid(UuidVersion::V7, cx);
11268 }
11269
11270 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11271 self.transact(cx, |this, cx| {
11272 let edits = this
11273 .selections
11274 .all::<Point>(cx)
11275 .into_iter()
11276 .map(|selection| {
11277 let uuid = match version {
11278 UuidVersion::V4 => uuid::Uuid::new_v4(),
11279 UuidVersion::V7 => uuid::Uuid::now_v7(),
11280 };
11281
11282 (selection.range(), uuid.to_string())
11283 });
11284 this.edit(edits, cx);
11285 this.refresh_inline_completion(true, false, cx);
11286 });
11287 }
11288
11289 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11290 /// last highlight added will be used.
11291 ///
11292 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11293 pub fn highlight_rows<T: 'static>(
11294 &mut self,
11295 range: Range<Anchor>,
11296 color: Hsla,
11297 should_autoscroll: bool,
11298 cx: &mut ViewContext<Self>,
11299 ) {
11300 let snapshot = self.buffer().read(cx).snapshot(cx);
11301 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11302 let ix = row_highlights.binary_search_by(|highlight| {
11303 Ordering::Equal
11304 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11305 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11306 });
11307
11308 if let Err(mut ix) = ix {
11309 let index = post_inc(&mut self.highlight_order);
11310
11311 // If this range intersects with the preceding highlight, then merge it with
11312 // the preceding highlight. Otherwise insert a new highlight.
11313 let mut merged = false;
11314 if ix > 0 {
11315 let prev_highlight = &mut row_highlights[ix - 1];
11316 if prev_highlight
11317 .range
11318 .end
11319 .cmp(&range.start, &snapshot)
11320 .is_ge()
11321 {
11322 ix -= 1;
11323 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11324 prev_highlight.range.end = range.end;
11325 }
11326 merged = true;
11327 prev_highlight.index = index;
11328 prev_highlight.color = color;
11329 prev_highlight.should_autoscroll = should_autoscroll;
11330 }
11331 }
11332
11333 if !merged {
11334 row_highlights.insert(
11335 ix,
11336 RowHighlight {
11337 range: range.clone(),
11338 index,
11339 color,
11340 should_autoscroll,
11341 },
11342 );
11343 }
11344
11345 // If any of the following highlights intersect with this one, merge them.
11346 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11347 let highlight = &row_highlights[ix];
11348 if next_highlight
11349 .range
11350 .start
11351 .cmp(&highlight.range.end, &snapshot)
11352 .is_le()
11353 {
11354 if next_highlight
11355 .range
11356 .end
11357 .cmp(&highlight.range.end, &snapshot)
11358 .is_gt()
11359 {
11360 row_highlights[ix].range.end = next_highlight.range.end;
11361 }
11362 row_highlights.remove(ix + 1);
11363 } else {
11364 break;
11365 }
11366 }
11367 }
11368 }
11369
11370 /// Remove any highlighted row ranges of the given type that intersect the
11371 /// given ranges.
11372 pub fn remove_highlighted_rows<T: 'static>(
11373 &mut self,
11374 ranges_to_remove: Vec<Range<Anchor>>,
11375 cx: &mut ViewContext<Self>,
11376 ) {
11377 let snapshot = self.buffer().read(cx).snapshot(cx);
11378 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11379 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11380 row_highlights.retain(|highlight| {
11381 while let Some(range_to_remove) = ranges_to_remove.peek() {
11382 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11383 Ordering::Less | Ordering::Equal => {
11384 ranges_to_remove.next();
11385 }
11386 Ordering::Greater => {
11387 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11388 Ordering::Less | Ordering::Equal => {
11389 return false;
11390 }
11391 Ordering::Greater => break,
11392 }
11393 }
11394 }
11395 }
11396
11397 true
11398 })
11399 }
11400
11401 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11402 pub fn clear_row_highlights<T: 'static>(&mut self) {
11403 self.highlighted_rows.remove(&TypeId::of::<T>());
11404 }
11405
11406 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11407 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11408 self.highlighted_rows
11409 .get(&TypeId::of::<T>())
11410 .map_or(&[] as &[_], |vec| vec.as_slice())
11411 .iter()
11412 .map(|highlight| (highlight.range.clone(), highlight.color))
11413 }
11414
11415 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11416 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11417 /// Allows to ignore certain kinds of highlights.
11418 pub fn highlighted_display_rows(
11419 &mut self,
11420 cx: &mut WindowContext,
11421 ) -> BTreeMap<DisplayRow, Hsla> {
11422 let snapshot = self.snapshot(cx);
11423 let mut used_highlight_orders = HashMap::default();
11424 self.highlighted_rows
11425 .iter()
11426 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11427 .fold(
11428 BTreeMap::<DisplayRow, Hsla>::new(),
11429 |mut unique_rows, highlight| {
11430 let start = highlight.range.start.to_display_point(&snapshot);
11431 let end = highlight.range.end.to_display_point(&snapshot);
11432 let start_row = start.row().0;
11433 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11434 && end.column() == 0
11435 {
11436 end.row().0.saturating_sub(1)
11437 } else {
11438 end.row().0
11439 };
11440 for row in start_row..=end_row {
11441 let used_index =
11442 used_highlight_orders.entry(row).or_insert(highlight.index);
11443 if highlight.index >= *used_index {
11444 *used_index = highlight.index;
11445 unique_rows.insert(DisplayRow(row), highlight.color);
11446 }
11447 }
11448 unique_rows
11449 },
11450 )
11451 }
11452
11453 pub fn highlighted_display_row_for_autoscroll(
11454 &self,
11455 snapshot: &DisplaySnapshot,
11456 ) -> Option<DisplayRow> {
11457 self.highlighted_rows
11458 .values()
11459 .flat_map(|highlighted_rows| highlighted_rows.iter())
11460 .filter_map(|highlight| {
11461 if highlight.should_autoscroll {
11462 Some(highlight.range.start.to_display_point(snapshot).row())
11463 } else {
11464 None
11465 }
11466 })
11467 .min()
11468 }
11469
11470 pub fn set_search_within_ranges(
11471 &mut self,
11472 ranges: &[Range<Anchor>],
11473 cx: &mut ViewContext<Self>,
11474 ) {
11475 self.highlight_background::<SearchWithinRange>(
11476 ranges,
11477 |colors| colors.editor_document_highlight_read_background,
11478 cx,
11479 )
11480 }
11481
11482 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11483 self.breadcrumb_header = Some(new_header);
11484 }
11485
11486 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11487 self.clear_background_highlights::<SearchWithinRange>(cx);
11488 }
11489
11490 pub fn highlight_background<T: 'static>(
11491 &mut self,
11492 ranges: &[Range<Anchor>],
11493 color_fetcher: fn(&ThemeColors) -> Hsla,
11494 cx: &mut ViewContext<Self>,
11495 ) {
11496 self.background_highlights
11497 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11498 self.scrollbar_marker_state.dirty = true;
11499 cx.notify();
11500 }
11501
11502 pub fn clear_background_highlights<T: 'static>(
11503 &mut self,
11504 cx: &mut ViewContext<Self>,
11505 ) -> Option<BackgroundHighlight> {
11506 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11507 if !text_highlights.1.is_empty() {
11508 self.scrollbar_marker_state.dirty = true;
11509 cx.notify();
11510 }
11511 Some(text_highlights)
11512 }
11513
11514 pub fn highlight_gutter<T: 'static>(
11515 &mut self,
11516 ranges: &[Range<Anchor>],
11517 color_fetcher: fn(&AppContext) -> Hsla,
11518 cx: &mut ViewContext<Self>,
11519 ) {
11520 self.gutter_highlights
11521 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11522 cx.notify();
11523 }
11524
11525 pub fn clear_gutter_highlights<T: 'static>(
11526 &mut self,
11527 cx: &mut ViewContext<Self>,
11528 ) -> Option<GutterHighlight> {
11529 cx.notify();
11530 self.gutter_highlights.remove(&TypeId::of::<T>())
11531 }
11532
11533 #[cfg(feature = "test-support")]
11534 pub fn all_text_background_highlights(
11535 &mut self,
11536 cx: &mut ViewContext<Self>,
11537 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11538 let snapshot = self.snapshot(cx);
11539 let buffer = &snapshot.buffer_snapshot;
11540 let start = buffer.anchor_before(0);
11541 let end = buffer.anchor_after(buffer.len());
11542 let theme = cx.theme().colors();
11543 self.background_highlights_in_range(start..end, &snapshot, theme)
11544 }
11545
11546 #[cfg(feature = "test-support")]
11547 pub fn search_background_highlights(
11548 &mut self,
11549 cx: &mut ViewContext<Self>,
11550 ) -> Vec<Range<Point>> {
11551 let snapshot = self.buffer().read(cx).snapshot(cx);
11552
11553 let highlights = self
11554 .background_highlights
11555 .get(&TypeId::of::<items::BufferSearchHighlights>());
11556
11557 if let Some((_color, ranges)) = highlights {
11558 ranges
11559 .iter()
11560 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11561 .collect_vec()
11562 } else {
11563 vec![]
11564 }
11565 }
11566
11567 fn document_highlights_for_position<'a>(
11568 &'a self,
11569 position: Anchor,
11570 buffer: &'a MultiBufferSnapshot,
11571 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11572 let read_highlights = self
11573 .background_highlights
11574 .get(&TypeId::of::<DocumentHighlightRead>())
11575 .map(|h| &h.1);
11576 let write_highlights = self
11577 .background_highlights
11578 .get(&TypeId::of::<DocumentHighlightWrite>())
11579 .map(|h| &h.1);
11580 let left_position = position.bias_left(buffer);
11581 let right_position = position.bias_right(buffer);
11582 read_highlights
11583 .into_iter()
11584 .chain(write_highlights)
11585 .flat_map(move |ranges| {
11586 let start_ix = match ranges.binary_search_by(|probe| {
11587 let cmp = probe.end.cmp(&left_position, buffer);
11588 if cmp.is_ge() {
11589 Ordering::Greater
11590 } else {
11591 Ordering::Less
11592 }
11593 }) {
11594 Ok(i) | Err(i) => i,
11595 };
11596
11597 ranges[start_ix..]
11598 .iter()
11599 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11600 })
11601 }
11602
11603 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11604 self.background_highlights
11605 .get(&TypeId::of::<T>())
11606 .map_or(false, |(_, highlights)| !highlights.is_empty())
11607 }
11608
11609 pub fn background_highlights_in_range(
11610 &self,
11611 search_range: Range<Anchor>,
11612 display_snapshot: &DisplaySnapshot,
11613 theme: &ThemeColors,
11614 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11615 let mut results = Vec::new();
11616 for (color_fetcher, ranges) in self.background_highlights.values() {
11617 let color = color_fetcher(theme);
11618 let start_ix = match ranges.binary_search_by(|probe| {
11619 let cmp = probe
11620 .end
11621 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11622 if cmp.is_gt() {
11623 Ordering::Greater
11624 } else {
11625 Ordering::Less
11626 }
11627 }) {
11628 Ok(i) | Err(i) => i,
11629 };
11630 for range in &ranges[start_ix..] {
11631 if range
11632 .start
11633 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11634 .is_ge()
11635 {
11636 break;
11637 }
11638
11639 let start = range.start.to_display_point(display_snapshot);
11640 let end = range.end.to_display_point(display_snapshot);
11641 results.push((start..end, color))
11642 }
11643 }
11644 results
11645 }
11646
11647 pub fn background_highlight_row_ranges<T: 'static>(
11648 &self,
11649 search_range: Range<Anchor>,
11650 display_snapshot: &DisplaySnapshot,
11651 count: usize,
11652 ) -> Vec<RangeInclusive<DisplayPoint>> {
11653 let mut results = Vec::new();
11654 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11655 return vec![];
11656 };
11657
11658 let start_ix = match ranges.binary_search_by(|probe| {
11659 let cmp = probe
11660 .end
11661 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11662 if cmp.is_gt() {
11663 Ordering::Greater
11664 } else {
11665 Ordering::Less
11666 }
11667 }) {
11668 Ok(i) | Err(i) => i,
11669 };
11670 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11671 if let (Some(start_display), Some(end_display)) = (start, end) {
11672 results.push(
11673 start_display.to_display_point(display_snapshot)
11674 ..=end_display.to_display_point(display_snapshot),
11675 );
11676 }
11677 };
11678 let mut start_row: Option<Point> = None;
11679 let mut end_row: Option<Point> = None;
11680 if ranges.len() > count {
11681 return Vec::new();
11682 }
11683 for range in &ranges[start_ix..] {
11684 if range
11685 .start
11686 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11687 .is_ge()
11688 {
11689 break;
11690 }
11691 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11692 if let Some(current_row) = &end_row {
11693 if end.row == current_row.row {
11694 continue;
11695 }
11696 }
11697 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11698 if start_row.is_none() {
11699 assert_eq!(end_row, None);
11700 start_row = Some(start);
11701 end_row = Some(end);
11702 continue;
11703 }
11704 if let Some(current_end) = end_row.as_mut() {
11705 if start.row > current_end.row + 1 {
11706 push_region(start_row, end_row);
11707 start_row = Some(start);
11708 end_row = Some(end);
11709 } else {
11710 // Merge two hunks.
11711 *current_end = end;
11712 }
11713 } else {
11714 unreachable!();
11715 }
11716 }
11717 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11718 push_region(start_row, end_row);
11719 results
11720 }
11721
11722 pub fn gutter_highlights_in_range(
11723 &self,
11724 search_range: Range<Anchor>,
11725 display_snapshot: &DisplaySnapshot,
11726 cx: &AppContext,
11727 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11728 let mut results = Vec::new();
11729 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11730 let color = color_fetcher(cx);
11731 let start_ix = match ranges.binary_search_by(|probe| {
11732 let cmp = probe
11733 .end
11734 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11735 if cmp.is_gt() {
11736 Ordering::Greater
11737 } else {
11738 Ordering::Less
11739 }
11740 }) {
11741 Ok(i) | Err(i) => i,
11742 };
11743 for range in &ranges[start_ix..] {
11744 if range
11745 .start
11746 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11747 .is_ge()
11748 {
11749 break;
11750 }
11751
11752 let start = range.start.to_display_point(display_snapshot);
11753 let end = range.end.to_display_point(display_snapshot);
11754 results.push((start..end, color))
11755 }
11756 }
11757 results
11758 }
11759
11760 /// Get the text ranges corresponding to the redaction query
11761 pub fn redacted_ranges(
11762 &self,
11763 search_range: Range<Anchor>,
11764 display_snapshot: &DisplaySnapshot,
11765 cx: &WindowContext,
11766 ) -> Vec<Range<DisplayPoint>> {
11767 display_snapshot
11768 .buffer_snapshot
11769 .redacted_ranges(search_range, |file| {
11770 if let Some(file) = file {
11771 file.is_private()
11772 && EditorSettings::get(
11773 Some(SettingsLocation {
11774 worktree_id: file.worktree_id(cx),
11775 path: file.path().as_ref(),
11776 }),
11777 cx,
11778 )
11779 .redact_private_values
11780 } else {
11781 false
11782 }
11783 })
11784 .map(|range| {
11785 range.start.to_display_point(display_snapshot)
11786 ..range.end.to_display_point(display_snapshot)
11787 })
11788 .collect()
11789 }
11790
11791 pub fn highlight_text<T: 'static>(
11792 &mut self,
11793 ranges: Vec<Range<Anchor>>,
11794 style: HighlightStyle,
11795 cx: &mut ViewContext<Self>,
11796 ) {
11797 self.display_map.update(cx, |map, _| {
11798 map.highlight_text(TypeId::of::<T>(), ranges, style)
11799 });
11800 cx.notify();
11801 }
11802
11803 pub(crate) fn highlight_inlays<T: 'static>(
11804 &mut self,
11805 highlights: Vec<InlayHighlight>,
11806 style: HighlightStyle,
11807 cx: &mut ViewContext<Self>,
11808 ) {
11809 self.display_map.update(cx, |map, _| {
11810 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11811 });
11812 cx.notify();
11813 }
11814
11815 pub fn text_highlights<'a, T: 'static>(
11816 &'a self,
11817 cx: &'a AppContext,
11818 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11819 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11820 }
11821
11822 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11823 let cleared = self
11824 .display_map
11825 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11826 if cleared {
11827 cx.notify();
11828 }
11829 }
11830
11831 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11832 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11833 && self.focus_handle.is_focused(cx)
11834 }
11835
11836 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11837 self.show_cursor_when_unfocused = is_enabled;
11838 cx.notify();
11839 }
11840
11841 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11842 cx.notify();
11843 }
11844
11845 fn on_buffer_event(
11846 &mut self,
11847 multibuffer: Model<MultiBuffer>,
11848 event: &multi_buffer::Event,
11849 cx: &mut ViewContext<Self>,
11850 ) {
11851 match event {
11852 multi_buffer::Event::Edited {
11853 singleton_buffer_edited,
11854 } => {
11855 self.scrollbar_marker_state.dirty = true;
11856 self.active_indent_guides_state.dirty = true;
11857 self.refresh_active_diagnostics(cx);
11858 self.refresh_code_actions(cx);
11859 if self.has_active_inline_completion() {
11860 self.update_visible_inline_completion(cx);
11861 }
11862 cx.emit(EditorEvent::BufferEdited);
11863 cx.emit(SearchEvent::MatchesInvalidated);
11864 if *singleton_buffer_edited {
11865 if let Some(project) = &self.project {
11866 let project = project.read(cx);
11867 #[allow(clippy::mutable_key_type)]
11868 let languages_affected = multibuffer
11869 .read(cx)
11870 .all_buffers()
11871 .into_iter()
11872 .filter_map(|buffer| {
11873 let buffer = buffer.read(cx);
11874 let language = buffer.language()?;
11875 if project.is_local()
11876 && project
11877 .language_servers_for_local_buffer(buffer, cx)
11878 .count()
11879 == 0
11880 {
11881 None
11882 } else {
11883 Some(language)
11884 }
11885 })
11886 .cloned()
11887 .collect::<HashSet<_>>();
11888 if !languages_affected.is_empty() {
11889 self.refresh_inlay_hints(
11890 InlayHintRefreshReason::BufferEdited(languages_affected),
11891 cx,
11892 );
11893 }
11894 }
11895 }
11896
11897 let Some(project) = &self.project else { return };
11898 let (telemetry, is_via_ssh) = {
11899 let project = project.read(cx);
11900 let telemetry = project.client().telemetry().clone();
11901 let is_via_ssh = project.is_via_ssh();
11902 (telemetry, is_via_ssh)
11903 };
11904 refresh_linked_ranges(self, cx);
11905 telemetry.log_edit_event("editor", is_via_ssh);
11906 }
11907 multi_buffer::Event::ExcerptsAdded {
11908 buffer,
11909 predecessor,
11910 excerpts,
11911 } => {
11912 self.tasks_update_task = Some(self.refresh_runnables(cx));
11913 let buffer_id = buffer.read(cx).remote_id();
11914 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
11915 if let Some(project) = &self.project {
11916 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
11917 }
11918 }
11919 cx.emit(EditorEvent::ExcerptsAdded {
11920 buffer: buffer.clone(),
11921 predecessor: *predecessor,
11922 excerpts: excerpts.clone(),
11923 });
11924 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11925 }
11926 multi_buffer::Event::ExcerptsRemoved { ids } => {
11927 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11928 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11929 }
11930 multi_buffer::Event::ExcerptsEdited { ids } => {
11931 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11932 }
11933 multi_buffer::Event::ExcerptsExpanded { ids } => {
11934 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11935 }
11936 multi_buffer::Event::Reparsed(buffer_id) => {
11937 self.tasks_update_task = Some(self.refresh_runnables(cx));
11938
11939 cx.emit(EditorEvent::Reparsed(*buffer_id));
11940 }
11941 multi_buffer::Event::LanguageChanged(buffer_id) => {
11942 linked_editing_ranges::refresh_linked_ranges(self, cx);
11943 cx.emit(EditorEvent::Reparsed(*buffer_id));
11944 cx.notify();
11945 }
11946 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11947 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11948 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11949 cx.emit(EditorEvent::TitleChanged)
11950 }
11951 // multi_buffer::Event::DiffBaseChanged => {
11952 // self.scrollbar_marker_state.dirty = true;
11953 // cx.emit(EditorEvent::DiffBaseChanged);
11954 // cx.notify();
11955 // }
11956 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11957 multi_buffer::Event::DiagnosticsUpdated => {
11958 self.refresh_active_diagnostics(cx);
11959 self.scrollbar_marker_state.dirty = true;
11960 cx.notify();
11961 }
11962 _ => {}
11963 };
11964 }
11965
11966 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11967 cx.notify();
11968 }
11969
11970 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11971 self.tasks_update_task = Some(self.refresh_runnables(cx));
11972 self.refresh_inline_completion(true, false, cx);
11973 self.refresh_inlay_hints(
11974 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11975 self.selections.newest_anchor().head(),
11976 &self.buffer.read(cx).snapshot(cx),
11977 cx,
11978 )),
11979 cx,
11980 );
11981
11982 let old_cursor_shape = self.cursor_shape;
11983
11984 {
11985 let editor_settings = EditorSettings::get_global(cx);
11986 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11987 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11988 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
11989 }
11990
11991 if old_cursor_shape != self.cursor_shape {
11992 cx.emit(EditorEvent::CursorShapeChanged);
11993 }
11994
11995 let project_settings = ProjectSettings::get_global(cx);
11996 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11997
11998 if self.mode == EditorMode::Full {
11999 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12000 if self.git_blame_inline_enabled != inline_blame_enabled {
12001 self.toggle_git_blame_inline_internal(false, cx);
12002 }
12003 }
12004
12005 cx.notify();
12006 }
12007
12008 pub fn set_searchable(&mut self, searchable: bool) {
12009 self.searchable = searchable;
12010 }
12011
12012 pub fn searchable(&self) -> bool {
12013 self.searchable
12014 }
12015
12016 fn open_proposed_changes_editor(
12017 &mut self,
12018 _: &OpenProposedChangesEditor,
12019 cx: &mut ViewContext<Self>,
12020 ) {
12021 let Some(workspace) = self.workspace() else {
12022 cx.propagate();
12023 return;
12024 };
12025
12026 let selections = self.selections.all::<usize>(cx);
12027 let buffer = self.buffer.read(cx);
12028 let mut new_selections_by_buffer = HashMap::default();
12029 for selection in selections {
12030 for (buffer, range, _) in
12031 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12032 {
12033 let mut range = range.to_point(buffer.read(cx));
12034 range.start.column = 0;
12035 range.end.column = buffer.read(cx).line_len(range.end.row);
12036 new_selections_by_buffer
12037 .entry(buffer)
12038 .or_insert(Vec::new())
12039 .push(range)
12040 }
12041 }
12042
12043 let proposed_changes_buffers = new_selections_by_buffer
12044 .into_iter()
12045 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12046 .collect::<Vec<_>>();
12047 let proposed_changes_editor = cx.new_view(|cx| {
12048 ProposedChangesEditor::new(
12049 "Proposed changes",
12050 proposed_changes_buffers,
12051 self.project.clone(),
12052 cx,
12053 )
12054 });
12055
12056 cx.window_context().defer(move |cx| {
12057 workspace.update(cx, |workspace, cx| {
12058 workspace.active_pane().update(cx, |pane, cx| {
12059 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12060 });
12061 });
12062 });
12063 }
12064
12065 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12066 self.open_excerpts_common(None, true, cx)
12067 }
12068
12069 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12070 self.open_excerpts_common(None, false, cx)
12071 }
12072
12073 fn open_excerpts_common(
12074 &mut self,
12075 jump_data: Option<JumpData>,
12076 split: bool,
12077 cx: &mut ViewContext<Self>,
12078 ) {
12079 let Some(workspace) = self.workspace() else {
12080 cx.propagate();
12081 return;
12082 };
12083
12084 if self.buffer.read(cx).is_singleton() {
12085 cx.propagate();
12086 return;
12087 }
12088
12089 let mut new_selections_by_buffer = HashMap::default();
12090 match &jump_data {
12091 Some(jump_data) => {
12092 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12093 if let Some(buffer) = multi_buffer_snapshot
12094 .buffer_id_for_excerpt(jump_data.excerpt_id)
12095 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12096 {
12097 let buffer_snapshot = buffer.read(cx).snapshot();
12098 let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12099 language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12100 } else {
12101 buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12102 };
12103 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12104 new_selections_by_buffer.insert(
12105 buffer,
12106 (
12107 vec![jump_to_offset..jump_to_offset],
12108 Some(jump_data.line_offset_from_top),
12109 ),
12110 );
12111 }
12112 }
12113 None => {
12114 let selections = self.selections.all::<usize>(cx);
12115 let buffer = self.buffer.read(cx);
12116 for selection in selections {
12117 for (mut buffer_handle, mut range, _) in
12118 buffer.range_to_buffer_ranges(selection.range(), cx)
12119 {
12120 // When editing branch buffers, jump to the corresponding location
12121 // in their base buffer.
12122 let buffer = buffer_handle.read(cx);
12123 if let Some(base_buffer) = buffer.base_buffer() {
12124 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12125 buffer_handle = base_buffer;
12126 }
12127
12128 if selection.reversed {
12129 mem::swap(&mut range.start, &mut range.end);
12130 }
12131 new_selections_by_buffer
12132 .entry(buffer_handle)
12133 .or_insert((Vec::new(), None))
12134 .0
12135 .push(range)
12136 }
12137 }
12138 }
12139 }
12140
12141 if new_selections_by_buffer.is_empty() {
12142 return;
12143 }
12144
12145 // We defer the pane interaction because we ourselves are a workspace item
12146 // and activating a new item causes the pane to call a method on us reentrantly,
12147 // which panics if we're on the stack.
12148 cx.window_context().defer(move |cx| {
12149 workspace.update(cx, |workspace, cx| {
12150 let pane = if split {
12151 workspace.adjacent_pane(cx)
12152 } else {
12153 workspace.active_pane().clone()
12154 };
12155
12156 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12157 let editor = buffer
12158 .read(cx)
12159 .file()
12160 .is_none()
12161 .then(|| {
12162 // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12163 // so `workspace.open_project_item` will never find them, always opening a new editor.
12164 // Instead, we try to activate the existing editor in the pane first.
12165 let (editor, pane_item_index) =
12166 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12167 let editor = item.downcast::<Editor>()?;
12168 let singleton_buffer =
12169 editor.read(cx).buffer().read(cx).as_singleton()?;
12170 if singleton_buffer == buffer {
12171 Some((editor, i))
12172 } else {
12173 None
12174 }
12175 })?;
12176 pane.update(cx, |pane, cx| {
12177 pane.activate_item(pane_item_index, true, true, cx)
12178 });
12179 Some(editor)
12180 })
12181 .flatten()
12182 .unwrap_or_else(|| {
12183 workspace.open_project_item::<Self>(
12184 pane.clone(),
12185 buffer,
12186 true,
12187 true,
12188 cx,
12189 )
12190 });
12191
12192 editor.update(cx, |editor, cx| {
12193 let autoscroll = match scroll_offset {
12194 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12195 None => Autoscroll::newest(),
12196 };
12197 let nav_history = editor.nav_history.take();
12198 editor.change_selections(Some(autoscroll), cx, |s| {
12199 s.select_ranges(ranges);
12200 });
12201 editor.nav_history = nav_history;
12202 });
12203 }
12204 })
12205 });
12206 }
12207
12208 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12209 let snapshot = self.buffer.read(cx).read(cx);
12210 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12211 Some(
12212 ranges
12213 .iter()
12214 .map(move |range| {
12215 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12216 })
12217 .collect(),
12218 )
12219 }
12220
12221 fn selection_replacement_ranges(
12222 &self,
12223 range: Range<OffsetUtf16>,
12224 cx: &mut AppContext,
12225 ) -> Vec<Range<OffsetUtf16>> {
12226 let selections = self.selections.all::<OffsetUtf16>(cx);
12227 let newest_selection = selections
12228 .iter()
12229 .max_by_key(|selection| selection.id)
12230 .unwrap();
12231 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12232 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12233 let snapshot = self.buffer.read(cx).read(cx);
12234 selections
12235 .into_iter()
12236 .map(|mut selection| {
12237 selection.start.0 =
12238 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12239 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12240 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12241 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12242 })
12243 .collect()
12244 }
12245
12246 fn report_editor_event(
12247 &self,
12248 operation: &'static str,
12249 file_extension: Option<String>,
12250 cx: &AppContext,
12251 ) {
12252 if cfg!(any(test, feature = "test-support")) {
12253 return;
12254 }
12255
12256 let Some(project) = &self.project else { return };
12257
12258 // If None, we are in a file without an extension
12259 let file = self
12260 .buffer
12261 .read(cx)
12262 .as_singleton()
12263 .and_then(|b| b.read(cx).file());
12264 let file_extension = file_extension.or(file
12265 .as_ref()
12266 .and_then(|file| Path::new(file.file_name(cx)).extension())
12267 .and_then(|e| e.to_str())
12268 .map(|a| a.to_string()));
12269
12270 let vim_mode = cx
12271 .global::<SettingsStore>()
12272 .raw_user_settings()
12273 .get("vim_mode")
12274 == Some(&serde_json::Value::Bool(true));
12275
12276 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12277 == language::language_settings::InlineCompletionProvider::Copilot;
12278 let copilot_enabled_for_language = self
12279 .buffer
12280 .read(cx)
12281 .settings_at(0, cx)
12282 .show_inline_completions;
12283
12284 let project = project.read(cx);
12285 let telemetry = project.client().telemetry().clone();
12286 telemetry.report_editor_event(
12287 file_extension,
12288 vim_mode,
12289 operation,
12290 copilot_enabled,
12291 copilot_enabled_for_language,
12292 project.is_via_ssh(),
12293 )
12294 }
12295
12296 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12297 /// with each line being an array of {text, highlight} objects.
12298 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12299 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12300 return;
12301 };
12302
12303 #[derive(Serialize)]
12304 struct Chunk<'a> {
12305 text: String,
12306 highlight: Option<&'a str>,
12307 }
12308
12309 let snapshot = buffer.read(cx).snapshot();
12310 let range = self
12311 .selected_text_range(false, cx)
12312 .and_then(|selection| {
12313 if selection.range.is_empty() {
12314 None
12315 } else {
12316 Some(selection.range)
12317 }
12318 })
12319 .unwrap_or_else(|| 0..snapshot.len());
12320
12321 let chunks = snapshot.chunks(range, true);
12322 let mut lines = Vec::new();
12323 let mut line: VecDeque<Chunk> = VecDeque::new();
12324
12325 let Some(style) = self.style.as_ref() else {
12326 return;
12327 };
12328
12329 for chunk in chunks {
12330 let highlight = chunk
12331 .syntax_highlight_id
12332 .and_then(|id| id.name(&style.syntax));
12333 let mut chunk_lines = chunk.text.split('\n').peekable();
12334 while let Some(text) = chunk_lines.next() {
12335 let mut merged_with_last_token = false;
12336 if let Some(last_token) = line.back_mut() {
12337 if last_token.highlight == highlight {
12338 last_token.text.push_str(text);
12339 merged_with_last_token = true;
12340 }
12341 }
12342
12343 if !merged_with_last_token {
12344 line.push_back(Chunk {
12345 text: text.into(),
12346 highlight,
12347 });
12348 }
12349
12350 if chunk_lines.peek().is_some() {
12351 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12352 line.pop_front();
12353 }
12354 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12355 line.pop_back();
12356 }
12357
12358 lines.push(mem::take(&mut line));
12359 }
12360 }
12361 }
12362
12363 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12364 return;
12365 };
12366 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12367 }
12368
12369 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12370 self.request_autoscroll(Autoscroll::newest(), cx);
12371 let position = self.selections.newest_display(cx).start;
12372 mouse_context_menu::deploy_context_menu(self, None, position, cx);
12373 }
12374
12375 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12376 &self.inlay_hint_cache
12377 }
12378
12379 pub fn replay_insert_event(
12380 &mut self,
12381 text: &str,
12382 relative_utf16_range: Option<Range<isize>>,
12383 cx: &mut ViewContext<Self>,
12384 ) {
12385 if !self.input_enabled {
12386 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12387 return;
12388 }
12389 if let Some(relative_utf16_range) = relative_utf16_range {
12390 let selections = self.selections.all::<OffsetUtf16>(cx);
12391 self.change_selections(None, cx, |s| {
12392 let new_ranges = selections.into_iter().map(|range| {
12393 let start = OffsetUtf16(
12394 range
12395 .head()
12396 .0
12397 .saturating_add_signed(relative_utf16_range.start),
12398 );
12399 let end = OffsetUtf16(
12400 range
12401 .head()
12402 .0
12403 .saturating_add_signed(relative_utf16_range.end),
12404 );
12405 start..end
12406 });
12407 s.select_ranges(new_ranges);
12408 });
12409 }
12410
12411 self.handle_input(text, cx);
12412 }
12413
12414 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12415 let Some(provider) = self.semantics_provider.as_ref() else {
12416 return false;
12417 };
12418
12419 let mut supports = false;
12420 self.buffer().read(cx).for_each_buffer(|buffer| {
12421 supports |= provider.supports_inlay_hints(buffer, cx);
12422 });
12423 supports
12424 }
12425
12426 pub fn focus(&self, cx: &mut WindowContext) {
12427 cx.focus(&self.focus_handle)
12428 }
12429
12430 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12431 self.focus_handle.is_focused(cx)
12432 }
12433
12434 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12435 cx.emit(EditorEvent::Focused);
12436
12437 if let Some(descendant) = self
12438 .last_focused_descendant
12439 .take()
12440 .and_then(|descendant| descendant.upgrade())
12441 {
12442 cx.focus(&descendant);
12443 } else {
12444 if let Some(blame) = self.blame.as_ref() {
12445 blame.update(cx, GitBlame::focus)
12446 }
12447
12448 self.blink_manager.update(cx, BlinkManager::enable);
12449 self.show_cursor_names(cx);
12450 self.buffer.update(cx, |buffer, cx| {
12451 buffer.finalize_last_transaction(cx);
12452 if self.leader_peer_id.is_none() {
12453 buffer.set_active_selections(
12454 &self.selections.disjoint_anchors(),
12455 self.selections.line_mode,
12456 self.cursor_shape,
12457 cx,
12458 );
12459 }
12460 });
12461 }
12462 }
12463
12464 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12465 cx.emit(EditorEvent::FocusedIn)
12466 }
12467
12468 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12469 if event.blurred != self.focus_handle {
12470 self.last_focused_descendant = Some(event.blurred);
12471 }
12472 }
12473
12474 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12475 self.blink_manager.update(cx, BlinkManager::disable);
12476 self.buffer
12477 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12478
12479 if let Some(blame) = self.blame.as_ref() {
12480 blame.update(cx, GitBlame::blur)
12481 }
12482 if !self.hover_state.focused(cx) {
12483 hide_hover(self, cx);
12484 }
12485
12486 self.hide_context_menu(cx);
12487 cx.emit(EditorEvent::Blurred);
12488 cx.notify();
12489 }
12490
12491 pub fn register_action<A: Action>(
12492 &mut self,
12493 listener: impl Fn(&A, &mut WindowContext) + 'static,
12494 ) -> Subscription {
12495 let id = self.next_editor_action_id.post_inc();
12496 let listener = Arc::new(listener);
12497 self.editor_actions.borrow_mut().insert(
12498 id,
12499 Box::new(move |cx| {
12500 let cx = cx.window_context();
12501 let listener = listener.clone();
12502 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12503 let action = action.downcast_ref().unwrap();
12504 if phase == DispatchPhase::Bubble {
12505 listener(action, cx)
12506 }
12507 })
12508 }),
12509 );
12510
12511 let editor_actions = self.editor_actions.clone();
12512 Subscription::new(move || {
12513 editor_actions.borrow_mut().remove(&id);
12514 })
12515 }
12516
12517 pub fn file_header_size(&self) -> u32 {
12518 FILE_HEADER_HEIGHT
12519 }
12520
12521 pub fn revert(
12522 &mut self,
12523 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12524 cx: &mut ViewContext<Self>,
12525 ) {
12526 self.buffer().update(cx, |multi_buffer, cx| {
12527 for (buffer_id, changes) in revert_changes {
12528 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12529 buffer.update(cx, |buffer, cx| {
12530 buffer.edit(
12531 changes.into_iter().map(|(range, text)| {
12532 (range, text.to_string().map(Arc::<str>::from))
12533 }),
12534 None,
12535 cx,
12536 );
12537 });
12538 }
12539 }
12540 });
12541 self.change_selections(None, cx, |selections| selections.refresh());
12542 }
12543
12544 pub fn to_pixel_point(
12545 &mut self,
12546 source: multi_buffer::Anchor,
12547 editor_snapshot: &EditorSnapshot,
12548 cx: &mut ViewContext<Self>,
12549 ) -> Option<gpui::Point<Pixels>> {
12550 let source_point = source.to_display_point(editor_snapshot);
12551 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12552 }
12553
12554 pub fn display_to_pixel_point(
12555 &self,
12556 source: DisplayPoint,
12557 editor_snapshot: &EditorSnapshot,
12558 cx: &WindowContext,
12559 ) -> Option<gpui::Point<Pixels>> {
12560 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12561 let text_layout_details = self.text_layout_details(cx);
12562 let scroll_top = text_layout_details
12563 .scroll_anchor
12564 .scroll_position(editor_snapshot)
12565 .y;
12566
12567 if source.row().as_f32() < scroll_top.floor() {
12568 return None;
12569 }
12570 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12571 let source_y = line_height * (source.row().as_f32() - scroll_top);
12572 Some(gpui::Point::new(source_x, source_y))
12573 }
12574
12575 pub fn has_active_completions_menu(&self) -> bool {
12576 self.context_menu.read().as_ref().map_or(false, |menu| {
12577 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
12578 })
12579 }
12580
12581 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12582 self.addons
12583 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12584 }
12585
12586 pub fn unregister_addon<T: Addon>(&mut self) {
12587 self.addons.remove(&std::any::TypeId::of::<T>());
12588 }
12589
12590 pub fn addon<T: Addon>(&self) -> Option<&T> {
12591 let type_id = std::any::TypeId::of::<T>();
12592 self.addons
12593 .get(&type_id)
12594 .and_then(|item| item.to_any().downcast_ref::<T>())
12595 }
12596
12597 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
12598 let text_layout_details = self.text_layout_details(cx);
12599 let style = &text_layout_details.editor_style;
12600 let font_id = cx.text_system().resolve_font(&style.text.font());
12601 let font_size = style.text.font_size.to_pixels(cx.rem_size());
12602 let line_height = style.text.line_height_in_pixels(cx.rem_size());
12603
12604 let em_width = cx
12605 .text_system()
12606 .typographic_bounds(font_id, font_size, 'm')
12607 .unwrap()
12608 .size
12609 .width;
12610
12611 gpui::Point::new(em_width, line_height)
12612 }
12613}
12614
12615fn get_unstaged_changes_for_buffers(
12616 project: &Model<Project>,
12617 buffers: impl IntoIterator<Item = Model<Buffer>>,
12618 cx: &mut ViewContext<Editor>,
12619) {
12620 let mut tasks = Vec::new();
12621 project.update(cx, |project, cx| {
12622 for buffer in buffers {
12623 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
12624 }
12625 });
12626 cx.spawn(|this, mut cx| async move {
12627 let change_sets = futures::future::join_all(tasks).await;
12628 this.update(&mut cx, |this, cx| {
12629 for change_set in change_sets {
12630 if let Some(change_set) = change_set.log_err() {
12631 this.diff_map.add_change_set(change_set, cx);
12632 }
12633 }
12634 })
12635 .ok();
12636 })
12637 .detach();
12638}
12639
12640fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
12641 let tab_size = tab_size.get() as usize;
12642 let mut width = offset;
12643
12644 for ch in text.chars() {
12645 width += if ch == '\t' {
12646 tab_size - (width % tab_size)
12647 } else {
12648 1
12649 };
12650 }
12651
12652 width - offset
12653}
12654
12655#[cfg(test)]
12656mod tests {
12657 use super::*;
12658
12659 #[test]
12660 fn test_string_size_with_expanded_tabs() {
12661 let nz = |val| NonZeroU32::new(val).unwrap();
12662 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
12663 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
12664 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
12665 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
12666 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
12667 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
12668 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
12669 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
12670 }
12671}
12672
12673/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
12674struct WordBreakingTokenizer<'a> {
12675 input: &'a str,
12676}
12677
12678impl<'a> WordBreakingTokenizer<'a> {
12679 fn new(input: &'a str) -> Self {
12680 Self { input }
12681 }
12682}
12683
12684fn is_char_ideographic(ch: char) -> bool {
12685 use unicode_script::Script::*;
12686 use unicode_script::UnicodeScript;
12687 matches!(ch.script(), Han | Tangut | Yi)
12688}
12689
12690fn is_grapheme_ideographic(text: &str) -> bool {
12691 text.chars().any(is_char_ideographic)
12692}
12693
12694fn is_grapheme_whitespace(text: &str) -> bool {
12695 text.chars().any(|x| x.is_whitespace())
12696}
12697
12698fn should_stay_with_preceding_ideograph(text: &str) -> bool {
12699 text.chars().next().map_or(false, |ch| {
12700 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
12701 })
12702}
12703
12704#[derive(PartialEq, Eq, Debug, Clone, Copy)]
12705struct WordBreakToken<'a> {
12706 token: &'a str,
12707 grapheme_len: usize,
12708 is_whitespace: bool,
12709}
12710
12711impl<'a> Iterator for WordBreakingTokenizer<'a> {
12712 /// Yields a span, the count of graphemes in the token, and whether it was
12713 /// whitespace. Note that it also breaks at word boundaries.
12714 type Item = WordBreakToken<'a>;
12715
12716 fn next(&mut self) -> Option<Self::Item> {
12717 use unicode_segmentation::UnicodeSegmentation;
12718 if self.input.is_empty() {
12719 return None;
12720 }
12721
12722 let mut iter = self.input.graphemes(true).peekable();
12723 let mut offset = 0;
12724 let mut graphemes = 0;
12725 if let Some(first_grapheme) = iter.next() {
12726 let is_whitespace = is_grapheme_whitespace(first_grapheme);
12727 offset += first_grapheme.len();
12728 graphemes += 1;
12729 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
12730 if let Some(grapheme) = iter.peek().copied() {
12731 if should_stay_with_preceding_ideograph(grapheme) {
12732 offset += grapheme.len();
12733 graphemes += 1;
12734 }
12735 }
12736 } else {
12737 let mut words = self.input[offset..].split_word_bound_indices().peekable();
12738 let mut next_word_bound = words.peek().copied();
12739 if next_word_bound.map_or(false, |(i, _)| i == 0) {
12740 next_word_bound = words.next();
12741 }
12742 while let Some(grapheme) = iter.peek().copied() {
12743 if next_word_bound.map_or(false, |(i, _)| i == offset) {
12744 break;
12745 };
12746 if is_grapheme_whitespace(grapheme) != is_whitespace {
12747 break;
12748 };
12749 offset += grapheme.len();
12750 graphemes += 1;
12751 iter.next();
12752 }
12753 }
12754 let token = &self.input[..offset];
12755 self.input = &self.input[offset..];
12756 if is_whitespace {
12757 Some(WordBreakToken {
12758 token: " ",
12759 grapheme_len: 1,
12760 is_whitespace: true,
12761 })
12762 } else {
12763 Some(WordBreakToken {
12764 token,
12765 grapheme_len: graphemes,
12766 is_whitespace: false,
12767 })
12768 }
12769 } else {
12770 None
12771 }
12772 }
12773}
12774
12775#[test]
12776fn test_word_breaking_tokenizer() {
12777 let tests: &[(&str, &[(&str, usize, bool)])] = &[
12778 ("", &[]),
12779 (" ", &[(" ", 1, true)]),
12780 ("Ʒ", &[("Ʒ", 1, false)]),
12781 ("Ǽ", &[("Ǽ", 1, false)]),
12782 ("⋑", &[("⋑", 1, false)]),
12783 ("⋑⋑", &[("⋑⋑", 2, false)]),
12784 (
12785 "原理,进而",
12786 &[
12787 ("原", 1, false),
12788 ("理,", 2, false),
12789 ("进", 1, false),
12790 ("而", 1, false),
12791 ],
12792 ),
12793 (
12794 "hello world",
12795 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
12796 ),
12797 (
12798 "hello, world",
12799 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
12800 ),
12801 (
12802 " hello world",
12803 &[
12804 (" ", 1, true),
12805 ("hello", 5, false),
12806 (" ", 1, true),
12807 ("world", 5, false),
12808 ],
12809 ),
12810 (
12811 "这是什么 \n 钢笔",
12812 &[
12813 ("这", 1, false),
12814 ("是", 1, false),
12815 ("什", 1, false),
12816 ("么", 1, false),
12817 (" ", 1, true),
12818 ("钢", 1, false),
12819 ("笔", 1, false),
12820 ],
12821 ),
12822 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
12823 ];
12824
12825 for (input, result) in tests {
12826 assert_eq!(
12827 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
12828 result
12829 .iter()
12830 .copied()
12831 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
12832 token,
12833 grapheme_len,
12834 is_whitespace,
12835 })
12836 .collect::<Vec<_>>()
12837 );
12838 }
12839}
12840
12841fn wrap_with_prefix(
12842 line_prefix: String,
12843 unwrapped_text: String,
12844 wrap_column: usize,
12845 tab_size: NonZeroU32,
12846) -> String {
12847 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
12848 let mut wrapped_text = String::new();
12849 let mut current_line = line_prefix.clone();
12850
12851 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
12852 let mut current_line_len = line_prefix_len;
12853 for WordBreakToken {
12854 token,
12855 grapheme_len,
12856 is_whitespace,
12857 } in tokenizer
12858 {
12859 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
12860 wrapped_text.push_str(current_line.trim_end());
12861 wrapped_text.push('\n');
12862 current_line.truncate(line_prefix.len());
12863 current_line_len = line_prefix_len;
12864 if !is_whitespace {
12865 current_line.push_str(token);
12866 current_line_len += grapheme_len;
12867 }
12868 } else if !is_whitespace {
12869 current_line.push_str(token);
12870 current_line_len += grapheme_len;
12871 } else if current_line_len != line_prefix_len {
12872 current_line.push(' ');
12873 current_line_len += 1;
12874 }
12875 }
12876
12877 if !current_line.is_empty() {
12878 wrapped_text.push_str(¤t_line);
12879 }
12880 wrapped_text
12881}
12882
12883#[test]
12884fn test_wrap_with_prefix() {
12885 assert_eq!(
12886 wrap_with_prefix(
12887 "# ".to_string(),
12888 "abcdefg".to_string(),
12889 4,
12890 NonZeroU32::new(4).unwrap()
12891 ),
12892 "# abcdefg"
12893 );
12894 assert_eq!(
12895 wrap_with_prefix(
12896 "".to_string(),
12897 "\thello world".to_string(),
12898 8,
12899 NonZeroU32::new(4).unwrap()
12900 ),
12901 "hello\nworld"
12902 );
12903 assert_eq!(
12904 wrap_with_prefix(
12905 "// ".to_string(),
12906 "xx \nyy zz aa bb cc".to_string(),
12907 12,
12908 NonZeroU32::new(4).unwrap()
12909 ),
12910 "// xx yy zz\n// aa bb cc"
12911 );
12912 assert_eq!(
12913 wrap_with_prefix(
12914 String::new(),
12915 "这是什么 \n 钢笔".to_string(),
12916 3,
12917 NonZeroU32::new(4).unwrap()
12918 ),
12919 "这是什\n么 钢\n笔"
12920 );
12921}
12922
12923fn hunks_for_selections(
12924 snapshot: &EditorSnapshot,
12925 selections: &[Selection<Point>],
12926) -> Vec<MultiBufferDiffHunk> {
12927 hunks_for_ranges(
12928 selections.iter().map(|selection| selection.range()),
12929 snapshot,
12930 )
12931}
12932
12933pub fn hunks_for_ranges(
12934 ranges: impl Iterator<Item = Range<Point>>,
12935 snapshot: &EditorSnapshot,
12936) -> Vec<MultiBufferDiffHunk> {
12937 let mut hunks = Vec::new();
12938 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12939 HashMap::default();
12940 for query_range in ranges {
12941 let query_rows =
12942 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
12943 for hunk in snapshot.diff_map.diff_hunks_in_range(
12944 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
12945 &snapshot.buffer_snapshot,
12946 ) {
12947 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12948 // when the caret is just above or just below the deleted hunk.
12949 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12950 let related_to_selection = if allow_adjacent {
12951 hunk.row_range.overlaps(&query_rows)
12952 || hunk.row_range.start == query_rows.end
12953 || hunk.row_range.end == query_rows.start
12954 } else {
12955 hunk.row_range.overlaps(&query_rows)
12956 };
12957 if related_to_selection {
12958 if !processed_buffer_rows
12959 .entry(hunk.buffer_id)
12960 .or_default()
12961 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12962 {
12963 continue;
12964 }
12965 hunks.push(hunk);
12966 }
12967 }
12968 }
12969
12970 hunks
12971}
12972
12973pub trait CollaborationHub {
12974 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12975 fn user_participant_indices<'a>(
12976 &self,
12977 cx: &'a AppContext,
12978 ) -> &'a HashMap<u64, ParticipantIndex>;
12979 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12980}
12981
12982impl CollaborationHub for Model<Project> {
12983 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12984 self.read(cx).collaborators()
12985 }
12986
12987 fn user_participant_indices<'a>(
12988 &self,
12989 cx: &'a AppContext,
12990 ) -> &'a HashMap<u64, ParticipantIndex> {
12991 self.read(cx).user_store().read(cx).participant_indices()
12992 }
12993
12994 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12995 let this = self.read(cx);
12996 let user_ids = this.collaborators().values().map(|c| c.user_id);
12997 this.user_store().read_with(cx, |user_store, cx| {
12998 user_store.participant_names(user_ids, cx)
12999 })
13000 }
13001}
13002
13003pub trait SemanticsProvider {
13004 fn hover(
13005 &self,
13006 buffer: &Model<Buffer>,
13007 position: text::Anchor,
13008 cx: &mut AppContext,
13009 ) -> Option<Task<Vec<project::Hover>>>;
13010
13011 fn inlay_hints(
13012 &self,
13013 buffer_handle: Model<Buffer>,
13014 range: Range<text::Anchor>,
13015 cx: &mut AppContext,
13016 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13017
13018 fn resolve_inlay_hint(
13019 &self,
13020 hint: InlayHint,
13021 buffer_handle: Model<Buffer>,
13022 server_id: LanguageServerId,
13023 cx: &mut AppContext,
13024 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13025
13026 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13027
13028 fn document_highlights(
13029 &self,
13030 buffer: &Model<Buffer>,
13031 position: text::Anchor,
13032 cx: &mut AppContext,
13033 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13034
13035 fn definitions(
13036 &self,
13037 buffer: &Model<Buffer>,
13038 position: text::Anchor,
13039 kind: GotoDefinitionKind,
13040 cx: &mut AppContext,
13041 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13042
13043 fn range_for_rename(
13044 &self,
13045 buffer: &Model<Buffer>,
13046 position: text::Anchor,
13047 cx: &mut AppContext,
13048 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13049
13050 fn perform_rename(
13051 &self,
13052 buffer: &Model<Buffer>,
13053 position: text::Anchor,
13054 new_name: String,
13055 cx: &mut AppContext,
13056 ) -> Option<Task<Result<ProjectTransaction>>>;
13057}
13058
13059pub trait CompletionProvider {
13060 fn completions(
13061 &self,
13062 buffer: &Model<Buffer>,
13063 buffer_position: text::Anchor,
13064 trigger: CompletionContext,
13065 cx: &mut ViewContext<Editor>,
13066 ) -> Task<Result<Vec<Completion>>>;
13067
13068 fn resolve_completions(
13069 &self,
13070 buffer: Model<Buffer>,
13071 completion_indices: Vec<usize>,
13072 completions: Arc<RwLock<Box<[Completion]>>>,
13073 cx: &mut ViewContext<Editor>,
13074 ) -> Task<Result<bool>>;
13075
13076 fn apply_additional_edits_for_completion(
13077 &self,
13078 buffer: Model<Buffer>,
13079 completion: Completion,
13080 push_to_history: bool,
13081 cx: &mut ViewContext<Editor>,
13082 ) -> Task<Result<Option<language::Transaction>>>;
13083
13084 fn is_completion_trigger(
13085 &self,
13086 buffer: &Model<Buffer>,
13087 position: language::Anchor,
13088 text: &str,
13089 trigger_in_words: bool,
13090 cx: &mut ViewContext<Editor>,
13091 ) -> bool;
13092
13093 fn sort_completions(&self) -> bool {
13094 true
13095 }
13096}
13097
13098pub trait CodeActionProvider {
13099 fn code_actions(
13100 &self,
13101 buffer: &Model<Buffer>,
13102 range: Range<text::Anchor>,
13103 cx: &mut WindowContext,
13104 ) -> Task<Result<Vec<CodeAction>>>;
13105
13106 fn apply_code_action(
13107 &self,
13108 buffer_handle: Model<Buffer>,
13109 action: CodeAction,
13110 excerpt_id: ExcerptId,
13111 push_to_history: bool,
13112 cx: &mut WindowContext,
13113 ) -> Task<Result<ProjectTransaction>>;
13114}
13115
13116impl CodeActionProvider for Model<Project> {
13117 fn code_actions(
13118 &self,
13119 buffer: &Model<Buffer>,
13120 range: Range<text::Anchor>,
13121 cx: &mut WindowContext,
13122 ) -> Task<Result<Vec<CodeAction>>> {
13123 self.update(cx, |project, cx| {
13124 project.code_actions(buffer, range, None, cx)
13125 })
13126 }
13127
13128 fn apply_code_action(
13129 &self,
13130 buffer_handle: Model<Buffer>,
13131 action: CodeAction,
13132 _excerpt_id: ExcerptId,
13133 push_to_history: bool,
13134 cx: &mut WindowContext,
13135 ) -> Task<Result<ProjectTransaction>> {
13136 self.update(cx, |project, cx| {
13137 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13138 })
13139 }
13140}
13141
13142fn snippet_completions(
13143 project: &Project,
13144 buffer: &Model<Buffer>,
13145 buffer_position: text::Anchor,
13146 cx: &mut AppContext,
13147) -> Task<Result<Vec<Completion>>> {
13148 let language = buffer.read(cx).language_at(buffer_position);
13149 let language_name = language.as_ref().map(|language| language.lsp_id());
13150 let snippet_store = project.snippets().read(cx);
13151 let snippets = snippet_store.snippets_for(language_name, cx);
13152
13153 if snippets.is_empty() {
13154 return Task::ready(Ok(vec![]));
13155 }
13156 let snapshot = buffer.read(cx).text_snapshot();
13157 let chars: String = snapshot
13158 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13159 .collect();
13160
13161 let scope = language.map(|language| language.default_scope());
13162 let executor = cx.background_executor().clone();
13163
13164 cx.background_executor().spawn(async move {
13165 let classifier = CharClassifier::new(scope).for_completion(true);
13166 let mut last_word = chars
13167 .chars()
13168 .take_while(|c| classifier.is_word(*c))
13169 .collect::<String>();
13170 last_word = last_word.chars().rev().collect();
13171
13172 if last_word.is_empty() {
13173 return Ok(vec![]);
13174 }
13175
13176 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13177 let to_lsp = |point: &text::Anchor| {
13178 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13179 point_to_lsp(end)
13180 };
13181 let lsp_end = to_lsp(&buffer_position);
13182
13183 let candidates = snippets
13184 .iter()
13185 .enumerate()
13186 .flat_map(|(ix, snippet)| {
13187 snippet
13188 .prefix
13189 .iter()
13190 .map(move |prefix| StringMatchCandidate::new(ix, prefix.clone()))
13191 })
13192 .collect::<Vec<StringMatchCandidate>>();
13193
13194 let mut matches = fuzzy::match_strings(
13195 &candidates,
13196 &last_word,
13197 last_word.chars().any(|c| c.is_uppercase()),
13198 100,
13199 &Default::default(),
13200 executor,
13201 )
13202 .await;
13203
13204 // Remove all candidates where the query's start does not match the start of any word in the candidate
13205 if let Some(query_start) = last_word.chars().next() {
13206 matches.retain(|string_match| {
13207 split_words(&string_match.string).any(|word| {
13208 // Check that the first codepoint of the word as lowercase matches the first
13209 // codepoint of the query as lowercase
13210 word.chars()
13211 .flat_map(|codepoint| codepoint.to_lowercase())
13212 .zip(query_start.to_lowercase())
13213 .all(|(word_cp, query_cp)| word_cp == query_cp)
13214 })
13215 });
13216 }
13217
13218 let matched_strings = matches
13219 .into_iter()
13220 .map(|m| m.string)
13221 .collect::<HashSet<_>>();
13222
13223 let result: Vec<Completion> = snippets
13224 .into_iter()
13225 .filter_map(|snippet| {
13226 let matching_prefix = snippet
13227 .prefix
13228 .iter()
13229 .find(|prefix| matched_strings.contains(*prefix))?;
13230 let start = as_offset - last_word.len();
13231 let start = snapshot.anchor_before(start);
13232 let range = start..buffer_position;
13233 let lsp_start = to_lsp(&start);
13234 let lsp_range = lsp::Range {
13235 start: lsp_start,
13236 end: lsp_end,
13237 };
13238 Some(Completion {
13239 old_range: range,
13240 new_text: snippet.body.clone(),
13241 label: CodeLabel {
13242 text: matching_prefix.clone(),
13243 runs: vec![],
13244 filter_range: 0..matching_prefix.len(),
13245 },
13246 server_id: LanguageServerId(usize::MAX),
13247 documentation: snippet.description.clone().map(Documentation::SingleLine),
13248 lsp_completion: lsp::CompletionItem {
13249 label: snippet.prefix.first().unwrap().clone(),
13250 kind: Some(CompletionItemKind::SNIPPET),
13251 label_details: snippet.description.as_ref().map(|description| {
13252 lsp::CompletionItemLabelDetails {
13253 detail: Some(description.clone()),
13254 description: None,
13255 }
13256 }),
13257 insert_text_format: Some(InsertTextFormat::SNIPPET),
13258 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13259 lsp::InsertReplaceEdit {
13260 new_text: snippet.body.clone(),
13261 insert: lsp_range,
13262 replace: lsp_range,
13263 },
13264 )),
13265 filter_text: Some(snippet.body.clone()),
13266 sort_text: Some(char::MAX.to_string()),
13267 ..Default::default()
13268 },
13269 confirm: None,
13270 })
13271 })
13272 .collect();
13273
13274 Ok(result)
13275 })
13276}
13277
13278impl CompletionProvider for Model<Project> {
13279 fn completions(
13280 &self,
13281 buffer: &Model<Buffer>,
13282 buffer_position: text::Anchor,
13283 options: CompletionContext,
13284 cx: &mut ViewContext<Editor>,
13285 ) -> Task<Result<Vec<Completion>>> {
13286 self.update(cx, |project, cx| {
13287 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13288 let project_completions = project.completions(buffer, buffer_position, options, cx);
13289 cx.background_executor().spawn(async move {
13290 let mut completions = project_completions.await?;
13291 let snippets_completions = snippets.await?;
13292 completions.extend(snippets_completions);
13293 Ok(completions)
13294 })
13295 })
13296 }
13297
13298 fn resolve_completions(
13299 &self,
13300 buffer: Model<Buffer>,
13301 completion_indices: Vec<usize>,
13302 completions: Arc<RwLock<Box<[Completion]>>>,
13303 cx: &mut ViewContext<Editor>,
13304 ) -> Task<Result<bool>> {
13305 self.update(cx, |project, cx| {
13306 project.resolve_completions(buffer, completion_indices, completions, cx)
13307 })
13308 }
13309
13310 fn apply_additional_edits_for_completion(
13311 &self,
13312 buffer: Model<Buffer>,
13313 completion: Completion,
13314 push_to_history: bool,
13315 cx: &mut ViewContext<Editor>,
13316 ) -> Task<Result<Option<language::Transaction>>> {
13317 self.update(cx, |project, cx| {
13318 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13319 })
13320 }
13321
13322 fn is_completion_trigger(
13323 &self,
13324 buffer: &Model<Buffer>,
13325 position: language::Anchor,
13326 text: &str,
13327 trigger_in_words: bool,
13328 cx: &mut ViewContext<Editor>,
13329 ) -> bool {
13330 let mut chars = text.chars();
13331 let char = if let Some(char) = chars.next() {
13332 char
13333 } else {
13334 return false;
13335 };
13336 if chars.next().is_some() {
13337 return false;
13338 }
13339
13340 let buffer = buffer.read(cx);
13341 let snapshot = buffer.snapshot();
13342 if !snapshot.settings_at(position, cx).show_completions_on_input {
13343 return false;
13344 }
13345 let classifier = snapshot.char_classifier_at(position).for_completion(true);
13346 if trigger_in_words && classifier.is_word(char) {
13347 return true;
13348 }
13349
13350 buffer.completion_triggers().contains(text)
13351 }
13352}
13353
13354impl SemanticsProvider for Model<Project> {
13355 fn hover(
13356 &self,
13357 buffer: &Model<Buffer>,
13358 position: text::Anchor,
13359 cx: &mut AppContext,
13360 ) -> Option<Task<Vec<project::Hover>>> {
13361 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13362 }
13363
13364 fn document_highlights(
13365 &self,
13366 buffer: &Model<Buffer>,
13367 position: text::Anchor,
13368 cx: &mut AppContext,
13369 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13370 Some(self.update(cx, |project, cx| {
13371 project.document_highlights(buffer, position, cx)
13372 }))
13373 }
13374
13375 fn definitions(
13376 &self,
13377 buffer: &Model<Buffer>,
13378 position: text::Anchor,
13379 kind: GotoDefinitionKind,
13380 cx: &mut AppContext,
13381 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13382 Some(self.update(cx, |project, cx| match kind {
13383 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13384 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13385 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13386 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13387 }))
13388 }
13389
13390 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13391 // TODO: make this work for remote projects
13392 self.read(cx)
13393 .language_servers_for_local_buffer(buffer.read(cx), cx)
13394 .any(
13395 |(_, server)| match server.capabilities().inlay_hint_provider {
13396 Some(lsp::OneOf::Left(enabled)) => enabled,
13397 Some(lsp::OneOf::Right(_)) => true,
13398 None => false,
13399 },
13400 )
13401 }
13402
13403 fn inlay_hints(
13404 &self,
13405 buffer_handle: Model<Buffer>,
13406 range: Range<text::Anchor>,
13407 cx: &mut AppContext,
13408 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13409 Some(self.update(cx, |project, cx| {
13410 project.inlay_hints(buffer_handle, range, cx)
13411 }))
13412 }
13413
13414 fn resolve_inlay_hint(
13415 &self,
13416 hint: InlayHint,
13417 buffer_handle: Model<Buffer>,
13418 server_id: LanguageServerId,
13419 cx: &mut AppContext,
13420 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13421 Some(self.update(cx, |project, cx| {
13422 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13423 }))
13424 }
13425
13426 fn range_for_rename(
13427 &self,
13428 buffer: &Model<Buffer>,
13429 position: text::Anchor,
13430 cx: &mut AppContext,
13431 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13432 Some(self.update(cx, |project, cx| {
13433 project.prepare_rename(buffer.clone(), position, cx)
13434 }))
13435 }
13436
13437 fn perform_rename(
13438 &self,
13439 buffer: &Model<Buffer>,
13440 position: text::Anchor,
13441 new_name: String,
13442 cx: &mut AppContext,
13443 ) -> Option<Task<Result<ProjectTransaction>>> {
13444 Some(self.update(cx, |project, cx| {
13445 project.perform_rename(buffer.clone(), position, new_name, cx)
13446 }))
13447 }
13448}
13449
13450fn inlay_hint_settings(
13451 location: Anchor,
13452 snapshot: &MultiBufferSnapshot,
13453 cx: &mut ViewContext<'_, Editor>,
13454) -> InlayHintSettings {
13455 let file = snapshot.file_at(location);
13456 let language = snapshot.language_at(location).map(|l| l.name());
13457 language_settings(language, file, cx).inlay_hints
13458}
13459
13460fn consume_contiguous_rows(
13461 contiguous_row_selections: &mut Vec<Selection<Point>>,
13462 selection: &Selection<Point>,
13463 display_map: &DisplaySnapshot,
13464 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13465) -> (MultiBufferRow, MultiBufferRow) {
13466 contiguous_row_selections.push(selection.clone());
13467 let start_row = MultiBufferRow(selection.start.row);
13468 let mut end_row = ending_row(selection, display_map);
13469
13470 while let Some(next_selection) = selections.peek() {
13471 if next_selection.start.row <= end_row.0 {
13472 end_row = ending_row(next_selection, display_map);
13473 contiguous_row_selections.push(selections.next().unwrap().clone());
13474 } else {
13475 break;
13476 }
13477 }
13478 (start_row, end_row)
13479}
13480
13481fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13482 if next_selection.end.column > 0 || next_selection.is_empty() {
13483 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13484 } else {
13485 MultiBufferRow(next_selection.end.row)
13486 }
13487}
13488
13489impl EditorSnapshot {
13490 pub fn remote_selections_in_range<'a>(
13491 &'a self,
13492 range: &'a Range<Anchor>,
13493 collaboration_hub: &dyn CollaborationHub,
13494 cx: &'a AppContext,
13495 ) -> impl 'a + Iterator<Item = RemoteSelection> {
13496 let participant_names = collaboration_hub.user_names(cx);
13497 let participant_indices = collaboration_hub.user_participant_indices(cx);
13498 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13499 let collaborators_by_replica_id = collaborators_by_peer_id
13500 .iter()
13501 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13502 .collect::<HashMap<_, _>>();
13503 self.buffer_snapshot
13504 .selections_in_range(range, false)
13505 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13506 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13507 let participant_index = participant_indices.get(&collaborator.user_id).copied();
13508 let user_name = participant_names.get(&collaborator.user_id).cloned();
13509 Some(RemoteSelection {
13510 replica_id,
13511 selection,
13512 cursor_shape,
13513 line_mode,
13514 participant_index,
13515 peer_id: collaborator.peer_id,
13516 user_name,
13517 })
13518 })
13519 }
13520
13521 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13522 self.display_snapshot.buffer_snapshot.language_at(position)
13523 }
13524
13525 pub fn is_focused(&self) -> bool {
13526 self.is_focused
13527 }
13528
13529 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13530 self.placeholder_text.as_ref()
13531 }
13532
13533 pub fn scroll_position(&self) -> gpui::Point<f32> {
13534 self.scroll_anchor.scroll_position(&self.display_snapshot)
13535 }
13536
13537 fn gutter_dimensions(
13538 &self,
13539 font_id: FontId,
13540 font_size: Pixels,
13541 em_width: Pixels,
13542 em_advance: Pixels,
13543 max_line_number_width: Pixels,
13544 cx: &AppContext,
13545 ) -> GutterDimensions {
13546 if !self.show_gutter {
13547 return GutterDimensions::default();
13548 }
13549 let descent = cx.text_system().descent(font_id, font_size);
13550
13551 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13552 matches!(
13553 ProjectSettings::get_global(cx).git.git_gutter,
13554 Some(GitGutterSetting::TrackedFiles)
13555 )
13556 });
13557 let gutter_settings = EditorSettings::get_global(cx).gutter;
13558 let show_line_numbers = self
13559 .show_line_numbers
13560 .unwrap_or(gutter_settings.line_numbers);
13561 let line_gutter_width = if show_line_numbers {
13562 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13563 let min_width_for_number_on_gutter = em_advance * 4.0;
13564 max_line_number_width.max(min_width_for_number_on_gutter)
13565 } else {
13566 0.0.into()
13567 };
13568
13569 let show_code_actions = self
13570 .show_code_actions
13571 .unwrap_or(gutter_settings.code_actions);
13572
13573 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13574
13575 let git_blame_entries_width =
13576 self.git_blame_gutter_max_author_length
13577 .map(|max_author_length| {
13578 // Length of the author name, but also space for the commit hash,
13579 // the spacing and the timestamp.
13580 let max_char_count = max_author_length
13581 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13582 + 7 // length of commit sha
13583 + 14 // length of max relative timestamp ("60 minutes ago")
13584 + 4; // gaps and margins
13585
13586 em_advance * max_char_count
13587 });
13588
13589 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13590 left_padding += if show_code_actions || show_runnables {
13591 em_width * 3.0
13592 } else if show_git_gutter && show_line_numbers {
13593 em_width * 2.0
13594 } else if show_git_gutter || show_line_numbers {
13595 em_width
13596 } else {
13597 px(0.)
13598 };
13599
13600 let right_padding = if gutter_settings.folds && show_line_numbers {
13601 em_width * 4.0
13602 } else if gutter_settings.folds {
13603 em_width * 3.0
13604 } else if show_line_numbers {
13605 em_width
13606 } else {
13607 px(0.)
13608 };
13609
13610 GutterDimensions {
13611 left_padding,
13612 right_padding,
13613 width: line_gutter_width + left_padding + right_padding,
13614 margin: -descent,
13615 git_blame_entries_width,
13616 }
13617 }
13618
13619 pub fn render_crease_toggle(
13620 &self,
13621 buffer_row: MultiBufferRow,
13622 row_contains_cursor: bool,
13623 editor: View<Editor>,
13624 cx: &mut WindowContext,
13625 ) -> Option<AnyElement> {
13626 let folded = self.is_line_folded(buffer_row);
13627 let mut is_foldable = false;
13628
13629 if let Some(crease) = self
13630 .crease_snapshot
13631 .query_row(buffer_row, &self.buffer_snapshot)
13632 {
13633 is_foldable = true;
13634 match crease {
13635 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
13636 if let Some(render_toggle) = render_toggle {
13637 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13638 if folded {
13639 editor.update(cx, |editor, cx| {
13640 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13641 });
13642 } else {
13643 editor.update(cx, |editor, cx| {
13644 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13645 });
13646 }
13647 });
13648 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
13649 }
13650 }
13651 }
13652 }
13653
13654 is_foldable |= self.starts_indent(buffer_row);
13655
13656 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
13657 Some(
13658 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
13659 .selected(folded)
13660 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13661 if folded {
13662 this.unfold_at(&UnfoldAt { buffer_row }, cx);
13663 } else {
13664 this.fold_at(&FoldAt { buffer_row }, cx);
13665 }
13666 }))
13667 .into_any_element(),
13668 )
13669 } else {
13670 None
13671 }
13672 }
13673
13674 pub fn render_crease_trailer(
13675 &self,
13676 buffer_row: MultiBufferRow,
13677 cx: &mut WindowContext,
13678 ) -> Option<AnyElement> {
13679 let folded = self.is_line_folded(buffer_row);
13680 if let Crease::Inline { render_trailer, .. } = self
13681 .crease_snapshot
13682 .query_row(buffer_row, &self.buffer_snapshot)?
13683 {
13684 let render_trailer = render_trailer.as_ref()?;
13685 Some(render_trailer(buffer_row, folded, cx))
13686 } else {
13687 None
13688 }
13689 }
13690}
13691
13692impl Deref for EditorSnapshot {
13693 type Target = DisplaySnapshot;
13694
13695 fn deref(&self) -> &Self::Target {
13696 &self.display_snapshot
13697 }
13698}
13699
13700#[derive(Clone, Debug, PartialEq, Eq)]
13701pub enum EditorEvent {
13702 InputIgnored {
13703 text: Arc<str>,
13704 },
13705 InputHandled {
13706 utf16_range_to_replace: Option<Range<isize>>,
13707 text: Arc<str>,
13708 },
13709 ExcerptsAdded {
13710 buffer: Model<Buffer>,
13711 predecessor: ExcerptId,
13712 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13713 },
13714 ExcerptsRemoved {
13715 ids: Vec<ExcerptId>,
13716 },
13717 ExcerptsEdited {
13718 ids: Vec<ExcerptId>,
13719 },
13720 ExcerptsExpanded {
13721 ids: Vec<ExcerptId>,
13722 },
13723 BufferEdited,
13724 Edited {
13725 transaction_id: clock::Lamport,
13726 },
13727 Reparsed(BufferId),
13728 Focused,
13729 FocusedIn,
13730 Blurred,
13731 DirtyChanged,
13732 Saved,
13733 TitleChanged,
13734 DiffBaseChanged,
13735 SelectionsChanged {
13736 local: bool,
13737 },
13738 ScrollPositionChanged {
13739 local: bool,
13740 autoscroll: bool,
13741 },
13742 Closed,
13743 TransactionUndone {
13744 transaction_id: clock::Lamport,
13745 },
13746 TransactionBegun {
13747 transaction_id: clock::Lamport,
13748 },
13749 Reloaded,
13750 CursorShapeChanged,
13751}
13752
13753impl EventEmitter<EditorEvent> for Editor {}
13754
13755impl FocusableView for Editor {
13756 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13757 self.focus_handle.clone()
13758 }
13759}
13760
13761impl Render for Editor {
13762 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13763 let settings = ThemeSettings::get_global(cx);
13764
13765 let mut text_style = match self.mode {
13766 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13767 color: cx.theme().colors().editor_foreground,
13768 font_family: settings.ui_font.family.clone(),
13769 font_features: settings.ui_font.features.clone(),
13770 font_fallbacks: settings.ui_font.fallbacks.clone(),
13771 font_size: rems(0.875).into(),
13772 font_weight: settings.ui_font.weight,
13773 line_height: relative(settings.buffer_line_height.value()),
13774 ..Default::default()
13775 },
13776 EditorMode::Full => TextStyle {
13777 color: cx.theme().colors().editor_foreground,
13778 font_family: settings.buffer_font.family.clone(),
13779 font_features: settings.buffer_font.features.clone(),
13780 font_fallbacks: settings.buffer_font.fallbacks.clone(),
13781 font_size: settings.buffer_font_size(cx).into(),
13782 font_weight: settings.buffer_font.weight,
13783 line_height: relative(settings.buffer_line_height.value()),
13784 ..Default::default()
13785 },
13786 };
13787 if let Some(text_style_refinement) = &self.text_style_refinement {
13788 text_style.refine(text_style_refinement)
13789 }
13790
13791 let background = match self.mode {
13792 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13793 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13794 EditorMode::Full => cx.theme().colors().editor_background,
13795 };
13796
13797 EditorElement::new(
13798 cx.view(),
13799 EditorStyle {
13800 background,
13801 local_player: cx.theme().players().local(),
13802 text: text_style,
13803 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13804 syntax: cx.theme().syntax().clone(),
13805 status: cx.theme().status().clone(),
13806 inlay_hints_style: make_inlay_hints_style(cx),
13807 suggestions_style: HighlightStyle {
13808 color: Some(cx.theme().status().predictive),
13809 ..HighlightStyle::default()
13810 },
13811 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13812 },
13813 )
13814 }
13815}
13816
13817impl ViewInputHandler for Editor {
13818 fn text_for_range(
13819 &mut self,
13820 range_utf16: Range<usize>,
13821 adjusted_range: &mut Option<Range<usize>>,
13822 cx: &mut ViewContext<Self>,
13823 ) -> Option<String> {
13824 let snapshot = self.buffer.read(cx).read(cx);
13825 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
13826 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
13827 if (start.0..end.0) != range_utf16 {
13828 adjusted_range.replace(start.0..end.0);
13829 }
13830 Some(snapshot.text_for_range(start..end).collect())
13831 }
13832
13833 fn selected_text_range(
13834 &mut self,
13835 ignore_disabled_input: bool,
13836 cx: &mut ViewContext<Self>,
13837 ) -> Option<UTF16Selection> {
13838 // Prevent the IME menu from appearing when holding down an alphabetic key
13839 // while input is disabled.
13840 if !ignore_disabled_input && !self.input_enabled {
13841 return None;
13842 }
13843
13844 let selection = self.selections.newest::<OffsetUtf16>(cx);
13845 let range = selection.range();
13846
13847 Some(UTF16Selection {
13848 range: range.start.0..range.end.0,
13849 reversed: selection.reversed,
13850 })
13851 }
13852
13853 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13854 let snapshot = self.buffer.read(cx).read(cx);
13855 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13856 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13857 }
13858
13859 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13860 self.clear_highlights::<InputComposition>(cx);
13861 self.ime_transaction.take();
13862 }
13863
13864 fn replace_text_in_range(
13865 &mut self,
13866 range_utf16: Option<Range<usize>>,
13867 text: &str,
13868 cx: &mut ViewContext<Self>,
13869 ) {
13870 if !self.input_enabled {
13871 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13872 return;
13873 }
13874
13875 self.transact(cx, |this, cx| {
13876 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13877 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13878 Some(this.selection_replacement_ranges(range_utf16, cx))
13879 } else {
13880 this.marked_text_ranges(cx)
13881 };
13882
13883 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13884 let newest_selection_id = this.selections.newest_anchor().id;
13885 this.selections
13886 .all::<OffsetUtf16>(cx)
13887 .iter()
13888 .zip(ranges_to_replace.iter())
13889 .find_map(|(selection, range)| {
13890 if selection.id == newest_selection_id {
13891 Some(
13892 (range.start.0 as isize - selection.head().0 as isize)
13893 ..(range.end.0 as isize - selection.head().0 as isize),
13894 )
13895 } else {
13896 None
13897 }
13898 })
13899 });
13900
13901 cx.emit(EditorEvent::InputHandled {
13902 utf16_range_to_replace: range_to_replace,
13903 text: text.into(),
13904 });
13905
13906 if let Some(new_selected_ranges) = new_selected_ranges {
13907 this.change_selections(None, cx, |selections| {
13908 selections.select_ranges(new_selected_ranges)
13909 });
13910 this.backspace(&Default::default(), cx);
13911 }
13912
13913 this.handle_input(text, cx);
13914 });
13915
13916 if let Some(transaction) = self.ime_transaction {
13917 self.buffer.update(cx, |buffer, cx| {
13918 buffer.group_until_transaction(transaction, cx);
13919 });
13920 }
13921
13922 self.unmark_text(cx);
13923 }
13924
13925 fn replace_and_mark_text_in_range(
13926 &mut self,
13927 range_utf16: Option<Range<usize>>,
13928 text: &str,
13929 new_selected_range_utf16: Option<Range<usize>>,
13930 cx: &mut ViewContext<Self>,
13931 ) {
13932 if !self.input_enabled {
13933 return;
13934 }
13935
13936 let transaction = self.transact(cx, |this, cx| {
13937 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13938 let snapshot = this.buffer.read(cx).read(cx);
13939 if let Some(relative_range_utf16) = range_utf16.as_ref() {
13940 for marked_range in &mut marked_ranges {
13941 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13942 marked_range.start.0 += relative_range_utf16.start;
13943 marked_range.start =
13944 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13945 marked_range.end =
13946 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13947 }
13948 }
13949 Some(marked_ranges)
13950 } else if let Some(range_utf16) = range_utf16 {
13951 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13952 Some(this.selection_replacement_ranges(range_utf16, cx))
13953 } else {
13954 None
13955 };
13956
13957 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13958 let newest_selection_id = this.selections.newest_anchor().id;
13959 this.selections
13960 .all::<OffsetUtf16>(cx)
13961 .iter()
13962 .zip(ranges_to_replace.iter())
13963 .find_map(|(selection, range)| {
13964 if selection.id == newest_selection_id {
13965 Some(
13966 (range.start.0 as isize - selection.head().0 as isize)
13967 ..(range.end.0 as isize - selection.head().0 as isize),
13968 )
13969 } else {
13970 None
13971 }
13972 })
13973 });
13974
13975 cx.emit(EditorEvent::InputHandled {
13976 utf16_range_to_replace: range_to_replace,
13977 text: text.into(),
13978 });
13979
13980 if let Some(ranges) = ranges_to_replace {
13981 this.change_selections(None, cx, |s| s.select_ranges(ranges));
13982 }
13983
13984 let marked_ranges = {
13985 let snapshot = this.buffer.read(cx).read(cx);
13986 this.selections
13987 .disjoint_anchors()
13988 .iter()
13989 .map(|selection| {
13990 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13991 })
13992 .collect::<Vec<_>>()
13993 };
13994
13995 if text.is_empty() {
13996 this.unmark_text(cx);
13997 } else {
13998 this.highlight_text::<InputComposition>(
13999 marked_ranges.clone(),
14000 HighlightStyle {
14001 underline: Some(UnderlineStyle {
14002 thickness: px(1.),
14003 color: None,
14004 wavy: false,
14005 }),
14006 ..Default::default()
14007 },
14008 cx,
14009 );
14010 }
14011
14012 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14013 let use_autoclose = this.use_autoclose;
14014 let use_auto_surround = this.use_auto_surround;
14015 this.set_use_autoclose(false);
14016 this.set_use_auto_surround(false);
14017 this.handle_input(text, cx);
14018 this.set_use_autoclose(use_autoclose);
14019 this.set_use_auto_surround(use_auto_surround);
14020
14021 if let Some(new_selected_range) = new_selected_range_utf16 {
14022 let snapshot = this.buffer.read(cx).read(cx);
14023 let new_selected_ranges = marked_ranges
14024 .into_iter()
14025 .map(|marked_range| {
14026 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14027 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14028 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14029 snapshot.clip_offset_utf16(new_start, Bias::Left)
14030 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14031 })
14032 .collect::<Vec<_>>();
14033
14034 drop(snapshot);
14035 this.change_selections(None, cx, |selections| {
14036 selections.select_ranges(new_selected_ranges)
14037 });
14038 }
14039 });
14040
14041 self.ime_transaction = self.ime_transaction.or(transaction);
14042 if let Some(transaction) = self.ime_transaction {
14043 self.buffer.update(cx, |buffer, cx| {
14044 buffer.group_until_transaction(transaction, cx);
14045 });
14046 }
14047
14048 if self.text_highlights::<InputComposition>(cx).is_none() {
14049 self.ime_transaction.take();
14050 }
14051 }
14052
14053 fn bounds_for_range(
14054 &mut self,
14055 range_utf16: Range<usize>,
14056 element_bounds: gpui::Bounds<Pixels>,
14057 cx: &mut ViewContext<Self>,
14058 ) -> Option<gpui::Bounds<Pixels>> {
14059 let text_layout_details = self.text_layout_details(cx);
14060 let gpui::Point {
14061 x: em_width,
14062 y: line_height,
14063 } = self.character_size(cx);
14064
14065 let snapshot = self.snapshot(cx);
14066 let scroll_position = snapshot.scroll_position();
14067 let scroll_left = scroll_position.x * em_width;
14068
14069 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14070 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14071 + self.gutter_dimensions.width
14072 + self.gutter_dimensions.margin;
14073 let y = line_height * (start.row().as_f32() - scroll_position.y);
14074
14075 Some(Bounds {
14076 origin: element_bounds.origin + point(x, y),
14077 size: size(em_width, line_height),
14078 })
14079 }
14080}
14081
14082trait SelectionExt {
14083 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14084 fn spanned_rows(
14085 &self,
14086 include_end_if_at_line_start: bool,
14087 map: &DisplaySnapshot,
14088 ) -> Range<MultiBufferRow>;
14089}
14090
14091impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14092 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14093 let start = self
14094 .start
14095 .to_point(&map.buffer_snapshot)
14096 .to_display_point(map);
14097 let end = self
14098 .end
14099 .to_point(&map.buffer_snapshot)
14100 .to_display_point(map);
14101 if self.reversed {
14102 end..start
14103 } else {
14104 start..end
14105 }
14106 }
14107
14108 fn spanned_rows(
14109 &self,
14110 include_end_if_at_line_start: bool,
14111 map: &DisplaySnapshot,
14112 ) -> Range<MultiBufferRow> {
14113 let start = self.start.to_point(&map.buffer_snapshot);
14114 let mut end = self.end.to_point(&map.buffer_snapshot);
14115 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14116 end.row -= 1;
14117 }
14118
14119 let buffer_start = map.prev_line_boundary(start).0;
14120 let buffer_end = map.next_line_boundary(end).0;
14121 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14122 }
14123}
14124
14125impl<T: InvalidationRegion> InvalidationStack<T> {
14126 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14127 where
14128 S: Clone + ToOffset,
14129 {
14130 while let Some(region) = self.last() {
14131 let all_selections_inside_invalidation_ranges =
14132 if selections.len() == region.ranges().len() {
14133 selections
14134 .iter()
14135 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14136 .all(|(selection, invalidation_range)| {
14137 let head = selection.head().to_offset(buffer);
14138 invalidation_range.start <= head && invalidation_range.end >= head
14139 })
14140 } else {
14141 false
14142 };
14143
14144 if all_selections_inside_invalidation_ranges {
14145 break;
14146 } else {
14147 self.pop();
14148 }
14149 }
14150 }
14151}
14152
14153impl<T> Default for InvalidationStack<T> {
14154 fn default() -> Self {
14155 Self(Default::default())
14156 }
14157}
14158
14159impl<T> Deref for InvalidationStack<T> {
14160 type Target = Vec<T>;
14161
14162 fn deref(&self) -> &Self::Target {
14163 &self.0
14164 }
14165}
14166
14167impl<T> DerefMut for InvalidationStack<T> {
14168 fn deref_mut(&mut self) -> &mut Self::Target {
14169 &mut self.0
14170 }
14171}
14172
14173impl InvalidationRegion for SnippetState {
14174 fn ranges(&self) -> &[Range<Anchor>] {
14175 &self.ranges[self.active_index]
14176 }
14177}
14178
14179pub fn diagnostic_block_renderer(
14180 diagnostic: Diagnostic,
14181 max_message_rows: Option<u8>,
14182 allow_closing: bool,
14183 _is_valid: bool,
14184) -> RenderBlock {
14185 let (text_without_backticks, code_ranges) =
14186 highlight_diagnostic_message(&diagnostic, max_message_rows);
14187
14188 Arc::new(move |cx: &mut BlockContext| {
14189 let group_id: SharedString = cx.block_id.to_string().into();
14190
14191 let mut text_style = cx.text_style().clone();
14192 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14193 let theme_settings = ThemeSettings::get_global(cx);
14194 text_style.font_family = theme_settings.buffer_font.family.clone();
14195 text_style.font_style = theme_settings.buffer_font.style;
14196 text_style.font_features = theme_settings.buffer_font.features.clone();
14197 text_style.font_weight = theme_settings.buffer_font.weight;
14198
14199 let multi_line_diagnostic = diagnostic.message.contains('\n');
14200
14201 let buttons = |diagnostic: &Diagnostic| {
14202 if multi_line_diagnostic {
14203 v_flex()
14204 } else {
14205 h_flex()
14206 }
14207 .when(allow_closing, |div| {
14208 div.children(diagnostic.is_primary.then(|| {
14209 IconButton::new("close-block", IconName::XCircle)
14210 .icon_color(Color::Muted)
14211 .size(ButtonSize::Compact)
14212 .style(ButtonStyle::Transparent)
14213 .visible_on_hover(group_id.clone())
14214 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14215 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14216 }))
14217 })
14218 .child(
14219 IconButton::new("copy-block", IconName::Copy)
14220 .icon_color(Color::Muted)
14221 .size(ButtonSize::Compact)
14222 .style(ButtonStyle::Transparent)
14223 .visible_on_hover(group_id.clone())
14224 .on_click({
14225 let message = diagnostic.message.clone();
14226 move |_click, cx| {
14227 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14228 }
14229 })
14230 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14231 )
14232 };
14233
14234 let icon_size = buttons(&diagnostic)
14235 .into_any_element()
14236 .layout_as_root(AvailableSpace::min_size(), cx);
14237
14238 h_flex()
14239 .id(cx.block_id)
14240 .group(group_id.clone())
14241 .relative()
14242 .size_full()
14243 .block_mouse_down()
14244 .pl(cx.gutter_dimensions.width)
14245 .w(cx.max_width - cx.gutter_dimensions.full_width())
14246 .child(
14247 div()
14248 .flex()
14249 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14250 .flex_shrink(),
14251 )
14252 .child(buttons(&diagnostic))
14253 .child(div().flex().flex_shrink_0().child(
14254 StyledText::new(text_without_backticks.clone()).with_highlights(
14255 &text_style,
14256 code_ranges.iter().map(|range| {
14257 (
14258 range.clone(),
14259 HighlightStyle {
14260 font_weight: Some(FontWeight::BOLD),
14261 ..Default::default()
14262 },
14263 )
14264 }),
14265 ),
14266 ))
14267 .into_any_element()
14268 })
14269}
14270
14271pub fn highlight_diagnostic_message(
14272 diagnostic: &Diagnostic,
14273 mut max_message_rows: Option<u8>,
14274) -> (SharedString, Vec<Range<usize>>) {
14275 let mut text_without_backticks = String::new();
14276 let mut code_ranges = Vec::new();
14277
14278 if let Some(source) = &diagnostic.source {
14279 text_without_backticks.push_str(source);
14280 code_ranges.push(0..source.len());
14281 text_without_backticks.push_str(": ");
14282 }
14283
14284 let mut prev_offset = 0;
14285 let mut in_code_block = false;
14286 let has_row_limit = max_message_rows.is_some();
14287 let mut newline_indices = diagnostic
14288 .message
14289 .match_indices('\n')
14290 .filter(|_| has_row_limit)
14291 .map(|(ix, _)| ix)
14292 .fuse()
14293 .peekable();
14294
14295 for (quote_ix, _) in diagnostic
14296 .message
14297 .match_indices('`')
14298 .chain([(diagnostic.message.len(), "")])
14299 {
14300 let mut first_newline_ix = None;
14301 let mut last_newline_ix = None;
14302 while let Some(newline_ix) = newline_indices.peek() {
14303 if *newline_ix < quote_ix {
14304 if first_newline_ix.is_none() {
14305 first_newline_ix = Some(*newline_ix);
14306 }
14307 last_newline_ix = Some(*newline_ix);
14308
14309 if let Some(rows_left) = &mut max_message_rows {
14310 if *rows_left == 0 {
14311 break;
14312 } else {
14313 *rows_left -= 1;
14314 }
14315 }
14316 let _ = newline_indices.next();
14317 } else {
14318 break;
14319 }
14320 }
14321 let prev_len = text_without_backticks.len();
14322 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14323 text_without_backticks.push_str(new_text);
14324 if in_code_block {
14325 code_ranges.push(prev_len..text_without_backticks.len());
14326 }
14327 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14328 in_code_block = !in_code_block;
14329 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14330 text_without_backticks.push_str("...");
14331 break;
14332 }
14333 }
14334
14335 (text_without_backticks.into(), code_ranges)
14336}
14337
14338fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14339 match severity {
14340 DiagnosticSeverity::ERROR => colors.error,
14341 DiagnosticSeverity::WARNING => colors.warning,
14342 DiagnosticSeverity::INFORMATION => colors.info,
14343 DiagnosticSeverity::HINT => colors.info,
14344 _ => colors.ignored,
14345 }
14346}
14347
14348pub fn styled_runs_for_code_label<'a>(
14349 label: &'a CodeLabel,
14350 syntax_theme: &'a theme::SyntaxTheme,
14351) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14352 let fade_out = HighlightStyle {
14353 fade_out: Some(0.35),
14354 ..Default::default()
14355 };
14356
14357 let mut prev_end = label.filter_range.end;
14358 label
14359 .runs
14360 .iter()
14361 .enumerate()
14362 .flat_map(move |(ix, (range, highlight_id))| {
14363 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14364 style
14365 } else {
14366 return Default::default();
14367 };
14368 let mut muted_style = style;
14369 muted_style.highlight(fade_out);
14370
14371 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14372 if range.start >= label.filter_range.end {
14373 if range.start > prev_end {
14374 runs.push((prev_end..range.start, fade_out));
14375 }
14376 runs.push((range.clone(), muted_style));
14377 } else if range.end <= label.filter_range.end {
14378 runs.push((range.clone(), style));
14379 } else {
14380 runs.push((range.start..label.filter_range.end, style));
14381 runs.push((label.filter_range.end..range.end, muted_style));
14382 }
14383 prev_end = cmp::max(prev_end, range.end);
14384
14385 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14386 runs.push((prev_end..label.text.len(), fade_out));
14387 }
14388
14389 runs
14390 })
14391}
14392
14393pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14394 let mut prev_index = 0;
14395 let mut prev_codepoint: Option<char> = None;
14396 text.char_indices()
14397 .chain([(text.len(), '\0')])
14398 .filter_map(move |(index, codepoint)| {
14399 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14400 let is_boundary = index == text.len()
14401 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14402 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14403 if is_boundary {
14404 let chunk = &text[prev_index..index];
14405 prev_index = index;
14406 Some(chunk)
14407 } else {
14408 None
14409 }
14410 })
14411}
14412
14413pub trait RangeToAnchorExt: Sized {
14414 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14415
14416 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14417 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14418 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14419 }
14420}
14421
14422impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14423 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14424 let start_offset = self.start.to_offset(snapshot);
14425 let end_offset = self.end.to_offset(snapshot);
14426 if start_offset == end_offset {
14427 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14428 } else {
14429 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14430 }
14431 }
14432}
14433
14434pub trait RowExt {
14435 fn as_f32(&self) -> f32;
14436
14437 fn next_row(&self) -> Self;
14438
14439 fn previous_row(&self) -> Self;
14440
14441 fn minus(&self, other: Self) -> u32;
14442}
14443
14444impl RowExt for DisplayRow {
14445 fn as_f32(&self) -> f32 {
14446 self.0 as f32
14447 }
14448
14449 fn next_row(&self) -> Self {
14450 Self(self.0 + 1)
14451 }
14452
14453 fn previous_row(&self) -> Self {
14454 Self(self.0.saturating_sub(1))
14455 }
14456
14457 fn minus(&self, other: Self) -> u32 {
14458 self.0 - other.0
14459 }
14460}
14461
14462impl RowExt for MultiBufferRow {
14463 fn as_f32(&self) -> f32 {
14464 self.0 as f32
14465 }
14466
14467 fn next_row(&self) -> Self {
14468 Self(self.0 + 1)
14469 }
14470
14471 fn previous_row(&self) -> Self {
14472 Self(self.0.saturating_sub(1))
14473 }
14474
14475 fn minus(&self, other: Self) -> u32 {
14476 self.0 - other.0
14477 }
14478}
14479
14480trait RowRangeExt {
14481 type Row;
14482
14483 fn len(&self) -> usize;
14484
14485 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14486}
14487
14488impl RowRangeExt for Range<MultiBufferRow> {
14489 type Row = MultiBufferRow;
14490
14491 fn len(&self) -> usize {
14492 (self.end.0 - self.start.0) as usize
14493 }
14494
14495 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14496 (self.start.0..self.end.0).map(MultiBufferRow)
14497 }
14498}
14499
14500impl RowRangeExt for Range<DisplayRow> {
14501 type Row = DisplayRow;
14502
14503 fn len(&self) -> usize {
14504 (self.end.0 - self.start.0) as usize
14505 }
14506
14507 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14508 (self.start.0..self.end.0).map(DisplayRow)
14509 }
14510}
14511
14512fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14513 if hunk.diff_base_byte_range.is_empty() {
14514 DiffHunkStatus::Added
14515 } else if hunk.row_range.is_empty() {
14516 DiffHunkStatus::Removed
14517 } else {
14518 DiffHunkStatus::Modified
14519 }
14520}
14521
14522/// If select range has more than one line, we
14523/// just point the cursor to range.start.
14524fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14525 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14526 range
14527 } else {
14528 range.start..range.start
14529 }
14530}
14531
14532pub struct KillRing(ClipboardItem);
14533impl Global for KillRing {}
14534
14535const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);