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)| StringMatchCandidate::new(id, completion.label.text.clone()))
1030 .collect();
1031
1032 Self {
1033 id,
1034 sort_completions,
1035 initial_position,
1036 buffer,
1037 completions: Arc::new(RwLock::new(completions)),
1038 match_candidates,
1039 matches: Vec::new().into(),
1040 selected_item: 0,
1041 scroll_handle: UniformListScrollHandle::new(),
1042 selected_completion_documentation_resolve_debounce: Some(Arc::new(Mutex::new(
1043 DebouncedDelay::new(),
1044 ))),
1045 }
1046 }
1047
1048 fn new_snippet_choices(
1049 id: CompletionId,
1050 sort_completions: bool,
1051 choices: &Vec<String>,
1052 selection: Range<Anchor>,
1053 buffer: Model<Buffer>,
1054 ) -> Self {
1055 let completions = choices
1056 .iter()
1057 .map(|choice| Completion {
1058 old_range: selection.start.text_anchor..selection.end.text_anchor,
1059 new_text: choice.to_string(),
1060 label: CodeLabel {
1061 text: choice.to_string(),
1062 runs: Default::default(),
1063 filter_range: Default::default(),
1064 },
1065 server_id: LanguageServerId(usize::MAX),
1066 documentation: None,
1067 lsp_completion: Default::default(),
1068 confirm: None,
1069 })
1070 .collect();
1071
1072 let match_candidates = choices
1073 .iter()
1074 .enumerate()
1075 .map(|(id, completion)| StringMatchCandidate::new(id, completion.to_string()))
1076 .collect();
1077 let matches = choices
1078 .iter()
1079 .enumerate()
1080 .map(|(id, completion)| StringMatch {
1081 candidate_id: id,
1082 score: 1.,
1083 positions: vec![],
1084 string: completion.clone(),
1085 })
1086 .collect();
1087 Self {
1088 id,
1089 sort_completions,
1090 initial_position: selection.start,
1091 buffer,
1092 completions: Arc::new(RwLock::new(completions)),
1093 match_candidates,
1094 matches,
1095 selected_item: 0,
1096 scroll_handle: UniformListScrollHandle::new(),
1097 selected_completion_documentation_resolve_debounce: Some(Arc::new(Mutex::new(
1098 DebouncedDelay::new(),
1099 ))),
1100 }
1101 }
1102
1103 fn suppress_documentation_resolution(mut self) -> Self {
1104 self.selected_completion_documentation_resolve_debounce
1105 .take();
1106 self
1107 }
1108
1109 fn select_first(
1110 &mut self,
1111 provider: Option<&dyn CompletionProvider>,
1112 cx: &mut ViewContext<Editor>,
1113 ) {
1114 self.selected_item = 0;
1115 self.scroll_handle
1116 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1117 self.attempt_resolve_selected_completion_documentation(provider, cx);
1118 cx.notify();
1119 }
1120
1121 fn select_prev(
1122 &mut self,
1123 provider: Option<&dyn CompletionProvider>,
1124 cx: &mut ViewContext<Editor>,
1125 ) {
1126 if self.selected_item > 0 {
1127 self.selected_item -= 1;
1128 } else {
1129 self.selected_item = self.matches.len() - 1;
1130 }
1131 self.scroll_handle
1132 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1133 self.attempt_resolve_selected_completion_documentation(provider, cx);
1134 cx.notify();
1135 }
1136
1137 fn select_next(
1138 &mut self,
1139 provider: Option<&dyn CompletionProvider>,
1140 cx: &mut ViewContext<Editor>,
1141 ) {
1142 if self.selected_item + 1 < self.matches.len() {
1143 self.selected_item += 1;
1144 } else {
1145 self.selected_item = 0;
1146 }
1147 self.scroll_handle
1148 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1149 self.attempt_resolve_selected_completion_documentation(provider, cx);
1150 cx.notify();
1151 }
1152
1153 fn select_last(
1154 &mut self,
1155 provider: Option<&dyn CompletionProvider>,
1156 cx: &mut ViewContext<Editor>,
1157 ) {
1158 self.selected_item = self.matches.len() - 1;
1159 self.scroll_handle
1160 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1161 self.attempt_resolve_selected_completion_documentation(provider, cx);
1162 cx.notify();
1163 }
1164
1165 fn pre_resolve_completion_documentation(
1166 buffer: Model<Buffer>,
1167 completions: Arc<RwLock<Box<[Completion]>>>,
1168 matches: Arc<[StringMatch]>,
1169 editor: &Editor,
1170 cx: &mut ViewContext<Editor>,
1171 ) -> Task<()> {
1172 let settings = EditorSettings::get_global(cx);
1173 if !settings.show_completion_documentation {
1174 return Task::ready(());
1175 }
1176
1177 let Some(provider) = editor.completion_provider.as_ref() else {
1178 return Task::ready(());
1179 };
1180
1181 let resolve_task = provider.resolve_completions(
1182 buffer,
1183 matches.iter().map(|m| m.candidate_id).collect(),
1184 completions.clone(),
1185 cx,
1186 );
1187
1188 cx.spawn(move |this, mut cx| async move {
1189 if let Some(true) = resolve_task.await.log_err() {
1190 this.update(&mut cx, |_, cx| cx.notify()).ok();
1191 }
1192 })
1193 }
1194
1195 fn attempt_resolve_selected_completion_documentation(
1196 &mut self,
1197 provider: Option<&dyn CompletionProvider>,
1198 cx: &mut ViewContext<Editor>,
1199 ) {
1200 let settings = EditorSettings::get_global(cx);
1201 if !settings.show_completion_documentation {
1202 return;
1203 }
1204
1205 let completion_index = self.matches[self.selected_item].candidate_id;
1206 let Some(provider) = provider else {
1207 return;
1208 };
1209 let Some(documentation_resolve) = self
1210 .selected_completion_documentation_resolve_debounce
1211 .as_ref()
1212 else {
1213 return;
1214 };
1215
1216 let resolve_task = provider.resolve_completions(
1217 self.buffer.clone(),
1218 vec![completion_index],
1219 self.completions.clone(),
1220 cx,
1221 );
1222
1223 let delay_ms =
1224 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1225 let delay = Duration::from_millis(delay_ms);
1226
1227 documentation_resolve.lock().fire_new(delay, cx, |_, cx| {
1228 cx.spawn(move |this, mut cx| async move {
1229 if let Some(true) = resolve_task.await.log_err() {
1230 this.update(&mut cx, |_, cx| cx.notify()).ok();
1231 }
1232 })
1233 });
1234 }
1235
1236 fn visible(&self) -> bool {
1237 !self.matches.is_empty()
1238 }
1239
1240 fn render(
1241 &self,
1242 style: &EditorStyle,
1243 max_height: Pixels,
1244 workspace: Option<WeakView<Workspace>>,
1245 cx: &mut ViewContext<Editor>,
1246 ) -> AnyElement {
1247 let settings = EditorSettings::get_global(cx);
1248 let show_completion_documentation = settings.show_completion_documentation;
1249
1250 let widest_completion_ix = self
1251 .matches
1252 .iter()
1253 .enumerate()
1254 .max_by_key(|(_, mat)| {
1255 let completions = self.completions.read();
1256 let completion = &completions[mat.candidate_id];
1257 let documentation = &completion.documentation;
1258
1259 let mut len = completion.label.text.chars().count();
1260 if let Some(Documentation::SingleLine(text)) = documentation {
1261 if show_completion_documentation {
1262 len += text.chars().count();
1263 }
1264 }
1265
1266 len
1267 })
1268 .map(|(ix, _)| ix);
1269
1270 let completions = self.completions.clone();
1271 let matches = self.matches.clone();
1272 let selected_item = self.selected_item;
1273 let style = style.clone();
1274
1275 let multiline_docs = if show_completion_documentation {
1276 let mat = &self.matches[selected_item];
1277 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1278 Some(Documentation::MultiLinePlainText(text)) => {
1279 Some(div().child(SharedString::from(text.clone())))
1280 }
1281 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1282 Some(div().child(render_parsed_markdown(
1283 "completions_markdown",
1284 parsed,
1285 &style,
1286 workspace,
1287 cx,
1288 )))
1289 }
1290 _ => None,
1291 };
1292 multiline_docs.map(|div| {
1293 div.id("multiline_docs")
1294 .max_h(max_height)
1295 .flex_1()
1296 .px_1p5()
1297 .py_1()
1298 .min_w(px(260.))
1299 .max_w(px(640.))
1300 .w(px(500.))
1301 .overflow_y_scroll()
1302 .occlude()
1303 })
1304 } else {
1305 None
1306 };
1307
1308 let list = uniform_list(
1309 cx.view().clone(),
1310 "completions",
1311 matches.len(),
1312 move |_editor, range, cx| {
1313 let start_ix = range.start;
1314 let completions_guard = completions.read();
1315
1316 matches[range]
1317 .iter()
1318 .enumerate()
1319 .map(|(ix, mat)| {
1320 let item_ix = start_ix + ix;
1321 let candidate_id = mat.candidate_id;
1322 let completion = &completions_guard[candidate_id];
1323
1324 let documentation = if show_completion_documentation {
1325 &completion.documentation
1326 } else {
1327 &None
1328 };
1329
1330 let highlights = gpui::combine_highlights(
1331 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1332 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1333 |(range, mut highlight)| {
1334 // Ignore font weight for syntax highlighting, as we'll use it
1335 // for fuzzy matches.
1336 highlight.font_weight = None;
1337
1338 if completion.lsp_completion.deprecated.unwrap_or(false) {
1339 highlight.strikethrough = Some(StrikethroughStyle {
1340 thickness: 1.0.into(),
1341 ..Default::default()
1342 });
1343 highlight.color = Some(cx.theme().colors().text_muted);
1344 }
1345
1346 (range, highlight)
1347 },
1348 ),
1349 );
1350 let completion_label = StyledText::new(completion.label.text.clone())
1351 .with_highlights(&style.text, highlights);
1352 let documentation_label =
1353 if let Some(Documentation::SingleLine(text)) = documentation {
1354 if text.trim().is_empty() {
1355 None
1356 } else {
1357 Some(
1358 Label::new(text.clone())
1359 .ml_4()
1360 .size(LabelSize::Small)
1361 .color(Color::Muted),
1362 )
1363 }
1364 } else {
1365 None
1366 };
1367
1368 let color_swatch = completion
1369 .color()
1370 .map(|color| div().size_4().bg(color).rounded_sm());
1371
1372 div().min_w(px(220.)).max_w(px(540.)).child(
1373 ListItem::new(mat.candidate_id)
1374 .inset(true)
1375 .selected(item_ix == selected_item)
1376 .on_click(cx.listener(move |editor, _event, cx| {
1377 cx.stop_propagation();
1378 if let Some(task) = editor.confirm_completion(
1379 &ConfirmCompletion {
1380 item_ix: Some(item_ix),
1381 },
1382 cx,
1383 ) {
1384 task.detach_and_log_err(cx)
1385 }
1386 }))
1387 .start_slot::<Div>(color_swatch)
1388 .child(h_flex().overflow_hidden().child(completion_label))
1389 .end_slot::<Label>(documentation_label),
1390 )
1391 })
1392 .collect()
1393 },
1394 )
1395 .occlude()
1396 .max_h(max_height)
1397 .track_scroll(self.scroll_handle.clone())
1398 .with_width_from_item(widest_completion_ix)
1399 .with_sizing_behavior(ListSizingBehavior::Infer);
1400
1401 Popover::new()
1402 .child(list)
1403 .when_some(multiline_docs, |popover, multiline_docs| {
1404 popover.aside(multiline_docs)
1405 })
1406 .into_any_element()
1407 }
1408
1409 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1410 let mut matches = if let Some(query) = query {
1411 fuzzy::match_strings(
1412 &self.match_candidates,
1413 query,
1414 query.chars().any(|c| c.is_uppercase()),
1415 100,
1416 &Default::default(),
1417 executor,
1418 )
1419 .await
1420 } else {
1421 self.match_candidates
1422 .iter()
1423 .enumerate()
1424 .map(|(candidate_id, candidate)| StringMatch {
1425 candidate_id,
1426 score: Default::default(),
1427 positions: Default::default(),
1428 string: candidate.string.clone(),
1429 })
1430 .collect()
1431 };
1432
1433 // Remove all candidates where the query's start does not match the start of any word in the candidate
1434 if let Some(query) = query {
1435 if let Some(query_start) = query.chars().next() {
1436 matches.retain(|string_match| {
1437 split_words(&string_match.string).any(|word| {
1438 // Check that the first codepoint of the word as lowercase matches the first
1439 // codepoint of the query as lowercase
1440 word.chars()
1441 .flat_map(|codepoint| codepoint.to_lowercase())
1442 .zip(query_start.to_lowercase())
1443 .all(|(word_cp, query_cp)| word_cp == query_cp)
1444 })
1445 });
1446 }
1447 }
1448
1449 let completions = self.completions.read();
1450 if self.sort_completions {
1451 matches.sort_unstable_by_key(|mat| {
1452 // We do want to strike a balance here between what the language server tells us
1453 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1454 // `Creat` and there is a local variable called `CreateComponent`).
1455 // So what we do is: we bucket all matches into two buckets
1456 // - Strong matches
1457 // - Weak matches
1458 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1459 // and the Weak matches are the rest.
1460 //
1461 // For the strong matches, we sort by our fuzzy-finder score first and for the weak
1462 // matches, we prefer language-server sort_text first.
1463 //
1464 // The thinking behind that: we want to show strong matches first in order of relevance(fuzzy score).
1465 // Rest of the matches(weak) can be sorted as language-server expects.
1466
1467 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1468 enum MatchScore<'a> {
1469 Strong {
1470 score: Reverse<OrderedFloat<f64>>,
1471 sort_text: Option<&'a str>,
1472 sort_key: (usize, &'a str),
1473 },
1474 Weak {
1475 sort_text: Option<&'a str>,
1476 score: Reverse<OrderedFloat<f64>>,
1477 sort_key: (usize, &'a str),
1478 },
1479 }
1480
1481 let completion = &completions[mat.candidate_id];
1482 let sort_key = completion.sort_key();
1483 let sort_text = completion.lsp_completion.sort_text.as_deref();
1484 let score = Reverse(OrderedFloat(mat.score));
1485
1486 if mat.score >= 0.2 {
1487 MatchScore::Strong {
1488 score,
1489 sort_text,
1490 sort_key,
1491 }
1492 } else {
1493 MatchScore::Weak {
1494 sort_text,
1495 score,
1496 sort_key,
1497 }
1498 }
1499 });
1500 }
1501
1502 for mat in &mut matches {
1503 let completion = &completions[mat.candidate_id];
1504 mat.string.clone_from(&completion.label.text);
1505 for position in &mut mat.positions {
1506 *position += completion.label.filter_range.start;
1507 }
1508 }
1509 drop(completions);
1510
1511 self.matches = matches.into();
1512 self.selected_item = 0;
1513 }
1514}
1515
1516#[derive(Clone)]
1517struct AvailableCodeAction {
1518 excerpt_id: ExcerptId,
1519 action: CodeAction,
1520 provider: Arc<dyn CodeActionProvider>,
1521}
1522
1523#[derive(Clone)]
1524struct CodeActionContents {
1525 tasks: Option<Arc<ResolvedTasks>>,
1526 actions: Option<Arc<[AvailableCodeAction]>>,
1527}
1528
1529impl CodeActionContents {
1530 fn len(&self) -> usize {
1531 match (&self.tasks, &self.actions) {
1532 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1533 (Some(tasks), None) => tasks.templates.len(),
1534 (None, Some(actions)) => actions.len(),
1535 (None, None) => 0,
1536 }
1537 }
1538
1539 fn is_empty(&self) -> bool {
1540 match (&self.tasks, &self.actions) {
1541 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1542 (Some(tasks), None) => tasks.templates.is_empty(),
1543 (None, Some(actions)) => actions.is_empty(),
1544 (None, None) => true,
1545 }
1546 }
1547
1548 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1549 self.tasks
1550 .iter()
1551 .flat_map(|tasks| {
1552 tasks
1553 .templates
1554 .iter()
1555 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1556 })
1557 .chain(self.actions.iter().flat_map(|actions| {
1558 actions.iter().map(|available| CodeActionsItem::CodeAction {
1559 excerpt_id: available.excerpt_id,
1560 action: available.action.clone(),
1561 provider: available.provider.clone(),
1562 })
1563 }))
1564 }
1565 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1566 match (&self.tasks, &self.actions) {
1567 (Some(tasks), Some(actions)) => {
1568 if index < tasks.templates.len() {
1569 tasks
1570 .templates
1571 .get(index)
1572 .cloned()
1573 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1574 } else {
1575 actions.get(index - tasks.templates.len()).map(|available| {
1576 CodeActionsItem::CodeAction {
1577 excerpt_id: available.excerpt_id,
1578 action: available.action.clone(),
1579 provider: available.provider.clone(),
1580 }
1581 })
1582 }
1583 }
1584 (Some(tasks), None) => tasks
1585 .templates
1586 .get(index)
1587 .cloned()
1588 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1589 (None, Some(actions)) => {
1590 actions
1591 .get(index)
1592 .map(|available| CodeActionsItem::CodeAction {
1593 excerpt_id: available.excerpt_id,
1594 action: available.action.clone(),
1595 provider: available.provider.clone(),
1596 })
1597 }
1598 (None, None) => None,
1599 }
1600 }
1601}
1602
1603#[allow(clippy::large_enum_variant)]
1604#[derive(Clone)]
1605enum CodeActionsItem {
1606 Task(TaskSourceKind, ResolvedTask),
1607 CodeAction {
1608 excerpt_id: ExcerptId,
1609 action: CodeAction,
1610 provider: Arc<dyn CodeActionProvider>,
1611 },
1612}
1613
1614impl CodeActionsItem {
1615 fn as_task(&self) -> Option<&ResolvedTask> {
1616 let Self::Task(_, task) = self else {
1617 return None;
1618 };
1619 Some(task)
1620 }
1621 fn as_code_action(&self) -> Option<&CodeAction> {
1622 let Self::CodeAction { action, .. } = self else {
1623 return None;
1624 };
1625 Some(action)
1626 }
1627 fn label(&self) -> String {
1628 match self {
1629 Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
1630 Self::Task(_, task) => task.resolved_label.clone(),
1631 }
1632 }
1633}
1634
1635struct CodeActionsMenu {
1636 actions: CodeActionContents,
1637 buffer: Model<Buffer>,
1638 selected_item: usize,
1639 scroll_handle: UniformListScrollHandle,
1640 deployed_from_indicator: Option<DisplayRow>,
1641}
1642
1643impl CodeActionsMenu {
1644 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1645 self.selected_item = 0;
1646 self.scroll_handle
1647 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1648 cx.notify()
1649 }
1650
1651 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1652 if self.selected_item > 0 {
1653 self.selected_item -= 1;
1654 } else {
1655 self.selected_item = self.actions.len() - 1;
1656 }
1657 self.scroll_handle
1658 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1659 cx.notify();
1660 }
1661
1662 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1663 if self.selected_item + 1 < self.actions.len() {
1664 self.selected_item += 1;
1665 } else {
1666 self.selected_item = 0;
1667 }
1668 self.scroll_handle
1669 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1670 cx.notify();
1671 }
1672
1673 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1674 self.selected_item = self.actions.len() - 1;
1675 self.scroll_handle
1676 .scroll_to_item(self.selected_item, ScrollStrategy::Top);
1677 cx.notify()
1678 }
1679
1680 fn visible(&self) -> bool {
1681 !self.actions.is_empty()
1682 }
1683
1684 fn render(
1685 &self,
1686 cursor_position: DisplayPoint,
1687 _style: &EditorStyle,
1688 max_height: Pixels,
1689 cx: &mut ViewContext<Editor>,
1690 ) -> (ContextMenuOrigin, AnyElement) {
1691 let actions = self.actions.clone();
1692 let selected_item = self.selected_item;
1693 let element = uniform_list(
1694 cx.view().clone(),
1695 "code_actions_menu",
1696 self.actions.len(),
1697 move |_this, range, cx| {
1698 actions
1699 .iter()
1700 .skip(range.start)
1701 .take(range.end - range.start)
1702 .enumerate()
1703 .map(|(ix, action)| {
1704 let item_ix = range.start + ix;
1705 let selected = selected_item == item_ix;
1706 let colors = cx.theme().colors();
1707 div()
1708 .px_1()
1709 .rounded_md()
1710 .text_color(colors.text)
1711 .when(selected, |style| {
1712 style
1713 .bg(colors.element_active)
1714 .text_color(colors.text_accent)
1715 })
1716 .hover(|style| {
1717 style
1718 .bg(colors.element_hover)
1719 .text_color(colors.text_accent)
1720 })
1721 .whitespace_nowrap()
1722 .when_some(action.as_code_action(), |this, action| {
1723 this.on_mouse_down(
1724 MouseButton::Left,
1725 cx.listener(move |editor, _, cx| {
1726 cx.stop_propagation();
1727 if let Some(task) = editor.confirm_code_action(
1728 &ConfirmCodeAction {
1729 item_ix: Some(item_ix),
1730 },
1731 cx,
1732 ) {
1733 task.detach_and_log_err(cx)
1734 }
1735 }),
1736 )
1737 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1738 .child(SharedString::from(action.lsp_action.title.clone()))
1739 })
1740 .when_some(action.as_task(), |this, task| {
1741 this.on_mouse_down(
1742 MouseButton::Left,
1743 cx.listener(move |editor, _, cx| {
1744 cx.stop_propagation();
1745 if let Some(task) = editor.confirm_code_action(
1746 &ConfirmCodeAction {
1747 item_ix: Some(item_ix),
1748 },
1749 cx,
1750 ) {
1751 task.detach_and_log_err(cx)
1752 }
1753 }),
1754 )
1755 .child(SharedString::from(task.resolved_label.clone()))
1756 })
1757 })
1758 .collect()
1759 },
1760 )
1761 .elevation_1(cx)
1762 .p_1()
1763 .max_h(max_height)
1764 .occlude()
1765 .track_scroll(self.scroll_handle.clone())
1766 .with_width_from_item(
1767 self.actions
1768 .iter()
1769 .enumerate()
1770 .max_by_key(|(_, action)| match action {
1771 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1772 CodeActionsItem::CodeAction { action, .. } => {
1773 action.lsp_action.title.chars().count()
1774 }
1775 })
1776 .map(|(ix, _)| ix),
1777 )
1778 .with_sizing_behavior(ListSizingBehavior::Infer)
1779 .into_any_element();
1780
1781 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1782 ContextMenuOrigin::GutterIndicator(row)
1783 } else {
1784 ContextMenuOrigin::EditorPoint(cursor_position)
1785 };
1786
1787 (cursor_position, element)
1788 }
1789}
1790
1791#[derive(Debug)]
1792struct ActiveDiagnosticGroup {
1793 primary_range: Range<Anchor>,
1794 primary_message: String,
1795 group_id: usize,
1796 blocks: HashMap<CustomBlockId, Diagnostic>,
1797 is_valid: bool,
1798}
1799
1800#[derive(Serialize, Deserialize, Clone, Debug)]
1801pub struct ClipboardSelection {
1802 pub len: usize,
1803 pub is_entire_line: bool,
1804 pub first_line_indent: u32,
1805}
1806
1807#[derive(Debug)]
1808pub(crate) struct NavigationData {
1809 cursor_anchor: Anchor,
1810 cursor_position: Point,
1811 scroll_anchor: ScrollAnchor,
1812 scroll_top_row: u32,
1813}
1814
1815#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1816pub enum GotoDefinitionKind {
1817 Symbol,
1818 Declaration,
1819 Type,
1820 Implementation,
1821}
1822
1823#[derive(Debug, Clone)]
1824enum InlayHintRefreshReason {
1825 Toggle(bool),
1826 SettingsChange(InlayHintSettings),
1827 NewLinesShown,
1828 BufferEdited(HashSet<Arc<Language>>),
1829 RefreshRequested,
1830 ExcerptsRemoved(Vec<ExcerptId>),
1831}
1832
1833impl InlayHintRefreshReason {
1834 fn description(&self) -> &'static str {
1835 match self {
1836 Self::Toggle(_) => "toggle",
1837 Self::SettingsChange(_) => "settings change",
1838 Self::NewLinesShown => "new lines shown",
1839 Self::BufferEdited(_) => "buffer edited",
1840 Self::RefreshRequested => "refresh requested",
1841 Self::ExcerptsRemoved(_) => "excerpts removed",
1842 }
1843 }
1844}
1845
1846pub(crate) struct FocusedBlock {
1847 id: BlockId,
1848 focus_handle: WeakFocusHandle,
1849}
1850
1851#[derive(Clone)]
1852struct JumpData {
1853 excerpt_id: ExcerptId,
1854 position: Point,
1855 anchor: text::Anchor,
1856 path: Option<project::ProjectPath>,
1857 line_offset_from_top: u32,
1858}
1859
1860impl Editor {
1861 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1862 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1863 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1864 Self::new(
1865 EditorMode::SingleLine { auto_width: false },
1866 buffer,
1867 None,
1868 false,
1869 cx,
1870 )
1871 }
1872
1873 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1874 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1875 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1876 Self::new(EditorMode::Full, buffer, None, false, cx)
1877 }
1878
1879 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1880 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1881 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1882 Self::new(
1883 EditorMode::SingleLine { auto_width: true },
1884 buffer,
1885 None,
1886 false,
1887 cx,
1888 )
1889 }
1890
1891 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1892 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1893 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1894 Self::new(
1895 EditorMode::AutoHeight { max_lines },
1896 buffer,
1897 None,
1898 false,
1899 cx,
1900 )
1901 }
1902
1903 pub fn for_buffer(
1904 buffer: Model<Buffer>,
1905 project: Option<Model<Project>>,
1906 cx: &mut ViewContext<Self>,
1907 ) -> Self {
1908 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1909 Self::new(EditorMode::Full, buffer, project, false, cx)
1910 }
1911
1912 pub fn for_multibuffer(
1913 buffer: Model<MultiBuffer>,
1914 project: Option<Model<Project>>,
1915 show_excerpt_controls: bool,
1916 cx: &mut ViewContext<Self>,
1917 ) -> Self {
1918 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1919 }
1920
1921 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1922 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1923 let mut clone = Self::new(
1924 self.mode,
1925 self.buffer.clone(),
1926 self.project.clone(),
1927 show_excerpt_controls,
1928 cx,
1929 );
1930 self.display_map.update(cx, |display_map, cx| {
1931 let snapshot = display_map.snapshot(cx);
1932 clone.display_map.update(cx, |display_map, cx| {
1933 display_map.set_state(&snapshot, cx);
1934 });
1935 });
1936 clone.selections.clone_state(&self.selections);
1937 clone.scroll_manager.clone_state(&self.scroll_manager);
1938 clone.searchable = self.searchable;
1939 clone
1940 }
1941
1942 pub fn new(
1943 mode: EditorMode,
1944 buffer: Model<MultiBuffer>,
1945 project: Option<Model<Project>>,
1946 show_excerpt_controls: bool,
1947 cx: &mut ViewContext<Self>,
1948 ) -> Self {
1949 let style = cx.text_style();
1950 let font_size = style.font_size.to_pixels(cx.rem_size());
1951 let editor = cx.view().downgrade();
1952 let fold_placeholder = FoldPlaceholder {
1953 constrain_width: true,
1954 render: Arc::new(move |fold_id, fold_range, cx| {
1955 let editor = editor.clone();
1956 div()
1957 .id(fold_id)
1958 .bg(cx.theme().colors().ghost_element_background)
1959 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1960 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1961 .rounded_sm()
1962 .size_full()
1963 .cursor_pointer()
1964 .child("⋯")
1965 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1966 .on_click(move |_, cx| {
1967 editor
1968 .update(cx, |editor, cx| {
1969 editor.unfold_ranges(
1970 &[fold_range.start..fold_range.end],
1971 true,
1972 false,
1973 cx,
1974 );
1975 cx.stop_propagation();
1976 })
1977 .ok();
1978 })
1979 .into_any()
1980 }),
1981 merge_adjacent: true,
1982 ..Default::default()
1983 };
1984 let display_map = cx.new_model(|cx| {
1985 DisplayMap::new(
1986 buffer.clone(),
1987 style.font(),
1988 font_size,
1989 None,
1990 show_excerpt_controls,
1991 FILE_HEADER_HEIGHT,
1992 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1993 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1994 fold_placeholder,
1995 cx,
1996 )
1997 });
1998
1999 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
2000
2001 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
2002
2003 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
2004 .then(|| language_settings::SoftWrap::None);
2005
2006 let mut project_subscriptions = Vec::new();
2007 if mode == EditorMode::Full {
2008 if let Some(project) = project.as_ref() {
2009 if buffer.read(cx).is_singleton() {
2010 project_subscriptions.push(cx.observe(project, |_, _, cx| {
2011 cx.emit(EditorEvent::TitleChanged);
2012 }));
2013 }
2014 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
2015 if let project::Event::RefreshInlayHints = event {
2016 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
2017 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
2018 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
2019 let focus_handle = editor.focus_handle(cx);
2020 if focus_handle.is_focused(cx) {
2021 let snapshot = buffer.read(cx).snapshot();
2022 for (range, snippet) in snippet_edits {
2023 let editor_range =
2024 language::range_from_lsp(*range).to_offset(&snapshot);
2025 editor
2026 .insert_snippet(&[editor_range], snippet.clone(), cx)
2027 .ok();
2028 }
2029 }
2030 }
2031 }
2032 }));
2033 if let Some(task_inventory) = project
2034 .read(cx)
2035 .task_store()
2036 .read(cx)
2037 .task_inventory()
2038 .cloned()
2039 {
2040 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
2041 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
2042 }));
2043 }
2044 }
2045 }
2046
2047 let inlay_hint_settings = inlay_hint_settings(
2048 selections.newest_anchor().head(),
2049 &buffer.read(cx).snapshot(cx),
2050 cx,
2051 );
2052 let focus_handle = cx.focus_handle();
2053 cx.on_focus(&focus_handle, Self::handle_focus).detach();
2054 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
2055 .detach();
2056 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
2057 .detach();
2058 cx.on_blur(&focus_handle, Self::handle_blur).detach();
2059
2060 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
2061 Some(false)
2062 } else {
2063 None
2064 };
2065
2066 let mut code_action_providers = Vec::new();
2067 if let Some(project) = project.clone() {
2068 code_action_providers.push(Arc::new(project) as Arc<_>);
2069 }
2070
2071 let mut this = Self {
2072 focus_handle,
2073 show_cursor_when_unfocused: false,
2074 last_focused_descendant: None,
2075 buffer: buffer.clone(),
2076 display_map: display_map.clone(),
2077 selections,
2078 scroll_manager: ScrollManager::new(cx),
2079 columnar_selection_tail: None,
2080 add_selections_state: None,
2081 select_next_state: None,
2082 select_prev_state: None,
2083 selection_history: Default::default(),
2084 autoclose_regions: Default::default(),
2085 snippet_stack: Default::default(),
2086 select_larger_syntax_node_stack: Vec::new(),
2087 ime_transaction: Default::default(),
2088 active_diagnostics: None,
2089 soft_wrap_mode_override,
2090 completion_provider: project.clone().map(|project| Box::new(project) as _),
2091 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
2092 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
2093 project,
2094 blink_manager: blink_manager.clone(),
2095 show_local_selections: true,
2096 mode,
2097 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
2098 show_gutter: mode == EditorMode::Full,
2099 show_line_numbers: None,
2100 use_relative_line_numbers: None,
2101 show_git_diff_gutter: None,
2102 show_code_actions: None,
2103 show_runnables: None,
2104 show_wrap_guides: None,
2105 show_indent_guides,
2106 placeholder_text: None,
2107 highlight_order: 0,
2108 highlighted_rows: HashMap::default(),
2109 background_highlights: Default::default(),
2110 gutter_highlights: TreeMap::default(),
2111 scrollbar_marker_state: ScrollbarMarkerState::default(),
2112 active_indent_guides_state: ActiveIndentGuidesState::default(),
2113 nav_history: None,
2114 context_menu: RwLock::new(None),
2115 mouse_context_menu: None,
2116 hunk_controls_menu_handle: PopoverMenuHandle::default(),
2117 completion_tasks: Default::default(),
2118 signature_help_state: SignatureHelpState::default(),
2119 auto_signature_help: None,
2120 find_all_references_task_sources: Vec::new(),
2121 next_completion_id: 0,
2122 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
2123 next_inlay_id: 0,
2124 code_action_providers,
2125 available_code_actions: Default::default(),
2126 code_actions_task: Default::default(),
2127 document_highlights_task: Default::default(),
2128 linked_editing_range_task: Default::default(),
2129 pending_rename: Default::default(),
2130 searchable: true,
2131 cursor_shape: EditorSettings::get_global(cx)
2132 .cursor_shape
2133 .unwrap_or_default(),
2134 current_line_highlight: None,
2135 autoindent_mode: Some(AutoindentMode::EachLine),
2136 collapse_matches: false,
2137 workspace: None,
2138 input_enabled: true,
2139 use_modal_editing: mode == EditorMode::Full,
2140 read_only: false,
2141 use_autoclose: true,
2142 use_auto_surround: true,
2143 auto_replace_emoji_shortcode: false,
2144 leader_peer_id: None,
2145 remote_id: None,
2146 hover_state: Default::default(),
2147 hovered_link_state: Default::default(),
2148 inline_completion_provider: None,
2149 active_inline_completion: None,
2150 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
2151 expanded_hunks: ExpandedHunks::default(),
2152 gutter_hovered: false,
2153 pixel_position_of_newest_cursor: None,
2154 last_bounds: None,
2155 expect_bounds_change: None,
2156 gutter_dimensions: GutterDimensions::default(),
2157 style: None,
2158 show_cursor_names: false,
2159 hovered_cursors: Default::default(),
2160 next_editor_action_id: EditorActionId::default(),
2161 editor_actions: Rc::default(),
2162 show_inline_completions_override: None,
2163 enable_inline_completions: true,
2164 custom_context_menu: None,
2165 show_git_blame_gutter: false,
2166 show_git_blame_inline: false,
2167 show_selection_menu: None,
2168 show_git_blame_inline_delay_task: None,
2169 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
2170 serialize_dirty_buffers: ProjectSettings::get_global(cx)
2171 .session
2172 .restore_unsaved_buffers,
2173 blame: None,
2174 blame_subscription: None,
2175 tasks: Default::default(),
2176 _subscriptions: vec![
2177 cx.observe(&buffer, Self::on_buffer_changed),
2178 cx.subscribe(&buffer, Self::on_buffer_event),
2179 cx.observe(&display_map, Self::on_display_map_changed),
2180 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
2181 cx.observe_global::<SettingsStore>(Self::settings_changed),
2182 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
2183 cx.observe_window_activation(|editor, cx| {
2184 let active = cx.is_window_active();
2185 editor.blink_manager.update(cx, |blink_manager, cx| {
2186 if active {
2187 blink_manager.enable(cx);
2188 } else {
2189 blink_manager.disable(cx);
2190 }
2191 });
2192 }),
2193 ],
2194 tasks_update_task: None,
2195 linked_edit_ranges: Default::default(),
2196 previous_search_ranges: None,
2197 breadcrumb_header: None,
2198 focused_block: None,
2199 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
2200 addons: HashMap::default(),
2201 _scroll_cursor_center_top_bottom_task: Task::ready(()),
2202 text_style_refinement: None,
2203 };
2204 this.tasks_update_task = Some(this.refresh_runnables(cx));
2205 this._subscriptions.extend(project_subscriptions);
2206
2207 this.end_selection(cx);
2208 this.scroll_manager.show_scrollbar(cx);
2209
2210 if mode == EditorMode::Full {
2211 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
2212 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2213
2214 if this.git_blame_inline_enabled {
2215 this.git_blame_inline_enabled = true;
2216 this.start_git_blame_inline(false, cx);
2217 }
2218 }
2219
2220 this.report_editor_event("open", None, cx);
2221 this
2222 }
2223
2224 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
2225 self.mouse_context_menu
2226 .as_ref()
2227 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
2228 }
2229
2230 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
2231 let mut key_context = KeyContext::new_with_defaults();
2232 key_context.add("Editor");
2233 let mode = match self.mode {
2234 EditorMode::SingleLine { .. } => "single_line",
2235 EditorMode::AutoHeight { .. } => "auto_height",
2236 EditorMode::Full => "full",
2237 };
2238
2239 if EditorSettings::jupyter_enabled(cx) {
2240 key_context.add("jupyter");
2241 }
2242
2243 key_context.set("mode", mode);
2244 if self.pending_rename.is_some() {
2245 key_context.add("renaming");
2246 }
2247 if self.context_menu_visible() {
2248 match self.context_menu.read().as_ref() {
2249 Some(ContextMenu::Completions(_)) => {
2250 key_context.add("menu");
2251 key_context.add("showing_completions")
2252 }
2253 Some(ContextMenu::CodeActions(_)) => {
2254 key_context.add("menu");
2255 key_context.add("showing_code_actions")
2256 }
2257 None => {}
2258 }
2259 }
2260
2261 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2262 if !self.focus_handle(cx).contains_focused(cx)
2263 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2264 {
2265 for addon in self.addons.values() {
2266 addon.extend_key_context(&mut key_context, cx)
2267 }
2268 }
2269
2270 if let Some(extension) = self
2271 .buffer
2272 .read(cx)
2273 .as_singleton()
2274 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2275 {
2276 key_context.set("extension", extension.to_string());
2277 }
2278
2279 if self.has_active_inline_completion(cx) {
2280 key_context.add("copilot_suggestion");
2281 key_context.add("inline_completion");
2282 }
2283
2284 key_context
2285 }
2286
2287 pub fn new_file(
2288 workspace: &mut Workspace,
2289 _: &workspace::NewFile,
2290 cx: &mut ViewContext<Workspace>,
2291 ) {
2292 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2293 "Failed to create buffer",
2294 cx,
2295 |e, _| match e.error_code() {
2296 ErrorCode::RemoteUpgradeRequired => Some(format!(
2297 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2298 e.error_tag("required").unwrap_or("the latest version")
2299 )),
2300 _ => None,
2301 },
2302 );
2303 }
2304
2305 pub fn new_in_workspace(
2306 workspace: &mut Workspace,
2307 cx: &mut ViewContext<Workspace>,
2308 ) -> Task<Result<View<Editor>>> {
2309 let project = workspace.project().clone();
2310 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2311
2312 cx.spawn(|workspace, mut cx| async move {
2313 let buffer = create.await?;
2314 workspace.update(&mut cx, |workspace, cx| {
2315 let editor =
2316 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2317 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2318 editor
2319 })
2320 })
2321 }
2322
2323 fn new_file_vertical(
2324 workspace: &mut Workspace,
2325 _: &workspace::NewFileSplitVertical,
2326 cx: &mut ViewContext<Workspace>,
2327 ) {
2328 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2329 }
2330
2331 fn new_file_horizontal(
2332 workspace: &mut Workspace,
2333 _: &workspace::NewFileSplitHorizontal,
2334 cx: &mut ViewContext<Workspace>,
2335 ) {
2336 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2337 }
2338
2339 fn new_file_in_direction(
2340 workspace: &mut Workspace,
2341 direction: SplitDirection,
2342 cx: &mut ViewContext<Workspace>,
2343 ) {
2344 let project = workspace.project().clone();
2345 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2346
2347 cx.spawn(|workspace, mut cx| async move {
2348 let buffer = create.await?;
2349 workspace.update(&mut cx, move |workspace, cx| {
2350 workspace.split_item(
2351 direction,
2352 Box::new(
2353 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2354 ),
2355 cx,
2356 )
2357 })?;
2358 anyhow::Ok(())
2359 })
2360 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2361 ErrorCode::RemoteUpgradeRequired => Some(format!(
2362 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2363 e.error_tag("required").unwrap_or("the latest version")
2364 )),
2365 _ => None,
2366 });
2367 }
2368
2369 pub fn leader_peer_id(&self) -> Option<PeerId> {
2370 self.leader_peer_id
2371 }
2372
2373 pub fn buffer(&self) -> &Model<MultiBuffer> {
2374 &self.buffer
2375 }
2376
2377 pub fn workspace(&self) -> Option<View<Workspace>> {
2378 self.workspace.as_ref()?.0.upgrade()
2379 }
2380
2381 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2382 self.buffer().read(cx).title(cx)
2383 }
2384
2385 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2386 let git_blame_gutter_max_author_length = self
2387 .render_git_blame_gutter(cx)
2388 .then(|| {
2389 if let Some(blame) = self.blame.as_ref() {
2390 let max_author_length =
2391 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2392 Some(max_author_length)
2393 } else {
2394 None
2395 }
2396 })
2397 .flatten();
2398
2399 EditorSnapshot {
2400 mode: self.mode,
2401 show_gutter: self.show_gutter,
2402 show_line_numbers: self.show_line_numbers,
2403 show_git_diff_gutter: self.show_git_diff_gutter,
2404 show_code_actions: self.show_code_actions,
2405 show_runnables: self.show_runnables,
2406 git_blame_gutter_max_author_length,
2407 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2408 scroll_anchor: self.scroll_manager.anchor(),
2409 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2410 placeholder_text: self.placeholder_text.clone(),
2411 is_focused: self.focus_handle.is_focused(cx),
2412 current_line_highlight: self
2413 .current_line_highlight
2414 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2415 gutter_hovered: self.gutter_hovered,
2416 }
2417 }
2418
2419 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2420 self.buffer.read(cx).language_at(point, cx)
2421 }
2422
2423 pub fn file_at<T: ToOffset>(
2424 &self,
2425 point: T,
2426 cx: &AppContext,
2427 ) -> Option<Arc<dyn language::File>> {
2428 self.buffer.read(cx).read(cx).file_at(point).cloned()
2429 }
2430
2431 pub fn active_excerpt(
2432 &self,
2433 cx: &AppContext,
2434 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2435 self.buffer
2436 .read(cx)
2437 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2438 }
2439
2440 pub fn mode(&self) -> EditorMode {
2441 self.mode
2442 }
2443
2444 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2445 self.collaboration_hub.as_deref()
2446 }
2447
2448 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2449 self.collaboration_hub = Some(hub);
2450 }
2451
2452 pub fn set_custom_context_menu(
2453 &mut self,
2454 f: impl 'static
2455 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2456 ) {
2457 self.custom_context_menu = Some(Box::new(f))
2458 }
2459
2460 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2461 self.completion_provider = provider;
2462 }
2463
2464 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2465 self.semantics_provider.clone()
2466 }
2467
2468 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2469 self.semantics_provider = provider;
2470 }
2471
2472 pub fn set_inline_completion_provider<T>(
2473 &mut self,
2474 provider: Option<Model<T>>,
2475 cx: &mut ViewContext<Self>,
2476 ) where
2477 T: InlineCompletionProvider,
2478 {
2479 self.inline_completion_provider =
2480 provider.map(|provider| RegisteredInlineCompletionProvider {
2481 _subscription: cx.observe(&provider, |this, _, cx| {
2482 if this.focus_handle.is_focused(cx) {
2483 this.update_visible_inline_completion(cx);
2484 }
2485 }),
2486 provider: Arc::new(provider),
2487 });
2488 self.refresh_inline_completion(false, false, cx);
2489 }
2490
2491 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2492 self.placeholder_text.as_deref()
2493 }
2494
2495 pub fn set_placeholder_text(
2496 &mut self,
2497 placeholder_text: impl Into<Arc<str>>,
2498 cx: &mut ViewContext<Self>,
2499 ) {
2500 let placeholder_text = Some(placeholder_text.into());
2501 if self.placeholder_text != placeholder_text {
2502 self.placeholder_text = placeholder_text;
2503 cx.notify();
2504 }
2505 }
2506
2507 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2508 self.cursor_shape = cursor_shape;
2509
2510 // Disrupt blink for immediate user feedback that the cursor shape has changed
2511 self.blink_manager.update(cx, BlinkManager::show_cursor);
2512
2513 cx.notify();
2514 }
2515
2516 pub fn set_current_line_highlight(
2517 &mut self,
2518 current_line_highlight: Option<CurrentLineHighlight>,
2519 ) {
2520 self.current_line_highlight = current_line_highlight;
2521 }
2522
2523 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2524 self.collapse_matches = collapse_matches;
2525 }
2526
2527 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2528 if self.collapse_matches {
2529 return range.start..range.start;
2530 }
2531 range.clone()
2532 }
2533
2534 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2535 if self.display_map.read(cx).clip_at_line_ends != clip {
2536 self.display_map
2537 .update(cx, |map, _| map.clip_at_line_ends = clip);
2538 }
2539 }
2540
2541 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2542 self.input_enabled = input_enabled;
2543 }
2544
2545 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2546 self.enable_inline_completions = enabled;
2547 }
2548
2549 pub fn set_autoindent(&mut self, autoindent: bool) {
2550 if autoindent {
2551 self.autoindent_mode = Some(AutoindentMode::EachLine);
2552 } else {
2553 self.autoindent_mode = None;
2554 }
2555 }
2556
2557 pub fn read_only(&self, cx: &AppContext) -> bool {
2558 self.read_only || self.buffer.read(cx).read_only()
2559 }
2560
2561 pub fn set_read_only(&mut self, read_only: bool) {
2562 self.read_only = read_only;
2563 }
2564
2565 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2566 self.use_autoclose = autoclose;
2567 }
2568
2569 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2570 self.use_auto_surround = auto_surround;
2571 }
2572
2573 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2574 self.auto_replace_emoji_shortcode = auto_replace;
2575 }
2576
2577 pub fn toggle_inline_completions(
2578 &mut self,
2579 _: &ToggleInlineCompletions,
2580 cx: &mut ViewContext<Self>,
2581 ) {
2582 if self.show_inline_completions_override.is_some() {
2583 self.set_show_inline_completions(None, cx);
2584 } else {
2585 let cursor = self.selections.newest_anchor().head();
2586 if let Some((buffer, cursor_buffer_position)) =
2587 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2588 {
2589 let show_inline_completions =
2590 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2591 self.set_show_inline_completions(Some(show_inline_completions), cx);
2592 }
2593 }
2594 }
2595
2596 pub fn set_show_inline_completions(
2597 &mut self,
2598 show_inline_completions: Option<bool>,
2599 cx: &mut ViewContext<Self>,
2600 ) {
2601 self.show_inline_completions_override = show_inline_completions;
2602 self.refresh_inline_completion(false, true, cx);
2603 }
2604
2605 fn should_show_inline_completions(
2606 &self,
2607 buffer: &Model<Buffer>,
2608 buffer_position: language::Anchor,
2609 cx: &AppContext,
2610 ) -> bool {
2611 if !self.snippet_stack.is_empty() {
2612 return false;
2613 }
2614
2615 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
2616 return false;
2617 }
2618
2619 if let Some(provider) = self.inline_completion_provider() {
2620 if let Some(show_inline_completions) = self.show_inline_completions_override {
2621 show_inline_completions
2622 } else {
2623 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2624 }
2625 } else {
2626 false
2627 }
2628 }
2629
2630 fn inline_completions_disabled_in_scope(
2631 &self,
2632 buffer: &Model<Buffer>,
2633 buffer_position: language::Anchor,
2634 cx: &AppContext,
2635 ) -> bool {
2636 let snapshot = buffer.read(cx).snapshot();
2637 let settings = snapshot.settings_at(buffer_position, cx);
2638
2639 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2640 return false;
2641 };
2642
2643 scope.override_name().map_or(false, |scope_name| {
2644 settings
2645 .inline_completions_disabled_in
2646 .iter()
2647 .any(|s| s == scope_name)
2648 })
2649 }
2650
2651 pub fn set_use_modal_editing(&mut self, to: bool) {
2652 self.use_modal_editing = to;
2653 }
2654
2655 pub fn use_modal_editing(&self) -> bool {
2656 self.use_modal_editing
2657 }
2658
2659 fn selections_did_change(
2660 &mut self,
2661 local: bool,
2662 old_cursor_position: &Anchor,
2663 show_completions: bool,
2664 cx: &mut ViewContext<Self>,
2665 ) {
2666 cx.invalidate_character_coordinates();
2667
2668 // Copy selections to primary selection buffer
2669 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2670 if local {
2671 let selections = self.selections.all::<usize>(cx);
2672 let buffer_handle = self.buffer.read(cx).read(cx);
2673
2674 let mut text = String::new();
2675 for (index, selection) in selections.iter().enumerate() {
2676 let text_for_selection = buffer_handle
2677 .text_for_range(selection.start..selection.end)
2678 .collect::<String>();
2679
2680 text.push_str(&text_for_selection);
2681 if index != selections.len() - 1 {
2682 text.push('\n');
2683 }
2684 }
2685
2686 if !text.is_empty() {
2687 cx.write_to_primary(ClipboardItem::new_string(text));
2688 }
2689 }
2690
2691 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2692 self.buffer.update(cx, |buffer, cx| {
2693 buffer.set_active_selections(
2694 &self.selections.disjoint_anchors(),
2695 self.selections.line_mode,
2696 self.cursor_shape,
2697 cx,
2698 )
2699 });
2700 }
2701 let display_map = self
2702 .display_map
2703 .update(cx, |display_map, cx| display_map.snapshot(cx));
2704 let buffer = &display_map.buffer_snapshot;
2705 self.add_selections_state = None;
2706 self.select_next_state = None;
2707 self.select_prev_state = None;
2708 self.select_larger_syntax_node_stack.clear();
2709 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2710 self.snippet_stack
2711 .invalidate(&self.selections.disjoint_anchors(), buffer);
2712 self.take_rename(false, cx);
2713
2714 let new_cursor_position = self.selections.newest_anchor().head();
2715
2716 self.push_to_nav_history(
2717 *old_cursor_position,
2718 Some(new_cursor_position.to_point(buffer)),
2719 cx,
2720 );
2721
2722 if local {
2723 let new_cursor_position = self.selections.newest_anchor().head();
2724 let mut context_menu = self.context_menu.write();
2725 let completion_menu = match context_menu.as_ref() {
2726 Some(ContextMenu::Completions(menu)) => Some(menu),
2727
2728 _ => {
2729 *context_menu = None;
2730 None
2731 }
2732 };
2733
2734 if let Some(completion_menu) = completion_menu {
2735 let cursor_position = new_cursor_position.to_offset(buffer);
2736 let (word_range, kind) =
2737 buffer.surrounding_word(completion_menu.initial_position, true);
2738 if kind == Some(CharKind::Word)
2739 && word_range.to_inclusive().contains(&cursor_position)
2740 {
2741 let mut completion_menu = completion_menu.clone();
2742 drop(context_menu);
2743
2744 let query = Self::completion_query(buffer, cursor_position);
2745 cx.spawn(move |this, mut cx| async move {
2746 completion_menu
2747 .filter(query.as_deref(), cx.background_executor().clone())
2748 .await;
2749
2750 this.update(&mut cx, |this, cx| {
2751 let mut context_menu = this.context_menu.write();
2752 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2753 return;
2754 };
2755
2756 if menu.id > completion_menu.id {
2757 return;
2758 }
2759
2760 *context_menu = Some(ContextMenu::Completions(completion_menu));
2761 drop(context_menu);
2762 cx.notify();
2763 })
2764 })
2765 .detach();
2766
2767 if show_completions {
2768 self.show_completions(&ShowCompletions { trigger: None }, cx);
2769 }
2770 } else {
2771 drop(context_menu);
2772 self.hide_context_menu(cx);
2773 }
2774 } else {
2775 drop(context_menu);
2776 }
2777
2778 hide_hover(self, cx);
2779
2780 if old_cursor_position.to_display_point(&display_map).row()
2781 != new_cursor_position.to_display_point(&display_map).row()
2782 {
2783 self.available_code_actions.take();
2784 }
2785 self.refresh_code_actions(cx);
2786 self.refresh_document_highlights(cx);
2787 refresh_matching_bracket_highlights(self, cx);
2788 self.discard_inline_completion(false, cx);
2789 linked_editing_ranges::refresh_linked_ranges(self, cx);
2790 if self.git_blame_inline_enabled {
2791 self.start_inline_blame_timer(cx);
2792 }
2793 }
2794
2795 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2796 cx.emit(EditorEvent::SelectionsChanged { local });
2797
2798 if self.selections.disjoint_anchors().len() == 1 {
2799 cx.emit(SearchEvent::ActiveMatchChanged)
2800 }
2801 cx.notify();
2802 }
2803
2804 pub fn change_selections<R>(
2805 &mut self,
2806 autoscroll: Option<Autoscroll>,
2807 cx: &mut ViewContext<Self>,
2808 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2809 ) -> R {
2810 self.change_selections_inner(autoscroll, true, cx, change)
2811 }
2812
2813 pub fn change_selections_inner<R>(
2814 &mut self,
2815 autoscroll: Option<Autoscroll>,
2816 request_completions: bool,
2817 cx: &mut ViewContext<Self>,
2818 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2819 ) -> R {
2820 let old_cursor_position = self.selections.newest_anchor().head();
2821 self.push_to_selection_history();
2822
2823 let (changed, result) = self.selections.change_with(cx, change);
2824
2825 if changed {
2826 if let Some(autoscroll) = autoscroll {
2827 self.request_autoscroll(autoscroll, cx);
2828 }
2829 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2830
2831 if self.should_open_signature_help_automatically(
2832 &old_cursor_position,
2833 self.signature_help_state.backspace_pressed(),
2834 cx,
2835 ) {
2836 self.show_signature_help(&ShowSignatureHelp, cx);
2837 }
2838 self.signature_help_state.set_backspace_pressed(false);
2839 }
2840
2841 result
2842 }
2843
2844 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2845 where
2846 I: IntoIterator<Item = (Range<S>, T)>,
2847 S: ToOffset,
2848 T: Into<Arc<str>>,
2849 {
2850 if self.read_only(cx) {
2851 return;
2852 }
2853
2854 self.buffer
2855 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2856 }
2857
2858 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2859 where
2860 I: IntoIterator<Item = (Range<S>, T)>,
2861 S: ToOffset,
2862 T: Into<Arc<str>>,
2863 {
2864 if self.read_only(cx) {
2865 return;
2866 }
2867
2868 self.buffer.update(cx, |buffer, cx| {
2869 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2870 });
2871 }
2872
2873 pub fn edit_with_block_indent<I, S, T>(
2874 &mut self,
2875 edits: I,
2876 original_indent_columns: Vec<u32>,
2877 cx: &mut ViewContext<Self>,
2878 ) where
2879 I: IntoIterator<Item = (Range<S>, T)>,
2880 S: ToOffset,
2881 T: Into<Arc<str>>,
2882 {
2883 if self.read_only(cx) {
2884 return;
2885 }
2886
2887 self.buffer.update(cx, |buffer, cx| {
2888 buffer.edit(
2889 edits,
2890 Some(AutoindentMode::Block {
2891 original_indent_columns,
2892 }),
2893 cx,
2894 )
2895 });
2896 }
2897
2898 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2899 self.hide_context_menu(cx);
2900
2901 match phase {
2902 SelectPhase::Begin {
2903 position,
2904 add,
2905 click_count,
2906 } => self.begin_selection(position, add, click_count, cx),
2907 SelectPhase::BeginColumnar {
2908 position,
2909 goal_column,
2910 reset,
2911 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2912 SelectPhase::Extend {
2913 position,
2914 click_count,
2915 } => self.extend_selection(position, click_count, cx),
2916 SelectPhase::Update {
2917 position,
2918 goal_column,
2919 scroll_delta,
2920 } => self.update_selection(position, goal_column, scroll_delta, cx),
2921 SelectPhase::End => self.end_selection(cx),
2922 }
2923 }
2924
2925 fn extend_selection(
2926 &mut self,
2927 position: DisplayPoint,
2928 click_count: usize,
2929 cx: &mut ViewContext<Self>,
2930 ) {
2931 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2932 let tail = self.selections.newest::<usize>(cx).tail();
2933 self.begin_selection(position, false, click_count, cx);
2934
2935 let position = position.to_offset(&display_map, Bias::Left);
2936 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2937
2938 let mut pending_selection = self
2939 .selections
2940 .pending_anchor()
2941 .expect("extend_selection not called with pending selection");
2942 if position >= tail {
2943 pending_selection.start = tail_anchor;
2944 } else {
2945 pending_selection.end = tail_anchor;
2946 pending_selection.reversed = true;
2947 }
2948
2949 let mut pending_mode = self.selections.pending_mode().unwrap();
2950 match &mut pending_mode {
2951 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2952 _ => {}
2953 }
2954
2955 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2956 s.set_pending(pending_selection, pending_mode)
2957 });
2958 }
2959
2960 fn begin_selection(
2961 &mut self,
2962 position: DisplayPoint,
2963 add: bool,
2964 click_count: usize,
2965 cx: &mut ViewContext<Self>,
2966 ) {
2967 if !self.focus_handle.is_focused(cx) {
2968 self.last_focused_descendant = None;
2969 cx.focus(&self.focus_handle);
2970 }
2971
2972 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2973 let buffer = &display_map.buffer_snapshot;
2974 let newest_selection = self.selections.newest_anchor().clone();
2975 let position = display_map.clip_point(position, Bias::Left);
2976
2977 let start;
2978 let end;
2979 let mode;
2980 let auto_scroll;
2981 match click_count {
2982 1 => {
2983 start = buffer.anchor_before(position.to_point(&display_map));
2984 end = start;
2985 mode = SelectMode::Character;
2986 auto_scroll = true;
2987 }
2988 2 => {
2989 let range = movement::surrounding_word(&display_map, position);
2990 start = buffer.anchor_before(range.start.to_point(&display_map));
2991 end = buffer.anchor_before(range.end.to_point(&display_map));
2992 mode = SelectMode::Word(start..end);
2993 auto_scroll = true;
2994 }
2995 3 => {
2996 let position = display_map
2997 .clip_point(position, Bias::Left)
2998 .to_point(&display_map);
2999 let line_start = display_map.prev_line_boundary(position).0;
3000 let next_line_start = buffer.clip_point(
3001 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3002 Bias::Left,
3003 );
3004 start = buffer.anchor_before(line_start);
3005 end = buffer.anchor_before(next_line_start);
3006 mode = SelectMode::Line(start..end);
3007 auto_scroll = true;
3008 }
3009 _ => {
3010 start = buffer.anchor_before(0);
3011 end = buffer.anchor_before(buffer.len());
3012 mode = SelectMode::All;
3013 auto_scroll = false;
3014 }
3015 }
3016
3017 let point_to_delete: Option<usize> = {
3018 let selected_points: Vec<Selection<Point>> =
3019 self.selections.disjoint_in_range(start..end, cx);
3020
3021 if !add || click_count > 1 {
3022 None
3023 } else if !selected_points.is_empty() {
3024 Some(selected_points[0].id)
3025 } else {
3026 let clicked_point_already_selected =
3027 self.selections.disjoint.iter().find(|selection| {
3028 selection.start.to_point(buffer) == start.to_point(buffer)
3029 || selection.end.to_point(buffer) == end.to_point(buffer)
3030 });
3031
3032 clicked_point_already_selected.map(|selection| selection.id)
3033 }
3034 };
3035
3036 let selections_count = self.selections.count();
3037
3038 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
3039 if let Some(point_to_delete) = point_to_delete {
3040 s.delete(point_to_delete);
3041
3042 if selections_count == 1 {
3043 s.set_pending_anchor_range(start..end, mode);
3044 }
3045 } else {
3046 if !add {
3047 s.clear_disjoint();
3048 } else if click_count > 1 {
3049 s.delete(newest_selection.id)
3050 }
3051
3052 s.set_pending_anchor_range(start..end, mode);
3053 }
3054 });
3055 }
3056
3057 fn begin_columnar_selection(
3058 &mut self,
3059 position: DisplayPoint,
3060 goal_column: u32,
3061 reset: bool,
3062 cx: &mut ViewContext<Self>,
3063 ) {
3064 if !self.focus_handle.is_focused(cx) {
3065 self.last_focused_descendant = None;
3066 cx.focus(&self.focus_handle);
3067 }
3068
3069 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3070
3071 if reset {
3072 let pointer_position = display_map
3073 .buffer_snapshot
3074 .anchor_before(position.to_point(&display_map));
3075
3076 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
3077 s.clear_disjoint();
3078 s.set_pending_anchor_range(
3079 pointer_position..pointer_position,
3080 SelectMode::Character,
3081 );
3082 });
3083 }
3084
3085 let tail = self.selections.newest::<Point>(cx).tail();
3086 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
3087
3088 if !reset {
3089 self.select_columns(
3090 tail.to_display_point(&display_map),
3091 position,
3092 goal_column,
3093 &display_map,
3094 cx,
3095 );
3096 }
3097 }
3098
3099 fn update_selection(
3100 &mut self,
3101 position: DisplayPoint,
3102 goal_column: u32,
3103 scroll_delta: gpui::Point<f32>,
3104 cx: &mut ViewContext<Self>,
3105 ) {
3106 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3107
3108 if let Some(tail) = self.columnar_selection_tail.as_ref() {
3109 let tail = tail.to_display_point(&display_map);
3110 self.select_columns(tail, position, goal_column, &display_map, cx);
3111 } else if let Some(mut pending) = self.selections.pending_anchor() {
3112 let buffer = self.buffer.read(cx).snapshot(cx);
3113 let head;
3114 let tail;
3115 let mode = self.selections.pending_mode().unwrap();
3116 match &mode {
3117 SelectMode::Character => {
3118 head = position.to_point(&display_map);
3119 tail = pending.tail().to_point(&buffer);
3120 }
3121 SelectMode::Word(original_range) => {
3122 let original_display_range = original_range.start.to_display_point(&display_map)
3123 ..original_range.end.to_display_point(&display_map);
3124 let original_buffer_range = original_display_range.start.to_point(&display_map)
3125 ..original_display_range.end.to_point(&display_map);
3126 if movement::is_inside_word(&display_map, position)
3127 || original_display_range.contains(&position)
3128 {
3129 let word_range = movement::surrounding_word(&display_map, position);
3130 if word_range.start < original_display_range.start {
3131 head = word_range.start.to_point(&display_map);
3132 } else {
3133 head = word_range.end.to_point(&display_map);
3134 }
3135 } else {
3136 head = position.to_point(&display_map);
3137 }
3138
3139 if head <= original_buffer_range.start {
3140 tail = original_buffer_range.end;
3141 } else {
3142 tail = original_buffer_range.start;
3143 }
3144 }
3145 SelectMode::Line(original_range) => {
3146 let original_range = original_range.to_point(&display_map.buffer_snapshot);
3147
3148 let position = display_map
3149 .clip_point(position, Bias::Left)
3150 .to_point(&display_map);
3151 let line_start = display_map.prev_line_boundary(position).0;
3152 let next_line_start = buffer.clip_point(
3153 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3154 Bias::Left,
3155 );
3156
3157 if line_start < original_range.start {
3158 head = line_start
3159 } else {
3160 head = next_line_start
3161 }
3162
3163 if head <= original_range.start {
3164 tail = original_range.end;
3165 } else {
3166 tail = original_range.start;
3167 }
3168 }
3169 SelectMode::All => {
3170 return;
3171 }
3172 };
3173
3174 if head < tail {
3175 pending.start = buffer.anchor_before(head);
3176 pending.end = buffer.anchor_before(tail);
3177 pending.reversed = true;
3178 } else {
3179 pending.start = buffer.anchor_before(tail);
3180 pending.end = buffer.anchor_before(head);
3181 pending.reversed = false;
3182 }
3183
3184 self.change_selections(None, cx, |s| {
3185 s.set_pending(pending, mode);
3186 });
3187 } else {
3188 log::error!("update_selection dispatched with no pending selection");
3189 return;
3190 }
3191
3192 self.apply_scroll_delta(scroll_delta, cx);
3193 cx.notify();
3194 }
3195
3196 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
3197 self.columnar_selection_tail.take();
3198 if self.selections.pending_anchor().is_some() {
3199 let selections = self.selections.all::<usize>(cx);
3200 self.change_selections(None, cx, |s| {
3201 s.select(selections);
3202 s.clear_pending();
3203 });
3204 }
3205 }
3206
3207 fn select_columns(
3208 &mut self,
3209 tail: DisplayPoint,
3210 head: DisplayPoint,
3211 goal_column: u32,
3212 display_map: &DisplaySnapshot,
3213 cx: &mut ViewContext<Self>,
3214 ) {
3215 let start_row = cmp::min(tail.row(), head.row());
3216 let end_row = cmp::max(tail.row(), head.row());
3217 let start_column = cmp::min(tail.column(), goal_column);
3218 let end_column = cmp::max(tail.column(), goal_column);
3219 let reversed = start_column < tail.column();
3220
3221 let selection_ranges = (start_row.0..=end_row.0)
3222 .map(DisplayRow)
3223 .filter_map(|row| {
3224 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3225 let start = display_map
3226 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3227 .to_point(display_map);
3228 let end = display_map
3229 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3230 .to_point(display_map);
3231 if reversed {
3232 Some(end..start)
3233 } else {
3234 Some(start..end)
3235 }
3236 } else {
3237 None
3238 }
3239 })
3240 .collect::<Vec<_>>();
3241
3242 self.change_selections(None, cx, |s| {
3243 s.select_ranges(selection_ranges);
3244 });
3245 cx.notify();
3246 }
3247
3248 pub fn has_pending_nonempty_selection(&self) -> bool {
3249 let pending_nonempty_selection = match self.selections.pending_anchor() {
3250 Some(Selection { start, end, .. }) => start != end,
3251 None => false,
3252 };
3253
3254 pending_nonempty_selection
3255 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3256 }
3257
3258 pub fn has_pending_selection(&self) -> bool {
3259 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3260 }
3261
3262 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
3263 if self.clear_expanded_diff_hunks(cx) {
3264 cx.notify();
3265 return;
3266 }
3267 if self.dismiss_menus_and_popups(true, cx) {
3268 return;
3269 }
3270
3271 if self.mode == EditorMode::Full
3272 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
3273 {
3274 return;
3275 }
3276
3277 cx.propagate();
3278 }
3279
3280 pub fn dismiss_menus_and_popups(
3281 &mut self,
3282 should_report_inline_completion_event: bool,
3283 cx: &mut ViewContext<Self>,
3284 ) -> bool {
3285 if self.take_rename(false, cx).is_some() {
3286 return true;
3287 }
3288
3289 if hide_hover(self, cx) {
3290 return true;
3291 }
3292
3293 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3294 return true;
3295 }
3296
3297 if self.hide_context_menu(cx).is_some() {
3298 return true;
3299 }
3300
3301 if self.mouse_context_menu.take().is_some() {
3302 return true;
3303 }
3304
3305 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3306 return true;
3307 }
3308
3309 if self.snippet_stack.pop().is_some() {
3310 return true;
3311 }
3312
3313 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3314 self.dismiss_diagnostics(cx);
3315 return true;
3316 }
3317
3318 false
3319 }
3320
3321 fn linked_editing_ranges_for(
3322 &self,
3323 selection: Range<text::Anchor>,
3324 cx: &AppContext,
3325 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3326 if self.linked_edit_ranges.is_empty() {
3327 return None;
3328 }
3329 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3330 selection.end.buffer_id.and_then(|end_buffer_id| {
3331 if selection.start.buffer_id != Some(end_buffer_id) {
3332 return None;
3333 }
3334 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3335 let snapshot = buffer.read(cx).snapshot();
3336 self.linked_edit_ranges
3337 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3338 .map(|ranges| (ranges, snapshot, buffer))
3339 })?;
3340 use text::ToOffset as TO;
3341 // find offset from the start of current range to current cursor position
3342 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3343
3344 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3345 let start_difference = start_offset - start_byte_offset;
3346 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3347 let end_difference = end_offset - start_byte_offset;
3348 // Current range has associated linked ranges.
3349 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3350 for range in linked_ranges.iter() {
3351 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3352 let end_offset = start_offset + end_difference;
3353 let start_offset = start_offset + start_difference;
3354 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3355 continue;
3356 }
3357 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3358 if s.start.buffer_id != selection.start.buffer_id
3359 || s.end.buffer_id != selection.end.buffer_id
3360 {
3361 return false;
3362 }
3363 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3364 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3365 }) {
3366 continue;
3367 }
3368 let start = buffer_snapshot.anchor_after(start_offset);
3369 let end = buffer_snapshot.anchor_after(end_offset);
3370 linked_edits
3371 .entry(buffer.clone())
3372 .or_default()
3373 .push(start..end);
3374 }
3375 Some(linked_edits)
3376 }
3377
3378 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3379 let text: Arc<str> = text.into();
3380
3381 if self.read_only(cx) {
3382 return;
3383 }
3384
3385 let selections = self.selections.all_adjusted(cx);
3386 let mut bracket_inserted = false;
3387 let mut edits = Vec::new();
3388 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3389 let mut new_selections = Vec::with_capacity(selections.len());
3390 let mut new_autoclose_regions = Vec::new();
3391 let snapshot = self.buffer.read(cx).read(cx);
3392
3393 for (selection, autoclose_region) in
3394 self.selections_with_autoclose_regions(selections, &snapshot)
3395 {
3396 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3397 // Determine if the inserted text matches the opening or closing
3398 // bracket of any of this language's bracket pairs.
3399 let mut bracket_pair = None;
3400 let mut is_bracket_pair_start = false;
3401 let mut is_bracket_pair_end = false;
3402 if !text.is_empty() {
3403 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3404 // and they are removing the character that triggered IME popup.
3405 for (pair, enabled) in scope.brackets() {
3406 if !pair.close && !pair.surround {
3407 continue;
3408 }
3409
3410 if enabled && pair.start.ends_with(text.as_ref()) {
3411 let prefix_len = pair.start.len() - text.len();
3412 let preceding_text_matches_prefix = prefix_len == 0
3413 || (selection.start.column >= (prefix_len as u32)
3414 && snapshot.contains_str_at(
3415 Point::new(
3416 selection.start.row,
3417 selection.start.column - (prefix_len as u32),
3418 ),
3419 &pair.start[..prefix_len],
3420 ));
3421 if preceding_text_matches_prefix {
3422 bracket_pair = Some(pair.clone());
3423 is_bracket_pair_start = true;
3424 break;
3425 }
3426 }
3427 if pair.end.as_str() == text.as_ref() {
3428 bracket_pair = Some(pair.clone());
3429 is_bracket_pair_end = true;
3430 break;
3431 }
3432 }
3433 }
3434
3435 if let Some(bracket_pair) = bracket_pair {
3436 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3437 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3438 let auto_surround =
3439 self.use_auto_surround && snapshot_settings.use_auto_surround;
3440 if selection.is_empty() {
3441 if is_bracket_pair_start {
3442 // If the inserted text is a suffix of an opening bracket and the
3443 // selection is preceded by the rest of the opening bracket, then
3444 // insert the closing bracket.
3445 let following_text_allows_autoclose = snapshot
3446 .chars_at(selection.start)
3447 .next()
3448 .map_or(true, |c| scope.should_autoclose_before(c));
3449
3450 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3451 && bracket_pair.start.len() == 1
3452 {
3453 let target = bracket_pair.start.chars().next().unwrap();
3454 let current_line_count = snapshot
3455 .reversed_chars_at(selection.start)
3456 .take_while(|&c| c != '\n')
3457 .filter(|&c| c == target)
3458 .count();
3459 current_line_count % 2 == 1
3460 } else {
3461 false
3462 };
3463
3464 if autoclose
3465 && bracket_pair.close
3466 && following_text_allows_autoclose
3467 && !is_closing_quote
3468 {
3469 let anchor = snapshot.anchor_before(selection.end);
3470 new_selections.push((selection.map(|_| anchor), text.len()));
3471 new_autoclose_regions.push((
3472 anchor,
3473 text.len(),
3474 selection.id,
3475 bracket_pair.clone(),
3476 ));
3477 edits.push((
3478 selection.range(),
3479 format!("{}{}", text, bracket_pair.end).into(),
3480 ));
3481 bracket_inserted = true;
3482 continue;
3483 }
3484 }
3485
3486 if let Some(region) = autoclose_region {
3487 // If the selection is followed by an auto-inserted closing bracket,
3488 // then don't insert that closing bracket again; just move the selection
3489 // past the closing bracket.
3490 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3491 && text.as_ref() == region.pair.end.as_str();
3492 if should_skip {
3493 let anchor = snapshot.anchor_after(selection.end);
3494 new_selections
3495 .push((selection.map(|_| anchor), region.pair.end.len()));
3496 continue;
3497 }
3498 }
3499
3500 let always_treat_brackets_as_autoclosed = snapshot
3501 .settings_at(selection.start, cx)
3502 .always_treat_brackets_as_autoclosed;
3503 if always_treat_brackets_as_autoclosed
3504 && is_bracket_pair_end
3505 && snapshot.contains_str_at(selection.end, text.as_ref())
3506 {
3507 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3508 // and the inserted text is a closing bracket and the selection is followed
3509 // by the closing bracket then move the selection past the closing bracket.
3510 let anchor = snapshot.anchor_after(selection.end);
3511 new_selections.push((selection.map(|_| anchor), text.len()));
3512 continue;
3513 }
3514 }
3515 // If an opening bracket is 1 character long and is typed while
3516 // text is selected, then surround that text with the bracket pair.
3517 else if auto_surround
3518 && bracket_pair.surround
3519 && is_bracket_pair_start
3520 && bracket_pair.start.chars().count() == 1
3521 {
3522 edits.push((selection.start..selection.start, text.clone()));
3523 edits.push((
3524 selection.end..selection.end,
3525 bracket_pair.end.as_str().into(),
3526 ));
3527 bracket_inserted = true;
3528 new_selections.push((
3529 Selection {
3530 id: selection.id,
3531 start: snapshot.anchor_after(selection.start),
3532 end: snapshot.anchor_before(selection.end),
3533 reversed: selection.reversed,
3534 goal: selection.goal,
3535 },
3536 0,
3537 ));
3538 continue;
3539 }
3540 }
3541 }
3542
3543 if self.auto_replace_emoji_shortcode
3544 && selection.is_empty()
3545 && text.as_ref().ends_with(':')
3546 {
3547 if let Some(possible_emoji_short_code) =
3548 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3549 {
3550 if !possible_emoji_short_code.is_empty() {
3551 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3552 let emoji_shortcode_start = Point::new(
3553 selection.start.row,
3554 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3555 );
3556
3557 // Remove shortcode from buffer
3558 edits.push((
3559 emoji_shortcode_start..selection.start,
3560 "".to_string().into(),
3561 ));
3562 new_selections.push((
3563 Selection {
3564 id: selection.id,
3565 start: snapshot.anchor_after(emoji_shortcode_start),
3566 end: snapshot.anchor_before(selection.start),
3567 reversed: selection.reversed,
3568 goal: selection.goal,
3569 },
3570 0,
3571 ));
3572
3573 // Insert emoji
3574 let selection_start_anchor = snapshot.anchor_after(selection.start);
3575 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3576 edits.push((selection.start..selection.end, emoji.to_string().into()));
3577
3578 continue;
3579 }
3580 }
3581 }
3582 }
3583
3584 // If not handling any auto-close operation, then just replace the selected
3585 // text with the given input and move the selection to the end of the
3586 // newly inserted text.
3587 let anchor = snapshot.anchor_after(selection.end);
3588 if !self.linked_edit_ranges.is_empty() {
3589 let start_anchor = snapshot.anchor_before(selection.start);
3590
3591 let is_word_char = text.chars().next().map_or(true, |char| {
3592 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3593 classifier.is_word(char)
3594 });
3595
3596 if is_word_char {
3597 if let Some(ranges) = self
3598 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3599 {
3600 for (buffer, edits) in ranges {
3601 linked_edits
3602 .entry(buffer.clone())
3603 .or_default()
3604 .extend(edits.into_iter().map(|range| (range, text.clone())));
3605 }
3606 }
3607 }
3608 }
3609
3610 new_selections.push((selection.map(|_| anchor), 0));
3611 edits.push((selection.start..selection.end, text.clone()));
3612 }
3613
3614 drop(snapshot);
3615
3616 self.transact(cx, |this, cx| {
3617 this.buffer.update(cx, |buffer, cx| {
3618 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3619 });
3620 for (buffer, edits) in linked_edits {
3621 buffer.update(cx, |buffer, cx| {
3622 let snapshot = buffer.snapshot();
3623 let edits = edits
3624 .into_iter()
3625 .map(|(range, text)| {
3626 use text::ToPoint as TP;
3627 let end_point = TP::to_point(&range.end, &snapshot);
3628 let start_point = TP::to_point(&range.start, &snapshot);
3629 (start_point..end_point, text)
3630 })
3631 .sorted_by_key(|(range, _)| range.start)
3632 .collect::<Vec<_>>();
3633 buffer.edit(edits, None, cx);
3634 })
3635 }
3636 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3637 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3638 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3639 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3640 .zip(new_selection_deltas)
3641 .map(|(selection, delta)| Selection {
3642 id: selection.id,
3643 start: selection.start + delta,
3644 end: selection.end + delta,
3645 reversed: selection.reversed,
3646 goal: SelectionGoal::None,
3647 })
3648 .collect::<Vec<_>>();
3649
3650 let mut i = 0;
3651 for (position, delta, selection_id, pair) in new_autoclose_regions {
3652 let position = position.to_offset(&map.buffer_snapshot) + delta;
3653 let start = map.buffer_snapshot.anchor_before(position);
3654 let end = map.buffer_snapshot.anchor_after(position);
3655 while let Some(existing_state) = this.autoclose_regions.get(i) {
3656 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3657 Ordering::Less => i += 1,
3658 Ordering::Greater => break,
3659 Ordering::Equal => {
3660 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3661 Ordering::Less => i += 1,
3662 Ordering::Equal => break,
3663 Ordering::Greater => break,
3664 }
3665 }
3666 }
3667 }
3668 this.autoclose_regions.insert(
3669 i,
3670 AutocloseRegion {
3671 selection_id,
3672 range: start..end,
3673 pair,
3674 },
3675 );
3676 }
3677
3678 let had_active_inline_completion = this.has_active_inline_completion(cx);
3679 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3680 s.select(new_selections)
3681 });
3682
3683 if !bracket_inserted {
3684 if let Some(on_type_format_task) =
3685 this.trigger_on_type_formatting(text.to_string(), cx)
3686 {
3687 on_type_format_task.detach_and_log_err(cx);
3688 }
3689 }
3690
3691 let editor_settings = EditorSettings::get_global(cx);
3692 if bracket_inserted
3693 && (editor_settings.auto_signature_help
3694 || editor_settings.show_signature_help_after_edits)
3695 {
3696 this.show_signature_help(&ShowSignatureHelp, cx);
3697 }
3698
3699 let trigger_in_words = !had_active_inline_completion;
3700 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3701 linked_editing_ranges::refresh_linked_ranges(this, cx);
3702 this.refresh_inline_completion(true, false, cx);
3703 });
3704 }
3705
3706 fn find_possible_emoji_shortcode_at_position(
3707 snapshot: &MultiBufferSnapshot,
3708 position: Point,
3709 ) -> Option<String> {
3710 let mut chars = Vec::new();
3711 let mut found_colon = false;
3712 for char in snapshot.reversed_chars_at(position).take(100) {
3713 // Found a possible emoji shortcode in the middle of the buffer
3714 if found_colon {
3715 if char.is_whitespace() {
3716 chars.reverse();
3717 return Some(chars.iter().collect());
3718 }
3719 // If the previous character is not a whitespace, we are in the middle of a word
3720 // and we only want to complete the shortcode if the word is made up of other emojis
3721 let mut containing_word = String::new();
3722 for ch in snapshot
3723 .reversed_chars_at(position)
3724 .skip(chars.len() + 1)
3725 .take(100)
3726 {
3727 if ch.is_whitespace() {
3728 break;
3729 }
3730 containing_word.push(ch);
3731 }
3732 let containing_word = containing_word.chars().rev().collect::<String>();
3733 if util::word_consists_of_emojis(containing_word.as_str()) {
3734 chars.reverse();
3735 return Some(chars.iter().collect());
3736 }
3737 }
3738
3739 if char.is_whitespace() || !char.is_ascii() {
3740 return None;
3741 }
3742 if char == ':' {
3743 found_colon = true;
3744 } else {
3745 chars.push(char);
3746 }
3747 }
3748 // Found a possible emoji shortcode at the beginning of the buffer
3749 chars.reverse();
3750 Some(chars.iter().collect())
3751 }
3752
3753 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3754 self.transact(cx, |this, cx| {
3755 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3756 let selections = this.selections.all::<usize>(cx);
3757 let multi_buffer = this.buffer.read(cx);
3758 let buffer = multi_buffer.snapshot(cx);
3759 selections
3760 .iter()
3761 .map(|selection| {
3762 let start_point = selection.start.to_point(&buffer);
3763 let mut indent =
3764 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3765 indent.len = cmp::min(indent.len, start_point.column);
3766 let start = selection.start;
3767 let end = selection.end;
3768 let selection_is_empty = start == end;
3769 let language_scope = buffer.language_scope_at(start);
3770 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3771 &language_scope
3772 {
3773 let leading_whitespace_len = buffer
3774 .reversed_chars_at(start)
3775 .take_while(|c| c.is_whitespace() && *c != '\n')
3776 .map(|c| c.len_utf8())
3777 .sum::<usize>();
3778
3779 let trailing_whitespace_len = buffer
3780 .chars_at(end)
3781 .take_while(|c| c.is_whitespace() && *c != '\n')
3782 .map(|c| c.len_utf8())
3783 .sum::<usize>();
3784
3785 let insert_extra_newline =
3786 language.brackets().any(|(pair, enabled)| {
3787 let pair_start = pair.start.trim_end();
3788 let pair_end = pair.end.trim_start();
3789
3790 enabled
3791 && pair.newline
3792 && buffer.contains_str_at(
3793 end + trailing_whitespace_len,
3794 pair_end,
3795 )
3796 && buffer.contains_str_at(
3797 (start - leading_whitespace_len)
3798 .saturating_sub(pair_start.len()),
3799 pair_start,
3800 )
3801 });
3802
3803 // Comment extension on newline is allowed only for cursor selections
3804 let comment_delimiter = maybe!({
3805 if !selection_is_empty {
3806 return None;
3807 }
3808
3809 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3810 return None;
3811 }
3812
3813 let delimiters = language.line_comment_prefixes();
3814 let max_len_of_delimiter =
3815 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3816 let (snapshot, range) =
3817 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3818
3819 let mut index_of_first_non_whitespace = 0;
3820 let comment_candidate = snapshot
3821 .chars_for_range(range)
3822 .skip_while(|c| {
3823 let should_skip = c.is_whitespace();
3824 if should_skip {
3825 index_of_first_non_whitespace += 1;
3826 }
3827 should_skip
3828 })
3829 .take(max_len_of_delimiter)
3830 .collect::<String>();
3831 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3832 comment_candidate.starts_with(comment_prefix.as_ref())
3833 })?;
3834 let cursor_is_placed_after_comment_marker =
3835 index_of_first_non_whitespace + comment_prefix.len()
3836 <= start_point.column as usize;
3837 if cursor_is_placed_after_comment_marker {
3838 Some(comment_prefix.clone())
3839 } else {
3840 None
3841 }
3842 });
3843 (comment_delimiter, insert_extra_newline)
3844 } else {
3845 (None, false)
3846 };
3847
3848 let capacity_for_delimiter = comment_delimiter
3849 .as_deref()
3850 .map(str::len)
3851 .unwrap_or_default();
3852 let mut new_text =
3853 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3854 new_text.push('\n');
3855 new_text.extend(indent.chars());
3856 if let Some(delimiter) = &comment_delimiter {
3857 new_text.push_str(delimiter);
3858 }
3859 if insert_extra_newline {
3860 new_text = new_text.repeat(2);
3861 }
3862
3863 let anchor = buffer.anchor_after(end);
3864 let new_selection = selection.map(|_| anchor);
3865 (
3866 (start..end, new_text),
3867 (insert_extra_newline, new_selection),
3868 )
3869 })
3870 .unzip()
3871 };
3872
3873 this.edit_with_autoindent(edits, cx);
3874 let buffer = this.buffer.read(cx).snapshot(cx);
3875 let new_selections = selection_fixup_info
3876 .into_iter()
3877 .map(|(extra_newline_inserted, new_selection)| {
3878 let mut cursor = new_selection.end.to_point(&buffer);
3879 if extra_newline_inserted {
3880 cursor.row -= 1;
3881 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3882 }
3883 new_selection.map(|_| cursor)
3884 })
3885 .collect();
3886
3887 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3888 this.refresh_inline_completion(true, false, cx);
3889 });
3890 }
3891
3892 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3893 let buffer = self.buffer.read(cx);
3894 let snapshot = buffer.snapshot(cx);
3895
3896 let mut edits = Vec::new();
3897 let mut rows = Vec::new();
3898
3899 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3900 let cursor = selection.head();
3901 let row = cursor.row;
3902
3903 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3904
3905 let newline = "\n".to_string();
3906 edits.push((start_of_line..start_of_line, newline));
3907
3908 rows.push(row + rows_inserted as u32);
3909 }
3910
3911 self.transact(cx, |editor, cx| {
3912 editor.edit(edits, cx);
3913
3914 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3915 let mut index = 0;
3916 s.move_cursors_with(|map, _, _| {
3917 let row = rows[index];
3918 index += 1;
3919
3920 let point = Point::new(row, 0);
3921 let boundary = map.next_line_boundary(point).1;
3922 let clipped = map.clip_point(boundary, Bias::Left);
3923
3924 (clipped, SelectionGoal::None)
3925 });
3926 });
3927
3928 let mut indent_edits = Vec::new();
3929 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3930 for row in rows {
3931 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3932 for (row, indent) in indents {
3933 if indent.len == 0 {
3934 continue;
3935 }
3936
3937 let text = match indent.kind {
3938 IndentKind::Space => " ".repeat(indent.len as usize),
3939 IndentKind::Tab => "\t".repeat(indent.len as usize),
3940 };
3941 let point = Point::new(row.0, 0);
3942 indent_edits.push((point..point, text));
3943 }
3944 }
3945 editor.edit(indent_edits, cx);
3946 });
3947 }
3948
3949 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3950 let buffer = self.buffer.read(cx);
3951 let snapshot = buffer.snapshot(cx);
3952
3953 let mut edits = Vec::new();
3954 let mut rows = Vec::new();
3955 let mut rows_inserted = 0;
3956
3957 for selection in self.selections.all_adjusted(cx) {
3958 let cursor = selection.head();
3959 let row = cursor.row;
3960
3961 let point = Point::new(row + 1, 0);
3962 let start_of_line = snapshot.clip_point(point, Bias::Left);
3963
3964 let newline = "\n".to_string();
3965 edits.push((start_of_line..start_of_line, newline));
3966
3967 rows_inserted += 1;
3968 rows.push(row + rows_inserted);
3969 }
3970
3971 self.transact(cx, |editor, cx| {
3972 editor.edit(edits, cx);
3973
3974 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3975 let mut index = 0;
3976 s.move_cursors_with(|map, _, _| {
3977 let row = rows[index];
3978 index += 1;
3979
3980 let point = Point::new(row, 0);
3981 let boundary = map.next_line_boundary(point).1;
3982 let clipped = map.clip_point(boundary, Bias::Left);
3983
3984 (clipped, SelectionGoal::None)
3985 });
3986 });
3987
3988 let mut indent_edits = Vec::new();
3989 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3990 for row in rows {
3991 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3992 for (row, indent) in indents {
3993 if indent.len == 0 {
3994 continue;
3995 }
3996
3997 let text = match indent.kind {
3998 IndentKind::Space => " ".repeat(indent.len as usize),
3999 IndentKind::Tab => "\t".repeat(indent.len as usize),
4000 };
4001 let point = Point::new(row.0, 0);
4002 indent_edits.push((point..point, text));
4003 }
4004 }
4005 editor.edit(indent_edits, cx);
4006 });
4007 }
4008
4009 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
4010 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
4011 original_indent_columns: Vec::new(),
4012 });
4013 self.insert_with_autoindent_mode(text, autoindent, cx);
4014 }
4015
4016 fn insert_with_autoindent_mode(
4017 &mut self,
4018 text: &str,
4019 autoindent_mode: Option<AutoindentMode>,
4020 cx: &mut ViewContext<Self>,
4021 ) {
4022 if self.read_only(cx) {
4023 return;
4024 }
4025
4026 let text: Arc<str> = text.into();
4027 self.transact(cx, |this, cx| {
4028 let old_selections = this.selections.all_adjusted(cx);
4029 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
4030 let anchors = {
4031 let snapshot = buffer.read(cx);
4032 old_selections
4033 .iter()
4034 .map(|s| {
4035 let anchor = snapshot.anchor_after(s.head());
4036 s.map(|_| anchor)
4037 })
4038 .collect::<Vec<_>>()
4039 };
4040 buffer.edit(
4041 old_selections
4042 .iter()
4043 .map(|s| (s.start..s.end, text.clone())),
4044 autoindent_mode,
4045 cx,
4046 );
4047 anchors
4048 });
4049
4050 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
4051 s.select_anchors(selection_anchors);
4052 })
4053 });
4054 }
4055
4056 fn trigger_completion_on_input(
4057 &mut self,
4058 text: &str,
4059 trigger_in_words: bool,
4060 cx: &mut ViewContext<Self>,
4061 ) {
4062 if self.is_completion_trigger(text, trigger_in_words, cx) {
4063 self.show_completions(
4064 &ShowCompletions {
4065 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
4066 },
4067 cx,
4068 );
4069 } else {
4070 self.hide_context_menu(cx);
4071 }
4072 }
4073
4074 fn is_completion_trigger(
4075 &self,
4076 text: &str,
4077 trigger_in_words: bool,
4078 cx: &mut ViewContext<Self>,
4079 ) -> bool {
4080 let position = self.selections.newest_anchor().head();
4081 let multibuffer = self.buffer.read(cx);
4082 let Some(buffer) = position
4083 .buffer_id
4084 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
4085 else {
4086 return false;
4087 };
4088
4089 if let Some(completion_provider) = &self.completion_provider {
4090 completion_provider.is_completion_trigger(
4091 &buffer,
4092 position.text_anchor,
4093 text,
4094 trigger_in_words,
4095 cx,
4096 )
4097 } else {
4098 false
4099 }
4100 }
4101
4102 /// If any empty selections is touching the start of its innermost containing autoclose
4103 /// region, expand it to select the brackets.
4104 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
4105 let selections = self.selections.all::<usize>(cx);
4106 let buffer = self.buffer.read(cx).read(cx);
4107 let new_selections = self
4108 .selections_with_autoclose_regions(selections, &buffer)
4109 .map(|(mut selection, region)| {
4110 if !selection.is_empty() {
4111 return selection;
4112 }
4113
4114 if let Some(region) = region {
4115 let mut range = region.range.to_offset(&buffer);
4116 if selection.start == range.start && range.start >= region.pair.start.len() {
4117 range.start -= region.pair.start.len();
4118 if buffer.contains_str_at(range.start, ®ion.pair.start)
4119 && buffer.contains_str_at(range.end, ®ion.pair.end)
4120 {
4121 range.end += region.pair.end.len();
4122 selection.start = range.start;
4123 selection.end = range.end;
4124
4125 return selection;
4126 }
4127 }
4128 }
4129
4130 let always_treat_brackets_as_autoclosed = buffer
4131 .settings_at(selection.start, cx)
4132 .always_treat_brackets_as_autoclosed;
4133
4134 if !always_treat_brackets_as_autoclosed {
4135 return selection;
4136 }
4137
4138 if let Some(scope) = buffer.language_scope_at(selection.start) {
4139 for (pair, enabled) in scope.brackets() {
4140 if !enabled || !pair.close {
4141 continue;
4142 }
4143
4144 if buffer.contains_str_at(selection.start, &pair.end) {
4145 let pair_start_len = pair.start.len();
4146 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
4147 {
4148 selection.start -= pair_start_len;
4149 selection.end += pair.end.len();
4150
4151 return selection;
4152 }
4153 }
4154 }
4155 }
4156
4157 selection
4158 })
4159 .collect();
4160
4161 drop(buffer);
4162 self.change_selections(None, cx, |selections| selections.select(new_selections));
4163 }
4164
4165 /// Iterate the given selections, and for each one, find the smallest surrounding
4166 /// autoclose region. This uses the ordering of the selections and the autoclose
4167 /// regions to avoid repeated comparisons.
4168 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4169 &'a self,
4170 selections: impl IntoIterator<Item = Selection<D>>,
4171 buffer: &'a MultiBufferSnapshot,
4172 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4173 let mut i = 0;
4174 let mut regions = self.autoclose_regions.as_slice();
4175 selections.into_iter().map(move |selection| {
4176 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4177
4178 let mut enclosing = None;
4179 while let Some(pair_state) = regions.get(i) {
4180 if pair_state.range.end.to_offset(buffer) < range.start {
4181 regions = ®ions[i + 1..];
4182 i = 0;
4183 } else if pair_state.range.start.to_offset(buffer) > range.end {
4184 break;
4185 } else {
4186 if pair_state.selection_id == selection.id {
4187 enclosing = Some(pair_state);
4188 }
4189 i += 1;
4190 }
4191 }
4192
4193 (selection, enclosing)
4194 })
4195 }
4196
4197 /// Remove any autoclose regions that no longer contain their selection.
4198 fn invalidate_autoclose_regions(
4199 &mut self,
4200 mut selections: &[Selection<Anchor>],
4201 buffer: &MultiBufferSnapshot,
4202 ) {
4203 self.autoclose_regions.retain(|state| {
4204 let mut i = 0;
4205 while let Some(selection) = selections.get(i) {
4206 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4207 selections = &selections[1..];
4208 continue;
4209 }
4210 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4211 break;
4212 }
4213 if selection.id == state.selection_id {
4214 return true;
4215 } else {
4216 i += 1;
4217 }
4218 }
4219 false
4220 });
4221 }
4222
4223 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4224 let offset = position.to_offset(buffer);
4225 let (word_range, kind) = buffer.surrounding_word(offset, true);
4226 if offset > word_range.start && kind == Some(CharKind::Word) {
4227 Some(
4228 buffer
4229 .text_for_range(word_range.start..offset)
4230 .collect::<String>(),
4231 )
4232 } else {
4233 None
4234 }
4235 }
4236
4237 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
4238 self.refresh_inlay_hints(
4239 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
4240 cx,
4241 );
4242 }
4243
4244 pub fn inlay_hints_enabled(&self) -> bool {
4245 self.inlay_hint_cache.enabled
4246 }
4247
4248 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
4249 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
4250 return;
4251 }
4252
4253 let reason_description = reason.description();
4254 let ignore_debounce = matches!(
4255 reason,
4256 InlayHintRefreshReason::SettingsChange(_)
4257 | InlayHintRefreshReason::Toggle(_)
4258 | InlayHintRefreshReason::ExcerptsRemoved(_)
4259 );
4260 let (invalidate_cache, required_languages) = match reason {
4261 InlayHintRefreshReason::Toggle(enabled) => {
4262 self.inlay_hint_cache.enabled = enabled;
4263 if enabled {
4264 (InvalidationStrategy::RefreshRequested, None)
4265 } else {
4266 self.inlay_hint_cache.clear();
4267 self.splice_inlays(
4268 self.visible_inlay_hints(cx)
4269 .iter()
4270 .map(|inlay| inlay.id)
4271 .collect(),
4272 Vec::new(),
4273 cx,
4274 );
4275 return;
4276 }
4277 }
4278 InlayHintRefreshReason::SettingsChange(new_settings) => {
4279 match self.inlay_hint_cache.update_settings(
4280 &self.buffer,
4281 new_settings,
4282 self.visible_inlay_hints(cx),
4283 cx,
4284 ) {
4285 ControlFlow::Break(Some(InlaySplice {
4286 to_remove,
4287 to_insert,
4288 })) => {
4289 self.splice_inlays(to_remove, to_insert, cx);
4290 return;
4291 }
4292 ControlFlow::Break(None) => return,
4293 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4294 }
4295 }
4296 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4297 if let Some(InlaySplice {
4298 to_remove,
4299 to_insert,
4300 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4301 {
4302 self.splice_inlays(to_remove, to_insert, cx);
4303 }
4304 return;
4305 }
4306 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4307 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4308 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4309 }
4310 InlayHintRefreshReason::RefreshRequested => {
4311 (InvalidationStrategy::RefreshRequested, None)
4312 }
4313 };
4314
4315 if let Some(InlaySplice {
4316 to_remove,
4317 to_insert,
4318 }) = self.inlay_hint_cache.spawn_hint_refresh(
4319 reason_description,
4320 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4321 invalidate_cache,
4322 ignore_debounce,
4323 cx,
4324 ) {
4325 self.splice_inlays(to_remove, to_insert, cx);
4326 }
4327 }
4328
4329 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4330 self.display_map
4331 .read(cx)
4332 .current_inlays()
4333 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4334 .cloned()
4335 .collect()
4336 }
4337
4338 pub fn excerpts_for_inlay_hints_query(
4339 &self,
4340 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4341 cx: &mut ViewContext<Editor>,
4342 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4343 let Some(project) = self.project.as_ref() else {
4344 return HashMap::default();
4345 };
4346 let project = project.read(cx);
4347 let multi_buffer = self.buffer().read(cx);
4348 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4349 let multi_buffer_visible_start = self
4350 .scroll_manager
4351 .anchor()
4352 .anchor
4353 .to_point(&multi_buffer_snapshot);
4354 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4355 multi_buffer_visible_start
4356 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4357 Bias::Left,
4358 );
4359 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4360 multi_buffer
4361 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4362 .into_iter()
4363 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4364 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4365 let buffer = buffer_handle.read(cx);
4366 let buffer_file = project::File::from_dyn(buffer.file())?;
4367 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4368 let worktree_entry = buffer_worktree
4369 .read(cx)
4370 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4371 if worktree_entry.is_ignored {
4372 return None;
4373 }
4374
4375 let language = buffer.language()?;
4376 if let Some(restrict_to_languages) = restrict_to_languages {
4377 if !restrict_to_languages.contains(language) {
4378 return None;
4379 }
4380 }
4381 Some((
4382 excerpt_id,
4383 (
4384 buffer_handle,
4385 buffer.version().clone(),
4386 excerpt_visible_range,
4387 ),
4388 ))
4389 })
4390 .collect()
4391 }
4392
4393 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4394 TextLayoutDetails {
4395 text_system: cx.text_system().clone(),
4396 editor_style: self.style.clone().unwrap(),
4397 rem_size: cx.rem_size(),
4398 scroll_anchor: self.scroll_manager.anchor(),
4399 visible_rows: self.visible_line_count(),
4400 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4401 }
4402 }
4403
4404 fn splice_inlays(
4405 &self,
4406 to_remove: Vec<InlayId>,
4407 to_insert: Vec<Inlay>,
4408 cx: &mut ViewContext<Self>,
4409 ) {
4410 self.display_map.update(cx, |display_map, cx| {
4411 display_map.splice_inlays(to_remove, to_insert, cx);
4412 });
4413 cx.notify();
4414 }
4415
4416 fn trigger_on_type_formatting(
4417 &self,
4418 input: String,
4419 cx: &mut ViewContext<Self>,
4420 ) -> Option<Task<Result<()>>> {
4421 if input.len() != 1 {
4422 return None;
4423 }
4424
4425 let project = self.project.as_ref()?;
4426 let position = self.selections.newest_anchor().head();
4427 let (buffer, buffer_position) = self
4428 .buffer
4429 .read(cx)
4430 .text_anchor_for_position(position, cx)?;
4431
4432 let settings = language_settings::language_settings(
4433 buffer
4434 .read(cx)
4435 .language_at(buffer_position)
4436 .map(|l| l.name()),
4437 buffer.read(cx).file(),
4438 cx,
4439 );
4440 if !settings.use_on_type_format {
4441 return None;
4442 }
4443
4444 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4445 // hence we do LSP request & edit on host side only — add formats to host's history.
4446 let push_to_lsp_host_history = true;
4447 // If this is not the host, append its history with new edits.
4448 let push_to_client_history = project.read(cx).is_via_collab();
4449
4450 let on_type_formatting = project.update(cx, |project, cx| {
4451 project.on_type_format(
4452 buffer.clone(),
4453 buffer_position,
4454 input,
4455 push_to_lsp_host_history,
4456 cx,
4457 )
4458 });
4459 Some(cx.spawn(|editor, mut cx| async move {
4460 if let Some(transaction) = on_type_formatting.await? {
4461 if push_to_client_history {
4462 buffer
4463 .update(&mut cx, |buffer, _| {
4464 buffer.push_transaction(transaction, Instant::now());
4465 })
4466 .ok();
4467 }
4468 editor.update(&mut cx, |editor, cx| {
4469 editor.refresh_document_highlights(cx);
4470 })?;
4471 }
4472 Ok(())
4473 }))
4474 }
4475
4476 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4477 if self.pending_rename.is_some() {
4478 return;
4479 }
4480
4481 let Some(provider) = self.completion_provider.as_ref() else {
4482 return;
4483 };
4484
4485 if !self.snippet_stack.is_empty() && self.context_menu.read().as_ref().is_some() {
4486 return;
4487 }
4488
4489 let position = self.selections.newest_anchor().head();
4490 let (buffer, buffer_position) =
4491 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4492 output
4493 } else {
4494 return;
4495 };
4496
4497 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4498 let is_followup_invoke = {
4499 let context_menu_state = self.context_menu.read();
4500 matches!(
4501 context_menu_state.deref(),
4502 Some(ContextMenu::Completions(_))
4503 )
4504 };
4505 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4506 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4507 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
4508 CompletionTriggerKind::TRIGGER_CHARACTER
4509 }
4510
4511 _ => CompletionTriggerKind::INVOKED,
4512 };
4513 let completion_context = CompletionContext {
4514 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4515 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4516 Some(String::from(trigger))
4517 } else {
4518 None
4519 }
4520 }),
4521 trigger_kind,
4522 };
4523 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4524 let sort_completions = provider.sort_completions();
4525
4526 let id = post_inc(&mut self.next_completion_id);
4527 let task = cx.spawn(|this, mut cx| {
4528 async move {
4529 this.update(&mut cx, |this, _| {
4530 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4531 })?;
4532 let completions = completions.await.log_err();
4533 let menu = if let Some(completions) = completions {
4534 let mut menu = CompletionsMenu::new(
4535 id,
4536 sort_completions,
4537 position,
4538 buffer.clone(),
4539 completions.into(),
4540 );
4541 menu.filter(query.as_deref(), cx.background_executor().clone())
4542 .await;
4543
4544 if menu.matches.is_empty() {
4545 None
4546 } else {
4547 this.update(&mut cx, |editor, cx| {
4548 let completions = menu.completions.clone();
4549 let matches = menu.matches.clone();
4550
4551 let delay_ms = EditorSettings::get_global(cx)
4552 .completion_documentation_secondary_query_debounce;
4553 let delay = Duration::from_millis(delay_ms);
4554 editor
4555 .completion_documentation_pre_resolve_debounce
4556 .fire_new(delay, cx, |editor, cx| {
4557 CompletionsMenu::pre_resolve_completion_documentation(
4558 buffer,
4559 completions,
4560 matches,
4561 editor,
4562 cx,
4563 )
4564 });
4565 })
4566 .ok();
4567 Some(menu)
4568 }
4569 } else {
4570 None
4571 };
4572
4573 this.update(&mut cx, |this, cx| {
4574 let mut context_menu = this.context_menu.write();
4575 match context_menu.as_ref() {
4576 None => {}
4577
4578 Some(ContextMenu::Completions(prev_menu)) => {
4579 if prev_menu.id > id {
4580 return;
4581 }
4582 }
4583
4584 _ => return,
4585 }
4586
4587 if this.focus_handle.is_focused(cx) && menu.is_some() {
4588 let menu = menu.unwrap();
4589 *context_menu = Some(ContextMenu::Completions(menu));
4590 drop(context_menu);
4591 this.discard_inline_completion(false, cx);
4592 cx.notify();
4593 } else if this.completion_tasks.len() <= 1 {
4594 // If there are no more completion tasks and the last menu was
4595 // empty, we should hide it. If it was already hidden, we should
4596 // also show the copilot completion when available.
4597 drop(context_menu);
4598 if this.hide_context_menu(cx).is_none() {
4599 this.update_visible_inline_completion(cx);
4600 }
4601 }
4602 })?;
4603
4604 Ok::<_, anyhow::Error>(())
4605 }
4606 .log_err()
4607 });
4608
4609 self.completion_tasks.push((id, task));
4610 }
4611
4612 pub fn confirm_completion(
4613 &mut self,
4614 action: &ConfirmCompletion,
4615 cx: &mut ViewContext<Self>,
4616 ) -> Option<Task<Result<()>>> {
4617 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4618 }
4619
4620 pub fn compose_completion(
4621 &mut self,
4622 action: &ComposeCompletion,
4623 cx: &mut ViewContext<Self>,
4624 ) -> Option<Task<Result<()>>> {
4625 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4626 }
4627
4628 fn do_completion(
4629 &mut self,
4630 item_ix: Option<usize>,
4631 intent: CompletionIntent,
4632 cx: &mut ViewContext<Editor>,
4633 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4634 use language::ToOffset as _;
4635
4636 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4637 menu
4638 } else {
4639 return None;
4640 };
4641
4642 let mat = completions_menu
4643 .matches
4644 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4645 let buffer_handle = completions_menu.buffer;
4646 let completions = completions_menu.completions.read();
4647 let completion = completions.get(mat.candidate_id)?;
4648 cx.stop_propagation();
4649
4650 let snippet;
4651 let text;
4652
4653 if completion.is_snippet() {
4654 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4655 text = snippet.as_ref().unwrap().text.clone();
4656 } else {
4657 snippet = None;
4658 text = completion.new_text.clone();
4659 };
4660 let selections = self.selections.all::<usize>(cx);
4661 let buffer = buffer_handle.read(cx);
4662 let old_range = completion.old_range.to_offset(buffer);
4663 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4664
4665 let newest_selection = self.selections.newest_anchor();
4666 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4667 return None;
4668 }
4669
4670 let lookbehind = newest_selection
4671 .start
4672 .text_anchor
4673 .to_offset(buffer)
4674 .saturating_sub(old_range.start);
4675 let lookahead = old_range
4676 .end
4677 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4678 let mut common_prefix_len = old_text
4679 .bytes()
4680 .zip(text.bytes())
4681 .take_while(|(a, b)| a == b)
4682 .count();
4683
4684 let snapshot = self.buffer.read(cx).snapshot(cx);
4685 let mut range_to_replace: Option<Range<isize>> = None;
4686 let mut ranges = Vec::new();
4687 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4688 for selection in &selections {
4689 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4690 let start = selection.start.saturating_sub(lookbehind);
4691 let end = selection.end + lookahead;
4692 if selection.id == newest_selection.id {
4693 range_to_replace = Some(
4694 ((start + common_prefix_len) as isize - selection.start as isize)
4695 ..(end as isize - selection.start as isize),
4696 );
4697 }
4698 ranges.push(start + common_prefix_len..end);
4699 } else {
4700 common_prefix_len = 0;
4701 ranges.clear();
4702 ranges.extend(selections.iter().map(|s| {
4703 if s.id == newest_selection.id {
4704 range_to_replace = Some(
4705 old_range.start.to_offset_utf16(&snapshot).0 as isize
4706 - selection.start as isize
4707 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4708 - selection.start as isize,
4709 );
4710 old_range.clone()
4711 } else {
4712 s.start..s.end
4713 }
4714 }));
4715 break;
4716 }
4717 if !self.linked_edit_ranges.is_empty() {
4718 let start_anchor = snapshot.anchor_before(selection.head());
4719 let end_anchor = snapshot.anchor_after(selection.tail());
4720 if let Some(ranges) = self
4721 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4722 {
4723 for (buffer, edits) in ranges {
4724 linked_edits.entry(buffer.clone()).or_default().extend(
4725 edits
4726 .into_iter()
4727 .map(|range| (range, text[common_prefix_len..].to_owned())),
4728 );
4729 }
4730 }
4731 }
4732 }
4733 let text = &text[common_prefix_len..];
4734
4735 cx.emit(EditorEvent::InputHandled {
4736 utf16_range_to_replace: range_to_replace,
4737 text: text.into(),
4738 });
4739
4740 self.transact(cx, |this, cx| {
4741 if let Some(mut snippet) = snippet {
4742 snippet.text = text.to_string();
4743 for tabstop in snippet
4744 .tabstops
4745 .iter_mut()
4746 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4747 {
4748 tabstop.start -= common_prefix_len as isize;
4749 tabstop.end -= common_prefix_len as isize;
4750 }
4751
4752 this.insert_snippet(&ranges, snippet, cx).log_err();
4753 } else {
4754 this.buffer.update(cx, |buffer, cx| {
4755 buffer.edit(
4756 ranges.iter().map(|range| (range.clone(), text)),
4757 this.autoindent_mode.clone(),
4758 cx,
4759 );
4760 });
4761 }
4762 for (buffer, edits) in linked_edits {
4763 buffer.update(cx, |buffer, cx| {
4764 let snapshot = buffer.snapshot();
4765 let edits = edits
4766 .into_iter()
4767 .map(|(range, text)| {
4768 use text::ToPoint as TP;
4769 let end_point = TP::to_point(&range.end, &snapshot);
4770 let start_point = TP::to_point(&range.start, &snapshot);
4771 (start_point..end_point, text)
4772 })
4773 .sorted_by_key(|(range, _)| range.start)
4774 .collect::<Vec<_>>();
4775 buffer.edit(edits, None, cx);
4776 })
4777 }
4778
4779 this.refresh_inline_completion(true, false, cx);
4780 });
4781
4782 let show_new_completions_on_confirm = completion
4783 .confirm
4784 .as_ref()
4785 .map_or(false, |confirm| confirm(intent, cx));
4786 if show_new_completions_on_confirm {
4787 self.show_completions(&ShowCompletions { trigger: None }, cx);
4788 }
4789
4790 let provider = self.completion_provider.as_ref()?;
4791 let apply_edits = provider.apply_additional_edits_for_completion(
4792 buffer_handle,
4793 completion.clone(),
4794 true,
4795 cx,
4796 );
4797
4798 let editor_settings = EditorSettings::get_global(cx);
4799 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4800 // After the code completion is finished, users often want to know what signatures are needed.
4801 // so we should automatically call signature_help
4802 self.show_signature_help(&ShowSignatureHelp, cx);
4803 }
4804
4805 Some(cx.foreground_executor().spawn(async move {
4806 apply_edits.await?;
4807 Ok(())
4808 }))
4809 }
4810
4811 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4812 let mut context_menu = self.context_menu.write();
4813 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4814 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4815 // Toggle if we're selecting the same one
4816 *context_menu = None;
4817 cx.notify();
4818 return;
4819 } else {
4820 // Otherwise, clear it and start a new one
4821 *context_menu = None;
4822 cx.notify();
4823 }
4824 }
4825 drop(context_menu);
4826 let snapshot = self.snapshot(cx);
4827 let deployed_from_indicator = action.deployed_from_indicator;
4828 let mut task = self.code_actions_task.take();
4829 let action = action.clone();
4830 cx.spawn(|editor, mut cx| async move {
4831 while let Some(prev_task) = task {
4832 prev_task.await.log_err();
4833 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4834 }
4835
4836 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4837 if editor.focus_handle.is_focused(cx) {
4838 let multibuffer_point = action
4839 .deployed_from_indicator
4840 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4841 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4842 let (buffer, buffer_row) = snapshot
4843 .buffer_snapshot
4844 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4845 .and_then(|(buffer_snapshot, range)| {
4846 editor
4847 .buffer
4848 .read(cx)
4849 .buffer(buffer_snapshot.remote_id())
4850 .map(|buffer| (buffer, range.start.row))
4851 })?;
4852 let (_, code_actions) = editor
4853 .available_code_actions
4854 .clone()
4855 .and_then(|(location, code_actions)| {
4856 let snapshot = location.buffer.read(cx).snapshot();
4857 let point_range = location.range.to_point(&snapshot);
4858 let point_range = point_range.start.row..=point_range.end.row;
4859 if point_range.contains(&buffer_row) {
4860 Some((location, code_actions))
4861 } else {
4862 None
4863 }
4864 })
4865 .unzip();
4866 let buffer_id = buffer.read(cx).remote_id();
4867 let tasks = editor
4868 .tasks
4869 .get(&(buffer_id, buffer_row))
4870 .map(|t| Arc::new(t.to_owned()));
4871 if tasks.is_none() && code_actions.is_none() {
4872 return None;
4873 }
4874
4875 editor.completion_tasks.clear();
4876 editor.discard_inline_completion(false, cx);
4877 let task_context =
4878 tasks
4879 .as_ref()
4880 .zip(editor.project.clone())
4881 .map(|(tasks, project)| {
4882 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4883 });
4884
4885 Some(cx.spawn(|editor, mut cx| async move {
4886 let task_context = match task_context {
4887 Some(task_context) => task_context.await,
4888 None => None,
4889 };
4890 let resolved_tasks =
4891 tasks.zip(task_context).map(|(tasks, task_context)| {
4892 Arc::new(ResolvedTasks {
4893 templates: tasks.resolve(&task_context).collect(),
4894 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4895 multibuffer_point.row,
4896 tasks.column,
4897 )),
4898 })
4899 });
4900 let spawn_straight_away = resolved_tasks
4901 .as_ref()
4902 .map_or(false, |tasks| tasks.templates.len() == 1)
4903 && code_actions
4904 .as_ref()
4905 .map_or(true, |actions| actions.is_empty());
4906 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4907 *editor.context_menu.write() =
4908 Some(ContextMenu::CodeActions(CodeActionsMenu {
4909 buffer,
4910 actions: CodeActionContents {
4911 tasks: resolved_tasks,
4912 actions: code_actions,
4913 },
4914 selected_item: Default::default(),
4915 scroll_handle: UniformListScrollHandle::default(),
4916 deployed_from_indicator,
4917 }));
4918 if spawn_straight_away {
4919 if let Some(task) = editor.confirm_code_action(
4920 &ConfirmCodeAction { item_ix: Some(0) },
4921 cx,
4922 ) {
4923 cx.notify();
4924 return task;
4925 }
4926 }
4927 cx.notify();
4928 Task::ready(Ok(()))
4929 }) {
4930 task.await
4931 } else {
4932 Ok(())
4933 }
4934 }))
4935 } else {
4936 Some(Task::ready(Ok(())))
4937 }
4938 })?;
4939 if let Some(task) = spawned_test_task {
4940 task.await?;
4941 }
4942
4943 Ok::<_, anyhow::Error>(())
4944 })
4945 .detach_and_log_err(cx);
4946 }
4947
4948 pub fn confirm_code_action(
4949 &mut self,
4950 action: &ConfirmCodeAction,
4951 cx: &mut ViewContext<Self>,
4952 ) -> Option<Task<Result<()>>> {
4953 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4954 menu
4955 } else {
4956 return None;
4957 };
4958 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4959 let action = actions_menu.actions.get(action_ix)?;
4960 let title = action.label();
4961 let buffer = actions_menu.buffer;
4962 let workspace = self.workspace()?;
4963
4964 match action {
4965 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4966 workspace.update(cx, |workspace, cx| {
4967 workspace::tasks::schedule_resolved_task(
4968 workspace,
4969 task_source_kind,
4970 resolved_task,
4971 false,
4972 cx,
4973 );
4974
4975 Some(Task::ready(Ok(())))
4976 })
4977 }
4978 CodeActionsItem::CodeAction {
4979 excerpt_id,
4980 action,
4981 provider,
4982 } => {
4983 let apply_code_action =
4984 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4985 let workspace = workspace.downgrade();
4986 Some(cx.spawn(|editor, cx| async move {
4987 let project_transaction = apply_code_action.await?;
4988 Self::open_project_transaction(
4989 &editor,
4990 workspace,
4991 project_transaction,
4992 title,
4993 cx,
4994 )
4995 .await
4996 }))
4997 }
4998 }
4999 }
5000
5001 pub async fn open_project_transaction(
5002 this: &WeakView<Editor>,
5003 workspace: WeakView<Workspace>,
5004 transaction: ProjectTransaction,
5005 title: String,
5006 mut cx: AsyncWindowContext,
5007 ) -> Result<()> {
5008 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
5009 cx.update(|cx| {
5010 entries.sort_unstable_by_key(|(buffer, _)| {
5011 buffer.read(cx).file().map(|f| f.path().clone())
5012 });
5013 })?;
5014
5015 // If the project transaction's edits are all contained within this editor, then
5016 // avoid opening a new editor to display them.
5017
5018 if let Some((buffer, transaction)) = entries.first() {
5019 if entries.len() == 1 {
5020 let excerpt = this.update(&mut cx, |editor, cx| {
5021 editor
5022 .buffer()
5023 .read(cx)
5024 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
5025 })?;
5026 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
5027 if excerpted_buffer == *buffer {
5028 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
5029 let excerpt_range = excerpt_range.to_offset(buffer);
5030 buffer
5031 .edited_ranges_for_transaction::<usize>(transaction)
5032 .all(|range| {
5033 excerpt_range.start <= range.start
5034 && excerpt_range.end >= range.end
5035 })
5036 })?;
5037
5038 if all_edits_within_excerpt {
5039 return Ok(());
5040 }
5041 }
5042 }
5043 }
5044 } else {
5045 return Ok(());
5046 }
5047
5048 let mut ranges_to_highlight = Vec::new();
5049 let excerpt_buffer = cx.new_model(|cx| {
5050 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5051 for (buffer_handle, transaction) in &entries {
5052 let buffer = buffer_handle.read(cx);
5053 ranges_to_highlight.extend(
5054 multibuffer.push_excerpts_with_context_lines(
5055 buffer_handle.clone(),
5056 buffer
5057 .edited_ranges_for_transaction::<usize>(transaction)
5058 .collect(),
5059 DEFAULT_MULTIBUFFER_CONTEXT,
5060 cx,
5061 ),
5062 );
5063 }
5064 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5065 multibuffer
5066 })?;
5067
5068 workspace.update(&mut cx, |workspace, cx| {
5069 let project = workspace.project().clone();
5070 let editor =
5071 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
5072 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
5073 editor.update(cx, |editor, cx| {
5074 editor.highlight_background::<Self>(
5075 &ranges_to_highlight,
5076 |theme| theme.editor_highlighted_line_background,
5077 cx,
5078 );
5079 });
5080 })?;
5081
5082 Ok(())
5083 }
5084
5085 pub fn clear_code_action_providers(&mut self) {
5086 self.code_action_providers.clear();
5087 self.available_code_actions.take();
5088 }
5089
5090 pub fn push_code_action_provider(
5091 &mut self,
5092 provider: Arc<dyn CodeActionProvider>,
5093 cx: &mut ViewContext<Self>,
5094 ) {
5095 self.code_action_providers.push(provider);
5096 self.refresh_code_actions(cx);
5097 }
5098
5099 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5100 let buffer = self.buffer.read(cx);
5101 let newest_selection = self.selections.newest_anchor().clone();
5102 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
5103 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
5104 if start_buffer != end_buffer {
5105 return None;
5106 }
5107
5108 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
5109 cx.background_executor()
5110 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5111 .await;
5112
5113 let (providers, tasks) = this.update(&mut cx, |this, cx| {
5114 let providers = this.code_action_providers.clone();
5115 let tasks = this
5116 .code_action_providers
5117 .iter()
5118 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
5119 .collect::<Vec<_>>();
5120 (providers, tasks)
5121 })?;
5122
5123 let mut actions = Vec::new();
5124 for (provider, provider_actions) in
5125 providers.into_iter().zip(future::join_all(tasks).await)
5126 {
5127 if let Some(provider_actions) = provider_actions.log_err() {
5128 actions.extend(provider_actions.into_iter().map(|action| {
5129 AvailableCodeAction {
5130 excerpt_id: newest_selection.start.excerpt_id,
5131 action,
5132 provider: provider.clone(),
5133 }
5134 }));
5135 }
5136 }
5137
5138 this.update(&mut cx, |this, cx| {
5139 this.available_code_actions = if actions.is_empty() {
5140 None
5141 } else {
5142 Some((
5143 Location {
5144 buffer: start_buffer,
5145 range: start..end,
5146 },
5147 actions.into(),
5148 ))
5149 };
5150 cx.notify();
5151 })
5152 }));
5153 None
5154 }
5155
5156 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
5157 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5158 self.show_git_blame_inline = false;
5159
5160 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
5161 cx.background_executor().timer(delay).await;
5162
5163 this.update(&mut cx, |this, cx| {
5164 this.show_git_blame_inline = true;
5165 cx.notify();
5166 })
5167 .log_err();
5168 }));
5169 }
5170 }
5171
5172 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5173 if self.pending_rename.is_some() {
5174 return None;
5175 }
5176
5177 let provider = self.semantics_provider.clone()?;
5178 let buffer = self.buffer.read(cx);
5179 let newest_selection = self.selections.newest_anchor().clone();
5180 let cursor_position = newest_selection.head();
5181 let (cursor_buffer, cursor_buffer_position) =
5182 buffer.text_anchor_for_position(cursor_position, cx)?;
5183 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5184 if cursor_buffer != tail_buffer {
5185 return None;
5186 }
5187
5188 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
5189 cx.background_executor()
5190 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
5191 .await;
5192
5193 let highlights = if let Some(highlights) = cx
5194 .update(|cx| {
5195 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5196 })
5197 .ok()
5198 .flatten()
5199 {
5200 highlights.await.log_err()
5201 } else {
5202 None
5203 };
5204
5205 if let Some(highlights) = highlights {
5206 this.update(&mut cx, |this, cx| {
5207 if this.pending_rename.is_some() {
5208 return;
5209 }
5210
5211 let buffer_id = cursor_position.buffer_id;
5212 let buffer = this.buffer.read(cx);
5213 if !buffer
5214 .text_anchor_for_position(cursor_position, cx)
5215 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5216 {
5217 return;
5218 }
5219
5220 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5221 let mut write_ranges = Vec::new();
5222 let mut read_ranges = Vec::new();
5223 for highlight in highlights {
5224 for (excerpt_id, excerpt_range) in
5225 buffer.excerpts_for_buffer(&cursor_buffer, cx)
5226 {
5227 let start = highlight
5228 .range
5229 .start
5230 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5231 let end = highlight
5232 .range
5233 .end
5234 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5235 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5236 continue;
5237 }
5238
5239 let range = Anchor {
5240 buffer_id,
5241 excerpt_id,
5242 text_anchor: start,
5243 }..Anchor {
5244 buffer_id,
5245 excerpt_id,
5246 text_anchor: end,
5247 };
5248 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5249 write_ranges.push(range);
5250 } else {
5251 read_ranges.push(range);
5252 }
5253 }
5254 }
5255
5256 this.highlight_background::<DocumentHighlightRead>(
5257 &read_ranges,
5258 |theme| theme.editor_document_highlight_read_background,
5259 cx,
5260 );
5261 this.highlight_background::<DocumentHighlightWrite>(
5262 &write_ranges,
5263 |theme| theme.editor_document_highlight_write_background,
5264 cx,
5265 );
5266 cx.notify();
5267 })
5268 .log_err();
5269 }
5270 }));
5271 None
5272 }
5273
5274 pub fn refresh_inline_completion(
5275 &mut self,
5276 debounce: bool,
5277 user_requested: bool,
5278 cx: &mut ViewContext<Self>,
5279 ) -> Option<()> {
5280 let provider = self.inline_completion_provider()?;
5281 let cursor = self.selections.newest_anchor().head();
5282 let (buffer, cursor_buffer_position) =
5283 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5284
5285 if !user_requested
5286 && (!self.enable_inline_completions
5287 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
5288 {
5289 self.discard_inline_completion(false, cx);
5290 return None;
5291 }
5292
5293 self.update_visible_inline_completion(cx);
5294 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
5295 Some(())
5296 }
5297
5298 fn cycle_inline_completion(
5299 &mut self,
5300 direction: Direction,
5301 cx: &mut ViewContext<Self>,
5302 ) -> Option<()> {
5303 let provider = self.inline_completion_provider()?;
5304 let cursor = self.selections.newest_anchor().head();
5305 let (buffer, cursor_buffer_position) =
5306 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5307 if !self.enable_inline_completions
5308 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5309 {
5310 return None;
5311 }
5312
5313 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5314 self.update_visible_inline_completion(cx);
5315
5316 Some(())
5317 }
5318
5319 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5320 if !self.has_active_inline_completion(cx) {
5321 self.refresh_inline_completion(false, true, cx);
5322 return;
5323 }
5324
5325 self.update_visible_inline_completion(cx);
5326 }
5327
5328 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5329 self.show_cursor_names(cx);
5330 }
5331
5332 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5333 self.show_cursor_names = true;
5334 cx.notify();
5335 cx.spawn(|this, mut cx| async move {
5336 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5337 this.update(&mut cx, |this, cx| {
5338 this.show_cursor_names = false;
5339 cx.notify()
5340 })
5341 .ok()
5342 })
5343 .detach();
5344 }
5345
5346 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5347 if self.has_active_inline_completion(cx) {
5348 self.cycle_inline_completion(Direction::Next, cx);
5349 } else {
5350 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5351 if is_copilot_disabled {
5352 cx.propagate();
5353 }
5354 }
5355 }
5356
5357 pub fn previous_inline_completion(
5358 &mut self,
5359 _: &PreviousInlineCompletion,
5360 cx: &mut ViewContext<Self>,
5361 ) {
5362 if self.has_active_inline_completion(cx) {
5363 self.cycle_inline_completion(Direction::Prev, cx);
5364 } else {
5365 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5366 if is_copilot_disabled {
5367 cx.propagate();
5368 }
5369 }
5370 }
5371
5372 pub fn accept_inline_completion(
5373 &mut self,
5374 _: &AcceptInlineCompletion,
5375 cx: &mut ViewContext<Self>,
5376 ) {
5377 let Some(completion) = self.take_active_inline_completion(cx) else {
5378 return;
5379 };
5380 if let Some(provider) = self.inline_completion_provider() {
5381 provider.accept(cx);
5382 }
5383
5384 cx.emit(EditorEvent::InputHandled {
5385 utf16_range_to_replace: None,
5386 text: completion.text.to_string().into(),
5387 });
5388
5389 if let Some(range) = completion.delete_range {
5390 self.change_selections(None, cx, |s| s.select_ranges([range]))
5391 }
5392 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5393 self.refresh_inline_completion(true, true, cx);
5394 cx.notify();
5395 }
5396
5397 pub fn accept_partial_inline_completion(
5398 &mut self,
5399 _: &AcceptPartialInlineCompletion,
5400 cx: &mut ViewContext<Self>,
5401 ) {
5402 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5403 if let Some(completion) = self.take_active_inline_completion(cx) {
5404 let mut partial_completion = completion
5405 .text
5406 .chars()
5407 .by_ref()
5408 .take_while(|c| c.is_alphabetic())
5409 .collect::<String>();
5410 if partial_completion.is_empty() {
5411 partial_completion = completion
5412 .text
5413 .chars()
5414 .by_ref()
5415 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5416 .collect::<String>();
5417 }
5418
5419 cx.emit(EditorEvent::InputHandled {
5420 utf16_range_to_replace: None,
5421 text: partial_completion.clone().into(),
5422 });
5423
5424 if let Some(range) = completion.delete_range {
5425 self.change_selections(None, cx, |s| s.select_ranges([range]))
5426 }
5427 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5428
5429 self.refresh_inline_completion(true, true, cx);
5430 cx.notify();
5431 }
5432 }
5433 }
5434
5435 fn discard_inline_completion(
5436 &mut self,
5437 should_report_inline_completion_event: bool,
5438 cx: &mut ViewContext<Self>,
5439 ) -> bool {
5440 if let Some(provider) = self.inline_completion_provider() {
5441 provider.discard(should_report_inline_completion_event, cx);
5442 }
5443
5444 self.take_active_inline_completion(cx).is_some()
5445 }
5446
5447 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5448 if let Some(completion) = self.active_inline_completion.as_ref() {
5449 let buffer = self.buffer.read(cx).read(cx);
5450 completion.position.is_valid(&buffer)
5451 } else {
5452 false
5453 }
5454 }
5455
5456 fn take_active_inline_completion(
5457 &mut self,
5458 cx: &mut ViewContext<Self>,
5459 ) -> Option<CompletionState> {
5460 let completion = self.active_inline_completion.take()?;
5461 let render_inlay_ids = completion.render_inlay_ids.clone();
5462 self.display_map.update(cx, |map, cx| {
5463 map.splice_inlays(render_inlay_ids, Default::default(), cx);
5464 });
5465 let buffer = self.buffer.read(cx).read(cx);
5466
5467 if completion.position.is_valid(&buffer) {
5468 Some(completion)
5469 } else {
5470 None
5471 }
5472 }
5473
5474 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5475 let selection = self.selections.newest_anchor();
5476 let cursor = selection.head();
5477
5478 let excerpt_id = cursor.excerpt_id;
5479
5480 if self.context_menu.read().is_none()
5481 && self.completion_tasks.is_empty()
5482 && selection.start == selection.end
5483 {
5484 if let Some(provider) = self.inline_completion_provider() {
5485 if let Some((buffer, cursor_buffer_position)) =
5486 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5487 {
5488 if let Some(proposal) =
5489 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5490 {
5491 let mut to_remove = Vec::new();
5492 if let Some(completion) = self.active_inline_completion.take() {
5493 to_remove.extend(completion.render_inlay_ids.iter());
5494 }
5495
5496 let to_add = proposal
5497 .inlays
5498 .iter()
5499 .filter_map(|inlay| {
5500 let snapshot = self.buffer.read(cx).snapshot(cx);
5501 let id = post_inc(&mut self.next_inlay_id);
5502 match inlay {
5503 InlayProposal::Hint(position, hint) => {
5504 let position =
5505 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5506 Some(Inlay::hint(id, position, hint))
5507 }
5508 InlayProposal::Suggestion(position, text) => {
5509 let position =
5510 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5511 Some(Inlay::suggestion(id, position, text.clone()))
5512 }
5513 }
5514 })
5515 .collect_vec();
5516
5517 self.active_inline_completion = Some(CompletionState {
5518 position: cursor,
5519 text: proposal.text,
5520 delete_range: proposal.delete_range.and_then(|range| {
5521 let snapshot = self.buffer.read(cx).snapshot(cx);
5522 let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
5523 let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
5524 Some(start?..end?)
5525 }),
5526 render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
5527 });
5528
5529 self.display_map
5530 .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
5531
5532 cx.notify();
5533 return;
5534 }
5535 }
5536 }
5537 }
5538
5539 self.discard_inline_completion(false, cx);
5540 }
5541
5542 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5543 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5544 }
5545
5546 fn render_code_actions_indicator(
5547 &self,
5548 _style: &EditorStyle,
5549 row: DisplayRow,
5550 is_active: bool,
5551 cx: &mut ViewContext<Self>,
5552 ) -> Option<IconButton> {
5553 if self.available_code_actions.is_some() {
5554 Some(
5555 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5556 .shape(ui::IconButtonShape::Square)
5557 .icon_size(IconSize::XSmall)
5558 .icon_color(Color::Muted)
5559 .selected(is_active)
5560 .tooltip({
5561 let focus_handle = self.focus_handle.clone();
5562 move |cx| {
5563 Tooltip::for_action_in(
5564 "Toggle Code Actions",
5565 &ToggleCodeActions {
5566 deployed_from_indicator: None,
5567 },
5568 &focus_handle,
5569 cx,
5570 )
5571 }
5572 })
5573 .on_click(cx.listener(move |editor, _e, cx| {
5574 editor.focus(cx);
5575 editor.toggle_code_actions(
5576 &ToggleCodeActions {
5577 deployed_from_indicator: Some(row),
5578 },
5579 cx,
5580 );
5581 })),
5582 )
5583 } else {
5584 None
5585 }
5586 }
5587
5588 fn clear_tasks(&mut self) {
5589 self.tasks.clear()
5590 }
5591
5592 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5593 if self.tasks.insert(key, value).is_some() {
5594 // This case should hopefully be rare, but just in case...
5595 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5596 }
5597 }
5598
5599 fn build_tasks_context(
5600 project: &Model<Project>,
5601 buffer: &Model<Buffer>,
5602 buffer_row: u32,
5603 tasks: &Arc<RunnableTasks>,
5604 cx: &mut ViewContext<Self>,
5605 ) -> Task<Option<task::TaskContext>> {
5606 let position = Point::new(buffer_row, tasks.column);
5607 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5608 let location = Location {
5609 buffer: buffer.clone(),
5610 range: range_start..range_start,
5611 };
5612 // Fill in the environmental variables from the tree-sitter captures
5613 let mut captured_task_variables = TaskVariables::default();
5614 for (capture_name, value) in tasks.extra_variables.clone() {
5615 captured_task_variables.insert(
5616 task::VariableName::Custom(capture_name.into()),
5617 value.clone(),
5618 );
5619 }
5620 project.update(cx, |project, cx| {
5621 project.task_store().update(cx, |task_store, cx| {
5622 task_store.task_context_for_location(captured_task_variables, location, cx)
5623 })
5624 })
5625 }
5626
5627 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
5628 let Some((workspace, _)) = self.workspace.clone() else {
5629 return;
5630 };
5631 let Some(project) = self.project.clone() else {
5632 return;
5633 };
5634
5635 // Try to find a closest, enclosing node using tree-sitter that has a
5636 // task
5637 let Some((buffer, buffer_row, tasks)) = self
5638 .find_enclosing_node_task(cx)
5639 // Or find the task that's closest in row-distance.
5640 .or_else(|| self.find_closest_task(cx))
5641 else {
5642 return;
5643 };
5644
5645 let reveal_strategy = action.reveal;
5646 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5647 cx.spawn(|_, mut cx| async move {
5648 let context = task_context.await?;
5649 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5650
5651 let resolved = resolved_task.resolved.as_mut()?;
5652 resolved.reveal = reveal_strategy;
5653
5654 workspace
5655 .update(&mut cx, |workspace, cx| {
5656 workspace::tasks::schedule_resolved_task(
5657 workspace,
5658 task_source_kind,
5659 resolved_task,
5660 false,
5661 cx,
5662 );
5663 })
5664 .ok()
5665 })
5666 .detach();
5667 }
5668
5669 fn find_closest_task(
5670 &mut self,
5671 cx: &mut ViewContext<Self>,
5672 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5673 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5674
5675 let ((buffer_id, row), tasks) = self
5676 .tasks
5677 .iter()
5678 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5679
5680 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5681 let tasks = Arc::new(tasks.to_owned());
5682 Some((buffer, *row, tasks))
5683 }
5684
5685 fn find_enclosing_node_task(
5686 &mut self,
5687 cx: &mut ViewContext<Self>,
5688 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5689 let snapshot = self.buffer.read(cx).snapshot(cx);
5690 let offset = self.selections.newest::<usize>(cx).head();
5691 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5692 let buffer_id = excerpt.buffer().remote_id();
5693
5694 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5695 let mut cursor = layer.node().walk();
5696
5697 while cursor.goto_first_child_for_byte(offset).is_some() {
5698 if cursor.node().end_byte() == offset {
5699 cursor.goto_next_sibling();
5700 }
5701 }
5702
5703 // Ascend to the smallest ancestor that contains the range and has a task.
5704 loop {
5705 let node = cursor.node();
5706 let node_range = node.byte_range();
5707 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5708
5709 // Check if this node contains our offset
5710 if node_range.start <= offset && node_range.end >= offset {
5711 // If it contains offset, check for task
5712 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5713 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5714 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5715 }
5716 }
5717
5718 if !cursor.goto_parent() {
5719 break;
5720 }
5721 }
5722 None
5723 }
5724
5725 fn render_run_indicator(
5726 &self,
5727 _style: &EditorStyle,
5728 is_active: bool,
5729 row: DisplayRow,
5730 cx: &mut ViewContext<Self>,
5731 ) -> IconButton {
5732 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5733 .shape(ui::IconButtonShape::Square)
5734 .icon_size(IconSize::XSmall)
5735 .icon_color(Color::Muted)
5736 .selected(is_active)
5737 .on_click(cx.listener(move |editor, _e, cx| {
5738 editor.focus(cx);
5739 editor.toggle_code_actions(
5740 &ToggleCodeActions {
5741 deployed_from_indicator: Some(row),
5742 },
5743 cx,
5744 );
5745 }))
5746 }
5747
5748 pub fn context_menu_visible(&self) -> bool {
5749 self.context_menu
5750 .read()
5751 .as_ref()
5752 .map_or(false, |menu| menu.visible())
5753 }
5754
5755 fn render_context_menu(
5756 &self,
5757 cursor_position: DisplayPoint,
5758 style: &EditorStyle,
5759 max_height: Pixels,
5760 cx: &mut ViewContext<Editor>,
5761 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5762 self.context_menu.read().as_ref().map(|menu| {
5763 menu.render(
5764 cursor_position,
5765 style,
5766 max_height,
5767 self.workspace.as_ref().map(|(w, _)| w.clone()),
5768 cx,
5769 )
5770 })
5771 }
5772
5773 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5774 cx.notify();
5775 self.completion_tasks.clear();
5776 let context_menu = self.context_menu.write().take();
5777 if context_menu.is_some() {
5778 self.update_visible_inline_completion(cx);
5779 }
5780 context_menu
5781 }
5782
5783 fn show_snippet_choices(
5784 &mut self,
5785 choices: &Vec<String>,
5786 selection: Range<Anchor>,
5787 cx: &mut ViewContext<Self>,
5788 ) {
5789 if selection.start.buffer_id.is_none() {
5790 return;
5791 }
5792 let buffer_id = selection.start.buffer_id.unwrap();
5793 let buffer = self.buffer().read(cx).buffer(buffer_id);
5794 let id = post_inc(&mut self.next_completion_id);
5795
5796 if let Some(buffer) = buffer {
5797 *self.context_menu.write() = Some(ContextMenu::Completions(
5798 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer)
5799 .suppress_documentation_resolution(),
5800 ));
5801 }
5802 }
5803
5804 pub fn insert_snippet(
5805 &mut self,
5806 insertion_ranges: &[Range<usize>],
5807 snippet: Snippet,
5808 cx: &mut ViewContext<Self>,
5809 ) -> Result<()> {
5810 struct Tabstop<T> {
5811 is_end_tabstop: bool,
5812 ranges: Vec<Range<T>>,
5813 choices: Option<Vec<String>>,
5814 }
5815
5816 let tabstops = self.buffer.update(cx, |buffer, cx| {
5817 let snippet_text: Arc<str> = snippet.text.clone().into();
5818 buffer.edit(
5819 insertion_ranges
5820 .iter()
5821 .cloned()
5822 .map(|range| (range, snippet_text.clone())),
5823 Some(AutoindentMode::EachLine),
5824 cx,
5825 );
5826
5827 let snapshot = &*buffer.read(cx);
5828 let snippet = &snippet;
5829 snippet
5830 .tabstops
5831 .iter()
5832 .map(|tabstop| {
5833 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5834 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5835 });
5836 let mut tabstop_ranges = tabstop
5837 .ranges
5838 .iter()
5839 .flat_map(|tabstop_range| {
5840 let mut delta = 0_isize;
5841 insertion_ranges.iter().map(move |insertion_range| {
5842 let insertion_start = insertion_range.start as isize + delta;
5843 delta +=
5844 snippet.text.len() as isize - insertion_range.len() as isize;
5845
5846 let start = ((insertion_start + tabstop_range.start) as usize)
5847 .min(snapshot.len());
5848 let end = ((insertion_start + tabstop_range.end) as usize)
5849 .min(snapshot.len());
5850 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5851 })
5852 })
5853 .collect::<Vec<_>>();
5854 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5855
5856 Tabstop {
5857 is_end_tabstop,
5858 ranges: tabstop_ranges,
5859 choices: tabstop.choices.clone(),
5860 }
5861 })
5862 .collect::<Vec<_>>()
5863 });
5864 if let Some(tabstop) = tabstops.first() {
5865 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5866 s.select_ranges(tabstop.ranges.iter().cloned());
5867 });
5868
5869 if let Some(choices) = &tabstop.choices {
5870 if let Some(selection) = tabstop.ranges.first() {
5871 self.show_snippet_choices(choices, selection.clone(), cx)
5872 }
5873 }
5874
5875 // If we're already at the last tabstop and it's at the end of the snippet,
5876 // we're done, we don't need to keep the state around.
5877 if !tabstop.is_end_tabstop {
5878 let choices = tabstops
5879 .iter()
5880 .map(|tabstop| tabstop.choices.clone())
5881 .collect();
5882
5883 let ranges = tabstops
5884 .into_iter()
5885 .map(|tabstop| tabstop.ranges)
5886 .collect::<Vec<_>>();
5887
5888 self.snippet_stack.push(SnippetState {
5889 active_index: 0,
5890 ranges,
5891 choices,
5892 });
5893 }
5894
5895 // Check whether the just-entered snippet ends with an auto-closable bracket.
5896 if self.autoclose_regions.is_empty() {
5897 let snapshot = self.buffer.read(cx).snapshot(cx);
5898 for selection in &mut self.selections.all::<Point>(cx) {
5899 let selection_head = selection.head();
5900 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5901 continue;
5902 };
5903
5904 let mut bracket_pair = None;
5905 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5906 let prev_chars = snapshot
5907 .reversed_chars_at(selection_head)
5908 .collect::<String>();
5909 for (pair, enabled) in scope.brackets() {
5910 if enabled
5911 && pair.close
5912 && prev_chars.starts_with(pair.start.as_str())
5913 && next_chars.starts_with(pair.end.as_str())
5914 {
5915 bracket_pair = Some(pair.clone());
5916 break;
5917 }
5918 }
5919 if let Some(pair) = bracket_pair {
5920 let start = snapshot.anchor_after(selection_head);
5921 let end = snapshot.anchor_after(selection_head);
5922 self.autoclose_regions.push(AutocloseRegion {
5923 selection_id: selection.id,
5924 range: start..end,
5925 pair,
5926 });
5927 }
5928 }
5929 }
5930 }
5931 Ok(())
5932 }
5933
5934 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5935 self.move_to_snippet_tabstop(Bias::Right, cx)
5936 }
5937
5938 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5939 self.move_to_snippet_tabstop(Bias::Left, cx)
5940 }
5941
5942 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5943 if let Some(mut snippet) = self.snippet_stack.pop() {
5944 match bias {
5945 Bias::Left => {
5946 if snippet.active_index > 0 {
5947 snippet.active_index -= 1;
5948 } else {
5949 self.snippet_stack.push(snippet);
5950 return false;
5951 }
5952 }
5953 Bias::Right => {
5954 if snippet.active_index + 1 < snippet.ranges.len() {
5955 snippet.active_index += 1;
5956 } else {
5957 self.snippet_stack.push(snippet);
5958 return false;
5959 }
5960 }
5961 }
5962 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5963 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5964 s.select_anchor_ranges(current_ranges.iter().cloned())
5965 });
5966
5967 if let Some(choices) = &snippet.choices[snippet.active_index] {
5968 if let Some(selection) = current_ranges.first() {
5969 self.show_snippet_choices(&choices, selection.clone(), cx);
5970 }
5971 }
5972
5973 // If snippet state is not at the last tabstop, push it back on the stack
5974 if snippet.active_index + 1 < snippet.ranges.len() {
5975 self.snippet_stack.push(snippet);
5976 }
5977 return true;
5978 }
5979 }
5980
5981 false
5982 }
5983
5984 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5985 self.transact(cx, |this, cx| {
5986 this.select_all(&SelectAll, cx);
5987 this.insert("", cx);
5988 });
5989 }
5990
5991 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5992 self.transact(cx, |this, cx| {
5993 this.select_autoclose_pair(cx);
5994 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5995 if !this.linked_edit_ranges.is_empty() {
5996 let selections = this.selections.all::<MultiBufferPoint>(cx);
5997 let snapshot = this.buffer.read(cx).snapshot(cx);
5998
5999 for selection in selections.iter() {
6000 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6001 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6002 if selection_start.buffer_id != selection_end.buffer_id {
6003 continue;
6004 }
6005 if let Some(ranges) =
6006 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6007 {
6008 for (buffer, entries) in ranges {
6009 linked_ranges.entry(buffer).or_default().extend(entries);
6010 }
6011 }
6012 }
6013 }
6014
6015 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6016 if !this.selections.line_mode {
6017 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6018 for selection in &mut selections {
6019 if selection.is_empty() {
6020 let old_head = selection.head();
6021 let mut new_head =
6022 movement::left(&display_map, old_head.to_display_point(&display_map))
6023 .to_point(&display_map);
6024 if let Some((buffer, line_buffer_range)) = display_map
6025 .buffer_snapshot
6026 .buffer_line_for_row(MultiBufferRow(old_head.row))
6027 {
6028 let indent_size =
6029 buffer.indent_size_for_line(line_buffer_range.start.row);
6030 let indent_len = match indent_size.kind {
6031 IndentKind::Space => {
6032 buffer.settings_at(line_buffer_range.start, cx).tab_size
6033 }
6034 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6035 };
6036 if old_head.column <= indent_size.len && old_head.column > 0 {
6037 let indent_len = indent_len.get();
6038 new_head = cmp::min(
6039 new_head,
6040 MultiBufferPoint::new(
6041 old_head.row,
6042 ((old_head.column - 1) / indent_len) * indent_len,
6043 ),
6044 );
6045 }
6046 }
6047
6048 selection.set_head(new_head, SelectionGoal::None);
6049 }
6050 }
6051 }
6052
6053 this.signature_help_state.set_backspace_pressed(true);
6054 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6055 this.insert("", cx);
6056 let empty_str: Arc<str> = Arc::from("");
6057 for (buffer, edits) in linked_ranges {
6058 let snapshot = buffer.read(cx).snapshot();
6059 use text::ToPoint as TP;
6060
6061 let edits = edits
6062 .into_iter()
6063 .map(|range| {
6064 let end_point = TP::to_point(&range.end, &snapshot);
6065 let mut start_point = TP::to_point(&range.start, &snapshot);
6066
6067 if end_point == start_point {
6068 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6069 .saturating_sub(1);
6070 start_point = TP::to_point(&offset, &snapshot);
6071 };
6072
6073 (start_point..end_point, empty_str.clone())
6074 })
6075 .sorted_by_key(|(range, _)| range.start)
6076 .collect::<Vec<_>>();
6077 buffer.update(cx, |this, cx| {
6078 this.edit(edits, None, cx);
6079 })
6080 }
6081 this.refresh_inline_completion(true, false, cx);
6082 linked_editing_ranges::refresh_linked_ranges(this, cx);
6083 });
6084 }
6085
6086 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
6087 self.transact(cx, |this, cx| {
6088 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6089 let line_mode = s.line_mode;
6090 s.move_with(|map, selection| {
6091 if selection.is_empty() && !line_mode {
6092 let cursor = movement::right(map, selection.head());
6093 selection.end = cursor;
6094 selection.reversed = true;
6095 selection.goal = SelectionGoal::None;
6096 }
6097 })
6098 });
6099 this.insert("", cx);
6100 this.refresh_inline_completion(true, false, cx);
6101 });
6102 }
6103
6104 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
6105 if self.move_to_prev_snippet_tabstop(cx) {
6106 return;
6107 }
6108
6109 self.outdent(&Outdent, cx);
6110 }
6111
6112 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
6113 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
6114 return;
6115 }
6116
6117 let mut selections = self.selections.all_adjusted(cx);
6118 let buffer = self.buffer.read(cx);
6119 let snapshot = buffer.snapshot(cx);
6120 let rows_iter = selections.iter().map(|s| s.head().row);
6121 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6122
6123 let mut edits = Vec::new();
6124 let mut prev_edited_row = 0;
6125 let mut row_delta = 0;
6126 for selection in &mut selections {
6127 if selection.start.row != prev_edited_row {
6128 row_delta = 0;
6129 }
6130 prev_edited_row = selection.end.row;
6131
6132 // If the selection is non-empty, then increase the indentation of the selected lines.
6133 if !selection.is_empty() {
6134 row_delta =
6135 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6136 continue;
6137 }
6138
6139 // If the selection is empty and the cursor is in the leading whitespace before the
6140 // suggested indentation, then auto-indent the line.
6141 let cursor = selection.head();
6142 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6143 if let Some(suggested_indent) =
6144 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6145 {
6146 if cursor.column < suggested_indent.len
6147 && cursor.column <= current_indent.len
6148 && current_indent.len <= suggested_indent.len
6149 {
6150 selection.start = Point::new(cursor.row, suggested_indent.len);
6151 selection.end = selection.start;
6152 if row_delta == 0 {
6153 edits.extend(Buffer::edit_for_indent_size_adjustment(
6154 cursor.row,
6155 current_indent,
6156 suggested_indent,
6157 ));
6158 row_delta = suggested_indent.len - current_indent.len;
6159 }
6160 continue;
6161 }
6162 }
6163
6164 // Otherwise, insert a hard or soft tab.
6165 let settings = buffer.settings_at(cursor, cx);
6166 let tab_size = if settings.hard_tabs {
6167 IndentSize::tab()
6168 } else {
6169 let tab_size = settings.tab_size.get();
6170 let char_column = snapshot
6171 .text_for_range(Point::new(cursor.row, 0)..cursor)
6172 .flat_map(str::chars)
6173 .count()
6174 + row_delta as usize;
6175 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6176 IndentSize::spaces(chars_to_next_tab_stop)
6177 };
6178 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6179 selection.end = selection.start;
6180 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6181 row_delta += tab_size.len;
6182 }
6183
6184 self.transact(cx, |this, cx| {
6185 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6186 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6187 this.refresh_inline_completion(true, false, cx);
6188 });
6189 }
6190
6191 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
6192 if self.read_only(cx) {
6193 return;
6194 }
6195 let mut selections = self.selections.all::<Point>(cx);
6196 let mut prev_edited_row = 0;
6197 let mut row_delta = 0;
6198 let mut edits = Vec::new();
6199 let buffer = self.buffer.read(cx);
6200 let snapshot = buffer.snapshot(cx);
6201 for selection in &mut selections {
6202 if selection.start.row != prev_edited_row {
6203 row_delta = 0;
6204 }
6205 prev_edited_row = selection.end.row;
6206
6207 row_delta =
6208 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6209 }
6210
6211 self.transact(cx, |this, cx| {
6212 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6213 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6214 });
6215 }
6216
6217 fn indent_selection(
6218 buffer: &MultiBuffer,
6219 snapshot: &MultiBufferSnapshot,
6220 selection: &mut Selection<Point>,
6221 edits: &mut Vec<(Range<Point>, String)>,
6222 delta_for_start_row: u32,
6223 cx: &AppContext,
6224 ) -> u32 {
6225 let settings = buffer.settings_at(selection.start, cx);
6226 let tab_size = settings.tab_size.get();
6227 let indent_kind = if settings.hard_tabs {
6228 IndentKind::Tab
6229 } else {
6230 IndentKind::Space
6231 };
6232 let mut start_row = selection.start.row;
6233 let mut end_row = selection.end.row + 1;
6234
6235 // If a selection ends at the beginning of a line, don't indent
6236 // that last line.
6237 if selection.end.column == 0 && selection.end.row > selection.start.row {
6238 end_row -= 1;
6239 }
6240
6241 // Avoid re-indenting a row that has already been indented by a
6242 // previous selection, but still update this selection's column
6243 // to reflect that indentation.
6244 if delta_for_start_row > 0 {
6245 start_row += 1;
6246 selection.start.column += delta_for_start_row;
6247 if selection.end.row == selection.start.row {
6248 selection.end.column += delta_for_start_row;
6249 }
6250 }
6251
6252 let mut delta_for_end_row = 0;
6253 let has_multiple_rows = start_row + 1 != end_row;
6254 for row in start_row..end_row {
6255 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6256 let indent_delta = match (current_indent.kind, indent_kind) {
6257 (IndentKind::Space, IndentKind::Space) => {
6258 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6259 IndentSize::spaces(columns_to_next_tab_stop)
6260 }
6261 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6262 (_, IndentKind::Tab) => IndentSize::tab(),
6263 };
6264
6265 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6266 0
6267 } else {
6268 selection.start.column
6269 };
6270 let row_start = Point::new(row, start);
6271 edits.push((
6272 row_start..row_start,
6273 indent_delta.chars().collect::<String>(),
6274 ));
6275
6276 // Update this selection's endpoints to reflect the indentation.
6277 if row == selection.start.row {
6278 selection.start.column += indent_delta.len;
6279 }
6280 if row == selection.end.row {
6281 selection.end.column += indent_delta.len;
6282 delta_for_end_row = indent_delta.len;
6283 }
6284 }
6285
6286 if selection.start.row == selection.end.row {
6287 delta_for_start_row + delta_for_end_row
6288 } else {
6289 delta_for_end_row
6290 }
6291 }
6292
6293 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
6294 if self.read_only(cx) {
6295 return;
6296 }
6297 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6298 let selections = self.selections.all::<Point>(cx);
6299 let mut deletion_ranges = Vec::new();
6300 let mut last_outdent = None;
6301 {
6302 let buffer = self.buffer.read(cx);
6303 let snapshot = buffer.snapshot(cx);
6304 for selection in &selections {
6305 let settings = buffer.settings_at(selection.start, cx);
6306 let tab_size = settings.tab_size.get();
6307 let mut rows = selection.spanned_rows(false, &display_map);
6308
6309 // Avoid re-outdenting a row that has already been outdented by a
6310 // previous selection.
6311 if let Some(last_row) = last_outdent {
6312 if last_row == rows.start {
6313 rows.start = rows.start.next_row();
6314 }
6315 }
6316 let has_multiple_rows = rows.len() > 1;
6317 for row in rows.iter_rows() {
6318 let indent_size = snapshot.indent_size_for_line(row);
6319 if indent_size.len > 0 {
6320 let deletion_len = match indent_size.kind {
6321 IndentKind::Space => {
6322 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6323 if columns_to_prev_tab_stop == 0 {
6324 tab_size
6325 } else {
6326 columns_to_prev_tab_stop
6327 }
6328 }
6329 IndentKind::Tab => 1,
6330 };
6331 let start = if has_multiple_rows
6332 || deletion_len > selection.start.column
6333 || indent_size.len < selection.start.column
6334 {
6335 0
6336 } else {
6337 selection.start.column - deletion_len
6338 };
6339 deletion_ranges.push(
6340 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6341 );
6342 last_outdent = Some(row);
6343 }
6344 }
6345 }
6346 }
6347
6348 self.transact(cx, |this, cx| {
6349 this.buffer.update(cx, |buffer, cx| {
6350 let empty_str: Arc<str> = Arc::default();
6351 buffer.edit(
6352 deletion_ranges
6353 .into_iter()
6354 .map(|range| (range, empty_str.clone())),
6355 None,
6356 cx,
6357 );
6358 });
6359 let selections = this.selections.all::<usize>(cx);
6360 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6361 });
6362 }
6363
6364 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
6365 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6366 let selections = self.selections.all::<Point>(cx);
6367
6368 let mut new_cursors = Vec::new();
6369 let mut edit_ranges = Vec::new();
6370 let mut selections = selections.iter().peekable();
6371 while let Some(selection) = selections.next() {
6372 let mut rows = selection.spanned_rows(false, &display_map);
6373 let goal_display_column = selection.head().to_display_point(&display_map).column();
6374
6375 // Accumulate contiguous regions of rows that we want to delete.
6376 while let Some(next_selection) = selections.peek() {
6377 let next_rows = next_selection.spanned_rows(false, &display_map);
6378 if next_rows.start <= rows.end {
6379 rows.end = next_rows.end;
6380 selections.next().unwrap();
6381 } else {
6382 break;
6383 }
6384 }
6385
6386 let buffer = &display_map.buffer_snapshot;
6387 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6388 let edit_end;
6389 let cursor_buffer_row;
6390 if buffer.max_point().row >= rows.end.0 {
6391 // If there's a line after the range, delete the \n from the end of the row range
6392 // and position the cursor on the next line.
6393 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6394 cursor_buffer_row = rows.end;
6395 } else {
6396 // If there isn't a line after the range, delete the \n from the line before the
6397 // start of the row range and position the cursor there.
6398 edit_start = edit_start.saturating_sub(1);
6399 edit_end = buffer.len();
6400 cursor_buffer_row = rows.start.previous_row();
6401 }
6402
6403 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6404 *cursor.column_mut() =
6405 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6406
6407 new_cursors.push((
6408 selection.id,
6409 buffer.anchor_after(cursor.to_point(&display_map)),
6410 ));
6411 edit_ranges.push(edit_start..edit_end);
6412 }
6413
6414 self.transact(cx, |this, cx| {
6415 let buffer = this.buffer.update(cx, |buffer, cx| {
6416 let empty_str: Arc<str> = Arc::default();
6417 buffer.edit(
6418 edit_ranges
6419 .into_iter()
6420 .map(|range| (range, empty_str.clone())),
6421 None,
6422 cx,
6423 );
6424 buffer.snapshot(cx)
6425 });
6426 let new_selections = new_cursors
6427 .into_iter()
6428 .map(|(id, cursor)| {
6429 let cursor = cursor.to_point(&buffer);
6430 Selection {
6431 id,
6432 start: cursor,
6433 end: cursor,
6434 reversed: false,
6435 goal: SelectionGoal::None,
6436 }
6437 })
6438 .collect();
6439
6440 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6441 s.select(new_selections);
6442 });
6443 });
6444 }
6445
6446 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6447 if self.read_only(cx) {
6448 return;
6449 }
6450 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6451 for selection in self.selections.all::<Point>(cx) {
6452 let start = MultiBufferRow(selection.start.row);
6453 // Treat single line selections as if they include the next line. Otherwise this action
6454 // would do nothing for single line selections individual cursors.
6455 let end = if selection.start.row == selection.end.row {
6456 MultiBufferRow(selection.start.row + 1)
6457 } else {
6458 MultiBufferRow(selection.end.row)
6459 };
6460
6461 if let Some(last_row_range) = row_ranges.last_mut() {
6462 if start <= last_row_range.end {
6463 last_row_range.end = end;
6464 continue;
6465 }
6466 }
6467 row_ranges.push(start..end);
6468 }
6469
6470 let snapshot = self.buffer.read(cx).snapshot(cx);
6471 let mut cursor_positions = Vec::new();
6472 for row_range in &row_ranges {
6473 let anchor = snapshot.anchor_before(Point::new(
6474 row_range.end.previous_row().0,
6475 snapshot.line_len(row_range.end.previous_row()),
6476 ));
6477 cursor_positions.push(anchor..anchor);
6478 }
6479
6480 self.transact(cx, |this, cx| {
6481 for row_range in row_ranges.into_iter().rev() {
6482 for row in row_range.iter_rows().rev() {
6483 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6484 let next_line_row = row.next_row();
6485 let indent = snapshot.indent_size_for_line(next_line_row);
6486 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6487
6488 let replace = if snapshot.line_len(next_line_row) > indent.len {
6489 " "
6490 } else {
6491 ""
6492 };
6493
6494 this.buffer.update(cx, |buffer, cx| {
6495 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6496 });
6497 }
6498 }
6499
6500 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6501 s.select_anchor_ranges(cursor_positions)
6502 });
6503 });
6504 }
6505
6506 pub fn sort_lines_case_sensitive(
6507 &mut self,
6508 _: &SortLinesCaseSensitive,
6509 cx: &mut ViewContext<Self>,
6510 ) {
6511 self.manipulate_lines(cx, |lines| lines.sort())
6512 }
6513
6514 pub fn sort_lines_case_insensitive(
6515 &mut self,
6516 _: &SortLinesCaseInsensitive,
6517 cx: &mut ViewContext<Self>,
6518 ) {
6519 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6520 }
6521
6522 pub fn unique_lines_case_insensitive(
6523 &mut self,
6524 _: &UniqueLinesCaseInsensitive,
6525 cx: &mut ViewContext<Self>,
6526 ) {
6527 self.manipulate_lines(cx, |lines| {
6528 let mut seen = HashSet::default();
6529 lines.retain(|line| seen.insert(line.to_lowercase()));
6530 })
6531 }
6532
6533 pub fn unique_lines_case_sensitive(
6534 &mut self,
6535 _: &UniqueLinesCaseSensitive,
6536 cx: &mut ViewContext<Self>,
6537 ) {
6538 self.manipulate_lines(cx, |lines| {
6539 let mut seen = HashSet::default();
6540 lines.retain(|line| seen.insert(*line));
6541 })
6542 }
6543
6544 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6545 let mut revert_changes = HashMap::default();
6546 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6547 for hunk in hunks_for_rows(
6548 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6549 &multi_buffer_snapshot,
6550 ) {
6551 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6552 }
6553 if !revert_changes.is_empty() {
6554 self.transact(cx, |editor, cx| {
6555 editor.revert(revert_changes, cx);
6556 });
6557 }
6558 }
6559
6560 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6561 let Some(project) = self.project.clone() else {
6562 return;
6563 };
6564 self.reload(project, cx).detach_and_notify_err(cx);
6565 }
6566
6567 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6568 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6569 if !revert_changes.is_empty() {
6570 self.transact(cx, |editor, cx| {
6571 editor.revert(revert_changes, cx);
6572 });
6573 }
6574 }
6575
6576 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6577 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6578 let project_path = buffer.read(cx).project_path(cx)?;
6579 let project = self.project.as_ref()?.read(cx);
6580 let entry = project.entry_for_path(&project_path, cx)?;
6581 let parent = match &entry.canonical_path {
6582 Some(canonical_path) => canonical_path.to_path_buf(),
6583 None => project.absolute_path(&project_path, cx)?,
6584 }
6585 .parent()?
6586 .to_path_buf();
6587 Some(parent)
6588 }) {
6589 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6590 }
6591 }
6592
6593 fn gather_revert_changes(
6594 &mut self,
6595 selections: &[Selection<Anchor>],
6596 cx: &mut ViewContext<'_, Editor>,
6597 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6598 let mut revert_changes = HashMap::default();
6599 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6600 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6601 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6602 }
6603 revert_changes
6604 }
6605
6606 pub fn prepare_revert_change(
6607 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6608 multi_buffer: &Model<MultiBuffer>,
6609 hunk: &MultiBufferDiffHunk,
6610 cx: &AppContext,
6611 ) -> Option<()> {
6612 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6613 let buffer = buffer.read(cx);
6614 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6615 let buffer_snapshot = buffer.snapshot();
6616 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6617 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6618 probe
6619 .0
6620 .start
6621 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6622 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6623 }) {
6624 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6625 Some(())
6626 } else {
6627 None
6628 }
6629 }
6630
6631 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6632 self.manipulate_lines(cx, |lines| lines.reverse())
6633 }
6634
6635 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6636 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6637 }
6638
6639 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6640 where
6641 Fn: FnMut(&mut Vec<&str>),
6642 {
6643 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6644 let buffer = self.buffer.read(cx).snapshot(cx);
6645
6646 let mut edits = Vec::new();
6647
6648 let selections = self.selections.all::<Point>(cx);
6649 let mut selections = selections.iter().peekable();
6650 let mut contiguous_row_selections = Vec::new();
6651 let mut new_selections = Vec::new();
6652 let mut added_lines = 0;
6653 let mut removed_lines = 0;
6654
6655 while let Some(selection) = selections.next() {
6656 let (start_row, end_row) = consume_contiguous_rows(
6657 &mut contiguous_row_selections,
6658 selection,
6659 &display_map,
6660 &mut selections,
6661 );
6662
6663 let start_point = Point::new(start_row.0, 0);
6664 let end_point = Point::new(
6665 end_row.previous_row().0,
6666 buffer.line_len(end_row.previous_row()),
6667 );
6668 let text = buffer
6669 .text_for_range(start_point..end_point)
6670 .collect::<String>();
6671
6672 let mut lines = text.split('\n').collect_vec();
6673
6674 let lines_before = lines.len();
6675 callback(&mut lines);
6676 let lines_after = lines.len();
6677
6678 edits.push((start_point..end_point, lines.join("\n")));
6679
6680 // Selections must change based on added and removed line count
6681 let start_row =
6682 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6683 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6684 new_selections.push(Selection {
6685 id: selection.id,
6686 start: start_row,
6687 end: end_row,
6688 goal: SelectionGoal::None,
6689 reversed: selection.reversed,
6690 });
6691
6692 if lines_after > lines_before {
6693 added_lines += lines_after - lines_before;
6694 } else if lines_before > lines_after {
6695 removed_lines += lines_before - lines_after;
6696 }
6697 }
6698
6699 self.transact(cx, |this, cx| {
6700 let buffer = this.buffer.update(cx, |buffer, cx| {
6701 buffer.edit(edits, None, cx);
6702 buffer.snapshot(cx)
6703 });
6704
6705 // Recalculate offsets on newly edited buffer
6706 let new_selections = new_selections
6707 .iter()
6708 .map(|s| {
6709 let start_point = Point::new(s.start.0, 0);
6710 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6711 Selection {
6712 id: s.id,
6713 start: buffer.point_to_offset(start_point),
6714 end: buffer.point_to_offset(end_point),
6715 goal: s.goal,
6716 reversed: s.reversed,
6717 }
6718 })
6719 .collect();
6720
6721 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6722 s.select(new_selections);
6723 });
6724
6725 this.request_autoscroll(Autoscroll::fit(), cx);
6726 });
6727 }
6728
6729 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6730 self.manipulate_text(cx, |text| text.to_uppercase())
6731 }
6732
6733 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6734 self.manipulate_text(cx, |text| text.to_lowercase())
6735 }
6736
6737 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6738 self.manipulate_text(cx, |text| {
6739 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6740 // https://github.com/rutrum/convert-case/issues/16
6741 text.split('\n')
6742 .map(|line| line.to_case(Case::Title))
6743 .join("\n")
6744 })
6745 }
6746
6747 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6748 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6749 }
6750
6751 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6752 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6753 }
6754
6755 pub fn convert_to_upper_camel_case(
6756 &mut self,
6757 _: &ConvertToUpperCamelCase,
6758 cx: &mut ViewContext<Self>,
6759 ) {
6760 self.manipulate_text(cx, |text| {
6761 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6762 // https://github.com/rutrum/convert-case/issues/16
6763 text.split('\n')
6764 .map(|line| line.to_case(Case::UpperCamel))
6765 .join("\n")
6766 })
6767 }
6768
6769 pub fn convert_to_lower_camel_case(
6770 &mut self,
6771 _: &ConvertToLowerCamelCase,
6772 cx: &mut ViewContext<Self>,
6773 ) {
6774 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6775 }
6776
6777 pub fn convert_to_opposite_case(
6778 &mut self,
6779 _: &ConvertToOppositeCase,
6780 cx: &mut ViewContext<Self>,
6781 ) {
6782 self.manipulate_text(cx, |text| {
6783 text.chars()
6784 .fold(String::with_capacity(text.len()), |mut t, c| {
6785 if c.is_uppercase() {
6786 t.extend(c.to_lowercase());
6787 } else {
6788 t.extend(c.to_uppercase());
6789 }
6790 t
6791 })
6792 })
6793 }
6794
6795 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6796 where
6797 Fn: FnMut(&str) -> String,
6798 {
6799 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6800 let buffer = self.buffer.read(cx).snapshot(cx);
6801
6802 let mut new_selections = Vec::new();
6803 let mut edits = Vec::new();
6804 let mut selection_adjustment = 0i32;
6805
6806 for selection in self.selections.all::<usize>(cx) {
6807 let selection_is_empty = selection.is_empty();
6808
6809 let (start, end) = if selection_is_empty {
6810 let word_range = movement::surrounding_word(
6811 &display_map,
6812 selection.start.to_display_point(&display_map),
6813 );
6814 let start = word_range.start.to_offset(&display_map, Bias::Left);
6815 let end = word_range.end.to_offset(&display_map, Bias::Left);
6816 (start, end)
6817 } else {
6818 (selection.start, selection.end)
6819 };
6820
6821 let text = buffer.text_for_range(start..end).collect::<String>();
6822 let old_length = text.len() as i32;
6823 let text = callback(&text);
6824
6825 new_selections.push(Selection {
6826 start: (start as i32 - selection_adjustment) as usize,
6827 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6828 goal: SelectionGoal::None,
6829 ..selection
6830 });
6831
6832 selection_adjustment += old_length - text.len() as i32;
6833
6834 edits.push((start..end, text));
6835 }
6836
6837 self.transact(cx, |this, cx| {
6838 this.buffer.update(cx, |buffer, cx| {
6839 buffer.edit(edits, None, cx);
6840 });
6841
6842 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6843 s.select(new_selections);
6844 });
6845
6846 this.request_autoscroll(Autoscroll::fit(), cx);
6847 });
6848 }
6849
6850 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6851 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6852 let buffer = &display_map.buffer_snapshot;
6853 let selections = self.selections.all::<Point>(cx);
6854
6855 let mut edits = Vec::new();
6856 let mut selections_iter = selections.iter().peekable();
6857 while let Some(selection) = selections_iter.next() {
6858 // Avoid duplicating the same lines twice.
6859 let mut rows = selection.spanned_rows(false, &display_map);
6860
6861 while let Some(next_selection) = selections_iter.peek() {
6862 let next_rows = next_selection.spanned_rows(false, &display_map);
6863 if next_rows.start < rows.end {
6864 rows.end = next_rows.end;
6865 selections_iter.next().unwrap();
6866 } else {
6867 break;
6868 }
6869 }
6870
6871 // Copy the text from the selected row region and splice it either at the start
6872 // or end of the region.
6873 let start = Point::new(rows.start.0, 0);
6874 let end = Point::new(
6875 rows.end.previous_row().0,
6876 buffer.line_len(rows.end.previous_row()),
6877 );
6878 let text = buffer
6879 .text_for_range(start..end)
6880 .chain(Some("\n"))
6881 .collect::<String>();
6882 let insert_location = if upwards {
6883 Point::new(rows.end.0, 0)
6884 } else {
6885 start
6886 };
6887 edits.push((insert_location..insert_location, text));
6888 }
6889
6890 self.transact(cx, |this, cx| {
6891 this.buffer.update(cx, |buffer, cx| {
6892 buffer.edit(edits, None, cx);
6893 });
6894
6895 this.request_autoscroll(Autoscroll::fit(), cx);
6896 });
6897 }
6898
6899 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6900 self.duplicate_line(true, cx);
6901 }
6902
6903 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6904 self.duplicate_line(false, cx);
6905 }
6906
6907 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6908 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6909 let buffer = self.buffer.read(cx).snapshot(cx);
6910
6911 let mut edits = Vec::new();
6912 let mut unfold_ranges = Vec::new();
6913 let mut refold_creases = Vec::new();
6914
6915 let selections = self.selections.all::<Point>(cx);
6916 let mut selections = selections.iter().peekable();
6917 let mut contiguous_row_selections = Vec::new();
6918 let mut new_selections = Vec::new();
6919
6920 while let Some(selection) = selections.next() {
6921 // Find all the selections that span a contiguous row range
6922 let (start_row, end_row) = consume_contiguous_rows(
6923 &mut contiguous_row_selections,
6924 selection,
6925 &display_map,
6926 &mut selections,
6927 );
6928
6929 // Move the text spanned by the row range to be before the line preceding the row range
6930 if start_row.0 > 0 {
6931 let range_to_move = Point::new(
6932 start_row.previous_row().0,
6933 buffer.line_len(start_row.previous_row()),
6934 )
6935 ..Point::new(
6936 end_row.previous_row().0,
6937 buffer.line_len(end_row.previous_row()),
6938 );
6939 let insertion_point = display_map
6940 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6941 .0;
6942
6943 // Don't move lines across excerpts
6944 if buffer
6945 .excerpt_boundaries_in_range((
6946 Bound::Excluded(insertion_point),
6947 Bound::Included(range_to_move.end),
6948 ))
6949 .next()
6950 .is_none()
6951 {
6952 let text = buffer
6953 .text_for_range(range_to_move.clone())
6954 .flat_map(|s| s.chars())
6955 .skip(1)
6956 .chain(['\n'])
6957 .collect::<String>();
6958
6959 edits.push((
6960 buffer.anchor_after(range_to_move.start)
6961 ..buffer.anchor_before(range_to_move.end),
6962 String::new(),
6963 ));
6964 let insertion_anchor = buffer.anchor_after(insertion_point);
6965 edits.push((insertion_anchor..insertion_anchor, text));
6966
6967 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6968
6969 // Move selections up
6970 new_selections.extend(contiguous_row_selections.drain(..).map(
6971 |mut selection| {
6972 selection.start.row -= row_delta;
6973 selection.end.row -= row_delta;
6974 selection
6975 },
6976 ));
6977
6978 // Move folds up
6979 unfold_ranges.push(range_to_move.clone());
6980 for fold in display_map.folds_in_range(
6981 buffer.anchor_before(range_to_move.start)
6982 ..buffer.anchor_after(range_to_move.end),
6983 ) {
6984 let mut start = fold.range.start.to_point(&buffer);
6985 let mut end = fold.range.end.to_point(&buffer);
6986 start.row -= row_delta;
6987 end.row -= row_delta;
6988 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6989 }
6990 }
6991 }
6992
6993 // If we didn't move line(s), preserve the existing selections
6994 new_selections.append(&mut contiguous_row_selections);
6995 }
6996
6997 self.transact(cx, |this, cx| {
6998 this.unfold_ranges(&unfold_ranges, true, true, cx);
6999 this.buffer.update(cx, |buffer, cx| {
7000 for (range, text) in edits {
7001 buffer.edit([(range, text)], None, cx);
7002 }
7003 });
7004 this.fold_creases(refold_creases, true, cx);
7005 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7006 s.select(new_selections);
7007 })
7008 });
7009 }
7010
7011 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
7012 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7013 let buffer = self.buffer.read(cx).snapshot(cx);
7014
7015 let mut edits = Vec::new();
7016 let mut unfold_ranges = Vec::new();
7017 let mut refold_creases = Vec::new();
7018
7019 let selections = self.selections.all::<Point>(cx);
7020 let mut selections = selections.iter().peekable();
7021 let mut contiguous_row_selections = Vec::new();
7022 let mut new_selections = Vec::new();
7023
7024 while let Some(selection) = selections.next() {
7025 // Find all the selections that span a contiguous row range
7026 let (start_row, end_row) = consume_contiguous_rows(
7027 &mut contiguous_row_selections,
7028 selection,
7029 &display_map,
7030 &mut selections,
7031 );
7032
7033 // Move the text spanned by the row range to be after the last line of the row range
7034 if end_row.0 <= buffer.max_point().row {
7035 let range_to_move =
7036 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7037 let insertion_point = display_map
7038 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7039 .0;
7040
7041 // Don't move lines across excerpt boundaries
7042 if buffer
7043 .excerpt_boundaries_in_range((
7044 Bound::Excluded(range_to_move.start),
7045 Bound::Included(insertion_point),
7046 ))
7047 .next()
7048 .is_none()
7049 {
7050 let mut text = String::from("\n");
7051 text.extend(buffer.text_for_range(range_to_move.clone()));
7052 text.pop(); // Drop trailing newline
7053 edits.push((
7054 buffer.anchor_after(range_to_move.start)
7055 ..buffer.anchor_before(range_to_move.end),
7056 String::new(),
7057 ));
7058 let insertion_anchor = buffer.anchor_after(insertion_point);
7059 edits.push((insertion_anchor..insertion_anchor, text));
7060
7061 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7062
7063 // Move selections down
7064 new_selections.extend(contiguous_row_selections.drain(..).map(
7065 |mut selection| {
7066 selection.start.row += row_delta;
7067 selection.end.row += row_delta;
7068 selection
7069 },
7070 ));
7071
7072 // Move folds down
7073 unfold_ranges.push(range_to_move.clone());
7074 for fold in display_map.folds_in_range(
7075 buffer.anchor_before(range_to_move.start)
7076 ..buffer.anchor_after(range_to_move.end),
7077 ) {
7078 let mut start = fold.range.start.to_point(&buffer);
7079 let mut end = fold.range.end.to_point(&buffer);
7080 start.row += row_delta;
7081 end.row += row_delta;
7082 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7083 }
7084 }
7085 }
7086
7087 // If we didn't move line(s), preserve the existing selections
7088 new_selections.append(&mut contiguous_row_selections);
7089 }
7090
7091 self.transact(cx, |this, cx| {
7092 this.unfold_ranges(&unfold_ranges, true, true, cx);
7093 this.buffer.update(cx, |buffer, cx| {
7094 for (range, text) in edits {
7095 buffer.edit([(range, text)], None, cx);
7096 }
7097 });
7098 this.fold_creases(refold_creases, true, cx);
7099 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
7100 });
7101 }
7102
7103 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
7104 let text_layout_details = &self.text_layout_details(cx);
7105 self.transact(cx, |this, cx| {
7106 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7107 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7108 let line_mode = s.line_mode;
7109 s.move_with(|display_map, selection| {
7110 if !selection.is_empty() || line_mode {
7111 return;
7112 }
7113
7114 let mut head = selection.head();
7115 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7116 if head.column() == display_map.line_len(head.row()) {
7117 transpose_offset = display_map
7118 .buffer_snapshot
7119 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7120 }
7121
7122 if transpose_offset == 0 {
7123 return;
7124 }
7125
7126 *head.column_mut() += 1;
7127 head = display_map.clip_point(head, Bias::Right);
7128 let goal = SelectionGoal::HorizontalPosition(
7129 display_map
7130 .x_for_display_point(head, text_layout_details)
7131 .into(),
7132 );
7133 selection.collapse_to(head, goal);
7134
7135 let transpose_start = display_map
7136 .buffer_snapshot
7137 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7138 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7139 let transpose_end = display_map
7140 .buffer_snapshot
7141 .clip_offset(transpose_offset + 1, Bias::Right);
7142 if let Some(ch) =
7143 display_map.buffer_snapshot.chars_at(transpose_start).next()
7144 {
7145 edits.push((transpose_start..transpose_offset, String::new()));
7146 edits.push((transpose_end..transpose_end, ch.to_string()));
7147 }
7148 }
7149 });
7150 edits
7151 });
7152 this.buffer
7153 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7154 let selections = this.selections.all::<usize>(cx);
7155 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7156 s.select(selections);
7157 });
7158 });
7159 }
7160
7161 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
7162 self.rewrap_impl(IsVimMode::No, cx)
7163 }
7164
7165 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
7166 let buffer = self.buffer.read(cx).snapshot(cx);
7167 let selections = self.selections.all::<Point>(cx);
7168 let mut selections = selections.iter().peekable();
7169
7170 let mut edits = Vec::new();
7171 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7172
7173 while let Some(selection) = selections.next() {
7174 let mut start_row = selection.start.row;
7175 let mut end_row = selection.end.row;
7176
7177 // Skip selections that overlap with a range that has already been rewrapped.
7178 let selection_range = start_row..end_row;
7179 if rewrapped_row_ranges
7180 .iter()
7181 .any(|range| range.overlaps(&selection_range))
7182 {
7183 continue;
7184 }
7185
7186 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7187
7188 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7189 match language_scope.language_name().0.as_ref() {
7190 "Markdown" | "Plain Text" => {
7191 should_rewrap = true;
7192 }
7193 _ => {}
7194 }
7195 }
7196
7197 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7198
7199 // Since not all lines in the selection may be at the same indent
7200 // level, choose the indent size that is the most common between all
7201 // of the lines.
7202 //
7203 // If there is a tie, we use the deepest indent.
7204 let (indent_size, indent_end) = {
7205 let mut indent_size_occurrences = HashMap::default();
7206 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7207
7208 for row in start_row..=end_row {
7209 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7210 rows_by_indent_size.entry(indent).or_default().push(row);
7211 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7212 }
7213
7214 let indent_size = indent_size_occurrences
7215 .into_iter()
7216 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7217 .map(|(indent, _)| indent)
7218 .unwrap_or_default();
7219 let row = rows_by_indent_size[&indent_size][0];
7220 let indent_end = Point::new(row, indent_size.len);
7221
7222 (indent_size, indent_end)
7223 };
7224
7225 let mut line_prefix = indent_size.chars().collect::<String>();
7226
7227 if let Some(comment_prefix) =
7228 buffer
7229 .language_scope_at(selection.head())
7230 .and_then(|language| {
7231 language
7232 .line_comment_prefixes()
7233 .iter()
7234 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7235 .cloned()
7236 })
7237 {
7238 line_prefix.push_str(&comment_prefix);
7239 should_rewrap = true;
7240 }
7241
7242 if !should_rewrap {
7243 continue;
7244 }
7245
7246 if selection.is_empty() {
7247 'expand_upwards: while start_row > 0 {
7248 let prev_row = start_row - 1;
7249 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7250 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7251 {
7252 start_row = prev_row;
7253 } else {
7254 break 'expand_upwards;
7255 }
7256 }
7257
7258 'expand_downwards: while end_row < buffer.max_point().row {
7259 let next_row = end_row + 1;
7260 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7261 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7262 {
7263 end_row = next_row;
7264 } else {
7265 break 'expand_downwards;
7266 }
7267 }
7268 }
7269
7270 let start = Point::new(start_row, 0);
7271 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7272 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7273 let Some(lines_without_prefixes) = selection_text
7274 .lines()
7275 .map(|line| {
7276 line.strip_prefix(&line_prefix)
7277 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7278 .ok_or_else(|| {
7279 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7280 })
7281 })
7282 .collect::<Result<Vec<_>, _>>()
7283 .log_err()
7284 else {
7285 continue;
7286 };
7287
7288 let wrap_column = buffer
7289 .settings_at(Point::new(start_row, 0), cx)
7290 .preferred_line_length as usize;
7291 let wrapped_text = wrap_with_prefix(
7292 line_prefix,
7293 lines_without_prefixes.join(" "),
7294 wrap_column,
7295 tab_size,
7296 );
7297
7298 // TODO: should always use char-based diff while still supporting cursor behavior that
7299 // matches vim.
7300 let diff = match is_vim_mode {
7301 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7302 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7303 };
7304 let mut offset = start.to_offset(&buffer);
7305 let mut moved_since_edit = true;
7306
7307 for change in diff.iter_all_changes() {
7308 let value = change.value();
7309 match change.tag() {
7310 ChangeTag::Equal => {
7311 offset += value.len();
7312 moved_since_edit = true;
7313 }
7314 ChangeTag::Delete => {
7315 let start = buffer.anchor_after(offset);
7316 let end = buffer.anchor_before(offset + value.len());
7317
7318 if moved_since_edit {
7319 edits.push((start..end, String::new()));
7320 } else {
7321 edits.last_mut().unwrap().0.end = end;
7322 }
7323
7324 offset += value.len();
7325 moved_since_edit = false;
7326 }
7327 ChangeTag::Insert => {
7328 if moved_since_edit {
7329 let anchor = buffer.anchor_after(offset);
7330 edits.push((anchor..anchor, value.to_string()));
7331 } else {
7332 edits.last_mut().unwrap().1.push_str(value);
7333 }
7334
7335 moved_since_edit = false;
7336 }
7337 }
7338 }
7339
7340 rewrapped_row_ranges.push(start_row..=end_row);
7341 }
7342
7343 self.buffer
7344 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7345 }
7346
7347 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
7348 let mut text = String::new();
7349 let buffer = self.buffer.read(cx).snapshot(cx);
7350 let mut selections = self.selections.all::<Point>(cx);
7351 let mut clipboard_selections = Vec::with_capacity(selections.len());
7352 {
7353 let max_point = buffer.max_point();
7354 let mut is_first = true;
7355 for selection in &mut selections {
7356 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7357 if is_entire_line {
7358 selection.start = Point::new(selection.start.row, 0);
7359 if !selection.is_empty() && selection.end.column == 0 {
7360 selection.end = cmp::min(max_point, selection.end);
7361 } else {
7362 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7363 }
7364 selection.goal = SelectionGoal::None;
7365 }
7366 if is_first {
7367 is_first = false;
7368 } else {
7369 text += "\n";
7370 }
7371 let mut len = 0;
7372 for chunk in buffer.text_for_range(selection.start..selection.end) {
7373 text.push_str(chunk);
7374 len += chunk.len();
7375 }
7376 clipboard_selections.push(ClipboardSelection {
7377 len,
7378 is_entire_line,
7379 first_line_indent: buffer
7380 .indent_size_for_line(MultiBufferRow(selection.start.row))
7381 .len,
7382 });
7383 }
7384 }
7385
7386 self.transact(cx, |this, cx| {
7387 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7388 s.select(selections);
7389 });
7390 this.insert("", cx);
7391 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7392 text,
7393 clipboard_selections,
7394 ));
7395 });
7396 }
7397
7398 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
7399 let selections = self.selections.all::<Point>(cx);
7400 let buffer = self.buffer.read(cx).read(cx);
7401 let mut text = String::new();
7402
7403 let mut clipboard_selections = Vec::with_capacity(selections.len());
7404 {
7405 let max_point = buffer.max_point();
7406 let mut is_first = true;
7407 for selection in selections.iter() {
7408 let mut start = selection.start;
7409 let mut end = selection.end;
7410 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7411 if is_entire_line {
7412 start = Point::new(start.row, 0);
7413 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7414 }
7415 if is_first {
7416 is_first = false;
7417 } else {
7418 text += "\n";
7419 }
7420 let mut len = 0;
7421 for chunk in buffer.text_for_range(start..end) {
7422 text.push_str(chunk);
7423 len += chunk.len();
7424 }
7425 clipboard_selections.push(ClipboardSelection {
7426 len,
7427 is_entire_line,
7428 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7429 });
7430 }
7431 }
7432
7433 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7434 text,
7435 clipboard_selections,
7436 ));
7437 }
7438
7439 pub fn do_paste(
7440 &mut self,
7441 text: &String,
7442 clipboard_selections: Option<Vec<ClipboardSelection>>,
7443 handle_entire_lines: bool,
7444 cx: &mut ViewContext<Self>,
7445 ) {
7446 if self.read_only(cx) {
7447 return;
7448 }
7449
7450 let clipboard_text = Cow::Borrowed(text);
7451
7452 self.transact(cx, |this, cx| {
7453 if let Some(mut clipboard_selections) = clipboard_selections {
7454 let old_selections = this.selections.all::<usize>(cx);
7455 let all_selections_were_entire_line =
7456 clipboard_selections.iter().all(|s| s.is_entire_line);
7457 let first_selection_indent_column =
7458 clipboard_selections.first().map(|s| s.first_line_indent);
7459 if clipboard_selections.len() != old_selections.len() {
7460 clipboard_selections.drain(..);
7461 }
7462 let cursor_offset = this.selections.last::<usize>(cx).head();
7463 let mut auto_indent_on_paste = true;
7464
7465 this.buffer.update(cx, |buffer, cx| {
7466 let snapshot = buffer.read(cx);
7467 auto_indent_on_paste =
7468 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7469
7470 let mut start_offset = 0;
7471 let mut edits = Vec::new();
7472 let mut original_indent_columns = Vec::new();
7473 for (ix, selection) in old_selections.iter().enumerate() {
7474 let to_insert;
7475 let entire_line;
7476 let original_indent_column;
7477 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7478 let end_offset = start_offset + clipboard_selection.len;
7479 to_insert = &clipboard_text[start_offset..end_offset];
7480 entire_line = clipboard_selection.is_entire_line;
7481 start_offset = end_offset + 1;
7482 original_indent_column = Some(clipboard_selection.first_line_indent);
7483 } else {
7484 to_insert = clipboard_text.as_str();
7485 entire_line = all_selections_were_entire_line;
7486 original_indent_column = first_selection_indent_column
7487 }
7488
7489 // If the corresponding selection was empty when this slice of the
7490 // clipboard text was written, then the entire line containing the
7491 // selection was copied. If this selection is also currently empty,
7492 // then paste the line before the current line of the buffer.
7493 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7494 let column = selection.start.to_point(&snapshot).column as usize;
7495 let line_start = selection.start - column;
7496 line_start..line_start
7497 } else {
7498 selection.range()
7499 };
7500
7501 edits.push((range, to_insert));
7502 original_indent_columns.extend(original_indent_column);
7503 }
7504 drop(snapshot);
7505
7506 buffer.edit(
7507 edits,
7508 if auto_indent_on_paste {
7509 Some(AutoindentMode::Block {
7510 original_indent_columns,
7511 })
7512 } else {
7513 None
7514 },
7515 cx,
7516 );
7517 });
7518
7519 let selections = this.selections.all::<usize>(cx);
7520 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7521 } else {
7522 this.insert(&clipboard_text, cx);
7523 }
7524 });
7525 }
7526
7527 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7528 if let Some(item) = cx.read_from_clipboard() {
7529 let entries = item.entries();
7530
7531 match entries.first() {
7532 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7533 // of all the pasted entries.
7534 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7535 .do_paste(
7536 clipboard_string.text(),
7537 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7538 true,
7539 cx,
7540 ),
7541 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7542 }
7543 }
7544 }
7545
7546 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7547 if self.read_only(cx) {
7548 return;
7549 }
7550
7551 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7552 if let Some((selections, _)) =
7553 self.selection_history.transaction(transaction_id).cloned()
7554 {
7555 self.change_selections(None, cx, |s| {
7556 s.select_anchors(selections.to_vec());
7557 });
7558 }
7559 self.request_autoscroll(Autoscroll::fit(), cx);
7560 self.unmark_text(cx);
7561 self.refresh_inline_completion(true, false, cx);
7562 cx.emit(EditorEvent::Edited { transaction_id });
7563 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7564 }
7565 }
7566
7567 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7568 if self.read_only(cx) {
7569 return;
7570 }
7571
7572 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7573 if let Some((_, Some(selections))) =
7574 self.selection_history.transaction(transaction_id).cloned()
7575 {
7576 self.change_selections(None, cx, |s| {
7577 s.select_anchors(selections.to_vec());
7578 });
7579 }
7580 self.request_autoscroll(Autoscroll::fit(), cx);
7581 self.unmark_text(cx);
7582 self.refresh_inline_completion(true, false, cx);
7583 cx.emit(EditorEvent::Edited { transaction_id });
7584 }
7585 }
7586
7587 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7588 self.buffer
7589 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7590 }
7591
7592 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7593 self.buffer
7594 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7595 }
7596
7597 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7598 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7599 let line_mode = s.line_mode;
7600 s.move_with(|map, selection| {
7601 let cursor = if selection.is_empty() && !line_mode {
7602 movement::left(map, selection.start)
7603 } else {
7604 selection.start
7605 };
7606 selection.collapse_to(cursor, SelectionGoal::None);
7607 });
7608 })
7609 }
7610
7611 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7612 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7613 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7614 })
7615 }
7616
7617 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7618 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7619 let line_mode = s.line_mode;
7620 s.move_with(|map, selection| {
7621 let cursor = if selection.is_empty() && !line_mode {
7622 movement::right(map, selection.end)
7623 } else {
7624 selection.end
7625 };
7626 selection.collapse_to(cursor, SelectionGoal::None)
7627 });
7628 })
7629 }
7630
7631 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7632 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7633 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7634 })
7635 }
7636
7637 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7638 if self.take_rename(true, cx).is_some() {
7639 return;
7640 }
7641
7642 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7643 cx.propagate();
7644 return;
7645 }
7646
7647 let text_layout_details = &self.text_layout_details(cx);
7648 let selection_count = self.selections.count();
7649 let first_selection = self.selections.first_anchor();
7650
7651 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7652 let line_mode = s.line_mode;
7653 s.move_with(|map, selection| {
7654 if !selection.is_empty() && !line_mode {
7655 selection.goal = SelectionGoal::None;
7656 }
7657 let (cursor, goal) = movement::up(
7658 map,
7659 selection.start,
7660 selection.goal,
7661 false,
7662 text_layout_details,
7663 );
7664 selection.collapse_to(cursor, goal);
7665 });
7666 });
7667
7668 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7669 {
7670 cx.propagate();
7671 }
7672 }
7673
7674 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7675 if self.take_rename(true, cx).is_some() {
7676 return;
7677 }
7678
7679 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7680 cx.propagate();
7681 return;
7682 }
7683
7684 let text_layout_details = &self.text_layout_details(cx);
7685
7686 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7687 let line_mode = s.line_mode;
7688 s.move_with(|map, selection| {
7689 if !selection.is_empty() && !line_mode {
7690 selection.goal = SelectionGoal::None;
7691 }
7692 let (cursor, goal) = movement::up_by_rows(
7693 map,
7694 selection.start,
7695 action.lines,
7696 selection.goal,
7697 false,
7698 text_layout_details,
7699 );
7700 selection.collapse_to(cursor, goal);
7701 });
7702 })
7703 }
7704
7705 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7706 if self.take_rename(true, cx).is_some() {
7707 return;
7708 }
7709
7710 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7711 cx.propagate();
7712 return;
7713 }
7714
7715 let text_layout_details = &self.text_layout_details(cx);
7716
7717 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7718 let line_mode = s.line_mode;
7719 s.move_with(|map, selection| {
7720 if !selection.is_empty() && !line_mode {
7721 selection.goal = SelectionGoal::None;
7722 }
7723 let (cursor, goal) = movement::down_by_rows(
7724 map,
7725 selection.start,
7726 action.lines,
7727 selection.goal,
7728 false,
7729 text_layout_details,
7730 );
7731 selection.collapse_to(cursor, goal);
7732 });
7733 })
7734 }
7735
7736 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7737 let text_layout_details = &self.text_layout_details(cx);
7738 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7739 s.move_heads_with(|map, head, goal| {
7740 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7741 })
7742 })
7743 }
7744
7745 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7746 let text_layout_details = &self.text_layout_details(cx);
7747 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7748 s.move_heads_with(|map, head, goal| {
7749 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7750 })
7751 })
7752 }
7753
7754 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7755 let Some(row_count) = self.visible_row_count() else {
7756 return;
7757 };
7758
7759 let text_layout_details = &self.text_layout_details(cx);
7760
7761 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7762 s.move_heads_with(|map, head, goal| {
7763 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7764 })
7765 })
7766 }
7767
7768 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7769 if self.take_rename(true, cx).is_some() {
7770 return;
7771 }
7772
7773 if self
7774 .context_menu
7775 .write()
7776 .as_mut()
7777 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7778 .unwrap_or(false)
7779 {
7780 return;
7781 }
7782
7783 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7784 cx.propagate();
7785 return;
7786 }
7787
7788 let Some(row_count) = self.visible_row_count() else {
7789 return;
7790 };
7791
7792 let autoscroll = if action.center_cursor {
7793 Autoscroll::center()
7794 } else {
7795 Autoscroll::fit()
7796 };
7797
7798 let text_layout_details = &self.text_layout_details(cx);
7799
7800 self.change_selections(Some(autoscroll), cx, |s| {
7801 let line_mode = s.line_mode;
7802 s.move_with(|map, selection| {
7803 if !selection.is_empty() && !line_mode {
7804 selection.goal = SelectionGoal::None;
7805 }
7806 let (cursor, goal) = movement::up_by_rows(
7807 map,
7808 selection.end,
7809 row_count,
7810 selection.goal,
7811 false,
7812 text_layout_details,
7813 );
7814 selection.collapse_to(cursor, goal);
7815 });
7816 });
7817 }
7818
7819 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7820 let text_layout_details = &self.text_layout_details(cx);
7821 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7822 s.move_heads_with(|map, head, goal| {
7823 movement::up(map, head, goal, false, text_layout_details)
7824 })
7825 })
7826 }
7827
7828 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7829 self.take_rename(true, cx);
7830
7831 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7832 cx.propagate();
7833 return;
7834 }
7835
7836 let text_layout_details = &self.text_layout_details(cx);
7837 let selection_count = self.selections.count();
7838 let first_selection = self.selections.first_anchor();
7839
7840 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7841 let line_mode = s.line_mode;
7842 s.move_with(|map, selection| {
7843 if !selection.is_empty() && !line_mode {
7844 selection.goal = SelectionGoal::None;
7845 }
7846 let (cursor, goal) = movement::down(
7847 map,
7848 selection.end,
7849 selection.goal,
7850 false,
7851 text_layout_details,
7852 );
7853 selection.collapse_to(cursor, goal);
7854 });
7855 });
7856
7857 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7858 {
7859 cx.propagate();
7860 }
7861 }
7862
7863 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7864 let Some(row_count) = self.visible_row_count() else {
7865 return;
7866 };
7867
7868 let text_layout_details = &self.text_layout_details(cx);
7869
7870 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7871 s.move_heads_with(|map, head, goal| {
7872 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7873 })
7874 })
7875 }
7876
7877 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7878 if self.take_rename(true, cx).is_some() {
7879 return;
7880 }
7881
7882 if self
7883 .context_menu
7884 .write()
7885 .as_mut()
7886 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7887 .unwrap_or(false)
7888 {
7889 return;
7890 }
7891
7892 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7893 cx.propagate();
7894 return;
7895 }
7896
7897 let Some(row_count) = self.visible_row_count() else {
7898 return;
7899 };
7900
7901 let autoscroll = if action.center_cursor {
7902 Autoscroll::center()
7903 } else {
7904 Autoscroll::fit()
7905 };
7906
7907 let text_layout_details = &self.text_layout_details(cx);
7908 self.change_selections(Some(autoscroll), cx, |s| {
7909 let line_mode = s.line_mode;
7910 s.move_with(|map, selection| {
7911 if !selection.is_empty() && !line_mode {
7912 selection.goal = SelectionGoal::None;
7913 }
7914 let (cursor, goal) = movement::down_by_rows(
7915 map,
7916 selection.end,
7917 row_count,
7918 selection.goal,
7919 false,
7920 text_layout_details,
7921 );
7922 selection.collapse_to(cursor, goal);
7923 });
7924 });
7925 }
7926
7927 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7928 let text_layout_details = &self.text_layout_details(cx);
7929 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7930 s.move_heads_with(|map, head, goal| {
7931 movement::down(map, head, goal, false, text_layout_details)
7932 })
7933 });
7934 }
7935
7936 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7937 if let Some(context_menu) = self.context_menu.write().as_mut() {
7938 context_menu.select_first(self.completion_provider.as_deref(), cx);
7939 }
7940 }
7941
7942 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7943 if let Some(context_menu) = self.context_menu.write().as_mut() {
7944 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7945 }
7946 }
7947
7948 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7949 if let Some(context_menu) = self.context_menu.write().as_mut() {
7950 context_menu.select_next(self.completion_provider.as_deref(), cx);
7951 }
7952 }
7953
7954 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7955 if let Some(context_menu) = self.context_menu.write().as_mut() {
7956 context_menu.select_last(self.completion_provider.as_deref(), cx);
7957 }
7958 }
7959
7960 pub fn move_to_previous_word_start(
7961 &mut self,
7962 _: &MoveToPreviousWordStart,
7963 cx: &mut ViewContext<Self>,
7964 ) {
7965 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7966 s.move_cursors_with(|map, head, _| {
7967 (
7968 movement::previous_word_start(map, head),
7969 SelectionGoal::None,
7970 )
7971 });
7972 })
7973 }
7974
7975 pub fn move_to_previous_subword_start(
7976 &mut self,
7977 _: &MoveToPreviousSubwordStart,
7978 cx: &mut ViewContext<Self>,
7979 ) {
7980 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7981 s.move_cursors_with(|map, head, _| {
7982 (
7983 movement::previous_subword_start(map, head),
7984 SelectionGoal::None,
7985 )
7986 });
7987 })
7988 }
7989
7990 pub fn select_to_previous_word_start(
7991 &mut self,
7992 _: &SelectToPreviousWordStart,
7993 cx: &mut ViewContext<Self>,
7994 ) {
7995 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7996 s.move_heads_with(|map, head, _| {
7997 (
7998 movement::previous_word_start(map, head),
7999 SelectionGoal::None,
8000 )
8001 });
8002 })
8003 }
8004
8005 pub fn select_to_previous_subword_start(
8006 &mut self,
8007 _: &SelectToPreviousSubwordStart,
8008 cx: &mut ViewContext<Self>,
8009 ) {
8010 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8011 s.move_heads_with(|map, head, _| {
8012 (
8013 movement::previous_subword_start(map, head),
8014 SelectionGoal::None,
8015 )
8016 });
8017 })
8018 }
8019
8020 pub fn delete_to_previous_word_start(
8021 &mut self,
8022 action: &DeleteToPreviousWordStart,
8023 cx: &mut ViewContext<Self>,
8024 ) {
8025 self.transact(cx, |this, cx| {
8026 this.select_autoclose_pair(cx);
8027 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8028 let line_mode = s.line_mode;
8029 s.move_with(|map, selection| {
8030 if selection.is_empty() && !line_mode {
8031 let cursor = if action.ignore_newlines {
8032 movement::previous_word_start(map, selection.head())
8033 } else {
8034 movement::previous_word_start_or_newline(map, selection.head())
8035 };
8036 selection.set_head(cursor, SelectionGoal::None);
8037 }
8038 });
8039 });
8040 this.insert("", cx);
8041 });
8042 }
8043
8044 pub fn delete_to_previous_subword_start(
8045 &mut self,
8046 _: &DeleteToPreviousSubwordStart,
8047 cx: &mut ViewContext<Self>,
8048 ) {
8049 self.transact(cx, |this, cx| {
8050 this.select_autoclose_pair(cx);
8051 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8052 let line_mode = s.line_mode;
8053 s.move_with(|map, selection| {
8054 if selection.is_empty() && !line_mode {
8055 let cursor = movement::previous_subword_start(map, selection.head());
8056 selection.set_head(cursor, SelectionGoal::None);
8057 }
8058 });
8059 });
8060 this.insert("", cx);
8061 });
8062 }
8063
8064 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
8065 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8066 s.move_cursors_with(|map, head, _| {
8067 (movement::next_word_end(map, head), SelectionGoal::None)
8068 });
8069 })
8070 }
8071
8072 pub fn move_to_next_subword_end(
8073 &mut self,
8074 _: &MoveToNextSubwordEnd,
8075 cx: &mut ViewContext<Self>,
8076 ) {
8077 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8078 s.move_cursors_with(|map, head, _| {
8079 (movement::next_subword_end(map, head), SelectionGoal::None)
8080 });
8081 })
8082 }
8083
8084 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
8085 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8086 s.move_heads_with(|map, head, _| {
8087 (movement::next_word_end(map, head), SelectionGoal::None)
8088 });
8089 })
8090 }
8091
8092 pub fn select_to_next_subword_end(
8093 &mut self,
8094 _: &SelectToNextSubwordEnd,
8095 cx: &mut ViewContext<Self>,
8096 ) {
8097 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8098 s.move_heads_with(|map, head, _| {
8099 (movement::next_subword_end(map, head), SelectionGoal::None)
8100 });
8101 })
8102 }
8103
8104 pub fn delete_to_next_word_end(
8105 &mut self,
8106 action: &DeleteToNextWordEnd,
8107 cx: &mut ViewContext<Self>,
8108 ) {
8109 self.transact(cx, |this, cx| {
8110 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8111 let line_mode = s.line_mode;
8112 s.move_with(|map, selection| {
8113 if selection.is_empty() && !line_mode {
8114 let cursor = if action.ignore_newlines {
8115 movement::next_word_end(map, selection.head())
8116 } else {
8117 movement::next_word_end_or_newline(map, selection.head())
8118 };
8119 selection.set_head(cursor, SelectionGoal::None);
8120 }
8121 });
8122 });
8123 this.insert("", cx);
8124 });
8125 }
8126
8127 pub fn delete_to_next_subword_end(
8128 &mut self,
8129 _: &DeleteToNextSubwordEnd,
8130 cx: &mut ViewContext<Self>,
8131 ) {
8132 self.transact(cx, |this, cx| {
8133 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8134 s.move_with(|map, selection| {
8135 if selection.is_empty() {
8136 let cursor = movement::next_subword_end(map, selection.head());
8137 selection.set_head(cursor, SelectionGoal::None);
8138 }
8139 });
8140 });
8141 this.insert("", cx);
8142 });
8143 }
8144
8145 pub fn move_to_beginning_of_line(
8146 &mut self,
8147 action: &MoveToBeginningOfLine,
8148 cx: &mut ViewContext<Self>,
8149 ) {
8150 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8151 s.move_cursors_with(|map, head, _| {
8152 (
8153 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8154 SelectionGoal::None,
8155 )
8156 });
8157 })
8158 }
8159
8160 pub fn select_to_beginning_of_line(
8161 &mut self,
8162 action: &SelectToBeginningOfLine,
8163 cx: &mut ViewContext<Self>,
8164 ) {
8165 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8166 s.move_heads_with(|map, head, _| {
8167 (
8168 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8169 SelectionGoal::None,
8170 )
8171 });
8172 });
8173 }
8174
8175 pub fn delete_to_beginning_of_line(
8176 &mut self,
8177 _: &DeleteToBeginningOfLine,
8178 cx: &mut ViewContext<Self>,
8179 ) {
8180 self.transact(cx, |this, cx| {
8181 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8182 s.move_with(|_, selection| {
8183 selection.reversed = true;
8184 });
8185 });
8186
8187 this.select_to_beginning_of_line(
8188 &SelectToBeginningOfLine {
8189 stop_at_soft_wraps: false,
8190 },
8191 cx,
8192 );
8193 this.backspace(&Backspace, cx);
8194 });
8195 }
8196
8197 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
8198 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8199 s.move_cursors_with(|map, head, _| {
8200 (
8201 movement::line_end(map, head, action.stop_at_soft_wraps),
8202 SelectionGoal::None,
8203 )
8204 });
8205 })
8206 }
8207
8208 pub fn select_to_end_of_line(
8209 &mut self,
8210 action: &SelectToEndOfLine,
8211 cx: &mut ViewContext<Self>,
8212 ) {
8213 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8214 s.move_heads_with(|map, head, _| {
8215 (
8216 movement::line_end(map, head, action.stop_at_soft_wraps),
8217 SelectionGoal::None,
8218 )
8219 });
8220 })
8221 }
8222
8223 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
8224 self.transact(cx, |this, cx| {
8225 this.select_to_end_of_line(
8226 &SelectToEndOfLine {
8227 stop_at_soft_wraps: false,
8228 },
8229 cx,
8230 );
8231 this.delete(&Delete, cx);
8232 });
8233 }
8234
8235 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
8236 self.transact(cx, |this, cx| {
8237 this.select_to_end_of_line(
8238 &SelectToEndOfLine {
8239 stop_at_soft_wraps: false,
8240 },
8241 cx,
8242 );
8243 this.cut(&Cut, cx);
8244 });
8245 }
8246
8247 pub fn move_to_start_of_paragraph(
8248 &mut self,
8249 _: &MoveToStartOfParagraph,
8250 cx: &mut ViewContext<Self>,
8251 ) {
8252 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8253 cx.propagate();
8254 return;
8255 }
8256
8257 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8258 s.move_with(|map, selection| {
8259 selection.collapse_to(
8260 movement::start_of_paragraph(map, selection.head(), 1),
8261 SelectionGoal::None,
8262 )
8263 });
8264 })
8265 }
8266
8267 pub fn move_to_end_of_paragraph(
8268 &mut self,
8269 _: &MoveToEndOfParagraph,
8270 cx: &mut ViewContext<Self>,
8271 ) {
8272 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8273 cx.propagate();
8274 return;
8275 }
8276
8277 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8278 s.move_with(|map, selection| {
8279 selection.collapse_to(
8280 movement::end_of_paragraph(map, selection.head(), 1),
8281 SelectionGoal::None,
8282 )
8283 });
8284 })
8285 }
8286
8287 pub fn select_to_start_of_paragraph(
8288 &mut self,
8289 _: &SelectToStartOfParagraph,
8290 cx: &mut ViewContext<Self>,
8291 ) {
8292 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8293 cx.propagate();
8294 return;
8295 }
8296
8297 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8298 s.move_heads_with(|map, head, _| {
8299 (
8300 movement::start_of_paragraph(map, head, 1),
8301 SelectionGoal::None,
8302 )
8303 });
8304 })
8305 }
8306
8307 pub fn select_to_end_of_paragraph(
8308 &mut self,
8309 _: &SelectToEndOfParagraph,
8310 cx: &mut ViewContext<Self>,
8311 ) {
8312 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8313 cx.propagate();
8314 return;
8315 }
8316
8317 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8318 s.move_heads_with(|map, head, _| {
8319 (
8320 movement::end_of_paragraph(map, head, 1),
8321 SelectionGoal::None,
8322 )
8323 });
8324 })
8325 }
8326
8327 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
8328 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8329 cx.propagate();
8330 return;
8331 }
8332
8333 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8334 s.select_ranges(vec![0..0]);
8335 });
8336 }
8337
8338 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
8339 let mut selection = self.selections.last::<Point>(cx);
8340 selection.set_head(Point::zero(), SelectionGoal::None);
8341
8342 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8343 s.select(vec![selection]);
8344 });
8345 }
8346
8347 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
8348 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8349 cx.propagate();
8350 return;
8351 }
8352
8353 let cursor = self.buffer.read(cx).read(cx).len();
8354 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8355 s.select_ranges(vec![cursor..cursor])
8356 });
8357 }
8358
8359 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8360 self.nav_history = nav_history;
8361 }
8362
8363 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8364 self.nav_history.as_ref()
8365 }
8366
8367 fn push_to_nav_history(
8368 &mut self,
8369 cursor_anchor: Anchor,
8370 new_position: Option<Point>,
8371 cx: &mut ViewContext<Self>,
8372 ) {
8373 if let Some(nav_history) = self.nav_history.as_mut() {
8374 let buffer = self.buffer.read(cx).read(cx);
8375 let cursor_position = cursor_anchor.to_point(&buffer);
8376 let scroll_state = self.scroll_manager.anchor();
8377 let scroll_top_row = scroll_state.top_row(&buffer);
8378 drop(buffer);
8379
8380 if let Some(new_position) = new_position {
8381 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8382 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8383 return;
8384 }
8385 }
8386
8387 nav_history.push(
8388 Some(NavigationData {
8389 cursor_anchor,
8390 cursor_position,
8391 scroll_anchor: scroll_state,
8392 scroll_top_row,
8393 }),
8394 cx,
8395 );
8396 }
8397 }
8398
8399 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
8400 let buffer = self.buffer.read(cx).snapshot(cx);
8401 let mut selection = self.selections.first::<usize>(cx);
8402 selection.set_head(buffer.len(), SelectionGoal::None);
8403 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8404 s.select(vec![selection]);
8405 });
8406 }
8407
8408 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
8409 let end = self.buffer.read(cx).read(cx).len();
8410 self.change_selections(None, cx, |s| {
8411 s.select_ranges(vec![0..end]);
8412 });
8413 }
8414
8415 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8416 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8417 let mut selections = self.selections.all::<Point>(cx);
8418 let max_point = display_map.buffer_snapshot.max_point();
8419 for selection in &mut selections {
8420 let rows = selection.spanned_rows(true, &display_map);
8421 selection.start = Point::new(rows.start.0, 0);
8422 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8423 selection.reversed = false;
8424 }
8425 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8426 s.select(selections);
8427 });
8428 }
8429
8430 pub fn split_selection_into_lines(
8431 &mut self,
8432 _: &SplitSelectionIntoLines,
8433 cx: &mut ViewContext<Self>,
8434 ) {
8435 let mut to_unfold = Vec::new();
8436 let mut new_selection_ranges = Vec::new();
8437 {
8438 let selections = self.selections.all::<Point>(cx);
8439 let buffer = self.buffer.read(cx).read(cx);
8440 for selection in selections {
8441 for row in selection.start.row..selection.end.row {
8442 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8443 new_selection_ranges.push(cursor..cursor);
8444 }
8445 new_selection_ranges.push(selection.end..selection.end);
8446 to_unfold.push(selection.start..selection.end);
8447 }
8448 }
8449 self.unfold_ranges(&to_unfold, true, true, cx);
8450 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8451 s.select_ranges(new_selection_ranges);
8452 });
8453 }
8454
8455 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8456 self.add_selection(true, cx);
8457 }
8458
8459 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8460 self.add_selection(false, cx);
8461 }
8462
8463 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8464 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8465 let mut selections = self.selections.all::<Point>(cx);
8466 let text_layout_details = self.text_layout_details(cx);
8467 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8468 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8469 let range = oldest_selection.display_range(&display_map).sorted();
8470
8471 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8472 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8473 let positions = start_x.min(end_x)..start_x.max(end_x);
8474
8475 selections.clear();
8476 let mut stack = Vec::new();
8477 for row in range.start.row().0..=range.end.row().0 {
8478 if let Some(selection) = self.selections.build_columnar_selection(
8479 &display_map,
8480 DisplayRow(row),
8481 &positions,
8482 oldest_selection.reversed,
8483 &text_layout_details,
8484 ) {
8485 stack.push(selection.id);
8486 selections.push(selection);
8487 }
8488 }
8489
8490 if above {
8491 stack.reverse();
8492 }
8493
8494 AddSelectionsState { above, stack }
8495 });
8496
8497 let last_added_selection = *state.stack.last().unwrap();
8498 let mut new_selections = Vec::new();
8499 if above == state.above {
8500 let end_row = if above {
8501 DisplayRow(0)
8502 } else {
8503 display_map.max_point().row()
8504 };
8505
8506 'outer: for selection in selections {
8507 if selection.id == last_added_selection {
8508 let range = selection.display_range(&display_map).sorted();
8509 debug_assert_eq!(range.start.row(), range.end.row());
8510 let mut row = range.start.row();
8511 let positions =
8512 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8513 px(start)..px(end)
8514 } else {
8515 let start_x =
8516 display_map.x_for_display_point(range.start, &text_layout_details);
8517 let end_x =
8518 display_map.x_for_display_point(range.end, &text_layout_details);
8519 start_x.min(end_x)..start_x.max(end_x)
8520 };
8521
8522 while row != end_row {
8523 if above {
8524 row.0 -= 1;
8525 } else {
8526 row.0 += 1;
8527 }
8528
8529 if let Some(new_selection) = self.selections.build_columnar_selection(
8530 &display_map,
8531 row,
8532 &positions,
8533 selection.reversed,
8534 &text_layout_details,
8535 ) {
8536 state.stack.push(new_selection.id);
8537 if above {
8538 new_selections.push(new_selection);
8539 new_selections.push(selection);
8540 } else {
8541 new_selections.push(selection);
8542 new_selections.push(new_selection);
8543 }
8544
8545 continue 'outer;
8546 }
8547 }
8548 }
8549
8550 new_selections.push(selection);
8551 }
8552 } else {
8553 new_selections = selections;
8554 new_selections.retain(|s| s.id != last_added_selection);
8555 state.stack.pop();
8556 }
8557
8558 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8559 s.select(new_selections);
8560 });
8561 if state.stack.len() > 1 {
8562 self.add_selections_state = Some(state);
8563 }
8564 }
8565
8566 pub fn select_next_match_internal(
8567 &mut self,
8568 display_map: &DisplaySnapshot,
8569 replace_newest: bool,
8570 autoscroll: Option<Autoscroll>,
8571 cx: &mut ViewContext<Self>,
8572 ) -> Result<()> {
8573 fn select_next_match_ranges(
8574 this: &mut Editor,
8575 range: Range<usize>,
8576 replace_newest: bool,
8577 auto_scroll: Option<Autoscroll>,
8578 cx: &mut ViewContext<Editor>,
8579 ) {
8580 this.unfold_ranges(&[range.clone()], false, true, cx);
8581 this.change_selections(auto_scroll, cx, |s| {
8582 if replace_newest {
8583 s.delete(s.newest_anchor().id);
8584 }
8585 s.insert_range(range.clone());
8586 });
8587 }
8588
8589 let buffer = &display_map.buffer_snapshot;
8590 let mut selections = self.selections.all::<usize>(cx);
8591 if let Some(mut select_next_state) = self.select_next_state.take() {
8592 let query = &select_next_state.query;
8593 if !select_next_state.done {
8594 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8595 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8596 let mut next_selected_range = None;
8597
8598 let bytes_after_last_selection =
8599 buffer.bytes_in_range(last_selection.end..buffer.len());
8600 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8601 let query_matches = query
8602 .stream_find_iter(bytes_after_last_selection)
8603 .map(|result| (last_selection.end, result))
8604 .chain(
8605 query
8606 .stream_find_iter(bytes_before_first_selection)
8607 .map(|result| (0, result)),
8608 );
8609
8610 for (start_offset, query_match) in query_matches {
8611 let query_match = query_match.unwrap(); // can only fail due to I/O
8612 let offset_range =
8613 start_offset + query_match.start()..start_offset + query_match.end();
8614 let display_range = offset_range.start.to_display_point(display_map)
8615 ..offset_range.end.to_display_point(display_map);
8616
8617 if !select_next_state.wordwise
8618 || (!movement::is_inside_word(display_map, display_range.start)
8619 && !movement::is_inside_word(display_map, display_range.end))
8620 {
8621 // TODO: This is n^2, because we might check all the selections
8622 if !selections
8623 .iter()
8624 .any(|selection| selection.range().overlaps(&offset_range))
8625 {
8626 next_selected_range = Some(offset_range);
8627 break;
8628 }
8629 }
8630 }
8631
8632 if let Some(next_selected_range) = next_selected_range {
8633 select_next_match_ranges(
8634 self,
8635 next_selected_range,
8636 replace_newest,
8637 autoscroll,
8638 cx,
8639 );
8640 } else {
8641 select_next_state.done = true;
8642 }
8643 }
8644
8645 self.select_next_state = Some(select_next_state);
8646 } else {
8647 let mut only_carets = true;
8648 let mut same_text_selected = true;
8649 let mut selected_text = None;
8650
8651 let mut selections_iter = selections.iter().peekable();
8652 while let Some(selection) = selections_iter.next() {
8653 if selection.start != selection.end {
8654 only_carets = false;
8655 }
8656
8657 if same_text_selected {
8658 if selected_text.is_none() {
8659 selected_text =
8660 Some(buffer.text_for_range(selection.range()).collect::<String>());
8661 }
8662
8663 if let Some(next_selection) = selections_iter.peek() {
8664 if next_selection.range().len() == selection.range().len() {
8665 let next_selected_text = buffer
8666 .text_for_range(next_selection.range())
8667 .collect::<String>();
8668 if Some(next_selected_text) != selected_text {
8669 same_text_selected = false;
8670 selected_text = None;
8671 }
8672 } else {
8673 same_text_selected = false;
8674 selected_text = None;
8675 }
8676 }
8677 }
8678 }
8679
8680 if only_carets {
8681 for selection in &mut selections {
8682 let word_range = movement::surrounding_word(
8683 display_map,
8684 selection.start.to_display_point(display_map),
8685 );
8686 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8687 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8688 selection.goal = SelectionGoal::None;
8689 selection.reversed = false;
8690 select_next_match_ranges(
8691 self,
8692 selection.start..selection.end,
8693 replace_newest,
8694 autoscroll,
8695 cx,
8696 );
8697 }
8698
8699 if selections.len() == 1 {
8700 let selection = selections
8701 .last()
8702 .expect("ensured that there's only one selection");
8703 let query = buffer
8704 .text_for_range(selection.start..selection.end)
8705 .collect::<String>();
8706 let is_empty = query.is_empty();
8707 let select_state = SelectNextState {
8708 query: AhoCorasick::new(&[query])?,
8709 wordwise: true,
8710 done: is_empty,
8711 };
8712 self.select_next_state = Some(select_state);
8713 } else {
8714 self.select_next_state = None;
8715 }
8716 } else if let Some(selected_text) = selected_text {
8717 self.select_next_state = Some(SelectNextState {
8718 query: AhoCorasick::new(&[selected_text])?,
8719 wordwise: false,
8720 done: false,
8721 });
8722 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8723 }
8724 }
8725 Ok(())
8726 }
8727
8728 pub fn select_all_matches(
8729 &mut self,
8730 _action: &SelectAllMatches,
8731 cx: &mut ViewContext<Self>,
8732 ) -> Result<()> {
8733 self.push_to_selection_history();
8734 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8735
8736 self.select_next_match_internal(&display_map, false, None, cx)?;
8737 let Some(select_next_state) = self.select_next_state.as_mut() else {
8738 return Ok(());
8739 };
8740 if select_next_state.done {
8741 return Ok(());
8742 }
8743
8744 let mut new_selections = self.selections.all::<usize>(cx);
8745
8746 let buffer = &display_map.buffer_snapshot;
8747 let query_matches = select_next_state
8748 .query
8749 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8750
8751 for query_match in query_matches {
8752 let query_match = query_match.unwrap(); // can only fail due to I/O
8753 let offset_range = query_match.start()..query_match.end();
8754 let display_range = offset_range.start.to_display_point(&display_map)
8755 ..offset_range.end.to_display_point(&display_map);
8756
8757 if !select_next_state.wordwise
8758 || (!movement::is_inside_word(&display_map, display_range.start)
8759 && !movement::is_inside_word(&display_map, display_range.end))
8760 {
8761 self.selections.change_with(cx, |selections| {
8762 new_selections.push(Selection {
8763 id: selections.new_selection_id(),
8764 start: offset_range.start,
8765 end: offset_range.end,
8766 reversed: false,
8767 goal: SelectionGoal::None,
8768 });
8769 });
8770 }
8771 }
8772
8773 new_selections.sort_by_key(|selection| selection.start);
8774 let mut ix = 0;
8775 while ix + 1 < new_selections.len() {
8776 let current_selection = &new_selections[ix];
8777 let next_selection = &new_selections[ix + 1];
8778 if current_selection.range().overlaps(&next_selection.range()) {
8779 if current_selection.id < next_selection.id {
8780 new_selections.remove(ix + 1);
8781 } else {
8782 new_selections.remove(ix);
8783 }
8784 } else {
8785 ix += 1;
8786 }
8787 }
8788
8789 select_next_state.done = true;
8790 self.unfold_ranges(
8791 &new_selections
8792 .iter()
8793 .map(|selection| selection.range())
8794 .collect::<Vec<_>>(),
8795 false,
8796 false,
8797 cx,
8798 );
8799 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8800 selections.select(new_selections)
8801 });
8802
8803 Ok(())
8804 }
8805
8806 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8807 self.push_to_selection_history();
8808 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8809 self.select_next_match_internal(
8810 &display_map,
8811 action.replace_newest,
8812 Some(Autoscroll::newest()),
8813 cx,
8814 )?;
8815 Ok(())
8816 }
8817
8818 pub fn select_previous(
8819 &mut self,
8820 action: &SelectPrevious,
8821 cx: &mut ViewContext<Self>,
8822 ) -> Result<()> {
8823 self.push_to_selection_history();
8824 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8825 let buffer = &display_map.buffer_snapshot;
8826 let mut selections = self.selections.all::<usize>(cx);
8827 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8828 let query = &select_prev_state.query;
8829 if !select_prev_state.done {
8830 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8831 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8832 let mut next_selected_range = None;
8833 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8834 let bytes_before_last_selection =
8835 buffer.reversed_bytes_in_range(0..last_selection.start);
8836 let bytes_after_first_selection =
8837 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8838 let query_matches = query
8839 .stream_find_iter(bytes_before_last_selection)
8840 .map(|result| (last_selection.start, result))
8841 .chain(
8842 query
8843 .stream_find_iter(bytes_after_first_selection)
8844 .map(|result| (buffer.len(), result)),
8845 );
8846 for (end_offset, query_match) in query_matches {
8847 let query_match = query_match.unwrap(); // can only fail due to I/O
8848 let offset_range =
8849 end_offset - query_match.end()..end_offset - query_match.start();
8850 let display_range = offset_range.start.to_display_point(&display_map)
8851 ..offset_range.end.to_display_point(&display_map);
8852
8853 if !select_prev_state.wordwise
8854 || (!movement::is_inside_word(&display_map, display_range.start)
8855 && !movement::is_inside_word(&display_map, display_range.end))
8856 {
8857 next_selected_range = Some(offset_range);
8858 break;
8859 }
8860 }
8861
8862 if let Some(next_selected_range) = next_selected_range {
8863 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8864 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8865 if action.replace_newest {
8866 s.delete(s.newest_anchor().id);
8867 }
8868 s.insert_range(next_selected_range);
8869 });
8870 } else {
8871 select_prev_state.done = true;
8872 }
8873 }
8874
8875 self.select_prev_state = Some(select_prev_state);
8876 } else {
8877 let mut only_carets = true;
8878 let mut same_text_selected = true;
8879 let mut selected_text = None;
8880
8881 let mut selections_iter = selections.iter().peekable();
8882 while let Some(selection) = selections_iter.next() {
8883 if selection.start != selection.end {
8884 only_carets = false;
8885 }
8886
8887 if same_text_selected {
8888 if selected_text.is_none() {
8889 selected_text =
8890 Some(buffer.text_for_range(selection.range()).collect::<String>());
8891 }
8892
8893 if let Some(next_selection) = selections_iter.peek() {
8894 if next_selection.range().len() == selection.range().len() {
8895 let next_selected_text = buffer
8896 .text_for_range(next_selection.range())
8897 .collect::<String>();
8898 if Some(next_selected_text) != selected_text {
8899 same_text_selected = false;
8900 selected_text = None;
8901 }
8902 } else {
8903 same_text_selected = false;
8904 selected_text = None;
8905 }
8906 }
8907 }
8908 }
8909
8910 if only_carets {
8911 for selection in &mut selections {
8912 let word_range = movement::surrounding_word(
8913 &display_map,
8914 selection.start.to_display_point(&display_map),
8915 );
8916 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8917 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8918 selection.goal = SelectionGoal::None;
8919 selection.reversed = false;
8920 }
8921 if selections.len() == 1 {
8922 let selection = selections
8923 .last()
8924 .expect("ensured that there's only one selection");
8925 let query = buffer
8926 .text_for_range(selection.start..selection.end)
8927 .collect::<String>();
8928 let is_empty = query.is_empty();
8929 let select_state = SelectNextState {
8930 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8931 wordwise: true,
8932 done: is_empty,
8933 };
8934 self.select_prev_state = Some(select_state);
8935 } else {
8936 self.select_prev_state = None;
8937 }
8938
8939 self.unfold_ranges(
8940 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8941 false,
8942 true,
8943 cx,
8944 );
8945 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8946 s.select(selections);
8947 });
8948 } else if let Some(selected_text) = selected_text {
8949 self.select_prev_state = Some(SelectNextState {
8950 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8951 wordwise: false,
8952 done: false,
8953 });
8954 self.select_previous(action, cx)?;
8955 }
8956 }
8957 Ok(())
8958 }
8959
8960 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8961 if self.read_only(cx) {
8962 return;
8963 }
8964 let text_layout_details = &self.text_layout_details(cx);
8965 self.transact(cx, |this, cx| {
8966 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8967 let mut edits = Vec::new();
8968 let mut selection_edit_ranges = Vec::new();
8969 let mut last_toggled_row = None;
8970 let snapshot = this.buffer.read(cx).read(cx);
8971 let empty_str: Arc<str> = Arc::default();
8972 let mut suffixes_inserted = Vec::new();
8973 let ignore_indent = action.ignore_indent;
8974
8975 fn comment_prefix_range(
8976 snapshot: &MultiBufferSnapshot,
8977 row: MultiBufferRow,
8978 comment_prefix: &str,
8979 comment_prefix_whitespace: &str,
8980 ignore_indent: bool,
8981 ) -> Range<Point> {
8982 let indent_size = if ignore_indent {
8983 0
8984 } else {
8985 snapshot.indent_size_for_line(row).len
8986 };
8987
8988 let start = Point::new(row.0, indent_size);
8989
8990 let mut line_bytes = snapshot
8991 .bytes_in_range(start..snapshot.max_point())
8992 .flatten()
8993 .copied();
8994
8995 // If this line currently begins with the line comment prefix, then record
8996 // the range containing the prefix.
8997 if line_bytes
8998 .by_ref()
8999 .take(comment_prefix.len())
9000 .eq(comment_prefix.bytes())
9001 {
9002 // Include any whitespace that matches the comment prefix.
9003 let matching_whitespace_len = line_bytes
9004 .zip(comment_prefix_whitespace.bytes())
9005 .take_while(|(a, b)| a == b)
9006 .count() as u32;
9007 let end = Point::new(
9008 start.row,
9009 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9010 );
9011 start..end
9012 } else {
9013 start..start
9014 }
9015 }
9016
9017 fn comment_suffix_range(
9018 snapshot: &MultiBufferSnapshot,
9019 row: MultiBufferRow,
9020 comment_suffix: &str,
9021 comment_suffix_has_leading_space: bool,
9022 ) -> Range<Point> {
9023 let end = Point::new(row.0, snapshot.line_len(row));
9024 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9025
9026 let mut line_end_bytes = snapshot
9027 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9028 .flatten()
9029 .copied();
9030
9031 let leading_space_len = if suffix_start_column > 0
9032 && line_end_bytes.next() == Some(b' ')
9033 && comment_suffix_has_leading_space
9034 {
9035 1
9036 } else {
9037 0
9038 };
9039
9040 // If this line currently begins with the line comment prefix, then record
9041 // the range containing the prefix.
9042 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9043 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9044 start..end
9045 } else {
9046 end..end
9047 }
9048 }
9049
9050 // TODO: Handle selections that cross excerpts
9051 for selection in &mut selections {
9052 let start_column = snapshot
9053 .indent_size_for_line(MultiBufferRow(selection.start.row))
9054 .len;
9055 let language = if let Some(language) =
9056 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9057 {
9058 language
9059 } else {
9060 continue;
9061 };
9062
9063 selection_edit_ranges.clear();
9064
9065 // If multiple selections contain a given row, avoid processing that
9066 // row more than once.
9067 let mut start_row = MultiBufferRow(selection.start.row);
9068 if last_toggled_row == Some(start_row) {
9069 start_row = start_row.next_row();
9070 }
9071 let end_row =
9072 if selection.end.row > selection.start.row && selection.end.column == 0 {
9073 MultiBufferRow(selection.end.row - 1)
9074 } else {
9075 MultiBufferRow(selection.end.row)
9076 };
9077 last_toggled_row = Some(end_row);
9078
9079 if start_row > end_row {
9080 continue;
9081 }
9082
9083 // If the language has line comments, toggle those.
9084 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9085
9086 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9087 if ignore_indent {
9088 full_comment_prefixes = full_comment_prefixes
9089 .into_iter()
9090 .map(|s| Arc::from(s.trim_end()))
9091 .collect();
9092 }
9093
9094 if !full_comment_prefixes.is_empty() {
9095 let first_prefix = full_comment_prefixes
9096 .first()
9097 .expect("prefixes is non-empty");
9098 let prefix_trimmed_lengths = full_comment_prefixes
9099 .iter()
9100 .map(|p| p.trim_end_matches(' ').len())
9101 .collect::<SmallVec<[usize; 4]>>();
9102
9103 let mut all_selection_lines_are_comments = true;
9104
9105 for row in start_row.0..=end_row.0 {
9106 let row = MultiBufferRow(row);
9107 if start_row < end_row && snapshot.is_line_blank(row) {
9108 continue;
9109 }
9110
9111 let prefix_range = full_comment_prefixes
9112 .iter()
9113 .zip(prefix_trimmed_lengths.iter().copied())
9114 .map(|(prefix, trimmed_prefix_len)| {
9115 comment_prefix_range(
9116 snapshot.deref(),
9117 row,
9118 &prefix[..trimmed_prefix_len],
9119 &prefix[trimmed_prefix_len..],
9120 ignore_indent,
9121 )
9122 })
9123 .max_by_key(|range| range.end.column - range.start.column)
9124 .expect("prefixes is non-empty");
9125
9126 if prefix_range.is_empty() {
9127 all_selection_lines_are_comments = false;
9128 }
9129
9130 selection_edit_ranges.push(prefix_range);
9131 }
9132
9133 if all_selection_lines_are_comments {
9134 edits.extend(
9135 selection_edit_ranges
9136 .iter()
9137 .cloned()
9138 .map(|range| (range, empty_str.clone())),
9139 );
9140 } else {
9141 let min_column = selection_edit_ranges
9142 .iter()
9143 .map(|range| range.start.column)
9144 .min()
9145 .unwrap_or(0);
9146 edits.extend(selection_edit_ranges.iter().map(|range| {
9147 let position = Point::new(range.start.row, min_column);
9148 (position..position, first_prefix.clone())
9149 }));
9150 }
9151 } else if let Some((full_comment_prefix, comment_suffix)) =
9152 language.block_comment_delimiters()
9153 {
9154 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9155 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9156 let prefix_range = comment_prefix_range(
9157 snapshot.deref(),
9158 start_row,
9159 comment_prefix,
9160 comment_prefix_whitespace,
9161 ignore_indent,
9162 );
9163 let suffix_range = comment_suffix_range(
9164 snapshot.deref(),
9165 end_row,
9166 comment_suffix.trim_start_matches(' '),
9167 comment_suffix.starts_with(' '),
9168 );
9169
9170 if prefix_range.is_empty() || suffix_range.is_empty() {
9171 edits.push((
9172 prefix_range.start..prefix_range.start,
9173 full_comment_prefix.clone(),
9174 ));
9175 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9176 suffixes_inserted.push((end_row, comment_suffix.len()));
9177 } else {
9178 edits.push((prefix_range, empty_str.clone()));
9179 edits.push((suffix_range, empty_str.clone()));
9180 }
9181 } else {
9182 continue;
9183 }
9184 }
9185
9186 drop(snapshot);
9187 this.buffer.update(cx, |buffer, cx| {
9188 buffer.edit(edits, None, cx);
9189 });
9190
9191 // Adjust selections so that they end before any comment suffixes that
9192 // were inserted.
9193 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9194 let mut selections = this.selections.all::<Point>(cx);
9195 let snapshot = this.buffer.read(cx).read(cx);
9196 for selection in &mut selections {
9197 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9198 match row.cmp(&MultiBufferRow(selection.end.row)) {
9199 Ordering::Less => {
9200 suffixes_inserted.next();
9201 continue;
9202 }
9203 Ordering::Greater => break,
9204 Ordering::Equal => {
9205 if selection.end.column == snapshot.line_len(row) {
9206 if selection.is_empty() {
9207 selection.start.column -= suffix_len as u32;
9208 }
9209 selection.end.column -= suffix_len as u32;
9210 }
9211 break;
9212 }
9213 }
9214 }
9215 }
9216
9217 drop(snapshot);
9218 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
9219
9220 let selections = this.selections.all::<Point>(cx);
9221 let selections_on_single_row = selections.windows(2).all(|selections| {
9222 selections[0].start.row == selections[1].start.row
9223 && selections[0].end.row == selections[1].end.row
9224 && selections[0].start.row == selections[0].end.row
9225 });
9226 let selections_selecting = selections
9227 .iter()
9228 .any(|selection| selection.start != selection.end);
9229 let advance_downwards = action.advance_downwards
9230 && selections_on_single_row
9231 && !selections_selecting
9232 && !matches!(this.mode, EditorMode::SingleLine { .. });
9233
9234 if advance_downwards {
9235 let snapshot = this.buffer.read(cx).snapshot(cx);
9236
9237 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
9238 s.move_cursors_with(|display_snapshot, display_point, _| {
9239 let mut point = display_point.to_point(display_snapshot);
9240 point.row += 1;
9241 point = snapshot.clip_point(point, Bias::Left);
9242 let display_point = point.to_display_point(display_snapshot);
9243 let goal = SelectionGoal::HorizontalPosition(
9244 display_snapshot
9245 .x_for_display_point(display_point, text_layout_details)
9246 .into(),
9247 );
9248 (display_point, goal)
9249 })
9250 });
9251 }
9252 });
9253 }
9254
9255 pub fn select_enclosing_symbol(
9256 &mut self,
9257 _: &SelectEnclosingSymbol,
9258 cx: &mut ViewContext<Self>,
9259 ) {
9260 let buffer = self.buffer.read(cx).snapshot(cx);
9261 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9262
9263 fn update_selection(
9264 selection: &Selection<usize>,
9265 buffer_snap: &MultiBufferSnapshot,
9266 ) -> Option<Selection<usize>> {
9267 let cursor = selection.head();
9268 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9269 for symbol in symbols.iter().rev() {
9270 let start = symbol.range.start.to_offset(buffer_snap);
9271 let end = symbol.range.end.to_offset(buffer_snap);
9272 let new_range = start..end;
9273 if start < selection.start || end > selection.end {
9274 return Some(Selection {
9275 id: selection.id,
9276 start: new_range.start,
9277 end: new_range.end,
9278 goal: SelectionGoal::None,
9279 reversed: selection.reversed,
9280 });
9281 }
9282 }
9283 None
9284 }
9285
9286 let mut selected_larger_symbol = false;
9287 let new_selections = old_selections
9288 .iter()
9289 .map(|selection| match update_selection(selection, &buffer) {
9290 Some(new_selection) => {
9291 if new_selection.range() != selection.range() {
9292 selected_larger_symbol = true;
9293 }
9294 new_selection
9295 }
9296 None => selection.clone(),
9297 })
9298 .collect::<Vec<_>>();
9299
9300 if selected_larger_symbol {
9301 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9302 s.select(new_selections);
9303 });
9304 }
9305 }
9306
9307 pub fn select_larger_syntax_node(
9308 &mut self,
9309 _: &SelectLargerSyntaxNode,
9310 cx: &mut ViewContext<Self>,
9311 ) {
9312 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9313 let buffer = self.buffer.read(cx).snapshot(cx);
9314 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9315
9316 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9317 let mut selected_larger_node = false;
9318 let new_selections = old_selections
9319 .iter()
9320 .map(|selection| {
9321 let old_range = selection.start..selection.end;
9322 let mut new_range = old_range.clone();
9323 while let Some(containing_range) =
9324 buffer.range_for_syntax_ancestor(new_range.clone())
9325 {
9326 new_range = containing_range;
9327 if !display_map.intersects_fold(new_range.start)
9328 && !display_map.intersects_fold(new_range.end)
9329 {
9330 break;
9331 }
9332 }
9333
9334 selected_larger_node |= new_range != old_range;
9335 Selection {
9336 id: selection.id,
9337 start: new_range.start,
9338 end: new_range.end,
9339 goal: SelectionGoal::None,
9340 reversed: selection.reversed,
9341 }
9342 })
9343 .collect::<Vec<_>>();
9344
9345 if selected_larger_node {
9346 stack.push(old_selections);
9347 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9348 s.select(new_selections);
9349 });
9350 }
9351 self.select_larger_syntax_node_stack = stack;
9352 }
9353
9354 pub fn select_smaller_syntax_node(
9355 &mut self,
9356 _: &SelectSmallerSyntaxNode,
9357 cx: &mut ViewContext<Self>,
9358 ) {
9359 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9360 if let Some(selections) = stack.pop() {
9361 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9362 s.select(selections.to_vec());
9363 });
9364 }
9365 self.select_larger_syntax_node_stack = stack;
9366 }
9367
9368 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
9369 if !EditorSettings::get_global(cx).gutter.runnables {
9370 self.clear_tasks();
9371 return Task::ready(());
9372 }
9373 let project = self.project.as_ref().map(Model::downgrade);
9374 cx.spawn(|this, mut cx| async move {
9375 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
9376 let Some(project) = project.and_then(|p| p.upgrade()) else {
9377 return;
9378 };
9379 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9380 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9381 }) else {
9382 return;
9383 };
9384
9385 let hide_runnables = project
9386 .update(&mut cx, |project, cx| {
9387 // Do not display any test indicators in non-dev server remote projects.
9388 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9389 })
9390 .unwrap_or(true);
9391 if hide_runnables {
9392 return;
9393 }
9394 let new_rows =
9395 cx.background_executor()
9396 .spawn({
9397 let snapshot = display_snapshot.clone();
9398 async move {
9399 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9400 }
9401 })
9402 .await;
9403 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9404
9405 this.update(&mut cx, |this, _| {
9406 this.clear_tasks();
9407 for (key, value) in rows {
9408 this.insert_tasks(key, value);
9409 }
9410 })
9411 .ok();
9412 })
9413 }
9414 fn fetch_runnable_ranges(
9415 snapshot: &DisplaySnapshot,
9416 range: Range<Anchor>,
9417 ) -> Vec<language::RunnableRange> {
9418 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9419 }
9420
9421 fn runnable_rows(
9422 project: Model<Project>,
9423 snapshot: DisplaySnapshot,
9424 runnable_ranges: Vec<RunnableRange>,
9425 mut cx: AsyncWindowContext,
9426 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9427 runnable_ranges
9428 .into_iter()
9429 .filter_map(|mut runnable| {
9430 let tasks = cx
9431 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9432 .ok()?;
9433 if tasks.is_empty() {
9434 return None;
9435 }
9436
9437 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9438
9439 let row = snapshot
9440 .buffer_snapshot
9441 .buffer_line_for_row(MultiBufferRow(point.row))?
9442 .1
9443 .start
9444 .row;
9445
9446 let context_range =
9447 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9448 Some((
9449 (runnable.buffer_id, row),
9450 RunnableTasks {
9451 templates: tasks,
9452 offset: MultiBufferOffset(runnable.run_range.start),
9453 context_range,
9454 column: point.column,
9455 extra_variables: runnable.extra_captures,
9456 },
9457 ))
9458 })
9459 .collect()
9460 }
9461
9462 fn templates_with_tags(
9463 project: &Model<Project>,
9464 runnable: &mut Runnable,
9465 cx: &WindowContext<'_>,
9466 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9467 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9468 let (worktree_id, file) = project
9469 .buffer_for_id(runnable.buffer, cx)
9470 .and_then(|buffer| buffer.read(cx).file())
9471 .map(|file| (file.worktree_id(cx), file.clone()))
9472 .unzip();
9473
9474 (
9475 project.task_store().read(cx).task_inventory().cloned(),
9476 worktree_id,
9477 file,
9478 )
9479 });
9480
9481 let tags = mem::take(&mut runnable.tags);
9482 let mut tags: Vec<_> = tags
9483 .into_iter()
9484 .flat_map(|tag| {
9485 let tag = tag.0.clone();
9486 inventory
9487 .as_ref()
9488 .into_iter()
9489 .flat_map(|inventory| {
9490 inventory.read(cx).list_tasks(
9491 file.clone(),
9492 Some(runnable.language.clone()),
9493 worktree_id,
9494 cx,
9495 )
9496 })
9497 .filter(move |(_, template)| {
9498 template.tags.iter().any(|source_tag| source_tag == &tag)
9499 })
9500 })
9501 .sorted_by_key(|(kind, _)| kind.to_owned())
9502 .collect();
9503 if let Some((leading_tag_source, _)) = tags.first() {
9504 // Strongest source wins; if we have worktree tag binding, prefer that to
9505 // global and language bindings;
9506 // if we have a global binding, prefer that to language binding.
9507 let first_mismatch = tags
9508 .iter()
9509 .position(|(tag_source, _)| tag_source != leading_tag_source);
9510 if let Some(index) = first_mismatch {
9511 tags.truncate(index);
9512 }
9513 }
9514
9515 tags
9516 }
9517
9518 pub fn move_to_enclosing_bracket(
9519 &mut self,
9520 _: &MoveToEnclosingBracket,
9521 cx: &mut ViewContext<Self>,
9522 ) {
9523 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9524 s.move_offsets_with(|snapshot, selection| {
9525 let Some(enclosing_bracket_ranges) =
9526 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9527 else {
9528 return;
9529 };
9530
9531 let mut best_length = usize::MAX;
9532 let mut best_inside = false;
9533 let mut best_in_bracket_range = false;
9534 let mut best_destination = None;
9535 for (open, close) in enclosing_bracket_ranges {
9536 let close = close.to_inclusive();
9537 let length = close.end() - open.start;
9538 let inside = selection.start >= open.end && selection.end <= *close.start();
9539 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9540 || close.contains(&selection.head());
9541
9542 // If best is next to a bracket and current isn't, skip
9543 if !in_bracket_range && best_in_bracket_range {
9544 continue;
9545 }
9546
9547 // Prefer smaller lengths unless best is inside and current isn't
9548 if length > best_length && (best_inside || !inside) {
9549 continue;
9550 }
9551
9552 best_length = length;
9553 best_inside = inside;
9554 best_in_bracket_range = in_bracket_range;
9555 best_destination = Some(
9556 if close.contains(&selection.start) && close.contains(&selection.end) {
9557 if inside {
9558 open.end
9559 } else {
9560 open.start
9561 }
9562 } else if inside {
9563 *close.start()
9564 } else {
9565 *close.end()
9566 },
9567 );
9568 }
9569
9570 if let Some(destination) = best_destination {
9571 selection.collapse_to(destination, SelectionGoal::None);
9572 }
9573 })
9574 });
9575 }
9576
9577 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9578 self.end_selection(cx);
9579 self.selection_history.mode = SelectionHistoryMode::Undoing;
9580 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9581 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9582 self.select_next_state = entry.select_next_state;
9583 self.select_prev_state = entry.select_prev_state;
9584 self.add_selections_state = entry.add_selections_state;
9585 self.request_autoscroll(Autoscroll::newest(), cx);
9586 }
9587 self.selection_history.mode = SelectionHistoryMode::Normal;
9588 }
9589
9590 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9591 self.end_selection(cx);
9592 self.selection_history.mode = SelectionHistoryMode::Redoing;
9593 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9594 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9595 self.select_next_state = entry.select_next_state;
9596 self.select_prev_state = entry.select_prev_state;
9597 self.add_selections_state = entry.add_selections_state;
9598 self.request_autoscroll(Autoscroll::newest(), cx);
9599 }
9600 self.selection_history.mode = SelectionHistoryMode::Normal;
9601 }
9602
9603 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9604 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9605 }
9606
9607 pub fn expand_excerpts_down(
9608 &mut self,
9609 action: &ExpandExcerptsDown,
9610 cx: &mut ViewContext<Self>,
9611 ) {
9612 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9613 }
9614
9615 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9616 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9617 }
9618
9619 pub fn expand_excerpts_for_direction(
9620 &mut self,
9621 lines: u32,
9622 direction: ExpandExcerptDirection,
9623 cx: &mut ViewContext<Self>,
9624 ) {
9625 let selections = self.selections.disjoint_anchors();
9626
9627 let lines = if lines == 0 {
9628 EditorSettings::get_global(cx).expand_excerpt_lines
9629 } else {
9630 lines
9631 };
9632
9633 self.buffer.update(cx, |buffer, cx| {
9634 buffer.expand_excerpts(
9635 selections
9636 .iter()
9637 .map(|selection| selection.head().excerpt_id)
9638 .dedup(),
9639 lines,
9640 direction,
9641 cx,
9642 )
9643 })
9644 }
9645
9646 pub fn expand_excerpt(
9647 &mut self,
9648 excerpt: ExcerptId,
9649 direction: ExpandExcerptDirection,
9650 cx: &mut ViewContext<Self>,
9651 ) {
9652 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9653 self.buffer.update(cx, |buffer, cx| {
9654 buffer.expand_excerpts([excerpt], lines, direction, cx)
9655 })
9656 }
9657
9658 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9659 self.go_to_diagnostic_impl(Direction::Next, cx)
9660 }
9661
9662 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9663 self.go_to_diagnostic_impl(Direction::Prev, cx)
9664 }
9665
9666 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9667 let buffer = self.buffer.read(cx).snapshot(cx);
9668 let selection = self.selections.newest::<usize>(cx);
9669
9670 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9671 if direction == Direction::Next {
9672 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9673 let (group_id, jump_to) = popover.activation_info();
9674 if self.activate_diagnostics(group_id, cx) {
9675 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9676 let mut new_selection = s.newest_anchor().clone();
9677 new_selection.collapse_to(jump_to, SelectionGoal::None);
9678 s.select_anchors(vec![new_selection.clone()]);
9679 });
9680 }
9681 return;
9682 }
9683 }
9684
9685 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9686 active_diagnostics
9687 .primary_range
9688 .to_offset(&buffer)
9689 .to_inclusive()
9690 });
9691 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9692 if active_primary_range.contains(&selection.head()) {
9693 *active_primary_range.start()
9694 } else {
9695 selection.head()
9696 }
9697 } else {
9698 selection.head()
9699 };
9700 let snapshot = self.snapshot(cx);
9701 loop {
9702 let diagnostics = if direction == Direction::Prev {
9703 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9704 } else {
9705 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9706 }
9707 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9708 let group = diagnostics
9709 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9710 // be sorted in a stable way
9711 // skip until we are at current active diagnostic, if it exists
9712 .skip_while(|entry| {
9713 (match direction {
9714 Direction::Prev => entry.range.start >= search_start,
9715 Direction::Next => entry.range.start <= search_start,
9716 }) && self
9717 .active_diagnostics
9718 .as_ref()
9719 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9720 })
9721 .find_map(|entry| {
9722 if entry.diagnostic.is_primary
9723 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9724 && !entry.range.is_empty()
9725 // if we match with the active diagnostic, skip it
9726 && Some(entry.diagnostic.group_id)
9727 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9728 {
9729 Some((entry.range, entry.diagnostic.group_id))
9730 } else {
9731 None
9732 }
9733 });
9734
9735 if let Some((primary_range, group_id)) = group {
9736 if self.activate_diagnostics(group_id, cx) {
9737 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9738 s.select(vec![Selection {
9739 id: selection.id,
9740 start: primary_range.start,
9741 end: primary_range.start,
9742 reversed: false,
9743 goal: SelectionGoal::None,
9744 }]);
9745 });
9746 }
9747 break;
9748 } else {
9749 // Cycle around to the start of the buffer, potentially moving back to the start of
9750 // the currently active diagnostic.
9751 active_primary_range.take();
9752 if direction == Direction::Prev {
9753 if search_start == buffer.len() {
9754 break;
9755 } else {
9756 search_start = buffer.len();
9757 }
9758 } else if search_start == 0 {
9759 break;
9760 } else {
9761 search_start = 0;
9762 }
9763 }
9764 }
9765 }
9766
9767 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9768 let snapshot = self
9769 .display_map
9770 .update(cx, |display_map, cx| display_map.snapshot(cx));
9771 let selection = self.selections.newest::<Point>(cx);
9772 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9773 }
9774
9775 fn go_to_hunk_after_position(
9776 &mut self,
9777 snapshot: &DisplaySnapshot,
9778 position: Point,
9779 cx: &mut ViewContext<'_, Editor>,
9780 ) -> Option<MultiBufferDiffHunk> {
9781 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9782 snapshot,
9783 position,
9784 false,
9785 snapshot
9786 .buffer_snapshot
9787 .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
9788 cx,
9789 ) {
9790 return Some(hunk);
9791 }
9792
9793 let wrapped_point = Point::zero();
9794 self.go_to_next_hunk_in_direction(
9795 snapshot,
9796 wrapped_point,
9797 true,
9798 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9799 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9800 ),
9801 cx,
9802 )
9803 }
9804
9805 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9806 let snapshot = self
9807 .display_map
9808 .update(cx, |display_map, cx| display_map.snapshot(cx));
9809 let selection = self.selections.newest::<Point>(cx);
9810
9811 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9812 }
9813
9814 fn go_to_hunk_before_position(
9815 &mut self,
9816 snapshot: &DisplaySnapshot,
9817 position: Point,
9818 cx: &mut ViewContext<'_, Editor>,
9819 ) -> Option<MultiBufferDiffHunk> {
9820 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9821 snapshot,
9822 position,
9823 false,
9824 snapshot
9825 .buffer_snapshot
9826 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
9827 cx,
9828 ) {
9829 return Some(hunk);
9830 }
9831
9832 let wrapped_point = snapshot.buffer_snapshot.max_point();
9833 self.go_to_next_hunk_in_direction(
9834 snapshot,
9835 wrapped_point,
9836 true,
9837 snapshot
9838 .buffer_snapshot
9839 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
9840 cx,
9841 )
9842 }
9843
9844 fn go_to_next_hunk_in_direction(
9845 &mut self,
9846 snapshot: &DisplaySnapshot,
9847 initial_point: Point,
9848 is_wrapped: bool,
9849 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9850 cx: &mut ViewContext<Editor>,
9851 ) -> Option<MultiBufferDiffHunk> {
9852 let display_point = initial_point.to_display_point(snapshot);
9853 let mut hunks = hunks
9854 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9855 .filter(|(display_hunk, _)| {
9856 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9857 })
9858 .dedup();
9859
9860 if let Some((display_hunk, hunk)) = hunks.next() {
9861 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9862 let row = display_hunk.start_display_row();
9863 let point = DisplayPoint::new(row, 0);
9864 s.select_display_ranges([point..point]);
9865 });
9866
9867 Some(hunk)
9868 } else {
9869 None
9870 }
9871 }
9872
9873 pub fn go_to_definition(
9874 &mut self,
9875 _: &GoToDefinition,
9876 cx: &mut ViewContext<Self>,
9877 ) -> Task<Result<Navigated>> {
9878 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9879 cx.spawn(|editor, mut cx| async move {
9880 if definition.await? == Navigated::Yes {
9881 return Ok(Navigated::Yes);
9882 }
9883 match editor.update(&mut cx, |editor, cx| {
9884 editor.find_all_references(&FindAllReferences, cx)
9885 })? {
9886 Some(references) => references.await,
9887 None => Ok(Navigated::No),
9888 }
9889 })
9890 }
9891
9892 pub fn go_to_declaration(
9893 &mut self,
9894 _: &GoToDeclaration,
9895 cx: &mut ViewContext<Self>,
9896 ) -> Task<Result<Navigated>> {
9897 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9898 }
9899
9900 pub fn go_to_declaration_split(
9901 &mut self,
9902 _: &GoToDeclaration,
9903 cx: &mut ViewContext<Self>,
9904 ) -> Task<Result<Navigated>> {
9905 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9906 }
9907
9908 pub fn go_to_implementation(
9909 &mut self,
9910 _: &GoToImplementation,
9911 cx: &mut ViewContext<Self>,
9912 ) -> Task<Result<Navigated>> {
9913 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9914 }
9915
9916 pub fn go_to_implementation_split(
9917 &mut self,
9918 _: &GoToImplementationSplit,
9919 cx: &mut ViewContext<Self>,
9920 ) -> Task<Result<Navigated>> {
9921 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9922 }
9923
9924 pub fn go_to_type_definition(
9925 &mut self,
9926 _: &GoToTypeDefinition,
9927 cx: &mut ViewContext<Self>,
9928 ) -> Task<Result<Navigated>> {
9929 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9930 }
9931
9932 pub fn go_to_definition_split(
9933 &mut self,
9934 _: &GoToDefinitionSplit,
9935 cx: &mut ViewContext<Self>,
9936 ) -> Task<Result<Navigated>> {
9937 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9938 }
9939
9940 pub fn go_to_type_definition_split(
9941 &mut self,
9942 _: &GoToTypeDefinitionSplit,
9943 cx: &mut ViewContext<Self>,
9944 ) -> Task<Result<Navigated>> {
9945 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9946 }
9947
9948 fn go_to_definition_of_kind(
9949 &mut self,
9950 kind: GotoDefinitionKind,
9951 split: bool,
9952 cx: &mut ViewContext<Self>,
9953 ) -> Task<Result<Navigated>> {
9954 let Some(provider) = self.semantics_provider.clone() else {
9955 return Task::ready(Ok(Navigated::No));
9956 };
9957 let head = self.selections.newest::<usize>(cx).head();
9958 let buffer = self.buffer.read(cx);
9959 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9960 text_anchor
9961 } else {
9962 return Task::ready(Ok(Navigated::No));
9963 };
9964
9965 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9966 return Task::ready(Ok(Navigated::No));
9967 };
9968
9969 cx.spawn(|editor, mut cx| async move {
9970 let definitions = definitions.await?;
9971 let navigated = editor
9972 .update(&mut cx, |editor, cx| {
9973 editor.navigate_to_hover_links(
9974 Some(kind),
9975 definitions
9976 .into_iter()
9977 .filter(|location| {
9978 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9979 })
9980 .map(HoverLink::Text)
9981 .collect::<Vec<_>>(),
9982 split,
9983 cx,
9984 )
9985 })?
9986 .await?;
9987 anyhow::Ok(navigated)
9988 })
9989 }
9990
9991 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9992 let position = self.selections.newest_anchor().head();
9993 let Some((buffer, buffer_position)) =
9994 self.buffer.read(cx).text_anchor_for_position(position, cx)
9995 else {
9996 return;
9997 };
9998
9999 cx.spawn(|editor, mut cx| async move {
10000 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
10001 editor.update(&mut cx, |_, cx| {
10002 cx.open_url(&url);
10003 })
10004 } else {
10005 Ok(())
10006 }
10007 })
10008 .detach();
10009 }
10010
10011 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
10012 let Some(workspace) = self.workspace() else {
10013 return;
10014 };
10015
10016 let position = self.selections.newest_anchor().head();
10017
10018 let Some((buffer, buffer_position)) =
10019 self.buffer.read(cx).text_anchor_for_position(position, cx)
10020 else {
10021 return;
10022 };
10023
10024 let project = self.project.clone();
10025
10026 cx.spawn(|_, mut cx| async move {
10027 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10028
10029 if let Some((_, path)) = result {
10030 workspace
10031 .update(&mut cx, |workspace, cx| {
10032 workspace.open_resolved_path(path, cx)
10033 })?
10034 .await?;
10035 }
10036 anyhow::Ok(())
10037 })
10038 .detach();
10039 }
10040
10041 pub(crate) fn navigate_to_hover_links(
10042 &mut self,
10043 kind: Option<GotoDefinitionKind>,
10044 mut definitions: Vec<HoverLink>,
10045 split: bool,
10046 cx: &mut ViewContext<Editor>,
10047 ) -> Task<Result<Navigated>> {
10048 // If there is one definition, just open it directly
10049 if definitions.len() == 1 {
10050 let definition = definitions.pop().unwrap();
10051
10052 enum TargetTaskResult {
10053 Location(Option<Location>),
10054 AlreadyNavigated,
10055 }
10056
10057 let target_task = match definition {
10058 HoverLink::Text(link) => {
10059 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10060 }
10061 HoverLink::InlayHint(lsp_location, server_id) => {
10062 let computation = self.compute_target_location(lsp_location, server_id, cx);
10063 cx.background_executor().spawn(async move {
10064 let location = computation.await?;
10065 Ok(TargetTaskResult::Location(location))
10066 })
10067 }
10068 HoverLink::Url(url) => {
10069 cx.open_url(&url);
10070 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10071 }
10072 HoverLink::File(path) => {
10073 if let Some(workspace) = self.workspace() {
10074 cx.spawn(|_, mut cx| async move {
10075 workspace
10076 .update(&mut cx, |workspace, cx| {
10077 workspace.open_resolved_path(path, cx)
10078 })?
10079 .await
10080 .map(|_| TargetTaskResult::AlreadyNavigated)
10081 })
10082 } else {
10083 Task::ready(Ok(TargetTaskResult::Location(None)))
10084 }
10085 }
10086 };
10087 cx.spawn(|editor, mut cx| async move {
10088 let target = match target_task.await.context("target resolution task")? {
10089 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10090 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10091 TargetTaskResult::Location(Some(target)) => target,
10092 };
10093
10094 editor.update(&mut cx, |editor, cx| {
10095 let Some(workspace) = editor.workspace() else {
10096 return Navigated::No;
10097 };
10098 let pane = workspace.read(cx).active_pane().clone();
10099
10100 let range = target.range.to_offset(target.buffer.read(cx));
10101 let range = editor.range_for_match(&range);
10102
10103 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10104 let buffer = target.buffer.read(cx);
10105 let range = check_multiline_range(buffer, range);
10106 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10107 s.select_ranges([range]);
10108 });
10109 } else {
10110 cx.window_context().defer(move |cx| {
10111 let target_editor: View<Self> =
10112 workspace.update(cx, |workspace, cx| {
10113 let pane = if split {
10114 workspace.adjacent_pane(cx)
10115 } else {
10116 workspace.active_pane().clone()
10117 };
10118
10119 workspace.open_project_item(
10120 pane,
10121 target.buffer.clone(),
10122 true,
10123 true,
10124 cx,
10125 )
10126 });
10127 target_editor.update(cx, |target_editor, cx| {
10128 // When selecting a definition in a different buffer, disable the nav history
10129 // to avoid creating a history entry at the previous cursor location.
10130 pane.update(cx, |pane, _| pane.disable_history());
10131 let buffer = target.buffer.read(cx);
10132 let range = check_multiline_range(buffer, range);
10133 target_editor.change_selections(
10134 Some(Autoscroll::focused()),
10135 cx,
10136 |s| {
10137 s.select_ranges([range]);
10138 },
10139 );
10140 pane.update(cx, |pane, _| pane.enable_history());
10141 });
10142 });
10143 }
10144 Navigated::Yes
10145 })
10146 })
10147 } else if !definitions.is_empty() {
10148 cx.spawn(|editor, mut cx| async move {
10149 let (title, location_tasks, workspace) = editor
10150 .update(&mut cx, |editor, cx| {
10151 let tab_kind = match kind {
10152 Some(GotoDefinitionKind::Implementation) => "Implementations",
10153 _ => "Definitions",
10154 };
10155 let title = definitions
10156 .iter()
10157 .find_map(|definition| match definition {
10158 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10159 let buffer = origin.buffer.read(cx);
10160 format!(
10161 "{} for {}",
10162 tab_kind,
10163 buffer
10164 .text_for_range(origin.range.clone())
10165 .collect::<String>()
10166 )
10167 }),
10168 HoverLink::InlayHint(_, _) => None,
10169 HoverLink::Url(_) => None,
10170 HoverLink::File(_) => None,
10171 })
10172 .unwrap_or(tab_kind.to_string());
10173 let location_tasks = definitions
10174 .into_iter()
10175 .map(|definition| match definition {
10176 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
10177 HoverLink::InlayHint(lsp_location, server_id) => {
10178 editor.compute_target_location(lsp_location, server_id, cx)
10179 }
10180 HoverLink::Url(_) => Task::ready(Ok(None)),
10181 HoverLink::File(_) => Task::ready(Ok(None)),
10182 })
10183 .collect::<Vec<_>>();
10184 (title, location_tasks, editor.workspace().clone())
10185 })
10186 .context("location tasks preparation")?;
10187
10188 let locations = future::join_all(location_tasks)
10189 .await
10190 .into_iter()
10191 .filter_map(|location| location.transpose())
10192 .collect::<Result<_>>()
10193 .context("location tasks")?;
10194
10195 let Some(workspace) = workspace else {
10196 return Ok(Navigated::No);
10197 };
10198 let opened = workspace
10199 .update(&mut cx, |workspace, cx| {
10200 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
10201 })
10202 .ok();
10203
10204 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10205 })
10206 } else {
10207 Task::ready(Ok(Navigated::No))
10208 }
10209 }
10210
10211 fn compute_target_location(
10212 &self,
10213 lsp_location: lsp::Location,
10214 server_id: LanguageServerId,
10215 cx: &mut ViewContext<Self>,
10216 ) -> Task<anyhow::Result<Option<Location>>> {
10217 let Some(project) = self.project.clone() else {
10218 return Task::Ready(Some(Ok(None)));
10219 };
10220
10221 cx.spawn(move |editor, mut cx| async move {
10222 let location_task = editor.update(&mut cx, |_, cx| {
10223 project.update(cx, |project, cx| {
10224 let language_server_name = project
10225 .language_server_statuses(cx)
10226 .find(|(id, _)| server_id == *id)
10227 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10228 language_server_name.map(|language_server_name| {
10229 project.open_local_buffer_via_lsp(
10230 lsp_location.uri.clone(),
10231 server_id,
10232 language_server_name,
10233 cx,
10234 )
10235 })
10236 })
10237 })?;
10238 let location = match location_task {
10239 Some(task) => Some({
10240 let target_buffer_handle = task.await.context("open local buffer")?;
10241 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10242 let target_start = target_buffer
10243 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10244 let target_end = target_buffer
10245 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10246 target_buffer.anchor_after(target_start)
10247 ..target_buffer.anchor_before(target_end)
10248 })?;
10249 Location {
10250 buffer: target_buffer_handle,
10251 range,
10252 }
10253 }),
10254 None => None,
10255 };
10256 Ok(location)
10257 })
10258 }
10259
10260 pub fn find_all_references(
10261 &mut self,
10262 _: &FindAllReferences,
10263 cx: &mut ViewContext<Self>,
10264 ) -> Option<Task<Result<Navigated>>> {
10265 let selection = self.selections.newest::<usize>(cx);
10266 let multi_buffer = self.buffer.read(cx);
10267 let head = selection.head();
10268
10269 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10270 let head_anchor = multi_buffer_snapshot.anchor_at(
10271 head,
10272 if head < selection.tail() {
10273 Bias::Right
10274 } else {
10275 Bias::Left
10276 },
10277 );
10278
10279 match self
10280 .find_all_references_task_sources
10281 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10282 {
10283 Ok(_) => {
10284 log::info!(
10285 "Ignoring repeated FindAllReferences invocation with the position of already running task"
10286 );
10287 return None;
10288 }
10289 Err(i) => {
10290 self.find_all_references_task_sources.insert(i, head_anchor);
10291 }
10292 }
10293
10294 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10295 let workspace = self.workspace()?;
10296 let project = workspace.read(cx).project().clone();
10297 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10298 Some(cx.spawn(|editor, mut cx| async move {
10299 let _cleanup = defer({
10300 let mut cx = cx.clone();
10301 move || {
10302 let _ = editor.update(&mut cx, |editor, _| {
10303 if let Ok(i) =
10304 editor
10305 .find_all_references_task_sources
10306 .binary_search_by(|anchor| {
10307 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10308 })
10309 {
10310 editor.find_all_references_task_sources.remove(i);
10311 }
10312 });
10313 }
10314 });
10315
10316 let locations = references.await?;
10317 if locations.is_empty() {
10318 return anyhow::Ok(Navigated::No);
10319 }
10320
10321 workspace.update(&mut cx, |workspace, cx| {
10322 let title = locations
10323 .first()
10324 .as_ref()
10325 .map(|location| {
10326 let buffer = location.buffer.read(cx);
10327 format!(
10328 "References to `{}`",
10329 buffer
10330 .text_for_range(location.range.clone())
10331 .collect::<String>()
10332 )
10333 })
10334 .unwrap();
10335 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10336 Navigated::Yes
10337 })
10338 }))
10339 }
10340
10341 /// Opens a multibuffer with the given project locations in it
10342 pub fn open_locations_in_multibuffer(
10343 workspace: &mut Workspace,
10344 mut locations: Vec<Location>,
10345 title: String,
10346 split: bool,
10347 cx: &mut ViewContext<Workspace>,
10348 ) {
10349 // If there are multiple definitions, open them in a multibuffer
10350 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10351 let mut locations = locations.into_iter().peekable();
10352 let mut ranges_to_highlight = Vec::new();
10353 let capability = workspace.project().read(cx).capability();
10354
10355 let excerpt_buffer = cx.new_model(|cx| {
10356 let mut multibuffer = MultiBuffer::new(capability);
10357 while let Some(location) = locations.next() {
10358 let buffer = location.buffer.read(cx);
10359 let mut ranges_for_buffer = Vec::new();
10360 let range = location.range.to_offset(buffer);
10361 ranges_for_buffer.push(range.clone());
10362
10363 while let Some(next_location) = locations.peek() {
10364 if next_location.buffer == location.buffer {
10365 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10366 locations.next();
10367 } else {
10368 break;
10369 }
10370 }
10371
10372 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10373 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10374 location.buffer.clone(),
10375 ranges_for_buffer,
10376 DEFAULT_MULTIBUFFER_CONTEXT,
10377 cx,
10378 ))
10379 }
10380
10381 multibuffer.with_title(title)
10382 });
10383
10384 let editor = cx.new_view(|cx| {
10385 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10386 });
10387 editor.update(cx, |editor, cx| {
10388 if let Some(first_range) = ranges_to_highlight.first() {
10389 editor.change_selections(None, cx, |selections| {
10390 selections.clear_disjoint();
10391 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10392 });
10393 }
10394 editor.highlight_background::<Self>(
10395 &ranges_to_highlight,
10396 |theme| theme.editor_highlighted_line_background,
10397 cx,
10398 );
10399 });
10400
10401 let item = Box::new(editor);
10402 let item_id = item.item_id();
10403
10404 if split {
10405 workspace.split_item(SplitDirection::Right, item.clone(), cx);
10406 } else {
10407 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10408 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10409 pane.close_current_preview_item(cx)
10410 } else {
10411 None
10412 }
10413 });
10414 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10415 }
10416 workspace.active_pane().update(cx, |pane, cx| {
10417 pane.set_preview_item_id(Some(item_id), cx);
10418 });
10419 }
10420
10421 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10422 use language::ToOffset as _;
10423
10424 let provider = self.semantics_provider.clone()?;
10425 let selection = self.selections.newest_anchor().clone();
10426 let (cursor_buffer, cursor_buffer_position) = self
10427 .buffer
10428 .read(cx)
10429 .text_anchor_for_position(selection.head(), cx)?;
10430 let (tail_buffer, cursor_buffer_position_end) = self
10431 .buffer
10432 .read(cx)
10433 .text_anchor_for_position(selection.tail(), cx)?;
10434 if tail_buffer != cursor_buffer {
10435 return None;
10436 }
10437
10438 let snapshot = cursor_buffer.read(cx).snapshot();
10439 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10440 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10441 let prepare_rename = provider
10442 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10443 .unwrap_or_else(|| Task::ready(Ok(None)));
10444 drop(snapshot);
10445
10446 Some(cx.spawn(|this, mut cx| async move {
10447 let rename_range = if let Some(range) = prepare_rename.await? {
10448 Some(range)
10449 } else {
10450 this.update(&mut cx, |this, cx| {
10451 let buffer = this.buffer.read(cx).snapshot(cx);
10452 let mut buffer_highlights = this
10453 .document_highlights_for_position(selection.head(), &buffer)
10454 .filter(|highlight| {
10455 highlight.start.excerpt_id == selection.head().excerpt_id
10456 && highlight.end.excerpt_id == selection.head().excerpt_id
10457 });
10458 buffer_highlights
10459 .next()
10460 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10461 })?
10462 };
10463 if let Some(rename_range) = rename_range {
10464 this.update(&mut cx, |this, cx| {
10465 let snapshot = cursor_buffer.read(cx).snapshot();
10466 let rename_buffer_range = rename_range.to_offset(&snapshot);
10467 let cursor_offset_in_rename_range =
10468 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10469 let cursor_offset_in_rename_range_end =
10470 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10471
10472 this.take_rename(false, cx);
10473 let buffer = this.buffer.read(cx).read(cx);
10474 let cursor_offset = selection.head().to_offset(&buffer);
10475 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10476 let rename_end = rename_start + rename_buffer_range.len();
10477 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10478 let mut old_highlight_id = None;
10479 let old_name: Arc<str> = buffer
10480 .chunks(rename_start..rename_end, true)
10481 .map(|chunk| {
10482 if old_highlight_id.is_none() {
10483 old_highlight_id = chunk.syntax_highlight_id;
10484 }
10485 chunk.text
10486 })
10487 .collect::<String>()
10488 .into();
10489
10490 drop(buffer);
10491
10492 // Position the selection in the rename editor so that it matches the current selection.
10493 this.show_local_selections = false;
10494 let rename_editor = cx.new_view(|cx| {
10495 let mut editor = Editor::single_line(cx);
10496 editor.buffer.update(cx, |buffer, cx| {
10497 buffer.edit([(0..0, old_name.clone())], None, cx)
10498 });
10499 let rename_selection_range = match cursor_offset_in_rename_range
10500 .cmp(&cursor_offset_in_rename_range_end)
10501 {
10502 Ordering::Equal => {
10503 editor.select_all(&SelectAll, cx);
10504 return editor;
10505 }
10506 Ordering::Less => {
10507 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10508 }
10509 Ordering::Greater => {
10510 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10511 }
10512 };
10513 if rename_selection_range.end > old_name.len() {
10514 editor.select_all(&SelectAll, cx);
10515 } else {
10516 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10517 s.select_ranges([rename_selection_range]);
10518 });
10519 }
10520 editor
10521 });
10522 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10523 if e == &EditorEvent::Focused {
10524 cx.emit(EditorEvent::FocusedIn)
10525 }
10526 })
10527 .detach();
10528
10529 let write_highlights =
10530 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10531 let read_highlights =
10532 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10533 let ranges = write_highlights
10534 .iter()
10535 .flat_map(|(_, ranges)| ranges.iter())
10536 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10537 .cloned()
10538 .collect();
10539
10540 this.highlight_text::<Rename>(
10541 ranges,
10542 HighlightStyle {
10543 fade_out: Some(0.6),
10544 ..Default::default()
10545 },
10546 cx,
10547 );
10548 let rename_focus_handle = rename_editor.focus_handle(cx);
10549 cx.focus(&rename_focus_handle);
10550 let block_id = this.insert_blocks(
10551 [BlockProperties {
10552 style: BlockStyle::Flex,
10553 placement: BlockPlacement::Below(range.start),
10554 height: 1,
10555 render: Arc::new({
10556 let rename_editor = rename_editor.clone();
10557 move |cx: &mut BlockContext| {
10558 let mut text_style = cx.editor_style.text.clone();
10559 if let Some(highlight_style) = old_highlight_id
10560 .and_then(|h| h.style(&cx.editor_style.syntax))
10561 {
10562 text_style = text_style.highlight(highlight_style);
10563 }
10564 div()
10565 .block_mouse_down()
10566 .pl(cx.anchor_x)
10567 .child(EditorElement::new(
10568 &rename_editor,
10569 EditorStyle {
10570 background: cx.theme().system().transparent,
10571 local_player: cx.editor_style.local_player,
10572 text: text_style,
10573 scrollbar_width: cx.editor_style.scrollbar_width,
10574 syntax: cx.editor_style.syntax.clone(),
10575 status: cx.editor_style.status.clone(),
10576 inlay_hints_style: HighlightStyle {
10577 font_weight: Some(FontWeight::BOLD),
10578 ..make_inlay_hints_style(cx)
10579 },
10580 suggestions_style: HighlightStyle {
10581 color: Some(cx.theme().status().predictive),
10582 ..HighlightStyle::default()
10583 },
10584 ..EditorStyle::default()
10585 },
10586 ))
10587 .into_any_element()
10588 }
10589 }),
10590 priority: 0,
10591 }],
10592 Some(Autoscroll::fit()),
10593 cx,
10594 )[0];
10595 this.pending_rename = Some(RenameState {
10596 range,
10597 old_name,
10598 editor: rename_editor,
10599 block_id,
10600 });
10601 })?;
10602 }
10603
10604 Ok(())
10605 }))
10606 }
10607
10608 pub fn confirm_rename(
10609 &mut self,
10610 _: &ConfirmRename,
10611 cx: &mut ViewContext<Self>,
10612 ) -> Option<Task<Result<()>>> {
10613 let rename = self.take_rename(false, cx)?;
10614 let workspace = self.workspace()?.downgrade();
10615 let (buffer, start) = self
10616 .buffer
10617 .read(cx)
10618 .text_anchor_for_position(rename.range.start, cx)?;
10619 let (end_buffer, _) = self
10620 .buffer
10621 .read(cx)
10622 .text_anchor_for_position(rename.range.end, cx)?;
10623 if buffer != end_buffer {
10624 return None;
10625 }
10626
10627 let old_name = rename.old_name;
10628 let new_name = rename.editor.read(cx).text(cx);
10629
10630 let rename = self.semantics_provider.as_ref()?.perform_rename(
10631 &buffer,
10632 start,
10633 new_name.clone(),
10634 cx,
10635 )?;
10636
10637 Some(cx.spawn(|editor, mut cx| async move {
10638 let project_transaction = rename.await?;
10639 Self::open_project_transaction(
10640 &editor,
10641 workspace,
10642 project_transaction,
10643 format!("Rename: {} → {}", old_name, new_name),
10644 cx.clone(),
10645 )
10646 .await?;
10647
10648 editor.update(&mut cx, |editor, cx| {
10649 editor.refresh_document_highlights(cx);
10650 })?;
10651 Ok(())
10652 }))
10653 }
10654
10655 fn take_rename(
10656 &mut self,
10657 moving_cursor: bool,
10658 cx: &mut ViewContext<Self>,
10659 ) -> Option<RenameState> {
10660 let rename = self.pending_rename.take()?;
10661 if rename.editor.focus_handle(cx).is_focused(cx) {
10662 cx.focus(&self.focus_handle);
10663 }
10664
10665 self.remove_blocks(
10666 [rename.block_id].into_iter().collect(),
10667 Some(Autoscroll::fit()),
10668 cx,
10669 );
10670 self.clear_highlights::<Rename>(cx);
10671 self.show_local_selections = true;
10672
10673 if moving_cursor {
10674 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10675 editor.selections.newest::<usize>(cx).head()
10676 });
10677
10678 // Update the selection to match the position of the selection inside
10679 // the rename editor.
10680 let snapshot = self.buffer.read(cx).read(cx);
10681 let rename_range = rename.range.to_offset(&snapshot);
10682 let cursor_in_editor = snapshot
10683 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10684 .min(rename_range.end);
10685 drop(snapshot);
10686
10687 self.change_selections(None, cx, |s| {
10688 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10689 });
10690 } else {
10691 self.refresh_document_highlights(cx);
10692 }
10693
10694 Some(rename)
10695 }
10696
10697 pub fn pending_rename(&self) -> Option<&RenameState> {
10698 self.pending_rename.as_ref()
10699 }
10700
10701 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10702 let project = match &self.project {
10703 Some(project) => project.clone(),
10704 None => return None,
10705 };
10706
10707 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10708 }
10709
10710 fn format_selections(
10711 &mut self,
10712 _: &FormatSelections,
10713 cx: &mut ViewContext<Self>,
10714 ) -> Option<Task<Result<()>>> {
10715 let project = match &self.project {
10716 Some(project) => project.clone(),
10717 None => return None,
10718 };
10719
10720 let selections = self
10721 .selections
10722 .all_adjusted(cx)
10723 .into_iter()
10724 .filter(|s| !s.is_empty())
10725 .collect_vec();
10726
10727 Some(self.perform_format(
10728 project,
10729 FormatTrigger::Manual,
10730 FormatTarget::Ranges(selections),
10731 cx,
10732 ))
10733 }
10734
10735 fn perform_format(
10736 &mut self,
10737 project: Model<Project>,
10738 trigger: FormatTrigger,
10739 target: FormatTarget,
10740 cx: &mut ViewContext<Self>,
10741 ) -> Task<Result<()>> {
10742 let buffer = self.buffer().clone();
10743 let mut buffers = buffer.read(cx).all_buffers();
10744 if trigger == FormatTrigger::Save {
10745 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10746 }
10747
10748 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10749 let format = project.update(cx, |project, cx| {
10750 project.format(buffers, true, trigger, target, cx)
10751 });
10752
10753 cx.spawn(|_, mut cx| async move {
10754 let transaction = futures::select_biased! {
10755 () = timeout => {
10756 log::warn!("timed out waiting for formatting");
10757 None
10758 }
10759 transaction = format.log_err().fuse() => transaction,
10760 };
10761
10762 buffer
10763 .update(&mut cx, |buffer, cx| {
10764 if let Some(transaction) = transaction {
10765 if !buffer.is_singleton() {
10766 buffer.push_transaction(&transaction.0, cx);
10767 }
10768 }
10769
10770 cx.notify();
10771 })
10772 .ok();
10773
10774 Ok(())
10775 })
10776 }
10777
10778 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10779 if let Some(project) = self.project.clone() {
10780 self.buffer.update(cx, |multi_buffer, cx| {
10781 project.update(cx, |project, cx| {
10782 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10783 });
10784 })
10785 }
10786 }
10787
10788 fn cancel_language_server_work(
10789 &mut self,
10790 _: &actions::CancelLanguageServerWork,
10791 cx: &mut ViewContext<Self>,
10792 ) {
10793 if let Some(project) = self.project.clone() {
10794 self.buffer.update(cx, |multi_buffer, cx| {
10795 project.update(cx, |project, cx| {
10796 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10797 });
10798 })
10799 }
10800 }
10801
10802 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10803 cx.show_character_palette();
10804 }
10805
10806 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10807 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10808 let buffer = self.buffer.read(cx).snapshot(cx);
10809 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10810 let is_valid = buffer
10811 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10812 .any(|entry| {
10813 entry.diagnostic.is_primary
10814 && !entry.range.is_empty()
10815 && entry.range.start == primary_range_start
10816 && entry.diagnostic.message == active_diagnostics.primary_message
10817 });
10818
10819 if is_valid != active_diagnostics.is_valid {
10820 active_diagnostics.is_valid = is_valid;
10821 let mut new_styles = HashMap::default();
10822 for (block_id, diagnostic) in &active_diagnostics.blocks {
10823 new_styles.insert(
10824 *block_id,
10825 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10826 );
10827 }
10828 self.display_map.update(cx, |display_map, _cx| {
10829 display_map.replace_blocks(new_styles)
10830 });
10831 }
10832 }
10833 }
10834
10835 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10836 self.dismiss_diagnostics(cx);
10837 let snapshot = self.snapshot(cx);
10838 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10839 let buffer = self.buffer.read(cx).snapshot(cx);
10840
10841 let mut primary_range = None;
10842 let mut primary_message = None;
10843 let mut group_end = Point::zero();
10844 let diagnostic_group = buffer
10845 .diagnostic_group::<MultiBufferPoint>(group_id)
10846 .filter_map(|entry| {
10847 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10848 && (entry.range.start.row == entry.range.end.row
10849 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10850 {
10851 return None;
10852 }
10853 if entry.range.end > group_end {
10854 group_end = entry.range.end;
10855 }
10856 if entry.diagnostic.is_primary {
10857 primary_range = Some(entry.range.clone());
10858 primary_message = Some(entry.diagnostic.message.clone());
10859 }
10860 Some(entry)
10861 })
10862 .collect::<Vec<_>>();
10863 let primary_range = primary_range?;
10864 let primary_message = primary_message?;
10865 let primary_range =
10866 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10867
10868 let blocks = display_map
10869 .insert_blocks(
10870 diagnostic_group.iter().map(|entry| {
10871 let diagnostic = entry.diagnostic.clone();
10872 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10873 BlockProperties {
10874 style: BlockStyle::Fixed,
10875 placement: BlockPlacement::Below(
10876 buffer.anchor_after(entry.range.start),
10877 ),
10878 height: message_height,
10879 render: diagnostic_block_renderer(diagnostic, None, true, true),
10880 priority: 0,
10881 }
10882 }),
10883 cx,
10884 )
10885 .into_iter()
10886 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10887 .collect();
10888
10889 Some(ActiveDiagnosticGroup {
10890 primary_range,
10891 primary_message,
10892 group_id,
10893 blocks,
10894 is_valid: true,
10895 })
10896 });
10897 self.active_diagnostics.is_some()
10898 }
10899
10900 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10901 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10902 self.display_map.update(cx, |display_map, cx| {
10903 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10904 });
10905 cx.notify();
10906 }
10907 }
10908
10909 pub fn set_selections_from_remote(
10910 &mut self,
10911 selections: Vec<Selection<Anchor>>,
10912 pending_selection: Option<Selection<Anchor>>,
10913 cx: &mut ViewContext<Self>,
10914 ) {
10915 let old_cursor_position = self.selections.newest_anchor().head();
10916 self.selections.change_with(cx, |s| {
10917 s.select_anchors(selections);
10918 if let Some(pending_selection) = pending_selection {
10919 s.set_pending(pending_selection, SelectMode::Character);
10920 } else {
10921 s.clear_pending();
10922 }
10923 });
10924 self.selections_did_change(false, &old_cursor_position, true, cx);
10925 }
10926
10927 fn push_to_selection_history(&mut self) {
10928 self.selection_history.push(SelectionHistoryEntry {
10929 selections: self.selections.disjoint_anchors(),
10930 select_next_state: self.select_next_state.clone(),
10931 select_prev_state: self.select_prev_state.clone(),
10932 add_selections_state: self.add_selections_state.clone(),
10933 });
10934 }
10935
10936 pub fn transact(
10937 &mut self,
10938 cx: &mut ViewContext<Self>,
10939 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10940 ) -> Option<TransactionId> {
10941 self.start_transaction_at(Instant::now(), cx);
10942 update(self, cx);
10943 self.end_transaction_at(Instant::now(), cx)
10944 }
10945
10946 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10947 self.end_selection(cx);
10948 if let Some(tx_id) = self
10949 .buffer
10950 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10951 {
10952 self.selection_history
10953 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10954 cx.emit(EditorEvent::TransactionBegun {
10955 transaction_id: tx_id,
10956 })
10957 }
10958 }
10959
10960 fn end_transaction_at(
10961 &mut self,
10962 now: Instant,
10963 cx: &mut ViewContext<Self>,
10964 ) -> Option<TransactionId> {
10965 if let Some(transaction_id) = self
10966 .buffer
10967 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10968 {
10969 if let Some((_, end_selections)) =
10970 self.selection_history.transaction_mut(transaction_id)
10971 {
10972 *end_selections = Some(self.selections.disjoint_anchors());
10973 } else {
10974 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10975 }
10976
10977 cx.emit(EditorEvent::Edited { transaction_id });
10978 Some(transaction_id)
10979 } else {
10980 None
10981 }
10982 }
10983
10984 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10985 let selection = self.selections.newest::<Point>(cx);
10986
10987 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10988 let range = if selection.is_empty() {
10989 let point = selection.head().to_display_point(&display_map);
10990 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10991 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10992 .to_point(&display_map);
10993 start..end
10994 } else {
10995 selection.range()
10996 };
10997 if display_map.folds_in_range(range).next().is_some() {
10998 self.unfold_lines(&Default::default(), cx)
10999 } else {
11000 self.fold(&Default::default(), cx)
11001 }
11002 }
11003
11004 pub fn toggle_fold_recursive(
11005 &mut self,
11006 _: &actions::ToggleFoldRecursive,
11007 cx: &mut ViewContext<Self>,
11008 ) {
11009 let selection = self.selections.newest::<Point>(cx);
11010
11011 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11012 let range = if selection.is_empty() {
11013 let point = selection.head().to_display_point(&display_map);
11014 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11015 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11016 .to_point(&display_map);
11017 start..end
11018 } else {
11019 selection.range()
11020 };
11021 if display_map.folds_in_range(range).next().is_some() {
11022 self.unfold_recursive(&Default::default(), cx)
11023 } else {
11024 self.fold_recursive(&Default::default(), cx)
11025 }
11026 }
11027
11028 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
11029 let mut to_fold = Vec::new();
11030 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11031 let selections = self.selections.all_adjusted(cx);
11032
11033 for selection in selections {
11034 let range = selection.range().sorted();
11035 let buffer_start_row = range.start.row;
11036
11037 if range.start.row != range.end.row {
11038 let mut found = false;
11039 let mut row = range.start.row;
11040 while row <= range.end.row {
11041 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11042 found = true;
11043 row = crease.range().end.row + 1;
11044 to_fold.push(crease);
11045 } else {
11046 row += 1
11047 }
11048 }
11049 if found {
11050 continue;
11051 }
11052 }
11053
11054 for row in (0..=range.start.row).rev() {
11055 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11056 if crease.range().end.row >= buffer_start_row {
11057 to_fold.push(crease);
11058 if row <= range.start.row {
11059 break;
11060 }
11061 }
11062 }
11063 }
11064 }
11065
11066 self.fold_creases(to_fold, true, cx);
11067 }
11068
11069 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
11070 let fold_at_level = fold_at.level;
11071 let snapshot = self.buffer.read(cx).snapshot(cx);
11072 let mut to_fold = Vec::new();
11073 let mut stack = vec![(0, snapshot.max_buffer_row().0, 1)];
11074
11075 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11076 while start_row < end_row {
11077 match self
11078 .snapshot(cx)
11079 .crease_for_buffer_row(MultiBufferRow(start_row))
11080 {
11081 Some(crease) => {
11082 let nested_start_row = crease.range().start.row + 1;
11083 let nested_end_row = crease.range().end.row;
11084
11085 if current_level < fold_at_level {
11086 stack.push((nested_start_row, nested_end_row, current_level + 1));
11087 } else if current_level == fold_at_level {
11088 to_fold.push(crease);
11089 }
11090
11091 start_row = nested_end_row + 1;
11092 }
11093 None => start_row += 1,
11094 }
11095 }
11096 }
11097
11098 self.fold_creases(to_fold, true, cx);
11099 }
11100
11101 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
11102 let mut fold_ranges = Vec::new();
11103 let snapshot = self.buffer.read(cx).snapshot(cx);
11104
11105 for row in 0..snapshot.max_buffer_row().0 {
11106 if let Some(foldable_range) =
11107 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
11108 {
11109 fold_ranges.push(foldable_range);
11110 }
11111 }
11112
11113 self.fold_creases(fold_ranges, true, cx);
11114 }
11115
11116 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
11117 let mut to_fold = Vec::new();
11118 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11119 let selections = self.selections.all_adjusted(cx);
11120
11121 for selection in selections {
11122 let range = selection.range().sorted();
11123 let buffer_start_row = range.start.row;
11124
11125 if range.start.row != range.end.row {
11126 let mut found = false;
11127 for row in range.start.row..=range.end.row {
11128 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11129 found = true;
11130 to_fold.push(crease);
11131 }
11132 }
11133 if found {
11134 continue;
11135 }
11136 }
11137
11138 for row in (0..=range.start.row).rev() {
11139 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11140 if crease.range().end.row >= buffer_start_row {
11141 to_fold.push(crease);
11142 } else {
11143 break;
11144 }
11145 }
11146 }
11147 }
11148
11149 self.fold_creases(to_fold, true, cx);
11150 }
11151
11152 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
11153 let buffer_row = fold_at.buffer_row;
11154 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11155
11156 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11157 let autoscroll = self
11158 .selections
11159 .all::<Point>(cx)
11160 .iter()
11161 .any(|selection| crease.range().overlaps(&selection.range()));
11162
11163 self.fold_creases(vec![crease], autoscroll, cx);
11164 }
11165 }
11166
11167 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
11168 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11169 let buffer = &display_map.buffer_snapshot;
11170 let selections = self.selections.all::<Point>(cx);
11171 let ranges = selections
11172 .iter()
11173 .map(|s| {
11174 let range = s.display_range(&display_map).sorted();
11175 let mut start = range.start.to_point(&display_map);
11176 let mut end = range.end.to_point(&display_map);
11177 start.column = 0;
11178 end.column = buffer.line_len(MultiBufferRow(end.row));
11179 start..end
11180 })
11181 .collect::<Vec<_>>();
11182
11183 self.unfold_ranges(&ranges, true, true, cx);
11184 }
11185
11186 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
11187 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11188 let selections = self.selections.all::<Point>(cx);
11189 let ranges = selections
11190 .iter()
11191 .map(|s| {
11192 let mut range = s.display_range(&display_map).sorted();
11193 *range.start.column_mut() = 0;
11194 *range.end.column_mut() = display_map.line_len(range.end.row());
11195 let start = range.start.to_point(&display_map);
11196 let end = range.end.to_point(&display_map);
11197 start..end
11198 })
11199 .collect::<Vec<_>>();
11200
11201 self.unfold_ranges(&ranges, true, true, cx);
11202 }
11203
11204 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
11205 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11206
11207 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11208 ..Point::new(
11209 unfold_at.buffer_row.0,
11210 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11211 );
11212
11213 let autoscroll = self
11214 .selections
11215 .all::<Point>(cx)
11216 .iter()
11217 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11218
11219 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
11220 }
11221
11222 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
11223 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11224 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11225 }
11226
11227 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
11228 let selections = self.selections.all::<Point>(cx);
11229 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11230 let line_mode = self.selections.line_mode;
11231 let ranges = selections
11232 .into_iter()
11233 .map(|s| {
11234 if line_mode {
11235 let start = Point::new(s.start.row, 0);
11236 let end = Point::new(
11237 s.end.row,
11238 display_map
11239 .buffer_snapshot
11240 .line_len(MultiBufferRow(s.end.row)),
11241 );
11242 Crease::simple(start..end, display_map.fold_placeholder.clone())
11243 } else {
11244 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11245 }
11246 })
11247 .collect::<Vec<_>>();
11248 self.fold_creases(ranges, true, cx);
11249 }
11250
11251 pub fn fold_creases<T: ToOffset + Clone>(
11252 &mut self,
11253 creases: Vec<Crease<T>>,
11254 auto_scroll: bool,
11255 cx: &mut ViewContext<Self>,
11256 ) {
11257 if creases.is_empty() {
11258 return;
11259 }
11260
11261 let mut buffers_affected = HashMap::default();
11262 let multi_buffer = self.buffer().read(cx);
11263 for crease in &creases {
11264 if let Some((_, buffer, _)) =
11265 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11266 {
11267 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11268 };
11269 }
11270
11271 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11272
11273 if auto_scroll {
11274 self.request_autoscroll(Autoscroll::fit(), cx);
11275 }
11276
11277 for buffer in buffers_affected.into_values() {
11278 self.sync_expanded_diff_hunks(buffer, cx);
11279 }
11280
11281 cx.notify();
11282
11283 if let Some(active_diagnostics) = self.active_diagnostics.take() {
11284 // Clear diagnostics block when folding a range that contains it.
11285 let snapshot = self.snapshot(cx);
11286 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11287 drop(snapshot);
11288 self.active_diagnostics = Some(active_diagnostics);
11289 self.dismiss_diagnostics(cx);
11290 } else {
11291 self.active_diagnostics = Some(active_diagnostics);
11292 }
11293 }
11294
11295 self.scrollbar_marker_state.dirty = true;
11296 }
11297
11298 /// Removes any folds whose ranges intersect any of the given ranges.
11299 pub fn unfold_ranges<T: ToOffset + Clone>(
11300 &mut self,
11301 ranges: &[Range<T>],
11302 inclusive: bool,
11303 auto_scroll: bool,
11304 cx: &mut ViewContext<Self>,
11305 ) {
11306 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11307 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11308 });
11309 }
11310
11311 /// Removes any folds with the given ranges.
11312 pub fn remove_folds_with_type<T: ToOffset + Clone>(
11313 &mut self,
11314 ranges: &[Range<T>],
11315 type_id: TypeId,
11316 auto_scroll: bool,
11317 cx: &mut ViewContext<Self>,
11318 ) {
11319 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11320 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11321 });
11322 }
11323
11324 fn remove_folds_with<T: ToOffset + Clone>(
11325 &mut self,
11326 ranges: &[Range<T>],
11327 auto_scroll: bool,
11328 cx: &mut ViewContext<Self>,
11329 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11330 ) {
11331 if ranges.is_empty() {
11332 return;
11333 }
11334
11335 let mut buffers_affected = HashMap::default();
11336 let multi_buffer = self.buffer().read(cx);
11337 for range in ranges {
11338 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11339 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
11340 };
11341 }
11342
11343 self.display_map.update(cx, update);
11344
11345 if auto_scroll {
11346 self.request_autoscroll(Autoscroll::fit(), cx);
11347 }
11348
11349 for buffer in buffers_affected.into_values() {
11350 self.sync_expanded_diff_hunks(buffer, cx);
11351 }
11352
11353 cx.notify();
11354 self.scrollbar_marker_state.dirty = true;
11355 self.active_indent_guides_state.dirty = true;
11356 }
11357
11358 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11359 self.display_map.read(cx).fold_placeholder.clone()
11360 }
11361
11362 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11363 if hovered != self.gutter_hovered {
11364 self.gutter_hovered = hovered;
11365 cx.notify();
11366 }
11367 }
11368
11369 pub fn insert_blocks(
11370 &mut self,
11371 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11372 autoscroll: Option<Autoscroll>,
11373 cx: &mut ViewContext<Self>,
11374 ) -> Vec<CustomBlockId> {
11375 let blocks = self
11376 .display_map
11377 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11378 if let Some(autoscroll) = autoscroll {
11379 self.request_autoscroll(autoscroll, cx);
11380 }
11381 cx.notify();
11382 blocks
11383 }
11384
11385 pub fn resize_blocks(
11386 &mut self,
11387 heights: HashMap<CustomBlockId, u32>,
11388 autoscroll: Option<Autoscroll>,
11389 cx: &mut ViewContext<Self>,
11390 ) {
11391 self.display_map
11392 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11393 if let Some(autoscroll) = autoscroll {
11394 self.request_autoscroll(autoscroll, cx);
11395 }
11396 cx.notify();
11397 }
11398
11399 pub fn replace_blocks(
11400 &mut self,
11401 renderers: HashMap<CustomBlockId, RenderBlock>,
11402 autoscroll: Option<Autoscroll>,
11403 cx: &mut ViewContext<Self>,
11404 ) {
11405 self.display_map
11406 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11407 if let Some(autoscroll) = autoscroll {
11408 self.request_autoscroll(autoscroll, cx);
11409 }
11410 cx.notify();
11411 }
11412
11413 pub fn remove_blocks(
11414 &mut self,
11415 block_ids: HashSet<CustomBlockId>,
11416 autoscroll: Option<Autoscroll>,
11417 cx: &mut ViewContext<Self>,
11418 ) {
11419 self.display_map.update(cx, |display_map, cx| {
11420 display_map.remove_blocks(block_ids, cx)
11421 });
11422 if let Some(autoscroll) = autoscroll {
11423 self.request_autoscroll(autoscroll, cx);
11424 }
11425 cx.notify();
11426 }
11427
11428 pub fn row_for_block(
11429 &self,
11430 block_id: CustomBlockId,
11431 cx: &mut ViewContext<Self>,
11432 ) -> Option<DisplayRow> {
11433 self.display_map
11434 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11435 }
11436
11437 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11438 self.focused_block = Some(focused_block);
11439 }
11440
11441 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11442 self.focused_block.take()
11443 }
11444
11445 pub fn insert_creases(
11446 &mut self,
11447 creases: impl IntoIterator<Item = Crease<Anchor>>,
11448 cx: &mut ViewContext<Self>,
11449 ) -> Vec<CreaseId> {
11450 self.display_map
11451 .update(cx, |map, cx| map.insert_creases(creases, cx))
11452 }
11453
11454 pub fn remove_creases(
11455 &mut self,
11456 ids: impl IntoIterator<Item = CreaseId>,
11457 cx: &mut ViewContext<Self>,
11458 ) {
11459 self.display_map
11460 .update(cx, |map, cx| map.remove_creases(ids, cx));
11461 }
11462
11463 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11464 self.display_map
11465 .update(cx, |map, cx| map.snapshot(cx))
11466 .longest_row()
11467 }
11468
11469 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11470 self.display_map
11471 .update(cx, |map, cx| map.snapshot(cx))
11472 .max_point()
11473 }
11474
11475 pub fn text(&self, cx: &AppContext) -> String {
11476 self.buffer.read(cx).read(cx).text()
11477 }
11478
11479 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11480 let text = self.text(cx);
11481 let text = text.trim();
11482
11483 if text.is_empty() {
11484 return None;
11485 }
11486
11487 Some(text.to_string())
11488 }
11489
11490 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11491 self.transact(cx, |this, cx| {
11492 this.buffer
11493 .read(cx)
11494 .as_singleton()
11495 .expect("you can only call set_text on editors for singleton buffers")
11496 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11497 });
11498 }
11499
11500 pub fn display_text(&self, cx: &mut AppContext) -> String {
11501 self.display_map
11502 .update(cx, |map, cx| map.snapshot(cx))
11503 .text()
11504 }
11505
11506 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11507 let mut wrap_guides = smallvec::smallvec![];
11508
11509 if self.show_wrap_guides == Some(false) {
11510 return wrap_guides;
11511 }
11512
11513 let settings = self.buffer.read(cx).settings_at(0, cx);
11514 if settings.show_wrap_guides {
11515 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11516 wrap_guides.push((soft_wrap as usize, true));
11517 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11518 wrap_guides.push((soft_wrap as usize, true));
11519 }
11520 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11521 }
11522
11523 wrap_guides
11524 }
11525
11526 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11527 let settings = self.buffer.read(cx).settings_at(0, cx);
11528 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11529 match mode {
11530 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11531 SoftWrap::None
11532 }
11533 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11534 language_settings::SoftWrap::PreferredLineLength => {
11535 SoftWrap::Column(settings.preferred_line_length)
11536 }
11537 language_settings::SoftWrap::Bounded => {
11538 SoftWrap::Bounded(settings.preferred_line_length)
11539 }
11540 }
11541 }
11542
11543 pub fn set_soft_wrap_mode(
11544 &mut self,
11545 mode: language_settings::SoftWrap,
11546 cx: &mut ViewContext<Self>,
11547 ) {
11548 self.soft_wrap_mode_override = Some(mode);
11549 cx.notify();
11550 }
11551
11552 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11553 self.text_style_refinement = Some(style);
11554 }
11555
11556 /// called by the Element so we know what style we were most recently rendered with.
11557 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11558 let rem_size = cx.rem_size();
11559 self.display_map.update(cx, |map, cx| {
11560 map.set_font(
11561 style.text.font(),
11562 style.text.font_size.to_pixels(rem_size),
11563 cx,
11564 )
11565 });
11566 self.style = Some(style);
11567 }
11568
11569 pub fn style(&self) -> Option<&EditorStyle> {
11570 self.style.as_ref()
11571 }
11572
11573 // Called by the element. This method is not designed to be called outside of the editor
11574 // element's layout code because it does not notify when rewrapping is computed synchronously.
11575 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11576 self.display_map
11577 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11578 }
11579
11580 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11581 if self.soft_wrap_mode_override.is_some() {
11582 self.soft_wrap_mode_override.take();
11583 } else {
11584 let soft_wrap = match self.soft_wrap_mode(cx) {
11585 SoftWrap::GitDiff => return,
11586 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11587 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11588 language_settings::SoftWrap::None
11589 }
11590 };
11591 self.soft_wrap_mode_override = Some(soft_wrap);
11592 }
11593 cx.notify();
11594 }
11595
11596 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11597 let Some(workspace) = self.workspace() else {
11598 return;
11599 };
11600 let fs = workspace.read(cx).app_state().fs.clone();
11601 let current_show = TabBarSettings::get_global(cx).show;
11602 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11603 setting.show = Some(!current_show);
11604 });
11605 }
11606
11607 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11608 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11609 self.buffer
11610 .read(cx)
11611 .settings_at(0, cx)
11612 .indent_guides
11613 .enabled
11614 });
11615 self.show_indent_guides = Some(!currently_enabled);
11616 cx.notify();
11617 }
11618
11619 fn should_show_indent_guides(&self) -> Option<bool> {
11620 self.show_indent_guides
11621 }
11622
11623 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11624 let mut editor_settings = EditorSettings::get_global(cx).clone();
11625 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11626 EditorSettings::override_global(editor_settings, cx);
11627 }
11628
11629 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11630 self.use_relative_line_numbers
11631 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11632 }
11633
11634 pub fn toggle_relative_line_numbers(
11635 &mut self,
11636 _: &ToggleRelativeLineNumbers,
11637 cx: &mut ViewContext<Self>,
11638 ) {
11639 let is_relative = self.should_use_relative_line_numbers(cx);
11640 self.set_relative_line_number(Some(!is_relative), cx)
11641 }
11642
11643 pub fn set_relative_line_number(
11644 &mut self,
11645 is_relative: Option<bool>,
11646 cx: &mut ViewContext<Self>,
11647 ) {
11648 self.use_relative_line_numbers = is_relative;
11649 cx.notify();
11650 }
11651
11652 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11653 self.show_gutter = show_gutter;
11654 cx.notify();
11655 }
11656
11657 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11658 self.show_line_numbers = Some(show_line_numbers);
11659 cx.notify();
11660 }
11661
11662 pub fn set_show_git_diff_gutter(
11663 &mut self,
11664 show_git_diff_gutter: bool,
11665 cx: &mut ViewContext<Self>,
11666 ) {
11667 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11668 cx.notify();
11669 }
11670
11671 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11672 self.show_code_actions = Some(show_code_actions);
11673 cx.notify();
11674 }
11675
11676 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11677 self.show_runnables = Some(show_runnables);
11678 cx.notify();
11679 }
11680
11681 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11682 if self.display_map.read(cx).masked != masked {
11683 self.display_map.update(cx, |map, _| map.masked = masked);
11684 }
11685 cx.notify()
11686 }
11687
11688 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11689 self.show_wrap_guides = Some(show_wrap_guides);
11690 cx.notify();
11691 }
11692
11693 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11694 self.show_indent_guides = Some(show_indent_guides);
11695 cx.notify();
11696 }
11697
11698 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11699 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11700 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11701 if let Some(dir) = file.abs_path(cx).parent() {
11702 return Some(dir.to_owned());
11703 }
11704 }
11705
11706 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11707 return Some(project_path.path.to_path_buf());
11708 }
11709 }
11710
11711 None
11712 }
11713
11714 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11715 self.active_excerpt(cx)?
11716 .1
11717 .read(cx)
11718 .file()
11719 .and_then(|f| f.as_local())
11720 }
11721
11722 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11723 if let Some(target) = self.target_file(cx) {
11724 cx.reveal_path(&target.abs_path(cx));
11725 }
11726 }
11727
11728 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11729 if let Some(file) = self.target_file(cx) {
11730 if let Some(path) = file.abs_path(cx).to_str() {
11731 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11732 }
11733 }
11734 }
11735
11736 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11737 if let Some(file) = self.target_file(cx) {
11738 if let Some(path) = file.path().to_str() {
11739 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11740 }
11741 }
11742 }
11743
11744 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11745 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11746
11747 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11748 self.start_git_blame(true, cx);
11749 }
11750
11751 cx.notify();
11752 }
11753
11754 pub fn toggle_git_blame_inline(
11755 &mut self,
11756 _: &ToggleGitBlameInline,
11757 cx: &mut ViewContext<Self>,
11758 ) {
11759 self.toggle_git_blame_inline_internal(true, cx);
11760 cx.notify();
11761 }
11762
11763 pub fn git_blame_inline_enabled(&self) -> bool {
11764 self.git_blame_inline_enabled
11765 }
11766
11767 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11768 self.show_selection_menu = self
11769 .show_selection_menu
11770 .map(|show_selections_menu| !show_selections_menu)
11771 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11772
11773 cx.notify();
11774 }
11775
11776 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11777 self.show_selection_menu
11778 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11779 }
11780
11781 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11782 if let Some(project) = self.project.as_ref() {
11783 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11784 return;
11785 };
11786
11787 if buffer.read(cx).file().is_none() {
11788 return;
11789 }
11790
11791 let focused = self.focus_handle(cx).contains_focused(cx);
11792
11793 let project = project.clone();
11794 let blame =
11795 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11796 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11797 self.blame = Some(blame);
11798 }
11799 }
11800
11801 fn toggle_git_blame_inline_internal(
11802 &mut self,
11803 user_triggered: bool,
11804 cx: &mut ViewContext<Self>,
11805 ) {
11806 if self.git_blame_inline_enabled {
11807 self.git_blame_inline_enabled = false;
11808 self.show_git_blame_inline = false;
11809 self.show_git_blame_inline_delay_task.take();
11810 } else {
11811 self.git_blame_inline_enabled = true;
11812 self.start_git_blame_inline(user_triggered, cx);
11813 }
11814
11815 cx.notify();
11816 }
11817
11818 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11819 self.start_git_blame(user_triggered, cx);
11820
11821 if ProjectSettings::get_global(cx)
11822 .git
11823 .inline_blame_delay()
11824 .is_some()
11825 {
11826 self.start_inline_blame_timer(cx);
11827 } else {
11828 self.show_git_blame_inline = true
11829 }
11830 }
11831
11832 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11833 self.blame.as_ref()
11834 }
11835
11836 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11837 self.show_git_blame_gutter && self.has_blame_entries(cx)
11838 }
11839
11840 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11841 self.show_git_blame_inline
11842 && self.focus_handle.is_focused(cx)
11843 && !self.newest_selection_head_on_empty_line(cx)
11844 && self.has_blame_entries(cx)
11845 }
11846
11847 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11848 self.blame()
11849 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11850 }
11851
11852 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11853 let cursor_anchor = self.selections.newest_anchor().head();
11854
11855 let snapshot = self.buffer.read(cx).snapshot(cx);
11856 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11857
11858 snapshot.line_len(buffer_row) == 0
11859 }
11860
11861 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11862 let buffer_and_selection = maybe!({
11863 let selection = self.selections.newest::<Point>(cx);
11864 let selection_range = selection.range();
11865
11866 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11867 (buffer, selection_range.start.row..selection_range.end.row)
11868 } else {
11869 let buffer_ranges = self
11870 .buffer()
11871 .read(cx)
11872 .range_to_buffer_ranges(selection_range, cx);
11873
11874 let (buffer, range, _) = if selection.reversed {
11875 buffer_ranges.first()
11876 } else {
11877 buffer_ranges.last()
11878 }?;
11879
11880 let snapshot = buffer.read(cx).snapshot();
11881 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11882 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11883 (buffer.clone(), selection)
11884 };
11885
11886 Some((buffer, selection))
11887 });
11888
11889 let Some((buffer, selection)) = buffer_and_selection else {
11890 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11891 };
11892
11893 let Some(project) = self.project.as_ref() else {
11894 return Task::ready(Err(anyhow!("editor does not have project")));
11895 };
11896
11897 project.update(cx, |project, cx| {
11898 project.get_permalink_to_line(&buffer, selection, cx)
11899 })
11900 }
11901
11902 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11903 let permalink_task = self.get_permalink_to_line(cx);
11904 let workspace = self.workspace();
11905
11906 cx.spawn(|_, mut cx| async move {
11907 match permalink_task.await {
11908 Ok(permalink) => {
11909 cx.update(|cx| {
11910 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11911 })
11912 .ok();
11913 }
11914 Err(err) => {
11915 let message = format!("Failed to copy permalink: {err}");
11916
11917 Err::<(), anyhow::Error>(err).log_err();
11918
11919 if let Some(workspace) = workspace {
11920 workspace
11921 .update(&mut cx, |workspace, cx| {
11922 struct CopyPermalinkToLine;
11923
11924 workspace.show_toast(
11925 Toast::new(
11926 NotificationId::unique::<CopyPermalinkToLine>(),
11927 message,
11928 ),
11929 cx,
11930 )
11931 })
11932 .ok();
11933 }
11934 }
11935 }
11936 })
11937 .detach();
11938 }
11939
11940 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11941 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11942 if let Some(file) = self.target_file(cx) {
11943 if let Some(path) = file.path().to_str() {
11944 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11945 }
11946 }
11947 }
11948
11949 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11950 let permalink_task = self.get_permalink_to_line(cx);
11951 let workspace = self.workspace();
11952
11953 cx.spawn(|_, mut cx| async move {
11954 match permalink_task.await {
11955 Ok(permalink) => {
11956 cx.update(|cx| {
11957 cx.open_url(permalink.as_ref());
11958 })
11959 .ok();
11960 }
11961 Err(err) => {
11962 let message = format!("Failed to open permalink: {err}");
11963
11964 Err::<(), anyhow::Error>(err).log_err();
11965
11966 if let Some(workspace) = workspace {
11967 workspace
11968 .update(&mut cx, |workspace, cx| {
11969 struct OpenPermalinkToLine;
11970
11971 workspace.show_toast(
11972 Toast::new(
11973 NotificationId::unique::<OpenPermalinkToLine>(),
11974 message,
11975 ),
11976 cx,
11977 )
11978 })
11979 .ok();
11980 }
11981 }
11982 }
11983 })
11984 .detach();
11985 }
11986
11987 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11988 /// last highlight added will be used.
11989 ///
11990 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11991 pub fn highlight_rows<T: 'static>(
11992 &mut self,
11993 range: Range<Anchor>,
11994 color: Hsla,
11995 should_autoscroll: bool,
11996 cx: &mut ViewContext<Self>,
11997 ) {
11998 let snapshot = self.buffer().read(cx).snapshot(cx);
11999 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12000 let ix = row_highlights.binary_search_by(|highlight| {
12001 Ordering::Equal
12002 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
12003 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
12004 });
12005
12006 if let Err(mut ix) = ix {
12007 let index = post_inc(&mut self.highlight_order);
12008
12009 // If this range intersects with the preceding highlight, then merge it with
12010 // the preceding highlight. Otherwise insert a new highlight.
12011 let mut merged = false;
12012 if ix > 0 {
12013 let prev_highlight = &mut row_highlights[ix - 1];
12014 if prev_highlight
12015 .range
12016 .end
12017 .cmp(&range.start, &snapshot)
12018 .is_ge()
12019 {
12020 ix -= 1;
12021 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12022 prev_highlight.range.end = range.end;
12023 }
12024 merged = true;
12025 prev_highlight.index = index;
12026 prev_highlight.color = color;
12027 prev_highlight.should_autoscroll = should_autoscroll;
12028 }
12029 }
12030
12031 if !merged {
12032 row_highlights.insert(
12033 ix,
12034 RowHighlight {
12035 range: range.clone(),
12036 index,
12037 color,
12038 should_autoscroll,
12039 },
12040 );
12041 }
12042
12043 // If any of the following highlights intersect with this one, merge them.
12044 while let Some(next_highlight) = row_highlights.get(ix + 1) {
12045 let highlight = &row_highlights[ix];
12046 if next_highlight
12047 .range
12048 .start
12049 .cmp(&highlight.range.end, &snapshot)
12050 .is_le()
12051 {
12052 if next_highlight
12053 .range
12054 .end
12055 .cmp(&highlight.range.end, &snapshot)
12056 .is_gt()
12057 {
12058 row_highlights[ix].range.end = next_highlight.range.end;
12059 }
12060 row_highlights.remove(ix + 1);
12061 } else {
12062 break;
12063 }
12064 }
12065 }
12066 }
12067
12068 /// Remove any highlighted row ranges of the given type that intersect the
12069 /// given ranges.
12070 pub fn remove_highlighted_rows<T: 'static>(
12071 &mut self,
12072 ranges_to_remove: Vec<Range<Anchor>>,
12073 cx: &mut ViewContext<Self>,
12074 ) {
12075 let snapshot = self.buffer().read(cx).snapshot(cx);
12076 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12077 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12078 row_highlights.retain(|highlight| {
12079 while let Some(range_to_remove) = ranges_to_remove.peek() {
12080 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12081 Ordering::Less | Ordering::Equal => {
12082 ranges_to_remove.next();
12083 }
12084 Ordering::Greater => {
12085 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12086 Ordering::Less | Ordering::Equal => {
12087 return false;
12088 }
12089 Ordering::Greater => break,
12090 }
12091 }
12092 }
12093 }
12094
12095 true
12096 })
12097 }
12098
12099 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12100 pub fn clear_row_highlights<T: 'static>(&mut self) {
12101 self.highlighted_rows.remove(&TypeId::of::<T>());
12102 }
12103
12104 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12105 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12106 self.highlighted_rows
12107 .get(&TypeId::of::<T>())
12108 .map_or(&[] as &[_], |vec| vec.as_slice())
12109 .iter()
12110 .map(|highlight| (highlight.range.clone(), highlight.color))
12111 }
12112
12113 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12114 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
12115 /// Allows to ignore certain kinds of highlights.
12116 pub fn highlighted_display_rows(
12117 &mut self,
12118 cx: &mut WindowContext,
12119 ) -> BTreeMap<DisplayRow, Hsla> {
12120 let snapshot = self.snapshot(cx);
12121 let mut used_highlight_orders = HashMap::default();
12122 self.highlighted_rows
12123 .iter()
12124 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12125 .fold(
12126 BTreeMap::<DisplayRow, Hsla>::new(),
12127 |mut unique_rows, highlight| {
12128 let start = highlight.range.start.to_display_point(&snapshot);
12129 let end = highlight.range.end.to_display_point(&snapshot);
12130 let start_row = start.row().0;
12131 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12132 && end.column() == 0
12133 {
12134 end.row().0.saturating_sub(1)
12135 } else {
12136 end.row().0
12137 };
12138 for row in start_row..=end_row {
12139 let used_index =
12140 used_highlight_orders.entry(row).or_insert(highlight.index);
12141 if highlight.index >= *used_index {
12142 *used_index = highlight.index;
12143 unique_rows.insert(DisplayRow(row), highlight.color);
12144 }
12145 }
12146 unique_rows
12147 },
12148 )
12149 }
12150
12151 pub fn highlighted_display_row_for_autoscroll(
12152 &self,
12153 snapshot: &DisplaySnapshot,
12154 ) -> Option<DisplayRow> {
12155 self.highlighted_rows
12156 .values()
12157 .flat_map(|highlighted_rows| highlighted_rows.iter())
12158 .filter_map(|highlight| {
12159 if highlight.should_autoscroll {
12160 Some(highlight.range.start.to_display_point(snapshot).row())
12161 } else {
12162 None
12163 }
12164 })
12165 .min()
12166 }
12167
12168 pub fn set_search_within_ranges(
12169 &mut self,
12170 ranges: &[Range<Anchor>],
12171 cx: &mut ViewContext<Self>,
12172 ) {
12173 self.highlight_background::<SearchWithinRange>(
12174 ranges,
12175 |colors| colors.editor_document_highlight_read_background,
12176 cx,
12177 )
12178 }
12179
12180 pub fn set_breadcrumb_header(&mut self, new_header: String) {
12181 self.breadcrumb_header = Some(new_header);
12182 }
12183
12184 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
12185 self.clear_background_highlights::<SearchWithinRange>(cx);
12186 }
12187
12188 pub fn highlight_background<T: 'static>(
12189 &mut self,
12190 ranges: &[Range<Anchor>],
12191 color_fetcher: fn(&ThemeColors) -> Hsla,
12192 cx: &mut ViewContext<Self>,
12193 ) {
12194 self.background_highlights
12195 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12196 self.scrollbar_marker_state.dirty = true;
12197 cx.notify();
12198 }
12199
12200 pub fn clear_background_highlights<T: 'static>(
12201 &mut self,
12202 cx: &mut ViewContext<Self>,
12203 ) -> Option<BackgroundHighlight> {
12204 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12205 if !text_highlights.1.is_empty() {
12206 self.scrollbar_marker_state.dirty = true;
12207 cx.notify();
12208 }
12209 Some(text_highlights)
12210 }
12211
12212 pub fn highlight_gutter<T: 'static>(
12213 &mut self,
12214 ranges: &[Range<Anchor>],
12215 color_fetcher: fn(&AppContext) -> Hsla,
12216 cx: &mut ViewContext<Self>,
12217 ) {
12218 self.gutter_highlights
12219 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12220 cx.notify();
12221 }
12222
12223 pub fn clear_gutter_highlights<T: 'static>(
12224 &mut self,
12225 cx: &mut ViewContext<Self>,
12226 ) -> Option<GutterHighlight> {
12227 cx.notify();
12228 self.gutter_highlights.remove(&TypeId::of::<T>())
12229 }
12230
12231 #[cfg(feature = "test-support")]
12232 pub fn all_text_background_highlights(
12233 &mut self,
12234 cx: &mut ViewContext<Self>,
12235 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12236 let snapshot = self.snapshot(cx);
12237 let buffer = &snapshot.buffer_snapshot;
12238 let start = buffer.anchor_before(0);
12239 let end = buffer.anchor_after(buffer.len());
12240 let theme = cx.theme().colors();
12241 self.background_highlights_in_range(start..end, &snapshot, theme)
12242 }
12243
12244 #[cfg(feature = "test-support")]
12245 pub fn search_background_highlights(
12246 &mut self,
12247 cx: &mut ViewContext<Self>,
12248 ) -> Vec<Range<Point>> {
12249 let snapshot = self.buffer().read(cx).snapshot(cx);
12250
12251 let highlights = self
12252 .background_highlights
12253 .get(&TypeId::of::<items::BufferSearchHighlights>());
12254
12255 if let Some((_color, ranges)) = highlights {
12256 ranges
12257 .iter()
12258 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12259 .collect_vec()
12260 } else {
12261 vec![]
12262 }
12263 }
12264
12265 fn document_highlights_for_position<'a>(
12266 &'a self,
12267 position: Anchor,
12268 buffer: &'a MultiBufferSnapshot,
12269 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12270 let read_highlights = self
12271 .background_highlights
12272 .get(&TypeId::of::<DocumentHighlightRead>())
12273 .map(|h| &h.1);
12274 let write_highlights = self
12275 .background_highlights
12276 .get(&TypeId::of::<DocumentHighlightWrite>())
12277 .map(|h| &h.1);
12278 let left_position = position.bias_left(buffer);
12279 let right_position = position.bias_right(buffer);
12280 read_highlights
12281 .into_iter()
12282 .chain(write_highlights)
12283 .flat_map(move |ranges| {
12284 let start_ix = match ranges.binary_search_by(|probe| {
12285 let cmp = probe.end.cmp(&left_position, buffer);
12286 if cmp.is_ge() {
12287 Ordering::Greater
12288 } else {
12289 Ordering::Less
12290 }
12291 }) {
12292 Ok(i) | Err(i) => i,
12293 };
12294
12295 ranges[start_ix..]
12296 .iter()
12297 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12298 })
12299 }
12300
12301 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12302 self.background_highlights
12303 .get(&TypeId::of::<T>())
12304 .map_or(false, |(_, highlights)| !highlights.is_empty())
12305 }
12306
12307 pub fn background_highlights_in_range(
12308 &self,
12309 search_range: Range<Anchor>,
12310 display_snapshot: &DisplaySnapshot,
12311 theme: &ThemeColors,
12312 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12313 let mut results = Vec::new();
12314 for (color_fetcher, ranges) in self.background_highlights.values() {
12315 let color = color_fetcher(theme);
12316 let start_ix = match ranges.binary_search_by(|probe| {
12317 let cmp = probe
12318 .end
12319 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12320 if cmp.is_gt() {
12321 Ordering::Greater
12322 } else {
12323 Ordering::Less
12324 }
12325 }) {
12326 Ok(i) | Err(i) => i,
12327 };
12328 for range in &ranges[start_ix..] {
12329 if range
12330 .start
12331 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12332 .is_ge()
12333 {
12334 break;
12335 }
12336
12337 let start = range.start.to_display_point(display_snapshot);
12338 let end = range.end.to_display_point(display_snapshot);
12339 results.push((start..end, color))
12340 }
12341 }
12342 results
12343 }
12344
12345 pub fn background_highlight_row_ranges<T: 'static>(
12346 &self,
12347 search_range: Range<Anchor>,
12348 display_snapshot: &DisplaySnapshot,
12349 count: usize,
12350 ) -> Vec<RangeInclusive<DisplayPoint>> {
12351 let mut results = Vec::new();
12352 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12353 return vec![];
12354 };
12355
12356 let start_ix = match ranges.binary_search_by(|probe| {
12357 let cmp = probe
12358 .end
12359 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12360 if cmp.is_gt() {
12361 Ordering::Greater
12362 } else {
12363 Ordering::Less
12364 }
12365 }) {
12366 Ok(i) | Err(i) => i,
12367 };
12368 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12369 if let (Some(start_display), Some(end_display)) = (start, end) {
12370 results.push(
12371 start_display.to_display_point(display_snapshot)
12372 ..=end_display.to_display_point(display_snapshot),
12373 );
12374 }
12375 };
12376 let mut start_row: Option<Point> = None;
12377 let mut end_row: Option<Point> = None;
12378 if ranges.len() > count {
12379 return Vec::new();
12380 }
12381 for range in &ranges[start_ix..] {
12382 if range
12383 .start
12384 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12385 .is_ge()
12386 {
12387 break;
12388 }
12389 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12390 if let Some(current_row) = &end_row {
12391 if end.row == current_row.row {
12392 continue;
12393 }
12394 }
12395 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12396 if start_row.is_none() {
12397 assert_eq!(end_row, None);
12398 start_row = Some(start);
12399 end_row = Some(end);
12400 continue;
12401 }
12402 if let Some(current_end) = end_row.as_mut() {
12403 if start.row > current_end.row + 1 {
12404 push_region(start_row, end_row);
12405 start_row = Some(start);
12406 end_row = Some(end);
12407 } else {
12408 // Merge two hunks.
12409 *current_end = end;
12410 }
12411 } else {
12412 unreachable!();
12413 }
12414 }
12415 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12416 push_region(start_row, end_row);
12417 results
12418 }
12419
12420 pub fn gutter_highlights_in_range(
12421 &self,
12422 search_range: Range<Anchor>,
12423 display_snapshot: &DisplaySnapshot,
12424 cx: &AppContext,
12425 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12426 let mut results = Vec::new();
12427 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12428 let color = color_fetcher(cx);
12429 let start_ix = match ranges.binary_search_by(|probe| {
12430 let cmp = probe
12431 .end
12432 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12433 if cmp.is_gt() {
12434 Ordering::Greater
12435 } else {
12436 Ordering::Less
12437 }
12438 }) {
12439 Ok(i) | Err(i) => i,
12440 };
12441 for range in &ranges[start_ix..] {
12442 if range
12443 .start
12444 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12445 .is_ge()
12446 {
12447 break;
12448 }
12449
12450 let start = range.start.to_display_point(display_snapshot);
12451 let end = range.end.to_display_point(display_snapshot);
12452 results.push((start..end, color))
12453 }
12454 }
12455 results
12456 }
12457
12458 /// Get the text ranges corresponding to the redaction query
12459 pub fn redacted_ranges(
12460 &self,
12461 search_range: Range<Anchor>,
12462 display_snapshot: &DisplaySnapshot,
12463 cx: &WindowContext,
12464 ) -> Vec<Range<DisplayPoint>> {
12465 display_snapshot
12466 .buffer_snapshot
12467 .redacted_ranges(search_range, |file| {
12468 if let Some(file) = file {
12469 file.is_private()
12470 && EditorSettings::get(
12471 Some(SettingsLocation {
12472 worktree_id: file.worktree_id(cx),
12473 path: file.path().as_ref(),
12474 }),
12475 cx,
12476 )
12477 .redact_private_values
12478 } else {
12479 false
12480 }
12481 })
12482 .map(|range| {
12483 range.start.to_display_point(display_snapshot)
12484 ..range.end.to_display_point(display_snapshot)
12485 })
12486 .collect()
12487 }
12488
12489 pub fn highlight_text<T: 'static>(
12490 &mut self,
12491 ranges: Vec<Range<Anchor>>,
12492 style: HighlightStyle,
12493 cx: &mut ViewContext<Self>,
12494 ) {
12495 self.display_map.update(cx, |map, _| {
12496 map.highlight_text(TypeId::of::<T>(), ranges, style)
12497 });
12498 cx.notify();
12499 }
12500
12501 pub(crate) fn highlight_inlays<T: 'static>(
12502 &mut self,
12503 highlights: Vec<InlayHighlight>,
12504 style: HighlightStyle,
12505 cx: &mut ViewContext<Self>,
12506 ) {
12507 self.display_map.update(cx, |map, _| {
12508 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12509 });
12510 cx.notify();
12511 }
12512
12513 pub fn text_highlights<'a, T: 'static>(
12514 &'a self,
12515 cx: &'a AppContext,
12516 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12517 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12518 }
12519
12520 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12521 let cleared = self
12522 .display_map
12523 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12524 if cleared {
12525 cx.notify();
12526 }
12527 }
12528
12529 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12530 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12531 && self.focus_handle.is_focused(cx)
12532 }
12533
12534 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12535 self.show_cursor_when_unfocused = is_enabled;
12536 cx.notify();
12537 }
12538
12539 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12540 cx.notify();
12541 }
12542
12543 fn on_buffer_event(
12544 &mut self,
12545 multibuffer: Model<MultiBuffer>,
12546 event: &multi_buffer::Event,
12547 cx: &mut ViewContext<Self>,
12548 ) {
12549 match event {
12550 multi_buffer::Event::Edited {
12551 singleton_buffer_edited,
12552 } => {
12553 self.scrollbar_marker_state.dirty = true;
12554 self.active_indent_guides_state.dirty = true;
12555 self.refresh_active_diagnostics(cx);
12556 self.refresh_code_actions(cx);
12557 if self.has_active_inline_completion(cx) {
12558 self.update_visible_inline_completion(cx);
12559 }
12560 cx.emit(EditorEvent::BufferEdited);
12561 cx.emit(SearchEvent::MatchesInvalidated);
12562 if *singleton_buffer_edited {
12563 if let Some(project) = &self.project {
12564 let project = project.read(cx);
12565 #[allow(clippy::mutable_key_type)]
12566 let languages_affected = multibuffer
12567 .read(cx)
12568 .all_buffers()
12569 .into_iter()
12570 .filter_map(|buffer| {
12571 let buffer = buffer.read(cx);
12572 let language = buffer.language()?;
12573 if project.is_local()
12574 && project.language_servers_for_buffer(buffer, cx).count() == 0
12575 {
12576 None
12577 } else {
12578 Some(language)
12579 }
12580 })
12581 .cloned()
12582 .collect::<HashSet<_>>();
12583 if !languages_affected.is_empty() {
12584 self.refresh_inlay_hints(
12585 InlayHintRefreshReason::BufferEdited(languages_affected),
12586 cx,
12587 );
12588 }
12589 }
12590 }
12591
12592 let Some(project) = &self.project else { return };
12593 let (telemetry, is_via_ssh) = {
12594 let project = project.read(cx);
12595 let telemetry = project.client().telemetry().clone();
12596 let is_via_ssh = project.is_via_ssh();
12597 (telemetry, is_via_ssh)
12598 };
12599 refresh_linked_ranges(self, cx);
12600 telemetry.log_edit_event("editor", is_via_ssh);
12601 }
12602 multi_buffer::Event::ExcerptsAdded {
12603 buffer,
12604 predecessor,
12605 excerpts,
12606 } => {
12607 self.tasks_update_task = Some(self.refresh_runnables(cx));
12608 cx.emit(EditorEvent::ExcerptsAdded {
12609 buffer: buffer.clone(),
12610 predecessor: *predecessor,
12611 excerpts: excerpts.clone(),
12612 });
12613 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12614 }
12615 multi_buffer::Event::ExcerptsRemoved { ids } => {
12616 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12617 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12618 }
12619 multi_buffer::Event::ExcerptsEdited { ids } => {
12620 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12621 }
12622 multi_buffer::Event::ExcerptsExpanded { ids } => {
12623 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12624 }
12625 multi_buffer::Event::Reparsed(buffer_id) => {
12626 self.tasks_update_task = Some(self.refresh_runnables(cx));
12627
12628 cx.emit(EditorEvent::Reparsed(*buffer_id));
12629 }
12630 multi_buffer::Event::LanguageChanged(buffer_id) => {
12631 linked_editing_ranges::refresh_linked_ranges(self, cx);
12632 cx.emit(EditorEvent::Reparsed(*buffer_id));
12633 cx.notify();
12634 }
12635 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12636 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12637 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12638 cx.emit(EditorEvent::TitleChanged)
12639 }
12640 multi_buffer::Event::DiffBaseChanged => {
12641 self.scrollbar_marker_state.dirty = true;
12642 cx.emit(EditorEvent::DiffBaseChanged);
12643 cx.notify();
12644 }
12645 multi_buffer::Event::DiffUpdated { buffer } => {
12646 self.sync_expanded_diff_hunks(buffer.clone(), cx);
12647 cx.notify();
12648 }
12649 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12650 multi_buffer::Event::DiagnosticsUpdated => {
12651 self.refresh_active_diagnostics(cx);
12652 self.scrollbar_marker_state.dirty = true;
12653 cx.notify();
12654 }
12655 _ => {}
12656 };
12657 }
12658
12659 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12660 cx.notify();
12661 }
12662
12663 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12664 self.tasks_update_task = Some(self.refresh_runnables(cx));
12665 self.refresh_inline_completion(true, false, cx);
12666 self.refresh_inlay_hints(
12667 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12668 self.selections.newest_anchor().head(),
12669 &self.buffer.read(cx).snapshot(cx),
12670 cx,
12671 )),
12672 cx,
12673 );
12674
12675 let old_cursor_shape = self.cursor_shape;
12676
12677 {
12678 let editor_settings = EditorSettings::get_global(cx);
12679 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12680 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12681 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12682 }
12683
12684 if old_cursor_shape != self.cursor_shape {
12685 cx.emit(EditorEvent::CursorShapeChanged);
12686 }
12687
12688 let project_settings = ProjectSettings::get_global(cx);
12689 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12690
12691 if self.mode == EditorMode::Full {
12692 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12693 if self.git_blame_inline_enabled != inline_blame_enabled {
12694 self.toggle_git_blame_inline_internal(false, cx);
12695 }
12696 }
12697
12698 cx.notify();
12699 }
12700
12701 pub fn set_searchable(&mut self, searchable: bool) {
12702 self.searchable = searchable;
12703 }
12704
12705 pub fn searchable(&self) -> bool {
12706 self.searchable
12707 }
12708
12709 fn open_proposed_changes_editor(
12710 &mut self,
12711 _: &OpenProposedChangesEditor,
12712 cx: &mut ViewContext<Self>,
12713 ) {
12714 let Some(workspace) = self.workspace() else {
12715 cx.propagate();
12716 return;
12717 };
12718
12719 let selections = self.selections.all::<usize>(cx);
12720 let buffer = self.buffer.read(cx);
12721 let mut new_selections_by_buffer = HashMap::default();
12722 for selection in selections {
12723 for (buffer, range, _) in
12724 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12725 {
12726 let mut range = range.to_point(buffer.read(cx));
12727 range.start.column = 0;
12728 range.end.column = buffer.read(cx).line_len(range.end.row);
12729 new_selections_by_buffer
12730 .entry(buffer)
12731 .or_insert(Vec::new())
12732 .push(range)
12733 }
12734 }
12735
12736 let proposed_changes_buffers = new_selections_by_buffer
12737 .into_iter()
12738 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12739 .collect::<Vec<_>>();
12740 let proposed_changes_editor = cx.new_view(|cx| {
12741 ProposedChangesEditor::new(
12742 "Proposed changes",
12743 proposed_changes_buffers,
12744 self.project.clone(),
12745 cx,
12746 )
12747 });
12748
12749 cx.window_context().defer(move |cx| {
12750 workspace.update(cx, |workspace, cx| {
12751 workspace.active_pane().update(cx, |pane, cx| {
12752 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12753 });
12754 });
12755 });
12756 }
12757
12758 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12759 self.open_excerpts_common(None, true, cx)
12760 }
12761
12762 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12763 self.open_excerpts_common(None, false, cx)
12764 }
12765
12766 fn open_excerpts_common(
12767 &mut self,
12768 jump_data: Option<JumpData>,
12769 split: bool,
12770 cx: &mut ViewContext<Self>,
12771 ) {
12772 let Some(workspace) = self.workspace() else {
12773 cx.propagate();
12774 return;
12775 };
12776
12777 if self.buffer.read(cx).is_singleton() {
12778 cx.propagate();
12779 return;
12780 }
12781
12782 let mut new_selections_by_buffer = HashMap::default();
12783 match &jump_data {
12784 Some(jump_data) => {
12785 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12786 if let Some(buffer) = multi_buffer_snapshot
12787 .buffer_id_for_excerpt(jump_data.excerpt_id)
12788 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12789 {
12790 let buffer_snapshot = buffer.read(cx).snapshot();
12791 let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12792 language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12793 } else {
12794 buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12795 };
12796 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12797 new_selections_by_buffer.insert(
12798 buffer,
12799 (
12800 vec![jump_to_offset..jump_to_offset],
12801 Some(jump_data.line_offset_from_top),
12802 ),
12803 );
12804 }
12805 }
12806 None => {
12807 let selections = self.selections.all::<usize>(cx);
12808 let buffer = self.buffer.read(cx);
12809 for selection in selections {
12810 for (mut buffer_handle, mut range, _) in
12811 buffer.range_to_buffer_ranges(selection.range(), cx)
12812 {
12813 // When editing branch buffers, jump to the corresponding location
12814 // in their base buffer.
12815 let buffer = buffer_handle.read(cx);
12816 if let Some(base_buffer) = buffer.diff_base_buffer() {
12817 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12818 buffer_handle = base_buffer;
12819 }
12820
12821 if selection.reversed {
12822 mem::swap(&mut range.start, &mut range.end);
12823 }
12824 new_selections_by_buffer
12825 .entry(buffer_handle)
12826 .or_insert((Vec::new(), None))
12827 .0
12828 .push(range)
12829 }
12830 }
12831 }
12832 }
12833
12834 if new_selections_by_buffer.is_empty() {
12835 return;
12836 }
12837
12838 // We defer the pane interaction because we ourselves are a workspace item
12839 // and activating a new item causes the pane to call a method on us reentrantly,
12840 // which panics if we're on the stack.
12841 cx.window_context().defer(move |cx| {
12842 workspace.update(cx, |workspace, cx| {
12843 let pane = if split {
12844 workspace.adjacent_pane(cx)
12845 } else {
12846 workspace.active_pane().clone()
12847 };
12848
12849 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12850 let editor =
12851 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12852 editor.update(cx, |editor, cx| {
12853 let autoscroll = match scroll_offset {
12854 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12855 None => Autoscroll::newest(),
12856 };
12857 let nav_history = editor.nav_history.take();
12858 editor.change_selections(Some(autoscroll), cx, |s| {
12859 s.select_ranges(ranges);
12860 });
12861 editor.nav_history = nav_history;
12862 });
12863 }
12864 })
12865 });
12866 }
12867
12868 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12869 let snapshot = self.buffer.read(cx).read(cx);
12870 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12871 Some(
12872 ranges
12873 .iter()
12874 .map(move |range| {
12875 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12876 })
12877 .collect(),
12878 )
12879 }
12880
12881 fn selection_replacement_ranges(
12882 &self,
12883 range: Range<OffsetUtf16>,
12884 cx: &mut AppContext,
12885 ) -> Vec<Range<OffsetUtf16>> {
12886 let selections = self.selections.all::<OffsetUtf16>(cx);
12887 let newest_selection = selections
12888 .iter()
12889 .max_by_key(|selection| selection.id)
12890 .unwrap();
12891 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12892 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12893 let snapshot = self.buffer.read(cx).read(cx);
12894 selections
12895 .into_iter()
12896 .map(|mut selection| {
12897 selection.start.0 =
12898 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12899 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12900 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12901 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12902 })
12903 .collect()
12904 }
12905
12906 fn report_editor_event(
12907 &self,
12908 operation: &'static str,
12909 file_extension: Option<String>,
12910 cx: &AppContext,
12911 ) {
12912 if cfg!(any(test, feature = "test-support")) {
12913 return;
12914 }
12915
12916 let Some(project) = &self.project else { return };
12917
12918 // If None, we are in a file without an extension
12919 let file = self
12920 .buffer
12921 .read(cx)
12922 .as_singleton()
12923 .and_then(|b| b.read(cx).file());
12924 let file_extension = file_extension.or(file
12925 .as_ref()
12926 .and_then(|file| Path::new(file.file_name(cx)).extension())
12927 .and_then(|e| e.to_str())
12928 .map(|a| a.to_string()));
12929
12930 let vim_mode = cx
12931 .global::<SettingsStore>()
12932 .raw_user_settings()
12933 .get("vim_mode")
12934 == Some(&serde_json::Value::Bool(true));
12935
12936 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12937 == language::language_settings::InlineCompletionProvider::Copilot;
12938 let copilot_enabled_for_language = self
12939 .buffer
12940 .read(cx)
12941 .settings_at(0, cx)
12942 .show_inline_completions;
12943
12944 let project = project.read(cx);
12945 let telemetry = project.client().telemetry().clone();
12946 telemetry.report_editor_event(
12947 file_extension,
12948 vim_mode,
12949 operation,
12950 copilot_enabled,
12951 copilot_enabled_for_language,
12952 project.is_via_ssh(),
12953 )
12954 }
12955
12956 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12957 /// with each line being an array of {text, highlight} objects.
12958 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12959 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12960 return;
12961 };
12962
12963 #[derive(Serialize)]
12964 struct Chunk<'a> {
12965 text: String,
12966 highlight: Option<&'a str>,
12967 }
12968
12969 let snapshot = buffer.read(cx).snapshot();
12970 let range = self
12971 .selected_text_range(false, cx)
12972 .and_then(|selection| {
12973 if selection.range.is_empty() {
12974 None
12975 } else {
12976 Some(selection.range)
12977 }
12978 })
12979 .unwrap_or_else(|| 0..snapshot.len());
12980
12981 let chunks = snapshot.chunks(range, true);
12982 let mut lines = Vec::new();
12983 let mut line: VecDeque<Chunk> = VecDeque::new();
12984
12985 let Some(style) = self.style.as_ref() else {
12986 return;
12987 };
12988
12989 for chunk in chunks {
12990 let highlight = chunk
12991 .syntax_highlight_id
12992 .and_then(|id| id.name(&style.syntax));
12993 let mut chunk_lines = chunk.text.split('\n').peekable();
12994 while let Some(text) = chunk_lines.next() {
12995 let mut merged_with_last_token = false;
12996 if let Some(last_token) = line.back_mut() {
12997 if last_token.highlight == highlight {
12998 last_token.text.push_str(text);
12999 merged_with_last_token = true;
13000 }
13001 }
13002
13003 if !merged_with_last_token {
13004 line.push_back(Chunk {
13005 text: text.into(),
13006 highlight,
13007 });
13008 }
13009
13010 if chunk_lines.peek().is_some() {
13011 if line.len() > 1 && line.front().unwrap().text.is_empty() {
13012 line.pop_front();
13013 }
13014 if line.len() > 1 && line.back().unwrap().text.is_empty() {
13015 line.pop_back();
13016 }
13017
13018 lines.push(mem::take(&mut line));
13019 }
13020 }
13021 }
13022
13023 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13024 return;
13025 };
13026 cx.write_to_clipboard(ClipboardItem::new_string(lines));
13027 }
13028
13029 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13030 &self.inlay_hint_cache
13031 }
13032
13033 pub fn replay_insert_event(
13034 &mut self,
13035 text: &str,
13036 relative_utf16_range: Option<Range<isize>>,
13037 cx: &mut ViewContext<Self>,
13038 ) {
13039 if !self.input_enabled {
13040 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13041 return;
13042 }
13043 if let Some(relative_utf16_range) = relative_utf16_range {
13044 let selections = self.selections.all::<OffsetUtf16>(cx);
13045 self.change_selections(None, cx, |s| {
13046 let new_ranges = selections.into_iter().map(|range| {
13047 let start = OffsetUtf16(
13048 range
13049 .head()
13050 .0
13051 .saturating_add_signed(relative_utf16_range.start),
13052 );
13053 let end = OffsetUtf16(
13054 range
13055 .head()
13056 .0
13057 .saturating_add_signed(relative_utf16_range.end),
13058 );
13059 start..end
13060 });
13061 s.select_ranges(new_ranges);
13062 });
13063 }
13064
13065 self.handle_input(text, cx);
13066 }
13067
13068 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
13069 let Some(provider) = self.semantics_provider.as_ref() else {
13070 return false;
13071 };
13072
13073 let mut supports = false;
13074 self.buffer().read(cx).for_each_buffer(|buffer| {
13075 supports |= provider.supports_inlay_hints(buffer, cx);
13076 });
13077 supports
13078 }
13079
13080 pub fn focus(&self, cx: &mut WindowContext) {
13081 cx.focus(&self.focus_handle)
13082 }
13083
13084 pub fn is_focused(&self, cx: &WindowContext) -> bool {
13085 self.focus_handle.is_focused(cx)
13086 }
13087
13088 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
13089 cx.emit(EditorEvent::Focused);
13090
13091 if let Some(descendant) = self
13092 .last_focused_descendant
13093 .take()
13094 .and_then(|descendant| descendant.upgrade())
13095 {
13096 cx.focus(&descendant);
13097 } else {
13098 if let Some(blame) = self.blame.as_ref() {
13099 blame.update(cx, GitBlame::focus)
13100 }
13101
13102 self.blink_manager.update(cx, BlinkManager::enable);
13103 self.show_cursor_names(cx);
13104 self.buffer.update(cx, |buffer, cx| {
13105 buffer.finalize_last_transaction(cx);
13106 if self.leader_peer_id.is_none() {
13107 buffer.set_active_selections(
13108 &self.selections.disjoint_anchors(),
13109 self.selections.line_mode,
13110 self.cursor_shape,
13111 cx,
13112 );
13113 }
13114 });
13115 }
13116 }
13117
13118 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13119 cx.emit(EditorEvent::FocusedIn)
13120 }
13121
13122 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13123 if event.blurred != self.focus_handle {
13124 self.last_focused_descendant = Some(event.blurred);
13125 }
13126 }
13127
13128 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13129 self.blink_manager.update(cx, BlinkManager::disable);
13130 self.buffer
13131 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13132
13133 if let Some(blame) = self.blame.as_ref() {
13134 blame.update(cx, GitBlame::blur)
13135 }
13136 if !self.hover_state.focused(cx) {
13137 hide_hover(self, cx);
13138 }
13139
13140 self.hide_context_menu(cx);
13141 cx.emit(EditorEvent::Blurred);
13142 cx.notify();
13143 }
13144
13145 pub fn register_action<A: Action>(
13146 &mut self,
13147 listener: impl Fn(&A, &mut WindowContext) + 'static,
13148 ) -> Subscription {
13149 let id = self.next_editor_action_id.post_inc();
13150 let listener = Arc::new(listener);
13151 self.editor_actions.borrow_mut().insert(
13152 id,
13153 Box::new(move |cx| {
13154 let cx = cx.window_context();
13155 let listener = listener.clone();
13156 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13157 let action = action.downcast_ref().unwrap();
13158 if phase == DispatchPhase::Bubble {
13159 listener(action, cx)
13160 }
13161 })
13162 }),
13163 );
13164
13165 let editor_actions = self.editor_actions.clone();
13166 Subscription::new(move || {
13167 editor_actions.borrow_mut().remove(&id);
13168 })
13169 }
13170
13171 pub fn file_header_size(&self) -> u32 {
13172 FILE_HEADER_HEIGHT
13173 }
13174
13175 pub fn revert(
13176 &mut self,
13177 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13178 cx: &mut ViewContext<Self>,
13179 ) {
13180 self.buffer().update(cx, |multi_buffer, cx| {
13181 for (buffer_id, changes) in revert_changes {
13182 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13183 buffer.update(cx, |buffer, cx| {
13184 buffer.edit(
13185 changes.into_iter().map(|(range, text)| {
13186 (range, text.to_string().map(Arc::<str>::from))
13187 }),
13188 None,
13189 cx,
13190 );
13191 });
13192 }
13193 }
13194 });
13195 self.change_selections(None, cx, |selections| selections.refresh());
13196 }
13197
13198 pub fn to_pixel_point(
13199 &mut self,
13200 source: multi_buffer::Anchor,
13201 editor_snapshot: &EditorSnapshot,
13202 cx: &mut ViewContext<Self>,
13203 ) -> Option<gpui::Point<Pixels>> {
13204 let source_point = source.to_display_point(editor_snapshot);
13205 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13206 }
13207
13208 pub fn display_to_pixel_point(
13209 &mut self,
13210 source: DisplayPoint,
13211 editor_snapshot: &EditorSnapshot,
13212 cx: &mut ViewContext<Self>,
13213 ) -> Option<gpui::Point<Pixels>> {
13214 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13215 let text_layout_details = self.text_layout_details(cx);
13216 let scroll_top = text_layout_details
13217 .scroll_anchor
13218 .scroll_position(editor_snapshot)
13219 .y;
13220
13221 if source.row().as_f32() < scroll_top.floor() {
13222 return None;
13223 }
13224 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13225 let source_y = line_height * (source.row().as_f32() - scroll_top);
13226 Some(gpui::Point::new(source_x, source_y))
13227 }
13228
13229 pub fn has_active_completions_menu(&self) -> bool {
13230 self.context_menu.read().as_ref().map_or(false, |menu| {
13231 menu.visible() && matches!(menu, ContextMenu::Completions(_))
13232 })
13233 }
13234
13235 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13236 self.addons
13237 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13238 }
13239
13240 pub fn unregister_addon<T: Addon>(&mut self) {
13241 self.addons.remove(&std::any::TypeId::of::<T>());
13242 }
13243
13244 pub fn addon<T: Addon>(&self) -> Option<&T> {
13245 let type_id = std::any::TypeId::of::<T>();
13246 self.addons
13247 .get(&type_id)
13248 .and_then(|item| item.to_any().downcast_ref::<T>())
13249 }
13250}
13251
13252fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13253 let tab_size = tab_size.get() as usize;
13254 let mut width = offset;
13255
13256 for ch in text.chars() {
13257 width += if ch == '\t' {
13258 tab_size - (width % tab_size)
13259 } else {
13260 1
13261 };
13262 }
13263
13264 width - offset
13265}
13266
13267#[cfg(test)]
13268mod tests {
13269 use super::*;
13270
13271 #[test]
13272 fn test_string_size_with_expanded_tabs() {
13273 let nz = |val| NonZeroU32::new(val).unwrap();
13274 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13275 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13276 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13277 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13278 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13279 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13280 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13281 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13282 }
13283}
13284
13285/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13286struct WordBreakingTokenizer<'a> {
13287 input: &'a str,
13288}
13289
13290impl<'a> WordBreakingTokenizer<'a> {
13291 fn new(input: &'a str) -> Self {
13292 Self { input }
13293 }
13294}
13295
13296fn is_char_ideographic(ch: char) -> bool {
13297 use unicode_script::Script::*;
13298 use unicode_script::UnicodeScript;
13299 matches!(ch.script(), Han | Tangut | Yi)
13300}
13301
13302fn is_grapheme_ideographic(text: &str) -> bool {
13303 text.chars().any(is_char_ideographic)
13304}
13305
13306fn is_grapheme_whitespace(text: &str) -> bool {
13307 text.chars().any(|x| x.is_whitespace())
13308}
13309
13310fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13311 text.chars().next().map_or(false, |ch| {
13312 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13313 })
13314}
13315
13316#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13317struct WordBreakToken<'a> {
13318 token: &'a str,
13319 grapheme_len: usize,
13320 is_whitespace: bool,
13321}
13322
13323impl<'a> Iterator for WordBreakingTokenizer<'a> {
13324 /// Yields a span, the count of graphemes in the token, and whether it was
13325 /// whitespace. Note that it also breaks at word boundaries.
13326 type Item = WordBreakToken<'a>;
13327
13328 fn next(&mut self) -> Option<Self::Item> {
13329 use unicode_segmentation::UnicodeSegmentation;
13330 if self.input.is_empty() {
13331 return None;
13332 }
13333
13334 let mut iter = self.input.graphemes(true).peekable();
13335 let mut offset = 0;
13336 let mut graphemes = 0;
13337 if let Some(first_grapheme) = iter.next() {
13338 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13339 offset += first_grapheme.len();
13340 graphemes += 1;
13341 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13342 if let Some(grapheme) = iter.peek().copied() {
13343 if should_stay_with_preceding_ideograph(grapheme) {
13344 offset += grapheme.len();
13345 graphemes += 1;
13346 }
13347 }
13348 } else {
13349 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13350 let mut next_word_bound = words.peek().copied();
13351 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13352 next_word_bound = words.next();
13353 }
13354 while let Some(grapheme) = iter.peek().copied() {
13355 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13356 break;
13357 };
13358 if is_grapheme_whitespace(grapheme) != is_whitespace {
13359 break;
13360 };
13361 offset += grapheme.len();
13362 graphemes += 1;
13363 iter.next();
13364 }
13365 }
13366 let token = &self.input[..offset];
13367 self.input = &self.input[offset..];
13368 if is_whitespace {
13369 Some(WordBreakToken {
13370 token: " ",
13371 grapheme_len: 1,
13372 is_whitespace: true,
13373 })
13374 } else {
13375 Some(WordBreakToken {
13376 token,
13377 grapheme_len: graphemes,
13378 is_whitespace: false,
13379 })
13380 }
13381 } else {
13382 None
13383 }
13384 }
13385}
13386
13387#[test]
13388fn test_word_breaking_tokenizer() {
13389 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13390 ("", &[]),
13391 (" ", &[(" ", 1, true)]),
13392 ("Ʒ", &[("Ʒ", 1, false)]),
13393 ("Ǽ", &[("Ǽ", 1, false)]),
13394 ("⋑", &[("⋑", 1, false)]),
13395 ("⋑⋑", &[("⋑⋑", 2, false)]),
13396 (
13397 "原理,进而",
13398 &[
13399 ("原", 1, false),
13400 ("理,", 2, false),
13401 ("进", 1, false),
13402 ("而", 1, false),
13403 ],
13404 ),
13405 (
13406 "hello world",
13407 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13408 ),
13409 (
13410 "hello, world",
13411 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13412 ),
13413 (
13414 " hello world",
13415 &[
13416 (" ", 1, true),
13417 ("hello", 5, false),
13418 (" ", 1, true),
13419 ("world", 5, false),
13420 ],
13421 ),
13422 (
13423 "这是什么 \n 钢笔",
13424 &[
13425 ("这", 1, false),
13426 ("是", 1, false),
13427 ("什", 1, false),
13428 ("么", 1, false),
13429 (" ", 1, true),
13430 ("钢", 1, false),
13431 ("笔", 1, false),
13432 ],
13433 ),
13434 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13435 ];
13436
13437 for (input, result) in tests {
13438 assert_eq!(
13439 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13440 result
13441 .iter()
13442 .copied()
13443 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13444 token,
13445 grapheme_len,
13446 is_whitespace,
13447 })
13448 .collect::<Vec<_>>()
13449 );
13450 }
13451}
13452
13453fn wrap_with_prefix(
13454 line_prefix: String,
13455 unwrapped_text: String,
13456 wrap_column: usize,
13457 tab_size: NonZeroU32,
13458) -> String {
13459 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13460 let mut wrapped_text = String::new();
13461 let mut current_line = line_prefix.clone();
13462
13463 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13464 let mut current_line_len = line_prefix_len;
13465 for WordBreakToken {
13466 token,
13467 grapheme_len,
13468 is_whitespace,
13469 } in tokenizer
13470 {
13471 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13472 wrapped_text.push_str(current_line.trim_end());
13473 wrapped_text.push('\n');
13474 current_line.truncate(line_prefix.len());
13475 current_line_len = line_prefix_len;
13476 if !is_whitespace {
13477 current_line.push_str(token);
13478 current_line_len += grapheme_len;
13479 }
13480 } else if !is_whitespace {
13481 current_line.push_str(token);
13482 current_line_len += grapheme_len;
13483 } else if current_line_len != line_prefix_len {
13484 current_line.push(' ');
13485 current_line_len += 1;
13486 }
13487 }
13488
13489 if !current_line.is_empty() {
13490 wrapped_text.push_str(¤t_line);
13491 }
13492 wrapped_text
13493}
13494
13495#[test]
13496fn test_wrap_with_prefix() {
13497 assert_eq!(
13498 wrap_with_prefix(
13499 "# ".to_string(),
13500 "abcdefg".to_string(),
13501 4,
13502 NonZeroU32::new(4).unwrap()
13503 ),
13504 "# abcdefg"
13505 );
13506 assert_eq!(
13507 wrap_with_prefix(
13508 "".to_string(),
13509 "\thello world".to_string(),
13510 8,
13511 NonZeroU32::new(4).unwrap()
13512 ),
13513 "hello\nworld"
13514 );
13515 assert_eq!(
13516 wrap_with_prefix(
13517 "// ".to_string(),
13518 "xx \nyy zz aa bb cc".to_string(),
13519 12,
13520 NonZeroU32::new(4).unwrap()
13521 ),
13522 "// xx yy zz\n// aa bb cc"
13523 );
13524 assert_eq!(
13525 wrap_with_prefix(
13526 String::new(),
13527 "这是什么 \n 钢笔".to_string(),
13528 3,
13529 NonZeroU32::new(4).unwrap()
13530 ),
13531 "这是什\n么 钢\n笔"
13532 );
13533}
13534
13535fn hunks_for_selections(
13536 multi_buffer_snapshot: &MultiBufferSnapshot,
13537 selections: &[Selection<Anchor>],
13538) -> Vec<MultiBufferDiffHunk> {
13539 let buffer_rows_for_selections = selections.iter().map(|selection| {
13540 let head = selection.head();
13541 let tail = selection.tail();
13542 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
13543 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
13544 if start > end {
13545 end..start
13546 } else {
13547 start..end
13548 }
13549 });
13550
13551 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
13552}
13553
13554pub fn hunks_for_rows(
13555 rows: impl Iterator<Item = Range<MultiBufferRow>>,
13556 multi_buffer_snapshot: &MultiBufferSnapshot,
13557) -> Vec<MultiBufferDiffHunk> {
13558 let mut hunks = Vec::new();
13559 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13560 HashMap::default();
13561 for selected_multi_buffer_rows in rows {
13562 let query_rows =
13563 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
13564 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
13565 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13566 // when the caret is just above or just below the deleted hunk.
13567 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13568 let related_to_selection = if allow_adjacent {
13569 hunk.row_range.overlaps(&query_rows)
13570 || hunk.row_range.start == query_rows.end
13571 || hunk.row_range.end == query_rows.start
13572 } else {
13573 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
13574 // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
13575 hunk.row_range.overlaps(&selected_multi_buffer_rows)
13576 || selected_multi_buffer_rows.end == hunk.row_range.start
13577 };
13578 if related_to_selection {
13579 if !processed_buffer_rows
13580 .entry(hunk.buffer_id)
13581 .or_default()
13582 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13583 {
13584 continue;
13585 }
13586 hunks.push(hunk);
13587 }
13588 }
13589 }
13590
13591 hunks
13592}
13593
13594pub trait CollaborationHub {
13595 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13596 fn user_participant_indices<'a>(
13597 &self,
13598 cx: &'a AppContext,
13599 ) -> &'a HashMap<u64, ParticipantIndex>;
13600 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13601}
13602
13603impl CollaborationHub for Model<Project> {
13604 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13605 self.read(cx).collaborators()
13606 }
13607
13608 fn user_participant_indices<'a>(
13609 &self,
13610 cx: &'a AppContext,
13611 ) -> &'a HashMap<u64, ParticipantIndex> {
13612 self.read(cx).user_store().read(cx).participant_indices()
13613 }
13614
13615 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13616 let this = self.read(cx);
13617 let user_ids = this.collaborators().values().map(|c| c.user_id);
13618 this.user_store().read_with(cx, |user_store, cx| {
13619 user_store.participant_names(user_ids, cx)
13620 })
13621 }
13622}
13623
13624pub trait SemanticsProvider {
13625 fn hover(
13626 &self,
13627 buffer: &Model<Buffer>,
13628 position: text::Anchor,
13629 cx: &mut AppContext,
13630 ) -> Option<Task<Vec<project::Hover>>>;
13631
13632 fn inlay_hints(
13633 &self,
13634 buffer_handle: Model<Buffer>,
13635 range: Range<text::Anchor>,
13636 cx: &mut AppContext,
13637 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13638
13639 fn resolve_inlay_hint(
13640 &self,
13641 hint: InlayHint,
13642 buffer_handle: Model<Buffer>,
13643 server_id: LanguageServerId,
13644 cx: &mut AppContext,
13645 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13646
13647 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13648
13649 fn document_highlights(
13650 &self,
13651 buffer: &Model<Buffer>,
13652 position: text::Anchor,
13653 cx: &mut AppContext,
13654 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13655
13656 fn definitions(
13657 &self,
13658 buffer: &Model<Buffer>,
13659 position: text::Anchor,
13660 kind: GotoDefinitionKind,
13661 cx: &mut AppContext,
13662 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13663
13664 fn range_for_rename(
13665 &self,
13666 buffer: &Model<Buffer>,
13667 position: text::Anchor,
13668 cx: &mut AppContext,
13669 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13670
13671 fn perform_rename(
13672 &self,
13673 buffer: &Model<Buffer>,
13674 position: text::Anchor,
13675 new_name: String,
13676 cx: &mut AppContext,
13677 ) -> Option<Task<Result<ProjectTransaction>>>;
13678}
13679
13680pub trait CompletionProvider {
13681 fn completions(
13682 &self,
13683 buffer: &Model<Buffer>,
13684 buffer_position: text::Anchor,
13685 trigger: CompletionContext,
13686 cx: &mut ViewContext<Editor>,
13687 ) -> Task<Result<Vec<Completion>>>;
13688
13689 fn resolve_completions(
13690 &self,
13691 buffer: Model<Buffer>,
13692 completion_indices: Vec<usize>,
13693 completions: Arc<RwLock<Box<[Completion]>>>,
13694 cx: &mut ViewContext<Editor>,
13695 ) -> Task<Result<bool>>;
13696
13697 fn apply_additional_edits_for_completion(
13698 &self,
13699 buffer: Model<Buffer>,
13700 completion: Completion,
13701 push_to_history: bool,
13702 cx: &mut ViewContext<Editor>,
13703 ) -> Task<Result<Option<language::Transaction>>>;
13704
13705 fn is_completion_trigger(
13706 &self,
13707 buffer: &Model<Buffer>,
13708 position: language::Anchor,
13709 text: &str,
13710 trigger_in_words: bool,
13711 cx: &mut ViewContext<Editor>,
13712 ) -> bool;
13713
13714 fn sort_completions(&self) -> bool {
13715 true
13716 }
13717}
13718
13719pub trait CodeActionProvider {
13720 fn code_actions(
13721 &self,
13722 buffer: &Model<Buffer>,
13723 range: Range<text::Anchor>,
13724 cx: &mut WindowContext,
13725 ) -> Task<Result<Vec<CodeAction>>>;
13726
13727 fn apply_code_action(
13728 &self,
13729 buffer_handle: Model<Buffer>,
13730 action: CodeAction,
13731 excerpt_id: ExcerptId,
13732 push_to_history: bool,
13733 cx: &mut WindowContext,
13734 ) -> Task<Result<ProjectTransaction>>;
13735}
13736
13737impl CodeActionProvider for Model<Project> {
13738 fn code_actions(
13739 &self,
13740 buffer: &Model<Buffer>,
13741 range: Range<text::Anchor>,
13742 cx: &mut WindowContext,
13743 ) -> Task<Result<Vec<CodeAction>>> {
13744 self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13745 }
13746
13747 fn apply_code_action(
13748 &self,
13749 buffer_handle: Model<Buffer>,
13750 action: CodeAction,
13751 _excerpt_id: ExcerptId,
13752 push_to_history: bool,
13753 cx: &mut WindowContext,
13754 ) -> Task<Result<ProjectTransaction>> {
13755 self.update(cx, |project, cx| {
13756 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13757 })
13758 }
13759}
13760
13761fn snippet_completions(
13762 project: &Project,
13763 buffer: &Model<Buffer>,
13764 buffer_position: text::Anchor,
13765 cx: &mut AppContext,
13766) -> Vec<Completion> {
13767 let language = buffer.read(cx).language_at(buffer_position);
13768 let language_name = language.as_ref().map(|language| language.lsp_id());
13769 let snippet_store = project.snippets().read(cx);
13770 let snippets = snippet_store.snippets_for(language_name, cx);
13771
13772 if snippets.is_empty() {
13773 return vec![];
13774 }
13775 let snapshot = buffer.read(cx).text_snapshot();
13776 let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13777
13778 let scope = language.map(|language| language.default_scope());
13779 let classifier = CharClassifier::new(scope).for_completion(true);
13780 let mut last_word = chars
13781 .take_while(|c| classifier.is_word(*c))
13782 .collect::<String>();
13783 last_word = last_word.chars().rev().collect();
13784 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13785 let to_lsp = |point: &text::Anchor| {
13786 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13787 point_to_lsp(end)
13788 };
13789 let lsp_end = to_lsp(&buffer_position);
13790 snippets
13791 .into_iter()
13792 .filter_map(|snippet| {
13793 let matching_prefix = snippet
13794 .prefix
13795 .iter()
13796 .find(|prefix| prefix.starts_with(&last_word))?;
13797 let start = as_offset - last_word.len();
13798 let start = snapshot.anchor_before(start);
13799 let range = start..buffer_position;
13800 let lsp_start = to_lsp(&start);
13801 let lsp_range = lsp::Range {
13802 start: lsp_start,
13803 end: lsp_end,
13804 };
13805 Some(Completion {
13806 old_range: range,
13807 new_text: snippet.body.clone(),
13808 label: CodeLabel {
13809 text: matching_prefix.clone(),
13810 runs: vec![],
13811 filter_range: 0..matching_prefix.len(),
13812 },
13813 server_id: LanguageServerId(usize::MAX),
13814 documentation: snippet.description.clone().map(Documentation::SingleLine),
13815 lsp_completion: lsp::CompletionItem {
13816 label: snippet.prefix.first().unwrap().clone(),
13817 kind: Some(CompletionItemKind::SNIPPET),
13818 label_details: snippet.description.as_ref().map(|description| {
13819 lsp::CompletionItemLabelDetails {
13820 detail: Some(description.clone()),
13821 description: None,
13822 }
13823 }),
13824 insert_text_format: Some(InsertTextFormat::SNIPPET),
13825 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13826 lsp::InsertReplaceEdit {
13827 new_text: snippet.body.clone(),
13828 insert: lsp_range,
13829 replace: lsp_range,
13830 },
13831 )),
13832 filter_text: Some(snippet.body.clone()),
13833 sort_text: Some(char::MAX.to_string()),
13834 ..Default::default()
13835 },
13836 confirm: None,
13837 })
13838 })
13839 .collect()
13840}
13841
13842impl CompletionProvider for Model<Project> {
13843 fn completions(
13844 &self,
13845 buffer: &Model<Buffer>,
13846 buffer_position: text::Anchor,
13847 options: CompletionContext,
13848 cx: &mut ViewContext<Editor>,
13849 ) -> Task<Result<Vec<Completion>>> {
13850 self.update(cx, |project, cx| {
13851 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13852 let project_completions = project.completions(buffer, buffer_position, options, cx);
13853 cx.background_executor().spawn(async move {
13854 let mut completions = project_completions.await?;
13855 //let snippets = snippets.into_iter().;
13856 completions.extend(snippets);
13857 Ok(completions)
13858 })
13859 })
13860 }
13861
13862 fn resolve_completions(
13863 &self,
13864 buffer: Model<Buffer>,
13865 completion_indices: Vec<usize>,
13866 completions: Arc<RwLock<Box<[Completion]>>>,
13867 cx: &mut ViewContext<Editor>,
13868 ) -> Task<Result<bool>> {
13869 self.update(cx, |project, cx| {
13870 project.resolve_completions(buffer, completion_indices, completions, cx)
13871 })
13872 }
13873
13874 fn apply_additional_edits_for_completion(
13875 &self,
13876 buffer: Model<Buffer>,
13877 completion: Completion,
13878 push_to_history: bool,
13879 cx: &mut ViewContext<Editor>,
13880 ) -> Task<Result<Option<language::Transaction>>> {
13881 self.update(cx, |project, cx| {
13882 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13883 })
13884 }
13885
13886 fn is_completion_trigger(
13887 &self,
13888 buffer: &Model<Buffer>,
13889 position: language::Anchor,
13890 text: &str,
13891 trigger_in_words: bool,
13892 cx: &mut ViewContext<Editor>,
13893 ) -> bool {
13894 if !EditorSettings::get_global(cx).show_completions_on_input {
13895 return false;
13896 }
13897
13898 let mut chars = text.chars();
13899 let char = if let Some(char) = chars.next() {
13900 char
13901 } else {
13902 return false;
13903 };
13904 if chars.next().is_some() {
13905 return false;
13906 }
13907
13908 let buffer = buffer.read(cx);
13909 let classifier = buffer
13910 .snapshot()
13911 .char_classifier_at(position)
13912 .for_completion(true);
13913 if trigger_in_words && classifier.is_word(char) {
13914 return true;
13915 }
13916
13917 buffer.completion_triggers().contains(text)
13918 }
13919}
13920
13921impl SemanticsProvider for Model<Project> {
13922 fn hover(
13923 &self,
13924 buffer: &Model<Buffer>,
13925 position: text::Anchor,
13926 cx: &mut AppContext,
13927 ) -> Option<Task<Vec<project::Hover>>> {
13928 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13929 }
13930
13931 fn document_highlights(
13932 &self,
13933 buffer: &Model<Buffer>,
13934 position: text::Anchor,
13935 cx: &mut AppContext,
13936 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13937 Some(self.update(cx, |project, cx| {
13938 project.document_highlights(buffer, position, cx)
13939 }))
13940 }
13941
13942 fn definitions(
13943 &self,
13944 buffer: &Model<Buffer>,
13945 position: text::Anchor,
13946 kind: GotoDefinitionKind,
13947 cx: &mut AppContext,
13948 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13949 Some(self.update(cx, |project, cx| match kind {
13950 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13951 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13952 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13953 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13954 }))
13955 }
13956
13957 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13958 // TODO: make this work for remote projects
13959 self.read(cx)
13960 .language_servers_for_buffer(buffer.read(cx), cx)
13961 .any(
13962 |(_, server)| match server.capabilities().inlay_hint_provider {
13963 Some(lsp::OneOf::Left(enabled)) => enabled,
13964 Some(lsp::OneOf::Right(_)) => true,
13965 None => false,
13966 },
13967 )
13968 }
13969
13970 fn inlay_hints(
13971 &self,
13972 buffer_handle: Model<Buffer>,
13973 range: Range<text::Anchor>,
13974 cx: &mut AppContext,
13975 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13976 Some(self.update(cx, |project, cx| {
13977 project.inlay_hints(buffer_handle, range, cx)
13978 }))
13979 }
13980
13981 fn resolve_inlay_hint(
13982 &self,
13983 hint: InlayHint,
13984 buffer_handle: Model<Buffer>,
13985 server_id: LanguageServerId,
13986 cx: &mut AppContext,
13987 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13988 Some(self.update(cx, |project, cx| {
13989 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13990 }))
13991 }
13992
13993 fn range_for_rename(
13994 &self,
13995 buffer: &Model<Buffer>,
13996 position: text::Anchor,
13997 cx: &mut AppContext,
13998 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13999 Some(self.update(cx, |project, cx| {
14000 project.prepare_rename(buffer.clone(), position, cx)
14001 }))
14002 }
14003
14004 fn perform_rename(
14005 &self,
14006 buffer: &Model<Buffer>,
14007 position: text::Anchor,
14008 new_name: String,
14009 cx: &mut AppContext,
14010 ) -> Option<Task<Result<ProjectTransaction>>> {
14011 Some(self.update(cx, |project, cx| {
14012 project.perform_rename(buffer.clone(), position, new_name, cx)
14013 }))
14014 }
14015}
14016
14017fn inlay_hint_settings(
14018 location: Anchor,
14019 snapshot: &MultiBufferSnapshot,
14020 cx: &mut ViewContext<'_, Editor>,
14021) -> InlayHintSettings {
14022 let file = snapshot.file_at(location);
14023 let language = snapshot.language_at(location).map(|l| l.name());
14024 language_settings(language, file, cx).inlay_hints
14025}
14026
14027fn consume_contiguous_rows(
14028 contiguous_row_selections: &mut Vec<Selection<Point>>,
14029 selection: &Selection<Point>,
14030 display_map: &DisplaySnapshot,
14031 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14032) -> (MultiBufferRow, MultiBufferRow) {
14033 contiguous_row_selections.push(selection.clone());
14034 let start_row = MultiBufferRow(selection.start.row);
14035 let mut end_row = ending_row(selection, display_map);
14036
14037 while let Some(next_selection) = selections.peek() {
14038 if next_selection.start.row <= end_row.0 {
14039 end_row = ending_row(next_selection, display_map);
14040 contiguous_row_selections.push(selections.next().unwrap().clone());
14041 } else {
14042 break;
14043 }
14044 }
14045 (start_row, end_row)
14046}
14047
14048fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14049 if next_selection.end.column > 0 || next_selection.is_empty() {
14050 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14051 } else {
14052 MultiBufferRow(next_selection.end.row)
14053 }
14054}
14055
14056impl EditorSnapshot {
14057 pub fn remote_selections_in_range<'a>(
14058 &'a self,
14059 range: &'a Range<Anchor>,
14060 collaboration_hub: &dyn CollaborationHub,
14061 cx: &'a AppContext,
14062 ) -> impl 'a + Iterator<Item = RemoteSelection> {
14063 let participant_names = collaboration_hub.user_names(cx);
14064 let participant_indices = collaboration_hub.user_participant_indices(cx);
14065 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14066 let collaborators_by_replica_id = collaborators_by_peer_id
14067 .iter()
14068 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14069 .collect::<HashMap<_, _>>();
14070 self.buffer_snapshot
14071 .selections_in_range(range, false)
14072 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14073 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14074 let participant_index = participant_indices.get(&collaborator.user_id).copied();
14075 let user_name = participant_names.get(&collaborator.user_id).cloned();
14076 Some(RemoteSelection {
14077 replica_id,
14078 selection,
14079 cursor_shape,
14080 line_mode,
14081 participant_index,
14082 peer_id: collaborator.peer_id,
14083 user_name,
14084 })
14085 })
14086 }
14087
14088 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14089 self.display_snapshot.buffer_snapshot.language_at(position)
14090 }
14091
14092 pub fn is_focused(&self) -> bool {
14093 self.is_focused
14094 }
14095
14096 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14097 self.placeholder_text.as_ref()
14098 }
14099
14100 pub fn scroll_position(&self) -> gpui::Point<f32> {
14101 self.scroll_anchor.scroll_position(&self.display_snapshot)
14102 }
14103
14104 fn gutter_dimensions(
14105 &self,
14106 font_id: FontId,
14107 font_size: Pixels,
14108 em_width: Pixels,
14109 em_advance: Pixels,
14110 max_line_number_width: Pixels,
14111 cx: &AppContext,
14112 ) -> GutterDimensions {
14113 if !self.show_gutter {
14114 return GutterDimensions::default();
14115 }
14116 let descent = cx.text_system().descent(font_id, font_size);
14117
14118 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14119 matches!(
14120 ProjectSettings::get_global(cx).git.git_gutter,
14121 Some(GitGutterSetting::TrackedFiles)
14122 )
14123 });
14124 let gutter_settings = EditorSettings::get_global(cx).gutter;
14125 let show_line_numbers = self
14126 .show_line_numbers
14127 .unwrap_or(gutter_settings.line_numbers);
14128 let line_gutter_width = if show_line_numbers {
14129 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14130 let min_width_for_number_on_gutter = em_advance * 4.0;
14131 max_line_number_width.max(min_width_for_number_on_gutter)
14132 } else {
14133 0.0.into()
14134 };
14135
14136 let show_code_actions = self
14137 .show_code_actions
14138 .unwrap_or(gutter_settings.code_actions);
14139
14140 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14141
14142 let git_blame_entries_width =
14143 self.git_blame_gutter_max_author_length
14144 .map(|max_author_length| {
14145 // Length of the author name, but also space for the commit hash,
14146 // the spacing and the timestamp.
14147 let max_char_count = max_author_length
14148 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14149 + 7 // length of commit sha
14150 + 14 // length of max relative timestamp ("60 minutes ago")
14151 + 4; // gaps and margins
14152
14153 em_advance * max_char_count
14154 });
14155
14156 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14157 left_padding += if show_code_actions || show_runnables {
14158 em_width * 3.0
14159 } else if show_git_gutter && show_line_numbers {
14160 em_width * 2.0
14161 } else if show_git_gutter || show_line_numbers {
14162 em_width
14163 } else {
14164 px(0.)
14165 };
14166
14167 let right_padding = if gutter_settings.folds && show_line_numbers {
14168 em_width * 4.0
14169 } else if gutter_settings.folds {
14170 em_width * 3.0
14171 } else if show_line_numbers {
14172 em_width
14173 } else {
14174 px(0.)
14175 };
14176
14177 GutterDimensions {
14178 left_padding,
14179 right_padding,
14180 width: line_gutter_width + left_padding + right_padding,
14181 margin: -descent,
14182 git_blame_entries_width,
14183 }
14184 }
14185
14186 pub fn render_crease_toggle(
14187 &self,
14188 buffer_row: MultiBufferRow,
14189 row_contains_cursor: bool,
14190 editor: View<Editor>,
14191 cx: &mut WindowContext,
14192 ) -> Option<AnyElement> {
14193 let folded = self.is_line_folded(buffer_row);
14194 let mut is_foldable = false;
14195
14196 if let Some(crease) = self
14197 .crease_snapshot
14198 .query_row(buffer_row, &self.buffer_snapshot)
14199 {
14200 is_foldable = true;
14201 match crease {
14202 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14203 if let Some(render_toggle) = render_toggle {
14204 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14205 if folded {
14206 editor.update(cx, |editor, cx| {
14207 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14208 });
14209 } else {
14210 editor.update(cx, |editor, cx| {
14211 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14212 });
14213 }
14214 });
14215 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14216 }
14217 }
14218 }
14219 }
14220
14221 is_foldable |= self.starts_indent(buffer_row);
14222
14223 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14224 Some(
14225 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14226 .selected(folded)
14227 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14228 if folded {
14229 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14230 } else {
14231 this.fold_at(&FoldAt { buffer_row }, cx);
14232 }
14233 }))
14234 .into_any_element(),
14235 )
14236 } else {
14237 None
14238 }
14239 }
14240
14241 pub fn render_crease_trailer(
14242 &self,
14243 buffer_row: MultiBufferRow,
14244 cx: &mut WindowContext,
14245 ) -> Option<AnyElement> {
14246 let folded = self.is_line_folded(buffer_row);
14247 if let Crease::Inline { render_trailer, .. } = self
14248 .crease_snapshot
14249 .query_row(buffer_row, &self.buffer_snapshot)?
14250 {
14251 let render_trailer = render_trailer.as_ref()?;
14252 Some(render_trailer(buffer_row, folded, cx))
14253 } else {
14254 None
14255 }
14256 }
14257}
14258
14259impl Deref for EditorSnapshot {
14260 type Target = DisplaySnapshot;
14261
14262 fn deref(&self) -> &Self::Target {
14263 &self.display_snapshot
14264 }
14265}
14266
14267#[derive(Clone, Debug, PartialEq, Eq)]
14268pub enum EditorEvent {
14269 InputIgnored {
14270 text: Arc<str>,
14271 },
14272 InputHandled {
14273 utf16_range_to_replace: Option<Range<isize>>,
14274 text: Arc<str>,
14275 },
14276 ExcerptsAdded {
14277 buffer: Model<Buffer>,
14278 predecessor: ExcerptId,
14279 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14280 },
14281 ExcerptsRemoved {
14282 ids: Vec<ExcerptId>,
14283 },
14284 ExcerptsEdited {
14285 ids: Vec<ExcerptId>,
14286 },
14287 ExcerptsExpanded {
14288 ids: Vec<ExcerptId>,
14289 },
14290 BufferEdited,
14291 Edited {
14292 transaction_id: clock::Lamport,
14293 },
14294 Reparsed(BufferId),
14295 Focused,
14296 FocusedIn,
14297 Blurred,
14298 DirtyChanged,
14299 Saved,
14300 TitleChanged,
14301 DiffBaseChanged,
14302 SelectionsChanged {
14303 local: bool,
14304 },
14305 ScrollPositionChanged {
14306 local: bool,
14307 autoscroll: bool,
14308 },
14309 Closed,
14310 TransactionUndone {
14311 transaction_id: clock::Lamport,
14312 },
14313 TransactionBegun {
14314 transaction_id: clock::Lamport,
14315 },
14316 Reloaded,
14317 CursorShapeChanged,
14318}
14319
14320impl EventEmitter<EditorEvent> for Editor {}
14321
14322impl FocusableView for Editor {
14323 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14324 self.focus_handle.clone()
14325 }
14326}
14327
14328impl Render for Editor {
14329 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14330 let settings = ThemeSettings::get_global(cx);
14331
14332 let mut text_style = match self.mode {
14333 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14334 color: cx.theme().colors().editor_foreground,
14335 font_family: settings.ui_font.family.clone(),
14336 font_features: settings.ui_font.features.clone(),
14337 font_fallbacks: settings.ui_font.fallbacks.clone(),
14338 font_size: rems(0.875).into(),
14339 font_weight: settings.ui_font.weight,
14340 line_height: relative(settings.buffer_line_height.value()),
14341 ..Default::default()
14342 },
14343 EditorMode::Full => TextStyle {
14344 color: cx.theme().colors().editor_foreground,
14345 font_family: settings.buffer_font.family.clone(),
14346 font_features: settings.buffer_font.features.clone(),
14347 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14348 font_size: settings.buffer_font_size(cx).into(),
14349 font_weight: settings.buffer_font.weight,
14350 line_height: relative(settings.buffer_line_height.value()),
14351 ..Default::default()
14352 },
14353 };
14354 if let Some(text_style_refinement) = &self.text_style_refinement {
14355 text_style.refine(text_style_refinement)
14356 }
14357
14358 let background = match self.mode {
14359 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14360 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14361 EditorMode::Full => cx.theme().colors().editor_background,
14362 };
14363
14364 EditorElement::new(
14365 cx.view(),
14366 EditorStyle {
14367 background,
14368 local_player: cx.theme().players().local(),
14369 text: text_style,
14370 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14371 syntax: cx.theme().syntax().clone(),
14372 status: cx.theme().status().clone(),
14373 inlay_hints_style: make_inlay_hints_style(cx),
14374 suggestions_style: HighlightStyle {
14375 color: Some(cx.theme().status().predictive),
14376 ..HighlightStyle::default()
14377 },
14378 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14379 },
14380 )
14381 }
14382}
14383
14384impl ViewInputHandler for Editor {
14385 fn text_for_range(
14386 &mut self,
14387 range_utf16: Range<usize>,
14388 cx: &mut ViewContext<Self>,
14389 ) -> Option<String> {
14390 Some(
14391 self.buffer
14392 .read(cx)
14393 .read(cx)
14394 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
14395 .collect(),
14396 )
14397 }
14398
14399 fn selected_text_range(
14400 &mut self,
14401 ignore_disabled_input: bool,
14402 cx: &mut ViewContext<Self>,
14403 ) -> Option<UTF16Selection> {
14404 // Prevent the IME menu from appearing when holding down an alphabetic key
14405 // while input is disabled.
14406 if !ignore_disabled_input && !self.input_enabled {
14407 return None;
14408 }
14409
14410 let selection = self.selections.newest::<OffsetUtf16>(cx);
14411 let range = selection.range();
14412
14413 Some(UTF16Selection {
14414 range: range.start.0..range.end.0,
14415 reversed: selection.reversed,
14416 })
14417 }
14418
14419 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14420 let snapshot = self.buffer.read(cx).read(cx);
14421 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14422 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14423 }
14424
14425 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14426 self.clear_highlights::<InputComposition>(cx);
14427 self.ime_transaction.take();
14428 }
14429
14430 fn replace_text_in_range(
14431 &mut self,
14432 range_utf16: Option<Range<usize>>,
14433 text: &str,
14434 cx: &mut ViewContext<Self>,
14435 ) {
14436 if !self.input_enabled {
14437 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14438 return;
14439 }
14440
14441 self.transact(cx, |this, cx| {
14442 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14443 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14444 Some(this.selection_replacement_ranges(range_utf16, cx))
14445 } else {
14446 this.marked_text_ranges(cx)
14447 };
14448
14449 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14450 let newest_selection_id = this.selections.newest_anchor().id;
14451 this.selections
14452 .all::<OffsetUtf16>(cx)
14453 .iter()
14454 .zip(ranges_to_replace.iter())
14455 .find_map(|(selection, range)| {
14456 if selection.id == newest_selection_id {
14457 Some(
14458 (range.start.0 as isize - selection.head().0 as isize)
14459 ..(range.end.0 as isize - selection.head().0 as isize),
14460 )
14461 } else {
14462 None
14463 }
14464 })
14465 });
14466
14467 cx.emit(EditorEvent::InputHandled {
14468 utf16_range_to_replace: range_to_replace,
14469 text: text.into(),
14470 });
14471
14472 if let Some(new_selected_ranges) = new_selected_ranges {
14473 this.change_selections(None, cx, |selections| {
14474 selections.select_ranges(new_selected_ranges)
14475 });
14476 this.backspace(&Default::default(), cx);
14477 }
14478
14479 this.handle_input(text, cx);
14480 });
14481
14482 if let Some(transaction) = self.ime_transaction {
14483 self.buffer.update(cx, |buffer, cx| {
14484 buffer.group_until_transaction(transaction, cx);
14485 });
14486 }
14487
14488 self.unmark_text(cx);
14489 }
14490
14491 fn replace_and_mark_text_in_range(
14492 &mut self,
14493 range_utf16: Option<Range<usize>>,
14494 text: &str,
14495 new_selected_range_utf16: Option<Range<usize>>,
14496 cx: &mut ViewContext<Self>,
14497 ) {
14498 if !self.input_enabled {
14499 return;
14500 }
14501
14502 let transaction = self.transact(cx, |this, cx| {
14503 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14504 let snapshot = this.buffer.read(cx).read(cx);
14505 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14506 for marked_range in &mut marked_ranges {
14507 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14508 marked_range.start.0 += relative_range_utf16.start;
14509 marked_range.start =
14510 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14511 marked_range.end =
14512 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14513 }
14514 }
14515 Some(marked_ranges)
14516 } else if let Some(range_utf16) = range_utf16 {
14517 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14518 Some(this.selection_replacement_ranges(range_utf16, cx))
14519 } else {
14520 None
14521 };
14522
14523 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14524 let newest_selection_id = this.selections.newest_anchor().id;
14525 this.selections
14526 .all::<OffsetUtf16>(cx)
14527 .iter()
14528 .zip(ranges_to_replace.iter())
14529 .find_map(|(selection, range)| {
14530 if selection.id == newest_selection_id {
14531 Some(
14532 (range.start.0 as isize - selection.head().0 as isize)
14533 ..(range.end.0 as isize - selection.head().0 as isize),
14534 )
14535 } else {
14536 None
14537 }
14538 })
14539 });
14540
14541 cx.emit(EditorEvent::InputHandled {
14542 utf16_range_to_replace: range_to_replace,
14543 text: text.into(),
14544 });
14545
14546 if let Some(ranges) = ranges_to_replace {
14547 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14548 }
14549
14550 let marked_ranges = {
14551 let snapshot = this.buffer.read(cx).read(cx);
14552 this.selections
14553 .disjoint_anchors()
14554 .iter()
14555 .map(|selection| {
14556 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14557 })
14558 .collect::<Vec<_>>()
14559 };
14560
14561 if text.is_empty() {
14562 this.unmark_text(cx);
14563 } else {
14564 this.highlight_text::<InputComposition>(
14565 marked_ranges.clone(),
14566 HighlightStyle {
14567 underline: Some(UnderlineStyle {
14568 thickness: px(1.),
14569 color: None,
14570 wavy: false,
14571 }),
14572 ..Default::default()
14573 },
14574 cx,
14575 );
14576 }
14577
14578 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14579 let use_autoclose = this.use_autoclose;
14580 let use_auto_surround = this.use_auto_surround;
14581 this.set_use_autoclose(false);
14582 this.set_use_auto_surround(false);
14583 this.handle_input(text, cx);
14584 this.set_use_autoclose(use_autoclose);
14585 this.set_use_auto_surround(use_auto_surround);
14586
14587 if let Some(new_selected_range) = new_selected_range_utf16 {
14588 let snapshot = this.buffer.read(cx).read(cx);
14589 let new_selected_ranges = marked_ranges
14590 .into_iter()
14591 .map(|marked_range| {
14592 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14593 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14594 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14595 snapshot.clip_offset_utf16(new_start, Bias::Left)
14596 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14597 })
14598 .collect::<Vec<_>>();
14599
14600 drop(snapshot);
14601 this.change_selections(None, cx, |selections| {
14602 selections.select_ranges(new_selected_ranges)
14603 });
14604 }
14605 });
14606
14607 self.ime_transaction = self.ime_transaction.or(transaction);
14608 if let Some(transaction) = self.ime_transaction {
14609 self.buffer.update(cx, |buffer, cx| {
14610 buffer.group_until_transaction(transaction, cx);
14611 });
14612 }
14613
14614 if self.text_highlights::<InputComposition>(cx).is_none() {
14615 self.ime_transaction.take();
14616 }
14617 }
14618
14619 fn bounds_for_range(
14620 &mut self,
14621 range_utf16: Range<usize>,
14622 element_bounds: gpui::Bounds<Pixels>,
14623 cx: &mut ViewContext<Self>,
14624 ) -> Option<gpui::Bounds<Pixels>> {
14625 let text_layout_details = self.text_layout_details(cx);
14626 let style = &text_layout_details.editor_style;
14627 let font_id = cx.text_system().resolve_font(&style.text.font());
14628 let font_size = style.text.font_size.to_pixels(cx.rem_size());
14629 let line_height = style.text.line_height_in_pixels(cx.rem_size());
14630
14631 let em_width = cx
14632 .text_system()
14633 .typographic_bounds(font_id, font_size, 'm')
14634 .unwrap()
14635 .size
14636 .width;
14637
14638 let snapshot = self.snapshot(cx);
14639 let scroll_position = snapshot.scroll_position();
14640 let scroll_left = scroll_position.x * em_width;
14641
14642 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14643 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14644 + self.gutter_dimensions.width;
14645 let y = line_height * (start.row().as_f32() - scroll_position.y);
14646
14647 Some(Bounds {
14648 origin: element_bounds.origin + point(x, y),
14649 size: size(em_width, line_height),
14650 })
14651 }
14652}
14653
14654trait SelectionExt {
14655 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14656 fn spanned_rows(
14657 &self,
14658 include_end_if_at_line_start: bool,
14659 map: &DisplaySnapshot,
14660 ) -> Range<MultiBufferRow>;
14661}
14662
14663impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14664 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14665 let start = self
14666 .start
14667 .to_point(&map.buffer_snapshot)
14668 .to_display_point(map);
14669 let end = self
14670 .end
14671 .to_point(&map.buffer_snapshot)
14672 .to_display_point(map);
14673 if self.reversed {
14674 end..start
14675 } else {
14676 start..end
14677 }
14678 }
14679
14680 fn spanned_rows(
14681 &self,
14682 include_end_if_at_line_start: bool,
14683 map: &DisplaySnapshot,
14684 ) -> Range<MultiBufferRow> {
14685 let start = self.start.to_point(&map.buffer_snapshot);
14686 let mut end = self.end.to_point(&map.buffer_snapshot);
14687 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14688 end.row -= 1;
14689 }
14690
14691 let buffer_start = map.prev_line_boundary(start).0;
14692 let buffer_end = map.next_line_boundary(end).0;
14693 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14694 }
14695}
14696
14697impl<T: InvalidationRegion> InvalidationStack<T> {
14698 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14699 where
14700 S: Clone + ToOffset,
14701 {
14702 while let Some(region) = self.last() {
14703 let all_selections_inside_invalidation_ranges =
14704 if selections.len() == region.ranges().len() {
14705 selections
14706 .iter()
14707 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14708 .all(|(selection, invalidation_range)| {
14709 let head = selection.head().to_offset(buffer);
14710 invalidation_range.start <= head && invalidation_range.end >= head
14711 })
14712 } else {
14713 false
14714 };
14715
14716 if all_selections_inside_invalidation_ranges {
14717 break;
14718 } else {
14719 self.pop();
14720 }
14721 }
14722 }
14723}
14724
14725impl<T> Default for InvalidationStack<T> {
14726 fn default() -> Self {
14727 Self(Default::default())
14728 }
14729}
14730
14731impl<T> Deref for InvalidationStack<T> {
14732 type Target = Vec<T>;
14733
14734 fn deref(&self) -> &Self::Target {
14735 &self.0
14736 }
14737}
14738
14739impl<T> DerefMut for InvalidationStack<T> {
14740 fn deref_mut(&mut self) -> &mut Self::Target {
14741 &mut self.0
14742 }
14743}
14744
14745impl InvalidationRegion for SnippetState {
14746 fn ranges(&self) -> &[Range<Anchor>] {
14747 &self.ranges[self.active_index]
14748 }
14749}
14750
14751pub fn diagnostic_block_renderer(
14752 diagnostic: Diagnostic,
14753 max_message_rows: Option<u8>,
14754 allow_closing: bool,
14755 _is_valid: bool,
14756) -> RenderBlock {
14757 let (text_without_backticks, code_ranges) =
14758 highlight_diagnostic_message(&diagnostic, max_message_rows);
14759
14760 Arc::new(move |cx: &mut BlockContext| {
14761 let group_id: SharedString = cx.block_id.to_string().into();
14762
14763 let mut text_style = cx.text_style().clone();
14764 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14765 let theme_settings = ThemeSettings::get_global(cx);
14766 text_style.font_family = theme_settings.buffer_font.family.clone();
14767 text_style.font_style = theme_settings.buffer_font.style;
14768 text_style.font_features = theme_settings.buffer_font.features.clone();
14769 text_style.font_weight = theme_settings.buffer_font.weight;
14770
14771 let multi_line_diagnostic = diagnostic.message.contains('\n');
14772
14773 let buttons = |diagnostic: &Diagnostic| {
14774 if multi_line_diagnostic {
14775 v_flex()
14776 } else {
14777 h_flex()
14778 }
14779 .when(allow_closing, |div| {
14780 div.children(diagnostic.is_primary.then(|| {
14781 IconButton::new("close-block", IconName::XCircle)
14782 .icon_color(Color::Muted)
14783 .size(ButtonSize::Compact)
14784 .style(ButtonStyle::Transparent)
14785 .visible_on_hover(group_id.clone())
14786 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14787 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14788 }))
14789 })
14790 .child(
14791 IconButton::new("copy-block", IconName::Copy)
14792 .icon_color(Color::Muted)
14793 .size(ButtonSize::Compact)
14794 .style(ButtonStyle::Transparent)
14795 .visible_on_hover(group_id.clone())
14796 .on_click({
14797 let message = diagnostic.message.clone();
14798 move |_click, cx| {
14799 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14800 }
14801 })
14802 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14803 )
14804 };
14805
14806 let icon_size = buttons(&diagnostic)
14807 .into_any_element()
14808 .layout_as_root(AvailableSpace::min_size(), cx);
14809
14810 h_flex()
14811 .id(cx.block_id)
14812 .group(group_id.clone())
14813 .relative()
14814 .size_full()
14815 .block_mouse_down()
14816 .pl(cx.gutter_dimensions.width)
14817 .w(cx.max_width - cx.gutter_dimensions.full_width())
14818 .child(
14819 div()
14820 .flex()
14821 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14822 .flex_shrink(),
14823 )
14824 .child(buttons(&diagnostic))
14825 .child(div().flex().flex_shrink_0().child(
14826 StyledText::new(text_without_backticks.clone()).with_highlights(
14827 &text_style,
14828 code_ranges.iter().map(|range| {
14829 (
14830 range.clone(),
14831 HighlightStyle {
14832 font_weight: Some(FontWeight::BOLD),
14833 ..Default::default()
14834 },
14835 )
14836 }),
14837 ),
14838 ))
14839 .into_any_element()
14840 })
14841}
14842
14843pub fn highlight_diagnostic_message(
14844 diagnostic: &Diagnostic,
14845 mut max_message_rows: Option<u8>,
14846) -> (SharedString, Vec<Range<usize>>) {
14847 let mut text_without_backticks = String::new();
14848 let mut code_ranges = Vec::new();
14849
14850 if let Some(source) = &diagnostic.source {
14851 text_without_backticks.push_str(source);
14852 code_ranges.push(0..source.len());
14853 text_without_backticks.push_str(": ");
14854 }
14855
14856 let mut prev_offset = 0;
14857 let mut in_code_block = false;
14858 let has_row_limit = max_message_rows.is_some();
14859 let mut newline_indices = diagnostic
14860 .message
14861 .match_indices('\n')
14862 .filter(|_| has_row_limit)
14863 .map(|(ix, _)| ix)
14864 .fuse()
14865 .peekable();
14866
14867 for (quote_ix, _) in diagnostic
14868 .message
14869 .match_indices('`')
14870 .chain([(diagnostic.message.len(), "")])
14871 {
14872 let mut first_newline_ix = None;
14873 let mut last_newline_ix = None;
14874 while let Some(newline_ix) = newline_indices.peek() {
14875 if *newline_ix < quote_ix {
14876 if first_newline_ix.is_none() {
14877 first_newline_ix = Some(*newline_ix);
14878 }
14879 last_newline_ix = Some(*newline_ix);
14880
14881 if let Some(rows_left) = &mut max_message_rows {
14882 if *rows_left == 0 {
14883 break;
14884 } else {
14885 *rows_left -= 1;
14886 }
14887 }
14888 let _ = newline_indices.next();
14889 } else {
14890 break;
14891 }
14892 }
14893 let prev_len = text_without_backticks.len();
14894 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14895 text_without_backticks.push_str(new_text);
14896 if in_code_block {
14897 code_ranges.push(prev_len..text_without_backticks.len());
14898 }
14899 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14900 in_code_block = !in_code_block;
14901 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14902 text_without_backticks.push_str("...");
14903 break;
14904 }
14905 }
14906
14907 (text_without_backticks.into(), code_ranges)
14908}
14909
14910fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14911 match severity {
14912 DiagnosticSeverity::ERROR => colors.error,
14913 DiagnosticSeverity::WARNING => colors.warning,
14914 DiagnosticSeverity::INFORMATION => colors.info,
14915 DiagnosticSeverity::HINT => colors.info,
14916 _ => colors.ignored,
14917 }
14918}
14919
14920pub fn styled_runs_for_code_label<'a>(
14921 label: &'a CodeLabel,
14922 syntax_theme: &'a theme::SyntaxTheme,
14923) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14924 let fade_out = HighlightStyle {
14925 fade_out: Some(0.35),
14926 ..Default::default()
14927 };
14928
14929 let mut prev_end = label.filter_range.end;
14930 label
14931 .runs
14932 .iter()
14933 .enumerate()
14934 .flat_map(move |(ix, (range, highlight_id))| {
14935 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14936 style
14937 } else {
14938 return Default::default();
14939 };
14940 let mut muted_style = style;
14941 muted_style.highlight(fade_out);
14942
14943 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14944 if range.start >= label.filter_range.end {
14945 if range.start > prev_end {
14946 runs.push((prev_end..range.start, fade_out));
14947 }
14948 runs.push((range.clone(), muted_style));
14949 } else if range.end <= label.filter_range.end {
14950 runs.push((range.clone(), style));
14951 } else {
14952 runs.push((range.start..label.filter_range.end, style));
14953 runs.push((label.filter_range.end..range.end, muted_style));
14954 }
14955 prev_end = cmp::max(prev_end, range.end);
14956
14957 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14958 runs.push((prev_end..label.text.len(), fade_out));
14959 }
14960
14961 runs
14962 })
14963}
14964
14965pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14966 let mut prev_index = 0;
14967 let mut prev_codepoint: Option<char> = None;
14968 text.char_indices()
14969 .chain([(text.len(), '\0')])
14970 .filter_map(move |(index, codepoint)| {
14971 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14972 let is_boundary = index == text.len()
14973 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14974 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14975 if is_boundary {
14976 let chunk = &text[prev_index..index];
14977 prev_index = index;
14978 Some(chunk)
14979 } else {
14980 None
14981 }
14982 })
14983}
14984
14985pub trait RangeToAnchorExt: Sized {
14986 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14987
14988 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14989 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14990 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14991 }
14992}
14993
14994impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14995 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14996 let start_offset = self.start.to_offset(snapshot);
14997 let end_offset = self.end.to_offset(snapshot);
14998 if start_offset == end_offset {
14999 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15000 } else {
15001 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15002 }
15003 }
15004}
15005
15006pub trait RowExt {
15007 fn as_f32(&self) -> f32;
15008
15009 fn next_row(&self) -> Self;
15010
15011 fn previous_row(&self) -> Self;
15012
15013 fn minus(&self, other: Self) -> u32;
15014}
15015
15016impl RowExt for DisplayRow {
15017 fn as_f32(&self) -> f32 {
15018 self.0 as f32
15019 }
15020
15021 fn next_row(&self) -> Self {
15022 Self(self.0 + 1)
15023 }
15024
15025 fn previous_row(&self) -> Self {
15026 Self(self.0.saturating_sub(1))
15027 }
15028
15029 fn minus(&self, other: Self) -> u32 {
15030 self.0 - other.0
15031 }
15032}
15033
15034impl RowExt for MultiBufferRow {
15035 fn as_f32(&self) -> f32 {
15036 self.0 as f32
15037 }
15038
15039 fn next_row(&self) -> Self {
15040 Self(self.0 + 1)
15041 }
15042
15043 fn previous_row(&self) -> Self {
15044 Self(self.0.saturating_sub(1))
15045 }
15046
15047 fn minus(&self, other: Self) -> u32 {
15048 self.0 - other.0
15049 }
15050}
15051
15052trait RowRangeExt {
15053 type Row;
15054
15055 fn len(&self) -> usize;
15056
15057 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15058}
15059
15060impl RowRangeExt for Range<MultiBufferRow> {
15061 type Row = MultiBufferRow;
15062
15063 fn len(&self) -> usize {
15064 (self.end.0 - self.start.0) as usize
15065 }
15066
15067 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15068 (self.start.0..self.end.0).map(MultiBufferRow)
15069 }
15070}
15071
15072impl RowRangeExt for Range<DisplayRow> {
15073 type Row = DisplayRow;
15074
15075 fn len(&self) -> usize {
15076 (self.end.0 - self.start.0) as usize
15077 }
15078
15079 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15080 (self.start.0..self.end.0).map(DisplayRow)
15081 }
15082}
15083
15084fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15085 if hunk.diff_base_byte_range.is_empty() {
15086 DiffHunkStatus::Added
15087 } else if hunk.row_range.is_empty() {
15088 DiffHunkStatus::Removed
15089 } else {
15090 DiffHunkStatus::Modified
15091 }
15092}
15093
15094/// If select range has more than one line, we
15095/// just point the cursor to range.start.
15096fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15097 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15098 range
15099 } else {
15100 range.start..range.start
15101 }
15102}
15103
15104const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);