1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod clangd_ext;
19mod debounced_delay;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod hunk_diff;
29mod indent_guides;
30mod inlay_hint_cache;
31mod inline_completion_provider;
32pub mod items;
33mod linked_editing_ranges;
34mod lsp_ext;
35mod mouse_context_menu;
36pub mod movement;
37mod persistence;
38mod proposed_changes_editor;
39mod rust_analyzer_ext;
40pub mod scroll;
41mod selections_collection;
42pub mod tasks;
43
44#[cfg(test)]
45mod editor_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50use ::git::diff::DiffHunkStatus;
51pub(crate) use actions::*;
52pub use actions::{OpenExcerpts, OpenExcerptsSplit};
53use aho_corasick::AhoCorasick;
54use anyhow::{anyhow, Context as _, Result};
55use blink_manager::BlinkManager;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use debounced_delay::DebouncedDelay;
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::{StringMatch, StringMatchCandidate};
73use git::blame::GitBlame;
74use gpui::{
75 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
76 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
77 ClipboardItem, Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent,
78 FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext,
79 ListSizingBehavior, Model, ModelContext, MouseButton, PaintQuad, ParentElement, Pixels, Render,
80 ScrollStrategy, SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task,
81 TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, View,
82 ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle, WeakView, WindowContext,
83};
84use highlight_matching_bracket::refresh_matching_bracket_highlights;
85use hover_popover::{hide_hover, HoverState};
86pub(crate) use hunk_diff::HoveredHunk;
87use hunk_diff::{diff_hunk_to_display, ExpandedHunks};
88use indent_guides::ActiveIndentGuidesState;
89use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
90pub use inline_completion_provider::*;
91pub use items::MAX_TAB_TITLE_LEN;
92use itertools::Itertools;
93use language::{
94 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
95 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
96 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
97 Point, Selection, SelectionGoal, TransactionId,
98};
99use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
100use linked_editing_ranges::refresh_linked_ranges;
101pub use proposed_changes_editor::{
102 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
103};
104use similar::{ChangeTag, TextDiff};
105use std::iter::Peekable;
106use task::{ResolvedTask, TaskTemplate, TaskVariables};
107
108use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
109pub use lsp::CompletionContext;
110use lsp::{
111 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
112 LanguageServerId, LanguageServerName,
113};
114use mouse_context_menu::MouseContextMenu;
115use movement::TextLayoutDetails;
116pub use multi_buffer::{
117 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
118 ToPoint,
119};
120use multi_buffer::{
121 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
122};
123use ordered_float::OrderedFloat;
124use parking_lot::{Mutex, RwLock};
125use project::{
126 lsp_store::{FormatTarget, FormatTrigger},
127 project_settings::{GitGutterSetting, ProjectSettings},
128 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Item, Location,
129 LocationLink, Project, ProjectTransaction, TaskSourceKind,
130};
131use rand::prelude::*;
132use rpc::{proto::*, ErrorExt};
133use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
134use selections_collection::{
135 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
136};
137use serde::{Deserialize, Serialize};
138use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
139use smallvec::SmallVec;
140use snippet::Snippet;
141use std::{
142 any::TypeId,
143 borrow::Cow,
144 cell::RefCell,
145 cmp::{self, Ordering, Reverse},
146 mem,
147 num::NonZeroU32,
148 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
149 path::{Path, PathBuf},
150 rc::Rc,
151 sync::Arc,
152 time::{Duration, Instant},
153};
154pub use sum_tree::Bias;
155use sum_tree::TreeMap;
156use text::{BufferId, OffsetUtf16, Rope};
157use theme::{
158 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
159 ThemeColors, ThemeSettings,
160};
161use ui::{
162 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
163 ListItem, Popover, PopoverMenuHandle, Tooltip,
164};
165use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
166use workspace::item::{ItemHandle, PreviewTabsSettings};
167use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
168use workspace::{
169 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
170};
171use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
172
173use crate::hover_links::find_url;
174use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
175
176pub const FILE_HEADER_HEIGHT: u32 = 2;
177pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
178pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
179pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
180const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
181const MAX_LINE_LEN: usize = 1024;
182const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
183const MAX_SELECTION_HISTORY_LEN: usize = 1024;
184pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
185#[doc(hidden)]
186pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
187#[doc(hidden)]
188pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
189
190pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
191pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
192
193pub fn render_parsed_markdown(
194 element_id: impl Into<ElementId>,
195 parsed: &language::ParsedMarkdown,
196 editor_style: &EditorStyle,
197 workspace: Option<WeakView<Workspace>>,
198 cx: &mut WindowContext,
199) -> InteractiveText {
200 let code_span_background_color = cx
201 .theme()
202 .colors()
203 .editor_document_highlight_read_background;
204
205 let highlights = gpui::combine_highlights(
206 parsed.highlights.iter().filter_map(|(range, highlight)| {
207 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
208 Some((range.clone(), highlight))
209 }),
210 parsed
211 .regions
212 .iter()
213 .zip(&parsed.region_ranges)
214 .filter_map(|(region, range)| {
215 if region.code {
216 Some((
217 range.clone(),
218 HighlightStyle {
219 background_color: Some(code_span_background_color),
220 ..Default::default()
221 },
222 ))
223 } else {
224 None
225 }
226 }),
227 );
228
229 let mut links = Vec::new();
230 let mut link_ranges = Vec::new();
231 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
232 if let Some(link) = region.link.clone() {
233 links.push(link);
234 link_ranges.push(range.clone());
235 }
236 }
237
238 InteractiveText::new(
239 element_id,
240 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
241 )
242 .on_click(link_ranges, move |clicked_range_ix, cx| {
243 match &links[clicked_range_ix] {
244 markdown::Link::Web { url } => cx.open_url(url),
245 markdown::Link::Path { path } => {
246 if let Some(workspace) = &workspace {
247 _ = workspace.update(cx, |workspace, cx| {
248 workspace.open_abs_path(path.clone(), false, cx).detach();
249 });
250 }
251 }
252 }
253 })
254}
255
256#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
257pub(crate) enum InlayId {
258 Suggestion(usize),
259 Hint(usize),
260}
261
262impl InlayId {
263 fn id(&self) -> usize {
264 match self {
265 Self::Suggestion(id) => *id,
266 Self::Hint(id) => *id,
267 }
268 }
269}
270
271enum DiffRowHighlight {}
272enum DocumentHighlightRead {}
273enum DocumentHighlightWrite {}
274enum InputComposition {}
275
276#[derive(Copy, Clone, PartialEq, Eq)]
277pub enum Direction {
278 Prev,
279 Next,
280}
281
282#[derive(Debug, Copy, Clone, PartialEq, Eq)]
283pub enum Navigated {
284 Yes,
285 No,
286}
287
288impl Navigated {
289 pub fn from_bool(yes: bool) -> Navigated {
290 if yes {
291 Navigated::Yes
292 } else {
293 Navigated::No
294 }
295 }
296}
297
298pub fn init_settings(cx: &mut AppContext) {
299 EditorSettings::register(cx);
300}
301
302pub fn init(cx: &mut AppContext) {
303 init_settings(cx);
304
305 workspace::register_project_item::<Editor>(cx);
306 workspace::FollowableViewRegistry::register::<Editor>(cx);
307 workspace::register_serializable_item::<Editor>(cx);
308
309 cx.observe_new_views(
310 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
311 workspace.register_action(Editor::new_file);
312 workspace.register_action(Editor::new_file_vertical);
313 workspace.register_action(Editor::new_file_horizontal);
314 },
315 )
316 .detach();
317
318 cx.on_action(move |_: &workspace::NewFile, cx| {
319 let app_state = workspace::AppState::global(cx);
320 if let Some(app_state) = app_state.upgrade() {
321 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
322 Editor::new_file(workspace, &Default::default(), cx)
323 })
324 .detach();
325 }
326 });
327 cx.on_action(move |_: &workspace::NewWindow, cx| {
328 let app_state = workspace::AppState::global(cx);
329 if let Some(app_state) = app_state.upgrade() {
330 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
331 Editor::new_file(workspace, &Default::default(), cx)
332 })
333 .detach();
334 }
335 });
336}
337
338pub struct SearchWithinRange;
339
340trait InvalidationRegion {
341 fn ranges(&self) -> &[Range<Anchor>];
342}
343
344#[derive(Clone, Debug, PartialEq)]
345pub enum SelectPhase {
346 Begin {
347 position: DisplayPoint,
348 add: bool,
349 click_count: usize,
350 },
351 BeginColumnar {
352 position: DisplayPoint,
353 reset: bool,
354 goal_column: u32,
355 },
356 Extend {
357 position: DisplayPoint,
358 click_count: usize,
359 },
360 Update {
361 position: DisplayPoint,
362 goal_column: u32,
363 scroll_delta: gpui::Point<f32>,
364 },
365 End,
366}
367
368#[derive(Clone, Debug)]
369pub enum SelectMode {
370 Character,
371 Word(Range<Anchor>),
372 Line(Range<Anchor>),
373 All,
374}
375
376#[derive(Copy, Clone, PartialEq, Eq, Debug)]
377pub enum EditorMode {
378 SingleLine { auto_width: bool },
379 AutoHeight { max_lines: usize },
380 Full,
381}
382
383#[derive(Copy, Clone, Debug)]
384pub enum SoftWrap {
385 /// Prefer not to wrap at all.
386 ///
387 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
388 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
389 GitDiff,
390 /// Prefer a single line generally, unless an overly long line is encountered.
391 None,
392 /// Soft wrap lines that exceed the editor width.
393 EditorWidth,
394 /// Soft wrap lines at the preferred line length.
395 Column(u32),
396 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
397 Bounded(u32),
398}
399
400#[derive(Clone)]
401pub struct EditorStyle {
402 pub background: Hsla,
403 pub local_player: PlayerColor,
404 pub text: TextStyle,
405 pub scrollbar_width: Pixels,
406 pub syntax: Arc<SyntaxTheme>,
407 pub status: StatusColors,
408 pub inlay_hints_style: HighlightStyle,
409 pub suggestions_style: HighlightStyle,
410 pub unnecessary_code_fade: f32,
411}
412
413impl Default for EditorStyle {
414 fn default() -> Self {
415 Self {
416 background: Hsla::default(),
417 local_player: PlayerColor::default(),
418 text: TextStyle::default(),
419 scrollbar_width: Pixels::default(),
420 syntax: Default::default(),
421 // HACK: Status colors don't have a real default.
422 // We should look into removing the status colors from the editor
423 // style and retrieve them directly from the theme.
424 status: StatusColors::dark(),
425 inlay_hints_style: HighlightStyle::default(),
426 suggestions_style: HighlightStyle::default(),
427 unnecessary_code_fade: Default::default(),
428 }
429 }
430}
431
432pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
433 let show_background = language_settings::language_settings(None, None, cx)
434 .inlay_hints
435 .show_background;
436
437 HighlightStyle {
438 color: Some(cx.theme().status().hint),
439 background_color: show_background.then(|| cx.theme().status().hint_background),
440 ..HighlightStyle::default()
441 }
442}
443
444type CompletionId = usize;
445
446#[derive(Clone, Debug)]
447struct CompletionState {
448 // render_inlay_ids represents the inlay hints that are inserted
449 // for rendering the inline completions. They may be discontinuous
450 // in the event that the completion provider returns some intersection
451 // with the existing content.
452 render_inlay_ids: Vec<InlayId>,
453 // text is the resulting rope that is inserted when the user accepts a completion.
454 text: Rope,
455 // position is the position of the cursor when the completion was triggered.
456 position: multi_buffer::Anchor,
457 // delete_range is the range of text that this completion state covers.
458 // if the completion is accepted, this range should be deleted.
459 delete_range: Option<Range<multi_buffer::Anchor>>,
460}
461
462#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
463struct EditorActionId(usize);
464
465impl EditorActionId {
466 pub fn post_inc(&mut self) -> Self {
467 let answer = self.0;
468
469 *self = Self(answer + 1);
470
471 Self(answer)
472 }
473}
474
475// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
476// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
477
478type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
479type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
480
481#[derive(Default)]
482struct ScrollbarMarkerState {
483 scrollbar_size: Size<Pixels>,
484 dirty: bool,
485 markers: Arc<[PaintQuad]>,
486 pending_refresh: Option<Task<Result<()>>>,
487}
488
489impl ScrollbarMarkerState {
490 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
491 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
492 }
493}
494
495#[derive(Clone, Debug)]
496struct RunnableTasks {
497 templates: Vec<(TaskSourceKind, TaskTemplate)>,
498 offset: MultiBufferOffset,
499 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
500 column: u32,
501 // Values of all named captures, including those starting with '_'
502 extra_variables: HashMap<String, String>,
503 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
504 context_range: Range<BufferOffset>,
505}
506
507impl RunnableTasks {
508 fn resolve<'a>(
509 &'a self,
510 cx: &'a task::TaskContext,
511 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
512 self.templates.iter().filter_map(|(kind, template)| {
513 template
514 .resolve_task(&kind.to_id_base(), cx)
515 .map(|task| (kind.clone(), task))
516 })
517 }
518}
519
520#[derive(Clone)]
521struct ResolvedTasks {
522 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
523 position: Anchor,
524}
525#[derive(Copy, Clone, Debug)]
526struct MultiBufferOffset(usize);
527#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
528struct BufferOffset(usize);
529
530// Addons allow storing per-editor state in other crates (e.g. Vim)
531pub trait Addon: 'static {
532 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
533
534 fn to_any(&self) -> &dyn std::any::Any;
535}
536
537#[derive(Debug, Copy, Clone, PartialEq, Eq)]
538pub enum IsVimMode {
539 Yes,
540 No,
541}
542
543/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
544///
545/// See the [module level documentation](self) for more information.
546pub struct Editor {
547 focus_handle: FocusHandle,
548 last_focused_descendant: Option<WeakFocusHandle>,
549 /// The text buffer being edited
550 buffer: Model<MultiBuffer>,
551 /// Map of how text in the buffer should be displayed.
552 /// Handles soft wraps, folds, fake inlay text insertions, etc.
553 pub display_map: Model<DisplayMap>,
554 pub selections: SelectionsCollection,
555 pub scroll_manager: ScrollManager,
556 /// When inline assist editors are linked, they all render cursors because
557 /// typing enters text into each of them, even the ones that aren't focused.
558 pub(crate) show_cursor_when_unfocused: bool,
559 columnar_selection_tail: Option<Anchor>,
560 add_selections_state: Option<AddSelectionsState>,
561 select_next_state: Option<SelectNextState>,
562 select_prev_state: Option<SelectNextState>,
563 selection_history: SelectionHistory,
564 autoclose_regions: Vec<AutocloseRegion>,
565 snippet_stack: InvalidationStack<SnippetState>,
566 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
567 ime_transaction: Option<TransactionId>,
568 active_diagnostics: Option<ActiveDiagnosticGroup>,
569 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
570
571 project: Option<Model<Project>>,
572 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
573 completion_provider: Option<Box<dyn CompletionProvider>>,
574 collaboration_hub: Option<Box<dyn CollaborationHub>>,
575 blink_manager: Model<BlinkManager>,
576 show_cursor_names: bool,
577 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
578 pub show_local_selections: bool,
579 mode: EditorMode,
580 show_breadcrumbs: bool,
581 show_gutter: bool,
582 show_line_numbers: Option<bool>,
583 use_relative_line_numbers: Option<bool>,
584 show_git_diff_gutter: Option<bool>,
585 show_code_actions: Option<bool>,
586 show_runnables: Option<bool>,
587 show_wrap_guides: Option<bool>,
588 show_indent_guides: Option<bool>,
589 placeholder_text: Option<Arc<str>>,
590 highlight_order: usize,
591 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
592 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
593 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
594 scrollbar_marker_state: ScrollbarMarkerState,
595 active_indent_guides_state: ActiveIndentGuidesState,
596 nav_history: Option<ItemNavHistory>,
597 context_menu: RwLock<Option<ContextMenu>>,
598 mouse_context_menu: Option<MouseContextMenu>,
599 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
600 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
601 signature_help_state: SignatureHelpState,
602 auto_signature_help: Option<bool>,
603 find_all_references_task_sources: Vec<Anchor>,
604 next_completion_id: CompletionId,
605 completion_documentation_pre_resolve_debounce: DebouncedDelay,
606 available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
607 code_actions_task: Option<Task<Result<()>>>,
608 document_highlights_task: Option<Task<()>>,
609 linked_editing_range_task: Option<Task<Option<()>>>,
610 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
611 pending_rename: Option<RenameState>,
612 searchable: bool,
613 cursor_shape: CursorShape,
614 current_line_highlight: Option<CurrentLineHighlight>,
615 collapse_matches: bool,
616 autoindent_mode: Option<AutoindentMode>,
617 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
618 input_enabled: bool,
619 use_modal_editing: bool,
620 read_only: bool,
621 leader_peer_id: Option<PeerId>,
622 remote_id: Option<ViewId>,
623 hover_state: HoverState,
624 gutter_hovered: bool,
625 hovered_link_state: Option<HoveredLinkState>,
626 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
627 code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
628 active_inline_completion: Option<CompletionState>,
629 // enable_inline_completions is a switch that Vim can use to disable
630 // inline completions based on its mode.
631 enable_inline_completions: bool,
632 show_inline_completions_override: Option<bool>,
633 inlay_hint_cache: InlayHintCache,
634 expanded_hunks: ExpandedHunks,
635 next_inlay_id: usize,
636 _subscriptions: Vec<Subscription>,
637 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
638 gutter_dimensions: GutterDimensions,
639 style: Option<EditorStyle>,
640 text_style_refinement: Option<TextStyleRefinement>,
641 next_editor_action_id: EditorActionId,
642 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
643 use_autoclose: bool,
644 use_auto_surround: bool,
645 auto_replace_emoji_shortcode: bool,
646 show_git_blame_gutter: bool,
647 show_git_blame_inline: bool,
648 show_git_blame_inline_delay_task: Option<Task<()>>,
649 git_blame_inline_enabled: bool,
650 serialize_dirty_buffers: bool,
651 show_selection_menu: Option<bool>,
652 blame: Option<Model<GitBlame>>,
653 blame_subscription: Option<Subscription>,
654 custom_context_menu: Option<
655 Box<
656 dyn 'static
657 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
658 >,
659 >,
660 last_bounds: Option<Bounds<Pixels>>,
661 expect_bounds_change: Option<Bounds<Pixels>>,
662 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
663 tasks_update_task: Option<Task<()>>,
664 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
665 breadcrumb_header: Option<String>,
666 focused_block: Option<FocusedBlock>,
667 next_scroll_position: NextScrollCursorCenterTopBottom,
668 addons: HashMap<TypeId, Box<dyn Addon>>,
669 _scroll_cursor_center_top_bottom_task: Task<()>,
670}
671
672#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
673enum NextScrollCursorCenterTopBottom {
674 #[default]
675 Center,
676 Top,
677 Bottom,
678}
679
680impl NextScrollCursorCenterTopBottom {
681 fn next(&self) -> Self {
682 match self {
683 Self::Center => Self::Top,
684 Self::Top => Self::Bottom,
685 Self::Bottom => Self::Center,
686 }
687 }
688}
689
690#[derive(Clone)]
691pub struct EditorSnapshot {
692 pub mode: EditorMode,
693 show_gutter: bool,
694 show_line_numbers: Option<bool>,
695 show_git_diff_gutter: Option<bool>,
696 show_code_actions: Option<bool>,
697 show_runnables: Option<bool>,
698 git_blame_gutter_max_author_length: Option<usize>,
699 pub display_snapshot: DisplaySnapshot,
700 pub placeholder_text: Option<Arc<str>>,
701 is_focused: bool,
702 scroll_anchor: ScrollAnchor,
703 ongoing_scroll: OngoingScroll,
704 current_line_highlight: CurrentLineHighlight,
705 gutter_hovered: bool,
706}
707
708const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
709
710#[derive(Default, Debug, Clone, Copy)]
711pub struct GutterDimensions {
712 pub left_padding: Pixels,
713 pub right_padding: Pixels,
714 pub width: Pixels,
715 pub margin: Pixels,
716 pub git_blame_entries_width: Option<Pixels>,
717}
718
719impl GutterDimensions {
720 /// The full width of the space taken up by the gutter.
721 pub fn full_width(&self) -> Pixels {
722 self.margin + self.width
723 }
724
725 /// The width of the space reserved for the fold indicators,
726 /// use alongside 'justify_end' and `gutter_width` to
727 /// right align content with the line numbers
728 pub fn fold_area_width(&self) -> Pixels {
729 self.margin + self.right_padding
730 }
731}
732
733#[derive(Debug)]
734pub struct RemoteSelection {
735 pub replica_id: ReplicaId,
736 pub selection: Selection<Anchor>,
737 pub cursor_shape: CursorShape,
738 pub peer_id: PeerId,
739 pub line_mode: bool,
740 pub participant_index: Option<ParticipantIndex>,
741 pub user_name: Option<SharedString>,
742}
743
744#[derive(Clone, Debug)]
745struct SelectionHistoryEntry {
746 selections: Arc<[Selection<Anchor>]>,
747 select_next_state: Option<SelectNextState>,
748 select_prev_state: Option<SelectNextState>,
749 add_selections_state: Option<AddSelectionsState>,
750}
751
752enum SelectionHistoryMode {
753 Normal,
754 Undoing,
755 Redoing,
756}
757
758#[derive(Clone, PartialEq, Eq, Hash)]
759struct HoveredCursor {
760 replica_id: u16,
761 selection_id: usize,
762}
763
764impl Default for SelectionHistoryMode {
765 fn default() -> Self {
766 Self::Normal
767 }
768}
769
770#[derive(Default)]
771struct SelectionHistory {
772 #[allow(clippy::type_complexity)]
773 selections_by_transaction:
774 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
775 mode: SelectionHistoryMode,
776 undo_stack: VecDeque<SelectionHistoryEntry>,
777 redo_stack: VecDeque<SelectionHistoryEntry>,
778}
779
780impl SelectionHistory {
781 fn insert_transaction(
782 &mut self,
783 transaction_id: TransactionId,
784 selections: Arc<[Selection<Anchor>]>,
785 ) {
786 self.selections_by_transaction
787 .insert(transaction_id, (selections, None));
788 }
789
790 #[allow(clippy::type_complexity)]
791 fn transaction(
792 &self,
793 transaction_id: TransactionId,
794 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
795 self.selections_by_transaction.get(&transaction_id)
796 }
797
798 #[allow(clippy::type_complexity)]
799 fn transaction_mut(
800 &mut self,
801 transaction_id: TransactionId,
802 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
803 self.selections_by_transaction.get_mut(&transaction_id)
804 }
805
806 fn push(&mut self, entry: SelectionHistoryEntry) {
807 if !entry.selections.is_empty() {
808 match self.mode {
809 SelectionHistoryMode::Normal => {
810 self.push_undo(entry);
811 self.redo_stack.clear();
812 }
813 SelectionHistoryMode::Undoing => self.push_redo(entry),
814 SelectionHistoryMode::Redoing => self.push_undo(entry),
815 }
816 }
817 }
818
819 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
820 if self
821 .undo_stack
822 .back()
823 .map_or(true, |e| e.selections != entry.selections)
824 {
825 self.undo_stack.push_back(entry);
826 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
827 self.undo_stack.pop_front();
828 }
829 }
830 }
831
832 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
833 if self
834 .redo_stack
835 .back()
836 .map_or(true, |e| e.selections != entry.selections)
837 {
838 self.redo_stack.push_back(entry);
839 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
840 self.redo_stack.pop_front();
841 }
842 }
843 }
844}
845
846struct RowHighlight {
847 index: usize,
848 range: Range<Anchor>,
849 color: Hsla,
850 should_autoscroll: bool,
851}
852
853#[derive(Clone, Debug)]
854struct AddSelectionsState {
855 above: bool,
856 stack: Vec<usize>,
857}
858
859#[derive(Clone)]
860struct SelectNextState {
861 query: AhoCorasick,
862 wordwise: bool,
863 done: bool,
864}
865
866impl std::fmt::Debug for SelectNextState {
867 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
868 f.debug_struct(std::any::type_name::<Self>())
869 .field("wordwise", &self.wordwise)
870 .field("done", &self.done)
871 .finish()
872 }
873}
874
875#[derive(Debug)]
876struct AutocloseRegion {
877 selection_id: usize,
878 range: Range<Anchor>,
879 pair: BracketPair,
880}
881
882#[derive(Debug)]
883struct SnippetState {
884 ranges: Vec<Vec<Range<Anchor>>>,
885 active_index: usize,
886 choices: Vec<Option<Vec<String>>>,
887}
888
889#[doc(hidden)]
890pub struct RenameState {
891 pub range: Range<Anchor>,
892 pub old_name: Arc<str>,
893 pub editor: View<Editor>,
894 block_id: CustomBlockId,
895}
896
897struct InvalidationStack<T>(Vec<T>);
898
899struct RegisteredInlineCompletionProvider {
900 provider: Arc<dyn InlineCompletionProviderHandle>,
901 _subscription: Subscription,
902}
903
904enum ContextMenu {
905 Completions(CompletionsMenu),
906 CodeActions(CodeActionsMenu),
907}
908
909impl ContextMenu {
910 fn select_first(
911 &mut self,
912 provider: Option<&dyn CompletionProvider>,
913 cx: &mut ViewContext<Editor>,
914 ) -> bool {
915 if self.visible() {
916 match self {
917 ContextMenu::Completions(menu) => menu.select_first(provider, cx),
918 ContextMenu::CodeActions(menu) => menu.select_first(cx),
919 }
920 true
921 } else {
922 false
923 }
924 }
925
926 fn select_prev(
927 &mut self,
928 provider: Option<&dyn CompletionProvider>,
929 cx: &mut ViewContext<Editor>,
930 ) -> bool {
931 if self.visible() {
932 match self {
933 ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
934 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
935 }
936 true
937 } else {
938 false
939 }
940 }
941
942 fn select_next(
943 &mut self,
944 provider: Option<&dyn CompletionProvider>,
945 cx: &mut ViewContext<Editor>,
946 ) -> bool {
947 if self.visible() {
948 match self {
949 ContextMenu::Completions(menu) => menu.select_next(provider, cx),
950 ContextMenu::CodeActions(menu) => menu.select_next(cx),
951 }
952 true
953 } else {
954 false
955 }
956 }
957
958 fn select_last(
959 &mut self,
960 provider: Option<&dyn CompletionProvider>,
961 cx: &mut ViewContext<Editor>,
962 ) -> bool {
963 if self.visible() {
964 match self {
965 ContextMenu::Completions(menu) => menu.select_last(provider, cx),
966 ContextMenu::CodeActions(menu) => menu.select_last(cx),
967 }
968 true
969 } else {
970 false
971 }
972 }
973
974 fn visible(&self) -> bool {
975 match self {
976 ContextMenu::Completions(menu) => menu.visible(),
977 ContextMenu::CodeActions(menu) => menu.visible(),
978 }
979 }
980
981 fn render(
982 &self,
983 cursor_position: DisplayPoint,
984 style: &EditorStyle,
985 max_height: Pixels,
986 workspace: Option<WeakView<Workspace>>,
987 cx: &mut ViewContext<Editor>,
988 ) -> (ContextMenuOrigin, AnyElement) {
989 match self {
990 ContextMenu::Completions(menu) => (
991 ContextMenuOrigin::EditorPoint(cursor_position),
992 menu.render(style, max_height, workspace, cx),
993 ),
994 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
995 }
996 }
997}
998
999enum ContextMenuOrigin {
1000 EditorPoint(DisplayPoint),
1001 GutterIndicator(DisplayRow),
1002}
1003
1004#[derive(Clone, Debug)]
1005struct CompletionsMenu {
1006 id: CompletionId,
1007 sort_completions: bool,
1008 initial_position: Anchor,
1009 buffer: Model<Buffer>,
1010 completions: Arc<RwLock<Box<[Completion]>>>,
1011 match_candidates: Arc<[StringMatchCandidate]>,
1012 matches: Arc<[StringMatch]>,
1013 selected_item: usize,
1014 scroll_handle: UniformListScrollHandle,
1015 selected_completion_documentation_resolve_debounce: Option<Arc<Mutex<DebouncedDelay>>>,
1016}
1017
1018impl CompletionsMenu {
1019 fn new(
1020 id: CompletionId,
1021 sort_completions: bool,
1022 initial_position: Anchor,
1023 buffer: Model<Buffer>,
1024 completions: Box<[Completion]>,
1025 ) -> Self {
1026 let match_candidates = completions
1027 .iter()
1028 .enumerate()
1029 .map(|(id, completion)| {
1030 StringMatchCandidate::new(
1031 id,
1032 completion.label.text[completion.label.filter_range.clone()].into(),
1033 )
1034 })
1035 .collect();
1036
1037 Self {
1038 id,
1039 sort_completions,
1040 initial_position,
1041 buffer,
1042 completions: Arc::new(RwLock::new(completions)),
1043 match_candidates,
1044 matches: Vec::new().into(),
1045 selected_item: 0,
1046 scroll_handle: UniformListScrollHandle::new(),
1047 selected_completion_documentation_resolve_debounce: Some(Arc::new(Mutex::new(
1048 DebouncedDelay::new(),
1049 ))),
1050 }
1051 }
1052
1053 fn new_snippet_choices(
1054 id: CompletionId,
1055 sort_completions: bool,
1056 choices: &Vec<String>,
1057 selection: Range<Anchor>,
1058 buffer: Model<Buffer>,
1059 ) -> Self {
1060 let completions = choices
1061 .iter()
1062 .map(|choice| Completion {
1063 old_range: selection.start.text_anchor..selection.end.text_anchor,
1064 new_text: choice.to_string(),
1065 label: CodeLabel {
1066 text: choice.to_string(),
1067 runs: Default::default(),
1068 filter_range: Default::default(),
1069 },
1070 server_id: LanguageServerId(usize::MAX),
1071 documentation: None,
1072 lsp_completion: Default::default(),
1073 confirm: None,
1074 })
1075 .collect();
1076
1077 let match_candidates = choices
1078 .iter()
1079 .enumerate()
1080 .map(|(id, completion)| StringMatchCandidate::new(id, completion.to_string()))
1081 .collect();
1082 let matches = choices
1083 .iter()
1084 .enumerate()
1085 .map(|(id, completion)| StringMatch {
1086 candidate_id: id,
1087 score: 1.,
1088 positions: vec![],
1089 string: completion.clone(),
1090 })
1091 .collect();
1092 Self {
1093 id,
1094 sort_completions,
1095 initial_position: selection.start,
1096 buffer,
1097 completions: Arc::new(RwLock::new(completions)),
1098 match_candidates,
1099 matches,
1100 selected_item: 0,
1101 scroll_handle: UniformListScrollHandle::new(),
1102 selected_completion_documentation_resolve_debounce: Some(Arc::new(Mutex::new(
1103 DebouncedDelay::new(),
1104 ))),
1105 }
1106 }
1107
1108 fn suppress_documentation_resolution(mut self) -> Self {
1109 self.selected_completion_documentation_resolve_debounce
1110 .take();
1111 self
1112 }
1113
1114 fn select_first(
1115 &mut self,
1116 provider: Option<&dyn CompletionProvider>,
1117 cx: &mut ViewContext<Editor>,
1118 ) {
1119 self.selected_item = 0;
1120 self.scroll_handle
1121 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1122 self.attempt_resolve_selected_completion_documentation(provider, cx);
1123 cx.notify();
1124 }
1125
1126 fn select_prev(
1127 &mut self,
1128 provider: Option<&dyn CompletionProvider>,
1129 cx: &mut ViewContext<Editor>,
1130 ) {
1131 if self.selected_item > 0 {
1132 self.selected_item -= 1;
1133 } else {
1134 self.selected_item = self.matches.len() - 1;
1135 }
1136 self.scroll_handle
1137 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1138 self.attempt_resolve_selected_completion_documentation(provider, cx);
1139 cx.notify();
1140 }
1141
1142 fn select_next(
1143 &mut self,
1144 provider: Option<&dyn CompletionProvider>,
1145 cx: &mut ViewContext<Editor>,
1146 ) {
1147 if self.selected_item + 1 < self.matches.len() {
1148 self.selected_item += 1;
1149 } else {
1150 self.selected_item = 0;
1151 }
1152 self.scroll_handle
1153 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1154 self.attempt_resolve_selected_completion_documentation(provider, cx);
1155 cx.notify();
1156 }
1157
1158 fn select_last(
1159 &mut self,
1160 provider: Option<&dyn CompletionProvider>,
1161 cx: &mut ViewContext<Editor>,
1162 ) {
1163 self.selected_item = self.matches.len() - 1;
1164 self.scroll_handle
1165 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1166 self.attempt_resolve_selected_completion_documentation(provider, cx);
1167 cx.notify();
1168 }
1169
1170 fn pre_resolve_completion_documentation(
1171 buffer: Model<Buffer>,
1172 completions: Arc<RwLock<Box<[Completion]>>>,
1173 matches: Arc<[StringMatch]>,
1174 editor: &Editor,
1175 cx: &mut ViewContext<Editor>,
1176 ) -> Task<()> {
1177 let settings = EditorSettings::get_global(cx);
1178 if !settings.show_completion_documentation {
1179 return Task::ready(());
1180 }
1181
1182 let Some(provider) = editor.completion_provider.as_ref() else {
1183 return Task::ready(());
1184 };
1185
1186 let resolve_task = provider.resolve_completions(
1187 buffer,
1188 matches.iter().map(|m| m.candidate_id).collect(),
1189 completions.clone(),
1190 cx,
1191 );
1192
1193 cx.spawn(move |this, mut cx| async move {
1194 if let Some(true) = resolve_task.await.log_err() {
1195 this.update(&mut cx, |_, cx| cx.notify()).ok();
1196 }
1197 })
1198 }
1199
1200 fn attempt_resolve_selected_completion_documentation(
1201 &mut self,
1202 provider: Option<&dyn CompletionProvider>,
1203 cx: &mut ViewContext<Editor>,
1204 ) {
1205 let settings = EditorSettings::get_global(cx);
1206 if !settings.show_completion_documentation {
1207 return;
1208 }
1209
1210 let completion_index = self.matches[self.selected_item].candidate_id;
1211 let Some(provider) = provider else {
1212 return;
1213 };
1214 let Some(documentation_resolve) = self
1215 .selected_completion_documentation_resolve_debounce
1216 .as_ref()
1217 else {
1218 return;
1219 };
1220
1221 let resolve_task = provider.resolve_completions(
1222 self.buffer.clone(),
1223 vec![completion_index],
1224 self.completions.clone(),
1225 cx,
1226 );
1227
1228 let delay_ms =
1229 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1230 let delay = Duration::from_millis(delay_ms);
1231
1232 documentation_resolve.lock().fire_new(delay, cx, |_, cx| {
1233 cx.spawn(move |this, mut cx| async move {
1234 if let Some(true) = resolve_task.await.log_err() {
1235 this.update(&mut cx, |_, cx| cx.notify()).ok();
1236 }
1237 })
1238 });
1239 }
1240
1241 fn visible(&self) -> bool {
1242 !self.matches.is_empty()
1243 }
1244
1245 fn render(
1246 &self,
1247 style: &EditorStyle,
1248 max_height: Pixels,
1249 workspace: Option<WeakView<Workspace>>,
1250 cx: &mut ViewContext<Editor>,
1251 ) -> AnyElement {
1252 let settings = EditorSettings::get_global(cx);
1253 let show_completion_documentation = settings.show_completion_documentation;
1254
1255 let widest_completion_ix = self
1256 .matches
1257 .iter()
1258 .enumerate()
1259 .max_by_key(|(_, mat)| {
1260 let completions = self.completions.read();
1261 let completion = &completions[mat.candidate_id];
1262 let documentation = &completion.documentation;
1263
1264 let mut len = completion.label.text.chars().count();
1265 if let Some(Documentation::SingleLine(text)) = documentation {
1266 if show_completion_documentation {
1267 len += text.chars().count();
1268 }
1269 }
1270
1271 len
1272 })
1273 .map(|(ix, _)| ix);
1274
1275 let completions = self.completions.clone();
1276 let matches = self.matches.clone();
1277 let selected_item = self.selected_item;
1278 let style = style.clone();
1279
1280 let multiline_docs = if show_completion_documentation {
1281 let mat = &self.matches[selected_item];
1282 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1283 Some(Documentation::MultiLinePlainText(text)) => {
1284 Some(div().child(SharedString::from(text.clone())))
1285 }
1286 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1287 Some(div().child(render_parsed_markdown(
1288 "completions_markdown",
1289 parsed,
1290 &style,
1291 workspace,
1292 cx,
1293 )))
1294 }
1295 _ => None,
1296 };
1297 multiline_docs.map(|div| {
1298 div.id("multiline_docs")
1299 .max_h(max_height)
1300 .flex_1()
1301 .px_1p5()
1302 .py_1()
1303 .min_w(px(260.))
1304 .max_w(px(640.))
1305 .w(px(500.))
1306 .overflow_y_scroll()
1307 .occlude()
1308 })
1309 } else {
1310 None
1311 };
1312
1313 let list = uniform_list(
1314 cx.view().clone(),
1315 "completions",
1316 matches.len(),
1317 move |_editor, range, cx| {
1318 let start_ix = range.start;
1319 let completions_guard = completions.read();
1320
1321 matches[range]
1322 .iter()
1323 .enumerate()
1324 .map(|(ix, mat)| {
1325 let item_ix = start_ix + ix;
1326 let candidate_id = mat.candidate_id;
1327 let completion = &completions_guard[candidate_id];
1328
1329 let documentation = if show_completion_documentation {
1330 &completion.documentation
1331 } else {
1332 &None
1333 };
1334
1335 let highlights = gpui::combine_highlights(
1336 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1337 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1338 |(range, mut highlight)| {
1339 // Ignore font weight for syntax highlighting, as we'll use it
1340 // for fuzzy matches.
1341 highlight.font_weight = None;
1342
1343 if completion.lsp_completion.deprecated.unwrap_or(false) {
1344 highlight.strikethrough = Some(StrikethroughStyle {
1345 thickness: 1.0.into(),
1346 ..Default::default()
1347 });
1348 highlight.color = Some(cx.theme().colors().text_muted);
1349 }
1350
1351 (range, highlight)
1352 },
1353 ),
1354 );
1355 let completion_label = StyledText::new(completion.label.text.clone())
1356 .with_highlights(&style.text, highlights);
1357 let documentation_label =
1358 if let Some(Documentation::SingleLine(text)) = documentation {
1359 if text.trim().is_empty() {
1360 None
1361 } else {
1362 Some(
1363 Label::new(text.clone())
1364 .ml_4()
1365 .size(LabelSize::Small)
1366 .color(Color::Muted),
1367 )
1368 }
1369 } else {
1370 None
1371 };
1372
1373 let color_swatch = completion
1374 .color()
1375 .map(|color| div().size_4().bg(color).rounded_sm());
1376
1377 div().min_w(px(220.)).max_w(px(540.)).child(
1378 ListItem::new(mat.candidate_id)
1379 .inset(true)
1380 .selected(item_ix == selected_item)
1381 .on_click(cx.listener(move |editor, _event, cx| {
1382 cx.stop_propagation();
1383 if let Some(task) = editor.confirm_completion(
1384 &ConfirmCompletion {
1385 item_ix: Some(item_ix),
1386 },
1387 cx,
1388 ) {
1389 task.detach_and_log_err(cx)
1390 }
1391 }))
1392 .start_slot::<Div>(color_swatch)
1393 .child(h_flex().overflow_hidden().child(completion_label))
1394 .end_slot::<Label>(documentation_label),
1395 )
1396 })
1397 .collect()
1398 },
1399 )
1400 .occlude()
1401 .max_h(max_height)
1402 .track_scroll(self.scroll_handle.clone())
1403 .with_width_from_item(widest_completion_ix)
1404 .with_sizing_behavior(ListSizingBehavior::Infer);
1405
1406 Popover::new()
1407 .child(list)
1408 .when_some(multiline_docs, |popover, multiline_docs| {
1409 popover.aside(multiline_docs)
1410 })
1411 .into_any_element()
1412 }
1413
1414 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1415 let mut matches = if let Some(query) = query {
1416 fuzzy::match_strings(
1417 &self.match_candidates,
1418 query,
1419 query.chars().any(|c| c.is_uppercase()),
1420 100,
1421 &Default::default(),
1422 executor,
1423 )
1424 .await
1425 } else {
1426 self.match_candidates
1427 .iter()
1428 .enumerate()
1429 .map(|(candidate_id, candidate)| StringMatch {
1430 candidate_id,
1431 score: Default::default(),
1432 positions: Default::default(),
1433 string: candidate.string.clone(),
1434 })
1435 .collect()
1436 };
1437
1438 // Remove all candidates where the query's start does not match the start of any word in the candidate
1439 if let Some(query) = query {
1440 if let Some(query_start) = query.chars().next() {
1441 matches.retain(|string_match| {
1442 split_words(&string_match.string).any(|word| {
1443 // Check that the first codepoint of the word as lowercase matches the first
1444 // codepoint of the query as lowercase
1445 word.chars()
1446 .flat_map(|codepoint| codepoint.to_lowercase())
1447 .zip(query_start.to_lowercase())
1448 .all(|(word_cp, query_cp)| word_cp == query_cp)
1449 })
1450 });
1451 }
1452 }
1453
1454 let completions = self.completions.read();
1455 if self.sort_completions {
1456 matches.sort_unstable_by_key(|mat| {
1457 // We do want to strike a balance here between what the language server tells us
1458 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1459 // `Creat` and there is a local variable called `CreateComponent`).
1460 // So what we do is: we bucket all matches into two buckets
1461 // - Strong matches
1462 // - Weak matches
1463 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1464 // and the Weak matches are the rest.
1465 //
1466 // For the strong matches, we sort by our fuzzy-finder score first and for the weak
1467 // matches, we prefer language-server sort_text first.
1468 //
1469 // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
1470 // Rest of the matches(weak) can be sorted as language-server expects.
1471
1472 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1473 enum MatchScore<'a> {
1474 Strong {
1475 score: Reverse<OrderedFloat<f64>>,
1476 sort_text: Option<&'a str>,
1477 sort_key: (usize, &'a str),
1478 },
1479 Weak {
1480 sort_text: Option<&'a str>,
1481 score: Reverse<OrderedFloat<f64>>,
1482 sort_key: (usize, &'a str),
1483 },
1484 }
1485
1486 let completion = &completions[mat.candidate_id];
1487 let sort_key = completion.sort_key();
1488 let sort_text = completion.lsp_completion.sort_text.as_deref();
1489 let score = Reverse(OrderedFloat(mat.score));
1490
1491 if mat.score >= 0.2 {
1492 MatchScore::Strong {
1493 score,
1494 sort_text,
1495 sort_key,
1496 }
1497 } else {
1498 MatchScore::Weak {
1499 sort_text,
1500 score,
1501 sort_key,
1502 }
1503 }
1504 });
1505 }
1506
1507 for mat in &mut matches {
1508 let completion = &completions[mat.candidate_id];
1509 mat.string.clone_from(&completion.label.text);
1510 for position in &mut mat.positions {
1511 *position += completion.label.filter_range.start;
1512 }
1513 }
1514 drop(completions);
1515
1516 self.matches = matches.into();
1517 self.selected_item = 0;
1518 }
1519}
1520
1521#[derive(Clone)]
1522struct AvailableCodeAction {
1523 excerpt_id: ExcerptId,
1524 action: CodeAction,
1525 provider: Arc<dyn CodeActionProvider>,
1526}
1527
1528#[derive(Clone)]
1529struct CodeActionContents {
1530 tasks: Option<Arc<ResolvedTasks>>,
1531 actions: Option<Arc<[AvailableCodeAction]>>,
1532}
1533
1534impl CodeActionContents {
1535 fn len(&self) -> usize {
1536 match (&self.tasks, &self.actions) {
1537 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1538 (Some(tasks), None) => tasks.templates.len(),
1539 (None, Some(actions)) => actions.len(),
1540 (None, None) => 0,
1541 }
1542 }
1543
1544 fn is_empty(&self) -> bool {
1545 match (&self.tasks, &self.actions) {
1546 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1547 (Some(tasks), None) => tasks.templates.is_empty(),
1548 (None, Some(actions)) => actions.is_empty(),
1549 (None, None) => true,
1550 }
1551 }
1552
1553 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1554 self.tasks
1555 .iter()
1556 .flat_map(|tasks| {
1557 tasks
1558 .templates
1559 .iter()
1560 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1561 })
1562 .chain(self.actions.iter().flat_map(|actions| {
1563 actions.iter().map(|available| CodeActionsItem::CodeAction {
1564 excerpt_id: available.excerpt_id,
1565 action: available.action.clone(),
1566 provider: available.provider.clone(),
1567 })
1568 }))
1569 }
1570 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1571 match (&self.tasks, &self.actions) {
1572 (Some(tasks), Some(actions)) => {
1573 if index < tasks.templates.len() {
1574 tasks
1575 .templates
1576 .get(index)
1577 .cloned()
1578 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1579 } else {
1580 actions.get(index - tasks.templates.len()).map(|available| {
1581 CodeActionsItem::CodeAction {
1582 excerpt_id: available.excerpt_id,
1583 action: available.action.clone(),
1584 provider: available.provider.clone(),
1585 }
1586 })
1587 }
1588 }
1589 (Some(tasks), None) => tasks
1590 .templates
1591 .get(index)
1592 .cloned()
1593 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1594 (None, Some(actions)) => {
1595 actions
1596 .get(index)
1597 .map(|available| CodeActionsItem::CodeAction {
1598 excerpt_id: available.excerpt_id,
1599 action: available.action.clone(),
1600 provider: available.provider.clone(),
1601 })
1602 }
1603 (None, None) => None,
1604 }
1605 }
1606}
1607
1608#[allow(clippy::large_enum_variant)]
1609#[derive(Clone)]
1610enum CodeActionsItem {
1611 Task(TaskSourceKind, ResolvedTask),
1612 CodeAction {
1613 excerpt_id: ExcerptId,
1614 action: CodeAction,
1615 provider: Arc<dyn CodeActionProvider>,
1616 },
1617}
1618
1619impl CodeActionsItem {
1620 fn as_task(&self) -> Option<&ResolvedTask> {
1621 let Self::Task(_, task) = self else {
1622 return None;
1623 };
1624 Some(task)
1625 }
1626 fn as_code_action(&self) -> Option<&CodeAction> {
1627 let Self::CodeAction { action, .. } = self else {
1628 return None;
1629 };
1630 Some(action)
1631 }
1632 fn label(&self) -> String {
1633 match self {
1634 Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
1635 Self::Task(_, task) => task.resolved_label.clone(),
1636 }
1637 }
1638}
1639
1640struct CodeActionsMenu {
1641 actions: CodeActionContents,
1642 buffer: Model<Buffer>,
1643 selected_item: usize,
1644 scroll_handle: UniformListScrollHandle,
1645 deployed_from_indicator: Option<DisplayRow>,
1646}
1647
1648impl CodeActionsMenu {
1649 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1650 self.selected_item = 0;
1651 self.scroll_handle
1652 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1653 cx.notify()
1654 }
1655
1656 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1657 if self.selected_item > 0 {
1658 self.selected_item -= 1;
1659 } else {
1660 self.selected_item = self.actions.len() - 1;
1661 }
1662 self.scroll_handle
1663 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1664 cx.notify();
1665 }
1666
1667 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1668 if self.selected_item + 1 < self.actions.len() {
1669 self.selected_item += 1;
1670 } else {
1671 self.selected_item = 0;
1672 }
1673 self.scroll_handle
1674 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1675 cx.notify();
1676 }
1677
1678 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1679 self.selected_item = self.actions.len() - 1;
1680 self.scroll_handle
1681 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1682 cx.notify()
1683 }
1684
1685 fn visible(&self) -> bool {
1686 !self.actions.is_empty()
1687 }
1688
1689 fn render(
1690 &self,
1691 cursor_position: DisplayPoint,
1692 _style: &EditorStyle,
1693 max_height: Pixels,
1694 cx: &mut ViewContext<Editor>,
1695 ) -> (ContextMenuOrigin, AnyElement) {
1696 let actions = self.actions.clone();
1697 let selected_item = self.selected_item;
1698 let element = uniform_list(
1699 cx.view().clone(),
1700 "code_actions_menu",
1701 self.actions.len(),
1702 move |_this, range, cx| {
1703 actions
1704 .iter()
1705 .skip(range.start)
1706 .take(range.end - range.start)
1707 .enumerate()
1708 .map(|(ix, action)| {
1709 let item_ix = range.start + ix;
1710 let selected = selected_item == item_ix;
1711 let colors = cx.theme().colors();
1712 div()
1713 .px_1()
1714 .rounded_md()
1715 .text_color(colors.text)
1716 .when(selected, |style| {
1717 style
1718 .bg(colors.element_active)
1719 .text_color(colors.text_accent)
1720 })
1721 .hover(|style| {
1722 style
1723 .bg(colors.element_hover)
1724 .text_color(colors.text_accent)
1725 })
1726 .whitespace_nowrap()
1727 .when_some(action.as_code_action(), |this, action| {
1728 this.on_mouse_down(
1729 MouseButton::Left,
1730 cx.listener(move |editor, _, cx| {
1731 cx.stop_propagation();
1732 if let Some(task) = editor.confirm_code_action(
1733 &ConfirmCodeAction {
1734 item_ix: Some(item_ix),
1735 },
1736 cx,
1737 ) {
1738 task.detach_and_log_err(cx)
1739 }
1740 }),
1741 )
1742 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1743 .child(SharedString::from(action.lsp_action.title.clone()))
1744 })
1745 .when_some(action.as_task(), |this, task| {
1746 this.on_mouse_down(
1747 MouseButton::Left,
1748 cx.listener(move |editor, _, cx| {
1749 cx.stop_propagation();
1750 if let Some(task) = editor.confirm_code_action(
1751 &ConfirmCodeAction {
1752 item_ix: Some(item_ix),
1753 },
1754 cx,
1755 ) {
1756 task.detach_and_log_err(cx)
1757 }
1758 }),
1759 )
1760 .child(SharedString::from(task.resolved_label.clone()))
1761 })
1762 })
1763 .collect()
1764 },
1765 )
1766 .elevation_1(cx)
1767 .p_1()
1768 .max_h(max_height)
1769 .occlude()
1770 .track_scroll(self.scroll_handle.clone())
1771 .with_width_from_item(
1772 self.actions
1773 .iter()
1774 .enumerate()
1775 .max_by_key(|(_, action)| match action {
1776 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1777 CodeActionsItem::CodeAction { action, .. } => {
1778 action.lsp_action.title.chars().count()
1779 }
1780 })
1781 .map(|(ix, _)| ix),
1782 )
1783 .with_sizing_behavior(ListSizingBehavior::Infer)
1784 .into_any_element();
1785
1786 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1787 ContextMenuOrigin::GutterIndicator(row)
1788 } else {
1789 ContextMenuOrigin::EditorPoint(cursor_position)
1790 };
1791
1792 (cursor_position, element)
1793 }
1794}
1795
1796#[derive(Debug)]
1797struct ActiveDiagnosticGroup {
1798 primary_range: Range<Anchor>,
1799 primary_message: String,
1800 group_id: usize,
1801 blocks: HashMap<CustomBlockId, Diagnostic>,
1802 is_valid: bool,
1803}
1804
1805#[derive(Serialize, Deserialize, Clone, Debug)]
1806pub struct ClipboardSelection {
1807 pub len: usize,
1808 pub is_entire_line: bool,
1809 pub first_line_indent: u32,
1810}
1811
1812#[derive(Debug)]
1813pub(crate) struct NavigationData {
1814 cursor_anchor: Anchor,
1815 cursor_position: Point,
1816 scroll_anchor: ScrollAnchor,
1817 scroll_top_row: u32,
1818}
1819
1820#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1821pub enum GotoDefinitionKind {
1822 Symbol,
1823 Declaration,
1824 Type,
1825 Implementation,
1826}
1827
1828#[derive(Debug, Clone)]
1829enum InlayHintRefreshReason {
1830 Toggle(bool),
1831 SettingsChange(InlayHintSettings),
1832 NewLinesShown,
1833 BufferEdited(HashSet<Arc<Language>>),
1834 RefreshRequested,
1835 ExcerptsRemoved(Vec<ExcerptId>),
1836}
1837
1838impl InlayHintRefreshReason {
1839 fn description(&self) -> &'static str {
1840 match self {
1841 Self::Toggle(_) => "toggle",
1842 Self::SettingsChange(_) => "settings change",
1843 Self::NewLinesShown => "new lines shown",
1844 Self::BufferEdited(_) => "buffer edited",
1845 Self::RefreshRequested => "refresh requested",
1846 Self::ExcerptsRemoved(_) => "excerpts removed",
1847 }
1848 }
1849}
1850
1851pub(crate) struct FocusedBlock {
1852 id: BlockId,
1853 focus_handle: WeakFocusHandle,
1854}
1855
1856#[derive(Clone)]
1857struct JumpData {
1858 excerpt_id: ExcerptId,
1859 position: Point,
1860 anchor: text::Anchor,
1861 path: Option<project::ProjectPath>,
1862 line_offset_from_top: u32,
1863}
1864
1865impl Editor {
1866 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1867 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1868 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1869 Self::new(
1870 EditorMode::SingleLine { auto_width: false },
1871 buffer,
1872 None,
1873 false,
1874 cx,
1875 )
1876 }
1877
1878 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1879 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1880 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1881 Self::new(EditorMode::Full, buffer, None, false, cx)
1882 }
1883
1884 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1885 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1886 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1887 Self::new(
1888 EditorMode::SingleLine { auto_width: true },
1889 buffer,
1890 None,
1891 false,
1892 cx,
1893 )
1894 }
1895
1896 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1897 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1898 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1899 Self::new(
1900 EditorMode::AutoHeight { max_lines },
1901 buffer,
1902 None,
1903 false,
1904 cx,
1905 )
1906 }
1907
1908 pub fn for_buffer(
1909 buffer: Model<Buffer>,
1910 project: Option<Model<Project>>,
1911 cx: &mut ViewContext<Self>,
1912 ) -> Self {
1913 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1914 Self::new(EditorMode::Full, buffer, project, false, cx)
1915 }
1916
1917 pub fn for_multibuffer(
1918 buffer: Model<MultiBuffer>,
1919 project: Option<Model<Project>>,
1920 show_excerpt_controls: bool,
1921 cx: &mut ViewContext<Self>,
1922 ) -> Self {
1923 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1924 }
1925
1926 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1927 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1928 let mut clone = Self::new(
1929 self.mode,
1930 self.buffer.clone(),
1931 self.project.clone(),
1932 show_excerpt_controls,
1933 cx,
1934 );
1935 self.display_map.update(cx, |display_map, cx| {
1936 let snapshot = display_map.snapshot(cx);
1937 clone.display_map.update(cx, |display_map, cx| {
1938 display_map.set_state(&snapshot, cx);
1939 });
1940 });
1941 clone.selections.clone_state(&self.selections);
1942 clone.scroll_manager.clone_state(&self.scroll_manager);
1943 clone.searchable = self.searchable;
1944 clone
1945 }
1946
1947 pub fn new(
1948 mode: EditorMode,
1949 buffer: Model<MultiBuffer>,
1950 project: Option<Model<Project>>,
1951 show_excerpt_controls: bool,
1952 cx: &mut ViewContext<Self>,
1953 ) -> Self {
1954 let style = cx.text_style();
1955 let font_size = style.font_size.to_pixels(cx.rem_size());
1956 let editor = cx.view().downgrade();
1957 let fold_placeholder = FoldPlaceholder {
1958 constrain_width: true,
1959 render: Arc::new(move |fold_id, fold_range, cx| {
1960 let editor = editor.clone();
1961 div()
1962 .id(fold_id)
1963 .bg(cx.theme().colors().ghost_element_background)
1964 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1965 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1966 .rounded_sm()
1967 .size_full()
1968 .cursor_pointer()
1969 .child("⋯")
1970 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1971 .on_click(move |_, cx| {
1972 editor
1973 .update(cx, |editor, cx| {
1974 editor.unfold_ranges(
1975 &[fold_range.start..fold_range.end],
1976 true,
1977 false,
1978 cx,
1979 );
1980 cx.stop_propagation();
1981 })
1982 .ok();
1983 })
1984 .into_any()
1985 }),
1986 merge_adjacent: true,
1987 ..Default::default()
1988 };
1989 let display_map = cx.new_model(|cx| {
1990 DisplayMap::new(
1991 buffer.clone(),
1992 style.font(),
1993 font_size,
1994 None,
1995 show_excerpt_controls,
1996 FILE_HEADER_HEIGHT,
1997 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1998 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1999 fold_placeholder,
2000 cx,
2001 )
2002 });
2003
2004 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
2005
2006 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
2007
2008 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
2009 .then(|| language_settings::SoftWrap::None);
2010
2011 let mut project_subscriptions = Vec::new();
2012 if mode == EditorMode::Full {
2013 if let Some(project) = project.as_ref() {
2014 if buffer.read(cx).is_singleton() {
2015 project_subscriptions.push(cx.observe(project, |_, _, cx| {
2016 cx.emit(EditorEvent::TitleChanged);
2017 }));
2018 }
2019 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
2020 if let project::Event::RefreshInlayHints = event {
2021 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
2022 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
2023 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
2024 let focus_handle = editor.focus_handle(cx);
2025 if focus_handle.is_focused(cx) {
2026 let snapshot = buffer.read(cx).snapshot();
2027 for (range, snippet) in snippet_edits {
2028 let editor_range =
2029 language::range_from_lsp(*range).to_offset(&snapshot);
2030 editor
2031 .insert_snippet(&[editor_range], snippet.clone(), cx)
2032 .ok();
2033 }
2034 }
2035 }
2036 }
2037 }));
2038 if let Some(task_inventory) = project
2039 .read(cx)
2040 .task_store()
2041 .read(cx)
2042 .task_inventory()
2043 .cloned()
2044 {
2045 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
2046 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
2047 }));
2048 }
2049 }
2050 }
2051
2052 let inlay_hint_settings = inlay_hint_settings(
2053 selections.newest_anchor().head(),
2054 &buffer.read(cx).snapshot(cx),
2055 cx,
2056 );
2057 let focus_handle = cx.focus_handle();
2058 cx.on_focus(&focus_handle, Self::handle_focus).detach();
2059 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
2060 .detach();
2061 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
2062 .detach();
2063 cx.on_blur(&focus_handle, Self::handle_blur).detach();
2064
2065 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
2066 Some(false)
2067 } else {
2068 None
2069 };
2070
2071 let mut code_action_providers = Vec::new();
2072 if let Some(project) = project.clone() {
2073 code_action_providers.push(Arc::new(project) as Arc<_>);
2074 }
2075
2076 let mut this = Self {
2077 focus_handle,
2078 show_cursor_when_unfocused: false,
2079 last_focused_descendant: None,
2080 buffer: buffer.clone(),
2081 display_map: display_map.clone(),
2082 selections,
2083 scroll_manager: ScrollManager::new(cx),
2084 columnar_selection_tail: None,
2085 add_selections_state: None,
2086 select_next_state: None,
2087 select_prev_state: None,
2088 selection_history: Default::default(),
2089 autoclose_regions: Default::default(),
2090 snippet_stack: Default::default(),
2091 select_larger_syntax_node_stack: Vec::new(),
2092 ime_transaction: Default::default(),
2093 active_diagnostics: None,
2094 soft_wrap_mode_override,
2095 completion_provider: project.clone().map(|project| Box::new(project) as _),
2096 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
2097 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
2098 project,
2099 blink_manager: blink_manager.clone(),
2100 show_local_selections: true,
2101 mode,
2102 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
2103 show_gutter: mode == EditorMode::Full,
2104 show_line_numbers: None,
2105 use_relative_line_numbers: None,
2106 show_git_diff_gutter: None,
2107 show_code_actions: None,
2108 show_runnables: None,
2109 show_wrap_guides: None,
2110 show_indent_guides,
2111 placeholder_text: None,
2112 highlight_order: 0,
2113 highlighted_rows: HashMap::default(),
2114 background_highlights: Default::default(),
2115 gutter_highlights: TreeMap::default(),
2116 scrollbar_marker_state: ScrollbarMarkerState::default(),
2117 active_indent_guides_state: ActiveIndentGuidesState::default(),
2118 nav_history: None,
2119 context_menu: RwLock::new(None),
2120 mouse_context_menu: None,
2121 hunk_controls_menu_handle: PopoverMenuHandle::default(),
2122 completion_tasks: Default::default(),
2123 signature_help_state: SignatureHelpState::default(),
2124 auto_signature_help: None,
2125 find_all_references_task_sources: Vec::new(),
2126 next_completion_id: 0,
2127 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
2128 next_inlay_id: 0,
2129 code_action_providers,
2130 available_code_actions: Default::default(),
2131 code_actions_task: Default::default(),
2132 document_highlights_task: Default::default(),
2133 linked_editing_range_task: Default::default(),
2134 pending_rename: Default::default(),
2135 searchable: true,
2136 cursor_shape: EditorSettings::get_global(cx)
2137 .cursor_shape
2138 .unwrap_or_default(),
2139 current_line_highlight: None,
2140 autoindent_mode: Some(AutoindentMode::EachLine),
2141 collapse_matches: false,
2142 workspace: None,
2143 input_enabled: true,
2144 use_modal_editing: mode == EditorMode::Full,
2145 read_only: false,
2146 use_autoclose: true,
2147 use_auto_surround: true,
2148 auto_replace_emoji_shortcode: false,
2149 leader_peer_id: None,
2150 remote_id: None,
2151 hover_state: Default::default(),
2152 hovered_link_state: Default::default(),
2153 inline_completion_provider: None,
2154 active_inline_completion: None,
2155 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
2156 expanded_hunks: ExpandedHunks::default(),
2157 gutter_hovered: false,
2158 pixel_position_of_newest_cursor: None,
2159 last_bounds: None,
2160 expect_bounds_change: None,
2161 gutter_dimensions: GutterDimensions::default(),
2162 style: None,
2163 show_cursor_names: false,
2164 hovered_cursors: Default::default(),
2165 next_editor_action_id: EditorActionId::default(),
2166 editor_actions: Rc::default(),
2167 show_inline_completions_override: None,
2168 enable_inline_completions: true,
2169 custom_context_menu: None,
2170 show_git_blame_gutter: false,
2171 show_git_blame_inline: false,
2172 show_selection_menu: None,
2173 show_git_blame_inline_delay_task: None,
2174 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
2175 serialize_dirty_buffers: ProjectSettings::get_global(cx)
2176 .session
2177 .restore_unsaved_buffers,
2178 blame: None,
2179 blame_subscription: None,
2180 tasks: Default::default(),
2181 _subscriptions: vec![
2182 cx.observe(&buffer, Self::on_buffer_changed),
2183 cx.subscribe(&buffer, Self::on_buffer_event),
2184 cx.observe(&display_map, Self::on_display_map_changed),
2185 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
2186 cx.observe_global::<SettingsStore>(Self::settings_changed),
2187 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
2188 cx.observe_window_activation(|editor, cx| {
2189 let active = cx.is_window_active();
2190 editor.blink_manager.update(cx, |blink_manager, cx| {
2191 if active {
2192 blink_manager.enable(cx);
2193 } else {
2194 blink_manager.disable(cx);
2195 }
2196 });
2197 }),
2198 ],
2199 tasks_update_task: None,
2200 linked_edit_ranges: Default::default(),
2201 previous_search_ranges: None,
2202 breadcrumb_header: None,
2203 focused_block: None,
2204 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
2205 addons: HashMap::default(),
2206 _scroll_cursor_center_top_bottom_task: Task::ready(()),
2207 text_style_refinement: None,
2208 };
2209 this.tasks_update_task = Some(this.refresh_runnables(cx));
2210 this._subscriptions.extend(project_subscriptions);
2211
2212 this.end_selection(cx);
2213 this.scroll_manager.show_scrollbar(cx);
2214
2215 if mode == EditorMode::Full {
2216 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
2217 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2218
2219 if this.git_blame_inline_enabled {
2220 this.git_blame_inline_enabled = true;
2221 this.start_git_blame_inline(false, cx);
2222 }
2223 }
2224
2225 this.report_editor_event("open", None, cx);
2226 this
2227 }
2228
2229 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
2230 self.mouse_context_menu
2231 .as_ref()
2232 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
2233 }
2234
2235 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
2236 let mut key_context = KeyContext::new_with_defaults();
2237 key_context.add("Editor");
2238 let mode = match self.mode {
2239 EditorMode::SingleLine { .. } => "single_line",
2240 EditorMode::AutoHeight { .. } => "auto_height",
2241 EditorMode::Full => "full",
2242 };
2243
2244 if EditorSettings::jupyter_enabled(cx) {
2245 key_context.add("jupyter");
2246 }
2247
2248 key_context.set("mode", mode);
2249 if self.pending_rename.is_some() {
2250 key_context.add("renaming");
2251 }
2252 if self.context_menu_visible() {
2253 match self.context_menu.read().as_ref() {
2254 Some(ContextMenu::Completions(_)) => {
2255 key_context.add("menu");
2256 key_context.add("showing_completions")
2257 }
2258 Some(ContextMenu::CodeActions(_)) => {
2259 key_context.add("menu");
2260 key_context.add("showing_code_actions")
2261 }
2262 None => {}
2263 }
2264 }
2265
2266 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2267 if !self.focus_handle(cx).contains_focused(cx)
2268 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2269 {
2270 for addon in self.addons.values() {
2271 addon.extend_key_context(&mut key_context, cx)
2272 }
2273 }
2274
2275 if let Some(extension) = self
2276 .buffer
2277 .read(cx)
2278 .as_singleton()
2279 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2280 {
2281 key_context.set("extension", extension.to_string());
2282 }
2283
2284 if self.has_active_inline_completion(cx) {
2285 key_context.add("copilot_suggestion");
2286 key_context.add("inline_completion");
2287 }
2288
2289 key_context
2290 }
2291
2292 pub fn new_file(
2293 workspace: &mut Workspace,
2294 _: &workspace::NewFile,
2295 cx: &mut ViewContext<Workspace>,
2296 ) {
2297 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2298 "Failed to create buffer",
2299 cx,
2300 |e, _| match e.error_code() {
2301 ErrorCode::RemoteUpgradeRequired => Some(format!(
2302 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2303 e.error_tag("required").unwrap_or("the latest version")
2304 )),
2305 _ => None,
2306 },
2307 );
2308 }
2309
2310 pub fn new_in_workspace(
2311 workspace: &mut Workspace,
2312 cx: &mut ViewContext<Workspace>,
2313 ) -> Task<Result<View<Editor>>> {
2314 let project = workspace.project().clone();
2315 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2316
2317 cx.spawn(|workspace, mut cx| async move {
2318 let buffer = create.await?;
2319 workspace.update(&mut cx, |workspace, cx| {
2320 let editor =
2321 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2322 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2323 editor
2324 })
2325 })
2326 }
2327
2328 fn new_file_vertical(
2329 workspace: &mut Workspace,
2330 _: &workspace::NewFileSplitVertical,
2331 cx: &mut ViewContext<Workspace>,
2332 ) {
2333 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2334 }
2335
2336 fn new_file_horizontal(
2337 workspace: &mut Workspace,
2338 _: &workspace::NewFileSplitHorizontal,
2339 cx: &mut ViewContext<Workspace>,
2340 ) {
2341 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2342 }
2343
2344 fn new_file_in_direction(
2345 workspace: &mut Workspace,
2346 direction: SplitDirection,
2347 cx: &mut ViewContext<Workspace>,
2348 ) {
2349 let project = workspace.project().clone();
2350 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2351
2352 cx.spawn(|workspace, mut cx| async move {
2353 let buffer = create.await?;
2354 workspace.update(&mut cx, move |workspace, cx| {
2355 workspace.split_item(
2356 direction,
2357 Box::new(
2358 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2359 ),
2360 cx,
2361 )
2362 })?;
2363 anyhow::Ok(())
2364 })
2365 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2366 ErrorCode::RemoteUpgradeRequired => Some(format!(
2367 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2368 e.error_tag("required").unwrap_or("the latest version")
2369 )),
2370 _ => None,
2371 });
2372 }
2373
2374 pub fn leader_peer_id(&self) -> Option<PeerId> {
2375 self.leader_peer_id
2376 }
2377
2378 pub fn buffer(&self) -> &Model<MultiBuffer> {
2379 &self.buffer
2380 }
2381
2382 pub fn workspace(&self) -> Option<View<Workspace>> {
2383 self.workspace.as_ref()?.0.upgrade()
2384 }
2385
2386 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2387 self.buffer().read(cx).title(cx)
2388 }
2389
2390 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2391 let git_blame_gutter_max_author_length = self
2392 .render_git_blame_gutter(cx)
2393 .then(|| {
2394 if let Some(blame) = self.blame.as_ref() {
2395 let max_author_length =
2396 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2397 Some(max_author_length)
2398 } else {
2399 None
2400 }
2401 })
2402 .flatten();
2403
2404 EditorSnapshot {
2405 mode: self.mode,
2406 show_gutter: self.show_gutter,
2407 show_line_numbers: self.show_line_numbers,
2408 show_git_diff_gutter: self.show_git_diff_gutter,
2409 show_code_actions: self.show_code_actions,
2410 show_runnables: self.show_runnables,
2411 git_blame_gutter_max_author_length,
2412 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2413 scroll_anchor: self.scroll_manager.anchor(),
2414 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2415 placeholder_text: self.placeholder_text.clone(),
2416 is_focused: self.focus_handle.is_focused(cx),
2417 current_line_highlight: self
2418 .current_line_highlight
2419 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2420 gutter_hovered: self.gutter_hovered,
2421 }
2422 }
2423
2424 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2425 self.buffer.read(cx).language_at(point, cx)
2426 }
2427
2428 pub fn file_at<T: ToOffset>(
2429 &self,
2430 point: T,
2431 cx: &AppContext,
2432 ) -> Option<Arc<dyn language::File>> {
2433 self.buffer.read(cx).read(cx).file_at(point).cloned()
2434 }
2435
2436 pub fn active_excerpt(
2437 &self,
2438 cx: &AppContext,
2439 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2440 self.buffer
2441 .read(cx)
2442 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2443 }
2444
2445 pub fn mode(&self) -> EditorMode {
2446 self.mode
2447 }
2448
2449 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2450 self.collaboration_hub.as_deref()
2451 }
2452
2453 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2454 self.collaboration_hub = Some(hub);
2455 }
2456
2457 pub fn set_custom_context_menu(
2458 &mut self,
2459 f: impl 'static
2460 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2461 ) {
2462 self.custom_context_menu = Some(Box::new(f))
2463 }
2464
2465 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2466 self.completion_provider = provider;
2467 }
2468
2469 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2470 self.semantics_provider.clone()
2471 }
2472
2473 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2474 self.semantics_provider = provider;
2475 }
2476
2477 pub fn set_inline_completion_provider<T>(
2478 &mut self,
2479 provider: Option<Model<T>>,
2480 cx: &mut ViewContext<Self>,
2481 ) where
2482 T: InlineCompletionProvider,
2483 {
2484 self.inline_completion_provider =
2485 provider.map(|provider| RegisteredInlineCompletionProvider {
2486 _subscription: cx.observe(&provider, |this, _, cx| {
2487 if this.focus_handle.is_focused(cx) {
2488 this.update_visible_inline_completion(cx);
2489 }
2490 }),
2491 provider: Arc::new(provider),
2492 });
2493 self.refresh_inline_completion(false, false, cx);
2494 }
2495
2496 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2497 self.placeholder_text.as_deref()
2498 }
2499
2500 pub fn set_placeholder_text(
2501 &mut self,
2502 placeholder_text: impl Into<Arc<str>>,
2503 cx: &mut ViewContext<Self>,
2504 ) {
2505 let placeholder_text = Some(placeholder_text.into());
2506 if self.placeholder_text != placeholder_text {
2507 self.placeholder_text = placeholder_text;
2508 cx.notify();
2509 }
2510 }
2511
2512 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2513 self.cursor_shape = cursor_shape;
2514
2515 // Disrupt blink for immediate user feedback that the cursor shape has changed
2516 self.blink_manager.update(cx, BlinkManager::show_cursor);
2517
2518 cx.notify();
2519 }
2520
2521 pub fn set_current_line_highlight(
2522 &mut self,
2523 current_line_highlight: Option<CurrentLineHighlight>,
2524 ) {
2525 self.current_line_highlight = current_line_highlight;
2526 }
2527
2528 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2529 self.collapse_matches = collapse_matches;
2530 }
2531
2532 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2533 if self.collapse_matches {
2534 return range.start..range.start;
2535 }
2536 range.clone()
2537 }
2538
2539 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2540 if self.display_map.read(cx).clip_at_line_ends != clip {
2541 self.display_map
2542 .update(cx, |map, _| map.clip_at_line_ends = clip);
2543 }
2544 }
2545
2546 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2547 self.input_enabled = input_enabled;
2548 }
2549
2550 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2551 self.enable_inline_completions = enabled;
2552 }
2553
2554 pub fn set_autoindent(&mut self, autoindent: bool) {
2555 if autoindent {
2556 self.autoindent_mode = Some(AutoindentMode::EachLine);
2557 } else {
2558 self.autoindent_mode = None;
2559 }
2560 }
2561
2562 pub fn read_only(&self, cx: &AppContext) -> bool {
2563 self.read_only || self.buffer.read(cx).read_only()
2564 }
2565
2566 pub fn set_read_only(&mut self, read_only: bool) {
2567 self.read_only = read_only;
2568 }
2569
2570 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2571 self.use_autoclose = autoclose;
2572 }
2573
2574 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2575 self.use_auto_surround = auto_surround;
2576 }
2577
2578 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2579 self.auto_replace_emoji_shortcode = auto_replace;
2580 }
2581
2582 pub fn toggle_inline_completions(
2583 &mut self,
2584 _: &ToggleInlineCompletions,
2585 cx: &mut ViewContext<Self>,
2586 ) {
2587 if self.show_inline_completions_override.is_some() {
2588 self.set_show_inline_completions(None, cx);
2589 } else {
2590 let cursor = self.selections.newest_anchor().head();
2591 if let Some((buffer, cursor_buffer_position)) =
2592 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2593 {
2594 let show_inline_completions =
2595 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2596 self.set_show_inline_completions(Some(show_inline_completions), cx);
2597 }
2598 }
2599 }
2600
2601 pub fn set_show_inline_completions(
2602 &mut self,
2603 show_inline_completions: Option<bool>,
2604 cx: &mut ViewContext<Self>,
2605 ) {
2606 self.show_inline_completions_override = show_inline_completions;
2607 self.refresh_inline_completion(false, true, cx);
2608 }
2609
2610 fn should_show_inline_completions(
2611 &self,
2612 buffer: &Model<Buffer>,
2613 buffer_position: language::Anchor,
2614 cx: &AppContext,
2615 ) -> bool {
2616 if !self.snippet_stack.is_empty() {
2617 return false;
2618 }
2619
2620 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
2621 return false;
2622 }
2623
2624 if let Some(provider) = self.inline_completion_provider() {
2625 if let Some(show_inline_completions) = self.show_inline_completions_override {
2626 show_inline_completions
2627 } else {
2628 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2629 }
2630 } else {
2631 false
2632 }
2633 }
2634
2635 fn inline_completions_disabled_in_scope(
2636 &self,
2637 buffer: &Model<Buffer>,
2638 buffer_position: language::Anchor,
2639 cx: &AppContext,
2640 ) -> bool {
2641 let snapshot = buffer.read(cx).snapshot();
2642 let settings = snapshot.settings_at(buffer_position, cx);
2643
2644 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2645 return false;
2646 };
2647
2648 scope.override_name().map_or(false, |scope_name| {
2649 settings
2650 .inline_completions_disabled_in
2651 .iter()
2652 .any(|s| s == scope_name)
2653 })
2654 }
2655
2656 pub fn set_use_modal_editing(&mut self, to: bool) {
2657 self.use_modal_editing = to;
2658 }
2659
2660 pub fn use_modal_editing(&self) -> bool {
2661 self.use_modal_editing
2662 }
2663
2664 fn selections_did_change(
2665 &mut self,
2666 local: bool,
2667 old_cursor_position: &Anchor,
2668 show_completions: bool,
2669 cx: &mut ViewContext<Self>,
2670 ) {
2671 cx.invalidate_character_coordinates();
2672
2673 // Copy selections to primary selection buffer
2674 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2675 if local {
2676 let selections = self.selections.all::<usize>(cx);
2677 let buffer_handle = self.buffer.read(cx).read(cx);
2678
2679 let mut text = String::new();
2680 for (index, selection) in selections.iter().enumerate() {
2681 let text_for_selection = buffer_handle
2682 .text_for_range(selection.start..selection.end)
2683 .collect::<String>();
2684
2685 text.push_str(&text_for_selection);
2686 if index != selections.len() - 1 {
2687 text.push('\n');
2688 }
2689 }
2690
2691 if !text.is_empty() {
2692 cx.write_to_primary(ClipboardItem::new_string(text));
2693 }
2694 }
2695
2696 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2697 self.buffer.update(cx, |buffer, cx| {
2698 buffer.set_active_selections(
2699 &self.selections.disjoint_anchors(),
2700 self.selections.line_mode,
2701 self.cursor_shape,
2702 cx,
2703 )
2704 });
2705 }
2706 let display_map = self
2707 .display_map
2708 .update(cx, |display_map, cx| display_map.snapshot(cx));
2709 let buffer = &display_map.buffer_snapshot;
2710 self.add_selections_state = None;
2711 self.select_next_state = None;
2712 self.select_prev_state = None;
2713 self.select_larger_syntax_node_stack.clear();
2714 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2715 self.snippet_stack
2716 .invalidate(&self.selections.disjoint_anchors(), buffer);
2717 self.take_rename(false, cx);
2718
2719 let new_cursor_position = self.selections.newest_anchor().head();
2720
2721 self.push_to_nav_history(
2722 *old_cursor_position,
2723 Some(new_cursor_position.to_point(buffer)),
2724 cx,
2725 );
2726
2727 if local {
2728 let new_cursor_position = self.selections.newest_anchor().head();
2729 let mut context_menu = self.context_menu.write();
2730 let completion_menu = match context_menu.as_ref() {
2731 Some(ContextMenu::Completions(menu)) => Some(menu),
2732
2733 _ => {
2734 *context_menu = None;
2735 None
2736 }
2737 };
2738
2739 if let Some(completion_menu) = completion_menu {
2740 let cursor_position = new_cursor_position.to_offset(buffer);
2741 let (word_range, kind) =
2742 buffer.surrounding_word(completion_menu.initial_position, true);
2743 if kind == Some(CharKind::Word)
2744 && word_range.to_inclusive().contains(&cursor_position)
2745 {
2746 let mut completion_menu = completion_menu.clone();
2747 drop(context_menu);
2748
2749 let query = Self::completion_query(buffer, cursor_position);
2750 cx.spawn(move |this, mut cx| async move {
2751 completion_menu
2752 .filter(query.as_deref(), cx.background_executor().clone())
2753 .await;
2754
2755 this.update(&mut cx, |this, cx| {
2756 let mut context_menu = this.context_menu.write();
2757 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2758 return;
2759 };
2760
2761 if menu.id > completion_menu.id {
2762 return;
2763 }
2764
2765 *context_menu = Some(ContextMenu::Completions(completion_menu));
2766 drop(context_menu);
2767 cx.notify();
2768 })
2769 })
2770 .detach();
2771
2772 if show_completions {
2773 self.show_completions(&ShowCompletions { trigger: None }, cx);
2774 }
2775 } else {
2776 drop(context_menu);
2777 self.hide_context_menu(cx);
2778 }
2779 } else {
2780 drop(context_menu);
2781 }
2782
2783 hide_hover(self, cx);
2784
2785 if old_cursor_position.to_display_point(&display_map).row()
2786 != new_cursor_position.to_display_point(&display_map).row()
2787 {
2788 self.available_code_actions.take();
2789 }
2790 self.refresh_code_actions(cx);
2791 self.refresh_document_highlights(cx);
2792 refresh_matching_bracket_highlights(self, cx);
2793 self.discard_inline_completion(false, cx);
2794 linked_editing_ranges::refresh_linked_ranges(self, cx);
2795 if self.git_blame_inline_enabled {
2796 self.start_inline_blame_timer(cx);
2797 }
2798 }
2799
2800 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2801 cx.emit(EditorEvent::SelectionsChanged { local });
2802
2803 if self.selections.disjoint_anchors().len() == 1 {
2804 cx.emit(SearchEvent::ActiveMatchChanged)
2805 }
2806 cx.notify();
2807 }
2808
2809 pub fn change_selections<R>(
2810 &mut self,
2811 autoscroll: Option<Autoscroll>,
2812 cx: &mut ViewContext<Self>,
2813 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2814 ) -> R {
2815 self.change_selections_inner(autoscroll, true, cx, change)
2816 }
2817
2818 pub fn change_selections_inner<R>(
2819 &mut self,
2820 autoscroll: Option<Autoscroll>,
2821 request_completions: bool,
2822 cx: &mut ViewContext<Self>,
2823 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2824 ) -> R {
2825 let old_cursor_position = self.selections.newest_anchor().head();
2826 self.push_to_selection_history();
2827
2828 let (changed, result) = self.selections.change_with(cx, change);
2829
2830 if changed {
2831 if let Some(autoscroll) = autoscroll {
2832 self.request_autoscroll(autoscroll, cx);
2833 }
2834 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2835
2836 if self.should_open_signature_help_automatically(
2837 &old_cursor_position,
2838 self.signature_help_state.backspace_pressed(),
2839 cx,
2840 ) {
2841 self.show_signature_help(&ShowSignatureHelp, cx);
2842 }
2843 self.signature_help_state.set_backspace_pressed(false);
2844 }
2845
2846 result
2847 }
2848
2849 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2850 where
2851 I: IntoIterator<Item = (Range<S>, T)>,
2852 S: ToOffset,
2853 T: Into<Arc<str>>,
2854 {
2855 if self.read_only(cx) {
2856 return;
2857 }
2858
2859 self.buffer
2860 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2861 }
2862
2863 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2864 where
2865 I: IntoIterator<Item = (Range<S>, T)>,
2866 S: ToOffset,
2867 T: Into<Arc<str>>,
2868 {
2869 if self.read_only(cx) {
2870 return;
2871 }
2872
2873 self.buffer.update(cx, |buffer, cx| {
2874 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2875 });
2876 }
2877
2878 pub fn edit_with_block_indent<I, S, T>(
2879 &mut self,
2880 edits: I,
2881 original_indent_columns: Vec<u32>,
2882 cx: &mut ViewContext<Self>,
2883 ) where
2884 I: IntoIterator<Item = (Range<S>, T)>,
2885 S: ToOffset,
2886 T: Into<Arc<str>>,
2887 {
2888 if self.read_only(cx) {
2889 return;
2890 }
2891
2892 self.buffer.update(cx, |buffer, cx| {
2893 buffer.edit(
2894 edits,
2895 Some(AutoindentMode::Block {
2896 original_indent_columns,
2897 }),
2898 cx,
2899 )
2900 });
2901 }
2902
2903 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2904 self.hide_context_menu(cx);
2905
2906 match phase {
2907 SelectPhase::Begin {
2908 position,
2909 add,
2910 click_count,
2911 } => self.begin_selection(position, add, click_count, cx),
2912 SelectPhase::BeginColumnar {
2913 position,
2914 goal_column,
2915 reset,
2916 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2917 SelectPhase::Extend {
2918 position,
2919 click_count,
2920 } => self.extend_selection(position, click_count, cx),
2921 SelectPhase::Update {
2922 position,
2923 goal_column,
2924 scroll_delta,
2925 } => self.update_selection(position, goal_column, scroll_delta, cx),
2926 SelectPhase::End => self.end_selection(cx),
2927 }
2928 }
2929
2930 fn extend_selection(
2931 &mut self,
2932 position: DisplayPoint,
2933 click_count: usize,
2934 cx: &mut ViewContext<Self>,
2935 ) {
2936 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2937 let tail = self.selections.newest::<usize>(cx).tail();
2938 self.begin_selection(position, false, click_count, cx);
2939
2940 let position = position.to_offset(&display_map, Bias::Left);
2941 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2942
2943 let mut pending_selection = self
2944 .selections
2945 .pending_anchor()
2946 .expect("extend_selection not called with pending selection");
2947 if position >= tail {
2948 pending_selection.start = tail_anchor;
2949 } else {
2950 pending_selection.end = tail_anchor;
2951 pending_selection.reversed = true;
2952 }
2953
2954 let mut pending_mode = self.selections.pending_mode().unwrap();
2955 match &mut pending_mode {
2956 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2957 _ => {}
2958 }
2959
2960 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2961 s.set_pending(pending_selection, pending_mode)
2962 });
2963 }
2964
2965 fn begin_selection(
2966 &mut self,
2967 position: DisplayPoint,
2968 add: bool,
2969 click_count: usize,
2970 cx: &mut ViewContext<Self>,
2971 ) {
2972 if !self.focus_handle.is_focused(cx) {
2973 self.last_focused_descendant = None;
2974 cx.focus(&self.focus_handle);
2975 }
2976
2977 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2978 let buffer = &display_map.buffer_snapshot;
2979 let newest_selection = self.selections.newest_anchor().clone();
2980 let position = display_map.clip_point(position, Bias::Left);
2981
2982 let start;
2983 let end;
2984 let mode;
2985 let auto_scroll;
2986 match click_count {
2987 1 => {
2988 start = buffer.anchor_before(position.to_point(&display_map));
2989 end = start;
2990 mode = SelectMode::Character;
2991 auto_scroll = true;
2992 }
2993 2 => {
2994 let range = movement::surrounding_word(&display_map, position);
2995 start = buffer.anchor_before(range.start.to_point(&display_map));
2996 end = buffer.anchor_before(range.end.to_point(&display_map));
2997 mode = SelectMode::Word(start..end);
2998 auto_scroll = true;
2999 }
3000 3 => {
3001 let position = display_map
3002 .clip_point(position, Bias::Left)
3003 .to_point(&display_map);
3004 let line_start = display_map.prev_line_boundary(position).0;
3005 let next_line_start = buffer.clip_point(
3006 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3007 Bias::Left,
3008 );
3009 start = buffer.anchor_before(line_start);
3010 end = buffer.anchor_before(next_line_start);
3011 mode = SelectMode::Line(start..end);
3012 auto_scroll = true;
3013 }
3014 _ => {
3015 start = buffer.anchor_before(0);
3016 end = buffer.anchor_before(buffer.len());
3017 mode = SelectMode::All;
3018 auto_scroll = false;
3019 }
3020 }
3021
3022 let point_to_delete: Option<usize> = {
3023 let selected_points: Vec<Selection<Point>> =
3024 self.selections.disjoint_in_range(start..end, cx);
3025
3026 if !add || click_count > 1 {
3027 None
3028 } else if !selected_points.is_empty() {
3029 Some(selected_points[0].id)
3030 } else {
3031 let clicked_point_already_selected =
3032 self.selections.disjoint.iter().find(|selection| {
3033 selection.start.to_point(buffer) == start.to_point(buffer)
3034 || selection.end.to_point(buffer) == end.to_point(buffer)
3035 });
3036
3037 clicked_point_already_selected.map(|selection| selection.id)
3038 }
3039 };
3040
3041 let selections_count = self.selections.count();
3042
3043 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
3044 if let Some(point_to_delete) = point_to_delete {
3045 s.delete(point_to_delete);
3046
3047 if selections_count == 1 {
3048 s.set_pending_anchor_range(start..end, mode);
3049 }
3050 } else {
3051 if !add {
3052 s.clear_disjoint();
3053 } else if click_count > 1 {
3054 s.delete(newest_selection.id)
3055 }
3056
3057 s.set_pending_anchor_range(start..end, mode);
3058 }
3059 });
3060 }
3061
3062 fn begin_columnar_selection(
3063 &mut self,
3064 position: DisplayPoint,
3065 goal_column: u32,
3066 reset: bool,
3067 cx: &mut ViewContext<Self>,
3068 ) {
3069 if !self.focus_handle.is_focused(cx) {
3070 self.last_focused_descendant = None;
3071 cx.focus(&self.focus_handle);
3072 }
3073
3074 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3075
3076 if reset {
3077 let pointer_position = display_map
3078 .buffer_snapshot
3079 .anchor_before(position.to_point(&display_map));
3080
3081 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
3082 s.clear_disjoint();
3083 s.set_pending_anchor_range(
3084 pointer_position..pointer_position,
3085 SelectMode::Character,
3086 );
3087 });
3088 }
3089
3090 let tail = self.selections.newest::<Point>(cx).tail();
3091 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
3092
3093 if !reset {
3094 self.select_columns(
3095 tail.to_display_point(&display_map),
3096 position,
3097 goal_column,
3098 &display_map,
3099 cx,
3100 );
3101 }
3102 }
3103
3104 fn update_selection(
3105 &mut self,
3106 position: DisplayPoint,
3107 goal_column: u32,
3108 scroll_delta: gpui::Point<f32>,
3109 cx: &mut ViewContext<Self>,
3110 ) {
3111 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3112
3113 if let Some(tail) = self.columnar_selection_tail.as_ref() {
3114 let tail = tail.to_display_point(&display_map);
3115 self.select_columns(tail, position, goal_column, &display_map, cx);
3116 } else if let Some(mut pending) = self.selections.pending_anchor() {
3117 let buffer = self.buffer.read(cx).snapshot(cx);
3118 let head;
3119 let tail;
3120 let mode = self.selections.pending_mode().unwrap();
3121 match &mode {
3122 SelectMode::Character => {
3123 head = position.to_point(&display_map);
3124 tail = pending.tail().to_point(&buffer);
3125 }
3126 SelectMode::Word(original_range) => {
3127 let original_display_range = original_range.start.to_display_point(&display_map)
3128 ..original_range.end.to_display_point(&display_map);
3129 let original_buffer_range = original_display_range.start.to_point(&display_map)
3130 ..original_display_range.end.to_point(&display_map);
3131 if movement::is_inside_word(&display_map, position)
3132 || original_display_range.contains(&position)
3133 {
3134 let word_range = movement::surrounding_word(&display_map, position);
3135 if word_range.start < original_display_range.start {
3136 head = word_range.start.to_point(&display_map);
3137 } else {
3138 head = word_range.end.to_point(&display_map);
3139 }
3140 } else {
3141 head = position.to_point(&display_map);
3142 }
3143
3144 if head <= original_buffer_range.start {
3145 tail = original_buffer_range.end;
3146 } else {
3147 tail = original_buffer_range.start;
3148 }
3149 }
3150 SelectMode::Line(original_range) => {
3151 let original_range = original_range.to_point(&display_map.buffer_snapshot);
3152
3153 let position = display_map
3154 .clip_point(position, Bias::Left)
3155 .to_point(&display_map);
3156 let line_start = display_map.prev_line_boundary(position).0;
3157 let next_line_start = buffer.clip_point(
3158 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3159 Bias::Left,
3160 );
3161
3162 if line_start < original_range.start {
3163 head = line_start
3164 } else {
3165 head = next_line_start
3166 }
3167
3168 if head <= original_range.start {
3169 tail = original_range.end;
3170 } else {
3171 tail = original_range.start;
3172 }
3173 }
3174 SelectMode::All => {
3175 return;
3176 }
3177 };
3178
3179 if head < tail {
3180 pending.start = buffer.anchor_before(head);
3181 pending.end = buffer.anchor_before(tail);
3182 pending.reversed = true;
3183 } else {
3184 pending.start = buffer.anchor_before(tail);
3185 pending.end = buffer.anchor_before(head);
3186 pending.reversed = false;
3187 }
3188
3189 self.change_selections(None, cx, |s| {
3190 s.set_pending(pending, mode);
3191 });
3192 } else {
3193 log::error!("update_selection dispatched with no pending selection");
3194 return;
3195 }
3196
3197 self.apply_scroll_delta(scroll_delta, cx);
3198 cx.notify();
3199 }
3200
3201 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
3202 self.columnar_selection_tail.take();
3203 if self.selections.pending_anchor().is_some() {
3204 let selections = self.selections.all::<usize>(cx);
3205 self.change_selections(None, cx, |s| {
3206 s.select(selections);
3207 s.clear_pending();
3208 });
3209 }
3210 }
3211
3212 fn select_columns(
3213 &mut self,
3214 tail: DisplayPoint,
3215 head: DisplayPoint,
3216 goal_column: u32,
3217 display_map: &DisplaySnapshot,
3218 cx: &mut ViewContext<Self>,
3219 ) {
3220 let start_row = cmp::min(tail.row(), head.row());
3221 let end_row = cmp::max(tail.row(), head.row());
3222 let start_column = cmp::min(tail.column(), goal_column);
3223 let end_column = cmp::max(tail.column(), goal_column);
3224 let reversed = start_column < tail.column();
3225
3226 let selection_ranges = (start_row.0..=end_row.0)
3227 .map(DisplayRow)
3228 .filter_map(|row| {
3229 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3230 let start = display_map
3231 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3232 .to_point(display_map);
3233 let end = display_map
3234 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3235 .to_point(display_map);
3236 if reversed {
3237 Some(end..start)
3238 } else {
3239 Some(start..end)
3240 }
3241 } else {
3242 None
3243 }
3244 })
3245 .collect::<Vec<_>>();
3246
3247 self.change_selections(None, cx, |s| {
3248 s.select_ranges(selection_ranges);
3249 });
3250 cx.notify();
3251 }
3252
3253 pub fn has_pending_nonempty_selection(&self) -> bool {
3254 let pending_nonempty_selection = match self.selections.pending_anchor() {
3255 Some(Selection { start, end, .. }) => start != end,
3256 None => false,
3257 };
3258
3259 pending_nonempty_selection
3260 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3261 }
3262
3263 pub fn has_pending_selection(&self) -> bool {
3264 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3265 }
3266
3267 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
3268 if self.clear_expanded_diff_hunks(cx) {
3269 cx.notify();
3270 return;
3271 }
3272 if self.dismiss_menus_and_popups(true, cx) {
3273 return;
3274 }
3275
3276 if self.mode == EditorMode::Full
3277 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
3278 {
3279 return;
3280 }
3281
3282 cx.propagate();
3283 }
3284
3285 pub fn dismiss_menus_and_popups(
3286 &mut self,
3287 should_report_inline_completion_event: bool,
3288 cx: &mut ViewContext<Self>,
3289 ) -> bool {
3290 if self.take_rename(false, cx).is_some() {
3291 return true;
3292 }
3293
3294 if hide_hover(self, cx) {
3295 return true;
3296 }
3297
3298 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3299 return true;
3300 }
3301
3302 if self.hide_context_menu(cx).is_some() {
3303 return true;
3304 }
3305
3306 if self.mouse_context_menu.take().is_some() {
3307 return true;
3308 }
3309
3310 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3311 return true;
3312 }
3313
3314 if self.snippet_stack.pop().is_some() {
3315 return true;
3316 }
3317
3318 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3319 self.dismiss_diagnostics(cx);
3320 return true;
3321 }
3322
3323 false
3324 }
3325
3326 fn linked_editing_ranges_for(
3327 &self,
3328 selection: Range<text::Anchor>,
3329 cx: &AppContext,
3330 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3331 if self.linked_edit_ranges.is_empty() {
3332 return None;
3333 }
3334 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3335 selection.end.buffer_id.and_then(|end_buffer_id| {
3336 if selection.start.buffer_id != Some(end_buffer_id) {
3337 return None;
3338 }
3339 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3340 let snapshot = buffer.read(cx).snapshot();
3341 self.linked_edit_ranges
3342 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3343 .map(|ranges| (ranges, snapshot, buffer))
3344 })?;
3345 use text::ToOffset as TO;
3346 // find offset from the start of current range to current cursor position
3347 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3348
3349 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3350 let start_difference = start_offset - start_byte_offset;
3351 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3352 let end_difference = end_offset - start_byte_offset;
3353 // Current range has associated linked ranges.
3354 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3355 for range in linked_ranges.iter() {
3356 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3357 let end_offset = start_offset + end_difference;
3358 let start_offset = start_offset + start_difference;
3359 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3360 continue;
3361 }
3362 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3363 if s.start.buffer_id != selection.start.buffer_id
3364 || s.end.buffer_id != selection.end.buffer_id
3365 {
3366 return false;
3367 }
3368 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3369 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3370 }) {
3371 continue;
3372 }
3373 let start = buffer_snapshot.anchor_after(start_offset);
3374 let end = buffer_snapshot.anchor_after(end_offset);
3375 linked_edits
3376 .entry(buffer.clone())
3377 .or_default()
3378 .push(start..end);
3379 }
3380 Some(linked_edits)
3381 }
3382
3383 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3384 let text: Arc<str> = text.into();
3385
3386 if self.read_only(cx) {
3387 return;
3388 }
3389
3390 let selections = self.selections.all_adjusted(cx);
3391 let mut bracket_inserted = false;
3392 let mut edits = Vec::new();
3393 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3394 let mut new_selections = Vec::with_capacity(selections.len());
3395 let mut new_autoclose_regions = Vec::new();
3396 let snapshot = self.buffer.read(cx).read(cx);
3397
3398 for (selection, autoclose_region) in
3399 self.selections_with_autoclose_regions(selections, &snapshot)
3400 {
3401 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3402 // Determine if the inserted text matches the opening or closing
3403 // bracket of any of this language's bracket pairs.
3404 let mut bracket_pair = None;
3405 let mut is_bracket_pair_start = false;
3406 let mut is_bracket_pair_end = false;
3407 if !text.is_empty() {
3408 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3409 // and they are removing the character that triggered IME popup.
3410 for (pair, enabled) in scope.brackets() {
3411 if !pair.close && !pair.surround {
3412 continue;
3413 }
3414
3415 if enabled && pair.start.ends_with(text.as_ref()) {
3416 let prefix_len = pair.start.len() - text.len();
3417 let preceding_text_matches_prefix = prefix_len == 0
3418 || (selection.start.column >= (prefix_len as u32)
3419 && snapshot.contains_str_at(
3420 Point::new(
3421 selection.start.row,
3422 selection.start.column - (prefix_len as u32),
3423 ),
3424 &pair.start[..prefix_len],
3425 ));
3426 if preceding_text_matches_prefix {
3427 bracket_pair = Some(pair.clone());
3428 is_bracket_pair_start = true;
3429 break;
3430 }
3431 }
3432 if pair.end.as_str() == text.as_ref() {
3433 bracket_pair = Some(pair.clone());
3434 is_bracket_pair_end = true;
3435 break;
3436 }
3437 }
3438 }
3439
3440 if let Some(bracket_pair) = bracket_pair {
3441 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3442 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3443 let auto_surround =
3444 self.use_auto_surround && snapshot_settings.use_auto_surround;
3445 if selection.is_empty() {
3446 if is_bracket_pair_start {
3447 // If the inserted text is a suffix of an opening bracket and the
3448 // selection is preceded by the rest of the opening bracket, then
3449 // insert the closing bracket.
3450 let following_text_allows_autoclose = snapshot
3451 .chars_at(selection.start)
3452 .next()
3453 .map_or(true, |c| scope.should_autoclose_before(c));
3454
3455 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3456 && bracket_pair.start.len() == 1
3457 {
3458 let target = bracket_pair.start.chars().next().unwrap();
3459 let current_line_count = snapshot
3460 .reversed_chars_at(selection.start)
3461 .take_while(|&c| c != '\n')
3462 .filter(|&c| c == target)
3463 .count();
3464 current_line_count % 2 == 1
3465 } else {
3466 false
3467 };
3468
3469 if autoclose
3470 && bracket_pair.close
3471 && following_text_allows_autoclose
3472 && !is_closing_quote
3473 {
3474 let anchor = snapshot.anchor_before(selection.end);
3475 new_selections.push((selection.map(|_| anchor), text.len()));
3476 new_autoclose_regions.push((
3477 anchor,
3478 text.len(),
3479 selection.id,
3480 bracket_pair.clone(),
3481 ));
3482 edits.push((
3483 selection.range(),
3484 format!("{}{}", text, bracket_pair.end).into(),
3485 ));
3486 bracket_inserted = true;
3487 continue;
3488 }
3489 }
3490
3491 if let Some(region) = autoclose_region {
3492 // If the selection is followed by an auto-inserted closing bracket,
3493 // then don't insert that closing bracket again; just move the selection
3494 // past the closing bracket.
3495 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3496 && text.as_ref() == region.pair.end.as_str();
3497 if should_skip {
3498 let anchor = snapshot.anchor_after(selection.end);
3499 new_selections
3500 .push((selection.map(|_| anchor), region.pair.end.len()));
3501 continue;
3502 }
3503 }
3504
3505 let always_treat_brackets_as_autoclosed = snapshot
3506 .settings_at(selection.start, cx)
3507 .always_treat_brackets_as_autoclosed;
3508 if always_treat_brackets_as_autoclosed
3509 && is_bracket_pair_end
3510 && snapshot.contains_str_at(selection.end, text.as_ref())
3511 {
3512 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3513 // and the inserted text is a closing bracket and the selection is followed
3514 // by the closing bracket then move the selection past the closing bracket.
3515 let anchor = snapshot.anchor_after(selection.end);
3516 new_selections.push((selection.map(|_| anchor), text.len()));
3517 continue;
3518 }
3519 }
3520 // If an opening bracket is 1 character long and is typed while
3521 // text is selected, then surround that text with the bracket pair.
3522 else if auto_surround
3523 && bracket_pair.surround
3524 && is_bracket_pair_start
3525 && bracket_pair.start.chars().count() == 1
3526 {
3527 edits.push((selection.start..selection.start, text.clone()));
3528 edits.push((
3529 selection.end..selection.end,
3530 bracket_pair.end.as_str().into(),
3531 ));
3532 bracket_inserted = true;
3533 new_selections.push((
3534 Selection {
3535 id: selection.id,
3536 start: snapshot.anchor_after(selection.start),
3537 end: snapshot.anchor_before(selection.end),
3538 reversed: selection.reversed,
3539 goal: selection.goal,
3540 },
3541 0,
3542 ));
3543 continue;
3544 }
3545 }
3546 }
3547
3548 if self.auto_replace_emoji_shortcode
3549 && selection.is_empty()
3550 && text.as_ref().ends_with(':')
3551 {
3552 if let Some(possible_emoji_short_code) =
3553 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3554 {
3555 if !possible_emoji_short_code.is_empty() {
3556 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3557 let emoji_shortcode_start = Point::new(
3558 selection.start.row,
3559 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3560 );
3561
3562 // Remove shortcode from buffer
3563 edits.push((
3564 emoji_shortcode_start..selection.start,
3565 "".to_string().into(),
3566 ));
3567 new_selections.push((
3568 Selection {
3569 id: selection.id,
3570 start: snapshot.anchor_after(emoji_shortcode_start),
3571 end: snapshot.anchor_before(selection.start),
3572 reversed: selection.reversed,
3573 goal: selection.goal,
3574 },
3575 0,
3576 ));
3577
3578 // Insert emoji
3579 let selection_start_anchor = snapshot.anchor_after(selection.start);
3580 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3581 edits.push((selection.start..selection.end, emoji.to_string().into()));
3582
3583 continue;
3584 }
3585 }
3586 }
3587 }
3588
3589 // If not handling any auto-close operation, then just replace the selected
3590 // text with the given input and move the selection to the end of the
3591 // newly inserted text.
3592 let anchor = snapshot.anchor_after(selection.end);
3593 if !self.linked_edit_ranges.is_empty() {
3594 let start_anchor = snapshot.anchor_before(selection.start);
3595
3596 let is_word_char = text.chars().next().map_or(true, |char| {
3597 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3598 classifier.is_word(char)
3599 });
3600
3601 if is_word_char {
3602 if let Some(ranges) = self
3603 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3604 {
3605 for (buffer, edits) in ranges {
3606 linked_edits
3607 .entry(buffer.clone())
3608 .or_default()
3609 .extend(edits.into_iter().map(|range| (range, text.clone())));
3610 }
3611 }
3612 }
3613 }
3614
3615 new_selections.push((selection.map(|_| anchor), 0));
3616 edits.push((selection.start..selection.end, text.clone()));
3617 }
3618
3619 drop(snapshot);
3620
3621 self.transact(cx, |this, cx| {
3622 this.buffer.update(cx, |buffer, cx| {
3623 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3624 });
3625 for (buffer, edits) in linked_edits {
3626 buffer.update(cx, |buffer, cx| {
3627 let snapshot = buffer.snapshot();
3628 let edits = edits
3629 .into_iter()
3630 .map(|(range, text)| {
3631 use text::ToPoint as TP;
3632 let end_point = TP::to_point(&range.end, &snapshot);
3633 let start_point = TP::to_point(&range.start, &snapshot);
3634 (start_point..end_point, text)
3635 })
3636 .sorted_by_key(|(range, _)| range.start)
3637 .collect::<Vec<_>>();
3638 buffer.edit(edits, None, cx);
3639 })
3640 }
3641 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3642 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3643 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3644 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3645 .zip(new_selection_deltas)
3646 .map(|(selection, delta)| Selection {
3647 id: selection.id,
3648 start: selection.start + delta,
3649 end: selection.end + delta,
3650 reversed: selection.reversed,
3651 goal: SelectionGoal::None,
3652 })
3653 .collect::<Vec<_>>();
3654
3655 let mut i = 0;
3656 for (position, delta, selection_id, pair) in new_autoclose_regions {
3657 let position = position.to_offset(&map.buffer_snapshot) + delta;
3658 let start = map.buffer_snapshot.anchor_before(position);
3659 let end = map.buffer_snapshot.anchor_after(position);
3660 while let Some(existing_state) = this.autoclose_regions.get(i) {
3661 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3662 Ordering::Less => i += 1,
3663 Ordering::Greater => break,
3664 Ordering::Equal => {
3665 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3666 Ordering::Less => i += 1,
3667 Ordering::Equal => break,
3668 Ordering::Greater => break,
3669 }
3670 }
3671 }
3672 }
3673 this.autoclose_regions.insert(
3674 i,
3675 AutocloseRegion {
3676 selection_id,
3677 range: start..end,
3678 pair,
3679 },
3680 );
3681 }
3682
3683 let had_active_inline_completion = this.has_active_inline_completion(cx);
3684 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3685 s.select(new_selections)
3686 });
3687
3688 if !bracket_inserted {
3689 if let Some(on_type_format_task) =
3690 this.trigger_on_type_formatting(text.to_string(), cx)
3691 {
3692 on_type_format_task.detach_and_log_err(cx);
3693 }
3694 }
3695
3696 let editor_settings = EditorSettings::get_global(cx);
3697 if bracket_inserted
3698 && (editor_settings.auto_signature_help
3699 || editor_settings.show_signature_help_after_edits)
3700 {
3701 this.show_signature_help(&ShowSignatureHelp, cx);
3702 }
3703
3704 let trigger_in_words = !had_active_inline_completion;
3705 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3706 linked_editing_ranges::refresh_linked_ranges(this, cx);
3707 this.refresh_inline_completion(true, false, cx);
3708 });
3709 }
3710
3711 fn find_possible_emoji_shortcode_at_position(
3712 snapshot: &MultiBufferSnapshot,
3713 position: Point,
3714 ) -> Option<String> {
3715 let mut chars = Vec::new();
3716 let mut found_colon = false;
3717 for char in snapshot.reversed_chars_at(position).take(100) {
3718 // Found a possible emoji shortcode in the middle of the buffer
3719 if found_colon {
3720 if char.is_whitespace() {
3721 chars.reverse();
3722 return Some(chars.iter().collect());
3723 }
3724 // If the previous character is not a whitespace, we are in the middle of a word
3725 // and we only want to complete the shortcode if the word is made up of other emojis
3726 let mut containing_word = String::new();
3727 for ch in snapshot
3728 .reversed_chars_at(position)
3729 .skip(chars.len() + 1)
3730 .take(100)
3731 {
3732 if ch.is_whitespace() {
3733 break;
3734 }
3735 containing_word.push(ch);
3736 }
3737 let containing_word = containing_word.chars().rev().collect::<String>();
3738 if util::word_consists_of_emojis(containing_word.as_str()) {
3739 chars.reverse();
3740 return Some(chars.iter().collect());
3741 }
3742 }
3743
3744 if char.is_whitespace() || !char.is_ascii() {
3745 return None;
3746 }
3747 if char == ':' {
3748 found_colon = true;
3749 } else {
3750 chars.push(char);
3751 }
3752 }
3753 // Found a possible emoji shortcode at the beginning of the buffer
3754 chars.reverse();
3755 Some(chars.iter().collect())
3756 }
3757
3758 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3759 self.transact(cx, |this, cx| {
3760 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3761 let selections = this.selections.all::<usize>(cx);
3762 let multi_buffer = this.buffer.read(cx);
3763 let buffer = multi_buffer.snapshot(cx);
3764 selections
3765 .iter()
3766 .map(|selection| {
3767 let start_point = selection.start.to_point(&buffer);
3768 let mut indent =
3769 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3770 indent.len = cmp::min(indent.len, start_point.column);
3771 let start = selection.start;
3772 let end = selection.end;
3773 let selection_is_empty = start == end;
3774 let language_scope = buffer.language_scope_at(start);
3775 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3776 &language_scope
3777 {
3778 let leading_whitespace_len = buffer
3779 .reversed_chars_at(start)
3780 .take_while(|c| c.is_whitespace() && *c != '\n')
3781 .map(|c| c.len_utf8())
3782 .sum::<usize>();
3783
3784 let trailing_whitespace_len = buffer
3785 .chars_at(end)
3786 .take_while(|c| c.is_whitespace() && *c != '\n')
3787 .map(|c| c.len_utf8())
3788 .sum::<usize>();
3789
3790 let insert_extra_newline =
3791 language.brackets().any(|(pair, enabled)| {
3792 let pair_start = pair.start.trim_end();
3793 let pair_end = pair.end.trim_start();
3794
3795 enabled
3796 && pair.newline
3797 && buffer.contains_str_at(
3798 end + trailing_whitespace_len,
3799 pair_end,
3800 )
3801 && buffer.contains_str_at(
3802 (start - leading_whitespace_len)
3803 .saturating_sub(pair_start.len()),
3804 pair_start,
3805 )
3806 });
3807
3808 // Comment extension on newline is allowed only for cursor selections
3809 let comment_delimiter = maybe!({
3810 if !selection_is_empty {
3811 return None;
3812 }
3813
3814 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3815 return None;
3816 }
3817
3818 let delimiters = language.line_comment_prefixes();
3819 let max_len_of_delimiter =
3820 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3821 let (snapshot, range) =
3822 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3823
3824 let mut index_of_first_non_whitespace = 0;
3825 let comment_candidate = snapshot
3826 .chars_for_range(range)
3827 .skip_while(|c| {
3828 let should_skip = c.is_whitespace();
3829 if should_skip {
3830 index_of_first_non_whitespace += 1;
3831 }
3832 should_skip
3833 })
3834 .take(max_len_of_delimiter)
3835 .collect::<String>();
3836 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3837 comment_candidate.starts_with(comment_prefix.as_ref())
3838 })?;
3839 let cursor_is_placed_after_comment_marker =
3840 index_of_first_non_whitespace + comment_prefix.len()
3841 <= start_point.column as usize;
3842 if cursor_is_placed_after_comment_marker {
3843 Some(comment_prefix.clone())
3844 } else {
3845 None
3846 }
3847 });
3848 (comment_delimiter, insert_extra_newline)
3849 } else {
3850 (None, false)
3851 };
3852
3853 let capacity_for_delimiter = comment_delimiter
3854 .as_deref()
3855 .map(str::len)
3856 .unwrap_or_default();
3857 let mut new_text =
3858 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3859 new_text.push('\n');
3860 new_text.extend(indent.chars());
3861 if let Some(delimiter) = &comment_delimiter {
3862 new_text.push_str(delimiter);
3863 }
3864 if insert_extra_newline {
3865 new_text = new_text.repeat(2);
3866 }
3867
3868 let anchor = buffer.anchor_after(end);
3869 let new_selection = selection.map(|_| anchor);
3870 (
3871 (start..end, new_text),
3872 (insert_extra_newline, new_selection),
3873 )
3874 })
3875 .unzip()
3876 };
3877
3878 this.edit_with_autoindent(edits, cx);
3879 let buffer = this.buffer.read(cx).snapshot(cx);
3880 let new_selections = selection_fixup_info
3881 .into_iter()
3882 .map(|(extra_newline_inserted, new_selection)| {
3883 let mut cursor = new_selection.end.to_point(&buffer);
3884 if extra_newline_inserted {
3885 cursor.row -= 1;
3886 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3887 }
3888 new_selection.map(|_| cursor)
3889 })
3890 .collect();
3891
3892 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3893 this.refresh_inline_completion(true, false, cx);
3894 });
3895 }
3896
3897 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3898 let buffer = self.buffer.read(cx);
3899 let snapshot = buffer.snapshot(cx);
3900
3901 let mut edits = Vec::new();
3902 let mut rows = Vec::new();
3903
3904 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3905 let cursor = selection.head();
3906 let row = cursor.row;
3907
3908 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3909
3910 let newline = "\n".to_string();
3911 edits.push((start_of_line..start_of_line, newline));
3912
3913 rows.push(row + rows_inserted as u32);
3914 }
3915
3916 self.transact(cx, |editor, cx| {
3917 editor.edit(edits, cx);
3918
3919 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3920 let mut index = 0;
3921 s.move_cursors_with(|map, _, _| {
3922 let row = rows[index];
3923 index += 1;
3924
3925 let point = Point::new(row, 0);
3926 let boundary = map.next_line_boundary(point).1;
3927 let clipped = map.clip_point(boundary, Bias::Left);
3928
3929 (clipped, SelectionGoal::None)
3930 });
3931 });
3932
3933 let mut indent_edits = Vec::new();
3934 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3935 for row in rows {
3936 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3937 for (row, indent) in indents {
3938 if indent.len == 0 {
3939 continue;
3940 }
3941
3942 let text = match indent.kind {
3943 IndentKind::Space => " ".repeat(indent.len as usize),
3944 IndentKind::Tab => "\t".repeat(indent.len as usize),
3945 };
3946 let point = Point::new(row.0, 0);
3947 indent_edits.push((point..point, text));
3948 }
3949 }
3950 editor.edit(indent_edits, cx);
3951 });
3952 }
3953
3954 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3955 let buffer = self.buffer.read(cx);
3956 let snapshot = buffer.snapshot(cx);
3957
3958 let mut edits = Vec::new();
3959 let mut rows = Vec::new();
3960 let mut rows_inserted = 0;
3961
3962 for selection in self.selections.all_adjusted(cx) {
3963 let cursor = selection.head();
3964 let row = cursor.row;
3965
3966 let point = Point::new(row + 1, 0);
3967 let start_of_line = snapshot.clip_point(point, Bias::Left);
3968
3969 let newline = "\n".to_string();
3970 edits.push((start_of_line..start_of_line, newline));
3971
3972 rows_inserted += 1;
3973 rows.push(row + rows_inserted);
3974 }
3975
3976 self.transact(cx, |editor, cx| {
3977 editor.edit(edits, cx);
3978
3979 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3980 let mut index = 0;
3981 s.move_cursors_with(|map, _, _| {
3982 let row = rows[index];
3983 index += 1;
3984
3985 let point = Point::new(row, 0);
3986 let boundary = map.next_line_boundary(point).1;
3987 let clipped = map.clip_point(boundary, Bias::Left);
3988
3989 (clipped, SelectionGoal::None)
3990 });
3991 });
3992
3993 let mut indent_edits = Vec::new();
3994 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3995 for row in rows {
3996 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3997 for (row, indent) in indents {
3998 if indent.len == 0 {
3999 continue;
4000 }
4001
4002 let text = match indent.kind {
4003 IndentKind::Space => " ".repeat(indent.len as usize),
4004 IndentKind::Tab => "\t".repeat(indent.len as usize),
4005 };
4006 let point = Point::new(row.0, 0);
4007 indent_edits.push((point..point, text));
4008 }
4009 }
4010 editor.edit(indent_edits, cx);
4011 });
4012 }
4013
4014 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
4015 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
4016 original_indent_columns: Vec::new(),
4017 });
4018 self.insert_with_autoindent_mode(text, autoindent, cx);
4019 }
4020
4021 fn insert_with_autoindent_mode(
4022 &mut self,
4023 text: &str,
4024 autoindent_mode: Option<AutoindentMode>,
4025 cx: &mut ViewContext<Self>,
4026 ) {
4027 if self.read_only(cx) {
4028 return;
4029 }
4030
4031 let text: Arc<str> = text.into();
4032 self.transact(cx, |this, cx| {
4033 let old_selections = this.selections.all_adjusted(cx);
4034 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
4035 let anchors = {
4036 let snapshot = buffer.read(cx);
4037 old_selections
4038 .iter()
4039 .map(|s| {
4040 let anchor = snapshot.anchor_after(s.head());
4041 s.map(|_| anchor)
4042 })
4043 .collect::<Vec<_>>()
4044 };
4045 buffer.edit(
4046 old_selections
4047 .iter()
4048 .map(|s| (s.start..s.end, text.clone())),
4049 autoindent_mode,
4050 cx,
4051 );
4052 anchors
4053 });
4054
4055 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
4056 s.select_anchors(selection_anchors);
4057 })
4058 });
4059 }
4060
4061 fn trigger_completion_on_input(
4062 &mut self,
4063 text: &str,
4064 trigger_in_words: bool,
4065 cx: &mut ViewContext<Self>,
4066 ) {
4067 if self.is_completion_trigger(text, trigger_in_words, cx) {
4068 self.show_completions(
4069 &ShowCompletions {
4070 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
4071 },
4072 cx,
4073 );
4074 } else {
4075 self.hide_context_menu(cx);
4076 }
4077 }
4078
4079 fn is_completion_trigger(
4080 &self,
4081 text: &str,
4082 trigger_in_words: bool,
4083 cx: &mut ViewContext<Self>,
4084 ) -> bool {
4085 let position = self.selections.newest_anchor().head();
4086 let multibuffer = self.buffer.read(cx);
4087 let Some(buffer) = position
4088 .buffer_id
4089 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
4090 else {
4091 return false;
4092 };
4093
4094 if let Some(completion_provider) = &self.completion_provider {
4095 completion_provider.is_completion_trigger(
4096 &buffer,
4097 position.text_anchor,
4098 text,
4099 trigger_in_words,
4100 cx,
4101 )
4102 } else {
4103 false
4104 }
4105 }
4106
4107 /// If any empty selections is touching the start of its innermost containing autoclose
4108 /// region, expand it to select the brackets.
4109 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
4110 let selections = self.selections.all::<usize>(cx);
4111 let buffer = self.buffer.read(cx).read(cx);
4112 let new_selections = self
4113 .selections_with_autoclose_regions(selections, &buffer)
4114 .map(|(mut selection, region)| {
4115 if !selection.is_empty() {
4116 return selection;
4117 }
4118
4119 if let Some(region) = region {
4120 let mut range = region.range.to_offset(&buffer);
4121 if selection.start == range.start && range.start >= region.pair.start.len() {
4122 range.start -= region.pair.start.len();
4123 if buffer.contains_str_at(range.start, ®ion.pair.start)
4124 && buffer.contains_str_at(range.end, ®ion.pair.end)
4125 {
4126 range.end += region.pair.end.len();
4127 selection.start = range.start;
4128 selection.end = range.end;
4129
4130 return selection;
4131 }
4132 }
4133 }
4134
4135 let always_treat_brackets_as_autoclosed = buffer
4136 .settings_at(selection.start, cx)
4137 .always_treat_brackets_as_autoclosed;
4138
4139 if !always_treat_brackets_as_autoclosed {
4140 return selection;
4141 }
4142
4143 if let Some(scope) = buffer.language_scope_at(selection.start) {
4144 for (pair, enabled) in scope.brackets() {
4145 if !enabled || !pair.close {
4146 continue;
4147 }
4148
4149 if buffer.contains_str_at(selection.start, &pair.end) {
4150 let pair_start_len = pair.start.len();
4151 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
4152 {
4153 selection.start -= pair_start_len;
4154 selection.end += pair.end.len();
4155
4156 return selection;
4157 }
4158 }
4159 }
4160 }
4161
4162 selection
4163 })
4164 .collect();
4165
4166 drop(buffer);
4167 self.change_selections(None, cx, |selections| selections.select(new_selections));
4168 }
4169
4170 /// Iterate the given selections, and for each one, find the smallest surrounding
4171 /// autoclose region. This uses the ordering of the selections and the autoclose
4172 /// regions to avoid repeated comparisons.
4173 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4174 &'a self,
4175 selections: impl IntoIterator<Item = Selection<D>>,
4176 buffer: &'a MultiBufferSnapshot,
4177 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4178 let mut i = 0;
4179 let mut regions = self.autoclose_regions.as_slice();
4180 selections.into_iter().map(move |selection| {
4181 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4182
4183 let mut enclosing = None;
4184 while let Some(pair_state) = regions.get(i) {
4185 if pair_state.range.end.to_offset(buffer) < range.start {
4186 regions = ®ions[i + 1..];
4187 i = 0;
4188 } else if pair_state.range.start.to_offset(buffer) > range.end {
4189 break;
4190 } else {
4191 if pair_state.selection_id == selection.id {
4192 enclosing = Some(pair_state);
4193 }
4194 i += 1;
4195 }
4196 }
4197
4198 (selection, enclosing)
4199 })
4200 }
4201
4202 /// Remove any autoclose regions that no longer contain their selection.
4203 fn invalidate_autoclose_regions(
4204 &mut self,
4205 mut selections: &[Selection<Anchor>],
4206 buffer: &MultiBufferSnapshot,
4207 ) {
4208 self.autoclose_regions.retain(|state| {
4209 let mut i = 0;
4210 while let Some(selection) = selections.get(i) {
4211 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4212 selections = &selections[1..];
4213 continue;
4214 }
4215 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4216 break;
4217 }
4218 if selection.id == state.selection_id {
4219 return true;
4220 } else {
4221 i += 1;
4222 }
4223 }
4224 false
4225 });
4226 }
4227
4228 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4229 let offset = position.to_offset(buffer);
4230 let (word_range, kind) = buffer.surrounding_word(offset, true);
4231 if offset > word_range.start && kind == Some(CharKind::Word) {
4232 Some(
4233 buffer
4234 .text_for_range(word_range.start..offset)
4235 .collect::<String>(),
4236 )
4237 } else {
4238 None
4239 }
4240 }
4241
4242 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
4243 self.refresh_inlay_hints(
4244 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
4245 cx,
4246 );
4247 }
4248
4249 pub fn inlay_hints_enabled(&self) -> bool {
4250 self.inlay_hint_cache.enabled
4251 }
4252
4253 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
4254 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
4255 return;
4256 }
4257
4258 let reason_description = reason.description();
4259 let ignore_debounce = matches!(
4260 reason,
4261 InlayHintRefreshReason::SettingsChange(_)
4262 | InlayHintRefreshReason::Toggle(_)
4263 | InlayHintRefreshReason::ExcerptsRemoved(_)
4264 );
4265 let (invalidate_cache, required_languages) = match reason {
4266 InlayHintRefreshReason::Toggle(enabled) => {
4267 self.inlay_hint_cache.enabled = enabled;
4268 if enabled {
4269 (InvalidationStrategy::RefreshRequested, None)
4270 } else {
4271 self.inlay_hint_cache.clear();
4272 self.splice_inlays(
4273 self.visible_inlay_hints(cx)
4274 .iter()
4275 .map(|inlay| inlay.id)
4276 .collect(),
4277 Vec::new(),
4278 cx,
4279 );
4280 return;
4281 }
4282 }
4283 InlayHintRefreshReason::SettingsChange(new_settings) => {
4284 match self.inlay_hint_cache.update_settings(
4285 &self.buffer,
4286 new_settings,
4287 self.visible_inlay_hints(cx),
4288 cx,
4289 ) {
4290 ControlFlow::Break(Some(InlaySplice {
4291 to_remove,
4292 to_insert,
4293 })) => {
4294 self.splice_inlays(to_remove, to_insert, cx);
4295 return;
4296 }
4297 ControlFlow::Break(None) => return,
4298 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4299 }
4300 }
4301 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4302 if let Some(InlaySplice {
4303 to_remove,
4304 to_insert,
4305 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4306 {
4307 self.splice_inlays(to_remove, to_insert, cx);
4308 }
4309 return;
4310 }
4311 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4312 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4313 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4314 }
4315 InlayHintRefreshReason::RefreshRequested => {
4316 (InvalidationStrategy::RefreshRequested, None)
4317 }
4318 };
4319
4320 if let Some(InlaySplice {
4321 to_remove,
4322 to_insert,
4323 }) = self.inlay_hint_cache.spawn_hint_refresh(
4324 reason_description,
4325 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4326 invalidate_cache,
4327 ignore_debounce,
4328 cx,
4329 ) {
4330 self.splice_inlays(to_remove, to_insert, cx);
4331 }
4332 }
4333
4334 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4335 self.display_map
4336 .read(cx)
4337 .current_inlays()
4338 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4339 .cloned()
4340 .collect()
4341 }
4342
4343 pub fn excerpts_for_inlay_hints_query(
4344 &self,
4345 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4346 cx: &mut ViewContext<Editor>,
4347 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4348 let Some(project) = self.project.as_ref() else {
4349 return HashMap::default();
4350 };
4351 let project = project.read(cx);
4352 let multi_buffer = self.buffer().read(cx);
4353 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4354 let multi_buffer_visible_start = self
4355 .scroll_manager
4356 .anchor()
4357 .anchor
4358 .to_point(&multi_buffer_snapshot);
4359 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4360 multi_buffer_visible_start
4361 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4362 Bias::Left,
4363 );
4364 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4365 multi_buffer
4366 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4367 .into_iter()
4368 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4369 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4370 let buffer = buffer_handle.read(cx);
4371 let buffer_file = project::File::from_dyn(buffer.file())?;
4372 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4373 let worktree_entry = buffer_worktree
4374 .read(cx)
4375 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4376 if worktree_entry.is_ignored {
4377 return None;
4378 }
4379
4380 let language = buffer.language()?;
4381 if let Some(restrict_to_languages) = restrict_to_languages {
4382 if !restrict_to_languages.contains(language) {
4383 return None;
4384 }
4385 }
4386 Some((
4387 excerpt_id,
4388 (
4389 buffer_handle,
4390 buffer.version().clone(),
4391 excerpt_visible_range,
4392 ),
4393 ))
4394 })
4395 .collect()
4396 }
4397
4398 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4399 TextLayoutDetails {
4400 text_system: cx.text_system().clone(),
4401 editor_style: self.style.clone().unwrap(),
4402 rem_size: cx.rem_size(),
4403 scroll_anchor: self.scroll_manager.anchor(),
4404 visible_rows: self.visible_line_count(),
4405 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4406 }
4407 }
4408
4409 fn splice_inlays(
4410 &self,
4411 to_remove: Vec<InlayId>,
4412 to_insert: Vec<Inlay>,
4413 cx: &mut ViewContext<Self>,
4414 ) {
4415 self.display_map.update(cx, |display_map, cx| {
4416 display_map.splice_inlays(to_remove, to_insert, cx);
4417 });
4418 cx.notify();
4419 }
4420
4421 fn trigger_on_type_formatting(
4422 &self,
4423 input: String,
4424 cx: &mut ViewContext<Self>,
4425 ) -> Option<Task<Result<()>>> {
4426 if input.len() != 1 {
4427 return None;
4428 }
4429
4430 let project = self.project.as_ref()?;
4431 let position = self.selections.newest_anchor().head();
4432 let (buffer, buffer_position) = self
4433 .buffer
4434 .read(cx)
4435 .text_anchor_for_position(position, cx)?;
4436
4437 let settings = language_settings::language_settings(
4438 buffer
4439 .read(cx)
4440 .language_at(buffer_position)
4441 .map(|l| l.name()),
4442 buffer.read(cx).file(),
4443 cx,
4444 );
4445 if !settings.use_on_type_format {
4446 return None;
4447 }
4448
4449 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4450 // hence we do LSP request & edit on host side only — add formats to host's history.
4451 let push_to_lsp_host_history = true;
4452 // If this is not the host, append its history with new edits.
4453 let push_to_client_history = project.read(cx).is_via_collab();
4454
4455 let on_type_formatting = project.update(cx, |project, cx| {
4456 project.on_type_format(
4457 buffer.clone(),
4458 buffer_position,
4459 input,
4460 push_to_lsp_host_history,
4461 cx,
4462 )
4463 });
4464 Some(cx.spawn(|editor, mut cx| async move {
4465 if let Some(transaction) = on_type_formatting.await? {
4466 if push_to_client_history {
4467 buffer
4468 .update(&mut cx, |buffer, _| {
4469 buffer.push_transaction(transaction, Instant::now());
4470 })
4471 .ok();
4472 }
4473 editor.update(&mut cx, |editor, cx| {
4474 editor.refresh_document_highlights(cx);
4475 })?;
4476 }
4477 Ok(())
4478 }))
4479 }
4480
4481 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4482 if self.pending_rename.is_some() {
4483 return;
4484 }
4485
4486 let Some(provider) = self.completion_provider.as_ref() else {
4487 return;
4488 };
4489
4490 if !self.snippet_stack.is_empty() && self.context_menu.read().as_ref().is_some() {
4491 return;
4492 }
4493
4494 let position = self.selections.newest_anchor().head();
4495 let (buffer, buffer_position) =
4496 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4497 output
4498 } else {
4499 return;
4500 };
4501
4502 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4503 let is_followup_invoke = {
4504 let context_menu_state = self.context_menu.read();
4505 matches!(
4506 context_menu_state.deref(),
4507 Some(ContextMenu::Completions(_))
4508 )
4509 };
4510 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4511 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4512 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
4513 CompletionTriggerKind::TRIGGER_CHARACTER
4514 }
4515
4516 _ => CompletionTriggerKind::INVOKED,
4517 };
4518 let completion_context = CompletionContext {
4519 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4520 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4521 Some(String::from(trigger))
4522 } else {
4523 None
4524 }
4525 }),
4526 trigger_kind,
4527 };
4528 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4529 let sort_completions = provider.sort_completions();
4530
4531 let id = post_inc(&mut self.next_completion_id);
4532 let task = cx.spawn(|this, mut cx| {
4533 async move {
4534 this.update(&mut cx, |this, _| {
4535 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4536 })?;
4537 let completions = completions.await.log_err();
4538 let menu = if let Some(completions) = completions {
4539 let mut menu = CompletionsMenu::new(
4540 id,
4541 sort_completions,
4542 position,
4543 buffer.clone(),
4544 completions.into(),
4545 );
4546 menu.filter(query.as_deref(), cx.background_executor().clone())
4547 .await;
4548
4549 if menu.matches.is_empty() {
4550 None
4551 } else {
4552 this.update(&mut cx, |editor, cx| {
4553 let completions = menu.completions.clone();
4554 let matches = menu.matches.clone();
4555
4556 let delay_ms = EditorSettings::get_global(cx)
4557 .completion_documentation_secondary_query_debounce;
4558 let delay = Duration::from_millis(delay_ms);
4559 editor
4560 .completion_documentation_pre_resolve_debounce
4561 .fire_new(delay, cx, |editor, cx| {
4562 CompletionsMenu::pre_resolve_completion_documentation(
4563 buffer,
4564 completions,
4565 matches,
4566 editor,
4567 cx,
4568 )
4569 });
4570 })
4571 .ok();
4572 Some(menu)
4573 }
4574 } else {
4575 None
4576 };
4577
4578 this.update(&mut cx, |this, cx| {
4579 let mut context_menu = this.context_menu.write();
4580 match context_menu.as_ref() {
4581 None => {}
4582
4583 Some(ContextMenu::Completions(prev_menu)) => {
4584 if prev_menu.id > id {
4585 return;
4586 }
4587 }
4588
4589 _ => return,
4590 }
4591
4592 if this.focus_handle.is_focused(cx) && menu.is_some() {
4593 let menu = menu.unwrap();
4594 *context_menu = Some(ContextMenu::Completions(menu));
4595 drop(context_menu);
4596 this.discard_inline_completion(false, cx);
4597 cx.notify();
4598 } else if this.completion_tasks.len() <= 1 {
4599 // If there are no more completion tasks and the last menu was
4600 // empty, we should hide it. If it was already hidden, we should
4601 // also show the copilot completion when available.
4602 drop(context_menu);
4603 if this.hide_context_menu(cx).is_none() {
4604 this.update_visible_inline_completion(cx);
4605 }
4606 }
4607 })?;
4608
4609 Ok::<_, anyhow::Error>(())
4610 }
4611 .log_err()
4612 });
4613
4614 self.completion_tasks.push((id, task));
4615 }
4616
4617 pub fn confirm_completion(
4618 &mut self,
4619 action: &ConfirmCompletion,
4620 cx: &mut ViewContext<Self>,
4621 ) -> Option<Task<Result<()>>> {
4622 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4623 }
4624
4625 pub fn compose_completion(
4626 &mut self,
4627 action: &ComposeCompletion,
4628 cx: &mut ViewContext<Self>,
4629 ) -> Option<Task<Result<()>>> {
4630 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4631 }
4632
4633 fn do_completion(
4634 &mut self,
4635 item_ix: Option<usize>,
4636 intent: CompletionIntent,
4637 cx: &mut ViewContext<Editor>,
4638 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4639 use language::ToOffset as _;
4640
4641 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4642 menu
4643 } else {
4644 return None;
4645 };
4646
4647 let mat = completions_menu
4648 .matches
4649 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4650 let buffer_handle = completions_menu.buffer;
4651 let completions = completions_menu.completions.read();
4652 let completion = completions.get(mat.candidate_id)?;
4653 cx.stop_propagation();
4654
4655 let snippet;
4656 let text;
4657
4658 if completion.is_snippet() {
4659 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4660 text = snippet.as_ref().unwrap().text.clone();
4661 } else {
4662 snippet = None;
4663 text = completion.new_text.clone();
4664 };
4665 let selections = self.selections.all::<usize>(cx);
4666 let buffer = buffer_handle.read(cx);
4667 let old_range = completion.old_range.to_offset(buffer);
4668 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4669
4670 let newest_selection = self.selections.newest_anchor();
4671 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4672 return None;
4673 }
4674
4675 let lookbehind = newest_selection
4676 .start
4677 .text_anchor
4678 .to_offset(buffer)
4679 .saturating_sub(old_range.start);
4680 let lookahead = old_range
4681 .end
4682 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4683 let mut common_prefix_len = old_text
4684 .bytes()
4685 .zip(text.bytes())
4686 .take_while(|(a, b)| a == b)
4687 .count();
4688
4689 let snapshot = self.buffer.read(cx).snapshot(cx);
4690 let mut range_to_replace: Option<Range<isize>> = None;
4691 let mut ranges = Vec::new();
4692 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4693 for selection in &selections {
4694 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4695 let start = selection.start.saturating_sub(lookbehind);
4696 let end = selection.end + lookahead;
4697 if selection.id == newest_selection.id {
4698 range_to_replace = Some(
4699 ((start + common_prefix_len) as isize - selection.start as isize)
4700 ..(end as isize - selection.start as isize),
4701 );
4702 }
4703 ranges.push(start + common_prefix_len..end);
4704 } else {
4705 common_prefix_len = 0;
4706 ranges.clear();
4707 ranges.extend(selections.iter().map(|s| {
4708 if s.id == newest_selection.id {
4709 range_to_replace = Some(
4710 old_range.start.to_offset_utf16(&snapshot).0 as isize
4711 - selection.start as isize
4712 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4713 - selection.start as isize,
4714 );
4715 old_range.clone()
4716 } else {
4717 s.start..s.end
4718 }
4719 }));
4720 break;
4721 }
4722 if !self.linked_edit_ranges.is_empty() {
4723 let start_anchor = snapshot.anchor_before(selection.head());
4724 let end_anchor = snapshot.anchor_after(selection.tail());
4725 if let Some(ranges) = self
4726 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4727 {
4728 for (buffer, edits) in ranges {
4729 linked_edits.entry(buffer.clone()).or_default().extend(
4730 edits
4731 .into_iter()
4732 .map(|range| (range, text[common_prefix_len..].to_owned())),
4733 );
4734 }
4735 }
4736 }
4737 }
4738 let text = &text[common_prefix_len..];
4739
4740 cx.emit(EditorEvent::InputHandled {
4741 utf16_range_to_replace: range_to_replace,
4742 text: text.into(),
4743 });
4744
4745 self.transact(cx, |this, cx| {
4746 if let Some(mut snippet) = snippet {
4747 snippet.text = text.to_string();
4748 for tabstop in snippet
4749 .tabstops
4750 .iter_mut()
4751 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4752 {
4753 tabstop.start -= common_prefix_len as isize;
4754 tabstop.end -= common_prefix_len as isize;
4755 }
4756
4757 this.insert_snippet(&ranges, snippet, cx).log_err();
4758 } else {
4759 this.buffer.update(cx, |buffer, cx| {
4760 buffer.edit(
4761 ranges.iter().map(|range| (range.clone(), text)),
4762 this.autoindent_mode.clone(),
4763 cx,
4764 );
4765 });
4766 }
4767 for (buffer, edits) in linked_edits {
4768 buffer.update(cx, |buffer, cx| {
4769 let snapshot = buffer.snapshot();
4770 let edits = edits
4771 .into_iter()
4772 .map(|(range, text)| {
4773 use text::ToPoint as TP;
4774 let end_point = TP::to_point(&range.end, &snapshot);
4775 let start_point = TP::to_point(&range.start, &snapshot);
4776 (start_point..end_point, text)
4777 })
4778 .sorted_by_key(|(range, _)| range.start)
4779 .collect::<Vec<_>>();
4780 buffer.edit(edits, None, cx);
4781 })
4782 }
4783
4784 this.refresh_inline_completion(true, false, cx);
4785 });
4786
4787 let show_new_completions_on_confirm = completion
4788 .confirm
4789 .as_ref()
4790 .map_or(false, |confirm| confirm(intent, cx));
4791 if show_new_completions_on_confirm {
4792 self.show_completions(&ShowCompletions { trigger: None }, cx);
4793 }
4794
4795 let provider = self.completion_provider.as_ref()?;
4796 let apply_edits = provider.apply_additional_edits_for_completion(
4797 buffer_handle,
4798 completion.clone(),
4799 true,
4800 cx,
4801 );
4802
4803 let editor_settings = EditorSettings::get_global(cx);
4804 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4805 // After the code completion is finished, users often want to know what signatures are needed.
4806 // so we should automatically call signature_help
4807 self.show_signature_help(&ShowSignatureHelp, cx);
4808 }
4809
4810 Some(cx.foreground_executor().spawn(async move {
4811 apply_edits.await?;
4812 Ok(())
4813 }))
4814 }
4815
4816 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4817 let mut context_menu = self.context_menu.write();
4818 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4819 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4820 // Toggle if we're selecting the same one
4821 *context_menu = None;
4822 cx.notify();
4823 return;
4824 } else {
4825 // Otherwise, clear it and start a new one
4826 *context_menu = None;
4827 cx.notify();
4828 }
4829 }
4830 drop(context_menu);
4831 let snapshot = self.snapshot(cx);
4832 let deployed_from_indicator = action.deployed_from_indicator;
4833 let mut task = self.code_actions_task.take();
4834 let action = action.clone();
4835 cx.spawn(|editor, mut cx| async move {
4836 while let Some(prev_task) = task {
4837 prev_task.await.log_err();
4838 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4839 }
4840
4841 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4842 if editor.focus_handle.is_focused(cx) {
4843 let multibuffer_point = action
4844 .deployed_from_indicator
4845 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4846 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4847 let (buffer, buffer_row) = snapshot
4848 .buffer_snapshot
4849 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4850 .and_then(|(buffer_snapshot, range)| {
4851 editor
4852 .buffer
4853 .read(cx)
4854 .buffer(buffer_snapshot.remote_id())
4855 .map(|buffer| (buffer, range.start.row))
4856 })?;
4857 let (_, code_actions) = editor
4858 .available_code_actions
4859 .clone()
4860 .and_then(|(location, code_actions)| {
4861 let snapshot = location.buffer.read(cx).snapshot();
4862 let point_range = location.range.to_point(&snapshot);
4863 let point_range = point_range.start.row..=point_range.end.row;
4864 if point_range.contains(&buffer_row) {
4865 Some((location, code_actions))
4866 } else {
4867 None
4868 }
4869 })
4870 .unzip();
4871 let buffer_id = buffer.read(cx).remote_id();
4872 let tasks = editor
4873 .tasks
4874 .get(&(buffer_id, buffer_row))
4875 .map(|t| Arc::new(t.to_owned()));
4876 if tasks.is_none() && code_actions.is_none() {
4877 return None;
4878 }
4879
4880 editor.completion_tasks.clear();
4881 editor.discard_inline_completion(false, cx);
4882 let task_context =
4883 tasks
4884 .as_ref()
4885 .zip(editor.project.clone())
4886 .map(|(tasks, project)| {
4887 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4888 });
4889
4890 Some(cx.spawn(|editor, mut cx| async move {
4891 let task_context = match task_context {
4892 Some(task_context) => task_context.await,
4893 None => None,
4894 };
4895 let resolved_tasks =
4896 tasks.zip(task_context).map(|(tasks, task_context)| {
4897 Arc::new(ResolvedTasks {
4898 templates: tasks.resolve(&task_context).collect(),
4899 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4900 multibuffer_point.row,
4901 tasks.column,
4902 )),
4903 })
4904 });
4905 let spawn_straight_away = resolved_tasks
4906 .as_ref()
4907 .map_or(false, |tasks| tasks.templates.len() == 1)
4908 && code_actions
4909 .as_ref()
4910 .map_or(true, |actions| actions.is_empty());
4911 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4912 *editor.context_menu.write() =
4913 Some(ContextMenu::CodeActions(CodeActionsMenu {
4914 buffer,
4915 actions: CodeActionContents {
4916 tasks: resolved_tasks,
4917 actions: code_actions,
4918 },
4919 selected_item: Default::default(),
4920 scroll_handle: UniformListScrollHandle::default(),
4921 deployed_from_indicator,
4922 }));
4923 if spawn_straight_away {
4924 if let Some(task) = editor.confirm_code_action(
4925 &ConfirmCodeAction { item_ix: Some(0) },
4926 cx,
4927 ) {
4928 cx.notify();
4929 return task;
4930 }
4931 }
4932 cx.notify();
4933 Task::ready(Ok(()))
4934 }) {
4935 task.await
4936 } else {
4937 Ok(())
4938 }
4939 }))
4940 } else {
4941 Some(Task::ready(Ok(())))
4942 }
4943 })?;
4944 if let Some(task) = spawned_test_task {
4945 task.await?;
4946 }
4947
4948 Ok::<_, anyhow::Error>(())
4949 })
4950 .detach_and_log_err(cx);
4951 }
4952
4953 pub fn confirm_code_action(
4954 &mut self,
4955 action: &ConfirmCodeAction,
4956 cx: &mut ViewContext<Self>,
4957 ) -> Option<Task<Result<()>>> {
4958 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4959 menu
4960 } else {
4961 return None;
4962 };
4963 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4964 let action = actions_menu.actions.get(action_ix)?;
4965 let title = action.label();
4966 let buffer = actions_menu.buffer;
4967 let workspace = self.workspace()?;
4968
4969 match action {
4970 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4971 workspace.update(cx, |workspace, cx| {
4972 workspace::tasks::schedule_resolved_task(
4973 workspace,
4974 task_source_kind,
4975 resolved_task,
4976 false,
4977 cx,
4978 );
4979
4980 Some(Task::ready(Ok(())))
4981 })
4982 }
4983 CodeActionsItem::CodeAction {
4984 excerpt_id,
4985 action,
4986 provider,
4987 } => {
4988 let apply_code_action =
4989 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4990 let workspace = workspace.downgrade();
4991 Some(cx.spawn(|editor, cx| async move {
4992 let project_transaction = apply_code_action.await?;
4993 Self::open_project_transaction(
4994 &editor,
4995 workspace,
4996 project_transaction,
4997 title,
4998 cx,
4999 )
5000 .await
5001 }))
5002 }
5003 }
5004 }
5005
5006 pub async fn open_project_transaction(
5007 this: &WeakView<Editor>,
5008 workspace: WeakView<Workspace>,
5009 transaction: ProjectTransaction,
5010 title: String,
5011 mut cx: AsyncWindowContext,
5012 ) -> Result<()> {
5013 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
5014 cx.update(|cx| {
5015 entries.sort_unstable_by_key(|(buffer, _)| {
5016 buffer.read(cx).file().map(|f| f.path().clone())
5017 });
5018 })?;
5019
5020 // If the project transaction's edits are all contained within this editor, then
5021 // avoid opening a new editor to display them.
5022
5023 if let Some((buffer, transaction)) = entries.first() {
5024 if entries.len() == 1 {
5025 let excerpt = this.update(&mut cx, |editor, cx| {
5026 editor
5027 .buffer()
5028 .read(cx)
5029 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
5030 })?;
5031 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
5032 if excerpted_buffer == *buffer {
5033 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
5034 let excerpt_range = excerpt_range.to_offset(buffer);
5035 buffer
5036 .edited_ranges_for_transaction::<usize>(transaction)
5037 .all(|range| {
5038 excerpt_range.start <= range.start
5039 && excerpt_range.end >= range.end
5040 })
5041 })?;
5042
5043 if all_edits_within_excerpt {
5044 return Ok(());
5045 }
5046 }
5047 }
5048 }
5049 } else {
5050 return Ok(());
5051 }
5052
5053 let mut ranges_to_highlight = Vec::new();
5054 let excerpt_buffer = cx.new_model(|cx| {
5055 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5056 for (buffer_handle, transaction) in &entries {
5057 let buffer = buffer_handle.read(cx);
5058 ranges_to_highlight.extend(
5059 multibuffer.push_excerpts_with_context_lines(
5060 buffer_handle.clone(),
5061 buffer
5062 .edited_ranges_for_transaction::<usize>(transaction)
5063 .collect(),
5064 DEFAULT_MULTIBUFFER_CONTEXT,
5065 cx,
5066 ),
5067 );
5068 }
5069 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5070 multibuffer
5071 })?;
5072
5073 workspace.update(&mut cx, |workspace, cx| {
5074 let project = workspace.project().clone();
5075 let editor =
5076 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
5077 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
5078 editor.update(cx, |editor, cx| {
5079 editor.highlight_background::<Self>(
5080 &ranges_to_highlight,
5081 |theme| theme.editor_highlighted_line_background,
5082 cx,
5083 );
5084 });
5085 })?;
5086
5087 Ok(())
5088 }
5089
5090 pub fn clear_code_action_providers(&mut self) {
5091 self.code_action_providers.clear();
5092 self.available_code_actions.take();
5093 }
5094
5095 pub fn push_code_action_provider(
5096 &mut self,
5097 provider: Arc<dyn CodeActionProvider>,
5098 cx: &mut ViewContext<Self>,
5099 ) {
5100 self.code_action_providers.push(provider);
5101 self.refresh_code_actions(cx);
5102 }
5103
5104 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5105 let buffer = self.buffer.read(cx);
5106 let newest_selection = self.selections.newest_anchor().clone();
5107 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
5108 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
5109 if start_buffer != end_buffer {
5110 return None;
5111 }
5112
5113 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
5114 cx.background_executor()
5115 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5116 .await;
5117
5118 let (providers, tasks) = this.update(&mut cx, |this, cx| {
5119 let providers = this.code_action_providers.clone();
5120 let tasks = this
5121 .code_action_providers
5122 .iter()
5123 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
5124 .collect::<Vec<_>>();
5125 (providers, tasks)
5126 })?;
5127
5128 let mut actions = Vec::new();
5129 for (provider, provider_actions) in
5130 providers.into_iter().zip(future::join_all(tasks).await)
5131 {
5132 if let Some(provider_actions) = provider_actions.log_err() {
5133 actions.extend(provider_actions.into_iter().map(|action| {
5134 AvailableCodeAction {
5135 excerpt_id: newest_selection.start.excerpt_id,
5136 action,
5137 provider: provider.clone(),
5138 }
5139 }));
5140 }
5141 }
5142
5143 this.update(&mut cx, |this, cx| {
5144 this.available_code_actions = if actions.is_empty() {
5145 None
5146 } else {
5147 Some((
5148 Location {
5149 buffer: start_buffer,
5150 range: start..end,
5151 },
5152 actions.into(),
5153 ))
5154 };
5155 cx.notify();
5156 })
5157 }));
5158 None
5159 }
5160
5161 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
5162 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5163 self.show_git_blame_inline = false;
5164
5165 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
5166 cx.background_executor().timer(delay).await;
5167
5168 this.update(&mut cx, |this, cx| {
5169 this.show_git_blame_inline = true;
5170 cx.notify();
5171 })
5172 .log_err();
5173 }));
5174 }
5175 }
5176
5177 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5178 if self.pending_rename.is_some() {
5179 return None;
5180 }
5181
5182 let provider = self.semantics_provider.clone()?;
5183 let buffer = self.buffer.read(cx);
5184 let newest_selection = self.selections.newest_anchor().clone();
5185 let cursor_position = newest_selection.head();
5186 let (cursor_buffer, cursor_buffer_position) =
5187 buffer.text_anchor_for_position(cursor_position, cx)?;
5188 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5189 if cursor_buffer != tail_buffer {
5190 return None;
5191 }
5192
5193 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
5194 cx.background_executor()
5195 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
5196 .await;
5197
5198 let highlights = if let Some(highlights) = cx
5199 .update(|cx| {
5200 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5201 })
5202 .ok()
5203 .flatten()
5204 {
5205 highlights.await.log_err()
5206 } else {
5207 None
5208 };
5209
5210 if let Some(highlights) = highlights {
5211 this.update(&mut cx, |this, cx| {
5212 if this.pending_rename.is_some() {
5213 return;
5214 }
5215
5216 let buffer_id = cursor_position.buffer_id;
5217 let buffer = this.buffer.read(cx);
5218 if !buffer
5219 .text_anchor_for_position(cursor_position, cx)
5220 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5221 {
5222 return;
5223 }
5224
5225 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5226 let mut write_ranges = Vec::new();
5227 let mut read_ranges = Vec::new();
5228 for highlight in highlights {
5229 for (excerpt_id, excerpt_range) in
5230 buffer.excerpts_for_buffer(&cursor_buffer, cx)
5231 {
5232 let start = highlight
5233 .range
5234 .start
5235 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5236 let end = highlight
5237 .range
5238 .end
5239 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5240 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5241 continue;
5242 }
5243
5244 let range = Anchor {
5245 buffer_id,
5246 excerpt_id,
5247 text_anchor: start,
5248 }..Anchor {
5249 buffer_id,
5250 excerpt_id,
5251 text_anchor: end,
5252 };
5253 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5254 write_ranges.push(range);
5255 } else {
5256 read_ranges.push(range);
5257 }
5258 }
5259 }
5260
5261 this.highlight_background::<DocumentHighlightRead>(
5262 &read_ranges,
5263 |theme| theme.editor_document_highlight_read_background,
5264 cx,
5265 );
5266 this.highlight_background::<DocumentHighlightWrite>(
5267 &write_ranges,
5268 |theme| theme.editor_document_highlight_write_background,
5269 cx,
5270 );
5271 cx.notify();
5272 })
5273 .log_err();
5274 }
5275 }));
5276 None
5277 }
5278
5279 pub fn refresh_inline_completion(
5280 &mut self,
5281 debounce: bool,
5282 user_requested: bool,
5283 cx: &mut ViewContext<Self>,
5284 ) -> Option<()> {
5285 let provider = self.inline_completion_provider()?;
5286 let cursor = self.selections.newest_anchor().head();
5287 let (buffer, cursor_buffer_position) =
5288 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5289
5290 if !user_requested
5291 && (!self.enable_inline_completions
5292 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
5293 {
5294 self.discard_inline_completion(false, cx);
5295 return None;
5296 }
5297
5298 self.update_visible_inline_completion(cx);
5299 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
5300 Some(())
5301 }
5302
5303 fn cycle_inline_completion(
5304 &mut self,
5305 direction: Direction,
5306 cx: &mut ViewContext<Self>,
5307 ) -> Option<()> {
5308 let provider = self.inline_completion_provider()?;
5309 let cursor = self.selections.newest_anchor().head();
5310 let (buffer, cursor_buffer_position) =
5311 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5312 if !self.enable_inline_completions
5313 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5314 {
5315 return None;
5316 }
5317
5318 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5319 self.update_visible_inline_completion(cx);
5320
5321 Some(())
5322 }
5323
5324 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5325 if !self.has_active_inline_completion(cx) {
5326 self.refresh_inline_completion(false, true, cx);
5327 return;
5328 }
5329
5330 self.update_visible_inline_completion(cx);
5331 }
5332
5333 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5334 self.show_cursor_names(cx);
5335 }
5336
5337 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5338 self.show_cursor_names = true;
5339 cx.notify();
5340 cx.spawn(|this, mut cx| async move {
5341 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5342 this.update(&mut cx, |this, cx| {
5343 this.show_cursor_names = false;
5344 cx.notify()
5345 })
5346 .ok()
5347 })
5348 .detach();
5349 }
5350
5351 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5352 if self.has_active_inline_completion(cx) {
5353 self.cycle_inline_completion(Direction::Next, cx);
5354 } else {
5355 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5356 if is_copilot_disabled {
5357 cx.propagate();
5358 }
5359 }
5360 }
5361
5362 pub fn previous_inline_completion(
5363 &mut self,
5364 _: &PreviousInlineCompletion,
5365 cx: &mut ViewContext<Self>,
5366 ) {
5367 if self.has_active_inline_completion(cx) {
5368 self.cycle_inline_completion(Direction::Prev, cx);
5369 } else {
5370 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5371 if is_copilot_disabled {
5372 cx.propagate();
5373 }
5374 }
5375 }
5376
5377 pub fn accept_inline_completion(
5378 &mut self,
5379 _: &AcceptInlineCompletion,
5380 cx: &mut ViewContext<Self>,
5381 ) {
5382 let Some(completion) = self.take_active_inline_completion(cx) else {
5383 return;
5384 };
5385 if let Some(provider) = self.inline_completion_provider() {
5386 provider.accept(cx);
5387 }
5388
5389 cx.emit(EditorEvent::InputHandled {
5390 utf16_range_to_replace: None,
5391 text: completion.text.to_string().into(),
5392 });
5393
5394 if let Some(range) = completion.delete_range {
5395 self.change_selections(None, cx, |s| s.select_ranges([range]))
5396 }
5397 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5398 self.refresh_inline_completion(true, true, cx);
5399 cx.notify();
5400 }
5401
5402 pub fn accept_partial_inline_completion(
5403 &mut self,
5404 _: &AcceptPartialInlineCompletion,
5405 cx: &mut ViewContext<Self>,
5406 ) {
5407 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5408 if let Some(completion) = self.take_active_inline_completion(cx) {
5409 let mut partial_completion = completion
5410 .text
5411 .chars()
5412 .by_ref()
5413 .take_while(|c| c.is_alphabetic())
5414 .collect::<String>();
5415 if partial_completion.is_empty() {
5416 partial_completion = completion
5417 .text
5418 .chars()
5419 .by_ref()
5420 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5421 .collect::<String>();
5422 }
5423
5424 cx.emit(EditorEvent::InputHandled {
5425 utf16_range_to_replace: None,
5426 text: partial_completion.clone().into(),
5427 });
5428
5429 if let Some(range) = completion.delete_range {
5430 self.change_selections(None, cx, |s| s.select_ranges([range]))
5431 }
5432 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5433
5434 self.refresh_inline_completion(true, true, cx);
5435 cx.notify();
5436 }
5437 }
5438 }
5439
5440 fn discard_inline_completion(
5441 &mut self,
5442 should_report_inline_completion_event: bool,
5443 cx: &mut ViewContext<Self>,
5444 ) -> bool {
5445 if let Some(provider) = self.inline_completion_provider() {
5446 provider.discard(should_report_inline_completion_event, cx);
5447 }
5448
5449 self.take_active_inline_completion(cx).is_some()
5450 }
5451
5452 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5453 if let Some(completion) = self.active_inline_completion.as_ref() {
5454 let buffer = self.buffer.read(cx).read(cx);
5455 completion.position.is_valid(&buffer)
5456 } else {
5457 false
5458 }
5459 }
5460
5461 fn take_active_inline_completion(
5462 &mut self,
5463 cx: &mut ViewContext<Self>,
5464 ) -> Option<CompletionState> {
5465 let completion = self.active_inline_completion.take()?;
5466 let render_inlay_ids = completion.render_inlay_ids.clone();
5467 self.display_map.update(cx, |map, cx| {
5468 map.splice_inlays(render_inlay_ids, Default::default(), cx);
5469 });
5470 let buffer = self.buffer.read(cx).read(cx);
5471
5472 if completion.position.is_valid(&buffer) {
5473 Some(completion)
5474 } else {
5475 None
5476 }
5477 }
5478
5479 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5480 let selection = self.selections.newest_anchor();
5481 let cursor = selection.head();
5482
5483 let excerpt_id = cursor.excerpt_id;
5484
5485 if self.context_menu.read().is_none()
5486 && self.completion_tasks.is_empty()
5487 && selection.start == selection.end
5488 {
5489 if let Some(provider) = self.inline_completion_provider() {
5490 if let Some((buffer, cursor_buffer_position)) =
5491 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5492 {
5493 if let Some(proposal) =
5494 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5495 {
5496 let mut to_remove = Vec::new();
5497 if let Some(completion) = self.active_inline_completion.take() {
5498 to_remove.extend(completion.render_inlay_ids.iter());
5499 }
5500
5501 let to_add = proposal
5502 .inlays
5503 .iter()
5504 .filter_map(|inlay| {
5505 let snapshot = self.buffer.read(cx).snapshot(cx);
5506 let id = post_inc(&mut self.next_inlay_id);
5507 match inlay {
5508 InlayProposal::Hint(position, hint) => {
5509 let position =
5510 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5511 Some(Inlay::hint(id, position, hint))
5512 }
5513 InlayProposal::Suggestion(position, text) => {
5514 let position =
5515 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5516 Some(Inlay::suggestion(id, position, text.clone()))
5517 }
5518 }
5519 })
5520 .collect_vec();
5521
5522 self.active_inline_completion = Some(CompletionState {
5523 position: cursor,
5524 text: proposal.text,
5525 delete_range: proposal.delete_range.and_then(|range| {
5526 let snapshot = self.buffer.read(cx).snapshot(cx);
5527 let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
5528 let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
5529 Some(start?..end?)
5530 }),
5531 render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
5532 });
5533
5534 self.display_map
5535 .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
5536
5537 cx.notify();
5538 return;
5539 }
5540 }
5541 }
5542 }
5543
5544 self.discard_inline_completion(false, cx);
5545 }
5546
5547 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5548 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5549 }
5550
5551 fn render_code_actions_indicator(
5552 &self,
5553 _style: &EditorStyle,
5554 row: DisplayRow,
5555 is_active: bool,
5556 cx: &mut ViewContext<Self>,
5557 ) -> Option<IconButton> {
5558 if self.available_code_actions.is_some() {
5559 Some(
5560 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5561 .shape(ui::IconButtonShape::Square)
5562 .icon_size(IconSize::XSmall)
5563 .icon_color(Color::Muted)
5564 .selected(is_active)
5565 .tooltip({
5566 let focus_handle = self.focus_handle.clone();
5567 move |cx| {
5568 Tooltip::for_action_in(
5569 "Toggle Code Actions",
5570 &ToggleCodeActions {
5571 deployed_from_indicator: None,
5572 },
5573 &focus_handle,
5574 cx,
5575 )
5576 }
5577 })
5578 .on_click(cx.listener(move |editor, _e, cx| {
5579 editor.focus(cx);
5580 editor.toggle_code_actions(
5581 &ToggleCodeActions {
5582 deployed_from_indicator: Some(row),
5583 },
5584 cx,
5585 );
5586 })),
5587 )
5588 } else {
5589 None
5590 }
5591 }
5592
5593 fn clear_tasks(&mut self) {
5594 self.tasks.clear()
5595 }
5596
5597 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5598 if self.tasks.insert(key, value).is_some() {
5599 // This case should hopefully be rare, but just in case...
5600 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5601 }
5602 }
5603
5604 fn build_tasks_context(
5605 project: &Model<Project>,
5606 buffer: &Model<Buffer>,
5607 buffer_row: u32,
5608 tasks: &Arc<RunnableTasks>,
5609 cx: &mut ViewContext<Self>,
5610 ) -> Task<Option<task::TaskContext>> {
5611 let position = Point::new(buffer_row, tasks.column);
5612 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5613 let location = Location {
5614 buffer: buffer.clone(),
5615 range: range_start..range_start,
5616 };
5617 // Fill in the environmental variables from the tree-sitter captures
5618 let mut captured_task_variables = TaskVariables::default();
5619 for (capture_name, value) in tasks.extra_variables.clone() {
5620 captured_task_variables.insert(
5621 task::VariableName::Custom(capture_name.into()),
5622 value.clone(),
5623 );
5624 }
5625 project.update(cx, |project, cx| {
5626 project.task_store().update(cx, |task_store, cx| {
5627 task_store.task_context_for_location(captured_task_variables, location, cx)
5628 })
5629 })
5630 }
5631
5632 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
5633 let Some((workspace, _)) = self.workspace.clone() else {
5634 return;
5635 };
5636 let Some(project) = self.project.clone() else {
5637 return;
5638 };
5639
5640 // Try to find a closest, enclosing node using tree-sitter that has a
5641 // task
5642 let Some((buffer, buffer_row, tasks)) = self
5643 .find_enclosing_node_task(cx)
5644 // Or find the task that's closest in row-distance.
5645 .or_else(|| self.find_closest_task(cx))
5646 else {
5647 return;
5648 };
5649
5650 let reveal_strategy = action.reveal;
5651 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5652 cx.spawn(|_, mut cx| async move {
5653 let context = task_context.await?;
5654 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5655
5656 let resolved = resolved_task.resolved.as_mut()?;
5657 resolved.reveal = reveal_strategy;
5658
5659 workspace
5660 .update(&mut cx, |workspace, cx| {
5661 workspace::tasks::schedule_resolved_task(
5662 workspace,
5663 task_source_kind,
5664 resolved_task,
5665 false,
5666 cx,
5667 );
5668 })
5669 .ok()
5670 })
5671 .detach();
5672 }
5673
5674 fn find_closest_task(
5675 &mut self,
5676 cx: &mut ViewContext<Self>,
5677 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5678 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5679
5680 let ((buffer_id, row), tasks) = self
5681 .tasks
5682 .iter()
5683 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5684
5685 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5686 let tasks = Arc::new(tasks.to_owned());
5687 Some((buffer, *row, tasks))
5688 }
5689
5690 fn find_enclosing_node_task(
5691 &mut self,
5692 cx: &mut ViewContext<Self>,
5693 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5694 let snapshot = self.buffer.read(cx).snapshot(cx);
5695 let offset = self.selections.newest::<usize>(cx).head();
5696 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5697 let buffer_id = excerpt.buffer().remote_id();
5698
5699 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5700 let mut cursor = layer.node().walk();
5701
5702 while cursor.goto_first_child_for_byte(offset).is_some() {
5703 if cursor.node().end_byte() == offset {
5704 cursor.goto_next_sibling();
5705 }
5706 }
5707
5708 // Ascend to the smallest ancestor that contains the range and has a task.
5709 loop {
5710 let node = cursor.node();
5711 let node_range = node.byte_range();
5712 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5713
5714 // Check if this node contains our offset
5715 if node_range.start <= offset && node_range.end >= offset {
5716 // If it contains offset, check for task
5717 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5718 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5719 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5720 }
5721 }
5722
5723 if !cursor.goto_parent() {
5724 break;
5725 }
5726 }
5727 None
5728 }
5729
5730 fn render_run_indicator(
5731 &self,
5732 _style: &EditorStyle,
5733 is_active: bool,
5734 row: DisplayRow,
5735 cx: &mut ViewContext<Self>,
5736 ) -> IconButton {
5737 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5738 .shape(ui::IconButtonShape::Square)
5739 .icon_size(IconSize::XSmall)
5740 .icon_color(Color::Muted)
5741 .selected(is_active)
5742 .on_click(cx.listener(move |editor, _e, cx| {
5743 editor.focus(cx);
5744 editor.toggle_code_actions(
5745 &ToggleCodeActions {
5746 deployed_from_indicator: Some(row),
5747 },
5748 cx,
5749 );
5750 }))
5751 }
5752
5753 pub fn context_menu_visible(&self) -> bool {
5754 self.context_menu
5755 .read()
5756 .as_ref()
5757 .map_or(false, |menu| menu.visible())
5758 }
5759
5760 fn render_context_menu(
5761 &self,
5762 cursor_position: DisplayPoint,
5763 style: &EditorStyle,
5764 max_height: Pixels,
5765 cx: &mut ViewContext<Editor>,
5766 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5767 self.context_menu.read().as_ref().map(|menu| {
5768 menu.render(
5769 cursor_position,
5770 style,
5771 max_height,
5772 self.workspace.as_ref().map(|(w, _)| w.clone()),
5773 cx,
5774 )
5775 })
5776 }
5777
5778 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5779 cx.notify();
5780 self.completion_tasks.clear();
5781 let context_menu = self.context_menu.write().take();
5782 if context_menu.is_some() {
5783 self.update_visible_inline_completion(cx);
5784 }
5785 context_menu
5786 }
5787
5788 fn show_snippet_choices(
5789 &mut self,
5790 choices: &Vec<String>,
5791 selection: Range<Anchor>,
5792 cx: &mut ViewContext<Self>,
5793 ) {
5794 if selection.start.buffer_id.is_none() {
5795 return;
5796 }
5797 let buffer_id = selection.start.buffer_id.unwrap();
5798 let buffer = self.buffer().read(cx).buffer(buffer_id);
5799 let id = post_inc(&mut self.next_completion_id);
5800
5801 if let Some(buffer) = buffer {
5802 *self.context_menu.write() = Some(ContextMenu::Completions(
5803 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer)
5804 .suppress_documentation_resolution(),
5805 ));
5806 }
5807 }
5808
5809 pub fn insert_snippet(
5810 &mut self,
5811 insertion_ranges: &[Range<usize>],
5812 snippet: Snippet,
5813 cx: &mut ViewContext<Self>,
5814 ) -> Result<()> {
5815 struct Tabstop<T> {
5816 is_end_tabstop: bool,
5817 ranges: Vec<Range<T>>,
5818 choices: Option<Vec<String>>,
5819 }
5820
5821 let tabstops = self.buffer.update(cx, |buffer, cx| {
5822 let snippet_text: Arc<str> = snippet.text.clone().into();
5823 buffer.edit(
5824 insertion_ranges
5825 .iter()
5826 .cloned()
5827 .map(|range| (range, snippet_text.clone())),
5828 Some(AutoindentMode::EachLine),
5829 cx,
5830 );
5831
5832 let snapshot = &*buffer.read(cx);
5833 let snippet = &snippet;
5834 snippet
5835 .tabstops
5836 .iter()
5837 .map(|tabstop| {
5838 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5839 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5840 });
5841 let mut tabstop_ranges = tabstop
5842 .ranges
5843 .iter()
5844 .flat_map(|tabstop_range| {
5845 let mut delta = 0_isize;
5846 insertion_ranges.iter().map(move |insertion_range| {
5847 let insertion_start = insertion_range.start as isize + delta;
5848 delta +=
5849 snippet.text.len() as isize - insertion_range.len() as isize;
5850
5851 let start = ((insertion_start + tabstop_range.start) as usize)
5852 .min(snapshot.len());
5853 let end = ((insertion_start + tabstop_range.end) as usize)
5854 .min(snapshot.len());
5855 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5856 })
5857 })
5858 .collect::<Vec<_>>();
5859 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5860
5861 Tabstop {
5862 is_end_tabstop,
5863 ranges: tabstop_ranges,
5864 choices: tabstop.choices.clone(),
5865 }
5866 })
5867 .collect::<Vec<_>>()
5868 });
5869 if let Some(tabstop) = tabstops.first() {
5870 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5871 s.select_ranges(tabstop.ranges.iter().cloned());
5872 });
5873
5874 if let Some(choices) = &tabstop.choices {
5875 if let Some(selection) = tabstop.ranges.first() {
5876 self.show_snippet_choices(choices, selection.clone(), cx)
5877 }
5878 }
5879
5880 // If we're already at the last tabstop and it's at the end of the snippet,
5881 // we're done, we don't need to keep the state around.
5882 if !tabstop.is_end_tabstop {
5883 let choices = tabstops
5884 .iter()
5885 .map(|tabstop| tabstop.choices.clone())
5886 .collect();
5887
5888 let ranges = tabstops
5889 .into_iter()
5890 .map(|tabstop| tabstop.ranges)
5891 .collect::<Vec<_>>();
5892
5893 self.snippet_stack.push(SnippetState {
5894 active_index: 0,
5895 ranges,
5896 choices,
5897 });
5898 }
5899
5900 // Check whether the just-entered snippet ends with an auto-closable bracket.
5901 if self.autoclose_regions.is_empty() {
5902 let snapshot = self.buffer.read(cx).snapshot(cx);
5903 for selection in &mut self.selections.all::<Point>(cx) {
5904 let selection_head = selection.head();
5905 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5906 continue;
5907 };
5908
5909 let mut bracket_pair = None;
5910 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5911 let prev_chars = snapshot
5912 .reversed_chars_at(selection_head)
5913 .collect::<String>();
5914 for (pair, enabled) in scope.brackets() {
5915 if enabled
5916 && pair.close
5917 && prev_chars.starts_with(pair.start.as_str())
5918 && next_chars.starts_with(pair.end.as_str())
5919 {
5920 bracket_pair = Some(pair.clone());
5921 break;
5922 }
5923 }
5924 if let Some(pair) = bracket_pair {
5925 let start = snapshot.anchor_after(selection_head);
5926 let end = snapshot.anchor_after(selection_head);
5927 self.autoclose_regions.push(AutocloseRegion {
5928 selection_id: selection.id,
5929 range: start..end,
5930 pair,
5931 });
5932 }
5933 }
5934 }
5935 }
5936 Ok(())
5937 }
5938
5939 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5940 self.move_to_snippet_tabstop(Bias::Right, cx)
5941 }
5942
5943 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5944 self.move_to_snippet_tabstop(Bias::Left, cx)
5945 }
5946
5947 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5948 if let Some(mut snippet) = self.snippet_stack.pop() {
5949 match bias {
5950 Bias::Left => {
5951 if snippet.active_index > 0 {
5952 snippet.active_index -= 1;
5953 } else {
5954 self.snippet_stack.push(snippet);
5955 return false;
5956 }
5957 }
5958 Bias::Right => {
5959 if snippet.active_index + 1 < snippet.ranges.len() {
5960 snippet.active_index += 1;
5961 } else {
5962 self.snippet_stack.push(snippet);
5963 return false;
5964 }
5965 }
5966 }
5967 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5968 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5969 s.select_anchor_ranges(current_ranges.iter().cloned())
5970 });
5971
5972 if let Some(choices) = &snippet.choices[snippet.active_index] {
5973 if let Some(selection) = current_ranges.first() {
5974 self.show_snippet_choices(&choices, selection.clone(), cx);
5975 }
5976 }
5977
5978 // If snippet state is not at the last tabstop, push it back on the stack
5979 if snippet.active_index + 1 < snippet.ranges.len() {
5980 self.snippet_stack.push(snippet);
5981 }
5982 return true;
5983 }
5984 }
5985
5986 false
5987 }
5988
5989 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5990 self.transact(cx, |this, cx| {
5991 this.select_all(&SelectAll, cx);
5992 this.insert("", cx);
5993 });
5994 }
5995
5996 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5997 self.transact(cx, |this, cx| {
5998 this.select_autoclose_pair(cx);
5999 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6000 if !this.linked_edit_ranges.is_empty() {
6001 let selections = this.selections.all::<MultiBufferPoint>(cx);
6002 let snapshot = this.buffer.read(cx).snapshot(cx);
6003
6004 for selection in selections.iter() {
6005 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6006 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6007 if selection_start.buffer_id != selection_end.buffer_id {
6008 continue;
6009 }
6010 if let Some(ranges) =
6011 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6012 {
6013 for (buffer, entries) in ranges {
6014 linked_ranges.entry(buffer).or_default().extend(entries);
6015 }
6016 }
6017 }
6018 }
6019
6020 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6021 if !this.selections.line_mode {
6022 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6023 for selection in &mut selections {
6024 if selection.is_empty() {
6025 let old_head = selection.head();
6026 let mut new_head =
6027 movement::left(&display_map, old_head.to_display_point(&display_map))
6028 .to_point(&display_map);
6029 if let Some((buffer, line_buffer_range)) = display_map
6030 .buffer_snapshot
6031 .buffer_line_for_row(MultiBufferRow(old_head.row))
6032 {
6033 let indent_size =
6034 buffer.indent_size_for_line(line_buffer_range.start.row);
6035 let indent_len = match indent_size.kind {
6036 IndentKind::Space => {
6037 buffer.settings_at(line_buffer_range.start, cx).tab_size
6038 }
6039 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6040 };
6041 if old_head.column <= indent_size.len && old_head.column > 0 {
6042 let indent_len = indent_len.get();
6043 new_head = cmp::min(
6044 new_head,
6045 MultiBufferPoint::new(
6046 old_head.row,
6047 ((old_head.column - 1) / indent_len) * indent_len,
6048 ),
6049 );
6050 }
6051 }
6052
6053 selection.set_head(new_head, SelectionGoal::None);
6054 }
6055 }
6056 }
6057
6058 this.signature_help_state.set_backspace_pressed(true);
6059 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6060 this.insert("", cx);
6061 let empty_str: Arc<str> = Arc::from("");
6062 for (buffer, edits) in linked_ranges {
6063 let snapshot = buffer.read(cx).snapshot();
6064 use text::ToPoint as TP;
6065
6066 let edits = edits
6067 .into_iter()
6068 .map(|range| {
6069 let end_point = TP::to_point(&range.end, &snapshot);
6070 let mut start_point = TP::to_point(&range.start, &snapshot);
6071
6072 if end_point == start_point {
6073 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6074 .saturating_sub(1);
6075 start_point = TP::to_point(&offset, &snapshot);
6076 };
6077
6078 (start_point..end_point, empty_str.clone())
6079 })
6080 .sorted_by_key(|(range, _)| range.start)
6081 .collect::<Vec<_>>();
6082 buffer.update(cx, |this, cx| {
6083 this.edit(edits, None, cx);
6084 })
6085 }
6086 this.refresh_inline_completion(true, false, cx);
6087 linked_editing_ranges::refresh_linked_ranges(this, cx);
6088 });
6089 }
6090
6091 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
6092 self.transact(cx, |this, cx| {
6093 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6094 let line_mode = s.line_mode;
6095 s.move_with(|map, selection| {
6096 if selection.is_empty() && !line_mode {
6097 let cursor = movement::right(map, selection.head());
6098 selection.end = cursor;
6099 selection.reversed = true;
6100 selection.goal = SelectionGoal::None;
6101 }
6102 })
6103 });
6104 this.insert("", cx);
6105 this.refresh_inline_completion(true, false, cx);
6106 });
6107 }
6108
6109 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
6110 if self.move_to_prev_snippet_tabstop(cx) {
6111 return;
6112 }
6113
6114 self.outdent(&Outdent, cx);
6115 }
6116
6117 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
6118 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
6119 return;
6120 }
6121
6122 let mut selections = self.selections.all_adjusted(cx);
6123 let buffer = self.buffer.read(cx);
6124 let snapshot = buffer.snapshot(cx);
6125 let rows_iter = selections.iter().map(|s| s.head().row);
6126 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6127
6128 let mut edits = Vec::new();
6129 let mut prev_edited_row = 0;
6130 let mut row_delta = 0;
6131 for selection in &mut selections {
6132 if selection.start.row != prev_edited_row {
6133 row_delta = 0;
6134 }
6135 prev_edited_row = selection.end.row;
6136
6137 // If the selection is non-empty, then increase the indentation of the selected lines.
6138 if !selection.is_empty() {
6139 row_delta =
6140 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6141 continue;
6142 }
6143
6144 // If the selection is empty and the cursor is in the leading whitespace before the
6145 // suggested indentation, then auto-indent the line.
6146 let cursor = selection.head();
6147 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6148 if let Some(suggested_indent) =
6149 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6150 {
6151 if cursor.column < suggested_indent.len
6152 && cursor.column <= current_indent.len
6153 && current_indent.len <= suggested_indent.len
6154 {
6155 selection.start = Point::new(cursor.row, suggested_indent.len);
6156 selection.end = selection.start;
6157 if row_delta == 0 {
6158 edits.extend(Buffer::edit_for_indent_size_adjustment(
6159 cursor.row,
6160 current_indent,
6161 suggested_indent,
6162 ));
6163 row_delta = suggested_indent.len - current_indent.len;
6164 }
6165 continue;
6166 }
6167 }
6168
6169 // Otherwise, insert a hard or soft tab.
6170 let settings = buffer.settings_at(cursor, cx);
6171 let tab_size = if settings.hard_tabs {
6172 IndentSize::tab()
6173 } else {
6174 let tab_size = settings.tab_size.get();
6175 let char_column = snapshot
6176 .text_for_range(Point::new(cursor.row, 0)..cursor)
6177 .flat_map(str::chars)
6178 .count()
6179 + row_delta as usize;
6180 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6181 IndentSize::spaces(chars_to_next_tab_stop)
6182 };
6183 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6184 selection.end = selection.start;
6185 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6186 row_delta += tab_size.len;
6187 }
6188
6189 self.transact(cx, |this, cx| {
6190 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6191 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6192 this.refresh_inline_completion(true, false, cx);
6193 });
6194 }
6195
6196 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
6197 if self.read_only(cx) {
6198 return;
6199 }
6200 let mut selections = self.selections.all::<Point>(cx);
6201 let mut prev_edited_row = 0;
6202 let mut row_delta = 0;
6203 let mut edits = Vec::new();
6204 let buffer = self.buffer.read(cx);
6205 let snapshot = buffer.snapshot(cx);
6206 for selection in &mut selections {
6207 if selection.start.row != prev_edited_row {
6208 row_delta = 0;
6209 }
6210 prev_edited_row = selection.end.row;
6211
6212 row_delta =
6213 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6214 }
6215
6216 self.transact(cx, |this, cx| {
6217 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6218 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6219 });
6220 }
6221
6222 fn indent_selection(
6223 buffer: &MultiBuffer,
6224 snapshot: &MultiBufferSnapshot,
6225 selection: &mut Selection<Point>,
6226 edits: &mut Vec<(Range<Point>, String)>,
6227 delta_for_start_row: u32,
6228 cx: &AppContext,
6229 ) -> u32 {
6230 let settings = buffer.settings_at(selection.start, cx);
6231 let tab_size = settings.tab_size.get();
6232 let indent_kind = if settings.hard_tabs {
6233 IndentKind::Tab
6234 } else {
6235 IndentKind::Space
6236 };
6237 let mut start_row = selection.start.row;
6238 let mut end_row = selection.end.row + 1;
6239
6240 // If a selection ends at the beginning of a line, don't indent
6241 // that last line.
6242 if selection.end.column == 0 && selection.end.row > selection.start.row {
6243 end_row -= 1;
6244 }
6245
6246 // Avoid re-indenting a row that has already been indented by a
6247 // previous selection, but still update this selection's column
6248 // to reflect that indentation.
6249 if delta_for_start_row > 0 {
6250 start_row += 1;
6251 selection.start.column += delta_for_start_row;
6252 if selection.end.row == selection.start.row {
6253 selection.end.column += delta_for_start_row;
6254 }
6255 }
6256
6257 let mut delta_for_end_row = 0;
6258 let has_multiple_rows = start_row + 1 != end_row;
6259 for row in start_row..end_row {
6260 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6261 let indent_delta = match (current_indent.kind, indent_kind) {
6262 (IndentKind::Space, IndentKind::Space) => {
6263 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6264 IndentSize::spaces(columns_to_next_tab_stop)
6265 }
6266 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6267 (_, IndentKind::Tab) => IndentSize::tab(),
6268 };
6269
6270 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6271 0
6272 } else {
6273 selection.start.column
6274 };
6275 let row_start = Point::new(row, start);
6276 edits.push((
6277 row_start..row_start,
6278 indent_delta.chars().collect::<String>(),
6279 ));
6280
6281 // Update this selection's endpoints to reflect the indentation.
6282 if row == selection.start.row {
6283 selection.start.column += indent_delta.len;
6284 }
6285 if row == selection.end.row {
6286 selection.end.column += indent_delta.len;
6287 delta_for_end_row = indent_delta.len;
6288 }
6289 }
6290
6291 if selection.start.row == selection.end.row {
6292 delta_for_start_row + delta_for_end_row
6293 } else {
6294 delta_for_end_row
6295 }
6296 }
6297
6298 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
6299 if self.read_only(cx) {
6300 return;
6301 }
6302 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6303 let selections = self.selections.all::<Point>(cx);
6304 let mut deletion_ranges = Vec::new();
6305 let mut last_outdent = None;
6306 {
6307 let buffer = self.buffer.read(cx);
6308 let snapshot = buffer.snapshot(cx);
6309 for selection in &selections {
6310 let settings = buffer.settings_at(selection.start, cx);
6311 let tab_size = settings.tab_size.get();
6312 let mut rows = selection.spanned_rows(false, &display_map);
6313
6314 // Avoid re-outdenting a row that has already been outdented by a
6315 // previous selection.
6316 if let Some(last_row) = last_outdent {
6317 if last_row == rows.start {
6318 rows.start = rows.start.next_row();
6319 }
6320 }
6321 let has_multiple_rows = rows.len() > 1;
6322 for row in rows.iter_rows() {
6323 let indent_size = snapshot.indent_size_for_line(row);
6324 if indent_size.len > 0 {
6325 let deletion_len = match indent_size.kind {
6326 IndentKind::Space => {
6327 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6328 if columns_to_prev_tab_stop == 0 {
6329 tab_size
6330 } else {
6331 columns_to_prev_tab_stop
6332 }
6333 }
6334 IndentKind::Tab => 1,
6335 };
6336 let start = if has_multiple_rows
6337 || deletion_len > selection.start.column
6338 || indent_size.len < selection.start.column
6339 {
6340 0
6341 } else {
6342 selection.start.column - deletion_len
6343 };
6344 deletion_ranges.push(
6345 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6346 );
6347 last_outdent = Some(row);
6348 }
6349 }
6350 }
6351 }
6352
6353 self.transact(cx, |this, cx| {
6354 this.buffer.update(cx, |buffer, cx| {
6355 let empty_str: Arc<str> = Arc::default();
6356 buffer.edit(
6357 deletion_ranges
6358 .into_iter()
6359 .map(|range| (range, empty_str.clone())),
6360 None,
6361 cx,
6362 );
6363 });
6364 let selections = this.selections.all::<usize>(cx);
6365 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6366 });
6367 }
6368
6369 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
6370 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6371 let selections = self.selections.all::<Point>(cx);
6372
6373 let mut new_cursors = Vec::new();
6374 let mut edit_ranges = Vec::new();
6375 let mut selections = selections.iter().peekable();
6376 while let Some(selection) = selections.next() {
6377 let mut rows = selection.spanned_rows(false, &display_map);
6378 let goal_display_column = selection.head().to_display_point(&display_map).column();
6379
6380 // Accumulate contiguous regions of rows that we want to delete.
6381 while let Some(next_selection) = selections.peek() {
6382 let next_rows = next_selection.spanned_rows(false, &display_map);
6383 if next_rows.start <= rows.end {
6384 rows.end = next_rows.end;
6385 selections.next().unwrap();
6386 } else {
6387 break;
6388 }
6389 }
6390
6391 let buffer = &display_map.buffer_snapshot;
6392 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6393 let edit_end;
6394 let cursor_buffer_row;
6395 if buffer.max_point().row >= rows.end.0 {
6396 // If there's a line after the range, delete the \n from the end of the row range
6397 // and position the cursor on the next line.
6398 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6399 cursor_buffer_row = rows.end;
6400 } else {
6401 // If there isn't a line after the range, delete the \n from the line before the
6402 // start of the row range and position the cursor there.
6403 edit_start = edit_start.saturating_sub(1);
6404 edit_end = buffer.len();
6405 cursor_buffer_row = rows.start.previous_row();
6406 }
6407
6408 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6409 *cursor.column_mut() =
6410 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6411
6412 new_cursors.push((
6413 selection.id,
6414 buffer.anchor_after(cursor.to_point(&display_map)),
6415 ));
6416 edit_ranges.push(edit_start..edit_end);
6417 }
6418
6419 self.transact(cx, |this, cx| {
6420 let buffer = this.buffer.update(cx, |buffer, cx| {
6421 let empty_str: Arc<str> = Arc::default();
6422 buffer.edit(
6423 edit_ranges
6424 .into_iter()
6425 .map(|range| (range, empty_str.clone())),
6426 None,
6427 cx,
6428 );
6429 buffer.snapshot(cx)
6430 });
6431 let new_selections = new_cursors
6432 .into_iter()
6433 .map(|(id, cursor)| {
6434 let cursor = cursor.to_point(&buffer);
6435 Selection {
6436 id,
6437 start: cursor,
6438 end: cursor,
6439 reversed: false,
6440 goal: SelectionGoal::None,
6441 }
6442 })
6443 .collect();
6444
6445 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6446 s.select(new_selections);
6447 });
6448 });
6449 }
6450
6451 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6452 if self.read_only(cx) {
6453 return;
6454 }
6455 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6456 for selection in self.selections.all::<Point>(cx) {
6457 let start = MultiBufferRow(selection.start.row);
6458 // Treat single line selections as if they include the next line. Otherwise this action
6459 // would do nothing for single line selections individual cursors.
6460 let end = if selection.start.row == selection.end.row {
6461 MultiBufferRow(selection.start.row + 1)
6462 } else {
6463 MultiBufferRow(selection.end.row)
6464 };
6465
6466 if let Some(last_row_range) = row_ranges.last_mut() {
6467 if start <= last_row_range.end {
6468 last_row_range.end = end;
6469 continue;
6470 }
6471 }
6472 row_ranges.push(start..end);
6473 }
6474
6475 let snapshot = self.buffer.read(cx).snapshot(cx);
6476 let mut cursor_positions = Vec::new();
6477 for row_range in &row_ranges {
6478 let anchor = snapshot.anchor_before(Point::new(
6479 row_range.end.previous_row().0,
6480 snapshot.line_len(row_range.end.previous_row()),
6481 ));
6482 cursor_positions.push(anchor..anchor);
6483 }
6484
6485 self.transact(cx, |this, cx| {
6486 for row_range in row_ranges.into_iter().rev() {
6487 for row in row_range.iter_rows().rev() {
6488 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6489 let next_line_row = row.next_row();
6490 let indent = snapshot.indent_size_for_line(next_line_row);
6491 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6492
6493 let replace = if snapshot.line_len(next_line_row) > indent.len {
6494 " "
6495 } else {
6496 ""
6497 };
6498
6499 this.buffer.update(cx, |buffer, cx| {
6500 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6501 });
6502 }
6503 }
6504
6505 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6506 s.select_anchor_ranges(cursor_positions)
6507 });
6508 });
6509 }
6510
6511 pub fn sort_lines_case_sensitive(
6512 &mut self,
6513 _: &SortLinesCaseSensitive,
6514 cx: &mut ViewContext<Self>,
6515 ) {
6516 self.manipulate_lines(cx, |lines| lines.sort())
6517 }
6518
6519 pub fn sort_lines_case_insensitive(
6520 &mut self,
6521 _: &SortLinesCaseInsensitive,
6522 cx: &mut ViewContext<Self>,
6523 ) {
6524 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6525 }
6526
6527 pub fn unique_lines_case_insensitive(
6528 &mut self,
6529 _: &UniqueLinesCaseInsensitive,
6530 cx: &mut ViewContext<Self>,
6531 ) {
6532 self.manipulate_lines(cx, |lines| {
6533 let mut seen = HashSet::default();
6534 lines.retain(|line| seen.insert(line.to_lowercase()));
6535 })
6536 }
6537
6538 pub fn unique_lines_case_sensitive(
6539 &mut self,
6540 _: &UniqueLinesCaseSensitive,
6541 cx: &mut ViewContext<Self>,
6542 ) {
6543 self.manipulate_lines(cx, |lines| {
6544 let mut seen = HashSet::default();
6545 lines.retain(|line| seen.insert(*line));
6546 })
6547 }
6548
6549 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6550 let mut revert_changes = HashMap::default();
6551 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6552 for hunk in hunks_for_rows(
6553 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6554 &multi_buffer_snapshot,
6555 ) {
6556 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6557 }
6558 if !revert_changes.is_empty() {
6559 self.transact(cx, |editor, cx| {
6560 editor.revert(revert_changes, cx);
6561 });
6562 }
6563 }
6564
6565 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6566 let Some(project) = self.project.clone() else {
6567 return;
6568 };
6569 self.reload(project, cx).detach_and_notify_err(cx);
6570 }
6571
6572 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6573 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6574 if !revert_changes.is_empty() {
6575 self.transact(cx, |editor, cx| {
6576 editor.revert(revert_changes, cx);
6577 });
6578 }
6579 }
6580
6581 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6582 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6583 let project_path = buffer.read(cx).project_path(cx)?;
6584 let project = self.project.as_ref()?.read(cx);
6585 let entry = project.entry_for_path(&project_path, cx)?;
6586 let parent = match &entry.canonical_path {
6587 Some(canonical_path) => canonical_path.to_path_buf(),
6588 None => project.absolute_path(&project_path, cx)?,
6589 }
6590 .parent()?
6591 .to_path_buf();
6592 Some(parent)
6593 }) {
6594 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6595 }
6596 }
6597
6598 fn gather_revert_changes(
6599 &mut self,
6600 selections: &[Selection<Anchor>],
6601 cx: &mut ViewContext<'_, Editor>,
6602 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6603 let mut revert_changes = HashMap::default();
6604 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6605 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6606 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6607 }
6608 revert_changes
6609 }
6610
6611 pub fn prepare_revert_change(
6612 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6613 multi_buffer: &Model<MultiBuffer>,
6614 hunk: &MultiBufferDiffHunk,
6615 cx: &AppContext,
6616 ) -> Option<()> {
6617 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6618 let buffer = buffer.read(cx);
6619 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6620 let buffer_snapshot = buffer.snapshot();
6621 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6622 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6623 probe
6624 .0
6625 .start
6626 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6627 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6628 }) {
6629 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6630 Some(())
6631 } else {
6632 None
6633 }
6634 }
6635
6636 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6637 self.manipulate_lines(cx, |lines| lines.reverse())
6638 }
6639
6640 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6641 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6642 }
6643
6644 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6645 where
6646 Fn: FnMut(&mut Vec<&str>),
6647 {
6648 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6649 let buffer = self.buffer.read(cx).snapshot(cx);
6650
6651 let mut edits = Vec::new();
6652
6653 let selections = self.selections.all::<Point>(cx);
6654 let mut selections = selections.iter().peekable();
6655 let mut contiguous_row_selections = Vec::new();
6656 let mut new_selections = Vec::new();
6657 let mut added_lines = 0;
6658 let mut removed_lines = 0;
6659
6660 while let Some(selection) = selections.next() {
6661 let (start_row, end_row) = consume_contiguous_rows(
6662 &mut contiguous_row_selections,
6663 selection,
6664 &display_map,
6665 &mut selections,
6666 );
6667
6668 let start_point = Point::new(start_row.0, 0);
6669 let end_point = Point::new(
6670 end_row.previous_row().0,
6671 buffer.line_len(end_row.previous_row()),
6672 );
6673 let text = buffer
6674 .text_for_range(start_point..end_point)
6675 .collect::<String>();
6676
6677 let mut lines = text.split('\n').collect_vec();
6678
6679 let lines_before = lines.len();
6680 callback(&mut lines);
6681 let lines_after = lines.len();
6682
6683 edits.push((start_point..end_point, lines.join("\n")));
6684
6685 // Selections must change based on added and removed line count
6686 let start_row =
6687 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6688 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6689 new_selections.push(Selection {
6690 id: selection.id,
6691 start: start_row,
6692 end: end_row,
6693 goal: SelectionGoal::None,
6694 reversed: selection.reversed,
6695 });
6696
6697 if lines_after > lines_before {
6698 added_lines += lines_after - lines_before;
6699 } else if lines_before > lines_after {
6700 removed_lines += lines_before - lines_after;
6701 }
6702 }
6703
6704 self.transact(cx, |this, cx| {
6705 let buffer = this.buffer.update(cx, |buffer, cx| {
6706 buffer.edit(edits, None, cx);
6707 buffer.snapshot(cx)
6708 });
6709
6710 // Recalculate offsets on newly edited buffer
6711 let new_selections = new_selections
6712 .iter()
6713 .map(|s| {
6714 let start_point = Point::new(s.start.0, 0);
6715 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6716 Selection {
6717 id: s.id,
6718 start: buffer.point_to_offset(start_point),
6719 end: buffer.point_to_offset(end_point),
6720 goal: s.goal,
6721 reversed: s.reversed,
6722 }
6723 })
6724 .collect();
6725
6726 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6727 s.select(new_selections);
6728 });
6729
6730 this.request_autoscroll(Autoscroll::fit(), cx);
6731 });
6732 }
6733
6734 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6735 self.manipulate_text(cx, |text| text.to_uppercase())
6736 }
6737
6738 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6739 self.manipulate_text(cx, |text| text.to_lowercase())
6740 }
6741
6742 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6743 self.manipulate_text(cx, |text| {
6744 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6745 // https://github.com/rutrum/convert-case/issues/16
6746 text.split('\n')
6747 .map(|line| line.to_case(Case::Title))
6748 .join("\n")
6749 })
6750 }
6751
6752 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6753 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6754 }
6755
6756 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6757 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6758 }
6759
6760 pub fn convert_to_upper_camel_case(
6761 &mut self,
6762 _: &ConvertToUpperCamelCase,
6763 cx: &mut ViewContext<Self>,
6764 ) {
6765 self.manipulate_text(cx, |text| {
6766 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6767 // https://github.com/rutrum/convert-case/issues/16
6768 text.split('\n')
6769 .map(|line| line.to_case(Case::UpperCamel))
6770 .join("\n")
6771 })
6772 }
6773
6774 pub fn convert_to_lower_camel_case(
6775 &mut self,
6776 _: &ConvertToLowerCamelCase,
6777 cx: &mut ViewContext<Self>,
6778 ) {
6779 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6780 }
6781
6782 pub fn convert_to_opposite_case(
6783 &mut self,
6784 _: &ConvertToOppositeCase,
6785 cx: &mut ViewContext<Self>,
6786 ) {
6787 self.manipulate_text(cx, |text| {
6788 text.chars()
6789 .fold(String::with_capacity(text.len()), |mut t, c| {
6790 if c.is_uppercase() {
6791 t.extend(c.to_lowercase());
6792 } else {
6793 t.extend(c.to_uppercase());
6794 }
6795 t
6796 })
6797 })
6798 }
6799
6800 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6801 where
6802 Fn: FnMut(&str) -> String,
6803 {
6804 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6805 let buffer = self.buffer.read(cx).snapshot(cx);
6806
6807 let mut new_selections = Vec::new();
6808 let mut edits = Vec::new();
6809 let mut selection_adjustment = 0i32;
6810
6811 for selection in self.selections.all::<usize>(cx) {
6812 let selection_is_empty = selection.is_empty();
6813
6814 let (start, end) = if selection_is_empty {
6815 let word_range = movement::surrounding_word(
6816 &display_map,
6817 selection.start.to_display_point(&display_map),
6818 );
6819 let start = word_range.start.to_offset(&display_map, Bias::Left);
6820 let end = word_range.end.to_offset(&display_map, Bias::Left);
6821 (start, end)
6822 } else {
6823 (selection.start, selection.end)
6824 };
6825
6826 let text = buffer.text_for_range(start..end).collect::<String>();
6827 let old_length = text.len() as i32;
6828 let text = callback(&text);
6829
6830 new_selections.push(Selection {
6831 start: (start as i32 - selection_adjustment) as usize,
6832 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6833 goal: SelectionGoal::None,
6834 ..selection
6835 });
6836
6837 selection_adjustment += old_length - text.len() as i32;
6838
6839 edits.push((start..end, text));
6840 }
6841
6842 self.transact(cx, |this, cx| {
6843 this.buffer.update(cx, |buffer, cx| {
6844 buffer.edit(edits, None, cx);
6845 });
6846
6847 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6848 s.select(new_selections);
6849 });
6850
6851 this.request_autoscroll(Autoscroll::fit(), cx);
6852 });
6853 }
6854
6855 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6856 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6857 let buffer = &display_map.buffer_snapshot;
6858 let selections = self.selections.all::<Point>(cx);
6859
6860 let mut edits = Vec::new();
6861 let mut selections_iter = selections.iter().peekable();
6862 while let Some(selection) = selections_iter.next() {
6863 // Avoid duplicating the same lines twice.
6864 let mut rows = selection.spanned_rows(false, &display_map);
6865
6866 while let Some(next_selection) = selections_iter.peek() {
6867 let next_rows = next_selection.spanned_rows(false, &display_map);
6868 if next_rows.start < rows.end {
6869 rows.end = next_rows.end;
6870 selections_iter.next().unwrap();
6871 } else {
6872 break;
6873 }
6874 }
6875
6876 // Copy the text from the selected row region and splice it either at the start
6877 // or end of the region.
6878 let start = Point::new(rows.start.0, 0);
6879 let end = Point::new(
6880 rows.end.previous_row().0,
6881 buffer.line_len(rows.end.previous_row()),
6882 );
6883 let text = buffer
6884 .text_for_range(start..end)
6885 .chain(Some("\n"))
6886 .collect::<String>();
6887 let insert_location = if upwards {
6888 Point::new(rows.end.0, 0)
6889 } else {
6890 start
6891 };
6892 edits.push((insert_location..insert_location, text));
6893 }
6894
6895 self.transact(cx, |this, cx| {
6896 this.buffer.update(cx, |buffer, cx| {
6897 buffer.edit(edits, None, cx);
6898 });
6899
6900 this.request_autoscroll(Autoscroll::fit(), cx);
6901 });
6902 }
6903
6904 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6905 self.duplicate_line(true, cx);
6906 }
6907
6908 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6909 self.duplicate_line(false, cx);
6910 }
6911
6912 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6913 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6914 let buffer = self.buffer.read(cx).snapshot(cx);
6915
6916 let mut edits = Vec::new();
6917 let mut unfold_ranges = Vec::new();
6918 let mut refold_creases = Vec::new();
6919
6920 let selections = self.selections.all::<Point>(cx);
6921 let mut selections = selections.iter().peekable();
6922 let mut contiguous_row_selections = Vec::new();
6923 let mut new_selections = Vec::new();
6924
6925 while let Some(selection) = selections.next() {
6926 // Find all the selections that span a contiguous row range
6927 let (start_row, end_row) = consume_contiguous_rows(
6928 &mut contiguous_row_selections,
6929 selection,
6930 &display_map,
6931 &mut selections,
6932 );
6933
6934 // Move the text spanned by the row range to be before the line preceding the row range
6935 if start_row.0 > 0 {
6936 let range_to_move = Point::new(
6937 start_row.previous_row().0,
6938 buffer.line_len(start_row.previous_row()),
6939 )
6940 ..Point::new(
6941 end_row.previous_row().0,
6942 buffer.line_len(end_row.previous_row()),
6943 );
6944 let insertion_point = display_map
6945 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6946 .0;
6947
6948 // Don't move lines across excerpts
6949 if buffer
6950 .excerpt_boundaries_in_range((
6951 Bound::Excluded(insertion_point),
6952 Bound::Included(range_to_move.end),
6953 ))
6954 .next()
6955 .is_none()
6956 {
6957 let text = buffer
6958 .text_for_range(range_to_move.clone())
6959 .flat_map(|s| s.chars())
6960 .skip(1)
6961 .chain(['\n'])
6962 .collect::<String>();
6963
6964 edits.push((
6965 buffer.anchor_after(range_to_move.start)
6966 ..buffer.anchor_before(range_to_move.end),
6967 String::new(),
6968 ));
6969 let insertion_anchor = buffer.anchor_after(insertion_point);
6970 edits.push((insertion_anchor..insertion_anchor, text));
6971
6972 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6973
6974 // Move selections up
6975 new_selections.extend(contiguous_row_selections.drain(..).map(
6976 |mut selection| {
6977 selection.start.row -= row_delta;
6978 selection.end.row -= row_delta;
6979 selection
6980 },
6981 ));
6982
6983 // Move folds up
6984 unfold_ranges.push(range_to_move.clone());
6985 for fold in display_map.folds_in_range(
6986 buffer.anchor_before(range_to_move.start)
6987 ..buffer.anchor_after(range_to_move.end),
6988 ) {
6989 let mut start = fold.range.start.to_point(&buffer);
6990 let mut end = fold.range.end.to_point(&buffer);
6991 start.row -= row_delta;
6992 end.row -= row_delta;
6993 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6994 }
6995 }
6996 }
6997
6998 // If we didn't move line(s), preserve the existing selections
6999 new_selections.append(&mut contiguous_row_selections);
7000 }
7001
7002 self.transact(cx, |this, cx| {
7003 this.unfold_ranges(&unfold_ranges, true, true, cx);
7004 this.buffer.update(cx, |buffer, cx| {
7005 for (range, text) in edits {
7006 buffer.edit([(range, text)], None, cx);
7007 }
7008 });
7009 this.fold_creases(refold_creases, true, cx);
7010 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7011 s.select(new_selections);
7012 })
7013 });
7014 }
7015
7016 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
7017 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7018 let buffer = self.buffer.read(cx).snapshot(cx);
7019
7020 let mut edits = Vec::new();
7021 let mut unfold_ranges = Vec::new();
7022 let mut refold_creases = Vec::new();
7023
7024 let selections = self.selections.all::<Point>(cx);
7025 let mut selections = selections.iter().peekable();
7026 let mut contiguous_row_selections = Vec::new();
7027 let mut new_selections = Vec::new();
7028
7029 while let Some(selection) = selections.next() {
7030 // Find all the selections that span a contiguous row range
7031 let (start_row, end_row) = consume_contiguous_rows(
7032 &mut contiguous_row_selections,
7033 selection,
7034 &display_map,
7035 &mut selections,
7036 );
7037
7038 // Move the text spanned by the row range to be after the last line of the row range
7039 if end_row.0 <= buffer.max_point().row {
7040 let range_to_move =
7041 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7042 let insertion_point = display_map
7043 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7044 .0;
7045
7046 // Don't move lines across excerpt boundaries
7047 if buffer
7048 .excerpt_boundaries_in_range((
7049 Bound::Excluded(range_to_move.start),
7050 Bound::Included(insertion_point),
7051 ))
7052 .next()
7053 .is_none()
7054 {
7055 let mut text = String::from("\n");
7056 text.extend(buffer.text_for_range(range_to_move.clone()));
7057 text.pop(); // Drop trailing newline
7058 edits.push((
7059 buffer.anchor_after(range_to_move.start)
7060 ..buffer.anchor_before(range_to_move.end),
7061 String::new(),
7062 ));
7063 let insertion_anchor = buffer.anchor_after(insertion_point);
7064 edits.push((insertion_anchor..insertion_anchor, text));
7065
7066 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7067
7068 // Move selections down
7069 new_selections.extend(contiguous_row_selections.drain(..).map(
7070 |mut selection| {
7071 selection.start.row += row_delta;
7072 selection.end.row += row_delta;
7073 selection
7074 },
7075 ));
7076
7077 // Move folds down
7078 unfold_ranges.push(range_to_move.clone());
7079 for fold in display_map.folds_in_range(
7080 buffer.anchor_before(range_to_move.start)
7081 ..buffer.anchor_after(range_to_move.end),
7082 ) {
7083 let mut start = fold.range.start.to_point(&buffer);
7084 let mut end = fold.range.end.to_point(&buffer);
7085 start.row += row_delta;
7086 end.row += row_delta;
7087 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7088 }
7089 }
7090 }
7091
7092 // If we didn't move line(s), preserve the existing selections
7093 new_selections.append(&mut contiguous_row_selections);
7094 }
7095
7096 self.transact(cx, |this, cx| {
7097 this.unfold_ranges(&unfold_ranges, true, true, cx);
7098 this.buffer.update(cx, |buffer, cx| {
7099 for (range, text) in edits {
7100 buffer.edit([(range, text)], None, cx);
7101 }
7102 });
7103 this.fold_creases(refold_creases, true, cx);
7104 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
7105 });
7106 }
7107
7108 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
7109 let text_layout_details = &self.text_layout_details(cx);
7110 self.transact(cx, |this, cx| {
7111 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7112 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7113 let line_mode = s.line_mode;
7114 s.move_with(|display_map, selection| {
7115 if !selection.is_empty() || line_mode {
7116 return;
7117 }
7118
7119 let mut head = selection.head();
7120 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7121 if head.column() == display_map.line_len(head.row()) {
7122 transpose_offset = display_map
7123 .buffer_snapshot
7124 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7125 }
7126
7127 if transpose_offset == 0 {
7128 return;
7129 }
7130
7131 *head.column_mut() += 1;
7132 head = display_map.clip_point(head, Bias::Right);
7133 let goal = SelectionGoal::HorizontalPosition(
7134 display_map
7135 .x_for_display_point(head, text_layout_details)
7136 .into(),
7137 );
7138 selection.collapse_to(head, goal);
7139
7140 let transpose_start = display_map
7141 .buffer_snapshot
7142 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7143 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7144 let transpose_end = display_map
7145 .buffer_snapshot
7146 .clip_offset(transpose_offset + 1, Bias::Right);
7147 if let Some(ch) =
7148 display_map.buffer_snapshot.chars_at(transpose_start).next()
7149 {
7150 edits.push((transpose_start..transpose_offset, String::new()));
7151 edits.push((transpose_end..transpose_end, ch.to_string()));
7152 }
7153 }
7154 });
7155 edits
7156 });
7157 this.buffer
7158 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7159 let selections = this.selections.all::<usize>(cx);
7160 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7161 s.select(selections);
7162 });
7163 });
7164 }
7165
7166 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
7167 self.rewrap_impl(IsVimMode::No, cx)
7168 }
7169
7170 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
7171 let buffer = self.buffer.read(cx).snapshot(cx);
7172 let selections = self.selections.all::<Point>(cx);
7173 let mut selections = selections.iter().peekable();
7174
7175 let mut edits = Vec::new();
7176 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7177
7178 while let Some(selection) = selections.next() {
7179 let mut start_row = selection.start.row;
7180 let mut end_row = selection.end.row;
7181
7182 // Skip selections that overlap with a range that has already been rewrapped.
7183 let selection_range = start_row..end_row;
7184 if rewrapped_row_ranges
7185 .iter()
7186 .any(|range| range.overlaps(&selection_range))
7187 {
7188 continue;
7189 }
7190
7191 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7192
7193 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7194 match language_scope.language_name().0.as_ref() {
7195 "Markdown" | "Plain Text" => {
7196 should_rewrap = true;
7197 }
7198 _ => {}
7199 }
7200 }
7201
7202 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7203
7204 // Since not all lines in the selection may be at the same indent
7205 // level, choose the indent size that is the most common between all
7206 // of the lines.
7207 //
7208 // If there is a tie, we use the deepest indent.
7209 let (indent_size, indent_end) = {
7210 let mut indent_size_occurrences = HashMap::default();
7211 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7212
7213 for row in start_row..=end_row {
7214 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7215 rows_by_indent_size.entry(indent).or_default().push(row);
7216 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7217 }
7218
7219 let indent_size = indent_size_occurrences
7220 .into_iter()
7221 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7222 .map(|(indent, _)| indent)
7223 .unwrap_or_default();
7224 let row = rows_by_indent_size[&indent_size][0];
7225 let indent_end = Point::new(row, indent_size.len);
7226
7227 (indent_size, indent_end)
7228 };
7229
7230 let mut line_prefix = indent_size.chars().collect::<String>();
7231
7232 if let Some(comment_prefix) =
7233 buffer
7234 .language_scope_at(selection.head())
7235 .and_then(|language| {
7236 language
7237 .line_comment_prefixes()
7238 .iter()
7239 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7240 .cloned()
7241 })
7242 {
7243 line_prefix.push_str(&comment_prefix);
7244 should_rewrap = true;
7245 }
7246
7247 if !should_rewrap {
7248 continue;
7249 }
7250
7251 if selection.is_empty() {
7252 'expand_upwards: while start_row > 0 {
7253 let prev_row = start_row - 1;
7254 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7255 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7256 {
7257 start_row = prev_row;
7258 } else {
7259 break 'expand_upwards;
7260 }
7261 }
7262
7263 'expand_downwards: while end_row < buffer.max_point().row {
7264 let next_row = end_row + 1;
7265 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7266 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7267 {
7268 end_row = next_row;
7269 } else {
7270 break 'expand_downwards;
7271 }
7272 }
7273 }
7274
7275 let start = Point::new(start_row, 0);
7276 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7277 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7278 let Some(lines_without_prefixes) = selection_text
7279 .lines()
7280 .map(|line| {
7281 line.strip_prefix(&line_prefix)
7282 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7283 .ok_or_else(|| {
7284 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7285 })
7286 })
7287 .collect::<Result<Vec<_>, _>>()
7288 .log_err()
7289 else {
7290 continue;
7291 };
7292
7293 let wrap_column = buffer
7294 .settings_at(Point::new(start_row, 0), cx)
7295 .preferred_line_length as usize;
7296 let wrapped_text = wrap_with_prefix(
7297 line_prefix,
7298 lines_without_prefixes.join(" "),
7299 wrap_column,
7300 tab_size,
7301 );
7302
7303 // TODO: should always use char-based diff while still supporting cursor behavior that
7304 // matches vim.
7305 let diff = match is_vim_mode {
7306 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7307 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7308 };
7309 let mut offset = start.to_offset(&buffer);
7310 let mut moved_since_edit = true;
7311
7312 for change in diff.iter_all_changes() {
7313 let value = change.value();
7314 match change.tag() {
7315 ChangeTag::Equal => {
7316 offset += value.len();
7317 moved_since_edit = true;
7318 }
7319 ChangeTag::Delete => {
7320 let start = buffer.anchor_after(offset);
7321 let end = buffer.anchor_before(offset + value.len());
7322
7323 if moved_since_edit {
7324 edits.push((start..end, String::new()));
7325 } else {
7326 edits.last_mut().unwrap().0.end = end;
7327 }
7328
7329 offset += value.len();
7330 moved_since_edit = false;
7331 }
7332 ChangeTag::Insert => {
7333 if moved_since_edit {
7334 let anchor = buffer.anchor_after(offset);
7335 edits.push((anchor..anchor, value.to_string()));
7336 } else {
7337 edits.last_mut().unwrap().1.push_str(value);
7338 }
7339
7340 moved_since_edit = false;
7341 }
7342 }
7343 }
7344
7345 rewrapped_row_ranges.push(start_row..=end_row);
7346 }
7347
7348 self.buffer
7349 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7350 }
7351
7352 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
7353 let mut text = String::new();
7354 let buffer = self.buffer.read(cx).snapshot(cx);
7355 let mut selections = self.selections.all::<Point>(cx);
7356 let mut clipboard_selections = Vec::with_capacity(selections.len());
7357 {
7358 let max_point = buffer.max_point();
7359 let mut is_first = true;
7360 for selection in &mut selections {
7361 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7362 if is_entire_line {
7363 selection.start = Point::new(selection.start.row, 0);
7364 if !selection.is_empty() && selection.end.column == 0 {
7365 selection.end = cmp::min(max_point, selection.end);
7366 } else {
7367 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7368 }
7369 selection.goal = SelectionGoal::None;
7370 }
7371 if is_first {
7372 is_first = false;
7373 } else {
7374 text += "\n";
7375 }
7376 let mut len = 0;
7377 for chunk in buffer.text_for_range(selection.start..selection.end) {
7378 text.push_str(chunk);
7379 len += chunk.len();
7380 }
7381 clipboard_selections.push(ClipboardSelection {
7382 len,
7383 is_entire_line,
7384 first_line_indent: buffer
7385 .indent_size_for_line(MultiBufferRow(selection.start.row))
7386 .len,
7387 });
7388 }
7389 }
7390
7391 self.transact(cx, |this, cx| {
7392 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7393 s.select(selections);
7394 });
7395 this.insert("", cx);
7396 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7397 text,
7398 clipboard_selections,
7399 ));
7400 });
7401 }
7402
7403 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
7404 let selections = self.selections.all::<Point>(cx);
7405 let buffer = self.buffer.read(cx).read(cx);
7406 let mut text = String::new();
7407
7408 let mut clipboard_selections = Vec::with_capacity(selections.len());
7409 {
7410 let max_point = buffer.max_point();
7411 let mut is_first = true;
7412 for selection in selections.iter() {
7413 let mut start = selection.start;
7414 let mut end = selection.end;
7415 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7416 if is_entire_line {
7417 start = Point::new(start.row, 0);
7418 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7419 }
7420 if is_first {
7421 is_first = false;
7422 } else {
7423 text += "\n";
7424 }
7425 let mut len = 0;
7426 for chunk in buffer.text_for_range(start..end) {
7427 text.push_str(chunk);
7428 len += chunk.len();
7429 }
7430 clipboard_selections.push(ClipboardSelection {
7431 len,
7432 is_entire_line,
7433 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7434 });
7435 }
7436 }
7437
7438 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7439 text,
7440 clipboard_selections,
7441 ));
7442 }
7443
7444 pub fn do_paste(
7445 &mut self,
7446 text: &String,
7447 clipboard_selections: Option<Vec<ClipboardSelection>>,
7448 handle_entire_lines: bool,
7449 cx: &mut ViewContext<Self>,
7450 ) {
7451 if self.read_only(cx) {
7452 return;
7453 }
7454
7455 let clipboard_text = Cow::Borrowed(text);
7456
7457 self.transact(cx, |this, cx| {
7458 if let Some(mut clipboard_selections) = clipboard_selections {
7459 let old_selections = this.selections.all::<usize>(cx);
7460 let all_selections_were_entire_line =
7461 clipboard_selections.iter().all(|s| s.is_entire_line);
7462 let first_selection_indent_column =
7463 clipboard_selections.first().map(|s| s.first_line_indent);
7464 if clipboard_selections.len() != old_selections.len() {
7465 clipboard_selections.drain(..);
7466 }
7467 let cursor_offset = this.selections.last::<usize>(cx).head();
7468 let mut auto_indent_on_paste = true;
7469
7470 this.buffer.update(cx, |buffer, cx| {
7471 let snapshot = buffer.read(cx);
7472 auto_indent_on_paste =
7473 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7474
7475 let mut start_offset = 0;
7476 let mut edits = Vec::new();
7477 let mut original_indent_columns = Vec::new();
7478 for (ix, selection) in old_selections.iter().enumerate() {
7479 let to_insert;
7480 let entire_line;
7481 let original_indent_column;
7482 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7483 let end_offset = start_offset + clipboard_selection.len;
7484 to_insert = &clipboard_text[start_offset..end_offset];
7485 entire_line = clipboard_selection.is_entire_line;
7486 start_offset = end_offset + 1;
7487 original_indent_column = Some(clipboard_selection.first_line_indent);
7488 } else {
7489 to_insert = clipboard_text.as_str();
7490 entire_line = all_selections_were_entire_line;
7491 original_indent_column = first_selection_indent_column
7492 }
7493
7494 // If the corresponding selection was empty when this slice of the
7495 // clipboard text was written, then the entire line containing the
7496 // selection was copied. If this selection is also currently empty,
7497 // then paste the line before the current line of the buffer.
7498 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7499 let column = selection.start.to_point(&snapshot).column as usize;
7500 let line_start = selection.start - column;
7501 line_start..line_start
7502 } else {
7503 selection.range()
7504 };
7505
7506 edits.push((range, to_insert));
7507 original_indent_columns.extend(original_indent_column);
7508 }
7509 drop(snapshot);
7510
7511 buffer.edit(
7512 edits,
7513 if auto_indent_on_paste {
7514 Some(AutoindentMode::Block {
7515 original_indent_columns,
7516 })
7517 } else {
7518 None
7519 },
7520 cx,
7521 );
7522 });
7523
7524 let selections = this.selections.all::<usize>(cx);
7525 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7526 } else {
7527 this.insert(&clipboard_text, cx);
7528 }
7529 });
7530 }
7531
7532 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7533 if let Some(item) = cx.read_from_clipboard() {
7534 let entries = item.entries();
7535
7536 match entries.first() {
7537 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7538 // of all the pasted entries.
7539 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7540 .do_paste(
7541 clipboard_string.text(),
7542 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7543 true,
7544 cx,
7545 ),
7546 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7547 }
7548 }
7549 }
7550
7551 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7552 if self.read_only(cx) {
7553 return;
7554 }
7555
7556 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7557 if let Some((selections, _)) =
7558 self.selection_history.transaction(transaction_id).cloned()
7559 {
7560 self.change_selections(None, cx, |s| {
7561 s.select_anchors(selections.to_vec());
7562 });
7563 }
7564 self.request_autoscroll(Autoscroll::fit(), cx);
7565 self.unmark_text(cx);
7566 self.refresh_inline_completion(true, false, cx);
7567 cx.emit(EditorEvent::Edited { transaction_id });
7568 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7569 }
7570 }
7571
7572 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7573 if self.read_only(cx) {
7574 return;
7575 }
7576
7577 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7578 if let Some((_, Some(selections))) =
7579 self.selection_history.transaction(transaction_id).cloned()
7580 {
7581 self.change_selections(None, cx, |s| {
7582 s.select_anchors(selections.to_vec());
7583 });
7584 }
7585 self.request_autoscroll(Autoscroll::fit(), cx);
7586 self.unmark_text(cx);
7587 self.refresh_inline_completion(true, false, cx);
7588 cx.emit(EditorEvent::Edited { transaction_id });
7589 }
7590 }
7591
7592 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7593 self.buffer
7594 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7595 }
7596
7597 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7598 self.buffer
7599 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7600 }
7601
7602 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7603 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7604 let line_mode = s.line_mode;
7605 s.move_with(|map, selection| {
7606 let cursor = if selection.is_empty() && !line_mode {
7607 movement::left(map, selection.start)
7608 } else {
7609 selection.start
7610 };
7611 selection.collapse_to(cursor, SelectionGoal::None);
7612 });
7613 })
7614 }
7615
7616 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7617 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7618 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7619 })
7620 }
7621
7622 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7623 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7624 let line_mode = s.line_mode;
7625 s.move_with(|map, selection| {
7626 let cursor = if selection.is_empty() && !line_mode {
7627 movement::right(map, selection.end)
7628 } else {
7629 selection.end
7630 };
7631 selection.collapse_to(cursor, SelectionGoal::None)
7632 });
7633 })
7634 }
7635
7636 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7637 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7638 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7639 })
7640 }
7641
7642 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7643 if self.take_rename(true, cx).is_some() {
7644 return;
7645 }
7646
7647 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7648 cx.propagate();
7649 return;
7650 }
7651
7652 let text_layout_details = &self.text_layout_details(cx);
7653 let selection_count = self.selections.count();
7654 let first_selection = self.selections.first_anchor();
7655
7656 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7657 let line_mode = s.line_mode;
7658 s.move_with(|map, selection| {
7659 if !selection.is_empty() && !line_mode {
7660 selection.goal = SelectionGoal::None;
7661 }
7662 let (cursor, goal) = movement::up(
7663 map,
7664 selection.start,
7665 selection.goal,
7666 false,
7667 text_layout_details,
7668 );
7669 selection.collapse_to(cursor, goal);
7670 });
7671 });
7672
7673 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7674 {
7675 cx.propagate();
7676 }
7677 }
7678
7679 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7680 if self.take_rename(true, cx).is_some() {
7681 return;
7682 }
7683
7684 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7685 cx.propagate();
7686 return;
7687 }
7688
7689 let text_layout_details = &self.text_layout_details(cx);
7690
7691 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7692 let line_mode = s.line_mode;
7693 s.move_with(|map, selection| {
7694 if !selection.is_empty() && !line_mode {
7695 selection.goal = SelectionGoal::None;
7696 }
7697 let (cursor, goal) = movement::up_by_rows(
7698 map,
7699 selection.start,
7700 action.lines,
7701 selection.goal,
7702 false,
7703 text_layout_details,
7704 );
7705 selection.collapse_to(cursor, goal);
7706 });
7707 })
7708 }
7709
7710 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7711 if self.take_rename(true, cx).is_some() {
7712 return;
7713 }
7714
7715 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7716 cx.propagate();
7717 return;
7718 }
7719
7720 let text_layout_details = &self.text_layout_details(cx);
7721
7722 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7723 let line_mode = s.line_mode;
7724 s.move_with(|map, selection| {
7725 if !selection.is_empty() && !line_mode {
7726 selection.goal = SelectionGoal::None;
7727 }
7728 let (cursor, goal) = movement::down_by_rows(
7729 map,
7730 selection.start,
7731 action.lines,
7732 selection.goal,
7733 false,
7734 text_layout_details,
7735 );
7736 selection.collapse_to(cursor, goal);
7737 });
7738 })
7739 }
7740
7741 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7742 let text_layout_details = &self.text_layout_details(cx);
7743 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7744 s.move_heads_with(|map, head, goal| {
7745 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7746 })
7747 })
7748 }
7749
7750 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7751 let text_layout_details = &self.text_layout_details(cx);
7752 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7753 s.move_heads_with(|map, head, goal| {
7754 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7755 })
7756 })
7757 }
7758
7759 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7760 let Some(row_count) = self.visible_row_count() else {
7761 return;
7762 };
7763
7764 let text_layout_details = &self.text_layout_details(cx);
7765
7766 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7767 s.move_heads_with(|map, head, goal| {
7768 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7769 })
7770 })
7771 }
7772
7773 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7774 if self.take_rename(true, cx).is_some() {
7775 return;
7776 }
7777
7778 if self
7779 .context_menu
7780 .write()
7781 .as_mut()
7782 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7783 .unwrap_or(false)
7784 {
7785 return;
7786 }
7787
7788 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7789 cx.propagate();
7790 return;
7791 }
7792
7793 let Some(row_count) = self.visible_row_count() else {
7794 return;
7795 };
7796
7797 let autoscroll = if action.center_cursor {
7798 Autoscroll::center()
7799 } else {
7800 Autoscroll::fit()
7801 };
7802
7803 let text_layout_details = &self.text_layout_details(cx);
7804
7805 self.change_selections(Some(autoscroll), cx, |s| {
7806 let line_mode = s.line_mode;
7807 s.move_with(|map, selection| {
7808 if !selection.is_empty() && !line_mode {
7809 selection.goal = SelectionGoal::None;
7810 }
7811 let (cursor, goal) = movement::up_by_rows(
7812 map,
7813 selection.end,
7814 row_count,
7815 selection.goal,
7816 false,
7817 text_layout_details,
7818 );
7819 selection.collapse_to(cursor, goal);
7820 });
7821 });
7822 }
7823
7824 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7825 let text_layout_details = &self.text_layout_details(cx);
7826 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7827 s.move_heads_with(|map, head, goal| {
7828 movement::up(map, head, goal, false, text_layout_details)
7829 })
7830 })
7831 }
7832
7833 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7834 self.take_rename(true, cx);
7835
7836 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7837 cx.propagate();
7838 return;
7839 }
7840
7841 let text_layout_details = &self.text_layout_details(cx);
7842 let selection_count = self.selections.count();
7843 let first_selection = self.selections.first_anchor();
7844
7845 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7846 let line_mode = s.line_mode;
7847 s.move_with(|map, selection| {
7848 if !selection.is_empty() && !line_mode {
7849 selection.goal = SelectionGoal::None;
7850 }
7851 let (cursor, goal) = movement::down(
7852 map,
7853 selection.end,
7854 selection.goal,
7855 false,
7856 text_layout_details,
7857 );
7858 selection.collapse_to(cursor, goal);
7859 });
7860 });
7861
7862 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7863 {
7864 cx.propagate();
7865 }
7866 }
7867
7868 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7869 let Some(row_count) = self.visible_row_count() else {
7870 return;
7871 };
7872
7873 let text_layout_details = &self.text_layout_details(cx);
7874
7875 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7876 s.move_heads_with(|map, head, goal| {
7877 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7878 })
7879 })
7880 }
7881
7882 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7883 if self.take_rename(true, cx).is_some() {
7884 return;
7885 }
7886
7887 if self
7888 .context_menu
7889 .write()
7890 .as_mut()
7891 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7892 .unwrap_or(false)
7893 {
7894 return;
7895 }
7896
7897 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7898 cx.propagate();
7899 return;
7900 }
7901
7902 let Some(row_count) = self.visible_row_count() else {
7903 return;
7904 };
7905
7906 let autoscroll = if action.center_cursor {
7907 Autoscroll::center()
7908 } else {
7909 Autoscroll::fit()
7910 };
7911
7912 let text_layout_details = &self.text_layout_details(cx);
7913 self.change_selections(Some(autoscroll), cx, |s| {
7914 let line_mode = s.line_mode;
7915 s.move_with(|map, selection| {
7916 if !selection.is_empty() && !line_mode {
7917 selection.goal = SelectionGoal::None;
7918 }
7919 let (cursor, goal) = movement::down_by_rows(
7920 map,
7921 selection.end,
7922 row_count,
7923 selection.goal,
7924 false,
7925 text_layout_details,
7926 );
7927 selection.collapse_to(cursor, goal);
7928 });
7929 });
7930 }
7931
7932 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7933 let text_layout_details = &self.text_layout_details(cx);
7934 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7935 s.move_heads_with(|map, head, goal| {
7936 movement::down(map, head, goal, false, text_layout_details)
7937 })
7938 });
7939 }
7940
7941 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7942 if let Some(context_menu) = self.context_menu.write().as_mut() {
7943 context_menu.select_first(self.completion_provider.as_deref(), cx);
7944 }
7945 }
7946
7947 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7948 if let Some(context_menu) = self.context_menu.write().as_mut() {
7949 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7950 }
7951 }
7952
7953 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7954 if let Some(context_menu) = self.context_menu.write().as_mut() {
7955 context_menu.select_next(self.completion_provider.as_deref(), cx);
7956 }
7957 }
7958
7959 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7960 if let Some(context_menu) = self.context_menu.write().as_mut() {
7961 context_menu.select_last(self.completion_provider.as_deref(), cx);
7962 }
7963 }
7964
7965 pub fn move_to_previous_word_start(
7966 &mut self,
7967 _: &MoveToPreviousWordStart,
7968 cx: &mut ViewContext<Self>,
7969 ) {
7970 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7971 s.move_cursors_with(|map, head, _| {
7972 (
7973 movement::previous_word_start(map, head),
7974 SelectionGoal::None,
7975 )
7976 });
7977 })
7978 }
7979
7980 pub fn move_to_previous_subword_start(
7981 &mut self,
7982 _: &MoveToPreviousSubwordStart,
7983 cx: &mut ViewContext<Self>,
7984 ) {
7985 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7986 s.move_cursors_with(|map, head, _| {
7987 (
7988 movement::previous_subword_start(map, head),
7989 SelectionGoal::None,
7990 )
7991 });
7992 })
7993 }
7994
7995 pub fn select_to_previous_word_start(
7996 &mut self,
7997 _: &SelectToPreviousWordStart,
7998 cx: &mut ViewContext<Self>,
7999 ) {
8000 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8001 s.move_heads_with(|map, head, _| {
8002 (
8003 movement::previous_word_start(map, head),
8004 SelectionGoal::None,
8005 )
8006 });
8007 })
8008 }
8009
8010 pub fn select_to_previous_subword_start(
8011 &mut self,
8012 _: &SelectToPreviousSubwordStart,
8013 cx: &mut ViewContext<Self>,
8014 ) {
8015 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8016 s.move_heads_with(|map, head, _| {
8017 (
8018 movement::previous_subword_start(map, head),
8019 SelectionGoal::None,
8020 )
8021 });
8022 })
8023 }
8024
8025 pub fn delete_to_previous_word_start(
8026 &mut self,
8027 action: &DeleteToPreviousWordStart,
8028 cx: &mut ViewContext<Self>,
8029 ) {
8030 self.transact(cx, |this, cx| {
8031 this.select_autoclose_pair(cx);
8032 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8033 let line_mode = s.line_mode;
8034 s.move_with(|map, selection| {
8035 if selection.is_empty() && !line_mode {
8036 let cursor = if action.ignore_newlines {
8037 movement::previous_word_start(map, selection.head())
8038 } else {
8039 movement::previous_word_start_or_newline(map, selection.head())
8040 };
8041 selection.set_head(cursor, SelectionGoal::None);
8042 }
8043 });
8044 });
8045 this.insert("", cx);
8046 });
8047 }
8048
8049 pub fn delete_to_previous_subword_start(
8050 &mut self,
8051 _: &DeleteToPreviousSubwordStart,
8052 cx: &mut ViewContext<Self>,
8053 ) {
8054 self.transact(cx, |this, cx| {
8055 this.select_autoclose_pair(cx);
8056 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8057 let line_mode = s.line_mode;
8058 s.move_with(|map, selection| {
8059 if selection.is_empty() && !line_mode {
8060 let cursor = movement::previous_subword_start(map, selection.head());
8061 selection.set_head(cursor, SelectionGoal::None);
8062 }
8063 });
8064 });
8065 this.insert("", cx);
8066 });
8067 }
8068
8069 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
8070 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8071 s.move_cursors_with(|map, head, _| {
8072 (movement::next_word_end(map, head), SelectionGoal::None)
8073 });
8074 })
8075 }
8076
8077 pub fn move_to_next_subword_end(
8078 &mut self,
8079 _: &MoveToNextSubwordEnd,
8080 cx: &mut ViewContext<Self>,
8081 ) {
8082 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8083 s.move_cursors_with(|map, head, _| {
8084 (movement::next_subword_end(map, head), SelectionGoal::None)
8085 });
8086 })
8087 }
8088
8089 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
8090 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8091 s.move_heads_with(|map, head, _| {
8092 (movement::next_word_end(map, head), SelectionGoal::None)
8093 });
8094 })
8095 }
8096
8097 pub fn select_to_next_subword_end(
8098 &mut self,
8099 _: &SelectToNextSubwordEnd,
8100 cx: &mut ViewContext<Self>,
8101 ) {
8102 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8103 s.move_heads_with(|map, head, _| {
8104 (movement::next_subword_end(map, head), SelectionGoal::None)
8105 });
8106 })
8107 }
8108
8109 pub fn delete_to_next_word_end(
8110 &mut self,
8111 action: &DeleteToNextWordEnd,
8112 cx: &mut ViewContext<Self>,
8113 ) {
8114 self.transact(cx, |this, cx| {
8115 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8116 let line_mode = s.line_mode;
8117 s.move_with(|map, selection| {
8118 if selection.is_empty() && !line_mode {
8119 let cursor = if action.ignore_newlines {
8120 movement::next_word_end(map, selection.head())
8121 } else {
8122 movement::next_word_end_or_newline(map, selection.head())
8123 };
8124 selection.set_head(cursor, SelectionGoal::None);
8125 }
8126 });
8127 });
8128 this.insert("", cx);
8129 });
8130 }
8131
8132 pub fn delete_to_next_subword_end(
8133 &mut self,
8134 _: &DeleteToNextSubwordEnd,
8135 cx: &mut ViewContext<Self>,
8136 ) {
8137 self.transact(cx, |this, cx| {
8138 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8139 s.move_with(|map, selection| {
8140 if selection.is_empty() {
8141 let cursor = movement::next_subword_end(map, selection.head());
8142 selection.set_head(cursor, SelectionGoal::None);
8143 }
8144 });
8145 });
8146 this.insert("", cx);
8147 });
8148 }
8149
8150 pub fn move_to_beginning_of_line(
8151 &mut self,
8152 action: &MoveToBeginningOfLine,
8153 cx: &mut ViewContext<Self>,
8154 ) {
8155 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8156 s.move_cursors_with(|map, head, _| {
8157 (
8158 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8159 SelectionGoal::None,
8160 )
8161 });
8162 })
8163 }
8164
8165 pub fn select_to_beginning_of_line(
8166 &mut self,
8167 action: &SelectToBeginningOfLine,
8168 cx: &mut ViewContext<Self>,
8169 ) {
8170 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8171 s.move_heads_with(|map, head, _| {
8172 (
8173 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8174 SelectionGoal::None,
8175 )
8176 });
8177 });
8178 }
8179
8180 pub fn delete_to_beginning_of_line(
8181 &mut self,
8182 _: &DeleteToBeginningOfLine,
8183 cx: &mut ViewContext<Self>,
8184 ) {
8185 self.transact(cx, |this, cx| {
8186 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8187 s.move_with(|_, selection| {
8188 selection.reversed = true;
8189 });
8190 });
8191
8192 this.select_to_beginning_of_line(
8193 &SelectToBeginningOfLine {
8194 stop_at_soft_wraps: false,
8195 },
8196 cx,
8197 );
8198 this.backspace(&Backspace, cx);
8199 });
8200 }
8201
8202 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
8203 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8204 s.move_cursors_with(|map, head, _| {
8205 (
8206 movement::line_end(map, head, action.stop_at_soft_wraps),
8207 SelectionGoal::None,
8208 )
8209 });
8210 })
8211 }
8212
8213 pub fn select_to_end_of_line(
8214 &mut self,
8215 action: &SelectToEndOfLine,
8216 cx: &mut ViewContext<Self>,
8217 ) {
8218 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8219 s.move_heads_with(|map, head, _| {
8220 (
8221 movement::line_end(map, head, action.stop_at_soft_wraps),
8222 SelectionGoal::None,
8223 )
8224 });
8225 })
8226 }
8227
8228 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
8229 self.transact(cx, |this, cx| {
8230 this.select_to_end_of_line(
8231 &SelectToEndOfLine {
8232 stop_at_soft_wraps: false,
8233 },
8234 cx,
8235 );
8236 this.delete(&Delete, cx);
8237 });
8238 }
8239
8240 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
8241 self.transact(cx, |this, cx| {
8242 this.select_to_end_of_line(
8243 &SelectToEndOfLine {
8244 stop_at_soft_wraps: false,
8245 },
8246 cx,
8247 );
8248 this.cut(&Cut, cx);
8249 });
8250 }
8251
8252 pub fn move_to_start_of_paragraph(
8253 &mut self,
8254 _: &MoveToStartOfParagraph,
8255 cx: &mut ViewContext<Self>,
8256 ) {
8257 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8258 cx.propagate();
8259 return;
8260 }
8261
8262 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8263 s.move_with(|map, selection| {
8264 selection.collapse_to(
8265 movement::start_of_paragraph(map, selection.head(), 1),
8266 SelectionGoal::None,
8267 )
8268 });
8269 })
8270 }
8271
8272 pub fn move_to_end_of_paragraph(
8273 &mut self,
8274 _: &MoveToEndOfParagraph,
8275 cx: &mut ViewContext<Self>,
8276 ) {
8277 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8278 cx.propagate();
8279 return;
8280 }
8281
8282 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8283 s.move_with(|map, selection| {
8284 selection.collapse_to(
8285 movement::end_of_paragraph(map, selection.head(), 1),
8286 SelectionGoal::None,
8287 )
8288 });
8289 })
8290 }
8291
8292 pub fn select_to_start_of_paragraph(
8293 &mut self,
8294 _: &SelectToStartOfParagraph,
8295 cx: &mut ViewContext<Self>,
8296 ) {
8297 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8298 cx.propagate();
8299 return;
8300 }
8301
8302 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8303 s.move_heads_with(|map, head, _| {
8304 (
8305 movement::start_of_paragraph(map, head, 1),
8306 SelectionGoal::None,
8307 )
8308 });
8309 })
8310 }
8311
8312 pub fn select_to_end_of_paragraph(
8313 &mut self,
8314 _: &SelectToEndOfParagraph,
8315 cx: &mut ViewContext<Self>,
8316 ) {
8317 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8318 cx.propagate();
8319 return;
8320 }
8321
8322 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8323 s.move_heads_with(|map, head, _| {
8324 (
8325 movement::end_of_paragraph(map, head, 1),
8326 SelectionGoal::None,
8327 )
8328 });
8329 })
8330 }
8331
8332 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
8333 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8334 cx.propagate();
8335 return;
8336 }
8337
8338 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8339 s.select_ranges(vec![0..0]);
8340 });
8341 }
8342
8343 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
8344 let mut selection = self.selections.last::<Point>(cx);
8345 selection.set_head(Point::zero(), SelectionGoal::None);
8346
8347 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8348 s.select(vec![selection]);
8349 });
8350 }
8351
8352 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
8353 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8354 cx.propagate();
8355 return;
8356 }
8357
8358 let cursor = self.buffer.read(cx).read(cx).len();
8359 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8360 s.select_ranges(vec![cursor..cursor])
8361 });
8362 }
8363
8364 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8365 self.nav_history = nav_history;
8366 }
8367
8368 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8369 self.nav_history.as_ref()
8370 }
8371
8372 fn push_to_nav_history(
8373 &mut self,
8374 cursor_anchor: Anchor,
8375 new_position: Option<Point>,
8376 cx: &mut ViewContext<Self>,
8377 ) {
8378 if let Some(nav_history) = self.nav_history.as_mut() {
8379 let buffer = self.buffer.read(cx).read(cx);
8380 let cursor_position = cursor_anchor.to_point(&buffer);
8381 let scroll_state = self.scroll_manager.anchor();
8382 let scroll_top_row = scroll_state.top_row(&buffer);
8383 drop(buffer);
8384
8385 if let Some(new_position) = new_position {
8386 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8387 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8388 return;
8389 }
8390 }
8391
8392 nav_history.push(
8393 Some(NavigationData {
8394 cursor_anchor,
8395 cursor_position,
8396 scroll_anchor: scroll_state,
8397 scroll_top_row,
8398 }),
8399 cx,
8400 );
8401 }
8402 }
8403
8404 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
8405 let buffer = self.buffer.read(cx).snapshot(cx);
8406 let mut selection = self.selections.first::<usize>(cx);
8407 selection.set_head(buffer.len(), SelectionGoal::None);
8408 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8409 s.select(vec![selection]);
8410 });
8411 }
8412
8413 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
8414 let end = self.buffer.read(cx).read(cx).len();
8415 self.change_selections(None, cx, |s| {
8416 s.select_ranges(vec![0..end]);
8417 });
8418 }
8419
8420 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8421 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8422 let mut selections = self.selections.all::<Point>(cx);
8423 let max_point = display_map.buffer_snapshot.max_point();
8424 for selection in &mut selections {
8425 let rows = selection.spanned_rows(true, &display_map);
8426 selection.start = Point::new(rows.start.0, 0);
8427 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8428 selection.reversed = false;
8429 }
8430 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8431 s.select(selections);
8432 });
8433 }
8434
8435 pub fn split_selection_into_lines(
8436 &mut self,
8437 _: &SplitSelectionIntoLines,
8438 cx: &mut ViewContext<Self>,
8439 ) {
8440 let mut to_unfold = Vec::new();
8441 let mut new_selection_ranges = Vec::new();
8442 {
8443 let selections = self.selections.all::<Point>(cx);
8444 let buffer = self.buffer.read(cx).read(cx);
8445 for selection in selections {
8446 for row in selection.start.row..selection.end.row {
8447 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8448 new_selection_ranges.push(cursor..cursor);
8449 }
8450 new_selection_ranges.push(selection.end..selection.end);
8451 to_unfold.push(selection.start..selection.end);
8452 }
8453 }
8454 self.unfold_ranges(&to_unfold, true, true, cx);
8455 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8456 s.select_ranges(new_selection_ranges);
8457 });
8458 }
8459
8460 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8461 self.add_selection(true, cx);
8462 }
8463
8464 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8465 self.add_selection(false, cx);
8466 }
8467
8468 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8469 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8470 let mut selections = self.selections.all::<Point>(cx);
8471 let text_layout_details = self.text_layout_details(cx);
8472 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8473 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8474 let range = oldest_selection.display_range(&display_map).sorted();
8475
8476 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8477 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8478 let positions = start_x.min(end_x)..start_x.max(end_x);
8479
8480 selections.clear();
8481 let mut stack = Vec::new();
8482 for row in range.start.row().0..=range.end.row().0 {
8483 if let Some(selection) = self.selections.build_columnar_selection(
8484 &display_map,
8485 DisplayRow(row),
8486 &positions,
8487 oldest_selection.reversed,
8488 &text_layout_details,
8489 ) {
8490 stack.push(selection.id);
8491 selections.push(selection);
8492 }
8493 }
8494
8495 if above {
8496 stack.reverse();
8497 }
8498
8499 AddSelectionsState { above, stack }
8500 });
8501
8502 let last_added_selection = *state.stack.last().unwrap();
8503 let mut new_selections = Vec::new();
8504 if above == state.above {
8505 let end_row = if above {
8506 DisplayRow(0)
8507 } else {
8508 display_map.max_point().row()
8509 };
8510
8511 'outer: for selection in selections {
8512 if selection.id == last_added_selection {
8513 let range = selection.display_range(&display_map).sorted();
8514 debug_assert_eq!(range.start.row(), range.end.row());
8515 let mut row = range.start.row();
8516 let positions =
8517 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8518 px(start)..px(end)
8519 } else {
8520 let start_x =
8521 display_map.x_for_display_point(range.start, &text_layout_details);
8522 let end_x =
8523 display_map.x_for_display_point(range.end, &text_layout_details);
8524 start_x.min(end_x)..start_x.max(end_x)
8525 };
8526
8527 while row != end_row {
8528 if above {
8529 row.0 -= 1;
8530 } else {
8531 row.0 += 1;
8532 }
8533
8534 if let Some(new_selection) = self.selections.build_columnar_selection(
8535 &display_map,
8536 row,
8537 &positions,
8538 selection.reversed,
8539 &text_layout_details,
8540 ) {
8541 state.stack.push(new_selection.id);
8542 if above {
8543 new_selections.push(new_selection);
8544 new_selections.push(selection);
8545 } else {
8546 new_selections.push(selection);
8547 new_selections.push(new_selection);
8548 }
8549
8550 continue 'outer;
8551 }
8552 }
8553 }
8554
8555 new_selections.push(selection);
8556 }
8557 } else {
8558 new_selections = selections;
8559 new_selections.retain(|s| s.id != last_added_selection);
8560 state.stack.pop();
8561 }
8562
8563 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8564 s.select(new_selections);
8565 });
8566 if state.stack.len() > 1 {
8567 self.add_selections_state = Some(state);
8568 }
8569 }
8570
8571 pub fn select_next_match_internal(
8572 &mut self,
8573 display_map: &DisplaySnapshot,
8574 replace_newest: bool,
8575 autoscroll: Option<Autoscroll>,
8576 cx: &mut ViewContext<Self>,
8577 ) -> Result<()> {
8578 fn select_next_match_ranges(
8579 this: &mut Editor,
8580 range: Range<usize>,
8581 replace_newest: bool,
8582 auto_scroll: Option<Autoscroll>,
8583 cx: &mut ViewContext<Editor>,
8584 ) {
8585 this.unfold_ranges(&[range.clone()], false, true, cx);
8586 this.change_selections(auto_scroll, cx, |s| {
8587 if replace_newest {
8588 s.delete(s.newest_anchor().id);
8589 }
8590 s.insert_range(range.clone());
8591 });
8592 }
8593
8594 let buffer = &display_map.buffer_snapshot;
8595 let mut selections = self.selections.all::<usize>(cx);
8596 if let Some(mut select_next_state) = self.select_next_state.take() {
8597 let query = &select_next_state.query;
8598 if !select_next_state.done {
8599 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8600 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8601 let mut next_selected_range = None;
8602
8603 let bytes_after_last_selection =
8604 buffer.bytes_in_range(last_selection.end..buffer.len());
8605 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8606 let query_matches = query
8607 .stream_find_iter(bytes_after_last_selection)
8608 .map(|result| (last_selection.end, result))
8609 .chain(
8610 query
8611 .stream_find_iter(bytes_before_first_selection)
8612 .map(|result| (0, result)),
8613 );
8614
8615 for (start_offset, query_match) in query_matches {
8616 let query_match = query_match.unwrap(); // can only fail due to I/O
8617 let offset_range =
8618 start_offset + query_match.start()..start_offset + query_match.end();
8619 let display_range = offset_range.start.to_display_point(display_map)
8620 ..offset_range.end.to_display_point(display_map);
8621
8622 if !select_next_state.wordwise
8623 || (!movement::is_inside_word(display_map, display_range.start)
8624 && !movement::is_inside_word(display_map, display_range.end))
8625 {
8626 // TODO: This is n^2, because we might check all the selections
8627 if !selections
8628 .iter()
8629 .any(|selection| selection.range().overlaps(&offset_range))
8630 {
8631 next_selected_range = Some(offset_range);
8632 break;
8633 }
8634 }
8635 }
8636
8637 if let Some(next_selected_range) = next_selected_range {
8638 select_next_match_ranges(
8639 self,
8640 next_selected_range,
8641 replace_newest,
8642 autoscroll,
8643 cx,
8644 );
8645 } else {
8646 select_next_state.done = true;
8647 }
8648 }
8649
8650 self.select_next_state = Some(select_next_state);
8651 } else {
8652 let mut only_carets = true;
8653 let mut same_text_selected = true;
8654 let mut selected_text = None;
8655
8656 let mut selections_iter = selections.iter().peekable();
8657 while let Some(selection) = selections_iter.next() {
8658 if selection.start != selection.end {
8659 only_carets = false;
8660 }
8661
8662 if same_text_selected {
8663 if selected_text.is_none() {
8664 selected_text =
8665 Some(buffer.text_for_range(selection.range()).collect::<String>());
8666 }
8667
8668 if let Some(next_selection) = selections_iter.peek() {
8669 if next_selection.range().len() == selection.range().len() {
8670 let next_selected_text = buffer
8671 .text_for_range(next_selection.range())
8672 .collect::<String>();
8673 if Some(next_selected_text) != selected_text {
8674 same_text_selected = false;
8675 selected_text = None;
8676 }
8677 } else {
8678 same_text_selected = false;
8679 selected_text = None;
8680 }
8681 }
8682 }
8683 }
8684
8685 if only_carets {
8686 for selection in &mut selections {
8687 let word_range = movement::surrounding_word(
8688 display_map,
8689 selection.start.to_display_point(display_map),
8690 );
8691 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8692 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8693 selection.goal = SelectionGoal::None;
8694 selection.reversed = false;
8695 select_next_match_ranges(
8696 self,
8697 selection.start..selection.end,
8698 replace_newest,
8699 autoscroll,
8700 cx,
8701 );
8702 }
8703
8704 if selections.len() == 1 {
8705 let selection = selections
8706 .last()
8707 .expect("ensured that there's only one selection");
8708 let query = buffer
8709 .text_for_range(selection.start..selection.end)
8710 .collect::<String>();
8711 let is_empty = query.is_empty();
8712 let select_state = SelectNextState {
8713 query: AhoCorasick::new(&[query])?,
8714 wordwise: true,
8715 done: is_empty,
8716 };
8717 self.select_next_state = Some(select_state);
8718 } else {
8719 self.select_next_state = None;
8720 }
8721 } else if let Some(selected_text) = selected_text {
8722 self.select_next_state = Some(SelectNextState {
8723 query: AhoCorasick::new(&[selected_text])?,
8724 wordwise: false,
8725 done: false,
8726 });
8727 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8728 }
8729 }
8730 Ok(())
8731 }
8732
8733 pub fn select_all_matches(
8734 &mut self,
8735 _action: &SelectAllMatches,
8736 cx: &mut ViewContext<Self>,
8737 ) -> Result<()> {
8738 self.push_to_selection_history();
8739 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8740
8741 self.select_next_match_internal(&display_map, false, None, cx)?;
8742 let Some(select_next_state) = self.select_next_state.as_mut() else {
8743 return Ok(());
8744 };
8745 if select_next_state.done {
8746 return Ok(());
8747 }
8748
8749 let mut new_selections = self.selections.all::<usize>(cx);
8750
8751 let buffer = &display_map.buffer_snapshot;
8752 let query_matches = select_next_state
8753 .query
8754 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8755
8756 for query_match in query_matches {
8757 let query_match = query_match.unwrap(); // can only fail due to I/O
8758 let offset_range = query_match.start()..query_match.end();
8759 let display_range = offset_range.start.to_display_point(&display_map)
8760 ..offset_range.end.to_display_point(&display_map);
8761
8762 if !select_next_state.wordwise
8763 || (!movement::is_inside_word(&display_map, display_range.start)
8764 && !movement::is_inside_word(&display_map, display_range.end))
8765 {
8766 self.selections.change_with(cx, |selections| {
8767 new_selections.push(Selection {
8768 id: selections.new_selection_id(),
8769 start: offset_range.start,
8770 end: offset_range.end,
8771 reversed: false,
8772 goal: SelectionGoal::None,
8773 });
8774 });
8775 }
8776 }
8777
8778 new_selections.sort_by_key(|selection| selection.start);
8779 let mut ix = 0;
8780 while ix + 1 < new_selections.len() {
8781 let current_selection = &new_selections[ix];
8782 let next_selection = &new_selections[ix + 1];
8783 if current_selection.range().overlaps(&next_selection.range()) {
8784 if current_selection.id < next_selection.id {
8785 new_selections.remove(ix + 1);
8786 } else {
8787 new_selections.remove(ix);
8788 }
8789 } else {
8790 ix += 1;
8791 }
8792 }
8793
8794 select_next_state.done = true;
8795 self.unfold_ranges(
8796 &new_selections
8797 .iter()
8798 .map(|selection| selection.range())
8799 .collect::<Vec<_>>(),
8800 false,
8801 false,
8802 cx,
8803 );
8804 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8805 selections.select(new_selections)
8806 });
8807
8808 Ok(())
8809 }
8810
8811 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8812 self.push_to_selection_history();
8813 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8814 self.select_next_match_internal(
8815 &display_map,
8816 action.replace_newest,
8817 Some(Autoscroll::newest()),
8818 cx,
8819 )?;
8820 Ok(())
8821 }
8822
8823 pub fn select_previous(
8824 &mut self,
8825 action: &SelectPrevious,
8826 cx: &mut ViewContext<Self>,
8827 ) -> Result<()> {
8828 self.push_to_selection_history();
8829 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8830 let buffer = &display_map.buffer_snapshot;
8831 let mut selections = self.selections.all::<usize>(cx);
8832 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8833 let query = &select_prev_state.query;
8834 if !select_prev_state.done {
8835 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8836 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8837 let mut next_selected_range = None;
8838 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8839 let bytes_before_last_selection =
8840 buffer.reversed_bytes_in_range(0..last_selection.start);
8841 let bytes_after_first_selection =
8842 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8843 let query_matches = query
8844 .stream_find_iter(bytes_before_last_selection)
8845 .map(|result| (last_selection.start, result))
8846 .chain(
8847 query
8848 .stream_find_iter(bytes_after_first_selection)
8849 .map(|result| (buffer.len(), result)),
8850 );
8851 for (end_offset, query_match) in query_matches {
8852 let query_match = query_match.unwrap(); // can only fail due to I/O
8853 let offset_range =
8854 end_offset - query_match.end()..end_offset - query_match.start();
8855 let display_range = offset_range.start.to_display_point(&display_map)
8856 ..offset_range.end.to_display_point(&display_map);
8857
8858 if !select_prev_state.wordwise
8859 || (!movement::is_inside_word(&display_map, display_range.start)
8860 && !movement::is_inside_word(&display_map, display_range.end))
8861 {
8862 next_selected_range = Some(offset_range);
8863 break;
8864 }
8865 }
8866
8867 if let Some(next_selected_range) = next_selected_range {
8868 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8869 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8870 if action.replace_newest {
8871 s.delete(s.newest_anchor().id);
8872 }
8873 s.insert_range(next_selected_range);
8874 });
8875 } else {
8876 select_prev_state.done = true;
8877 }
8878 }
8879
8880 self.select_prev_state = Some(select_prev_state);
8881 } else {
8882 let mut only_carets = true;
8883 let mut same_text_selected = true;
8884 let mut selected_text = None;
8885
8886 let mut selections_iter = selections.iter().peekable();
8887 while let Some(selection) = selections_iter.next() {
8888 if selection.start != selection.end {
8889 only_carets = false;
8890 }
8891
8892 if same_text_selected {
8893 if selected_text.is_none() {
8894 selected_text =
8895 Some(buffer.text_for_range(selection.range()).collect::<String>());
8896 }
8897
8898 if let Some(next_selection) = selections_iter.peek() {
8899 if next_selection.range().len() == selection.range().len() {
8900 let next_selected_text = buffer
8901 .text_for_range(next_selection.range())
8902 .collect::<String>();
8903 if Some(next_selected_text) != selected_text {
8904 same_text_selected = false;
8905 selected_text = None;
8906 }
8907 } else {
8908 same_text_selected = false;
8909 selected_text = None;
8910 }
8911 }
8912 }
8913 }
8914
8915 if only_carets {
8916 for selection in &mut selections {
8917 let word_range = movement::surrounding_word(
8918 &display_map,
8919 selection.start.to_display_point(&display_map),
8920 );
8921 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8922 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8923 selection.goal = SelectionGoal::None;
8924 selection.reversed = false;
8925 }
8926 if selections.len() == 1 {
8927 let selection = selections
8928 .last()
8929 .expect("ensured that there's only one selection");
8930 let query = buffer
8931 .text_for_range(selection.start..selection.end)
8932 .collect::<String>();
8933 let is_empty = query.is_empty();
8934 let select_state = SelectNextState {
8935 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8936 wordwise: true,
8937 done: is_empty,
8938 };
8939 self.select_prev_state = Some(select_state);
8940 } else {
8941 self.select_prev_state = None;
8942 }
8943
8944 self.unfold_ranges(
8945 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8946 false,
8947 true,
8948 cx,
8949 );
8950 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8951 s.select(selections);
8952 });
8953 } else if let Some(selected_text) = selected_text {
8954 self.select_prev_state = Some(SelectNextState {
8955 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8956 wordwise: false,
8957 done: false,
8958 });
8959 self.select_previous(action, cx)?;
8960 }
8961 }
8962 Ok(())
8963 }
8964
8965 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8966 if self.read_only(cx) {
8967 return;
8968 }
8969 let text_layout_details = &self.text_layout_details(cx);
8970 self.transact(cx, |this, cx| {
8971 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8972 let mut edits = Vec::new();
8973 let mut selection_edit_ranges = Vec::new();
8974 let mut last_toggled_row = None;
8975 let snapshot = this.buffer.read(cx).read(cx);
8976 let empty_str: Arc<str> = Arc::default();
8977 let mut suffixes_inserted = Vec::new();
8978 let ignore_indent = action.ignore_indent;
8979
8980 fn comment_prefix_range(
8981 snapshot: &MultiBufferSnapshot,
8982 row: MultiBufferRow,
8983 comment_prefix: &str,
8984 comment_prefix_whitespace: &str,
8985 ignore_indent: bool,
8986 ) -> Range<Point> {
8987 let indent_size = if ignore_indent {
8988 0
8989 } else {
8990 snapshot.indent_size_for_line(row).len
8991 };
8992
8993 let start = Point::new(row.0, indent_size);
8994
8995 let mut line_bytes = snapshot
8996 .bytes_in_range(start..snapshot.max_point())
8997 .flatten()
8998 .copied();
8999
9000 // If this line currently begins with the line comment prefix, then record
9001 // the range containing the prefix.
9002 if line_bytes
9003 .by_ref()
9004 .take(comment_prefix.len())
9005 .eq(comment_prefix.bytes())
9006 {
9007 // Include any whitespace that matches the comment prefix.
9008 let matching_whitespace_len = line_bytes
9009 .zip(comment_prefix_whitespace.bytes())
9010 .take_while(|(a, b)| a == b)
9011 .count() as u32;
9012 let end = Point::new(
9013 start.row,
9014 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9015 );
9016 start..end
9017 } else {
9018 start..start
9019 }
9020 }
9021
9022 fn comment_suffix_range(
9023 snapshot: &MultiBufferSnapshot,
9024 row: MultiBufferRow,
9025 comment_suffix: &str,
9026 comment_suffix_has_leading_space: bool,
9027 ) -> Range<Point> {
9028 let end = Point::new(row.0, snapshot.line_len(row));
9029 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9030
9031 let mut line_end_bytes = snapshot
9032 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9033 .flatten()
9034 .copied();
9035
9036 let leading_space_len = if suffix_start_column > 0
9037 && line_end_bytes.next() == Some(b' ')
9038 && comment_suffix_has_leading_space
9039 {
9040 1
9041 } else {
9042 0
9043 };
9044
9045 // If this line currently begins with the line comment prefix, then record
9046 // the range containing the prefix.
9047 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9048 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9049 start..end
9050 } else {
9051 end..end
9052 }
9053 }
9054
9055 // TODO: Handle selections that cross excerpts
9056 for selection in &mut selections {
9057 let start_column = snapshot
9058 .indent_size_for_line(MultiBufferRow(selection.start.row))
9059 .len;
9060 let language = if let Some(language) =
9061 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9062 {
9063 language
9064 } else {
9065 continue;
9066 };
9067
9068 selection_edit_ranges.clear();
9069
9070 // If multiple selections contain a given row, avoid processing that
9071 // row more than once.
9072 let mut start_row = MultiBufferRow(selection.start.row);
9073 if last_toggled_row == Some(start_row) {
9074 start_row = start_row.next_row();
9075 }
9076 let end_row =
9077 if selection.end.row > selection.start.row && selection.end.column == 0 {
9078 MultiBufferRow(selection.end.row - 1)
9079 } else {
9080 MultiBufferRow(selection.end.row)
9081 };
9082 last_toggled_row = Some(end_row);
9083
9084 if start_row > end_row {
9085 continue;
9086 }
9087
9088 // If the language has line comments, toggle those.
9089 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9090
9091 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9092 if ignore_indent {
9093 full_comment_prefixes = full_comment_prefixes
9094 .into_iter()
9095 .map(|s| Arc::from(s.trim_end()))
9096 .collect();
9097 }
9098
9099 if !full_comment_prefixes.is_empty() {
9100 let first_prefix = full_comment_prefixes
9101 .first()
9102 .expect("prefixes is non-empty");
9103 let prefix_trimmed_lengths = full_comment_prefixes
9104 .iter()
9105 .map(|p| p.trim_end_matches(' ').len())
9106 .collect::<SmallVec<[usize; 4]>>();
9107
9108 let mut all_selection_lines_are_comments = true;
9109
9110 for row in start_row.0..=end_row.0 {
9111 let row = MultiBufferRow(row);
9112 if start_row < end_row && snapshot.is_line_blank(row) {
9113 continue;
9114 }
9115
9116 let prefix_range = full_comment_prefixes
9117 .iter()
9118 .zip(prefix_trimmed_lengths.iter().copied())
9119 .map(|(prefix, trimmed_prefix_len)| {
9120 comment_prefix_range(
9121 snapshot.deref(),
9122 row,
9123 &prefix[..trimmed_prefix_len],
9124 &prefix[trimmed_prefix_len..],
9125 ignore_indent,
9126 )
9127 })
9128 .max_by_key(|range| range.end.column - range.start.column)
9129 .expect("prefixes is non-empty");
9130
9131 if prefix_range.is_empty() {
9132 all_selection_lines_are_comments = false;
9133 }
9134
9135 selection_edit_ranges.push(prefix_range);
9136 }
9137
9138 if all_selection_lines_are_comments {
9139 edits.extend(
9140 selection_edit_ranges
9141 .iter()
9142 .cloned()
9143 .map(|range| (range, empty_str.clone())),
9144 );
9145 } else {
9146 let min_column = selection_edit_ranges
9147 .iter()
9148 .map(|range| range.start.column)
9149 .min()
9150 .unwrap_or(0);
9151 edits.extend(selection_edit_ranges.iter().map(|range| {
9152 let position = Point::new(range.start.row, min_column);
9153 (position..position, first_prefix.clone())
9154 }));
9155 }
9156 } else if let Some((full_comment_prefix, comment_suffix)) =
9157 language.block_comment_delimiters()
9158 {
9159 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9160 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9161 let prefix_range = comment_prefix_range(
9162 snapshot.deref(),
9163 start_row,
9164 comment_prefix,
9165 comment_prefix_whitespace,
9166 ignore_indent,
9167 );
9168 let suffix_range = comment_suffix_range(
9169 snapshot.deref(),
9170 end_row,
9171 comment_suffix.trim_start_matches(' '),
9172 comment_suffix.starts_with(' '),
9173 );
9174
9175 if prefix_range.is_empty() || suffix_range.is_empty() {
9176 edits.push((
9177 prefix_range.start..prefix_range.start,
9178 full_comment_prefix.clone(),
9179 ));
9180 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9181 suffixes_inserted.push((end_row, comment_suffix.len()));
9182 } else {
9183 edits.push((prefix_range, empty_str.clone()));
9184 edits.push((suffix_range, empty_str.clone()));
9185 }
9186 } else {
9187 continue;
9188 }
9189 }
9190
9191 drop(snapshot);
9192 this.buffer.update(cx, |buffer, cx| {
9193 buffer.edit(edits, None, cx);
9194 });
9195
9196 // Adjust selections so that they end before any comment suffixes that
9197 // were inserted.
9198 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9199 let mut selections = this.selections.all::<Point>(cx);
9200 let snapshot = this.buffer.read(cx).read(cx);
9201 for selection in &mut selections {
9202 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9203 match row.cmp(&MultiBufferRow(selection.end.row)) {
9204 Ordering::Less => {
9205 suffixes_inserted.next();
9206 continue;
9207 }
9208 Ordering::Greater => break,
9209 Ordering::Equal => {
9210 if selection.end.column == snapshot.line_len(row) {
9211 if selection.is_empty() {
9212 selection.start.column -= suffix_len as u32;
9213 }
9214 selection.end.column -= suffix_len as u32;
9215 }
9216 break;
9217 }
9218 }
9219 }
9220 }
9221
9222 drop(snapshot);
9223 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
9224
9225 let selections = this.selections.all::<Point>(cx);
9226 let selections_on_single_row = selections.windows(2).all(|selections| {
9227 selections[0].start.row == selections[1].start.row
9228 && selections[0].end.row == selections[1].end.row
9229 && selections[0].start.row == selections[0].end.row
9230 });
9231 let selections_selecting = selections
9232 .iter()
9233 .any(|selection| selection.start != selection.end);
9234 let advance_downwards = action.advance_downwards
9235 && selections_on_single_row
9236 && !selections_selecting
9237 && !matches!(this.mode, EditorMode::SingleLine { .. });
9238
9239 if advance_downwards {
9240 let snapshot = this.buffer.read(cx).snapshot(cx);
9241
9242 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
9243 s.move_cursors_with(|display_snapshot, display_point, _| {
9244 let mut point = display_point.to_point(display_snapshot);
9245 point.row += 1;
9246 point = snapshot.clip_point(point, Bias::Left);
9247 let display_point = point.to_display_point(display_snapshot);
9248 let goal = SelectionGoal::HorizontalPosition(
9249 display_snapshot
9250 .x_for_display_point(display_point, text_layout_details)
9251 .into(),
9252 );
9253 (display_point, goal)
9254 })
9255 });
9256 }
9257 });
9258 }
9259
9260 pub fn select_enclosing_symbol(
9261 &mut self,
9262 _: &SelectEnclosingSymbol,
9263 cx: &mut ViewContext<Self>,
9264 ) {
9265 let buffer = self.buffer.read(cx).snapshot(cx);
9266 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9267
9268 fn update_selection(
9269 selection: &Selection<usize>,
9270 buffer_snap: &MultiBufferSnapshot,
9271 ) -> Option<Selection<usize>> {
9272 let cursor = selection.head();
9273 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9274 for symbol in symbols.iter().rev() {
9275 let start = symbol.range.start.to_offset(buffer_snap);
9276 let end = symbol.range.end.to_offset(buffer_snap);
9277 let new_range = start..end;
9278 if start < selection.start || end > selection.end {
9279 return Some(Selection {
9280 id: selection.id,
9281 start: new_range.start,
9282 end: new_range.end,
9283 goal: SelectionGoal::None,
9284 reversed: selection.reversed,
9285 });
9286 }
9287 }
9288 None
9289 }
9290
9291 let mut selected_larger_symbol = false;
9292 let new_selections = old_selections
9293 .iter()
9294 .map(|selection| match update_selection(selection, &buffer) {
9295 Some(new_selection) => {
9296 if new_selection.range() != selection.range() {
9297 selected_larger_symbol = true;
9298 }
9299 new_selection
9300 }
9301 None => selection.clone(),
9302 })
9303 .collect::<Vec<_>>();
9304
9305 if selected_larger_symbol {
9306 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9307 s.select(new_selections);
9308 });
9309 }
9310 }
9311
9312 pub fn select_larger_syntax_node(
9313 &mut self,
9314 _: &SelectLargerSyntaxNode,
9315 cx: &mut ViewContext<Self>,
9316 ) {
9317 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9318 let buffer = self.buffer.read(cx).snapshot(cx);
9319 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9320
9321 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9322 let mut selected_larger_node = false;
9323 let new_selections = old_selections
9324 .iter()
9325 .map(|selection| {
9326 let old_range = selection.start..selection.end;
9327 let mut new_range = old_range.clone();
9328 while let Some(containing_range) =
9329 buffer.range_for_syntax_ancestor(new_range.clone())
9330 {
9331 new_range = containing_range;
9332 if !display_map.intersects_fold(new_range.start)
9333 && !display_map.intersects_fold(new_range.end)
9334 {
9335 break;
9336 }
9337 }
9338
9339 selected_larger_node |= new_range != old_range;
9340 Selection {
9341 id: selection.id,
9342 start: new_range.start,
9343 end: new_range.end,
9344 goal: SelectionGoal::None,
9345 reversed: selection.reversed,
9346 }
9347 })
9348 .collect::<Vec<_>>();
9349
9350 if selected_larger_node {
9351 stack.push(old_selections);
9352 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9353 s.select(new_selections);
9354 });
9355 }
9356 self.select_larger_syntax_node_stack = stack;
9357 }
9358
9359 pub fn select_smaller_syntax_node(
9360 &mut self,
9361 _: &SelectSmallerSyntaxNode,
9362 cx: &mut ViewContext<Self>,
9363 ) {
9364 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9365 if let Some(selections) = stack.pop() {
9366 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9367 s.select(selections.to_vec());
9368 });
9369 }
9370 self.select_larger_syntax_node_stack = stack;
9371 }
9372
9373 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
9374 if !EditorSettings::get_global(cx).gutter.runnables {
9375 self.clear_tasks();
9376 return Task::ready(());
9377 }
9378 let project = self.project.as_ref().map(Model::downgrade);
9379 cx.spawn(|this, mut cx| async move {
9380 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
9381 let Some(project) = project.and_then(|p| p.upgrade()) else {
9382 return;
9383 };
9384 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9385 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9386 }) else {
9387 return;
9388 };
9389
9390 let hide_runnables = project
9391 .update(&mut cx, |project, cx| {
9392 // Do not display any test indicators in non-dev server remote projects.
9393 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9394 })
9395 .unwrap_or(true);
9396 if hide_runnables {
9397 return;
9398 }
9399 let new_rows =
9400 cx.background_executor()
9401 .spawn({
9402 let snapshot = display_snapshot.clone();
9403 async move {
9404 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9405 }
9406 })
9407 .await;
9408 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9409
9410 this.update(&mut cx, |this, _| {
9411 this.clear_tasks();
9412 for (key, value) in rows {
9413 this.insert_tasks(key, value);
9414 }
9415 })
9416 .ok();
9417 })
9418 }
9419 fn fetch_runnable_ranges(
9420 snapshot: &DisplaySnapshot,
9421 range: Range<Anchor>,
9422 ) -> Vec<language::RunnableRange> {
9423 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9424 }
9425
9426 fn runnable_rows(
9427 project: Model<Project>,
9428 snapshot: DisplaySnapshot,
9429 runnable_ranges: Vec<RunnableRange>,
9430 mut cx: AsyncWindowContext,
9431 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9432 runnable_ranges
9433 .into_iter()
9434 .filter_map(|mut runnable| {
9435 let tasks = cx
9436 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9437 .ok()?;
9438 if tasks.is_empty() {
9439 return None;
9440 }
9441
9442 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9443
9444 let row = snapshot
9445 .buffer_snapshot
9446 .buffer_line_for_row(MultiBufferRow(point.row))?
9447 .1
9448 .start
9449 .row;
9450
9451 let context_range =
9452 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9453 Some((
9454 (runnable.buffer_id, row),
9455 RunnableTasks {
9456 templates: tasks,
9457 offset: MultiBufferOffset(runnable.run_range.start),
9458 context_range,
9459 column: point.column,
9460 extra_variables: runnable.extra_captures,
9461 },
9462 ))
9463 })
9464 .collect()
9465 }
9466
9467 fn templates_with_tags(
9468 project: &Model<Project>,
9469 runnable: &mut Runnable,
9470 cx: &WindowContext<'_>,
9471 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9472 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9473 let (worktree_id, file) = project
9474 .buffer_for_id(runnable.buffer, cx)
9475 .and_then(|buffer| buffer.read(cx).file())
9476 .map(|file| (file.worktree_id(cx), file.clone()))
9477 .unzip();
9478
9479 (
9480 project.task_store().read(cx).task_inventory().cloned(),
9481 worktree_id,
9482 file,
9483 )
9484 });
9485
9486 let tags = mem::take(&mut runnable.tags);
9487 let mut tags: Vec<_> = tags
9488 .into_iter()
9489 .flat_map(|tag| {
9490 let tag = tag.0.clone();
9491 inventory
9492 .as_ref()
9493 .into_iter()
9494 .flat_map(|inventory| {
9495 inventory.read(cx).list_tasks(
9496 file.clone(),
9497 Some(runnable.language.clone()),
9498 worktree_id,
9499 cx,
9500 )
9501 })
9502 .filter(move |(_, template)| {
9503 template.tags.iter().any(|source_tag| source_tag == &tag)
9504 })
9505 })
9506 .sorted_by_key(|(kind, _)| kind.to_owned())
9507 .collect();
9508 if let Some((leading_tag_source, _)) = tags.first() {
9509 // Strongest source wins; if we have worktree tag binding, prefer that to
9510 // global and language bindings;
9511 // if we have a global binding, prefer that to language binding.
9512 let first_mismatch = tags
9513 .iter()
9514 .position(|(tag_source, _)| tag_source != leading_tag_source);
9515 if let Some(index) = first_mismatch {
9516 tags.truncate(index);
9517 }
9518 }
9519
9520 tags
9521 }
9522
9523 pub fn move_to_enclosing_bracket(
9524 &mut self,
9525 _: &MoveToEnclosingBracket,
9526 cx: &mut ViewContext<Self>,
9527 ) {
9528 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9529 s.move_offsets_with(|snapshot, selection| {
9530 let Some(enclosing_bracket_ranges) =
9531 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9532 else {
9533 return;
9534 };
9535
9536 let mut best_length = usize::MAX;
9537 let mut best_inside = false;
9538 let mut best_in_bracket_range = false;
9539 let mut best_destination = None;
9540 for (open, close) in enclosing_bracket_ranges {
9541 let close = close.to_inclusive();
9542 let length = close.end() - open.start;
9543 let inside = selection.start >= open.end && selection.end <= *close.start();
9544 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9545 || close.contains(&selection.head());
9546
9547 // If best is next to a bracket and current isn't, skip
9548 if !in_bracket_range && best_in_bracket_range {
9549 continue;
9550 }
9551
9552 // Prefer smaller lengths unless best is inside and current isn't
9553 if length > best_length && (best_inside || !inside) {
9554 continue;
9555 }
9556
9557 best_length = length;
9558 best_inside = inside;
9559 best_in_bracket_range = in_bracket_range;
9560 best_destination = Some(
9561 if close.contains(&selection.start) && close.contains(&selection.end) {
9562 if inside {
9563 open.end
9564 } else {
9565 open.start
9566 }
9567 } else if inside {
9568 *close.start()
9569 } else {
9570 *close.end()
9571 },
9572 );
9573 }
9574
9575 if let Some(destination) = best_destination {
9576 selection.collapse_to(destination, SelectionGoal::None);
9577 }
9578 })
9579 });
9580 }
9581
9582 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9583 self.end_selection(cx);
9584 self.selection_history.mode = SelectionHistoryMode::Undoing;
9585 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9586 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9587 self.select_next_state = entry.select_next_state;
9588 self.select_prev_state = entry.select_prev_state;
9589 self.add_selections_state = entry.add_selections_state;
9590 self.request_autoscroll(Autoscroll::newest(), cx);
9591 }
9592 self.selection_history.mode = SelectionHistoryMode::Normal;
9593 }
9594
9595 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9596 self.end_selection(cx);
9597 self.selection_history.mode = SelectionHistoryMode::Redoing;
9598 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9599 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9600 self.select_next_state = entry.select_next_state;
9601 self.select_prev_state = entry.select_prev_state;
9602 self.add_selections_state = entry.add_selections_state;
9603 self.request_autoscroll(Autoscroll::newest(), cx);
9604 }
9605 self.selection_history.mode = SelectionHistoryMode::Normal;
9606 }
9607
9608 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9609 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9610 }
9611
9612 pub fn expand_excerpts_down(
9613 &mut self,
9614 action: &ExpandExcerptsDown,
9615 cx: &mut ViewContext<Self>,
9616 ) {
9617 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9618 }
9619
9620 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9621 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9622 }
9623
9624 pub fn expand_excerpts_for_direction(
9625 &mut self,
9626 lines: u32,
9627 direction: ExpandExcerptDirection,
9628 cx: &mut ViewContext<Self>,
9629 ) {
9630 let selections = self.selections.disjoint_anchors();
9631
9632 let lines = if lines == 0 {
9633 EditorSettings::get_global(cx).expand_excerpt_lines
9634 } else {
9635 lines
9636 };
9637
9638 self.buffer.update(cx, |buffer, cx| {
9639 buffer.expand_excerpts(
9640 selections
9641 .iter()
9642 .map(|selection| selection.head().excerpt_id)
9643 .dedup(),
9644 lines,
9645 direction,
9646 cx,
9647 )
9648 })
9649 }
9650
9651 pub fn expand_excerpt(
9652 &mut self,
9653 excerpt: ExcerptId,
9654 direction: ExpandExcerptDirection,
9655 cx: &mut ViewContext<Self>,
9656 ) {
9657 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9658 self.buffer.update(cx, |buffer, cx| {
9659 buffer.expand_excerpts([excerpt], lines, direction, cx)
9660 })
9661 }
9662
9663 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9664 self.go_to_diagnostic_impl(Direction::Next, cx)
9665 }
9666
9667 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9668 self.go_to_diagnostic_impl(Direction::Prev, cx)
9669 }
9670
9671 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9672 let buffer = self.buffer.read(cx).snapshot(cx);
9673 let selection = self.selections.newest::<usize>(cx);
9674
9675 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9676 if direction == Direction::Next {
9677 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9678 let (group_id, jump_to) = popover.activation_info();
9679 if self.activate_diagnostics(group_id, cx) {
9680 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9681 let mut new_selection = s.newest_anchor().clone();
9682 new_selection.collapse_to(jump_to, SelectionGoal::None);
9683 s.select_anchors(vec![new_selection.clone()]);
9684 });
9685 }
9686 return;
9687 }
9688 }
9689
9690 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9691 active_diagnostics
9692 .primary_range
9693 .to_offset(&buffer)
9694 .to_inclusive()
9695 });
9696 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9697 if active_primary_range.contains(&selection.head()) {
9698 *active_primary_range.start()
9699 } else {
9700 selection.head()
9701 }
9702 } else {
9703 selection.head()
9704 };
9705 let snapshot = self.snapshot(cx);
9706 loop {
9707 let diagnostics = if direction == Direction::Prev {
9708 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9709 } else {
9710 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9711 }
9712 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9713 let group = diagnostics
9714 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9715 // be sorted in a stable way
9716 // skip until we are at current active diagnostic, if it exists
9717 .skip_while(|entry| {
9718 (match direction {
9719 Direction::Prev => entry.range.start >= search_start,
9720 Direction::Next => entry.range.start <= search_start,
9721 }) && self
9722 .active_diagnostics
9723 .as_ref()
9724 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9725 })
9726 .find_map(|entry| {
9727 if entry.diagnostic.is_primary
9728 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9729 && !entry.range.is_empty()
9730 // if we match with the active diagnostic, skip it
9731 && Some(entry.diagnostic.group_id)
9732 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9733 {
9734 Some((entry.range, entry.diagnostic.group_id))
9735 } else {
9736 None
9737 }
9738 });
9739
9740 if let Some((primary_range, group_id)) = group {
9741 if self.activate_diagnostics(group_id, cx) {
9742 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9743 s.select(vec![Selection {
9744 id: selection.id,
9745 start: primary_range.start,
9746 end: primary_range.start,
9747 reversed: false,
9748 goal: SelectionGoal::None,
9749 }]);
9750 });
9751 }
9752 break;
9753 } else {
9754 // Cycle around to the start of the buffer, potentially moving back to the start of
9755 // the currently active diagnostic.
9756 active_primary_range.take();
9757 if direction == Direction::Prev {
9758 if search_start == buffer.len() {
9759 break;
9760 } else {
9761 search_start = buffer.len();
9762 }
9763 } else if search_start == 0 {
9764 break;
9765 } else {
9766 search_start = 0;
9767 }
9768 }
9769 }
9770 }
9771
9772 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9773 let snapshot = self
9774 .display_map
9775 .update(cx, |display_map, cx| display_map.snapshot(cx));
9776 let selection = self.selections.newest::<Point>(cx);
9777 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9778 }
9779
9780 fn go_to_hunk_after_position(
9781 &mut self,
9782 snapshot: &DisplaySnapshot,
9783 position: Point,
9784 cx: &mut ViewContext<'_, Editor>,
9785 ) -> Option<MultiBufferDiffHunk> {
9786 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9787 snapshot,
9788 position,
9789 false,
9790 snapshot
9791 .buffer_snapshot
9792 .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
9793 cx,
9794 ) {
9795 return Some(hunk);
9796 }
9797
9798 let wrapped_point = Point::zero();
9799 self.go_to_next_hunk_in_direction(
9800 snapshot,
9801 wrapped_point,
9802 true,
9803 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9804 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9805 ),
9806 cx,
9807 )
9808 }
9809
9810 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9811 let snapshot = self
9812 .display_map
9813 .update(cx, |display_map, cx| display_map.snapshot(cx));
9814 let selection = self.selections.newest::<Point>(cx);
9815
9816 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9817 }
9818
9819 fn go_to_hunk_before_position(
9820 &mut self,
9821 snapshot: &DisplaySnapshot,
9822 position: Point,
9823 cx: &mut ViewContext<'_, Editor>,
9824 ) -> Option<MultiBufferDiffHunk> {
9825 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9826 snapshot,
9827 position,
9828 false,
9829 snapshot
9830 .buffer_snapshot
9831 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
9832 cx,
9833 ) {
9834 return Some(hunk);
9835 }
9836
9837 let wrapped_point = snapshot.buffer_snapshot.max_point();
9838 self.go_to_next_hunk_in_direction(
9839 snapshot,
9840 wrapped_point,
9841 true,
9842 snapshot
9843 .buffer_snapshot
9844 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
9845 cx,
9846 )
9847 }
9848
9849 fn go_to_next_hunk_in_direction(
9850 &mut self,
9851 snapshot: &DisplaySnapshot,
9852 initial_point: Point,
9853 is_wrapped: bool,
9854 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9855 cx: &mut ViewContext<Editor>,
9856 ) -> Option<MultiBufferDiffHunk> {
9857 let display_point = initial_point.to_display_point(snapshot);
9858 let mut hunks = hunks
9859 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9860 .filter(|(display_hunk, _)| {
9861 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9862 })
9863 .dedup();
9864
9865 if let Some((display_hunk, hunk)) = hunks.next() {
9866 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9867 let row = display_hunk.start_display_row();
9868 let point = DisplayPoint::new(row, 0);
9869 s.select_display_ranges([point..point]);
9870 });
9871
9872 Some(hunk)
9873 } else {
9874 None
9875 }
9876 }
9877
9878 pub fn go_to_definition(
9879 &mut self,
9880 _: &GoToDefinition,
9881 cx: &mut ViewContext<Self>,
9882 ) -> Task<Result<Navigated>> {
9883 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9884 cx.spawn(|editor, mut cx| async move {
9885 if definition.await? == Navigated::Yes {
9886 return Ok(Navigated::Yes);
9887 }
9888 match editor.update(&mut cx, |editor, cx| {
9889 editor.find_all_references(&FindAllReferences, cx)
9890 })? {
9891 Some(references) => references.await,
9892 None => Ok(Navigated::No),
9893 }
9894 })
9895 }
9896
9897 pub fn go_to_declaration(
9898 &mut self,
9899 _: &GoToDeclaration,
9900 cx: &mut ViewContext<Self>,
9901 ) -> Task<Result<Navigated>> {
9902 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9903 }
9904
9905 pub fn go_to_declaration_split(
9906 &mut self,
9907 _: &GoToDeclaration,
9908 cx: &mut ViewContext<Self>,
9909 ) -> Task<Result<Navigated>> {
9910 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9911 }
9912
9913 pub fn go_to_implementation(
9914 &mut self,
9915 _: &GoToImplementation,
9916 cx: &mut ViewContext<Self>,
9917 ) -> Task<Result<Navigated>> {
9918 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9919 }
9920
9921 pub fn go_to_implementation_split(
9922 &mut self,
9923 _: &GoToImplementationSplit,
9924 cx: &mut ViewContext<Self>,
9925 ) -> Task<Result<Navigated>> {
9926 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9927 }
9928
9929 pub fn go_to_type_definition(
9930 &mut self,
9931 _: &GoToTypeDefinition,
9932 cx: &mut ViewContext<Self>,
9933 ) -> Task<Result<Navigated>> {
9934 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9935 }
9936
9937 pub fn go_to_definition_split(
9938 &mut self,
9939 _: &GoToDefinitionSplit,
9940 cx: &mut ViewContext<Self>,
9941 ) -> Task<Result<Navigated>> {
9942 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9943 }
9944
9945 pub fn go_to_type_definition_split(
9946 &mut self,
9947 _: &GoToTypeDefinitionSplit,
9948 cx: &mut ViewContext<Self>,
9949 ) -> Task<Result<Navigated>> {
9950 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9951 }
9952
9953 fn go_to_definition_of_kind(
9954 &mut self,
9955 kind: GotoDefinitionKind,
9956 split: bool,
9957 cx: &mut ViewContext<Self>,
9958 ) -> Task<Result<Navigated>> {
9959 let Some(provider) = self.semantics_provider.clone() else {
9960 return Task::ready(Ok(Navigated::No));
9961 };
9962 let head = self.selections.newest::<usize>(cx).head();
9963 let buffer = self.buffer.read(cx);
9964 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9965 text_anchor
9966 } else {
9967 return Task::ready(Ok(Navigated::No));
9968 };
9969
9970 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9971 return Task::ready(Ok(Navigated::No));
9972 };
9973
9974 cx.spawn(|editor, mut cx| async move {
9975 let definitions = definitions.await?;
9976 let navigated = editor
9977 .update(&mut cx, |editor, cx| {
9978 editor.navigate_to_hover_links(
9979 Some(kind),
9980 definitions
9981 .into_iter()
9982 .filter(|location| {
9983 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9984 })
9985 .map(HoverLink::Text)
9986 .collect::<Vec<_>>(),
9987 split,
9988 cx,
9989 )
9990 })?
9991 .await?;
9992 anyhow::Ok(navigated)
9993 })
9994 }
9995
9996 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9997 let position = self.selections.newest_anchor().head();
9998 let Some((buffer, buffer_position)) =
9999 self.buffer.read(cx).text_anchor_for_position(position, cx)
10000 else {
10001 return;
10002 };
10003
10004 cx.spawn(|editor, mut cx| async move {
10005 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
10006 editor.update(&mut cx, |_, cx| {
10007 cx.open_url(&url);
10008 })
10009 } else {
10010 Ok(())
10011 }
10012 })
10013 .detach();
10014 }
10015
10016 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
10017 let Some(workspace) = self.workspace() else {
10018 return;
10019 };
10020
10021 let position = self.selections.newest_anchor().head();
10022
10023 let Some((buffer, buffer_position)) =
10024 self.buffer.read(cx).text_anchor_for_position(position, cx)
10025 else {
10026 return;
10027 };
10028
10029 let project = self.project.clone();
10030
10031 cx.spawn(|_, mut cx| async move {
10032 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10033
10034 if let Some((_, path)) = result {
10035 workspace
10036 .update(&mut cx, |workspace, cx| {
10037 workspace.open_resolved_path(path, cx)
10038 })?
10039 .await?;
10040 }
10041 anyhow::Ok(())
10042 })
10043 .detach();
10044 }
10045
10046 pub(crate) fn navigate_to_hover_links(
10047 &mut self,
10048 kind: Option<GotoDefinitionKind>,
10049 mut definitions: Vec<HoverLink>,
10050 split: bool,
10051 cx: &mut ViewContext<Editor>,
10052 ) -> Task<Result<Navigated>> {
10053 // If there is one definition, just open it directly
10054 if definitions.len() == 1 {
10055 let definition = definitions.pop().unwrap();
10056
10057 enum TargetTaskResult {
10058 Location(Option<Location>),
10059 AlreadyNavigated,
10060 }
10061
10062 let target_task = match definition {
10063 HoverLink::Text(link) => {
10064 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10065 }
10066 HoverLink::InlayHint(lsp_location, server_id) => {
10067 let computation = self.compute_target_location(lsp_location, server_id, cx);
10068 cx.background_executor().spawn(async move {
10069 let location = computation.await?;
10070 Ok(TargetTaskResult::Location(location))
10071 })
10072 }
10073 HoverLink::Url(url) => {
10074 cx.open_url(&url);
10075 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10076 }
10077 HoverLink::File(path) => {
10078 if let Some(workspace) = self.workspace() {
10079 cx.spawn(|_, mut cx| async move {
10080 workspace
10081 .update(&mut cx, |workspace, cx| {
10082 workspace.open_resolved_path(path, cx)
10083 })?
10084 .await
10085 .map(|_| TargetTaskResult::AlreadyNavigated)
10086 })
10087 } else {
10088 Task::ready(Ok(TargetTaskResult::Location(None)))
10089 }
10090 }
10091 };
10092 cx.spawn(|editor, mut cx| async move {
10093 let target = match target_task.await.context("target resolution task")? {
10094 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10095 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10096 TargetTaskResult::Location(Some(target)) => target,
10097 };
10098
10099 editor.update(&mut cx, |editor, cx| {
10100 let Some(workspace) = editor.workspace() else {
10101 return Navigated::No;
10102 };
10103 let pane = workspace.read(cx).active_pane().clone();
10104
10105 let range = target.range.to_offset(target.buffer.read(cx));
10106 let range = editor.range_for_match(&range);
10107
10108 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10109 let buffer = target.buffer.read(cx);
10110 let range = check_multiline_range(buffer, range);
10111 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10112 s.select_ranges([range]);
10113 });
10114 } else {
10115 cx.window_context().defer(move |cx| {
10116 let target_editor: View<Self> =
10117 workspace.update(cx, |workspace, cx| {
10118 let pane = if split {
10119 workspace.adjacent_pane(cx)
10120 } else {
10121 workspace.active_pane().clone()
10122 };
10123
10124 workspace.open_project_item(
10125 pane,
10126 target.buffer.clone(),
10127 true,
10128 true,
10129 cx,
10130 )
10131 });
10132 target_editor.update(cx, |target_editor, cx| {
10133 // When selecting a definition in a different buffer, disable the nav history
10134 // to avoid creating a history entry at the previous cursor location.
10135 pane.update(cx, |pane, _| pane.disable_history());
10136 let buffer = target.buffer.read(cx);
10137 let range = check_multiline_range(buffer, range);
10138 target_editor.change_selections(
10139 Some(Autoscroll::focused()),
10140 cx,
10141 |s| {
10142 s.select_ranges([range]);
10143 },
10144 );
10145 pane.update(cx, |pane, _| pane.enable_history());
10146 });
10147 });
10148 }
10149 Navigated::Yes
10150 })
10151 })
10152 } else if !definitions.is_empty() {
10153 cx.spawn(|editor, mut cx| async move {
10154 let (title, location_tasks, workspace) = editor
10155 .update(&mut cx, |editor, cx| {
10156 let tab_kind = match kind {
10157 Some(GotoDefinitionKind::Implementation) => "Implementations",
10158 _ => "Definitions",
10159 };
10160 let title = definitions
10161 .iter()
10162 .find_map(|definition| match definition {
10163 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10164 let buffer = origin.buffer.read(cx);
10165 format!(
10166 "{} for {}",
10167 tab_kind,
10168 buffer
10169 .text_for_range(origin.range.clone())
10170 .collect::<String>()
10171 )
10172 }),
10173 HoverLink::InlayHint(_, _) => None,
10174 HoverLink::Url(_) => None,
10175 HoverLink::File(_) => None,
10176 })
10177 .unwrap_or(tab_kind.to_string());
10178 let location_tasks = definitions
10179 .into_iter()
10180 .map(|definition| match definition {
10181 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
10182 HoverLink::InlayHint(lsp_location, server_id) => {
10183 editor.compute_target_location(lsp_location, server_id, cx)
10184 }
10185 HoverLink::Url(_) => Task::ready(Ok(None)),
10186 HoverLink::File(_) => Task::ready(Ok(None)),
10187 })
10188 .collect::<Vec<_>>();
10189 (title, location_tasks, editor.workspace().clone())
10190 })
10191 .context("location tasks preparation")?;
10192
10193 let locations = future::join_all(location_tasks)
10194 .await
10195 .into_iter()
10196 .filter_map(|location| location.transpose())
10197 .collect::<Result<_>>()
10198 .context("location tasks")?;
10199
10200 let Some(workspace) = workspace else {
10201 return Ok(Navigated::No);
10202 };
10203 let opened = workspace
10204 .update(&mut cx, |workspace, cx| {
10205 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10206 })
10207 .ok();
10208
10209 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10210 })
10211 } else {
10212 Task::ready(Ok(Navigated::No))
10213 }
10214 }
10215
10216 fn compute_target_location(
10217 &self,
10218 lsp_location: lsp::Location,
10219 server_id: LanguageServerId,
10220 cx: &mut ViewContext<Self>,
10221 ) -> Task<anyhow::Result<Option<Location>>> {
10222 let Some(project) = self.project.clone() else {
10223 return Task::Ready(Some(Ok(None)));
10224 };
10225
10226 cx.spawn(move |editor, mut cx| async move {
10227 let location_task = editor.update(&mut cx, |_, cx| {
10228 project.update(cx, |project, cx| {
10229 let language_server_name = project
10230 .language_server_statuses(cx)
10231 .find(|(id, _)| server_id == *id)
10232 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10233 language_server_name.map(|language_server_name| {
10234 project.open_local_buffer_via_lsp(
10235 lsp_location.uri.clone(),
10236 server_id,
10237 language_server_name,
10238 cx,
10239 )
10240 })
10241 })
10242 })?;
10243 let location = match location_task {
10244 Some(task) => Some({
10245 let target_buffer_handle = task.await.context("open local buffer")?;
10246 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10247 let target_start = target_buffer
10248 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10249 let target_end = target_buffer
10250 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10251 target_buffer.anchor_after(target_start)
10252 ..target_buffer.anchor_before(target_end)
10253 })?;
10254 Location {
10255 buffer: target_buffer_handle,
10256 range,
10257 }
10258 }),
10259 None => None,
10260 };
10261 Ok(location)
10262 })
10263 }
10264
10265 pub fn find_all_references(
10266 &mut self,
10267 _: &FindAllReferences,
10268 cx: &mut ViewContext<Self>,
10269 ) -> Option<Task<Result<Navigated>>> {
10270 let selection = self.selections.newest::<usize>(cx);
10271 let multi_buffer = self.buffer.read(cx);
10272 let head = selection.head();
10273
10274 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10275 let head_anchor = multi_buffer_snapshot.anchor_at(
10276 head,
10277 if head < selection.tail() {
10278 Bias::Right
10279 } else {
10280 Bias::Left
10281 },
10282 );
10283
10284 match self
10285 .find_all_references_task_sources
10286 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10287 {
10288 Ok(_) => {
10289 log::info!(
10290 "Ignoring repeated FindAllReferences invocation with the position of already running task"
10291 );
10292 return None;
10293 }
10294 Err(i) => {
10295 self.find_all_references_task_sources.insert(i, head_anchor);
10296 }
10297 }
10298
10299 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10300 let workspace = self.workspace()?;
10301 let project = workspace.read(cx).project().clone();
10302 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10303 Some(cx.spawn(|editor, mut cx| async move {
10304 let _cleanup = defer({
10305 let mut cx = cx.clone();
10306 move || {
10307 let _ = editor.update(&mut cx, |editor, _| {
10308 if let Ok(i) =
10309 editor
10310 .find_all_references_task_sources
10311 .binary_search_by(|anchor| {
10312 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10313 })
10314 {
10315 editor.find_all_references_task_sources.remove(i);
10316 }
10317 });
10318 }
10319 });
10320
10321 let locations = references.await?;
10322 if locations.is_empty() {
10323 return anyhow::Ok(Navigated::No);
10324 }
10325
10326 workspace.update(&mut cx, |workspace, cx| {
10327 let title = locations
10328 .first()
10329 .as_ref()
10330 .map(|location| {
10331 let buffer = location.buffer.read(cx);
10332 format!(
10333 "References to `{}`",
10334 buffer
10335 .text_for_range(location.range.clone())
10336 .collect::<String>()
10337 )
10338 })
10339 .unwrap();
10340 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10341 Navigated::Yes
10342 })
10343 }))
10344 }
10345
10346 /// Opens a multibuffer with the given project locations in it
10347 pub fn open_locations_in_multibuffer(
10348 workspace: &mut Workspace,
10349 mut locations: Vec<Location>,
10350 title: String,
10351 split: bool,
10352 cx: &mut ViewContext<Workspace>,
10353 ) {
10354 // If there are multiple definitions, open them in a multibuffer
10355 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10356 let mut locations = locations.into_iter().peekable();
10357 let mut ranges_to_highlight = Vec::new();
10358 let capability = workspace.project().read(cx).capability();
10359
10360 let excerpt_buffer = cx.new_model(|cx| {
10361 let mut multibuffer = MultiBuffer::new(capability);
10362 while let Some(location) = locations.next() {
10363 let buffer = location.buffer.read(cx);
10364 let mut ranges_for_buffer = Vec::new();
10365 let range = location.range.to_offset(buffer);
10366 ranges_for_buffer.push(range.clone());
10367
10368 while let Some(next_location) = locations.peek() {
10369 if next_location.buffer == location.buffer {
10370 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10371 locations.next();
10372 } else {
10373 break;
10374 }
10375 }
10376
10377 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10378 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10379 location.buffer.clone(),
10380 ranges_for_buffer,
10381 DEFAULT_MULTIBUFFER_CONTEXT,
10382 cx,
10383 ))
10384 }
10385
10386 multibuffer.with_title(title)
10387 });
10388
10389 let editor = cx.new_view(|cx| {
10390 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10391 });
10392 editor.update(cx, |editor, cx| {
10393 if let Some(first_range) = ranges_to_highlight.first() {
10394 editor.change_selections(None, cx, |selections| {
10395 selections.clear_disjoint();
10396 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10397 });
10398 }
10399 editor.highlight_background::<Self>(
10400 &ranges_to_highlight,
10401 |theme| theme.editor_highlighted_line_background,
10402 cx,
10403 );
10404 });
10405
10406 let item = Box::new(editor);
10407 let item_id = item.item_id();
10408
10409 if split {
10410 workspace.split_item(SplitDirection::Right, item.clone(), cx);
10411 } else {
10412 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10413 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10414 pane.close_current_preview_item(cx)
10415 } else {
10416 None
10417 }
10418 });
10419 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10420 }
10421 workspace.active_pane().update(cx, |pane, cx| {
10422 pane.set_preview_item_id(Some(item_id), cx);
10423 });
10424 }
10425
10426 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10427 use language::ToOffset as _;
10428
10429 let provider = self.semantics_provider.clone()?;
10430 let selection = self.selections.newest_anchor().clone();
10431 let (cursor_buffer, cursor_buffer_position) = self
10432 .buffer
10433 .read(cx)
10434 .text_anchor_for_position(selection.head(), cx)?;
10435 let (tail_buffer, cursor_buffer_position_end) = self
10436 .buffer
10437 .read(cx)
10438 .text_anchor_for_position(selection.tail(), cx)?;
10439 if tail_buffer != cursor_buffer {
10440 return None;
10441 }
10442
10443 let snapshot = cursor_buffer.read(cx).snapshot();
10444 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10445 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10446 let prepare_rename = provider
10447 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10448 .unwrap_or_else(|| Task::ready(Ok(None)));
10449 drop(snapshot);
10450
10451 Some(cx.spawn(|this, mut cx| async move {
10452 let rename_range = if let Some(range) = prepare_rename.await? {
10453 Some(range)
10454 } else {
10455 this.update(&mut cx, |this, cx| {
10456 let buffer = this.buffer.read(cx).snapshot(cx);
10457 let mut buffer_highlights = this
10458 .document_highlights_for_position(selection.head(), &buffer)
10459 .filter(|highlight| {
10460 highlight.start.excerpt_id == selection.head().excerpt_id
10461 && highlight.end.excerpt_id == selection.head().excerpt_id
10462 });
10463 buffer_highlights
10464 .next()
10465 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10466 })?
10467 };
10468 if let Some(rename_range) = rename_range {
10469 this.update(&mut cx, |this, cx| {
10470 let snapshot = cursor_buffer.read(cx).snapshot();
10471 let rename_buffer_range = rename_range.to_offset(&snapshot);
10472 let cursor_offset_in_rename_range =
10473 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10474 let cursor_offset_in_rename_range_end =
10475 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10476
10477 this.take_rename(false, cx);
10478 let buffer = this.buffer.read(cx).read(cx);
10479 let cursor_offset = selection.head().to_offset(&buffer);
10480 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10481 let rename_end = rename_start + rename_buffer_range.len();
10482 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10483 let mut old_highlight_id = None;
10484 let old_name: Arc<str> = buffer
10485 .chunks(rename_start..rename_end, true)
10486 .map(|chunk| {
10487 if old_highlight_id.is_none() {
10488 old_highlight_id = chunk.syntax_highlight_id;
10489 }
10490 chunk.text
10491 })
10492 .collect::<String>()
10493 .into();
10494
10495 drop(buffer);
10496
10497 // Position the selection in the rename editor so that it matches the current selection.
10498 this.show_local_selections = false;
10499 let rename_editor = cx.new_view(|cx| {
10500 let mut editor = Editor::single_line(cx);
10501 editor.buffer.update(cx, |buffer, cx| {
10502 buffer.edit([(0..0, old_name.clone())], None, cx)
10503 });
10504 let rename_selection_range = match cursor_offset_in_rename_range
10505 .cmp(&cursor_offset_in_rename_range_end)
10506 {
10507 Ordering::Equal => {
10508 editor.select_all(&SelectAll, cx);
10509 return editor;
10510 }
10511 Ordering::Less => {
10512 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10513 }
10514 Ordering::Greater => {
10515 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10516 }
10517 };
10518 if rename_selection_range.end > old_name.len() {
10519 editor.select_all(&SelectAll, cx);
10520 } else {
10521 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10522 s.select_ranges([rename_selection_range]);
10523 });
10524 }
10525 editor
10526 });
10527 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10528 if e == &EditorEvent::Focused {
10529 cx.emit(EditorEvent::FocusedIn)
10530 }
10531 })
10532 .detach();
10533
10534 let write_highlights =
10535 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10536 let read_highlights =
10537 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10538 let ranges = write_highlights
10539 .iter()
10540 .flat_map(|(_, ranges)| ranges.iter())
10541 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10542 .cloned()
10543 .collect();
10544
10545 this.highlight_text::<Rename>(
10546 ranges,
10547 HighlightStyle {
10548 fade_out: Some(0.6),
10549 ..Default::default()
10550 },
10551 cx,
10552 );
10553 let rename_focus_handle = rename_editor.focus_handle(cx);
10554 cx.focus(&rename_focus_handle);
10555 let block_id = this.insert_blocks(
10556 [BlockProperties {
10557 style: BlockStyle::Flex,
10558 placement: BlockPlacement::Below(range.start),
10559 height: 1,
10560 render: Arc::new({
10561 let rename_editor = rename_editor.clone();
10562 move |cx: &mut BlockContext| {
10563 let mut text_style = cx.editor_style.text.clone();
10564 if let Some(highlight_style) = old_highlight_id
10565 .and_then(|h| h.style(&cx.editor_style.syntax))
10566 {
10567 text_style = text_style.highlight(highlight_style);
10568 }
10569 div()
10570 .block_mouse_down()
10571 .pl(cx.anchor_x)
10572 .child(EditorElement::new(
10573 &rename_editor,
10574 EditorStyle {
10575 background: cx.theme().system().transparent,
10576 local_player: cx.editor_style.local_player,
10577 text: text_style,
10578 scrollbar_width: cx.editor_style.scrollbar_width,
10579 syntax: cx.editor_style.syntax.clone(),
10580 status: cx.editor_style.status.clone(),
10581 inlay_hints_style: HighlightStyle {
10582 font_weight: Some(FontWeight::BOLD),
10583 ..make_inlay_hints_style(cx)
10584 },
10585 suggestions_style: HighlightStyle {
10586 color: Some(cx.theme().status().predictive),
10587 ..HighlightStyle::default()
10588 },
10589 ..EditorStyle::default()
10590 },
10591 ))
10592 .into_any_element()
10593 }
10594 }),
10595 priority: 0,
10596 }],
10597 Some(Autoscroll::fit()),
10598 cx,
10599 )[0];
10600 this.pending_rename = Some(RenameState {
10601 range,
10602 old_name,
10603 editor: rename_editor,
10604 block_id,
10605 });
10606 })?;
10607 }
10608
10609 Ok(())
10610 }))
10611 }
10612
10613 pub fn confirm_rename(
10614 &mut self,
10615 _: &ConfirmRename,
10616 cx: &mut ViewContext<Self>,
10617 ) -> Option<Task<Result<()>>> {
10618 let rename = self.take_rename(false, cx)?;
10619 let workspace = self.workspace()?.downgrade();
10620 let (buffer, start) = self
10621 .buffer
10622 .read(cx)
10623 .text_anchor_for_position(rename.range.start, cx)?;
10624 let (end_buffer, _) = self
10625 .buffer
10626 .read(cx)
10627 .text_anchor_for_position(rename.range.end, cx)?;
10628 if buffer != end_buffer {
10629 return None;
10630 }
10631
10632 let old_name = rename.old_name;
10633 let new_name = rename.editor.read(cx).text(cx);
10634
10635 let rename = self.semantics_provider.as_ref()?.perform_rename(
10636 &buffer,
10637 start,
10638 new_name.clone(),
10639 cx,
10640 )?;
10641
10642 Some(cx.spawn(|editor, mut cx| async move {
10643 let project_transaction = rename.await?;
10644 Self::open_project_transaction(
10645 &editor,
10646 workspace,
10647 project_transaction,
10648 format!("Rename: {} → {}", old_name, new_name),
10649 cx.clone(),
10650 )
10651 .await?;
10652
10653 editor.update(&mut cx, |editor, cx| {
10654 editor.refresh_document_highlights(cx);
10655 })?;
10656 Ok(())
10657 }))
10658 }
10659
10660 fn take_rename(
10661 &mut self,
10662 moving_cursor: bool,
10663 cx: &mut ViewContext<Self>,
10664 ) -> Option<RenameState> {
10665 let rename = self.pending_rename.take()?;
10666 if rename.editor.focus_handle(cx).is_focused(cx) {
10667 cx.focus(&self.focus_handle);
10668 }
10669
10670 self.remove_blocks(
10671 [rename.block_id].into_iter().collect(),
10672 Some(Autoscroll::fit()),
10673 cx,
10674 );
10675 self.clear_highlights::<Rename>(cx);
10676 self.show_local_selections = true;
10677
10678 if moving_cursor {
10679 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10680 editor.selections.newest::<usize>(cx).head()
10681 });
10682
10683 // Update the selection to match the position of the selection inside
10684 // the rename editor.
10685 let snapshot = self.buffer.read(cx).read(cx);
10686 let rename_range = rename.range.to_offset(&snapshot);
10687 let cursor_in_editor = snapshot
10688 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10689 .min(rename_range.end);
10690 drop(snapshot);
10691
10692 self.change_selections(None, cx, |s| {
10693 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10694 });
10695 } else {
10696 self.refresh_document_highlights(cx);
10697 }
10698
10699 Some(rename)
10700 }
10701
10702 pub fn pending_rename(&self) -> Option<&RenameState> {
10703 self.pending_rename.as_ref()
10704 }
10705
10706 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10707 let project = match &self.project {
10708 Some(project) => project.clone(),
10709 None => return None,
10710 };
10711
10712 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10713 }
10714
10715 fn format_selections(
10716 &mut self,
10717 _: &FormatSelections,
10718 cx: &mut ViewContext<Self>,
10719 ) -> Option<Task<Result<()>>> {
10720 let project = match &self.project {
10721 Some(project) => project.clone(),
10722 None => return None,
10723 };
10724
10725 let selections = self
10726 .selections
10727 .all_adjusted(cx)
10728 .into_iter()
10729 .filter(|s| !s.is_empty())
10730 .collect_vec();
10731
10732 Some(self.perform_format(
10733 project,
10734 FormatTrigger::Manual,
10735 FormatTarget::Ranges(selections),
10736 cx,
10737 ))
10738 }
10739
10740 fn perform_format(
10741 &mut self,
10742 project: Model<Project>,
10743 trigger: FormatTrigger,
10744 target: FormatTarget,
10745 cx: &mut ViewContext<Self>,
10746 ) -> Task<Result<()>> {
10747 let buffer = self.buffer().clone();
10748 let mut buffers = buffer.read(cx).all_buffers();
10749 if trigger == FormatTrigger::Save {
10750 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10751 }
10752
10753 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10754 let format = project.update(cx, |project, cx| {
10755 project.format(buffers, true, trigger, target, cx)
10756 });
10757
10758 cx.spawn(|_, mut cx| async move {
10759 let transaction = futures::select_biased! {
10760 () = timeout => {
10761 log::warn!("timed out waiting for formatting");
10762 None
10763 }
10764 transaction = format.log_err().fuse() => transaction,
10765 };
10766
10767 buffer
10768 .update(&mut cx, |buffer, cx| {
10769 if let Some(transaction) = transaction {
10770 if !buffer.is_singleton() {
10771 buffer.push_transaction(&transaction.0, cx);
10772 }
10773 }
10774
10775 cx.notify();
10776 })
10777 .ok();
10778
10779 Ok(())
10780 })
10781 }
10782
10783 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10784 if let Some(project) = self.project.clone() {
10785 self.buffer.update(cx, |multi_buffer, cx| {
10786 project.update(cx, |project, cx| {
10787 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10788 });
10789 })
10790 }
10791 }
10792
10793 fn cancel_language_server_work(
10794 &mut self,
10795 _: &actions::CancelLanguageServerWork,
10796 cx: &mut ViewContext<Self>,
10797 ) {
10798 if let Some(project) = self.project.clone() {
10799 self.buffer.update(cx, |multi_buffer, cx| {
10800 project.update(cx, |project, cx| {
10801 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10802 });
10803 })
10804 }
10805 }
10806
10807 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10808 cx.show_character_palette();
10809 }
10810
10811 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10812 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10813 let buffer = self.buffer.read(cx).snapshot(cx);
10814 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10815 let is_valid = buffer
10816 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10817 .any(|entry| {
10818 entry.diagnostic.is_primary
10819 && !entry.range.is_empty()
10820 && entry.range.start == primary_range_start
10821 && entry.diagnostic.message == active_diagnostics.primary_message
10822 });
10823
10824 if is_valid != active_diagnostics.is_valid {
10825 active_diagnostics.is_valid = is_valid;
10826 let mut new_styles = HashMap::default();
10827 for (block_id, diagnostic) in &active_diagnostics.blocks {
10828 new_styles.insert(
10829 *block_id,
10830 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10831 );
10832 }
10833 self.display_map.update(cx, |display_map, _cx| {
10834 display_map.replace_blocks(new_styles)
10835 });
10836 }
10837 }
10838 }
10839
10840 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10841 self.dismiss_diagnostics(cx);
10842 let snapshot = self.snapshot(cx);
10843 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10844 let buffer = self.buffer.read(cx).snapshot(cx);
10845
10846 let mut primary_range = None;
10847 let mut primary_message = None;
10848 let mut group_end = Point::zero();
10849 let diagnostic_group = buffer
10850 .diagnostic_group::<MultiBufferPoint>(group_id)
10851 .filter_map(|entry| {
10852 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10853 && (entry.range.start.row == entry.range.end.row
10854 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10855 {
10856 return None;
10857 }
10858 if entry.range.end > group_end {
10859 group_end = entry.range.end;
10860 }
10861 if entry.diagnostic.is_primary {
10862 primary_range = Some(entry.range.clone());
10863 primary_message = Some(entry.diagnostic.message.clone());
10864 }
10865 Some(entry)
10866 })
10867 .collect::<Vec<_>>();
10868 let primary_range = primary_range?;
10869 let primary_message = primary_message?;
10870 let primary_range =
10871 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10872
10873 let blocks = display_map
10874 .insert_blocks(
10875 diagnostic_group.iter().map(|entry| {
10876 let diagnostic = entry.diagnostic.clone();
10877 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10878 BlockProperties {
10879 style: BlockStyle::Fixed,
10880 placement: BlockPlacement::Below(
10881 buffer.anchor_after(entry.range.start),
10882 ),
10883 height: message_height,
10884 render: diagnostic_block_renderer(diagnostic, None, true, true),
10885 priority: 0,
10886 }
10887 }),
10888 cx,
10889 )
10890 .into_iter()
10891 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10892 .collect();
10893
10894 Some(ActiveDiagnosticGroup {
10895 primary_range,
10896 primary_message,
10897 group_id,
10898 blocks,
10899 is_valid: true,
10900 })
10901 });
10902 self.active_diagnostics.is_some()
10903 }
10904
10905 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10906 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10907 self.display_map.update(cx, |display_map, cx| {
10908 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10909 });
10910 cx.notify();
10911 }
10912 }
10913
10914 pub fn set_selections_from_remote(
10915 &mut self,
10916 selections: Vec<Selection<Anchor>>,
10917 pending_selection: Option<Selection<Anchor>>,
10918 cx: &mut ViewContext<Self>,
10919 ) {
10920 let old_cursor_position = self.selections.newest_anchor().head();
10921 self.selections.change_with(cx, |s| {
10922 s.select_anchors(selections);
10923 if let Some(pending_selection) = pending_selection {
10924 s.set_pending(pending_selection, SelectMode::Character);
10925 } else {
10926 s.clear_pending();
10927 }
10928 });
10929 self.selections_did_change(false, &old_cursor_position, true, cx);
10930 }
10931
10932 fn push_to_selection_history(&mut self) {
10933 self.selection_history.push(SelectionHistoryEntry {
10934 selections: self.selections.disjoint_anchors(),
10935 select_next_state: self.select_next_state.clone(),
10936 select_prev_state: self.select_prev_state.clone(),
10937 add_selections_state: self.add_selections_state.clone(),
10938 });
10939 }
10940
10941 pub fn transact(
10942 &mut self,
10943 cx: &mut ViewContext<Self>,
10944 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10945 ) -> Option<TransactionId> {
10946 self.start_transaction_at(Instant::now(), cx);
10947 update(self, cx);
10948 self.end_transaction_at(Instant::now(), cx)
10949 }
10950
10951 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10952 self.end_selection(cx);
10953 if let Some(tx_id) = self
10954 .buffer
10955 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10956 {
10957 self.selection_history
10958 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10959 cx.emit(EditorEvent::TransactionBegun {
10960 transaction_id: tx_id,
10961 })
10962 }
10963 }
10964
10965 fn end_transaction_at(
10966 &mut self,
10967 now: Instant,
10968 cx: &mut ViewContext<Self>,
10969 ) -> Option<TransactionId> {
10970 if let Some(transaction_id) = self
10971 .buffer
10972 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10973 {
10974 if let Some((_, end_selections)) =
10975 self.selection_history.transaction_mut(transaction_id)
10976 {
10977 *end_selections = Some(self.selections.disjoint_anchors());
10978 } else {
10979 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10980 }
10981
10982 cx.emit(EditorEvent::Edited { transaction_id });
10983 Some(transaction_id)
10984 } else {
10985 None
10986 }
10987 }
10988
10989 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10990 let selection = self.selections.newest::<Point>(cx);
10991
10992 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10993 let range = if selection.is_empty() {
10994 let point = selection.head().to_display_point(&display_map);
10995 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10996 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10997 .to_point(&display_map);
10998 start..end
10999 } else {
11000 selection.range()
11001 };
11002 if display_map.folds_in_range(range).next().is_some() {
11003 self.unfold_lines(&Default::default(), cx)
11004 } else {
11005 self.fold(&Default::default(), cx)
11006 }
11007 }
11008
11009 pub fn toggle_fold_recursive(
11010 &mut self,
11011 _: &actions::ToggleFoldRecursive,
11012 cx: &mut ViewContext<Self>,
11013 ) {
11014 let selection = self.selections.newest::<Point>(cx);
11015
11016 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11017 let range = if selection.is_empty() {
11018 let point = selection.head().to_display_point(&display_map);
11019 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11020 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11021 .to_point(&display_map);
11022 start..end
11023 } else {
11024 selection.range()
11025 };
11026 if display_map.folds_in_range(range).next().is_some() {
11027 self.unfold_recursive(&Default::default(), cx)
11028 } else {
11029 self.fold_recursive(&Default::default(), cx)
11030 }
11031 }
11032
11033 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
11034 let mut to_fold = Vec::new();
11035 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11036 let selections = self.selections.all_adjusted(cx);
11037
11038 for selection in selections {
11039 let range = selection.range().sorted();
11040 let buffer_start_row = range.start.row;
11041
11042 if range.start.row != range.end.row {
11043 let mut found = false;
11044 let mut row = range.start.row;
11045 while row <= range.end.row {
11046 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11047 found = true;
11048 row = crease.range().end.row + 1;
11049 to_fold.push(crease);
11050 } else {
11051 row += 1
11052 }
11053 }
11054 if found {
11055 continue;
11056 }
11057 }
11058
11059 for row in (0..=range.start.row).rev() {
11060 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11061 if crease.range().end.row >= buffer_start_row {
11062 to_fold.push(crease);
11063 if row <= range.start.row {
11064 break;
11065 }
11066 }
11067 }
11068 }
11069 }
11070
11071 self.fold_creases(to_fold, true, cx);
11072 }
11073
11074 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
11075 let fold_at_level = fold_at.level;
11076 let snapshot = self.buffer.read(cx).snapshot(cx);
11077 let mut to_fold = Vec::new();
11078 let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
11079
11080 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11081 while start_row < end_row {
11082 match self
11083 .snapshot(cx)
11084 .crease_for_buffer_row(MultiBufferRow(start_row))
11085 {
11086 Some(crease) => {
11087 let nested_start_row = crease.range().start.row + 1;
11088 let nested_end_row = crease.range().end.row;
11089
11090 if current_level < fold_at_level {
11091 stack.push((nested_start_row, nested_end_row, current_level + 1));
11092 } else if current_level == fold_at_level {
11093 to_fold.push(crease);
11094 }
11095
11096 start_row = nested_end_row + 1;
11097 }
11098 None => start_row += 1,
11099 }
11100 }
11101 }
11102
11103 self.fold_creases(to_fold, true, cx);
11104 }
11105
11106 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
11107 let mut fold_ranges = Vec::new();
11108 let snapshot = self.buffer.read(cx).snapshot(cx);
11109
11110 for row in 0..snapshot.max_buffer_row().0 {
11111 if let Some(foldable_range) =
11112 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
11113 {
11114 fold_ranges.push(foldable_range);
11115 }
11116 }
11117
11118 self.fold_creases(fold_ranges, true, cx);
11119 }
11120
11121 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
11122 let mut to_fold = Vec::new();
11123 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11124 let selections = self.selections.all_adjusted(cx);
11125
11126 for selection in selections {
11127 let range = selection.range().sorted();
11128 let buffer_start_row = range.start.row;
11129
11130 if range.start.row != range.end.row {
11131 let mut found = false;
11132 for row in range.start.row..=range.end.row {
11133 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11134 found = true;
11135 to_fold.push(crease);
11136 }
11137 }
11138 if found {
11139 continue;
11140 }
11141 }
11142
11143 for row in (0..=range.start.row).rev() {
11144 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11145 if crease.range().end.row >= buffer_start_row {
11146 to_fold.push(crease);
11147 } else {
11148 break;
11149 }
11150 }
11151 }
11152 }
11153
11154 self.fold_creases(to_fold, true, cx);
11155 }
11156
11157 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
11158 let buffer_row = fold_at.buffer_row;
11159 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11160
11161 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11162 let autoscroll = self
11163 .selections
11164 .all::<Point>(cx)
11165 .iter()
11166 .any(|selection| crease.range().overlaps(&selection.range()));
11167
11168 self.fold_creases(vec![crease], autoscroll, cx);
11169 }
11170 }
11171
11172 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
11173 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11174 let buffer = &display_map.buffer_snapshot;
11175 let selections = self.selections.all::<Point>(cx);
11176 let ranges = selections
11177 .iter()
11178 .map(|s| {
11179 let range = s.display_range(&display_map).sorted();
11180 let mut start = range.start.to_point(&display_map);
11181 let mut end = range.end.to_point(&display_map);
11182 start.column = 0;
11183 end.column = buffer.line_len(MultiBufferRow(end.row));
11184 start..end
11185 })
11186 .collect::<Vec<_>>();
11187
11188 self.unfold_ranges(&ranges, true, true, cx);
11189 }
11190
11191 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11192 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11193 let selections = self.selections.all::<Point>(cx);
11194 let ranges = selections
11195 .iter()
11196 .map(|s| {
11197 let mut range = s.display_range(&display_map).sorted();
11198 *range.start.column_mut() = 0;
11199 *range.end.column_mut() = display_map.line_len(range.end.row());
11200 let start = range.start.to_point(&display_map);
11201 let end = range.end.to_point(&display_map);
11202 start..end
11203 })
11204 .collect::<Vec<_>>();
11205
11206 self.unfold_ranges(&ranges, true, true, cx);
11207 }
11208
11209 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11210 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11211
11212 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11213 ..Point::new(
11214 unfold_at.buffer_row.0,
11215 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11216 );
11217
11218 let autoscroll = self
11219 .selections
11220 .all::<Point>(cx)
11221 .iter()
11222 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11223
11224 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11225 }
11226
11227 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11228 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11229 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11230 }
11231
11232 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11233 let selections = self.selections.all::<Point>(cx);
11234 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11235 let line_mode = self.selections.line_mode;
11236 let ranges = selections
11237 .into_iter()
11238 .map(|s| {
11239 if line_mode {
11240 let start = Point::new(s.start.row, 0);
11241 let end = Point::new(
11242 s.end.row,
11243 display_map
11244 .buffer_snapshot
11245 .line_len(MultiBufferRow(s.end.row)),
11246 );
11247 Crease::simple(start..end, display_map.fold_placeholder.clone())
11248 } else {
11249 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11250 }
11251 })
11252 .collect::<Vec<_>>();
11253 self.fold_creases(ranges, true, cx);
11254 }
11255
11256 pub fn fold_creases<T: ToOffset + Clone>(
11257 &mut self,
11258 creases: Vec<Crease<T>>,
11259 auto_scroll: bool,
11260 cx: &mut ViewContext<Self>,
11261 ) {
11262 if creases.is_empty() {
11263 return;
11264 }
11265
11266 let mut buffers_affected = HashMap::default();
11267 let multi_buffer = self.buffer().read(cx);
11268 for crease in &creases {
11269 if let Some((_, buffer, _)) =
11270 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11271 {
11272 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11273 };
11274 }
11275
11276 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11277
11278 if auto_scroll {
11279 self.request_autoscroll(Autoscroll::fit(), cx);
11280 }
11281
11282 for buffer in buffers_affected.into_values() {
11283 self.sync_expanded_diff_hunks(buffer, cx);
11284 }
11285
11286 cx.notify();
11287
11288 if let Some(active_diagnostics) = self.active_diagnostics.take() {
11289 // Clear diagnostics block when folding a range that contains it.
11290 let snapshot = self.snapshot(cx);
11291 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11292 drop(snapshot);
11293 self.active_diagnostics = Some(active_diagnostics);
11294 self.dismiss_diagnostics(cx);
11295 } else {
11296 self.active_diagnostics = Some(active_diagnostics);
11297 }
11298 }
11299
11300 self.scrollbar_marker_state.dirty = true;
11301 }
11302
11303 /// Removes any folds whose ranges intersect any of the given ranges.
11304 pub fn unfold_ranges<T: ToOffset + Clone>(
11305 &mut self,
11306 ranges: &[Range<T>],
11307 inclusive: bool,
11308 auto_scroll: bool,
11309 cx: &mut ViewContext<Self>,
11310 ) {
11311 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11312 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11313 });
11314 }
11315
11316 /// Removes any folds with the given ranges.
11317 pub fn remove_folds_with_type<T: ToOffset + Clone>(
11318 &mut self,
11319 ranges: &[Range<T>],
11320 type_id: TypeId,
11321 auto_scroll: bool,
11322 cx: &mut ViewContext<Self>,
11323 ) {
11324 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11325 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11326 });
11327 }
11328
11329 fn remove_folds_with<T: ToOffset + Clone>(
11330 &mut self,
11331 ranges: &[Range<T>],
11332 auto_scroll: bool,
11333 cx: &mut ViewContext<Self>,
11334 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11335 ) {
11336 if ranges.is_empty() {
11337 return;
11338 }
11339
11340 let mut buffers_affected = HashMap::default();
11341 let multi_buffer = self.buffer().read(cx);
11342 for range in ranges {
11343 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11344 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11345 };
11346 }
11347
11348 self.display_map.update(cx, update);
11349
11350 if auto_scroll {
11351 self.request_autoscroll(Autoscroll::fit(), cx);
11352 }
11353
11354 for buffer in buffers_affected.into_values() {
11355 self.sync_expanded_diff_hunks(buffer, cx);
11356 }
11357
11358 cx.notify();
11359 self.scrollbar_marker_state.dirty = true;
11360 self.active_indent_guides_state.dirty = true;
11361 }
11362
11363 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11364 self.display_map.read(cx).fold_placeholder.clone()
11365 }
11366
11367 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11368 if hovered != self.gutter_hovered {
11369 self.gutter_hovered = hovered;
11370 cx.notify();
11371 }
11372 }
11373
11374 pub fn insert_blocks(
11375 &mut self,
11376 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11377 autoscroll: Option<Autoscroll>,
11378 cx: &mut ViewContext<Self>,
11379 ) -> Vec<CustomBlockId> {
11380 let blocks = self
11381 .display_map
11382 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11383 if let Some(autoscroll) = autoscroll {
11384 self.request_autoscroll(autoscroll, cx);
11385 }
11386 cx.notify();
11387 blocks
11388 }
11389
11390 pub fn resize_blocks(
11391 &mut self,
11392 heights: HashMap<CustomBlockId, u32>,
11393 autoscroll: Option<Autoscroll>,
11394 cx: &mut ViewContext<Self>,
11395 ) {
11396 self.display_map
11397 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11398 if let Some(autoscroll) = autoscroll {
11399 self.request_autoscroll(autoscroll, cx);
11400 }
11401 cx.notify();
11402 }
11403
11404 pub fn replace_blocks(
11405 &mut self,
11406 renderers: HashMap<CustomBlockId, RenderBlock>,
11407 autoscroll: Option<Autoscroll>,
11408 cx: &mut ViewContext<Self>,
11409 ) {
11410 self.display_map
11411 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11412 if let Some(autoscroll) = autoscroll {
11413 self.request_autoscroll(autoscroll, cx);
11414 }
11415 cx.notify();
11416 }
11417
11418 pub fn remove_blocks(
11419 &mut self,
11420 block_ids: HashSet<CustomBlockId>,
11421 autoscroll: Option<Autoscroll>,
11422 cx: &mut ViewContext<Self>,
11423 ) {
11424 self.display_map.update(cx, |display_map, cx| {
11425 display_map.remove_blocks(block_ids, cx)
11426 });
11427 if let Some(autoscroll) = autoscroll {
11428 self.request_autoscroll(autoscroll, cx);
11429 }
11430 cx.notify();
11431 }
11432
11433 pub fn row_for_block(
11434 &self,
11435 block_id: CustomBlockId,
11436 cx: &mut ViewContext<Self>,
11437 ) -> Option<DisplayRow> {
11438 self.display_map
11439 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11440 }
11441
11442 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11443 self.focused_block = Some(focused_block);
11444 }
11445
11446 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11447 self.focused_block.take()
11448 }
11449
11450 pub fn insert_creases(
11451 &mut self,
11452 creases: impl IntoIterator<Item = Crease<Anchor>>,
11453 cx: &mut ViewContext<Self>,
11454 ) -> Vec<CreaseId> {
11455 self.display_map
11456 .update(cx, |map, cx| map.insert_creases(creases, cx))
11457 }
11458
11459 pub fn remove_creases(
11460 &mut self,
11461 ids: impl IntoIterator<Item = CreaseId>,
11462 cx: &mut ViewContext<Self>,
11463 ) {
11464 self.display_map
11465 .update(cx, |map, cx| map.remove_creases(ids, cx));
11466 }
11467
11468 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11469 self.display_map
11470 .update(cx, |map, cx| map.snapshot(cx))
11471 .longest_row()
11472 }
11473
11474 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11475 self.display_map
11476 .update(cx, |map, cx| map.snapshot(cx))
11477 .max_point()
11478 }
11479
11480 pub fn text(&self, cx: &AppContext) -> String {
11481 self.buffer.read(cx).read(cx).text()
11482 }
11483
11484 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11485 let text = self.text(cx);
11486 let text = text.trim();
11487
11488 if text.is_empty() {
11489 return None;
11490 }
11491
11492 Some(text.to_string())
11493 }
11494
11495 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11496 self.transact(cx, |this, cx| {
11497 this.buffer
11498 .read(cx)
11499 .as_singleton()
11500 .expect("you can only call set_text on editors for singleton buffers")
11501 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11502 });
11503 }
11504
11505 pub fn display_text(&self, cx: &mut AppContext) -> String {
11506 self.display_map
11507 .update(cx, |map, cx| map.snapshot(cx))
11508 .text()
11509 }
11510
11511 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11512 let mut wrap_guides = smallvec::smallvec![];
11513
11514 if self.show_wrap_guides == Some(false) {
11515 return wrap_guides;
11516 }
11517
11518 let settings = self.buffer.read(cx).settings_at(0, cx);
11519 if settings.show_wrap_guides {
11520 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11521 wrap_guides.push((soft_wrap as usize, true));
11522 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11523 wrap_guides.push((soft_wrap as usize, true));
11524 }
11525 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11526 }
11527
11528 wrap_guides
11529 }
11530
11531 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11532 let settings = self.buffer.read(cx).settings_at(0, cx);
11533 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11534 match mode {
11535 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11536 SoftWrap::None
11537 }
11538 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11539 language_settings::SoftWrap::PreferredLineLength => {
11540 SoftWrap::Column(settings.preferred_line_length)
11541 }
11542 language_settings::SoftWrap::Bounded => {
11543 SoftWrap::Bounded(settings.preferred_line_length)
11544 }
11545 }
11546 }
11547
11548 pub fn set_soft_wrap_mode(
11549 &mut self,
11550 mode: language_settings::SoftWrap,
11551 cx: &mut ViewContext<Self>,
11552 ) {
11553 self.soft_wrap_mode_override = Some(mode);
11554 cx.notify();
11555 }
11556
11557 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11558 self.text_style_refinement = Some(style);
11559 }
11560
11561 /// called by the Element so we know what style we were most recently rendered with.
11562 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11563 let rem_size = cx.rem_size();
11564 self.display_map.update(cx, |map, cx| {
11565 map.set_font(
11566 style.text.font(),
11567 style.text.font_size.to_pixels(rem_size),
11568 cx,
11569 )
11570 });
11571 self.style = Some(style);
11572 }
11573
11574 pub fn style(&self) -> Option<&EditorStyle> {
11575 self.style.as_ref()
11576 }
11577
11578 // Called by the element. This method is not designed to be called outside of the editor
11579 // element's layout code because it does not notify when rewrapping is computed synchronously.
11580 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11581 self.display_map
11582 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11583 }
11584
11585 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11586 if self.soft_wrap_mode_override.is_some() {
11587 self.soft_wrap_mode_override.take();
11588 } else {
11589 let soft_wrap = match self.soft_wrap_mode(cx) {
11590 SoftWrap::GitDiff => return,
11591 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11592 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11593 language_settings::SoftWrap::None
11594 }
11595 };
11596 self.soft_wrap_mode_override = Some(soft_wrap);
11597 }
11598 cx.notify();
11599 }
11600
11601 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11602 let Some(workspace) = self.workspace() else {
11603 return;
11604 };
11605 let fs = workspace.read(cx).app_state().fs.clone();
11606 let current_show = TabBarSettings::get_global(cx).show;
11607 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11608 setting.show = Some(!current_show);
11609 });
11610 }
11611
11612 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11613 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11614 self.buffer
11615 .read(cx)
11616 .settings_at(0, cx)
11617 .indent_guides
11618 .enabled
11619 });
11620 self.show_indent_guides = Some(!currently_enabled);
11621 cx.notify();
11622 }
11623
11624 fn should_show_indent_guides(&self) -> Option<bool> {
11625 self.show_indent_guides
11626 }
11627
11628 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11629 let mut editor_settings = EditorSettings::get_global(cx).clone();
11630 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11631 EditorSettings::override_global(editor_settings, cx);
11632 }
11633
11634 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11635 self.use_relative_line_numbers
11636 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11637 }
11638
11639 pub fn toggle_relative_line_numbers(
11640 &mut self,
11641 _: &ToggleRelativeLineNumbers,
11642 cx: &mut ViewContext<Self>,
11643 ) {
11644 let is_relative = self.should_use_relative_line_numbers(cx);
11645 self.set_relative_line_number(Some(!is_relative), cx)
11646 }
11647
11648 pub fn set_relative_line_number(
11649 &mut self,
11650 is_relative: Option<bool>,
11651 cx: &mut ViewContext<Self>,
11652 ) {
11653 self.use_relative_line_numbers = is_relative;
11654 cx.notify();
11655 }
11656
11657 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11658 self.show_gutter = show_gutter;
11659 cx.notify();
11660 }
11661
11662 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11663 self.show_line_numbers = Some(show_line_numbers);
11664 cx.notify();
11665 }
11666
11667 pub fn set_show_git_diff_gutter(
11668 &mut self,
11669 show_git_diff_gutter: bool,
11670 cx: &mut ViewContext<Self>,
11671 ) {
11672 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11673 cx.notify();
11674 }
11675
11676 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11677 self.show_code_actions = Some(show_code_actions);
11678 cx.notify();
11679 }
11680
11681 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11682 self.show_runnables = Some(show_runnables);
11683 cx.notify();
11684 }
11685
11686 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11687 if self.display_map.read(cx).masked != masked {
11688 self.display_map.update(cx, |map, _| map.masked = masked);
11689 }
11690 cx.notify()
11691 }
11692
11693 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11694 self.show_wrap_guides = Some(show_wrap_guides);
11695 cx.notify();
11696 }
11697
11698 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11699 self.show_indent_guides = Some(show_indent_guides);
11700 cx.notify();
11701 }
11702
11703 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11704 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11705 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11706 if let Some(dir) = file.abs_path(cx).parent() {
11707 return Some(dir.to_owned());
11708 }
11709 }
11710
11711 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11712 return Some(project_path.path.to_path_buf());
11713 }
11714 }
11715
11716 None
11717 }
11718
11719 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11720 self.active_excerpt(cx)?
11721 .1
11722 .read(cx)
11723 .file()
11724 .and_then(|f| f.as_local())
11725 }
11726
11727 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11728 if let Some(target) = self.target_file(cx) {
11729 cx.reveal_path(&target.abs_path(cx));
11730 }
11731 }
11732
11733 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11734 if let Some(file) = self.target_file(cx) {
11735 if let Some(path) = file.abs_path(cx).to_str() {
11736 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11737 }
11738 }
11739 }
11740
11741 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11742 if let Some(file) = self.target_file(cx) {
11743 if let Some(path) = file.path().to_str() {
11744 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11745 }
11746 }
11747 }
11748
11749 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11750 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11751
11752 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11753 self.start_git_blame(true, cx);
11754 }
11755
11756 cx.notify();
11757 }
11758
11759 pub fn toggle_git_blame_inline(
11760 &mut self,
11761 _: &ToggleGitBlameInline,
11762 cx: &mut ViewContext<Self>,
11763 ) {
11764 self.toggle_git_blame_inline_internal(true, cx);
11765 cx.notify();
11766 }
11767
11768 pub fn git_blame_inline_enabled(&self) -> bool {
11769 self.git_blame_inline_enabled
11770 }
11771
11772 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11773 self.show_selection_menu = self
11774 .show_selection_menu
11775 .map(|show_selections_menu| !show_selections_menu)
11776 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11777
11778 cx.notify();
11779 }
11780
11781 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11782 self.show_selection_menu
11783 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11784 }
11785
11786 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11787 if let Some(project) = self.project.as_ref() {
11788 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11789 return;
11790 };
11791
11792 if buffer.read(cx).file().is_none() {
11793 return;
11794 }
11795
11796 let focused = self.focus_handle(cx).contains_focused(cx);
11797
11798 let project = project.clone();
11799 let blame =
11800 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11801 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11802 self.blame = Some(blame);
11803 }
11804 }
11805
11806 fn toggle_git_blame_inline_internal(
11807 &mut self,
11808 user_triggered: bool,
11809 cx: &mut ViewContext<Self>,
11810 ) {
11811 if self.git_blame_inline_enabled {
11812 self.git_blame_inline_enabled = false;
11813 self.show_git_blame_inline = false;
11814 self.show_git_blame_inline_delay_task.take();
11815 } else {
11816 self.git_blame_inline_enabled = true;
11817 self.start_git_blame_inline(user_triggered, cx);
11818 }
11819
11820 cx.notify();
11821 }
11822
11823 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11824 self.start_git_blame(user_triggered, cx);
11825
11826 if ProjectSettings::get_global(cx)
11827 .git
11828 .inline_blame_delay()
11829 .is_some()
11830 {
11831 self.start_inline_blame_timer(cx);
11832 } else {
11833 self.show_git_blame_inline = true
11834 }
11835 }
11836
11837 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11838 self.blame.as_ref()
11839 }
11840
11841 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11842 self.show_git_blame_gutter && self.has_blame_entries(cx)
11843 }
11844
11845 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11846 self.show_git_blame_inline
11847 && self.focus_handle.is_focused(cx)
11848 && !self.newest_selection_head_on_empty_line(cx)
11849 && self.has_blame_entries(cx)
11850 }
11851
11852 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11853 self.blame()
11854 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11855 }
11856
11857 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11858 let cursor_anchor = self.selections.newest_anchor().head();
11859
11860 let snapshot = self.buffer.read(cx).snapshot(cx);
11861 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11862
11863 snapshot.line_len(buffer_row) == 0
11864 }
11865
11866 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11867 let buffer_and_selection = maybe!({
11868 let selection = self.selections.newest::<Point>(cx);
11869 let selection_range = selection.range();
11870
11871 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11872 (buffer, selection_range.start.row..selection_range.end.row)
11873 } else {
11874 let buffer_ranges = self
11875 .buffer()
11876 .read(cx)
11877 .range_to_buffer_ranges(selection_range, cx);
11878
11879 let (buffer, range, _) = if selection.reversed {
11880 buffer_ranges.first()
11881 } else {
11882 buffer_ranges.last()
11883 }?;
11884
11885 let snapshot = buffer.read(cx).snapshot();
11886 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11887 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11888 (buffer.clone(), selection)
11889 };
11890
11891 Some((buffer, selection))
11892 });
11893
11894 let Some((buffer, selection)) = buffer_and_selection else {
11895 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11896 };
11897
11898 let Some(project) = self.project.as_ref() else {
11899 return Task::ready(Err(anyhow!("editor does not have project")));
11900 };
11901
11902 project.update(cx, |project, cx| {
11903 project.get_permalink_to_line(&buffer, selection, cx)
11904 })
11905 }
11906
11907 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11908 let permalink_task = self.get_permalink_to_line(cx);
11909 let workspace = self.workspace();
11910
11911 cx.spawn(|_, mut cx| async move {
11912 match permalink_task.await {
11913 Ok(permalink) => {
11914 cx.update(|cx| {
11915 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11916 })
11917 .ok();
11918 }
11919 Err(err) => {
11920 let message = format!("Failed to copy permalink: {err}");
11921
11922 Err::<(), anyhow::Error>(err).log_err();
11923
11924 if let Some(workspace) = workspace {
11925 workspace
11926 .update(&mut cx, |workspace, cx| {
11927 struct CopyPermalinkToLine;
11928
11929 workspace.show_toast(
11930 Toast::new(
11931 NotificationId::unique::<CopyPermalinkToLine>(),
11932 message,
11933 ),
11934 cx,
11935 )
11936 })
11937 .ok();
11938 }
11939 }
11940 }
11941 })
11942 .detach();
11943 }
11944
11945 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11946 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11947 if let Some(file) = self.target_file(cx) {
11948 if let Some(path) = file.path().to_str() {
11949 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11950 }
11951 }
11952 }
11953
11954 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11955 let permalink_task = self.get_permalink_to_line(cx);
11956 let workspace = self.workspace();
11957
11958 cx.spawn(|_, mut cx| async move {
11959 match permalink_task.await {
11960 Ok(permalink) => {
11961 cx.update(|cx| {
11962 cx.open_url(permalink.as_ref());
11963 })
11964 .ok();
11965 }
11966 Err(err) => {
11967 let message = format!("Failed to open permalink: {err}");
11968
11969 Err::<(), anyhow::Error>(err).log_err();
11970
11971 if let Some(workspace) = workspace {
11972 workspace
11973 .update(&mut cx, |workspace, cx| {
11974 struct OpenPermalinkToLine;
11975
11976 workspace.show_toast(
11977 Toast::new(
11978 NotificationId::unique::<OpenPermalinkToLine>(),
11979 message,
11980 ),
11981 cx,
11982 )
11983 })
11984 .ok();
11985 }
11986 }
11987 }
11988 })
11989 .detach();
11990 }
11991
11992 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11993 /// last highlight added will be used.
11994 ///
11995 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11996 pub fn highlight_rows<T: 'static>(
11997 &mut self,
11998 range: Range<Anchor>,
11999 color: Hsla,
12000 should_autoscroll: bool,
12001 cx: &mut ViewContext<Self>,
12002 ) {
12003 let snapshot = self.buffer().read(cx).snapshot(cx);
12004 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12005 let ix = row_highlights.binary_search_by(|highlight| {
12006 Ordering::Equal
12007 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
12008 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
12009 });
12010
12011 if let Err(mut ix) = ix {
12012 let index = post_inc(&mut self.highlight_order);
12013
12014 // If this range intersects with the preceding highlight, then merge it with
12015 // the preceding highlight. Otherwise insert a new highlight.
12016 let mut merged = false;
12017 if ix > 0 {
12018 let prev_highlight = &mut row_highlights[ix - 1];
12019 if prev_highlight
12020 .range
12021 .end
12022 .cmp(&range.start, &snapshot)
12023 .is_ge()
12024 {
12025 ix -= 1;
12026 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12027 prev_highlight.range.end = range.end;
12028 }
12029 merged = true;
12030 prev_highlight.index = index;
12031 prev_highlight.color = color;
12032 prev_highlight.should_autoscroll = should_autoscroll;
12033 }
12034 }
12035
12036 if !merged {
12037 row_highlights.insert(
12038 ix,
12039 RowHighlight {
12040 range: range.clone(),
12041 index,
12042 color,
12043 should_autoscroll,
12044 },
12045 );
12046 }
12047
12048 // If any of the following highlights intersect with this one, merge them.
12049 while let Some(next_highlight) = row_highlights.get(ix + 1) {
12050 let highlight = &row_highlights[ix];
12051 if next_highlight
12052 .range
12053 .start
12054 .cmp(&highlight.range.end, &snapshot)
12055 .is_le()
12056 {
12057 if next_highlight
12058 .range
12059 .end
12060 .cmp(&highlight.range.end, &snapshot)
12061 .is_gt()
12062 {
12063 row_highlights[ix].range.end = next_highlight.range.end;
12064 }
12065 row_highlights.remove(ix + 1);
12066 } else {
12067 break;
12068 }
12069 }
12070 }
12071 }
12072
12073 /// Remove any highlighted row ranges of the given type that intersect the
12074 /// given ranges.
12075 pub fn remove_highlighted_rows<T: 'static>(
12076 &mut self,
12077 ranges_to_remove: Vec<Range<Anchor>>,
12078 cx: &mut ViewContext<Self>,
12079 ) {
12080 let snapshot = self.buffer().read(cx).snapshot(cx);
12081 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12082 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12083 row_highlights.retain(|highlight| {
12084 while let Some(range_to_remove) = ranges_to_remove.peek() {
12085 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12086 Ordering::Less | Ordering::Equal => {
12087 ranges_to_remove.next();
12088 }
12089 Ordering::Greater => {
12090 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12091 Ordering::Less | Ordering::Equal => {
12092 return false;
12093 }
12094 Ordering::Greater => break,
12095 }
12096 }
12097 }
12098 }
12099
12100 true
12101 })
12102 }
12103
12104 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12105 pub fn clear_row_highlights<T: 'static>(&mut self) {
12106 self.highlighted_rows.remove(&TypeId::of::<T>());
12107 }
12108
12109 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12110 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12111 self.highlighted_rows
12112 .get(&TypeId::of::<T>())
12113 .map_or(&[] as &[_], |vec| vec.as_slice())
12114 .iter()
12115 .map(|highlight| (highlight.range.clone(), highlight.color))
12116 }
12117
12118 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12119 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
12120 /// Allows to ignore certain kinds of highlights.
12121 pub fn highlighted_display_rows(
12122 &mut self,
12123 cx: &mut WindowContext,
12124 ) -> BTreeMap<DisplayRow, Hsla> {
12125 let snapshot = self.snapshot(cx);
12126 let mut used_highlight_orders = HashMap::default();
12127 self.highlighted_rows
12128 .iter()
12129 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12130 .fold(
12131 BTreeMap::<DisplayRow, Hsla>::new(),
12132 |mut unique_rows, highlight| {
12133 let start = highlight.range.start.to_display_point(&snapshot);
12134 let end = highlight.range.end.to_display_point(&snapshot);
12135 let start_row = start.row().0;
12136 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12137 && end.column() == 0
12138 {
12139 end.row().0.saturating_sub(1)
12140 } else {
12141 end.row().0
12142 };
12143 for row in start_row..=end_row {
12144 let used_index =
12145 used_highlight_orders.entry(row).or_insert(highlight.index);
12146 if highlight.index >= *used_index {
12147 *used_index = highlight.index;
12148 unique_rows.insert(DisplayRow(row), highlight.color);
12149 }
12150 }
12151 unique_rows
12152 },
12153 )
12154 }
12155
12156 pub fn highlighted_display_row_for_autoscroll(
12157 &self,
12158 snapshot: &DisplaySnapshot,
12159 ) -> Option<DisplayRow> {
12160 self.highlighted_rows
12161 .values()
12162 .flat_map(|highlighted_rows| highlighted_rows.iter())
12163 .filter_map(|highlight| {
12164 if highlight.should_autoscroll {
12165 Some(highlight.range.start.to_display_point(snapshot).row())
12166 } else {
12167 None
12168 }
12169 })
12170 .min()
12171 }
12172
12173 pub fn set_search_within_ranges(
12174 &mut self,
12175 ranges: &[Range<Anchor>],
12176 cx: &mut ViewContext<Self>,
12177 ) {
12178 self.highlight_background::<SearchWithinRange>(
12179 ranges,
12180 |colors| colors.editor_document_highlight_read_background,
12181 cx,
12182 )
12183 }
12184
12185 pub fn set_breadcrumb_header(&mut self, new_header: String) {
12186 self.breadcrumb_header = Some(new_header);
12187 }
12188
12189 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12190 self.clear_background_highlights::<SearchWithinRange>(cx);
12191 }
12192
12193 pub fn highlight_background<T: 'static>(
12194 &mut self,
12195 ranges: &[Range<Anchor>],
12196 color_fetcher: fn(&ThemeColors) -> Hsla,
12197 cx: &mut ViewContext<Self>,
12198 ) {
12199 self.background_highlights
12200 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12201 self.scrollbar_marker_state.dirty = true;
12202 cx.notify();
12203 }
12204
12205 pub fn clear_background_highlights<T: 'static>(
12206 &mut self,
12207 cx: &mut ViewContext<Self>,
12208 ) -> Option<BackgroundHighlight> {
12209 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12210 if !text_highlights.1.is_empty() {
12211 self.scrollbar_marker_state.dirty = true;
12212 cx.notify();
12213 }
12214 Some(text_highlights)
12215 }
12216
12217 pub fn highlight_gutter<T: 'static>(
12218 &mut self,
12219 ranges: &[Range<Anchor>],
12220 color_fetcher: fn(&AppContext) -> Hsla,
12221 cx: &mut ViewContext<Self>,
12222 ) {
12223 self.gutter_highlights
12224 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12225 cx.notify();
12226 }
12227
12228 pub fn clear_gutter_highlights<T: 'static>(
12229 &mut self,
12230 cx: &mut ViewContext<Self>,
12231 ) -> Option<GutterHighlight> {
12232 cx.notify();
12233 self.gutter_highlights.remove(&TypeId::of::<T>())
12234 }
12235
12236 #[cfg(feature = "test-support")]
12237 pub fn all_text_background_highlights(
12238 &mut self,
12239 cx: &mut ViewContext<Self>,
12240 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12241 let snapshot = self.snapshot(cx);
12242 let buffer = &snapshot.buffer_snapshot;
12243 let start = buffer.anchor_before(0);
12244 let end = buffer.anchor_after(buffer.len());
12245 let theme = cx.theme().colors();
12246 self.background_highlights_in_range(start..end, &snapshot, theme)
12247 }
12248
12249 #[cfg(feature = "test-support")]
12250 pub fn search_background_highlights(
12251 &mut self,
12252 cx: &mut ViewContext<Self>,
12253 ) -> Vec<Range<Point>> {
12254 let snapshot = self.buffer().read(cx).snapshot(cx);
12255
12256 let highlights = self
12257 .background_highlights
12258 .get(&TypeId::of::<items::BufferSearchHighlights>());
12259
12260 if let Some((_color, ranges)) = highlights {
12261 ranges
12262 .iter()
12263 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12264 .collect_vec()
12265 } else {
12266 vec![]
12267 }
12268 }
12269
12270 fn document_highlights_for_position<'a>(
12271 &'a self,
12272 position: Anchor,
12273 buffer: &'a MultiBufferSnapshot,
12274 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12275 let read_highlights = self
12276 .background_highlights
12277 .get(&TypeId::of::<DocumentHighlightRead>())
12278 .map(|h| &h.1);
12279 let write_highlights = self
12280 .background_highlights
12281 .get(&TypeId::of::<DocumentHighlightWrite>())
12282 .map(|h| &h.1);
12283 let left_position = position.bias_left(buffer);
12284 let right_position = position.bias_right(buffer);
12285 read_highlights
12286 .into_iter()
12287 .chain(write_highlights)
12288 .flat_map(move |ranges| {
12289 let start_ix = match ranges.binary_search_by(|probe| {
12290 let cmp = probe.end.cmp(&left_position, buffer);
12291 if cmp.is_ge() {
12292 Ordering::Greater
12293 } else {
12294 Ordering::Less
12295 }
12296 }) {
12297 Ok(i) | Err(i) => i,
12298 };
12299
12300 ranges[start_ix..]
12301 .iter()
12302 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12303 })
12304 }
12305
12306 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12307 self.background_highlights
12308 .get(&TypeId::of::<T>())
12309 .map_or(false, |(_, highlights)| !highlights.is_empty())
12310 }
12311
12312 pub fn background_highlights_in_range(
12313 &self,
12314 search_range: Range<Anchor>,
12315 display_snapshot: &DisplaySnapshot,
12316 theme: &ThemeColors,
12317 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12318 let mut results = Vec::new();
12319 for (color_fetcher, ranges) in self.background_highlights.values() {
12320 let color = color_fetcher(theme);
12321 let start_ix = match ranges.binary_search_by(|probe| {
12322 let cmp = probe
12323 .end
12324 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12325 if cmp.is_gt() {
12326 Ordering::Greater
12327 } else {
12328 Ordering::Less
12329 }
12330 }) {
12331 Ok(i) | Err(i) => i,
12332 };
12333 for range in &ranges[start_ix..] {
12334 if range
12335 .start
12336 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12337 .is_ge()
12338 {
12339 break;
12340 }
12341
12342 let start = range.start.to_display_point(display_snapshot);
12343 let end = range.end.to_display_point(display_snapshot);
12344 results.push((start..end, color))
12345 }
12346 }
12347 results
12348 }
12349
12350 pub fn background_highlight_row_ranges<T: 'static>(
12351 &self,
12352 search_range: Range<Anchor>,
12353 display_snapshot: &DisplaySnapshot,
12354 count: usize,
12355 ) -> Vec<RangeInclusive<DisplayPoint>> {
12356 let mut results = Vec::new();
12357 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12358 return vec![];
12359 };
12360
12361 let start_ix = match ranges.binary_search_by(|probe| {
12362 let cmp = probe
12363 .end
12364 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12365 if cmp.is_gt() {
12366 Ordering::Greater
12367 } else {
12368 Ordering::Less
12369 }
12370 }) {
12371 Ok(i) | Err(i) => i,
12372 };
12373 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12374 if let (Some(start_display), Some(end_display)) = (start, end) {
12375 results.push(
12376 start_display.to_display_point(display_snapshot)
12377 ..=end_display.to_display_point(display_snapshot),
12378 );
12379 }
12380 };
12381 let mut start_row: Option<Point> = None;
12382 let mut end_row: Option<Point> = None;
12383 if ranges.len() > count {
12384 return Vec::new();
12385 }
12386 for range in &ranges[start_ix..] {
12387 if range
12388 .start
12389 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12390 .is_ge()
12391 {
12392 break;
12393 }
12394 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12395 if let Some(current_row) = &end_row {
12396 if end.row == current_row.row {
12397 continue;
12398 }
12399 }
12400 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12401 if start_row.is_none() {
12402 assert_eq!(end_row, None);
12403 start_row = Some(start);
12404 end_row = Some(end);
12405 continue;
12406 }
12407 if let Some(current_end) = end_row.as_mut() {
12408 if start.row > current_end.row + 1 {
12409 push_region(start_row, end_row);
12410 start_row = Some(start);
12411 end_row = Some(end);
12412 } else {
12413 // Merge two hunks.
12414 *current_end = end;
12415 }
12416 } else {
12417 unreachable!();
12418 }
12419 }
12420 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12421 push_region(start_row, end_row);
12422 results
12423 }
12424
12425 pub fn gutter_highlights_in_range(
12426 &self,
12427 search_range: Range<Anchor>,
12428 display_snapshot: &DisplaySnapshot,
12429 cx: &AppContext,
12430 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12431 let mut results = Vec::new();
12432 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12433 let color = color_fetcher(cx);
12434 let start_ix = match ranges.binary_search_by(|probe| {
12435 let cmp = probe
12436 .end
12437 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12438 if cmp.is_gt() {
12439 Ordering::Greater
12440 } else {
12441 Ordering::Less
12442 }
12443 }) {
12444 Ok(i) | Err(i) => i,
12445 };
12446 for range in &ranges[start_ix..] {
12447 if range
12448 .start
12449 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12450 .is_ge()
12451 {
12452 break;
12453 }
12454
12455 let start = range.start.to_display_point(display_snapshot);
12456 let end = range.end.to_display_point(display_snapshot);
12457 results.push((start..end, color))
12458 }
12459 }
12460 results
12461 }
12462
12463 /// Get the text ranges corresponding to the redaction query
12464 pub fn redacted_ranges(
12465 &self,
12466 search_range: Range<Anchor>,
12467 display_snapshot: &DisplaySnapshot,
12468 cx: &WindowContext,
12469 ) -> Vec<Range<DisplayPoint>> {
12470 display_snapshot
12471 .buffer_snapshot
12472 .redacted_ranges(search_range, |file| {
12473 if let Some(file) = file {
12474 file.is_private()
12475 && EditorSettings::get(
12476 Some(SettingsLocation {
12477 worktree_id: file.worktree_id(cx),
12478 path: file.path().as_ref(),
12479 }),
12480 cx,
12481 )
12482 .redact_private_values
12483 } else {
12484 false
12485 }
12486 })
12487 .map(|range| {
12488 range.start.to_display_point(display_snapshot)
12489 ..range.end.to_display_point(display_snapshot)
12490 })
12491 .collect()
12492 }
12493
12494 pub fn highlight_text<T: 'static>(
12495 &mut self,
12496 ranges: Vec<Range<Anchor>>,
12497 style: HighlightStyle,
12498 cx: &mut ViewContext<Self>,
12499 ) {
12500 self.display_map.update(cx, |map, _| {
12501 map.highlight_text(TypeId::of::<T>(), ranges, style)
12502 });
12503 cx.notify();
12504 }
12505
12506 pub(crate) fn highlight_inlays<T: 'static>(
12507 &mut self,
12508 highlights: Vec<InlayHighlight>,
12509 style: HighlightStyle,
12510 cx: &mut ViewContext<Self>,
12511 ) {
12512 self.display_map.update(cx, |map, _| {
12513 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12514 });
12515 cx.notify();
12516 }
12517
12518 pub fn text_highlights<'a, T: 'static>(
12519 &'a self,
12520 cx: &'a AppContext,
12521 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12522 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12523 }
12524
12525 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12526 let cleared = self
12527 .display_map
12528 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12529 if cleared {
12530 cx.notify();
12531 }
12532 }
12533
12534 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12535 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12536 && self.focus_handle.is_focused(cx)
12537 }
12538
12539 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12540 self.show_cursor_when_unfocused = is_enabled;
12541 cx.notify();
12542 }
12543
12544 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12545 cx.notify();
12546 }
12547
12548 fn on_buffer_event(
12549 &mut self,
12550 multibuffer: Model<MultiBuffer>,
12551 event: &multi_buffer::Event,
12552 cx: &mut ViewContext<Self>,
12553 ) {
12554 match event {
12555 multi_buffer::Event::Edited {
12556 singleton_buffer_edited,
12557 } => {
12558 self.scrollbar_marker_state.dirty = true;
12559 self.active_indent_guides_state.dirty = true;
12560 self.refresh_active_diagnostics(cx);
12561 self.refresh_code_actions(cx);
12562 if self.has_active_inline_completion(cx) {
12563 self.update_visible_inline_completion(cx);
12564 }
12565 cx.emit(EditorEvent::BufferEdited);
12566 cx.emit(SearchEvent::MatchesInvalidated);
12567 if *singleton_buffer_edited {
12568 if let Some(project) = &self.project {
12569 let project = project.read(cx);
12570 #[allow(clippy::mutable_key_type)]
12571 let languages_affected = multibuffer
12572 .read(cx)
12573 .all_buffers()
12574 .into_iter()
12575 .filter_map(|buffer| {
12576 let buffer = buffer.read(cx);
12577 let language = buffer.language()?;
12578 if project.is_local()
12579 && project.language_servers_for_buffer(buffer, cx).count() == 0
12580 {
12581 None
12582 } else {
12583 Some(language)
12584 }
12585 })
12586 .cloned()
12587 .collect::<HashSet<_>>();
12588 if !languages_affected.is_empty() {
12589 self.refresh_inlay_hints(
12590 InlayHintRefreshReason::BufferEdited(languages_affected),
12591 cx,
12592 );
12593 }
12594 }
12595 }
12596
12597 let Some(project) = &self.project else { return };
12598 let (telemetry, is_via_ssh) = {
12599 let project = project.read(cx);
12600 let telemetry = project.client().telemetry().clone();
12601 let is_via_ssh = project.is_via_ssh();
12602 (telemetry, is_via_ssh)
12603 };
12604 refresh_linked_ranges(self, cx);
12605 telemetry.log_edit_event("editor", is_via_ssh);
12606 }
12607 multi_buffer::Event::ExcerptsAdded {
12608 buffer,
12609 predecessor,
12610 excerpts,
12611 } => {
12612 self.tasks_update_task = Some(self.refresh_runnables(cx));
12613 cx.emit(EditorEvent::ExcerptsAdded {
12614 buffer: buffer.clone(),
12615 predecessor: *predecessor,
12616 excerpts: excerpts.clone(),
12617 });
12618 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12619 }
12620 multi_buffer::Event::ExcerptsRemoved { ids } => {
12621 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12622 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12623 }
12624 multi_buffer::Event::ExcerptsEdited { ids } => {
12625 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12626 }
12627 multi_buffer::Event::ExcerptsExpanded { ids } => {
12628 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12629 }
12630 multi_buffer::Event::Reparsed(buffer_id) => {
12631 self.tasks_update_task = Some(self.refresh_runnables(cx));
12632
12633 cx.emit(EditorEvent::Reparsed(*buffer_id));
12634 }
12635 multi_buffer::Event::LanguageChanged(buffer_id) => {
12636 linked_editing_ranges::refresh_linked_ranges(self, cx);
12637 cx.emit(EditorEvent::Reparsed(*buffer_id));
12638 cx.notify();
12639 }
12640 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12641 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12642 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12643 cx.emit(EditorEvent::TitleChanged)
12644 }
12645 multi_buffer::Event::DiffBaseChanged => {
12646 self.scrollbar_marker_state.dirty = true;
12647 cx.emit(EditorEvent::DiffBaseChanged);
12648 cx.notify();
12649 }
12650 multi_buffer::Event::DiffUpdated { buffer } => {
12651 self.sync_expanded_diff_hunks(buffer.clone(), cx);
12652 cx.notify();
12653 }
12654 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12655 multi_buffer::Event::DiagnosticsUpdated => {
12656 self.refresh_active_diagnostics(cx);
12657 self.scrollbar_marker_state.dirty = true;
12658 cx.notify();
12659 }
12660 _ => {}
12661 };
12662 }
12663
12664 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12665 cx.notify();
12666 }
12667
12668 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12669 self.tasks_update_task = Some(self.refresh_runnables(cx));
12670 self.refresh_inline_completion(true, false, cx);
12671 self.refresh_inlay_hints(
12672 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12673 self.selections.newest_anchor().head(),
12674 &self.buffer.read(cx).snapshot(cx),
12675 cx,
12676 )),
12677 cx,
12678 );
12679
12680 let old_cursor_shape = self.cursor_shape;
12681
12682 {
12683 let editor_settings = EditorSettings::get_global(cx);
12684 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12685 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12686 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12687 }
12688
12689 if old_cursor_shape != self.cursor_shape {
12690 cx.emit(EditorEvent::CursorShapeChanged);
12691 }
12692
12693 let project_settings = ProjectSettings::get_global(cx);
12694 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12695
12696 if self.mode == EditorMode::Full {
12697 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12698 if self.git_blame_inline_enabled != inline_blame_enabled {
12699 self.toggle_git_blame_inline_internal(false, cx);
12700 }
12701 }
12702
12703 cx.notify();
12704 }
12705
12706 pub fn set_searchable(&mut self, searchable: bool) {
12707 self.searchable = searchable;
12708 }
12709
12710 pub fn searchable(&self) -> bool {
12711 self.searchable
12712 }
12713
12714 fn open_proposed_changes_editor(
12715 &mut self,
12716 _: &OpenProposedChangesEditor,
12717 cx: &mut ViewContext<Self>,
12718 ) {
12719 let Some(workspace) = self.workspace() else {
12720 cx.propagate();
12721 return;
12722 };
12723
12724 let selections = self.selections.all::<usize>(cx);
12725 let buffer = self.buffer.read(cx);
12726 let mut new_selections_by_buffer = HashMap::default();
12727 for selection in selections {
12728 for (buffer, range, _) in
12729 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12730 {
12731 let mut range = range.to_point(buffer.read(cx));
12732 range.start.column = 0;
12733 range.end.column = buffer.read(cx).line_len(range.end.row);
12734 new_selections_by_buffer
12735 .entry(buffer)
12736 .or_insert(Vec::new())
12737 .push(range)
12738 }
12739 }
12740
12741 let proposed_changes_buffers = new_selections_by_buffer
12742 .into_iter()
12743 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12744 .collect::<Vec<_>>();
12745 let proposed_changes_editor = cx.new_view(|cx| {
12746 ProposedChangesEditor::new(
12747 "Proposed changes",
12748 proposed_changes_buffers,
12749 self.project.clone(),
12750 cx,
12751 )
12752 });
12753
12754 cx.window_context().defer(move |cx| {
12755 workspace.update(cx, |workspace, cx| {
12756 workspace.active_pane().update(cx, |pane, cx| {
12757 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12758 });
12759 });
12760 });
12761 }
12762
12763 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12764 self.open_excerpts_common(None, true, cx)
12765 }
12766
12767 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12768 self.open_excerpts_common(None, false, cx)
12769 }
12770
12771 fn open_excerpts_common(
12772 &mut self,
12773 jump_data: Option<JumpData>,
12774 split: bool,
12775 cx: &mut ViewContext<Self>,
12776 ) {
12777 let Some(workspace) = self.workspace() else {
12778 cx.propagate();
12779 return;
12780 };
12781
12782 if self.buffer.read(cx).is_singleton() {
12783 cx.propagate();
12784 return;
12785 }
12786
12787 let mut new_selections_by_buffer = HashMap::default();
12788 match &jump_data {
12789 Some(jump_data) => {
12790 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12791 if let Some(buffer) = multi_buffer_snapshot
12792 .buffer_id_for_excerpt(jump_data.excerpt_id)
12793 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12794 {
12795 let buffer_snapshot = buffer.read(cx).snapshot();
12796 let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12797 language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12798 } else {
12799 buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12800 };
12801 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12802 new_selections_by_buffer.insert(
12803 buffer,
12804 (
12805 vec![jump_to_offset..jump_to_offset],
12806 Some(jump_data.line_offset_from_top),
12807 ),
12808 );
12809 }
12810 }
12811 None => {
12812 let selections = self.selections.all::<usize>(cx);
12813 let buffer = self.buffer.read(cx);
12814 for selection in selections {
12815 for (mut buffer_handle, mut range, _) in
12816 buffer.range_to_buffer_ranges(selection.range(), cx)
12817 {
12818 // When editing branch buffers, jump to the corresponding location
12819 // in their base buffer.
12820 let buffer = buffer_handle.read(cx);
12821 if let Some(base_buffer) = buffer.diff_base_buffer() {
12822 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12823 buffer_handle = base_buffer;
12824 }
12825
12826 if selection.reversed {
12827 mem::swap(&mut range.start, &mut range.end);
12828 }
12829 new_selections_by_buffer
12830 .entry(buffer_handle)
12831 .or_insert((Vec::new(), None))
12832 .0
12833 .push(range)
12834 }
12835 }
12836 }
12837 }
12838
12839 if new_selections_by_buffer.is_empty() {
12840 return;
12841 }
12842
12843 // We defer the pane interaction because we ourselves are a workspace item
12844 // and activating a new item causes the pane to call a method on us reentrantly,
12845 // which panics if we're on the stack.
12846 cx.window_context().defer(move |cx| {
12847 workspace.update(cx, |workspace, cx| {
12848 let pane = if split {
12849 workspace.adjacent_pane(cx)
12850 } else {
12851 workspace.active_pane().clone()
12852 };
12853
12854 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12855 let editor =
12856 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12857 editor.update(cx, |editor, cx| {
12858 let autoscroll = match scroll_offset {
12859 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12860 None => Autoscroll::newest(),
12861 };
12862 let nav_history = editor.nav_history.take();
12863 editor.change_selections(Some(autoscroll), cx, |s| {
12864 s.select_ranges(ranges);
12865 });
12866 editor.nav_history = nav_history;
12867 });
12868 }
12869 })
12870 });
12871 }
12872
12873 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12874 let snapshot = self.buffer.read(cx).read(cx);
12875 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12876 Some(
12877 ranges
12878 .iter()
12879 .map(move |range| {
12880 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12881 })
12882 .collect(),
12883 )
12884 }
12885
12886 fn selection_replacement_ranges(
12887 &self,
12888 range: Range<OffsetUtf16>,
12889 cx: &mut AppContext,
12890 ) -> Vec<Range<OffsetUtf16>> {
12891 let selections = self.selections.all::<OffsetUtf16>(cx);
12892 let newest_selection = selections
12893 .iter()
12894 .max_by_key(|selection| selection.id)
12895 .unwrap();
12896 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12897 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12898 let snapshot = self.buffer.read(cx).read(cx);
12899 selections
12900 .into_iter()
12901 .map(|mut selection| {
12902 selection.start.0 =
12903 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12904 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12905 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12906 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12907 })
12908 .collect()
12909 }
12910
12911 fn report_editor_event(
12912 &self,
12913 operation: &'static str,
12914 file_extension: Option<String>,
12915 cx: &AppContext,
12916 ) {
12917 if cfg!(any(test, feature = "test-support")) {
12918 return;
12919 }
12920
12921 let Some(project) = &self.project else { return };
12922
12923 // If None, we are in a file without an extension
12924 let file = self
12925 .buffer
12926 .read(cx)
12927 .as_singleton()
12928 .and_then(|b| b.read(cx).file());
12929 let file_extension = file_extension.or(file
12930 .as_ref()
12931 .and_then(|file| Path::new(file.file_name(cx)).extension())
12932 .and_then(|e| e.to_str())
12933 .map(|a| a.to_string()));
12934
12935 let vim_mode = cx
12936 .global::<SettingsStore>()
12937 .raw_user_settings()
12938 .get("vim_mode")
12939 == Some(&serde_json::Value::Bool(true));
12940
12941 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12942 == language::language_settings::InlineCompletionProvider::Copilot;
12943 let copilot_enabled_for_language = self
12944 .buffer
12945 .read(cx)
12946 .settings_at(0, cx)
12947 .show_inline_completions;
12948
12949 let project = project.read(cx);
12950 let telemetry = project.client().telemetry().clone();
12951 telemetry.report_editor_event(
12952 file_extension,
12953 vim_mode,
12954 operation,
12955 copilot_enabled,
12956 copilot_enabled_for_language,
12957 project.is_via_ssh(),
12958 )
12959 }
12960
12961 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12962 /// with each line being an array of {text, highlight} objects.
12963 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12964 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12965 return;
12966 };
12967
12968 #[derive(Serialize)]
12969 struct Chunk<'a> {
12970 text: String,
12971 highlight: Option<&'a str>,
12972 }
12973
12974 let snapshot = buffer.read(cx).snapshot();
12975 let range = self
12976 .selected_text_range(false, cx)
12977 .and_then(|selection| {
12978 if selection.range.is_empty() {
12979 None
12980 } else {
12981 Some(selection.range)
12982 }
12983 })
12984 .unwrap_or_else(|| 0..snapshot.len());
12985
12986 let chunks = snapshot.chunks(range, true);
12987 let mut lines = Vec::new();
12988 let mut line: VecDeque<Chunk> = VecDeque::new();
12989
12990 let Some(style) = self.style.as_ref() else {
12991 return;
12992 };
12993
12994 for chunk in chunks {
12995 let highlight = chunk
12996 .syntax_highlight_id
12997 .and_then(|id| id.name(&style.syntax));
12998 let mut chunk_lines = chunk.text.split('\n').peekable();
12999 while let Some(text) = chunk_lines.next() {
13000 let mut merged_with_last_token = false;
13001 if let Some(last_token) = line.back_mut() {
13002 if last_token.highlight == highlight {
13003 last_token.text.push_str(text);
13004 merged_with_last_token = true;
13005 }
13006 }
13007
13008 if !merged_with_last_token {
13009 line.push_back(Chunk {
13010 text: text.into(),
13011 highlight,
13012 });
13013 }
13014
13015 if chunk_lines.peek().is_some() {
13016 if line.len() > 1 && line.front().unwrap().text.is_empty() {
13017 line.pop_front();
13018 }
13019 if line.len() > 1 && line.back().unwrap().text.is_empty() {
13020 line.pop_back();
13021 }
13022
13023 lines.push(mem::take(&mut line));
13024 }
13025 }
13026 }
13027
13028 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13029 return;
13030 };
13031 cx.write_to_clipboard(ClipboardItem::new_string(lines));
13032 }
13033
13034 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13035 &self.inlay_hint_cache
13036 }
13037
13038 pub fn replay_insert_event(
13039 &mut self,
13040 text: &str,
13041 relative_utf16_range: Option<Range<isize>>,
13042 cx: &mut ViewContext<Self>,
13043 ) {
13044 if !self.input_enabled {
13045 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13046 return;
13047 }
13048 if let Some(relative_utf16_range) = relative_utf16_range {
13049 let selections = self.selections.all::<OffsetUtf16>(cx);
13050 self.change_selections(None, cx, |s| {
13051 let new_ranges = selections.into_iter().map(|range| {
13052 let start = OffsetUtf16(
13053 range
13054 .head()
13055 .0
13056 .saturating_add_signed(relative_utf16_range.start),
13057 );
13058 let end = OffsetUtf16(
13059 range
13060 .head()
13061 .0
13062 .saturating_add_signed(relative_utf16_range.end),
13063 );
13064 start..end
13065 });
13066 s.select_ranges(new_ranges);
13067 });
13068 }
13069
13070 self.handle_input(text, cx);
13071 }
13072
13073 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
13074 let Some(provider) = self.semantics_provider.as_ref() else {
13075 return false;
13076 };
13077
13078 let mut supports = false;
13079 self.buffer().read(cx).for_each_buffer(|buffer| {
13080 supports |= provider.supports_inlay_hints(buffer, cx);
13081 });
13082 supports
13083 }
13084
13085 pub fn focus(&self, cx: &mut WindowContext) {
13086 cx.focus(&self.focus_handle)
13087 }
13088
13089 pub fn is_focused(&self, cx: &WindowContext) -> bool {
13090 self.focus_handle.is_focused(cx)
13091 }
13092
13093 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13094 cx.emit(EditorEvent::Focused);
13095
13096 if let Some(descendant) = self
13097 .last_focused_descendant
13098 .take()
13099 .and_then(|descendant| descendant.upgrade())
13100 {
13101 cx.focus(&descendant);
13102 } else {
13103 if let Some(blame) = self.blame.as_ref() {
13104 blame.update(cx, GitBlame::focus)
13105 }
13106
13107 self.blink_manager.update(cx, BlinkManager::enable);
13108 self.show_cursor_names(cx);
13109 self.buffer.update(cx, |buffer, cx| {
13110 buffer.finalize_last_transaction(cx);
13111 if self.leader_peer_id.is_none() {
13112 buffer.set_active_selections(
13113 &self.selections.disjoint_anchors(),
13114 self.selections.line_mode,
13115 self.cursor_shape,
13116 cx,
13117 );
13118 }
13119 });
13120 }
13121 }
13122
13123 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13124 cx.emit(EditorEvent::FocusedIn)
13125 }
13126
13127 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13128 if event.blurred != self.focus_handle {
13129 self.last_focused_descendant = Some(event.blurred);
13130 }
13131 }
13132
13133 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13134 self.blink_manager.update(cx, BlinkManager::disable);
13135 self.buffer
13136 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13137
13138 if let Some(blame) = self.blame.as_ref() {
13139 blame.update(cx, GitBlame::blur)
13140 }
13141 if !self.hover_state.focused(cx) {
13142 hide_hover(self, cx);
13143 }
13144
13145 self.hide_context_menu(cx);
13146 cx.emit(EditorEvent::Blurred);
13147 cx.notify();
13148 }
13149
13150 pub fn register_action<A: Action>(
13151 &mut self,
13152 listener: impl Fn(&A, &mut WindowContext) + 'static,
13153 ) -> Subscription {
13154 let id = self.next_editor_action_id.post_inc();
13155 let listener = Arc::new(listener);
13156 self.editor_actions.borrow_mut().insert(
13157 id,
13158 Box::new(move |cx| {
13159 let cx = cx.window_context();
13160 let listener = listener.clone();
13161 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13162 let action = action.downcast_ref().unwrap();
13163 if phase == DispatchPhase::Bubble {
13164 listener(action, cx)
13165 }
13166 })
13167 }),
13168 );
13169
13170 let editor_actions = self.editor_actions.clone();
13171 Subscription::new(move || {
13172 editor_actions.borrow_mut().remove(&id);
13173 })
13174 }
13175
13176 pub fn file_header_size(&self) -> u32 {
13177 FILE_HEADER_HEIGHT
13178 }
13179
13180 pub fn revert(
13181 &mut self,
13182 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13183 cx: &mut ViewContext<Self>,
13184 ) {
13185 self.buffer().update(cx, |multi_buffer, cx| {
13186 for (buffer_id, changes) in revert_changes {
13187 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13188 buffer.update(cx, |buffer, cx| {
13189 buffer.edit(
13190 changes.into_iter().map(|(range, text)| {
13191 (range, text.to_string().map(Arc::<str>::from))
13192 }),
13193 None,
13194 cx,
13195 );
13196 });
13197 }
13198 }
13199 });
13200 self.change_selections(None, cx, |selections| selections.refresh());
13201 }
13202
13203 pub fn to_pixel_point(
13204 &mut self,
13205 source: multi_buffer::Anchor,
13206 editor_snapshot: &EditorSnapshot,
13207 cx: &mut ViewContext<Self>,
13208 ) -> Option<gpui::Point<Pixels>> {
13209 let source_point = source.to_display_point(editor_snapshot);
13210 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13211 }
13212
13213 pub fn display_to_pixel_point(
13214 &mut self,
13215 source: DisplayPoint,
13216 editor_snapshot: &EditorSnapshot,
13217 cx: &mut ViewContext<Self>,
13218 ) -> Option<gpui::Point<Pixels>> {
13219 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13220 let text_layout_details = self.text_layout_details(cx);
13221 let scroll_top = text_layout_details
13222 .scroll_anchor
13223 .scroll_position(editor_snapshot)
13224 .y;
13225
13226 if source.row().as_f32() < scroll_top.floor() {
13227 return None;
13228 }
13229 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13230 let source_y = line_height * (source.row().as_f32() - scroll_top);
13231 Some(gpui::Point::new(source_x, source_y))
13232 }
13233
13234 pub fn has_active_completions_menu(&self) -> bool {
13235 self.context_menu.read().as_ref().map_or(false, |menu| {
13236 menu.visible() && matches!(menu, ContextMenu::Completions(_))
13237 })
13238 }
13239
13240 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13241 self.addons
13242 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13243 }
13244
13245 pub fn unregister_addon<T: Addon>(&mut self) {
13246 self.addons.remove(&std::any::TypeId::of::<T>());
13247 }
13248
13249 pub fn addon<T: Addon>(&self) -> Option<&T> {
13250 let type_id = std::any::TypeId::of::<T>();
13251 self.addons
13252 .get(&type_id)
13253 .and_then(|item| item.to_any().downcast_ref::<T>())
13254 }
13255}
13256
13257fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13258 let tab_size = tab_size.get() as usize;
13259 let mut width = offset;
13260
13261 for ch in text.chars() {
13262 width += if ch == '\t' {
13263 tab_size - (width % tab_size)
13264 } else {
13265 1
13266 };
13267 }
13268
13269 width - offset
13270}
13271
13272#[cfg(test)]
13273mod tests {
13274 use super::*;
13275
13276 #[test]
13277 fn test_string_size_with_expanded_tabs() {
13278 let nz = |val| NonZeroU32::new(val).unwrap();
13279 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13280 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13281 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13282 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13283 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13284 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13285 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13286 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13287 }
13288}
13289
13290/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13291struct WordBreakingTokenizer<'a> {
13292 input: &'a str,
13293}
13294
13295impl<'a> WordBreakingTokenizer<'a> {
13296 fn new(input: &'a str) -> Self {
13297 Self { input }
13298 }
13299}
13300
13301fn is_char_ideographic(ch: char) -> bool {
13302 use unicode_script::Script::*;
13303 use unicode_script::UnicodeScript;
13304 matches!(ch.script(), Han | Tangut | Yi)
13305}
13306
13307fn is_grapheme_ideographic(text: &str) -> bool {
13308 text.chars().any(is_char_ideographic)
13309}
13310
13311fn is_grapheme_whitespace(text: &str) -> bool {
13312 text.chars().any(|x| x.is_whitespace())
13313}
13314
13315fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13316 text.chars().next().map_or(false, |ch| {
13317 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13318 })
13319}
13320
13321#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13322struct WordBreakToken<'a> {
13323 token: &'a str,
13324 grapheme_len: usize,
13325 is_whitespace: bool,
13326}
13327
13328impl<'a> Iterator for WordBreakingTokenizer<'a> {
13329 /// Yields a span, the count of graphemes in the token, and whether it was
13330 /// whitespace. Note that it also breaks at word boundaries.
13331 type Item = WordBreakToken<'a>;
13332
13333 fn next(&mut self) -> Option<Self::Item> {
13334 use unicode_segmentation::UnicodeSegmentation;
13335 if self.input.is_empty() {
13336 return None;
13337 }
13338
13339 let mut iter = self.input.graphemes(true).peekable();
13340 let mut offset = 0;
13341 let mut graphemes = 0;
13342 if let Some(first_grapheme) = iter.next() {
13343 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13344 offset += first_grapheme.len();
13345 graphemes += 1;
13346 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13347 if let Some(grapheme) = iter.peek().copied() {
13348 if should_stay_with_preceding_ideograph(grapheme) {
13349 offset += grapheme.len();
13350 graphemes += 1;
13351 }
13352 }
13353 } else {
13354 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13355 let mut next_word_bound = words.peek().copied();
13356 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13357 next_word_bound = words.next();
13358 }
13359 while let Some(grapheme) = iter.peek().copied() {
13360 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13361 break;
13362 };
13363 if is_grapheme_whitespace(grapheme) != is_whitespace {
13364 break;
13365 };
13366 offset += grapheme.len();
13367 graphemes += 1;
13368 iter.next();
13369 }
13370 }
13371 let token = &self.input[..offset];
13372 self.input = &self.input[offset..];
13373 if is_whitespace {
13374 Some(WordBreakToken {
13375 token: " ",
13376 grapheme_len: 1,
13377 is_whitespace: true,
13378 })
13379 } else {
13380 Some(WordBreakToken {
13381 token,
13382 grapheme_len: graphemes,
13383 is_whitespace: false,
13384 })
13385 }
13386 } else {
13387 None
13388 }
13389 }
13390}
13391
13392#[test]
13393fn test_word_breaking_tokenizer() {
13394 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13395 ("", &[]),
13396 (" ", &[(" ", 1, true)]),
13397 ("Ʒ", &[("Ʒ", 1, false)]),
13398 ("Ǽ", &[("Ǽ", 1, false)]),
13399 ("⋑", &[("⋑", 1, false)]),
13400 ("⋑⋑", &[("⋑⋑", 2, false)]),
13401 (
13402 "原理,进而",
13403 &[
13404 ("原", 1, false),
13405 ("理,", 2, false),
13406 ("进", 1, false),
13407 ("而", 1, false),
13408 ],
13409 ),
13410 (
13411 "hello world",
13412 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13413 ),
13414 (
13415 "hello, world",
13416 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13417 ),
13418 (
13419 " hello world",
13420 &[
13421 (" ", 1, true),
13422 ("hello", 5, false),
13423 (" ", 1, true),
13424 ("world", 5, false),
13425 ],
13426 ),
13427 (
13428 "这是什么 \n 钢笔",
13429 &[
13430 ("这", 1, false),
13431 ("是", 1, false),
13432 ("什", 1, false),
13433 ("么", 1, false),
13434 (" ", 1, true),
13435 ("钢", 1, false),
13436 ("笔", 1, false),
13437 ],
13438 ),
13439 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13440 ];
13441
13442 for (input, result) in tests {
13443 assert_eq!(
13444 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13445 result
13446 .iter()
13447 .copied()
13448 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13449 token,
13450 grapheme_len,
13451 is_whitespace,
13452 })
13453 .collect::<Vec<_>>()
13454 );
13455 }
13456}
13457
13458fn wrap_with_prefix(
13459 line_prefix: String,
13460 unwrapped_text: String,
13461 wrap_column: usize,
13462 tab_size: NonZeroU32,
13463) -> String {
13464 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13465 let mut wrapped_text = String::new();
13466 let mut current_line = line_prefix.clone();
13467
13468 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13469 let mut current_line_len = line_prefix_len;
13470 for WordBreakToken {
13471 token,
13472 grapheme_len,
13473 is_whitespace,
13474 } in tokenizer
13475 {
13476 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13477 wrapped_text.push_str(current_line.trim_end());
13478 wrapped_text.push('\n');
13479 current_line.truncate(line_prefix.len());
13480 current_line_len = line_prefix_len;
13481 if !is_whitespace {
13482 current_line.push_str(token);
13483 current_line_len += grapheme_len;
13484 }
13485 } else if !is_whitespace {
13486 current_line.push_str(token);
13487 current_line_len += grapheme_len;
13488 } else if current_line_len != line_prefix_len {
13489 current_line.push(' ');
13490 current_line_len += 1;
13491 }
13492 }
13493
13494 if !current_line.is_empty() {
13495 wrapped_text.push_str(¤t_line);
13496 }
13497 wrapped_text
13498}
13499
13500#[test]
13501fn test_wrap_with_prefix() {
13502 assert_eq!(
13503 wrap_with_prefix(
13504 "# ".to_string(),
13505 "abcdefg".to_string(),
13506 4,
13507 NonZeroU32::new(4).unwrap()
13508 ),
13509 "# abcdefg"
13510 );
13511 assert_eq!(
13512 wrap_with_prefix(
13513 "".to_string(),
13514 "\thello world".to_string(),
13515 8,
13516 NonZeroU32::new(4).unwrap()
13517 ),
13518 "hello\nworld"
13519 );
13520 assert_eq!(
13521 wrap_with_prefix(
13522 "// ".to_string(),
13523 "xx \nyy zz aa bb cc".to_string(),
13524 12,
13525 NonZeroU32::new(4).unwrap()
13526 ),
13527 "// xx yy zz\n// aa bb cc"
13528 );
13529 assert_eq!(
13530 wrap_with_prefix(
13531 String::new(),
13532 "这是什么 \n 钢笔".to_string(),
13533 3,
13534 NonZeroU32::new(4).unwrap()
13535 ),
13536 "这是什\n么 钢\n笔"
13537 );
13538}
13539
13540fn hunks_for_selections(
13541 multi_buffer_snapshot: &MultiBufferSnapshot,
13542 selections: &[Selection<Anchor>],
13543) -> Vec<MultiBufferDiffHunk> {
13544 let buffer_rows_for_selections = selections.iter().map(|selection| {
13545 let head = selection.head();
13546 let tail = selection.tail();
13547 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13548 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13549 if start > end {
13550 end..start
13551 } else {
13552 start..end
13553 }
13554 });
13555
13556 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13557}
13558
13559pub fn hunks_for_rows(
13560 rows: impl Iterator<Item = Range<MultiBufferRow>>,
13561 multi_buffer_snapshot: &MultiBufferSnapshot,
13562) -> Vec<MultiBufferDiffHunk> {
13563 let mut hunks = Vec::new();
13564 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13565 HashMap::default();
13566 for selected_multi_buffer_rows in rows {
13567 let query_rows =
13568 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13569 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13570 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13571 // when the caret is just above or just below the deleted hunk.
13572 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13573 let related_to_selection = if allow_adjacent {
13574 hunk.row_range.overlaps(&query_rows)
13575 || hunk.row_range.start == query_rows.end
13576 || hunk.row_range.end == query_rows.start
13577 } else {
13578 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13579 // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13580 hunk.row_range.overlaps(&selected_multi_buffer_rows)
13581 || selected_multi_buffer_rows.end == hunk.row_range.start
13582 };
13583 if related_to_selection {
13584 if !processed_buffer_rows
13585 .entry(hunk.buffer_id)
13586 .or_default()
13587 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13588 {
13589 continue;
13590 }
13591 hunks.push(hunk);
13592 }
13593 }
13594 }
13595
13596 hunks
13597}
13598
13599pub trait CollaborationHub {
13600 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13601 fn user_participant_indices<'a>(
13602 &self,
13603 cx: &'a AppContext,
13604 ) -> &'a HashMap<u64, ParticipantIndex>;
13605 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13606}
13607
13608impl CollaborationHub for Model<Project> {
13609 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13610 self.read(cx).collaborators()
13611 }
13612
13613 fn user_participant_indices<'a>(
13614 &self,
13615 cx: &'a AppContext,
13616 ) -> &'a HashMap<u64, ParticipantIndex> {
13617 self.read(cx).user_store().read(cx).participant_indices()
13618 }
13619
13620 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13621 let this = self.read(cx);
13622 let user_ids = this.collaborators().values().map(|c| c.user_id);
13623 this.user_store().read_with(cx, |user_store, cx| {
13624 user_store.participant_names(user_ids, cx)
13625 })
13626 }
13627}
13628
13629pub trait SemanticsProvider {
13630 fn hover(
13631 &self,
13632 buffer: &Model<Buffer>,
13633 position: text::Anchor,
13634 cx: &mut AppContext,
13635 ) -> Option<Task<Vec<project::Hover>>>;
13636
13637 fn inlay_hints(
13638 &self,
13639 buffer_handle: Model<Buffer>,
13640 range: Range<text::Anchor>,
13641 cx: &mut AppContext,
13642 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13643
13644 fn resolve_inlay_hint(
13645 &self,
13646 hint: InlayHint,
13647 buffer_handle: Model<Buffer>,
13648 server_id: LanguageServerId,
13649 cx: &mut AppContext,
13650 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13651
13652 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13653
13654 fn document_highlights(
13655 &self,
13656 buffer: &Model<Buffer>,
13657 position: text::Anchor,
13658 cx: &mut AppContext,
13659 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13660
13661 fn definitions(
13662 &self,
13663 buffer: &Model<Buffer>,
13664 position: text::Anchor,
13665 kind: GotoDefinitionKind,
13666 cx: &mut AppContext,
13667 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13668
13669 fn range_for_rename(
13670 &self,
13671 buffer: &Model<Buffer>,
13672 position: text::Anchor,
13673 cx: &mut AppContext,
13674 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13675
13676 fn perform_rename(
13677 &self,
13678 buffer: &Model<Buffer>,
13679 position: text::Anchor,
13680 new_name: String,
13681 cx: &mut AppContext,
13682 ) -> Option<Task<Result<ProjectTransaction>>>;
13683}
13684
13685pub trait CompletionProvider {
13686 fn completions(
13687 &self,
13688 buffer: &Model<Buffer>,
13689 buffer_position: text::Anchor,
13690 trigger: CompletionContext,
13691 cx: &mut ViewContext<Editor>,
13692 ) -> Task<Result<Vec<Completion>>>;
13693
13694 fn resolve_completions(
13695 &self,
13696 buffer: Model<Buffer>,
13697 completion_indices: Vec<usize>,
13698 completions: Arc<RwLock<Box<[Completion]>>>,
13699 cx: &mut ViewContext<Editor>,
13700 ) -> Task<Result<bool>>;
13701
13702 fn apply_additional_edits_for_completion(
13703 &self,
13704 buffer: Model<Buffer>,
13705 completion: Completion,
13706 push_to_history: bool,
13707 cx: &mut ViewContext<Editor>,
13708 ) -> Task<Result<Option<language::Transaction>>>;
13709
13710 fn is_completion_trigger(
13711 &self,
13712 buffer: &Model<Buffer>,
13713 position: language::Anchor,
13714 text: &str,
13715 trigger_in_words: bool,
13716 cx: &mut ViewContext<Editor>,
13717 ) -> bool;
13718
13719 fn sort_completions(&self) -> bool {
13720 true
13721 }
13722}
13723
13724pub trait CodeActionProvider {
13725 fn code_actions(
13726 &self,
13727 buffer: &Model<Buffer>,
13728 range: Range<text::Anchor>,
13729 cx: &mut WindowContext,
13730 ) -> Task<Result<Vec<CodeAction>>>;
13731
13732 fn apply_code_action(
13733 &self,
13734 buffer_handle: Model<Buffer>,
13735 action: CodeAction,
13736 excerpt_id: ExcerptId,
13737 push_to_history: bool,
13738 cx: &mut WindowContext,
13739 ) -> Task<Result<ProjectTransaction>>;
13740}
13741
13742impl CodeActionProvider for Model<Project> {
13743 fn code_actions(
13744 &self,
13745 buffer: &Model<Buffer>,
13746 range: Range<text::Anchor>,
13747 cx: &mut WindowContext,
13748 ) -> Task<Result<Vec<CodeAction>>> {
13749 self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13750 }
13751
13752 fn apply_code_action(
13753 &self,
13754 buffer_handle: Model<Buffer>,
13755 action: CodeAction,
13756 _excerpt_id: ExcerptId,
13757 push_to_history: bool,
13758 cx: &mut WindowContext,
13759 ) -> Task<Result<ProjectTransaction>> {
13760 self.update(cx, |project, cx| {
13761 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13762 })
13763 }
13764}
13765
13766fn snippet_completions(
13767 project: &Project,
13768 buffer: &Model<Buffer>,
13769 buffer_position: text::Anchor,
13770 cx: &mut AppContext,
13771) -> Vec<Completion> {
13772 let language = buffer.read(cx).language_at(buffer_position);
13773 let language_name = language.as_ref().map(|language| language.lsp_id());
13774 let snippet_store = project.snippets().read(cx);
13775 let snippets = snippet_store.snippets_for(language_name, cx);
13776
13777 if snippets.is_empty() {
13778 return vec![];
13779 }
13780 let snapshot = buffer.read(cx).text_snapshot();
13781 let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13782
13783 let scope = language.map(|language| language.default_scope());
13784 let classifier = CharClassifier::new(scope).for_completion(true);
13785 let mut last_word = chars
13786 .take_while(|c| classifier.is_word(*c))
13787 .collect::<String>();
13788 last_word = last_word.chars().rev().collect();
13789 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13790 let to_lsp = |point: &text::Anchor| {
13791 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13792 point_to_lsp(end)
13793 };
13794 let lsp_end = to_lsp(&buffer_position);
13795 snippets
13796 .into_iter()
13797 .filter_map(|snippet| {
13798 let matching_prefix = snippet
13799 .prefix
13800 .iter()
13801 .find(|prefix| prefix.starts_with(&last_word))?;
13802 let start = as_offset - last_word.len();
13803 let start = snapshot.anchor_before(start);
13804 let range = start..buffer_position;
13805 let lsp_start = to_lsp(&start);
13806 let lsp_range = lsp::Range {
13807 start: lsp_start,
13808 end: lsp_end,
13809 };
13810 Some(Completion {
13811 old_range: range,
13812 new_text: snippet.body.clone(),
13813 label: CodeLabel {
13814 text: matching_prefix.clone(),
13815 runs: vec![],
13816 filter_range: 0..matching_prefix.len(),
13817 },
13818 server_id: LanguageServerId(usize::MAX),
13819 documentation: snippet.description.clone().map(Documentation::SingleLine),
13820 lsp_completion: lsp::CompletionItem {
13821 label: snippet.prefix.first().unwrap().clone(),
13822 kind: Some(CompletionItemKind::SNIPPET),
13823 label_details: snippet.description.as_ref().map(|description| {
13824 lsp::CompletionItemLabelDetails {
13825 detail: Some(description.clone()),
13826 description: None,
13827 }
13828 }),
13829 insert_text_format: Some(InsertTextFormat::SNIPPET),
13830 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13831 lsp::InsertReplaceEdit {
13832 new_text: snippet.body.clone(),
13833 insert: lsp_range,
13834 replace: lsp_range,
13835 },
13836 )),
13837 filter_text: Some(snippet.body.clone()),
13838 sort_text: Some(char::MAX.to_string()),
13839 ..Default::default()
13840 },
13841 confirm: None,
13842 })
13843 })
13844 .collect()
13845}
13846
13847impl CompletionProvider for Model<Project> {
13848 fn completions(
13849 &self,
13850 buffer: &Model<Buffer>,
13851 buffer_position: text::Anchor,
13852 options: CompletionContext,
13853 cx: &mut ViewContext<Editor>,
13854 ) -> Task<Result<Vec<Completion>>> {
13855 self.update(cx, |project, cx| {
13856 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13857 let project_completions = project.completions(buffer, buffer_position, options, cx);
13858 cx.background_executor().spawn(async move {
13859 let mut completions = project_completions.await?;
13860 //let snippets = snippets.into_iter().;
13861 completions.extend(snippets);
13862 Ok(completions)
13863 })
13864 })
13865 }
13866
13867 fn resolve_completions(
13868 &self,
13869 buffer: Model<Buffer>,
13870 completion_indices: Vec<usize>,
13871 completions: Arc<RwLock<Box<[Completion]>>>,
13872 cx: &mut ViewContext<Editor>,
13873 ) -> Task<Result<bool>> {
13874 self.update(cx, |project, cx| {
13875 project.resolve_completions(buffer, completion_indices, completions, cx)
13876 })
13877 }
13878
13879 fn apply_additional_edits_for_completion(
13880 &self,
13881 buffer: Model<Buffer>,
13882 completion: Completion,
13883 push_to_history: bool,
13884 cx: &mut ViewContext<Editor>,
13885 ) -> Task<Result<Option<language::Transaction>>> {
13886 self.update(cx, |project, cx| {
13887 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13888 })
13889 }
13890
13891 fn is_completion_trigger(
13892 &self,
13893 buffer: &Model<Buffer>,
13894 position: language::Anchor,
13895 text: &str,
13896 trigger_in_words: bool,
13897 cx: &mut ViewContext<Editor>,
13898 ) -> bool {
13899 if !EditorSettings::get_global(cx).show_completions_on_input {
13900 return false;
13901 }
13902
13903 let mut chars = text.chars();
13904 let char = if let Some(char) = chars.next() {
13905 char
13906 } else {
13907 return false;
13908 };
13909 if chars.next().is_some() {
13910 return false;
13911 }
13912
13913 let buffer = buffer.read(cx);
13914 let classifier = buffer
13915 .snapshot()
13916 .char_classifier_at(position)
13917 .for_completion(true);
13918 if trigger_in_words && classifier.is_word(char) {
13919 return true;
13920 }
13921
13922 buffer.completion_triggers().contains(text)
13923 }
13924}
13925
13926impl SemanticsProvider for Model<Project> {
13927 fn hover(
13928 &self,
13929 buffer: &Model<Buffer>,
13930 position: text::Anchor,
13931 cx: &mut AppContext,
13932 ) -> Option<Task<Vec<project::Hover>>> {
13933 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13934 }
13935
13936 fn document_highlights(
13937 &self,
13938 buffer: &Model<Buffer>,
13939 position: text::Anchor,
13940 cx: &mut AppContext,
13941 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13942 Some(self.update(cx, |project, cx| {
13943 project.document_highlights(buffer, position, cx)
13944 }))
13945 }
13946
13947 fn definitions(
13948 &self,
13949 buffer: &Model<Buffer>,
13950 position: text::Anchor,
13951 kind: GotoDefinitionKind,
13952 cx: &mut AppContext,
13953 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13954 Some(self.update(cx, |project, cx| match kind {
13955 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13956 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13957 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13958 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13959 }))
13960 }
13961
13962 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13963 // TODO: make this work for remote projects
13964 self.read(cx)
13965 .language_servers_for_buffer(buffer.read(cx), cx)
13966 .any(
13967 |(_, server)| match server.capabilities().inlay_hint_provider {
13968 Some(lsp::OneOf::Left(enabled)) => enabled,
13969 Some(lsp::OneOf::Right(_)) => true,
13970 None => false,
13971 },
13972 )
13973 }
13974
13975 fn inlay_hints(
13976 &self,
13977 buffer_handle: Model<Buffer>,
13978 range: Range<text::Anchor>,
13979 cx: &mut AppContext,
13980 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13981 Some(self.update(cx, |project, cx| {
13982 project.inlay_hints(buffer_handle, range, cx)
13983 }))
13984 }
13985
13986 fn resolve_inlay_hint(
13987 &self,
13988 hint: InlayHint,
13989 buffer_handle: Model<Buffer>,
13990 server_id: LanguageServerId,
13991 cx: &mut AppContext,
13992 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13993 Some(self.update(cx, |project, cx| {
13994 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13995 }))
13996 }
13997
13998 fn range_for_rename(
13999 &self,
14000 buffer: &Model<Buffer>,
14001 position: text::Anchor,
14002 cx: &mut AppContext,
14003 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14004 Some(self.update(cx, |project, cx| {
14005 project.prepare_rename(buffer.clone(), position, cx)
14006 }))
14007 }
14008
14009 fn perform_rename(
14010 &self,
14011 buffer: &Model<Buffer>,
14012 position: text::Anchor,
14013 new_name: String,
14014 cx: &mut AppContext,
14015 ) -> Option<Task<Result<ProjectTransaction>>> {
14016 Some(self.update(cx, |project, cx| {
14017 project.perform_rename(buffer.clone(), position, new_name, cx)
14018 }))
14019 }
14020}
14021
14022fn inlay_hint_settings(
14023 location: Anchor,
14024 snapshot: &MultiBufferSnapshot,
14025 cx: &mut ViewContext<'_, Editor>,
14026) -> InlayHintSettings {
14027 let file = snapshot.file_at(location);
14028 let language = snapshot.language_at(location).map(|l| l.name());
14029 language_settings(language, file, cx).inlay_hints
14030}
14031
14032fn consume_contiguous_rows(
14033 contiguous_row_selections: &mut Vec<Selection<Point>>,
14034 selection: &Selection<Point>,
14035 display_map: &DisplaySnapshot,
14036 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14037) -> (MultiBufferRow, MultiBufferRow) {
14038 contiguous_row_selections.push(selection.clone());
14039 let start_row = MultiBufferRow(selection.start.row);
14040 let mut end_row = ending_row(selection, display_map);
14041
14042 while let Some(next_selection) = selections.peek() {
14043 if next_selection.start.row <= end_row.0 {
14044 end_row = ending_row(next_selection, display_map);
14045 contiguous_row_selections.push(selections.next().unwrap().clone());
14046 } else {
14047 break;
14048 }
14049 }
14050 (start_row, end_row)
14051}
14052
14053fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14054 if next_selection.end.column > 0 || next_selection.is_empty() {
14055 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14056 } else {
14057 MultiBufferRow(next_selection.end.row)
14058 }
14059}
14060
14061impl EditorSnapshot {
14062 pub fn remote_selections_in_range<'a>(
14063 &'a self,
14064 range: &'a Range<Anchor>,
14065 collaboration_hub: &dyn CollaborationHub,
14066 cx: &'a AppContext,
14067 ) -> impl 'a + Iterator<Item = RemoteSelection> {
14068 let participant_names = collaboration_hub.user_names(cx);
14069 let participant_indices = collaboration_hub.user_participant_indices(cx);
14070 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14071 let collaborators_by_replica_id = collaborators_by_peer_id
14072 .iter()
14073 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14074 .collect::<HashMap<_, _>>();
14075 self.buffer_snapshot
14076 .selections_in_range(range, false)
14077 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14078 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14079 let participant_index = participant_indices.get(&collaborator.user_id).copied();
14080 let user_name = participant_names.get(&collaborator.user_id).cloned();
14081 Some(RemoteSelection {
14082 replica_id,
14083 selection,
14084 cursor_shape,
14085 line_mode,
14086 participant_index,
14087 peer_id: collaborator.peer_id,
14088 user_name,
14089 })
14090 })
14091 }
14092
14093 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14094 self.display_snapshot.buffer_snapshot.language_at(position)
14095 }
14096
14097 pub fn is_focused(&self) -> bool {
14098 self.is_focused
14099 }
14100
14101 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14102 self.placeholder_text.as_ref()
14103 }
14104
14105 pub fn scroll_position(&self) -> gpui::Point<f32> {
14106 self.scroll_anchor.scroll_position(&self.display_snapshot)
14107 }
14108
14109 fn gutter_dimensions(
14110 &self,
14111 font_id: FontId,
14112 font_size: Pixels,
14113 em_width: Pixels,
14114 em_advance: Pixels,
14115 max_line_number_width: Pixels,
14116 cx: &AppContext,
14117 ) -> GutterDimensions {
14118 if !self.show_gutter {
14119 return GutterDimensions::default();
14120 }
14121 let descent = cx.text_system().descent(font_id, font_size);
14122
14123 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14124 matches!(
14125 ProjectSettings::get_global(cx).git.git_gutter,
14126 Some(GitGutterSetting::TrackedFiles)
14127 )
14128 });
14129 let gutter_settings = EditorSettings::get_global(cx).gutter;
14130 let show_line_numbers = self
14131 .show_line_numbers
14132 .unwrap_or(gutter_settings.line_numbers);
14133 let line_gutter_width = if show_line_numbers {
14134 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14135 let min_width_for_number_on_gutter = em_advance * 4.0;
14136 max_line_number_width.max(min_width_for_number_on_gutter)
14137 } else {
14138 0.0.into()
14139 };
14140
14141 let show_code_actions = self
14142 .show_code_actions
14143 .unwrap_or(gutter_settings.code_actions);
14144
14145 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14146
14147 let git_blame_entries_width =
14148 self.git_blame_gutter_max_author_length
14149 .map(|max_author_length| {
14150 // Length of the author name, but also space for the commit hash,
14151 // the spacing and the timestamp.
14152 let max_char_count = max_author_length
14153 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14154 + 7 // length of commit sha
14155 + 14 // length of max relative timestamp ("60 minutes ago")
14156 + 4; // gaps and margins
14157
14158 em_advance * max_char_count
14159 });
14160
14161 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14162 left_padding += if show_code_actions || show_runnables {
14163 em_width * 3.0
14164 } else if show_git_gutter && show_line_numbers {
14165 em_width * 2.0
14166 } else if show_git_gutter || show_line_numbers {
14167 em_width
14168 } else {
14169 px(0.)
14170 };
14171
14172 let right_padding = if gutter_settings.folds && show_line_numbers {
14173 em_width * 4.0
14174 } else if gutter_settings.folds {
14175 em_width * 3.0
14176 } else if show_line_numbers {
14177 em_width
14178 } else {
14179 px(0.)
14180 };
14181
14182 GutterDimensions {
14183 left_padding,
14184 right_padding,
14185 width: line_gutter_width + left_padding + right_padding,
14186 margin: -descent,
14187 git_blame_entries_width,
14188 }
14189 }
14190
14191 pub fn render_crease_toggle(
14192 &self,
14193 buffer_row: MultiBufferRow,
14194 row_contains_cursor: bool,
14195 editor: View<Editor>,
14196 cx: &mut WindowContext,
14197 ) -> Option<AnyElement> {
14198 let folded = self.is_line_folded(buffer_row);
14199 let mut is_foldable = false;
14200
14201 if let Some(crease) = self
14202 .crease_snapshot
14203 .query_row(buffer_row, &self.buffer_snapshot)
14204 {
14205 is_foldable = true;
14206 match crease {
14207 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14208 if let Some(render_toggle) = render_toggle {
14209 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14210 if folded {
14211 editor.update(cx, |editor, cx| {
14212 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14213 });
14214 } else {
14215 editor.update(cx, |editor, cx| {
14216 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14217 });
14218 }
14219 });
14220 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14221 }
14222 }
14223 }
14224 }
14225
14226 is_foldable |= self.starts_indent(buffer_row);
14227
14228 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14229 Some(
14230 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14231 .selected(folded)
14232 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14233 if folded {
14234 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14235 } else {
14236 this.fold_at(&FoldAt { buffer_row }, cx);
14237 }
14238 }))
14239 .into_any_element(),
14240 )
14241 } else {
14242 None
14243 }
14244 }
14245
14246 pub fn render_crease_trailer(
14247 &self,
14248 buffer_row: MultiBufferRow,
14249 cx: &mut WindowContext,
14250 ) -> Option<AnyElement> {
14251 let folded = self.is_line_folded(buffer_row);
14252 if let Crease::Inline { render_trailer, .. } = self
14253 .crease_snapshot
14254 .query_row(buffer_row, &self.buffer_snapshot)?
14255 {
14256 let render_trailer = render_trailer.as_ref()?;
14257 Some(render_trailer(buffer_row, folded, cx))
14258 } else {
14259 None
14260 }
14261 }
14262}
14263
14264impl Deref for EditorSnapshot {
14265 type Target = DisplaySnapshot;
14266
14267 fn deref(&self) -> &Self::Target {
14268 &self.display_snapshot
14269 }
14270}
14271
14272#[derive(Clone, Debug, PartialEq, Eq)]
14273pub enum EditorEvent {
14274 InputIgnored {
14275 text: Arc<str>,
14276 },
14277 InputHandled {
14278 utf16_range_to_replace: Option<Range<isize>>,
14279 text: Arc<str>,
14280 },
14281 ExcerptsAdded {
14282 buffer: Model<Buffer>,
14283 predecessor: ExcerptId,
14284 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14285 },
14286 ExcerptsRemoved {
14287 ids: Vec<ExcerptId>,
14288 },
14289 ExcerptsEdited {
14290 ids: Vec<ExcerptId>,
14291 },
14292 ExcerptsExpanded {
14293 ids: Vec<ExcerptId>,
14294 },
14295 BufferEdited,
14296 Edited {
14297 transaction_id: clock::Lamport,
14298 },
14299 Reparsed(BufferId),
14300 Focused,
14301 FocusedIn,
14302 Blurred,
14303 DirtyChanged,
14304 Saved,
14305 TitleChanged,
14306 DiffBaseChanged,
14307 SelectionsChanged {
14308 local: bool,
14309 },
14310 ScrollPositionChanged {
14311 local: bool,
14312 autoscroll: bool,
14313 },
14314 Closed,
14315 TransactionUndone {
14316 transaction_id: clock::Lamport,
14317 },
14318 TransactionBegun {
14319 transaction_id: clock::Lamport,
14320 },
14321 Reloaded,
14322 CursorShapeChanged,
14323}
14324
14325impl EventEmitter<EditorEvent> for Editor {}
14326
14327impl FocusableView for Editor {
14328 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14329 self.focus_handle.clone()
14330 }
14331}
14332
14333impl Render for Editor {
14334 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14335 let settings = ThemeSettings::get_global(cx);
14336
14337 let mut text_style = match self.mode {
14338 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14339 color: cx.theme().colors().editor_foreground,
14340 font_family: settings.ui_font.family.clone(),
14341 font_features: settings.ui_font.features.clone(),
14342 font_fallbacks: settings.ui_font.fallbacks.clone(),
14343 font_size: rems(0.875).into(),
14344 font_weight: settings.ui_font.weight,
14345 line_height: relative(settings.buffer_line_height.value()),
14346 ..Default::default()
14347 },
14348 EditorMode::Full => TextStyle {
14349 color: cx.theme().colors().editor_foreground,
14350 font_family: settings.buffer_font.family.clone(),
14351 font_features: settings.buffer_font.features.clone(),
14352 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14353 font_size: settings.buffer_font_size(cx).into(),
14354 font_weight: settings.buffer_font.weight,
14355 line_height: relative(settings.buffer_line_height.value()),
14356 ..Default::default()
14357 },
14358 };
14359 if let Some(text_style_refinement) = &self.text_style_refinement {
14360 text_style.refine(text_style_refinement)
14361 }
14362
14363 let background = match self.mode {
14364 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14365 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14366 EditorMode::Full => cx.theme().colors().editor_background,
14367 };
14368
14369 EditorElement::new(
14370 cx.view(),
14371 EditorStyle {
14372 background,
14373 local_player: cx.theme().players().local(),
14374 text: text_style,
14375 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14376 syntax: cx.theme().syntax().clone(),
14377 status: cx.theme().status().clone(),
14378 inlay_hints_style: make_inlay_hints_style(cx),
14379 suggestions_style: HighlightStyle {
14380 color: Some(cx.theme().status().predictive),
14381 ..HighlightStyle::default()
14382 },
14383 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14384 },
14385 )
14386 }
14387}
14388
14389impl ViewInputHandler for Editor {
14390 fn text_for_range(
14391 &mut self,
14392 range_utf16: Range<usize>,
14393 adjusted_range: &mut Option<Range<usize>>,
14394 cx: &mut ViewContext<Self>,
14395 ) -> Option<String> {
14396 let snapshot = self.buffer.read(cx).read(cx);
14397 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14398 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14399 if (start.0..end.0) != range_utf16 {
14400 adjusted_range.replace(start.0..end.0);
14401 }
14402 Some(snapshot.text_for_range(start..end).collect())
14403 }
14404
14405 fn selected_text_range(
14406 &mut self,
14407 ignore_disabled_input: bool,
14408 cx: &mut ViewContext<Self>,
14409 ) -> Option<UTF16Selection> {
14410 // Prevent the IME menu from appearing when holding down an alphabetic key
14411 // while input is disabled.
14412 if !ignore_disabled_input && !self.input_enabled {
14413 return None;
14414 }
14415
14416 let selection = self.selections.newest::<OffsetUtf16>(cx);
14417 let range = selection.range();
14418
14419 Some(UTF16Selection {
14420 range: range.start.0..range.end.0,
14421 reversed: selection.reversed,
14422 })
14423 }
14424
14425 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14426 let snapshot = self.buffer.read(cx).read(cx);
14427 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14428 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14429 }
14430
14431 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14432 self.clear_highlights::<InputComposition>(cx);
14433 self.ime_transaction.take();
14434 }
14435
14436 fn replace_text_in_range(
14437 &mut self,
14438 range_utf16: Option<Range<usize>>,
14439 text: &str,
14440 cx: &mut ViewContext<Self>,
14441 ) {
14442 if !self.input_enabled {
14443 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14444 return;
14445 }
14446
14447 self.transact(cx, |this, cx| {
14448 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14449 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14450 Some(this.selection_replacement_ranges(range_utf16, cx))
14451 } else {
14452 this.marked_text_ranges(cx)
14453 };
14454
14455 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14456 let newest_selection_id = this.selections.newest_anchor().id;
14457 this.selections
14458 .all::<OffsetUtf16>(cx)
14459 .iter()
14460 .zip(ranges_to_replace.iter())
14461 .find_map(|(selection, range)| {
14462 if selection.id == newest_selection_id {
14463 Some(
14464 (range.start.0 as isize - selection.head().0 as isize)
14465 ..(range.end.0 as isize - selection.head().0 as isize),
14466 )
14467 } else {
14468 None
14469 }
14470 })
14471 });
14472
14473 cx.emit(EditorEvent::InputHandled {
14474 utf16_range_to_replace: range_to_replace,
14475 text: text.into(),
14476 });
14477
14478 if let Some(new_selected_ranges) = new_selected_ranges {
14479 this.change_selections(None, cx, |selections| {
14480 selections.select_ranges(new_selected_ranges)
14481 });
14482 this.backspace(&Default::default(), cx);
14483 }
14484
14485 this.handle_input(text, cx);
14486 });
14487
14488 if let Some(transaction) = self.ime_transaction {
14489 self.buffer.update(cx, |buffer, cx| {
14490 buffer.group_until_transaction(transaction, cx);
14491 });
14492 }
14493
14494 self.unmark_text(cx);
14495 }
14496
14497 fn replace_and_mark_text_in_range(
14498 &mut self,
14499 range_utf16: Option<Range<usize>>,
14500 text: &str,
14501 new_selected_range_utf16: Option<Range<usize>>,
14502 cx: &mut ViewContext<Self>,
14503 ) {
14504 if !self.input_enabled {
14505 return;
14506 }
14507
14508 let transaction = self.transact(cx, |this, cx| {
14509 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14510 let snapshot = this.buffer.read(cx).read(cx);
14511 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14512 for marked_range in &mut marked_ranges {
14513 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14514 marked_range.start.0 += relative_range_utf16.start;
14515 marked_range.start =
14516 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14517 marked_range.end =
14518 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14519 }
14520 }
14521 Some(marked_ranges)
14522 } else if let Some(range_utf16) = range_utf16 {
14523 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14524 Some(this.selection_replacement_ranges(range_utf16, cx))
14525 } else {
14526 None
14527 };
14528
14529 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14530 let newest_selection_id = this.selections.newest_anchor().id;
14531 this.selections
14532 .all::<OffsetUtf16>(cx)
14533 .iter()
14534 .zip(ranges_to_replace.iter())
14535 .find_map(|(selection, range)| {
14536 if selection.id == newest_selection_id {
14537 Some(
14538 (range.start.0 as isize - selection.head().0 as isize)
14539 ..(range.end.0 as isize - selection.head().0 as isize),
14540 )
14541 } else {
14542 None
14543 }
14544 })
14545 });
14546
14547 cx.emit(EditorEvent::InputHandled {
14548 utf16_range_to_replace: range_to_replace,
14549 text: text.into(),
14550 });
14551
14552 if let Some(ranges) = ranges_to_replace {
14553 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14554 }
14555
14556 let marked_ranges = {
14557 let snapshot = this.buffer.read(cx).read(cx);
14558 this.selections
14559 .disjoint_anchors()
14560 .iter()
14561 .map(|selection| {
14562 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14563 })
14564 .collect::<Vec<_>>()
14565 };
14566
14567 if text.is_empty() {
14568 this.unmark_text(cx);
14569 } else {
14570 this.highlight_text::<InputComposition>(
14571 marked_ranges.clone(),
14572 HighlightStyle {
14573 underline: Some(UnderlineStyle {
14574 thickness: px(1.),
14575 color: None,
14576 wavy: false,
14577 }),
14578 ..Default::default()
14579 },
14580 cx,
14581 );
14582 }
14583
14584 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14585 let use_autoclose = this.use_autoclose;
14586 let use_auto_surround = this.use_auto_surround;
14587 this.set_use_autoclose(false);
14588 this.set_use_auto_surround(false);
14589 this.handle_input(text, cx);
14590 this.set_use_autoclose(use_autoclose);
14591 this.set_use_auto_surround(use_auto_surround);
14592
14593 if let Some(new_selected_range) = new_selected_range_utf16 {
14594 let snapshot = this.buffer.read(cx).read(cx);
14595 let new_selected_ranges = marked_ranges
14596 .into_iter()
14597 .map(|marked_range| {
14598 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14599 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14600 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14601 snapshot.clip_offset_utf16(new_start, Bias::Left)
14602 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14603 })
14604 .collect::<Vec<_>>();
14605
14606 drop(snapshot);
14607 this.change_selections(None, cx, |selections| {
14608 selections.select_ranges(new_selected_ranges)
14609 });
14610 }
14611 });
14612
14613 self.ime_transaction = self.ime_transaction.or(transaction);
14614 if let Some(transaction) = self.ime_transaction {
14615 self.buffer.update(cx, |buffer, cx| {
14616 buffer.group_until_transaction(transaction, cx);
14617 });
14618 }
14619
14620 if self.text_highlights::<InputComposition>(cx).is_none() {
14621 self.ime_transaction.take();
14622 }
14623 }
14624
14625 fn bounds_for_range(
14626 &mut self,
14627 range_utf16: Range<usize>,
14628 element_bounds: gpui::Bounds<Pixels>,
14629 cx: &mut ViewContext<Self>,
14630 ) -> Option<gpui::Bounds<Pixels>> {
14631 let text_layout_details = self.text_layout_details(cx);
14632 let style = &text_layout_details.editor_style;
14633 let font_id = cx.text_system().resolve_font(&style.text.font());
14634 let font_size = style.text.font_size.to_pixels(cx.rem_size());
14635 let line_height = style.text.line_height_in_pixels(cx.rem_size());
14636
14637 let em_width = cx
14638 .text_system()
14639 .typographic_bounds(font_id, font_size, 'm')
14640 .unwrap()
14641 .size
14642 .width;
14643
14644 let snapshot = self.snapshot(cx);
14645 let scroll_position = snapshot.scroll_position();
14646 let scroll_left = scroll_position.x * em_width;
14647
14648 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14649 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14650 + self.gutter_dimensions.width;
14651 let y = line_height * (start.row().as_f32() - scroll_position.y);
14652
14653 Some(Bounds {
14654 origin: element_bounds.origin + point(x, y),
14655 size: size(em_width, line_height),
14656 })
14657 }
14658}
14659
14660trait SelectionExt {
14661 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14662 fn spanned_rows(
14663 &self,
14664 include_end_if_at_line_start: bool,
14665 map: &DisplaySnapshot,
14666 ) -> Range<MultiBufferRow>;
14667}
14668
14669impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14670 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14671 let start = self
14672 .start
14673 .to_point(&map.buffer_snapshot)
14674 .to_display_point(map);
14675 let end = self
14676 .end
14677 .to_point(&map.buffer_snapshot)
14678 .to_display_point(map);
14679 if self.reversed {
14680 end..start
14681 } else {
14682 start..end
14683 }
14684 }
14685
14686 fn spanned_rows(
14687 &self,
14688 include_end_if_at_line_start: bool,
14689 map: &DisplaySnapshot,
14690 ) -> Range<MultiBufferRow> {
14691 let start = self.start.to_point(&map.buffer_snapshot);
14692 let mut end = self.end.to_point(&map.buffer_snapshot);
14693 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14694 end.row -= 1;
14695 }
14696
14697 let buffer_start = map.prev_line_boundary(start).0;
14698 let buffer_end = map.next_line_boundary(end).0;
14699 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14700 }
14701}
14702
14703impl<T: InvalidationRegion> InvalidationStack<T> {
14704 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14705 where
14706 S: Clone + ToOffset,
14707 {
14708 while let Some(region) = self.last() {
14709 let all_selections_inside_invalidation_ranges =
14710 if selections.len() == region.ranges().len() {
14711 selections
14712 .iter()
14713 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14714 .all(|(selection, invalidation_range)| {
14715 let head = selection.head().to_offset(buffer);
14716 invalidation_range.start <= head && invalidation_range.end >= head
14717 })
14718 } else {
14719 false
14720 };
14721
14722 if all_selections_inside_invalidation_ranges {
14723 break;
14724 } else {
14725 self.pop();
14726 }
14727 }
14728 }
14729}
14730
14731impl<T> Default for InvalidationStack<T> {
14732 fn default() -> Self {
14733 Self(Default::default())
14734 }
14735}
14736
14737impl<T> Deref for InvalidationStack<T> {
14738 type Target = Vec<T>;
14739
14740 fn deref(&self) -> &Self::Target {
14741 &self.0
14742 }
14743}
14744
14745impl<T> DerefMut for InvalidationStack<T> {
14746 fn deref_mut(&mut self) -> &mut Self::Target {
14747 &mut self.0
14748 }
14749}
14750
14751impl InvalidationRegion for SnippetState {
14752 fn ranges(&self) -> &[Range<Anchor>] {
14753 &self.ranges[self.active_index]
14754 }
14755}
14756
14757pub fn diagnostic_block_renderer(
14758 diagnostic: Diagnostic,
14759 max_message_rows: Option<u8>,
14760 allow_closing: bool,
14761 _is_valid: bool,
14762) -> RenderBlock {
14763 let (text_without_backticks, code_ranges) =
14764 highlight_diagnostic_message(&diagnostic, max_message_rows);
14765
14766 Arc::new(move |cx: &mut BlockContext| {
14767 let group_id: SharedString = cx.block_id.to_string().into();
14768
14769 let mut text_style = cx.text_style().clone();
14770 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14771 let theme_settings = ThemeSettings::get_global(cx);
14772 text_style.font_family = theme_settings.buffer_font.family.clone();
14773 text_style.font_style = theme_settings.buffer_font.style;
14774 text_style.font_features = theme_settings.buffer_font.features.clone();
14775 text_style.font_weight = theme_settings.buffer_font.weight;
14776
14777 let multi_line_diagnostic = diagnostic.message.contains('\n');
14778
14779 let buttons = |diagnostic: &Diagnostic| {
14780 if multi_line_diagnostic {
14781 v_flex()
14782 } else {
14783 h_flex()
14784 }
14785 .when(allow_closing, |div| {
14786 div.children(diagnostic.is_primary.then(|| {
14787 IconButton::new("close-block", IconName::XCircle)
14788 .icon_color(Color::Muted)
14789 .size(ButtonSize::Compact)
14790 .style(ButtonStyle::Transparent)
14791 .visible_on_hover(group_id.clone())
14792 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14793 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14794 }))
14795 })
14796 .child(
14797 IconButton::new("copy-block", IconName::Copy)
14798 .icon_color(Color::Muted)
14799 .size(ButtonSize::Compact)
14800 .style(ButtonStyle::Transparent)
14801 .visible_on_hover(group_id.clone())
14802 .on_click({
14803 let message = diagnostic.message.clone();
14804 move |_click, cx| {
14805 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14806 }
14807 })
14808 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14809 )
14810 };
14811
14812 let icon_size = buttons(&diagnostic)
14813 .into_any_element()
14814 .layout_as_root(AvailableSpace::min_size(), cx);
14815
14816 h_flex()
14817 .id(cx.block_id)
14818 .group(group_id.clone())
14819 .relative()
14820 .size_full()
14821 .block_mouse_down()
14822 .pl(cx.gutter_dimensions.width)
14823 .w(cx.max_width - cx.gutter_dimensions.full_width())
14824 .child(
14825 div()
14826 .flex()
14827 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14828 .flex_shrink(),
14829 )
14830 .child(buttons(&diagnostic))
14831 .child(div().flex().flex_shrink_0().child(
14832 StyledText::new(text_without_backticks.clone()).with_highlights(
14833 &text_style,
14834 code_ranges.iter().map(|range| {
14835 (
14836 range.clone(),
14837 HighlightStyle {
14838 font_weight: Some(FontWeight::BOLD),
14839 ..Default::default()
14840 },
14841 )
14842 }),
14843 ),
14844 ))
14845 .into_any_element()
14846 })
14847}
14848
14849pub fn highlight_diagnostic_message(
14850 diagnostic: &Diagnostic,
14851 mut max_message_rows: Option<u8>,
14852) -> (SharedString, Vec<Range<usize>>) {
14853 let mut text_without_backticks = String::new();
14854 let mut code_ranges = Vec::new();
14855
14856 if let Some(source) = &diagnostic.source {
14857 text_without_backticks.push_str(source);
14858 code_ranges.push(0..source.len());
14859 text_without_backticks.push_str(": ");
14860 }
14861
14862 let mut prev_offset = 0;
14863 let mut in_code_block = false;
14864 let has_row_limit = max_message_rows.is_some();
14865 let mut newline_indices = diagnostic
14866 .message
14867 .match_indices('\n')
14868 .filter(|_| has_row_limit)
14869 .map(|(ix, _)| ix)
14870 .fuse()
14871 .peekable();
14872
14873 for (quote_ix, _) in diagnostic
14874 .message
14875 .match_indices('`')
14876 .chain([(diagnostic.message.len(), "")])
14877 {
14878 let mut first_newline_ix = None;
14879 let mut last_newline_ix = None;
14880 while let Some(newline_ix) = newline_indices.peek() {
14881 if *newline_ix < quote_ix {
14882 if first_newline_ix.is_none() {
14883 first_newline_ix = Some(*newline_ix);
14884 }
14885 last_newline_ix = Some(*newline_ix);
14886
14887 if let Some(rows_left) = &mut max_message_rows {
14888 if *rows_left == 0 {
14889 break;
14890 } else {
14891 *rows_left -= 1;
14892 }
14893 }
14894 let _ = newline_indices.next();
14895 } else {
14896 break;
14897 }
14898 }
14899 let prev_len = text_without_backticks.len();
14900 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14901 text_without_backticks.push_str(new_text);
14902 if in_code_block {
14903 code_ranges.push(prev_len..text_without_backticks.len());
14904 }
14905 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14906 in_code_block = !in_code_block;
14907 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14908 text_without_backticks.push_str("...");
14909 break;
14910 }
14911 }
14912
14913 (text_without_backticks.into(), code_ranges)
14914}
14915
14916fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14917 match severity {
14918 DiagnosticSeverity::ERROR => colors.error,
14919 DiagnosticSeverity::WARNING => colors.warning,
14920 DiagnosticSeverity::INFORMATION => colors.info,
14921 DiagnosticSeverity::HINT => colors.info,
14922 _ => colors.ignored,
14923 }
14924}
14925
14926pub fn styled_runs_for_code_label<'a>(
14927 label: &'a CodeLabel,
14928 syntax_theme: &'a theme::SyntaxTheme,
14929) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14930 let fade_out = HighlightStyle {
14931 fade_out: Some(0.35),
14932 ..Default::default()
14933 };
14934
14935 let mut prev_end = label.filter_range.end;
14936 label
14937 .runs
14938 .iter()
14939 .enumerate()
14940 .flat_map(move |(ix, (range, highlight_id))| {
14941 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14942 style
14943 } else {
14944 return Default::default();
14945 };
14946 let mut muted_style = style;
14947 muted_style.highlight(fade_out);
14948
14949 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14950 if range.start >= label.filter_range.end {
14951 if range.start > prev_end {
14952 runs.push((prev_end..range.start, fade_out));
14953 }
14954 runs.push((range.clone(), muted_style));
14955 } else if range.end <= label.filter_range.end {
14956 runs.push((range.clone(), style));
14957 } else {
14958 runs.push((range.start..label.filter_range.end, style));
14959 runs.push((label.filter_range.end..range.end, muted_style));
14960 }
14961 prev_end = cmp::max(prev_end, range.end);
14962
14963 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14964 runs.push((prev_end..label.text.len(), fade_out));
14965 }
14966
14967 runs
14968 })
14969}
14970
14971pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14972 let mut prev_index = 0;
14973 let mut prev_codepoint: Option<char> = None;
14974 text.char_indices()
14975 .chain([(text.len(), '\0')])
14976 .filter_map(move |(index, codepoint)| {
14977 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14978 let is_boundary = index == text.len()
14979 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14980 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14981 if is_boundary {
14982 let chunk = &text[prev_index..index];
14983 prev_index = index;
14984 Some(chunk)
14985 } else {
14986 None
14987 }
14988 })
14989}
14990
14991pub trait RangeToAnchorExt: Sized {
14992 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14993
14994 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14995 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14996 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14997 }
14998}
14999
15000impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15001 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15002 let start_offset = self.start.to_offset(snapshot);
15003 let end_offset = self.end.to_offset(snapshot);
15004 if start_offset == end_offset {
15005 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15006 } else {
15007 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15008 }
15009 }
15010}
15011
15012pub trait RowExt {
15013 fn as_f32(&self) -> f32;
15014
15015 fn next_row(&self) -> Self;
15016
15017 fn previous_row(&self) -> Self;
15018
15019 fn minus(&self, other: Self) -> u32;
15020}
15021
15022impl RowExt for DisplayRow {
15023 fn as_f32(&self) -> f32 {
15024 self.0 as f32
15025 }
15026
15027 fn next_row(&self) -> Self {
15028 Self(self.0 + 1)
15029 }
15030
15031 fn previous_row(&self) -> Self {
15032 Self(self.0.saturating_sub(1))
15033 }
15034
15035 fn minus(&self, other: Self) -> u32 {
15036 self.0 - other.0
15037 }
15038}
15039
15040impl RowExt for MultiBufferRow {
15041 fn as_f32(&self) -> f32 {
15042 self.0 as f32
15043 }
15044
15045 fn next_row(&self) -> Self {
15046 Self(self.0 + 1)
15047 }
15048
15049 fn previous_row(&self) -> Self {
15050 Self(self.0.saturating_sub(1))
15051 }
15052
15053 fn minus(&self, other: Self) -> u32 {
15054 self.0 - other.0
15055 }
15056}
15057
15058trait RowRangeExt {
15059 type Row;
15060
15061 fn len(&self) -> usize;
15062
15063 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15064}
15065
15066impl RowRangeExt for Range<MultiBufferRow> {
15067 type Row = MultiBufferRow;
15068
15069 fn len(&self) -> usize {
15070 (self.end.0 - self.start.0) as usize
15071 }
15072
15073 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15074 (self.start.0..self.end.0).map(MultiBufferRow)
15075 }
15076}
15077
15078impl RowRangeExt for Range<DisplayRow> {
15079 type Row = DisplayRow;
15080
15081 fn len(&self) -> usize {
15082 (self.end.0 - self.start.0) as usize
15083 }
15084
15085 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15086 (self.start.0..self.end.0).map(DisplayRow)
15087 }
15088}
15089
15090fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15091 if hunk.diff_base_byte_range.is_empty() {
15092 DiffHunkStatus::Added
15093 } else if hunk.row_range.is_empty() {
15094 DiffHunkStatus::Removed
15095 } else {
15096 DiffHunkStatus::Modified
15097 }
15098}
15099
15100/// If select range has more than one line, we
15101/// just point the cursor to range.start.
15102fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15103 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15104 range
15105 } else {
15106 range.start..range.start
15107 }
15108}
15109
15110const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);