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, OpenLspBufferHandle},
133 project_settings::{GitGutterSetting, ProjectSettings},
134 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
135 LspStore, 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
194pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
195pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
196
197pub fn render_parsed_markdown(
198 element_id: impl Into<ElementId>,
199 parsed: &language::ParsedMarkdown,
200 editor_style: &EditorStyle,
201 workspace: Option<WeakView<Workspace>>,
202 cx: &mut WindowContext,
203) -> InteractiveText {
204 let code_span_background_color = cx
205 .theme()
206 .colors()
207 .editor_document_highlight_read_background;
208
209 let highlights = gpui::combine_highlights(
210 parsed.highlights.iter().filter_map(|(range, highlight)| {
211 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
212 Some((range.clone(), highlight))
213 }),
214 parsed
215 .regions
216 .iter()
217 .zip(&parsed.region_ranges)
218 .filter_map(|(region, range)| {
219 if region.code {
220 Some((
221 range.clone(),
222 HighlightStyle {
223 background_color: Some(code_span_background_color),
224 ..Default::default()
225 },
226 ))
227 } else {
228 None
229 }
230 }),
231 );
232
233 let mut links = Vec::new();
234 let mut link_ranges = Vec::new();
235 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
236 if let Some(link) = region.link.clone() {
237 links.push(link);
238 link_ranges.push(range.clone());
239 }
240 }
241
242 InteractiveText::new(
243 element_id,
244 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
245 )
246 .on_click(link_ranges, move |clicked_range_ix, cx| {
247 match &links[clicked_range_ix] {
248 markdown::Link::Web { url } => cx.open_url(url),
249 markdown::Link::Path { path } => {
250 if let Some(workspace) = &workspace {
251 _ = workspace.update(cx, |workspace, cx| {
252 workspace.open_abs_path(path.clone(), false, cx).detach();
253 });
254 }
255 }
256 }
257 })
258}
259
260#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
261pub(crate) enum InlayId {
262 Suggestion(usize),
263 Hint(usize),
264}
265
266impl InlayId {
267 fn id(&self) -> usize {
268 match self {
269 Self::Suggestion(id) => *id,
270 Self::Hint(id) => *id,
271 }
272 }
273}
274
275enum DiffRowHighlight {}
276enum DocumentHighlightRead {}
277enum DocumentHighlightWrite {}
278enum InputComposition {}
279
280#[derive(Debug, Copy, Clone, PartialEq, Eq)]
281pub enum Navigated {
282 Yes,
283 No,
284}
285
286impl Navigated {
287 pub fn from_bool(yes: bool) -> Navigated {
288 if yes {
289 Navigated::Yes
290 } else {
291 Navigated::No
292 }
293 }
294}
295
296pub fn init_settings(cx: &mut AppContext) {
297 EditorSettings::register(cx);
298}
299
300pub fn init(cx: &mut AppContext) {
301 init_settings(cx);
302
303 workspace::register_project_item::<Editor>(cx);
304 workspace::FollowableViewRegistry::register::<Editor>(cx);
305 workspace::register_serializable_item::<Editor>(cx);
306
307 cx.observe_new_views(
308 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
309 workspace.register_action(Editor::new_file);
310 workspace.register_action(Editor::new_file_vertical);
311 workspace.register_action(Editor::new_file_horizontal);
312 },
313 )
314 .detach();
315
316 cx.on_action(move |_: &workspace::NewFile, cx| {
317 let app_state = workspace::AppState::global(cx);
318 if let Some(app_state) = app_state.upgrade() {
319 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
320 Editor::new_file(workspace, &Default::default(), cx)
321 })
322 .detach();
323 }
324 });
325 cx.on_action(move |_: &workspace::NewWindow, cx| {
326 let app_state = workspace::AppState::global(cx);
327 if let Some(app_state) = app_state.upgrade() {
328 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
329 Editor::new_file(workspace, &Default::default(), cx)
330 })
331 .detach();
332 }
333 });
334 git::project_diff::init(cx);
335}
336
337pub struct SearchWithinRange;
338
339trait InvalidationRegion {
340 fn ranges(&self) -> &[Range<Anchor>];
341}
342
343#[derive(Clone, Debug, PartialEq)]
344pub enum SelectPhase {
345 Begin {
346 position: DisplayPoint,
347 add: bool,
348 click_count: usize,
349 },
350 BeginColumnar {
351 position: DisplayPoint,
352 reset: bool,
353 goal_column: u32,
354 },
355 Extend {
356 position: DisplayPoint,
357 click_count: usize,
358 },
359 Update {
360 position: DisplayPoint,
361 goal_column: u32,
362 scroll_delta: gpui::Point<f32>,
363 },
364 End,
365}
366
367#[derive(Clone, Debug)]
368pub enum SelectMode {
369 Character,
370 Word(Range<Anchor>),
371 Line(Range<Anchor>),
372 All,
373}
374
375#[derive(Copy, Clone, PartialEq, Eq, Debug)]
376pub enum EditorMode {
377 SingleLine { auto_width: bool },
378 AutoHeight { max_lines: usize },
379 Full,
380}
381
382#[derive(Copy, Clone, Debug)]
383pub enum SoftWrap {
384 /// Prefer not to wrap at all.
385 ///
386 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
387 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
388 GitDiff,
389 /// Prefer a single line generally, unless an overly long line is encountered.
390 None,
391 /// Soft wrap lines that exceed the editor width.
392 EditorWidth,
393 /// Soft wrap lines at the preferred line length.
394 Column(u32),
395 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
396 Bounded(u32),
397}
398
399#[derive(Clone)]
400pub struct EditorStyle {
401 pub background: Hsla,
402 pub local_player: PlayerColor,
403 pub text: TextStyle,
404 pub scrollbar_width: Pixels,
405 pub syntax: Arc<SyntaxTheme>,
406 pub status: StatusColors,
407 pub inlay_hints_style: HighlightStyle,
408 pub suggestions_style: HighlightStyle,
409 pub unnecessary_code_fade: f32,
410}
411
412impl Default for EditorStyle {
413 fn default() -> Self {
414 Self {
415 background: Hsla::default(),
416 local_player: PlayerColor::default(),
417 text: TextStyle::default(),
418 scrollbar_width: Pixels::default(),
419 syntax: Default::default(),
420 // HACK: Status colors don't have a real default.
421 // We should look into removing the status colors from the editor
422 // style and retrieve them directly from the theme.
423 status: StatusColors::dark(),
424 inlay_hints_style: HighlightStyle::default(),
425 suggestions_style: HighlightStyle::default(),
426 unnecessary_code_fade: Default::default(),
427 }
428 }
429}
430
431pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
432 let show_background = language_settings::language_settings(None, None, cx)
433 .inlay_hints
434 .show_background;
435
436 HighlightStyle {
437 color: Some(cx.theme().status().hint),
438 background_color: show_background.then(|| cx.theme().status().hint_background),
439 ..HighlightStyle::default()
440 }
441}
442
443type CompletionId = usize;
444
445enum InlineCompletion {
446 Edit(Vec<(Range<Anchor>, String)>),
447 Move(Anchor),
448}
449
450struct InlineCompletionState {
451 inlay_ids: Vec<InlayId>,
452 completion: InlineCompletion,
453 invalidation_range: Range<Anchor>,
454}
455
456enum InlineCompletionHighlight {}
457
458#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
459struct EditorActionId(usize);
460
461impl EditorActionId {
462 pub fn post_inc(&mut self) -> Self {
463 let answer = self.0;
464
465 *self = Self(answer + 1);
466
467 Self(answer)
468 }
469}
470
471// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
472// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
473
474type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
475type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
476
477#[derive(Default)]
478struct ScrollbarMarkerState {
479 scrollbar_size: Size<Pixels>,
480 dirty: bool,
481 markers: Arc<[PaintQuad]>,
482 pending_refresh: Option<Task<Result<()>>>,
483}
484
485impl ScrollbarMarkerState {
486 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
487 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
488 }
489}
490
491#[derive(Clone, Debug)]
492struct RunnableTasks {
493 templates: Vec<(TaskSourceKind, TaskTemplate)>,
494 offset: MultiBufferOffset,
495 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
496 column: u32,
497 // Values of all named captures, including those starting with '_'
498 extra_variables: HashMap<String, String>,
499 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
500 context_range: Range<BufferOffset>,
501}
502
503impl RunnableTasks {
504 fn resolve<'a>(
505 &'a self,
506 cx: &'a task::TaskContext,
507 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
508 self.templates.iter().filter_map(|(kind, template)| {
509 template
510 .resolve_task(&kind.to_id_base(), cx)
511 .map(|task| (kind.clone(), task))
512 })
513 }
514}
515
516#[derive(Clone)]
517struct ResolvedTasks {
518 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
519 position: Anchor,
520}
521#[derive(Copy, Clone, Debug)]
522struct MultiBufferOffset(usize);
523#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
524struct BufferOffset(usize);
525
526// Addons allow storing per-editor state in other crates (e.g. Vim)
527pub trait Addon: 'static {
528 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
529
530 fn to_any(&self) -> &dyn std::any::Any;
531}
532
533#[derive(Debug, Copy, Clone, PartialEq, Eq)]
534pub enum IsVimMode {
535 Yes,
536 No,
537}
538
539/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
540///
541/// See the [module level documentation](self) for more information.
542pub struct Editor {
543 focus_handle: FocusHandle,
544 last_focused_descendant: Option<WeakFocusHandle>,
545 /// The text buffer being edited
546 buffer: Model<MultiBuffer>,
547 /// Map of how text in the buffer should be displayed.
548 /// Handles soft wraps, folds, fake inlay text insertions, etc.
549 pub display_map: Model<DisplayMap>,
550 pub selections: SelectionsCollection,
551 pub scroll_manager: ScrollManager,
552 /// When inline assist editors are linked, they all render cursors because
553 /// typing enters text into each of them, even the ones that aren't focused.
554 pub(crate) show_cursor_when_unfocused: bool,
555 columnar_selection_tail: Option<Anchor>,
556 add_selections_state: Option<AddSelectionsState>,
557 select_next_state: Option<SelectNextState>,
558 select_prev_state: Option<SelectNextState>,
559 selection_history: SelectionHistory,
560 autoclose_regions: Vec<AutocloseRegion>,
561 snippet_stack: InvalidationStack<SnippetState>,
562 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
563 ime_transaction: Option<TransactionId>,
564 active_diagnostics: Option<ActiveDiagnosticGroup>,
565 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
566
567 project: Option<Model<Project>>,
568 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
569 completion_provider: Option<Box<dyn CompletionProvider>>,
570 collaboration_hub: Option<Box<dyn CollaborationHub>>,
571 blink_manager: Model<BlinkManager>,
572 show_cursor_names: bool,
573 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
574 pub show_local_selections: bool,
575 mode: EditorMode,
576 show_breadcrumbs: bool,
577 show_gutter: bool,
578 show_line_numbers: Option<bool>,
579 use_relative_line_numbers: Option<bool>,
580 show_git_diff_gutter: Option<bool>,
581 show_code_actions: Option<bool>,
582 show_runnables: Option<bool>,
583 show_wrap_guides: Option<bool>,
584 show_indent_guides: Option<bool>,
585 placeholder_text: Option<Arc<str>>,
586 highlight_order: usize,
587 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
588 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
589 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
590 scrollbar_marker_state: ScrollbarMarkerState,
591 active_indent_guides_state: ActiveIndentGuidesState,
592 nav_history: Option<ItemNavHistory>,
593 context_menu: RwLock<Option<CodeContextMenu>>,
594 mouse_context_menu: Option<MouseContextMenu>,
595 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
596 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
597 signature_help_state: SignatureHelpState,
598 auto_signature_help: Option<bool>,
599 find_all_references_task_sources: Vec<Anchor>,
600 next_completion_id: CompletionId,
601 available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
602 code_actions_task: Option<Task<Result<()>>>,
603 document_highlights_task: Option<Task<()>>,
604 linked_editing_range_task: Option<Task<Option<()>>>,
605 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
606 pending_rename: Option<RenameState>,
607 searchable: bool,
608 cursor_shape: CursorShape,
609 current_line_highlight: Option<CurrentLineHighlight>,
610 collapse_matches: bool,
611 autoindent_mode: Option<AutoindentMode>,
612 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
613 input_enabled: bool,
614 use_modal_editing: bool,
615 read_only: bool,
616 leader_peer_id: Option<PeerId>,
617 remote_id: Option<ViewId>,
618 hover_state: HoverState,
619 gutter_hovered: bool,
620 hovered_link_state: Option<HoveredLinkState>,
621 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
622 code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
623 active_inline_completion: Option<InlineCompletionState>,
624 // enable_inline_completions is a switch that Vim can use to disable
625 // inline completions based on its mode.
626 enable_inline_completions: bool,
627 show_inline_completions_override: Option<bool>,
628 inlay_hint_cache: InlayHintCache,
629 diff_map: DiffMap,
630 next_inlay_id: usize,
631 _subscriptions: Vec<Subscription>,
632 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
633 gutter_dimensions: GutterDimensions,
634 style: Option<EditorStyle>,
635 text_style_refinement: Option<TextStyleRefinement>,
636 next_editor_action_id: EditorActionId,
637 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
638 use_autoclose: bool,
639 use_auto_surround: bool,
640 auto_replace_emoji_shortcode: bool,
641 show_git_blame_gutter: bool,
642 show_git_blame_inline: bool,
643 show_git_blame_inline_delay_task: Option<Task<()>>,
644 git_blame_inline_enabled: bool,
645 serialize_dirty_buffers: bool,
646 show_selection_menu: Option<bool>,
647 blame: Option<Model<GitBlame>>,
648 blame_subscription: Option<Subscription>,
649 custom_context_menu: Option<
650 Box<
651 dyn 'static
652 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
653 >,
654 >,
655 last_bounds: Option<Bounds<Pixels>>,
656 expect_bounds_change: Option<Bounds<Pixels>>,
657 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
658 tasks_update_task: Option<Task<()>>,
659 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
660 breadcrumb_header: Option<String>,
661 focused_block: Option<FocusedBlock>,
662 next_scroll_position: NextScrollCursorCenterTopBottom,
663 addons: HashMap<TypeId, Box<dyn Addon>>,
664 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
665 _scroll_cursor_center_top_bottom_task: Task<()>,
666}
667
668#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
669enum NextScrollCursorCenterTopBottom {
670 #[default]
671 Center,
672 Top,
673 Bottom,
674}
675
676impl NextScrollCursorCenterTopBottom {
677 fn next(&self) -> Self {
678 match self {
679 Self::Center => Self::Top,
680 Self::Top => Self::Bottom,
681 Self::Bottom => Self::Center,
682 }
683 }
684}
685
686#[derive(Clone)]
687pub struct EditorSnapshot {
688 pub mode: EditorMode,
689 show_gutter: bool,
690 show_line_numbers: Option<bool>,
691 show_git_diff_gutter: Option<bool>,
692 show_code_actions: Option<bool>,
693 show_runnables: Option<bool>,
694 git_blame_gutter_max_author_length: Option<usize>,
695 pub display_snapshot: DisplaySnapshot,
696 pub placeholder_text: Option<Arc<str>>,
697 diff_map: DiffMapSnapshot,
698 is_focused: bool,
699 scroll_anchor: ScrollAnchor,
700 ongoing_scroll: OngoingScroll,
701 current_line_highlight: CurrentLineHighlight,
702 gutter_hovered: bool,
703}
704
705const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
706
707#[derive(Default, Debug, Clone, Copy)]
708pub struct GutterDimensions {
709 pub left_padding: Pixels,
710 pub right_padding: Pixels,
711 pub width: Pixels,
712 pub margin: Pixels,
713 pub git_blame_entries_width: Option<Pixels>,
714}
715
716impl GutterDimensions {
717 /// The full width of the space taken up by the gutter.
718 pub fn full_width(&self) -> Pixels {
719 self.margin + self.width
720 }
721
722 /// The width of the space reserved for the fold indicators,
723 /// use alongside 'justify_end' and `gutter_width` to
724 /// right align content with the line numbers
725 pub fn fold_area_width(&self) -> Pixels {
726 self.margin + self.right_padding
727 }
728}
729
730#[derive(Debug)]
731pub struct RemoteSelection {
732 pub replica_id: ReplicaId,
733 pub selection: Selection<Anchor>,
734 pub cursor_shape: CursorShape,
735 pub peer_id: PeerId,
736 pub line_mode: bool,
737 pub participant_index: Option<ParticipantIndex>,
738 pub user_name: Option<SharedString>,
739}
740
741#[derive(Clone, Debug)]
742struct SelectionHistoryEntry {
743 selections: Arc<[Selection<Anchor>]>,
744 select_next_state: Option<SelectNextState>,
745 select_prev_state: Option<SelectNextState>,
746 add_selections_state: Option<AddSelectionsState>,
747}
748
749enum SelectionHistoryMode {
750 Normal,
751 Undoing,
752 Redoing,
753}
754
755#[derive(Clone, PartialEq, Eq, Hash)]
756struct HoveredCursor {
757 replica_id: u16,
758 selection_id: usize,
759}
760
761impl Default for SelectionHistoryMode {
762 fn default() -> Self {
763 Self::Normal
764 }
765}
766
767#[derive(Default)]
768struct SelectionHistory {
769 #[allow(clippy::type_complexity)]
770 selections_by_transaction:
771 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
772 mode: SelectionHistoryMode,
773 undo_stack: VecDeque<SelectionHistoryEntry>,
774 redo_stack: VecDeque<SelectionHistoryEntry>,
775}
776
777impl SelectionHistory {
778 fn insert_transaction(
779 &mut self,
780 transaction_id: TransactionId,
781 selections: Arc<[Selection<Anchor>]>,
782 ) {
783 self.selections_by_transaction
784 .insert(transaction_id, (selections, None));
785 }
786
787 #[allow(clippy::type_complexity)]
788 fn transaction(
789 &self,
790 transaction_id: TransactionId,
791 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
792 self.selections_by_transaction.get(&transaction_id)
793 }
794
795 #[allow(clippy::type_complexity)]
796 fn transaction_mut(
797 &mut self,
798 transaction_id: TransactionId,
799 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
800 self.selections_by_transaction.get_mut(&transaction_id)
801 }
802
803 fn push(&mut self, entry: SelectionHistoryEntry) {
804 if !entry.selections.is_empty() {
805 match self.mode {
806 SelectionHistoryMode::Normal => {
807 self.push_undo(entry);
808 self.redo_stack.clear();
809 }
810 SelectionHistoryMode::Undoing => self.push_redo(entry),
811 SelectionHistoryMode::Redoing => self.push_undo(entry),
812 }
813 }
814 }
815
816 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
817 if self
818 .undo_stack
819 .back()
820 .map_or(true, |e| e.selections != entry.selections)
821 {
822 self.undo_stack.push_back(entry);
823 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
824 self.undo_stack.pop_front();
825 }
826 }
827 }
828
829 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
830 if self
831 .redo_stack
832 .back()
833 .map_or(true, |e| e.selections != entry.selections)
834 {
835 self.redo_stack.push_back(entry);
836 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
837 self.redo_stack.pop_front();
838 }
839 }
840 }
841}
842
843struct RowHighlight {
844 index: usize,
845 range: Range<Anchor>,
846 color: Hsla,
847 should_autoscroll: bool,
848}
849
850#[derive(Clone, Debug)]
851struct AddSelectionsState {
852 above: bool,
853 stack: Vec<usize>,
854}
855
856#[derive(Clone)]
857struct SelectNextState {
858 query: AhoCorasick,
859 wordwise: bool,
860 done: bool,
861}
862
863impl std::fmt::Debug for SelectNextState {
864 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
865 f.debug_struct(std::any::type_name::<Self>())
866 .field("wordwise", &self.wordwise)
867 .field("done", &self.done)
868 .finish()
869 }
870}
871
872#[derive(Debug)]
873struct AutocloseRegion {
874 selection_id: usize,
875 range: Range<Anchor>,
876 pair: BracketPair,
877}
878
879#[derive(Debug)]
880struct SnippetState {
881 ranges: Vec<Vec<Range<Anchor>>>,
882 active_index: usize,
883 choices: Vec<Option<Vec<String>>>,
884}
885
886#[doc(hidden)]
887pub struct RenameState {
888 pub range: Range<Anchor>,
889 pub old_name: Arc<str>,
890 pub editor: View<Editor>,
891 block_id: CustomBlockId,
892}
893
894struct InvalidationStack<T>(Vec<T>);
895
896struct RegisteredInlineCompletionProvider {
897 provider: Arc<dyn InlineCompletionProviderHandle>,
898 _subscription: Subscription,
899}
900
901#[derive(Debug)]
902struct ActiveDiagnosticGroup {
903 primary_range: Range<Anchor>,
904 primary_message: String,
905 group_id: usize,
906 blocks: HashMap<CustomBlockId, Diagnostic>,
907 is_valid: bool,
908}
909
910#[derive(Serialize, Deserialize, Clone, Debug)]
911pub struct ClipboardSelection {
912 pub len: usize,
913 pub is_entire_line: bool,
914 pub first_line_indent: u32,
915}
916
917#[derive(Debug)]
918pub(crate) struct NavigationData {
919 cursor_anchor: Anchor,
920 cursor_position: Point,
921 scroll_anchor: ScrollAnchor,
922 scroll_top_row: u32,
923}
924
925#[derive(Debug, Clone, Copy, PartialEq, Eq)]
926pub enum GotoDefinitionKind {
927 Symbol,
928 Declaration,
929 Type,
930 Implementation,
931}
932
933#[derive(Debug, Clone)]
934enum InlayHintRefreshReason {
935 Toggle(bool),
936 SettingsChange(InlayHintSettings),
937 NewLinesShown,
938 BufferEdited(HashSet<Arc<Language>>),
939 RefreshRequested,
940 ExcerptsRemoved(Vec<ExcerptId>),
941}
942
943impl InlayHintRefreshReason {
944 fn description(&self) -> &'static str {
945 match self {
946 Self::Toggle(_) => "toggle",
947 Self::SettingsChange(_) => "settings change",
948 Self::NewLinesShown => "new lines shown",
949 Self::BufferEdited(_) => "buffer edited",
950 Self::RefreshRequested => "refresh requested",
951 Self::ExcerptsRemoved(_) => "excerpts removed",
952 }
953 }
954}
955
956pub(crate) struct FocusedBlock {
957 id: BlockId,
958 focus_handle: WeakFocusHandle,
959}
960
961#[derive(Clone)]
962struct JumpData {
963 excerpt_id: ExcerptId,
964 position: Point,
965 anchor: text::Anchor,
966 path: Option<project::ProjectPath>,
967 line_offset_from_top: u32,
968}
969
970impl Editor {
971 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
972 let buffer = cx.new_model(|cx| Buffer::local("", cx));
973 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
974 Self::new(
975 EditorMode::SingleLine { auto_width: false },
976 buffer,
977 None,
978 false,
979 cx,
980 )
981 }
982
983 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
984 let buffer = cx.new_model(|cx| Buffer::local("", cx));
985 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
986 Self::new(EditorMode::Full, buffer, None, false, cx)
987 }
988
989 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
990 let buffer = cx.new_model(|cx| Buffer::local("", cx));
991 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
992 Self::new(
993 EditorMode::SingleLine { auto_width: true },
994 buffer,
995 None,
996 false,
997 cx,
998 )
999 }
1000
1001 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1002 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1003 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1004 Self::new(
1005 EditorMode::AutoHeight { max_lines },
1006 buffer,
1007 None,
1008 false,
1009 cx,
1010 )
1011 }
1012
1013 pub fn for_buffer(
1014 buffer: Model<Buffer>,
1015 project: Option<Model<Project>>,
1016 cx: &mut ViewContext<Self>,
1017 ) -> Self {
1018 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1019 Self::new(EditorMode::Full, buffer, project, false, cx)
1020 }
1021
1022 pub fn for_multibuffer(
1023 buffer: Model<MultiBuffer>,
1024 project: Option<Model<Project>>,
1025 show_excerpt_controls: bool,
1026 cx: &mut ViewContext<Self>,
1027 ) -> Self {
1028 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1029 }
1030
1031 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1032 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1033 let mut clone = Self::new(
1034 self.mode,
1035 self.buffer.clone(),
1036 self.project.clone(),
1037 show_excerpt_controls,
1038 cx,
1039 );
1040 self.display_map.update(cx, |display_map, cx| {
1041 let snapshot = display_map.snapshot(cx);
1042 clone.display_map.update(cx, |display_map, cx| {
1043 display_map.set_state(&snapshot, cx);
1044 });
1045 });
1046 clone.selections.clone_state(&self.selections);
1047 clone.scroll_manager.clone_state(&self.scroll_manager);
1048 clone.searchable = self.searchable;
1049 clone
1050 }
1051
1052 pub fn new(
1053 mode: EditorMode,
1054 buffer: Model<MultiBuffer>,
1055 project: Option<Model<Project>>,
1056 show_excerpt_controls: bool,
1057 cx: &mut ViewContext<Self>,
1058 ) -> Self {
1059 let style = cx.text_style();
1060 let font_size = style.font_size.to_pixels(cx.rem_size());
1061 let editor = cx.view().downgrade();
1062 let fold_placeholder = FoldPlaceholder {
1063 constrain_width: true,
1064 render: Arc::new(move |fold_id, fold_range, cx| {
1065 let editor = editor.clone();
1066 div()
1067 .id(fold_id)
1068 .bg(cx.theme().colors().ghost_element_background)
1069 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1070 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1071 .rounded_sm()
1072 .size_full()
1073 .cursor_pointer()
1074 .child("⋯")
1075 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1076 .on_click(move |_, cx| {
1077 editor
1078 .update(cx, |editor, cx| {
1079 editor.unfold_ranges(
1080 &[fold_range.start..fold_range.end],
1081 true,
1082 false,
1083 cx,
1084 );
1085 cx.stop_propagation();
1086 })
1087 .ok();
1088 })
1089 .into_any()
1090 }),
1091 merge_adjacent: true,
1092 ..Default::default()
1093 };
1094 let display_map = cx.new_model(|cx| {
1095 DisplayMap::new(
1096 buffer.clone(),
1097 style.font(),
1098 font_size,
1099 None,
1100 show_excerpt_controls,
1101 FILE_HEADER_HEIGHT,
1102 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1103 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1104 fold_placeholder,
1105 cx,
1106 )
1107 });
1108
1109 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1110
1111 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1112
1113 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1114 .then(|| language_settings::SoftWrap::None);
1115
1116 let mut project_subscriptions = Vec::new();
1117 if mode == EditorMode::Full {
1118 if let Some(project) = project.as_ref() {
1119 if buffer.read(cx).is_singleton() {
1120 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1121 cx.emit(EditorEvent::TitleChanged);
1122 }));
1123 }
1124 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1125 if let project::Event::RefreshInlayHints = event {
1126 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1127 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1128 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1129 let focus_handle = editor.focus_handle(cx);
1130 if focus_handle.is_focused(cx) {
1131 let snapshot = buffer.read(cx).snapshot();
1132 for (range, snippet) in snippet_edits {
1133 let editor_range =
1134 language::range_from_lsp(*range).to_offset(&snapshot);
1135 editor
1136 .insert_snippet(&[editor_range], snippet.clone(), cx)
1137 .ok();
1138 }
1139 }
1140 }
1141 }
1142 }));
1143 if let Some(task_inventory) = project
1144 .read(cx)
1145 .task_store()
1146 .read(cx)
1147 .task_inventory()
1148 .cloned()
1149 {
1150 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1151 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1152 }));
1153 }
1154 }
1155 }
1156
1157 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1158
1159 let inlay_hint_settings =
1160 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1161 let focus_handle = cx.focus_handle();
1162 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1163 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1164 .detach();
1165 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1166 .detach();
1167 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1168
1169 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1170 Some(false)
1171 } else {
1172 None
1173 };
1174
1175 let mut code_action_providers = Vec::new();
1176 if let Some(project) = project.clone() {
1177 get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
1178 code_action_providers.push(Arc::new(project) as Arc<_>);
1179 }
1180
1181 let mut this = Self {
1182 focus_handle,
1183 show_cursor_when_unfocused: false,
1184 last_focused_descendant: None,
1185 buffer: buffer.clone(),
1186 display_map: display_map.clone(),
1187 selections,
1188 scroll_manager: ScrollManager::new(cx),
1189 columnar_selection_tail: None,
1190 add_selections_state: None,
1191 select_next_state: None,
1192 select_prev_state: None,
1193 selection_history: Default::default(),
1194 autoclose_regions: Default::default(),
1195 snippet_stack: Default::default(),
1196 select_larger_syntax_node_stack: Vec::new(),
1197 ime_transaction: Default::default(),
1198 active_diagnostics: None,
1199 soft_wrap_mode_override,
1200 completion_provider: project.clone().map(|project| Box::new(project) as _),
1201 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1202 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1203 project,
1204 blink_manager: blink_manager.clone(),
1205 show_local_selections: true,
1206 mode,
1207 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1208 show_gutter: mode == EditorMode::Full,
1209 show_line_numbers: None,
1210 use_relative_line_numbers: None,
1211 show_git_diff_gutter: None,
1212 show_code_actions: None,
1213 show_runnables: None,
1214 show_wrap_guides: None,
1215 show_indent_guides,
1216 placeholder_text: None,
1217 highlight_order: 0,
1218 highlighted_rows: HashMap::default(),
1219 background_highlights: Default::default(),
1220 gutter_highlights: TreeMap::default(),
1221 scrollbar_marker_state: ScrollbarMarkerState::default(),
1222 active_indent_guides_state: ActiveIndentGuidesState::default(),
1223 nav_history: None,
1224 context_menu: RwLock::new(None),
1225 mouse_context_menu: None,
1226 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1227 completion_tasks: Default::default(),
1228 signature_help_state: SignatureHelpState::default(),
1229 auto_signature_help: None,
1230 find_all_references_task_sources: Vec::new(),
1231 next_completion_id: 0,
1232 next_inlay_id: 0,
1233 code_action_providers,
1234 available_code_actions: Default::default(),
1235 code_actions_task: Default::default(),
1236 document_highlights_task: Default::default(),
1237 linked_editing_range_task: Default::default(),
1238 pending_rename: Default::default(),
1239 searchable: true,
1240 cursor_shape: EditorSettings::get_global(cx)
1241 .cursor_shape
1242 .unwrap_or_default(),
1243 current_line_highlight: None,
1244 autoindent_mode: Some(AutoindentMode::EachLine),
1245 collapse_matches: false,
1246 workspace: None,
1247 input_enabled: true,
1248 use_modal_editing: mode == EditorMode::Full,
1249 read_only: false,
1250 use_autoclose: true,
1251 use_auto_surround: true,
1252 auto_replace_emoji_shortcode: false,
1253 leader_peer_id: None,
1254 remote_id: None,
1255 hover_state: Default::default(),
1256 hovered_link_state: Default::default(),
1257 inline_completion_provider: None,
1258 active_inline_completion: None,
1259 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1260 diff_map: DiffMap::default(),
1261 gutter_hovered: false,
1262 pixel_position_of_newest_cursor: None,
1263 last_bounds: None,
1264 expect_bounds_change: None,
1265 gutter_dimensions: GutterDimensions::default(),
1266 style: None,
1267 show_cursor_names: false,
1268 hovered_cursors: Default::default(),
1269 next_editor_action_id: EditorActionId::default(),
1270 editor_actions: Rc::default(),
1271 show_inline_completions_override: None,
1272 enable_inline_completions: true,
1273 custom_context_menu: None,
1274 show_git_blame_gutter: false,
1275 show_git_blame_inline: false,
1276 show_selection_menu: None,
1277 show_git_blame_inline_delay_task: None,
1278 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1279 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1280 .session
1281 .restore_unsaved_buffers,
1282 blame: None,
1283 blame_subscription: None,
1284 tasks: Default::default(),
1285 _subscriptions: vec![
1286 cx.observe(&buffer, Self::on_buffer_changed),
1287 cx.subscribe(&buffer, Self::on_buffer_event),
1288 cx.observe(&display_map, Self::on_display_map_changed),
1289 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1290 cx.observe_global::<SettingsStore>(Self::settings_changed),
1291 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1292 cx.observe_window_activation(|editor, cx| {
1293 let active = cx.is_window_active();
1294 editor.blink_manager.update(cx, |blink_manager, cx| {
1295 if active {
1296 blink_manager.enable(cx);
1297 } else {
1298 blink_manager.disable(cx);
1299 }
1300 });
1301 }),
1302 ],
1303 tasks_update_task: None,
1304 linked_edit_ranges: Default::default(),
1305 previous_search_ranges: None,
1306 breadcrumb_header: None,
1307 focused_block: None,
1308 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1309 addons: HashMap::default(),
1310 registered_buffers: 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 if let Some(buffer) = buffer.read(cx).as_singleton() {
1330 if let Some(project) = this.project.as_ref() {
1331 let lsp_store = project.read(cx).lsp_store();
1332 let handle = lsp_store.update(cx, |lsp_store, cx| {
1333 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1334 });
1335 this.registered_buffers
1336 .insert(buffer.read(cx).remote_id(), handle);
1337 }
1338 }
1339 }
1340
1341 this.report_editor_event("open", None, cx);
1342 this
1343 }
1344
1345 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
1346 self.mouse_context_menu
1347 .as_ref()
1348 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1349 }
1350
1351 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
1352 let mut key_context = KeyContext::new_with_defaults();
1353 key_context.add("Editor");
1354 let mode = match self.mode {
1355 EditorMode::SingleLine { .. } => "single_line",
1356 EditorMode::AutoHeight { .. } => "auto_height",
1357 EditorMode::Full => "full",
1358 };
1359
1360 if EditorSettings::jupyter_enabled(cx) {
1361 key_context.add("jupyter");
1362 }
1363
1364 key_context.set("mode", mode);
1365 if self.pending_rename.is_some() {
1366 key_context.add("renaming");
1367 }
1368 if self.context_menu_visible() {
1369 match self.context_menu.read().as_ref() {
1370 Some(CodeContextMenu::Completions(_)) => {
1371 key_context.add("menu");
1372 key_context.add("showing_completions")
1373 }
1374 Some(CodeContextMenu::CodeActions(_)) => {
1375 key_context.add("menu");
1376 key_context.add("showing_code_actions")
1377 }
1378 None => {}
1379 }
1380 }
1381
1382 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1383 if !self.focus_handle(cx).contains_focused(cx)
1384 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
1385 {
1386 for addon in self.addons.values() {
1387 addon.extend_key_context(&mut key_context, cx)
1388 }
1389 }
1390
1391 if let Some(extension) = self
1392 .buffer
1393 .read(cx)
1394 .as_singleton()
1395 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1396 {
1397 key_context.set("extension", extension.to_string());
1398 }
1399
1400 if self.has_active_inline_completion() {
1401 key_context.add("copilot_suggestion");
1402 key_context.add("inline_completion");
1403 }
1404
1405 key_context
1406 }
1407
1408 pub fn new_file(
1409 workspace: &mut Workspace,
1410 _: &workspace::NewFile,
1411 cx: &mut ViewContext<Workspace>,
1412 ) {
1413 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
1414 "Failed to create buffer",
1415 cx,
1416 |e, _| match e.error_code() {
1417 ErrorCode::RemoteUpgradeRequired => Some(format!(
1418 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1419 e.error_tag("required").unwrap_or("the latest version")
1420 )),
1421 _ => None,
1422 },
1423 );
1424 }
1425
1426 pub fn new_in_workspace(
1427 workspace: &mut Workspace,
1428 cx: &mut ViewContext<Workspace>,
1429 ) -> Task<Result<View<Editor>>> {
1430 let project = workspace.project().clone();
1431 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1432
1433 cx.spawn(|workspace, mut cx| async move {
1434 let buffer = create.await?;
1435 workspace.update(&mut cx, |workspace, cx| {
1436 let editor =
1437 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
1438 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
1439 editor
1440 })
1441 })
1442 }
1443
1444 fn new_file_vertical(
1445 workspace: &mut Workspace,
1446 _: &workspace::NewFileSplitVertical,
1447 cx: &mut ViewContext<Workspace>,
1448 ) {
1449 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
1450 }
1451
1452 fn new_file_horizontal(
1453 workspace: &mut Workspace,
1454 _: &workspace::NewFileSplitHorizontal,
1455 cx: &mut ViewContext<Workspace>,
1456 ) {
1457 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
1458 }
1459
1460 fn new_file_in_direction(
1461 workspace: &mut Workspace,
1462 direction: SplitDirection,
1463 cx: &mut ViewContext<Workspace>,
1464 ) {
1465 let project = workspace.project().clone();
1466 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1467
1468 cx.spawn(|workspace, mut cx| async move {
1469 let buffer = create.await?;
1470 workspace.update(&mut cx, move |workspace, cx| {
1471 workspace.split_item(
1472 direction,
1473 Box::new(
1474 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
1475 ),
1476 cx,
1477 )
1478 })?;
1479 anyhow::Ok(())
1480 })
1481 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
1482 ErrorCode::RemoteUpgradeRequired => Some(format!(
1483 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1484 e.error_tag("required").unwrap_or("the latest version")
1485 )),
1486 _ => None,
1487 });
1488 }
1489
1490 pub fn leader_peer_id(&self) -> Option<PeerId> {
1491 self.leader_peer_id
1492 }
1493
1494 pub fn buffer(&self) -> &Model<MultiBuffer> {
1495 &self.buffer
1496 }
1497
1498 pub fn workspace(&self) -> Option<View<Workspace>> {
1499 self.workspace.as_ref()?.0.upgrade()
1500 }
1501
1502 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
1503 self.buffer().read(cx).title(cx)
1504 }
1505
1506 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
1507 let git_blame_gutter_max_author_length = self
1508 .render_git_blame_gutter(cx)
1509 .then(|| {
1510 if let Some(blame) = self.blame.as_ref() {
1511 let max_author_length =
1512 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1513 Some(max_author_length)
1514 } else {
1515 None
1516 }
1517 })
1518 .flatten();
1519
1520 EditorSnapshot {
1521 mode: self.mode,
1522 show_gutter: self.show_gutter,
1523 show_line_numbers: self.show_line_numbers,
1524 show_git_diff_gutter: self.show_git_diff_gutter,
1525 show_code_actions: self.show_code_actions,
1526 show_runnables: self.show_runnables,
1527 git_blame_gutter_max_author_length,
1528 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1529 scroll_anchor: self.scroll_manager.anchor(),
1530 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1531 placeholder_text: self.placeholder_text.clone(),
1532 diff_map: self.diff_map.snapshot(),
1533 is_focused: self.focus_handle.is_focused(cx),
1534 current_line_highlight: self
1535 .current_line_highlight
1536 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1537 gutter_hovered: self.gutter_hovered,
1538 }
1539 }
1540
1541 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
1542 self.buffer.read(cx).language_at(point, cx)
1543 }
1544
1545 pub fn file_at<T: ToOffset>(
1546 &self,
1547 point: T,
1548 cx: &AppContext,
1549 ) -> Option<Arc<dyn language::File>> {
1550 self.buffer.read(cx).read(cx).file_at(point).cloned()
1551 }
1552
1553 pub fn active_excerpt(
1554 &self,
1555 cx: &AppContext,
1556 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
1557 self.buffer
1558 .read(cx)
1559 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1560 }
1561
1562 pub fn mode(&self) -> EditorMode {
1563 self.mode
1564 }
1565
1566 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1567 self.collaboration_hub.as_deref()
1568 }
1569
1570 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1571 self.collaboration_hub = Some(hub);
1572 }
1573
1574 pub fn set_custom_context_menu(
1575 &mut self,
1576 f: impl 'static
1577 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
1578 ) {
1579 self.custom_context_menu = Some(Box::new(f))
1580 }
1581
1582 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1583 self.completion_provider = provider;
1584 }
1585
1586 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1587 self.semantics_provider.clone()
1588 }
1589
1590 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1591 self.semantics_provider = provider;
1592 }
1593
1594 pub fn set_inline_completion_provider<T>(
1595 &mut self,
1596 provider: Option<Model<T>>,
1597 cx: &mut ViewContext<Self>,
1598 ) where
1599 T: InlineCompletionProvider,
1600 {
1601 self.inline_completion_provider =
1602 provider.map(|provider| RegisteredInlineCompletionProvider {
1603 _subscription: cx.observe(&provider, |this, _, cx| {
1604 if this.focus_handle.is_focused(cx) {
1605 this.update_visible_inline_completion(cx);
1606 }
1607 }),
1608 provider: Arc::new(provider),
1609 });
1610 self.refresh_inline_completion(false, false, cx);
1611 }
1612
1613 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
1614 self.placeholder_text.as_deref()
1615 }
1616
1617 pub fn set_placeholder_text(
1618 &mut self,
1619 placeholder_text: impl Into<Arc<str>>,
1620 cx: &mut ViewContext<Self>,
1621 ) {
1622 let placeholder_text = Some(placeholder_text.into());
1623 if self.placeholder_text != placeholder_text {
1624 self.placeholder_text = placeholder_text;
1625 cx.notify();
1626 }
1627 }
1628
1629 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
1630 self.cursor_shape = cursor_shape;
1631
1632 // Disrupt blink for immediate user feedback that the cursor shape has changed
1633 self.blink_manager.update(cx, BlinkManager::show_cursor);
1634
1635 cx.notify();
1636 }
1637
1638 pub fn set_current_line_highlight(
1639 &mut self,
1640 current_line_highlight: Option<CurrentLineHighlight>,
1641 ) {
1642 self.current_line_highlight = current_line_highlight;
1643 }
1644
1645 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1646 self.collapse_matches = collapse_matches;
1647 }
1648
1649 pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
1650 let buffers = self.buffer.read(cx).all_buffers();
1651 let Some(lsp_store) = self.lsp_store(cx) else {
1652 return;
1653 };
1654 lsp_store.update(cx, |lsp_store, cx| {
1655 for buffer in buffers {
1656 self.registered_buffers
1657 .entry(buffer.read(cx).remote_id())
1658 .or_insert_with(|| {
1659 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1660 });
1661 }
1662 })
1663 }
1664
1665 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1666 if self.collapse_matches {
1667 return range.start..range.start;
1668 }
1669 range.clone()
1670 }
1671
1672 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
1673 if self.display_map.read(cx).clip_at_line_ends != clip {
1674 self.display_map
1675 .update(cx, |map, _| map.clip_at_line_ends = clip);
1676 }
1677 }
1678
1679 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1680 self.input_enabled = input_enabled;
1681 }
1682
1683 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
1684 self.enable_inline_completions = enabled;
1685 }
1686
1687 pub fn set_autoindent(&mut self, autoindent: bool) {
1688 if autoindent {
1689 self.autoindent_mode = Some(AutoindentMode::EachLine);
1690 } else {
1691 self.autoindent_mode = None;
1692 }
1693 }
1694
1695 pub fn read_only(&self, cx: &AppContext) -> bool {
1696 self.read_only || self.buffer.read(cx).read_only()
1697 }
1698
1699 pub fn set_read_only(&mut self, read_only: bool) {
1700 self.read_only = read_only;
1701 }
1702
1703 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1704 self.use_autoclose = autoclose;
1705 }
1706
1707 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1708 self.use_auto_surround = auto_surround;
1709 }
1710
1711 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1712 self.auto_replace_emoji_shortcode = auto_replace;
1713 }
1714
1715 pub fn toggle_inline_completions(
1716 &mut self,
1717 _: &ToggleInlineCompletions,
1718 cx: &mut ViewContext<Self>,
1719 ) {
1720 if self.show_inline_completions_override.is_some() {
1721 self.set_show_inline_completions(None, cx);
1722 } else {
1723 let cursor = self.selections.newest_anchor().head();
1724 if let Some((buffer, cursor_buffer_position)) =
1725 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1726 {
1727 let show_inline_completions =
1728 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
1729 self.set_show_inline_completions(Some(show_inline_completions), cx);
1730 }
1731 }
1732 }
1733
1734 pub fn set_show_inline_completions(
1735 &mut self,
1736 show_inline_completions: Option<bool>,
1737 cx: &mut ViewContext<Self>,
1738 ) {
1739 self.show_inline_completions_override = show_inline_completions;
1740 self.refresh_inline_completion(false, true, cx);
1741 }
1742
1743 fn should_show_inline_completions(
1744 &self,
1745 buffer: &Model<Buffer>,
1746 buffer_position: language::Anchor,
1747 cx: &AppContext,
1748 ) -> bool {
1749 if !self.snippet_stack.is_empty() {
1750 return false;
1751 }
1752
1753 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
1754 return false;
1755 }
1756
1757 if let Some(provider) = self.inline_completion_provider() {
1758 if let Some(show_inline_completions) = self.show_inline_completions_override {
1759 show_inline_completions
1760 } else {
1761 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
1762 }
1763 } else {
1764 false
1765 }
1766 }
1767
1768 fn inline_completions_disabled_in_scope(
1769 &self,
1770 buffer: &Model<Buffer>,
1771 buffer_position: language::Anchor,
1772 cx: &AppContext,
1773 ) -> bool {
1774 let snapshot = buffer.read(cx).snapshot();
1775 let settings = snapshot.settings_at(buffer_position, cx);
1776
1777 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1778 return false;
1779 };
1780
1781 scope.override_name().map_or(false, |scope_name| {
1782 settings
1783 .inline_completions_disabled_in
1784 .iter()
1785 .any(|s| s == scope_name)
1786 })
1787 }
1788
1789 pub fn set_use_modal_editing(&mut self, to: bool) {
1790 self.use_modal_editing = to;
1791 }
1792
1793 pub fn use_modal_editing(&self) -> bool {
1794 self.use_modal_editing
1795 }
1796
1797 fn selections_did_change(
1798 &mut self,
1799 local: bool,
1800 old_cursor_position: &Anchor,
1801 show_completions: bool,
1802 cx: &mut ViewContext<Self>,
1803 ) {
1804 cx.invalidate_character_coordinates();
1805
1806 // Copy selections to primary selection buffer
1807 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1808 if local {
1809 let selections = self.selections.all::<usize>(cx);
1810 let buffer_handle = self.buffer.read(cx).read(cx);
1811
1812 let mut text = String::new();
1813 for (index, selection) in selections.iter().enumerate() {
1814 let text_for_selection = buffer_handle
1815 .text_for_range(selection.start..selection.end)
1816 .collect::<String>();
1817
1818 text.push_str(&text_for_selection);
1819 if index != selections.len() - 1 {
1820 text.push('\n');
1821 }
1822 }
1823
1824 if !text.is_empty() {
1825 cx.write_to_primary(ClipboardItem::new_string(text));
1826 }
1827 }
1828
1829 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
1830 self.buffer.update(cx, |buffer, cx| {
1831 buffer.set_active_selections(
1832 &self.selections.disjoint_anchors(),
1833 self.selections.line_mode,
1834 self.cursor_shape,
1835 cx,
1836 )
1837 });
1838 }
1839 let display_map = self
1840 .display_map
1841 .update(cx, |display_map, cx| display_map.snapshot(cx));
1842 let buffer = &display_map.buffer_snapshot;
1843 self.add_selections_state = None;
1844 self.select_next_state = None;
1845 self.select_prev_state = None;
1846 self.select_larger_syntax_node_stack.clear();
1847 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1848 self.snippet_stack
1849 .invalidate(&self.selections.disjoint_anchors(), buffer);
1850 self.take_rename(false, cx);
1851
1852 let new_cursor_position = self.selections.newest_anchor().head();
1853
1854 self.push_to_nav_history(
1855 *old_cursor_position,
1856 Some(new_cursor_position.to_point(buffer)),
1857 cx,
1858 );
1859
1860 if local {
1861 let new_cursor_position = self.selections.newest_anchor().head();
1862 let mut context_menu = self.context_menu.write();
1863 let completion_menu = match context_menu.as_ref() {
1864 Some(CodeContextMenu::Completions(menu)) => Some(menu),
1865
1866 _ => {
1867 *context_menu = None;
1868 None
1869 }
1870 };
1871
1872 if let Some(completion_menu) = completion_menu {
1873 let cursor_position = new_cursor_position.to_offset(buffer);
1874 let (word_range, kind) =
1875 buffer.surrounding_word(completion_menu.initial_position, true);
1876 if kind == Some(CharKind::Word)
1877 && word_range.to_inclusive().contains(&cursor_position)
1878 {
1879 let mut completion_menu = completion_menu.clone();
1880 drop(context_menu);
1881
1882 let query = Self::completion_query(buffer, cursor_position);
1883 cx.spawn(move |this, mut cx| async move {
1884 completion_menu
1885 .filter(query.as_deref(), cx.background_executor().clone())
1886 .await;
1887
1888 this.update(&mut cx, |this, cx| {
1889 let mut context_menu = this.context_menu.write();
1890 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
1891 else {
1892 return;
1893 };
1894
1895 if menu.id > completion_menu.id {
1896 return;
1897 }
1898
1899 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
1900 drop(context_menu);
1901 cx.notify();
1902 })
1903 })
1904 .detach();
1905
1906 if show_completions {
1907 self.show_completions(&ShowCompletions { trigger: None }, cx);
1908 }
1909 } else {
1910 drop(context_menu);
1911 self.hide_context_menu(cx);
1912 }
1913 } else {
1914 drop(context_menu);
1915 }
1916
1917 hide_hover(self, cx);
1918
1919 if old_cursor_position.to_display_point(&display_map).row()
1920 != new_cursor_position.to_display_point(&display_map).row()
1921 {
1922 self.available_code_actions.take();
1923 }
1924 self.refresh_code_actions(cx);
1925 self.refresh_document_highlights(cx);
1926 refresh_matching_bracket_highlights(self, cx);
1927 self.update_visible_inline_completion(cx);
1928 linked_editing_ranges::refresh_linked_ranges(self, cx);
1929 if self.git_blame_inline_enabled {
1930 self.start_inline_blame_timer(cx);
1931 }
1932 }
1933
1934 self.blink_manager.update(cx, BlinkManager::pause_blinking);
1935 cx.emit(EditorEvent::SelectionsChanged { local });
1936
1937 if self.selections.disjoint_anchors().len() == 1 {
1938 cx.emit(SearchEvent::ActiveMatchChanged)
1939 }
1940 cx.notify();
1941 }
1942
1943 pub fn change_selections<R>(
1944 &mut self,
1945 autoscroll: Option<Autoscroll>,
1946 cx: &mut ViewContext<Self>,
1947 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
1948 ) -> R {
1949 self.change_selections_inner(autoscroll, true, cx, change)
1950 }
1951
1952 pub fn change_selections_inner<R>(
1953 &mut self,
1954 autoscroll: Option<Autoscroll>,
1955 request_completions: bool,
1956 cx: &mut ViewContext<Self>,
1957 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
1958 ) -> R {
1959 let old_cursor_position = self.selections.newest_anchor().head();
1960 self.push_to_selection_history();
1961
1962 let (changed, result) = self.selections.change_with(cx, change);
1963
1964 if changed {
1965 if let Some(autoscroll) = autoscroll {
1966 self.request_autoscroll(autoscroll, cx);
1967 }
1968 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
1969
1970 if self.should_open_signature_help_automatically(
1971 &old_cursor_position,
1972 self.signature_help_state.backspace_pressed(),
1973 cx,
1974 ) {
1975 self.show_signature_help(&ShowSignatureHelp, cx);
1976 }
1977 self.signature_help_state.set_backspace_pressed(false);
1978 }
1979
1980 result
1981 }
1982
1983 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
1984 where
1985 I: IntoIterator<Item = (Range<S>, T)>,
1986 S: ToOffset,
1987 T: Into<Arc<str>>,
1988 {
1989 if self.read_only(cx) {
1990 return;
1991 }
1992
1993 self.buffer
1994 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
1995 }
1996
1997 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
1998 where
1999 I: IntoIterator<Item = (Range<S>, T)>,
2000 S: ToOffset,
2001 T: Into<Arc<str>>,
2002 {
2003 if self.read_only(cx) {
2004 return;
2005 }
2006
2007 self.buffer.update(cx, |buffer, cx| {
2008 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2009 });
2010 }
2011
2012 pub fn edit_with_block_indent<I, S, T>(
2013 &mut self,
2014 edits: I,
2015 original_indent_columns: Vec<u32>,
2016 cx: &mut ViewContext<Self>,
2017 ) where
2018 I: IntoIterator<Item = (Range<S>, T)>,
2019 S: ToOffset,
2020 T: Into<Arc<str>>,
2021 {
2022 if self.read_only(cx) {
2023 return;
2024 }
2025
2026 self.buffer.update(cx, |buffer, cx| {
2027 buffer.edit(
2028 edits,
2029 Some(AutoindentMode::Block {
2030 original_indent_columns,
2031 }),
2032 cx,
2033 )
2034 });
2035 }
2036
2037 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2038 self.hide_context_menu(cx);
2039
2040 match phase {
2041 SelectPhase::Begin {
2042 position,
2043 add,
2044 click_count,
2045 } => self.begin_selection(position, add, click_count, cx),
2046 SelectPhase::BeginColumnar {
2047 position,
2048 goal_column,
2049 reset,
2050 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2051 SelectPhase::Extend {
2052 position,
2053 click_count,
2054 } => self.extend_selection(position, click_count, cx),
2055 SelectPhase::Update {
2056 position,
2057 goal_column,
2058 scroll_delta,
2059 } => self.update_selection(position, goal_column, scroll_delta, cx),
2060 SelectPhase::End => self.end_selection(cx),
2061 }
2062 }
2063
2064 fn extend_selection(
2065 &mut self,
2066 position: DisplayPoint,
2067 click_count: usize,
2068 cx: &mut ViewContext<Self>,
2069 ) {
2070 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2071 let tail = self.selections.newest::<usize>(cx).tail();
2072 self.begin_selection(position, false, click_count, cx);
2073
2074 let position = position.to_offset(&display_map, Bias::Left);
2075 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2076
2077 let mut pending_selection = self
2078 .selections
2079 .pending_anchor()
2080 .expect("extend_selection not called with pending selection");
2081 if position >= tail {
2082 pending_selection.start = tail_anchor;
2083 } else {
2084 pending_selection.end = tail_anchor;
2085 pending_selection.reversed = true;
2086 }
2087
2088 let mut pending_mode = self.selections.pending_mode().unwrap();
2089 match &mut pending_mode {
2090 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2091 _ => {}
2092 }
2093
2094 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2095 s.set_pending(pending_selection, pending_mode)
2096 });
2097 }
2098
2099 fn begin_selection(
2100 &mut self,
2101 position: DisplayPoint,
2102 add: bool,
2103 click_count: usize,
2104 cx: &mut ViewContext<Self>,
2105 ) {
2106 if !self.focus_handle.is_focused(cx) {
2107 self.last_focused_descendant = None;
2108 cx.focus(&self.focus_handle);
2109 }
2110
2111 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2112 let buffer = &display_map.buffer_snapshot;
2113 let newest_selection = self.selections.newest_anchor().clone();
2114 let position = display_map.clip_point(position, Bias::Left);
2115
2116 let start;
2117 let end;
2118 let mode;
2119 let mut auto_scroll;
2120 match click_count {
2121 1 => {
2122 start = buffer.anchor_before(position.to_point(&display_map));
2123 end = start;
2124 mode = SelectMode::Character;
2125 auto_scroll = true;
2126 }
2127 2 => {
2128 let range = movement::surrounding_word(&display_map, position);
2129 start = buffer.anchor_before(range.start.to_point(&display_map));
2130 end = buffer.anchor_before(range.end.to_point(&display_map));
2131 mode = SelectMode::Word(start..end);
2132 auto_scroll = true;
2133 }
2134 3 => {
2135 let position = display_map
2136 .clip_point(position, Bias::Left)
2137 .to_point(&display_map);
2138 let line_start = display_map.prev_line_boundary(position).0;
2139 let next_line_start = buffer.clip_point(
2140 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2141 Bias::Left,
2142 );
2143 start = buffer.anchor_before(line_start);
2144 end = buffer.anchor_before(next_line_start);
2145 mode = SelectMode::Line(start..end);
2146 auto_scroll = true;
2147 }
2148 _ => {
2149 start = buffer.anchor_before(0);
2150 end = buffer.anchor_before(buffer.len());
2151 mode = SelectMode::All;
2152 auto_scroll = false;
2153 }
2154 }
2155 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2156
2157 let point_to_delete: Option<usize> = {
2158 let selected_points: Vec<Selection<Point>> =
2159 self.selections.disjoint_in_range(start..end, cx);
2160
2161 if !add || click_count > 1 {
2162 None
2163 } else if !selected_points.is_empty() {
2164 Some(selected_points[0].id)
2165 } else {
2166 let clicked_point_already_selected =
2167 self.selections.disjoint.iter().find(|selection| {
2168 selection.start.to_point(buffer) == start.to_point(buffer)
2169 || selection.end.to_point(buffer) == end.to_point(buffer)
2170 });
2171
2172 clicked_point_already_selected.map(|selection| selection.id)
2173 }
2174 };
2175
2176 let selections_count = self.selections.count();
2177
2178 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2179 if let Some(point_to_delete) = point_to_delete {
2180 s.delete(point_to_delete);
2181
2182 if selections_count == 1 {
2183 s.set_pending_anchor_range(start..end, mode);
2184 }
2185 } else {
2186 if !add {
2187 s.clear_disjoint();
2188 } else if click_count > 1 {
2189 s.delete(newest_selection.id)
2190 }
2191
2192 s.set_pending_anchor_range(start..end, mode);
2193 }
2194 });
2195 }
2196
2197 fn begin_columnar_selection(
2198 &mut self,
2199 position: DisplayPoint,
2200 goal_column: u32,
2201 reset: bool,
2202 cx: &mut ViewContext<Self>,
2203 ) {
2204 if !self.focus_handle.is_focused(cx) {
2205 self.last_focused_descendant = None;
2206 cx.focus(&self.focus_handle);
2207 }
2208
2209 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2210
2211 if reset {
2212 let pointer_position = display_map
2213 .buffer_snapshot
2214 .anchor_before(position.to_point(&display_map));
2215
2216 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2217 s.clear_disjoint();
2218 s.set_pending_anchor_range(
2219 pointer_position..pointer_position,
2220 SelectMode::Character,
2221 );
2222 });
2223 }
2224
2225 let tail = self.selections.newest::<Point>(cx).tail();
2226 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2227
2228 if !reset {
2229 self.select_columns(
2230 tail.to_display_point(&display_map),
2231 position,
2232 goal_column,
2233 &display_map,
2234 cx,
2235 );
2236 }
2237 }
2238
2239 fn update_selection(
2240 &mut self,
2241 position: DisplayPoint,
2242 goal_column: u32,
2243 scroll_delta: gpui::Point<f32>,
2244 cx: &mut ViewContext<Self>,
2245 ) {
2246 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2247
2248 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2249 let tail = tail.to_display_point(&display_map);
2250 self.select_columns(tail, position, goal_column, &display_map, cx);
2251 } else if let Some(mut pending) = self.selections.pending_anchor() {
2252 let buffer = self.buffer.read(cx).snapshot(cx);
2253 let head;
2254 let tail;
2255 let mode = self.selections.pending_mode().unwrap();
2256 match &mode {
2257 SelectMode::Character => {
2258 head = position.to_point(&display_map);
2259 tail = pending.tail().to_point(&buffer);
2260 }
2261 SelectMode::Word(original_range) => {
2262 let original_display_range = original_range.start.to_display_point(&display_map)
2263 ..original_range.end.to_display_point(&display_map);
2264 let original_buffer_range = original_display_range.start.to_point(&display_map)
2265 ..original_display_range.end.to_point(&display_map);
2266 if movement::is_inside_word(&display_map, position)
2267 || original_display_range.contains(&position)
2268 {
2269 let word_range = movement::surrounding_word(&display_map, position);
2270 if word_range.start < original_display_range.start {
2271 head = word_range.start.to_point(&display_map);
2272 } else {
2273 head = word_range.end.to_point(&display_map);
2274 }
2275 } else {
2276 head = position.to_point(&display_map);
2277 }
2278
2279 if head <= original_buffer_range.start {
2280 tail = original_buffer_range.end;
2281 } else {
2282 tail = original_buffer_range.start;
2283 }
2284 }
2285 SelectMode::Line(original_range) => {
2286 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2287
2288 let position = display_map
2289 .clip_point(position, Bias::Left)
2290 .to_point(&display_map);
2291 let line_start = display_map.prev_line_boundary(position).0;
2292 let next_line_start = buffer.clip_point(
2293 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2294 Bias::Left,
2295 );
2296
2297 if line_start < original_range.start {
2298 head = line_start
2299 } else {
2300 head = next_line_start
2301 }
2302
2303 if head <= original_range.start {
2304 tail = original_range.end;
2305 } else {
2306 tail = original_range.start;
2307 }
2308 }
2309 SelectMode::All => {
2310 return;
2311 }
2312 };
2313
2314 if head < tail {
2315 pending.start = buffer.anchor_before(head);
2316 pending.end = buffer.anchor_before(tail);
2317 pending.reversed = true;
2318 } else {
2319 pending.start = buffer.anchor_before(tail);
2320 pending.end = buffer.anchor_before(head);
2321 pending.reversed = false;
2322 }
2323
2324 self.change_selections(None, cx, |s| {
2325 s.set_pending(pending, mode);
2326 });
2327 } else {
2328 log::error!("update_selection dispatched with no pending selection");
2329 return;
2330 }
2331
2332 self.apply_scroll_delta(scroll_delta, cx);
2333 cx.notify();
2334 }
2335
2336 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2337 self.columnar_selection_tail.take();
2338 if self.selections.pending_anchor().is_some() {
2339 let selections = self.selections.all::<usize>(cx);
2340 self.change_selections(None, cx, |s| {
2341 s.select(selections);
2342 s.clear_pending();
2343 });
2344 }
2345 }
2346
2347 fn select_columns(
2348 &mut self,
2349 tail: DisplayPoint,
2350 head: DisplayPoint,
2351 goal_column: u32,
2352 display_map: &DisplaySnapshot,
2353 cx: &mut ViewContext<Self>,
2354 ) {
2355 let start_row = cmp::min(tail.row(), head.row());
2356 let end_row = cmp::max(tail.row(), head.row());
2357 let start_column = cmp::min(tail.column(), goal_column);
2358 let end_column = cmp::max(tail.column(), goal_column);
2359 let reversed = start_column < tail.column();
2360
2361 let selection_ranges = (start_row.0..=end_row.0)
2362 .map(DisplayRow)
2363 .filter_map(|row| {
2364 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2365 let start = display_map
2366 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2367 .to_point(display_map);
2368 let end = display_map
2369 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2370 .to_point(display_map);
2371 if reversed {
2372 Some(end..start)
2373 } else {
2374 Some(start..end)
2375 }
2376 } else {
2377 None
2378 }
2379 })
2380 .collect::<Vec<_>>();
2381
2382 self.change_selections(None, cx, |s| {
2383 s.select_ranges(selection_ranges);
2384 });
2385 cx.notify();
2386 }
2387
2388 pub fn has_pending_nonempty_selection(&self) -> bool {
2389 let pending_nonempty_selection = match self.selections.pending_anchor() {
2390 Some(Selection { start, end, .. }) => start != end,
2391 None => false,
2392 };
2393
2394 pending_nonempty_selection
2395 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2396 }
2397
2398 pub fn has_pending_selection(&self) -> bool {
2399 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2400 }
2401
2402 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2403 if self.clear_expanded_diff_hunks(cx) {
2404 cx.notify();
2405 return;
2406 }
2407 if self.dismiss_menus_and_popups(true, cx) {
2408 return;
2409 }
2410
2411 if self.mode == EditorMode::Full
2412 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
2413 {
2414 return;
2415 }
2416
2417 cx.propagate();
2418 }
2419
2420 pub fn dismiss_menus_and_popups(
2421 &mut self,
2422 should_report_inline_completion_event: bool,
2423 cx: &mut ViewContext<Self>,
2424 ) -> bool {
2425 if self.take_rename(false, cx).is_some() {
2426 return true;
2427 }
2428
2429 if hide_hover(self, cx) {
2430 return true;
2431 }
2432
2433 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2434 return true;
2435 }
2436
2437 if self.hide_context_menu(cx).is_some() {
2438 return true;
2439 }
2440
2441 if self.mouse_context_menu.take().is_some() {
2442 return true;
2443 }
2444
2445 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2446 return true;
2447 }
2448
2449 if self.snippet_stack.pop().is_some() {
2450 return true;
2451 }
2452
2453 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2454 self.dismiss_diagnostics(cx);
2455 return true;
2456 }
2457
2458 false
2459 }
2460
2461 fn linked_editing_ranges_for(
2462 &self,
2463 selection: Range<text::Anchor>,
2464 cx: &AppContext,
2465 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2466 if self.linked_edit_ranges.is_empty() {
2467 return None;
2468 }
2469 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2470 selection.end.buffer_id.and_then(|end_buffer_id| {
2471 if selection.start.buffer_id != Some(end_buffer_id) {
2472 return None;
2473 }
2474 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2475 let snapshot = buffer.read(cx).snapshot();
2476 self.linked_edit_ranges
2477 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2478 .map(|ranges| (ranges, snapshot, buffer))
2479 })?;
2480 use text::ToOffset as TO;
2481 // find offset from the start of current range to current cursor position
2482 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2483
2484 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2485 let start_difference = start_offset - start_byte_offset;
2486 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2487 let end_difference = end_offset - start_byte_offset;
2488 // Current range has associated linked ranges.
2489 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2490 for range in linked_ranges.iter() {
2491 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2492 let end_offset = start_offset + end_difference;
2493 let start_offset = start_offset + start_difference;
2494 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2495 continue;
2496 }
2497 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
2498 if s.start.buffer_id != selection.start.buffer_id
2499 || s.end.buffer_id != selection.end.buffer_id
2500 {
2501 return false;
2502 }
2503 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2504 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2505 }) {
2506 continue;
2507 }
2508 let start = buffer_snapshot.anchor_after(start_offset);
2509 let end = buffer_snapshot.anchor_after(end_offset);
2510 linked_edits
2511 .entry(buffer.clone())
2512 .or_default()
2513 .push(start..end);
2514 }
2515 Some(linked_edits)
2516 }
2517
2518 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2519 let text: Arc<str> = text.into();
2520
2521 if self.read_only(cx) {
2522 return;
2523 }
2524
2525 let selections = self.selections.all_adjusted(cx);
2526 let mut bracket_inserted = false;
2527 let mut edits = Vec::new();
2528 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2529 let mut new_selections = Vec::with_capacity(selections.len());
2530 let mut new_autoclose_regions = Vec::new();
2531 let snapshot = self.buffer.read(cx).read(cx);
2532
2533 for (selection, autoclose_region) in
2534 self.selections_with_autoclose_regions(selections, &snapshot)
2535 {
2536 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2537 // Determine if the inserted text matches the opening or closing
2538 // bracket of any of this language's bracket pairs.
2539 let mut bracket_pair = None;
2540 let mut is_bracket_pair_start = false;
2541 let mut is_bracket_pair_end = false;
2542 if !text.is_empty() {
2543 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2544 // and they are removing the character that triggered IME popup.
2545 for (pair, enabled) in scope.brackets() {
2546 if !pair.close && !pair.surround {
2547 continue;
2548 }
2549
2550 if enabled && pair.start.ends_with(text.as_ref()) {
2551 let prefix_len = pair.start.len() - text.len();
2552 let preceding_text_matches_prefix = prefix_len == 0
2553 || (selection.start.column >= (prefix_len as u32)
2554 && snapshot.contains_str_at(
2555 Point::new(
2556 selection.start.row,
2557 selection.start.column - (prefix_len as u32),
2558 ),
2559 &pair.start[..prefix_len],
2560 ));
2561 if preceding_text_matches_prefix {
2562 bracket_pair = Some(pair.clone());
2563 is_bracket_pair_start = true;
2564 break;
2565 }
2566 }
2567 if pair.end.as_str() == text.as_ref() {
2568 bracket_pair = Some(pair.clone());
2569 is_bracket_pair_end = true;
2570 break;
2571 }
2572 }
2573 }
2574
2575 if let Some(bracket_pair) = bracket_pair {
2576 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2577 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2578 let auto_surround =
2579 self.use_auto_surround && snapshot_settings.use_auto_surround;
2580 if selection.is_empty() {
2581 if is_bracket_pair_start {
2582 // If the inserted text is a suffix of an opening bracket and the
2583 // selection is preceded by the rest of the opening bracket, then
2584 // insert the closing bracket.
2585 let following_text_allows_autoclose = snapshot
2586 .chars_at(selection.start)
2587 .next()
2588 .map_or(true, |c| scope.should_autoclose_before(c));
2589
2590 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2591 && bracket_pair.start.len() == 1
2592 {
2593 let target = bracket_pair.start.chars().next().unwrap();
2594 let current_line_count = snapshot
2595 .reversed_chars_at(selection.start)
2596 .take_while(|&c| c != '\n')
2597 .filter(|&c| c == target)
2598 .count();
2599 current_line_count % 2 == 1
2600 } else {
2601 false
2602 };
2603
2604 if autoclose
2605 && bracket_pair.close
2606 && following_text_allows_autoclose
2607 && !is_closing_quote
2608 {
2609 let anchor = snapshot.anchor_before(selection.end);
2610 new_selections.push((selection.map(|_| anchor), text.len()));
2611 new_autoclose_regions.push((
2612 anchor,
2613 text.len(),
2614 selection.id,
2615 bracket_pair.clone(),
2616 ));
2617 edits.push((
2618 selection.range(),
2619 format!("{}{}", text, bracket_pair.end).into(),
2620 ));
2621 bracket_inserted = true;
2622 continue;
2623 }
2624 }
2625
2626 if let Some(region) = autoclose_region {
2627 // If the selection is followed by an auto-inserted closing bracket,
2628 // then don't insert that closing bracket again; just move the selection
2629 // past the closing bracket.
2630 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2631 && text.as_ref() == region.pair.end.as_str();
2632 if should_skip {
2633 let anchor = snapshot.anchor_after(selection.end);
2634 new_selections
2635 .push((selection.map(|_| anchor), region.pair.end.len()));
2636 continue;
2637 }
2638 }
2639
2640 let always_treat_brackets_as_autoclosed = snapshot
2641 .settings_at(selection.start, cx)
2642 .always_treat_brackets_as_autoclosed;
2643 if always_treat_brackets_as_autoclosed
2644 && is_bracket_pair_end
2645 && snapshot.contains_str_at(selection.end, text.as_ref())
2646 {
2647 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2648 // and the inserted text is a closing bracket and the selection is followed
2649 // by the closing bracket then move the selection past the closing bracket.
2650 let anchor = snapshot.anchor_after(selection.end);
2651 new_selections.push((selection.map(|_| anchor), text.len()));
2652 continue;
2653 }
2654 }
2655 // If an opening bracket is 1 character long and is typed while
2656 // text is selected, then surround that text with the bracket pair.
2657 else if auto_surround
2658 && bracket_pair.surround
2659 && is_bracket_pair_start
2660 && bracket_pair.start.chars().count() == 1
2661 {
2662 edits.push((selection.start..selection.start, text.clone()));
2663 edits.push((
2664 selection.end..selection.end,
2665 bracket_pair.end.as_str().into(),
2666 ));
2667 bracket_inserted = true;
2668 new_selections.push((
2669 Selection {
2670 id: selection.id,
2671 start: snapshot.anchor_after(selection.start),
2672 end: snapshot.anchor_before(selection.end),
2673 reversed: selection.reversed,
2674 goal: selection.goal,
2675 },
2676 0,
2677 ));
2678 continue;
2679 }
2680 }
2681 }
2682
2683 if self.auto_replace_emoji_shortcode
2684 && selection.is_empty()
2685 && text.as_ref().ends_with(':')
2686 {
2687 if let Some(possible_emoji_short_code) =
2688 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2689 {
2690 if !possible_emoji_short_code.is_empty() {
2691 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2692 let emoji_shortcode_start = Point::new(
2693 selection.start.row,
2694 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2695 );
2696
2697 // Remove shortcode from buffer
2698 edits.push((
2699 emoji_shortcode_start..selection.start,
2700 "".to_string().into(),
2701 ));
2702 new_selections.push((
2703 Selection {
2704 id: selection.id,
2705 start: snapshot.anchor_after(emoji_shortcode_start),
2706 end: snapshot.anchor_before(selection.start),
2707 reversed: selection.reversed,
2708 goal: selection.goal,
2709 },
2710 0,
2711 ));
2712
2713 // Insert emoji
2714 let selection_start_anchor = snapshot.anchor_after(selection.start);
2715 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2716 edits.push((selection.start..selection.end, emoji.to_string().into()));
2717
2718 continue;
2719 }
2720 }
2721 }
2722 }
2723
2724 // If not handling any auto-close operation, then just replace the selected
2725 // text with the given input and move the selection to the end of the
2726 // newly inserted text.
2727 let anchor = snapshot.anchor_after(selection.end);
2728 if !self.linked_edit_ranges.is_empty() {
2729 let start_anchor = snapshot.anchor_before(selection.start);
2730
2731 let is_word_char = text.chars().next().map_or(true, |char| {
2732 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2733 classifier.is_word(char)
2734 });
2735
2736 if is_word_char {
2737 if let Some(ranges) = self
2738 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2739 {
2740 for (buffer, edits) in ranges {
2741 linked_edits
2742 .entry(buffer.clone())
2743 .or_default()
2744 .extend(edits.into_iter().map(|range| (range, text.clone())));
2745 }
2746 }
2747 }
2748 }
2749
2750 new_selections.push((selection.map(|_| anchor), 0));
2751 edits.push((selection.start..selection.end, text.clone()));
2752 }
2753
2754 drop(snapshot);
2755
2756 self.transact(cx, |this, cx| {
2757 this.buffer.update(cx, |buffer, cx| {
2758 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2759 });
2760 for (buffer, edits) in linked_edits {
2761 buffer.update(cx, |buffer, cx| {
2762 let snapshot = buffer.snapshot();
2763 let edits = edits
2764 .into_iter()
2765 .map(|(range, text)| {
2766 use text::ToPoint as TP;
2767 let end_point = TP::to_point(&range.end, &snapshot);
2768 let start_point = TP::to_point(&range.start, &snapshot);
2769 (start_point..end_point, text)
2770 })
2771 .sorted_by_key(|(range, _)| range.start)
2772 .collect::<Vec<_>>();
2773 buffer.edit(edits, None, cx);
2774 })
2775 }
2776 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2777 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2778 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2779 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2780 .zip(new_selection_deltas)
2781 .map(|(selection, delta)| Selection {
2782 id: selection.id,
2783 start: selection.start + delta,
2784 end: selection.end + delta,
2785 reversed: selection.reversed,
2786 goal: SelectionGoal::None,
2787 })
2788 .collect::<Vec<_>>();
2789
2790 let mut i = 0;
2791 for (position, delta, selection_id, pair) in new_autoclose_regions {
2792 let position = position.to_offset(&map.buffer_snapshot) + delta;
2793 let start = map.buffer_snapshot.anchor_before(position);
2794 let end = map.buffer_snapshot.anchor_after(position);
2795 while let Some(existing_state) = this.autoclose_regions.get(i) {
2796 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2797 Ordering::Less => i += 1,
2798 Ordering::Greater => break,
2799 Ordering::Equal => {
2800 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2801 Ordering::Less => i += 1,
2802 Ordering::Equal => break,
2803 Ordering::Greater => break,
2804 }
2805 }
2806 }
2807 }
2808 this.autoclose_regions.insert(
2809 i,
2810 AutocloseRegion {
2811 selection_id,
2812 range: start..end,
2813 pair,
2814 },
2815 );
2816 }
2817
2818 let had_active_inline_completion = this.has_active_inline_completion();
2819 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
2820 s.select(new_selections)
2821 });
2822
2823 if !bracket_inserted {
2824 if let Some(on_type_format_task) =
2825 this.trigger_on_type_formatting(text.to_string(), cx)
2826 {
2827 on_type_format_task.detach_and_log_err(cx);
2828 }
2829 }
2830
2831 let editor_settings = EditorSettings::get_global(cx);
2832 if bracket_inserted
2833 && (editor_settings.auto_signature_help
2834 || editor_settings.show_signature_help_after_edits)
2835 {
2836 this.show_signature_help(&ShowSignatureHelp, cx);
2837 }
2838
2839 let trigger_in_words = !had_active_inline_completion;
2840 this.trigger_completion_on_input(&text, trigger_in_words, cx);
2841 linked_editing_ranges::refresh_linked_ranges(this, cx);
2842 this.refresh_inline_completion(true, false, cx);
2843 });
2844 }
2845
2846 fn find_possible_emoji_shortcode_at_position(
2847 snapshot: &MultiBufferSnapshot,
2848 position: Point,
2849 ) -> Option<String> {
2850 let mut chars = Vec::new();
2851 let mut found_colon = false;
2852 for char in snapshot.reversed_chars_at(position).take(100) {
2853 // Found a possible emoji shortcode in the middle of the buffer
2854 if found_colon {
2855 if char.is_whitespace() {
2856 chars.reverse();
2857 return Some(chars.iter().collect());
2858 }
2859 // If the previous character is not a whitespace, we are in the middle of a word
2860 // and we only want to complete the shortcode if the word is made up of other emojis
2861 let mut containing_word = String::new();
2862 for ch in snapshot
2863 .reversed_chars_at(position)
2864 .skip(chars.len() + 1)
2865 .take(100)
2866 {
2867 if ch.is_whitespace() {
2868 break;
2869 }
2870 containing_word.push(ch);
2871 }
2872 let containing_word = containing_word.chars().rev().collect::<String>();
2873 if util::word_consists_of_emojis(containing_word.as_str()) {
2874 chars.reverse();
2875 return Some(chars.iter().collect());
2876 }
2877 }
2878
2879 if char.is_whitespace() || !char.is_ascii() {
2880 return None;
2881 }
2882 if char == ':' {
2883 found_colon = true;
2884 } else {
2885 chars.push(char);
2886 }
2887 }
2888 // Found a possible emoji shortcode at the beginning of the buffer
2889 chars.reverse();
2890 Some(chars.iter().collect())
2891 }
2892
2893 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2894 self.transact(cx, |this, cx| {
2895 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2896 let selections = this.selections.all::<usize>(cx);
2897 let multi_buffer = this.buffer.read(cx);
2898 let buffer = multi_buffer.snapshot(cx);
2899 selections
2900 .iter()
2901 .map(|selection| {
2902 let start_point = selection.start.to_point(&buffer);
2903 let mut indent =
2904 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
2905 indent.len = cmp::min(indent.len, start_point.column);
2906 let start = selection.start;
2907 let end = selection.end;
2908 let selection_is_empty = start == end;
2909 let language_scope = buffer.language_scope_at(start);
2910 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
2911 &language_scope
2912 {
2913 let leading_whitespace_len = buffer
2914 .reversed_chars_at(start)
2915 .take_while(|c| c.is_whitespace() && *c != '\n')
2916 .map(|c| c.len_utf8())
2917 .sum::<usize>();
2918
2919 let trailing_whitespace_len = buffer
2920 .chars_at(end)
2921 .take_while(|c| c.is_whitespace() && *c != '\n')
2922 .map(|c| c.len_utf8())
2923 .sum::<usize>();
2924
2925 let insert_extra_newline =
2926 language.brackets().any(|(pair, enabled)| {
2927 let pair_start = pair.start.trim_end();
2928 let pair_end = pair.end.trim_start();
2929
2930 enabled
2931 && pair.newline
2932 && buffer.contains_str_at(
2933 end + trailing_whitespace_len,
2934 pair_end,
2935 )
2936 && buffer.contains_str_at(
2937 (start - leading_whitespace_len)
2938 .saturating_sub(pair_start.len()),
2939 pair_start,
2940 )
2941 });
2942
2943 // Comment extension on newline is allowed only for cursor selections
2944 let comment_delimiter = maybe!({
2945 if !selection_is_empty {
2946 return None;
2947 }
2948
2949 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
2950 return None;
2951 }
2952
2953 let delimiters = language.line_comment_prefixes();
2954 let max_len_of_delimiter =
2955 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
2956 let (snapshot, range) =
2957 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
2958
2959 let mut index_of_first_non_whitespace = 0;
2960 let comment_candidate = snapshot
2961 .chars_for_range(range)
2962 .skip_while(|c| {
2963 let should_skip = c.is_whitespace();
2964 if should_skip {
2965 index_of_first_non_whitespace += 1;
2966 }
2967 should_skip
2968 })
2969 .take(max_len_of_delimiter)
2970 .collect::<String>();
2971 let comment_prefix = delimiters.iter().find(|comment_prefix| {
2972 comment_candidate.starts_with(comment_prefix.as_ref())
2973 })?;
2974 let cursor_is_placed_after_comment_marker =
2975 index_of_first_non_whitespace + comment_prefix.len()
2976 <= start_point.column as usize;
2977 if cursor_is_placed_after_comment_marker {
2978 Some(comment_prefix.clone())
2979 } else {
2980 None
2981 }
2982 });
2983 (comment_delimiter, insert_extra_newline)
2984 } else {
2985 (None, false)
2986 };
2987
2988 let capacity_for_delimiter = comment_delimiter
2989 .as_deref()
2990 .map(str::len)
2991 .unwrap_or_default();
2992 let mut new_text =
2993 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
2994 new_text.push('\n');
2995 new_text.extend(indent.chars());
2996 if let Some(delimiter) = &comment_delimiter {
2997 new_text.push_str(delimiter);
2998 }
2999 if insert_extra_newline {
3000 new_text = new_text.repeat(2);
3001 }
3002
3003 let anchor = buffer.anchor_after(end);
3004 let new_selection = selection.map(|_| anchor);
3005 (
3006 (start..end, new_text),
3007 (insert_extra_newline, new_selection),
3008 )
3009 })
3010 .unzip()
3011 };
3012
3013 this.edit_with_autoindent(edits, cx);
3014 let buffer = this.buffer.read(cx).snapshot(cx);
3015 let new_selections = selection_fixup_info
3016 .into_iter()
3017 .map(|(extra_newline_inserted, new_selection)| {
3018 let mut cursor = new_selection.end.to_point(&buffer);
3019 if extra_newline_inserted {
3020 cursor.row -= 1;
3021 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3022 }
3023 new_selection.map(|_| cursor)
3024 })
3025 .collect();
3026
3027 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3028 this.refresh_inline_completion(true, false, cx);
3029 });
3030 }
3031
3032 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3033 let buffer = self.buffer.read(cx);
3034 let snapshot = buffer.snapshot(cx);
3035
3036 let mut edits = Vec::new();
3037 let mut rows = Vec::new();
3038
3039 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3040 let cursor = selection.head();
3041 let row = cursor.row;
3042
3043 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3044
3045 let newline = "\n".to_string();
3046 edits.push((start_of_line..start_of_line, newline));
3047
3048 rows.push(row + rows_inserted as u32);
3049 }
3050
3051 self.transact(cx, |editor, cx| {
3052 editor.edit(edits, cx);
3053
3054 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3055 let mut index = 0;
3056 s.move_cursors_with(|map, _, _| {
3057 let row = rows[index];
3058 index += 1;
3059
3060 let point = Point::new(row, 0);
3061 let boundary = map.next_line_boundary(point).1;
3062 let clipped = map.clip_point(boundary, Bias::Left);
3063
3064 (clipped, SelectionGoal::None)
3065 });
3066 });
3067
3068 let mut indent_edits = Vec::new();
3069 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3070 for row in rows {
3071 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3072 for (row, indent) in indents {
3073 if indent.len == 0 {
3074 continue;
3075 }
3076
3077 let text = match indent.kind {
3078 IndentKind::Space => " ".repeat(indent.len as usize),
3079 IndentKind::Tab => "\t".repeat(indent.len as usize),
3080 };
3081 let point = Point::new(row.0, 0);
3082 indent_edits.push((point..point, text));
3083 }
3084 }
3085 editor.edit(indent_edits, cx);
3086 });
3087 }
3088
3089 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3090 let buffer = self.buffer.read(cx);
3091 let snapshot = buffer.snapshot(cx);
3092
3093 let mut edits = Vec::new();
3094 let mut rows = Vec::new();
3095 let mut rows_inserted = 0;
3096
3097 for selection in self.selections.all_adjusted(cx) {
3098 let cursor = selection.head();
3099 let row = cursor.row;
3100
3101 let point = Point::new(row + 1, 0);
3102 let start_of_line = snapshot.clip_point(point, Bias::Left);
3103
3104 let newline = "\n".to_string();
3105 edits.push((start_of_line..start_of_line, newline));
3106
3107 rows_inserted += 1;
3108 rows.push(row + rows_inserted);
3109 }
3110
3111 self.transact(cx, |editor, cx| {
3112 editor.edit(edits, cx);
3113
3114 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3115 let mut index = 0;
3116 s.move_cursors_with(|map, _, _| {
3117 let row = rows[index];
3118 index += 1;
3119
3120 let point = Point::new(row, 0);
3121 let boundary = map.next_line_boundary(point).1;
3122 let clipped = map.clip_point(boundary, Bias::Left);
3123
3124 (clipped, SelectionGoal::None)
3125 });
3126 });
3127
3128 let mut indent_edits = Vec::new();
3129 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3130 for row in rows {
3131 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3132 for (row, indent) in indents {
3133 if indent.len == 0 {
3134 continue;
3135 }
3136
3137 let text = match indent.kind {
3138 IndentKind::Space => " ".repeat(indent.len as usize),
3139 IndentKind::Tab => "\t".repeat(indent.len as usize),
3140 };
3141 let point = Point::new(row.0, 0);
3142 indent_edits.push((point..point, text));
3143 }
3144 }
3145 editor.edit(indent_edits, cx);
3146 });
3147 }
3148
3149 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3150 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3151 original_indent_columns: Vec::new(),
3152 });
3153 self.insert_with_autoindent_mode(text, autoindent, cx);
3154 }
3155
3156 fn insert_with_autoindent_mode(
3157 &mut self,
3158 text: &str,
3159 autoindent_mode: Option<AutoindentMode>,
3160 cx: &mut ViewContext<Self>,
3161 ) {
3162 if self.read_only(cx) {
3163 return;
3164 }
3165
3166 let text: Arc<str> = text.into();
3167 self.transact(cx, |this, cx| {
3168 let old_selections = this.selections.all_adjusted(cx);
3169 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3170 let anchors = {
3171 let snapshot = buffer.read(cx);
3172 old_selections
3173 .iter()
3174 .map(|s| {
3175 let anchor = snapshot.anchor_after(s.head());
3176 s.map(|_| anchor)
3177 })
3178 .collect::<Vec<_>>()
3179 };
3180 buffer.edit(
3181 old_selections
3182 .iter()
3183 .map(|s| (s.start..s.end, text.clone())),
3184 autoindent_mode,
3185 cx,
3186 );
3187 anchors
3188 });
3189
3190 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3191 s.select_anchors(selection_anchors);
3192 })
3193 });
3194 }
3195
3196 fn trigger_completion_on_input(
3197 &mut self,
3198 text: &str,
3199 trigger_in_words: bool,
3200 cx: &mut ViewContext<Self>,
3201 ) {
3202 if self.is_completion_trigger(text, trigger_in_words, cx) {
3203 self.show_completions(
3204 &ShowCompletions {
3205 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3206 },
3207 cx,
3208 );
3209 } else {
3210 self.hide_context_menu(cx);
3211 }
3212 }
3213
3214 fn is_completion_trigger(
3215 &self,
3216 text: &str,
3217 trigger_in_words: bool,
3218 cx: &mut ViewContext<Self>,
3219 ) -> bool {
3220 let position = self.selections.newest_anchor().head();
3221 let multibuffer = self.buffer.read(cx);
3222 let Some(buffer) = position
3223 .buffer_id
3224 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3225 else {
3226 return false;
3227 };
3228
3229 if let Some(completion_provider) = &self.completion_provider {
3230 completion_provider.is_completion_trigger(
3231 &buffer,
3232 position.text_anchor,
3233 text,
3234 trigger_in_words,
3235 cx,
3236 )
3237 } else {
3238 false
3239 }
3240 }
3241
3242 /// If any empty selections is touching the start of its innermost containing autoclose
3243 /// region, expand it to select the brackets.
3244 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3245 let selections = self.selections.all::<usize>(cx);
3246 let buffer = self.buffer.read(cx).read(cx);
3247 let new_selections = self
3248 .selections_with_autoclose_regions(selections, &buffer)
3249 .map(|(mut selection, region)| {
3250 if !selection.is_empty() {
3251 return selection;
3252 }
3253
3254 if let Some(region) = region {
3255 let mut range = region.range.to_offset(&buffer);
3256 if selection.start == range.start && range.start >= region.pair.start.len() {
3257 range.start -= region.pair.start.len();
3258 if buffer.contains_str_at(range.start, ®ion.pair.start)
3259 && buffer.contains_str_at(range.end, ®ion.pair.end)
3260 {
3261 range.end += region.pair.end.len();
3262 selection.start = range.start;
3263 selection.end = range.end;
3264
3265 return selection;
3266 }
3267 }
3268 }
3269
3270 let always_treat_brackets_as_autoclosed = buffer
3271 .settings_at(selection.start, cx)
3272 .always_treat_brackets_as_autoclosed;
3273
3274 if !always_treat_brackets_as_autoclosed {
3275 return selection;
3276 }
3277
3278 if let Some(scope) = buffer.language_scope_at(selection.start) {
3279 for (pair, enabled) in scope.brackets() {
3280 if !enabled || !pair.close {
3281 continue;
3282 }
3283
3284 if buffer.contains_str_at(selection.start, &pair.end) {
3285 let pair_start_len = pair.start.len();
3286 if buffer.contains_str_at(
3287 selection.start.saturating_sub(pair_start_len),
3288 &pair.start,
3289 ) {
3290 selection.start -= pair_start_len;
3291 selection.end += pair.end.len();
3292
3293 return selection;
3294 }
3295 }
3296 }
3297 }
3298
3299 selection
3300 })
3301 .collect();
3302
3303 drop(buffer);
3304 self.change_selections(None, cx, |selections| selections.select(new_selections));
3305 }
3306
3307 /// Iterate the given selections, and for each one, find the smallest surrounding
3308 /// autoclose region. This uses the ordering of the selections and the autoclose
3309 /// regions to avoid repeated comparisons.
3310 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3311 &'a self,
3312 selections: impl IntoIterator<Item = Selection<D>>,
3313 buffer: &'a MultiBufferSnapshot,
3314 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3315 let mut i = 0;
3316 let mut regions = self.autoclose_regions.as_slice();
3317 selections.into_iter().map(move |selection| {
3318 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3319
3320 let mut enclosing = None;
3321 while let Some(pair_state) = regions.get(i) {
3322 if pair_state.range.end.to_offset(buffer) < range.start {
3323 regions = ®ions[i + 1..];
3324 i = 0;
3325 } else if pair_state.range.start.to_offset(buffer) > range.end {
3326 break;
3327 } else {
3328 if pair_state.selection_id == selection.id {
3329 enclosing = Some(pair_state);
3330 }
3331 i += 1;
3332 }
3333 }
3334
3335 (selection, enclosing)
3336 })
3337 }
3338
3339 /// Remove any autoclose regions that no longer contain their selection.
3340 fn invalidate_autoclose_regions(
3341 &mut self,
3342 mut selections: &[Selection<Anchor>],
3343 buffer: &MultiBufferSnapshot,
3344 ) {
3345 self.autoclose_regions.retain(|state| {
3346 let mut i = 0;
3347 while let Some(selection) = selections.get(i) {
3348 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3349 selections = &selections[1..];
3350 continue;
3351 }
3352 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3353 break;
3354 }
3355 if selection.id == state.selection_id {
3356 return true;
3357 } else {
3358 i += 1;
3359 }
3360 }
3361 false
3362 });
3363 }
3364
3365 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3366 let offset = position.to_offset(buffer);
3367 let (word_range, kind) = buffer.surrounding_word(offset, true);
3368 if offset > word_range.start && kind == Some(CharKind::Word) {
3369 Some(
3370 buffer
3371 .text_for_range(word_range.start..offset)
3372 .collect::<String>(),
3373 )
3374 } else {
3375 None
3376 }
3377 }
3378
3379 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3380 self.refresh_inlay_hints(
3381 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3382 cx,
3383 );
3384 }
3385
3386 pub fn inlay_hints_enabled(&self) -> bool {
3387 self.inlay_hint_cache.enabled
3388 }
3389
3390 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3391 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3392 return;
3393 }
3394
3395 let reason_description = reason.description();
3396 let ignore_debounce = matches!(
3397 reason,
3398 InlayHintRefreshReason::SettingsChange(_)
3399 | InlayHintRefreshReason::Toggle(_)
3400 | InlayHintRefreshReason::ExcerptsRemoved(_)
3401 );
3402 let (invalidate_cache, required_languages) = match reason {
3403 InlayHintRefreshReason::Toggle(enabled) => {
3404 self.inlay_hint_cache.enabled = enabled;
3405 if enabled {
3406 (InvalidationStrategy::RefreshRequested, None)
3407 } else {
3408 self.inlay_hint_cache.clear();
3409 self.splice_inlays(
3410 self.visible_inlay_hints(cx)
3411 .iter()
3412 .map(|inlay| inlay.id)
3413 .collect(),
3414 Vec::new(),
3415 cx,
3416 );
3417 return;
3418 }
3419 }
3420 InlayHintRefreshReason::SettingsChange(new_settings) => {
3421 match self.inlay_hint_cache.update_settings(
3422 &self.buffer,
3423 new_settings,
3424 self.visible_inlay_hints(cx),
3425 cx,
3426 ) {
3427 ControlFlow::Break(Some(InlaySplice {
3428 to_remove,
3429 to_insert,
3430 })) => {
3431 self.splice_inlays(to_remove, to_insert, cx);
3432 return;
3433 }
3434 ControlFlow::Break(None) => return,
3435 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3436 }
3437 }
3438 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3439 if let Some(InlaySplice {
3440 to_remove,
3441 to_insert,
3442 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3443 {
3444 self.splice_inlays(to_remove, to_insert, cx);
3445 }
3446 return;
3447 }
3448 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3449 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3450 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3451 }
3452 InlayHintRefreshReason::RefreshRequested => {
3453 (InvalidationStrategy::RefreshRequested, None)
3454 }
3455 };
3456
3457 if let Some(InlaySplice {
3458 to_remove,
3459 to_insert,
3460 }) = self.inlay_hint_cache.spawn_hint_refresh(
3461 reason_description,
3462 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3463 invalidate_cache,
3464 ignore_debounce,
3465 cx,
3466 ) {
3467 self.splice_inlays(to_remove, to_insert, cx);
3468 }
3469 }
3470
3471 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
3472 self.display_map
3473 .read(cx)
3474 .current_inlays()
3475 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3476 .cloned()
3477 .collect()
3478 }
3479
3480 pub fn excerpts_for_inlay_hints_query(
3481 &self,
3482 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3483 cx: &mut ViewContext<Editor>,
3484 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3485 let Some(project) = self.project.as_ref() else {
3486 return HashMap::default();
3487 };
3488 let project = project.read(cx);
3489 let multi_buffer = self.buffer().read(cx);
3490 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3491 let multi_buffer_visible_start = self
3492 .scroll_manager
3493 .anchor()
3494 .anchor
3495 .to_point(&multi_buffer_snapshot);
3496 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3497 multi_buffer_visible_start
3498 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3499 Bias::Left,
3500 );
3501 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3502 multi_buffer
3503 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
3504 .into_iter()
3505 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3506 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
3507 let buffer = buffer_handle.read(cx);
3508 let buffer_file = project::File::from_dyn(buffer.file())?;
3509 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3510 let worktree_entry = buffer_worktree
3511 .read(cx)
3512 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3513 if worktree_entry.is_ignored {
3514 return None;
3515 }
3516
3517 let language = buffer.language()?;
3518 if let Some(restrict_to_languages) = restrict_to_languages {
3519 if !restrict_to_languages.contains(language) {
3520 return None;
3521 }
3522 }
3523 Some((
3524 excerpt_id,
3525 (
3526 buffer_handle,
3527 buffer.version().clone(),
3528 excerpt_visible_range,
3529 ),
3530 ))
3531 })
3532 .collect()
3533 }
3534
3535 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3536 TextLayoutDetails {
3537 text_system: cx.text_system().clone(),
3538 editor_style: self.style.clone().unwrap(),
3539 rem_size: cx.rem_size(),
3540 scroll_anchor: self.scroll_manager.anchor(),
3541 visible_rows: self.visible_line_count(),
3542 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3543 }
3544 }
3545
3546 fn splice_inlays(
3547 &self,
3548 to_remove: Vec<InlayId>,
3549 to_insert: Vec<Inlay>,
3550 cx: &mut ViewContext<Self>,
3551 ) {
3552 self.display_map.update(cx, |display_map, cx| {
3553 display_map.splice_inlays(to_remove, to_insert, cx)
3554 });
3555 cx.notify();
3556 }
3557
3558 fn trigger_on_type_formatting(
3559 &self,
3560 input: String,
3561 cx: &mut ViewContext<Self>,
3562 ) -> Option<Task<Result<()>>> {
3563 if input.len() != 1 {
3564 return None;
3565 }
3566
3567 let project = self.project.as_ref()?;
3568 let position = self.selections.newest_anchor().head();
3569 let (buffer, buffer_position) = self
3570 .buffer
3571 .read(cx)
3572 .text_anchor_for_position(position, cx)?;
3573
3574 let settings = language_settings::language_settings(
3575 buffer
3576 .read(cx)
3577 .language_at(buffer_position)
3578 .map(|l| l.name()),
3579 buffer.read(cx).file(),
3580 cx,
3581 );
3582 if !settings.use_on_type_format {
3583 return None;
3584 }
3585
3586 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3587 // hence we do LSP request & edit on host side only — add formats to host's history.
3588 let push_to_lsp_host_history = true;
3589 // If this is not the host, append its history with new edits.
3590 let push_to_client_history = project.read(cx).is_via_collab();
3591
3592 let on_type_formatting = project.update(cx, |project, cx| {
3593 project.on_type_format(
3594 buffer.clone(),
3595 buffer_position,
3596 input,
3597 push_to_lsp_host_history,
3598 cx,
3599 )
3600 });
3601 Some(cx.spawn(|editor, mut cx| async move {
3602 if let Some(transaction) = on_type_formatting.await? {
3603 if push_to_client_history {
3604 buffer
3605 .update(&mut cx, |buffer, _| {
3606 buffer.push_transaction(transaction, Instant::now());
3607 })
3608 .ok();
3609 }
3610 editor.update(&mut cx, |editor, cx| {
3611 editor.refresh_document_highlights(cx);
3612 })?;
3613 }
3614 Ok(())
3615 }))
3616 }
3617
3618 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
3619 if self.pending_rename.is_some() {
3620 return;
3621 }
3622
3623 let Some(provider) = self.completion_provider.as_ref() else {
3624 return;
3625 };
3626
3627 if !self.snippet_stack.is_empty() && self.context_menu.read().as_ref().is_some() {
3628 return;
3629 }
3630
3631 let position = self.selections.newest_anchor().head();
3632 let (buffer, buffer_position) =
3633 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3634 output
3635 } else {
3636 return;
3637 };
3638 let show_completion_documentation = buffer
3639 .read(cx)
3640 .snapshot()
3641 .settings_at(buffer_position, cx)
3642 .show_completion_documentation;
3643
3644 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3645
3646 let aside_was_displayed = match self.context_menu.read().deref() {
3647 Some(CodeContextMenu::Completions(menu)) => menu.aside_was_displayed.get(),
3648 _ => false,
3649 };
3650 let trigger_kind = match &options.trigger {
3651 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3652 CompletionTriggerKind::TRIGGER_CHARACTER
3653 }
3654 _ => CompletionTriggerKind::INVOKED,
3655 };
3656 let completion_context = CompletionContext {
3657 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3658 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3659 Some(String::from(trigger))
3660 } else {
3661 None
3662 }
3663 }),
3664 trigger_kind,
3665 };
3666 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
3667 let sort_completions = provider.sort_completions();
3668
3669 let id = post_inc(&mut self.next_completion_id);
3670 let task = cx.spawn(|editor, mut cx| {
3671 async move {
3672 editor.update(&mut cx, |this, _| {
3673 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3674 })?;
3675 let completions = completions.await.log_err();
3676 let menu = if let Some(completions) = completions {
3677 let mut menu = CompletionsMenu::new(
3678 id,
3679 sort_completions,
3680 show_completion_documentation,
3681 position,
3682 buffer.clone(),
3683 completions.into(),
3684 aside_was_displayed,
3685 );
3686 menu.filter(query.as_deref(), cx.background_executor().clone())
3687 .await;
3688
3689 if menu.matches.is_empty() {
3690 None
3691 } else {
3692 Some(menu)
3693 }
3694 } else {
3695 None
3696 };
3697
3698 editor.update(&mut cx, |editor, cx| {
3699 let mut context_menu = editor.context_menu.write();
3700 match context_menu.as_ref() {
3701 None => {}
3702
3703 Some(CodeContextMenu::Completions(prev_menu)) => {
3704 if prev_menu.id > id {
3705 return;
3706 }
3707 }
3708
3709 _ => return,
3710 }
3711
3712 if editor.focus_handle.is_focused(cx) && menu.is_some() {
3713 let mut menu = menu.unwrap();
3714 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3715 *context_menu = Some(CodeContextMenu::Completions(menu));
3716 drop(context_menu);
3717 cx.notify();
3718 } else if editor.completion_tasks.len() <= 1 {
3719 // If there are no more completion tasks and the last menu was
3720 // empty, we should hide it. If it was already hidden, we should
3721 // also show the copilot completion when available.
3722 drop(context_menu);
3723 editor.hide_context_menu(cx);
3724 }
3725 })?;
3726
3727 Ok::<_, anyhow::Error>(())
3728 }
3729 .log_err()
3730 });
3731
3732 self.completion_tasks.push((id, task));
3733 }
3734
3735 pub fn confirm_completion(
3736 &mut self,
3737 action: &ConfirmCompletion,
3738 cx: &mut ViewContext<Self>,
3739 ) -> Option<Task<Result<()>>> {
3740 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
3741 }
3742
3743 pub fn compose_completion(
3744 &mut self,
3745 action: &ComposeCompletion,
3746 cx: &mut ViewContext<Self>,
3747 ) -> Option<Task<Result<()>>> {
3748 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
3749 }
3750
3751 fn do_completion(
3752 &mut self,
3753 item_ix: Option<usize>,
3754 intent: CompletionIntent,
3755 cx: &mut ViewContext<Editor>,
3756 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3757 use language::ToOffset as _;
3758
3759 self.discard_inline_completion(true, cx);
3760 let completions_menu =
3761 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3762 menu
3763 } else {
3764 return None;
3765 };
3766
3767 let mat = completions_menu
3768 .matches
3769 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
3770 let buffer_handle = completions_menu.buffer;
3771 let completions = completions_menu.completions.read();
3772 let completion = completions.get(mat.candidate_id)?;
3773 cx.stop_propagation();
3774
3775 let snippet;
3776 let text;
3777
3778 if completion.is_snippet() {
3779 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3780 text = snippet.as_ref().unwrap().text.clone();
3781 } else {
3782 snippet = None;
3783 text = completion.new_text.clone();
3784 };
3785 let selections = self.selections.all::<usize>(cx);
3786 let buffer = buffer_handle.read(cx);
3787 let old_range = completion.old_range.to_offset(buffer);
3788 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3789
3790 let newest_selection = self.selections.newest_anchor();
3791 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3792 return None;
3793 }
3794
3795 let lookbehind = newest_selection
3796 .start
3797 .text_anchor
3798 .to_offset(buffer)
3799 .saturating_sub(old_range.start);
3800 let lookahead = old_range
3801 .end
3802 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3803 let mut common_prefix_len = old_text
3804 .bytes()
3805 .zip(text.bytes())
3806 .take_while(|(a, b)| a == b)
3807 .count();
3808
3809 let snapshot = self.buffer.read(cx).snapshot(cx);
3810 let mut range_to_replace: Option<Range<isize>> = None;
3811 let mut ranges = Vec::new();
3812 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3813 for selection in &selections {
3814 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3815 let start = selection.start.saturating_sub(lookbehind);
3816 let end = selection.end + lookahead;
3817 if selection.id == newest_selection.id {
3818 range_to_replace = Some(
3819 ((start + common_prefix_len) as isize - selection.start as isize)
3820 ..(end as isize - selection.start as isize),
3821 );
3822 }
3823 ranges.push(start + common_prefix_len..end);
3824 } else {
3825 common_prefix_len = 0;
3826 ranges.clear();
3827 ranges.extend(selections.iter().map(|s| {
3828 if s.id == newest_selection.id {
3829 range_to_replace = Some(
3830 old_range.start.to_offset_utf16(&snapshot).0 as isize
3831 - selection.start as isize
3832 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3833 - selection.start as isize,
3834 );
3835 old_range.clone()
3836 } else {
3837 s.start..s.end
3838 }
3839 }));
3840 break;
3841 }
3842 if !self.linked_edit_ranges.is_empty() {
3843 let start_anchor = snapshot.anchor_before(selection.head());
3844 let end_anchor = snapshot.anchor_after(selection.tail());
3845 if let Some(ranges) = self
3846 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
3847 {
3848 for (buffer, edits) in ranges {
3849 linked_edits.entry(buffer.clone()).or_default().extend(
3850 edits
3851 .into_iter()
3852 .map(|range| (range, text[common_prefix_len..].to_owned())),
3853 );
3854 }
3855 }
3856 }
3857 }
3858 let text = &text[common_prefix_len..];
3859
3860 cx.emit(EditorEvent::InputHandled {
3861 utf16_range_to_replace: range_to_replace,
3862 text: text.into(),
3863 });
3864
3865 self.transact(cx, |this, cx| {
3866 if let Some(mut snippet) = snippet {
3867 snippet.text = text.to_string();
3868 for tabstop in snippet
3869 .tabstops
3870 .iter_mut()
3871 .flat_map(|tabstop| tabstop.ranges.iter_mut())
3872 {
3873 tabstop.start -= common_prefix_len as isize;
3874 tabstop.end -= common_prefix_len as isize;
3875 }
3876
3877 this.insert_snippet(&ranges, snippet, cx).log_err();
3878 } else {
3879 this.buffer.update(cx, |buffer, cx| {
3880 buffer.edit(
3881 ranges.iter().map(|range| (range.clone(), text)),
3882 this.autoindent_mode.clone(),
3883 cx,
3884 );
3885 });
3886 }
3887 for (buffer, edits) in linked_edits {
3888 buffer.update(cx, |buffer, cx| {
3889 let snapshot = buffer.snapshot();
3890 let edits = edits
3891 .into_iter()
3892 .map(|(range, text)| {
3893 use text::ToPoint as TP;
3894 let end_point = TP::to_point(&range.end, &snapshot);
3895 let start_point = TP::to_point(&range.start, &snapshot);
3896 (start_point..end_point, text)
3897 })
3898 .sorted_by_key(|(range, _)| range.start)
3899 .collect::<Vec<_>>();
3900 buffer.edit(edits, None, cx);
3901 })
3902 }
3903
3904 this.refresh_inline_completion(true, false, cx);
3905 });
3906
3907 let show_new_completions_on_confirm = completion
3908 .confirm
3909 .as_ref()
3910 .map_or(false, |confirm| confirm(intent, cx));
3911 if show_new_completions_on_confirm {
3912 self.show_completions(&ShowCompletions { trigger: None }, cx);
3913 }
3914
3915 let provider = self.completion_provider.as_ref()?;
3916 let apply_edits = provider.apply_additional_edits_for_completion(
3917 buffer_handle,
3918 completion.clone(),
3919 true,
3920 cx,
3921 );
3922
3923 let editor_settings = EditorSettings::get_global(cx);
3924 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
3925 // After the code completion is finished, users often want to know what signatures are needed.
3926 // so we should automatically call signature_help
3927 self.show_signature_help(&ShowSignatureHelp, cx);
3928 }
3929
3930 Some(cx.foreground_executor().spawn(async move {
3931 apply_edits.await?;
3932 Ok(())
3933 }))
3934 }
3935
3936 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
3937 let mut context_menu = self.context_menu.write();
3938 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
3939 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
3940 // Toggle if we're selecting the same one
3941 *context_menu = None;
3942 cx.notify();
3943 return;
3944 } else {
3945 // Otherwise, clear it and start a new one
3946 *context_menu = None;
3947 cx.notify();
3948 }
3949 }
3950 drop(context_menu);
3951 let snapshot = self.snapshot(cx);
3952 let deployed_from_indicator = action.deployed_from_indicator;
3953 let mut task = self.code_actions_task.take();
3954 let action = action.clone();
3955 cx.spawn(|editor, mut cx| async move {
3956 while let Some(prev_task) = task {
3957 prev_task.await.log_err();
3958 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
3959 }
3960
3961 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
3962 if editor.focus_handle.is_focused(cx) {
3963 let multibuffer_point = action
3964 .deployed_from_indicator
3965 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
3966 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
3967 let (buffer, buffer_row) = snapshot
3968 .buffer_snapshot
3969 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
3970 .and_then(|(buffer_snapshot, range)| {
3971 editor
3972 .buffer
3973 .read(cx)
3974 .buffer(buffer_snapshot.remote_id())
3975 .map(|buffer| (buffer, range.start.row))
3976 })?;
3977 let (_, code_actions) = editor
3978 .available_code_actions
3979 .clone()
3980 .and_then(|(location, code_actions)| {
3981 let snapshot = location.buffer.read(cx).snapshot();
3982 let point_range = location.range.to_point(&snapshot);
3983 let point_range = point_range.start.row..=point_range.end.row;
3984 if point_range.contains(&buffer_row) {
3985 Some((location, code_actions))
3986 } else {
3987 None
3988 }
3989 })
3990 .unzip();
3991 let buffer_id = buffer.read(cx).remote_id();
3992 let tasks = editor
3993 .tasks
3994 .get(&(buffer_id, buffer_row))
3995 .map(|t| Arc::new(t.to_owned()));
3996 if tasks.is_none() && code_actions.is_none() {
3997 return None;
3998 }
3999
4000 editor.completion_tasks.clear();
4001 editor.discard_inline_completion(false, cx);
4002 let task_context =
4003 tasks
4004 .as_ref()
4005 .zip(editor.project.clone())
4006 .map(|(tasks, project)| {
4007 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4008 });
4009
4010 Some(cx.spawn(|editor, mut cx| async move {
4011 let task_context = match task_context {
4012 Some(task_context) => task_context.await,
4013 None => None,
4014 };
4015 let resolved_tasks =
4016 tasks.zip(task_context).map(|(tasks, task_context)| {
4017 Arc::new(ResolvedTasks {
4018 templates: tasks.resolve(&task_context).collect(),
4019 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4020 multibuffer_point.row,
4021 tasks.column,
4022 )),
4023 })
4024 });
4025 let spawn_straight_away = resolved_tasks
4026 .as_ref()
4027 .map_or(false, |tasks| tasks.templates.len() == 1)
4028 && code_actions
4029 .as_ref()
4030 .map_or(true, |actions| actions.is_empty());
4031 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4032 *editor.context_menu.write() =
4033 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4034 buffer,
4035 actions: CodeActionContents {
4036 tasks: resolved_tasks,
4037 actions: code_actions,
4038 },
4039 selected_item: Default::default(),
4040 scroll_handle: UniformListScrollHandle::default(),
4041 deployed_from_indicator,
4042 }));
4043 if spawn_straight_away {
4044 if let Some(task) = editor.confirm_code_action(
4045 &ConfirmCodeAction { item_ix: Some(0) },
4046 cx,
4047 ) {
4048 cx.notify();
4049 return task;
4050 }
4051 }
4052 cx.notify();
4053 Task::ready(Ok(()))
4054 }) {
4055 task.await
4056 } else {
4057 Ok(())
4058 }
4059 }))
4060 } else {
4061 Some(Task::ready(Ok(())))
4062 }
4063 })?;
4064 if let Some(task) = spawned_test_task {
4065 task.await?;
4066 }
4067
4068 Ok::<_, anyhow::Error>(())
4069 })
4070 .detach_and_log_err(cx);
4071 }
4072
4073 pub fn confirm_code_action(
4074 &mut self,
4075 action: &ConfirmCodeAction,
4076 cx: &mut ViewContext<Self>,
4077 ) -> Option<Task<Result<()>>> {
4078 let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4079 menu
4080 } else {
4081 return None;
4082 };
4083 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4084 let action = actions_menu.actions.get(action_ix)?;
4085 let title = action.label();
4086 let buffer = actions_menu.buffer;
4087 let workspace = self.workspace()?;
4088
4089 match action {
4090 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4091 workspace.update(cx, |workspace, cx| {
4092 workspace::tasks::schedule_resolved_task(
4093 workspace,
4094 task_source_kind,
4095 resolved_task,
4096 false,
4097 cx,
4098 );
4099
4100 Some(Task::ready(Ok(())))
4101 })
4102 }
4103 CodeActionsItem::CodeAction {
4104 excerpt_id,
4105 action,
4106 provider,
4107 } => {
4108 let apply_code_action =
4109 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4110 let workspace = workspace.downgrade();
4111 Some(cx.spawn(|editor, cx| async move {
4112 let project_transaction = apply_code_action.await?;
4113 Self::open_project_transaction(
4114 &editor,
4115 workspace,
4116 project_transaction,
4117 title,
4118 cx,
4119 )
4120 .await
4121 }))
4122 }
4123 }
4124 }
4125
4126 pub async fn open_project_transaction(
4127 this: &WeakView<Editor>,
4128 workspace: WeakView<Workspace>,
4129 transaction: ProjectTransaction,
4130 title: String,
4131 mut cx: AsyncWindowContext,
4132 ) -> Result<()> {
4133 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4134 cx.update(|cx| {
4135 entries.sort_unstable_by_key(|(buffer, _)| {
4136 buffer.read(cx).file().map(|f| f.path().clone())
4137 });
4138 })?;
4139
4140 // If the project transaction's edits are all contained within this editor, then
4141 // avoid opening a new editor to display them.
4142
4143 if let Some((buffer, transaction)) = entries.first() {
4144 if entries.len() == 1 {
4145 let excerpt = this.update(&mut cx, |editor, cx| {
4146 editor
4147 .buffer()
4148 .read(cx)
4149 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4150 })?;
4151 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4152 if excerpted_buffer == *buffer {
4153 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4154 let excerpt_range = excerpt_range.to_offset(buffer);
4155 buffer
4156 .edited_ranges_for_transaction::<usize>(transaction)
4157 .all(|range| {
4158 excerpt_range.start <= range.start
4159 && excerpt_range.end >= range.end
4160 })
4161 })?;
4162
4163 if all_edits_within_excerpt {
4164 return Ok(());
4165 }
4166 }
4167 }
4168 }
4169 } else {
4170 return Ok(());
4171 }
4172
4173 let mut ranges_to_highlight = Vec::new();
4174 let excerpt_buffer = cx.new_model(|cx| {
4175 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4176 for (buffer_handle, transaction) in &entries {
4177 let buffer = buffer_handle.read(cx);
4178 ranges_to_highlight.extend(
4179 multibuffer.push_excerpts_with_context_lines(
4180 buffer_handle.clone(),
4181 buffer
4182 .edited_ranges_for_transaction::<usize>(transaction)
4183 .collect(),
4184 DEFAULT_MULTIBUFFER_CONTEXT,
4185 cx,
4186 ),
4187 );
4188 }
4189 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4190 multibuffer
4191 })?;
4192
4193 workspace.update(&mut cx, |workspace, cx| {
4194 let project = workspace.project().clone();
4195 let editor =
4196 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4197 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4198 editor.update(cx, |editor, cx| {
4199 editor.highlight_background::<Self>(
4200 &ranges_to_highlight,
4201 |theme| theme.editor_highlighted_line_background,
4202 cx,
4203 );
4204 });
4205 })?;
4206
4207 Ok(())
4208 }
4209
4210 pub fn clear_code_action_providers(&mut self) {
4211 self.code_action_providers.clear();
4212 self.available_code_actions.take();
4213 }
4214
4215 pub fn push_code_action_provider(
4216 &mut self,
4217 provider: Arc<dyn CodeActionProvider>,
4218 cx: &mut ViewContext<Self>,
4219 ) {
4220 self.code_action_providers.push(provider);
4221 self.refresh_code_actions(cx);
4222 }
4223
4224 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4225 let buffer = self.buffer.read(cx);
4226 let newest_selection = self.selections.newest_anchor().clone();
4227 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4228 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4229 if start_buffer != end_buffer {
4230 return None;
4231 }
4232
4233 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4234 cx.background_executor()
4235 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4236 .await;
4237
4238 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4239 let providers = this.code_action_providers.clone();
4240 let tasks = this
4241 .code_action_providers
4242 .iter()
4243 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4244 .collect::<Vec<_>>();
4245 (providers, tasks)
4246 })?;
4247
4248 let mut actions = Vec::new();
4249 for (provider, provider_actions) in
4250 providers.into_iter().zip(future::join_all(tasks).await)
4251 {
4252 if let Some(provider_actions) = provider_actions.log_err() {
4253 actions.extend(provider_actions.into_iter().map(|action| {
4254 AvailableCodeAction {
4255 excerpt_id: newest_selection.start.excerpt_id,
4256 action,
4257 provider: provider.clone(),
4258 }
4259 }));
4260 }
4261 }
4262
4263 this.update(&mut cx, |this, cx| {
4264 this.available_code_actions = if actions.is_empty() {
4265 None
4266 } else {
4267 Some((
4268 Location {
4269 buffer: start_buffer,
4270 range: start..end,
4271 },
4272 actions.into(),
4273 ))
4274 };
4275 cx.notify();
4276 })
4277 }));
4278 None
4279 }
4280
4281 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4282 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4283 self.show_git_blame_inline = false;
4284
4285 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4286 cx.background_executor().timer(delay).await;
4287
4288 this.update(&mut cx, |this, cx| {
4289 this.show_git_blame_inline = true;
4290 cx.notify();
4291 })
4292 .log_err();
4293 }));
4294 }
4295 }
4296
4297 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4298 if self.pending_rename.is_some() {
4299 return None;
4300 }
4301
4302 let provider = self.semantics_provider.clone()?;
4303 let buffer = self.buffer.read(cx);
4304 let newest_selection = self.selections.newest_anchor().clone();
4305 let cursor_position = newest_selection.head();
4306 let (cursor_buffer, cursor_buffer_position) =
4307 buffer.text_anchor_for_position(cursor_position, cx)?;
4308 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4309 if cursor_buffer != tail_buffer {
4310 return None;
4311 }
4312 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4313 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4314 cx.background_executor()
4315 .timer(Duration::from_millis(debounce))
4316 .await;
4317
4318 let highlights = if let Some(highlights) = cx
4319 .update(|cx| {
4320 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4321 })
4322 .ok()
4323 .flatten()
4324 {
4325 highlights.await.log_err()
4326 } else {
4327 None
4328 };
4329
4330 if let Some(highlights) = highlights {
4331 this.update(&mut cx, |this, cx| {
4332 if this.pending_rename.is_some() {
4333 return;
4334 }
4335
4336 let buffer_id = cursor_position.buffer_id;
4337 let buffer = this.buffer.read(cx);
4338 if !buffer
4339 .text_anchor_for_position(cursor_position, cx)
4340 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4341 {
4342 return;
4343 }
4344
4345 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4346 let mut write_ranges = Vec::new();
4347 let mut read_ranges = Vec::new();
4348 for highlight in highlights {
4349 for (excerpt_id, excerpt_range) in
4350 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4351 {
4352 let start = highlight
4353 .range
4354 .start
4355 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4356 let end = highlight
4357 .range
4358 .end
4359 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4360 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4361 continue;
4362 }
4363
4364 let range = Anchor {
4365 buffer_id,
4366 excerpt_id,
4367 text_anchor: start,
4368 }..Anchor {
4369 buffer_id,
4370 excerpt_id,
4371 text_anchor: end,
4372 };
4373 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4374 write_ranges.push(range);
4375 } else {
4376 read_ranges.push(range);
4377 }
4378 }
4379 }
4380
4381 this.highlight_background::<DocumentHighlightRead>(
4382 &read_ranges,
4383 |theme| theme.editor_document_highlight_read_background,
4384 cx,
4385 );
4386 this.highlight_background::<DocumentHighlightWrite>(
4387 &write_ranges,
4388 |theme| theme.editor_document_highlight_write_background,
4389 cx,
4390 );
4391 cx.notify();
4392 })
4393 .log_err();
4394 }
4395 }));
4396 None
4397 }
4398
4399 pub fn refresh_inline_completion(
4400 &mut self,
4401 debounce: bool,
4402 user_requested: bool,
4403 cx: &mut ViewContext<Self>,
4404 ) -> Option<()> {
4405 let provider = self.inline_completion_provider()?;
4406 let cursor = self.selections.newest_anchor().head();
4407 let (buffer, cursor_buffer_position) =
4408 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4409
4410 if !user_requested
4411 && (!self.enable_inline_completions
4412 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4413 || !self.is_focused(cx))
4414 {
4415 self.discard_inline_completion(false, cx);
4416 return None;
4417 }
4418
4419 self.update_visible_inline_completion(cx);
4420 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4421 Some(())
4422 }
4423
4424 fn cycle_inline_completion(
4425 &mut self,
4426 direction: Direction,
4427 cx: &mut ViewContext<Self>,
4428 ) -> Option<()> {
4429 let provider = self.inline_completion_provider()?;
4430 let cursor = self.selections.newest_anchor().head();
4431 let (buffer, cursor_buffer_position) =
4432 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4433 if !self.enable_inline_completions
4434 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4435 {
4436 return None;
4437 }
4438
4439 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4440 self.update_visible_inline_completion(cx);
4441
4442 Some(())
4443 }
4444
4445 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4446 if !self.has_active_inline_completion() {
4447 self.refresh_inline_completion(false, true, cx);
4448 return;
4449 }
4450
4451 self.update_visible_inline_completion(cx);
4452 }
4453
4454 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4455 self.show_cursor_names(cx);
4456 }
4457
4458 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4459 self.show_cursor_names = true;
4460 cx.notify();
4461 cx.spawn(|this, mut cx| async move {
4462 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4463 this.update(&mut cx, |this, cx| {
4464 this.show_cursor_names = false;
4465 cx.notify()
4466 })
4467 .ok()
4468 })
4469 .detach();
4470 }
4471
4472 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4473 if self.has_active_inline_completion() {
4474 self.cycle_inline_completion(Direction::Next, cx);
4475 } else {
4476 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4477 if is_copilot_disabled {
4478 cx.propagate();
4479 }
4480 }
4481 }
4482
4483 pub fn previous_inline_completion(
4484 &mut self,
4485 _: &PreviousInlineCompletion,
4486 cx: &mut ViewContext<Self>,
4487 ) {
4488 if self.has_active_inline_completion() {
4489 self.cycle_inline_completion(Direction::Prev, cx);
4490 } else {
4491 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4492 if is_copilot_disabled {
4493 cx.propagate();
4494 }
4495 }
4496 }
4497
4498 pub fn accept_inline_completion(
4499 &mut self,
4500 _: &AcceptInlineCompletion,
4501 cx: &mut ViewContext<Self>,
4502 ) {
4503 self.hide_context_menu(cx);
4504
4505 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4506 return;
4507 };
4508
4509 self.report_inline_completion_event(true, cx);
4510
4511 match &active_inline_completion.completion {
4512 InlineCompletion::Move(position) => {
4513 let position = *position;
4514 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4515 selections.select_anchor_ranges([position..position]);
4516 });
4517 }
4518 InlineCompletion::Edit(edits) => {
4519 if let Some(provider) = self.inline_completion_provider() {
4520 provider.accept(cx);
4521 }
4522
4523 let snapshot = self.buffer.read(cx).snapshot(cx);
4524 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4525
4526 self.buffer.update(cx, |buffer, cx| {
4527 buffer.edit(edits.iter().cloned(), None, cx)
4528 });
4529
4530 self.change_selections(None, cx, |s| {
4531 s.select_anchor_ranges([last_edit_end..last_edit_end])
4532 });
4533
4534 self.update_visible_inline_completion(cx);
4535 if self.active_inline_completion.is_none() {
4536 self.refresh_inline_completion(true, true, cx);
4537 }
4538
4539 cx.notify();
4540 }
4541 }
4542 }
4543
4544 pub fn accept_partial_inline_completion(
4545 &mut self,
4546 _: &AcceptPartialInlineCompletion,
4547 cx: &mut ViewContext<Self>,
4548 ) {
4549 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4550 return;
4551 };
4552 if self.selections.count() != 1 {
4553 return;
4554 }
4555
4556 self.report_inline_completion_event(true, cx);
4557
4558 match &active_inline_completion.completion {
4559 InlineCompletion::Move(position) => {
4560 let position = *position;
4561 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4562 selections.select_anchor_ranges([position..position]);
4563 });
4564 }
4565 InlineCompletion::Edit(edits) => {
4566 if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
4567 let text = edits[0].1.as_str();
4568 let mut partial_completion = text
4569 .chars()
4570 .by_ref()
4571 .take_while(|c| c.is_alphabetic())
4572 .collect::<String>();
4573 if partial_completion.is_empty() {
4574 partial_completion = text
4575 .chars()
4576 .by_ref()
4577 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4578 .collect::<String>();
4579 }
4580
4581 cx.emit(EditorEvent::InputHandled {
4582 utf16_range_to_replace: None,
4583 text: partial_completion.clone().into(),
4584 });
4585
4586 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4587
4588 self.refresh_inline_completion(true, true, cx);
4589 cx.notify();
4590 }
4591 }
4592 }
4593 }
4594
4595 fn discard_inline_completion(
4596 &mut self,
4597 should_report_inline_completion_event: bool,
4598 cx: &mut ViewContext<Self>,
4599 ) -> bool {
4600 if should_report_inline_completion_event {
4601 self.report_inline_completion_event(false, cx);
4602 }
4603
4604 if let Some(provider) = self.inline_completion_provider() {
4605 provider.discard(cx);
4606 }
4607
4608 self.take_active_inline_completion(cx).is_some()
4609 }
4610
4611 fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
4612 let Some(provider) = self.inline_completion_provider() else {
4613 return;
4614 };
4615 let Some(project) = self.project.as_ref() else {
4616 return;
4617 };
4618 let Some((_, buffer, _)) = self
4619 .buffer
4620 .read(cx)
4621 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4622 else {
4623 return;
4624 };
4625
4626 let project = project.read(cx);
4627 let extension = buffer
4628 .read(cx)
4629 .file()
4630 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4631 project.client().telemetry().report_inline_completion_event(
4632 provider.name().into(),
4633 accepted,
4634 extension,
4635 );
4636 }
4637
4638 pub fn has_active_inline_completion(&self) -> bool {
4639 self.active_inline_completion.is_some()
4640 }
4641
4642 fn take_active_inline_completion(
4643 &mut self,
4644 cx: &mut ViewContext<Self>,
4645 ) -> Option<InlineCompletion> {
4646 let active_inline_completion = self.active_inline_completion.take()?;
4647 self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
4648 self.clear_highlights::<InlineCompletionHighlight>(cx);
4649 Some(active_inline_completion.completion)
4650 }
4651
4652 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4653 let selection = self.selections.newest_anchor();
4654 let cursor = selection.head();
4655 let multibuffer = self.buffer.read(cx).snapshot(cx);
4656 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
4657 let excerpt_id = cursor.excerpt_id;
4658
4659 if !offset_selection.is_empty()
4660 || self
4661 .active_inline_completion
4662 .as_ref()
4663 .map_or(false, |completion| {
4664 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
4665 let invalidation_range = invalidation_range.start..=invalidation_range.end;
4666 !invalidation_range.contains(&offset_selection.head())
4667 })
4668 {
4669 self.discard_inline_completion(false, cx);
4670 return None;
4671 }
4672
4673 self.take_active_inline_completion(cx);
4674 let provider = self.inline_completion_provider()?;
4675
4676 let (buffer, cursor_buffer_position) =
4677 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4678
4679 let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
4680 let edits = completion
4681 .edits
4682 .into_iter()
4683 .map(|(range, new_text)| {
4684 (
4685 multibuffer
4686 .anchor_in_excerpt(excerpt_id, range.start)
4687 .unwrap()
4688 ..multibuffer
4689 .anchor_in_excerpt(excerpt_id, range.end)
4690 .unwrap(),
4691 new_text,
4692 )
4693 })
4694 .collect::<Vec<_>>();
4695 if edits.is_empty() {
4696 return None;
4697 }
4698
4699 let first_edit_start = edits.first().unwrap().0.start;
4700 let edit_start_row = first_edit_start
4701 .to_point(&multibuffer)
4702 .row
4703 .saturating_sub(2);
4704
4705 let last_edit_end = edits.last().unwrap().0.end;
4706 let edit_end_row = cmp::min(
4707 multibuffer.max_point().row,
4708 last_edit_end.to_point(&multibuffer).row + 2,
4709 );
4710
4711 let cursor_row = cursor.to_point(&multibuffer).row;
4712
4713 let mut inlay_ids = Vec::new();
4714 let invalidation_row_range;
4715 let completion;
4716 if cursor_row < edit_start_row {
4717 invalidation_row_range = cursor_row..edit_end_row;
4718 completion = InlineCompletion::Move(first_edit_start);
4719 } else if cursor_row > edit_end_row {
4720 invalidation_row_range = edit_start_row..cursor_row;
4721 completion = InlineCompletion::Move(first_edit_start);
4722 } else {
4723 if edits
4724 .iter()
4725 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
4726 {
4727 let mut inlays = Vec::new();
4728 for (range, new_text) in &edits {
4729 let inlay = Inlay::suggestion(
4730 post_inc(&mut self.next_inlay_id),
4731 range.start,
4732 new_text.as_str(),
4733 );
4734 inlay_ids.push(inlay.id);
4735 inlays.push(inlay);
4736 }
4737
4738 self.splice_inlays(vec![], inlays, cx);
4739 } else {
4740 let background_color = cx.theme().status().deleted_background;
4741 self.highlight_text::<InlineCompletionHighlight>(
4742 edits.iter().map(|(range, _)| range.clone()).collect(),
4743 HighlightStyle {
4744 background_color: Some(background_color),
4745 ..Default::default()
4746 },
4747 cx,
4748 );
4749 }
4750
4751 invalidation_row_range = edit_start_row..edit_end_row;
4752 completion = InlineCompletion::Edit(edits);
4753 };
4754
4755 let invalidation_range = multibuffer
4756 .anchor_before(Point::new(invalidation_row_range.start, 0))
4757 ..multibuffer.anchor_after(Point::new(
4758 invalidation_row_range.end,
4759 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
4760 ));
4761
4762 self.active_inline_completion = Some(InlineCompletionState {
4763 inlay_ids,
4764 completion,
4765 invalidation_range,
4766 });
4767 cx.notify();
4768
4769 Some(())
4770 }
4771
4772 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
4773 Some(self.inline_completion_provider.as_ref()?.provider.clone())
4774 }
4775
4776 fn render_code_actions_indicator(
4777 &self,
4778 _style: &EditorStyle,
4779 row: DisplayRow,
4780 is_active: bool,
4781 cx: &mut ViewContext<Self>,
4782 ) -> Option<IconButton> {
4783 if self.available_code_actions.is_some() {
4784 Some(
4785 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
4786 .shape(ui::IconButtonShape::Square)
4787 .icon_size(IconSize::XSmall)
4788 .icon_color(Color::Muted)
4789 .selected(is_active)
4790 .tooltip({
4791 let focus_handle = self.focus_handle.clone();
4792 move |cx| {
4793 Tooltip::for_action_in(
4794 "Toggle Code Actions",
4795 &ToggleCodeActions {
4796 deployed_from_indicator: None,
4797 },
4798 &focus_handle,
4799 cx,
4800 )
4801 }
4802 })
4803 .on_click(cx.listener(move |editor, _e, cx| {
4804 editor.focus(cx);
4805 editor.toggle_code_actions(
4806 &ToggleCodeActions {
4807 deployed_from_indicator: Some(row),
4808 },
4809 cx,
4810 );
4811 })),
4812 )
4813 } else {
4814 None
4815 }
4816 }
4817
4818 fn clear_tasks(&mut self) {
4819 self.tasks.clear()
4820 }
4821
4822 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
4823 if self.tasks.insert(key, value).is_some() {
4824 // This case should hopefully be rare, but just in case...
4825 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
4826 }
4827 }
4828
4829 fn build_tasks_context(
4830 project: &Model<Project>,
4831 buffer: &Model<Buffer>,
4832 buffer_row: u32,
4833 tasks: &Arc<RunnableTasks>,
4834 cx: &mut ViewContext<Self>,
4835 ) -> Task<Option<task::TaskContext>> {
4836 let position = Point::new(buffer_row, tasks.column);
4837 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4838 let location = Location {
4839 buffer: buffer.clone(),
4840 range: range_start..range_start,
4841 };
4842 // Fill in the environmental variables from the tree-sitter captures
4843 let mut captured_task_variables = TaskVariables::default();
4844 for (capture_name, value) in tasks.extra_variables.clone() {
4845 captured_task_variables.insert(
4846 task::VariableName::Custom(capture_name.into()),
4847 value.clone(),
4848 );
4849 }
4850 project.update(cx, |project, cx| {
4851 project.task_store().update(cx, |task_store, cx| {
4852 task_store.task_context_for_location(captured_task_variables, location, cx)
4853 })
4854 })
4855 }
4856
4857 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
4858 let Some((workspace, _)) = self.workspace.clone() else {
4859 return;
4860 };
4861 let Some(project) = self.project.clone() else {
4862 return;
4863 };
4864
4865 // Try to find a closest, enclosing node using tree-sitter that has a
4866 // task
4867 let Some((buffer, buffer_row, tasks)) = self
4868 .find_enclosing_node_task(cx)
4869 // Or find the task that's closest in row-distance.
4870 .or_else(|| self.find_closest_task(cx))
4871 else {
4872 return;
4873 };
4874
4875 let reveal_strategy = action.reveal;
4876 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
4877 cx.spawn(|_, mut cx| async move {
4878 let context = task_context.await?;
4879 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
4880
4881 let resolved = resolved_task.resolved.as_mut()?;
4882 resolved.reveal = reveal_strategy;
4883
4884 workspace
4885 .update(&mut cx, |workspace, cx| {
4886 workspace::tasks::schedule_resolved_task(
4887 workspace,
4888 task_source_kind,
4889 resolved_task,
4890 false,
4891 cx,
4892 );
4893 })
4894 .ok()
4895 })
4896 .detach();
4897 }
4898
4899 fn find_closest_task(
4900 &mut self,
4901 cx: &mut ViewContext<Self>,
4902 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
4903 let cursor_row = self.selections.newest_adjusted(cx).head().row;
4904
4905 let ((buffer_id, row), tasks) = self
4906 .tasks
4907 .iter()
4908 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
4909
4910 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
4911 let tasks = Arc::new(tasks.to_owned());
4912 Some((buffer, *row, tasks))
4913 }
4914
4915 fn find_enclosing_node_task(
4916 &mut self,
4917 cx: &mut ViewContext<Self>,
4918 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
4919 let snapshot = self.buffer.read(cx).snapshot(cx);
4920 let offset = self.selections.newest::<usize>(cx).head();
4921 let excerpt = snapshot.excerpt_containing(offset..offset)?;
4922 let buffer_id = excerpt.buffer().remote_id();
4923
4924 let layer = excerpt.buffer().syntax_layer_at(offset)?;
4925 let mut cursor = layer.node().walk();
4926
4927 while cursor.goto_first_child_for_byte(offset).is_some() {
4928 if cursor.node().end_byte() == offset {
4929 cursor.goto_next_sibling();
4930 }
4931 }
4932
4933 // Ascend to the smallest ancestor that contains the range and has a task.
4934 loop {
4935 let node = cursor.node();
4936 let node_range = node.byte_range();
4937 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
4938
4939 // Check if this node contains our offset
4940 if node_range.start <= offset && node_range.end >= offset {
4941 // If it contains offset, check for task
4942 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
4943 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
4944 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
4945 }
4946 }
4947
4948 if !cursor.goto_parent() {
4949 break;
4950 }
4951 }
4952 None
4953 }
4954
4955 fn render_run_indicator(
4956 &self,
4957 _style: &EditorStyle,
4958 is_active: bool,
4959 row: DisplayRow,
4960 cx: &mut ViewContext<Self>,
4961 ) -> IconButton {
4962 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
4963 .shape(ui::IconButtonShape::Square)
4964 .icon_size(IconSize::XSmall)
4965 .icon_color(Color::Muted)
4966 .selected(is_active)
4967 .on_click(cx.listener(move |editor, _e, cx| {
4968 editor.focus(cx);
4969 editor.toggle_code_actions(
4970 &ToggleCodeActions {
4971 deployed_from_indicator: Some(row),
4972 },
4973 cx,
4974 );
4975 }))
4976 }
4977
4978 pub fn context_menu_visible(&self) -> bool {
4979 self.context_menu
4980 .read()
4981 .as_ref()
4982 .map_or(false, |menu| menu.visible())
4983 }
4984
4985 fn render_context_menu(
4986 &self,
4987 cursor_position: DisplayPoint,
4988 style: &EditorStyle,
4989 max_height: Pixels,
4990 cx: &mut ViewContext<Editor>,
4991 ) -> Option<(ContextMenuOrigin, AnyElement)> {
4992 self.context_menu.read().as_ref().map(|menu| {
4993 menu.render(
4994 cursor_position,
4995 style,
4996 max_height,
4997 self.workspace.as_ref().map(|(w, _)| w.clone()),
4998 cx,
4999 )
5000 })
5001 }
5002
5003 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
5004 cx.notify();
5005 self.completion_tasks.clear();
5006 self.context_menu.write().take()
5007 }
5008
5009 fn show_snippet_choices(
5010 &mut self,
5011 choices: &Vec<String>,
5012 selection: Range<Anchor>,
5013 cx: &mut ViewContext<Self>,
5014 ) {
5015 if selection.start.buffer_id.is_none() {
5016 return;
5017 }
5018 let buffer_id = selection.start.buffer_id.unwrap();
5019 let buffer = self.buffer().read(cx).buffer(buffer_id);
5020 let id = post_inc(&mut self.next_completion_id);
5021
5022 if let Some(buffer) = buffer {
5023 *self.context_menu.write() = Some(CodeContextMenu::Completions(
5024 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5025 ));
5026 }
5027 }
5028
5029 pub fn insert_snippet(
5030 &mut self,
5031 insertion_ranges: &[Range<usize>],
5032 snippet: Snippet,
5033 cx: &mut ViewContext<Self>,
5034 ) -> Result<()> {
5035 struct Tabstop<T> {
5036 is_end_tabstop: bool,
5037 ranges: Vec<Range<T>>,
5038 choices: Option<Vec<String>>,
5039 }
5040
5041 let tabstops = self.buffer.update(cx, |buffer, cx| {
5042 let snippet_text: Arc<str> = snippet.text.clone().into();
5043 buffer.edit(
5044 insertion_ranges
5045 .iter()
5046 .cloned()
5047 .map(|range| (range, snippet_text.clone())),
5048 Some(AutoindentMode::EachLine),
5049 cx,
5050 );
5051
5052 let snapshot = &*buffer.read(cx);
5053 let snippet = &snippet;
5054 snippet
5055 .tabstops
5056 .iter()
5057 .map(|tabstop| {
5058 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5059 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5060 });
5061 let mut tabstop_ranges = tabstop
5062 .ranges
5063 .iter()
5064 .flat_map(|tabstop_range| {
5065 let mut delta = 0_isize;
5066 insertion_ranges.iter().map(move |insertion_range| {
5067 let insertion_start = insertion_range.start as isize + delta;
5068 delta +=
5069 snippet.text.len() as isize - insertion_range.len() as isize;
5070
5071 let start = ((insertion_start + tabstop_range.start) as usize)
5072 .min(snapshot.len());
5073 let end = ((insertion_start + tabstop_range.end) as usize)
5074 .min(snapshot.len());
5075 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5076 })
5077 })
5078 .collect::<Vec<_>>();
5079 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5080
5081 Tabstop {
5082 is_end_tabstop,
5083 ranges: tabstop_ranges,
5084 choices: tabstop.choices.clone(),
5085 }
5086 })
5087 .collect::<Vec<_>>()
5088 });
5089 if let Some(tabstop) = tabstops.first() {
5090 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5091 s.select_ranges(tabstop.ranges.iter().cloned());
5092 });
5093
5094 if let Some(choices) = &tabstop.choices {
5095 if let Some(selection) = tabstop.ranges.first() {
5096 self.show_snippet_choices(choices, selection.clone(), cx)
5097 }
5098 }
5099
5100 // If we're already at the last tabstop and it's at the end of the snippet,
5101 // we're done, we don't need to keep the state around.
5102 if !tabstop.is_end_tabstop {
5103 let choices = tabstops
5104 .iter()
5105 .map(|tabstop| tabstop.choices.clone())
5106 .collect();
5107
5108 let ranges = tabstops
5109 .into_iter()
5110 .map(|tabstop| tabstop.ranges)
5111 .collect::<Vec<_>>();
5112
5113 self.snippet_stack.push(SnippetState {
5114 active_index: 0,
5115 ranges,
5116 choices,
5117 });
5118 }
5119
5120 // Check whether the just-entered snippet ends with an auto-closable bracket.
5121 if self.autoclose_regions.is_empty() {
5122 let snapshot = self.buffer.read(cx).snapshot(cx);
5123 for selection in &mut self.selections.all::<Point>(cx) {
5124 let selection_head = selection.head();
5125 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5126 continue;
5127 };
5128
5129 let mut bracket_pair = None;
5130 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5131 let prev_chars = snapshot
5132 .reversed_chars_at(selection_head)
5133 .collect::<String>();
5134 for (pair, enabled) in scope.brackets() {
5135 if enabled
5136 && pair.close
5137 && prev_chars.starts_with(pair.start.as_str())
5138 && next_chars.starts_with(pair.end.as_str())
5139 {
5140 bracket_pair = Some(pair.clone());
5141 break;
5142 }
5143 }
5144 if let Some(pair) = bracket_pair {
5145 let start = snapshot.anchor_after(selection_head);
5146 let end = snapshot.anchor_after(selection_head);
5147 self.autoclose_regions.push(AutocloseRegion {
5148 selection_id: selection.id,
5149 range: start..end,
5150 pair,
5151 });
5152 }
5153 }
5154 }
5155 }
5156 Ok(())
5157 }
5158
5159 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5160 self.move_to_snippet_tabstop(Bias::Right, cx)
5161 }
5162
5163 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5164 self.move_to_snippet_tabstop(Bias::Left, cx)
5165 }
5166
5167 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5168 if let Some(mut snippet) = self.snippet_stack.pop() {
5169 match bias {
5170 Bias::Left => {
5171 if snippet.active_index > 0 {
5172 snippet.active_index -= 1;
5173 } else {
5174 self.snippet_stack.push(snippet);
5175 return false;
5176 }
5177 }
5178 Bias::Right => {
5179 if snippet.active_index + 1 < snippet.ranges.len() {
5180 snippet.active_index += 1;
5181 } else {
5182 self.snippet_stack.push(snippet);
5183 return false;
5184 }
5185 }
5186 }
5187 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5188 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5189 s.select_anchor_ranges(current_ranges.iter().cloned())
5190 });
5191
5192 if let Some(choices) = &snippet.choices[snippet.active_index] {
5193 if let Some(selection) = current_ranges.first() {
5194 self.show_snippet_choices(&choices, selection.clone(), cx);
5195 }
5196 }
5197
5198 // If snippet state is not at the last tabstop, push it back on the stack
5199 if snippet.active_index + 1 < snippet.ranges.len() {
5200 self.snippet_stack.push(snippet);
5201 }
5202 return true;
5203 }
5204 }
5205
5206 false
5207 }
5208
5209 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5210 self.transact(cx, |this, cx| {
5211 this.select_all(&SelectAll, cx);
5212 this.insert("", cx);
5213 });
5214 }
5215
5216 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5217 self.transact(cx, |this, cx| {
5218 this.select_autoclose_pair(cx);
5219 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5220 if !this.linked_edit_ranges.is_empty() {
5221 let selections = this.selections.all::<MultiBufferPoint>(cx);
5222 let snapshot = this.buffer.read(cx).snapshot(cx);
5223
5224 for selection in selections.iter() {
5225 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5226 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5227 if selection_start.buffer_id != selection_end.buffer_id {
5228 continue;
5229 }
5230 if let Some(ranges) =
5231 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5232 {
5233 for (buffer, entries) in ranges {
5234 linked_ranges.entry(buffer).or_default().extend(entries);
5235 }
5236 }
5237 }
5238 }
5239
5240 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5241 if !this.selections.line_mode {
5242 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5243 for selection in &mut selections {
5244 if selection.is_empty() {
5245 let old_head = selection.head();
5246 let mut new_head =
5247 movement::left(&display_map, old_head.to_display_point(&display_map))
5248 .to_point(&display_map);
5249 if let Some((buffer, line_buffer_range)) = display_map
5250 .buffer_snapshot
5251 .buffer_line_for_row(MultiBufferRow(old_head.row))
5252 {
5253 let indent_size =
5254 buffer.indent_size_for_line(line_buffer_range.start.row);
5255 let indent_len = match indent_size.kind {
5256 IndentKind::Space => {
5257 buffer.settings_at(line_buffer_range.start, cx).tab_size
5258 }
5259 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5260 };
5261 if old_head.column <= indent_size.len && old_head.column > 0 {
5262 let indent_len = indent_len.get();
5263 new_head = cmp::min(
5264 new_head,
5265 MultiBufferPoint::new(
5266 old_head.row,
5267 ((old_head.column - 1) / indent_len) * indent_len,
5268 ),
5269 );
5270 }
5271 }
5272
5273 selection.set_head(new_head, SelectionGoal::None);
5274 }
5275 }
5276 }
5277
5278 this.signature_help_state.set_backspace_pressed(true);
5279 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5280 this.insert("", cx);
5281 let empty_str: Arc<str> = Arc::from("");
5282 for (buffer, edits) in linked_ranges {
5283 let snapshot = buffer.read(cx).snapshot();
5284 use text::ToPoint as TP;
5285
5286 let edits = edits
5287 .into_iter()
5288 .map(|range| {
5289 let end_point = TP::to_point(&range.end, &snapshot);
5290 let mut start_point = TP::to_point(&range.start, &snapshot);
5291
5292 if end_point == start_point {
5293 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5294 .saturating_sub(1);
5295 start_point = TP::to_point(&offset, &snapshot);
5296 };
5297
5298 (start_point..end_point, empty_str.clone())
5299 })
5300 .sorted_by_key(|(range, _)| range.start)
5301 .collect::<Vec<_>>();
5302 buffer.update(cx, |this, cx| {
5303 this.edit(edits, None, cx);
5304 })
5305 }
5306 this.refresh_inline_completion(true, false, cx);
5307 linked_editing_ranges::refresh_linked_ranges(this, cx);
5308 });
5309 }
5310
5311 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5312 self.transact(cx, |this, cx| {
5313 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5314 let line_mode = s.line_mode;
5315 s.move_with(|map, selection| {
5316 if selection.is_empty() && !line_mode {
5317 let cursor = movement::right(map, selection.head());
5318 selection.end = cursor;
5319 selection.reversed = true;
5320 selection.goal = SelectionGoal::None;
5321 }
5322 })
5323 });
5324 this.insert("", cx);
5325 this.refresh_inline_completion(true, false, cx);
5326 });
5327 }
5328
5329 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5330 if self.move_to_prev_snippet_tabstop(cx) {
5331 return;
5332 }
5333
5334 self.outdent(&Outdent, cx);
5335 }
5336
5337 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5338 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5339 return;
5340 }
5341
5342 let mut selections = self.selections.all_adjusted(cx);
5343 let buffer = self.buffer.read(cx);
5344 let snapshot = buffer.snapshot(cx);
5345 let rows_iter = selections.iter().map(|s| s.head().row);
5346 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5347
5348 let mut edits = Vec::new();
5349 let mut prev_edited_row = 0;
5350 let mut row_delta = 0;
5351 for selection in &mut selections {
5352 if selection.start.row != prev_edited_row {
5353 row_delta = 0;
5354 }
5355 prev_edited_row = selection.end.row;
5356
5357 // If the selection is non-empty, then increase the indentation of the selected lines.
5358 if !selection.is_empty() {
5359 row_delta =
5360 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5361 continue;
5362 }
5363
5364 // If the selection is empty and the cursor is in the leading whitespace before the
5365 // suggested indentation, then auto-indent the line.
5366 let cursor = selection.head();
5367 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5368 if let Some(suggested_indent) =
5369 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5370 {
5371 if cursor.column < suggested_indent.len
5372 && cursor.column <= current_indent.len
5373 && current_indent.len <= suggested_indent.len
5374 {
5375 selection.start = Point::new(cursor.row, suggested_indent.len);
5376 selection.end = selection.start;
5377 if row_delta == 0 {
5378 edits.extend(Buffer::edit_for_indent_size_adjustment(
5379 cursor.row,
5380 current_indent,
5381 suggested_indent,
5382 ));
5383 row_delta = suggested_indent.len - current_indent.len;
5384 }
5385 continue;
5386 }
5387 }
5388
5389 // Otherwise, insert a hard or soft tab.
5390 let settings = buffer.settings_at(cursor, cx);
5391 let tab_size = if settings.hard_tabs {
5392 IndentSize::tab()
5393 } else {
5394 let tab_size = settings.tab_size.get();
5395 let char_column = snapshot
5396 .text_for_range(Point::new(cursor.row, 0)..cursor)
5397 .flat_map(str::chars)
5398 .count()
5399 + row_delta as usize;
5400 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5401 IndentSize::spaces(chars_to_next_tab_stop)
5402 };
5403 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5404 selection.end = selection.start;
5405 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5406 row_delta += tab_size.len;
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 this.refresh_inline_completion(true, false, cx);
5413 });
5414 }
5415
5416 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5417 if self.read_only(cx) {
5418 return;
5419 }
5420 let mut selections = self.selections.all::<Point>(cx);
5421 let mut prev_edited_row = 0;
5422 let mut row_delta = 0;
5423 let mut edits = Vec::new();
5424 let buffer = self.buffer.read(cx);
5425 let snapshot = buffer.snapshot(cx);
5426 for selection in &mut selections {
5427 if selection.start.row != prev_edited_row {
5428 row_delta = 0;
5429 }
5430 prev_edited_row = selection.end.row;
5431
5432 row_delta =
5433 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5434 }
5435
5436 self.transact(cx, |this, cx| {
5437 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5438 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5439 });
5440 }
5441
5442 fn indent_selection(
5443 buffer: &MultiBuffer,
5444 snapshot: &MultiBufferSnapshot,
5445 selection: &mut Selection<Point>,
5446 edits: &mut Vec<(Range<Point>, String)>,
5447 delta_for_start_row: u32,
5448 cx: &AppContext,
5449 ) -> u32 {
5450 let settings = buffer.settings_at(selection.start, cx);
5451 let tab_size = settings.tab_size.get();
5452 let indent_kind = if settings.hard_tabs {
5453 IndentKind::Tab
5454 } else {
5455 IndentKind::Space
5456 };
5457 let mut start_row = selection.start.row;
5458 let mut end_row = selection.end.row + 1;
5459
5460 // If a selection ends at the beginning of a line, don't indent
5461 // that last line.
5462 if selection.end.column == 0 && selection.end.row > selection.start.row {
5463 end_row -= 1;
5464 }
5465
5466 // Avoid re-indenting a row that has already been indented by a
5467 // previous selection, but still update this selection's column
5468 // to reflect that indentation.
5469 if delta_for_start_row > 0 {
5470 start_row += 1;
5471 selection.start.column += delta_for_start_row;
5472 if selection.end.row == selection.start.row {
5473 selection.end.column += delta_for_start_row;
5474 }
5475 }
5476
5477 let mut delta_for_end_row = 0;
5478 let has_multiple_rows = start_row + 1 != end_row;
5479 for row in start_row..end_row {
5480 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5481 let indent_delta = match (current_indent.kind, indent_kind) {
5482 (IndentKind::Space, IndentKind::Space) => {
5483 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5484 IndentSize::spaces(columns_to_next_tab_stop)
5485 }
5486 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5487 (_, IndentKind::Tab) => IndentSize::tab(),
5488 };
5489
5490 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5491 0
5492 } else {
5493 selection.start.column
5494 };
5495 let row_start = Point::new(row, start);
5496 edits.push((
5497 row_start..row_start,
5498 indent_delta.chars().collect::<String>(),
5499 ));
5500
5501 // Update this selection's endpoints to reflect the indentation.
5502 if row == selection.start.row {
5503 selection.start.column += indent_delta.len;
5504 }
5505 if row == selection.end.row {
5506 selection.end.column += indent_delta.len;
5507 delta_for_end_row = indent_delta.len;
5508 }
5509 }
5510
5511 if selection.start.row == selection.end.row {
5512 delta_for_start_row + delta_for_end_row
5513 } else {
5514 delta_for_end_row
5515 }
5516 }
5517
5518 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5519 if self.read_only(cx) {
5520 return;
5521 }
5522 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5523 let selections = self.selections.all::<Point>(cx);
5524 let mut deletion_ranges = Vec::new();
5525 let mut last_outdent = None;
5526 {
5527 let buffer = self.buffer.read(cx);
5528 let snapshot = buffer.snapshot(cx);
5529 for selection in &selections {
5530 let settings = buffer.settings_at(selection.start, cx);
5531 let tab_size = settings.tab_size.get();
5532 let mut rows = selection.spanned_rows(false, &display_map);
5533
5534 // Avoid re-outdenting a row that has already been outdented by a
5535 // previous selection.
5536 if let Some(last_row) = last_outdent {
5537 if last_row == rows.start {
5538 rows.start = rows.start.next_row();
5539 }
5540 }
5541 let has_multiple_rows = rows.len() > 1;
5542 for row in rows.iter_rows() {
5543 let indent_size = snapshot.indent_size_for_line(row);
5544 if indent_size.len > 0 {
5545 let deletion_len = match indent_size.kind {
5546 IndentKind::Space => {
5547 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5548 if columns_to_prev_tab_stop == 0 {
5549 tab_size
5550 } else {
5551 columns_to_prev_tab_stop
5552 }
5553 }
5554 IndentKind::Tab => 1,
5555 };
5556 let start = if has_multiple_rows
5557 || deletion_len > selection.start.column
5558 || indent_size.len < selection.start.column
5559 {
5560 0
5561 } else {
5562 selection.start.column - deletion_len
5563 };
5564 deletion_ranges.push(
5565 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5566 );
5567 last_outdent = Some(row);
5568 }
5569 }
5570 }
5571 }
5572
5573 self.transact(cx, |this, cx| {
5574 this.buffer.update(cx, |buffer, cx| {
5575 let empty_str: Arc<str> = Arc::default();
5576 buffer.edit(
5577 deletion_ranges
5578 .into_iter()
5579 .map(|range| (range, empty_str.clone())),
5580 None,
5581 cx,
5582 );
5583 });
5584 let selections = this.selections.all::<usize>(cx);
5585 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5586 });
5587 }
5588
5589 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
5590 if self.read_only(cx) {
5591 return;
5592 }
5593 let selections = self
5594 .selections
5595 .all::<usize>(cx)
5596 .into_iter()
5597 .map(|s| s.range());
5598
5599 self.transact(cx, |this, cx| {
5600 this.buffer.update(cx, |buffer, cx| {
5601 buffer.autoindent_ranges(selections, cx);
5602 });
5603 let selections = this.selections.all::<usize>(cx);
5604 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5605 });
5606 }
5607
5608 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5609 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5610 let selections = self.selections.all::<Point>(cx);
5611
5612 let mut new_cursors = Vec::new();
5613 let mut edit_ranges = Vec::new();
5614 let mut selections = selections.iter().peekable();
5615 while let Some(selection) = selections.next() {
5616 let mut rows = selection.spanned_rows(false, &display_map);
5617 let goal_display_column = selection.head().to_display_point(&display_map).column();
5618
5619 // Accumulate contiguous regions of rows that we want to delete.
5620 while let Some(next_selection) = selections.peek() {
5621 let next_rows = next_selection.spanned_rows(false, &display_map);
5622 if next_rows.start <= rows.end {
5623 rows.end = next_rows.end;
5624 selections.next().unwrap();
5625 } else {
5626 break;
5627 }
5628 }
5629
5630 let buffer = &display_map.buffer_snapshot;
5631 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5632 let edit_end;
5633 let cursor_buffer_row;
5634 if buffer.max_point().row >= rows.end.0 {
5635 // If there's a line after the range, delete the \n from the end of the row range
5636 // and position the cursor on the next line.
5637 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5638 cursor_buffer_row = rows.end;
5639 } else {
5640 // If there isn't a line after the range, delete the \n from the line before the
5641 // start of the row range and position the cursor there.
5642 edit_start = edit_start.saturating_sub(1);
5643 edit_end = buffer.len();
5644 cursor_buffer_row = rows.start.previous_row();
5645 }
5646
5647 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5648 *cursor.column_mut() =
5649 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5650
5651 new_cursors.push((
5652 selection.id,
5653 buffer.anchor_after(cursor.to_point(&display_map)),
5654 ));
5655 edit_ranges.push(edit_start..edit_end);
5656 }
5657
5658 self.transact(cx, |this, cx| {
5659 let buffer = this.buffer.update(cx, |buffer, cx| {
5660 let empty_str: Arc<str> = Arc::default();
5661 buffer.edit(
5662 edit_ranges
5663 .into_iter()
5664 .map(|range| (range, empty_str.clone())),
5665 None,
5666 cx,
5667 );
5668 buffer.snapshot(cx)
5669 });
5670 let new_selections = new_cursors
5671 .into_iter()
5672 .map(|(id, cursor)| {
5673 let cursor = cursor.to_point(&buffer);
5674 Selection {
5675 id,
5676 start: cursor,
5677 end: cursor,
5678 reversed: false,
5679 goal: SelectionGoal::None,
5680 }
5681 })
5682 .collect();
5683
5684 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5685 s.select(new_selections);
5686 });
5687 });
5688 }
5689
5690 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5691 if self.read_only(cx) {
5692 return;
5693 }
5694 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5695 for selection in self.selections.all::<Point>(cx) {
5696 let start = MultiBufferRow(selection.start.row);
5697 // Treat single line selections as if they include the next line. Otherwise this action
5698 // would do nothing for single line selections individual cursors.
5699 let end = if selection.start.row == selection.end.row {
5700 MultiBufferRow(selection.start.row + 1)
5701 } else {
5702 MultiBufferRow(selection.end.row)
5703 };
5704
5705 if let Some(last_row_range) = row_ranges.last_mut() {
5706 if start <= last_row_range.end {
5707 last_row_range.end = end;
5708 continue;
5709 }
5710 }
5711 row_ranges.push(start..end);
5712 }
5713
5714 let snapshot = self.buffer.read(cx).snapshot(cx);
5715 let mut cursor_positions = Vec::new();
5716 for row_range in &row_ranges {
5717 let anchor = snapshot.anchor_before(Point::new(
5718 row_range.end.previous_row().0,
5719 snapshot.line_len(row_range.end.previous_row()),
5720 ));
5721 cursor_positions.push(anchor..anchor);
5722 }
5723
5724 self.transact(cx, |this, cx| {
5725 for row_range in row_ranges.into_iter().rev() {
5726 for row in row_range.iter_rows().rev() {
5727 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5728 let next_line_row = row.next_row();
5729 let indent = snapshot.indent_size_for_line(next_line_row);
5730 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5731
5732 let replace = if snapshot.line_len(next_line_row) > indent.len {
5733 " "
5734 } else {
5735 ""
5736 };
5737
5738 this.buffer.update(cx, |buffer, cx| {
5739 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5740 });
5741 }
5742 }
5743
5744 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5745 s.select_anchor_ranges(cursor_positions)
5746 });
5747 });
5748 }
5749
5750 pub fn sort_lines_case_sensitive(
5751 &mut self,
5752 _: &SortLinesCaseSensitive,
5753 cx: &mut ViewContext<Self>,
5754 ) {
5755 self.manipulate_lines(cx, |lines| lines.sort())
5756 }
5757
5758 pub fn sort_lines_case_insensitive(
5759 &mut self,
5760 _: &SortLinesCaseInsensitive,
5761 cx: &mut ViewContext<Self>,
5762 ) {
5763 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5764 }
5765
5766 pub fn unique_lines_case_insensitive(
5767 &mut self,
5768 _: &UniqueLinesCaseInsensitive,
5769 cx: &mut ViewContext<Self>,
5770 ) {
5771 self.manipulate_lines(cx, |lines| {
5772 let mut seen = HashSet::default();
5773 lines.retain(|line| seen.insert(line.to_lowercase()));
5774 })
5775 }
5776
5777 pub fn unique_lines_case_sensitive(
5778 &mut self,
5779 _: &UniqueLinesCaseSensitive,
5780 cx: &mut ViewContext<Self>,
5781 ) {
5782 self.manipulate_lines(cx, |lines| {
5783 let mut seen = HashSet::default();
5784 lines.retain(|line| seen.insert(*line));
5785 })
5786 }
5787
5788 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
5789 let mut revert_changes = HashMap::default();
5790 let snapshot = self.snapshot(cx);
5791 for hunk in hunks_for_ranges(
5792 Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
5793 &snapshot,
5794 ) {
5795 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5796 }
5797 if !revert_changes.is_empty() {
5798 self.transact(cx, |editor, cx| {
5799 editor.revert(revert_changes, cx);
5800 });
5801 }
5802 }
5803
5804 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
5805 let Some(project) = self.project.clone() else {
5806 return;
5807 };
5808 self.reload(project, cx).detach_and_notify_err(cx);
5809 }
5810
5811 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
5812 let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
5813 if !revert_changes.is_empty() {
5814 self.transact(cx, |editor, cx| {
5815 editor.revert(revert_changes, cx);
5816 });
5817 }
5818 }
5819
5820 fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
5821 let snapshot = self.buffer.read(cx).read(cx);
5822 if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
5823 drop(snapshot);
5824 let mut revert_changes = HashMap::default();
5825 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5826 if !revert_changes.is_empty() {
5827 self.revert(revert_changes, cx)
5828 }
5829 }
5830 }
5831
5832 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
5833 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
5834 let project_path = buffer.read(cx).project_path(cx)?;
5835 let project = self.project.as_ref()?.read(cx);
5836 let entry = project.entry_for_path(&project_path, cx)?;
5837 let parent = match &entry.canonical_path {
5838 Some(canonical_path) => canonical_path.to_path_buf(),
5839 None => project.absolute_path(&project_path, cx)?,
5840 }
5841 .parent()?
5842 .to_path_buf();
5843 Some(parent)
5844 }) {
5845 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
5846 }
5847 }
5848
5849 fn gather_revert_changes(
5850 &mut self,
5851 selections: &[Selection<Point>],
5852 cx: &mut ViewContext<'_, Editor>,
5853 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
5854 let mut revert_changes = HashMap::default();
5855 let snapshot = self.snapshot(cx);
5856 for hunk in hunks_for_selections(&snapshot, selections) {
5857 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5858 }
5859 revert_changes
5860 }
5861
5862 pub fn prepare_revert_change(
5863 &mut self,
5864 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
5865 hunk: &MultiBufferDiffHunk,
5866 cx: &AppContext,
5867 ) -> Option<()> {
5868 let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
5869 let buffer = buffer.read(cx);
5870 let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
5871 let original_text = change_set
5872 .read(cx)
5873 .base_text
5874 .as_ref()?
5875 .read(cx)
5876 .as_rope()
5877 .slice(hunk.diff_base_byte_range.clone());
5878 let buffer_snapshot = buffer.snapshot();
5879 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
5880 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
5881 probe
5882 .0
5883 .start
5884 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
5885 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
5886 }) {
5887 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
5888 Some(())
5889 } else {
5890 None
5891 }
5892 }
5893
5894 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
5895 self.manipulate_lines(cx, |lines| lines.reverse())
5896 }
5897
5898 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
5899 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
5900 }
5901
5902 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
5903 where
5904 Fn: FnMut(&mut Vec<&str>),
5905 {
5906 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5907 let buffer = self.buffer.read(cx).snapshot(cx);
5908
5909 let mut edits = Vec::new();
5910
5911 let selections = self.selections.all::<Point>(cx);
5912 let mut selections = selections.iter().peekable();
5913 let mut contiguous_row_selections = Vec::new();
5914 let mut new_selections = Vec::new();
5915 let mut added_lines = 0;
5916 let mut removed_lines = 0;
5917
5918 while let Some(selection) = selections.next() {
5919 let (start_row, end_row) = consume_contiguous_rows(
5920 &mut contiguous_row_selections,
5921 selection,
5922 &display_map,
5923 &mut selections,
5924 );
5925
5926 let start_point = Point::new(start_row.0, 0);
5927 let end_point = Point::new(
5928 end_row.previous_row().0,
5929 buffer.line_len(end_row.previous_row()),
5930 );
5931 let text = buffer
5932 .text_for_range(start_point..end_point)
5933 .collect::<String>();
5934
5935 let mut lines = text.split('\n').collect_vec();
5936
5937 let lines_before = lines.len();
5938 callback(&mut lines);
5939 let lines_after = lines.len();
5940
5941 edits.push((start_point..end_point, lines.join("\n")));
5942
5943 // Selections must change based on added and removed line count
5944 let start_row =
5945 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
5946 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
5947 new_selections.push(Selection {
5948 id: selection.id,
5949 start: start_row,
5950 end: end_row,
5951 goal: SelectionGoal::None,
5952 reversed: selection.reversed,
5953 });
5954
5955 if lines_after > lines_before {
5956 added_lines += lines_after - lines_before;
5957 } else if lines_before > lines_after {
5958 removed_lines += lines_before - lines_after;
5959 }
5960 }
5961
5962 self.transact(cx, |this, cx| {
5963 let buffer = this.buffer.update(cx, |buffer, cx| {
5964 buffer.edit(edits, None, cx);
5965 buffer.snapshot(cx)
5966 });
5967
5968 // Recalculate offsets on newly edited buffer
5969 let new_selections = new_selections
5970 .iter()
5971 .map(|s| {
5972 let start_point = Point::new(s.start.0, 0);
5973 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
5974 Selection {
5975 id: s.id,
5976 start: buffer.point_to_offset(start_point),
5977 end: buffer.point_to_offset(end_point),
5978 goal: s.goal,
5979 reversed: s.reversed,
5980 }
5981 })
5982 .collect();
5983
5984 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5985 s.select(new_selections);
5986 });
5987
5988 this.request_autoscroll(Autoscroll::fit(), cx);
5989 });
5990 }
5991
5992 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
5993 self.manipulate_text(cx, |text| text.to_uppercase())
5994 }
5995
5996 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
5997 self.manipulate_text(cx, |text| text.to_lowercase())
5998 }
5999
6000 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6001 self.manipulate_text(cx, |text| {
6002 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6003 // https://github.com/rutrum/convert-case/issues/16
6004 text.split('\n')
6005 .map(|line| line.to_case(Case::Title))
6006 .join("\n")
6007 })
6008 }
6009
6010 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6011 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6012 }
6013
6014 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6015 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6016 }
6017
6018 pub fn convert_to_upper_camel_case(
6019 &mut self,
6020 _: &ConvertToUpperCamelCase,
6021 cx: &mut ViewContext<Self>,
6022 ) {
6023 self.manipulate_text(cx, |text| {
6024 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6025 // https://github.com/rutrum/convert-case/issues/16
6026 text.split('\n')
6027 .map(|line| line.to_case(Case::UpperCamel))
6028 .join("\n")
6029 })
6030 }
6031
6032 pub fn convert_to_lower_camel_case(
6033 &mut self,
6034 _: &ConvertToLowerCamelCase,
6035 cx: &mut ViewContext<Self>,
6036 ) {
6037 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6038 }
6039
6040 pub fn convert_to_opposite_case(
6041 &mut self,
6042 _: &ConvertToOppositeCase,
6043 cx: &mut ViewContext<Self>,
6044 ) {
6045 self.manipulate_text(cx, |text| {
6046 text.chars()
6047 .fold(String::with_capacity(text.len()), |mut t, c| {
6048 if c.is_uppercase() {
6049 t.extend(c.to_lowercase());
6050 } else {
6051 t.extend(c.to_uppercase());
6052 }
6053 t
6054 })
6055 })
6056 }
6057
6058 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6059 where
6060 Fn: FnMut(&str) -> String,
6061 {
6062 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6063 let buffer = self.buffer.read(cx).snapshot(cx);
6064
6065 let mut new_selections = Vec::new();
6066 let mut edits = Vec::new();
6067 let mut selection_adjustment = 0i32;
6068
6069 for selection in self.selections.all::<usize>(cx) {
6070 let selection_is_empty = selection.is_empty();
6071
6072 let (start, end) = if selection_is_empty {
6073 let word_range = movement::surrounding_word(
6074 &display_map,
6075 selection.start.to_display_point(&display_map),
6076 );
6077 let start = word_range.start.to_offset(&display_map, Bias::Left);
6078 let end = word_range.end.to_offset(&display_map, Bias::Left);
6079 (start, end)
6080 } else {
6081 (selection.start, selection.end)
6082 };
6083
6084 let text = buffer.text_for_range(start..end).collect::<String>();
6085 let old_length = text.len() as i32;
6086 let text = callback(&text);
6087
6088 new_selections.push(Selection {
6089 start: (start as i32 - selection_adjustment) as usize,
6090 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6091 goal: SelectionGoal::None,
6092 ..selection
6093 });
6094
6095 selection_adjustment += old_length - text.len() as i32;
6096
6097 edits.push((start..end, text));
6098 }
6099
6100 self.transact(cx, |this, cx| {
6101 this.buffer.update(cx, |buffer, cx| {
6102 buffer.edit(edits, None, cx);
6103 });
6104
6105 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6106 s.select(new_selections);
6107 });
6108
6109 this.request_autoscroll(Autoscroll::fit(), cx);
6110 });
6111 }
6112
6113 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6114 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6115 let buffer = &display_map.buffer_snapshot;
6116 let selections = self.selections.all::<Point>(cx);
6117
6118 let mut edits = Vec::new();
6119 let mut selections_iter = selections.iter().peekable();
6120 while let Some(selection) = selections_iter.next() {
6121 // Avoid duplicating the same lines twice.
6122 let mut rows = selection.spanned_rows(false, &display_map);
6123
6124 while let Some(next_selection) = selections_iter.peek() {
6125 let next_rows = next_selection.spanned_rows(false, &display_map);
6126 if next_rows.start < rows.end {
6127 rows.end = next_rows.end;
6128 selections_iter.next().unwrap();
6129 } else {
6130 break;
6131 }
6132 }
6133
6134 // Copy the text from the selected row region and splice it either at the start
6135 // or end of the region.
6136 let start = Point::new(rows.start.0, 0);
6137 let end = Point::new(
6138 rows.end.previous_row().0,
6139 buffer.line_len(rows.end.previous_row()),
6140 );
6141 let text = buffer
6142 .text_for_range(start..end)
6143 .chain(Some("\n"))
6144 .collect::<String>();
6145 let insert_location = if upwards {
6146 Point::new(rows.end.0, 0)
6147 } else {
6148 start
6149 };
6150 edits.push((insert_location..insert_location, text));
6151 }
6152
6153 self.transact(cx, |this, cx| {
6154 this.buffer.update(cx, |buffer, cx| {
6155 buffer.edit(edits, None, cx);
6156 });
6157
6158 this.request_autoscroll(Autoscroll::fit(), cx);
6159 });
6160 }
6161
6162 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6163 self.duplicate_line(true, cx);
6164 }
6165
6166 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6167 self.duplicate_line(false, cx);
6168 }
6169
6170 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6171 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6172 let buffer = self.buffer.read(cx).snapshot(cx);
6173
6174 let mut edits = Vec::new();
6175 let mut unfold_ranges = Vec::new();
6176 let mut refold_creases = Vec::new();
6177
6178 let selections = self.selections.all::<Point>(cx);
6179 let mut selections = selections.iter().peekable();
6180 let mut contiguous_row_selections = Vec::new();
6181 let mut new_selections = Vec::new();
6182
6183 while let Some(selection) = selections.next() {
6184 // Find all the selections that span a contiguous row range
6185 let (start_row, end_row) = consume_contiguous_rows(
6186 &mut contiguous_row_selections,
6187 selection,
6188 &display_map,
6189 &mut selections,
6190 );
6191
6192 // Move the text spanned by the row range to be before the line preceding the row range
6193 if start_row.0 > 0 {
6194 let range_to_move = Point::new(
6195 start_row.previous_row().0,
6196 buffer.line_len(start_row.previous_row()),
6197 )
6198 ..Point::new(
6199 end_row.previous_row().0,
6200 buffer.line_len(end_row.previous_row()),
6201 );
6202 let insertion_point = display_map
6203 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6204 .0;
6205
6206 // Don't move lines across excerpts
6207 if buffer
6208 .excerpt_boundaries_in_range((
6209 Bound::Excluded(insertion_point),
6210 Bound::Included(range_to_move.end),
6211 ))
6212 .next()
6213 .is_none()
6214 {
6215 let text = buffer
6216 .text_for_range(range_to_move.clone())
6217 .flat_map(|s| s.chars())
6218 .skip(1)
6219 .chain(['\n'])
6220 .collect::<String>();
6221
6222 edits.push((
6223 buffer.anchor_after(range_to_move.start)
6224 ..buffer.anchor_before(range_to_move.end),
6225 String::new(),
6226 ));
6227 let insertion_anchor = buffer.anchor_after(insertion_point);
6228 edits.push((insertion_anchor..insertion_anchor, text));
6229
6230 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6231
6232 // Move selections up
6233 new_selections.extend(contiguous_row_selections.drain(..).map(
6234 |mut selection| {
6235 selection.start.row -= row_delta;
6236 selection.end.row -= row_delta;
6237 selection
6238 },
6239 ));
6240
6241 // Move folds up
6242 unfold_ranges.push(range_to_move.clone());
6243 for fold in display_map.folds_in_range(
6244 buffer.anchor_before(range_to_move.start)
6245 ..buffer.anchor_after(range_to_move.end),
6246 ) {
6247 let mut start = fold.range.start.to_point(&buffer);
6248 let mut end = fold.range.end.to_point(&buffer);
6249 start.row -= row_delta;
6250 end.row -= row_delta;
6251 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6252 }
6253 }
6254 }
6255
6256 // If we didn't move line(s), preserve the existing selections
6257 new_selections.append(&mut contiguous_row_selections);
6258 }
6259
6260 self.transact(cx, |this, cx| {
6261 this.unfold_ranges(&unfold_ranges, true, true, cx);
6262 this.buffer.update(cx, |buffer, cx| {
6263 for (range, text) in edits {
6264 buffer.edit([(range, text)], None, cx);
6265 }
6266 });
6267 this.fold_creases(refold_creases, true, cx);
6268 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6269 s.select(new_selections);
6270 })
6271 });
6272 }
6273
6274 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6275 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6276 let buffer = self.buffer.read(cx).snapshot(cx);
6277
6278 let mut edits = Vec::new();
6279 let mut unfold_ranges = Vec::new();
6280 let mut refold_creases = Vec::new();
6281
6282 let selections = self.selections.all::<Point>(cx);
6283 let mut selections = selections.iter().peekable();
6284 let mut contiguous_row_selections = Vec::new();
6285 let mut new_selections = Vec::new();
6286
6287 while let Some(selection) = selections.next() {
6288 // Find all the selections that span a contiguous row range
6289 let (start_row, end_row) = consume_contiguous_rows(
6290 &mut contiguous_row_selections,
6291 selection,
6292 &display_map,
6293 &mut selections,
6294 );
6295
6296 // Move the text spanned by the row range to be after the last line of the row range
6297 if end_row.0 <= buffer.max_point().row {
6298 let range_to_move =
6299 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6300 let insertion_point = display_map
6301 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6302 .0;
6303
6304 // Don't move lines across excerpt boundaries
6305 if buffer
6306 .excerpt_boundaries_in_range((
6307 Bound::Excluded(range_to_move.start),
6308 Bound::Included(insertion_point),
6309 ))
6310 .next()
6311 .is_none()
6312 {
6313 let mut text = String::from("\n");
6314 text.extend(buffer.text_for_range(range_to_move.clone()));
6315 text.pop(); // Drop trailing newline
6316 edits.push((
6317 buffer.anchor_after(range_to_move.start)
6318 ..buffer.anchor_before(range_to_move.end),
6319 String::new(),
6320 ));
6321 let insertion_anchor = buffer.anchor_after(insertion_point);
6322 edits.push((insertion_anchor..insertion_anchor, text));
6323
6324 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6325
6326 // Move selections down
6327 new_selections.extend(contiguous_row_selections.drain(..).map(
6328 |mut selection| {
6329 selection.start.row += row_delta;
6330 selection.end.row += row_delta;
6331 selection
6332 },
6333 ));
6334
6335 // Move folds down
6336 unfold_ranges.push(range_to_move.clone());
6337 for fold in display_map.folds_in_range(
6338 buffer.anchor_before(range_to_move.start)
6339 ..buffer.anchor_after(range_to_move.end),
6340 ) {
6341 let mut start = fold.range.start.to_point(&buffer);
6342 let mut end = fold.range.end.to_point(&buffer);
6343 start.row += row_delta;
6344 end.row += row_delta;
6345 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6346 }
6347 }
6348 }
6349
6350 // If we didn't move line(s), preserve the existing selections
6351 new_selections.append(&mut contiguous_row_selections);
6352 }
6353
6354 self.transact(cx, |this, cx| {
6355 this.unfold_ranges(&unfold_ranges, true, true, cx);
6356 this.buffer.update(cx, |buffer, cx| {
6357 for (range, text) in edits {
6358 buffer.edit([(range, text)], None, cx);
6359 }
6360 });
6361 this.fold_creases(refold_creases, true, cx);
6362 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6363 });
6364 }
6365
6366 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6367 let text_layout_details = &self.text_layout_details(cx);
6368 self.transact(cx, |this, cx| {
6369 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6370 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6371 let line_mode = s.line_mode;
6372 s.move_with(|display_map, selection| {
6373 if !selection.is_empty() || line_mode {
6374 return;
6375 }
6376
6377 let mut head = selection.head();
6378 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6379 if head.column() == display_map.line_len(head.row()) {
6380 transpose_offset = display_map
6381 .buffer_snapshot
6382 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6383 }
6384
6385 if transpose_offset == 0 {
6386 return;
6387 }
6388
6389 *head.column_mut() += 1;
6390 head = display_map.clip_point(head, Bias::Right);
6391 let goal = SelectionGoal::HorizontalPosition(
6392 display_map
6393 .x_for_display_point(head, text_layout_details)
6394 .into(),
6395 );
6396 selection.collapse_to(head, goal);
6397
6398 let transpose_start = display_map
6399 .buffer_snapshot
6400 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6401 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6402 let transpose_end = display_map
6403 .buffer_snapshot
6404 .clip_offset(transpose_offset + 1, Bias::Right);
6405 if let Some(ch) =
6406 display_map.buffer_snapshot.chars_at(transpose_start).next()
6407 {
6408 edits.push((transpose_start..transpose_offset, String::new()));
6409 edits.push((transpose_end..transpose_end, ch.to_string()));
6410 }
6411 }
6412 });
6413 edits
6414 });
6415 this.buffer
6416 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6417 let selections = this.selections.all::<usize>(cx);
6418 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6419 s.select(selections);
6420 });
6421 });
6422 }
6423
6424 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6425 self.rewrap_impl(IsVimMode::No, cx)
6426 }
6427
6428 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
6429 let buffer = self.buffer.read(cx).snapshot(cx);
6430 let selections = self.selections.all::<Point>(cx);
6431 let mut selections = selections.iter().peekable();
6432
6433 let mut edits = Vec::new();
6434 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6435
6436 while let Some(selection) = selections.next() {
6437 let mut start_row = selection.start.row;
6438 let mut end_row = selection.end.row;
6439
6440 // Skip selections that overlap with a range that has already been rewrapped.
6441 let selection_range = start_row..end_row;
6442 if rewrapped_row_ranges
6443 .iter()
6444 .any(|range| range.overlaps(&selection_range))
6445 {
6446 continue;
6447 }
6448
6449 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
6450
6451 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6452 match language_scope.language_name().0.as_ref() {
6453 "Markdown" | "Plain Text" => {
6454 should_rewrap = true;
6455 }
6456 _ => {}
6457 }
6458 }
6459
6460 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
6461
6462 // Since not all lines in the selection may be at the same indent
6463 // level, choose the indent size that is the most common between all
6464 // of the lines.
6465 //
6466 // If there is a tie, we use the deepest indent.
6467 let (indent_size, indent_end) = {
6468 let mut indent_size_occurrences = HashMap::default();
6469 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6470
6471 for row in start_row..=end_row {
6472 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6473 rows_by_indent_size.entry(indent).or_default().push(row);
6474 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6475 }
6476
6477 let indent_size = indent_size_occurrences
6478 .into_iter()
6479 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
6480 .map(|(indent, _)| indent)
6481 .unwrap_or_default();
6482 let row = rows_by_indent_size[&indent_size][0];
6483 let indent_end = Point::new(row, indent_size.len);
6484
6485 (indent_size, indent_end)
6486 };
6487
6488 let mut line_prefix = indent_size.chars().collect::<String>();
6489
6490 if let Some(comment_prefix) =
6491 buffer
6492 .language_scope_at(selection.head())
6493 .and_then(|language| {
6494 language
6495 .line_comment_prefixes()
6496 .iter()
6497 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6498 .cloned()
6499 })
6500 {
6501 line_prefix.push_str(&comment_prefix);
6502 should_rewrap = true;
6503 }
6504
6505 if !should_rewrap {
6506 continue;
6507 }
6508
6509 if selection.is_empty() {
6510 'expand_upwards: while start_row > 0 {
6511 let prev_row = start_row - 1;
6512 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6513 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6514 {
6515 start_row = prev_row;
6516 } else {
6517 break 'expand_upwards;
6518 }
6519 }
6520
6521 'expand_downwards: while end_row < buffer.max_point().row {
6522 let next_row = end_row + 1;
6523 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6524 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6525 {
6526 end_row = next_row;
6527 } else {
6528 break 'expand_downwards;
6529 }
6530 }
6531 }
6532
6533 let start = Point::new(start_row, 0);
6534 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6535 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6536 let Some(lines_without_prefixes) = selection_text
6537 .lines()
6538 .map(|line| {
6539 line.strip_prefix(&line_prefix)
6540 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6541 .ok_or_else(|| {
6542 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6543 })
6544 })
6545 .collect::<Result<Vec<_>, _>>()
6546 .log_err()
6547 else {
6548 continue;
6549 };
6550
6551 let wrap_column = buffer
6552 .settings_at(Point::new(start_row, 0), cx)
6553 .preferred_line_length as usize;
6554 let wrapped_text = wrap_with_prefix(
6555 line_prefix,
6556 lines_without_prefixes.join(" "),
6557 wrap_column,
6558 tab_size,
6559 );
6560
6561 // TODO: should always use char-based diff while still supporting cursor behavior that
6562 // matches vim.
6563 let diff = match is_vim_mode {
6564 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
6565 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
6566 };
6567 let mut offset = start.to_offset(&buffer);
6568 let mut moved_since_edit = true;
6569
6570 for change in diff.iter_all_changes() {
6571 let value = change.value();
6572 match change.tag() {
6573 ChangeTag::Equal => {
6574 offset += value.len();
6575 moved_since_edit = true;
6576 }
6577 ChangeTag::Delete => {
6578 let start = buffer.anchor_after(offset);
6579 let end = buffer.anchor_before(offset + value.len());
6580
6581 if moved_since_edit {
6582 edits.push((start..end, String::new()));
6583 } else {
6584 edits.last_mut().unwrap().0.end = end;
6585 }
6586
6587 offset += value.len();
6588 moved_since_edit = false;
6589 }
6590 ChangeTag::Insert => {
6591 if moved_since_edit {
6592 let anchor = buffer.anchor_after(offset);
6593 edits.push((anchor..anchor, value.to_string()));
6594 } else {
6595 edits.last_mut().unwrap().1.push_str(value);
6596 }
6597
6598 moved_since_edit = false;
6599 }
6600 }
6601 }
6602
6603 rewrapped_row_ranges.push(start_row..=end_row);
6604 }
6605
6606 self.buffer
6607 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6608 }
6609
6610 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
6611 let mut text = String::new();
6612 let buffer = self.buffer.read(cx).snapshot(cx);
6613 let mut selections = self.selections.all::<Point>(cx);
6614 let mut clipboard_selections = Vec::with_capacity(selections.len());
6615 {
6616 let max_point = buffer.max_point();
6617 let mut is_first = true;
6618 for selection in &mut selections {
6619 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6620 if is_entire_line {
6621 selection.start = Point::new(selection.start.row, 0);
6622 if !selection.is_empty() && selection.end.column == 0 {
6623 selection.end = cmp::min(max_point, selection.end);
6624 } else {
6625 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6626 }
6627 selection.goal = SelectionGoal::None;
6628 }
6629 if is_first {
6630 is_first = false;
6631 } else {
6632 text += "\n";
6633 }
6634 let mut len = 0;
6635 for chunk in buffer.text_for_range(selection.start..selection.end) {
6636 text.push_str(chunk);
6637 len += chunk.len();
6638 }
6639 clipboard_selections.push(ClipboardSelection {
6640 len,
6641 is_entire_line,
6642 first_line_indent: buffer
6643 .indent_size_for_line(MultiBufferRow(selection.start.row))
6644 .len,
6645 });
6646 }
6647 }
6648
6649 self.transact(cx, |this, cx| {
6650 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6651 s.select(selections);
6652 });
6653 this.insert("", cx);
6654 });
6655 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
6656 }
6657
6658 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6659 let item = self.cut_common(cx);
6660 cx.write_to_clipboard(item);
6661 }
6662
6663 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
6664 self.change_selections(None, cx, |s| {
6665 s.move_with(|snapshot, sel| {
6666 if sel.is_empty() {
6667 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
6668 }
6669 });
6670 });
6671 let item = self.cut_common(cx);
6672 cx.set_global(KillRing(item))
6673 }
6674
6675 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
6676 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
6677 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
6678 (kill_ring.text().to_string(), kill_ring.metadata_json())
6679 } else {
6680 return;
6681 }
6682 } else {
6683 return;
6684 };
6685 self.do_paste(&text, metadata, false, cx);
6686 }
6687
6688 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6689 let selections = self.selections.all::<Point>(cx);
6690 let buffer = self.buffer.read(cx).read(cx);
6691 let mut text = String::new();
6692
6693 let mut clipboard_selections = Vec::with_capacity(selections.len());
6694 {
6695 let max_point = buffer.max_point();
6696 let mut is_first = true;
6697 for selection in selections.iter() {
6698 let mut start = selection.start;
6699 let mut end = selection.end;
6700 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6701 if is_entire_line {
6702 start = Point::new(start.row, 0);
6703 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6704 }
6705 if is_first {
6706 is_first = false;
6707 } else {
6708 text += "\n";
6709 }
6710 let mut len = 0;
6711 for chunk in buffer.text_for_range(start..end) {
6712 text.push_str(chunk);
6713 len += chunk.len();
6714 }
6715 clipboard_selections.push(ClipboardSelection {
6716 len,
6717 is_entire_line,
6718 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6719 });
6720 }
6721 }
6722
6723 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6724 text,
6725 clipboard_selections,
6726 ));
6727 }
6728
6729 pub fn do_paste(
6730 &mut self,
6731 text: &String,
6732 clipboard_selections: Option<Vec<ClipboardSelection>>,
6733 handle_entire_lines: bool,
6734 cx: &mut ViewContext<Self>,
6735 ) {
6736 if self.read_only(cx) {
6737 return;
6738 }
6739
6740 let clipboard_text = Cow::Borrowed(text);
6741
6742 self.transact(cx, |this, cx| {
6743 if let Some(mut clipboard_selections) = clipboard_selections {
6744 let old_selections = this.selections.all::<usize>(cx);
6745 let all_selections_were_entire_line =
6746 clipboard_selections.iter().all(|s| s.is_entire_line);
6747 let first_selection_indent_column =
6748 clipboard_selections.first().map(|s| s.first_line_indent);
6749 if clipboard_selections.len() != old_selections.len() {
6750 clipboard_selections.drain(..);
6751 }
6752 let cursor_offset = this.selections.last::<usize>(cx).head();
6753 let mut auto_indent_on_paste = true;
6754
6755 this.buffer.update(cx, |buffer, cx| {
6756 let snapshot = buffer.read(cx);
6757 auto_indent_on_paste =
6758 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
6759
6760 let mut start_offset = 0;
6761 let mut edits = Vec::new();
6762 let mut original_indent_columns = Vec::new();
6763 for (ix, selection) in old_selections.iter().enumerate() {
6764 let to_insert;
6765 let entire_line;
6766 let original_indent_column;
6767 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6768 let end_offset = start_offset + clipboard_selection.len;
6769 to_insert = &clipboard_text[start_offset..end_offset];
6770 entire_line = clipboard_selection.is_entire_line;
6771 start_offset = end_offset + 1;
6772 original_indent_column = Some(clipboard_selection.first_line_indent);
6773 } else {
6774 to_insert = clipboard_text.as_str();
6775 entire_line = all_selections_were_entire_line;
6776 original_indent_column = first_selection_indent_column
6777 }
6778
6779 // If the corresponding selection was empty when this slice of the
6780 // clipboard text was written, then the entire line containing the
6781 // selection was copied. If this selection is also currently empty,
6782 // then paste the line before the current line of the buffer.
6783 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6784 let column = selection.start.to_point(&snapshot).column as usize;
6785 let line_start = selection.start - column;
6786 line_start..line_start
6787 } else {
6788 selection.range()
6789 };
6790
6791 edits.push((range, to_insert));
6792 original_indent_columns.extend(original_indent_column);
6793 }
6794 drop(snapshot);
6795
6796 buffer.edit(
6797 edits,
6798 if auto_indent_on_paste {
6799 Some(AutoindentMode::Block {
6800 original_indent_columns,
6801 })
6802 } else {
6803 None
6804 },
6805 cx,
6806 );
6807 });
6808
6809 let selections = this.selections.all::<usize>(cx);
6810 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6811 } else {
6812 this.insert(&clipboard_text, cx);
6813 }
6814 });
6815 }
6816
6817 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6818 if let Some(item) = cx.read_from_clipboard() {
6819 let entries = item.entries();
6820
6821 match entries.first() {
6822 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
6823 // of all the pasted entries.
6824 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
6825 .do_paste(
6826 clipboard_string.text(),
6827 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
6828 true,
6829 cx,
6830 ),
6831 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
6832 }
6833 }
6834 }
6835
6836 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
6837 if self.read_only(cx) {
6838 return;
6839 }
6840
6841 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
6842 if let Some((selections, _)) =
6843 self.selection_history.transaction(transaction_id).cloned()
6844 {
6845 self.change_selections(None, cx, |s| {
6846 s.select_anchors(selections.to_vec());
6847 });
6848 }
6849 self.request_autoscroll(Autoscroll::fit(), cx);
6850 self.unmark_text(cx);
6851 self.refresh_inline_completion(true, false, cx);
6852 cx.emit(EditorEvent::Edited { transaction_id });
6853 cx.emit(EditorEvent::TransactionUndone { transaction_id });
6854 }
6855 }
6856
6857 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
6858 if self.read_only(cx) {
6859 return;
6860 }
6861
6862 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
6863 if let Some((_, Some(selections))) =
6864 self.selection_history.transaction(transaction_id).cloned()
6865 {
6866 self.change_selections(None, cx, |s| {
6867 s.select_anchors(selections.to_vec());
6868 });
6869 }
6870 self.request_autoscroll(Autoscroll::fit(), cx);
6871 self.unmark_text(cx);
6872 self.refresh_inline_completion(true, false, cx);
6873 cx.emit(EditorEvent::Edited { transaction_id });
6874 }
6875 }
6876
6877 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
6878 self.buffer
6879 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
6880 }
6881
6882 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
6883 self.buffer
6884 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
6885 }
6886
6887 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
6888 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6889 let line_mode = s.line_mode;
6890 s.move_with(|map, selection| {
6891 let cursor = if selection.is_empty() && !line_mode {
6892 movement::left(map, selection.start)
6893 } else {
6894 selection.start
6895 };
6896 selection.collapse_to(cursor, SelectionGoal::None);
6897 });
6898 })
6899 }
6900
6901 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
6902 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6903 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
6904 })
6905 }
6906
6907 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
6908 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6909 let line_mode = s.line_mode;
6910 s.move_with(|map, selection| {
6911 let cursor = if selection.is_empty() && !line_mode {
6912 movement::right(map, selection.end)
6913 } else {
6914 selection.end
6915 };
6916 selection.collapse_to(cursor, SelectionGoal::None)
6917 });
6918 })
6919 }
6920
6921 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
6922 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6923 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
6924 })
6925 }
6926
6927 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
6928 if self.take_rename(true, cx).is_some() {
6929 return;
6930 }
6931
6932 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6933 cx.propagate();
6934 return;
6935 }
6936
6937 let text_layout_details = &self.text_layout_details(cx);
6938 let selection_count = self.selections.count();
6939 let first_selection = self.selections.first_anchor();
6940
6941 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6942 let line_mode = s.line_mode;
6943 s.move_with(|map, selection| {
6944 if !selection.is_empty() && !line_mode {
6945 selection.goal = SelectionGoal::None;
6946 }
6947 let (cursor, goal) = movement::up(
6948 map,
6949 selection.start,
6950 selection.goal,
6951 false,
6952 text_layout_details,
6953 );
6954 selection.collapse_to(cursor, goal);
6955 });
6956 });
6957
6958 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
6959 {
6960 cx.propagate();
6961 }
6962 }
6963
6964 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
6965 if self.take_rename(true, cx).is_some() {
6966 return;
6967 }
6968
6969 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6970 cx.propagate();
6971 return;
6972 }
6973
6974 let text_layout_details = &self.text_layout_details(cx);
6975
6976 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6977 let line_mode = s.line_mode;
6978 s.move_with(|map, selection| {
6979 if !selection.is_empty() && !line_mode {
6980 selection.goal = SelectionGoal::None;
6981 }
6982 let (cursor, goal) = movement::up_by_rows(
6983 map,
6984 selection.start,
6985 action.lines,
6986 selection.goal,
6987 false,
6988 text_layout_details,
6989 );
6990 selection.collapse_to(cursor, goal);
6991 });
6992 })
6993 }
6994
6995 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
6996 if self.take_rename(true, cx).is_some() {
6997 return;
6998 }
6999
7000 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7001 cx.propagate();
7002 return;
7003 }
7004
7005 let text_layout_details = &self.text_layout_details(cx);
7006
7007 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7008 let line_mode = s.line_mode;
7009 s.move_with(|map, selection| {
7010 if !selection.is_empty() && !line_mode {
7011 selection.goal = SelectionGoal::None;
7012 }
7013 let (cursor, goal) = movement::down_by_rows(
7014 map,
7015 selection.start,
7016 action.lines,
7017 selection.goal,
7018 false,
7019 text_layout_details,
7020 );
7021 selection.collapse_to(cursor, goal);
7022 });
7023 })
7024 }
7025
7026 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7027 let text_layout_details = &self.text_layout_details(cx);
7028 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7029 s.move_heads_with(|map, head, goal| {
7030 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7031 })
7032 })
7033 }
7034
7035 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7036 let text_layout_details = &self.text_layout_details(cx);
7037 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7038 s.move_heads_with(|map, head, goal| {
7039 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7040 })
7041 })
7042 }
7043
7044 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7045 let Some(row_count) = self.visible_row_count() else {
7046 return;
7047 };
7048
7049 let text_layout_details = &self.text_layout_details(cx);
7050
7051 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7052 s.move_heads_with(|map, head, goal| {
7053 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7054 })
7055 })
7056 }
7057
7058 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7059 if self.take_rename(true, cx).is_some() {
7060 return;
7061 }
7062
7063 if self
7064 .context_menu
7065 .write()
7066 .as_mut()
7067 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7068 .unwrap_or(false)
7069 {
7070 return;
7071 }
7072
7073 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7074 cx.propagate();
7075 return;
7076 }
7077
7078 let Some(row_count) = self.visible_row_count() else {
7079 return;
7080 };
7081
7082 let autoscroll = if action.center_cursor {
7083 Autoscroll::center()
7084 } else {
7085 Autoscroll::fit()
7086 };
7087
7088 let text_layout_details = &self.text_layout_details(cx);
7089
7090 self.change_selections(Some(autoscroll), cx, |s| {
7091 let line_mode = s.line_mode;
7092 s.move_with(|map, selection| {
7093 if !selection.is_empty() && !line_mode {
7094 selection.goal = SelectionGoal::None;
7095 }
7096 let (cursor, goal) = movement::up_by_rows(
7097 map,
7098 selection.end,
7099 row_count,
7100 selection.goal,
7101 false,
7102 text_layout_details,
7103 );
7104 selection.collapse_to(cursor, goal);
7105 });
7106 });
7107 }
7108
7109 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7110 let text_layout_details = &self.text_layout_details(cx);
7111 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7112 s.move_heads_with(|map, head, goal| {
7113 movement::up(map, head, goal, false, text_layout_details)
7114 })
7115 })
7116 }
7117
7118 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7119 self.take_rename(true, cx);
7120
7121 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7122 cx.propagate();
7123 return;
7124 }
7125
7126 let text_layout_details = &self.text_layout_details(cx);
7127 let selection_count = self.selections.count();
7128 let first_selection = self.selections.first_anchor();
7129
7130 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7131 let line_mode = s.line_mode;
7132 s.move_with(|map, selection| {
7133 if !selection.is_empty() && !line_mode {
7134 selection.goal = SelectionGoal::None;
7135 }
7136 let (cursor, goal) = movement::down(
7137 map,
7138 selection.end,
7139 selection.goal,
7140 false,
7141 text_layout_details,
7142 );
7143 selection.collapse_to(cursor, goal);
7144 });
7145 });
7146
7147 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7148 {
7149 cx.propagate();
7150 }
7151 }
7152
7153 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7154 let Some(row_count) = self.visible_row_count() else {
7155 return;
7156 };
7157
7158 let text_layout_details = &self.text_layout_details(cx);
7159
7160 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7161 s.move_heads_with(|map, head, goal| {
7162 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7163 })
7164 })
7165 }
7166
7167 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7168 if self.take_rename(true, cx).is_some() {
7169 return;
7170 }
7171
7172 if self
7173 .context_menu
7174 .write()
7175 .as_mut()
7176 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7177 .unwrap_or(false)
7178 {
7179 return;
7180 }
7181
7182 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7183 cx.propagate();
7184 return;
7185 }
7186
7187 let Some(row_count) = self.visible_row_count() else {
7188 return;
7189 };
7190
7191 let autoscroll = if action.center_cursor {
7192 Autoscroll::center()
7193 } else {
7194 Autoscroll::fit()
7195 };
7196
7197 let text_layout_details = &self.text_layout_details(cx);
7198 self.change_selections(Some(autoscroll), cx, |s| {
7199 let line_mode = s.line_mode;
7200 s.move_with(|map, selection| {
7201 if !selection.is_empty() && !line_mode {
7202 selection.goal = SelectionGoal::None;
7203 }
7204 let (cursor, goal) = movement::down_by_rows(
7205 map,
7206 selection.end,
7207 row_count,
7208 selection.goal,
7209 false,
7210 text_layout_details,
7211 );
7212 selection.collapse_to(cursor, goal);
7213 });
7214 });
7215 }
7216
7217 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7218 let text_layout_details = &self.text_layout_details(cx);
7219 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7220 s.move_heads_with(|map, head, goal| {
7221 movement::down(map, head, goal, false, text_layout_details)
7222 })
7223 });
7224 }
7225
7226 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7227 if let Some(context_menu) = self.context_menu.write().as_mut() {
7228 context_menu.select_first(self.completion_provider.as_deref(), cx);
7229 }
7230 }
7231
7232 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7233 if let Some(context_menu) = self.context_menu.write().as_mut() {
7234 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7235 }
7236 }
7237
7238 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7239 if let Some(context_menu) = self.context_menu.write().as_mut() {
7240 context_menu.select_next(self.completion_provider.as_deref(), cx);
7241 }
7242 }
7243
7244 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7245 if let Some(context_menu) = self.context_menu.write().as_mut() {
7246 context_menu.select_last(self.completion_provider.as_deref(), cx);
7247 }
7248 }
7249
7250 pub fn move_to_previous_word_start(
7251 &mut self,
7252 _: &MoveToPreviousWordStart,
7253 cx: &mut ViewContext<Self>,
7254 ) {
7255 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7256 s.move_cursors_with(|map, head, _| {
7257 (
7258 movement::previous_word_start(map, head),
7259 SelectionGoal::None,
7260 )
7261 });
7262 })
7263 }
7264
7265 pub fn move_to_previous_subword_start(
7266 &mut self,
7267 _: &MoveToPreviousSubwordStart,
7268 cx: &mut ViewContext<Self>,
7269 ) {
7270 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7271 s.move_cursors_with(|map, head, _| {
7272 (
7273 movement::previous_subword_start(map, head),
7274 SelectionGoal::None,
7275 )
7276 });
7277 })
7278 }
7279
7280 pub fn select_to_previous_word_start(
7281 &mut self,
7282 _: &SelectToPreviousWordStart,
7283 cx: &mut ViewContext<Self>,
7284 ) {
7285 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7286 s.move_heads_with(|map, head, _| {
7287 (
7288 movement::previous_word_start(map, head),
7289 SelectionGoal::None,
7290 )
7291 });
7292 })
7293 }
7294
7295 pub fn select_to_previous_subword_start(
7296 &mut self,
7297 _: &SelectToPreviousSubwordStart,
7298 cx: &mut ViewContext<Self>,
7299 ) {
7300 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7301 s.move_heads_with(|map, head, _| {
7302 (
7303 movement::previous_subword_start(map, head),
7304 SelectionGoal::None,
7305 )
7306 });
7307 })
7308 }
7309
7310 pub fn delete_to_previous_word_start(
7311 &mut self,
7312 action: &DeleteToPreviousWordStart,
7313 cx: &mut ViewContext<Self>,
7314 ) {
7315 self.transact(cx, |this, cx| {
7316 this.select_autoclose_pair(cx);
7317 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7318 let line_mode = s.line_mode;
7319 s.move_with(|map, selection| {
7320 if selection.is_empty() && !line_mode {
7321 let cursor = if action.ignore_newlines {
7322 movement::previous_word_start(map, selection.head())
7323 } else {
7324 movement::previous_word_start_or_newline(map, selection.head())
7325 };
7326 selection.set_head(cursor, SelectionGoal::None);
7327 }
7328 });
7329 });
7330 this.insert("", cx);
7331 });
7332 }
7333
7334 pub fn delete_to_previous_subword_start(
7335 &mut self,
7336 _: &DeleteToPreviousSubwordStart,
7337 cx: &mut ViewContext<Self>,
7338 ) {
7339 self.transact(cx, |this, cx| {
7340 this.select_autoclose_pair(cx);
7341 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7342 let line_mode = s.line_mode;
7343 s.move_with(|map, selection| {
7344 if selection.is_empty() && !line_mode {
7345 let cursor = movement::previous_subword_start(map, selection.head());
7346 selection.set_head(cursor, SelectionGoal::None);
7347 }
7348 });
7349 });
7350 this.insert("", cx);
7351 });
7352 }
7353
7354 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7355 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7356 s.move_cursors_with(|map, head, _| {
7357 (movement::next_word_end(map, head), SelectionGoal::None)
7358 });
7359 })
7360 }
7361
7362 pub fn move_to_next_subword_end(
7363 &mut self,
7364 _: &MoveToNextSubwordEnd,
7365 cx: &mut ViewContext<Self>,
7366 ) {
7367 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7368 s.move_cursors_with(|map, head, _| {
7369 (movement::next_subword_end(map, head), SelectionGoal::None)
7370 });
7371 })
7372 }
7373
7374 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7375 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7376 s.move_heads_with(|map, head, _| {
7377 (movement::next_word_end(map, head), SelectionGoal::None)
7378 });
7379 })
7380 }
7381
7382 pub fn select_to_next_subword_end(
7383 &mut self,
7384 _: &SelectToNextSubwordEnd,
7385 cx: &mut ViewContext<Self>,
7386 ) {
7387 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7388 s.move_heads_with(|map, head, _| {
7389 (movement::next_subword_end(map, head), SelectionGoal::None)
7390 });
7391 })
7392 }
7393
7394 pub fn delete_to_next_word_end(
7395 &mut self,
7396 action: &DeleteToNextWordEnd,
7397 cx: &mut ViewContext<Self>,
7398 ) {
7399 self.transact(cx, |this, cx| {
7400 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7401 let line_mode = s.line_mode;
7402 s.move_with(|map, selection| {
7403 if selection.is_empty() && !line_mode {
7404 let cursor = if action.ignore_newlines {
7405 movement::next_word_end(map, selection.head())
7406 } else {
7407 movement::next_word_end_or_newline(map, selection.head())
7408 };
7409 selection.set_head(cursor, SelectionGoal::None);
7410 }
7411 });
7412 });
7413 this.insert("", cx);
7414 });
7415 }
7416
7417 pub fn delete_to_next_subword_end(
7418 &mut self,
7419 _: &DeleteToNextSubwordEnd,
7420 cx: &mut ViewContext<Self>,
7421 ) {
7422 self.transact(cx, |this, cx| {
7423 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7424 s.move_with(|map, selection| {
7425 if selection.is_empty() {
7426 let cursor = movement::next_subword_end(map, selection.head());
7427 selection.set_head(cursor, SelectionGoal::None);
7428 }
7429 });
7430 });
7431 this.insert("", cx);
7432 });
7433 }
7434
7435 pub fn move_to_beginning_of_line(
7436 &mut self,
7437 action: &MoveToBeginningOfLine,
7438 cx: &mut ViewContext<Self>,
7439 ) {
7440 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7441 s.move_cursors_with(|map, head, _| {
7442 (
7443 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7444 SelectionGoal::None,
7445 )
7446 });
7447 })
7448 }
7449
7450 pub fn select_to_beginning_of_line(
7451 &mut self,
7452 action: &SelectToBeginningOfLine,
7453 cx: &mut ViewContext<Self>,
7454 ) {
7455 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7456 s.move_heads_with(|map, head, _| {
7457 (
7458 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7459 SelectionGoal::None,
7460 )
7461 });
7462 });
7463 }
7464
7465 pub fn delete_to_beginning_of_line(
7466 &mut self,
7467 _: &DeleteToBeginningOfLine,
7468 cx: &mut ViewContext<Self>,
7469 ) {
7470 self.transact(cx, |this, cx| {
7471 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7472 s.move_with(|_, selection| {
7473 selection.reversed = true;
7474 });
7475 });
7476
7477 this.select_to_beginning_of_line(
7478 &SelectToBeginningOfLine {
7479 stop_at_soft_wraps: false,
7480 },
7481 cx,
7482 );
7483 this.backspace(&Backspace, cx);
7484 });
7485 }
7486
7487 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7488 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7489 s.move_cursors_with(|map, head, _| {
7490 (
7491 movement::line_end(map, head, action.stop_at_soft_wraps),
7492 SelectionGoal::None,
7493 )
7494 });
7495 })
7496 }
7497
7498 pub fn select_to_end_of_line(
7499 &mut self,
7500 action: &SelectToEndOfLine,
7501 cx: &mut ViewContext<Self>,
7502 ) {
7503 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7504 s.move_heads_with(|map, head, _| {
7505 (
7506 movement::line_end(map, head, action.stop_at_soft_wraps),
7507 SelectionGoal::None,
7508 )
7509 });
7510 })
7511 }
7512
7513 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7514 self.transact(cx, |this, cx| {
7515 this.select_to_end_of_line(
7516 &SelectToEndOfLine {
7517 stop_at_soft_wraps: false,
7518 },
7519 cx,
7520 );
7521 this.delete(&Delete, cx);
7522 });
7523 }
7524
7525 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7526 self.transact(cx, |this, cx| {
7527 this.select_to_end_of_line(
7528 &SelectToEndOfLine {
7529 stop_at_soft_wraps: false,
7530 },
7531 cx,
7532 );
7533 this.cut(&Cut, cx);
7534 });
7535 }
7536
7537 pub fn move_to_start_of_paragraph(
7538 &mut self,
7539 _: &MoveToStartOfParagraph,
7540 cx: &mut ViewContext<Self>,
7541 ) {
7542 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7543 cx.propagate();
7544 return;
7545 }
7546
7547 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7548 s.move_with(|map, selection| {
7549 selection.collapse_to(
7550 movement::start_of_paragraph(map, selection.head(), 1),
7551 SelectionGoal::None,
7552 )
7553 });
7554 })
7555 }
7556
7557 pub fn move_to_end_of_paragraph(
7558 &mut self,
7559 _: &MoveToEndOfParagraph,
7560 cx: &mut ViewContext<Self>,
7561 ) {
7562 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7563 cx.propagate();
7564 return;
7565 }
7566
7567 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7568 s.move_with(|map, selection| {
7569 selection.collapse_to(
7570 movement::end_of_paragraph(map, selection.head(), 1),
7571 SelectionGoal::None,
7572 )
7573 });
7574 })
7575 }
7576
7577 pub fn select_to_start_of_paragraph(
7578 &mut self,
7579 _: &SelectToStartOfParagraph,
7580 cx: &mut ViewContext<Self>,
7581 ) {
7582 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7583 cx.propagate();
7584 return;
7585 }
7586
7587 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7588 s.move_heads_with(|map, head, _| {
7589 (
7590 movement::start_of_paragraph(map, head, 1),
7591 SelectionGoal::None,
7592 )
7593 });
7594 })
7595 }
7596
7597 pub fn select_to_end_of_paragraph(
7598 &mut self,
7599 _: &SelectToEndOfParagraph,
7600 cx: &mut ViewContext<Self>,
7601 ) {
7602 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7603 cx.propagate();
7604 return;
7605 }
7606
7607 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7608 s.move_heads_with(|map, head, _| {
7609 (
7610 movement::end_of_paragraph(map, head, 1),
7611 SelectionGoal::None,
7612 )
7613 });
7614 })
7615 }
7616
7617 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7618 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7619 cx.propagate();
7620 return;
7621 }
7622
7623 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7624 s.select_ranges(vec![0..0]);
7625 });
7626 }
7627
7628 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7629 let mut selection = self.selections.last::<Point>(cx);
7630 selection.set_head(Point::zero(), SelectionGoal::None);
7631
7632 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7633 s.select(vec![selection]);
7634 });
7635 }
7636
7637 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7638 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7639 cx.propagate();
7640 return;
7641 }
7642
7643 let cursor = self.buffer.read(cx).read(cx).len();
7644 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7645 s.select_ranges(vec![cursor..cursor])
7646 });
7647 }
7648
7649 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7650 self.nav_history = nav_history;
7651 }
7652
7653 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7654 self.nav_history.as_ref()
7655 }
7656
7657 fn push_to_nav_history(
7658 &mut self,
7659 cursor_anchor: Anchor,
7660 new_position: Option<Point>,
7661 cx: &mut ViewContext<Self>,
7662 ) {
7663 if let Some(nav_history) = self.nav_history.as_mut() {
7664 let buffer = self.buffer.read(cx).read(cx);
7665 let cursor_position = cursor_anchor.to_point(&buffer);
7666 let scroll_state = self.scroll_manager.anchor();
7667 let scroll_top_row = scroll_state.top_row(&buffer);
7668 drop(buffer);
7669
7670 if let Some(new_position) = new_position {
7671 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7672 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7673 return;
7674 }
7675 }
7676
7677 nav_history.push(
7678 Some(NavigationData {
7679 cursor_anchor,
7680 cursor_position,
7681 scroll_anchor: scroll_state,
7682 scroll_top_row,
7683 }),
7684 cx,
7685 );
7686 }
7687 }
7688
7689 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7690 let buffer = self.buffer.read(cx).snapshot(cx);
7691 let mut selection = self.selections.first::<usize>(cx);
7692 selection.set_head(buffer.len(), SelectionGoal::None);
7693 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7694 s.select(vec![selection]);
7695 });
7696 }
7697
7698 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7699 let end = self.buffer.read(cx).read(cx).len();
7700 self.change_selections(None, cx, |s| {
7701 s.select_ranges(vec![0..end]);
7702 });
7703 }
7704
7705 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7706 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7707 let mut selections = self.selections.all::<Point>(cx);
7708 let max_point = display_map.buffer_snapshot.max_point();
7709 for selection in &mut selections {
7710 let rows = selection.spanned_rows(true, &display_map);
7711 selection.start = Point::new(rows.start.0, 0);
7712 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7713 selection.reversed = false;
7714 }
7715 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7716 s.select(selections);
7717 });
7718 }
7719
7720 pub fn split_selection_into_lines(
7721 &mut self,
7722 _: &SplitSelectionIntoLines,
7723 cx: &mut ViewContext<Self>,
7724 ) {
7725 let mut to_unfold = Vec::new();
7726 let mut new_selection_ranges = Vec::new();
7727 {
7728 let selections = self.selections.all::<Point>(cx);
7729 let buffer = self.buffer.read(cx).read(cx);
7730 for selection in selections {
7731 for row in selection.start.row..selection.end.row {
7732 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7733 new_selection_ranges.push(cursor..cursor);
7734 }
7735 new_selection_ranges.push(selection.end..selection.end);
7736 to_unfold.push(selection.start..selection.end);
7737 }
7738 }
7739 self.unfold_ranges(&to_unfold, true, true, cx);
7740 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7741 s.select_ranges(new_selection_ranges);
7742 });
7743 }
7744
7745 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7746 self.add_selection(true, cx);
7747 }
7748
7749 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7750 self.add_selection(false, cx);
7751 }
7752
7753 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7754 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7755 let mut selections = self.selections.all::<Point>(cx);
7756 let text_layout_details = self.text_layout_details(cx);
7757 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7758 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7759 let range = oldest_selection.display_range(&display_map).sorted();
7760
7761 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7762 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7763 let positions = start_x.min(end_x)..start_x.max(end_x);
7764
7765 selections.clear();
7766 let mut stack = Vec::new();
7767 for row in range.start.row().0..=range.end.row().0 {
7768 if let Some(selection) = self.selections.build_columnar_selection(
7769 &display_map,
7770 DisplayRow(row),
7771 &positions,
7772 oldest_selection.reversed,
7773 &text_layout_details,
7774 ) {
7775 stack.push(selection.id);
7776 selections.push(selection);
7777 }
7778 }
7779
7780 if above {
7781 stack.reverse();
7782 }
7783
7784 AddSelectionsState { above, stack }
7785 });
7786
7787 let last_added_selection = *state.stack.last().unwrap();
7788 let mut new_selections = Vec::new();
7789 if above == state.above {
7790 let end_row = if above {
7791 DisplayRow(0)
7792 } else {
7793 display_map.max_point().row()
7794 };
7795
7796 'outer: for selection in selections {
7797 if selection.id == last_added_selection {
7798 let range = selection.display_range(&display_map).sorted();
7799 debug_assert_eq!(range.start.row(), range.end.row());
7800 let mut row = range.start.row();
7801 let positions =
7802 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7803 px(start)..px(end)
7804 } else {
7805 let start_x =
7806 display_map.x_for_display_point(range.start, &text_layout_details);
7807 let end_x =
7808 display_map.x_for_display_point(range.end, &text_layout_details);
7809 start_x.min(end_x)..start_x.max(end_x)
7810 };
7811
7812 while row != end_row {
7813 if above {
7814 row.0 -= 1;
7815 } else {
7816 row.0 += 1;
7817 }
7818
7819 if let Some(new_selection) = self.selections.build_columnar_selection(
7820 &display_map,
7821 row,
7822 &positions,
7823 selection.reversed,
7824 &text_layout_details,
7825 ) {
7826 state.stack.push(new_selection.id);
7827 if above {
7828 new_selections.push(new_selection);
7829 new_selections.push(selection);
7830 } else {
7831 new_selections.push(selection);
7832 new_selections.push(new_selection);
7833 }
7834
7835 continue 'outer;
7836 }
7837 }
7838 }
7839
7840 new_selections.push(selection);
7841 }
7842 } else {
7843 new_selections = selections;
7844 new_selections.retain(|s| s.id != last_added_selection);
7845 state.stack.pop();
7846 }
7847
7848 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7849 s.select(new_selections);
7850 });
7851 if state.stack.len() > 1 {
7852 self.add_selections_state = Some(state);
7853 }
7854 }
7855
7856 pub fn select_next_match_internal(
7857 &mut self,
7858 display_map: &DisplaySnapshot,
7859 replace_newest: bool,
7860 autoscroll: Option<Autoscroll>,
7861 cx: &mut ViewContext<Self>,
7862 ) -> Result<()> {
7863 fn select_next_match_ranges(
7864 this: &mut Editor,
7865 range: Range<usize>,
7866 replace_newest: bool,
7867 auto_scroll: Option<Autoscroll>,
7868 cx: &mut ViewContext<Editor>,
7869 ) {
7870 this.unfold_ranges(&[range.clone()], false, true, cx);
7871 this.change_selections(auto_scroll, cx, |s| {
7872 if replace_newest {
7873 s.delete(s.newest_anchor().id);
7874 }
7875 s.insert_range(range.clone());
7876 });
7877 }
7878
7879 let buffer = &display_map.buffer_snapshot;
7880 let mut selections = self.selections.all::<usize>(cx);
7881 if let Some(mut select_next_state) = self.select_next_state.take() {
7882 let query = &select_next_state.query;
7883 if !select_next_state.done {
7884 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7885 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7886 let mut next_selected_range = None;
7887
7888 let bytes_after_last_selection =
7889 buffer.bytes_in_range(last_selection.end..buffer.len());
7890 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
7891 let query_matches = query
7892 .stream_find_iter(bytes_after_last_selection)
7893 .map(|result| (last_selection.end, result))
7894 .chain(
7895 query
7896 .stream_find_iter(bytes_before_first_selection)
7897 .map(|result| (0, result)),
7898 );
7899
7900 for (start_offset, query_match) in query_matches {
7901 let query_match = query_match.unwrap(); // can only fail due to I/O
7902 let offset_range =
7903 start_offset + query_match.start()..start_offset + query_match.end();
7904 let display_range = offset_range.start.to_display_point(display_map)
7905 ..offset_range.end.to_display_point(display_map);
7906
7907 if !select_next_state.wordwise
7908 || (!movement::is_inside_word(display_map, display_range.start)
7909 && !movement::is_inside_word(display_map, display_range.end))
7910 {
7911 // TODO: This is n^2, because we might check all the selections
7912 if !selections
7913 .iter()
7914 .any(|selection| selection.range().overlaps(&offset_range))
7915 {
7916 next_selected_range = Some(offset_range);
7917 break;
7918 }
7919 }
7920 }
7921
7922 if let Some(next_selected_range) = next_selected_range {
7923 select_next_match_ranges(
7924 self,
7925 next_selected_range,
7926 replace_newest,
7927 autoscroll,
7928 cx,
7929 );
7930 } else {
7931 select_next_state.done = true;
7932 }
7933 }
7934
7935 self.select_next_state = Some(select_next_state);
7936 } else {
7937 let mut only_carets = true;
7938 let mut same_text_selected = true;
7939 let mut selected_text = None;
7940
7941 let mut selections_iter = selections.iter().peekable();
7942 while let Some(selection) = selections_iter.next() {
7943 if selection.start != selection.end {
7944 only_carets = false;
7945 }
7946
7947 if same_text_selected {
7948 if selected_text.is_none() {
7949 selected_text =
7950 Some(buffer.text_for_range(selection.range()).collect::<String>());
7951 }
7952
7953 if let Some(next_selection) = selections_iter.peek() {
7954 if next_selection.range().len() == selection.range().len() {
7955 let next_selected_text = buffer
7956 .text_for_range(next_selection.range())
7957 .collect::<String>();
7958 if Some(next_selected_text) != selected_text {
7959 same_text_selected = false;
7960 selected_text = None;
7961 }
7962 } else {
7963 same_text_selected = false;
7964 selected_text = None;
7965 }
7966 }
7967 }
7968 }
7969
7970 if only_carets {
7971 for selection in &mut selections {
7972 let word_range = movement::surrounding_word(
7973 display_map,
7974 selection.start.to_display_point(display_map),
7975 );
7976 selection.start = word_range.start.to_offset(display_map, Bias::Left);
7977 selection.end = word_range.end.to_offset(display_map, Bias::Left);
7978 selection.goal = SelectionGoal::None;
7979 selection.reversed = false;
7980 select_next_match_ranges(
7981 self,
7982 selection.start..selection.end,
7983 replace_newest,
7984 autoscroll,
7985 cx,
7986 );
7987 }
7988
7989 if selections.len() == 1 {
7990 let selection = selections
7991 .last()
7992 .expect("ensured that there's only one selection");
7993 let query = buffer
7994 .text_for_range(selection.start..selection.end)
7995 .collect::<String>();
7996 let is_empty = query.is_empty();
7997 let select_state = SelectNextState {
7998 query: AhoCorasick::new(&[query])?,
7999 wordwise: true,
8000 done: is_empty,
8001 };
8002 self.select_next_state = Some(select_state);
8003 } else {
8004 self.select_next_state = None;
8005 }
8006 } else if let Some(selected_text) = selected_text {
8007 self.select_next_state = Some(SelectNextState {
8008 query: AhoCorasick::new(&[selected_text])?,
8009 wordwise: false,
8010 done: false,
8011 });
8012 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8013 }
8014 }
8015 Ok(())
8016 }
8017
8018 pub fn select_all_matches(
8019 &mut self,
8020 _action: &SelectAllMatches,
8021 cx: &mut ViewContext<Self>,
8022 ) -> Result<()> {
8023 self.push_to_selection_history();
8024 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8025
8026 self.select_next_match_internal(&display_map, false, None, cx)?;
8027 let Some(select_next_state) = self.select_next_state.as_mut() else {
8028 return Ok(());
8029 };
8030 if select_next_state.done {
8031 return Ok(());
8032 }
8033
8034 let mut new_selections = self.selections.all::<usize>(cx);
8035
8036 let buffer = &display_map.buffer_snapshot;
8037 let query_matches = select_next_state
8038 .query
8039 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8040
8041 for query_match in query_matches {
8042 let query_match = query_match.unwrap(); // can only fail due to I/O
8043 let offset_range = query_match.start()..query_match.end();
8044 let display_range = offset_range.start.to_display_point(&display_map)
8045 ..offset_range.end.to_display_point(&display_map);
8046
8047 if !select_next_state.wordwise
8048 || (!movement::is_inside_word(&display_map, display_range.start)
8049 && !movement::is_inside_word(&display_map, display_range.end))
8050 {
8051 self.selections.change_with(cx, |selections| {
8052 new_selections.push(Selection {
8053 id: selections.new_selection_id(),
8054 start: offset_range.start,
8055 end: offset_range.end,
8056 reversed: false,
8057 goal: SelectionGoal::None,
8058 });
8059 });
8060 }
8061 }
8062
8063 new_selections.sort_by_key(|selection| selection.start);
8064 let mut ix = 0;
8065 while ix + 1 < new_selections.len() {
8066 let current_selection = &new_selections[ix];
8067 let next_selection = &new_selections[ix + 1];
8068 if current_selection.range().overlaps(&next_selection.range()) {
8069 if current_selection.id < next_selection.id {
8070 new_selections.remove(ix + 1);
8071 } else {
8072 new_selections.remove(ix);
8073 }
8074 } else {
8075 ix += 1;
8076 }
8077 }
8078
8079 select_next_state.done = true;
8080 self.unfold_ranges(
8081 &new_selections
8082 .iter()
8083 .map(|selection| selection.range())
8084 .collect::<Vec<_>>(),
8085 false,
8086 false,
8087 cx,
8088 );
8089 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8090 selections.select(new_selections)
8091 });
8092
8093 Ok(())
8094 }
8095
8096 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8097 self.push_to_selection_history();
8098 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8099 self.select_next_match_internal(
8100 &display_map,
8101 action.replace_newest,
8102 Some(Autoscroll::newest()),
8103 cx,
8104 )?;
8105 Ok(())
8106 }
8107
8108 pub fn select_previous(
8109 &mut self,
8110 action: &SelectPrevious,
8111 cx: &mut ViewContext<Self>,
8112 ) -> Result<()> {
8113 self.push_to_selection_history();
8114 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8115 let buffer = &display_map.buffer_snapshot;
8116 let mut selections = self.selections.all::<usize>(cx);
8117 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8118 let query = &select_prev_state.query;
8119 if !select_prev_state.done {
8120 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8121 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8122 let mut next_selected_range = None;
8123 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8124 let bytes_before_last_selection =
8125 buffer.reversed_bytes_in_range(0..last_selection.start);
8126 let bytes_after_first_selection =
8127 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8128 let query_matches = query
8129 .stream_find_iter(bytes_before_last_selection)
8130 .map(|result| (last_selection.start, result))
8131 .chain(
8132 query
8133 .stream_find_iter(bytes_after_first_selection)
8134 .map(|result| (buffer.len(), result)),
8135 );
8136 for (end_offset, query_match) in query_matches {
8137 let query_match = query_match.unwrap(); // can only fail due to I/O
8138 let offset_range =
8139 end_offset - query_match.end()..end_offset - query_match.start();
8140 let display_range = offset_range.start.to_display_point(&display_map)
8141 ..offset_range.end.to_display_point(&display_map);
8142
8143 if !select_prev_state.wordwise
8144 || (!movement::is_inside_word(&display_map, display_range.start)
8145 && !movement::is_inside_word(&display_map, display_range.end))
8146 {
8147 next_selected_range = Some(offset_range);
8148 break;
8149 }
8150 }
8151
8152 if let Some(next_selected_range) = next_selected_range {
8153 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8154 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8155 if action.replace_newest {
8156 s.delete(s.newest_anchor().id);
8157 }
8158 s.insert_range(next_selected_range);
8159 });
8160 } else {
8161 select_prev_state.done = true;
8162 }
8163 }
8164
8165 self.select_prev_state = Some(select_prev_state);
8166 } else {
8167 let mut only_carets = true;
8168 let mut same_text_selected = true;
8169 let mut selected_text = None;
8170
8171 let mut selections_iter = selections.iter().peekable();
8172 while let Some(selection) = selections_iter.next() {
8173 if selection.start != selection.end {
8174 only_carets = false;
8175 }
8176
8177 if same_text_selected {
8178 if selected_text.is_none() {
8179 selected_text =
8180 Some(buffer.text_for_range(selection.range()).collect::<String>());
8181 }
8182
8183 if let Some(next_selection) = selections_iter.peek() {
8184 if next_selection.range().len() == selection.range().len() {
8185 let next_selected_text = buffer
8186 .text_for_range(next_selection.range())
8187 .collect::<String>();
8188 if Some(next_selected_text) != selected_text {
8189 same_text_selected = false;
8190 selected_text = None;
8191 }
8192 } else {
8193 same_text_selected = false;
8194 selected_text = None;
8195 }
8196 }
8197 }
8198 }
8199
8200 if only_carets {
8201 for selection in &mut selections {
8202 let word_range = movement::surrounding_word(
8203 &display_map,
8204 selection.start.to_display_point(&display_map),
8205 );
8206 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8207 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8208 selection.goal = SelectionGoal::None;
8209 selection.reversed = false;
8210 }
8211 if selections.len() == 1 {
8212 let selection = selections
8213 .last()
8214 .expect("ensured that there's only one selection");
8215 let query = buffer
8216 .text_for_range(selection.start..selection.end)
8217 .collect::<String>();
8218 let is_empty = query.is_empty();
8219 let select_state = SelectNextState {
8220 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8221 wordwise: true,
8222 done: is_empty,
8223 };
8224 self.select_prev_state = Some(select_state);
8225 } else {
8226 self.select_prev_state = None;
8227 }
8228
8229 self.unfold_ranges(
8230 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8231 false,
8232 true,
8233 cx,
8234 );
8235 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8236 s.select(selections);
8237 });
8238 } else if let Some(selected_text) = selected_text {
8239 self.select_prev_state = Some(SelectNextState {
8240 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8241 wordwise: false,
8242 done: false,
8243 });
8244 self.select_previous(action, cx)?;
8245 }
8246 }
8247 Ok(())
8248 }
8249
8250 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8251 if self.read_only(cx) {
8252 return;
8253 }
8254 let text_layout_details = &self.text_layout_details(cx);
8255 self.transact(cx, |this, cx| {
8256 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8257 let mut edits = Vec::new();
8258 let mut selection_edit_ranges = Vec::new();
8259 let mut last_toggled_row = None;
8260 let snapshot = this.buffer.read(cx).read(cx);
8261 let empty_str: Arc<str> = Arc::default();
8262 let mut suffixes_inserted = Vec::new();
8263 let ignore_indent = action.ignore_indent;
8264
8265 fn comment_prefix_range(
8266 snapshot: &MultiBufferSnapshot,
8267 row: MultiBufferRow,
8268 comment_prefix: &str,
8269 comment_prefix_whitespace: &str,
8270 ignore_indent: bool,
8271 ) -> Range<Point> {
8272 let indent_size = if ignore_indent {
8273 0
8274 } else {
8275 snapshot.indent_size_for_line(row).len
8276 };
8277
8278 let start = Point::new(row.0, indent_size);
8279
8280 let mut line_bytes = snapshot
8281 .bytes_in_range(start..snapshot.max_point())
8282 .flatten()
8283 .copied();
8284
8285 // If this line currently begins with the line comment prefix, then record
8286 // the range containing the prefix.
8287 if line_bytes
8288 .by_ref()
8289 .take(comment_prefix.len())
8290 .eq(comment_prefix.bytes())
8291 {
8292 // Include any whitespace that matches the comment prefix.
8293 let matching_whitespace_len = line_bytes
8294 .zip(comment_prefix_whitespace.bytes())
8295 .take_while(|(a, b)| a == b)
8296 .count() as u32;
8297 let end = Point::new(
8298 start.row,
8299 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8300 );
8301 start..end
8302 } else {
8303 start..start
8304 }
8305 }
8306
8307 fn comment_suffix_range(
8308 snapshot: &MultiBufferSnapshot,
8309 row: MultiBufferRow,
8310 comment_suffix: &str,
8311 comment_suffix_has_leading_space: bool,
8312 ) -> Range<Point> {
8313 let end = Point::new(row.0, snapshot.line_len(row));
8314 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8315
8316 let mut line_end_bytes = snapshot
8317 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8318 .flatten()
8319 .copied();
8320
8321 let leading_space_len = if suffix_start_column > 0
8322 && line_end_bytes.next() == Some(b' ')
8323 && comment_suffix_has_leading_space
8324 {
8325 1
8326 } else {
8327 0
8328 };
8329
8330 // If this line currently begins with the line comment prefix, then record
8331 // the range containing the prefix.
8332 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8333 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8334 start..end
8335 } else {
8336 end..end
8337 }
8338 }
8339
8340 // TODO: Handle selections that cross excerpts
8341 for selection in &mut selections {
8342 let start_column = snapshot
8343 .indent_size_for_line(MultiBufferRow(selection.start.row))
8344 .len;
8345 let language = if let Some(language) =
8346 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8347 {
8348 language
8349 } else {
8350 continue;
8351 };
8352
8353 selection_edit_ranges.clear();
8354
8355 // If multiple selections contain a given row, avoid processing that
8356 // row more than once.
8357 let mut start_row = MultiBufferRow(selection.start.row);
8358 if last_toggled_row == Some(start_row) {
8359 start_row = start_row.next_row();
8360 }
8361 let end_row =
8362 if selection.end.row > selection.start.row && selection.end.column == 0 {
8363 MultiBufferRow(selection.end.row - 1)
8364 } else {
8365 MultiBufferRow(selection.end.row)
8366 };
8367 last_toggled_row = Some(end_row);
8368
8369 if start_row > end_row {
8370 continue;
8371 }
8372
8373 // If the language has line comments, toggle those.
8374 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8375
8376 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8377 if ignore_indent {
8378 full_comment_prefixes = full_comment_prefixes
8379 .into_iter()
8380 .map(|s| Arc::from(s.trim_end()))
8381 .collect();
8382 }
8383
8384 if !full_comment_prefixes.is_empty() {
8385 let first_prefix = full_comment_prefixes
8386 .first()
8387 .expect("prefixes is non-empty");
8388 let prefix_trimmed_lengths = full_comment_prefixes
8389 .iter()
8390 .map(|p| p.trim_end_matches(' ').len())
8391 .collect::<SmallVec<[usize; 4]>>();
8392
8393 let mut all_selection_lines_are_comments = true;
8394
8395 for row in start_row.0..=end_row.0 {
8396 let row = MultiBufferRow(row);
8397 if start_row < end_row && snapshot.is_line_blank(row) {
8398 continue;
8399 }
8400
8401 let prefix_range = full_comment_prefixes
8402 .iter()
8403 .zip(prefix_trimmed_lengths.iter().copied())
8404 .map(|(prefix, trimmed_prefix_len)| {
8405 comment_prefix_range(
8406 snapshot.deref(),
8407 row,
8408 &prefix[..trimmed_prefix_len],
8409 &prefix[trimmed_prefix_len..],
8410 ignore_indent,
8411 )
8412 })
8413 .max_by_key(|range| range.end.column - range.start.column)
8414 .expect("prefixes is non-empty");
8415
8416 if prefix_range.is_empty() {
8417 all_selection_lines_are_comments = false;
8418 }
8419
8420 selection_edit_ranges.push(prefix_range);
8421 }
8422
8423 if all_selection_lines_are_comments {
8424 edits.extend(
8425 selection_edit_ranges
8426 .iter()
8427 .cloned()
8428 .map(|range| (range, empty_str.clone())),
8429 );
8430 } else {
8431 let min_column = selection_edit_ranges
8432 .iter()
8433 .map(|range| range.start.column)
8434 .min()
8435 .unwrap_or(0);
8436 edits.extend(selection_edit_ranges.iter().map(|range| {
8437 let position = Point::new(range.start.row, min_column);
8438 (position..position, first_prefix.clone())
8439 }));
8440 }
8441 } else if let Some((full_comment_prefix, comment_suffix)) =
8442 language.block_comment_delimiters()
8443 {
8444 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8445 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8446 let prefix_range = comment_prefix_range(
8447 snapshot.deref(),
8448 start_row,
8449 comment_prefix,
8450 comment_prefix_whitespace,
8451 ignore_indent,
8452 );
8453 let suffix_range = comment_suffix_range(
8454 snapshot.deref(),
8455 end_row,
8456 comment_suffix.trim_start_matches(' '),
8457 comment_suffix.starts_with(' '),
8458 );
8459
8460 if prefix_range.is_empty() || suffix_range.is_empty() {
8461 edits.push((
8462 prefix_range.start..prefix_range.start,
8463 full_comment_prefix.clone(),
8464 ));
8465 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8466 suffixes_inserted.push((end_row, comment_suffix.len()));
8467 } else {
8468 edits.push((prefix_range, empty_str.clone()));
8469 edits.push((suffix_range, empty_str.clone()));
8470 }
8471 } else {
8472 continue;
8473 }
8474 }
8475
8476 drop(snapshot);
8477 this.buffer.update(cx, |buffer, cx| {
8478 buffer.edit(edits, None, cx);
8479 });
8480
8481 // Adjust selections so that they end before any comment suffixes that
8482 // were inserted.
8483 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8484 let mut selections = this.selections.all::<Point>(cx);
8485 let snapshot = this.buffer.read(cx).read(cx);
8486 for selection in &mut selections {
8487 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8488 match row.cmp(&MultiBufferRow(selection.end.row)) {
8489 Ordering::Less => {
8490 suffixes_inserted.next();
8491 continue;
8492 }
8493 Ordering::Greater => break,
8494 Ordering::Equal => {
8495 if selection.end.column == snapshot.line_len(row) {
8496 if selection.is_empty() {
8497 selection.start.column -= suffix_len as u32;
8498 }
8499 selection.end.column -= suffix_len as u32;
8500 }
8501 break;
8502 }
8503 }
8504 }
8505 }
8506
8507 drop(snapshot);
8508 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8509
8510 let selections = this.selections.all::<Point>(cx);
8511 let selections_on_single_row = selections.windows(2).all(|selections| {
8512 selections[0].start.row == selections[1].start.row
8513 && selections[0].end.row == selections[1].end.row
8514 && selections[0].start.row == selections[0].end.row
8515 });
8516 let selections_selecting = selections
8517 .iter()
8518 .any(|selection| selection.start != selection.end);
8519 let advance_downwards = action.advance_downwards
8520 && selections_on_single_row
8521 && !selections_selecting
8522 && !matches!(this.mode, EditorMode::SingleLine { .. });
8523
8524 if advance_downwards {
8525 let snapshot = this.buffer.read(cx).snapshot(cx);
8526
8527 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8528 s.move_cursors_with(|display_snapshot, display_point, _| {
8529 let mut point = display_point.to_point(display_snapshot);
8530 point.row += 1;
8531 point = snapshot.clip_point(point, Bias::Left);
8532 let display_point = point.to_display_point(display_snapshot);
8533 let goal = SelectionGoal::HorizontalPosition(
8534 display_snapshot
8535 .x_for_display_point(display_point, text_layout_details)
8536 .into(),
8537 );
8538 (display_point, goal)
8539 })
8540 });
8541 }
8542 });
8543 }
8544
8545 pub fn select_enclosing_symbol(
8546 &mut self,
8547 _: &SelectEnclosingSymbol,
8548 cx: &mut ViewContext<Self>,
8549 ) {
8550 let buffer = self.buffer.read(cx).snapshot(cx);
8551 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8552
8553 fn update_selection(
8554 selection: &Selection<usize>,
8555 buffer_snap: &MultiBufferSnapshot,
8556 ) -> Option<Selection<usize>> {
8557 let cursor = selection.head();
8558 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8559 for symbol in symbols.iter().rev() {
8560 let start = symbol.range.start.to_offset(buffer_snap);
8561 let end = symbol.range.end.to_offset(buffer_snap);
8562 let new_range = start..end;
8563 if start < selection.start || end > selection.end {
8564 return Some(Selection {
8565 id: selection.id,
8566 start: new_range.start,
8567 end: new_range.end,
8568 goal: SelectionGoal::None,
8569 reversed: selection.reversed,
8570 });
8571 }
8572 }
8573 None
8574 }
8575
8576 let mut selected_larger_symbol = false;
8577 let new_selections = old_selections
8578 .iter()
8579 .map(|selection| match update_selection(selection, &buffer) {
8580 Some(new_selection) => {
8581 if new_selection.range() != selection.range() {
8582 selected_larger_symbol = true;
8583 }
8584 new_selection
8585 }
8586 None => selection.clone(),
8587 })
8588 .collect::<Vec<_>>();
8589
8590 if selected_larger_symbol {
8591 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8592 s.select(new_selections);
8593 });
8594 }
8595 }
8596
8597 pub fn select_larger_syntax_node(
8598 &mut self,
8599 _: &SelectLargerSyntaxNode,
8600 cx: &mut ViewContext<Self>,
8601 ) {
8602 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8603 let buffer = self.buffer.read(cx).snapshot(cx);
8604 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8605
8606 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8607 let mut selected_larger_node = false;
8608 let new_selections = old_selections
8609 .iter()
8610 .map(|selection| {
8611 let old_range = selection.start..selection.end;
8612 let mut new_range = old_range.clone();
8613 while let Some(containing_range) =
8614 buffer.range_for_syntax_ancestor(new_range.clone())
8615 {
8616 new_range = containing_range;
8617 if !display_map.intersects_fold(new_range.start)
8618 && !display_map.intersects_fold(new_range.end)
8619 {
8620 break;
8621 }
8622 }
8623
8624 selected_larger_node |= new_range != old_range;
8625 Selection {
8626 id: selection.id,
8627 start: new_range.start,
8628 end: new_range.end,
8629 goal: SelectionGoal::None,
8630 reversed: selection.reversed,
8631 }
8632 })
8633 .collect::<Vec<_>>();
8634
8635 if selected_larger_node {
8636 stack.push(old_selections);
8637 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8638 s.select(new_selections);
8639 });
8640 }
8641 self.select_larger_syntax_node_stack = stack;
8642 }
8643
8644 pub fn select_smaller_syntax_node(
8645 &mut self,
8646 _: &SelectSmallerSyntaxNode,
8647 cx: &mut ViewContext<Self>,
8648 ) {
8649 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8650 if let Some(selections) = stack.pop() {
8651 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8652 s.select(selections.to_vec());
8653 });
8654 }
8655 self.select_larger_syntax_node_stack = stack;
8656 }
8657
8658 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8659 if !EditorSettings::get_global(cx).gutter.runnables {
8660 self.clear_tasks();
8661 return Task::ready(());
8662 }
8663 let project = self.project.as_ref().map(Model::downgrade);
8664 cx.spawn(|this, mut cx| async move {
8665 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
8666 let Some(project) = project.and_then(|p| p.upgrade()) else {
8667 return;
8668 };
8669 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8670 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8671 }) else {
8672 return;
8673 };
8674
8675 let hide_runnables = project
8676 .update(&mut cx, |project, cx| {
8677 // Do not display any test indicators in non-dev server remote projects.
8678 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8679 })
8680 .unwrap_or(true);
8681 if hide_runnables {
8682 return;
8683 }
8684 let new_rows =
8685 cx.background_executor()
8686 .spawn({
8687 let snapshot = display_snapshot.clone();
8688 async move {
8689 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8690 }
8691 })
8692 .await;
8693 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8694
8695 this.update(&mut cx, |this, _| {
8696 this.clear_tasks();
8697 for (key, value) in rows {
8698 this.insert_tasks(key, value);
8699 }
8700 })
8701 .ok();
8702 })
8703 }
8704 fn fetch_runnable_ranges(
8705 snapshot: &DisplaySnapshot,
8706 range: Range<Anchor>,
8707 ) -> Vec<language::RunnableRange> {
8708 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8709 }
8710
8711 fn runnable_rows(
8712 project: Model<Project>,
8713 snapshot: DisplaySnapshot,
8714 runnable_ranges: Vec<RunnableRange>,
8715 mut cx: AsyncWindowContext,
8716 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8717 runnable_ranges
8718 .into_iter()
8719 .filter_map(|mut runnable| {
8720 let tasks = cx
8721 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8722 .ok()?;
8723 if tasks.is_empty() {
8724 return None;
8725 }
8726
8727 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8728
8729 let row = snapshot
8730 .buffer_snapshot
8731 .buffer_line_for_row(MultiBufferRow(point.row))?
8732 .1
8733 .start
8734 .row;
8735
8736 let context_range =
8737 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8738 Some((
8739 (runnable.buffer_id, row),
8740 RunnableTasks {
8741 templates: tasks,
8742 offset: MultiBufferOffset(runnable.run_range.start),
8743 context_range,
8744 column: point.column,
8745 extra_variables: runnable.extra_captures,
8746 },
8747 ))
8748 })
8749 .collect()
8750 }
8751
8752 fn templates_with_tags(
8753 project: &Model<Project>,
8754 runnable: &mut Runnable,
8755 cx: &WindowContext<'_>,
8756 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8757 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8758 let (worktree_id, file) = project
8759 .buffer_for_id(runnable.buffer, cx)
8760 .and_then(|buffer| buffer.read(cx).file())
8761 .map(|file| (file.worktree_id(cx), file.clone()))
8762 .unzip();
8763
8764 (
8765 project.task_store().read(cx).task_inventory().cloned(),
8766 worktree_id,
8767 file,
8768 )
8769 });
8770
8771 let tags = mem::take(&mut runnable.tags);
8772 let mut tags: Vec<_> = tags
8773 .into_iter()
8774 .flat_map(|tag| {
8775 let tag = tag.0.clone();
8776 inventory
8777 .as_ref()
8778 .into_iter()
8779 .flat_map(|inventory| {
8780 inventory.read(cx).list_tasks(
8781 file.clone(),
8782 Some(runnable.language.clone()),
8783 worktree_id,
8784 cx,
8785 )
8786 })
8787 .filter(move |(_, template)| {
8788 template.tags.iter().any(|source_tag| source_tag == &tag)
8789 })
8790 })
8791 .sorted_by_key(|(kind, _)| kind.to_owned())
8792 .collect();
8793 if let Some((leading_tag_source, _)) = tags.first() {
8794 // Strongest source wins; if we have worktree tag binding, prefer that to
8795 // global and language bindings;
8796 // if we have a global binding, prefer that to language binding.
8797 let first_mismatch = tags
8798 .iter()
8799 .position(|(tag_source, _)| tag_source != leading_tag_source);
8800 if let Some(index) = first_mismatch {
8801 tags.truncate(index);
8802 }
8803 }
8804
8805 tags
8806 }
8807
8808 pub fn move_to_enclosing_bracket(
8809 &mut self,
8810 _: &MoveToEnclosingBracket,
8811 cx: &mut ViewContext<Self>,
8812 ) {
8813 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8814 s.move_offsets_with(|snapshot, selection| {
8815 let Some(enclosing_bracket_ranges) =
8816 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8817 else {
8818 return;
8819 };
8820
8821 let mut best_length = usize::MAX;
8822 let mut best_inside = false;
8823 let mut best_in_bracket_range = false;
8824 let mut best_destination = None;
8825 for (open, close) in enclosing_bracket_ranges {
8826 let close = close.to_inclusive();
8827 let length = close.end() - open.start;
8828 let inside = selection.start >= open.end && selection.end <= *close.start();
8829 let in_bracket_range = open.to_inclusive().contains(&selection.head())
8830 || close.contains(&selection.head());
8831
8832 // If best is next to a bracket and current isn't, skip
8833 if !in_bracket_range && best_in_bracket_range {
8834 continue;
8835 }
8836
8837 // Prefer smaller lengths unless best is inside and current isn't
8838 if length > best_length && (best_inside || !inside) {
8839 continue;
8840 }
8841
8842 best_length = length;
8843 best_inside = inside;
8844 best_in_bracket_range = in_bracket_range;
8845 best_destination = Some(
8846 if close.contains(&selection.start) && close.contains(&selection.end) {
8847 if inside {
8848 open.end
8849 } else {
8850 open.start
8851 }
8852 } else if inside {
8853 *close.start()
8854 } else {
8855 *close.end()
8856 },
8857 );
8858 }
8859
8860 if let Some(destination) = best_destination {
8861 selection.collapse_to(destination, SelectionGoal::None);
8862 }
8863 })
8864 });
8865 }
8866
8867 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
8868 self.end_selection(cx);
8869 self.selection_history.mode = SelectionHistoryMode::Undoing;
8870 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
8871 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8872 self.select_next_state = entry.select_next_state;
8873 self.select_prev_state = entry.select_prev_state;
8874 self.add_selections_state = entry.add_selections_state;
8875 self.request_autoscroll(Autoscroll::newest(), cx);
8876 }
8877 self.selection_history.mode = SelectionHistoryMode::Normal;
8878 }
8879
8880 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
8881 self.end_selection(cx);
8882 self.selection_history.mode = SelectionHistoryMode::Redoing;
8883 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
8884 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8885 self.select_next_state = entry.select_next_state;
8886 self.select_prev_state = entry.select_prev_state;
8887 self.add_selections_state = entry.add_selections_state;
8888 self.request_autoscroll(Autoscroll::newest(), cx);
8889 }
8890 self.selection_history.mode = SelectionHistoryMode::Normal;
8891 }
8892
8893 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
8894 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
8895 }
8896
8897 pub fn expand_excerpts_down(
8898 &mut self,
8899 action: &ExpandExcerptsDown,
8900 cx: &mut ViewContext<Self>,
8901 ) {
8902 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
8903 }
8904
8905 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
8906 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
8907 }
8908
8909 pub fn expand_excerpts_for_direction(
8910 &mut self,
8911 lines: u32,
8912 direction: ExpandExcerptDirection,
8913 cx: &mut ViewContext<Self>,
8914 ) {
8915 let selections = self.selections.disjoint_anchors();
8916
8917 let lines = if lines == 0 {
8918 EditorSettings::get_global(cx).expand_excerpt_lines
8919 } else {
8920 lines
8921 };
8922
8923 self.buffer.update(cx, |buffer, cx| {
8924 buffer.expand_excerpts(
8925 selections
8926 .iter()
8927 .map(|selection| selection.head().excerpt_id)
8928 .dedup(),
8929 lines,
8930 direction,
8931 cx,
8932 )
8933 })
8934 }
8935
8936 pub fn expand_excerpt(
8937 &mut self,
8938 excerpt: ExcerptId,
8939 direction: ExpandExcerptDirection,
8940 cx: &mut ViewContext<Self>,
8941 ) {
8942 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
8943 self.buffer.update(cx, |buffer, cx| {
8944 buffer.expand_excerpts([excerpt], lines, direction, cx)
8945 })
8946 }
8947
8948 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
8949 self.go_to_diagnostic_impl(Direction::Next, cx)
8950 }
8951
8952 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
8953 self.go_to_diagnostic_impl(Direction::Prev, cx)
8954 }
8955
8956 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
8957 let buffer = self.buffer.read(cx).snapshot(cx);
8958 let selection = self.selections.newest::<usize>(cx);
8959
8960 // If there is an active Diagnostic Popover jump to its diagnostic instead.
8961 if direction == Direction::Next {
8962 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
8963 let (group_id, jump_to) = popover.activation_info();
8964 if self.activate_diagnostics(group_id, cx) {
8965 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8966 let mut new_selection = s.newest_anchor().clone();
8967 new_selection.collapse_to(jump_to, SelectionGoal::None);
8968 s.select_anchors(vec![new_selection.clone()]);
8969 });
8970 }
8971 return;
8972 }
8973 }
8974
8975 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
8976 active_diagnostics
8977 .primary_range
8978 .to_offset(&buffer)
8979 .to_inclusive()
8980 });
8981 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
8982 if active_primary_range.contains(&selection.head()) {
8983 *active_primary_range.start()
8984 } else {
8985 selection.head()
8986 }
8987 } else {
8988 selection.head()
8989 };
8990 let snapshot = self.snapshot(cx);
8991 loop {
8992 let diagnostics = if direction == Direction::Prev {
8993 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
8994 } else {
8995 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
8996 }
8997 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
8998 let group = diagnostics
8999 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9000 // be sorted in a stable way
9001 // skip until we are at current active diagnostic, if it exists
9002 .skip_while(|entry| {
9003 (match direction {
9004 Direction::Prev => entry.range.start >= search_start,
9005 Direction::Next => entry.range.start <= search_start,
9006 }) && self
9007 .active_diagnostics
9008 .as_ref()
9009 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9010 })
9011 .find_map(|entry| {
9012 if entry.diagnostic.is_primary
9013 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9014 && !entry.range.is_empty()
9015 // if we match with the active diagnostic, skip it
9016 && Some(entry.diagnostic.group_id)
9017 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9018 {
9019 Some((entry.range, entry.diagnostic.group_id))
9020 } else {
9021 None
9022 }
9023 });
9024
9025 if let Some((primary_range, group_id)) = group {
9026 if self.activate_diagnostics(group_id, cx) {
9027 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9028 s.select(vec![Selection {
9029 id: selection.id,
9030 start: primary_range.start,
9031 end: primary_range.start,
9032 reversed: false,
9033 goal: SelectionGoal::None,
9034 }]);
9035 });
9036 }
9037 break;
9038 } else {
9039 // Cycle around to the start of the buffer, potentially moving back to the start of
9040 // the currently active diagnostic.
9041 active_primary_range.take();
9042 if direction == Direction::Prev {
9043 if search_start == buffer.len() {
9044 break;
9045 } else {
9046 search_start = buffer.len();
9047 }
9048 } else if search_start == 0 {
9049 break;
9050 } else {
9051 search_start = 0;
9052 }
9053 }
9054 }
9055 }
9056
9057 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9058 let snapshot = self.snapshot(cx);
9059 let selection = self.selections.newest::<Point>(cx);
9060 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9061 }
9062
9063 fn go_to_hunk_after_position(
9064 &mut self,
9065 snapshot: &EditorSnapshot,
9066 position: Point,
9067 cx: &mut ViewContext<'_, Editor>,
9068 ) -> Option<MultiBufferDiffHunk> {
9069 for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
9070 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9071 snapshot,
9072 position,
9073 ix > 0,
9074 snapshot.diff_map.diff_hunks_in_range(
9075 position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
9076 &snapshot.buffer_snapshot,
9077 ),
9078 cx,
9079 ) {
9080 return Some(hunk);
9081 }
9082 }
9083 None
9084 }
9085
9086 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9087 let snapshot = self.snapshot(cx);
9088 let selection = self.selections.newest::<Point>(cx);
9089 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9090 }
9091
9092 fn go_to_hunk_before_position(
9093 &mut self,
9094 snapshot: &EditorSnapshot,
9095 position: Point,
9096 cx: &mut ViewContext<'_, Editor>,
9097 ) -> Option<MultiBufferDiffHunk> {
9098 for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
9099 .into_iter()
9100 .enumerate()
9101 {
9102 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9103 snapshot,
9104 position,
9105 ix > 0,
9106 snapshot
9107 .diff_map
9108 .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
9109 cx,
9110 ) {
9111 return Some(hunk);
9112 }
9113 }
9114 None
9115 }
9116
9117 fn go_to_next_hunk_in_direction(
9118 &mut self,
9119 snapshot: &DisplaySnapshot,
9120 initial_point: Point,
9121 is_wrapped: bool,
9122 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9123 cx: &mut ViewContext<Editor>,
9124 ) -> Option<MultiBufferDiffHunk> {
9125 let display_point = initial_point.to_display_point(snapshot);
9126 let mut hunks = hunks
9127 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9128 .filter(|(display_hunk, _)| {
9129 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9130 })
9131 .dedup();
9132
9133 if let Some((display_hunk, hunk)) = hunks.next() {
9134 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9135 let row = display_hunk.start_display_row();
9136 let point = DisplayPoint::new(row, 0);
9137 s.select_display_ranges([point..point]);
9138 });
9139
9140 Some(hunk)
9141 } else {
9142 None
9143 }
9144 }
9145
9146 pub fn go_to_definition(
9147 &mut self,
9148 _: &GoToDefinition,
9149 cx: &mut ViewContext<Self>,
9150 ) -> Task<Result<Navigated>> {
9151 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9152 cx.spawn(|editor, mut cx| async move {
9153 if definition.await? == Navigated::Yes {
9154 return Ok(Navigated::Yes);
9155 }
9156 match editor.update(&mut cx, |editor, cx| {
9157 editor.find_all_references(&FindAllReferences, cx)
9158 })? {
9159 Some(references) => references.await,
9160 None => Ok(Navigated::No),
9161 }
9162 })
9163 }
9164
9165 pub fn go_to_declaration(
9166 &mut self,
9167 _: &GoToDeclaration,
9168 cx: &mut ViewContext<Self>,
9169 ) -> Task<Result<Navigated>> {
9170 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9171 }
9172
9173 pub fn go_to_declaration_split(
9174 &mut self,
9175 _: &GoToDeclaration,
9176 cx: &mut ViewContext<Self>,
9177 ) -> Task<Result<Navigated>> {
9178 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9179 }
9180
9181 pub fn go_to_implementation(
9182 &mut self,
9183 _: &GoToImplementation,
9184 cx: &mut ViewContext<Self>,
9185 ) -> Task<Result<Navigated>> {
9186 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9187 }
9188
9189 pub fn go_to_implementation_split(
9190 &mut self,
9191 _: &GoToImplementationSplit,
9192 cx: &mut ViewContext<Self>,
9193 ) -> Task<Result<Navigated>> {
9194 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9195 }
9196
9197 pub fn go_to_type_definition(
9198 &mut self,
9199 _: &GoToTypeDefinition,
9200 cx: &mut ViewContext<Self>,
9201 ) -> Task<Result<Navigated>> {
9202 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9203 }
9204
9205 pub fn go_to_definition_split(
9206 &mut self,
9207 _: &GoToDefinitionSplit,
9208 cx: &mut ViewContext<Self>,
9209 ) -> Task<Result<Navigated>> {
9210 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9211 }
9212
9213 pub fn go_to_type_definition_split(
9214 &mut self,
9215 _: &GoToTypeDefinitionSplit,
9216 cx: &mut ViewContext<Self>,
9217 ) -> Task<Result<Navigated>> {
9218 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9219 }
9220
9221 fn go_to_definition_of_kind(
9222 &mut self,
9223 kind: GotoDefinitionKind,
9224 split: bool,
9225 cx: &mut ViewContext<Self>,
9226 ) -> Task<Result<Navigated>> {
9227 let Some(provider) = self.semantics_provider.clone() else {
9228 return Task::ready(Ok(Navigated::No));
9229 };
9230 let head = self.selections.newest::<usize>(cx).head();
9231 let buffer = self.buffer.read(cx);
9232 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9233 text_anchor
9234 } else {
9235 return Task::ready(Ok(Navigated::No));
9236 };
9237
9238 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9239 return Task::ready(Ok(Navigated::No));
9240 };
9241
9242 cx.spawn(|editor, mut cx| async move {
9243 let definitions = definitions.await?;
9244 let navigated = editor
9245 .update(&mut cx, |editor, cx| {
9246 editor.navigate_to_hover_links(
9247 Some(kind),
9248 definitions
9249 .into_iter()
9250 .filter(|location| {
9251 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9252 })
9253 .map(HoverLink::Text)
9254 .collect::<Vec<_>>(),
9255 split,
9256 cx,
9257 )
9258 })?
9259 .await?;
9260 anyhow::Ok(navigated)
9261 })
9262 }
9263
9264 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9265 let position = self.selections.newest_anchor().head();
9266 let Some((buffer, buffer_position)) =
9267 self.buffer.read(cx).text_anchor_for_position(position, cx)
9268 else {
9269 return;
9270 };
9271
9272 cx.spawn(|editor, mut cx| async move {
9273 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9274 editor.update(&mut cx, |_, cx| {
9275 cx.open_url(&url);
9276 })
9277 } else {
9278 Ok(())
9279 }
9280 })
9281 .detach();
9282 }
9283
9284 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9285 let Some(workspace) = self.workspace() else {
9286 return;
9287 };
9288
9289 let position = self.selections.newest_anchor().head();
9290
9291 let Some((buffer, buffer_position)) =
9292 self.buffer.read(cx).text_anchor_for_position(position, cx)
9293 else {
9294 return;
9295 };
9296
9297 let project = self.project.clone();
9298
9299 cx.spawn(|_, mut cx| async move {
9300 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9301
9302 if let Some((_, path)) = result {
9303 workspace
9304 .update(&mut cx, |workspace, cx| {
9305 workspace.open_resolved_path(path, cx)
9306 })?
9307 .await?;
9308 }
9309 anyhow::Ok(())
9310 })
9311 .detach();
9312 }
9313
9314 pub(crate) fn navigate_to_hover_links(
9315 &mut self,
9316 kind: Option<GotoDefinitionKind>,
9317 mut definitions: Vec<HoverLink>,
9318 split: bool,
9319 cx: &mut ViewContext<Editor>,
9320 ) -> Task<Result<Navigated>> {
9321 // If there is one definition, just open it directly
9322 if definitions.len() == 1 {
9323 let definition = definitions.pop().unwrap();
9324
9325 enum TargetTaskResult {
9326 Location(Option<Location>),
9327 AlreadyNavigated,
9328 }
9329
9330 let target_task = match definition {
9331 HoverLink::Text(link) => {
9332 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9333 }
9334 HoverLink::InlayHint(lsp_location, server_id) => {
9335 let computation = self.compute_target_location(lsp_location, server_id, cx);
9336 cx.background_executor().spawn(async move {
9337 let location = computation.await?;
9338 Ok(TargetTaskResult::Location(location))
9339 })
9340 }
9341 HoverLink::Url(url) => {
9342 cx.open_url(&url);
9343 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9344 }
9345 HoverLink::File(path) => {
9346 if let Some(workspace) = self.workspace() {
9347 cx.spawn(|_, mut cx| async move {
9348 workspace
9349 .update(&mut cx, |workspace, cx| {
9350 workspace.open_resolved_path(path, cx)
9351 })?
9352 .await
9353 .map(|_| TargetTaskResult::AlreadyNavigated)
9354 })
9355 } else {
9356 Task::ready(Ok(TargetTaskResult::Location(None)))
9357 }
9358 }
9359 };
9360 cx.spawn(|editor, mut cx| async move {
9361 let target = match target_task.await.context("target resolution task")? {
9362 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9363 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9364 TargetTaskResult::Location(Some(target)) => target,
9365 };
9366
9367 editor.update(&mut cx, |editor, cx| {
9368 let Some(workspace) = editor.workspace() else {
9369 return Navigated::No;
9370 };
9371 let pane = workspace.read(cx).active_pane().clone();
9372
9373 let range = target.range.to_offset(target.buffer.read(cx));
9374 let range = editor.range_for_match(&range);
9375
9376 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9377 let buffer = target.buffer.read(cx);
9378 let range = check_multiline_range(buffer, range);
9379 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9380 s.select_ranges([range]);
9381 });
9382 } else {
9383 cx.window_context().defer(move |cx| {
9384 let target_editor: View<Self> =
9385 workspace.update(cx, |workspace, cx| {
9386 let pane = if split {
9387 workspace.adjacent_pane(cx)
9388 } else {
9389 workspace.active_pane().clone()
9390 };
9391
9392 workspace.open_project_item(
9393 pane,
9394 target.buffer.clone(),
9395 true,
9396 true,
9397 cx,
9398 )
9399 });
9400 target_editor.update(cx, |target_editor, cx| {
9401 // When selecting a definition in a different buffer, disable the nav history
9402 // to avoid creating a history entry at the previous cursor location.
9403 pane.update(cx, |pane, _| pane.disable_history());
9404 let buffer = target.buffer.read(cx);
9405 let range = check_multiline_range(buffer, range);
9406 target_editor.change_selections(
9407 Some(Autoscroll::focused()),
9408 cx,
9409 |s| {
9410 s.select_ranges([range]);
9411 },
9412 );
9413 pane.update(cx, |pane, _| pane.enable_history());
9414 });
9415 });
9416 }
9417 Navigated::Yes
9418 })
9419 })
9420 } else if !definitions.is_empty() {
9421 cx.spawn(|editor, mut cx| async move {
9422 let (title, location_tasks, workspace) = editor
9423 .update(&mut cx, |editor, cx| {
9424 let tab_kind = match kind {
9425 Some(GotoDefinitionKind::Implementation) => "Implementations",
9426 _ => "Definitions",
9427 };
9428 let title = definitions
9429 .iter()
9430 .find_map(|definition| match definition {
9431 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9432 let buffer = origin.buffer.read(cx);
9433 format!(
9434 "{} for {}",
9435 tab_kind,
9436 buffer
9437 .text_for_range(origin.range.clone())
9438 .collect::<String>()
9439 )
9440 }),
9441 HoverLink::InlayHint(_, _) => None,
9442 HoverLink::Url(_) => None,
9443 HoverLink::File(_) => None,
9444 })
9445 .unwrap_or(tab_kind.to_string());
9446 let location_tasks = definitions
9447 .into_iter()
9448 .map(|definition| match definition {
9449 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9450 HoverLink::InlayHint(lsp_location, server_id) => {
9451 editor.compute_target_location(lsp_location, server_id, cx)
9452 }
9453 HoverLink::Url(_) => Task::ready(Ok(None)),
9454 HoverLink::File(_) => Task::ready(Ok(None)),
9455 })
9456 .collect::<Vec<_>>();
9457 (title, location_tasks, editor.workspace().clone())
9458 })
9459 .context("location tasks preparation")?;
9460
9461 let locations = future::join_all(location_tasks)
9462 .await
9463 .into_iter()
9464 .filter_map(|location| location.transpose())
9465 .collect::<Result<_>>()
9466 .context("location tasks")?;
9467
9468 let Some(workspace) = workspace else {
9469 return Ok(Navigated::No);
9470 };
9471 let opened = workspace
9472 .update(&mut cx, |workspace, cx| {
9473 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9474 })
9475 .ok();
9476
9477 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9478 })
9479 } else {
9480 Task::ready(Ok(Navigated::No))
9481 }
9482 }
9483
9484 fn compute_target_location(
9485 &self,
9486 lsp_location: lsp::Location,
9487 server_id: LanguageServerId,
9488 cx: &mut ViewContext<Self>,
9489 ) -> Task<anyhow::Result<Option<Location>>> {
9490 let Some(project) = self.project.clone() else {
9491 return Task::Ready(Some(Ok(None)));
9492 };
9493
9494 cx.spawn(move |editor, mut cx| async move {
9495 let location_task = editor.update(&mut cx, |_, cx| {
9496 project.update(cx, |project, cx| {
9497 let language_server_name = project
9498 .language_server_statuses(cx)
9499 .find(|(id, _)| server_id == *id)
9500 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9501 language_server_name.map(|language_server_name| {
9502 project.open_local_buffer_via_lsp(
9503 lsp_location.uri.clone(),
9504 server_id,
9505 language_server_name,
9506 cx,
9507 )
9508 })
9509 })
9510 })?;
9511 let location = match location_task {
9512 Some(task) => Some({
9513 let target_buffer_handle = task.await.context("open local buffer")?;
9514 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9515 let target_start = target_buffer
9516 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9517 let target_end = target_buffer
9518 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9519 target_buffer.anchor_after(target_start)
9520 ..target_buffer.anchor_before(target_end)
9521 })?;
9522 Location {
9523 buffer: target_buffer_handle,
9524 range,
9525 }
9526 }),
9527 None => None,
9528 };
9529 Ok(location)
9530 })
9531 }
9532
9533 pub fn find_all_references(
9534 &mut self,
9535 _: &FindAllReferences,
9536 cx: &mut ViewContext<Self>,
9537 ) -> Option<Task<Result<Navigated>>> {
9538 let selection = self.selections.newest::<usize>(cx);
9539 let multi_buffer = self.buffer.read(cx);
9540 let head = selection.head();
9541
9542 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9543 let head_anchor = multi_buffer_snapshot.anchor_at(
9544 head,
9545 if head < selection.tail() {
9546 Bias::Right
9547 } else {
9548 Bias::Left
9549 },
9550 );
9551
9552 match self
9553 .find_all_references_task_sources
9554 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9555 {
9556 Ok(_) => {
9557 log::info!(
9558 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9559 );
9560 return None;
9561 }
9562 Err(i) => {
9563 self.find_all_references_task_sources.insert(i, head_anchor);
9564 }
9565 }
9566
9567 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9568 let workspace = self.workspace()?;
9569 let project = workspace.read(cx).project().clone();
9570 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9571 Some(cx.spawn(|editor, mut cx| async move {
9572 let _cleanup = defer({
9573 let mut cx = cx.clone();
9574 move || {
9575 let _ = editor.update(&mut cx, |editor, _| {
9576 if let Ok(i) =
9577 editor
9578 .find_all_references_task_sources
9579 .binary_search_by(|anchor| {
9580 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9581 })
9582 {
9583 editor.find_all_references_task_sources.remove(i);
9584 }
9585 });
9586 }
9587 });
9588
9589 let locations = references.await?;
9590 if locations.is_empty() {
9591 return anyhow::Ok(Navigated::No);
9592 }
9593
9594 workspace.update(&mut cx, |workspace, cx| {
9595 let title = locations
9596 .first()
9597 .as_ref()
9598 .map(|location| {
9599 let buffer = location.buffer.read(cx);
9600 format!(
9601 "References to `{}`",
9602 buffer
9603 .text_for_range(location.range.clone())
9604 .collect::<String>()
9605 )
9606 })
9607 .unwrap();
9608 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9609 Navigated::Yes
9610 })
9611 }))
9612 }
9613
9614 /// Opens a multibuffer with the given project locations in it
9615 pub fn open_locations_in_multibuffer(
9616 workspace: &mut Workspace,
9617 mut locations: Vec<Location>,
9618 title: String,
9619 split: bool,
9620 cx: &mut ViewContext<Workspace>,
9621 ) {
9622 // If there are multiple definitions, open them in a multibuffer
9623 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9624 let mut locations = locations.into_iter().peekable();
9625 let mut ranges_to_highlight = Vec::new();
9626 let capability = workspace.project().read(cx).capability();
9627
9628 let excerpt_buffer = cx.new_model(|cx| {
9629 let mut multibuffer = MultiBuffer::new(capability);
9630 while let Some(location) = locations.next() {
9631 let buffer = location.buffer.read(cx);
9632 let mut ranges_for_buffer = Vec::new();
9633 let range = location.range.to_offset(buffer);
9634 ranges_for_buffer.push(range.clone());
9635
9636 while let Some(next_location) = locations.peek() {
9637 if next_location.buffer == location.buffer {
9638 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9639 locations.next();
9640 } else {
9641 break;
9642 }
9643 }
9644
9645 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9646 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9647 location.buffer.clone(),
9648 ranges_for_buffer,
9649 DEFAULT_MULTIBUFFER_CONTEXT,
9650 cx,
9651 ))
9652 }
9653
9654 multibuffer.with_title(title)
9655 });
9656
9657 let editor = cx.new_view(|cx| {
9658 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9659 });
9660 editor.update(cx, |editor, cx| {
9661 if let Some(first_range) = ranges_to_highlight.first() {
9662 editor.change_selections(None, cx, |selections| {
9663 selections.clear_disjoint();
9664 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9665 });
9666 }
9667 editor.highlight_background::<Self>(
9668 &ranges_to_highlight,
9669 |theme| theme.editor_highlighted_line_background,
9670 cx,
9671 );
9672 editor.register_buffers_with_language_servers(cx);
9673 });
9674
9675 let item = Box::new(editor);
9676 let item_id = item.item_id();
9677
9678 if split {
9679 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9680 } else {
9681 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9682 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9683 pane.close_current_preview_item(cx)
9684 } else {
9685 None
9686 }
9687 });
9688 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9689 }
9690 workspace.active_pane().update(cx, |pane, cx| {
9691 pane.set_preview_item_id(Some(item_id), cx);
9692 });
9693 }
9694
9695 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9696 use language::ToOffset as _;
9697
9698 let provider = self.semantics_provider.clone()?;
9699 let selection = self.selections.newest_anchor().clone();
9700 let (cursor_buffer, cursor_buffer_position) = self
9701 .buffer
9702 .read(cx)
9703 .text_anchor_for_position(selection.head(), cx)?;
9704 let (tail_buffer, cursor_buffer_position_end) = self
9705 .buffer
9706 .read(cx)
9707 .text_anchor_for_position(selection.tail(), cx)?;
9708 if tail_buffer != cursor_buffer {
9709 return None;
9710 }
9711
9712 let snapshot = cursor_buffer.read(cx).snapshot();
9713 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9714 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9715 let prepare_rename = provider
9716 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
9717 .unwrap_or_else(|| Task::ready(Ok(None)));
9718 drop(snapshot);
9719
9720 Some(cx.spawn(|this, mut cx| async move {
9721 let rename_range = if let Some(range) = prepare_rename.await? {
9722 Some(range)
9723 } else {
9724 this.update(&mut cx, |this, cx| {
9725 let buffer = this.buffer.read(cx).snapshot(cx);
9726 let mut buffer_highlights = this
9727 .document_highlights_for_position(selection.head(), &buffer)
9728 .filter(|highlight| {
9729 highlight.start.excerpt_id == selection.head().excerpt_id
9730 && highlight.end.excerpt_id == selection.head().excerpt_id
9731 });
9732 buffer_highlights
9733 .next()
9734 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9735 })?
9736 };
9737 if let Some(rename_range) = rename_range {
9738 this.update(&mut cx, |this, cx| {
9739 let snapshot = cursor_buffer.read(cx).snapshot();
9740 let rename_buffer_range = rename_range.to_offset(&snapshot);
9741 let cursor_offset_in_rename_range =
9742 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9743 let cursor_offset_in_rename_range_end =
9744 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9745
9746 this.take_rename(false, cx);
9747 let buffer = this.buffer.read(cx).read(cx);
9748 let cursor_offset = selection.head().to_offset(&buffer);
9749 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9750 let rename_end = rename_start + rename_buffer_range.len();
9751 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9752 let mut old_highlight_id = None;
9753 let old_name: Arc<str> = buffer
9754 .chunks(rename_start..rename_end, true)
9755 .map(|chunk| {
9756 if old_highlight_id.is_none() {
9757 old_highlight_id = chunk.syntax_highlight_id;
9758 }
9759 chunk.text
9760 })
9761 .collect::<String>()
9762 .into();
9763
9764 drop(buffer);
9765
9766 // Position the selection in the rename editor so that it matches the current selection.
9767 this.show_local_selections = false;
9768 let rename_editor = cx.new_view(|cx| {
9769 let mut editor = Editor::single_line(cx);
9770 editor.buffer.update(cx, |buffer, cx| {
9771 buffer.edit([(0..0, old_name.clone())], None, cx)
9772 });
9773 let rename_selection_range = match cursor_offset_in_rename_range
9774 .cmp(&cursor_offset_in_rename_range_end)
9775 {
9776 Ordering::Equal => {
9777 editor.select_all(&SelectAll, cx);
9778 return editor;
9779 }
9780 Ordering::Less => {
9781 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9782 }
9783 Ordering::Greater => {
9784 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9785 }
9786 };
9787 if rename_selection_range.end > old_name.len() {
9788 editor.select_all(&SelectAll, cx);
9789 } else {
9790 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9791 s.select_ranges([rename_selection_range]);
9792 });
9793 }
9794 editor
9795 });
9796 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
9797 if e == &EditorEvent::Focused {
9798 cx.emit(EditorEvent::FocusedIn)
9799 }
9800 })
9801 .detach();
9802
9803 let write_highlights =
9804 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9805 let read_highlights =
9806 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9807 let ranges = write_highlights
9808 .iter()
9809 .flat_map(|(_, ranges)| ranges.iter())
9810 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9811 .cloned()
9812 .collect();
9813
9814 this.highlight_text::<Rename>(
9815 ranges,
9816 HighlightStyle {
9817 fade_out: Some(0.6),
9818 ..Default::default()
9819 },
9820 cx,
9821 );
9822 let rename_focus_handle = rename_editor.focus_handle(cx);
9823 cx.focus(&rename_focus_handle);
9824 let block_id = this.insert_blocks(
9825 [BlockProperties {
9826 style: BlockStyle::Flex,
9827 placement: BlockPlacement::Below(range.start),
9828 height: 1,
9829 render: Arc::new({
9830 let rename_editor = rename_editor.clone();
9831 move |cx: &mut BlockContext| {
9832 let mut text_style = cx.editor_style.text.clone();
9833 if let Some(highlight_style) = old_highlight_id
9834 .and_then(|h| h.style(&cx.editor_style.syntax))
9835 {
9836 text_style = text_style.highlight(highlight_style);
9837 }
9838 div()
9839 .block_mouse_down()
9840 .pl(cx.anchor_x)
9841 .child(EditorElement::new(
9842 &rename_editor,
9843 EditorStyle {
9844 background: cx.theme().system().transparent,
9845 local_player: cx.editor_style.local_player,
9846 text: text_style,
9847 scrollbar_width: cx.editor_style.scrollbar_width,
9848 syntax: cx.editor_style.syntax.clone(),
9849 status: cx.editor_style.status.clone(),
9850 inlay_hints_style: HighlightStyle {
9851 font_weight: Some(FontWeight::BOLD),
9852 ..make_inlay_hints_style(cx)
9853 },
9854 suggestions_style: HighlightStyle {
9855 color: Some(cx.theme().status().predictive),
9856 ..HighlightStyle::default()
9857 },
9858 ..EditorStyle::default()
9859 },
9860 ))
9861 .into_any_element()
9862 }
9863 }),
9864 priority: 0,
9865 }],
9866 Some(Autoscroll::fit()),
9867 cx,
9868 )[0];
9869 this.pending_rename = Some(RenameState {
9870 range,
9871 old_name,
9872 editor: rename_editor,
9873 block_id,
9874 });
9875 })?;
9876 }
9877
9878 Ok(())
9879 }))
9880 }
9881
9882 pub fn confirm_rename(
9883 &mut self,
9884 _: &ConfirmRename,
9885 cx: &mut ViewContext<Self>,
9886 ) -> Option<Task<Result<()>>> {
9887 let rename = self.take_rename(false, cx)?;
9888 let workspace = self.workspace()?.downgrade();
9889 let (buffer, start) = self
9890 .buffer
9891 .read(cx)
9892 .text_anchor_for_position(rename.range.start, cx)?;
9893 let (end_buffer, _) = self
9894 .buffer
9895 .read(cx)
9896 .text_anchor_for_position(rename.range.end, cx)?;
9897 if buffer != end_buffer {
9898 return None;
9899 }
9900
9901 let old_name = rename.old_name;
9902 let new_name = rename.editor.read(cx).text(cx);
9903
9904 let rename = self.semantics_provider.as_ref()?.perform_rename(
9905 &buffer,
9906 start,
9907 new_name.clone(),
9908 cx,
9909 )?;
9910
9911 Some(cx.spawn(|editor, mut cx| async move {
9912 let project_transaction = rename.await?;
9913 Self::open_project_transaction(
9914 &editor,
9915 workspace,
9916 project_transaction,
9917 format!("Rename: {} → {}", old_name, new_name),
9918 cx.clone(),
9919 )
9920 .await?;
9921
9922 editor.update(&mut cx, |editor, cx| {
9923 editor.refresh_document_highlights(cx);
9924 })?;
9925 Ok(())
9926 }))
9927 }
9928
9929 fn take_rename(
9930 &mut self,
9931 moving_cursor: bool,
9932 cx: &mut ViewContext<Self>,
9933 ) -> Option<RenameState> {
9934 let rename = self.pending_rename.take()?;
9935 if rename.editor.focus_handle(cx).is_focused(cx) {
9936 cx.focus(&self.focus_handle);
9937 }
9938
9939 self.remove_blocks(
9940 [rename.block_id].into_iter().collect(),
9941 Some(Autoscroll::fit()),
9942 cx,
9943 );
9944 self.clear_highlights::<Rename>(cx);
9945 self.show_local_selections = true;
9946
9947 if moving_cursor {
9948 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
9949 editor.selections.newest::<usize>(cx).head()
9950 });
9951
9952 // Update the selection to match the position of the selection inside
9953 // the rename editor.
9954 let snapshot = self.buffer.read(cx).read(cx);
9955 let rename_range = rename.range.to_offset(&snapshot);
9956 let cursor_in_editor = snapshot
9957 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
9958 .min(rename_range.end);
9959 drop(snapshot);
9960
9961 self.change_selections(None, cx, |s| {
9962 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
9963 });
9964 } else {
9965 self.refresh_document_highlights(cx);
9966 }
9967
9968 Some(rename)
9969 }
9970
9971 pub fn pending_rename(&self) -> Option<&RenameState> {
9972 self.pending_rename.as_ref()
9973 }
9974
9975 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9976 let project = match &self.project {
9977 Some(project) => project.clone(),
9978 None => return None,
9979 };
9980
9981 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
9982 }
9983
9984 fn format_selections(
9985 &mut self,
9986 _: &FormatSelections,
9987 cx: &mut ViewContext<Self>,
9988 ) -> Option<Task<Result<()>>> {
9989 let project = match &self.project {
9990 Some(project) => project.clone(),
9991 None => return None,
9992 };
9993
9994 let selections = self
9995 .selections
9996 .all_adjusted(cx)
9997 .into_iter()
9998 .filter(|s| !s.is_empty())
9999 .collect_vec();
10000
10001 Some(self.perform_format(
10002 project,
10003 FormatTrigger::Manual,
10004 FormatTarget::Ranges(selections),
10005 cx,
10006 ))
10007 }
10008
10009 fn perform_format(
10010 &mut self,
10011 project: Model<Project>,
10012 trigger: FormatTrigger,
10013 target: FormatTarget,
10014 cx: &mut ViewContext<Self>,
10015 ) -> Task<Result<()>> {
10016 let buffer = self.buffer().clone();
10017 let mut buffers = buffer.read(cx).all_buffers();
10018 if trigger == FormatTrigger::Save {
10019 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10020 }
10021
10022 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10023 let format = project.update(cx, |project, cx| {
10024 project.format(buffers, true, trigger, target, cx)
10025 });
10026
10027 cx.spawn(|_, mut cx| async move {
10028 let transaction = futures::select_biased! {
10029 () = timeout => {
10030 log::warn!("timed out waiting for formatting");
10031 None
10032 }
10033 transaction = format.log_err().fuse() => transaction,
10034 };
10035
10036 buffer
10037 .update(&mut cx, |buffer, cx| {
10038 if let Some(transaction) = transaction {
10039 if !buffer.is_singleton() {
10040 buffer.push_transaction(&transaction.0, cx);
10041 }
10042 }
10043
10044 cx.notify();
10045 })
10046 .ok();
10047
10048 Ok(())
10049 })
10050 }
10051
10052 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10053 if let Some(project) = self.project.clone() {
10054 self.buffer.update(cx, |multi_buffer, cx| {
10055 project.update(cx, |project, cx| {
10056 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10057 });
10058 })
10059 }
10060 }
10061
10062 fn cancel_language_server_work(
10063 &mut self,
10064 _: &actions::CancelLanguageServerWork,
10065 cx: &mut ViewContext<Self>,
10066 ) {
10067 if let Some(project) = self.project.clone() {
10068 self.buffer.update(cx, |multi_buffer, cx| {
10069 project.update(cx, |project, cx| {
10070 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10071 });
10072 })
10073 }
10074 }
10075
10076 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10077 cx.show_character_palette();
10078 }
10079
10080 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10081 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10082 let buffer = self.buffer.read(cx).snapshot(cx);
10083 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10084 let is_valid = buffer
10085 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10086 .any(|entry| {
10087 entry.diagnostic.is_primary
10088 && !entry.range.is_empty()
10089 && entry.range.start == primary_range_start
10090 && entry.diagnostic.message == active_diagnostics.primary_message
10091 });
10092
10093 if is_valid != active_diagnostics.is_valid {
10094 active_diagnostics.is_valid = is_valid;
10095 let mut new_styles = HashMap::default();
10096 for (block_id, diagnostic) in &active_diagnostics.blocks {
10097 new_styles.insert(
10098 *block_id,
10099 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10100 );
10101 }
10102 self.display_map.update(cx, |display_map, _cx| {
10103 display_map.replace_blocks(new_styles)
10104 });
10105 }
10106 }
10107 }
10108
10109 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10110 self.dismiss_diagnostics(cx);
10111 let snapshot = self.snapshot(cx);
10112 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10113 let buffer = self.buffer.read(cx).snapshot(cx);
10114
10115 let mut primary_range = None;
10116 let mut primary_message = None;
10117 let mut group_end = Point::zero();
10118 let diagnostic_group = buffer
10119 .diagnostic_group::<MultiBufferPoint>(group_id)
10120 .filter_map(|entry| {
10121 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10122 && (entry.range.start.row == entry.range.end.row
10123 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10124 {
10125 return None;
10126 }
10127 if entry.range.end > group_end {
10128 group_end = entry.range.end;
10129 }
10130 if entry.diagnostic.is_primary {
10131 primary_range = Some(entry.range.clone());
10132 primary_message = Some(entry.diagnostic.message.clone());
10133 }
10134 Some(entry)
10135 })
10136 .collect::<Vec<_>>();
10137 let primary_range = primary_range?;
10138 let primary_message = primary_message?;
10139 let primary_range =
10140 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10141
10142 let blocks = display_map
10143 .insert_blocks(
10144 diagnostic_group.iter().map(|entry| {
10145 let diagnostic = entry.diagnostic.clone();
10146 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10147 BlockProperties {
10148 style: BlockStyle::Fixed,
10149 placement: BlockPlacement::Below(
10150 buffer.anchor_after(entry.range.start),
10151 ),
10152 height: message_height,
10153 render: diagnostic_block_renderer(diagnostic, None, true, true),
10154 priority: 0,
10155 }
10156 }),
10157 cx,
10158 )
10159 .into_iter()
10160 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10161 .collect();
10162
10163 Some(ActiveDiagnosticGroup {
10164 primary_range,
10165 primary_message,
10166 group_id,
10167 blocks,
10168 is_valid: true,
10169 })
10170 });
10171 self.active_diagnostics.is_some()
10172 }
10173
10174 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10175 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10176 self.display_map.update(cx, |display_map, cx| {
10177 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10178 });
10179 cx.notify();
10180 }
10181 }
10182
10183 pub fn set_selections_from_remote(
10184 &mut self,
10185 selections: Vec<Selection<Anchor>>,
10186 pending_selection: Option<Selection<Anchor>>,
10187 cx: &mut ViewContext<Self>,
10188 ) {
10189 let old_cursor_position = self.selections.newest_anchor().head();
10190 self.selections.change_with(cx, |s| {
10191 s.select_anchors(selections);
10192 if let Some(pending_selection) = pending_selection {
10193 s.set_pending(pending_selection, SelectMode::Character);
10194 } else {
10195 s.clear_pending();
10196 }
10197 });
10198 self.selections_did_change(false, &old_cursor_position, true, cx);
10199 }
10200
10201 fn push_to_selection_history(&mut self) {
10202 self.selection_history.push(SelectionHistoryEntry {
10203 selections: self.selections.disjoint_anchors(),
10204 select_next_state: self.select_next_state.clone(),
10205 select_prev_state: self.select_prev_state.clone(),
10206 add_selections_state: self.add_selections_state.clone(),
10207 });
10208 }
10209
10210 pub fn transact(
10211 &mut self,
10212 cx: &mut ViewContext<Self>,
10213 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10214 ) -> Option<TransactionId> {
10215 self.start_transaction_at(Instant::now(), cx);
10216 update(self, cx);
10217 self.end_transaction_at(Instant::now(), cx)
10218 }
10219
10220 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10221 self.end_selection(cx);
10222 if let Some(tx_id) = self
10223 .buffer
10224 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10225 {
10226 self.selection_history
10227 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10228 cx.emit(EditorEvent::TransactionBegun {
10229 transaction_id: tx_id,
10230 })
10231 }
10232 }
10233
10234 fn end_transaction_at(
10235 &mut self,
10236 now: Instant,
10237 cx: &mut ViewContext<Self>,
10238 ) -> Option<TransactionId> {
10239 if let Some(transaction_id) = self
10240 .buffer
10241 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10242 {
10243 if let Some((_, end_selections)) =
10244 self.selection_history.transaction_mut(transaction_id)
10245 {
10246 *end_selections = Some(self.selections.disjoint_anchors());
10247 } else {
10248 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10249 }
10250
10251 cx.emit(EditorEvent::Edited { transaction_id });
10252 Some(transaction_id)
10253 } else {
10254 None
10255 }
10256 }
10257
10258 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10259 let selection = self.selections.newest::<Point>(cx);
10260
10261 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10262 let range = if selection.is_empty() {
10263 let point = selection.head().to_display_point(&display_map);
10264 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10265 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10266 .to_point(&display_map);
10267 start..end
10268 } else {
10269 selection.range()
10270 };
10271 if display_map.folds_in_range(range).next().is_some() {
10272 self.unfold_lines(&Default::default(), cx)
10273 } else {
10274 self.fold(&Default::default(), cx)
10275 }
10276 }
10277
10278 pub fn toggle_fold_recursive(
10279 &mut self,
10280 _: &actions::ToggleFoldRecursive,
10281 cx: &mut ViewContext<Self>,
10282 ) {
10283 let selection = self.selections.newest::<Point>(cx);
10284
10285 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10286 let range = if selection.is_empty() {
10287 let point = selection.head().to_display_point(&display_map);
10288 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10289 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10290 .to_point(&display_map);
10291 start..end
10292 } else {
10293 selection.range()
10294 };
10295 if display_map.folds_in_range(range).next().is_some() {
10296 self.unfold_recursive(&Default::default(), cx)
10297 } else {
10298 self.fold_recursive(&Default::default(), cx)
10299 }
10300 }
10301
10302 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10303 let mut to_fold = Vec::new();
10304 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10305 let selections = self.selections.all_adjusted(cx);
10306
10307 for selection in selections {
10308 let range = selection.range().sorted();
10309 let buffer_start_row = range.start.row;
10310
10311 if range.start.row != range.end.row {
10312 let mut found = false;
10313 let mut row = range.start.row;
10314 while row <= range.end.row {
10315 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10316 found = true;
10317 row = crease.range().end.row + 1;
10318 to_fold.push(crease);
10319 } else {
10320 row += 1
10321 }
10322 }
10323 if found {
10324 continue;
10325 }
10326 }
10327
10328 for row in (0..=range.start.row).rev() {
10329 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10330 if crease.range().end.row >= buffer_start_row {
10331 to_fold.push(crease);
10332 if row <= range.start.row {
10333 break;
10334 }
10335 }
10336 }
10337 }
10338 }
10339
10340 self.fold_creases(to_fold, true, cx);
10341 }
10342
10343 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10344 if !self.buffer.read(cx).is_singleton() {
10345 return;
10346 }
10347
10348 let fold_at_level = fold_at.level;
10349 let snapshot = self.buffer.read(cx).snapshot(cx);
10350 let mut to_fold = Vec::new();
10351 let mut stack = vec![(0, snapshot.max_row().0, 1)];
10352
10353 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10354 while start_row < end_row {
10355 match self
10356 .snapshot(cx)
10357 .crease_for_buffer_row(MultiBufferRow(start_row))
10358 {
10359 Some(crease) => {
10360 let nested_start_row = crease.range().start.row + 1;
10361 let nested_end_row = crease.range().end.row;
10362
10363 if current_level < fold_at_level {
10364 stack.push((nested_start_row, nested_end_row, current_level + 1));
10365 } else if current_level == fold_at_level {
10366 to_fold.push(crease);
10367 }
10368
10369 start_row = nested_end_row + 1;
10370 }
10371 None => start_row += 1,
10372 }
10373 }
10374 }
10375
10376 self.fold_creases(to_fold, true, cx);
10377 }
10378
10379 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10380 if !self.buffer.read(cx).is_singleton() {
10381 return;
10382 }
10383
10384 let mut fold_ranges = Vec::new();
10385 let snapshot = self.buffer.read(cx).snapshot(cx);
10386
10387 for row in 0..snapshot.max_row().0 {
10388 if let Some(foldable_range) =
10389 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10390 {
10391 fold_ranges.push(foldable_range);
10392 }
10393 }
10394
10395 self.fold_creases(fold_ranges, true, cx);
10396 }
10397
10398 pub fn fold_function_bodies(
10399 &mut self,
10400 _: &actions::FoldFunctionBodies,
10401 cx: &mut ViewContext<Self>,
10402 ) {
10403 let snapshot = self.buffer.read(cx).snapshot(cx);
10404 let Some((_, _, buffer)) = snapshot.as_singleton() else {
10405 return;
10406 };
10407 let creases = buffer
10408 .function_body_fold_ranges(0..buffer.len())
10409 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10410 .collect();
10411
10412 self.fold_creases(creases, true, cx);
10413 }
10414
10415 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10416 let mut to_fold = Vec::new();
10417 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10418 let selections = self.selections.all_adjusted(cx);
10419
10420 for selection in selections {
10421 let range = selection.range().sorted();
10422 let buffer_start_row = range.start.row;
10423
10424 if range.start.row != range.end.row {
10425 let mut found = false;
10426 for row in range.start.row..=range.end.row {
10427 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10428 found = true;
10429 to_fold.push(crease);
10430 }
10431 }
10432 if found {
10433 continue;
10434 }
10435 }
10436
10437 for row in (0..=range.start.row).rev() {
10438 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10439 if crease.range().end.row >= buffer_start_row {
10440 to_fold.push(crease);
10441 } else {
10442 break;
10443 }
10444 }
10445 }
10446 }
10447
10448 self.fold_creases(to_fold, true, cx);
10449 }
10450
10451 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10452 let buffer_row = fold_at.buffer_row;
10453 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10454
10455 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10456 let autoscroll = self
10457 .selections
10458 .all::<Point>(cx)
10459 .iter()
10460 .any(|selection| crease.range().overlaps(&selection.range()));
10461
10462 self.fold_creases(vec![crease], autoscroll, cx);
10463 }
10464 }
10465
10466 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10467 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10468 let buffer = &display_map.buffer_snapshot;
10469 let selections = self.selections.all::<Point>(cx);
10470 let ranges = selections
10471 .iter()
10472 .map(|s| {
10473 let range = s.display_range(&display_map).sorted();
10474 let mut start = range.start.to_point(&display_map);
10475 let mut end = range.end.to_point(&display_map);
10476 start.column = 0;
10477 end.column = buffer.line_len(MultiBufferRow(end.row));
10478 start..end
10479 })
10480 .collect::<Vec<_>>();
10481
10482 self.unfold_ranges(&ranges, true, true, cx);
10483 }
10484
10485 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10486 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10487 let selections = self.selections.all::<Point>(cx);
10488 let ranges = selections
10489 .iter()
10490 .map(|s| {
10491 let mut range = s.display_range(&display_map).sorted();
10492 *range.start.column_mut() = 0;
10493 *range.end.column_mut() = display_map.line_len(range.end.row());
10494 let start = range.start.to_point(&display_map);
10495 let end = range.end.to_point(&display_map);
10496 start..end
10497 })
10498 .collect::<Vec<_>>();
10499
10500 self.unfold_ranges(&ranges, true, true, cx);
10501 }
10502
10503 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10504 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10505
10506 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10507 ..Point::new(
10508 unfold_at.buffer_row.0,
10509 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10510 );
10511
10512 let autoscroll = self
10513 .selections
10514 .all::<Point>(cx)
10515 .iter()
10516 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10517
10518 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10519 }
10520
10521 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10522 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10523 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10524 }
10525
10526 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10527 let selections = self.selections.all::<Point>(cx);
10528 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10529 let line_mode = self.selections.line_mode;
10530 let ranges = selections
10531 .into_iter()
10532 .map(|s| {
10533 if line_mode {
10534 let start = Point::new(s.start.row, 0);
10535 let end = Point::new(
10536 s.end.row,
10537 display_map
10538 .buffer_snapshot
10539 .line_len(MultiBufferRow(s.end.row)),
10540 );
10541 Crease::simple(start..end, display_map.fold_placeholder.clone())
10542 } else {
10543 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10544 }
10545 })
10546 .collect::<Vec<_>>();
10547 self.fold_creases(ranges, true, cx);
10548 }
10549
10550 pub fn fold_creases<T: ToOffset + Clone>(
10551 &mut self,
10552 creases: Vec<Crease<T>>,
10553 auto_scroll: bool,
10554 cx: &mut ViewContext<Self>,
10555 ) {
10556 if creases.is_empty() {
10557 return;
10558 }
10559
10560 let mut buffers_affected = HashSet::default();
10561 let multi_buffer = self.buffer().read(cx);
10562 for crease in &creases {
10563 if let Some((_, buffer, _)) =
10564 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10565 {
10566 buffers_affected.insert(buffer.read(cx).remote_id());
10567 };
10568 }
10569
10570 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10571
10572 if auto_scroll {
10573 self.request_autoscroll(Autoscroll::fit(), cx);
10574 }
10575
10576 for buffer_id in buffers_affected {
10577 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10578 }
10579
10580 cx.notify();
10581
10582 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10583 // Clear diagnostics block when folding a range that contains it.
10584 let snapshot = self.snapshot(cx);
10585 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10586 drop(snapshot);
10587 self.active_diagnostics = Some(active_diagnostics);
10588 self.dismiss_diagnostics(cx);
10589 } else {
10590 self.active_diagnostics = Some(active_diagnostics);
10591 }
10592 }
10593
10594 self.scrollbar_marker_state.dirty = true;
10595 }
10596
10597 /// Removes any folds whose ranges intersect any of the given ranges.
10598 pub fn unfold_ranges<T: ToOffset + Clone>(
10599 &mut self,
10600 ranges: &[Range<T>],
10601 inclusive: bool,
10602 auto_scroll: bool,
10603 cx: &mut ViewContext<Self>,
10604 ) {
10605 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10606 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10607 });
10608 }
10609
10610 /// Removes any folds with the given ranges.
10611 pub fn remove_folds_with_type<T: ToOffset + Clone>(
10612 &mut self,
10613 ranges: &[Range<T>],
10614 type_id: TypeId,
10615 auto_scroll: bool,
10616 cx: &mut ViewContext<Self>,
10617 ) {
10618 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10619 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
10620 });
10621 }
10622
10623 fn remove_folds_with<T: ToOffset + Clone>(
10624 &mut self,
10625 ranges: &[Range<T>],
10626 auto_scroll: bool,
10627 cx: &mut ViewContext<Self>,
10628 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
10629 ) {
10630 if ranges.is_empty() {
10631 return;
10632 }
10633
10634 let mut buffers_affected = HashSet::default();
10635 let multi_buffer = self.buffer().read(cx);
10636 for range in ranges {
10637 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10638 buffers_affected.insert(buffer.read(cx).remote_id());
10639 };
10640 }
10641
10642 self.display_map.update(cx, update);
10643
10644 if auto_scroll {
10645 self.request_autoscroll(Autoscroll::fit(), cx);
10646 }
10647
10648 for buffer_id in buffers_affected {
10649 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10650 }
10651
10652 cx.notify();
10653 self.scrollbar_marker_state.dirty = true;
10654 self.active_indent_guides_state.dirty = true;
10655 }
10656
10657 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10658 self.display_map.read(cx).fold_placeholder.clone()
10659 }
10660
10661 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10662 if hovered != self.gutter_hovered {
10663 self.gutter_hovered = hovered;
10664 cx.notify();
10665 }
10666 }
10667
10668 pub fn insert_blocks(
10669 &mut self,
10670 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10671 autoscroll: Option<Autoscroll>,
10672 cx: &mut ViewContext<Self>,
10673 ) -> Vec<CustomBlockId> {
10674 let blocks = self
10675 .display_map
10676 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10677 if let Some(autoscroll) = autoscroll {
10678 self.request_autoscroll(autoscroll, cx);
10679 }
10680 cx.notify();
10681 blocks
10682 }
10683
10684 pub fn resize_blocks(
10685 &mut self,
10686 heights: HashMap<CustomBlockId, u32>,
10687 autoscroll: Option<Autoscroll>,
10688 cx: &mut ViewContext<Self>,
10689 ) {
10690 self.display_map
10691 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10692 if let Some(autoscroll) = autoscroll {
10693 self.request_autoscroll(autoscroll, cx);
10694 }
10695 cx.notify();
10696 }
10697
10698 pub fn replace_blocks(
10699 &mut self,
10700 renderers: HashMap<CustomBlockId, RenderBlock>,
10701 autoscroll: Option<Autoscroll>,
10702 cx: &mut ViewContext<Self>,
10703 ) {
10704 self.display_map
10705 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10706 if let Some(autoscroll) = autoscroll {
10707 self.request_autoscroll(autoscroll, cx);
10708 }
10709 cx.notify();
10710 }
10711
10712 pub fn remove_blocks(
10713 &mut self,
10714 block_ids: HashSet<CustomBlockId>,
10715 autoscroll: Option<Autoscroll>,
10716 cx: &mut ViewContext<Self>,
10717 ) {
10718 self.display_map.update(cx, |display_map, cx| {
10719 display_map.remove_blocks(block_ids, cx)
10720 });
10721 if let Some(autoscroll) = autoscroll {
10722 self.request_autoscroll(autoscroll, cx);
10723 }
10724 cx.notify();
10725 }
10726
10727 pub fn row_for_block(
10728 &self,
10729 block_id: CustomBlockId,
10730 cx: &mut ViewContext<Self>,
10731 ) -> Option<DisplayRow> {
10732 self.display_map
10733 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10734 }
10735
10736 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10737 self.focused_block = Some(focused_block);
10738 }
10739
10740 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10741 self.focused_block.take()
10742 }
10743
10744 pub fn insert_creases(
10745 &mut self,
10746 creases: impl IntoIterator<Item = Crease<Anchor>>,
10747 cx: &mut ViewContext<Self>,
10748 ) -> Vec<CreaseId> {
10749 self.display_map
10750 .update(cx, |map, cx| map.insert_creases(creases, cx))
10751 }
10752
10753 pub fn remove_creases(
10754 &mut self,
10755 ids: impl IntoIterator<Item = CreaseId>,
10756 cx: &mut ViewContext<Self>,
10757 ) {
10758 self.display_map
10759 .update(cx, |map, cx| map.remove_creases(ids, cx));
10760 }
10761
10762 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10763 self.display_map
10764 .update(cx, |map, cx| map.snapshot(cx))
10765 .longest_row()
10766 }
10767
10768 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10769 self.display_map
10770 .update(cx, |map, cx| map.snapshot(cx))
10771 .max_point()
10772 }
10773
10774 pub fn text(&self, cx: &AppContext) -> String {
10775 self.buffer.read(cx).read(cx).text()
10776 }
10777
10778 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10779 let text = self.text(cx);
10780 let text = text.trim();
10781
10782 if text.is_empty() {
10783 return None;
10784 }
10785
10786 Some(text.to_string())
10787 }
10788
10789 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10790 self.transact(cx, |this, cx| {
10791 this.buffer
10792 .read(cx)
10793 .as_singleton()
10794 .expect("you can only call set_text on editors for singleton buffers")
10795 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10796 });
10797 }
10798
10799 pub fn display_text(&self, cx: &mut AppContext) -> String {
10800 self.display_map
10801 .update(cx, |map, cx| map.snapshot(cx))
10802 .text()
10803 }
10804
10805 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10806 let mut wrap_guides = smallvec::smallvec![];
10807
10808 if self.show_wrap_guides == Some(false) {
10809 return wrap_guides;
10810 }
10811
10812 let settings = self.buffer.read(cx).settings_at(0, cx);
10813 if settings.show_wrap_guides {
10814 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10815 wrap_guides.push((soft_wrap as usize, true));
10816 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10817 wrap_guides.push((soft_wrap as usize, true));
10818 }
10819 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10820 }
10821
10822 wrap_guides
10823 }
10824
10825 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10826 let settings = self.buffer.read(cx).settings_at(0, cx);
10827 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
10828 match mode {
10829 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
10830 SoftWrap::None
10831 }
10832 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10833 language_settings::SoftWrap::PreferredLineLength => {
10834 SoftWrap::Column(settings.preferred_line_length)
10835 }
10836 language_settings::SoftWrap::Bounded => {
10837 SoftWrap::Bounded(settings.preferred_line_length)
10838 }
10839 }
10840 }
10841
10842 pub fn set_soft_wrap_mode(
10843 &mut self,
10844 mode: language_settings::SoftWrap,
10845 cx: &mut ViewContext<Self>,
10846 ) {
10847 self.soft_wrap_mode_override = Some(mode);
10848 cx.notify();
10849 }
10850
10851 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
10852 self.text_style_refinement = Some(style);
10853 }
10854
10855 /// called by the Element so we know what style we were most recently rendered with.
10856 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10857 let rem_size = cx.rem_size();
10858 self.display_map.update(cx, |map, cx| {
10859 map.set_font(
10860 style.text.font(),
10861 style.text.font_size.to_pixels(rem_size),
10862 cx,
10863 )
10864 });
10865 self.style = Some(style);
10866 }
10867
10868 pub fn style(&self) -> Option<&EditorStyle> {
10869 self.style.as_ref()
10870 }
10871
10872 // Called by the element. This method is not designed to be called outside of the editor
10873 // element's layout code because it does not notify when rewrapping is computed synchronously.
10874 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10875 self.display_map
10876 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10877 }
10878
10879 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10880 if self.soft_wrap_mode_override.is_some() {
10881 self.soft_wrap_mode_override.take();
10882 } else {
10883 let soft_wrap = match self.soft_wrap_mode(cx) {
10884 SoftWrap::GitDiff => return,
10885 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
10886 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
10887 language_settings::SoftWrap::None
10888 }
10889 };
10890 self.soft_wrap_mode_override = Some(soft_wrap);
10891 }
10892 cx.notify();
10893 }
10894
10895 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10896 let Some(workspace) = self.workspace() else {
10897 return;
10898 };
10899 let fs = workspace.read(cx).app_state().fs.clone();
10900 let current_show = TabBarSettings::get_global(cx).show;
10901 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10902 setting.show = Some(!current_show);
10903 });
10904 }
10905
10906 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10907 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10908 self.buffer
10909 .read(cx)
10910 .settings_at(0, cx)
10911 .indent_guides
10912 .enabled
10913 });
10914 self.show_indent_guides = Some(!currently_enabled);
10915 cx.notify();
10916 }
10917
10918 fn should_show_indent_guides(&self) -> Option<bool> {
10919 self.show_indent_guides
10920 }
10921
10922 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10923 let mut editor_settings = EditorSettings::get_global(cx).clone();
10924 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10925 EditorSettings::override_global(editor_settings, cx);
10926 }
10927
10928 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
10929 self.use_relative_line_numbers
10930 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
10931 }
10932
10933 pub fn toggle_relative_line_numbers(
10934 &mut self,
10935 _: &ToggleRelativeLineNumbers,
10936 cx: &mut ViewContext<Self>,
10937 ) {
10938 let is_relative = self.should_use_relative_line_numbers(cx);
10939 self.set_relative_line_number(Some(!is_relative), cx)
10940 }
10941
10942 pub fn set_relative_line_number(
10943 &mut self,
10944 is_relative: Option<bool>,
10945 cx: &mut ViewContext<Self>,
10946 ) {
10947 self.use_relative_line_numbers = is_relative;
10948 cx.notify();
10949 }
10950
10951 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10952 self.show_gutter = show_gutter;
10953 cx.notify();
10954 }
10955
10956 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10957 self.show_line_numbers = Some(show_line_numbers);
10958 cx.notify();
10959 }
10960
10961 pub fn set_show_git_diff_gutter(
10962 &mut self,
10963 show_git_diff_gutter: bool,
10964 cx: &mut ViewContext<Self>,
10965 ) {
10966 self.show_git_diff_gutter = Some(show_git_diff_gutter);
10967 cx.notify();
10968 }
10969
10970 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10971 self.show_code_actions = Some(show_code_actions);
10972 cx.notify();
10973 }
10974
10975 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10976 self.show_runnables = Some(show_runnables);
10977 cx.notify();
10978 }
10979
10980 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10981 if self.display_map.read(cx).masked != masked {
10982 self.display_map.update(cx, |map, _| map.masked = masked);
10983 }
10984 cx.notify()
10985 }
10986
10987 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10988 self.show_wrap_guides = Some(show_wrap_guides);
10989 cx.notify();
10990 }
10991
10992 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10993 self.show_indent_guides = Some(show_indent_guides);
10994 cx.notify();
10995 }
10996
10997 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10998 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10999 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11000 if let Some(dir) = file.abs_path(cx).parent() {
11001 return Some(dir.to_owned());
11002 }
11003 }
11004
11005 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11006 return Some(project_path.path.to_path_buf());
11007 }
11008 }
11009
11010 None
11011 }
11012
11013 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11014 self.active_excerpt(cx)?
11015 .1
11016 .read(cx)
11017 .file()
11018 .and_then(|f| f.as_local())
11019 }
11020
11021 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11022 if let Some(target) = self.target_file(cx) {
11023 cx.reveal_path(&target.abs_path(cx));
11024 }
11025 }
11026
11027 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11028 if let Some(file) = self.target_file(cx) {
11029 if let Some(path) = file.abs_path(cx).to_str() {
11030 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11031 }
11032 }
11033 }
11034
11035 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11036 if let Some(file) = self.target_file(cx) {
11037 if let Some(path) = file.path().to_str() {
11038 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11039 }
11040 }
11041 }
11042
11043 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11044 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11045
11046 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11047 self.start_git_blame(true, cx);
11048 }
11049
11050 cx.notify();
11051 }
11052
11053 pub fn toggle_git_blame_inline(
11054 &mut self,
11055 _: &ToggleGitBlameInline,
11056 cx: &mut ViewContext<Self>,
11057 ) {
11058 self.toggle_git_blame_inline_internal(true, cx);
11059 cx.notify();
11060 }
11061
11062 pub fn git_blame_inline_enabled(&self) -> bool {
11063 self.git_blame_inline_enabled
11064 }
11065
11066 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11067 self.show_selection_menu = self
11068 .show_selection_menu
11069 .map(|show_selections_menu| !show_selections_menu)
11070 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11071
11072 cx.notify();
11073 }
11074
11075 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11076 self.show_selection_menu
11077 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11078 }
11079
11080 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11081 if let Some(project) = self.project.as_ref() {
11082 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11083 return;
11084 };
11085
11086 if buffer.read(cx).file().is_none() {
11087 return;
11088 }
11089
11090 let focused = self.focus_handle(cx).contains_focused(cx);
11091
11092 let project = project.clone();
11093 let blame =
11094 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11095 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11096 self.blame = Some(blame);
11097 }
11098 }
11099
11100 fn toggle_git_blame_inline_internal(
11101 &mut self,
11102 user_triggered: bool,
11103 cx: &mut ViewContext<Self>,
11104 ) {
11105 if self.git_blame_inline_enabled {
11106 self.git_blame_inline_enabled = false;
11107 self.show_git_blame_inline = false;
11108 self.show_git_blame_inline_delay_task.take();
11109 } else {
11110 self.git_blame_inline_enabled = true;
11111 self.start_git_blame_inline(user_triggered, cx);
11112 }
11113
11114 cx.notify();
11115 }
11116
11117 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11118 self.start_git_blame(user_triggered, cx);
11119
11120 if ProjectSettings::get_global(cx)
11121 .git
11122 .inline_blame_delay()
11123 .is_some()
11124 {
11125 self.start_inline_blame_timer(cx);
11126 } else {
11127 self.show_git_blame_inline = true
11128 }
11129 }
11130
11131 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11132 self.blame.as_ref()
11133 }
11134
11135 pub fn show_git_blame_gutter(&self) -> bool {
11136 self.show_git_blame_gutter
11137 }
11138
11139 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11140 self.show_git_blame_gutter && self.has_blame_entries(cx)
11141 }
11142
11143 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11144 self.show_git_blame_inline
11145 && self.focus_handle.is_focused(cx)
11146 && !self.newest_selection_head_on_empty_line(cx)
11147 && self.has_blame_entries(cx)
11148 }
11149
11150 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11151 self.blame()
11152 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11153 }
11154
11155 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11156 let cursor_anchor = self.selections.newest_anchor().head();
11157
11158 let snapshot = self.buffer.read(cx).snapshot(cx);
11159 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11160
11161 snapshot.line_len(buffer_row) == 0
11162 }
11163
11164 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11165 let buffer_and_selection = maybe!({
11166 let selection = self.selections.newest::<Point>(cx);
11167 let selection_range = selection.range();
11168
11169 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11170 (buffer, selection_range.start.row..selection_range.end.row)
11171 } else {
11172 let buffer_ranges = self
11173 .buffer()
11174 .read(cx)
11175 .range_to_buffer_ranges(selection_range, cx);
11176
11177 let (buffer, range, _) = if selection.reversed {
11178 buffer_ranges.first()
11179 } else {
11180 buffer_ranges.last()
11181 }?;
11182
11183 let snapshot = buffer.read(cx).snapshot();
11184 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11185 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11186 (buffer.clone(), selection)
11187 };
11188
11189 Some((buffer, selection))
11190 });
11191
11192 let Some((buffer, selection)) = buffer_and_selection else {
11193 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11194 };
11195
11196 let Some(project) = self.project.as_ref() else {
11197 return Task::ready(Err(anyhow!("editor does not have project")));
11198 };
11199
11200 project.update(cx, |project, cx| {
11201 project.get_permalink_to_line(&buffer, selection, cx)
11202 })
11203 }
11204
11205 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11206 let permalink_task = self.get_permalink_to_line(cx);
11207 let workspace = self.workspace();
11208
11209 cx.spawn(|_, mut cx| async move {
11210 match permalink_task.await {
11211 Ok(permalink) => {
11212 cx.update(|cx| {
11213 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11214 })
11215 .ok();
11216 }
11217 Err(err) => {
11218 let message = format!("Failed to copy permalink: {err}");
11219
11220 Err::<(), anyhow::Error>(err).log_err();
11221
11222 if let Some(workspace) = workspace {
11223 workspace
11224 .update(&mut cx, |workspace, cx| {
11225 struct CopyPermalinkToLine;
11226
11227 workspace.show_toast(
11228 Toast::new(
11229 NotificationId::unique::<CopyPermalinkToLine>(),
11230 message,
11231 ),
11232 cx,
11233 )
11234 })
11235 .ok();
11236 }
11237 }
11238 }
11239 })
11240 .detach();
11241 }
11242
11243 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11244 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11245 if let Some(file) = self.target_file(cx) {
11246 if let Some(path) = file.path().to_str() {
11247 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11248 }
11249 }
11250 }
11251
11252 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11253 let permalink_task = self.get_permalink_to_line(cx);
11254 let workspace = self.workspace();
11255
11256 cx.spawn(|_, mut cx| async move {
11257 match permalink_task.await {
11258 Ok(permalink) => {
11259 cx.update(|cx| {
11260 cx.open_url(permalink.as_ref());
11261 })
11262 .ok();
11263 }
11264 Err(err) => {
11265 let message = format!("Failed to open permalink: {err}");
11266
11267 Err::<(), anyhow::Error>(err).log_err();
11268
11269 if let Some(workspace) = workspace {
11270 workspace
11271 .update(&mut cx, |workspace, cx| {
11272 struct OpenPermalinkToLine;
11273
11274 workspace.show_toast(
11275 Toast::new(
11276 NotificationId::unique::<OpenPermalinkToLine>(),
11277 message,
11278 ),
11279 cx,
11280 )
11281 })
11282 .ok();
11283 }
11284 }
11285 }
11286 })
11287 .detach();
11288 }
11289
11290 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11291 self.insert_uuid(UuidVersion::V4, cx);
11292 }
11293
11294 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11295 self.insert_uuid(UuidVersion::V7, cx);
11296 }
11297
11298 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11299 self.transact(cx, |this, cx| {
11300 let edits = this
11301 .selections
11302 .all::<Point>(cx)
11303 .into_iter()
11304 .map(|selection| {
11305 let uuid = match version {
11306 UuidVersion::V4 => uuid::Uuid::new_v4(),
11307 UuidVersion::V7 => uuid::Uuid::now_v7(),
11308 };
11309
11310 (selection.range(), uuid.to_string())
11311 });
11312 this.edit(edits, cx);
11313 this.refresh_inline_completion(true, false, cx);
11314 });
11315 }
11316
11317 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11318 /// last highlight added will be used.
11319 ///
11320 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11321 pub fn highlight_rows<T: 'static>(
11322 &mut self,
11323 range: Range<Anchor>,
11324 color: Hsla,
11325 should_autoscroll: bool,
11326 cx: &mut ViewContext<Self>,
11327 ) {
11328 let snapshot = self.buffer().read(cx).snapshot(cx);
11329 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11330 let ix = row_highlights.binary_search_by(|highlight| {
11331 Ordering::Equal
11332 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11333 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11334 });
11335
11336 if let Err(mut ix) = ix {
11337 let index = post_inc(&mut self.highlight_order);
11338
11339 // If this range intersects with the preceding highlight, then merge it with
11340 // the preceding highlight. Otherwise insert a new highlight.
11341 let mut merged = false;
11342 if ix > 0 {
11343 let prev_highlight = &mut row_highlights[ix - 1];
11344 if prev_highlight
11345 .range
11346 .end
11347 .cmp(&range.start, &snapshot)
11348 .is_ge()
11349 {
11350 ix -= 1;
11351 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11352 prev_highlight.range.end = range.end;
11353 }
11354 merged = true;
11355 prev_highlight.index = index;
11356 prev_highlight.color = color;
11357 prev_highlight.should_autoscroll = should_autoscroll;
11358 }
11359 }
11360
11361 if !merged {
11362 row_highlights.insert(
11363 ix,
11364 RowHighlight {
11365 range: range.clone(),
11366 index,
11367 color,
11368 should_autoscroll,
11369 },
11370 );
11371 }
11372
11373 // If any of the following highlights intersect with this one, merge them.
11374 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11375 let highlight = &row_highlights[ix];
11376 if next_highlight
11377 .range
11378 .start
11379 .cmp(&highlight.range.end, &snapshot)
11380 .is_le()
11381 {
11382 if next_highlight
11383 .range
11384 .end
11385 .cmp(&highlight.range.end, &snapshot)
11386 .is_gt()
11387 {
11388 row_highlights[ix].range.end = next_highlight.range.end;
11389 }
11390 row_highlights.remove(ix + 1);
11391 } else {
11392 break;
11393 }
11394 }
11395 }
11396 }
11397
11398 /// Remove any highlighted row ranges of the given type that intersect the
11399 /// given ranges.
11400 pub fn remove_highlighted_rows<T: 'static>(
11401 &mut self,
11402 ranges_to_remove: Vec<Range<Anchor>>,
11403 cx: &mut ViewContext<Self>,
11404 ) {
11405 let snapshot = self.buffer().read(cx).snapshot(cx);
11406 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11407 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11408 row_highlights.retain(|highlight| {
11409 while let Some(range_to_remove) = ranges_to_remove.peek() {
11410 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11411 Ordering::Less | Ordering::Equal => {
11412 ranges_to_remove.next();
11413 }
11414 Ordering::Greater => {
11415 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11416 Ordering::Less | Ordering::Equal => {
11417 return false;
11418 }
11419 Ordering::Greater => break,
11420 }
11421 }
11422 }
11423 }
11424
11425 true
11426 })
11427 }
11428
11429 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11430 pub fn clear_row_highlights<T: 'static>(&mut self) {
11431 self.highlighted_rows.remove(&TypeId::of::<T>());
11432 }
11433
11434 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11435 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11436 self.highlighted_rows
11437 .get(&TypeId::of::<T>())
11438 .map_or(&[] as &[_], |vec| vec.as_slice())
11439 .iter()
11440 .map(|highlight| (highlight.range.clone(), highlight.color))
11441 }
11442
11443 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11444 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11445 /// Allows to ignore certain kinds of highlights.
11446 pub fn highlighted_display_rows(
11447 &mut self,
11448 cx: &mut WindowContext,
11449 ) -> BTreeMap<DisplayRow, Hsla> {
11450 let snapshot = self.snapshot(cx);
11451 let mut used_highlight_orders = HashMap::default();
11452 self.highlighted_rows
11453 .iter()
11454 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11455 .fold(
11456 BTreeMap::<DisplayRow, Hsla>::new(),
11457 |mut unique_rows, highlight| {
11458 let start = highlight.range.start.to_display_point(&snapshot);
11459 let end = highlight.range.end.to_display_point(&snapshot);
11460 let start_row = start.row().0;
11461 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11462 && end.column() == 0
11463 {
11464 end.row().0.saturating_sub(1)
11465 } else {
11466 end.row().0
11467 };
11468 for row in start_row..=end_row {
11469 let used_index =
11470 used_highlight_orders.entry(row).or_insert(highlight.index);
11471 if highlight.index >= *used_index {
11472 *used_index = highlight.index;
11473 unique_rows.insert(DisplayRow(row), highlight.color);
11474 }
11475 }
11476 unique_rows
11477 },
11478 )
11479 }
11480
11481 pub fn highlighted_display_row_for_autoscroll(
11482 &self,
11483 snapshot: &DisplaySnapshot,
11484 ) -> Option<DisplayRow> {
11485 self.highlighted_rows
11486 .values()
11487 .flat_map(|highlighted_rows| highlighted_rows.iter())
11488 .filter_map(|highlight| {
11489 if highlight.should_autoscroll {
11490 Some(highlight.range.start.to_display_point(snapshot).row())
11491 } else {
11492 None
11493 }
11494 })
11495 .min()
11496 }
11497
11498 pub fn set_search_within_ranges(
11499 &mut self,
11500 ranges: &[Range<Anchor>],
11501 cx: &mut ViewContext<Self>,
11502 ) {
11503 self.highlight_background::<SearchWithinRange>(
11504 ranges,
11505 |colors| colors.editor_document_highlight_read_background,
11506 cx,
11507 )
11508 }
11509
11510 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11511 self.breadcrumb_header = Some(new_header);
11512 }
11513
11514 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11515 self.clear_background_highlights::<SearchWithinRange>(cx);
11516 }
11517
11518 pub fn highlight_background<T: 'static>(
11519 &mut self,
11520 ranges: &[Range<Anchor>],
11521 color_fetcher: fn(&ThemeColors) -> Hsla,
11522 cx: &mut ViewContext<Self>,
11523 ) {
11524 self.background_highlights
11525 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11526 self.scrollbar_marker_state.dirty = true;
11527 cx.notify();
11528 }
11529
11530 pub fn clear_background_highlights<T: 'static>(
11531 &mut self,
11532 cx: &mut ViewContext<Self>,
11533 ) -> Option<BackgroundHighlight> {
11534 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11535 if !text_highlights.1.is_empty() {
11536 self.scrollbar_marker_state.dirty = true;
11537 cx.notify();
11538 }
11539 Some(text_highlights)
11540 }
11541
11542 pub fn highlight_gutter<T: 'static>(
11543 &mut self,
11544 ranges: &[Range<Anchor>],
11545 color_fetcher: fn(&AppContext) -> Hsla,
11546 cx: &mut ViewContext<Self>,
11547 ) {
11548 self.gutter_highlights
11549 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11550 cx.notify();
11551 }
11552
11553 pub fn clear_gutter_highlights<T: 'static>(
11554 &mut self,
11555 cx: &mut ViewContext<Self>,
11556 ) -> Option<GutterHighlight> {
11557 cx.notify();
11558 self.gutter_highlights.remove(&TypeId::of::<T>())
11559 }
11560
11561 #[cfg(feature = "test-support")]
11562 pub fn all_text_background_highlights(
11563 &mut self,
11564 cx: &mut ViewContext<Self>,
11565 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11566 let snapshot = self.snapshot(cx);
11567 let buffer = &snapshot.buffer_snapshot;
11568 let start = buffer.anchor_before(0);
11569 let end = buffer.anchor_after(buffer.len());
11570 let theme = cx.theme().colors();
11571 self.background_highlights_in_range(start..end, &snapshot, theme)
11572 }
11573
11574 #[cfg(feature = "test-support")]
11575 pub fn search_background_highlights(
11576 &mut self,
11577 cx: &mut ViewContext<Self>,
11578 ) -> Vec<Range<Point>> {
11579 let snapshot = self.buffer().read(cx).snapshot(cx);
11580
11581 let highlights = self
11582 .background_highlights
11583 .get(&TypeId::of::<items::BufferSearchHighlights>());
11584
11585 if let Some((_color, ranges)) = highlights {
11586 ranges
11587 .iter()
11588 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11589 .collect_vec()
11590 } else {
11591 vec![]
11592 }
11593 }
11594
11595 fn document_highlights_for_position<'a>(
11596 &'a self,
11597 position: Anchor,
11598 buffer: &'a MultiBufferSnapshot,
11599 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11600 let read_highlights = self
11601 .background_highlights
11602 .get(&TypeId::of::<DocumentHighlightRead>())
11603 .map(|h| &h.1);
11604 let write_highlights = self
11605 .background_highlights
11606 .get(&TypeId::of::<DocumentHighlightWrite>())
11607 .map(|h| &h.1);
11608 let left_position = position.bias_left(buffer);
11609 let right_position = position.bias_right(buffer);
11610 read_highlights
11611 .into_iter()
11612 .chain(write_highlights)
11613 .flat_map(move |ranges| {
11614 let start_ix = match ranges.binary_search_by(|probe| {
11615 let cmp = probe.end.cmp(&left_position, buffer);
11616 if cmp.is_ge() {
11617 Ordering::Greater
11618 } else {
11619 Ordering::Less
11620 }
11621 }) {
11622 Ok(i) | Err(i) => i,
11623 };
11624
11625 ranges[start_ix..]
11626 .iter()
11627 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11628 })
11629 }
11630
11631 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11632 self.background_highlights
11633 .get(&TypeId::of::<T>())
11634 .map_or(false, |(_, highlights)| !highlights.is_empty())
11635 }
11636
11637 pub fn background_highlights_in_range(
11638 &self,
11639 search_range: Range<Anchor>,
11640 display_snapshot: &DisplaySnapshot,
11641 theme: &ThemeColors,
11642 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11643 let mut results = Vec::new();
11644 for (color_fetcher, ranges) in self.background_highlights.values() {
11645 let color = color_fetcher(theme);
11646 let start_ix = match ranges.binary_search_by(|probe| {
11647 let cmp = probe
11648 .end
11649 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11650 if cmp.is_gt() {
11651 Ordering::Greater
11652 } else {
11653 Ordering::Less
11654 }
11655 }) {
11656 Ok(i) | Err(i) => i,
11657 };
11658 for range in &ranges[start_ix..] {
11659 if range
11660 .start
11661 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11662 .is_ge()
11663 {
11664 break;
11665 }
11666
11667 let start = range.start.to_display_point(display_snapshot);
11668 let end = range.end.to_display_point(display_snapshot);
11669 results.push((start..end, color))
11670 }
11671 }
11672 results
11673 }
11674
11675 pub fn background_highlight_row_ranges<T: 'static>(
11676 &self,
11677 search_range: Range<Anchor>,
11678 display_snapshot: &DisplaySnapshot,
11679 count: usize,
11680 ) -> Vec<RangeInclusive<DisplayPoint>> {
11681 let mut results = Vec::new();
11682 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11683 return vec![];
11684 };
11685
11686 let start_ix = match ranges.binary_search_by(|probe| {
11687 let cmp = probe
11688 .end
11689 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11690 if cmp.is_gt() {
11691 Ordering::Greater
11692 } else {
11693 Ordering::Less
11694 }
11695 }) {
11696 Ok(i) | Err(i) => i,
11697 };
11698 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11699 if let (Some(start_display), Some(end_display)) = (start, end) {
11700 results.push(
11701 start_display.to_display_point(display_snapshot)
11702 ..=end_display.to_display_point(display_snapshot),
11703 );
11704 }
11705 };
11706 let mut start_row: Option<Point> = None;
11707 let mut end_row: Option<Point> = None;
11708 if ranges.len() > count {
11709 return Vec::new();
11710 }
11711 for range in &ranges[start_ix..] {
11712 if range
11713 .start
11714 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11715 .is_ge()
11716 {
11717 break;
11718 }
11719 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11720 if let Some(current_row) = &end_row {
11721 if end.row == current_row.row {
11722 continue;
11723 }
11724 }
11725 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11726 if start_row.is_none() {
11727 assert_eq!(end_row, None);
11728 start_row = Some(start);
11729 end_row = Some(end);
11730 continue;
11731 }
11732 if let Some(current_end) = end_row.as_mut() {
11733 if start.row > current_end.row + 1 {
11734 push_region(start_row, end_row);
11735 start_row = Some(start);
11736 end_row = Some(end);
11737 } else {
11738 // Merge two hunks.
11739 *current_end = end;
11740 }
11741 } else {
11742 unreachable!();
11743 }
11744 }
11745 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11746 push_region(start_row, end_row);
11747 results
11748 }
11749
11750 pub fn gutter_highlights_in_range(
11751 &self,
11752 search_range: Range<Anchor>,
11753 display_snapshot: &DisplaySnapshot,
11754 cx: &AppContext,
11755 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11756 let mut results = Vec::new();
11757 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11758 let color = color_fetcher(cx);
11759 let start_ix = match ranges.binary_search_by(|probe| {
11760 let cmp = probe
11761 .end
11762 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11763 if cmp.is_gt() {
11764 Ordering::Greater
11765 } else {
11766 Ordering::Less
11767 }
11768 }) {
11769 Ok(i) | Err(i) => i,
11770 };
11771 for range in &ranges[start_ix..] {
11772 if range
11773 .start
11774 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11775 .is_ge()
11776 {
11777 break;
11778 }
11779
11780 let start = range.start.to_display_point(display_snapshot);
11781 let end = range.end.to_display_point(display_snapshot);
11782 results.push((start..end, color))
11783 }
11784 }
11785 results
11786 }
11787
11788 /// Get the text ranges corresponding to the redaction query
11789 pub fn redacted_ranges(
11790 &self,
11791 search_range: Range<Anchor>,
11792 display_snapshot: &DisplaySnapshot,
11793 cx: &WindowContext,
11794 ) -> Vec<Range<DisplayPoint>> {
11795 display_snapshot
11796 .buffer_snapshot
11797 .redacted_ranges(search_range, |file| {
11798 if let Some(file) = file {
11799 file.is_private()
11800 && EditorSettings::get(
11801 Some(SettingsLocation {
11802 worktree_id: file.worktree_id(cx),
11803 path: file.path().as_ref(),
11804 }),
11805 cx,
11806 )
11807 .redact_private_values
11808 } else {
11809 false
11810 }
11811 })
11812 .map(|range| {
11813 range.start.to_display_point(display_snapshot)
11814 ..range.end.to_display_point(display_snapshot)
11815 })
11816 .collect()
11817 }
11818
11819 pub fn highlight_text<T: 'static>(
11820 &mut self,
11821 ranges: Vec<Range<Anchor>>,
11822 style: HighlightStyle,
11823 cx: &mut ViewContext<Self>,
11824 ) {
11825 self.display_map.update(cx, |map, _| {
11826 map.highlight_text(TypeId::of::<T>(), ranges, style)
11827 });
11828 cx.notify();
11829 }
11830
11831 pub(crate) fn highlight_inlays<T: 'static>(
11832 &mut self,
11833 highlights: Vec<InlayHighlight>,
11834 style: HighlightStyle,
11835 cx: &mut ViewContext<Self>,
11836 ) {
11837 self.display_map.update(cx, |map, _| {
11838 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11839 });
11840 cx.notify();
11841 }
11842
11843 pub fn text_highlights<'a, T: 'static>(
11844 &'a self,
11845 cx: &'a AppContext,
11846 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11847 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11848 }
11849
11850 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11851 let cleared = self
11852 .display_map
11853 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11854 if cleared {
11855 cx.notify();
11856 }
11857 }
11858
11859 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11860 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11861 && self.focus_handle.is_focused(cx)
11862 }
11863
11864 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11865 self.show_cursor_when_unfocused = is_enabled;
11866 cx.notify();
11867 }
11868
11869 pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
11870 self.project
11871 .as_ref()
11872 .map(|project| project.read(cx).lsp_store())
11873 }
11874
11875 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11876 cx.notify();
11877 }
11878
11879 fn on_buffer_event(
11880 &mut self,
11881 multibuffer: Model<MultiBuffer>,
11882 event: &multi_buffer::Event,
11883 cx: &mut ViewContext<Self>,
11884 ) {
11885 match event {
11886 multi_buffer::Event::Edited {
11887 singleton_buffer_edited,
11888 edited_buffer: buffer_edited,
11889 } => {
11890 self.scrollbar_marker_state.dirty = true;
11891 self.active_indent_guides_state.dirty = true;
11892 self.refresh_active_diagnostics(cx);
11893 self.refresh_code_actions(cx);
11894 if self.has_active_inline_completion() {
11895 self.update_visible_inline_completion(cx);
11896 }
11897 if let Some(buffer) = buffer_edited {
11898 let buffer_id = buffer.read(cx).remote_id();
11899 if !self.registered_buffers.contains_key(&buffer_id) {
11900 if let Some(lsp_store) = self.lsp_store(cx) {
11901 lsp_store.update(cx, |lsp_store, cx| {
11902 self.registered_buffers.insert(
11903 buffer_id,
11904 lsp_store.register_buffer_with_language_servers(&buffer, cx),
11905 );
11906 })
11907 }
11908 }
11909 }
11910 cx.emit(EditorEvent::BufferEdited);
11911 cx.emit(SearchEvent::MatchesInvalidated);
11912 if *singleton_buffer_edited {
11913 if let Some(project) = &self.project {
11914 let project = project.read(cx);
11915 #[allow(clippy::mutable_key_type)]
11916 let languages_affected = multibuffer
11917 .read(cx)
11918 .all_buffers()
11919 .into_iter()
11920 .filter_map(|buffer| {
11921 let buffer = buffer.read(cx);
11922 let language = buffer.language()?;
11923 if project.is_local()
11924 && project
11925 .language_servers_for_local_buffer(buffer, cx)
11926 .count()
11927 == 0
11928 {
11929 None
11930 } else {
11931 Some(language)
11932 }
11933 })
11934 .cloned()
11935 .collect::<HashSet<_>>();
11936 if !languages_affected.is_empty() {
11937 self.refresh_inlay_hints(
11938 InlayHintRefreshReason::BufferEdited(languages_affected),
11939 cx,
11940 );
11941 }
11942 }
11943 }
11944
11945 let Some(project) = &self.project else { return };
11946 let (telemetry, is_via_ssh) = {
11947 let project = project.read(cx);
11948 let telemetry = project.client().telemetry().clone();
11949 let is_via_ssh = project.is_via_ssh();
11950 (telemetry, is_via_ssh)
11951 };
11952 refresh_linked_ranges(self, cx);
11953 telemetry.log_edit_event("editor", is_via_ssh);
11954 }
11955 multi_buffer::Event::ExcerptsAdded {
11956 buffer,
11957 predecessor,
11958 excerpts,
11959 } => {
11960 self.tasks_update_task = Some(self.refresh_runnables(cx));
11961 let buffer_id = buffer.read(cx).remote_id();
11962 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
11963 if let Some(project) = &self.project {
11964 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
11965 }
11966 }
11967 cx.emit(EditorEvent::ExcerptsAdded {
11968 buffer: buffer.clone(),
11969 predecessor: *predecessor,
11970 excerpts: excerpts.clone(),
11971 });
11972 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11973 }
11974 multi_buffer::Event::ExcerptsRemoved { ids } => {
11975 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11976 let buffer = self.buffer.read(cx);
11977 self.registered_buffers
11978 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
11979 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11980 }
11981 multi_buffer::Event::ExcerptsEdited { ids } => {
11982 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11983 }
11984 multi_buffer::Event::ExcerptsExpanded { ids } => {
11985 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11986 }
11987 multi_buffer::Event::Reparsed(buffer_id) => {
11988 self.tasks_update_task = Some(self.refresh_runnables(cx));
11989
11990 cx.emit(EditorEvent::Reparsed(*buffer_id));
11991 }
11992 multi_buffer::Event::LanguageChanged(buffer_id) => {
11993 linked_editing_ranges::refresh_linked_ranges(self, cx);
11994 cx.emit(EditorEvent::Reparsed(*buffer_id));
11995 cx.notify();
11996 }
11997 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11998 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11999 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12000 cx.emit(EditorEvent::TitleChanged)
12001 }
12002 // multi_buffer::Event::DiffBaseChanged => {
12003 // self.scrollbar_marker_state.dirty = true;
12004 // cx.emit(EditorEvent::DiffBaseChanged);
12005 // cx.notify();
12006 // }
12007 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12008 multi_buffer::Event::DiagnosticsUpdated => {
12009 self.refresh_active_diagnostics(cx);
12010 self.scrollbar_marker_state.dirty = true;
12011 cx.notify();
12012 }
12013 _ => {}
12014 };
12015 }
12016
12017 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12018 cx.notify();
12019 }
12020
12021 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12022 self.tasks_update_task = Some(self.refresh_runnables(cx));
12023 self.refresh_inline_completion(true, false, cx);
12024 self.refresh_inlay_hints(
12025 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12026 self.selections.newest_anchor().head(),
12027 &self.buffer.read(cx).snapshot(cx),
12028 cx,
12029 )),
12030 cx,
12031 );
12032
12033 let old_cursor_shape = self.cursor_shape;
12034
12035 {
12036 let editor_settings = EditorSettings::get_global(cx);
12037 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12038 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12039 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12040 }
12041
12042 if old_cursor_shape != self.cursor_shape {
12043 cx.emit(EditorEvent::CursorShapeChanged);
12044 }
12045
12046 let project_settings = ProjectSettings::get_global(cx);
12047 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12048
12049 if self.mode == EditorMode::Full {
12050 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12051 if self.git_blame_inline_enabled != inline_blame_enabled {
12052 self.toggle_git_blame_inline_internal(false, cx);
12053 }
12054 }
12055
12056 cx.notify();
12057 }
12058
12059 pub fn set_searchable(&mut self, searchable: bool) {
12060 self.searchable = searchable;
12061 }
12062
12063 pub fn searchable(&self) -> bool {
12064 self.searchable
12065 }
12066
12067 fn open_proposed_changes_editor(
12068 &mut self,
12069 _: &OpenProposedChangesEditor,
12070 cx: &mut ViewContext<Self>,
12071 ) {
12072 let Some(workspace) = self.workspace() else {
12073 cx.propagate();
12074 return;
12075 };
12076
12077 let selections = self.selections.all::<usize>(cx);
12078 let buffer = self.buffer.read(cx);
12079 let mut new_selections_by_buffer = HashMap::default();
12080 for selection in selections {
12081 for (buffer, range, _) in
12082 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12083 {
12084 let mut range = range.to_point(buffer.read(cx));
12085 range.start.column = 0;
12086 range.end.column = buffer.read(cx).line_len(range.end.row);
12087 new_selections_by_buffer
12088 .entry(buffer)
12089 .or_insert(Vec::new())
12090 .push(range)
12091 }
12092 }
12093
12094 let proposed_changes_buffers = new_selections_by_buffer
12095 .into_iter()
12096 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12097 .collect::<Vec<_>>();
12098 let proposed_changes_editor = cx.new_view(|cx| {
12099 ProposedChangesEditor::new(
12100 "Proposed changes",
12101 proposed_changes_buffers,
12102 self.project.clone(),
12103 cx,
12104 )
12105 });
12106
12107 cx.window_context().defer(move |cx| {
12108 workspace.update(cx, |workspace, cx| {
12109 workspace.active_pane().update(cx, |pane, cx| {
12110 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12111 });
12112 });
12113 });
12114 }
12115
12116 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12117 self.open_excerpts_common(None, true, cx)
12118 }
12119
12120 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12121 self.open_excerpts_common(None, false, cx)
12122 }
12123
12124 fn open_excerpts_common(
12125 &mut self,
12126 jump_data: Option<JumpData>,
12127 split: bool,
12128 cx: &mut ViewContext<Self>,
12129 ) {
12130 let Some(workspace) = self.workspace() else {
12131 cx.propagate();
12132 return;
12133 };
12134
12135 if self.buffer.read(cx).is_singleton() {
12136 cx.propagate();
12137 return;
12138 }
12139
12140 let mut new_selections_by_buffer = HashMap::default();
12141 match &jump_data {
12142 Some(jump_data) => {
12143 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12144 if let Some(buffer) = multi_buffer_snapshot
12145 .buffer_id_for_excerpt(jump_data.excerpt_id)
12146 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12147 {
12148 let buffer_snapshot = buffer.read(cx).snapshot();
12149 let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12150 language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12151 } else {
12152 buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12153 };
12154 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12155 new_selections_by_buffer.insert(
12156 buffer,
12157 (
12158 vec![jump_to_offset..jump_to_offset],
12159 Some(jump_data.line_offset_from_top),
12160 ),
12161 );
12162 }
12163 }
12164 None => {
12165 let selections = self.selections.all::<usize>(cx);
12166 let buffer = self.buffer.read(cx);
12167 for selection in selections {
12168 for (mut buffer_handle, mut range, _) in
12169 buffer.range_to_buffer_ranges(selection.range(), cx)
12170 {
12171 // When editing branch buffers, jump to the corresponding location
12172 // in their base buffer.
12173 let buffer = buffer_handle.read(cx);
12174 if let Some(base_buffer) = buffer.base_buffer() {
12175 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12176 buffer_handle = base_buffer;
12177 }
12178
12179 if selection.reversed {
12180 mem::swap(&mut range.start, &mut range.end);
12181 }
12182 new_selections_by_buffer
12183 .entry(buffer_handle)
12184 .or_insert((Vec::new(), None))
12185 .0
12186 .push(range)
12187 }
12188 }
12189 }
12190 }
12191
12192 if new_selections_by_buffer.is_empty() {
12193 return;
12194 }
12195
12196 // We defer the pane interaction because we ourselves are a workspace item
12197 // and activating a new item causes the pane to call a method on us reentrantly,
12198 // which panics if we're on the stack.
12199 cx.window_context().defer(move |cx| {
12200 workspace.update(cx, |workspace, cx| {
12201 let pane = if split {
12202 workspace.adjacent_pane(cx)
12203 } else {
12204 workspace.active_pane().clone()
12205 };
12206
12207 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12208 let editor = buffer
12209 .read(cx)
12210 .file()
12211 .is_none()
12212 .then(|| {
12213 // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12214 // so `workspace.open_project_item` will never find them, always opening a new editor.
12215 // Instead, we try to activate the existing editor in the pane first.
12216 let (editor, pane_item_index) =
12217 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12218 let editor = item.downcast::<Editor>()?;
12219 let singleton_buffer =
12220 editor.read(cx).buffer().read(cx).as_singleton()?;
12221 if singleton_buffer == buffer {
12222 Some((editor, i))
12223 } else {
12224 None
12225 }
12226 })?;
12227 pane.update(cx, |pane, cx| {
12228 pane.activate_item(pane_item_index, true, true, cx)
12229 });
12230 Some(editor)
12231 })
12232 .flatten()
12233 .unwrap_or_else(|| {
12234 workspace.open_project_item::<Self>(
12235 pane.clone(),
12236 buffer,
12237 true,
12238 true,
12239 cx,
12240 )
12241 });
12242
12243 editor.update(cx, |editor, cx| {
12244 let autoscroll = match scroll_offset {
12245 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12246 None => Autoscroll::newest(),
12247 };
12248 let nav_history = editor.nav_history.take();
12249 editor.change_selections(Some(autoscroll), cx, |s| {
12250 s.select_ranges(ranges);
12251 });
12252 editor.nav_history = nav_history;
12253 });
12254 }
12255 })
12256 });
12257 }
12258
12259 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12260 let snapshot = self.buffer.read(cx).read(cx);
12261 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12262 Some(
12263 ranges
12264 .iter()
12265 .map(move |range| {
12266 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12267 })
12268 .collect(),
12269 )
12270 }
12271
12272 fn selection_replacement_ranges(
12273 &self,
12274 range: Range<OffsetUtf16>,
12275 cx: &mut AppContext,
12276 ) -> Vec<Range<OffsetUtf16>> {
12277 let selections = self.selections.all::<OffsetUtf16>(cx);
12278 let newest_selection = selections
12279 .iter()
12280 .max_by_key(|selection| selection.id)
12281 .unwrap();
12282 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12283 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12284 let snapshot = self.buffer.read(cx).read(cx);
12285 selections
12286 .into_iter()
12287 .map(|mut selection| {
12288 selection.start.0 =
12289 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12290 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12291 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12292 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12293 })
12294 .collect()
12295 }
12296
12297 fn report_editor_event(
12298 &self,
12299 operation: &'static str,
12300 file_extension: Option<String>,
12301 cx: &AppContext,
12302 ) {
12303 if cfg!(any(test, feature = "test-support")) {
12304 return;
12305 }
12306
12307 let Some(project) = &self.project else { return };
12308
12309 // If None, we are in a file without an extension
12310 let file = self
12311 .buffer
12312 .read(cx)
12313 .as_singleton()
12314 .and_then(|b| b.read(cx).file());
12315 let file_extension = file_extension.or(file
12316 .as_ref()
12317 .and_then(|file| Path::new(file.file_name(cx)).extension())
12318 .and_then(|e| e.to_str())
12319 .map(|a| a.to_string()));
12320
12321 let vim_mode = cx
12322 .global::<SettingsStore>()
12323 .raw_user_settings()
12324 .get("vim_mode")
12325 == Some(&serde_json::Value::Bool(true));
12326
12327 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12328 == language::language_settings::InlineCompletionProvider::Copilot;
12329 let copilot_enabled_for_language = self
12330 .buffer
12331 .read(cx)
12332 .settings_at(0, cx)
12333 .show_inline_completions;
12334
12335 let project = project.read(cx);
12336 let telemetry = project.client().telemetry().clone();
12337 telemetry.report_editor_event(
12338 file_extension,
12339 vim_mode,
12340 operation,
12341 copilot_enabled,
12342 copilot_enabled_for_language,
12343 project.is_via_ssh(),
12344 )
12345 }
12346
12347 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12348 /// with each line being an array of {text, highlight} objects.
12349 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12350 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12351 return;
12352 };
12353
12354 #[derive(Serialize)]
12355 struct Chunk<'a> {
12356 text: String,
12357 highlight: Option<&'a str>,
12358 }
12359
12360 let snapshot = buffer.read(cx).snapshot();
12361 let range = self
12362 .selected_text_range(false, cx)
12363 .and_then(|selection| {
12364 if selection.range.is_empty() {
12365 None
12366 } else {
12367 Some(selection.range)
12368 }
12369 })
12370 .unwrap_or_else(|| 0..snapshot.len());
12371
12372 let chunks = snapshot.chunks(range, true);
12373 let mut lines = Vec::new();
12374 let mut line: VecDeque<Chunk> = VecDeque::new();
12375
12376 let Some(style) = self.style.as_ref() else {
12377 return;
12378 };
12379
12380 for chunk in chunks {
12381 let highlight = chunk
12382 .syntax_highlight_id
12383 .and_then(|id| id.name(&style.syntax));
12384 let mut chunk_lines = chunk.text.split('\n').peekable();
12385 while let Some(text) = chunk_lines.next() {
12386 let mut merged_with_last_token = false;
12387 if let Some(last_token) = line.back_mut() {
12388 if last_token.highlight == highlight {
12389 last_token.text.push_str(text);
12390 merged_with_last_token = true;
12391 }
12392 }
12393
12394 if !merged_with_last_token {
12395 line.push_back(Chunk {
12396 text: text.into(),
12397 highlight,
12398 });
12399 }
12400
12401 if chunk_lines.peek().is_some() {
12402 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12403 line.pop_front();
12404 }
12405 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12406 line.pop_back();
12407 }
12408
12409 lines.push(mem::take(&mut line));
12410 }
12411 }
12412 }
12413
12414 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12415 return;
12416 };
12417 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12418 }
12419
12420 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12421 self.request_autoscroll(Autoscroll::newest(), cx);
12422 let position = self.selections.newest_display(cx).start;
12423 mouse_context_menu::deploy_context_menu(self, None, position, cx);
12424 }
12425
12426 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12427 &self.inlay_hint_cache
12428 }
12429
12430 pub fn replay_insert_event(
12431 &mut self,
12432 text: &str,
12433 relative_utf16_range: Option<Range<isize>>,
12434 cx: &mut ViewContext<Self>,
12435 ) {
12436 if !self.input_enabled {
12437 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12438 return;
12439 }
12440 if let Some(relative_utf16_range) = relative_utf16_range {
12441 let selections = self.selections.all::<OffsetUtf16>(cx);
12442 self.change_selections(None, cx, |s| {
12443 let new_ranges = selections.into_iter().map(|range| {
12444 let start = OffsetUtf16(
12445 range
12446 .head()
12447 .0
12448 .saturating_add_signed(relative_utf16_range.start),
12449 );
12450 let end = OffsetUtf16(
12451 range
12452 .head()
12453 .0
12454 .saturating_add_signed(relative_utf16_range.end),
12455 );
12456 start..end
12457 });
12458 s.select_ranges(new_ranges);
12459 });
12460 }
12461
12462 self.handle_input(text, cx);
12463 }
12464
12465 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12466 let Some(provider) = self.semantics_provider.as_ref() else {
12467 return false;
12468 };
12469
12470 let mut supports = false;
12471 self.buffer().read(cx).for_each_buffer(|buffer| {
12472 supports |= provider.supports_inlay_hints(buffer, cx);
12473 });
12474 supports
12475 }
12476
12477 pub fn focus(&self, cx: &mut WindowContext) {
12478 cx.focus(&self.focus_handle)
12479 }
12480
12481 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12482 self.focus_handle.is_focused(cx)
12483 }
12484
12485 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12486 cx.emit(EditorEvent::Focused);
12487
12488 if let Some(descendant) = self
12489 .last_focused_descendant
12490 .take()
12491 .and_then(|descendant| descendant.upgrade())
12492 {
12493 cx.focus(&descendant);
12494 } else {
12495 if let Some(blame) = self.blame.as_ref() {
12496 blame.update(cx, GitBlame::focus)
12497 }
12498
12499 self.blink_manager.update(cx, BlinkManager::enable);
12500 self.show_cursor_names(cx);
12501 self.buffer.update(cx, |buffer, cx| {
12502 buffer.finalize_last_transaction(cx);
12503 if self.leader_peer_id.is_none() {
12504 buffer.set_active_selections(
12505 &self.selections.disjoint_anchors(),
12506 self.selections.line_mode,
12507 self.cursor_shape,
12508 cx,
12509 );
12510 }
12511 });
12512 }
12513 }
12514
12515 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12516 cx.emit(EditorEvent::FocusedIn)
12517 }
12518
12519 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12520 if event.blurred != self.focus_handle {
12521 self.last_focused_descendant = Some(event.blurred);
12522 }
12523 }
12524
12525 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12526 self.blink_manager.update(cx, BlinkManager::disable);
12527 self.buffer
12528 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12529
12530 if let Some(blame) = self.blame.as_ref() {
12531 blame.update(cx, GitBlame::blur)
12532 }
12533 if !self.hover_state.focused(cx) {
12534 hide_hover(self, cx);
12535 }
12536
12537 self.hide_context_menu(cx);
12538 cx.emit(EditorEvent::Blurred);
12539 cx.notify();
12540 }
12541
12542 pub fn register_action<A: Action>(
12543 &mut self,
12544 listener: impl Fn(&A, &mut WindowContext) + 'static,
12545 ) -> Subscription {
12546 let id = self.next_editor_action_id.post_inc();
12547 let listener = Arc::new(listener);
12548 self.editor_actions.borrow_mut().insert(
12549 id,
12550 Box::new(move |cx| {
12551 let cx = cx.window_context();
12552 let listener = listener.clone();
12553 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12554 let action = action.downcast_ref().unwrap();
12555 if phase == DispatchPhase::Bubble {
12556 listener(action, cx)
12557 }
12558 })
12559 }),
12560 );
12561
12562 let editor_actions = self.editor_actions.clone();
12563 Subscription::new(move || {
12564 editor_actions.borrow_mut().remove(&id);
12565 })
12566 }
12567
12568 pub fn file_header_size(&self) -> u32 {
12569 FILE_HEADER_HEIGHT
12570 }
12571
12572 pub fn revert(
12573 &mut self,
12574 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12575 cx: &mut ViewContext<Self>,
12576 ) {
12577 self.buffer().update(cx, |multi_buffer, cx| {
12578 for (buffer_id, changes) in revert_changes {
12579 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12580 buffer.update(cx, |buffer, cx| {
12581 buffer.edit(
12582 changes.into_iter().map(|(range, text)| {
12583 (range, text.to_string().map(Arc::<str>::from))
12584 }),
12585 None,
12586 cx,
12587 );
12588 });
12589 }
12590 }
12591 });
12592 self.change_selections(None, cx, |selections| selections.refresh());
12593 }
12594
12595 pub fn to_pixel_point(
12596 &mut self,
12597 source: multi_buffer::Anchor,
12598 editor_snapshot: &EditorSnapshot,
12599 cx: &mut ViewContext<Self>,
12600 ) -> Option<gpui::Point<Pixels>> {
12601 let source_point = source.to_display_point(editor_snapshot);
12602 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12603 }
12604
12605 pub fn display_to_pixel_point(
12606 &self,
12607 source: DisplayPoint,
12608 editor_snapshot: &EditorSnapshot,
12609 cx: &WindowContext,
12610 ) -> Option<gpui::Point<Pixels>> {
12611 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12612 let text_layout_details = self.text_layout_details(cx);
12613 let scroll_top = text_layout_details
12614 .scroll_anchor
12615 .scroll_position(editor_snapshot)
12616 .y;
12617
12618 if source.row().as_f32() < scroll_top.floor() {
12619 return None;
12620 }
12621 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12622 let source_y = line_height * (source.row().as_f32() - scroll_top);
12623 Some(gpui::Point::new(source_x, source_y))
12624 }
12625
12626 pub fn has_active_completions_menu(&self) -> bool {
12627 self.context_menu.read().as_ref().map_or(false, |menu| {
12628 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
12629 })
12630 }
12631
12632 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12633 self.addons
12634 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12635 }
12636
12637 pub fn unregister_addon<T: Addon>(&mut self) {
12638 self.addons.remove(&std::any::TypeId::of::<T>());
12639 }
12640
12641 pub fn addon<T: Addon>(&self) -> Option<&T> {
12642 let type_id = std::any::TypeId::of::<T>();
12643 self.addons
12644 .get(&type_id)
12645 .and_then(|item| item.to_any().downcast_ref::<T>())
12646 }
12647
12648 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
12649 let text_layout_details = self.text_layout_details(cx);
12650 let style = &text_layout_details.editor_style;
12651 let font_id = cx.text_system().resolve_font(&style.text.font());
12652 let font_size = style.text.font_size.to_pixels(cx.rem_size());
12653 let line_height = style.text.line_height_in_pixels(cx.rem_size());
12654
12655 let em_width = cx
12656 .text_system()
12657 .typographic_bounds(font_id, font_size, 'm')
12658 .unwrap()
12659 .size
12660 .width;
12661
12662 gpui::Point::new(em_width, line_height)
12663 }
12664}
12665
12666fn get_unstaged_changes_for_buffers(
12667 project: &Model<Project>,
12668 buffers: impl IntoIterator<Item = Model<Buffer>>,
12669 cx: &mut ViewContext<Editor>,
12670) {
12671 let mut tasks = Vec::new();
12672 project.update(cx, |project, cx| {
12673 for buffer in buffers {
12674 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
12675 }
12676 });
12677 cx.spawn(|this, mut cx| async move {
12678 let change_sets = futures::future::join_all(tasks).await;
12679 this.update(&mut cx, |this, cx| {
12680 for change_set in change_sets {
12681 if let Some(change_set) = change_set.log_err() {
12682 this.diff_map.add_change_set(change_set, cx);
12683 }
12684 }
12685 })
12686 .ok();
12687 })
12688 .detach();
12689}
12690
12691fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
12692 let tab_size = tab_size.get() as usize;
12693 let mut width = offset;
12694
12695 for ch in text.chars() {
12696 width += if ch == '\t' {
12697 tab_size - (width % tab_size)
12698 } else {
12699 1
12700 };
12701 }
12702
12703 width - offset
12704}
12705
12706#[cfg(test)]
12707mod tests {
12708 use super::*;
12709
12710 #[test]
12711 fn test_string_size_with_expanded_tabs() {
12712 let nz = |val| NonZeroU32::new(val).unwrap();
12713 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
12714 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
12715 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
12716 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
12717 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
12718 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
12719 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
12720 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
12721 }
12722}
12723
12724/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
12725struct WordBreakingTokenizer<'a> {
12726 input: &'a str,
12727}
12728
12729impl<'a> WordBreakingTokenizer<'a> {
12730 fn new(input: &'a str) -> Self {
12731 Self { input }
12732 }
12733}
12734
12735fn is_char_ideographic(ch: char) -> bool {
12736 use unicode_script::Script::*;
12737 use unicode_script::UnicodeScript;
12738 matches!(ch.script(), Han | Tangut | Yi)
12739}
12740
12741fn is_grapheme_ideographic(text: &str) -> bool {
12742 text.chars().any(is_char_ideographic)
12743}
12744
12745fn is_grapheme_whitespace(text: &str) -> bool {
12746 text.chars().any(|x| x.is_whitespace())
12747}
12748
12749fn should_stay_with_preceding_ideograph(text: &str) -> bool {
12750 text.chars().next().map_or(false, |ch| {
12751 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
12752 })
12753}
12754
12755#[derive(PartialEq, Eq, Debug, Clone, Copy)]
12756struct WordBreakToken<'a> {
12757 token: &'a str,
12758 grapheme_len: usize,
12759 is_whitespace: bool,
12760}
12761
12762impl<'a> Iterator for WordBreakingTokenizer<'a> {
12763 /// Yields a span, the count of graphemes in the token, and whether it was
12764 /// whitespace. Note that it also breaks at word boundaries.
12765 type Item = WordBreakToken<'a>;
12766
12767 fn next(&mut self) -> Option<Self::Item> {
12768 use unicode_segmentation::UnicodeSegmentation;
12769 if self.input.is_empty() {
12770 return None;
12771 }
12772
12773 let mut iter = self.input.graphemes(true).peekable();
12774 let mut offset = 0;
12775 let mut graphemes = 0;
12776 if let Some(first_grapheme) = iter.next() {
12777 let is_whitespace = is_grapheme_whitespace(first_grapheme);
12778 offset += first_grapheme.len();
12779 graphemes += 1;
12780 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
12781 if let Some(grapheme) = iter.peek().copied() {
12782 if should_stay_with_preceding_ideograph(grapheme) {
12783 offset += grapheme.len();
12784 graphemes += 1;
12785 }
12786 }
12787 } else {
12788 let mut words = self.input[offset..].split_word_bound_indices().peekable();
12789 let mut next_word_bound = words.peek().copied();
12790 if next_word_bound.map_or(false, |(i, _)| i == 0) {
12791 next_word_bound = words.next();
12792 }
12793 while let Some(grapheme) = iter.peek().copied() {
12794 if next_word_bound.map_or(false, |(i, _)| i == offset) {
12795 break;
12796 };
12797 if is_grapheme_whitespace(grapheme) != is_whitespace {
12798 break;
12799 };
12800 offset += grapheme.len();
12801 graphemes += 1;
12802 iter.next();
12803 }
12804 }
12805 let token = &self.input[..offset];
12806 self.input = &self.input[offset..];
12807 if is_whitespace {
12808 Some(WordBreakToken {
12809 token: " ",
12810 grapheme_len: 1,
12811 is_whitespace: true,
12812 })
12813 } else {
12814 Some(WordBreakToken {
12815 token,
12816 grapheme_len: graphemes,
12817 is_whitespace: false,
12818 })
12819 }
12820 } else {
12821 None
12822 }
12823 }
12824}
12825
12826#[test]
12827fn test_word_breaking_tokenizer() {
12828 let tests: &[(&str, &[(&str, usize, bool)])] = &[
12829 ("", &[]),
12830 (" ", &[(" ", 1, true)]),
12831 ("Ʒ", &[("Ʒ", 1, false)]),
12832 ("Ǽ", &[("Ǽ", 1, false)]),
12833 ("⋑", &[("⋑", 1, false)]),
12834 ("⋑⋑", &[("⋑⋑", 2, false)]),
12835 (
12836 "原理,进而",
12837 &[
12838 ("原", 1, false),
12839 ("理,", 2, false),
12840 ("进", 1, false),
12841 ("而", 1, false),
12842 ],
12843 ),
12844 (
12845 "hello world",
12846 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
12847 ),
12848 (
12849 "hello, world",
12850 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
12851 ),
12852 (
12853 " hello world",
12854 &[
12855 (" ", 1, true),
12856 ("hello", 5, false),
12857 (" ", 1, true),
12858 ("world", 5, false),
12859 ],
12860 ),
12861 (
12862 "这是什么 \n 钢笔",
12863 &[
12864 ("这", 1, false),
12865 ("是", 1, false),
12866 ("什", 1, false),
12867 ("么", 1, false),
12868 (" ", 1, true),
12869 ("钢", 1, false),
12870 ("笔", 1, false),
12871 ],
12872 ),
12873 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
12874 ];
12875
12876 for (input, result) in tests {
12877 assert_eq!(
12878 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
12879 result
12880 .iter()
12881 .copied()
12882 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
12883 token,
12884 grapheme_len,
12885 is_whitespace,
12886 })
12887 .collect::<Vec<_>>()
12888 );
12889 }
12890}
12891
12892fn wrap_with_prefix(
12893 line_prefix: String,
12894 unwrapped_text: String,
12895 wrap_column: usize,
12896 tab_size: NonZeroU32,
12897) -> String {
12898 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
12899 let mut wrapped_text = String::new();
12900 let mut current_line = line_prefix.clone();
12901
12902 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
12903 let mut current_line_len = line_prefix_len;
12904 for WordBreakToken {
12905 token,
12906 grapheme_len,
12907 is_whitespace,
12908 } in tokenizer
12909 {
12910 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
12911 wrapped_text.push_str(current_line.trim_end());
12912 wrapped_text.push('\n');
12913 current_line.truncate(line_prefix.len());
12914 current_line_len = line_prefix_len;
12915 if !is_whitespace {
12916 current_line.push_str(token);
12917 current_line_len += grapheme_len;
12918 }
12919 } else if !is_whitespace {
12920 current_line.push_str(token);
12921 current_line_len += grapheme_len;
12922 } else if current_line_len != line_prefix_len {
12923 current_line.push(' ');
12924 current_line_len += 1;
12925 }
12926 }
12927
12928 if !current_line.is_empty() {
12929 wrapped_text.push_str(¤t_line);
12930 }
12931 wrapped_text
12932}
12933
12934#[test]
12935fn test_wrap_with_prefix() {
12936 assert_eq!(
12937 wrap_with_prefix(
12938 "# ".to_string(),
12939 "abcdefg".to_string(),
12940 4,
12941 NonZeroU32::new(4).unwrap()
12942 ),
12943 "# abcdefg"
12944 );
12945 assert_eq!(
12946 wrap_with_prefix(
12947 "".to_string(),
12948 "\thello world".to_string(),
12949 8,
12950 NonZeroU32::new(4).unwrap()
12951 ),
12952 "hello\nworld"
12953 );
12954 assert_eq!(
12955 wrap_with_prefix(
12956 "// ".to_string(),
12957 "xx \nyy zz aa bb cc".to_string(),
12958 12,
12959 NonZeroU32::new(4).unwrap()
12960 ),
12961 "// xx yy zz\n// aa bb cc"
12962 );
12963 assert_eq!(
12964 wrap_with_prefix(
12965 String::new(),
12966 "这是什么 \n 钢笔".to_string(),
12967 3,
12968 NonZeroU32::new(4).unwrap()
12969 ),
12970 "这是什\n么 钢\n笔"
12971 );
12972}
12973
12974fn hunks_for_selections(
12975 snapshot: &EditorSnapshot,
12976 selections: &[Selection<Point>],
12977) -> Vec<MultiBufferDiffHunk> {
12978 hunks_for_ranges(
12979 selections.iter().map(|selection| selection.range()),
12980 snapshot,
12981 )
12982}
12983
12984pub fn hunks_for_ranges(
12985 ranges: impl Iterator<Item = Range<Point>>,
12986 snapshot: &EditorSnapshot,
12987) -> Vec<MultiBufferDiffHunk> {
12988 let mut hunks = Vec::new();
12989 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12990 HashMap::default();
12991 for query_range in ranges {
12992 let query_rows =
12993 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
12994 for hunk in snapshot.diff_map.diff_hunks_in_range(
12995 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
12996 &snapshot.buffer_snapshot,
12997 ) {
12998 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12999 // when the caret is just above or just below the deleted hunk.
13000 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13001 let related_to_selection = if allow_adjacent {
13002 hunk.row_range.overlaps(&query_rows)
13003 || hunk.row_range.start == query_rows.end
13004 || hunk.row_range.end == query_rows.start
13005 } else {
13006 hunk.row_range.overlaps(&query_rows)
13007 };
13008 if related_to_selection {
13009 if !processed_buffer_rows
13010 .entry(hunk.buffer_id)
13011 .or_default()
13012 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13013 {
13014 continue;
13015 }
13016 hunks.push(hunk);
13017 }
13018 }
13019 }
13020
13021 hunks
13022}
13023
13024pub trait CollaborationHub {
13025 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13026 fn user_participant_indices<'a>(
13027 &self,
13028 cx: &'a AppContext,
13029 ) -> &'a HashMap<u64, ParticipantIndex>;
13030 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13031}
13032
13033impl CollaborationHub for Model<Project> {
13034 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13035 self.read(cx).collaborators()
13036 }
13037
13038 fn user_participant_indices<'a>(
13039 &self,
13040 cx: &'a AppContext,
13041 ) -> &'a HashMap<u64, ParticipantIndex> {
13042 self.read(cx).user_store().read(cx).participant_indices()
13043 }
13044
13045 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13046 let this = self.read(cx);
13047 let user_ids = this.collaborators().values().map(|c| c.user_id);
13048 this.user_store().read_with(cx, |user_store, cx| {
13049 user_store.participant_names(user_ids, cx)
13050 })
13051 }
13052}
13053
13054pub trait SemanticsProvider {
13055 fn hover(
13056 &self,
13057 buffer: &Model<Buffer>,
13058 position: text::Anchor,
13059 cx: &mut AppContext,
13060 ) -> Option<Task<Vec<project::Hover>>>;
13061
13062 fn inlay_hints(
13063 &self,
13064 buffer_handle: Model<Buffer>,
13065 range: Range<text::Anchor>,
13066 cx: &mut AppContext,
13067 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13068
13069 fn resolve_inlay_hint(
13070 &self,
13071 hint: InlayHint,
13072 buffer_handle: Model<Buffer>,
13073 server_id: LanguageServerId,
13074 cx: &mut AppContext,
13075 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13076
13077 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13078
13079 fn document_highlights(
13080 &self,
13081 buffer: &Model<Buffer>,
13082 position: text::Anchor,
13083 cx: &mut AppContext,
13084 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13085
13086 fn definitions(
13087 &self,
13088 buffer: &Model<Buffer>,
13089 position: text::Anchor,
13090 kind: GotoDefinitionKind,
13091 cx: &mut AppContext,
13092 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13093
13094 fn range_for_rename(
13095 &self,
13096 buffer: &Model<Buffer>,
13097 position: text::Anchor,
13098 cx: &mut AppContext,
13099 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13100
13101 fn perform_rename(
13102 &self,
13103 buffer: &Model<Buffer>,
13104 position: text::Anchor,
13105 new_name: String,
13106 cx: &mut AppContext,
13107 ) -> Option<Task<Result<ProjectTransaction>>>;
13108}
13109
13110pub trait CompletionProvider {
13111 fn completions(
13112 &self,
13113 buffer: &Model<Buffer>,
13114 buffer_position: text::Anchor,
13115 trigger: CompletionContext,
13116 cx: &mut ViewContext<Editor>,
13117 ) -> Task<Result<Vec<Completion>>>;
13118
13119 fn resolve_completions(
13120 &self,
13121 buffer: Model<Buffer>,
13122 completion_indices: Vec<usize>,
13123 completions: Arc<RwLock<Box<[Completion]>>>,
13124 cx: &mut ViewContext<Editor>,
13125 ) -> Task<Result<bool>>;
13126
13127 fn apply_additional_edits_for_completion(
13128 &self,
13129 buffer: Model<Buffer>,
13130 completion: Completion,
13131 push_to_history: bool,
13132 cx: &mut ViewContext<Editor>,
13133 ) -> Task<Result<Option<language::Transaction>>>;
13134
13135 fn is_completion_trigger(
13136 &self,
13137 buffer: &Model<Buffer>,
13138 position: language::Anchor,
13139 text: &str,
13140 trigger_in_words: bool,
13141 cx: &mut ViewContext<Editor>,
13142 ) -> bool;
13143
13144 fn sort_completions(&self) -> bool {
13145 true
13146 }
13147}
13148
13149pub trait CodeActionProvider {
13150 fn code_actions(
13151 &self,
13152 buffer: &Model<Buffer>,
13153 range: Range<text::Anchor>,
13154 cx: &mut WindowContext,
13155 ) -> Task<Result<Vec<CodeAction>>>;
13156
13157 fn apply_code_action(
13158 &self,
13159 buffer_handle: Model<Buffer>,
13160 action: CodeAction,
13161 excerpt_id: ExcerptId,
13162 push_to_history: bool,
13163 cx: &mut WindowContext,
13164 ) -> Task<Result<ProjectTransaction>>;
13165}
13166
13167impl CodeActionProvider for Model<Project> {
13168 fn code_actions(
13169 &self,
13170 buffer: &Model<Buffer>,
13171 range: Range<text::Anchor>,
13172 cx: &mut WindowContext,
13173 ) -> Task<Result<Vec<CodeAction>>> {
13174 self.update(cx, |project, cx| {
13175 project.code_actions(buffer, range, None, cx)
13176 })
13177 }
13178
13179 fn apply_code_action(
13180 &self,
13181 buffer_handle: Model<Buffer>,
13182 action: CodeAction,
13183 _excerpt_id: ExcerptId,
13184 push_to_history: bool,
13185 cx: &mut WindowContext,
13186 ) -> Task<Result<ProjectTransaction>> {
13187 self.update(cx, |project, cx| {
13188 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13189 })
13190 }
13191}
13192
13193fn snippet_completions(
13194 project: &Project,
13195 buffer: &Model<Buffer>,
13196 buffer_position: text::Anchor,
13197 cx: &mut AppContext,
13198) -> Task<Result<Vec<Completion>>> {
13199 let language = buffer.read(cx).language_at(buffer_position);
13200 let language_name = language.as_ref().map(|language| language.lsp_id());
13201 let snippet_store = project.snippets().read(cx);
13202 let snippets = snippet_store.snippets_for(language_name, cx);
13203
13204 if snippets.is_empty() {
13205 return Task::ready(Ok(vec![]));
13206 }
13207 let snapshot = buffer.read(cx).text_snapshot();
13208 let chars: String = snapshot
13209 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13210 .collect();
13211
13212 let scope = language.map(|language| language.default_scope());
13213 let executor = cx.background_executor().clone();
13214
13215 cx.background_executor().spawn(async move {
13216 let classifier = CharClassifier::new(scope).for_completion(true);
13217 let mut last_word = chars
13218 .chars()
13219 .take_while(|c| classifier.is_word(*c))
13220 .collect::<String>();
13221 last_word = last_word.chars().rev().collect();
13222
13223 if last_word.is_empty() {
13224 return Ok(vec![]);
13225 }
13226
13227 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13228 let to_lsp = |point: &text::Anchor| {
13229 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13230 point_to_lsp(end)
13231 };
13232 let lsp_end = to_lsp(&buffer_position);
13233
13234 let candidates = snippets
13235 .iter()
13236 .enumerate()
13237 .flat_map(|(ix, snippet)| {
13238 snippet
13239 .prefix
13240 .iter()
13241 .map(move |prefix| StringMatchCandidate::new(ix, prefix.clone()))
13242 })
13243 .collect::<Vec<StringMatchCandidate>>();
13244
13245 let mut matches = fuzzy::match_strings(
13246 &candidates,
13247 &last_word,
13248 last_word.chars().any(|c| c.is_uppercase()),
13249 100,
13250 &Default::default(),
13251 executor,
13252 )
13253 .await;
13254
13255 // Remove all candidates where the query's start does not match the start of any word in the candidate
13256 if let Some(query_start) = last_word.chars().next() {
13257 matches.retain(|string_match| {
13258 split_words(&string_match.string).any(|word| {
13259 // Check that the first codepoint of the word as lowercase matches the first
13260 // codepoint of the query as lowercase
13261 word.chars()
13262 .flat_map(|codepoint| codepoint.to_lowercase())
13263 .zip(query_start.to_lowercase())
13264 .all(|(word_cp, query_cp)| word_cp == query_cp)
13265 })
13266 });
13267 }
13268
13269 let matched_strings = matches
13270 .into_iter()
13271 .map(|m| m.string)
13272 .collect::<HashSet<_>>();
13273
13274 let result: Vec<Completion> = snippets
13275 .into_iter()
13276 .filter_map(|snippet| {
13277 let matching_prefix = snippet
13278 .prefix
13279 .iter()
13280 .find(|prefix| matched_strings.contains(*prefix))?;
13281 let start = as_offset - last_word.len();
13282 let start = snapshot.anchor_before(start);
13283 let range = start..buffer_position;
13284 let lsp_start = to_lsp(&start);
13285 let lsp_range = lsp::Range {
13286 start: lsp_start,
13287 end: lsp_end,
13288 };
13289 Some(Completion {
13290 old_range: range,
13291 new_text: snippet.body.clone(),
13292 label: CodeLabel {
13293 text: matching_prefix.clone(),
13294 runs: vec![],
13295 filter_range: 0..matching_prefix.len(),
13296 },
13297 server_id: LanguageServerId(usize::MAX),
13298 documentation: snippet.description.clone().map(Documentation::SingleLine),
13299 lsp_completion: lsp::CompletionItem {
13300 label: snippet.prefix.first().unwrap().clone(),
13301 kind: Some(CompletionItemKind::SNIPPET),
13302 label_details: snippet.description.as_ref().map(|description| {
13303 lsp::CompletionItemLabelDetails {
13304 detail: Some(description.clone()),
13305 description: None,
13306 }
13307 }),
13308 insert_text_format: Some(InsertTextFormat::SNIPPET),
13309 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13310 lsp::InsertReplaceEdit {
13311 new_text: snippet.body.clone(),
13312 insert: lsp_range,
13313 replace: lsp_range,
13314 },
13315 )),
13316 filter_text: Some(snippet.body.clone()),
13317 sort_text: Some(char::MAX.to_string()),
13318 ..Default::default()
13319 },
13320 confirm: None,
13321 })
13322 })
13323 .collect();
13324
13325 Ok(result)
13326 })
13327}
13328
13329impl CompletionProvider for Model<Project> {
13330 fn completions(
13331 &self,
13332 buffer: &Model<Buffer>,
13333 buffer_position: text::Anchor,
13334 options: CompletionContext,
13335 cx: &mut ViewContext<Editor>,
13336 ) -> Task<Result<Vec<Completion>>> {
13337 self.update(cx, |project, cx| {
13338 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13339 let project_completions = project.completions(buffer, buffer_position, options, cx);
13340 cx.background_executor().spawn(async move {
13341 let mut completions = project_completions.await?;
13342 let snippets_completions = snippets.await?;
13343 completions.extend(snippets_completions);
13344 Ok(completions)
13345 })
13346 })
13347 }
13348
13349 fn resolve_completions(
13350 &self,
13351 buffer: Model<Buffer>,
13352 completion_indices: Vec<usize>,
13353 completions: Arc<RwLock<Box<[Completion]>>>,
13354 cx: &mut ViewContext<Editor>,
13355 ) -> Task<Result<bool>> {
13356 self.update(cx, |project, cx| {
13357 project.resolve_completions(buffer, completion_indices, completions, cx)
13358 })
13359 }
13360
13361 fn apply_additional_edits_for_completion(
13362 &self,
13363 buffer: Model<Buffer>,
13364 completion: Completion,
13365 push_to_history: bool,
13366 cx: &mut ViewContext<Editor>,
13367 ) -> Task<Result<Option<language::Transaction>>> {
13368 self.update(cx, |project, cx| {
13369 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13370 })
13371 }
13372
13373 fn is_completion_trigger(
13374 &self,
13375 buffer: &Model<Buffer>,
13376 position: language::Anchor,
13377 text: &str,
13378 trigger_in_words: bool,
13379 cx: &mut ViewContext<Editor>,
13380 ) -> bool {
13381 let mut chars = text.chars();
13382 let char = if let Some(char) = chars.next() {
13383 char
13384 } else {
13385 return false;
13386 };
13387 if chars.next().is_some() {
13388 return false;
13389 }
13390
13391 let buffer = buffer.read(cx);
13392 let snapshot = buffer.snapshot();
13393 if !snapshot.settings_at(position, cx).show_completions_on_input {
13394 return false;
13395 }
13396 let classifier = snapshot.char_classifier_at(position).for_completion(true);
13397 if trigger_in_words && classifier.is_word(char) {
13398 return true;
13399 }
13400
13401 buffer.completion_triggers().contains(text)
13402 }
13403}
13404
13405impl SemanticsProvider for Model<Project> {
13406 fn hover(
13407 &self,
13408 buffer: &Model<Buffer>,
13409 position: text::Anchor,
13410 cx: &mut AppContext,
13411 ) -> Option<Task<Vec<project::Hover>>> {
13412 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13413 }
13414
13415 fn document_highlights(
13416 &self,
13417 buffer: &Model<Buffer>,
13418 position: text::Anchor,
13419 cx: &mut AppContext,
13420 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13421 Some(self.update(cx, |project, cx| {
13422 project.document_highlights(buffer, position, cx)
13423 }))
13424 }
13425
13426 fn definitions(
13427 &self,
13428 buffer: &Model<Buffer>,
13429 position: text::Anchor,
13430 kind: GotoDefinitionKind,
13431 cx: &mut AppContext,
13432 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13433 Some(self.update(cx, |project, cx| match kind {
13434 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13435 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13436 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13437 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13438 }))
13439 }
13440
13441 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13442 // TODO: make this work for remote projects
13443 self.read(cx)
13444 .language_servers_for_local_buffer(buffer.read(cx), cx)
13445 .any(
13446 |(_, server)| match server.capabilities().inlay_hint_provider {
13447 Some(lsp::OneOf::Left(enabled)) => enabled,
13448 Some(lsp::OneOf::Right(_)) => true,
13449 None => false,
13450 },
13451 )
13452 }
13453
13454 fn inlay_hints(
13455 &self,
13456 buffer_handle: Model<Buffer>,
13457 range: Range<text::Anchor>,
13458 cx: &mut AppContext,
13459 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13460 Some(self.update(cx, |project, cx| {
13461 project.inlay_hints(buffer_handle, range, cx)
13462 }))
13463 }
13464
13465 fn resolve_inlay_hint(
13466 &self,
13467 hint: InlayHint,
13468 buffer_handle: Model<Buffer>,
13469 server_id: LanguageServerId,
13470 cx: &mut AppContext,
13471 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13472 Some(self.update(cx, |project, cx| {
13473 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13474 }))
13475 }
13476
13477 fn range_for_rename(
13478 &self,
13479 buffer: &Model<Buffer>,
13480 position: text::Anchor,
13481 cx: &mut AppContext,
13482 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13483 Some(self.update(cx, |project, cx| {
13484 project.prepare_rename(buffer.clone(), position, cx)
13485 }))
13486 }
13487
13488 fn perform_rename(
13489 &self,
13490 buffer: &Model<Buffer>,
13491 position: text::Anchor,
13492 new_name: String,
13493 cx: &mut AppContext,
13494 ) -> Option<Task<Result<ProjectTransaction>>> {
13495 Some(self.update(cx, |project, cx| {
13496 project.perform_rename(buffer.clone(), position, new_name, cx)
13497 }))
13498 }
13499}
13500
13501fn inlay_hint_settings(
13502 location: Anchor,
13503 snapshot: &MultiBufferSnapshot,
13504 cx: &mut ViewContext<'_, Editor>,
13505) -> InlayHintSettings {
13506 let file = snapshot.file_at(location);
13507 let language = snapshot.language_at(location).map(|l| l.name());
13508 language_settings(language, file, cx).inlay_hints
13509}
13510
13511fn consume_contiguous_rows(
13512 contiguous_row_selections: &mut Vec<Selection<Point>>,
13513 selection: &Selection<Point>,
13514 display_map: &DisplaySnapshot,
13515 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13516) -> (MultiBufferRow, MultiBufferRow) {
13517 contiguous_row_selections.push(selection.clone());
13518 let start_row = MultiBufferRow(selection.start.row);
13519 let mut end_row = ending_row(selection, display_map);
13520
13521 while let Some(next_selection) = selections.peek() {
13522 if next_selection.start.row <= end_row.0 {
13523 end_row = ending_row(next_selection, display_map);
13524 contiguous_row_selections.push(selections.next().unwrap().clone());
13525 } else {
13526 break;
13527 }
13528 }
13529 (start_row, end_row)
13530}
13531
13532fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13533 if next_selection.end.column > 0 || next_selection.is_empty() {
13534 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13535 } else {
13536 MultiBufferRow(next_selection.end.row)
13537 }
13538}
13539
13540impl EditorSnapshot {
13541 pub fn remote_selections_in_range<'a>(
13542 &'a self,
13543 range: &'a Range<Anchor>,
13544 collaboration_hub: &dyn CollaborationHub,
13545 cx: &'a AppContext,
13546 ) -> impl 'a + Iterator<Item = RemoteSelection> {
13547 let participant_names = collaboration_hub.user_names(cx);
13548 let participant_indices = collaboration_hub.user_participant_indices(cx);
13549 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13550 let collaborators_by_replica_id = collaborators_by_peer_id
13551 .iter()
13552 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13553 .collect::<HashMap<_, _>>();
13554 self.buffer_snapshot
13555 .selections_in_range(range, false)
13556 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13557 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13558 let participant_index = participant_indices.get(&collaborator.user_id).copied();
13559 let user_name = participant_names.get(&collaborator.user_id).cloned();
13560 Some(RemoteSelection {
13561 replica_id,
13562 selection,
13563 cursor_shape,
13564 line_mode,
13565 participant_index,
13566 peer_id: collaborator.peer_id,
13567 user_name,
13568 })
13569 })
13570 }
13571
13572 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13573 self.display_snapshot.buffer_snapshot.language_at(position)
13574 }
13575
13576 pub fn is_focused(&self) -> bool {
13577 self.is_focused
13578 }
13579
13580 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13581 self.placeholder_text.as_ref()
13582 }
13583
13584 pub fn scroll_position(&self) -> gpui::Point<f32> {
13585 self.scroll_anchor.scroll_position(&self.display_snapshot)
13586 }
13587
13588 fn gutter_dimensions(
13589 &self,
13590 font_id: FontId,
13591 font_size: Pixels,
13592 em_width: Pixels,
13593 em_advance: Pixels,
13594 max_line_number_width: Pixels,
13595 cx: &AppContext,
13596 ) -> GutterDimensions {
13597 if !self.show_gutter {
13598 return GutterDimensions::default();
13599 }
13600 let descent = cx.text_system().descent(font_id, font_size);
13601
13602 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13603 matches!(
13604 ProjectSettings::get_global(cx).git.git_gutter,
13605 Some(GitGutterSetting::TrackedFiles)
13606 )
13607 });
13608 let gutter_settings = EditorSettings::get_global(cx).gutter;
13609 let show_line_numbers = self
13610 .show_line_numbers
13611 .unwrap_or(gutter_settings.line_numbers);
13612 let line_gutter_width = if show_line_numbers {
13613 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13614 let min_width_for_number_on_gutter = em_advance * 4.0;
13615 max_line_number_width.max(min_width_for_number_on_gutter)
13616 } else {
13617 0.0.into()
13618 };
13619
13620 let show_code_actions = self
13621 .show_code_actions
13622 .unwrap_or(gutter_settings.code_actions);
13623
13624 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13625
13626 let git_blame_entries_width =
13627 self.git_blame_gutter_max_author_length
13628 .map(|max_author_length| {
13629 // Length of the author name, but also space for the commit hash,
13630 // the spacing and the timestamp.
13631 let max_char_count = max_author_length
13632 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13633 + 7 // length of commit sha
13634 + 14 // length of max relative timestamp ("60 minutes ago")
13635 + 4; // gaps and margins
13636
13637 em_advance * max_char_count
13638 });
13639
13640 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13641 left_padding += if show_code_actions || show_runnables {
13642 em_width * 3.0
13643 } else if show_git_gutter && show_line_numbers {
13644 em_width * 2.0
13645 } else if show_git_gutter || show_line_numbers {
13646 em_width
13647 } else {
13648 px(0.)
13649 };
13650
13651 let right_padding = if gutter_settings.folds && show_line_numbers {
13652 em_width * 4.0
13653 } else if gutter_settings.folds {
13654 em_width * 3.0
13655 } else if show_line_numbers {
13656 em_width
13657 } else {
13658 px(0.)
13659 };
13660
13661 GutterDimensions {
13662 left_padding,
13663 right_padding,
13664 width: line_gutter_width + left_padding + right_padding,
13665 margin: -descent,
13666 git_blame_entries_width,
13667 }
13668 }
13669
13670 pub fn render_crease_toggle(
13671 &self,
13672 buffer_row: MultiBufferRow,
13673 row_contains_cursor: bool,
13674 editor: View<Editor>,
13675 cx: &mut WindowContext,
13676 ) -> Option<AnyElement> {
13677 let folded = self.is_line_folded(buffer_row);
13678 let mut is_foldable = false;
13679
13680 if let Some(crease) = self
13681 .crease_snapshot
13682 .query_row(buffer_row, &self.buffer_snapshot)
13683 {
13684 is_foldable = true;
13685 match crease {
13686 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
13687 if let Some(render_toggle) = render_toggle {
13688 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13689 if folded {
13690 editor.update(cx, |editor, cx| {
13691 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13692 });
13693 } else {
13694 editor.update(cx, |editor, cx| {
13695 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13696 });
13697 }
13698 });
13699 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
13700 }
13701 }
13702 }
13703 }
13704
13705 is_foldable |= self.starts_indent(buffer_row);
13706
13707 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
13708 Some(
13709 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
13710 .selected(folded)
13711 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13712 if folded {
13713 this.unfold_at(&UnfoldAt { buffer_row }, cx);
13714 } else {
13715 this.fold_at(&FoldAt { buffer_row }, cx);
13716 }
13717 }))
13718 .into_any_element(),
13719 )
13720 } else {
13721 None
13722 }
13723 }
13724
13725 pub fn render_crease_trailer(
13726 &self,
13727 buffer_row: MultiBufferRow,
13728 cx: &mut WindowContext,
13729 ) -> Option<AnyElement> {
13730 let folded = self.is_line_folded(buffer_row);
13731 if let Crease::Inline { render_trailer, .. } = self
13732 .crease_snapshot
13733 .query_row(buffer_row, &self.buffer_snapshot)?
13734 {
13735 let render_trailer = render_trailer.as_ref()?;
13736 Some(render_trailer(buffer_row, folded, cx))
13737 } else {
13738 None
13739 }
13740 }
13741}
13742
13743impl Deref for EditorSnapshot {
13744 type Target = DisplaySnapshot;
13745
13746 fn deref(&self) -> &Self::Target {
13747 &self.display_snapshot
13748 }
13749}
13750
13751#[derive(Clone, Debug, PartialEq, Eq)]
13752pub enum EditorEvent {
13753 InputIgnored {
13754 text: Arc<str>,
13755 },
13756 InputHandled {
13757 utf16_range_to_replace: Option<Range<isize>>,
13758 text: Arc<str>,
13759 },
13760 ExcerptsAdded {
13761 buffer: Model<Buffer>,
13762 predecessor: ExcerptId,
13763 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13764 },
13765 ExcerptsRemoved {
13766 ids: Vec<ExcerptId>,
13767 },
13768 ExcerptsEdited {
13769 ids: Vec<ExcerptId>,
13770 },
13771 ExcerptsExpanded {
13772 ids: Vec<ExcerptId>,
13773 },
13774 BufferEdited,
13775 Edited {
13776 transaction_id: clock::Lamport,
13777 },
13778 Reparsed(BufferId),
13779 Focused,
13780 FocusedIn,
13781 Blurred,
13782 DirtyChanged,
13783 Saved,
13784 TitleChanged,
13785 DiffBaseChanged,
13786 SelectionsChanged {
13787 local: bool,
13788 },
13789 ScrollPositionChanged {
13790 local: bool,
13791 autoscroll: bool,
13792 },
13793 Closed,
13794 TransactionUndone {
13795 transaction_id: clock::Lamport,
13796 },
13797 TransactionBegun {
13798 transaction_id: clock::Lamport,
13799 },
13800 Reloaded,
13801 CursorShapeChanged,
13802}
13803
13804impl EventEmitter<EditorEvent> for Editor {}
13805
13806impl FocusableView for Editor {
13807 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13808 self.focus_handle.clone()
13809 }
13810}
13811
13812impl Render for Editor {
13813 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13814 let settings = ThemeSettings::get_global(cx);
13815
13816 let mut text_style = match self.mode {
13817 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13818 color: cx.theme().colors().editor_foreground,
13819 font_family: settings.ui_font.family.clone(),
13820 font_features: settings.ui_font.features.clone(),
13821 font_fallbacks: settings.ui_font.fallbacks.clone(),
13822 font_size: rems(0.875).into(),
13823 font_weight: settings.ui_font.weight,
13824 line_height: relative(settings.buffer_line_height.value()),
13825 ..Default::default()
13826 },
13827 EditorMode::Full => TextStyle {
13828 color: cx.theme().colors().editor_foreground,
13829 font_family: settings.buffer_font.family.clone(),
13830 font_features: settings.buffer_font.features.clone(),
13831 font_fallbacks: settings.buffer_font.fallbacks.clone(),
13832 font_size: settings.buffer_font_size(cx).into(),
13833 font_weight: settings.buffer_font.weight,
13834 line_height: relative(settings.buffer_line_height.value()),
13835 ..Default::default()
13836 },
13837 };
13838 if let Some(text_style_refinement) = &self.text_style_refinement {
13839 text_style.refine(text_style_refinement)
13840 }
13841
13842 let background = match self.mode {
13843 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13844 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13845 EditorMode::Full => cx.theme().colors().editor_background,
13846 };
13847
13848 EditorElement::new(
13849 cx.view(),
13850 EditorStyle {
13851 background,
13852 local_player: cx.theme().players().local(),
13853 text: text_style,
13854 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13855 syntax: cx.theme().syntax().clone(),
13856 status: cx.theme().status().clone(),
13857 inlay_hints_style: make_inlay_hints_style(cx),
13858 suggestions_style: HighlightStyle {
13859 color: Some(cx.theme().status().predictive),
13860 ..HighlightStyle::default()
13861 },
13862 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13863 },
13864 )
13865 }
13866}
13867
13868impl ViewInputHandler for Editor {
13869 fn text_for_range(
13870 &mut self,
13871 range_utf16: Range<usize>,
13872 adjusted_range: &mut Option<Range<usize>>,
13873 cx: &mut ViewContext<Self>,
13874 ) -> Option<String> {
13875 let snapshot = self.buffer.read(cx).read(cx);
13876 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
13877 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
13878 if (start.0..end.0) != range_utf16 {
13879 adjusted_range.replace(start.0..end.0);
13880 }
13881 Some(snapshot.text_for_range(start..end).collect())
13882 }
13883
13884 fn selected_text_range(
13885 &mut self,
13886 ignore_disabled_input: bool,
13887 cx: &mut ViewContext<Self>,
13888 ) -> Option<UTF16Selection> {
13889 // Prevent the IME menu from appearing when holding down an alphabetic key
13890 // while input is disabled.
13891 if !ignore_disabled_input && !self.input_enabled {
13892 return None;
13893 }
13894
13895 let selection = self.selections.newest::<OffsetUtf16>(cx);
13896 let range = selection.range();
13897
13898 Some(UTF16Selection {
13899 range: range.start.0..range.end.0,
13900 reversed: selection.reversed,
13901 })
13902 }
13903
13904 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13905 let snapshot = self.buffer.read(cx).read(cx);
13906 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13907 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13908 }
13909
13910 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13911 self.clear_highlights::<InputComposition>(cx);
13912 self.ime_transaction.take();
13913 }
13914
13915 fn replace_text_in_range(
13916 &mut self,
13917 range_utf16: Option<Range<usize>>,
13918 text: &str,
13919 cx: &mut ViewContext<Self>,
13920 ) {
13921 if !self.input_enabled {
13922 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13923 return;
13924 }
13925
13926 self.transact(cx, |this, cx| {
13927 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13928 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13929 Some(this.selection_replacement_ranges(range_utf16, cx))
13930 } else {
13931 this.marked_text_ranges(cx)
13932 };
13933
13934 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13935 let newest_selection_id = this.selections.newest_anchor().id;
13936 this.selections
13937 .all::<OffsetUtf16>(cx)
13938 .iter()
13939 .zip(ranges_to_replace.iter())
13940 .find_map(|(selection, range)| {
13941 if selection.id == newest_selection_id {
13942 Some(
13943 (range.start.0 as isize - selection.head().0 as isize)
13944 ..(range.end.0 as isize - selection.head().0 as isize),
13945 )
13946 } else {
13947 None
13948 }
13949 })
13950 });
13951
13952 cx.emit(EditorEvent::InputHandled {
13953 utf16_range_to_replace: range_to_replace,
13954 text: text.into(),
13955 });
13956
13957 if let Some(new_selected_ranges) = new_selected_ranges {
13958 this.change_selections(None, cx, |selections| {
13959 selections.select_ranges(new_selected_ranges)
13960 });
13961 this.backspace(&Default::default(), cx);
13962 }
13963
13964 this.handle_input(text, cx);
13965 });
13966
13967 if let Some(transaction) = self.ime_transaction {
13968 self.buffer.update(cx, |buffer, cx| {
13969 buffer.group_until_transaction(transaction, cx);
13970 });
13971 }
13972
13973 self.unmark_text(cx);
13974 }
13975
13976 fn replace_and_mark_text_in_range(
13977 &mut self,
13978 range_utf16: Option<Range<usize>>,
13979 text: &str,
13980 new_selected_range_utf16: Option<Range<usize>>,
13981 cx: &mut ViewContext<Self>,
13982 ) {
13983 if !self.input_enabled {
13984 return;
13985 }
13986
13987 let transaction = self.transact(cx, |this, cx| {
13988 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13989 let snapshot = this.buffer.read(cx).read(cx);
13990 if let Some(relative_range_utf16) = range_utf16.as_ref() {
13991 for marked_range in &mut marked_ranges {
13992 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13993 marked_range.start.0 += relative_range_utf16.start;
13994 marked_range.start =
13995 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13996 marked_range.end =
13997 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13998 }
13999 }
14000 Some(marked_ranges)
14001 } else if let Some(range_utf16) = range_utf16 {
14002 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14003 Some(this.selection_replacement_ranges(range_utf16, cx))
14004 } else {
14005 None
14006 };
14007
14008 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14009 let newest_selection_id = this.selections.newest_anchor().id;
14010 this.selections
14011 .all::<OffsetUtf16>(cx)
14012 .iter()
14013 .zip(ranges_to_replace.iter())
14014 .find_map(|(selection, range)| {
14015 if selection.id == newest_selection_id {
14016 Some(
14017 (range.start.0 as isize - selection.head().0 as isize)
14018 ..(range.end.0 as isize - selection.head().0 as isize),
14019 )
14020 } else {
14021 None
14022 }
14023 })
14024 });
14025
14026 cx.emit(EditorEvent::InputHandled {
14027 utf16_range_to_replace: range_to_replace,
14028 text: text.into(),
14029 });
14030
14031 if let Some(ranges) = ranges_to_replace {
14032 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14033 }
14034
14035 let marked_ranges = {
14036 let snapshot = this.buffer.read(cx).read(cx);
14037 this.selections
14038 .disjoint_anchors()
14039 .iter()
14040 .map(|selection| {
14041 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14042 })
14043 .collect::<Vec<_>>()
14044 };
14045
14046 if text.is_empty() {
14047 this.unmark_text(cx);
14048 } else {
14049 this.highlight_text::<InputComposition>(
14050 marked_ranges.clone(),
14051 HighlightStyle {
14052 underline: Some(UnderlineStyle {
14053 thickness: px(1.),
14054 color: None,
14055 wavy: false,
14056 }),
14057 ..Default::default()
14058 },
14059 cx,
14060 );
14061 }
14062
14063 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14064 let use_autoclose = this.use_autoclose;
14065 let use_auto_surround = this.use_auto_surround;
14066 this.set_use_autoclose(false);
14067 this.set_use_auto_surround(false);
14068 this.handle_input(text, cx);
14069 this.set_use_autoclose(use_autoclose);
14070 this.set_use_auto_surround(use_auto_surround);
14071
14072 if let Some(new_selected_range) = new_selected_range_utf16 {
14073 let snapshot = this.buffer.read(cx).read(cx);
14074 let new_selected_ranges = marked_ranges
14075 .into_iter()
14076 .map(|marked_range| {
14077 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14078 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14079 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14080 snapshot.clip_offset_utf16(new_start, Bias::Left)
14081 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14082 })
14083 .collect::<Vec<_>>();
14084
14085 drop(snapshot);
14086 this.change_selections(None, cx, |selections| {
14087 selections.select_ranges(new_selected_ranges)
14088 });
14089 }
14090 });
14091
14092 self.ime_transaction = self.ime_transaction.or(transaction);
14093 if let Some(transaction) = self.ime_transaction {
14094 self.buffer.update(cx, |buffer, cx| {
14095 buffer.group_until_transaction(transaction, cx);
14096 });
14097 }
14098
14099 if self.text_highlights::<InputComposition>(cx).is_none() {
14100 self.ime_transaction.take();
14101 }
14102 }
14103
14104 fn bounds_for_range(
14105 &mut self,
14106 range_utf16: Range<usize>,
14107 element_bounds: gpui::Bounds<Pixels>,
14108 cx: &mut ViewContext<Self>,
14109 ) -> Option<gpui::Bounds<Pixels>> {
14110 let text_layout_details = self.text_layout_details(cx);
14111 let gpui::Point {
14112 x: em_width,
14113 y: line_height,
14114 } = self.character_size(cx);
14115
14116 let snapshot = self.snapshot(cx);
14117 let scroll_position = snapshot.scroll_position();
14118 let scroll_left = scroll_position.x * em_width;
14119
14120 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14121 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14122 + self.gutter_dimensions.width
14123 + self.gutter_dimensions.margin;
14124 let y = line_height * (start.row().as_f32() - scroll_position.y);
14125
14126 Some(Bounds {
14127 origin: element_bounds.origin + point(x, y),
14128 size: size(em_width, line_height),
14129 })
14130 }
14131}
14132
14133trait SelectionExt {
14134 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14135 fn spanned_rows(
14136 &self,
14137 include_end_if_at_line_start: bool,
14138 map: &DisplaySnapshot,
14139 ) -> Range<MultiBufferRow>;
14140}
14141
14142impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14143 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14144 let start = self
14145 .start
14146 .to_point(&map.buffer_snapshot)
14147 .to_display_point(map);
14148 let end = self
14149 .end
14150 .to_point(&map.buffer_snapshot)
14151 .to_display_point(map);
14152 if self.reversed {
14153 end..start
14154 } else {
14155 start..end
14156 }
14157 }
14158
14159 fn spanned_rows(
14160 &self,
14161 include_end_if_at_line_start: bool,
14162 map: &DisplaySnapshot,
14163 ) -> Range<MultiBufferRow> {
14164 let start = self.start.to_point(&map.buffer_snapshot);
14165 let mut end = self.end.to_point(&map.buffer_snapshot);
14166 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14167 end.row -= 1;
14168 }
14169
14170 let buffer_start = map.prev_line_boundary(start).0;
14171 let buffer_end = map.next_line_boundary(end).0;
14172 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14173 }
14174}
14175
14176impl<T: InvalidationRegion> InvalidationStack<T> {
14177 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14178 where
14179 S: Clone + ToOffset,
14180 {
14181 while let Some(region) = self.last() {
14182 let all_selections_inside_invalidation_ranges =
14183 if selections.len() == region.ranges().len() {
14184 selections
14185 .iter()
14186 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14187 .all(|(selection, invalidation_range)| {
14188 let head = selection.head().to_offset(buffer);
14189 invalidation_range.start <= head && invalidation_range.end >= head
14190 })
14191 } else {
14192 false
14193 };
14194
14195 if all_selections_inside_invalidation_ranges {
14196 break;
14197 } else {
14198 self.pop();
14199 }
14200 }
14201 }
14202}
14203
14204impl<T> Default for InvalidationStack<T> {
14205 fn default() -> Self {
14206 Self(Default::default())
14207 }
14208}
14209
14210impl<T> Deref for InvalidationStack<T> {
14211 type Target = Vec<T>;
14212
14213 fn deref(&self) -> &Self::Target {
14214 &self.0
14215 }
14216}
14217
14218impl<T> DerefMut for InvalidationStack<T> {
14219 fn deref_mut(&mut self) -> &mut Self::Target {
14220 &mut self.0
14221 }
14222}
14223
14224impl InvalidationRegion for SnippetState {
14225 fn ranges(&self) -> &[Range<Anchor>] {
14226 &self.ranges[self.active_index]
14227 }
14228}
14229
14230pub fn diagnostic_block_renderer(
14231 diagnostic: Diagnostic,
14232 max_message_rows: Option<u8>,
14233 allow_closing: bool,
14234 _is_valid: bool,
14235) -> RenderBlock {
14236 let (text_without_backticks, code_ranges) =
14237 highlight_diagnostic_message(&diagnostic, max_message_rows);
14238
14239 Arc::new(move |cx: &mut BlockContext| {
14240 let group_id: SharedString = cx.block_id.to_string().into();
14241
14242 let mut text_style = cx.text_style().clone();
14243 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14244 let theme_settings = ThemeSettings::get_global(cx);
14245 text_style.font_family = theme_settings.buffer_font.family.clone();
14246 text_style.font_style = theme_settings.buffer_font.style;
14247 text_style.font_features = theme_settings.buffer_font.features.clone();
14248 text_style.font_weight = theme_settings.buffer_font.weight;
14249
14250 let multi_line_diagnostic = diagnostic.message.contains('\n');
14251
14252 let buttons = |diagnostic: &Diagnostic| {
14253 if multi_line_diagnostic {
14254 v_flex()
14255 } else {
14256 h_flex()
14257 }
14258 .when(allow_closing, |div| {
14259 div.children(diagnostic.is_primary.then(|| {
14260 IconButton::new("close-block", IconName::XCircle)
14261 .icon_color(Color::Muted)
14262 .size(ButtonSize::Compact)
14263 .style(ButtonStyle::Transparent)
14264 .visible_on_hover(group_id.clone())
14265 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14266 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14267 }))
14268 })
14269 .child(
14270 IconButton::new("copy-block", IconName::Copy)
14271 .icon_color(Color::Muted)
14272 .size(ButtonSize::Compact)
14273 .style(ButtonStyle::Transparent)
14274 .visible_on_hover(group_id.clone())
14275 .on_click({
14276 let message = diagnostic.message.clone();
14277 move |_click, cx| {
14278 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14279 }
14280 })
14281 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14282 )
14283 };
14284
14285 let icon_size = buttons(&diagnostic)
14286 .into_any_element()
14287 .layout_as_root(AvailableSpace::min_size(), cx);
14288
14289 h_flex()
14290 .id(cx.block_id)
14291 .group(group_id.clone())
14292 .relative()
14293 .size_full()
14294 .block_mouse_down()
14295 .pl(cx.gutter_dimensions.width)
14296 .w(cx.max_width - cx.gutter_dimensions.full_width())
14297 .child(
14298 div()
14299 .flex()
14300 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14301 .flex_shrink(),
14302 )
14303 .child(buttons(&diagnostic))
14304 .child(div().flex().flex_shrink_0().child(
14305 StyledText::new(text_without_backticks.clone()).with_highlights(
14306 &text_style,
14307 code_ranges.iter().map(|range| {
14308 (
14309 range.clone(),
14310 HighlightStyle {
14311 font_weight: Some(FontWeight::BOLD),
14312 ..Default::default()
14313 },
14314 )
14315 }),
14316 ),
14317 ))
14318 .into_any_element()
14319 })
14320}
14321
14322pub fn highlight_diagnostic_message(
14323 diagnostic: &Diagnostic,
14324 mut max_message_rows: Option<u8>,
14325) -> (SharedString, Vec<Range<usize>>) {
14326 let mut text_without_backticks = String::new();
14327 let mut code_ranges = Vec::new();
14328
14329 if let Some(source) = &diagnostic.source {
14330 text_without_backticks.push_str(source);
14331 code_ranges.push(0..source.len());
14332 text_without_backticks.push_str(": ");
14333 }
14334
14335 let mut prev_offset = 0;
14336 let mut in_code_block = false;
14337 let has_row_limit = max_message_rows.is_some();
14338 let mut newline_indices = diagnostic
14339 .message
14340 .match_indices('\n')
14341 .filter(|_| has_row_limit)
14342 .map(|(ix, _)| ix)
14343 .fuse()
14344 .peekable();
14345
14346 for (quote_ix, _) in diagnostic
14347 .message
14348 .match_indices('`')
14349 .chain([(diagnostic.message.len(), "")])
14350 {
14351 let mut first_newline_ix = None;
14352 let mut last_newline_ix = None;
14353 while let Some(newline_ix) = newline_indices.peek() {
14354 if *newline_ix < quote_ix {
14355 if first_newline_ix.is_none() {
14356 first_newline_ix = Some(*newline_ix);
14357 }
14358 last_newline_ix = Some(*newline_ix);
14359
14360 if let Some(rows_left) = &mut max_message_rows {
14361 if *rows_left == 0 {
14362 break;
14363 } else {
14364 *rows_left -= 1;
14365 }
14366 }
14367 let _ = newline_indices.next();
14368 } else {
14369 break;
14370 }
14371 }
14372 let prev_len = text_without_backticks.len();
14373 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14374 text_without_backticks.push_str(new_text);
14375 if in_code_block {
14376 code_ranges.push(prev_len..text_without_backticks.len());
14377 }
14378 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14379 in_code_block = !in_code_block;
14380 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14381 text_without_backticks.push_str("...");
14382 break;
14383 }
14384 }
14385
14386 (text_without_backticks.into(), code_ranges)
14387}
14388
14389fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14390 match severity {
14391 DiagnosticSeverity::ERROR => colors.error,
14392 DiagnosticSeverity::WARNING => colors.warning,
14393 DiagnosticSeverity::INFORMATION => colors.info,
14394 DiagnosticSeverity::HINT => colors.info,
14395 _ => colors.ignored,
14396 }
14397}
14398
14399pub fn styled_runs_for_code_label<'a>(
14400 label: &'a CodeLabel,
14401 syntax_theme: &'a theme::SyntaxTheme,
14402) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14403 let fade_out = HighlightStyle {
14404 fade_out: Some(0.35),
14405 ..Default::default()
14406 };
14407
14408 let mut prev_end = label.filter_range.end;
14409 label
14410 .runs
14411 .iter()
14412 .enumerate()
14413 .flat_map(move |(ix, (range, highlight_id))| {
14414 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14415 style
14416 } else {
14417 return Default::default();
14418 };
14419 let mut muted_style = style;
14420 muted_style.highlight(fade_out);
14421
14422 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14423 if range.start >= label.filter_range.end {
14424 if range.start > prev_end {
14425 runs.push((prev_end..range.start, fade_out));
14426 }
14427 runs.push((range.clone(), muted_style));
14428 } else if range.end <= label.filter_range.end {
14429 runs.push((range.clone(), style));
14430 } else {
14431 runs.push((range.start..label.filter_range.end, style));
14432 runs.push((label.filter_range.end..range.end, muted_style));
14433 }
14434 prev_end = cmp::max(prev_end, range.end);
14435
14436 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14437 runs.push((prev_end..label.text.len(), fade_out));
14438 }
14439
14440 runs
14441 })
14442}
14443
14444pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14445 let mut prev_index = 0;
14446 let mut prev_codepoint: Option<char> = None;
14447 text.char_indices()
14448 .chain([(text.len(), '\0')])
14449 .filter_map(move |(index, codepoint)| {
14450 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14451 let is_boundary = index == text.len()
14452 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14453 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14454 if is_boundary {
14455 let chunk = &text[prev_index..index];
14456 prev_index = index;
14457 Some(chunk)
14458 } else {
14459 None
14460 }
14461 })
14462}
14463
14464pub trait RangeToAnchorExt: Sized {
14465 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14466
14467 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14468 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14469 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14470 }
14471}
14472
14473impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14474 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14475 let start_offset = self.start.to_offset(snapshot);
14476 let end_offset = self.end.to_offset(snapshot);
14477 if start_offset == end_offset {
14478 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14479 } else {
14480 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14481 }
14482 }
14483}
14484
14485pub trait RowExt {
14486 fn as_f32(&self) -> f32;
14487
14488 fn next_row(&self) -> Self;
14489
14490 fn previous_row(&self) -> Self;
14491
14492 fn minus(&self, other: Self) -> u32;
14493}
14494
14495impl RowExt for DisplayRow {
14496 fn as_f32(&self) -> f32 {
14497 self.0 as f32
14498 }
14499
14500 fn next_row(&self) -> Self {
14501 Self(self.0 + 1)
14502 }
14503
14504 fn previous_row(&self) -> Self {
14505 Self(self.0.saturating_sub(1))
14506 }
14507
14508 fn minus(&self, other: Self) -> u32 {
14509 self.0 - other.0
14510 }
14511}
14512
14513impl RowExt for MultiBufferRow {
14514 fn as_f32(&self) -> f32 {
14515 self.0 as f32
14516 }
14517
14518 fn next_row(&self) -> Self {
14519 Self(self.0 + 1)
14520 }
14521
14522 fn previous_row(&self) -> Self {
14523 Self(self.0.saturating_sub(1))
14524 }
14525
14526 fn minus(&self, other: Self) -> u32 {
14527 self.0 - other.0
14528 }
14529}
14530
14531trait RowRangeExt {
14532 type Row;
14533
14534 fn len(&self) -> usize;
14535
14536 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14537}
14538
14539impl RowRangeExt for Range<MultiBufferRow> {
14540 type Row = MultiBufferRow;
14541
14542 fn len(&self) -> usize {
14543 (self.end.0 - self.start.0) as usize
14544 }
14545
14546 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14547 (self.start.0..self.end.0).map(MultiBufferRow)
14548 }
14549}
14550
14551impl RowRangeExt for Range<DisplayRow> {
14552 type Row = DisplayRow;
14553
14554 fn len(&self) -> usize {
14555 (self.end.0 - self.start.0) as usize
14556 }
14557
14558 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14559 (self.start.0..self.end.0).map(DisplayRow)
14560 }
14561}
14562
14563fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14564 if hunk.diff_base_byte_range.is_empty() {
14565 DiffHunkStatus::Added
14566 } else if hunk.row_range.is_empty() {
14567 DiffHunkStatus::Removed
14568 } else {
14569 DiffHunkStatus::Modified
14570 }
14571}
14572
14573/// If select range has more than one line, we
14574/// just point the cursor to range.start.
14575fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14576 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14577 range
14578 } else {
14579 range.start..range.start
14580 }
14581}
14582
14583pub struct KillRing(ClipboardItem);
14584impl Global for KillRing {}
14585
14586const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);