1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod clangd_ext;
19mod code_context_menus;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod hunk_diff;
29mod indent_guides;
30mod inlay_hint_cache;
31pub mod items;
32mod linked_editing_ranges;
33mod lsp_ext;
34mod mouse_context_menu;
35pub mod movement;
36mod persistence;
37mod proposed_changes_editor;
38mod rust_analyzer_ext;
39pub mod scroll;
40mod selections_collection;
41pub mod tasks;
42
43#[cfg(test)]
44mod editor_tests;
45#[cfg(test)]
46mod inline_completion_tests;
47mod signature_help;
48#[cfg(any(test, feature = "test-support"))]
49pub mod test;
50
51use ::git::diff::DiffHunkStatus;
52pub(crate) use actions::*;
53pub use actions::{OpenExcerpts, OpenExcerptsSplit};
54use aho_corasick::AhoCorasick;
55use anyhow::{anyhow, Context as _, Result};
56use blink_manager::BlinkManager;
57use client::{Collaborator, ParticipantIndex};
58use clock::ReplicaId;
59use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
60use convert_case::{Case, Casing};
61use display_map::*;
62pub use display_map::{DisplayPoint, FoldPlaceholder};
63pub use editor_settings::{
64 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
65};
66pub use editor_settings_controls::*;
67use element::LineWithInvisibles;
68pub use element::{
69 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
70};
71use futures::{future, FutureExt};
72use fuzzy::StringMatchCandidate;
73
74use code_context_menus::{
75 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
76 CompletionEntry, CompletionsMenu, ContextMenuOrigin,
77};
78use git::blame::GitBlame;
79use gpui::{
80 div, impl_actions, point, prelude::*, px, relative, size, Action, AnyElement, AppContext,
81 AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context,
82 DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent, FocusableView, FontId,
83 FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Model, ModelContext,
84 MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText,
85 Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
86 UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
87 WeakView, WindowContext,
88};
89use highlight_matching_bracket::refresh_matching_bracket_highlights;
90use hover_popover::{hide_hover, HoverState};
91pub(crate) use hunk_diff::HoveredHunk;
92use hunk_diff::{diff_hunk_to_display, DiffMap, DiffMapSnapshot};
93use indent_guides::ActiveIndentGuidesState;
94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
95pub use inline_completion::Direction;
96use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
97pub use items::MAX_TAB_TITLE_LEN;
98use itertools::Itertools;
99use language::{
100 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
101 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
102 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
103 Point, Selection, SelectionGoal, TransactionId,
104};
105use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
106use linked_editing_ranges::refresh_linked_ranges;
107use mouse_context_menu::MouseContextMenu;
108pub use proposed_changes_editor::{
109 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
110};
111use similar::{ChangeTag, TextDiff};
112use std::iter::Peekable;
113use task::{ResolvedTask, TaskTemplate, TaskVariables};
114
115use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
116pub use lsp::CompletionContext;
117use lsp::{
118 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
119 LanguageServerId, LanguageServerName,
120};
121
122use movement::TextLayoutDetails;
123pub use multi_buffer::{
124 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
125 ToPoint,
126};
127use multi_buffer::{
128 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
129};
130use project::{
131 buffer_store::BufferChangeSet,
132 lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
133 project_settings::{GitGutterSetting, ProjectSettings},
134 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
135 LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
136};
137use rand::prelude::*;
138use rpc::{proto::*, ErrorExt};
139use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
140use selections_collection::{
141 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
142};
143use serde::{Deserialize, Serialize};
144use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
145use smallvec::SmallVec;
146use snippet::Snippet;
147use std::{
148 any::TypeId,
149 borrow::Cow,
150 cell::RefCell,
151 cmp::{self, Ordering, Reverse},
152 mem,
153 num::NonZeroU32,
154 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
155 path::{Path, PathBuf},
156 rc::Rc,
157 sync::Arc,
158 time::{Duration, Instant},
159};
160pub use sum_tree::Bias;
161use sum_tree::TreeMap;
162use text::{BufferId, OffsetUtf16, Rope};
163use theme::{
164 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
165 ThemeColors, ThemeSettings,
166};
167use ui::{
168 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
169 PopoverMenuHandle, Tooltip,
170};
171use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
172use workspace::item::{ItemHandle, PreviewTabsSettings};
173use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
174use workspace::{
175 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
176};
177use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
178
179use crate::hover_links::{find_url, find_url_from_range};
180use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
181
182pub const FILE_HEADER_HEIGHT: u32 = 2;
183pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
184pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
185pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
186const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
187const MAX_LINE_LEN: usize = 1024;
188const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
189const MAX_SELECTION_HISTORY_LEN: usize = 1024;
190pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
191#[doc(hidden)]
192pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
193
194pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
195pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
196
197pub fn render_parsed_markdown(
198 element_id: impl Into<ElementId>,
199 parsed: &language::ParsedMarkdown,
200 editor_style: &EditorStyle,
201 workspace: Option<WeakView<Workspace>>,
202 cx: &mut WindowContext,
203) -> InteractiveText {
204 let code_span_background_color = cx
205 .theme()
206 .colors()
207 .editor_document_highlight_read_background;
208
209 let highlights = gpui::combine_highlights(
210 parsed.highlights.iter().filter_map(|(range, highlight)| {
211 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
212 Some((range.clone(), highlight))
213 }),
214 parsed
215 .regions
216 .iter()
217 .zip(&parsed.region_ranges)
218 .filter_map(|(region, range)| {
219 if region.code {
220 Some((
221 range.clone(),
222 HighlightStyle {
223 background_color: Some(code_span_background_color),
224 ..Default::default()
225 },
226 ))
227 } else {
228 None
229 }
230 }),
231 );
232
233 let mut links = Vec::new();
234 let mut link_ranges = Vec::new();
235 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
236 if let Some(link) = region.link.clone() {
237 links.push(link);
238 link_ranges.push(range.clone());
239 }
240 }
241
242 InteractiveText::new(
243 element_id,
244 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
245 )
246 .on_click(link_ranges, move |clicked_range_ix, cx| {
247 match &links[clicked_range_ix] {
248 markdown::Link::Web { url } => cx.open_url(url),
249 markdown::Link::Path { path } => {
250 if let Some(workspace) = &workspace {
251 _ = workspace.update(cx, |workspace, cx| {
252 workspace.open_abs_path(path.clone(), false, cx).detach();
253 });
254 }
255 }
256 }
257 })
258}
259
260#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
261pub enum InlayId {
262 InlineCompletion(usize),
263 Hint(usize),
264}
265
266impl InlayId {
267 fn id(&self) -> usize {
268 match self {
269 Self::InlineCompletion(id) => *id,
270 Self::Hint(id) => *id,
271 }
272 }
273}
274
275enum DiffRowHighlight {}
276enum DocumentHighlightRead {}
277enum DocumentHighlightWrite {}
278enum InputComposition {}
279
280#[derive(Debug, Copy, Clone, PartialEq, Eq)]
281pub enum Navigated {
282 Yes,
283 No,
284}
285
286impl Navigated {
287 pub fn from_bool(yes: bool) -> Navigated {
288 if yes {
289 Navigated::Yes
290 } else {
291 Navigated::No
292 }
293 }
294}
295
296pub fn init_settings(cx: &mut AppContext) {
297 EditorSettings::register(cx);
298}
299
300pub fn init(cx: &mut AppContext) {
301 init_settings(cx);
302
303 workspace::register_project_item::<Editor>(cx);
304 workspace::FollowableViewRegistry::register::<Editor>(cx);
305 workspace::register_serializable_item::<Editor>(cx);
306
307 cx.observe_new_views(
308 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
309 workspace.register_action(Editor::new_file);
310 workspace.register_action(Editor::new_file_vertical);
311 workspace.register_action(Editor::new_file_horizontal);
312 },
313 )
314 .detach();
315
316 cx.on_action(move |_: &workspace::NewFile, cx| {
317 let app_state = workspace::AppState::global(cx);
318 if let Some(app_state) = app_state.upgrade() {
319 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
320 Editor::new_file(workspace, &Default::default(), cx)
321 })
322 .detach();
323 }
324 });
325 cx.on_action(move |_: &workspace::NewWindow, cx| {
326 let app_state = workspace::AppState::global(cx);
327 if let Some(app_state) = app_state.upgrade() {
328 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
329 Editor::new_file(workspace, &Default::default(), cx)
330 })
331 .detach();
332 }
333 });
334 git::project_diff::init(cx);
335}
336
337pub struct SearchWithinRange;
338
339trait InvalidationRegion {
340 fn ranges(&self) -> &[Range<Anchor>];
341}
342
343#[derive(Clone, Debug, PartialEq)]
344pub enum SelectPhase {
345 Begin {
346 position: DisplayPoint,
347 add: bool,
348 click_count: usize,
349 },
350 BeginColumnar {
351 position: DisplayPoint,
352 reset: bool,
353 goal_column: u32,
354 },
355 Extend {
356 position: DisplayPoint,
357 click_count: usize,
358 },
359 Update {
360 position: DisplayPoint,
361 goal_column: u32,
362 scroll_delta: gpui::Point<f32>,
363 },
364 End,
365}
366
367#[derive(Clone, Debug)]
368pub enum SelectMode {
369 Character,
370 Word(Range<Anchor>),
371 Line(Range<Anchor>),
372 All,
373}
374
375#[derive(Copy, Clone, PartialEq, Eq, Debug)]
376pub enum EditorMode {
377 SingleLine { auto_width: bool },
378 AutoHeight { max_lines: usize },
379 Full,
380}
381
382#[derive(Copy, Clone, Debug)]
383pub enum SoftWrap {
384 /// Prefer not to wrap at all.
385 ///
386 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
387 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
388 GitDiff,
389 /// Prefer a single line generally, unless an overly long line is encountered.
390 None,
391 /// Soft wrap lines that exceed the editor width.
392 EditorWidth,
393 /// Soft wrap lines at the preferred line length.
394 Column(u32),
395 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
396 Bounded(u32),
397}
398
399#[derive(Clone)]
400pub struct EditorStyle {
401 pub background: Hsla,
402 pub local_player: PlayerColor,
403 pub text: TextStyle,
404 pub scrollbar_width: Pixels,
405 pub syntax: Arc<SyntaxTheme>,
406 pub status: StatusColors,
407 pub inlay_hints_style: HighlightStyle,
408 pub inline_completion_styles: InlineCompletionStyles,
409 pub unnecessary_code_fade: f32,
410}
411
412impl Default for EditorStyle {
413 fn default() -> Self {
414 Self {
415 background: Hsla::default(),
416 local_player: PlayerColor::default(),
417 text: TextStyle::default(),
418 scrollbar_width: Pixels::default(),
419 syntax: Default::default(),
420 // HACK: Status colors don't have a real default.
421 // We should look into removing the status colors from the editor
422 // style and retrieve them directly from the theme.
423 status: StatusColors::dark(),
424 inlay_hints_style: HighlightStyle::default(),
425 inline_completion_styles: InlineCompletionStyles {
426 insertion: HighlightStyle::default(),
427 whitespace: HighlightStyle::default(),
428 },
429 unnecessary_code_fade: Default::default(),
430 }
431 }
432}
433
434pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
435 let show_background = language_settings::language_settings(None, None, cx)
436 .inlay_hints
437 .show_background;
438
439 HighlightStyle {
440 color: Some(cx.theme().status().hint),
441 background_color: show_background.then(|| cx.theme().status().hint_background),
442 ..HighlightStyle::default()
443 }
444}
445
446pub fn make_suggestion_styles(cx: &WindowContext) -> InlineCompletionStyles {
447 InlineCompletionStyles {
448 insertion: HighlightStyle {
449 color: Some(cx.theme().status().predictive),
450 ..HighlightStyle::default()
451 },
452 whitespace: HighlightStyle {
453 background_color: Some(cx.theme().status().created_background),
454 ..HighlightStyle::default()
455 },
456 }
457}
458
459type CompletionId = usize;
460
461#[derive(Debug, Clone)]
462enum InlineCompletionMenuHint {
463 Loading,
464 Loaded { text: InlineCompletionText },
465 None,
466}
467
468impl InlineCompletionMenuHint {
469 pub fn label(&self) -> &'static str {
470 match self {
471 InlineCompletionMenuHint::Loading | InlineCompletionMenuHint::Loaded { .. } => {
472 "Edit Prediction"
473 }
474 InlineCompletionMenuHint::None => "No Prediction",
475 }
476 }
477}
478
479#[derive(Clone, Debug)]
480enum InlineCompletionText {
481 Move(SharedString),
482 Edit {
483 text: SharedString,
484 highlights: Vec<(Range<usize>, HighlightStyle)>,
485 },
486}
487
488enum InlineCompletion {
489 Edit(Vec<(Range<Anchor>, String)>),
490 Move(Anchor),
491}
492
493struct InlineCompletionState {
494 inlay_ids: Vec<InlayId>,
495 completion: InlineCompletion,
496 invalidation_range: Range<Anchor>,
497}
498
499enum InlineCompletionHighlight {}
500
501#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
502struct EditorActionId(usize);
503
504impl EditorActionId {
505 pub fn post_inc(&mut self) -> Self {
506 let answer = self.0;
507
508 *self = Self(answer + 1);
509
510 Self(answer)
511 }
512}
513
514// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
515// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
516
517type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
518type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
519
520#[derive(Default)]
521struct ScrollbarMarkerState {
522 scrollbar_size: Size<Pixels>,
523 dirty: bool,
524 markers: Arc<[PaintQuad]>,
525 pending_refresh: Option<Task<Result<()>>>,
526}
527
528impl ScrollbarMarkerState {
529 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
530 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
531 }
532}
533
534#[derive(Clone, Debug)]
535struct RunnableTasks {
536 templates: Vec<(TaskSourceKind, TaskTemplate)>,
537 offset: MultiBufferOffset,
538 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
539 column: u32,
540 // Values of all named captures, including those starting with '_'
541 extra_variables: HashMap<String, String>,
542 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
543 context_range: Range<BufferOffset>,
544}
545
546impl RunnableTasks {
547 fn resolve<'a>(
548 &'a self,
549 cx: &'a task::TaskContext,
550 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
551 self.templates.iter().filter_map(|(kind, template)| {
552 template
553 .resolve_task(&kind.to_id_base(), cx)
554 .map(|task| (kind.clone(), task))
555 })
556 }
557}
558
559#[derive(Clone)]
560struct ResolvedTasks {
561 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
562 position: Anchor,
563}
564#[derive(Copy, Clone, Debug)]
565struct MultiBufferOffset(usize);
566#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
567struct BufferOffset(usize);
568
569// Addons allow storing per-editor state in other crates (e.g. Vim)
570pub trait Addon: 'static {
571 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
572
573 fn to_any(&self) -> &dyn std::any::Any;
574}
575
576#[derive(Debug, Copy, Clone, PartialEq, Eq)]
577pub enum IsVimMode {
578 Yes,
579 No,
580}
581
582/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
583///
584/// See the [module level documentation](self) for more information.
585pub struct Editor {
586 focus_handle: FocusHandle,
587 last_focused_descendant: Option<WeakFocusHandle>,
588 /// The text buffer being edited
589 buffer: Model<MultiBuffer>,
590 /// Map of how text in the buffer should be displayed.
591 /// Handles soft wraps, folds, fake inlay text insertions, etc.
592 pub display_map: Model<DisplayMap>,
593 pub selections: SelectionsCollection,
594 pub scroll_manager: ScrollManager,
595 /// When inline assist editors are linked, they all render cursors because
596 /// typing enters text into each of them, even the ones that aren't focused.
597 pub(crate) show_cursor_when_unfocused: bool,
598 columnar_selection_tail: Option<Anchor>,
599 add_selections_state: Option<AddSelectionsState>,
600 select_next_state: Option<SelectNextState>,
601 select_prev_state: Option<SelectNextState>,
602 selection_history: SelectionHistory,
603 autoclose_regions: Vec<AutocloseRegion>,
604 snippet_stack: InvalidationStack<SnippetState>,
605 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
606 ime_transaction: Option<TransactionId>,
607 active_diagnostics: Option<ActiveDiagnosticGroup>,
608 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
609
610 project: Option<Model<Project>>,
611 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
612 completion_provider: Option<Box<dyn CompletionProvider>>,
613 collaboration_hub: Option<Box<dyn CollaborationHub>>,
614 blink_manager: Model<BlinkManager>,
615 show_cursor_names: bool,
616 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
617 pub show_local_selections: bool,
618 mode: EditorMode,
619 show_breadcrumbs: bool,
620 show_gutter: bool,
621 show_scrollbars: bool,
622 show_line_numbers: Option<bool>,
623 use_relative_line_numbers: Option<bool>,
624 show_git_diff_gutter: Option<bool>,
625 show_code_actions: Option<bool>,
626 show_runnables: Option<bool>,
627 show_wrap_guides: Option<bool>,
628 show_indent_guides: Option<bool>,
629 placeholder_text: Option<Arc<str>>,
630 highlight_order: usize,
631 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
632 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
633 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
634 scrollbar_marker_state: ScrollbarMarkerState,
635 active_indent_guides_state: ActiveIndentGuidesState,
636 nav_history: Option<ItemNavHistory>,
637 context_menu: RefCell<Option<CodeContextMenu>>,
638 mouse_context_menu: Option<MouseContextMenu>,
639 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
640 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
641 signature_help_state: SignatureHelpState,
642 auto_signature_help: Option<bool>,
643 find_all_references_task_sources: Vec<Anchor>,
644 next_completion_id: CompletionId,
645 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
646 code_actions_task: Option<Task<Result<()>>>,
647 document_highlights_task: Option<Task<()>>,
648 linked_editing_range_task: Option<Task<Option<()>>>,
649 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
650 pending_rename: Option<RenameState>,
651 searchable: bool,
652 cursor_shape: CursorShape,
653 current_line_highlight: Option<CurrentLineHighlight>,
654 collapse_matches: bool,
655 autoindent_mode: Option<AutoindentMode>,
656 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
657 input_enabled: bool,
658 use_modal_editing: bool,
659 read_only: bool,
660 leader_peer_id: Option<PeerId>,
661 remote_id: Option<ViewId>,
662 hover_state: HoverState,
663 gutter_hovered: bool,
664 hovered_link_state: Option<HoveredLinkState>,
665 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
666 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
667 active_inline_completion: Option<InlineCompletionState>,
668 // enable_inline_completions is a switch that Vim can use to disable
669 // inline completions based on its mode.
670 enable_inline_completions: bool,
671 show_inline_completions_override: Option<bool>,
672 inlay_hint_cache: InlayHintCache,
673 diff_map: DiffMap,
674 next_inlay_id: usize,
675 _subscriptions: Vec<Subscription>,
676 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
677 gutter_dimensions: GutterDimensions,
678 style: Option<EditorStyle>,
679 text_style_refinement: Option<TextStyleRefinement>,
680 next_editor_action_id: EditorActionId,
681 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
682 use_autoclose: bool,
683 use_auto_surround: bool,
684 auto_replace_emoji_shortcode: bool,
685 show_git_blame_gutter: bool,
686 show_git_blame_inline: bool,
687 show_git_blame_inline_delay_task: Option<Task<()>>,
688 git_blame_inline_enabled: bool,
689 serialize_dirty_buffers: bool,
690 show_selection_menu: Option<bool>,
691 blame: Option<Model<GitBlame>>,
692 blame_subscription: Option<Subscription>,
693 custom_context_menu: Option<
694 Box<
695 dyn 'static
696 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
697 >,
698 >,
699 last_bounds: Option<Bounds<Pixels>>,
700 expect_bounds_change: Option<Bounds<Pixels>>,
701 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
702 tasks_update_task: Option<Task<()>>,
703 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
704 breadcrumb_header: Option<String>,
705 focused_block: Option<FocusedBlock>,
706 next_scroll_position: NextScrollCursorCenterTopBottom,
707 addons: HashMap<TypeId, Box<dyn Addon>>,
708 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
709 toggle_fold_multiple_buffers: Task<()>,
710 _scroll_cursor_center_top_bottom_task: Task<()>,
711}
712
713#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
714enum NextScrollCursorCenterTopBottom {
715 #[default]
716 Center,
717 Top,
718 Bottom,
719}
720
721impl NextScrollCursorCenterTopBottom {
722 fn next(&self) -> Self {
723 match self {
724 Self::Center => Self::Top,
725 Self::Top => Self::Bottom,
726 Self::Bottom => Self::Center,
727 }
728 }
729}
730
731#[derive(Clone)]
732pub struct EditorSnapshot {
733 pub mode: EditorMode,
734 show_gutter: bool,
735 show_line_numbers: Option<bool>,
736 show_git_diff_gutter: Option<bool>,
737 show_code_actions: Option<bool>,
738 show_runnables: Option<bool>,
739 git_blame_gutter_max_author_length: Option<usize>,
740 pub display_snapshot: DisplaySnapshot,
741 pub placeholder_text: Option<Arc<str>>,
742 diff_map: DiffMapSnapshot,
743 is_focused: bool,
744 scroll_anchor: ScrollAnchor,
745 ongoing_scroll: OngoingScroll,
746 current_line_highlight: CurrentLineHighlight,
747 gutter_hovered: bool,
748}
749
750const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
751
752#[derive(Default, Debug, Clone, Copy)]
753pub struct GutterDimensions {
754 pub left_padding: Pixels,
755 pub right_padding: Pixels,
756 pub width: Pixels,
757 pub margin: Pixels,
758 pub git_blame_entries_width: Option<Pixels>,
759}
760
761impl GutterDimensions {
762 /// The full width of the space taken up by the gutter.
763 pub fn full_width(&self) -> Pixels {
764 self.margin + self.width
765 }
766
767 /// The width of the space reserved for the fold indicators,
768 /// use alongside 'justify_end' and `gutter_width` to
769 /// right align content with the line numbers
770 pub fn fold_area_width(&self) -> Pixels {
771 self.margin + self.right_padding
772 }
773}
774
775#[derive(Debug)]
776pub struct RemoteSelection {
777 pub replica_id: ReplicaId,
778 pub selection: Selection<Anchor>,
779 pub cursor_shape: CursorShape,
780 pub peer_id: PeerId,
781 pub line_mode: bool,
782 pub participant_index: Option<ParticipantIndex>,
783 pub user_name: Option<SharedString>,
784}
785
786#[derive(Clone, Debug)]
787struct SelectionHistoryEntry {
788 selections: Arc<[Selection<Anchor>]>,
789 select_next_state: Option<SelectNextState>,
790 select_prev_state: Option<SelectNextState>,
791 add_selections_state: Option<AddSelectionsState>,
792}
793
794enum SelectionHistoryMode {
795 Normal,
796 Undoing,
797 Redoing,
798}
799
800#[derive(Clone, PartialEq, Eq, Hash)]
801struct HoveredCursor {
802 replica_id: u16,
803 selection_id: usize,
804}
805
806impl Default for SelectionHistoryMode {
807 fn default() -> Self {
808 Self::Normal
809 }
810}
811
812#[derive(Default)]
813struct SelectionHistory {
814 #[allow(clippy::type_complexity)]
815 selections_by_transaction:
816 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
817 mode: SelectionHistoryMode,
818 undo_stack: VecDeque<SelectionHistoryEntry>,
819 redo_stack: VecDeque<SelectionHistoryEntry>,
820}
821
822impl SelectionHistory {
823 fn insert_transaction(
824 &mut self,
825 transaction_id: TransactionId,
826 selections: Arc<[Selection<Anchor>]>,
827 ) {
828 self.selections_by_transaction
829 .insert(transaction_id, (selections, None));
830 }
831
832 #[allow(clippy::type_complexity)]
833 fn transaction(
834 &self,
835 transaction_id: TransactionId,
836 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
837 self.selections_by_transaction.get(&transaction_id)
838 }
839
840 #[allow(clippy::type_complexity)]
841 fn transaction_mut(
842 &mut self,
843 transaction_id: TransactionId,
844 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
845 self.selections_by_transaction.get_mut(&transaction_id)
846 }
847
848 fn push(&mut self, entry: SelectionHistoryEntry) {
849 if !entry.selections.is_empty() {
850 match self.mode {
851 SelectionHistoryMode::Normal => {
852 self.push_undo(entry);
853 self.redo_stack.clear();
854 }
855 SelectionHistoryMode::Undoing => self.push_redo(entry),
856 SelectionHistoryMode::Redoing => self.push_undo(entry),
857 }
858 }
859 }
860
861 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
862 if self
863 .undo_stack
864 .back()
865 .map_or(true, |e| e.selections != entry.selections)
866 {
867 self.undo_stack.push_back(entry);
868 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
869 self.undo_stack.pop_front();
870 }
871 }
872 }
873
874 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
875 if self
876 .redo_stack
877 .back()
878 .map_or(true, |e| e.selections != entry.selections)
879 {
880 self.redo_stack.push_back(entry);
881 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
882 self.redo_stack.pop_front();
883 }
884 }
885 }
886}
887
888struct RowHighlight {
889 index: usize,
890 range: Range<Anchor>,
891 color: Hsla,
892 should_autoscroll: bool,
893}
894
895#[derive(Clone, Debug)]
896struct AddSelectionsState {
897 above: bool,
898 stack: Vec<usize>,
899}
900
901#[derive(Clone)]
902struct SelectNextState {
903 query: AhoCorasick,
904 wordwise: bool,
905 done: bool,
906}
907
908impl std::fmt::Debug for SelectNextState {
909 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
910 f.debug_struct(std::any::type_name::<Self>())
911 .field("wordwise", &self.wordwise)
912 .field("done", &self.done)
913 .finish()
914 }
915}
916
917#[derive(Debug)]
918struct AutocloseRegion {
919 selection_id: usize,
920 range: Range<Anchor>,
921 pair: BracketPair,
922}
923
924#[derive(Debug)]
925struct SnippetState {
926 ranges: Vec<Vec<Range<Anchor>>>,
927 active_index: usize,
928 choices: Vec<Option<Vec<String>>>,
929}
930
931#[doc(hidden)]
932pub struct RenameState {
933 pub range: Range<Anchor>,
934 pub old_name: Arc<str>,
935 pub editor: View<Editor>,
936 block_id: CustomBlockId,
937}
938
939struct InvalidationStack<T>(Vec<T>);
940
941struct RegisteredInlineCompletionProvider {
942 provider: Arc<dyn InlineCompletionProviderHandle>,
943 _subscription: Subscription,
944}
945
946#[derive(Debug)]
947struct ActiveDiagnosticGroup {
948 primary_range: Range<Anchor>,
949 primary_message: String,
950 group_id: usize,
951 blocks: HashMap<CustomBlockId, Diagnostic>,
952 is_valid: bool,
953}
954
955#[derive(Serialize, Deserialize, Clone, Debug)]
956pub struct ClipboardSelection {
957 pub len: usize,
958 pub is_entire_line: bool,
959 pub first_line_indent: u32,
960}
961
962#[derive(Debug)]
963pub(crate) struct NavigationData {
964 cursor_anchor: Anchor,
965 cursor_position: Point,
966 scroll_anchor: ScrollAnchor,
967 scroll_top_row: u32,
968}
969
970#[derive(Debug, Clone, Copy, PartialEq, Eq)]
971pub enum GotoDefinitionKind {
972 Symbol,
973 Declaration,
974 Type,
975 Implementation,
976}
977
978#[derive(Debug, Clone)]
979enum InlayHintRefreshReason {
980 Toggle(bool),
981 SettingsChange(InlayHintSettings),
982 NewLinesShown,
983 BufferEdited(HashSet<Arc<Language>>),
984 RefreshRequested,
985 ExcerptsRemoved(Vec<ExcerptId>),
986}
987
988impl InlayHintRefreshReason {
989 fn description(&self) -> &'static str {
990 match self {
991 Self::Toggle(_) => "toggle",
992 Self::SettingsChange(_) => "settings change",
993 Self::NewLinesShown => "new lines shown",
994 Self::BufferEdited(_) => "buffer edited",
995 Self::RefreshRequested => "refresh requested",
996 Self::ExcerptsRemoved(_) => "excerpts removed",
997 }
998 }
999}
1000
1001pub enum FormatTarget {
1002 Buffers,
1003 Ranges(Vec<Range<MultiBufferPoint>>),
1004}
1005
1006pub(crate) struct FocusedBlock {
1007 id: BlockId,
1008 focus_handle: WeakFocusHandle,
1009}
1010
1011#[derive(Clone)]
1012enum JumpData {
1013 MultiBufferRow {
1014 row: MultiBufferRow,
1015 line_offset_from_top: u32,
1016 },
1017 MultiBufferPoint {
1018 excerpt_id: ExcerptId,
1019 position: Point,
1020 anchor: text::Anchor,
1021 line_offset_from_top: u32,
1022 },
1023}
1024
1025impl Editor {
1026 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1027 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1028 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1029 Self::new(
1030 EditorMode::SingleLine { auto_width: false },
1031 buffer,
1032 None,
1033 false,
1034 cx,
1035 )
1036 }
1037
1038 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1039 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1040 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1041 Self::new(EditorMode::Full, buffer, None, false, cx)
1042 }
1043
1044 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1045 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1046 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1047 Self::new(
1048 EditorMode::SingleLine { auto_width: true },
1049 buffer,
1050 None,
1051 false,
1052 cx,
1053 )
1054 }
1055
1056 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1057 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1058 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1059 Self::new(
1060 EditorMode::AutoHeight { max_lines },
1061 buffer,
1062 None,
1063 false,
1064 cx,
1065 )
1066 }
1067
1068 pub fn for_buffer(
1069 buffer: Model<Buffer>,
1070 project: Option<Model<Project>>,
1071 cx: &mut ViewContext<Self>,
1072 ) -> Self {
1073 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1074 Self::new(EditorMode::Full, buffer, project, false, cx)
1075 }
1076
1077 pub fn for_multibuffer(
1078 buffer: Model<MultiBuffer>,
1079 project: Option<Model<Project>>,
1080 show_excerpt_controls: bool,
1081 cx: &mut ViewContext<Self>,
1082 ) -> Self {
1083 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1084 }
1085
1086 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1087 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1088 let mut clone = Self::new(
1089 self.mode,
1090 self.buffer.clone(),
1091 self.project.clone(),
1092 show_excerpt_controls,
1093 cx,
1094 );
1095 self.display_map.update(cx, |display_map, cx| {
1096 let snapshot = display_map.snapshot(cx);
1097 clone.display_map.update(cx, |display_map, cx| {
1098 display_map.set_state(&snapshot, cx);
1099 });
1100 });
1101 clone.selections.clone_state(&self.selections);
1102 clone.scroll_manager.clone_state(&self.scroll_manager);
1103 clone.searchable = self.searchable;
1104 clone
1105 }
1106
1107 pub fn new(
1108 mode: EditorMode,
1109 buffer: Model<MultiBuffer>,
1110 project: Option<Model<Project>>,
1111 show_excerpt_controls: bool,
1112 cx: &mut ViewContext<Self>,
1113 ) -> Self {
1114 let style = cx.text_style();
1115 let font_size = style.font_size.to_pixels(cx.rem_size());
1116 let editor = cx.view().downgrade();
1117 let fold_placeholder = FoldPlaceholder {
1118 constrain_width: true,
1119 render: Arc::new(move |fold_id, fold_range, cx| {
1120 let editor = editor.clone();
1121 div()
1122 .id(fold_id)
1123 .bg(cx.theme().colors().ghost_element_background)
1124 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1125 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1126 .rounded_sm()
1127 .size_full()
1128 .cursor_pointer()
1129 .child("⋯")
1130 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1131 .on_click(move |_, cx| {
1132 editor
1133 .update(cx, |editor, cx| {
1134 editor.unfold_ranges(
1135 &[fold_range.start..fold_range.end],
1136 true,
1137 false,
1138 cx,
1139 );
1140 cx.stop_propagation();
1141 })
1142 .ok();
1143 })
1144 .into_any()
1145 }),
1146 merge_adjacent: true,
1147 ..Default::default()
1148 };
1149 let display_map = cx.new_model(|cx| {
1150 DisplayMap::new(
1151 buffer.clone(),
1152 style.font(),
1153 font_size,
1154 None,
1155 show_excerpt_controls,
1156 FILE_HEADER_HEIGHT,
1157 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1158 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1159 fold_placeholder,
1160 cx,
1161 )
1162 });
1163
1164 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1165
1166 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1167
1168 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1169 .then(|| language_settings::SoftWrap::None);
1170
1171 let mut project_subscriptions = Vec::new();
1172 if mode == EditorMode::Full {
1173 if let Some(project) = project.as_ref() {
1174 if buffer.read(cx).is_singleton() {
1175 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1176 cx.emit(EditorEvent::TitleChanged);
1177 }));
1178 }
1179 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1180 if let project::Event::RefreshInlayHints = event {
1181 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1182 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1183 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1184 let focus_handle = editor.focus_handle(cx);
1185 if focus_handle.is_focused(cx) {
1186 let snapshot = buffer.read(cx).snapshot();
1187 for (range, snippet) in snippet_edits {
1188 let editor_range =
1189 language::range_from_lsp(*range).to_offset(&snapshot);
1190 editor
1191 .insert_snippet(&[editor_range], snippet.clone(), cx)
1192 .ok();
1193 }
1194 }
1195 }
1196 }
1197 }));
1198 if let Some(task_inventory) = project
1199 .read(cx)
1200 .task_store()
1201 .read(cx)
1202 .task_inventory()
1203 .cloned()
1204 {
1205 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1206 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1207 }));
1208 }
1209 }
1210 }
1211
1212 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1213
1214 let inlay_hint_settings =
1215 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1216 let focus_handle = cx.focus_handle();
1217 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1218 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1219 .detach();
1220 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1221 .detach();
1222 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1223
1224 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1225 Some(false)
1226 } else {
1227 None
1228 };
1229
1230 let mut code_action_providers = Vec::new();
1231 if let Some(project) = project.clone() {
1232 get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
1233 code_action_providers.push(Rc::new(project) as Rc<_>);
1234 }
1235
1236 let mut this = Self {
1237 focus_handle,
1238 show_cursor_when_unfocused: false,
1239 last_focused_descendant: None,
1240 buffer: buffer.clone(),
1241 display_map: display_map.clone(),
1242 selections,
1243 scroll_manager: ScrollManager::new(cx),
1244 columnar_selection_tail: None,
1245 add_selections_state: None,
1246 select_next_state: None,
1247 select_prev_state: None,
1248 selection_history: Default::default(),
1249 autoclose_regions: Default::default(),
1250 snippet_stack: Default::default(),
1251 select_larger_syntax_node_stack: Vec::new(),
1252 ime_transaction: Default::default(),
1253 active_diagnostics: None,
1254 soft_wrap_mode_override,
1255 completion_provider: project.clone().map(|project| Box::new(project) as _),
1256 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1257 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1258 project,
1259 blink_manager: blink_manager.clone(),
1260 show_local_selections: true,
1261 show_scrollbars: true,
1262 mode,
1263 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1264 show_gutter: mode == EditorMode::Full,
1265 show_line_numbers: None,
1266 use_relative_line_numbers: None,
1267 show_git_diff_gutter: None,
1268 show_code_actions: None,
1269 show_runnables: None,
1270 show_wrap_guides: None,
1271 show_indent_guides,
1272 placeholder_text: None,
1273 highlight_order: 0,
1274 highlighted_rows: HashMap::default(),
1275 background_highlights: Default::default(),
1276 gutter_highlights: TreeMap::default(),
1277 scrollbar_marker_state: ScrollbarMarkerState::default(),
1278 active_indent_guides_state: ActiveIndentGuidesState::default(),
1279 nav_history: None,
1280 context_menu: RefCell::new(None),
1281 mouse_context_menu: None,
1282 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1283 completion_tasks: Default::default(),
1284 signature_help_state: SignatureHelpState::default(),
1285 auto_signature_help: None,
1286 find_all_references_task_sources: Vec::new(),
1287 next_completion_id: 0,
1288 next_inlay_id: 0,
1289 code_action_providers,
1290 available_code_actions: Default::default(),
1291 code_actions_task: Default::default(),
1292 document_highlights_task: Default::default(),
1293 linked_editing_range_task: Default::default(),
1294 pending_rename: Default::default(),
1295 searchable: true,
1296 cursor_shape: EditorSettings::get_global(cx)
1297 .cursor_shape
1298 .unwrap_or_default(),
1299 current_line_highlight: None,
1300 autoindent_mode: Some(AutoindentMode::EachLine),
1301 collapse_matches: false,
1302 workspace: None,
1303 input_enabled: true,
1304 use_modal_editing: mode == EditorMode::Full,
1305 read_only: false,
1306 use_autoclose: true,
1307 use_auto_surround: true,
1308 auto_replace_emoji_shortcode: false,
1309 leader_peer_id: None,
1310 remote_id: None,
1311 hover_state: Default::default(),
1312 hovered_link_state: Default::default(),
1313 inline_completion_provider: None,
1314 active_inline_completion: None,
1315 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1316 diff_map: DiffMap::default(),
1317 gutter_hovered: false,
1318 pixel_position_of_newest_cursor: None,
1319 last_bounds: None,
1320 expect_bounds_change: None,
1321 gutter_dimensions: GutterDimensions::default(),
1322 style: None,
1323 show_cursor_names: false,
1324 hovered_cursors: Default::default(),
1325 next_editor_action_id: EditorActionId::default(),
1326 editor_actions: Rc::default(),
1327 show_inline_completions_override: None,
1328 enable_inline_completions: true,
1329 custom_context_menu: None,
1330 show_git_blame_gutter: false,
1331 show_git_blame_inline: false,
1332 show_selection_menu: None,
1333 show_git_blame_inline_delay_task: None,
1334 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1335 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1336 .session
1337 .restore_unsaved_buffers,
1338 blame: None,
1339 blame_subscription: None,
1340 tasks: Default::default(),
1341 _subscriptions: vec![
1342 cx.observe(&buffer, Self::on_buffer_changed),
1343 cx.subscribe(&buffer, Self::on_buffer_event),
1344 cx.observe(&display_map, Self::on_display_map_changed),
1345 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1346 cx.observe_global::<SettingsStore>(Self::settings_changed),
1347 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1348 cx.observe_window_activation(|editor, cx| {
1349 let active = cx.is_window_active();
1350 editor.blink_manager.update(cx, |blink_manager, cx| {
1351 if active {
1352 blink_manager.enable(cx);
1353 } else {
1354 blink_manager.disable(cx);
1355 }
1356 });
1357 }),
1358 ],
1359 tasks_update_task: None,
1360 linked_edit_ranges: Default::default(),
1361 previous_search_ranges: None,
1362 breadcrumb_header: None,
1363 focused_block: None,
1364 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1365 addons: HashMap::default(),
1366 registered_buffers: HashMap::default(),
1367 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1368 toggle_fold_multiple_buffers: Task::ready(()),
1369 text_style_refinement: None,
1370 };
1371 this.tasks_update_task = Some(this.refresh_runnables(cx));
1372 this._subscriptions.extend(project_subscriptions);
1373
1374 this.end_selection(cx);
1375 this.scroll_manager.show_scrollbar(cx);
1376
1377 if mode == EditorMode::Full {
1378 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1379 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1380
1381 if this.git_blame_inline_enabled {
1382 this.git_blame_inline_enabled = true;
1383 this.start_git_blame_inline(false, cx);
1384 }
1385
1386 if let Some(buffer) = buffer.read(cx).as_singleton() {
1387 if let Some(project) = this.project.as_ref() {
1388 let lsp_store = project.read(cx).lsp_store();
1389 let handle = lsp_store.update(cx, |lsp_store, cx| {
1390 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1391 });
1392 this.registered_buffers
1393 .insert(buffer.read(cx).remote_id(), handle);
1394 }
1395 }
1396 }
1397
1398 this.report_editor_event("Editor Opened", None, cx);
1399 this
1400 }
1401
1402 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
1403 self.mouse_context_menu
1404 .as_ref()
1405 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1406 }
1407
1408 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
1409 let mut key_context = KeyContext::new_with_defaults();
1410 key_context.add("Editor");
1411 let mode = match self.mode {
1412 EditorMode::SingleLine { .. } => "single_line",
1413 EditorMode::AutoHeight { .. } => "auto_height",
1414 EditorMode::Full => "full",
1415 };
1416
1417 if EditorSettings::jupyter_enabled(cx) {
1418 key_context.add("jupyter");
1419 }
1420
1421 key_context.set("mode", mode);
1422 if self.pending_rename.is_some() {
1423 key_context.add("renaming");
1424 }
1425 match self.context_menu.borrow().as_ref() {
1426 Some(CodeContextMenu::Completions(_)) => {
1427 key_context.add("menu");
1428 key_context.add("showing_completions")
1429 }
1430 Some(CodeContextMenu::CodeActions(_)) => {
1431 key_context.add("menu");
1432 key_context.add("showing_code_actions")
1433 }
1434 None => {}
1435 }
1436
1437 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1438 if !self.focus_handle(cx).contains_focused(cx)
1439 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
1440 {
1441 for addon in self.addons.values() {
1442 addon.extend_key_context(&mut key_context, cx)
1443 }
1444 }
1445
1446 if let Some(extension) = self
1447 .buffer
1448 .read(cx)
1449 .as_singleton()
1450 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1451 {
1452 key_context.set("extension", extension.to_string());
1453 }
1454
1455 if self.has_active_inline_completion() {
1456 key_context.add("copilot_suggestion");
1457 key_context.add("inline_completion");
1458 }
1459
1460 if !self
1461 .selections
1462 .disjoint
1463 .iter()
1464 .all(|selection| selection.start == selection.end)
1465 {
1466 key_context.add("selection");
1467 }
1468
1469 key_context
1470 }
1471
1472 pub fn new_file(
1473 workspace: &mut Workspace,
1474 _: &workspace::NewFile,
1475 cx: &mut ViewContext<Workspace>,
1476 ) {
1477 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
1478 "Failed to create buffer",
1479 cx,
1480 |e, _| match e.error_code() {
1481 ErrorCode::RemoteUpgradeRequired => Some(format!(
1482 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1483 e.error_tag("required").unwrap_or("the latest version")
1484 )),
1485 _ => None,
1486 },
1487 );
1488 }
1489
1490 pub fn new_in_workspace(
1491 workspace: &mut Workspace,
1492 cx: &mut ViewContext<Workspace>,
1493 ) -> Task<Result<View<Editor>>> {
1494 let project = workspace.project().clone();
1495 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1496
1497 cx.spawn(|workspace, mut cx| async move {
1498 let buffer = create.await?;
1499 workspace.update(&mut cx, |workspace, cx| {
1500 let editor =
1501 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
1502 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
1503 editor
1504 })
1505 })
1506 }
1507
1508 fn new_file_vertical(
1509 workspace: &mut Workspace,
1510 _: &workspace::NewFileSplitVertical,
1511 cx: &mut ViewContext<Workspace>,
1512 ) {
1513 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
1514 }
1515
1516 fn new_file_horizontal(
1517 workspace: &mut Workspace,
1518 _: &workspace::NewFileSplitHorizontal,
1519 cx: &mut ViewContext<Workspace>,
1520 ) {
1521 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
1522 }
1523
1524 fn new_file_in_direction(
1525 workspace: &mut Workspace,
1526 direction: SplitDirection,
1527 cx: &mut ViewContext<Workspace>,
1528 ) {
1529 let project = workspace.project().clone();
1530 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1531
1532 cx.spawn(|workspace, mut cx| async move {
1533 let buffer = create.await?;
1534 workspace.update(&mut cx, move |workspace, cx| {
1535 workspace.split_item(
1536 direction,
1537 Box::new(
1538 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
1539 ),
1540 cx,
1541 )
1542 })?;
1543 anyhow::Ok(())
1544 })
1545 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
1546 ErrorCode::RemoteUpgradeRequired => Some(format!(
1547 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1548 e.error_tag("required").unwrap_or("the latest version")
1549 )),
1550 _ => None,
1551 });
1552 }
1553
1554 pub fn leader_peer_id(&self) -> Option<PeerId> {
1555 self.leader_peer_id
1556 }
1557
1558 pub fn buffer(&self) -> &Model<MultiBuffer> {
1559 &self.buffer
1560 }
1561
1562 pub fn workspace(&self) -> Option<View<Workspace>> {
1563 self.workspace.as_ref()?.0.upgrade()
1564 }
1565
1566 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
1567 self.buffer().read(cx).title(cx)
1568 }
1569
1570 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
1571 let git_blame_gutter_max_author_length = self
1572 .render_git_blame_gutter(cx)
1573 .then(|| {
1574 if let Some(blame) = self.blame.as_ref() {
1575 let max_author_length =
1576 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1577 Some(max_author_length)
1578 } else {
1579 None
1580 }
1581 })
1582 .flatten();
1583
1584 EditorSnapshot {
1585 mode: self.mode,
1586 show_gutter: self.show_gutter,
1587 show_line_numbers: self.show_line_numbers,
1588 show_git_diff_gutter: self.show_git_diff_gutter,
1589 show_code_actions: self.show_code_actions,
1590 show_runnables: self.show_runnables,
1591 git_blame_gutter_max_author_length,
1592 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1593 scroll_anchor: self.scroll_manager.anchor(),
1594 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1595 placeholder_text: self.placeholder_text.clone(),
1596 diff_map: self.diff_map.snapshot(),
1597 is_focused: self.focus_handle.is_focused(cx),
1598 current_line_highlight: self
1599 .current_line_highlight
1600 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1601 gutter_hovered: self.gutter_hovered,
1602 }
1603 }
1604
1605 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
1606 self.buffer.read(cx).language_at(point, cx)
1607 }
1608
1609 pub fn file_at<T: ToOffset>(
1610 &self,
1611 point: T,
1612 cx: &AppContext,
1613 ) -> Option<Arc<dyn language::File>> {
1614 self.buffer.read(cx).read(cx).file_at(point).cloned()
1615 }
1616
1617 pub fn active_excerpt(
1618 &self,
1619 cx: &AppContext,
1620 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
1621 self.buffer
1622 .read(cx)
1623 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1624 }
1625
1626 pub fn mode(&self) -> EditorMode {
1627 self.mode
1628 }
1629
1630 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1631 self.collaboration_hub.as_deref()
1632 }
1633
1634 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1635 self.collaboration_hub = Some(hub);
1636 }
1637
1638 pub fn set_custom_context_menu(
1639 &mut self,
1640 f: impl 'static
1641 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
1642 ) {
1643 self.custom_context_menu = Some(Box::new(f))
1644 }
1645
1646 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1647 self.completion_provider = provider;
1648 }
1649
1650 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1651 self.semantics_provider.clone()
1652 }
1653
1654 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1655 self.semantics_provider = provider;
1656 }
1657
1658 pub fn set_inline_completion_provider<T>(
1659 &mut self,
1660 provider: Option<Model<T>>,
1661 cx: &mut ViewContext<Self>,
1662 ) where
1663 T: InlineCompletionProvider,
1664 {
1665 self.inline_completion_provider =
1666 provider.map(|provider| RegisteredInlineCompletionProvider {
1667 _subscription: cx.observe(&provider, |this, _, cx| {
1668 if this.focus_handle.is_focused(cx) {
1669 this.update_visible_inline_completion(cx);
1670 }
1671 }),
1672 provider: Arc::new(provider),
1673 });
1674 self.refresh_inline_completion(false, false, cx);
1675 }
1676
1677 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
1678 self.placeholder_text.as_deref()
1679 }
1680
1681 pub fn set_placeholder_text(
1682 &mut self,
1683 placeholder_text: impl Into<Arc<str>>,
1684 cx: &mut ViewContext<Self>,
1685 ) {
1686 let placeholder_text = Some(placeholder_text.into());
1687 if self.placeholder_text != placeholder_text {
1688 self.placeholder_text = placeholder_text;
1689 cx.notify();
1690 }
1691 }
1692
1693 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
1694 self.cursor_shape = cursor_shape;
1695
1696 // Disrupt blink for immediate user feedback that the cursor shape has changed
1697 self.blink_manager.update(cx, BlinkManager::show_cursor);
1698
1699 cx.notify();
1700 }
1701
1702 pub fn set_current_line_highlight(
1703 &mut self,
1704 current_line_highlight: Option<CurrentLineHighlight>,
1705 ) {
1706 self.current_line_highlight = current_line_highlight;
1707 }
1708
1709 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1710 self.collapse_matches = collapse_matches;
1711 }
1712
1713 pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
1714 let buffers = self.buffer.read(cx).all_buffers();
1715 let Some(lsp_store) = self.lsp_store(cx) else {
1716 return;
1717 };
1718 lsp_store.update(cx, |lsp_store, cx| {
1719 for buffer in buffers {
1720 self.registered_buffers
1721 .entry(buffer.read(cx).remote_id())
1722 .or_insert_with(|| {
1723 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1724 });
1725 }
1726 })
1727 }
1728
1729 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1730 if self.collapse_matches {
1731 return range.start..range.start;
1732 }
1733 range.clone()
1734 }
1735
1736 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
1737 if self.display_map.read(cx).clip_at_line_ends != clip {
1738 self.display_map
1739 .update(cx, |map, _| map.clip_at_line_ends = clip);
1740 }
1741 }
1742
1743 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1744 self.input_enabled = input_enabled;
1745 }
1746
1747 pub fn set_inline_completions_enabled(&mut self, enabled: bool, cx: &mut ViewContext<Self>) {
1748 self.enable_inline_completions = enabled;
1749 if !self.enable_inline_completions {
1750 self.take_active_inline_completion(cx);
1751 cx.notify();
1752 }
1753 }
1754
1755 pub fn set_autoindent(&mut self, autoindent: bool) {
1756 if autoindent {
1757 self.autoindent_mode = Some(AutoindentMode::EachLine);
1758 } else {
1759 self.autoindent_mode = None;
1760 }
1761 }
1762
1763 pub fn read_only(&self, cx: &AppContext) -> bool {
1764 self.read_only || self.buffer.read(cx).read_only()
1765 }
1766
1767 pub fn set_read_only(&mut self, read_only: bool) {
1768 self.read_only = read_only;
1769 }
1770
1771 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1772 self.use_autoclose = autoclose;
1773 }
1774
1775 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1776 self.use_auto_surround = auto_surround;
1777 }
1778
1779 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1780 self.auto_replace_emoji_shortcode = auto_replace;
1781 }
1782
1783 pub fn toggle_inline_completions(
1784 &mut self,
1785 _: &ToggleInlineCompletions,
1786 cx: &mut ViewContext<Self>,
1787 ) {
1788 if self.show_inline_completions_override.is_some() {
1789 self.set_show_inline_completions(None, cx);
1790 } else {
1791 let cursor = self.selections.newest_anchor().head();
1792 if let Some((buffer, cursor_buffer_position)) =
1793 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1794 {
1795 let show_inline_completions =
1796 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
1797 self.set_show_inline_completions(Some(show_inline_completions), cx);
1798 }
1799 }
1800 }
1801
1802 pub fn set_show_inline_completions(
1803 &mut self,
1804 show_inline_completions: Option<bool>,
1805 cx: &mut ViewContext<Self>,
1806 ) {
1807 self.show_inline_completions_override = show_inline_completions;
1808 self.refresh_inline_completion(false, true, cx);
1809 }
1810
1811 pub fn inline_completions_enabled(&self, cx: &AppContext) -> bool {
1812 let cursor = self.selections.newest_anchor().head();
1813 if let Some((buffer, buffer_position)) =
1814 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1815 {
1816 self.should_show_inline_completions(&buffer, buffer_position, cx)
1817 } else {
1818 false
1819 }
1820 }
1821
1822 fn should_show_inline_completions(
1823 &self,
1824 buffer: &Model<Buffer>,
1825 buffer_position: language::Anchor,
1826 cx: &AppContext,
1827 ) -> bool {
1828 if !self.snippet_stack.is_empty() {
1829 return false;
1830 }
1831
1832 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
1833 return false;
1834 }
1835
1836 if let Some(provider) = self.inline_completion_provider() {
1837 if let Some(show_inline_completions) = self.show_inline_completions_override {
1838 show_inline_completions
1839 } else {
1840 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
1841 }
1842 } else {
1843 false
1844 }
1845 }
1846
1847 fn inline_completions_disabled_in_scope(
1848 &self,
1849 buffer: &Model<Buffer>,
1850 buffer_position: language::Anchor,
1851 cx: &AppContext,
1852 ) -> bool {
1853 let snapshot = buffer.read(cx).snapshot();
1854 let settings = snapshot.settings_at(buffer_position, cx);
1855
1856 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1857 return false;
1858 };
1859
1860 scope.override_name().map_or(false, |scope_name| {
1861 settings
1862 .inline_completions_disabled_in
1863 .iter()
1864 .any(|s| s == scope_name)
1865 })
1866 }
1867
1868 pub fn set_use_modal_editing(&mut self, to: bool) {
1869 self.use_modal_editing = to;
1870 }
1871
1872 pub fn use_modal_editing(&self) -> bool {
1873 self.use_modal_editing
1874 }
1875
1876 fn selections_did_change(
1877 &mut self,
1878 local: bool,
1879 old_cursor_position: &Anchor,
1880 show_completions: bool,
1881 cx: &mut ViewContext<Self>,
1882 ) {
1883 cx.invalidate_character_coordinates();
1884
1885 // Copy selections to primary selection buffer
1886 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1887 if local {
1888 let selections = self.selections.all::<usize>(cx);
1889 let buffer_handle = self.buffer.read(cx).read(cx);
1890
1891 let mut text = String::new();
1892 for (index, selection) in selections.iter().enumerate() {
1893 let text_for_selection = buffer_handle
1894 .text_for_range(selection.start..selection.end)
1895 .collect::<String>();
1896
1897 text.push_str(&text_for_selection);
1898 if index != selections.len() - 1 {
1899 text.push('\n');
1900 }
1901 }
1902
1903 if !text.is_empty() {
1904 cx.write_to_primary(ClipboardItem::new_string(text));
1905 }
1906 }
1907
1908 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
1909 self.buffer.update(cx, |buffer, cx| {
1910 buffer.set_active_selections(
1911 &self.selections.disjoint_anchors(),
1912 self.selections.line_mode,
1913 self.cursor_shape,
1914 cx,
1915 )
1916 });
1917 }
1918 let display_map = self
1919 .display_map
1920 .update(cx, |display_map, cx| display_map.snapshot(cx));
1921 let buffer = &display_map.buffer_snapshot;
1922 self.add_selections_state = None;
1923 self.select_next_state = None;
1924 self.select_prev_state = None;
1925 self.select_larger_syntax_node_stack.clear();
1926 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1927 self.snippet_stack
1928 .invalidate(&self.selections.disjoint_anchors(), buffer);
1929 self.take_rename(false, cx);
1930
1931 let new_cursor_position = self.selections.newest_anchor().head();
1932
1933 self.push_to_nav_history(
1934 *old_cursor_position,
1935 Some(new_cursor_position.to_point(buffer)),
1936 cx,
1937 );
1938
1939 if local {
1940 let new_cursor_position = self.selections.newest_anchor().head();
1941 let mut context_menu = self.context_menu.borrow_mut();
1942 let completion_menu = match context_menu.as_ref() {
1943 Some(CodeContextMenu::Completions(menu)) => Some(menu),
1944 _ => {
1945 *context_menu = None;
1946 None
1947 }
1948 };
1949
1950 if let Some(completion_menu) = completion_menu {
1951 let cursor_position = new_cursor_position.to_offset(buffer);
1952 let (word_range, kind) =
1953 buffer.surrounding_word(completion_menu.initial_position, true);
1954 if kind == Some(CharKind::Word)
1955 && word_range.to_inclusive().contains(&cursor_position)
1956 {
1957 let mut completion_menu = completion_menu.clone();
1958 drop(context_menu);
1959
1960 let query = Self::completion_query(buffer, cursor_position);
1961 cx.spawn(move |this, mut cx| async move {
1962 completion_menu
1963 .filter(query.as_deref(), cx.background_executor().clone())
1964 .await;
1965
1966 this.update(&mut cx, |this, cx| {
1967 let mut context_menu = this.context_menu.borrow_mut();
1968 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
1969 else {
1970 return;
1971 };
1972
1973 if menu.id > completion_menu.id {
1974 return;
1975 }
1976
1977 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
1978 drop(context_menu);
1979 cx.notify();
1980 })
1981 })
1982 .detach();
1983
1984 if show_completions {
1985 self.show_completions(&ShowCompletions { trigger: None }, cx);
1986 }
1987 } else {
1988 drop(context_menu);
1989 self.hide_context_menu(cx);
1990 }
1991 } else {
1992 drop(context_menu);
1993 }
1994
1995 hide_hover(self, cx);
1996
1997 if old_cursor_position.to_display_point(&display_map).row()
1998 != new_cursor_position.to_display_point(&display_map).row()
1999 {
2000 self.available_code_actions.take();
2001 }
2002 self.refresh_code_actions(cx);
2003 self.refresh_document_highlights(cx);
2004 refresh_matching_bracket_highlights(self, cx);
2005 self.update_visible_inline_completion(cx);
2006 linked_editing_ranges::refresh_linked_ranges(self, cx);
2007 if self.git_blame_inline_enabled {
2008 self.start_inline_blame_timer(cx);
2009 }
2010 }
2011
2012 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2013 cx.emit(EditorEvent::SelectionsChanged { local });
2014
2015 if self.selections.disjoint_anchors().len() == 1 {
2016 cx.emit(SearchEvent::ActiveMatchChanged)
2017 }
2018 cx.notify();
2019 }
2020
2021 pub fn change_selections<R>(
2022 &mut self,
2023 autoscroll: Option<Autoscroll>,
2024 cx: &mut ViewContext<Self>,
2025 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2026 ) -> R {
2027 self.change_selections_inner(autoscroll, true, cx, change)
2028 }
2029
2030 pub fn change_selections_inner<R>(
2031 &mut self,
2032 autoscroll: Option<Autoscroll>,
2033 request_completions: bool,
2034 cx: &mut ViewContext<Self>,
2035 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2036 ) -> R {
2037 let old_cursor_position = self.selections.newest_anchor().head();
2038 self.push_to_selection_history();
2039
2040 let (changed, result) = self.selections.change_with(cx, change);
2041
2042 if changed {
2043 if let Some(autoscroll) = autoscroll {
2044 self.request_autoscroll(autoscroll, cx);
2045 }
2046 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2047
2048 if self.should_open_signature_help_automatically(
2049 &old_cursor_position,
2050 self.signature_help_state.backspace_pressed(),
2051 cx,
2052 ) {
2053 self.show_signature_help(&ShowSignatureHelp, cx);
2054 }
2055 self.signature_help_state.set_backspace_pressed(false);
2056 }
2057
2058 result
2059 }
2060
2061 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2062 where
2063 I: IntoIterator<Item = (Range<S>, T)>,
2064 S: ToOffset,
2065 T: Into<Arc<str>>,
2066 {
2067 if self.read_only(cx) {
2068 return;
2069 }
2070
2071 self.buffer
2072 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2073 }
2074
2075 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2076 where
2077 I: IntoIterator<Item = (Range<S>, T)>,
2078 S: ToOffset,
2079 T: Into<Arc<str>>,
2080 {
2081 if self.read_only(cx) {
2082 return;
2083 }
2084
2085 self.buffer.update(cx, |buffer, cx| {
2086 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2087 });
2088 }
2089
2090 pub fn edit_with_block_indent<I, S, T>(
2091 &mut self,
2092 edits: I,
2093 original_indent_columns: Vec<u32>,
2094 cx: &mut ViewContext<Self>,
2095 ) where
2096 I: IntoIterator<Item = (Range<S>, T)>,
2097 S: ToOffset,
2098 T: Into<Arc<str>>,
2099 {
2100 if self.read_only(cx) {
2101 return;
2102 }
2103
2104 self.buffer.update(cx, |buffer, cx| {
2105 buffer.edit(
2106 edits,
2107 Some(AutoindentMode::Block {
2108 original_indent_columns,
2109 }),
2110 cx,
2111 )
2112 });
2113 }
2114
2115 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2116 self.hide_context_menu(cx);
2117
2118 match phase {
2119 SelectPhase::Begin {
2120 position,
2121 add,
2122 click_count,
2123 } => self.begin_selection(position, add, click_count, cx),
2124 SelectPhase::BeginColumnar {
2125 position,
2126 goal_column,
2127 reset,
2128 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2129 SelectPhase::Extend {
2130 position,
2131 click_count,
2132 } => self.extend_selection(position, click_count, cx),
2133 SelectPhase::Update {
2134 position,
2135 goal_column,
2136 scroll_delta,
2137 } => self.update_selection(position, goal_column, scroll_delta, cx),
2138 SelectPhase::End => self.end_selection(cx),
2139 }
2140 }
2141
2142 fn extend_selection(
2143 &mut self,
2144 position: DisplayPoint,
2145 click_count: usize,
2146 cx: &mut ViewContext<Self>,
2147 ) {
2148 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2149 let tail = self.selections.newest::<usize>(cx).tail();
2150 self.begin_selection(position, false, click_count, cx);
2151
2152 let position = position.to_offset(&display_map, Bias::Left);
2153 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2154
2155 let mut pending_selection = self
2156 .selections
2157 .pending_anchor()
2158 .expect("extend_selection not called with pending selection");
2159 if position >= tail {
2160 pending_selection.start = tail_anchor;
2161 } else {
2162 pending_selection.end = tail_anchor;
2163 pending_selection.reversed = true;
2164 }
2165
2166 let mut pending_mode = self.selections.pending_mode().unwrap();
2167 match &mut pending_mode {
2168 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2169 _ => {}
2170 }
2171
2172 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2173 s.set_pending(pending_selection, pending_mode)
2174 });
2175 }
2176
2177 fn begin_selection(
2178 &mut self,
2179 position: DisplayPoint,
2180 add: bool,
2181 click_count: usize,
2182 cx: &mut ViewContext<Self>,
2183 ) {
2184 if !self.focus_handle.is_focused(cx) {
2185 self.last_focused_descendant = None;
2186 cx.focus(&self.focus_handle);
2187 }
2188
2189 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2190 let buffer = &display_map.buffer_snapshot;
2191 let newest_selection = self.selections.newest_anchor().clone();
2192 let position = display_map.clip_point(position, Bias::Left);
2193
2194 let start;
2195 let end;
2196 let mode;
2197 let mut auto_scroll;
2198 match click_count {
2199 1 => {
2200 start = buffer.anchor_before(position.to_point(&display_map));
2201 end = start;
2202 mode = SelectMode::Character;
2203 auto_scroll = true;
2204 }
2205 2 => {
2206 let range = movement::surrounding_word(&display_map, position);
2207 start = buffer.anchor_before(range.start.to_point(&display_map));
2208 end = buffer.anchor_before(range.end.to_point(&display_map));
2209 mode = SelectMode::Word(start..end);
2210 auto_scroll = true;
2211 }
2212 3 => {
2213 let position = display_map
2214 .clip_point(position, Bias::Left)
2215 .to_point(&display_map);
2216 let line_start = display_map.prev_line_boundary(position).0;
2217 let next_line_start = buffer.clip_point(
2218 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2219 Bias::Left,
2220 );
2221 start = buffer.anchor_before(line_start);
2222 end = buffer.anchor_before(next_line_start);
2223 mode = SelectMode::Line(start..end);
2224 auto_scroll = true;
2225 }
2226 _ => {
2227 start = buffer.anchor_before(0);
2228 end = buffer.anchor_before(buffer.len());
2229 mode = SelectMode::All;
2230 auto_scroll = false;
2231 }
2232 }
2233 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2234
2235 let point_to_delete: Option<usize> = {
2236 let selected_points: Vec<Selection<Point>> =
2237 self.selections.disjoint_in_range(start..end, cx);
2238
2239 if !add || click_count > 1 {
2240 None
2241 } else if !selected_points.is_empty() {
2242 Some(selected_points[0].id)
2243 } else {
2244 let clicked_point_already_selected =
2245 self.selections.disjoint.iter().find(|selection| {
2246 selection.start.to_point(buffer) == start.to_point(buffer)
2247 || selection.end.to_point(buffer) == end.to_point(buffer)
2248 });
2249
2250 clicked_point_already_selected.map(|selection| selection.id)
2251 }
2252 };
2253
2254 let selections_count = self.selections.count();
2255
2256 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2257 if let Some(point_to_delete) = point_to_delete {
2258 s.delete(point_to_delete);
2259
2260 if selections_count == 1 {
2261 s.set_pending_anchor_range(start..end, mode);
2262 }
2263 } else {
2264 if !add {
2265 s.clear_disjoint();
2266 } else if click_count > 1 {
2267 s.delete(newest_selection.id)
2268 }
2269
2270 s.set_pending_anchor_range(start..end, mode);
2271 }
2272 });
2273 }
2274
2275 fn begin_columnar_selection(
2276 &mut self,
2277 position: DisplayPoint,
2278 goal_column: u32,
2279 reset: bool,
2280 cx: &mut ViewContext<Self>,
2281 ) {
2282 if !self.focus_handle.is_focused(cx) {
2283 self.last_focused_descendant = None;
2284 cx.focus(&self.focus_handle);
2285 }
2286
2287 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2288
2289 if reset {
2290 let pointer_position = display_map
2291 .buffer_snapshot
2292 .anchor_before(position.to_point(&display_map));
2293
2294 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2295 s.clear_disjoint();
2296 s.set_pending_anchor_range(
2297 pointer_position..pointer_position,
2298 SelectMode::Character,
2299 );
2300 });
2301 }
2302
2303 let tail = self.selections.newest::<Point>(cx).tail();
2304 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2305
2306 if !reset {
2307 self.select_columns(
2308 tail.to_display_point(&display_map),
2309 position,
2310 goal_column,
2311 &display_map,
2312 cx,
2313 );
2314 }
2315 }
2316
2317 fn update_selection(
2318 &mut self,
2319 position: DisplayPoint,
2320 goal_column: u32,
2321 scroll_delta: gpui::Point<f32>,
2322 cx: &mut ViewContext<Self>,
2323 ) {
2324 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2325
2326 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2327 let tail = tail.to_display_point(&display_map);
2328 self.select_columns(tail, position, goal_column, &display_map, cx);
2329 } else if let Some(mut pending) = self.selections.pending_anchor() {
2330 let buffer = self.buffer.read(cx).snapshot(cx);
2331 let head;
2332 let tail;
2333 let mode = self.selections.pending_mode().unwrap();
2334 match &mode {
2335 SelectMode::Character => {
2336 head = position.to_point(&display_map);
2337 tail = pending.tail().to_point(&buffer);
2338 }
2339 SelectMode::Word(original_range) => {
2340 let original_display_range = original_range.start.to_display_point(&display_map)
2341 ..original_range.end.to_display_point(&display_map);
2342 let original_buffer_range = original_display_range.start.to_point(&display_map)
2343 ..original_display_range.end.to_point(&display_map);
2344 if movement::is_inside_word(&display_map, position)
2345 || original_display_range.contains(&position)
2346 {
2347 let word_range = movement::surrounding_word(&display_map, position);
2348 if word_range.start < original_display_range.start {
2349 head = word_range.start.to_point(&display_map);
2350 } else {
2351 head = word_range.end.to_point(&display_map);
2352 }
2353 } else {
2354 head = position.to_point(&display_map);
2355 }
2356
2357 if head <= original_buffer_range.start {
2358 tail = original_buffer_range.end;
2359 } else {
2360 tail = original_buffer_range.start;
2361 }
2362 }
2363 SelectMode::Line(original_range) => {
2364 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2365
2366 let position = display_map
2367 .clip_point(position, Bias::Left)
2368 .to_point(&display_map);
2369 let line_start = display_map.prev_line_boundary(position).0;
2370 let next_line_start = buffer.clip_point(
2371 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2372 Bias::Left,
2373 );
2374
2375 if line_start < original_range.start {
2376 head = line_start
2377 } else {
2378 head = next_line_start
2379 }
2380
2381 if head <= original_range.start {
2382 tail = original_range.end;
2383 } else {
2384 tail = original_range.start;
2385 }
2386 }
2387 SelectMode::All => {
2388 return;
2389 }
2390 };
2391
2392 if head < tail {
2393 pending.start = buffer.anchor_before(head);
2394 pending.end = buffer.anchor_before(tail);
2395 pending.reversed = true;
2396 } else {
2397 pending.start = buffer.anchor_before(tail);
2398 pending.end = buffer.anchor_before(head);
2399 pending.reversed = false;
2400 }
2401
2402 self.change_selections(None, cx, |s| {
2403 s.set_pending(pending, mode);
2404 });
2405 } else {
2406 log::error!("update_selection dispatched with no pending selection");
2407 return;
2408 }
2409
2410 self.apply_scroll_delta(scroll_delta, cx);
2411 cx.notify();
2412 }
2413
2414 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2415 self.columnar_selection_tail.take();
2416 if self.selections.pending_anchor().is_some() {
2417 let selections = self.selections.all::<usize>(cx);
2418 self.change_selections(None, cx, |s| {
2419 s.select(selections);
2420 s.clear_pending();
2421 });
2422 }
2423 }
2424
2425 fn select_columns(
2426 &mut self,
2427 tail: DisplayPoint,
2428 head: DisplayPoint,
2429 goal_column: u32,
2430 display_map: &DisplaySnapshot,
2431 cx: &mut ViewContext<Self>,
2432 ) {
2433 let start_row = cmp::min(tail.row(), head.row());
2434 let end_row = cmp::max(tail.row(), head.row());
2435 let start_column = cmp::min(tail.column(), goal_column);
2436 let end_column = cmp::max(tail.column(), goal_column);
2437 let reversed = start_column < tail.column();
2438
2439 let selection_ranges = (start_row.0..=end_row.0)
2440 .map(DisplayRow)
2441 .filter_map(|row| {
2442 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2443 let start = display_map
2444 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2445 .to_point(display_map);
2446 let end = display_map
2447 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2448 .to_point(display_map);
2449 if reversed {
2450 Some(end..start)
2451 } else {
2452 Some(start..end)
2453 }
2454 } else {
2455 None
2456 }
2457 })
2458 .collect::<Vec<_>>();
2459
2460 self.change_selections(None, cx, |s| {
2461 s.select_ranges(selection_ranges);
2462 });
2463 cx.notify();
2464 }
2465
2466 pub fn has_pending_nonempty_selection(&self) -> bool {
2467 let pending_nonempty_selection = match self.selections.pending_anchor() {
2468 Some(Selection { start, end, .. }) => start != end,
2469 None => false,
2470 };
2471
2472 pending_nonempty_selection
2473 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2474 }
2475
2476 pub fn has_pending_selection(&self) -> bool {
2477 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2478 }
2479
2480 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2481 if self.clear_expanded_diff_hunks(cx) {
2482 cx.notify();
2483 return;
2484 }
2485 if self.dismiss_menus_and_popups(true, cx) {
2486 return;
2487 }
2488
2489 if self.mode == EditorMode::Full
2490 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
2491 {
2492 return;
2493 }
2494
2495 cx.propagate();
2496 }
2497
2498 pub fn dismiss_menus_and_popups(
2499 &mut self,
2500 should_report_inline_completion_event: bool,
2501 cx: &mut ViewContext<Self>,
2502 ) -> bool {
2503 if self.take_rename(false, cx).is_some() {
2504 return true;
2505 }
2506
2507 if hide_hover(self, cx) {
2508 return true;
2509 }
2510
2511 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2512 return true;
2513 }
2514
2515 if self.hide_context_menu(cx).is_some() {
2516 if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
2517 self.update_visible_inline_completion(cx);
2518 }
2519 return true;
2520 }
2521
2522 if self.mouse_context_menu.take().is_some() {
2523 return true;
2524 }
2525
2526 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2527 return true;
2528 }
2529
2530 if self.snippet_stack.pop().is_some() {
2531 return true;
2532 }
2533
2534 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2535 self.dismiss_diagnostics(cx);
2536 return true;
2537 }
2538
2539 false
2540 }
2541
2542 fn linked_editing_ranges_for(
2543 &self,
2544 selection: Range<text::Anchor>,
2545 cx: &AppContext,
2546 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2547 if self.linked_edit_ranges.is_empty() {
2548 return None;
2549 }
2550 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2551 selection.end.buffer_id.and_then(|end_buffer_id| {
2552 if selection.start.buffer_id != Some(end_buffer_id) {
2553 return None;
2554 }
2555 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2556 let snapshot = buffer.read(cx).snapshot();
2557 self.linked_edit_ranges
2558 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2559 .map(|ranges| (ranges, snapshot, buffer))
2560 })?;
2561 use text::ToOffset as TO;
2562 // find offset from the start of current range to current cursor position
2563 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2564
2565 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2566 let start_difference = start_offset - start_byte_offset;
2567 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2568 let end_difference = end_offset - start_byte_offset;
2569 // Current range has associated linked ranges.
2570 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2571 for range in linked_ranges.iter() {
2572 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2573 let end_offset = start_offset + end_difference;
2574 let start_offset = start_offset + start_difference;
2575 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2576 continue;
2577 }
2578 if self.selections.disjoint_anchor_ranges().any(|s| {
2579 if s.start.buffer_id != selection.start.buffer_id
2580 || s.end.buffer_id != selection.end.buffer_id
2581 {
2582 return false;
2583 }
2584 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2585 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2586 }) {
2587 continue;
2588 }
2589 let start = buffer_snapshot.anchor_after(start_offset);
2590 let end = buffer_snapshot.anchor_after(end_offset);
2591 linked_edits
2592 .entry(buffer.clone())
2593 .or_default()
2594 .push(start..end);
2595 }
2596 Some(linked_edits)
2597 }
2598
2599 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2600 let text: Arc<str> = text.into();
2601
2602 if self.read_only(cx) {
2603 return;
2604 }
2605
2606 let selections = self.selections.all_adjusted(cx);
2607 let mut bracket_inserted = false;
2608 let mut edits = Vec::new();
2609 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2610 let mut new_selections = Vec::with_capacity(selections.len());
2611 let mut new_autoclose_regions = Vec::new();
2612 let snapshot = self.buffer.read(cx).read(cx);
2613
2614 for (selection, autoclose_region) in
2615 self.selections_with_autoclose_regions(selections, &snapshot)
2616 {
2617 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2618 // Determine if the inserted text matches the opening or closing
2619 // bracket of any of this language's bracket pairs.
2620 let mut bracket_pair = None;
2621 let mut is_bracket_pair_start = false;
2622 let mut is_bracket_pair_end = false;
2623 if !text.is_empty() {
2624 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2625 // and they are removing the character that triggered IME popup.
2626 for (pair, enabled) in scope.brackets() {
2627 if !pair.close && !pair.surround {
2628 continue;
2629 }
2630
2631 if enabled && pair.start.ends_with(text.as_ref()) {
2632 let prefix_len = pair.start.len() - text.len();
2633 let preceding_text_matches_prefix = prefix_len == 0
2634 || (selection.start.column >= (prefix_len as u32)
2635 && snapshot.contains_str_at(
2636 Point::new(
2637 selection.start.row,
2638 selection.start.column - (prefix_len as u32),
2639 ),
2640 &pair.start[..prefix_len],
2641 ));
2642 if preceding_text_matches_prefix {
2643 bracket_pair = Some(pair.clone());
2644 is_bracket_pair_start = true;
2645 break;
2646 }
2647 }
2648 if pair.end.as_str() == text.as_ref() {
2649 bracket_pair = Some(pair.clone());
2650 is_bracket_pair_end = true;
2651 break;
2652 }
2653 }
2654 }
2655
2656 if let Some(bracket_pair) = bracket_pair {
2657 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2658 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2659 let auto_surround =
2660 self.use_auto_surround && snapshot_settings.use_auto_surround;
2661 if selection.is_empty() {
2662 if is_bracket_pair_start {
2663 // If the inserted text is a suffix of an opening bracket and the
2664 // selection is preceded by the rest of the opening bracket, then
2665 // insert the closing bracket.
2666 let following_text_allows_autoclose = snapshot
2667 .chars_at(selection.start)
2668 .next()
2669 .map_or(true, |c| scope.should_autoclose_before(c));
2670
2671 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2672 && bracket_pair.start.len() == 1
2673 {
2674 let target = bracket_pair.start.chars().next().unwrap();
2675 let current_line_count = snapshot
2676 .reversed_chars_at(selection.start)
2677 .take_while(|&c| c != '\n')
2678 .filter(|&c| c == target)
2679 .count();
2680 current_line_count % 2 == 1
2681 } else {
2682 false
2683 };
2684
2685 if autoclose
2686 && bracket_pair.close
2687 && following_text_allows_autoclose
2688 && !is_closing_quote
2689 {
2690 let anchor = snapshot.anchor_before(selection.end);
2691 new_selections.push((selection.map(|_| anchor), text.len()));
2692 new_autoclose_regions.push((
2693 anchor,
2694 text.len(),
2695 selection.id,
2696 bracket_pair.clone(),
2697 ));
2698 edits.push((
2699 selection.range(),
2700 format!("{}{}", text, bracket_pair.end).into(),
2701 ));
2702 bracket_inserted = true;
2703 continue;
2704 }
2705 }
2706
2707 if let Some(region) = autoclose_region {
2708 // If the selection is followed by an auto-inserted closing bracket,
2709 // then don't insert that closing bracket again; just move the selection
2710 // past the closing bracket.
2711 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2712 && text.as_ref() == region.pair.end.as_str();
2713 if should_skip {
2714 let anchor = snapshot.anchor_after(selection.end);
2715 new_selections
2716 .push((selection.map(|_| anchor), region.pair.end.len()));
2717 continue;
2718 }
2719 }
2720
2721 let always_treat_brackets_as_autoclosed = snapshot
2722 .settings_at(selection.start, cx)
2723 .always_treat_brackets_as_autoclosed;
2724 if always_treat_brackets_as_autoclosed
2725 && is_bracket_pair_end
2726 && snapshot.contains_str_at(selection.end, text.as_ref())
2727 {
2728 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2729 // and the inserted text is a closing bracket and the selection is followed
2730 // by the closing bracket then move the selection past the closing bracket.
2731 let anchor = snapshot.anchor_after(selection.end);
2732 new_selections.push((selection.map(|_| anchor), text.len()));
2733 continue;
2734 }
2735 }
2736 // If an opening bracket is 1 character long and is typed while
2737 // text is selected, then surround that text with the bracket pair.
2738 else if auto_surround
2739 && bracket_pair.surround
2740 && is_bracket_pair_start
2741 && bracket_pair.start.chars().count() == 1
2742 {
2743 edits.push((selection.start..selection.start, text.clone()));
2744 edits.push((
2745 selection.end..selection.end,
2746 bracket_pair.end.as_str().into(),
2747 ));
2748 bracket_inserted = true;
2749 new_selections.push((
2750 Selection {
2751 id: selection.id,
2752 start: snapshot.anchor_after(selection.start),
2753 end: snapshot.anchor_before(selection.end),
2754 reversed: selection.reversed,
2755 goal: selection.goal,
2756 },
2757 0,
2758 ));
2759 continue;
2760 }
2761 }
2762 }
2763
2764 if self.auto_replace_emoji_shortcode
2765 && selection.is_empty()
2766 && text.as_ref().ends_with(':')
2767 {
2768 if let Some(possible_emoji_short_code) =
2769 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2770 {
2771 if !possible_emoji_short_code.is_empty() {
2772 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2773 let emoji_shortcode_start = Point::new(
2774 selection.start.row,
2775 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2776 );
2777
2778 // Remove shortcode from buffer
2779 edits.push((
2780 emoji_shortcode_start..selection.start,
2781 "".to_string().into(),
2782 ));
2783 new_selections.push((
2784 Selection {
2785 id: selection.id,
2786 start: snapshot.anchor_after(emoji_shortcode_start),
2787 end: snapshot.anchor_before(selection.start),
2788 reversed: selection.reversed,
2789 goal: selection.goal,
2790 },
2791 0,
2792 ));
2793
2794 // Insert emoji
2795 let selection_start_anchor = snapshot.anchor_after(selection.start);
2796 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2797 edits.push((selection.start..selection.end, emoji.to_string().into()));
2798
2799 continue;
2800 }
2801 }
2802 }
2803 }
2804
2805 // If not handling any auto-close operation, then just replace the selected
2806 // text with the given input and move the selection to the end of the
2807 // newly inserted text.
2808 let anchor = snapshot.anchor_after(selection.end);
2809 if !self.linked_edit_ranges.is_empty() {
2810 let start_anchor = snapshot.anchor_before(selection.start);
2811
2812 let is_word_char = text.chars().next().map_or(true, |char| {
2813 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2814 classifier.is_word(char)
2815 });
2816
2817 if is_word_char {
2818 if let Some(ranges) = self
2819 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2820 {
2821 for (buffer, edits) in ranges {
2822 linked_edits
2823 .entry(buffer.clone())
2824 .or_default()
2825 .extend(edits.into_iter().map(|range| (range, text.clone())));
2826 }
2827 }
2828 }
2829 }
2830
2831 new_selections.push((selection.map(|_| anchor), 0));
2832 edits.push((selection.start..selection.end, text.clone()));
2833 }
2834
2835 drop(snapshot);
2836
2837 self.transact(cx, |this, cx| {
2838 this.buffer.update(cx, |buffer, cx| {
2839 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2840 });
2841 for (buffer, edits) in linked_edits {
2842 buffer.update(cx, |buffer, cx| {
2843 let snapshot = buffer.snapshot();
2844 let edits = edits
2845 .into_iter()
2846 .map(|(range, text)| {
2847 use text::ToPoint as TP;
2848 let end_point = TP::to_point(&range.end, &snapshot);
2849 let start_point = TP::to_point(&range.start, &snapshot);
2850 (start_point..end_point, text)
2851 })
2852 .sorted_by_key(|(range, _)| range.start)
2853 .collect::<Vec<_>>();
2854 buffer.edit(edits, None, cx);
2855 })
2856 }
2857 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2858 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2859 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2860 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2861 .zip(new_selection_deltas)
2862 .map(|(selection, delta)| Selection {
2863 id: selection.id,
2864 start: selection.start + delta,
2865 end: selection.end + delta,
2866 reversed: selection.reversed,
2867 goal: SelectionGoal::None,
2868 })
2869 .collect::<Vec<_>>();
2870
2871 let mut i = 0;
2872 for (position, delta, selection_id, pair) in new_autoclose_regions {
2873 let position = position.to_offset(&map.buffer_snapshot) + delta;
2874 let start = map.buffer_snapshot.anchor_before(position);
2875 let end = map.buffer_snapshot.anchor_after(position);
2876 while let Some(existing_state) = this.autoclose_regions.get(i) {
2877 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2878 Ordering::Less => i += 1,
2879 Ordering::Greater => break,
2880 Ordering::Equal => {
2881 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2882 Ordering::Less => i += 1,
2883 Ordering::Equal => break,
2884 Ordering::Greater => break,
2885 }
2886 }
2887 }
2888 }
2889 this.autoclose_regions.insert(
2890 i,
2891 AutocloseRegion {
2892 selection_id,
2893 range: start..end,
2894 pair,
2895 },
2896 );
2897 }
2898
2899 let had_active_inline_completion = this.has_active_inline_completion();
2900 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
2901 s.select(new_selections)
2902 });
2903
2904 if !bracket_inserted {
2905 if let Some(on_type_format_task) =
2906 this.trigger_on_type_formatting(text.to_string(), cx)
2907 {
2908 on_type_format_task.detach_and_log_err(cx);
2909 }
2910 }
2911
2912 let editor_settings = EditorSettings::get_global(cx);
2913 if bracket_inserted
2914 && (editor_settings.auto_signature_help
2915 || editor_settings.show_signature_help_after_edits)
2916 {
2917 this.show_signature_help(&ShowSignatureHelp, cx);
2918 }
2919
2920 let trigger_in_words =
2921 this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
2922 this.trigger_completion_on_input(&text, trigger_in_words, cx);
2923 linked_editing_ranges::refresh_linked_ranges(this, cx);
2924 this.refresh_inline_completion(true, false, cx);
2925 });
2926 }
2927
2928 fn find_possible_emoji_shortcode_at_position(
2929 snapshot: &MultiBufferSnapshot,
2930 position: Point,
2931 ) -> Option<String> {
2932 let mut chars = Vec::new();
2933 let mut found_colon = false;
2934 for char in snapshot.reversed_chars_at(position).take(100) {
2935 // Found a possible emoji shortcode in the middle of the buffer
2936 if found_colon {
2937 if char.is_whitespace() {
2938 chars.reverse();
2939 return Some(chars.iter().collect());
2940 }
2941 // If the previous character is not a whitespace, we are in the middle of a word
2942 // and we only want to complete the shortcode if the word is made up of other emojis
2943 let mut containing_word = String::new();
2944 for ch in snapshot
2945 .reversed_chars_at(position)
2946 .skip(chars.len() + 1)
2947 .take(100)
2948 {
2949 if ch.is_whitespace() {
2950 break;
2951 }
2952 containing_word.push(ch);
2953 }
2954 let containing_word = containing_word.chars().rev().collect::<String>();
2955 if util::word_consists_of_emojis(containing_word.as_str()) {
2956 chars.reverse();
2957 return Some(chars.iter().collect());
2958 }
2959 }
2960
2961 if char.is_whitespace() || !char.is_ascii() {
2962 return None;
2963 }
2964 if char == ':' {
2965 found_colon = true;
2966 } else {
2967 chars.push(char);
2968 }
2969 }
2970 // Found a possible emoji shortcode at the beginning of the buffer
2971 chars.reverse();
2972 Some(chars.iter().collect())
2973 }
2974
2975 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2976 self.transact(cx, |this, cx| {
2977 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2978 let selections = this.selections.all::<usize>(cx);
2979 let multi_buffer = this.buffer.read(cx);
2980 let buffer = multi_buffer.snapshot(cx);
2981 selections
2982 .iter()
2983 .map(|selection| {
2984 let start_point = selection.start.to_point(&buffer);
2985 let mut indent =
2986 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
2987 indent.len = cmp::min(indent.len, start_point.column);
2988 let start = selection.start;
2989 let end = selection.end;
2990 let selection_is_empty = start == end;
2991 let language_scope = buffer.language_scope_at(start);
2992 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
2993 &language_scope
2994 {
2995 let leading_whitespace_len = buffer
2996 .reversed_chars_at(start)
2997 .take_while(|c| c.is_whitespace() && *c != '\n')
2998 .map(|c| c.len_utf8())
2999 .sum::<usize>();
3000
3001 let trailing_whitespace_len = buffer
3002 .chars_at(end)
3003 .take_while(|c| c.is_whitespace() && *c != '\n')
3004 .map(|c| c.len_utf8())
3005 .sum::<usize>();
3006
3007 let insert_extra_newline =
3008 language.brackets().any(|(pair, enabled)| {
3009 let pair_start = pair.start.trim_end();
3010 let pair_end = pair.end.trim_start();
3011
3012 enabled
3013 && pair.newline
3014 && buffer.contains_str_at(
3015 end + trailing_whitespace_len,
3016 pair_end,
3017 )
3018 && buffer.contains_str_at(
3019 (start - leading_whitespace_len)
3020 .saturating_sub(pair_start.len()),
3021 pair_start,
3022 )
3023 });
3024
3025 // Comment extension on newline is allowed only for cursor selections
3026 let comment_delimiter = maybe!({
3027 if !selection_is_empty {
3028 return None;
3029 }
3030
3031 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3032 return None;
3033 }
3034
3035 let delimiters = language.line_comment_prefixes();
3036 let max_len_of_delimiter =
3037 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3038 let (snapshot, range) =
3039 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3040
3041 let mut index_of_first_non_whitespace = 0;
3042 let comment_candidate = snapshot
3043 .chars_for_range(range)
3044 .skip_while(|c| {
3045 let should_skip = c.is_whitespace();
3046 if should_skip {
3047 index_of_first_non_whitespace += 1;
3048 }
3049 should_skip
3050 })
3051 .take(max_len_of_delimiter)
3052 .collect::<String>();
3053 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3054 comment_candidate.starts_with(comment_prefix.as_ref())
3055 })?;
3056 let cursor_is_placed_after_comment_marker =
3057 index_of_first_non_whitespace + comment_prefix.len()
3058 <= start_point.column as usize;
3059 if cursor_is_placed_after_comment_marker {
3060 Some(comment_prefix.clone())
3061 } else {
3062 None
3063 }
3064 });
3065 (comment_delimiter, insert_extra_newline)
3066 } else {
3067 (None, false)
3068 };
3069
3070 let capacity_for_delimiter = comment_delimiter
3071 .as_deref()
3072 .map(str::len)
3073 .unwrap_or_default();
3074 let mut new_text =
3075 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3076 new_text.push('\n');
3077 new_text.extend(indent.chars());
3078 if let Some(delimiter) = &comment_delimiter {
3079 new_text.push_str(delimiter);
3080 }
3081 if insert_extra_newline {
3082 new_text = new_text.repeat(2);
3083 }
3084
3085 let anchor = buffer.anchor_after(end);
3086 let new_selection = selection.map(|_| anchor);
3087 (
3088 (start..end, new_text),
3089 (insert_extra_newline, new_selection),
3090 )
3091 })
3092 .unzip()
3093 };
3094
3095 this.edit_with_autoindent(edits, cx);
3096 let buffer = this.buffer.read(cx).snapshot(cx);
3097 let new_selections = selection_fixup_info
3098 .into_iter()
3099 .map(|(extra_newline_inserted, new_selection)| {
3100 let mut cursor = new_selection.end.to_point(&buffer);
3101 if extra_newline_inserted {
3102 cursor.row -= 1;
3103 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3104 }
3105 new_selection.map(|_| cursor)
3106 })
3107 .collect();
3108
3109 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3110 this.refresh_inline_completion(true, false, cx);
3111 });
3112 }
3113
3114 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3115 let buffer = self.buffer.read(cx);
3116 let snapshot = buffer.snapshot(cx);
3117
3118 let mut edits = Vec::new();
3119 let mut rows = Vec::new();
3120
3121 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3122 let cursor = selection.head();
3123 let row = cursor.row;
3124
3125 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3126
3127 let newline = "\n".to_string();
3128 edits.push((start_of_line..start_of_line, newline));
3129
3130 rows.push(row + rows_inserted as u32);
3131 }
3132
3133 self.transact(cx, |editor, cx| {
3134 editor.edit(edits, cx);
3135
3136 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3137 let mut index = 0;
3138 s.move_cursors_with(|map, _, _| {
3139 let row = rows[index];
3140 index += 1;
3141
3142 let point = Point::new(row, 0);
3143 let boundary = map.next_line_boundary(point).1;
3144 let clipped = map.clip_point(boundary, Bias::Left);
3145
3146 (clipped, SelectionGoal::None)
3147 });
3148 });
3149
3150 let mut indent_edits = Vec::new();
3151 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3152 for row in rows {
3153 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3154 for (row, indent) in indents {
3155 if indent.len == 0 {
3156 continue;
3157 }
3158
3159 let text = match indent.kind {
3160 IndentKind::Space => " ".repeat(indent.len as usize),
3161 IndentKind::Tab => "\t".repeat(indent.len as usize),
3162 };
3163 let point = Point::new(row.0, 0);
3164 indent_edits.push((point..point, text));
3165 }
3166 }
3167 editor.edit(indent_edits, cx);
3168 });
3169 }
3170
3171 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3172 let buffer = self.buffer.read(cx);
3173 let snapshot = buffer.snapshot(cx);
3174
3175 let mut edits = Vec::new();
3176 let mut rows = Vec::new();
3177 let mut rows_inserted = 0;
3178
3179 for selection in self.selections.all_adjusted(cx) {
3180 let cursor = selection.head();
3181 let row = cursor.row;
3182
3183 let point = Point::new(row + 1, 0);
3184 let start_of_line = snapshot.clip_point(point, Bias::Left);
3185
3186 let newline = "\n".to_string();
3187 edits.push((start_of_line..start_of_line, newline));
3188
3189 rows_inserted += 1;
3190 rows.push(row + rows_inserted);
3191 }
3192
3193 self.transact(cx, |editor, cx| {
3194 editor.edit(edits, cx);
3195
3196 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3197 let mut index = 0;
3198 s.move_cursors_with(|map, _, _| {
3199 let row = rows[index];
3200 index += 1;
3201
3202 let point = Point::new(row, 0);
3203 let boundary = map.next_line_boundary(point).1;
3204 let clipped = map.clip_point(boundary, Bias::Left);
3205
3206 (clipped, SelectionGoal::None)
3207 });
3208 });
3209
3210 let mut indent_edits = Vec::new();
3211 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3212 for row in rows {
3213 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3214 for (row, indent) in indents {
3215 if indent.len == 0 {
3216 continue;
3217 }
3218
3219 let text = match indent.kind {
3220 IndentKind::Space => " ".repeat(indent.len as usize),
3221 IndentKind::Tab => "\t".repeat(indent.len as usize),
3222 };
3223 let point = Point::new(row.0, 0);
3224 indent_edits.push((point..point, text));
3225 }
3226 }
3227 editor.edit(indent_edits, cx);
3228 });
3229 }
3230
3231 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3232 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3233 original_indent_columns: Vec::new(),
3234 });
3235 self.insert_with_autoindent_mode(text, autoindent, cx);
3236 }
3237
3238 fn insert_with_autoindent_mode(
3239 &mut self,
3240 text: &str,
3241 autoindent_mode: Option<AutoindentMode>,
3242 cx: &mut ViewContext<Self>,
3243 ) {
3244 if self.read_only(cx) {
3245 return;
3246 }
3247
3248 let text: Arc<str> = text.into();
3249 self.transact(cx, |this, cx| {
3250 let old_selections = this.selections.all_adjusted(cx);
3251 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3252 let anchors = {
3253 let snapshot = buffer.read(cx);
3254 old_selections
3255 .iter()
3256 .map(|s| {
3257 let anchor = snapshot.anchor_after(s.head());
3258 s.map(|_| anchor)
3259 })
3260 .collect::<Vec<_>>()
3261 };
3262 buffer.edit(
3263 old_selections
3264 .iter()
3265 .map(|s| (s.start..s.end, text.clone())),
3266 autoindent_mode,
3267 cx,
3268 );
3269 anchors
3270 });
3271
3272 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3273 s.select_anchors(selection_anchors);
3274 })
3275 });
3276 }
3277
3278 fn trigger_completion_on_input(
3279 &mut self,
3280 text: &str,
3281 trigger_in_words: bool,
3282 cx: &mut ViewContext<Self>,
3283 ) {
3284 if self.is_completion_trigger(text, trigger_in_words, cx) {
3285 self.show_completions(
3286 &ShowCompletions {
3287 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3288 },
3289 cx,
3290 );
3291 } else {
3292 self.hide_context_menu(cx);
3293 }
3294 }
3295
3296 fn is_completion_trigger(
3297 &self,
3298 text: &str,
3299 trigger_in_words: bool,
3300 cx: &mut ViewContext<Self>,
3301 ) -> bool {
3302 let position = self.selections.newest_anchor().head();
3303 let multibuffer = self.buffer.read(cx);
3304 let Some(buffer) = position
3305 .buffer_id
3306 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3307 else {
3308 return false;
3309 };
3310
3311 if let Some(completion_provider) = &self.completion_provider {
3312 completion_provider.is_completion_trigger(
3313 &buffer,
3314 position.text_anchor,
3315 text,
3316 trigger_in_words,
3317 cx,
3318 )
3319 } else {
3320 false
3321 }
3322 }
3323
3324 /// If any empty selections is touching the start of its innermost containing autoclose
3325 /// region, expand it to select the brackets.
3326 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3327 let selections = self.selections.all::<usize>(cx);
3328 let buffer = self.buffer.read(cx).read(cx);
3329 let new_selections = self
3330 .selections_with_autoclose_regions(selections, &buffer)
3331 .map(|(mut selection, region)| {
3332 if !selection.is_empty() {
3333 return selection;
3334 }
3335
3336 if let Some(region) = region {
3337 let mut range = region.range.to_offset(&buffer);
3338 if selection.start == range.start && range.start >= region.pair.start.len() {
3339 range.start -= region.pair.start.len();
3340 if buffer.contains_str_at(range.start, ®ion.pair.start)
3341 && buffer.contains_str_at(range.end, ®ion.pair.end)
3342 {
3343 range.end += region.pair.end.len();
3344 selection.start = range.start;
3345 selection.end = range.end;
3346
3347 return selection;
3348 }
3349 }
3350 }
3351
3352 let always_treat_brackets_as_autoclosed = buffer
3353 .settings_at(selection.start, cx)
3354 .always_treat_brackets_as_autoclosed;
3355
3356 if !always_treat_brackets_as_autoclosed {
3357 return selection;
3358 }
3359
3360 if let Some(scope) = buffer.language_scope_at(selection.start) {
3361 for (pair, enabled) in scope.brackets() {
3362 if !enabled || !pair.close {
3363 continue;
3364 }
3365
3366 if buffer.contains_str_at(selection.start, &pair.end) {
3367 let pair_start_len = pair.start.len();
3368 if buffer.contains_str_at(
3369 selection.start.saturating_sub(pair_start_len),
3370 &pair.start,
3371 ) {
3372 selection.start -= pair_start_len;
3373 selection.end += pair.end.len();
3374
3375 return selection;
3376 }
3377 }
3378 }
3379 }
3380
3381 selection
3382 })
3383 .collect();
3384
3385 drop(buffer);
3386 self.change_selections(None, cx, |selections| selections.select(new_selections));
3387 }
3388
3389 /// Iterate the given selections, and for each one, find the smallest surrounding
3390 /// autoclose region. This uses the ordering of the selections and the autoclose
3391 /// regions to avoid repeated comparisons.
3392 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3393 &'a self,
3394 selections: impl IntoIterator<Item = Selection<D>>,
3395 buffer: &'a MultiBufferSnapshot,
3396 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3397 let mut i = 0;
3398 let mut regions = self.autoclose_regions.as_slice();
3399 selections.into_iter().map(move |selection| {
3400 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3401
3402 let mut enclosing = None;
3403 while let Some(pair_state) = regions.get(i) {
3404 if pair_state.range.end.to_offset(buffer) < range.start {
3405 regions = ®ions[i + 1..];
3406 i = 0;
3407 } else if pair_state.range.start.to_offset(buffer) > range.end {
3408 break;
3409 } else {
3410 if pair_state.selection_id == selection.id {
3411 enclosing = Some(pair_state);
3412 }
3413 i += 1;
3414 }
3415 }
3416
3417 (selection, enclosing)
3418 })
3419 }
3420
3421 /// Remove any autoclose regions that no longer contain their selection.
3422 fn invalidate_autoclose_regions(
3423 &mut self,
3424 mut selections: &[Selection<Anchor>],
3425 buffer: &MultiBufferSnapshot,
3426 ) {
3427 self.autoclose_regions.retain(|state| {
3428 let mut i = 0;
3429 while let Some(selection) = selections.get(i) {
3430 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3431 selections = &selections[1..];
3432 continue;
3433 }
3434 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3435 break;
3436 }
3437 if selection.id == state.selection_id {
3438 return true;
3439 } else {
3440 i += 1;
3441 }
3442 }
3443 false
3444 });
3445 }
3446
3447 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3448 let offset = position.to_offset(buffer);
3449 let (word_range, kind) = buffer.surrounding_word(offset, true);
3450 if offset > word_range.start && kind == Some(CharKind::Word) {
3451 Some(
3452 buffer
3453 .text_for_range(word_range.start..offset)
3454 .collect::<String>(),
3455 )
3456 } else {
3457 None
3458 }
3459 }
3460
3461 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3462 self.refresh_inlay_hints(
3463 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3464 cx,
3465 );
3466 }
3467
3468 pub fn inlay_hints_enabled(&self) -> bool {
3469 self.inlay_hint_cache.enabled
3470 }
3471
3472 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3473 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3474 return;
3475 }
3476
3477 let reason_description = reason.description();
3478 let ignore_debounce = matches!(
3479 reason,
3480 InlayHintRefreshReason::SettingsChange(_)
3481 | InlayHintRefreshReason::Toggle(_)
3482 | InlayHintRefreshReason::ExcerptsRemoved(_)
3483 );
3484 let (invalidate_cache, required_languages) = match reason {
3485 InlayHintRefreshReason::Toggle(enabled) => {
3486 self.inlay_hint_cache.enabled = enabled;
3487 if enabled {
3488 (InvalidationStrategy::RefreshRequested, None)
3489 } else {
3490 self.inlay_hint_cache.clear();
3491 self.splice_inlays(
3492 self.visible_inlay_hints(cx)
3493 .iter()
3494 .map(|inlay| inlay.id)
3495 .collect(),
3496 Vec::new(),
3497 cx,
3498 );
3499 return;
3500 }
3501 }
3502 InlayHintRefreshReason::SettingsChange(new_settings) => {
3503 match self.inlay_hint_cache.update_settings(
3504 &self.buffer,
3505 new_settings,
3506 self.visible_inlay_hints(cx),
3507 cx,
3508 ) {
3509 ControlFlow::Break(Some(InlaySplice {
3510 to_remove,
3511 to_insert,
3512 })) => {
3513 self.splice_inlays(to_remove, to_insert, cx);
3514 return;
3515 }
3516 ControlFlow::Break(None) => return,
3517 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3518 }
3519 }
3520 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3521 if let Some(InlaySplice {
3522 to_remove,
3523 to_insert,
3524 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3525 {
3526 self.splice_inlays(to_remove, to_insert, cx);
3527 }
3528 return;
3529 }
3530 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3531 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3532 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3533 }
3534 InlayHintRefreshReason::RefreshRequested => {
3535 (InvalidationStrategy::RefreshRequested, None)
3536 }
3537 };
3538
3539 if let Some(InlaySplice {
3540 to_remove,
3541 to_insert,
3542 }) = self.inlay_hint_cache.spawn_hint_refresh(
3543 reason_description,
3544 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3545 invalidate_cache,
3546 ignore_debounce,
3547 cx,
3548 ) {
3549 self.splice_inlays(to_remove, to_insert, cx);
3550 }
3551 }
3552
3553 fn visible_inlay_hints(&self, cx: &ViewContext<Editor>) -> Vec<Inlay> {
3554 self.display_map
3555 .read(cx)
3556 .current_inlays()
3557 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3558 .cloned()
3559 .collect()
3560 }
3561
3562 pub fn excerpts_for_inlay_hints_query(
3563 &self,
3564 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3565 cx: &mut ViewContext<Editor>,
3566 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3567 let Some(project) = self.project.as_ref() else {
3568 return HashMap::default();
3569 };
3570 let project = project.read(cx);
3571 let multi_buffer = self.buffer().read(cx);
3572 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3573 let multi_buffer_visible_start = self
3574 .scroll_manager
3575 .anchor()
3576 .anchor
3577 .to_point(&multi_buffer_snapshot);
3578 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3579 multi_buffer_visible_start
3580 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3581 Bias::Left,
3582 );
3583 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3584 multi_buffer_snapshot
3585 .range_to_buffer_ranges(multi_buffer_visible_range)
3586 .into_iter()
3587 .filter(|(_, excerpt_visible_range)| !excerpt_visible_range.is_empty())
3588 .filter_map(|(excerpt, excerpt_visible_range)| {
3589 let buffer_file = project::File::from_dyn(excerpt.buffer().file())?;
3590 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3591 let worktree_entry = buffer_worktree
3592 .read(cx)
3593 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3594 if worktree_entry.is_ignored {
3595 return None;
3596 }
3597
3598 let language = excerpt.buffer().language()?;
3599 if let Some(restrict_to_languages) = restrict_to_languages {
3600 if !restrict_to_languages.contains(language) {
3601 return None;
3602 }
3603 }
3604 Some((
3605 excerpt.id(),
3606 (
3607 multi_buffer.buffer(excerpt.buffer_id()).unwrap(),
3608 excerpt.buffer().version().clone(),
3609 excerpt_visible_range,
3610 ),
3611 ))
3612 })
3613 .collect()
3614 }
3615
3616 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3617 TextLayoutDetails {
3618 text_system: cx.text_system().clone(),
3619 editor_style: self.style.clone().unwrap(),
3620 rem_size: cx.rem_size(),
3621 scroll_anchor: self.scroll_manager.anchor(),
3622 visible_rows: self.visible_line_count(),
3623 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3624 }
3625 }
3626
3627 pub fn splice_inlays(
3628 &self,
3629 to_remove: Vec<InlayId>,
3630 to_insert: Vec<Inlay>,
3631 cx: &mut ViewContext<Self>,
3632 ) {
3633 self.display_map.update(cx, |display_map, cx| {
3634 display_map.splice_inlays(to_remove, to_insert, cx)
3635 });
3636 cx.notify();
3637 }
3638
3639 fn trigger_on_type_formatting(
3640 &self,
3641 input: String,
3642 cx: &mut ViewContext<Self>,
3643 ) -> Option<Task<Result<()>>> {
3644 if input.len() != 1 {
3645 return None;
3646 }
3647
3648 let project = self.project.as_ref()?;
3649 let position = self.selections.newest_anchor().head();
3650 let (buffer, buffer_position) = self
3651 .buffer
3652 .read(cx)
3653 .text_anchor_for_position(position, cx)?;
3654
3655 let settings = language_settings::language_settings(
3656 buffer
3657 .read(cx)
3658 .language_at(buffer_position)
3659 .map(|l| l.name()),
3660 buffer.read(cx).file(),
3661 cx,
3662 );
3663 if !settings.use_on_type_format {
3664 return None;
3665 }
3666
3667 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3668 // hence we do LSP request & edit on host side only — add formats to host's history.
3669 let push_to_lsp_host_history = true;
3670 // If this is not the host, append its history with new edits.
3671 let push_to_client_history = project.read(cx).is_via_collab();
3672
3673 let on_type_formatting = project.update(cx, |project, cx| {
3674 project.on_type_format(
3675 buffer.clone(),
3676 buffer_position,
3677 input,
3678 push_to_lsp_host_history,
3679 cx,
3680 )
3681 });
3682 Some(cx.spawn(|editor, mut cx| async move {
3683 if let Some(transaction) = on_type_formatting.await? {
3684 if push_to_client_history {
3685 buffer
3686 .update(&mut cx, |buffer, _| {
3687 buffer.push_transaction(transaction, Instant::now());
3688 })
3689 .ok();
3690 }
3691 editor.update(&mut cx, |editor, cx| {
3692 editor.refresh_document_highlights(cx);
3693 })?;
3694 }
3695 Ok(())
3696 }))
3697 }
3698
3699 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
3700 if self.pending_rename.is_some() {
3701 return;
3702 }
3703
3704 let Some(provider) = self.completion_provider.as_ref() else {
3705 return;
3706 };
3707
3708 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3709 return;
3710 }
3711
3712 let position = self.selections.newest_anchor().head();
3713 let (buffer, buffer_position) =
3714 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3715 output
3716 } else {
3717 return;
3718 };
3719 let show_completion_documentation = buffer
3720 .read(cx)
3721 .snapshot()
3722 .settings_at(buffer_position, cx)
3723 .show_completion_documentation;
3724
3725 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3726
3727 let trigger_kind = match &options.trigger {
3728 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3729 CompletionTriggerKind::TRIGGER_CHARACTER
3730 }
3731 _ => CompletionTriggerKind::INVOKED,
3732 };
3733 let completion_context = CompletionContext {
3734 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3735 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3736 Some(String::from(trigger))
3737 } else {
3738 None
3739 }
3740 }),
3741 trigger_kind,
3742 };
3743 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
3744 let sort_completions = provider.sort_completions();
3745
3746 let id = post_inc(&mut self.next_completion_id);
3747 let task = cx.spawn(|editor, mut cx| {
3748 async move {
3749 editor.update(&mut cx, |this, _| {
3750 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3751 })?;
3752 let completions = completions.await.log_err();
3753 let menu = if let Some(completions) = completions {
3754 let mut menu = CompletionsMenu::new(
3755 id,
3756 sort_completions,
3757 show_completion_documentation,
3758 position,
3759 buffer.clone(),
3760 completions.into(),
3761 );
3762
3763 menu.filter(query.as_deref(), cx.background_executor().clone())
3764 .await;
3765
3766 menu.visible().then_some(menu)
3767 } else {
3768 None
3769 };
3770
3771 editor.update(&mut cx, |editor, cx| {
3772 match editor.context_menu.borrow().as_ref() {
3773 None => {}
3774 Some(CodeContextMenu::Completions(prev_menu)) => {
3775 if prev_menu.id > id {
3776 return;
3777 }
3778 }
3779 _ => return,
3780 }
3781
3782 if editor.focus_handle.is_focused(cx) && menu.is_some() {
3783 let mut menu = menu.unwrap();
3784 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3785
3786 if editor.show_inline_completions_in_menu(cx) {
3787 if let Some(hint) = editor.inline_completion_menu_hint(cx) {
3788 menu.show_inline_completion_hint(hint);
3789 }
3790 } else {
3791 editor.discard_inline_completion(false, cx);
3792 }
3793
3794 *editor.context_menu.borrow_mut() =
3795 Some(CodeContextMenu::Completions(menu));
3796
3797 cx.notify();
3798 } else if editor.completion_tasks.len() <= 1 {
3799 // If there are no more completion tasks and the last menu was
3800 // empty, we should hide it.
3801 let was_hidden = editor.hide_context_menu(cx).is_none();
3802 // If it was already hidden and we don't show inline
3803 // completions in the menu, we should also show the
3804 // inline-completion when available.
3805 if was_hidden && editor.show_inline_completions_in_menu(cx) {
3806 editor.update_visible_inline_completion(cx);
3807 }
3808 }
3809 })?;
3810
3811 Ok::<_, anyhow::Error>(())
3812 }
3813 .log_err()
3814 });
3815
3816 self.completion_tasks.push((id, task));
3817 }
3818
3819 pub fn confirm_completion(
3820 &mut self,
3821 action: &ConfirmCompletion,
3822 cx: &mut ViewContext<Self>,
3823 ) -> Option<Task<Result<()>>> {
3824 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
3825 }
3826
3827 pub fn compose_completion(
3828 &mut self,
3829 action: &ComposeCompletion,
3830 cx: &mut ViewContext<Self>,
3831 ) -> Option<Task<Result<()>>> {
3832 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
3833 }
3834
3835 fn do_completion(
3836 &mut self,
3837 item_ix: Option<usize>,
3838 intent: CompletionIntent,
3839 cx: &mut ViewContext<Editor>,
3840 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3841 use language::ToOffset as _;
3842
3843 {
3844 let context_menu = self.context_menu.borrow();
3845 if let CodeContextMenu::Completions(menu) = context_menu.as_ref()? {
3846 let entries = menu.entries.borrow();
3847 let entry = entries.get(item_ix.unwrap_or(menu.selected_item));
3848 match entry {
3849 Some(CompletionEntry::InlineCompletionHint(
3850 InlineCompletionMenuHint::Loading,
3851 )) => return Some(Task::ready(Ok(()))),
3852 Some(CompletionEntry::InlineCompletionHint(InlineCompletionMenuHint::None)) => {
3853 drop(entries);
3854 drop(context_menu);
3855 self.context_menu_next(&Default::default(), cx);
3856 return Some(Task::ready(Ok(())));
3857 }
3858 _ => {}
3859 }
3860 }
3861 }
3862
3863 let completions_menu =
3864 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3865 menu
3866 } else {
3867 return None;
3868 };
3869
3870 let entries = completions_menu.entries.borrow();
3871 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
3872 let mat = match mat {
3873 CompletionEntry::InlineCompletionHint(_) => {
3874 self.accept_inline_completion(&AcceptInlineCompletion, cx);
3875 cx.stop_propagation();
3876 return Some(Task::ready(Ok(())));
3877 }
3878 CompletionEntry::Match(mat) => {
3879 if self.show_inline_completions_in_menu(cx) {
3880 self.discard_inline_completion(true, cx);
3881 }
3882 mat
3883 }
3884 };
3885 let candidate_id = mat.candidate_id;
3886 drop(entries);
3887
3888 let buffer_handle = completions_menu.buffer;
3889 let completion = completions_menu
3890 .completions
3891 .borrow()
3892 .get(candidate_id)?
3893 .clone();
3894 cx.stop_propagation();
3895
3896 let snippet;
3897 let text;
3898
3899 if completion.is_snippet() {
3900 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3901 text = snippet.as_ref().unwrap().text.clone();
3902 } else {
3903 snippet = None;
3904 text = completion.new_text.clone();
3905 };
3906 let selections = self.selections.all::<usize>(cx);
3907 let buffer = buffer_handle.read(cx);
3908 let old_range = completion.old_range.to_offset(buffer);
3909 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3910
3911 let newest_selection = self.selections.newest_anchor();
3912 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3913 return None;
3914 }
3915
3916 let lookbehind = newest_selection
3917 .start
3918 .text_anchor
3919 .to_offset(buffer)
3920 .saturating_sub(old_range.start);
3921 let lookahead = old_range
3922 .end
3923 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3924 let mut common_prefix_len = old_text
3925 .bytes()
3926 .zip(text.bytes())
3927 .take_while(|(a, b)| a == b)
3928 .count();
3929
3930 let snapshot = self.buffer.read(cx).snapshot(cx);
3931 let mut range_to_replace: Option<Range<isize>> = None;
3932 let mut ranges = Vec::new();
3933 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3934 for selection in &selections {
3935 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3936 let start = selection.start.saturating_sub(lookbehind);
3937 let end = selection.end + lookahead;
3938 if selection.id == newest_selection.id {
3939 range_to_replace = Some(
3940 ((start + common_prefix_len) as isize - selection.start as isize)
3941 ..(end as isize - selection.start as isize),
3942 );
3943 }
3944 ranges.push(start + common_prefix_len..end);
3945 } else {
3946 common_prefix_len = 0;
3947 ranges.clear();
3948 ranges.extend(selections.iter().map(|s| {
3949 if s.id == newest_selection.id {
3950 range_to_replace = Some(
3951 old_range.start.to_offset_utf16(&snapshot).0 as isize
3952 - selection.start as isize
3953 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3954 - selection.start as isize,
3955 );
3956 old_range.clone()
3957 } else {
3958 s.start..s.end
3959 }
3960 }));
3961 break;
3962 }
3963 if !self.linked_edit_ranges.is_empty() {
3964 let start_anchor = snapshot.anchor_before(selection.head());
3965 let end_anchor = snapshot.anchor_after(selection.tail());
3966 if let Some(ranges) = self
3967 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
3968 {
3969 for (buffer, edits) in ranges {
3970 linked_edits.entry(buffer.clone()).or_default().extend(
3971 edits
3972 .into_iter()
3973 .map(|range| (range, text[common_prefix_len..].to_owned())),
3974 );
3975 }
3976 }
3977 }
3978 }
3979 let text = &text[common_prefix_len..];
3980
3981 cx.emit(EditorEvent::InputHandled {
3982 utf16_range_to_replace: range_to_replace,
3983 text: text.into(),
3984 });
3985
3986 self.transact(cx, |this, cx| {
3987 if let Some(mut snippet) = snippet {
3988 snippet.text = text.to_string();
3989 for tabstop in snippet
3990 .tabstops
3991 .iter_mut()
3992 .flat_map(|tabstop| tabstop.ranges.iter_mut())
3993 {
3994 tabstop.start -= common_prefix_len as isize;
3995 tabstop.end -= common_prefix_len as isize;
3996 }
3997
3998 this.insert_snippet(&ranges, snippet, cx).log_err();
3999 } else {
4000 this.buffer.update(cx, |buffer, cx| {
4001 buffer.edit(
4002 ranges.iter().map(|range| (range.clone(), text)),
4003 this.autoindent_mode.clone(),
4004 cx,
4005 );
4006 });
4007 }
4008 for (buffer, edits) in linked_edits {
4009 buffer.update(cx, |buffer, cx| {
4010 let snapshot = buffer.snapshot();
4011 let edits = edits
4012 .into_iter()
4013 .map(|(range, text)| {
4014 use text::ToPoint as TP;
4015 let end_point = TP::to_point(&range.end, &snapshot);
4016 let start_point = TP::to_point(&range.start, &snapshot);
4017 (start_point..end_point, text)
4018 })
4019 .sorted_by_key(|(range, _)| range.start)
4020 .collect::<Vec<_>>();
4021 buffer.edit(edits, None, cx);
4022 })
4023 }
4024
4025 this.refresh_inline_completion(true, false, cx);
4026 });
4027
4028 let show_new_completions_on_confirm = completion
4029 .confirm
4030 .as_ref()
4031 .map_or(false, |confirm| confirm(intent, cx));
4032 if show_new_completions_on_confirm {
4033 self.show_completions(&ShowCompletions { trigger: None }, cx);
4034 }
4035
4036 let provider = self.completion_provider.as_ref()?;
4037 drop(completion);
4038 let apply_edits = provider.apply_additional_edits_for_completion(
4039 buffer_handle,
4040 completions_menu.completions.clone(),
4041 candidate_id,
4042 true,
4043 cx,
4044 );
4045
4046 let editor_settings = EditorSettings::get_global(cx);
4047 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4048 // After the code completion is finished, users often want to know what signatures are needed.
4049 // so we should automatically call signature_help
4050 self.show_signature_help(&ShowSignatureHelp, cx);
4051 }
4052
4053 Some(cx.foreground_executor().spawn(async move {
4054 apply_edits.await?;
4055 Ok(())
4056 }))
4057 }
4058
4059 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4060 let mut context_menu = self.context_menu.borrow_mut();
4061 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4062 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4063 // Toggle if we're selecting the same one
4064 *context_menu = None;
4065 cx.notify();
4066 return;
4067 } else {
4068 // Otherwise, clear it and start a new one
4069 *context_menu = None;
4070 cx.notify();
4071 }
4072 }
4073 drop(context_menu);
4074 let snapshot = self.snapshot(cx);
4075 let deployed_from_indicator = action.deployed_from_indicator;
4076 let mut task = self.code_actions_task.take();
4077 let action = action.clone();
4078 cx.spawn(|editor, mut cx| async move {
4079 while let Some(prev_task) = task {
4080 prev_task.await.log_err();
4081 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4082 }
4083
4084 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4085 if editor.focus_handle.is_focused(cx) {
4086 let multibuffer_point = action
4087 .deployed_from_indicator
4088 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4089 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4090 let (buffer, buffer_row) = snapshot
4091 .buffer_snapshot
4092 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4093 .and_then(|(buffer_snapshot, range)| {
4094 editor
4095 .buffer
4096 .read(cx)
4097 .buffer(buffer_snapshot.remote_id())
4098 .map(|buffer| (buffer, range.start.row))
4099 })?;
4100 let (_, code_actions) = editor
4101 .available_code_actions
4102 .clone()
4103 .and_then(|(location, code_actions)| {
4104 let snapshot = location.buffer.read(cx).snapshot();
4105 let point_range = location.range.to_point(&snapshot);
4106 let point_range = point_range.start.row..=point_range.end.row;
4107 if point_range.contains(&buffer_row) {
4108 Some((location, code_actions))
4109 } else {
4110 None
4111 }
4112 })
4113 .unzip();
4114 let buffer_id = buffer.read(cx).remote_id();
4115 let tasks = editor
4116 .tasks
4117 .get(&(buffer_id, buffer_row))
4118 .map(|t| Arc::new(t.to_owned()));
4119 if tasks.is_none() && code_actions.is_none() {
4120 return None;
4121 }
4122
4123 editor.completion_tasks.clear();
4124 editor.discard_inline_completion(false, cx);
4125 let task_context =
4126 tasks
4127 .as_ref()
4128 .zip(editor.project.clone())
4129 .map(|(tasks, project)| {
4130 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4131 });
4132
4133 Some(cx.spawn(|editor, mut cx| async move {
4134 let task_context = match task_context {
4135 Some(task_context) => task_context.await,
4136 None => None,
4137 };
4138 let resolved_tasks =
4139 tasks.zip(task_context).map(|(tasks, task_context)| {
4140 Rc::new(ResolvedTasks {
4141 templates: tasks.resolve(&task_context).collect(),
4142 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4143 multibuffer_point.row,
4144 tasks.column,
4145 )),
4146 })
4147 });
4148 let spawn_straight_away = resolved_tasks
4149 .as_ref()
4150 .map_or(false, |tasks| tasks.templates.len() == 1)
4151 && code_actions
4152 .as_ref()
4153 .map_or(true, |actions| actions.is_empty());
4154 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4155 *editor.context_menu.borrow_mut() =
4156 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4157 buffer,
4158 actions: CodeActionContents {
4159 tasks: resolved_tasks,
4160 actions: code_actions,
4161 },
4162 selected_item: Default::default(),
4163 scroll_handle: UniformListScrollHandle::default(),
4164 deployed_from_indicator,
4165 }));
4166 if spawn_straight_away {
4167 if let Some(task) = editor.confirm_code_action(
4168 &ConfirmCodeAction { item_ix: Some(0) },
4169 cx,
4170 ) {
4171 cx.notify();
4172 return task;
4173 }
4174 }
4175 cx.notify();
4176 Task::ready(Ok(()))
4177 }) {
4178 task.await
4179 } else {
4180 Ok(())
4181 }
4182 }))
4183 } else {
4184 Some(Task::ready(Ok(())))
4185 }
4186 })?;
4187 if let Some(task) = spawned_test_task {
4188 task.await?;
4189 }
4190
4191 Ok::<_, anyhow::Error>(())
4192 })
4193 .detach_and_log_err(cx);
4194 }
4195
4196 pub fn confirm_code_action(
4197 &mut self,
4198 action: &ConfirmCodeAction,
4199 cx: &mut ViewContext<Self>,
4200 ) -> Option<Task<Result<()>>> {
4201 let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4202 menu
4203 } else {
4204 return None;
4205 };
4206 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4207 let action = actions_menu.actions.get(action_ix)?;
4208 let title = action.label();
4209 let buffer = actions_menu.buffer;
4210 let workspace = self.workspace()?;
4211
4212 match action {
4213 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4214 workspace.update(cx, |workspace, cx| {
4215 workspace::tasks::schedule_resolved_task(
4216 workspace,
4217 task_source_kind,
4218 resolved_task,
4219 false,
4220 cx,
4221 );
4222
4223 Some(Task::ready(Ok(())))
4224 })
4225 }
4226 CodeActionsItem::CodeAction {
4227 excerpt_id,
4228 action,
4229 provider,
4230 } => {
4231 let apply_code_action =
4232 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4233 let workspace = workspace.downgrade();
4234 Some(cx.spawn(|editor, cx| async move {
4235 let project_transaction = apply_code_action.await?;
4236 Self::open_project_transaction(
4237 &editor,
4238 workspace,
4239 project_transaction,
4240 title,
4241 cx,
4242 )
4243 .await
4244 }))
4245 }
4246 }
4247 }
4248
4249 pub async fn open_project_transaction(
4250 this: &WeakView<Editor>,
4251 workspace: WeakView<Workspace>,
4252 transaction: ProjectTransaction,
4253 title: String,
4254 mut cx: AsyncWindowContext,
4255 ) -> Result<()> {
4256 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4257 cx.update(|cx| {
4258 entries.sort_unstable_by_key(|(buffer, _)| {
4259 buffer.read(cx).file().map(|f| f.path().clone())
4260 });
4261 })?;
4262
4263 // If the project transaction's edits are all contained within this editor, then
4264 // avoid opening a new editor to display them.
4265
4266 if let Some((buffer, transaction)) = entries.first() {
4267 if entries.len() == 1 {
4268 let excerpt = this.update(&mut cx, |editor, cx| {
4269 editor
4270 .buffer()
4271 .read(cx)
4272 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4273 })?;
4274 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4275 if excerpted_buffer == *buffer {
4276 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4277 let excerpt_range = excerpt_range.to_offset(buffer);
4278 buffer
4279 .edited_ranges_for_transaction::<usize>(transaction)
4280 .all(|range| {
4281 excerpt_range.start <= range.start
4282 && excerpt_range.end >= range.end
4283 })
4284 })?;
4285
4286 if all_edits_within_excerpt {
4287 return Ok(());
4288 }
4289 }
4290 }
4291 }
4292 } else {
4293 return Ok(());
4294 }
4295
4296 let mut ranges_to_highlight = Vec::new();
4297 let excerpt_buffer = cx.new_model(|cx| {
4298 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4299 for (buffer_handle, transaction) in &entries {
4300 let buffer = buffer_handle.read(cx);
4301 ranges_to_highlight.extend(
4302 multibuffer.push_excerpts_with_context_lines(
4303 buffer_handle.clone(),
4304 buffer
4305 .edited_ranges_for_transaction::<usize>(transaction)
4306 .collect(),
4307 DEFAULT_MULTIBUFFER_CONTEXT,
4308 cx,
4309 ),
4310 );
4311 }
4312 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4313 multibuffer
4314 })?;
4315
4316 workspace.update(&mut cx, |workspace, cx| {
4317 let project = workspace.project().clone();
4318 let editor =
4319 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4320 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4321 editor.update(cx, |editor, cx| {
4322 editor.highlight_background::<Self>(
4323 &ranges_to_highlight,
4324 |theme| theme.editor_highlighted_line_background,
4325 cx,
4326 );
4327 });
4328 })?;
4329
4330 Ok(())
4331 }
4332
4333 pub fn clear_code_action_providers(&mut self) {
4334 self.code_action_providers.clear();
4335 self.available_code_actions.take();
4336 }
4337
4338 pub fn add_code_action_provider(
4339 &mut self,
4340 provider: Rc<dyn CodeActionProvider>,
4341 cx: &mut ViewContext<Self>,
4342 ) {
4343 if self
4344 .code_action_providers
4345 .iter()
4346 .any(|existing_provider| existing_provider.id() == provider.id())
4347 {
4348 return;
4349 }
4350
4351 self.code_action_providers.push(provider);
4352 self.refresh_code_actions(cx);
4353 }
4354
4355 pub fn remove_code_action_provider(&mut self, id: Arc<str>, cx: &mut ViewContext<Self>) {
4356 self.code_action_providers
4357 .retain(|provider| provider.id() != id);
4358 self.refresh_code_actions(cx);
4359 }
4360
4361 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4362 let buffer = self.buffer.read(cx);
4363 let newest_selection = self.selections.newest_anchor().clone();
4364 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4365 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4366 if start_buffer != end_buffer {
4367 return None;
4368 }
4369
4370 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4371 cx.background_executor()
4372 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4373 .await;
4374
4375 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4376 let providers = this.code_action_providers.clone();
4377 let tasks = this
4378 .code_action_providers
4379 .iter()
4380 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4381 .collect::<Vec<_>>();
4382 (providers, tasks)
4383 })?;
4384
4385 let mut actions = Vec::new();
4386 for (provider, provider_actions) in
4387 providers.into_iter().zip(future::join_all(tasks).await)
4388 {
4389 if let Some(provider_actions) = provider_actions.log_err() {
4390 actions.extend(provider_actions.into_iter().map(|action| {
4391 AvailableCodeAction {
4392 excerpt_id: newest_selection.start.excerpt_id,
4393 action,
4394 provider: provider.clone(),
4395 }
4396 }));
4397 }
4398 }
4399
4400 this.update(&mut cx, |this, cx| {
4401 this.available_code_actions = if actions.is_empty() {
4402 None
4403 } else {
4404 Some((
4405 Location {
4406 buffer: start_buffer,
4407 range: start..end,
4408 },
4409 actions.into(),
4410 ))
4411 };
4412 cx.notify();
4413 })
4414 }));
4415 None
4416 }
4417
4418 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4419 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4420 self.show_git_blame_inline = false;
4421
4422 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4423 cx.background_executor().timer(delay).await;
4424
4425 this.update(&mut cx, |this, cx| {
4426 this.show_git_blame_inline = true;
4427 cx.notify();
4428 })
4429 .log_err();
4430 }));
4431 }
4432 }
4433
4434 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4435 if self.pending_rename.is_some() {
4436 return None;
4437 }
4438
4439 let provider = self.semantics_provider.clone()?;
4440 let buffer = self.buffer.read(cx);
4441 let newest_selection = self.selections.newest_anchor().clone();
4442 let cursor_position = newest_selection.head();
4443 let (cursor_buffer, cursor_buffer_position) =
4444 buffer.text_anchor_for_position(cursor_position, cx)?;
4445 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4446 if cursor_buffer != tail_buffer {
4447 return None;
4448 }
4449 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4450 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4451 cx.background_executor()
4452 .timer(Duration::from_millis(debounce))
4453 .await;
4454
4455 let highlights = if let Some(highlights) = cx
4456 .update(|cx| {
4457 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4458 })
4459 .ok()
4460 .flatten()
4461 {
4462 highlights.await.log_err()
4463 } else {
4464 None
4465 };
4466
4467 if let Some(highlights) = highlights {
4468 this.update(&mut cx, |this, cx| {
4469 if this.pending_rename.is_some() {
4470 return;
4471 }
4472
4473 let buffer_id = cursor_position.buffer_id;
4474 let buffer = this.buffer.read(cx);
4475 if !buffer
4476 .text_anchor_for_position(cursor_position, cx)
4477 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4478 {
4479 return;
4480 }
4481
4482 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4483 let mut write_ranges = Vec::new();
4484 let mut read_ranges = Vec::new();
4485 for highlight in highlights {
4486 for (excerpt_id, excerpt_range) in
4487 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4488 {
4489 let start = highlight
4490 .range
4491 .start
4492 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4493 let end = highlight
4494 .range
4495 .end
4496 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4497 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4498 continue;
4499 }
4500
4501 let range = Anchor {
4502 buffer_id,
4503 excerpt_id,
4504 text_anchor: start,
4505 }..Anchor {
4506 buffer_id,
4507 excerpt_id,
4508 text_anchor: end,
4509 };
4510 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4511 write_ranges.push(range);
4512 } else {
4513 read_ranges.push(range);
4514 }
4515 }
4516 }
4517
4518 this.highlight_background::<DocumentHighlightRead>(
4519 &read_ranges,
4520 |theme| theme.editor_document_highlight_read_background,
4521 cx,
4522 );
4523 this.highlight_background::<DocumentHighlightWrite>(
4524 &write_ranges,
4525 |theme| theme.editor_document_highlight_write_background,
4526 cx,
4527 );
4528 cx.notify();
4529 })
4530 .log_err();
4531 }
4532 }));
4533 None
4534 }
4535
4536 pub fn refresh_inline_completion(
4537 &mut self,
4538 debounce: bool,
4539 user_requested: bool,
4540 cx: &mut ViewContext<Self>,
4541 ) -> Option<()> {
4542 let provider = self.inline_completion_provider()?;
4543 let cursor = self.selections.newest_anchor().head();
4544 let (buffer, cursor_buffer_position) =
4545 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4546
4547 if !user_requested
4548 && (!self.enable_inline_completions
4549 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4550 || !self.is_focused(cx)
4551 || buffer.read(cx).is_empty())
4552 {
4553 self.discard_inline_completion(false, cx);
4554 return None;
4555 }
4556
4557 self.update_visible_inline_completion(cx);
4558 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4559 Some(())
4560 }
4561
4562 fn cycle_inline_completion(
4563 &mut self,
4564 direction: Direction,
4565 cx: &mut ViewContext<Self>,
4566 ) -> Option<()> {
4567 let provider = self.inline_completion_provider()?;
4568 let cursor = self.selections.newest_anchor().head();
4569 let (buffer, cursor_buffer_position) =
4570 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4571 if !self.enable_inline_completions
4572 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4573 {
4574 return None;
4575 }
4576
4577 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4578 self.update_visible_inline_completion(cx);
4579
4580 Some(())
4581 }
4582
4583 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4584 if !self.has_active_inline_completion() {
4585 self.refresh_inline_completion(false, true, cx);
4586 return;
4587 }
4588
4589 self.update_visible_inline_completion(cx);
4590 }
4591
4592 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4593 self.show_cursor_names(cx);
4594 }
4595
4596 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4597 self.show_cursor_names = true;
4598 cx.notify();
4599 cx.spawn(|this, mut cx| async move {
4600 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4601 this.update(&mut cx, |this, cx| {
4602 this.show_cursor_names = false;
4603 cx.notify()
4604 })
4605 .ok()
4606 })
4607 .detach();
4608 }
4609
4610 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4611 if self.has_active_inline_completion() {
4612 self.cycle_inline_completion(Direction::Next, cx);
4613 } else {
4614 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4615 if is_copilot_disabled {
4616 cx.propagate();
4617 }
4618 }
4619 }
4620
4621 pub fn previous_inline_completion(
4622 &mut self,
4623 _: &PreviousInlineCompletion,
4624 cx: &mut ViewContext<Self>,
4625 ) {
4626 if self.has_active_inline_completion() {
4627 self.cycle_inline_completion(Direction::Prev, cx);
4628 } else {
4629 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4630 if is_copilot_disabled {
4631 cx.propagate();
4632 }
4633 }
4634 }
4635
4636 pub fn accept_inline_completion(
4637 &mut self,
4638 _: &AcceptInlineCompletion,
4639 cx: &mut ViewContext<Self>,
4640 ) {
4641 let buffer = self.buffer.read(cx);
4642 let snapshot = buffer.snapshot(cx);
4643 let selection = self.selections.newest_adjusted(cx);
4644 let cursor = selection.head();
4645 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
4646 let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
4647 if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
4648 {
4649 if cursor.column < suggested_indent.len
4650 && cursor.column <= current_indent.len
4651 && current_indent.len <= suggested_indent.len
4652 {
4653 self.tab(&Default::default(), cx);
4654 return;
4655 }
4656 }
4657
4658 if self.show_inline_completions_in_menu(cx) {
4659 self.hide_context_menu(cx);
4660 }
4661
4662 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4663 return;
4664 };
4665
4666 self.report_inline_completion_event(true, cx);
4667
4668 match &active_inline_completion.completion {
4669 InlineCompletion::Move(position) => {
4670 let position = *position;
4671 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4672 selections.select_anchor_ranges([position..position]);
4673 });
4674 }
4675 InlineCompletion::Edit(edits) => {
4676 if let Some(provider) = self.inline_completion_provider() {
4677 provider.accept(cx);
4678 }
4679
4680 let snapshot = self.buffer.read(cx).snapshot(cx);
4681 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4682
4683 self.buffer.update(cx, |buffer, cx| {
4684 buffer.edit(edits.iter().cloned(), None, cx)
4685 });
4686
4687 self.change_selections(None, cx, |s| {
4688 s.select_anchor_ranges([last_edit_end..last_edit_end])
4689 });
4690
4691 self.update_visible_inline_completion(cx);
4692 if self.active_inline_completion.is_none() {
4693 self.refresh_inline_completion(true, true, cx);
4694 }
4695
4696 cx.notify();
4697 }
4698 }
4699 }
4700
4701 pub fn accept_partial_inline_completion(
4702 &mut self,
4703 _: &AcceptPartialInlineCompletion,
4704 cx: &mut ViewContext<Self>,
4705 ) {
4706 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4707 return;
4708 };
4709 if self.selections.count() != 1 {
4710 return;
4711 }
4712
4713 self.report_inline_completion_event(true, cx);
4714
4715 match &active_inline_completion.completion {
4716 InlineCompletion::Move(position) => {
4717 let position = *position;
4718 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4719 selections.select_anchor_ranges([position..position]);
4720 });
4721 }
4722 InlineCompletion::Edit(edits) => {
4723 if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
4724 let text = edits[0].1.as_str();
4725 let mut partial_completion = text
4726 .chars()
4727 .by_ref()
4728 .take_while(|c| c.is_alphabetic())
4729 .collect::<String>();
4730 if partial_completion.is_empty() {
4731 partial_completion = text
4732 .chars()
4733 .by_ref()
4734 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4735 .collect::<String>();
4736 }
4737
4738 cx.emit(EditorEvent::InputHandled {
4739 utf16_range_to_replace: None,
4740 text: partial_completion.clone().into(),
4741 });
4742
4743 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4744
4745 self.refresh_inline_completion(true, true, cx);
4746 cx.notify();
4747 }
4748 }
4749 }
4750 }
4751
4752 fn discard_inline_completion(
4753 &mut self,
4754 should_report_inline_completion_event: bool,
4755 cx: &mut ViewContext<Self>,
4756 ) -> bool {
4757 if should_report_inline_completion_event {
4758 self.report_inline_completion_event(false, cx);
4759 }
4760
4761 if let Some(provider) = self.inline_completion_provider() {
4762 provider.discard(cx);
4763 }
4764
4765 self.take_active_inline_completion(cx).is_some()
4766 }
4767
4768 fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
4769 let Some(provider) = self.inline_completion_provider() else {
4770 return;
4771 };
4772
4773 let Some((_, buffer, _)) = self
4774 .buffer
4775 .read(cx)
4776 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4777 else {
4778 return;
4779 };
4780
4781 let extension = buffer
4782 .read(cx)
4783 .file()
4784 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4785
4786 let event_type = match accepted {
4787 true => "Inline Completion Accepted",
4788 false => "Inline Completion Discarded",
4789 };
4790 telemetry::event!(
4791 event_type,
4792 provider = provider.name(),
4793 suggestion_accepted = accepted,
4794 file_extension = extension,
4795 );
4796 }
4797
4798 pub fn has_active_inline_completion(&self) -> bool {
4799 self.active_inline_completion.is_some()
4800 }
4801
4802 fn take_active_inline_completion(
4803 &mut self,
4804 cx: &mut ViewContext<Self>,
4805 ) -> Option<InlineCompletion> {
4806 let active_inline_completion = self.active_inline_completion.take()?;
4807 self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
4808 self.clear_highlights::<InlineCompletionHighlight>(cx);
4809 Some(active_inline_completion.completion)
4810 }
4811
4812 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4813 let selection = self.selections.newest_anchor();
4814 let cursor = selection.head();
4815 let multibuffer = self.buffer.read(cx).snapshot(cx);
4816 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
4817 let excerpt_id = cursor.excerpt_id;
4818
4819 let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
4820 && (self.context_menu.borrow().is_some()
4821 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
4822 if completions_menu_has_precedence
4823 || !offset_selection.is_empty()
4824 || !self.enable_inline_completions
4825 || self
4826 .active_inline_completion
4827 .as_ref()
4828 .map_or(false, |completion| {
4829 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
4830 let invalidation_range = invalidation_range.start..=invalidation_range.end;
4831 !invalidation_range.contains(&offset_selection.head())
4832 })
4833 {
4834 self.discard_inline_completion(false, cx);
4835 return None;
4836 }
4837
4838 self.take_active_inline_completion(cx);
4839 let provider = self.inline_completion_provider()?;
4840
4841 let (buffer, cursor_buffer_position) =
4842 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4843
4844 let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
4845 let edits = completion
4846 .edits
4847 .into_iter()
4848 .flat_map(|(range, new_text)| {
4849 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
4850 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
4851 Some((start..end, new_text))
4852 })
4853 .collect::<Vec<_>>();
4854 if edits.is_empty() {
4855 return None;
4856 }
4857
4858 let first_edit_start = edits.first().unwrap().0.start;
4859 let edit_start_row = first_edit_start
4860 .to_point(&multibuffer)
4861 .row
4862 .saturating_sub(2);
4863
4864 let last_edit_end = edits.last().unwrap().0.end;
4865 let edit_end_row = cmp::min(
4866 multibuffer.max_point().row,
4867 last_edit_end.to_point(&multibuffer).row + 2,
4868 );
4869
4870 let cursor_row = cursor.to_point(&multibuffer).row;
4871
4872 let mut inlay_ids = Vec::new();
4873 let invalidation_row_range;
4874 let completion;
4875 if cursor_row < edit_start_row {
4876 invalidation_row_range = cursor_row..edit_end_row;
4877 completion = InlineCompletion::Move(first_edit_start);
4878 } else if cursor_row > edit_end_row {
4879 invalidation_row_range = edit_start_row..cursor_row;
4880 completion = InlineCompletion::Move(first_edit_start);
4881 } else {
4882 if edits
4883 .iter()
4884 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
4885 {
4886 let mut inlays = Vec::new();
4887 for (range, new_text) in &edits {
4888 let inlay = Inlay::inline_completion(
4889 post_inc(&mut self.next_inlay_id),
4890 range.start,
4891 new_text.as_str(),
4892 );
4893 inlay_ids.push(inlay.id);
4894 inlays.push(inlay);
4895 }
4896
4897 self.splice_inlays(vec![], inlays, cx);
4898 } else {
4899 let background_color = cx.theme().status().deleted_background;
4900 self.highlight_text::<InlineCompletionHighlight>(
4901 edits.iter().map(|(range, _)| range.clone()).collect(),
4902 HighlightStyle {
4903 background_color: Some(background_color),
4904 ..Default::default()
4905 },
4906 cx,
4907 );
4908 }
4909
4910 invalidation_row_range = edit_start_row..edit_end_row;
4911 completion = InlineCompletion::Edit(edits);
4912 };
4913
4914 let invalidation_range = multibuffer
4915 .anchor_before(Point::new(invalidation_row_range.start, 0))
4916 ..multibuffer.anchor_after(Point::new(
4917 invalidation_row_range.end,
4918 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
4919 ));
4920
4921 self.active_inline_completion = Some(InlineCompletionState {
4922 inlay_ids,
4923 completion,
4924 invalidation_range,
4925 });
4926
4927 if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
4928 if let Some(hint) = self.inline_completion_menu_hint(cx) {
4929 match self.context_menu.borrow_mut().as_mut() {
4930 Some(CodeContextMenu::Completions(menu)) => {
4931 menu.show_inline_completion_hint(hint);
4932 }
4933 _ => {}
4934 }
4935 }
4936 }
4937
4938 cx.notify();
4939
4940 Some(())
4941 }
4942
4943 fn inline_completion_menu_hint(
4944 &mut self,
4945 cx: &mut ViewContext<Self>,
4946 ) -> Option<InlineCompletionMenuHint> {
4947 let provider = self.inline_completion_provider()?;
4948 if self.has_active_inline_completion() {
4949 let editor_snapshot = self.snapshot(cx);
4950
4951 let text = match &self.active_inline_completion.as_ref()?.completion {
4952 InlineCompletion::Edit(edits) => {
4953 inline_completion_edit_text(&editor_snapshot, edits, true, cx)
4954 }
4955 InlineCompletion::Move(target) => {
4956 let target_point =
4957 target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
4958 let target_line = target_point.row + 1;
4959 InlineCompletionText::Move(
4960 format!("Jump to edit in line {}", target_line).into(),
4961 )
4962 }
4963 };
4964
4965 Some(InlineCompletionMenuHint::Loaded { text })
4966 } else if provider.is_refreshing(cx) {
4967 Some(InlineCompletionMenuHint::Loading)
4968 } else {
4969 Some(InlineCompletionMenuHint::None)
4970 }
4971 }
4972
4973 pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
4974 Some(self.inline_completion_provider.as_ref()?.provider.clone())
4975 }
4976
4977 fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
4978 EditorSettings::get_global(cx).show_inline_completions_in_menu
4979 && self
4980 .inline_completion_provider()
4981 .map_or(false, |provider| provider.show_completions_in_menu())
4982 }
4983
4984 fn render_code_actions_indicator(
4985 &self,
4986 _style: &EditorStyle,
4987 row: DisplayRow,
4988 is_active: bool,
4989 cx: &mut ViewContext<Self>,
4990 ) -> Option<IconButton> {
4991 if self.available_code_actions.is_some() {
4992 Some(
4993 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
4994 .shape(ui::IconButtonShape::Square)
4995 .icon_size(IconSize::XSmall)
4996 .icon_color(Color::Muted)
4997 .toggle_state(is_active)
4998 .tooltip({
4999 let focus_handle = self.focus_handle.clone();
5000 move |cx| {
5001 Tooltip::for_action_in(
5002 "Toggle Code Actions",
5003 &ToggleCodeActions {
5004 deployed_from_indicator: None,
5005 },
5006 &focus_handle,
5007 cx,
5008 )
5009 }
5010 })
5011 .on_click(cx.listener(move |editor, _e, cx| {
5012 editor.focus(cx);
5013 editor.toggle_code_actions(
5014 &ToggleCodeActions {
5015 deployed_from_indicator: Some(row),
5016 },
5017 cx,
5018 );
5019 })),
5020 )
5021 } else {
5022 None
5023 }
5024 }
5025
5026 fn clear_tasks(&mut self) {
5027 self.tasks.clear()
5028 }
5029
5030 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5031 if self.tasks.insert(key, value).is_some() {
5032 // This case should hopefully be rare, but just in case...
5033 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5034 }
5035 }
5036
5037 fn build_tasks_context(
5038 project: &Model<Project>,
5039 buffer: &Model<Buffer>,
5040 buffer_row: u32,
5041 tasks: &Arc<RunnableTasks>,
5042 cx: &mut ViewContext<Self>,
5043 ) -> Task<Option<task::TaskContext>> {
5044 let position = Point::new(buffer_row, tasks.column);
5045 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5046 let location = Location {
5047 buffer: buffer.clone(),
5048 range: range_start..range_start,
5049 };
5050 // Fill in the environmental variables from the tree-sitter captures
5051 let mut captured_task_variables = TaskVariables::default();
5052 for (capture_name, value) in tasks.extra_variables.clone() {
5053 captured_task_variables.insert(
5054 task::VariableName::Custom(capture_name.into()),
5055 value.clone(),
5056 );
5057 }
5058 project.update(cx, |project, cx| {
5059 project.task_store().update(cx, |task_store, cx| {
5060 task_store.task_context_for_location(captured_task_variables, location, cx)
5061 })
5062 })
5063 }
5064
5065 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
5066 let Some((workspace, _)) = self.workspace.clone() else {
5067 return;
5068 };
5069 let Some(project) = self.project.clone() else {
5070 return;
5071 };
5072
5073 // Try to find a closest, enclosing node using tree-sitter that has a
5074 // task
5075 let Some((buffer, buffer_row, tasks)) = self
5076 .find_enclosing_node_task(cx)
5077 // Or find the task that's closest in row-distance.
5078 .or_else(|| self.find_closest_task(cx))
5079 else {
5080 return;
5081 };
5082
5083 let reveal_strategy = action.reveal;
5084 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5085 cx.spawn(|_, mut cx| async move {
5086 let context = task_context.await?;
5087 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5088
5089 let resolved = resolved_task.resolved.as_mut()?;
5090 resolved.reveal = reveal_strategy;
5091
5092 workspace
5093 .update(&mut cx, |workspace, cx| {
5094 workspace::tasks::schedule_resolved_task(
5095 workspace,
5096 task_source_kind,
5097 resolved_task,
5098 false,
5099 cx,
5100 );
5101 })
5102 .ok()
5103 })
5104 .detach();
5105 }
5106
5107 fn find_closest_task(
5108 &mut self,
5109 cx: &mut ViewContext<Self>,
5110 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5111 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5112
5113 let ((buffer_id, row), tasks) = self
5114 .tasks
5115 .iter()
5116 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5117
5118 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5119 let tasks = Arc::new(tasks.to_owned());
5120 Some((buffer, *row, tasks))
5121 }
5122
5123 fn find_enclosing_node_task(
5124 &mut self,
5125 cx: &mut ViewContext<Self>,
5126 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5127 let snapshot = self.buffer.read(cx).snapshot(cx);
5128 let offset = self.selections.newest::<usize>(cx).head();
5129 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5130 let buffer_id = excerpt.buffer().remote_id();
5131
5132 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5133 let mut cursor = layer.node().walk();
5134
5135 while cursor.goto_first_child_for_byte(offset).is_some() {
5136 if cursor.node().end_byte() == offset {
5137 cursor.goto_next_sibling();
5138 }
5139 }
5140
5141 // Ascend to the smallest ancestor that contains the range and has a task.
5142 loop {
5143 let node = cursor.node();
5144 let node_range = node.byte_range();
5145 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5146
5147 // Check if this node contains our offset
5148 if node_range.start <= offset && node_range.end >= offset {
5149 // If it contains offset, check for task
5150 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5151 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5152 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5153 }
5154 }
5155
5156 if !cursor.goto_parent() {
5157 break;
5158 }
5159 }
5160 None
5161 }
5162
5163 fn render_run_indicator(
5164 &self,
5165 _style: &EditorStyle,
5166 is_active: bool,
5167 row: DisplayRow,
5168 cx: &mut ViewContext<Self>,
5169 ) -> IconButton {
5170 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5171 .shape(ui::IconButtonShape::Square)
5172 .icon_size(IconSize::XSmall)
5173 .icon_color(Color::Muted)
5174 .toggle_state(is_active)
5175 .on_click(cx.listener(move |editor, _e, cx| {
5176 editor.focus(cx);
5177 editor.toggle_code_actions(
5178 &ToggleCodeActions {
5179 deployed_from_indicator: Some(row),
5180 },
5181 cx,
5182 );
5183 }))
5184 }
5185
5186 #[cfg(any(feature = "test-support", test))]
5187 pub fn context_menu_visible(&self) -> bool {
5188 self.context_menu
5189 .borrow()
5190 .as_ref()
5191 .map_or(false, |menu| menu.visible())
5192 }
5193
5194 #[cfg(feature = "test-support")]
5195 pub fn context_menu_contains_inline_completion(&self) -> bool {
5196 self.context_menu
5197 .borrow()
5198 .as_ref()
5199 .map_or(false, |menu| match menu {
5200 CodeContextMenu::Completions(menu) => {
5201 menu.entries.borrow().first().map_or(false, |entry| {
5202 matches!(entry, CompletionEntry::InlineCompletionHint(_))
5203 })
5204 }
5205 CodeContextMenu::CodeActions(_) => false,
5206 })
5207 }
5208
5209 fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
5210 self.context_menu
5211 .borrow()
5212 .as_ref()
5213 .map(|menu| menu.origin(cursor_position))
5214 }
5215
5216 fn render_context_menu(
5217 &self,
5218 style: &EditorStyle,
5219 max_height_in_lines: u32,
5220 cx: &mut ViewContext<Editor>,
5221 ) -> Option<AnyElement> {
5222 self.context_menu.borrow().as_ref().and_then(|menu| {
5223 if menu.visible() {
5224 Some(menu.render(style, max_height_in_lines, cx))
5225 } else {
5226 None
5227 }
5228 })
5229 }
5230
5231 fn render_context_menu_aside(
5232 &self,
5233 style: &EditorStyle,
5234 max_size: Size<Pixels>,
5235 cx: &mut ViewContext<Editor>,
5236 ) -> Option<AnyElement> {
5237 self.context_menu.borrow().as_ref().and_then(|menu| {
5238 if menu.visible() {
5239 menu.render_aside(
5240 style,
5241 max_size,
5242 self.workspace.as_ref().map(|(w, _)| w.clone()),
5243 cx,
5244 )
5245 } else {
5246 None
5247 }
5248 })
5249 }
5250
5251 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
5252 cx.notify();
5253 self.completion_tasks.clear();
5254 let context_menu = self.context_menu.borrow_mut().take();
5255 if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
5256 self.update_visible_inline_completion(cx);
5257 }
5258 context_menu
5259 }
5260
5261 fn show_snippet_choices(
5262 &mut self,
5263 choices: &Vec<String>,
5264 selection: Range<Anchor>,
5265 cx: &mut ViewContext<Self>,
5266 ) {
5267 if selection.start.buffer_id.is_none() {
5268 return;
5269 }
5270 let buffer_id = selection.start.buffer_id.unwrap();
5271 let buffer = self.buffer().read(cx).buffer(buffer_id);
5272 let id = post_inc(&mut self.next_completion_id);
5273
5274 if let Some(buffer) = buffer {
5275 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5276 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5277 ));
5278 }
5279 }
5280
5281 pub fn insert_snippet(
5282 &mut self,
5283 insertion_ranges: &[Range<usize>],
5284 snippet: Snippet,
5285 cx: &mut ViewContext<Self>,
5286 ) -> Result<()> {
5287 struct Tabstop<T> {
5288 is_end_tabstop: bool,
5289 ranges: Vec<Range<T>>,
5290 choices: Option<Vec<String>>,
5291 }
5292
5293 let tabstops = self.buffer.update(cx, |buffer, cx| {
5294 let snippet_text: Arc<str> = snippet.text.clone().into();
5295 buffer.edit(
5296 insertion_ranges
5297 .iter()
5298 .cloned()
5299 .map(|range| (range, snippet_text.clone())),
5300 Some(AutoindentMode::EachLine),
5301 cx,
5302 );
5303
5304 let snapshot = &*buffer.read(cx);
5305 let snippet = &snippet;
5306 snippet
5307 .tabstops
5308 .iter()
5309 .map(|tabstop| {
5310 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5311 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5312 });
5313 let mut tabstop_ranges = tabstop
5314 .ranges
5315 .iter()
5316 .flat_map(|tabstop_range| {
5317 let mut delta = 0_isize;
5318 insertion_ranges.iter().map(move |insertion_range| {
5319 let insertion_start = insertion_range.start as isize + delta;
5320 delta +=
5321 snippet.text.len() as isize - insertion_range.len() as isize;
5322
5323 let start = ((insertion_start + tabstop_range.start) as usize)
5324 .min(snapshot.len());
5325 let end = ((insertion_start + tabstop_range.end) as usize)
5326 .min(snapshot.len());
5327 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5328 })
5329 })
5330 .collect::<Vec<_>>();
5331 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5332
5333 Tabstop {
5334 is_end_tabstop,
5335 ranges: tabstop_ranges,
5336 choices: tabstop.choices.clone(),
5337 }
5338 })
5339 .collect::<Vec<_>>()
5340 });
5341 if let Some(tabstop) = tabstops.first() {
5342 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5343 s.select_ranges(tabstop.ranges.iter().cloned());
5344 });
5345
5346 if let Some(choices) = &tabstop.choices {
5347 if let Some(selection) = tabstop.ranges.first() {
5348 self.show_snippet_choices(choices, selection.clone(), cx)
5349 }
5350 }
5351
5352 // If we're already at the last tabstop and it's at the end of the snippet,
5353 // we're done, we don't need to keep the state around.
5354 if !tabstop.is_end_tabstop {
5355 let choices = tabstops
5356 .iter()
5357 .map(|tabstop| tabstop.choices.clone())
5358 .collect();
5359
5360 let ranges = tabstops
5361 .into_iter()
5362 .map(|tabstop| tabstop.ranges)
5363 .collect::<Vec<_>>();
5364
5365 self.snippet_stack.push(SnippetState {
5366 active_index: 0,
5367 ranges,
5368 choices,
5369 });
5370 }
5371
5372 // Check whether the just-entered snippet ends with an auto-closable bracket.
5373 if self.autoclose_regions.is_empty() {
5374 let snapshot = self.buffer.read(cx).snapshot(cx);
5375 for selection in &mut self.selections.all::<Point>(cx) {
5376 let selection_head = selection.head();
5377 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5378 continue;
5379 };
5380
5381 let mut bracket_pair = None;
5382 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5383 let prev_chars = snapshot
5384 .reversed_chars_at(selection_head)
5385 .collect::<String>();
5386 for (pair, enabled) in scope.brackets() {
5387 if enabled
5388 && pair.close
5389 && prev_chars.starts_with(pair.start.as_str())
5390 && next_chars.starts_with(pair.end.as_str())
5391 {
5392 bracket_pair = Some(pair.clone());
5393 break;
5394 }
5395 }
5396 if let Some(pair) = bracket_pair {
5397 let start = snapshot.anchor_after(selection_head);
5398 let end = snapshot.anchor_after(selection_head);
5399 self.autoclose_regions.push(AutocloseRegion {
5400 selection_id: selection.id,
5401 range: start..end,
5402 pair,
5403 });
5404 }
5405 }
5406 }
5407 }
5408 Ok(())
5409 }
5410
5411 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5412 self.move_to_snippet_tabstop(Bias::Right, cx)
5413 }
5414
5415 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5416 self.move_to_snippet_tabstop(Bias::Left, cx)
5417 }
5418
5419 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5420 if let Some(mut snippet) = self.snippet_stack.pop() {
5421 match bias {
5422 Bias::Left => {
5423 if snippet.active_index > 0 {
5424 snippet.active_index -= 1;
5425 } else {
5426 self.snippet_stack.push(snippet);
5427 return false;
5428 }
5429 }
5430 Bias::Right => {
5431 if snippet.active_index + 1 < snippet.ranges.len() {
5432 snippet.active_index += 1;
5433 } else {
5434 self.snippet_stack.push(snippet);
5435 return false;
5436 }
5437 }
5438 }
5439 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5440 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5441 s.select_anchor_ranges(current_ranges.iter().cloned())
5442 });
5443
5444 if let Some(choices) = &snippet.choices[snippet.active_index] {
5445 if let Some(selection) = current_ranges.first() {
5446 self.show_snippet_choices(&choices, selection.clone(), cx);
5447 }
5448 }
5449
5450 // If snippet state is not at the last tabstop, push it back on the stack
5451 if snippet.active_index + 1 < snippet.ranges.len() {
5452 self.snippet_stack.push(snippet);
5453 }
5454 return true;
5455 }
5456 }
5457
5458 false
5459 }
5460
5461 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5462 self.transact(cx, |this, cx| {
5463 this.select_all(&SelectAll, cx);
5464 this.insert("", cx);
5465 });
5466 }
5467
5468 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5469 self.transact(cx, |this, cx| {
5470 this.select_autoclose_pair(cx);
5471 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5472 if !this.linked_edit_ranges.is_empty() {
5473 let selections = this.selections.all::<MultiBufferPoint>(cx);
5474 let snapshot = this.buffer.read(cx).snapshot(cx);
5475
5476 for selection in selections.iter() {
5477 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5478 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5479 if selection_start.buffer_id != selection_end.buffer_id {
5480 continue;
5481 }
5482 if let Some(ranges) =
5483 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5484 {
5485 for (buffer, entries) in ranges {
5486 linked_ranges.entry(buffer).or_default().extend(entries);
5487 }
5488 }
5489 }
5490 }
5491
5492 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5493 if !this.selections.line_mode {
5494 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5495 for selection in &mut selections {
5496 if selection.is_empty() {
5497 let old_head = selection.head();
5498 let mut new_head =
5499 movement::left(&display_map, old_head.to_display_point(&display_map))
5500 .to_point(&display_map);
5501 if let Some((buffer, line_buffer_range)) = display_map
5502 .buffer_snapshot
5503 .buffer_line_for_row(MultiBufferRow(old_head.row))
5504 {
5505 let indent_size =
5506 buffer.indent_size_for_line(line_buffer_range.start.row);
5507 let indent_len = match indent_size.kind {
5508 IndentKind::Space => {
5509 buffer.settings_at(line_buffer_range.start, cx).tab_size
5510 }
5511 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5512 };
5513 if old_head.column <= indent_size.len && old_head.column > 0 {
5514 let indent_len = indent_len.get();
5515 new_head = cmp::min(
5516 new_head,
5517 MultiBufferPoint::new(
5518 old_head.row,
5519 ((old_head.column - 1) / indent_len) * indent_len,
5520 ),
5521 );
5522 }
5523 }
5524
5525 selection.set_head(new_head, SelectionGoal::None);
5526 }
5527 }
5528 }
5529
5530 this.signature_help_state.set_backspace_pressed(true);
5531 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5532 this.insert("", cx);
5533 let empty_str: Arc<str> = Arc::from("");
5534 for (buffer, edits) in linked_ranges {
5535 let snapshot = buffer.read(cx).snapshot();
5536 use text::ToPoint as TP;
5537
5538 let edits = edits
5539 .into_iter()
5540 .map(|range| {
5541 let end_point = TP::to_point(&range.end, &snapshot);
5542 let mut start_point = TP::to_point(&range.start, &snapshot);
5543
5544 if end_point == start_point {
5545 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5546 .saturating_sub(1);
5547 start_point =
5548 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
5549 };
5550
5551 (start_point..end_point, empty_str.clone())
5552 })
5553 .sorted_by_key(|(range, _)| range.start)
5554 .collect::<Vec<_>>();
5555 buffer.update(cx, |this, cx| {
5556 this.edit(edits, None, cx);
5557 })
5558 }
5559 this.refresh_inline_completion(true, false, cx);
5560 linked_editing_ranges::refresh_linked_ranges(this, cx);
5561 });
5562 }
5563
5564 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5565 self.transact(cx, |this, cx| {
5566 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5567 let line_mode = s.line_mode;
5568 s.move_with(|map, selection| {
5569 if selection.is_empty() && !line_mode {
5570 let cursor = movement::right(map, selection.head());
5571 selection.end = cursor;
5572 selection.reversed = true;
5573 selection.goal = SelectionGoal::None;
5574 }
5575 })
5576 });
5577 this.insert("", cx);
5578 this.refresh_inline_completion(true, false, cx);
5579 });
5580 }
5581
5582 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5583 if self.move_to_prev_snippet_tabstop(cx) {
5584 return;
5585 }
5586
5587 self.outdent(&Outdent, cx);
5588 }
5589
5590 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5591 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5592 return;
5593 }
5594
5595 let mut selections = self.selections.all_adjusted(cx);
5596 let buffer = self.buffer.read(cx);
5597 let snapshot = buffer.snapshot(cx);
5598 let rows_iter = selections.iter().map(|s| s.head().row);
5599 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5600
5601 let mut edits = Vec::new();
5602 let mut prev_edited_row = 0;
5603 let mut row_delta = 0;
5604 for selection in &mut selections {
5605 if selection.start.row != prev_edited_row {
5606 row_delta = 0;
5607 }
5608 prev_edited_row = selection.end.row;
5609
5610 // If the selection is non-empty, then increase the indentation of the selected lines.
5611 if !selection.is_empty() {
5612 row_delta =
5613 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5614 continue;
5615 }
5616
5617 // If the selection is empty and the cursor is in the leading whitespace before the
5618 // suggested indentation, then auto-indent the line.
5619 let cursor = selection.head();
5620 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5621 if let Some(suggested_indent) =
5622 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5623 {
5624 if cursor.column < suggested_indent.len
5625 && cursor.column <= current_indent.len
5626 && current_indent.len <= suggested_indent.len
5627 {
5628 selection.start = Point::new(cursor.row, suggested_indent.len);
5629 selection.end = selection.start;
5630 if row_delta == 0 {
5631 edits.extend(Buffer::edit_for_indent_size_adjustment(
5632 cursor.row,
5633 current_indent,
5634 suggested_indent,
5635 ));
5636 row_delta = suggested_indent.len - current_indent.len;
5637 }
5638 continue;
5639 }
5640 }
5641
5642 // Otherwise, insert a hard or soft tab.
5643 let settings = buffer.settings_at(cursor, cx);
5644 let tab_size = if settings.hard_tabs {
5645 IndentSize::tab()
5646 } else {
5647 let tab_size = settings.tab_size.get();
5648 let char_column = snapshot
5649 .text_for_range(Point::new(cursor.row, 0)..cursor)
5650 .flat_map(str::chars)
5651 .count()
5652 + row_delta as usize;
5653 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5654 IndentSize::spaces(chars_to_next_tab_stop)
5655 };
5656 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5657 selection.end = selection.start;
5658 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5659 row_delta += tab_size.len;
5660 }
5661
5662 self.transact(cx, |this, cx| {
5663 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5664 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5665 this.refresh_inline_completion(true, false, cx);
5666 });
5667 }
5668
5669 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5670 if self.read_only(cx) {
5671 return;
5672 }
5673 let mut selections = self.selections.all::<Point>(cx);
5674 let mut prev_edited_row = 0;
5675 let mut row_delta = 0;
5676 let mut edits = Vec::new();
5677 let buffer = self.buffer.read(cx);
5678 let snapshot = buffer.snapshot(cx);
5679 for selection in &mut selections {
5680 if selection.start.row != prev_edited_row {
5681 row_delta = 0;
5682 }
5683 prev_edited_row = selection.end.row;
5684
5685 row_delta =
5686 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5687 }
5688
5689 self.transact(cx, |this, cx| {
5690 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5691 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5692 });
5693 }
5694
5695 fn indent_selection(
5696 buffer: &MultiBuffer,
5697 snapshot: &MultiBufferSnapshot,
5698 selection: &mut Selection<Point>,
5699 edits: &mut Vec<(Range<Point>, String)>,
5700 delta_for_start_row: u32,
5701 cx: &AppContext,
5702 ) -> u32 {
5703 let settings = buffer.settings_at(selection.start, cx);
5704 let tab_size = settings.tab_size.get();
5705 let indent_kind = if settings.hard_tabs {
5706 IndentKind::Tab
5707 } else {
5708 IndentKind::Space
5709 };
5710 let mut start_row = selection.start.row;
5711 let mut end_row = selection.end.row + 1;
5712
5713 // If a selection ends at the beginning of a line, don't indent
5714 // that last line.
5715 if selection.end.column == 0 && selection.end.row > selection.start.row {
5716 end_row -= 1;
5717 }
5718
5719 // Avoid re-indenting a row that has already been indented by a
5720 // previous selection, but still update this selection's column
5721 // to reflect that indentation.
5722 if delta_for_start_row > 0 {
5723 start_row += 1;
5724 selection.start.column += delta_for_start_row;
5725 if selection.end.row == selection.start.row {
5726 selection.end.column += delta_for_start_row;
5727 }
5728 }
5729
5730 let mut delta_for_end_row = 0;
5731 let has_multiple_rows = start_row + 1 != end_row;
5732 for row in start_row..end_row {
5733 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5734 let indent_delta = match (current_indent.kind, indent_kind) {
5735 (IndentKind::Space, IndentKind::Space) => {
5736 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5737 IndentSize::spaces(columns_to_next_tab_stop)
5738 }
5739 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5740 (_, IndentKind::Tab) => IndentSize::tab(),
5741 };
5742
5743 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5744 0
5745 } else {
5746 selection.start.column
5747 };
5748 let row_start = Point::new(row, start);
5749 edits.push((
5750 row_start..row_start,
5751 indent_delta.chars().collect::<String>(),
5752 ));
5753
5754 // Update this selection's endpoints to reflect the indentation.
5755 if row == selection.start.row {
5756 selection.start.column += indent_delta.len;
5757 }
5758 if row == selection.end.row {
5759 selection.end.column += indent_delta.len;
5760 delta_for_end_row = indent_delta.len;
5761 }
5762 }
5763
5764 if selection.start.row == selection.end.row {
5765 delta_for_start_row + delta_for_end_row
5766 } else {
5767 delta_for_end_row
5768 }
5769 }
5770
5771 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5772 if self.read_only(cx) {
5773 return;
5774 }
5775 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5776 let selections = self.selections.all::<Point>(cx);
5777 let mut deletion_ranges = Vec::new();
5778 let mut last_outdent = None;
5779 {
5780 let buffer = self.buffer.read(cx);
5781 let snapshot = buffer.snapshot(cx);
5782 for selection in &selections {
5783 let settings = buffer.settings_at(selection.start, cx);
5784 let tab_size = settings.tab_size.get();
5785 let mut rows = selection.spanned_rows(false, &display_map);
5786
5787 // Avoid re-outdenting a row that has already been outdented by a
5788 // previous selection.
5789 if let Some(last_row) = last_outdent {
5790 if last_row == rows.start {
5791 rows.start = rows.start.next_row();
5792 }
5793 }
5794 let has_multiple_rows = rows.len() > 1;
5795 for row in rows.iter_rows() {
5796 let indent_size = snapshot.indent_size_for_line(row);
5797 if indent_size.len > 0 {
5798 let deletion_len = match indent_size.kind {
5799 IndentKind::Space => {
5800 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5801 if columns_to_prev_tab_stop == 0 {
5802 tab_size
5803 } else {
5804 columns_to_prev_tab_stop
5805 }
5806 }
5807 IndentKind::Tab => 1,
5808 };
5809 let start = if has_multiple_rows
5810 || deletion_len > selection.start.column
5811 || indent_size.len < selection.start.column
5812 {
5813 0
5814 } else {
5815 selection.start.column - deletion_len
5816 };
5817 deletion_ranges.push(
5818 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5819 );
5820 last_outdent = Some(row);
5821 }
5822 }
5823 }
5824 }
5825
5826 self.transact(cx, |this, cx| {
5827 this.buffer.update(cx, |buffer, cx| {
5828 let empty_str: Arc<str> = Arc::default();
5829 buffer.edit(
5830 deletion_ranges
5831 .into_iter()
5832 .map(|range| (range, empty_str.clone())),
5833 None,
5834 cx,
5835 );
5836 });
5837 let selections = this.selections.all::<usize>(cx);
5838 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5839 });
5840 }
5841
5842 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
5843 if self.read_only(cx) {
5844 return;
5845 }
5846 let selections = self
5847 .selections
5848 .all::<usize>(cx)
5849 .into_iter()
5850 .map(|s| s.range());
5851
5852 self.transact(cx, |this, cx| {
5853 this.buffer.update(cx, |buffer, cx| {
5854 buffer.autoindent_ranges(selections, cx);
5855 });
5856 let selections = this.selections.all::<usize>(cx);
5857 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5858 });
5859 }
5860
5861 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5862 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5863 let selections = self.selections.all::<Point>(cx);
5864
5865 let mut new_cursors = Vec::new();
5866 let mut edit_ranges = Vec::new();
5867 let mut selections = selections.iter().peekable();
5868 while let Some(selection) = selections.next() {
5869 let mut rows = selection.spanned_rows(false, &display_map);
5870 let goal_display_column = selection.head().to_display_point(&display_map).column();
5871
5872 // Accumulate contiguous regions of rows that we want to delete.
5873 while let Some(next_selection) = selections.peek() {
5874 let next_rows = next_selection.spanned_rows(false, &display_map);
5875 if next_rows.start <= rows.end {
5876 rows.end = next_rows.end;
5877 selections.next().unwrap();
5878 } else {
5879 break;
5880 }
5881 }
5882
5883 let buffer = &display_map.buffer_snapshot;
5884 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5885 let edit_end;
5886 let cursor_buffer_row;
5887 if buffer.max_point().row >= rows.end.0 {
5888 // If there's a line after the range, delete the \n from the end of the row range
5889 // and position the cursor on the next line.
5890 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5891 cursor_buffer_row = rows.end;
5892 } else {
5893 // If there isn't a line after the range, delete the \n from the line before the
5894 // start of the row range and position the cursor there.
5895 edit_start = edit_start.saturating_sub(1);
5896 edit_end = buffer.len();
5897 cursor_buffer_row = rows.start.previous_row();
5898 }
5899
5900 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5901 *cursor.column_mut() =
5902 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5903
5904 new_cursors.push((
5905 selection.id,
5906 buffer.anchor_after(cursor.to_point(&display_map)),
5907 ));
5908 edit_ranges.push(edit_start..edit_end);
5909 }
5910
5911 self.transact(cx, |this, cx| {
5912 let buffer = this.buffer.update(cx, |buffer, cx| {
5913 let empty_str: Arc<str> = Arc::default();
5914 buffer.edit(
5915 edit_ranges
5916 .into_iter()
5917 .map(|range| (range, empty_str.clone())),
5918 None,
5919 cx,
5920 );
5921 buffer.snapshot(cx)
5922 });
5923 let new_selections = new_cursors
5924 .into_iter()
5925 .map(|(id, cursor)| {
5926 let cursor = cursor.to_point(&buffer);
5927 Selection {
5928 id,
5929 start: cursor,
5930 end: cursor,
5931 reversed: false,
5932 goal: SelectionGoal::None,
5933 }
5934 })
5935 .collect();
5936
5937 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5938 s.select(new_selections);
5939 });
5940 });
5941 }
5942
5943 pub fn join_lines_impl(&mut self, insert_whitespace: bool, cx: &mut ViewContext<Self>) {
5944 if self.read_only(cx) {
5945 return;
5946 }
5947 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5948 for selection in self.selections.all::<Point>(cx) {
5949 let start = MultiBufferRow(selection.start.row);
5950 // Treat single line selections as if they include the next line. Otherwise this action
5951 // would do nothing for single line selections individual cursors.
5952 let end = if selection.start.row == selection.end.row {
5953 MultiBufferRow(selection.start.row + 1)
5954 } else {
5955 MultiBufferRow(selection.end.row)
5956 };
5957
5958 if let Some(last_row_range) = row_ranges.last_mut() {
5959 if start <= last_row_range.end {
5960 last_row_range.end = end;
5961 continue;
5962 }
5963 }
5964 row_ranges.push(start..end);
5965 }
5966
5967 let snapshot = self.buffer.read(cx).snapshot(cx);
5968 let mut cursor_positions = Vec::new();
5969 for row_range in &row_ranges {
5970 let anchor = snapshot.anchor_before(Point::new(
5971 row_range.end.previous_row().0,
5972 snapshot.line_len(row_range.end.previous_row()),
5973 ));
5974 cursor_positions.push(anchor..anchor);
5975 }
5976
5977 self.transact(cx, |this, cx| {
5978 for row_range in row_ranges.into_iter().rev() {
5979 for row in row_range.iter_rows().rev() {
5980 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5981 let next_line_row = row.next_row();
5982 let indent = snapshot.indent_size_for_line(next_line_row);
5983 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5984
5985 let replace =
5986 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
5987 " "
5988 } else {
5989 ""
5990 };
5991
5992 this.buffer.update(cx, |buffer, cx| {
5993 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5994 });
5995 }
5996 }
5997
5998 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5999 s.select_anchor_ranges(cursor_positions)
6000 });
6001 });
6002 }
6003
6004 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6005 self.join_lines_impl(true, cx);
6006 }
6007
6008 pub fn sort_lines_case_sensitive(
6009 &mut self,
6010 _: &SortLinesCaseSensitive,
6011 cx: &mut ViewContext<Self>,
6012 ) {
6013 self.manipulate_lines(cx, |lines| lines.sort())
6014 }
6015
6016 pub fn sort_lines_case_insensitive(
6017 &mut self,
6018 _: &SortLinesCaseInsensitive,
6019 cx: &mut ViewContext<Self>,
6020 ) {
6021 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6022 }
6023
6024 pub fn unique_lines_case_insensitive(
6025 &mut self,
6026 _: &UniqueLinesCaseInsensitive,
6027 cx: &mut ViewContext<Self>,
6028 ) {
6029 self.manipulate_lines(cx, |lines| {
6030 let mut seen = HashSet::default();
6031 lines.retain(|line| seen.insert(line.to_lowercase()));
6032 })
6033 }
6034
6035 pub fn unique_lines_case_sensitive(
6036 &mut self,
6037 _: &UniqueLinesCaseSensitive,
6038 cx: &mut ViewContext<Self>,
6039 ) {
6040 self.manipulate_lines(cx, |lines| {
6041 let mut seen = HashSet::default();
6042 lines.retain(|line| seen.insert(*line));
6043 })
6044 }
6045
6046 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6047 let mut revert_changes = HashMap::default();
6048 let snapshot = self.snapshot(cx);
6049 for hunk in hunks_for_ranges(
6050 Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
6051 &snapshot,
6052 ) {
6053 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6054 }
6055 if !revert_changes.is_empty() {
6056 self.transact(cx, |editor, cx| {
6057 editor.revert(revert_changes, cx);
6058 });
6059 }
6060 }
6061
6062 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6063 let Some(project) = self.project.clone() else {
6064 return;
6065 };
6066 self.reload(project, cx).detach_and_notify_err(cx);
6067 }
6068
6069 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6070 let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
6071 if !revert_changes.is_empty() {
6072 self.transact(cx, |editor, cx| {
6073 editor.revert(revert_changes, cx);
6074 });
6075 }
6076 }
6077
6078 fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
6079 let snapshot = self.buffer.read(cx).read(cx);
6080 if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
6081 drop(snapshot);
6082 let mut revert_changes = HashMap::default();
6083 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6084 if !revert_changes.is_empty() {
6085 self.revert(revert_changes, cx)
6086 }
6087 }
6088 }
6089
6090 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6091 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6092 let project_path = buffer.read(cx).project_path(cx)?;
6093 let project = self.project.as_ref()?.read(cx);
6094 let entry = project.entry_for_path(&project_path, cx)?;
6095 let parent = match &entry.canonical_path {
6096 Some(canonical_path) => canonical_path.to_path_buf(),
6097 None => project.absolute_path(&project_path, cx)?,
6098 }
6099 .parent()?
6100 .to_path_buf();
6101 Some(parent)
6102 }) {
6103 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6104 }
6105 }
6106
6107 fn gather_revert_changes(
6108 &mut self,
6109 selections: &[Selection<Point>],
6110 cx: &mut ViewContext<Editor>,
6111 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6112 let mut revert_changes = HashMap::default();
6113 let snapshot = self.snapshot(cx);
6114 for hunk in hunks_for_selections(&snapshot, selections) {
6115 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6116 }
6117 revert_changes
6118 }
6119
6120 pub fn prepare_revert_change(
6121 &mut self,
6122 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6123 hunk: &MultiBufferDiffHunk,
6124 cx: &AppContext,
6125 ) -> Option<()> {
6126 let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
6127 let buffer = buffer.read(cx);
6128 let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
6129 let original_text = change_set
6130 .read(cx)
6131 .base_text
6132 .as_ref()?
6133 .read(cx)
6134 .as_rope()
6135 .slice(hunk.diff_base_byte_range.clone());
6136 let buffer_snapshot = buffer.snapshot();
6137 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6138 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6139 probe
6140 .0
6141 .start
6142 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6143 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6144 }) {
6145 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6146 Some(())
6147 } else {
6148 None
6149 }
6150 }
6151
6152 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6153 self.manipulate_lines(cx, |lines| lines.reverse())
6154 }
6155
6156 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6157 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6158 }
6159
6160 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6161 where
6162 Fn: FnMut(&mut Vec<&str>),
6163 {
6164 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6165 let buffer = self.buffer.read(cx).snapshot(cx);
6166
6167 let mut edits = Vec::new();
6168
6169 let selections = self.selections.all::<Point>(cx);
6170 let mut selections = selections.iter().peekable();
6171 let mut contiguous_row_selections = Vec::new();
6172 let mut new_selections = Vec::new();
6173 let mut added_lines = 0;
6174 let mut removed_lines = 0;
6175
6176 while let Some(selection) = selections.next() {
6177 let (start_row, end_row) = consume_contiguous_rows(
6178 &mut contiguous_row_selections,
6179 selection,
6180 &display_map,
6181 &mut selections,
6182 );
6183
6184 let start_point = Point::new(start_row.0, 0);
6185 let end_point = Point::new(
6186 end_row.previous_row().0,
6187 buffer.line_len(end_row.previous_row()),
6188 );
6189 let text = buffer
6190 .text_for_range(start_point..end_point)
6191 .collect::<String>();
6192
6193 let mut lines = text.split('\n').collect_vec();
6194
6195 let lines_before = lines.len();
6196 callback(&mut lines);
6197 let lines_after = lines.len();
6198
6199 edits.push((start_point..end_point, lines.join("\n")));
6200
6201 // Selections must change based on added and removed line count
6202 let start_row =
6203 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6204 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6205 new_selections.push(Selection {
6206 id: selection.id,
6207 start: start_row,
6208 end: end_row,
6209 goal: SelectionGoal::None,
6210 reversed: selection.reversed,
6211 });
6212
6213 if lines_after > lines_before {
6214 added_lines += lines_after - lines_before;
6215 } else if lines_before > lines_after {
6216 removed_lines += lines_before - lines_after;
6217 }
6218 }
6219
6220 self.transact(cx, |this, cx| {
6221 let buffer = this.buffer.update(cx, |buffer, cx| {
6222 buffer.edit(edits, None, cx);
6223 buffer.snapshot(cx)
6224 });
6225
6226 // Recalculate offsets on newly edited buffer
6227 let new_selections = new_selections
6228 .iter()
6229 .map(|s| {
6230 let start_point = Point::new(s.start.0, 0);
6231 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6232 Selection {
6233 id: s.id,
6234 start: buffer.point_to_offset(start_point),
6235 end: buffer.point_to_offset(end_point),
6236 goal: s.goal,
6237 reversed: s.reversed,
6238 }
6239 })
6240 .collect();
6241
6242 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6243 s.select(new_selections);
6244 });
6245
6246 this.request_autoscroll(Autoscroll::fit(), cx);
6247 });
6248 }
6249
6250 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6251 self.manipulate_text(cx, |text| text.to_uppercase())
6252 }
6253
6254 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6255 self.manipulate_text(cx, |text| text.to_lowercase())
6256 }
6257
6258 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6259 self.manipulate_text(cx, |text| {
6260 text.split('\n')
6261 .map(|line| line.to_case(Case::Title))
6262 .join("\n")
6263 })
6264 }
6265
6266 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6267 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6268 }
6269
6270 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6271 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6272 }
6273
6274 pub fn convert_to_upper_camel_case(
6275 &mut self,
6276 _: &ConvertToUpperCamelCase,
6277 cx: &mut ViewContext<Self>,
6278 ) {
6279 self.manipulate_text(cx, |text| {
6280 text.split('\n')
6281 .map(|line| line.to_case(Case::UpperCamel))
6282 .join("\n")
6283 })
6284 }
6285
6286 pub fn convert_to_lower_camel_case(
6287 &mut self,
6288 _: &ConvertToLowerCamelCase,
6289 cx: &mut ViewContext<Self>,
6290 ) {
6291 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6292 }
6293
6294 pub fn convert_to_opposite_case(
6295 &mut self,
6296 _: &ConvertToOppositeCase,
6297 cx: &mut ViewContext<Self>,
6298 ) {
6299 self.manipulate_text(cx, |text| {
6300 text.chars()
6301 .fold(String::with_capacity(text.len()), |mut t, c| {
6302 if c.is_uppercase() {
6303 t.extend(c.to_lowercase());
6304 } else {
6305 t.extend(c.to_uppercase());
6306 }
6307 t
6308 })
6309 })
6310 }
6311
6312 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6313 where
6314 Fn: FnMut(&str) -> String,
6315 {
6316 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6317 let buffer = self.buffer.read(cx).snapshot(cx);
6318
6319 let mut new_selections = Vec::new();
6320 let mut edits = Vec::new();
6321 let mut selection_adjustment = 0i32;
6322
6323 for selection in self.selections.all::<usize>(cx) {
6324 let selection_is_empty = selection.is_empty();
6325
6326 let (start, end) = if selection_is_empty {
6327 let word_range = movement::surrounding_word(
6328 &display_map,
6329 selection.start.to_display_point(&display_map),
6330 );
6331 let start = word_range.start.to_offset(&display_map, Bias::Left);
6332 let end = word_range.end.to_offset(&display_map, Bias::Left);
6333 (start, end)
6334 } else {
6335 (selection.start, selection.end)
6336 };
6337
6338 let text = buffer.text_for_range(start..end).collect::<String>();
6339 let old_length = text.len() as i32;
6340 let text = callback(&text);
6341
6342 new_selections.push(Selection {
6343 start: (start as i32 - selection_adjustment) as usize,
6344 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6345 goal: SelectionGoal::None,
6346 ..selection
6347 });
6348
6349 selection_adjustment += old_length - text.len() as i32;
6350
6351 edits.push((start..end, text));
6352 }
6353
6354 self.transact(cx, |this, cx| {
6355 this.buffer.update(cx, |buffer, cx| {
6356 buffer.edit(edits, None, cx);
6357 });
6358
6359 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6360 s.select(new_selections);
6361 });
6362
6363 this.request_autoscroll(Autoscroll::fit(), cx);
6364 });
6365 }
6366
6367 pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
6368 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6369 let buffer = &display_map.buffer_snapshot;
6370 let selections = self.selections.all::<Point>(cx);
6371
6372 let mut edits = Vec::new();
6373 let mut selections_iter = selections.iter().peekable();
6374 while let Some(selection) = selections_iter.next() {
6375 let mut rows = selection.spanned_rows(false, &display_map);
6376 // duplicate line-wise
6377 if whole_lines || selection.start == selection.end {
6378 // Avoid duplicating the same lines twice.
6379 while let Some(next_selection) = selections_iter.peek() {
6380 let next_rows = next_selection.spanned_rows(false, &display_map);
6381 if next_rows.start < rows.end {
6382 rows.end = next_rows.end;
6383 selections_iter.next().unwrap();
6384 } else {
6385 break;
6386 }
6387 }
6388
6389 // Copy the text from the selected row region and splice it either at the start
6390 // or end of the region.
6391 let start = Point::new(rows.start.0, 0);
6392 let end = Point::new(
6393 rows.end.previous_row().0,
6394 buffer.line_len(rows.end.previous_row()),
6395 );
6396 let text = buffer
6397 .text_for_range(start..end)
6398 .chain(Some("\n"))
6399 .collect::<String>();
6400 let insert_location = if upwards {
6401 Point::new(rows.end.0, 0)
6402 } else {
6403 start
6404 };
6405 edits.push((insert_location..insert_location, text));
6406 } else {
6407 // duplicate character-wise
6408 let start = selection.start;
6409 let end = selection.end;
6410 let text = buffer.text_for_range(start..end).collect::<String>();
6411 edits.push((selection.end..selection.end, text));
6412 }
6413 }
6414
6415 self.transact(cx, |this, cx| {
6416 this.buffer.update(cx, |buffer, cx| {
6417 buffer.edit(edits, None, cx);
6418 });
6419
6420 this.request_autoscroll(Autoscroll::fit(), cx);
6421 });
6422 }
6423
6424 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6425 self.duplicate(true, true, cx);
6426 }
6427
6428 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6429 self.duplicate(false, true, cx);
6430 }
6431
6432 pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
6433 self.duplicate(false, false, cx);
6434 }
6435
6436 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6437 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6438 let buffer = self.buffer.read(cx).snapshot(cx);
6439
6440 let mut edits = Vec::new();
6441 let mut unfold_ranges = Vec::new();
6442 let mut refold_creases = Vec::new();
6443
6444 let selections = self.selections.all::<Point>(cx);
6445 let mut selections = selections.iter().peekable();
6446 let mut contiguous_row_selections = Vec::new();
6447 let mut new_selections = Vec::new();
6448
6449 while let Some(selection) = selections.next() {
6450 // Find all the selections that span a contiguous row range
6451 let (start_row, end_row) = consume_contiguous_rows(
6452 &mut contiguous_row_selections,
6453 selection,
6454 &display_map,
6455 &mut selections,
6456 );
6457
6458 // Move the text spanned by the row range to be before the line preceding the row range
6459 if start_row.0 > 0 {
6460 let range_to_move = Point::new(
6461 start_row.previous_row().0,
6462 buffer.line_len(start_row.previous_row()),
6463 )
6464 ..Point::new(
6465 end_row.previous_row().0,
6466 buffer.line_len(end_row.previous_row()),
6467 );
6468 let insertion_point = display_map
6469 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6470 .0;
6471
6472 // Don't move lines across excerpts
6473 if buffer
6474 .excerpt_boundaries_in_range((
6475 Bound::Excluded(insertion_point),
6476 Bound::Included(range_to_move.end),
6477 ))
6478 .next()
6479 .is_none()
6480 {
6481 let text = buffer
6482 .text_for_range(range_to_move.clone())
6483 .flat_map(|s| s.chars())
6484 .skip(1)
6485 .chain(['\n'])
6486 .collect::<String>();
6487
6488 edits.push((
6489 buffer.anchor_after(range_to_move.start)
6490 ..buffer.anchor_before(range_to_move.end),
6491 String::new(),
6492 ));
6493 let insertion_anchor = buffer.anchor_after(insertion_point);
6494 edits.push((insertion_anchor..insertion_anchor, text));
6495
6496 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6497
6498 // Move selections up
6499 new_selections.extend(contiguous_row_selections.drain(..).map(
6500 |mut selection| {
6501 selection.start.row -= row_delta;
6502 selection.end.row -= row_delta;
6503 selection
6504 },
6505 ));
6506
6507 // Move folds up
6508 unfold_ranges.push(range_to_move.clone());
6509 for fold in display_map.folds_in_range(
6510 buffer.anchor_before(range_to_move.start)
6511 ..buffer.anchor_after(range_to_move.end),
6512 ) {
6513 let mut start = fold.range.start.to_point(&buffer);
6514 let mut end = fold.range.end.to_point(&buffer);
6515 start.row -= row_delta;
6516 end.row -= row_delta;
6517 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6518 }
6519 }
6520 }
6521
6522 // If we didn't move line(s), preserve the existing selections
6523 new_selections.append(&mut contiguous_row_selections);
6524 }
6525
6526 self.transact(cx, |this, cx| {
6527 this.unfold_ranges(&unfold_ranges, true, true, cx);
6528 this.buffer.update(cx, |buffer, cx| {
6529 for (range, text) in edits {
6530 buffer.edit([(range, text)], None, cx);
6531 }
6532 });
6533 this.fold_creases(refold_creases, true, cx);
6534 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6535 s.select(new_selections);
6536 })
6537 });
6538 }
6539
6540 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6541 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6542 let buffer = self.buffer.read(cx).snapshot(cx);
6543
6544 let mut edits = Vec::new();
6545 let mut unfold_ranges = Vec::new();
6546 let mut refold_creases = Vec::new();
6547
6548 let selections = self.selections.all::<Point>(cx);
6549 let mut selections = selections.iter().peekable();
6550 let mut contiguous_row_selections = Vec::new();
6551 let mut new_selections = Vec::new();
6552
6553 while let Some(selection) = selections.next() {
6554 // Find all the selections that span a contiguous row range
6555 let (start_row, end_row) = consume_contiguous_rows(
6556 &mut contiguous_row_selections,
6557 selection,
6558 &display_map,
6559 &mut selections,
6560 );
6561
6562 // Move the text spanned by the row range to be after the last line of the row range
6563 if end_row.0 <= buffer.max_point().row {
6564 let range_to_move =
6565 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6566 let insertion_point = display_map
6567 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6568 .0;
6569
6570 // Don't move lines across excerpt boundaries
6571 if buffer
6572 .excerpt_boundaries_in_range((
6573 Bound::Excluded(range_to_move.start),
6574 Bound::Included(insertion_point),
6575 ))
6576 .next()
6577 .is_none()
6578 {
6579 let mut text = String::from("\n");
6580 text.extend(buffer.text_for_range(range_to_move.clone()));
6581 text.pop(); // Drop trailing newline
6582 edits.push((
6583 buffer.anchor_after(range_to_move.start)
6584 ..buffer.anchor_before(range_to_move.end),
6585 String::new(),
6586 ));
6587 let insertion_anchor = buffer.anchor_after(insertion_point);
6588 edits.push((insertion_anchor..insertion_anchor, text));
6589
6590 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6591
6592 // Move selections down
6593 new_selections.extend(contiguous_row_selections.drain(..).map(
6594 |mut selection| {
6595 selection.start.row += row_delta;
6596 selection.end.row += row_delta;
6597 selection
6598 },
6599 ));
6600
6601 // Move folds down
6602 unfold_ranges.push(range_to_move.clone());
6603 for fold in display_map.folds_in_range(
6604 buffer.anchor_before(range_to_move.start)
6605 ..buffer.anchor_after(range_to_move.end),
6606 ) {
6607 let mut start = fold.range.start.to_point(&buffer);
6608 let mut end = fold.range.end.to_point(&buffer);
6609 start.row += row_delta;
6610 end.row += row_delta;
6611 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6612 }
6613 }
6614 }
6615
6616 // If we didn't move line(s), preserve the existing selections
6617 new_selections.append(&mut contiguous_row_selections);
6618 }
6619
6620 self.transact(cx, |this, cx| {
6621 this.unfold_ranges(&unfold_ranges, true, true, cx);
6622 this.buffer.update(cx, |buffer, cx| {
6623 for (range, text) in edits {
6624 buffer.edit([(range, text)], None, cx);
6625 }
6626 });
6627 this.fold_creases(refold_creases, true, cx);
6628 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6629 });
6630 }
6631
6632 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6633 let text_layout_details = &self.text_layout_details(cx);
6634 self.transact(cx, |this, cx| {
6635 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6636 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6637 let line_mode = s.line_mode;
6638 s.move_with(|display_map, selection| {
6639 if !selection.is_empty() || line_mode {
6640 return;
6641 }
6642
6643 let mut head = selection.head();
6644 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6645 if head.column() == display_map.line_len(head.row()) {
6646 transpose_offset = display_map
6647 .buffer_snapshot
6648 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6649 }
6650
6651 if transpose_offset == 0 {
6652 return;
6653 }
6654
6655 *head.column_mut() += 1;
6656 head = display_map.clip_point(head, Bias::Right);
6657 let goal = SelectionGoal::HorizontalPosition(
6658 display_map
6659 .x_for_display_point(head, text_layout_details)
6660 .into(),
6661 );
6662 selection.collapse_to(head, goal);
6663
6664 let transpose_start = display_map
6665 .buffer_snapshot
6666 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6667 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6668 let transpose_end = display_map
6669 .buffer_snapshot
6670 .clip_offset(transpose_offset + 1, Bias::Right);
6671 if let Some(ch) =
6672 display_map.buffer_snapshot.chars_at(transpose_start).next()
6673 {
6674 edits.push((transpose_start..transpose_offset, String::new()));
6675 edits.push((transpose_end..transpose_end, ch.to_string()));
6676 }
6677 }
6678 });
6679 edits
6680 });
6681 this.buffer
6682 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6683 let selections = this.selections.all::<usize>(cx);
6684 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6685 s.select(selections);
6686 });
6687 });
6688 }
6689
6690 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6691 self.rewrap_impl(IsVimMode::No, cx)
6692 }
6693
6694 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
6695 let buffer = self.buffer.read(cx).snapshot(cx);
6696 let selections = self.selections.all::<Point>(cx);
6697 let mut selections = selections.iter().peekable();
6698
6699 let mut edits = Vec::new();
6700 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6701
6702 while let Some(selection) = selections.next() {
6703 let mut start_row = selection.start.row;
6704 let mut end_row = selection.end.row;
6705
6706 // Skip selections that overlap with a range that has already been rewrapped.
6707 let selection_range = start_row..end_row;
6708 if rewrapped_row_ranges
6709 .iter()
6710 .any(|range| range.overlaps(&selection_range))
6711 {
6712 continue;
6713 }
6714
6715 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
6716
6717 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6718 match language_scope.language_name().0.as_ref() {
6719 "Markdown" | "Plain Text" => {
6720 should_rewrap = true;
6721 }
6722 _ => {}
6723 }
6724 }
6725
6726 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
6727
6728 // Since not all lines in the selection may be at the same indent
6729 // level, choose the indent size that is the most common between all
6730 // of the lines.
6731 //
6732 // If there is a tie, we use the deepest indent.
6733 let (indent_size, indent_end) = {
6734 let mut indent_size_occurrences = HashMap::default();
6735 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6736
6737 for row in start_row..=end_row {
6738 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6739 rows_by_indent_size.entry(indent).or_default().push(row);
6740 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6741 }
6742
6743 let indent_size = indent_size_occurrences
6744 .into_iter()
6745 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
6746 .map(|(indent, _)| indent)
6747 .unwrap_or_default();
6748 let row = rows_by_indent_size[&indent_size][0];
6749 let indent_end = Point::new(row, indent_size.len);
6750
6751 (indent_size, indent_end)
6752 };
6753
6754 let mut line_prefix = indent_size.chars().collect::<String>();
6755
6756 if let Some(comment_prefix) =
6757 buffer
6758 .language_scope_at(selection.head())
6759 .and_then(|language| {
6760 language
6761 .line_comment_prefixes()
6762 .iter()
6763 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6764 .cloned()
6765 })
6766 {
6767 line_prefix.push_str(&comment_prefix);
6768 should_rewrap = true;
6769 }
6770
6771 if !should_rewrap {
6772 continue;
6773 }
6774
6775 if selection.is_empty() {
6776 'expand_upwards: while start_row > 0 {
6777 let prev_row = start_row - 1;
6778 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6779 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6780 {
6781 start_row = prev_row;
6782 } else {
6783 break 'expand_upwards;
6784 }
6785 }
6786
6787 'expand_downwards: while end_row < buffer.max_point().row {
6788 let next_row = end_row + 1;
6789 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6790 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6791 {
6792 end_row = next_row;
6793 } else {
6794 break 'expand_downwards;
6795 }
6796 }
6797 }
6798
6799 let start = Point::new(start_row, 0);
6800 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6801 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6802 let Some(lines_without_prefixes) = selection_text
6803 .lines()
6804 .map(|line| {
6805 line.strip_prefix(&line_prefix)
6806 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6807 .ok_or_else(|| {
6808 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6809 })
6810 })
6811 .collect::<Result<Vec<_>, _>>()
6812 .log_err()
6813 else {
6814 continue;
6815 };
6816
6817 let wrap_column = buffer
6818 .settings_at(Point::new(start_row, 0), cx)
6819 .preferred_line_length as usize;
6820 let wrapped_text = wrap_with_prefix(
6821 line_prefix,
6822 lines_without_prefixes.join(" "),
6823 wrap_column,
6824 tab_size,
6825 );
6826
6827 // TODO: should always use char-based diff while still supporting cursor behavior that
6828 // matches vim.
6829 let diff = match is_vim_mode {
6830 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
6831 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
6832 };
6833 let mut offset = start.to_offset(&buffer);
6834 let mut moved_since_edit = true;
6835
6836 for change in diff.iter_all_changes() {
6837 let value = change.value();
6838 match change.tag() {
6839 ChangeTag::Equal => {
6840 offset += value.len();
6841 moved_since_edit = true;
6842 }
6843 ChangeTag::Delete => {
6844 let start = buffer.anchor_after(offset);
6845 let end = buffer.anchor_before(offset + value.len());
6846
6847 if moved_since_edit {
6848 edits.push((start..end, String::new()));
6849 } else {
6850 edits.last_mut().unwrap().0.end = end;
6851 }
6852
6853 offset += value.len();
6854 moved_since_edit = false;
6855 }
6856 ChangeTag::Insert => {
6857 if moved_since_edit {
6858 let anchor = buffer.anchor_after(offset);
6859 edits.push((anchor..anchor, value.to_string()));
6860 } else {
6861 edits.last_mut().unwrap().1.push_str(value);
6862 }
6863
6864 moved_since_edit = false;
6865 }
6866 }
6867 }
6868
6869 rewrapped_row_ranges.push(start_row..=end_row);
6870 }
6871
6872 self.buffer
6873 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6874 }
6875
6876 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
6877 let mut text = String::new();
6878 let buffer = self.buffer.read(cx).snapshot(cx);
6879 let mut selections = self.selections.all::<Point>(cx);
6880 let mut clipboard_selections = Vec::with_capacity(selections.len());
6881 {
6882 let max_point = buffer.max_point();
6883 let mut is_first = true;
6884 for selection in &mut selections {
6885 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6886 if is_entire_line {
6887 selection.start = Point::new(selection.start.row, 0);
6888 if !selection.is_empty() && selection.end.column == 0 {
6889 selection.end = cmp::min(max_point, selection.end);
6890 } else {
6891 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6892 }
6893 selection.goal = SelectionGoal::None;
6894 }
6895 if is_first {
6896 is_first = false;
6897 } else {
6898 text += "\n";
6899 }
6900 let mut len = 0;
6901 for chunk in buffer.text_for_range(selection.start..selection.end) {
6902 text.push_str(chunk);
6903 len += chunk.len();
6904 }
6905 clipboard_selections.push(ClipboardSelection {
6906 len,
6907 is_entire_line,
6908 first_line_indent: buffer
6909 .indent_size_for_line(MultiBufferRow(selection.start.row))
6910 .len,
6911 });
6912 }
6913 }
6914
6915 self.transact(cx, |this, cx| {
6916 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6917 s.select(selections);
6918 });
6919 this.insert("", cx);
6920 });
6921 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
6922 }
6923
6924 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6925 let item = self.cut_common(cx);
6926 cx.write_to_clipboard(item);
6927 }
6928
6929 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
6930 self.change_selections(None, cx, |s| {
6931 s.move_with(|snapshot, sel| {
6932 if sel.is_empty() {
6933 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
6934 }
6935 });
6936 });
6937 let item = self.cut_common(cx);
6938 cx.set_global(KillRing(item))
6939 }
6940
6941 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
6942 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
6943 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
6944 (kill_ring.text().to_string(), kill_ring.metadata_json())
6945 } else {
6946 return;
6947 }
6948 } else {
6949 return;
6950 };
6951 self.do_paste(&text, metadata, false, cx);
6952 }
6953
6954 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6955 let selections = self.selections.all::<Point>(cx);
6956 let buffer = self.buffer.read(cx).read(cx);
6957 let mut text = String::new();
6958
6959 let mut clipboard_selections = Vec::with_capacity(selections.len());
6960 {
6961 let max_point = buffer.max_point();
6962 let mut is_first = true;
6963 for selection in selections.iter() {
6964 let mut start = selection.start;
6965 let mut end = selection.end;
6966 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6967 if is_entire_line {
6968 start = Point::new(start.row, 0);
6969 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6970 }
6971 if is_first {
6972 is_first = false;
6973 } else {
6974 text += "\n";
6975 }
6976 let mut len = 0;
6977 for chunk in buffer.text_for_range(start..end) {
6978 text.push_str(chunk);
6979 len += chunk.len();
6980 }
6981 clipboard_selections.push(ClipboardSelection {
6982 len,
6983 is_entire_line,
6984 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6985 });
6986 }
6987 }
6988
6989 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6990 text,
6991 clipboard_selections,
6992 ));
6993 }
6994
6995 pub fn do_paste(
6996 &mut self,
6997 text: &String,
6998 clipboard_selections: Option<Vec<ClipboardSelection>>,
6999 handle_entire_lines: bool,
7000 cx: &mut ViewContext<Self>,
7001 ) {
7002 if self.read_only(cx) {
7003 return;
7004 }
7005
7006 let clipboard_text = Cow::Borrowed(text);
7007
7008 self.transact(cx, |this, cx| {
7009 if let Some(mut clipboard_selections) = clipboard_selections {
7010 let old_selections = this.selections.all::<usize>(cx);
7011 let all_selections_were_entire_line =
7012 clipboard_selections.iter().all(|s| s.is_entire_line);
7013 let first_selection_indent_column =
7014 clipboard_selections.first().map(|s| s.first_line_indent);
7015 if clipboard_selections.len() != old_selections.len() {
7016 clipboard_selections.drain(..);
7017 }
7018 let cursor_offset = this.selections.last::<usize>(cx).head();
7019 let mut auto_indent_on_paste = true;
7020
7021 this.buffer.update(cx, |buffer, cx| {
7022 let snapshot = buffer.read(cx);
7023 auto_indent_on_paste =
7024 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7025
7026 let mut start_offset = 0;
7027 let mut edits = Vec::new();
7028 let mut original_indent_columns = Vec::new();
7029 for (ix, selection) in old_selections.iter().enumerate() {
7030 let to_insert;
7031 let entire_line;
7032 let original_indent_column;
7033 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7034 let end_offset = start_offset + clipboard_selection.len;
7035 to_insert = &clipboard_text[start_offset..end_offset];
7036 entire_line = clipboard_selection.is_entire_line;
7037 start_offset = end_offset + 1;
7038 original_indent_column = Some(clipboard_selection.first_line_indent);
7039 } else {
7040 to_insert = clipboard_text.as_str();
7041 entire_line = all_selections_were_entire_line;
7042 original_indent_column = first_selection_indent_column
7043 }
7044
7045 // If the corresponding selection was empty when this slice of the
7046 // clipboard text was written, then the entire line containing the
7047 // selection was copied. If this selection is also currently empty,
7048 // then paste the line before the current line of the buffer.
7049 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7050 let column = selection.start.to_point(&snapshot).column as usize;
7051 let line_start = selection.start - column;
7052 line_start..line_start
7053 } else {
7054 selection.range()
7055 };
7056
7057 edits.push((range, to_insert));
7058 original_indent_columns.extend(original_indent_column);
7059 }
7060 drop(snapshot);
7061
7062 buffer.edit(
7063 edits,
7064 if auto_indent_on_paste {
7065 Some(AutoindentMode::Block {
7066 original_indent_columns,
7067 })
7068 } else {
7069 None
7070 },
7071 cx,
7072 );
7073 });
7074
7075 let selections = this.selections.all::<usize>(cx);
7076 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7077 } else {
7078 this.insert(&clipboard_text, cx);
7079 }
7080 });
7081 }
7082
7083 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7084 if let Some(item) = cx.read_from_clipboard() {
7085 let entries = item.entries();
7086
7087 match entries.first() {
7088 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7089 // of all the pasted entries.
7090 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7091 .do_paste(
7092 clipboard_string.text(),
7093 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7094 true,
7095 cx,
7096 ),
7097 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7098 }
7099 }
7100 }
7101
7102 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7103 if self.read_only(cx) {
7104 return;
7105 }
7106
7107 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7108 if let Some((selections, _)) =
7109 self.selection_history.transaction(transaction_id).cloned()
7110 {
7111 self.change_selections(None, cx, |s| {
7112 s.select_anchors(selections.to_vec());
7113 });
7114 }
7115 self.request_autoscroll(Autoscroll::fit(), cx);
7116 self.unmark_text(cx);
7117 self.refresh_inline_completion(true, false, cx);
7118 cx.emit(EditorEvent::Edited { transaction_id });
7119 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7120 }
7121 }
7122
7123 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7124 if self.read_only(cx) {
7125 return;
7126 }
7127
7128 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7129 if let Some((_, Some(selections))) =
7130 self.selection_history.transaction(transaction_id).cloned()
7131 {
7132 self.change_selections(None, cx, |s| {
7133 s.select_anchors(selections.to_vec());
7134 });
7135 }
7136 self.request_autoscroll(Autoscroll::fit(), cx);
7137 self.unmark_text(cx);
7138 self.refresh_inline_completion(true, false, cx);
7139 cx.emit(EditorEvent::Edited { transaction_id });
7140 }
7141 }
7142
7143 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7144 self.buffer
7145 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7146 }
7147
7148 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7149 self.buffer
7150 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7151 }
7152
7153 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7154 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7155 let line_mode = s.line_mode;
7156 s.move_with(|map, selection| {
7157 let cursor = if selection.is_empty() && !line_mode {
7158 movement::left(map, selection.start)
7159 } else {
7160 selection.start
7161 };
7162 selection.collapse_to(cursor, SelectionGoal::None);
7163 });
7164 })
7165 }
7166
7167 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7168 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7169 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7170 })
7171 }
7172
7173 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7174 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7175 let line_mode = s.line_mode;
7176 s.move_with(|map, selection| {
7177 let cursor = if selection.is_empty() && !line_mode {
7178 movement::right(map, selection.end)
7179 } else {
7180 selection.end
7181 };
7182 selection.collapse_to(cursor, SelectionGoal::None)
7183 });
7184 })
7185 }
7186
7187 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7188 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7189 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7190 })
7191 }
7192
7193 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7194 if self.take_rename(true, cx).is_some() {
7195 return;
7196 }
7197
7198 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7199 cx.propagate();
7200 return;
7201 }
7202
7203 let text_layout_details = &self.text_layout_details(cx);
7204 let selection_count = self.selections.count();
7205 let first_selection = self.selections.first_anchor();
7206
7207 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7208 let line_mode = s.line_mode;
7209 s.move_with(|map, selection| {
7210 if !selection.is_empty() && !line_mode {
7211 selection.goal = SelectionGoal::None;
7212 }
7213 let (cursor, goal) = movement::up(
7214 map,
7215 selection.start,
7216 selection.goal,
7217 false,
7218 text_layout_details,
7219 );
7220 selection.collapse_to(cursor, goal);
7221 });
7222 });
7223
7224 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7225 {
7226 cx.propagate();
7227 }
7228 }
7229
7230 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7231 if self.take_rename(true, cx).is_some() {
7232 return;
7233 }
7234
7235 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7236 cx.propagate();
7237 return;
7238 }
7239
7240 let text_layout_details = &self.text_layout_details(cx);
7241
7242 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7243 let line_mode = s.line_mode;
7244 s.move_with(|map, selection| {
7245 if !selection.is_empty() && !line_mode {
7246 selection.goal = SelectionGoal::None;
7247 }
7248 let (cursor, goal) = movement::up_by_rows(
7249 map,
7250 selection.start,
7251 action.lines,
7252 selection.goal,
7253 false,
7254 text_layout_details,
7255 );
7256 selection.collapse_to(cursor, goal);
7257 });
7258 })
7259 }
7260
7261 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7262 if self.take_rename(true, cx).is_some() {
7263 return;
7264 }
7265
7266 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7267 cx.propagate();
7268 return;
7269 }
7270
7271 let text_layout_details = &self.text_layout_details(cx);
7272
7273 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7274 let line_mode = s.line_mode;
7275 s.move_with(|map, selection| {
7276 if !selection.is_empty() && !line_mode {
7277 selection.goal = SelectionGoal::None;
7278 }
7279 let (cursor, goal) = movement::down_by_rows(
7280 map,
7281 selection.start,
7282 action.lines,
7283 selection.goal,
7284 false,
7285 text_layout_details,
7286 );
7287 selection.collapse_to(cursor, goal);
7288 });
7289 })
7290 }
7291
7292 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7293 let text_layout_details = &self.text_layout_details(cx);
7294 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7295 s.move_heads_with(|map, head, goal| {
7296 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7297 })
7298 })
7299 }
7300
7301 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7302 let text_layout_details = &self.text_layout_details(cx);
7303 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7304 s.move_heads_with(|map, head, goal| {
7305 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7306 })
7307 })
7308 }
7309
7310 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7311 let Some(row_count) = self.visible_row_count() else {
7312 return;
7313 };
7314
7315 let text_layout_details = &self.text_layout_details(cx);
7316
7317 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7318 s.move_heads_with(|map, head, goal| {
7319 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7320 })
7321 })
7322 }
7323
7324 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7325 if self.take_rename(true, cx).is_some() {
7326 return;
7327 }
7328
7329 if self
7330 .context_menu
7331 .borrow_mut()
7332 .as_mut()
7333 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7334 .unwrap_or(false)
7335 {
7336 return;
7337 }
7338
7339 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7340 cx.propagate();
7341 return;
7342 }
7343
7344 let Some(row_count) = self.visible_row_count() else {
7345 return;
7346 };
7347
7348 let autoscroll = if action.center_cursor {
7349 Autoscroll::center()
7350 } else {
7351 Autoscroll::fit()
7352 };
7353
7354 let text_layout_details = &self.text_layout_details(cx);
7355
7356 self.change_selections(Some(autoscroll), cx, |s| {
7357 let line_mode = s.line_mode;
7358 s.move_with(|map, selection| {
7359 if !selection.is_empty() && !line_mode {
7360 selection.goal = SelectionGoal::None;
7361 }
7362 let (cursor, goal) = movement::up_by_rows(
7363 map,
7364 selection.end,
7365 row_count,
7366 selection.goal,
7367 false,
7368 text_layout_details,
7369 );
7370 selection.collapse_to(cursor, goal);
7371 });
7372 });
7373 }
7374
7375 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7376 let text_layout_details = &self.text_layout_details(cx);
7377 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7378 s.move_heads_with(|map, head, goal| {
7379 movement::up(map, head, goal, false, text_layout_details)
7380 })
7381 })
7382 }
7383
7384 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7385 self.take_rename(true, cx);
7386
7387 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7388 cx.propagate();
7389 return;
7390 }
7391
7392 let text_layout_details = &self.text_layout_details(cx);
7393 let selection_count = self.selections.count();
7394 let first_selection = self.selections.first_anchor();
7395
7396 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7397 let line_mode = s.line_mode;
7398 s.move_with(|map, selection| {
7399 if !selection.is_empty() && !line_mode {
7400 selection.goal = SelectionGoal::None;
7401 }
7402 let (cursor, goal) = movement::down(
7403 map,
7404 selection.end,
7405 selection.goal,
7406 false,
7407 text_layout_details,
7408 );
7409 selection.collapse_to(cursor, goal);
7410 });
7411 });
7412
7413 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7414 {
7415 cx.propagate();
7416 }
7417 }
7418
7419 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7420 let Some(row_count) = self.visible_row_count() else {
7421 return;
7422 };
7423
7424 let text_layout_details = &self.text_layout_details(cx);
7425
7426 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7427 s.move_heads_with(|map, head, goal| {
7428 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7429 })
7430 })
7431 }
7432
7433 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7434 if self.take_rename(true, cx).is_some() {
7435 return;
7436 }
7437
7438 if self
7439 .context_menu
7440 .borrow_mut()
7441 .as_mut()
7442 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7443 .unwrap_or(false)
7444 {
7445 return;
7446 }
7447
7448 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7449 cx.propagate();
7450 return;
7451 }
7452
7453 let Some(row_count) = self.visible_row_count() else {
7454 return;
7455 };
7456
7457 let autoscroll = if action.center_cursor {
7458 Autoscroll::center()
7459 } else {
7460 Autoscroll::fit()
7461 };
7462
7463 let text_layout_details = &self.text_layout_details(cx);
7464 self.change_selections(Some(autoscroll), cx, |s| {
7465 let line_mode = s.line_mode;
7466 s.move_with(|map, selection| {
7467 if !selection.is_empty() && !line_mode {
7468 selection.goal = SelectionGoal::None;
7469 }
7470 let (cursor, goal) = movement::down_by_rows(
7471 map,
7472 selection.end,
7473 row_count,
7474 selection.goal,
7475 false,
7476 text_layout_details,
7477 );
7478 selection.collapse_to(cursor, goal);
7479 });
7480 });
7481 }
7482
7483 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7484 let text_layout_details = &self.text_layout_details(cx);
7485 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7486 s.move_heads_with(|map, head, goal| {
7487 movement::down(map, head, goal, false, text_layout_details)
7488 })
7489 });
7490 }
7491
7492 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7493 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7494 context_menu.select_first(self.completion_provider.as_deref(), cx);
7495 }
7496 }
7497
7498 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7499 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7500 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7501 }
7502 }
7503
7504 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7505 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7506 context_menu.select_next(self.completion_provider.as_deref(), cx);
7507 }
7508 }
7509
7510 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7511 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7512 context_menu.select_last(self.completion_provider.as_deref(), cx);
7513 }
7514 }
7515
7516 pub fn move_to_previous_word_start(
7517 &mut self,
7518 _: &MoveToPreviousWordStart,
7519 cx: &mut ViewContext<Self>,
7520 ) {
7521 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7522 s.move_cursors_with(|map, head, _| {
7523 (
7524 movement::previous_word_start(map, head),
7525 SelectionGoal::None,
7526 )
7527 });
7528 })
7529 }
7530
7531 pub fn move_to_previous_subword_start(
7532 &mut self,
7533 _: &MoveToPreviousSubwordStart,
7534 cx: &mut ViewContext<Self>,
7535 ) {
7536 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7537 s.move_cursors_with(|map, head, _| {
7538 (
7539 movement::previous_subword_start(map, head),
7540 SelectionGoal::None,
7541 )
7542 });
7543 })
7544 }
7545
7546 pub fn select_to_previous_word_start(
7547 &mut self,
7548 _: &SelectToPreviousWordStart,
7549 cx: &mut ViewContext<Self>,
7550 ) {
7551 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7552 s.move_heads_with(|map, head, _| {
7553 (
7554 movement::previous_word_start(map, head),
7555 SelectionGoal::None,
7556 )
7557 });
7558 })
7559 }
7560
7561 pub fn select_to_previous_subword_start(
7562 &mut self,
7563 _: &SelectToPreviousSubwordStart,
7564 cx: &mut ViewContext<Self>,
7565 ) {
7566 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7567 s.move_heads_with(|map, head, _| {
7568 (
7569 movement::previous_subword_start(map, head),
7570 SelectionGoal::None,
7571 )
7572 });
7573 })
7574 }
7575
7576 pub fn delete_to_previous_word_start(
7577 &mut self,
7578 action: &DeleteToPreviousWordStart,
7579 cx: &mut ViewContext<Self>,
7580 ) {
7581 self.transact(cx, |this, cx| {
7582 this.select_autoclose_pair(cx);
7583 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7584 let line_mode = s.line_mode;
7585 s.move_with(|map, selection| {
7586 if selection.is_empty() && !line_mode {
7587 let cursor = if action.ignore_newlines {
7588 movement::previous_word_start(map, selection.head())
7589 } else {
7590 movement::previous_word_start_or_newline(map, selection.head())
7591 };
7592 selection.set_head(cursor, SelectionGoal::None);
7593 }
7594 });
7595 });
7596 this.insert("", cx);
7597 });
7598 }
7599
7600 pub fn delete_to_previous_subword_start(
7601 &mut self,
7602 _: &DeleteToPreviousSubwordStart,
7603 cx: &mut ViewContext<Self>,
7604 ) {
7605 self.transact(cx, |this, cx| {
7606 this.select_autoclose_pair(cx);
7607 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7608 let line_mode = s.line_mode;
7609 s.move_with(|map, selection| {
7610 if selection.is_empty() && !line_mode {
7611 let cursor = movement::previous_subword_start(map, selection.head());
7612 selection.set_head(cursor, SelectionGoal::None);
7613 }
7614 });
7615 });
7616 this.insert("", cx);
7617 });
7618 }
7619
7620 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7621 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7622 s.move_cursors_with(|map, head, _| {
7623 (movement::next_word_end(map, head), SelectionGoal::None)
7624 });
7625 })
7626 }
7627
7628 pub fn move_to_next_subword_end(
7629 &mut self,
7630 _: &MoveToNextSubwordEnd,
7631 cx: &mut ViewContext<Self>,
7632 ) {
7633 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7634 s.move_cursors_with(|map, head, _| {
7635 (movement::next_subword_end(map, head), SelectionGoal::None)
7636 });
7637 })
7638 }
7639
7640 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7641 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7642 s.move_heads_with(|map, head, _| {
7643 (movement::next_word_end(map, head), SelectionGoal::None)
7644 });
7645 })
7646 }
7647
7648 pub fn select_to_next_subword_end(
7649 &mut self,
7650 _: &SelectToNextSubwordEnd,
7651 cx: &mut ViewContext<Self>,
7652 ) {
7653 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7654 s.move_heads_with(|map, head, _| {
7655 (movement::next_subword_end(map, head), SelectionGoal::None)
7656 });
7657 })
7658 }
7659
7660 pub fn delete_to_next_word_end(
7661 &mut self,
7662 action: &DeleteToNextWordEnd,
7663 cx: &mut ViewContext<Self>,
7664 ) {
7665 self.transact(cx, |this, cx| {
7666 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7667 let line_mode = s.line_mode;
7668 s.move_with(|map, selection| {
7669 if selection.is_empty() && !line_mode {
7670 let cursor = if action.ignore_newlines {
7671 movement::next_word_end(map, selection.head())
7672 } else {
7673 movement::next_word_end_or_newline(map, selection.head())
7674 };
7675 selection.set_head(cursor, SelectionGoal::None);
7676 }
7677 });
7678 });
7679 this.insert("", cx);
7680 });
7681 }
7682
7683 pub fn delete_to_next_subword_end(
7684 &mut self,
7685 _: &DeleteToNextSubwordEnd,
7686 cx: &mut ViewContext<Self>,
7687 ) {
7688 self.transact(cx, |this, cx| {
7689 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7690 s.move_with(|map, selection| {
7691 if selection.is_empty() {
7692 let cursor = movement::next_subword_end(map, selection.head());
7693 selection.set_head(cursor, SelectionGoal::None);
7694 }
7695 });
7696 });
7697 this.insert("", cx);
7698 });
7699 }
7700
7701 pub fn move_to_beginning_of_line(
7702 &mut self,
7703 action: &MoveToBeginningOfLine,
7704 cx: &mut ViewContext<Self>,
7705 ) {
7706 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7707 s.move_cursors_with(|map, head, _| {
7708 (
7709 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7710 SelectionGoal::None,
7711 )
7712 });
7713 })
7714 }
7715
7716 pub fn select_to_beginning_of_line(
7717 &mut self,
7718 action: &SelectToBeginningOfLine,
7719 cx: &mut ViewContext<Self>,
7720 ) {
7721 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7722 s.move_heads_with(|map, head, _| {
7723 (
7724 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7725 SelectionGoal::None,
7726 )
7727 });
7728 });
7729 }
7730
7731 pub fn delete_to_beginning_of_line(
7732 &mut self,
7733 _: &DeleteToBeginningOfLine,
7734 cx: &mut ViewContext<Self>,
7735 ) {
7736 self.transact(cx, |this, cx| {
7737 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7738 s.move_with(|_, selection| {
7739 selection.reversed = true;
7740 });
7741 });
7742
7743 this.select_to_beginning_of_line(
7744 &SelectToBeginningOfLine {
7745 stop_at_soft_wraps: false,
7746 },
7747 cx,
7748 );
7749 this.backspace(&Backspace, cx);
7750 });
7751 }
7752
7753 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7754 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7755 s.move_cursors_with(|map, head, _| {
7756 (
7757 movement::line_end(map, head, action.stop_at_soft_wraps),
7758 SelectionGoal::None,
7759 )
7760 });
7761 })
7762 }
7763
7764 pub fn select_to_end_of_line(
7765 &mut self,
7766 action: &SelectToEndOfLine,
7767 cx: &mut ViewContext<Self>,
7768 ) {
7769 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7770 s.move_heads_with(|map, head, _| {
7771 (
7772 movement::line_end(map, head, action.stop_at_soft_wraps),
7773 SelectionGoal::None,
7774 )
7775 });
7776 })
7777 }
7778
7779 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7780 self.transact(cx, |this, cx| {
7781 this.select_to_end_of_line(
7782 &SelectToEndOfLine {
7783 stop_at_soft_wraps: false,
7784 },
7785 cx,
7786 );
7787 this.delete(&Delete, cx);
7788 });
7789 }
7790
7791 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7792 self.transact(cx, |this, cx| {
7793 this.select_to_end_of_line(
7794 &SelectToEndOfLine {
7795 stop_at_soft_wraps: false,
7796 },
7797 cx,
7798 );
7799 this.cut(&Cut, cx);
7800 });
7801 }
7802
7803 pub fn move_to_start_of_paragraph(
7804 &mut self,
7805 _: &MoveToStartOfParagraph,
7806 cx: &mut ViewContext<Self>,
7807 ) {
7808 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7809 cx.propagate();
7810 return;
7811 }
7812
7813 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7814 s.move_with(|map, selection| {
7815 selection.collapse_to(
7816 movement::start_of_paragraph(map, selection.head(), 1),
7817 SelectionGoal::None,
7818 )
7819 });
7820 })
7821 }
7822
7823 pub fn move_to_end_of_paragraph(
7824 &mut self,
7825 _: &MoveToEndOfParagraph,
7826 cx: &mut ViewContext<Self>,
7827 ) {
7828 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7829 cx.propagate();
7830 return;
7831 }
7832
7833 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7834 s.move_with(|map, selection| {
7835 selection.collapse_to(
7836 movement::end_of_paragraph(map, selection.head(), 1),
7837 SelectionGoal::None,
7838 )
7839 });
7840 })
7841 }
7842
7843 pub fn select_to_start_of_paragraph(
7844 &mut self,
7845 _: &SelectToStartOfParagraph,
7846 cx: &mut ViewContext<Self>,
7847 ) {
7848 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7849 cx.propagate();
7850 return;
7851 }
7852
7853 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7854 s.move_heads_with(|map, head, _| {
7855 (
7856 movement::start_of_paragraph(map, head, 1),
7857 SelectionGoal::None,
7858 )
7859 });
7860 })
7861 }
7862
7863 pub fn select_to_end_of_paragraph(
7864 &mut self,
7865 _: &SelectToEndOfParagraph,
7866 cx: &mut ViewContext<Self>,
7867 ) {
7868 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7869 cx.propagate();
7870 return;
7871 }
7872
7873 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7874 s.move_heads_with(|map, head, _| {
7875 (
7876 movement::end_of_paragraph(map, head, 1),
7877 SelectionGoal::None,
7878 )
7879 });
7880 })
7881 }
7882
7883 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7884 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7885 cx.propagate();
7886 return;
7887 }
7888
7889 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7890 s.select_ranges(vec![0..0]);
7891 });
7892 }
7893
7894 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7895 let mut selection = self.selections.last::<Point>(cx);
7896 selection.set_head(Point::zero(), SelectionGoal::None);
7897
7898 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7899 s.select(vec![selection]);
7900 });
7901 }
7902
7903 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7904 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7905 cx.propagate();
7906 return;
7907 }
7908
7909 let cursor = self.buffer.read(cx).read(cx).len();
7910 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7911 s.select_ranges(vec![cursor..cursor])
7912 });
7913 }
7914
7915 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7916 self.nav_history = nav_history;
7917 }
7918
7919 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7920 self.nav_history.as_ref()
7921 }
7922
7923 fn push_to_nav_history(
7924 &mut self,
7925 cursor_anchor: Anchor,
7926 new_position: Option<Point>,
7927 cx: &mut ViewContext<Self>,
7928 ) {
7929 if let Some(nav_history) = self.nav_history.as_mut() {
7930 let buffer = self.buffer.read(cx).read(cx);
7931 let cursor_position = cursor_anchor.to_point(&buffer);
7932 let scroll_state = self.scroll_manager.anchor();
7933 let scroll_top_row = scroll_state.top_row(&buffer);
7934 drop(buffer);
7935
7936 if let Some(new_position) = new_position {
7937 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7938 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7939 return;
7940 }
7941 }
7942
7943 nav_history.push(
7944 Some(NavigationData {
7945 cursor_anchor,
7946 cursor_position,
7947 scroll_anchor: scroll_state,
7948 scroll_top_row,
7949 }),
7950 cx,
7951 );
7952 }
7953 }
7954
7955 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7956 let buffer = self.buffer.read(cx).snapshot(cx);
7957 let mut selection = self.selections.first::<usize>(cx);
7958 selection.set_head(buffer.len(), SelectionGoal::None);
7959 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7960 s.select(vec![selection]);
7961 });
7962 }
7963
7964 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7965 let end = self.buffer.read(cx).read(cx).len();
7966 self.change_selections(None, cx, |s| {
7967 s.select_ranges(vec![0..end]);
7968 });
7969 }
7970
7971 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7972 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7973 let mut selections = self.selections.all::<Point>(cx);
7974 let max_point = display_map.buffer_snapshot.max_point();
7975 for selection in &mut selections {
7976 let rows = selection.spanned_rows(true, &display_map);
7977 selection.start = Point::new(rows.start.0, 0);
7978 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7979 selection.reversed = false;
7980 }
7981 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7982 s.select(selections);
7983 });
7984 }
7985
7986 pub fn split_selection_into_lines(
7987 &mut self,
7988 _: &SplitSelectionIntoLines,
7989 cx: &mut ViewContext<Self>,
7990 ) {
7991 let mut to_unfold = Vec::new();
7992 let mut new_selection_ranges = Vec::new();
7993 {
7994 let selections = self.selections.all::<Point>(cx);
7995 let buffer = self.buffer.read(cx).read(cx);
7996 for selection in selections {
7997 for row in selection.start.row..selection.end.row {
7998 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7999 new_selection_ranges.push(cursor..cursor);
8000 }
8001 new_selection_ranges.push(selection.end..selection.end);
8002 to_unfold.push(selection.start..selection.end);
8003 }
8004 }
8005 self.unfold_ranges(&to_unfold, true, true, cx);
8006 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8007 s.select_ranges(new_selection_ranges);
8008 });
8009 }
8010
8011 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8012 self.add_selection(true, cx);
8013 }
8014
8015 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8016 self.add_selection(false, cx);
8017 }
8018
8019 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8020 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8021 let mut selections = self.selections.all::<Point>(cx);
8022 let text_layout_details = self.text_layout_details(cx);
8023 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8024 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8025 let range = oldest_selection.display_range(&display_map).sorted();
8026
8027 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8028 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8029 let positions = start_x.min(end_x)..start_x.max(end_x);
8030
8031 selections.clear();
8032 let mut stack = Vec::new();
8033 for row in range.start.row().0..=range.end.row().0 {
8034 if let Some(selection) = self.selections.build_columnar_selection(
8035 &display_map,
8036 DisplayRow(row),
8037 &positions,
8038 oldest_selection.reversed,
8039 &text_layout_details,
8040 ) {
8041 stack.push(selection.id);
8042 selections.push(selection);
8043 }
8044 }
8045
8046 if above {
8047 stack.reverse();
8048 }
8049
8050 AddSelectionsState { above, stack }
8051 });
8052
8053 let last_added_selection = *state.stack.last().unwrap();
8054 let mut new_selections = Vec::new();
8055 if above == state.above {
8056 let end_row = if above {
8057 DisplayRow(0)
8058 } else {
8059 display_map.max_point().row()
8060 };
8061
8062 'outer: for selection in selections {
8063 if selection.id == last_added_selection {
8064 let range = selection.display_range(&display_map).sorted();
8065 debug_assert_eq!(range.start.row(), range.end.row());
8066 let mut row = range.start.row();
8067 let positions =
8068 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8069 px(start)..px(end)
8070 } else {
8071 let start_x =
8072 display_map.x_for_display_point(range.start, &text_layout_details);
8073 let end_x =
8074 display_map.x_for_display_point(range.end, &text_layout_details);
8075 start_x.min(end_x)..start_x.max(end_x)
8076 };
8077
8078 while row != end_row {
8079 if above {
8080 row.0 -= 1;
8081 } else {
8082 row.0 += 1;
8083 }
8084
8085 if let Some(new_selection) = self.selections.build_columnar_selection(
8086 &display_map,
8087 row,
8088 &positions,
8089 selection.reversed,
8090 &text_layout_details,
8091 ) {
8092 state.stack.push(new_selection.id);
8093 if above {
8094 new_selections.push(new_selection);
8095 new_selections.push(selection);
8096 } else {
8097 new_selections.push(selection);
8098 new_selections.push(new_selection);
8099 }
8100
8101 continue 'outer;
8102 }
8103 }
8104 }
8105
8106 new_selections.push(selection);
8107 }
8108 } else {
8109 new_selections = selections;
8110 new_selections.retain(|s| s.id != last_added_selection);
8111 state.stack.pop();
8112 }
8113
8114 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8115 s.select(new_selections);
8116 });
8117 if state.stack.len() > 1 {
8118 self.add_selections_state = Some(state);
8119 }
8120 }
8121
8122 pub fn select_next_match_internal(
8123 &mut self,
8124 display_map: &DisplaySnapshot,
8125 replace_newest: bool,
8126 autoscroll: Option<Autoscroll>,
8127 cx: &mut ViewContext<Self>,
8128 ) -> Result<()> {
8129 fn select_next_match_ranges(
8130 this: &mut Editor,
8131 range: Range<usize>,
8132 replace_newest: bool,
8133 auto_scroll: Option<Autoscroll>,
8134 cx: &mut ViewContext<Editor>,
8135 ) {
8136 this.unfold_ranges(&[range.clone()], false, true, cx);
8137 this.change_selections(auto_scroll, cx, |s| {
8138 if replace_newest {
8139 s.delete(s.newest_anchor().id);
8140 }
8141 s.insert_range(range.clone());
8142 });
8143 }
8144
8145 let buffer = &display_map.buffer_snapshot;
8146 let mut selections = self.selections.all::<usize>(cx);
8147 if let Some(mut select_next_state) = self.select_next_state.take() {
8148 let query = &select_next_state.query;
8149 if !select_next_state.done {
8150 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8151 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8152 let mut next_selected_range = None;
8153
8154 let bytes_after_last_selection =
8155 buffer.bytes_in_range(last_selection.end..buffer.len());
8156 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8157 let query_matches = query
8158 .stream_find_iter(bytes_after_last_selection)
8159 .map(|result| (last_selection.end, result))
8160 .chain(
8161 query
8162 .stream_find_iter(bytes_before_first_selection)
8163 .map(|result| (0, result)),
8164 );
8165
8166 for (start_offset, query_match) in query_matches {
8167 let query_match = query_match.unwrap(); // can only fail due to I/O
8168 let offset_range =
8169 start_offset + query_match.start()..start_offset + query_match.end();
8170 let display_range = offset_range.start.to_display_point(display_map)
8171 ..offset_range.end.to_display_point(display_map);
8172
8173 if !select_next_state.wordwise
8174 || (!movement::is_inside_word(display_map, display_range.start)
8175 && !movement::is_inside_word(display_map, display_range.end))
8176 {
8177 // TODO: This is n^2, because we might check all the selections
8178 if !selections
8179 .iter()
8180 .any(|selection| selection.range().overlaps(&offset_range))
8181 {
8182 next_selected_range = Some(offset_range);
8183 break;
8184 }
8185 }
8186 }
8187
8188 if let Some(next_selected_range) = next_selected_range {
8189 select_next_match_ranges(
8190 self,
8191 next_selected_range,
8192 replace_newest,
8193 autoscroll,
8194 cx,
8195 );
8196 } else {
8197 select_next_state.done = true;
8198 }
8199 }
8200
8201 self.select_next_state = Some(select_next_state);
8202 } else {
8203 let mut only_carets = true;
8204 let mut same_text_selected = true;
8205 let mut selected_text = None;
8206
8207 let mut selections_iter = selections.iter().peekable();
8208 while let Some(selection) = selections_iter.next() {
8209 if selection.start != selection.end {
8210 only_carets = false;
8211 }
8212
8213 if same_text_selected {
8214 if selected_text.is_none() {
8215 selected_text =
8216 Some(buffer.text_for_range(selection.range()).collect::<String>());
8217 }
8218
8219 if let Some(next_selection) = selections_iter.peek() {
8220 if next_selection.range().len() == selection.range().len() {
8221 let next_selected_text = buffer
8222 .text_for_range(next_selection.range())
8223 .collect::<String>();
8224 if Some(next_selected_text) != selected_text {
8225 same_text_selected = false;
8226 selected_text = None;
8227 }
8228 } else {
8229 same_text_selected = false;
8230 selected_text = None;
8231 }
8232 }
8233 }
8234 }
8235
8236 if only_carets {
8237 for selection in &mut selections {
8238 let word_range = movement::surrounding_word(
8239 display_map,
8240 selection.start.to_display_point(display_map),
8241 );
8242 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8243 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8244 selection.goal = SelectionGoal::None;
8245 selection.reversed = false;
8246 select_next_match_ranges(
8247 self,
8248 selection.start..selection.end,
8249 replace_newest,
8250 autoscroll,
8251 cx,
8252 );
8253 }
8254
8255 if selections.len() == 1 {
8256 let selection = selections
8257 .last()
8258 .expect("ensured that there's only one selection");
8259 let query = buffer
8260 .text_for_range(selection.start..selection.end)
8261 .collect::<String>();
8262 let is_empty = query.is_empty();
8263 let select_state = SelectNextState {
8264 query: AhoCorasick::new(&[query])?,
8265 wordwise: true,
8266 done: is_empty,
8267 };
8268 self.select_next_state = Some(select_state);
8269 } else {
8270 self.select_next_state = None;
8271 }
8272 } else if let Some(selected_text) = selected_text {
8273 self.select_next_state = Some(SelectNextState {
8274 query: AhoCorasick::new(&[selected_text])?,
8275 wordwise: false,
8276 done: false,
8277 });
8278 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8279 }
8280 }
8281 Ok(())
8282 }
8283
8284 pub fn select_all_matches(
8285 &mut self,
8286 _action: &SelectAllMatches,
8287 cx: &mut ViewContext<Self>,
8288 ) -> Result<()> {
8289 self.push_to_selection_history();
8290 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8291
8292 self.select_next_match_internal(&display_map, false, None, cx)?;
8293 let Some(select_next_state) = self.select_next_state.as_mut() else {
8294 return Ok(());
8295 };
8296 if select_next_state.done {
8297 return Ok(());
8298 }
8299
8300 let mut new_selections = self.selections.all::<usize>(cx);
8301
8302 let buffer = &display_map.buffer_snapshot;
8303 let query_matches = select_next_state
8304 .query
8305 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8306
8307 for query_match in query_matches {
8308 let query_match = query_match.unwrap(); // can only fail due to I/O
8309 let offset_range = query_match.start()..query_match.end();
8310 let display_range = offset_range.start.to_display_point(&display_map)
8311 ..offset_range.end.to_display_point(&display_map);
8312
8313 if !select_next_state.wordwise
8314 || (!movement::is_inside_word(&display_map, display_range.start)
8315 && !movement::is_inside_word(&display_map, display_range.end))
8316 {
8317 self.selections.change_with(cx, |selections| {
8318 new_selections.push(Selection {
8319 id: selections.new_selection_id(),
8320 start: offset_range.start,
8321 end: offset_range.end,
8322 reversed: false,
8323 goal: SelectionGoal::None,
8324 });
8325 });
8326 }
8327 }
8328
8329 new_selections.sort_by_key(|selection| selection.start);
8330 let mut ix = 0;
8331 while ix + 1 < new_selections.len() {
8332 let current_selection = &new_selections[ix];
8333 let next_selection = &new_selections[ix + 1];
8334 if current_selection.range().overlaps(&next_selection.range()) {
8335 if current_selection.id < next_selection.id {
8336 new_selections.remove(ix + 1);
8337 } else {
8338 new_selections.remove(ix);
8339 }
8340 } else {
8341 ix += 1;
8342 }
8343 }
8344
8345 select_next_state.done = true;
8346 self.unfold_ranges(
8347 &new_selections
8348 .iter()
8349 .map(|selection| selection.range())
8350 .collect::<Vec<_>>(),
8351 false,
8352 false,
8353 cx,
8354 );
8355 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8356 selections.select(new_selections)
8357 });
8358
8359 Ok(())
8360 }
8361
8362 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8363 self.push_to_selection_history();
8364 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8365 self.select_next_match_internal(
8366 &display_map,
8367 action.replace_newest,
8368 Some(Autoscroll::newest()),
8369 cx,
8370 )?;
8371 Ok(())
8372 }
8373
8374 pub fn select_previous(
8375 &mut self,
8376 action: &SelectPrevious,
8377 cx: &mut ViewContext<Self>,
8378 ) -> Result<()> {
8379 self.push_to_selection_history();
8380 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8381 let buffer = &display_map.buffer_snapshot;
8382 let mut selections = self.selections.all::<usize>(cx);
8383 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8384 let query = &select_prev_state.query;
8385 if !select_prev_state.done {
8386 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8387 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8388 let mut next_selected_range = None;
8389 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8390 let bytes_before_last_selection =
8391 buffer.reversed_bytes_in_range(0..last_selection.start);
8392 let bytes_after_first_selection =
8393 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8394 let query_matches = query
8395 .stream_find_iter(bytes_before_last_selection)
8396 .map(|result| (last_selection.start, result))
8397 .chain(
8398 query
8399 .stream_find_iter(bytes_after_first_selection)
8400 .map(|result| (buffer.len(), result)),
8401 );
8402 for (end_offset, query_match) in query_matches {
8403 let query_match = query_match.unwrap(); // can only fail due to I/O
8404 let offset_range =
8405 end_offset - query_match.end()..end_offset - query_match.start();
8406 let display_range = offset_range.start.to_display_point(&display_map)
8407 ..offset_range.end.to_display_point(&display_map);
8408
8409 if !select_prev_state.wordwise
8410 || (!movement::is_inside_word(&display_map, display_range.start)
8411 && !movement::is_inside_word(&display_map, display_range.end))
8412 {
8413 next_selected_range = Some(offset_range);
8414 break;
8415 }
8416 }
8417
8418 if let Some(next_selected_range) = next_selected_range {
8419 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8420 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8421 if action.replace_newest {
8422 s.delete(s.newest_anchor().id);
8423 }
8424 s.insert_range(next_selected_range);
8425 });
8426 } else {
8427 select_prev_state.done = true;
8428 }
8429 }
8430
8431 self.select_prev_state = Some(select_prev_state);
8432 } else {
8433 let mut only_carets = true;
8434 let mut same_text_selected = true;
8435 let mut selected_text = None;
8436
8437 let mut selections_iter = selections.iter().peekable();
8438 while let Some(selection) = selections_iter.next() {
8439 if selection.start != selection.end {
8440 only_carets = false;
8441 }
8442
8443 if same_text_selected {
8444 if selected_text.is_none() {
8445 selected_text =
8446 Some(buffer.text_for_range(selection.range()).collect::<String>());
8447 }
8448
8449 if let Some(next_selection) = selections_iter.peek() {
8450 if next_selection.range().len() == selection.range().len() {
8451 let next_selected_text = buffer
8452 .text_for_range(next_selection.range())
8453 .collect::<String>();
8454 if Some(next_selected_text) != selected_text {
8455 same_text_selected = false;
8456 selected_text = None;
8457 }
8458 } else {
8459 same_text_selected = false;
8460 selected_text = None;
8461 }
8462 }
8463 }
8464 }
8465
8466 if only_carets {
8467 for selection in &mut selections {
8468 let word_range = movement::surrounding_word(
8469 &display_map,
8470 selection.start.to_display_point(&display_map),
8471 );
8472 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8473 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8474 selection.goal = SelectionGoal::None;
8475 selection.reversed = false;
8476 }
8477 if selections.len() == 1 {
8478 let selection = selections
8479 .last()
8480 .expect("ensured that there's only one selection");
8481 let query = buffer
8482 .text_for_range(selection.start..selection.end)
8483 .collect::<String>();
8484 let is_empty = query.is_empty();
8485 let select_state = SelectNextState {
8486 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8487 wordwise: true,
8488 done: is_empty,
8489 };
8490 self.select_prev_state = Some(select_state);
8491 } else {
8492 self.select_prev_state = None;
8493 }
8494
8495 self.unfold_ranges(
8496 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8497 false,
8498 true,
8499 cx,
8500 );
8501 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8502 s.select(selections);
8503 });
8504 } else if let Some(selected_text) = selected_text {
8505 self.select_prev_state = Some(SelectNextState {
8506 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8507 wordwise: false,
8508 done: false,
8509 });
8510 self.select_previous(action, cx)?;
8511 }
8512 }
8513 Ok(())
8514 }
8515
8516 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8517 if self.read_only(cx) {
8518 return;
8519 }
8520 let text_layout_details = &self.text_layout_details(cx);
8521 self.transact(cx, |this, cx| {
8522 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8523 let mut edits = Vec::new();
8524 let mut selection_edit_ranges = Vec::new();
8525 let mut last_toggled_row = None;
8526 let snapshot = this.buffer.read(cx).read(cx);
8527 let empty_str: Arc<str> = Arc::default();
8528 let mut suffixes_inserted = Vec::new();
8529 let ignore_indent = action.ignore_indent;
8530
8531 fn comment_prefix_range(
8532 snapshot: &MultiBufferSnapshot,
8533 row: MultiBufferRow,
8534 comment_prefix: &str,
8535 comment_prefix_whitespace: &str,
8536 ignore_indent: bool,
8537 ) -> Range<Point> {
8538 let indent_size = if ignore_indent {
8539 0
8540 } else {
8541 snapshot.indent_size_for_line(row).len
8542 };
8543
8544 let start = Point::new(row.0, indent_size);
8545
8546 let mut line_bytes = snapshot
8547 .bytes_in_range(start..snapshot.max_point())
8548 .flatten()
8549 .copied();
8550
8551 // If this line currently begins with the line comment prefix, then record
8552 // the range containing the prefix.
8553 if line_bytes
8554 .by_ref()
8555 .take(comment_prefix.len())
8556 .eq(comment_prefix.bytes())
8557 {
8558 // Include any whitespace that matches the comment prefix.
8559 let matching_whitespace_len = line_bytes
8560 .zip(comment_prefix_whitespace.bytes())
8561 .take_while(|(a, b)| a == b)
8562 .count() as u32;
8563 let end = Point::new(
8564 start.row,
8565 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8566 );
8567 start..end
8568 } else {
8569 start..start
8570 }
8571 }
8572
8573 fn comment_suffix_range(
8574 snapshot: &MultiBufferSnapshot,
8575 row: MultiBufferRow,
8576 comment_suffix: &str,
8577 comment_suffix_has_leading_space: bool,
8578 ) -> Range<Point> {
8579 let end = Point::new(row.0, snapshot.line_len(row));
8580 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8581
8582 let mut line_end_bytes = snapshot
8583 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8584 .flatten()
8585 .copied();
8586
8587 let leading_space_len = if suffix_start_column > 0
8588 && line_end_bytes.next() == Some(b' ')
8589 && comment_suffix_has_leading_space
8590 {
8591 1
8592 } else {
8593 0
8594 };
8595
8596 // If this line currently begins with the line comment prefix, then record
8597 // the range containing the prefix.
8598 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8599 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8600 start..end
8601 } else {
8602 end..end
8603 }
8604 }
8605
8606 // TODO: Handle selections that cross excerpts
8607 for selection in &mut selections {
8608 let start_column = snapshot
8609 .indent_size_for_line(MultiBufferRow(selection.start.row))
8610 .len;
8611 let language = if let Some(language) =
8612 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8613 {
8614 language
8615 } else {
8616 continue;
8617 };
8618
8619 selection_edit_ranges.clear();
8620
8621 // If multiple selections contain a given row, avoid processing that
8622 // row more than once.
8623 let mut start_row = MultiBufferRow(selection.start.row);
8624 if last_toggled_row == Some(start_row) {
8625 start_row = start_row.next_row();
8626 }
8627 let end_row =
8628 if selection.end.row > selection.start.row && selection.end.column == 0 {
8629 MultiBufferRow(selection.end.row - 1)
8630 } else {
8631 MultiBufferRow(selection.end.row)
8632 };
8633 last_toggled_row = Some(end_row);
8634
8635 if start_row > end_row {
8636 continue;
8637 }
8638
8639 // If the language has line comments, toggle those.
8640 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8641
8642 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8643 if ignore_indent {
8644 full_comment_prefixes = full_comment_prefixes
8645 .into_iter()
8646 .map(|s| Arc::from(s.trim_end()))
8647 .collect();
8648 }
8649
8650 if !full_comment_prefixes.is_empty() {
8651 let first_prefix = full_comment_prefixes
8652 .first()
8653 .expect("prefixes is non-empty");
8654 let prefix_trimmed_lengths = full_comment_prefixes
8655 .iter()
8656 .map(|p| p.trim_end_matches(' ').len())
8657 .collect::<SmallVec<[usize; 4]>>();
8658
8659 let mut all_selection_lines_are_comments = true;
8660
8661 for row in start_row.0..=end_row.0 {
8662 let row = MultiBufferRow(row);
8663 if start_row < end_row && snapshot.is_line_blank(row) {
8664 continue;
8665 }
8666
8667 let prefix_range = full_comment_prefixes
8668 .iter()
8669 .zip(prefix_trimmed_lengths.iter().copied())
8670 .map(|(prefix, trimmed_prefix_len)| {
8671 comment_prefix_range(
8672 snapshot.deref(),
8673 row,
8674 &prefix[..trimmed_prefix_len],
8675 &prefix[trimmed_prefix_len..],
8676 ignore_indent,
8677 )
8678 })
8679 .max_by_key(|range| range.end.column - range.start.column)
8680 .expect("prefixes is non-empty");
8681
8682 if prefix_range.is_empty() {
8683 all_selection_lines_are_comments = false;
8684 }
8685
8686 selection_edit_ranges.push(prefix_range);
8687 }
8688
8689 if all_selection_lines_are_comments {
8690 edits.extend(
8691 selection_edit_ranges
8692 .iter()
8693 .cloned()
8694 .map(|range| (range, empty_str.clone())),
8695 );
8696 } else {
8697 let min_column = selection_edit_ranges
8698 .iter()
8699 .map(|range| range.start.column)
8700 .min()
8701 .unwrap_or(0);
8702 edits.extend(selection_edit_ranges.iter().map(|range| {
8703 let position = Point::new(range.start.row, min_column);
8704 (position..position, first_prefix.clone())
8705 }));
8706 }
8707 } else if let Some((full_comment_prefix, comment_suffix)) =
8708 language.block_comment_delimiters()
8709 {
8710 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8711 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8712 let prefix_range = comment_prefix_range(
8713 snapshot.deref(),
8714 start_row,
8715 comment_prefix,
8716 comment_prefix_whitespace,
8717 ignore_indent,
8718 );
8719 let suffix_range = comment_suffix_range(
8720 snapshot.deref(),
8721 end_row,
8722 comment_suffix.trim_start_matches(' '),
8723 comment_suffix.starts_with(' '),
8724 );
8725
8726 if prefix_range.is_empty() || suffix_range.is_empty() {
8727 edits.push((
8728 prefix_range.start..prefix_range.start,
8729 full_comment_prefix.clone(),
8730 ));
8731 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8732 suffixes_inserted.push((end_row, comment_suffix.len()));
8733 } else {
8734 edits.push((prefix_range, empty_str.clone()));
8735 edits.push((suffix_range, empty_str.clone()));
8736 }
8737 } else {
8738 continue;
8739 }
8740 }
8741
8742 drop(snapshot);
8743 this.buffer.update(cx, |buffer, cx| {
8744 buffer.edit(edits, None, cx);
8745 });
8746
8747 // Adjust selections so that they end before any comment suffixes that
8748 // were inserted.
8749 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8750 let mut selections = this.selections.all::<Point>(cx);
8751 let snapshot = this.buffer.read(cx).read(cx);
8752 for selection in &mut selections {
8753 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8754 match row.cmp(&MultiBufferRow(selection.end.row)) {
8755 Ordering::Less => {
8756 suffixes_inserted.next();
8757 continue;
8758 }
8759 Ordering::Greater => break,
8760 Ordering::Equal => {
8761 if selection.end.column == snapshot.line_len(row) {
8762 if selection.is_empty() {
8763 selection.start.column -= suffix_len as u32;
8764 }
8765 selection.end.column -= suffix_len as u32;
8766 }
8767 break;
8768 }
8769 }
8770 }
8771 }
8772
8773 drop(snapshot);
8774 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8775
8776 let selections = this.selections.all::<Point>(cx);
8777 let selections_on_single_row = selections.windows(2).all(|selections| {
8778 selections[0].start.row == selections[1].start.row
8779 && selections[0].end.row == selections[1].end.row
8780 && selections[0].start.row == selections[0].end.row
8781 });
8782 let selections_selecting = selections
8783 .iter()
8784 .any(|selection| selection.start != selection.end);
8785 let advance_downwards = action.advance_downwards
8786 && selections_on_single_row
8787 && !selections_selecting
8788 && !matches!(this.mode, EditorMode::SingleLine { .. });
8789
8790 if advance_downwards {
8791 let snapshot = this.buffer.read(cx).snapshot(cx);
8792
8793 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8794 s.move_cursors_with(|display_snapshot, display_point, _| {
8795 let mut point = display_point.to_point(display_snapshot);
8796 point.row += 1;
8797 point = snapshot.clip_point(point, Bias::Left);
8798 let display_point = point.to_display_point(display_snapshot);
8799 let goal = SelectionGoal::HorizontalPosition(
8800 display_snapshot
8801 .x_for_display_point(display_point, text_layout_details)
8802 .into(),
8803 );
8804 (display_point, goal)
8805 })
8806 });
8807 }
8808 });
8809 }
8810
8811 pub fn select_enclosing_symbol(
8812 &mut self,
8813 _: &SelectEnclosingSymbol,
8814 cx: &mut ViewContext<Self>,
8815 ) {
8816 let buffer = self.buffer.read(cx).snapshot(cx);
8817 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8818
8819 fn update_selection(
8820 selection: &Selection<usize>,
8821 buffer_snap: &MultiBufferSnapshot,
8822 ) -> Option<Selection<usize>> {
8823 let cursor = selection.head();
8824 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8825 for symbol in symbols.iter().rev() {
8826 let start = symbol.range.start.to_offset(buffer_snap);
8827 let end = symbol.range.end.to_offset(buffer_snap);
8828 let new_range = start..end;
8829 if start < selection.start || end > selection.end {
8830 return Some(Selection {
8831 id: selection.id,
8832 start: new_range.start,
8833 end: new_range.end,
8834 goal: SelectionGoal::None,
8835 reversed: selection.reversed,
8836 });
8837 }
8838 }
8839 None
8840 }
8841
8842 let mut selected_larger_symbol = false;
8843 let new_selections = old_selections
8844 .iter()
8845 .map(|selection| match update_selection(selection, &buffer) {
8846 Some(new_selection) => {
8847 if new_selection.range() != selection.range() {
8848 selected_larger_symbol = true;
8849 }
8850 new_selection
8851 }
8852 None => selection.clone(),
8853 })
8854 .collect::<Vec<_>>();
8855
8856 if selected_larger_symbol {
8857 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8858 s.select(new_selections);
8859 });
8860 }
8861 }
8862
8863 pub fn select_larger_syntax_node(
8864 &mut self,
8865 _: &SelectLargerSyntaxNode,
8866 cx: &mut ViewContext<Self>,
8867 ) {
8868 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8869 let buffer = self.buffer.read(cx).snapshot(cx);
8870 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8871
8872 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8873 let mut selected_larger_node = false;
8874 let new_selections = old_selections
8875 .iter()
8876 .map(|selection| {
8877 let old_range = selection.start..selection.end;
8878 let mut new_range = old_range.clone();
8879 let mut new_node = None;
8880 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
8881 {
8882 new_node = Some(node);
8883 new_range = containing_range;
8884 if !display_map.intersects_fold(new_range.start)
8885 && !display_map.intersects_fold(new_range.end)
8886 {
8887 break;
8888 }
8889 }
8890
8891 if let Some(node) = new_node {
8892 // Log the ancestor, to support using this action as a way to explore TreeSitter
8893 // nodes. Parent and grandparent are also logged because this operation will not
8894 // visit nodes that have the same range as their parent.
8895 log::info!("Node: {node:?}");
8896 let parent = node.parent();
8897 log::info!("Parent: {parent:?}");
8898 let grandparent = parent.and_then(|x| x.parent());
8899 log::info!("Grandparent: {grandparent:?}");
8900 }
8901
8902 selected_larger_node |= new_range != old_range;
8903 Selection {
8904 id: selection.id,
8905 start: new_range.start,
8906 end: new_range.end,
8907 goal: SelectionGoal::None,
8908 reversed: selection.reversed,
8909 }
8910 })
8911 .collect::<Vec<_>>();
8912
8913 if selected_larger_node {
8914 stack.push(old_selections);
8915 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8916 s.select(new_selections);
8917 });
8918 }
8919 self.select_larger_syntax_node_stack = stack;
8920 }
8921
8922 pub fn select_smaller_syntax_node(
8923 &mut self,
8924 _: &SelectSmallerSyntaxNode,
8925 cx: &mut ViewContext<Self>,
8926 ) {
8927 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8928 if let Some(selections) = stack.pop() {
8929 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8930 s.select(selections.to_vec());
8931 });
8932 }
8933 self.select_larger_syntax_node_stack = stack;
8934 }
8935
8936 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8937 if !EditorSettings::get_global(cx).gutter.runnables {
8938 self.clear_tasks();
8939 return Task::ready(());
8940 }
8941 let project = self.project.as_ref().map(Model::downgrade);
8942 cx.spawn(|this, mut cx| async move {
8943 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
8944 let Some(project) = project.and_then(|p| p.upgrade()) else {
8945 return;
8946 };
8947 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8948 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8949 }) else {
8950 return;
8951 };
8952
8953 let hide_runnables = project
8954 .update(&mut cx, |project, cx| {
8955 // Do not display any test indicators in non-dev server remote projects.
8956 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8957 })
8958 .unwrap_or(true);
8959 if hide_runnables {
8960 return;
8961 }
8962 let new_rows =
8963 cx.background_executor()
8964 .spawn({
8965 let snapshot = display_snapshot.clone();
8966 async move {
8967 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8968 }
8969 })
8970 .await;
8971 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8972
8973 this.update(&mut cx, |this, _| {
8974 this.clear_tasks();
8975 for (key, value) in rows {
8976 this.insert_tasks(key, value);
8977 }
8978 })
8979 .ok();
8980 })
8981 }
8982 fn fetch_runnable_ranges(
8983 snapshot: &DisplaySnapshot,
8984 range: Range<Anchor>,
8985 ) -> Vec<language::RunnableRange> {
8986 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8987 }
8988
8989 fn runnable_rows(
8990 project: Model<Project>,
8991 snapshot: DisplaySnapshot,
8992 runnable_ranges: Vec<RunnableRange>,
8993 mut cx: AsyncWindowContext,
8994 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8995 runnable_ranges
8996 .into_iter()
8997 .filter_map(|mut runnable| {
8998 let tasks = cx
8999 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9000 .ok()?;
9001 if tasks.is_empty() {
9002 return None;
9003 }
9004
9005 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9006
9007 let row = snapshot
9008 .buffer_snapshot
9009 .buffer_line_for_row(MultiBufferRow(point.row))?
9010 .1
9011 .start
9012 .row;
9013
9014 let context_range =
9015 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9016 Some((
9017 (runnable.buffer_id, row),
9018 RunnableTasks {
9019 templates: tasks,
9020 offset: MultiBufferOffset(runnable.run_range.start),
9021 context_range,
9022 column: point.column,
9023 extra_variables: runnable.extra_captures,
9024 },
9025 ))
9026 })
9027 .collect()
9028 }
9029
9030 fn templates_with_tags(
9031 project: &Model<Project>,
9032 runnable: &mut Runnable,
9033 cx: &WindowContext,
9034 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9035 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9036 let (worktree_id, file) = project
9037 .buffer_for_id(runnable.buffer, cx)
9038 .and_then(|buffer| buffer.read(cx).file())
9039 .map(|file| (file.worktree_id(cx), file.clone()))
9040 .unzip();
9041
9042 (
9043 project.task_store().read(cx).task_inventory().cloned(),
9044 worktree_id,
9045 file,
9046 )
9047 });
9048
9049 let tags = mem::take(&mut runnable.tags);
9050 let mut tags: Vec<_> = tags
9051 .into_iter()
9052 .flat_map(|tag| {
9053 let tag = tag.0.clone();
9054 inventory
9055 .as_ref()
9056 .into_iter()
9057 .flat_map(|inventory| {
9058 inventory.read(cx).list_tasks(
9059 file.clone(),
9060 Some(runnable.language.clone()),
9061 worktree_id,
9062 cx,
9063 )
9064 })
9065 .filter(move |(_, template)| {
9066 template.tags.iter().any(|source_tag| source_tag == &tag)
9067 })
9068 })
9069 .sorted_by_key(|(kind, _)| kind.to_owned())
9070 .collect();
9071 if let Some((leading_tag_source, _)) = tags.first() {
9072 // Strongest source wins; if we have worktree tag binding, prefer that to
9073 // global and language bindings;
9074 // if we have a global binding, prefer that to language binding.
9075 let first_mismatch = tags
9076 .iter()
9077 .position(|(tag_source, _)| tag_source != leading_tag_source);
9078 if let Some(index) = first_mismatch {
9079 tags.truncate(index);
9080 }
9081 }
9082
9083 tags
9084 }
9085
9086 pub fn move_to_enclosing_bracket(
9087 &mut self,
9088 _: &MoveToEnclosingBracket,
9089 cx: &mut ViewContext<Self>,
9090 ) {
9091 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9092 s.move_offsets_with(|snapshot, selection| {
9093 let Some(enclosing_bracket_ranges) =
9094 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9095 else {
9096 return;
9097 };
9098
9099 let mut best_length = usize::MAX;
9100 let mut best_inside = false;
9101 let mut best_in_bracket_range = false;
9102 let mut best_destination = None;
9103 for (open, close) in enclosing_bracket_ranges {
9104 let close = close.to_inclusive();
9105 let length = close.end() - open.start;
9106 let inside = selection.start >= open.end && selection.end <= *close.start();
9107 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9108 || close.contains(&selection.head());
9109
9110 // If best is next to a bracket and current isn't, skip
9111 if !in_bracket_range && best_in_bracket_range {
9112 continue;
9113 }
9114
9115 // Prefer smaller lengths unless best is inside and current isn't
9116 if length > best_length && (best_inside || !inside) {
9117 continue;
9118 }
9119
9120 best_length = length;
9121 best_inside = inside;
9122 best_in_bracket_range = in_bracket_range;
9123 best_destination = Some(
9124 if close.contains(&selection.start) && close.contains(&selection.end) {
9125 if inside {
9126 open.end
9127 } else {
9128 open.start
9129 }
9130 } else if inside {
9131 *close.start()
9132 } else {
9133 *close.end()
9134 },
9135 );
9136 }
9137
9138 if let Some(destination) = best_destination {
9139 selection.collapse_to(destination, SelectionGoal::None);
9140 }
9141 })
9142 });
9143 }
9144
9145 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9146 self.end_selection(cx);
9147 self.selection_history.mode = SelectionHistoryMode::Undoing;
9148 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9149 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9150 self.select_next_state = entry.select_next_state;
9151 self.select_prev_state = entry.select_prev_state;
9152 self.add_selections_state = entry.add_selections_state;
9153 self.request_autoscroll(Autoscroll::newest(), cx);
9154 }
9155 self.selection_history.mode = SelectionHistoryMode::Normal;
9156 }
9157
9158 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9159 self.end_selection(cx);
9160 self.selection_history.mode = SelectionHistoryMode::Redoing;
9161 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9162 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9163 self.select_next_state = entry.select_next_state;
9164 self.select_prev_state = entry.select_prev_state;
9165 self.add_selections_state = entry.add_selections_state;
9166 self.request_autoscroll(Autoscroll::newest(), cx);
9167 }
9168 self.selection_history.mode = SelectionHistoryMode::Normal;
9169 }
9170
9171 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9172 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9173 }
9174
9175 pub fn expand_excerpts_down(
9176 &mut self,
9177 action: &ExpandExcerptsDown,
9178 cx: &mut ViewContext<Self>,
9179 ) {
9180 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9181 }
9182
9183 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9184 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9185 }
9186
9187 pub fn expand_excerpts_for_direction(
9188 &mut self,
9189 lines: u32,
9190 direction: ExpandExcerptDirection,
9191 cx: &mut ViewContext<Self>,
9192 ) {
9193 let selections = self.selections.disjoint_anchors();
9194
9195 let lines = if lines == 0 {
9196 EditorSettings::get_global(cx).expand_excerpt_lines
9197 } else {
9198 lines
9199 };
9200
9201 self.buffer.update(cx, |buffer, cx| {
9202 let snapshot = buffer.snapshot(cx);
9203 let mut excerpt_ids = selections
9204 .iter()
9205 .flat_map(|selection| {
9206 snapshot
9207 .excerpts_for_range(selection.range())
9208 .map(|excerpt| excerpt.id())
9209 })
9210 .collect::<Vec<_>>();
9211 excerpt_ids.sort();
9212 excerpt_ids.dedup();
9213 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
9214 })
9215 }
9216
9217 pub fn expand_excerpt(
9218 &mut self,
9219 excerpt: ExcerptId,
9220 direction: ExpandExcerptDirection,
9221 cx: &mut ViewContext<Self>,
9222 ) {
9223 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9224 self.buffer.update(cx, |buffer, cx| {
9225 buffer.expand_excerpts([excerpt], lines, direction, cx)
9226 })
9227 }
9228
9229 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9230 self.go_to_diagnostic_impl(Direction::Next, cx)
9231 }
9232
9233 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9234 self.go_to_diagnostic_impl(Direction::Prev, cx)
9235 }
9236
9237 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9238 let buffer = self.buffer.read(cx).snapshot(cx);
9239 let selection = self.selections.newest::<usize>(cx);
9240
9241 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9242 if direction == Direction::Next {
9243 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9244 self.activate_diagnostics(popover.group_id(), cx);
9245 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
9246 let primary_range_start = active_diagnostics.primary_range.start;
9247 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9248 let mut new_selection = s.newest_anchor().clone();
9249 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
9250 s.select_anchors(vec![new_selection.clone()]);
9251 });
9252 }
9253 return;
9254 }
9255 }
9256
9257 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9258 active_diagnostics
9259 .primary_range
9260 .to_offset(&buffer)
9261 .to_inclusive()
9262 });
9263 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9264 if active_primary_range.contains(&selection.head()) {
9265 *active_primary_range.start()
9266 } else {
9267 selection.head()
9268 }
9269 } else {
9270 selection.head()
9271 };
9272 let snapshot = self.snapshot(cx);
9273 loop {
9274 let diagnostics = if direction == Direction::Prev {
9275 buffer.diagnostics_in_range(0..search_start, true)
9276 } else {
9277 buffer.diagnostics_in_range(search_start..buffer.len(), false)
9278 }
9279 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9280 let search_start_anchor = buffer.anchor_after(search_start);
9281 let group = diagnostics
9282 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9283 // be sorted in a stable way
9284 // skip until we are at current active diagnostic, if it exists
9285 .skip_while(|entry| {
9286 let is_in_range = match direction {
9287 Direction::Prev => {
9288 entry.range.start.cmp(&search_start_anchor, &buffer).is_ge()
9289 }
9290 Direction::Next => {
9291 entry.range.start.cmp(&search_start_anchor, &buffer).is_le()
9292 }
9293 };
9294 is_in_range
9295 && self
9296 .active_diagnostics
9297 .as_ref()
9298 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9299 })
9300 .find_map(|entry| {
9301 if entry.diagnostic.is_primary
9302 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9303 && !(entry.range.start == entry.range.end)
9304 // if we match with the active diagnostic, skip it
9305 && Some(entry.diagnostic.group_id)
9306 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9307 {
9308 Some((entry.range, entry.diagnostic.group_id))
9309 } else {
9310 None
9311 }
9312 });
9313
9314 if let Some((primary_range, group_id)) = group {
9315 self.activate_diagnostics(group_id, cx);
9316 let primary_range = primary_range.to_offset(&buffer);
9317 if self.active_diagnostics.is_some() {
9318 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9319 s.select(vec![Selection {
9320 id: selection.id,
9321 start: primary_range.start,
9322 end: primary_range.start,
9323 reversed: false,
9324 goal: SelectionGoal::None,
9325 }]);
9326 });
9327 }
9328 break;
9329 } else {
9330 // Cycle around to the start of the buffer, potentially moving back to the start of
9331 // the currently active diagnostic.
9332 active_primary_range.take();
9333 if direction == Direction::Prev {
9334 if search_start == buffer.len() {
9335 break;
9336 } else {
9337 search_start = buffer.len();
9338 }
9339 } else if search_start == 0 {
9340 break;
9341 } else {
9342 search_start = 0;
9343 }
9344 }
9345 }
9346 }
9347
9348 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9349 let snapshot = self.snapshot(cx);
9350 let selection = self.selections.newest::<Point>(cx);
9351 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9352 }
9353
9354 fn go_to_hunk_after_position(
9355 &mut self,
9356 snapshot: &EditorSnapshot,
9357 position: Point,
9358 cx: &mut ViewContext<Editor>,
9359 ) -> Option<MultiBufferDiffHunk> {
9360 for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
9361 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9362 snapshot,
9363 position,
9364 ix > 0,
9365 snapshot.diff_map.diff_hunks_in_range(
9366 position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
9367 &snapshot.buffer_snapshot,
9368 ),
9369 cx,
9370 ) {
9371 return Some(hunk);
9372 }
9373 }
9374 None
9375 }
9376
9377 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9378 let snapshot = self.snapshot(cx);
9379 let selection = self.selections.newest::<Point>(cx);
9380 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9381 }
9382
9383 fn go_to_hunk_before_position(
9384 &mut self,
9385 snapshot: &EditorSnapshot,
9386 position: Point,
9387 cx: &mut ViewContext<Editor>,
9388 ) -> Option<MultiBufferDiffHunk> {
9389 for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
9390 .into_iter()
9391 .enumerate()
9392 {
9393 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9394 snapshot,
9395 position,
9396 ix > 0,
9397 snapshot
9398 .diff_map
9399 .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
9400 cx,
9401 ) {
9402 return Some(hunk);
9403 }
9404 }
9405 None
9406 }
9407
9408 fn go_to_next_hunk_in_direction(
9409 &mut self,
9410 snapshot: &DisplaySnapshot,
9411 initial_point: Point,
9412 is_wrapped: bool,
9413 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9414 cx: &mut ViewContext<Editor>,
9415 ) -> Option<MultiBufferDiffHunk> {
9416 let display_point = initial_point.to_display_point(snapshot);
9417 let mut hunks = hunks
9418 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9419 .filter(|(display_hunk, _)| {
9420 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9421 })
9422 .dedup();
9423
9424 if let Some((display_hunk, hunk)) = hunks.next() {
9425 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9426 let row = display_hunk.start_display_row();
9427 let point = DisplayPoint::new(row, 0);
9428 s.select_display_ranges([point..point]);
9429 });
9430
9431 Some(hunk)
9432 } else {
9433 None
9434 }
9435 }
9436
9437 pub fn go_to_definition(
9438 &mut self,
9439 _: &GoToDefinition,
9440 cx: &mut ViewContext<Self>,
9441 ) -> Task<Result<Navigated>> {
9442 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9443 cx.spawn(|editor, mut cx| async move {
9444 if definition.await? == Navigated::Yes {
9445 return Ok(Navigated::Yes);
9446 }
9447 match editor.update(&mut cx, |editor, cx| {
9448 editor.find_all_references(&FindAllReferences, cx)
9449 })? {
9450 Some(references) => references.await,
9451 None => Ok(Navigated::No),
9452 }
9453 })
9454 }
9455
9456 pub fn go_to_declaration(
9457 &mut self,
9458 _: &GoToDeclaration,
9459 cx: &mut ViewContext<Self>,
9460 ) -> Task<Result<Navigated>> {
9461 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9462 }
9463
9464 pub fn go_to_declaration_split(
9465 &mut self,
9466 _: &GoToDeclaration,
9467 cx: &mut ViewContext<Self>,
9468 ) -> Task<Result<Navigated>> {
9469 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9470 }
9471
9472 pub fn go_to_implementation(
9473 &mut self,
9474 _: &GoToImplementation,
9475 cx: &mut ViewContext<Self>,
9476 ) -> Task<Result<Navigated>> {
9477 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9478 }
9479
9480 pub fn go_to_implementation_split(
9481 &mut self,
9482 _: &GoToImplementationSplit,
9483 cx: &mut ViewContext<Self>,
9484 ) -> Task<Result<Navigated>> {
9485 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9486 }
9487
9488 pub fn go_to_type_definition(
9489 &mut self,
9490 _: &GoToTypeDefinition,
9491 cx: &mut ViewContext<Self>,
9492 ) -> Task<Result<Navigated>> {
9493 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9494 }
9495
9496 pub fn go_to_definition_split(
9497 &mut self,
9498 _: &GoToDefinitionSplit,
9499 cx: &mut ViewContext<Self>,
9500 ) -> Task<Result<Navigated>> {
9501 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9502 }
9503
9504 pub fn go_to_type_definition_split(
9505 &mut self,
9506 _: &GoToTypeDefinitionSplit,
9507 cx: &mut ViewContext<Self>,
9508 ) -> Task<Result<Navigated>> {
9509 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9510 }
9511
9512 fn go_to_definition_of_kind(
9513 &mut self,
9514 kind: GotoDefinitionKind,
9515 split: bool,
9516 cx: &mut ViewContext<Self>,
9517 ) -> Task<Result<Navigated>> {
9518 let Some(provider) = self.semantics_provider.clone() else {
9519 return Task::ready(Ok(Navigated::No));
9520 };
9521 let head = self.selections.newest::<usize>(cx).head();
9522 let buffer = self.buffer.read(cx);
9523 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9524 text_anchor
9525 } else {
9526 return Task::ready(Ok(Navigated::No));
9527 };
9528
9529 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9530 return Task::ready(Ok(Navigated::No));
9531 };
9532
9533 cx.spawn(|editor, mut cx| async move {
9534 let definitions = definitions.await?;
9535 let navigated = editor
9536 .update(&mut cx, |editor, cx| {
9537 editor.navigate_to_hover_links(
9538 Some(kind),
9539 definitions
9540 .into_iter()
9541 .filter(|location| {
9542 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9543 })
9544 .map(HoverLink::Text)
9545 .collect::<Vec<_>>(),
9546 split,
9547 cx,
9548 )
9549 })?
9550 .await?;
9551 anyhow::Ok(navigated)
9552 })
9553 }
9554
9555 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9556 let selection = self.selections.newest_anchor();
9557 let head = selection.head();
9558 let tail = selection.tail();
9559
9560 let Some((buffer, start_position)) =
9561 self.buffer.read(cx).text_anchor_for_position(head, cx)
9562 else {
9563 return;
9564 };
9565
9566 let end_position = if head != tail {
9567 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
9568 return;
9569 };
9570 Some(pos)
9571 } else {
9572 None
9573 };
9574
9575 let url_finder = cx.spawn(|editor, mut cx| async move {
9576 let url = if let Some(end_pos) = end_position {
9577 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
9578 } else {
9579 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
9580 };
9581
9582 if let Some(url) = url {
9583 editor.update(&mut cx, |_, cx| {
9584 cx.open_url(&url);
9585 })
9586 } else {
9587 Ok(())
9588 }
9589 });
9590
9591 url_finder.detach();
9592 }
9593
9594 pub fn open_selected_filename(&mut self, _: &OpenSelectedFilename, cx: &mut ViewContext<Self>) {
9595 let Some(workspace) = self.workspace() else {
9596 return;
9597 };
9598
9599 let position = self.selections.newest_anchor().head();
9600
9601 let Some((buffer, buffer_position)) =
9602 self.buffer.read(cx).text_anchor_for_position(position, cx)
9603 else {
9604 return;
9605 };
9606
9607 let project = self.project.clone();
9608
9609 cx.spawn(|_, mut cx| async move {
9610 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9611
9612 if let Some((_, path)) = result {
9613 workspace
9614 .update(&mut cx, |workspace, cx| {
9615 workspace.open_resolved_path(path, cx)
9616 })?
9617 .await?;
9618 }
9619 anyhow::Ok(())
9620 })
9621 .detach();
9622 }
9623
9624 pub(crate) fn navigate_to_hover_links(
9625 &mut self,
9626 kind: Option<GotoDefinitionKind>,
9627 mut definitions: Vec<HoverLink>,
9628 split: bool,
9629 cx: &mut ViewContext<Editor>,
9630 ) -> Task<Result<Navigated>> {
9631 // If there is one definition, just open it directly
9632 if definitions.len() == 1 {
9633 let definition = definitions.pop().unwrap();
9634
9635 enum TargetTaskResult {
9636 Location(Option<Location>),
9637 AlreadyNavigated,
9638 }
9639
9640 let target_task = match definition {
9641 HoverLink::Text(link) => {
9642 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9643 }
9644 HoverLink::InlayHint(lsp_location, server_id) => {
9645 let computation = self.compute_target_location(lsp_location, server_id, cx);
9646 cx.background_executor().spawn(async move {
9647 let location = computation.await?;
9648 Ok(TargetTaskResult::Location(location))
9649 })
9650 }
9651 HoverLink::Url(url) => {
9652 cx.open_url(&url);
9653 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9654 }
9655 HoverLink::File(path) => {
9656 if let Some(workspace) = self.workspace() {
9657 cx.spawn(|_, mut cx| async move {
9658 workspace
9659 .update(&mut cx, |workspace, cx| {
9660 workspace.open_resolved_path(path, cx)
9661 })?
9662 .await
9663 .map(|_| TargetTaskResult::AlreadyNavigated)
9664 })
9665 } else {
9666 Task::ready(Ok(TargetTaskResult::Location(None)))
9667 }
9668 }
9669 };
9670 cx.spawn(|editor, mut cx| async move {
9671 let target = match target_task.await.context("target resolution task")? {
9672 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9673 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9674 TargetTaskResult::Location(Some(target)) => target,
9675 };
9676
9677 editor.update(&mut cx, |editor, cx| {
9678 let Some(workspace) = editor.workspace() else {
9679 return Navigated::No;
9680 };
9681 let pane = workspace.read(cx).active_pane().clone();
9682
9683 let range = target.range.to_offset(target.buffer.read(cx));
9684 let range = editor.range_for_match(&range);
9685
9686 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9687 let buffer = target.buffer.read(cx);
9688 let range = check_multiline_range(buffer, range);
9689 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9690 s.select_ranges([range]);
9691 });
9692 } else {
9693 cx.window_context().defer(move |cx| {
9694 let target_editor: View<Self> =
9695 workspace.update(cx, |workspace, cx| {
9696 let pane = if split {
9697 workspace.adjacent_pane(cx)
9698 } else {
9699 workspace.active_pane().clone()
9700 };
9701
9702 workspace.open_project_item(
9703 pane,
9704 target.buffer.clone(),
9705 true,
9706 true,
9707 cx,
9708 )
9709 });
9710 target_editor.update(cx, |target_editor, cx| {
9711 // When selecting a definition in a different buffer, disable the nav history
9712 // to avoid creating a history entry at the previous cursor location.
9713 pane.update(cx, |pane, _| pane.disable_history());
9714 let buffer = target.buffer.read(cx);
9715 let range = check_multiline_range(buffer, range);
9716 target_editor.change_selections(
9717 Some(Autoscroll::focused()),
9718 cx,
9719 |s| {
9720 s.select_ranges([range]);
9721 },
9722 );
9723 pane.update(cx, |pane, _| pane.enable_history());
9724 });
9725 });
9726 }
9727 Navigated::Yes
9728 })
9729 })
9730 } else if !definitions.is_empty() {
9731 cx.spawn(|editor, mut cx| async move {
9732 let (title, location_tasks, workspace) = editor
9733 .update(&mut cx, |editor, cx| {
9734 let tab_kind = match kind {
9735 Some(GotoDefinitionKind::Implementation) => "Implementations",
9736 _ => "Definitions",
9737 };
9738 let title = definitions
9739 .iter()
9740 .find_map(|definition| match definition {
9741 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9742 let buffer = origin.buffer.read(cx);
9743 format!(
9744 "{} for {}",
9745 tab_kind,
9746 buffer
9747 .text_for_range(origin.range.clone())
9748 .collect::<String>()
9749 )
9750 }),
9751 HoverLink::InlayHint(_, _) => None,
9752 HoverLink::Url(_) => None,
9753 HoverLink::File(_) => None,
9754 })
9755 .unwrap_or(tab_kind.to_string());
9756 let location_tasks = definitions
9757 .into_iter()
9758 .map(|definition| match definition {
9759 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
9760 HoverLink::InlayHint(lsp_location, server_id) => {
9761 editor.compute_target_location(lsp_location, server_id, cx)
9762 }
9763 HoverLink::Url(_) => Task::ready(Ok(None)),
9764 HoverLink::File(_) => Task::ready(Ok(None)),
9765 })
9766 .collect::<Vec<_>>();
9767 (title, location_tasks, editor.workspace().clone())
9768 })
9769 .context("location tasks preparation")?;
9770
9771 let locations = future::join_all(location_tasks)
9772 .await
9773 .into_iter()
9774 .filter_map(|location| location.transpose())
9775 .collect::<Result<_>>()
9776 .context("location tasks")?;
9777
9778 let Some(workspace) = workspace else {
9779 return Ok(Navigated::No);
9780 };
9781 let opened = workspace
9782 .update(&mut cx, |workspace, cx| {
9783 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9784 })
9785 .ok();
9786
9787 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9788 })
9789 } else {
9790 Task::ready(Ok(Navigated::No))
9791 }
9792 }
9793
9794 fn compute_target_location(
9795 &self,
9796 lsp_location: lsp::Location,
9797 server_id: LanguageServerId,
9798 cx: &mut ViewContext<Self>,
9799 ) -> Task<anyhow::Result<Option<Location>>> {
9800 let Some(project) = self.project.clone() else {
9801 return Task::ready(Ok(None));
9802 };
9803
9804 cx.spawn(move |editor, mut cx| async move {
9805 let location_task = editor.update(&mut cx, |_, cx| {
9806 project.update(cx, |project, cx| {
9807 let language_server_name = project
9808 .language_server_statuses(cx)
9809 .find(|(id, _)| server_id == *id)
9810 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9811 language_server_name.map(|language_server_name| {
9812 project.open_local_buffer_via_lsp(
9813 lsp_location.uri.clone(),
9814 server_id,
9815 language_server_name,
9816 cx,
9817 )
9818 })
9819 })
9820 })?;
9821 let location = match location_task {
9822 Some(task) => Some({
9823 let target_buffer_handle = task.await.context("open local buffer")?;
9824 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9825 let target_start = target_buffer
9826 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9827 let target_end = target_buffer
9828 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9829 target_buffer.anchor_after(target_start)
9830 ..target_buffer.anchor_before(target_end)
9831 })?;
9832 Location {
9833 buffer: target_buffer_handle,
9834 range,
9835 }
9836 }),
9837 None => None,
9838 };
9839 Ok(location)
9840 })
9841 }
9842
9843 pub fn find_all_references(
9844 &mut self,
9845 _: &FindAllReferences,
9846 cx: &mut ViewContext<Self>,
9847 ) -> Option<Task<Result<Navigated>>> {
9848 let selection = self.selections.newest::<usize>(cx);
9849 let multi_buffer = self.buffer.read(cx);
9850 let head = selection.head();
9851
9852 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9853 let head_anchor = multi_buffer_snapshot.anchor_at(
9854 head,
9855 if head < selection.tail() {
9856 Bias::Right
9857 } else {
9858 Bias::Left
9859 },
9860 );
9861
9862 match self
9863 .find_all_references_task_sources
9864 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9865 {
9866 Ok(_) => {
9867 log::info!(
9868 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9869 );
9870 return None;
9871 }
9872 Err(i) => {
9873 self.find_all_references_task_sources.insert(i, head_anchor);
9874 }
9875 }
9876
9877 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9878 let workspace = self.workspace()?;
9879 let project = workspace.read(cx).project().clone();
9880 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9881 Some(cx.spawn(|editor, mut cx| async move {
9882 let _cleanup = defer({
9883 let mut cx = cx.clone();
9884 move || {
9885 let _ = editor.update(&mut cx, |editor, _| {
9886 if let Ok(i) =
9887 editor
9888 .find_all_references_task_sources
9889 .binary_search_by(|anchor| {
9890 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9891 })
9892 {
9893 editor.find_all_references_task_sources.remove(i);
9894 }
9895 });
9896 }
9897 });
9898
9899 let locations = references.await?;
9900 if locations.is_empty() {
9901 return anyhow::Ok(Navigated::No);
9902 }
9903
9904 workspace.update(&mut cx, |workspace, cx| {
9905 let title = locations
9906 .first()
9907 .as_ref()
9908 .map(|location| {
9909 let buffer = location.buffer.read(cx);
9910 format!(
9911 "References to `{}`",
9912 buffer
9913 .text_for_range(location.range.clone())
9914 .collect::<String>()
9915 )
9916 })
9917 .unwrap();
9918 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9919 Navigated::Yes
9920 })
9921 }))
9922 }
9923
9924 /// Opens a multibuffer with the given project locations in it
9925 pub fn open_locations_in_multibuffer(
9926 workspace: &mut Workspace,
9927 mut locations: Vec<Location>,
9928 title: String,
9929 split: bool,
9930 cx: &mut ViewContext<Workspace>,
9931 ) {
9932 // If there are multiple definitions, open them in a multibuffer
9933 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9934 let mut locations = locations.into_iter().peekable();
9935 let mut ranges_to_highlight = Vec::new();
9936 let capability = workspace.project().read(cx).capability();
9937
9938 let excerpt_buffer = cx.new_model(|cx| {
9939 let mut multibuffer = MultiBuffer::new(capability);
9940 while let Some(location) = locations.next() {
9941 let buffer = location.buffer.read(cx);
9942 let mut ranges_for_buffer = Vec::new();
9943 let range = location.range.to_offset(buffer);
9944 ranges_for_buffer.push(range.clone());
9945
9946 while let Some(next_location) = locations.peek() {
9947 if next_location.buffer == location.buffer {
9948 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9949 locations.next();
9950 } else {
9951 break;
9952 }
9953 }
9954
9955 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9956 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9957 location.buffer.clone(),
9958 ranges_for_buffer,
9959 DEFAULT_MULTIBUFFER_CONTEXT,
9960 cx,
9961 ))
9962 }
9963
9964 multibuffer.with_title(title)
9965 });
9966
9967 let editor = cx.new_view(|cx| {
9968 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9969 });
9970 editor.update(cx, |editor, cx| {
9971 if let Some(first_range) = ranges_to_highlight.first() {
9972 editor.change_selections(None, cx, |selections| {
9973 selections.clear_disjoint();
9974 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9975 });
9976 }
9977 editor.highlight_background::<Self>(
9978 &ranges_to_highlight,
9979 |theme| theme.editor_highlighted_line_background,
9980 cx,
9981 );
9982 editor.register_buffers_with_language_servers(cx);
9983 });
9984
9985 let item = Box::new(editor);
9986 let item_id = item.item_id();
9987
9988 if split {
9989 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9990 } else {
9991 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9992 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9993 pane.close_current_preview_item(cx)
9994 } else {
9995 None
9996 }
9997 });
9998 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9999 }
10000 workspace.active_pane().update(cx, |pane, cx| {
10001 pane.set_preview_item_id(Some(item_id), cx);
10002 });
10003 }
10004
10005 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10006 use language::ToOffset as _;
10007
10008 let provider = self.semantics_provider.clone()?;
10009 let selection = self.selections.newest_anchor().clone();
10010 let (cursor_buffer, cursor_buffer_position) = self
10011 .buffer
10012 .read(cx)
10013 .text_anchor_for_position(selection.head(), cx)?;
10014 let (tail_buffer, cursor_buffer_position_end) = self
10015 .buffer
10016 .read(cx)
10017 .text_anchor_for_position(selection.tail(), cx)?;
10018 if tail_buffer != cursor_buffer {
10019 return None;
10020 }
10021
10022 let snapshot = cursor_buffer.read(cx).snapshot();
10023 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10024 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10025 let prepare_rename = provider
10026 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10027 .unwrap_or_else(|| Task::ready(Ok(None)));
10028 drop(snapshot);
10029
10030 Some(cx.spawn(|this, mut cx| async move {
10031 let rename_range = if let Some(range) = prepare_rename.await? {
10032 Some(range)
10033 } else {
10034 this.update(&mut cx, |this, cx| {
10035 let buffer = this.buffer.read(cx).snapshot(cx);
10036 let mut buffer_highlights = this
10037 .document_highlights_for_position(selection.head(), &buffer)
10038 .filter(|highlight| {
10039 highlight.start.excerpt_id == selection.head().excerpt_id
10040 && highlight.end.excerpt_id == selection.head().excerpt_id
10041 });
10042 buffer_highlights
10043 .next()
10044 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10045 })?
10046 };
10047 if let Some(rename_range) = rename_range {
10048 this.update(&mut cx, |this, cx| {
10049 let snapshot = cursor_buffer.read(cx).snapshot();
10050 let rename_buffer_range = rename_range.to_offset(&snapshot);
10051 let cursor_offset_in_rename_range =
10052 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10053 let cursor_offset_in_rename_range_end =
10054 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10055
10056 this.take_rename(false, cx);
10057 let buffer = this.buffer.read(cx).read(cx);
10058 let cursor_offset = selection.head().to_offset(&buffer);
10059 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10060 let rename_end = rename_start + rename_buffer_range.len();
10061 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10062 let mut old_highlight_id = None;
10063 let old_name: Arc<str> = buffer
10064 .chunks(rename_start..rename_end, true)
10065 .map(|chunk| {
10066 if old_highlight_id.is_none() {
10067 old_highlight_id = chunk.syntax_highlight_id;
10068 }
10069 chunk.text
10070 })
10071 .collect::<String>()
10072 .into();
10073
10074 drop(buffer);
10075
10076 // Position the selection in the rename editor so that it matches the current selection.
10077 this.show_local_selections = false;
10078 let rename_editor = cx.new_view(|cx| {
10079 let mut editor = Editor::single_line(cx);
10080 editor.buffer.update(cx, |buffer, cx| {
10081 buffer.edit([(0..0, old_name.clone())], None, cx)
10082 });
10083 let rename_selection_range = match cursor_offset_in_rename_range
10084 .cmp(&cursor_offset_in_rename_range_end)
10085 {
10086 Ordering::Equal => {
10087 editor.select_all(&SelectAll, cx);
10088 return editor;
10089 }
10090 Ordering::Less => {
10091 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10092 }
10093 Ordering::Greater => {
10094 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10095 }
10096 };
10097 if rename_selection_range.end > old_name.len() {
10098 editor.select_all(&SelectAll, cx);
10099 } else {
10100 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10101 s.select_ranges([rename_selection_range]);
10102 });
10103 }
10104 editor
10105 });
10106 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10107 if e == &EditorEvent::Focused {
10108 cx.emit(EditorEvent::FocusedIn)
10109 }
10110 })
10111 .detach();
10112
10113 let write_highlights =
10114 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10115 let read_highlights =
10116 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10117 let ranges = write_highlights
10118 .iter()
10119 .flat_map(|(_, ranges)| ranges.iter())
10120 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10121 .cloned()
10122 .collect();
10123
10124 this.highlight_text::<Rename>(
10125 ranges,
10126 HighlightStyle {
10127 fade_out: Some(0.6),
10128 ..Default::default()
10129 },
10130 cx,
10131 );
10132 let rename_focus_handle = rename_editor.focus_handle(cx);
10133 cx.focus(&rename_focus_handle);
10134 let block_id = this.insert_blocks(
10135 [BlockProperties {
10136 style: BlockStyle::Flex,
10137 placement: BlockPlacement::Below(range.start),
10138 height: 1,
10139 render: Arc::new({
10140 let rename_editor = rename_editor.clone();
10141 move |cx: &mut BlockContext| {
10142 let mut text_style = cx.editor_style.text.clone();
10143 if let Some(highlight_style) = old_highlight_id
10144 .and_then(|h| h.style(&cx.editor_style.syntax))
10145 {
10146 text_style = text_style.highlight(highlight_style);
10147 }
10148 div()
10149 .block_mouse_down()
10150 .pl(cx.anchor_x)
10151 .child(EditorElement::new(
10152 &rename_editor,
10153 EditorStyle {
10154 background: cx.theme().system().transparent,
10155 local_player: cx.editor_style.local_player,
10156 text: text_style,
10157 scrollbar_width: cx.editor_style.scrollbar_width,
10158 syntax: cx.editor_style.syntax.clone(),
10159 status: cx.editor_style.status.clone(),
10160 inlay_hints_style: HighlightStyle {
10161 font_weight: Some(FontWeight::BOLD),
10162 ..make_inlay_hints_style(cx)
10163 },
10164 inline_completion_styles: make_suggestion_styles(
10165 cx,
10166 ),
10167 ..EditorStyle::default()
10168 },
10169 ))
10170 .into_any_element()
10171 }
10172 }),
10173 priority: 0,
10174 }],
10175 Some(Autoscroll::fit()),
10176 cx,
10177 )[0];
10178 this.pending_rename = Some(RenameState {
10179 range,
10180 old_name,
10181 editor: rename_editor,
10182 block_id,
10183 });
10184 })?;
10185 }
10186
10187 Ok(())
10188 }))
10189 }
10190
10191 pub fn confirm_rename(
10192 &mut self,
10193 _: &ConfirmRename,
10194 cx: &mut ViewContext<Self>,
10195 ) -> Option<Task<Result<()>>> {
10196 let rename = self.take_rename(false, cx)?;
10197 let workspace = self.workspace()?.downgrade();
10198 let (buffer, start) = self
10199 .buffer
10200 .read(cx)
10201 .text_anchor_for_position(rename.range.start, cx)?;
10202 let (end_buffer, _) = self
10203 .buffer
10204 .read(cx)
10205 .text_anchor_for_position(rename.range.end, cx)?;
10206 if buffer != end_buffer {
10207 return None;
10208 }
10209
10210 let old_name = rename.old_name;
10211 let new_name = rename.editor.read(cx).text(cx);
10212
10213 let rename = self.semantics_provider.as_ref()?.perform_rename(
10214 &buffer,
10215 start,
10216 new_name.clone(),
10217 cx,
10218 )?;
10219
10220 Some(cx.spawn(|editor, mut cx| async move {
10221 let project_transaction = rename.await?;
10222 Self::open_project_transaction(
10223 &editor,
10224 workspace,
10225 project_transaction,
10226 format!("Rename: {} → {}", old_name, new_name),
10227 cx.clone(),
10228 )
10229 .await?;
10230
10231 editor.update(&mut cx, |editor, cx| {
10232 editor.refresh_document_highlights(cx);
10233 })?;
10234 Ok(())
10235 }))
10236 }
10237
10238 fn take_rename(
10239 &mut self,
10240 moving_cursor: bool,
10241 cx: &mut ViewContext<Self>,
10242 ) -> Option<RenameState> {
10243 let rename = self.pending_rename.take()?;
10244 if rename.editor.focus_handle(cx).is_focused(cx) {
10245 cx.focus(&self.focus_handle);
10246 }
10247
10248 self.remove_blocks(
10249 [rename.block_id].into_iter().collect(),
10250 Some(Autoscroll::fit()),
10251 cx,
10252 );
10253 self.clear_highlights::<Rename>(cx);
10254 self.show_local_selections = true;
10255
10256 if moving_cursor {
10257 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10258 editor.selections.newest::<usize>(cx).head()
10259 });
10260
10261 // Update the selection to match the position of the selection inside
10262 // the rename editor.
10263 let snapshot = self.buffer.read(cx).read(cx);
10264 let rename_range = rename.range.to_offset(&snapshot);
10265 let cursor_in_editor = snapshot
10266 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10267 .min(rename_range.end);
10268 drop(snapshot);
10269
10270 self.change_selections(None, cx, |s| {
10271 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10272 });
10273 } else {
10274 self.refresh_document_highlights(cx);
10275 }
10276
10277 Some(rename)
10278 }
10279
10280 pub fn pending_rename(&self) -> Option<&RenameState> {
10281 self.pending_rename.as_ref()
10282 }
10283
10284 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10285 let project = match &self.project {
10286 Some(project) => project.clone(),
10287 None => return None,
10288 };
10289
10290 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffers, cx))
10291 }
10292
10293 fn format_selections(
10294 &mut self,
10295 _: &FormatSelections,
10296 cx: &mut ViewContext<Self>,
10297 ) -> Option<Task<Result<()>>> {
10298 let project = match &self.project {
10299 Some(project) => project.clone(),
10300 None => return None,
10301 };
10302
10303 let ranges = self
10304 .selections
10305 .all_adjusted(cx)
10306 .into_iter()
10307 .map(|selection| selection.range())
10308 .collect_vec();
10309
10310 Some(self.perform_format(
10311 project,
10312 FormatTrigger::Manual,
10313 FormatTarget::Ranges(ranges),
10314 cx,
10315 ))
10316 }
10317
10318 fn perform_format(
10319 &mut self,
10320 project: Model<Project>,
10321 trigger: FormatTrigger,
10322 target: FormatTarget,
10323 cx: &mut ViewContext<Self>,
10324 ) -> Task<Result<()>> {
10325 let buffer = self.buffer.clone();
10326 let (buffers, target) = match target {
10327 FormatTarget::Buffers => {
10328 let mut buffers = buffer.read(cx).all_buffers();
10329 if trigger == FormatTrigger::Save {
10330 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10331 }
10332 (buffers, LspFormatTarget::Buffers)
10333 }
10334 FormatTarget::Ranges(selection_ranges) => {
10335 let multi_buffer = buffer.read(cx);
10336 let snapshot = multi_buffer.read(cx);
10337 let mut buffers = HashSet::default();
10338 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
10339 BTreeMap::new();
10340 for selection_range in selection_ranges {
10341 for (excerpt, buffer_range) in snapshot.range_to_buffer_ranges(selection_range)
10342 {
10343 let buffer_id = excerpt.buffer_id();
10344 let start = excerpt.buffer().anchor_before(buffer_range.start);
10345 let end = excerpt.buffer().anchor_after(buffer_range.end);
10346 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
10347 buffer_id_to_ranges
10348 .entry(buffer_id)
10349 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
10350 .or_insert_with(|| vec![start..end]);
10351 }
10352 }
10353 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
10354 }
10355 };
10356
10357 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10358 let format = project.update(cx, |project, cx| {
10359 project.format(buffers, target, true, trigger, cx)
10360 });
10361
10362 cx.spawn(|_, mut cx| async move {
10363 let transaction = futures::select_biased! {
10364 () = timeout => {
10365 log::warn!("timed out waiting for formatting");
10366 None
10367 }
10368 transaction = format.log_err().fuse() => transaction,
10369 };
10370
10371 buffer
10372 .update(&mut cx, |buffer, cx| {
10373 if let Some(transaction) = transaction {
10374 if !buffer.is_singleton() {
10375 buffer.push_transaction(&transaction.0, cx);
10376 }
10377 }
10378
10379 cx.notify();
10380 })
10381 .ok();
10382
10383 Ok(())
10384 })
10385 }
10386
10387 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10388 if let Some(project) = self.project.clone() {
10389 self.buffer.update(cx, |multi_buffer, cx| {
10390 project.update(cx, |project, cx| {
10391 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10392 });
10393 })
10394 }
10395 }
10396
10397 fn cancel_language_server_work(
10398 &mut self,
10399 _: &actions::CancelLanguageServerWork,
10400 cx: &mut ViewContext<Self>,
10401 ) {
10402 if let Some(project) = self.project.clone() {
10403 self.buffer.update(cx, |multi_buffer, cx| {
10404 project.update(cx, |project, cx| {
10405 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10406 });
10407 })
10408 }
10409 }
10410
10411 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10412 cx.show_character_palette();
10413 }
10414
10415 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10416 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10417 let buffer = self.buffer.read(cx).snapshot(cx);
10418 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10419 let is_valid = buffer
10420 .diagnostics_in_range(active_diagnostics.primary_range.clone(), false)
10421 .any(|entry| {
10422 let range = entry.range.to_offset(&buffer);
10423 entry.diagnostic.is_primary
10424 && !range.is_empty()
10425 && range.start == primary_range_start
10426 && entry.diagnostic.message == active_diagnostics.primary_message
10427 });
10428
10429 if is_valid != active_diagnostics.is_valid {
10430 active_diagnostics.is_valid = is_valid;
10431 let mut new_styles = HashMap::default();
10432 for (block_id, diagnostic) in &active_diagnostics.blocks {
10433 new_styles.insert(
10434 *block_id,
10435 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10436 );
10437 }
10438 self.display_map.update(cx, |display_map, _cx| {
10439 display_map.replace_blocks(new_styles)
10440 });
10441 }
10442 }
10443 }
10444
10445 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
10446 self.dismiss_diagnostics(cx);
10447 let snapshot = self.snapshot(cx);
10448 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10449 let buffer = self.buffer.read(cx).snapshot(cx);
10450
10451 let mut primary_range = None;
10452 let mut primary_message = None;
10453 let mut group_end = Point::zero();
10454 let diagnostic_group = buffer
10455 .diagnostic_group(group_id)
10456 .filter_map(|entry| {
10457 let start = entry.range.start.to_point(&buffer);
10458 let end = entry.range.end.to_point(&buffer);
10459 if snapshot.is_line_folded(MultiBufferRow(start.row))
10460 && (start.row == end.row
10461 || snapshot.is_line_folded(MultiBufferRow(end.row)))
10462 {
10463 return None;
10464 }
10465 if end > group_end {
10466 group_end = end;
10467 }
10468 if entry.diagnostic.is_primary {
10469 primary_range = Some(entry.range.clone());
10470 primary_message = Some(entry.diagnostic.message.clone());
10471 }
10472 Some(entry)
10473 })
10474 .collect::<Vec<_>>();
10475 let primary_range = primary_range?;
10476 let primary_message = primary_message?;
10477
10478 let blocks = display_map
10479 .insert_blocks(
10480 diagnostic_group.iter().map(|entry| {
10481 let diagnostic = entry.diagnostic.clone();
10482 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10483 BlockProperties {
10484 style: BlockStyle::Fixed,
10485 placement: BlockPlacement::Below(
10486 buffer.anchor_after(entry.range.start),
10487 ),
10488 height: message_height,
10489 render: diagnostic_block_renderer(diagnostic, None, true, true),
10490 priority: 0,
10491 }
10492 }),
10493 cx,
10494 )
10495 .into_iter()
10496 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10497 .collect();
10498
10499 Some(ActiveDiagnosticGroup {
10500 primary_range,
10501 primary_message,
10502 group_id,
10503 blocks,
10504 is_valid: true,
10505 })
10506 });
10507 }
10508
10509 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10510 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10511 self.display_map.update(cx, |display_map, cx| {
10512 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10513 });
10514 cx.notify();
10515 }
10516 }
10517
10518 pub fn set_selections_from_remote(
10519 &mut self,
10520 selections: Vec<Selection<Anchor>>,
10521 pending_selection: Option<Selection<Anchor>>,
10522 cx: &mut ViewContext<Self>,
10523 ) {
10524 let old_cursor_position = self.selections.newest_anchor().head();
10525 self.selections.change_with(cx, |s| {
10526 s.select_anchors(selections);
10527 if let Some(pending_selection) = pending_selection {
10528 s.set_pending(pending_selection, SelectMode::Character);
10529 } else {
10530 s.clear_pending();
10531 }
10532 });
10533 self.selections_did_change(false, &old_cursor_position, true, cx);
10534 }
10535
10536 fn push_to_selection_history(&mut self) {
10537 self.selection_history.push(SelectionHistoryEntry {
10538 selections: self.selections.disjoint_anchors(),
10539 select_next_state: self.select_next_state.clone(),
10540 select_prev_state: self.select_prev_state.clone(),
10541 add_selections_state: self.add_selections_state.clone(),
10542 });
10543 }
10544
10545 pub fn transact(
10546 &mut self,
10547 cx: &mut ViewContext<Self>,
10548 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10549 ) -> Option<TransactionId> {
10550 self.start_transaction_at(Instant::now(), cx);
10551 update(self, cx);
10552 self.end_transaction_at(Instant::now(), cx)
10553 }
10554
10555 pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10556 self.end_selection(cx);
10557 if let Some(tx_id) = self
10558 .buffer
10559 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10560 {
10561 self.selection_history
10562 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10563 cx.emit(EditorEvent::TransactionBegun {
10564 transaction_id: tx_id,
10565 })
10566 }
10567 }
10568
10569 pub fn end_transaction_at(
10570 &mut self,
10571 now: Instant,
10572 cx: &mut ViewContext<Self>,
10573 ) -> Option<TransactionId> {
10574 if let Some(transaction_id) = self
10575 .buffer
10576 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10577 {
10578 if let Some((_, end_selections)) =
10579 self.selection_history.transaction_mut(transaction_id)
10580 {
10581 *end_selections = Some(self.selections.disjoint_anchors());
10582 } else {
10583 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10584 }
10585
10586 cx.emit(EditorEvent::Edited { transaction_id });
10587 Some(transaction_id)
10588 } else {
10589 None
10590 }
10591 }
10592
10593 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10594 if self.is_singleton(cx) {
10595 let selection = self.selections.newest::<Point>(cx);
10596
10597 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10598 let range = if selection.is_empty() {
10599 let point = selection.head().to_display_point(&display_map);
10600 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10601 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10602 .to_point(&display_map);
10603 start..end
10604 } else {
10605 selection.range()
10606 };
10607 if display_map.folds_in_range(range).next().is_some() {
10608 self.unfold_lines(&Default::default(), cx)
10609 } else {
10610 self.fold(&Default::default(), cx)
10611 }
10612 } else {
10613 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10614 let mut toggled_buffers = HashSet::default();
10615 for (_, buffer_snapshot, _) in
10616 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10617 {
10618 let buffer_id = buffer_snapshot.remote_id();
10619 if toggled_buffers.insert(buffer_id) {
10620 if self.buffer_folded(buffer_id, cx) {
10621 self.unfold_buffer(buffer_id, cx);
10622 } else {
10623 self.fold_buffer(buffer_id, cx);
10624 }
10625 }
10626 }
10627 }
10628 }
10629
10630 pub fn toggle_fold_recursive(
10631 &mut self,
10632 _: &actions::ToggleFoldRecursive,
10633 cx: &mut ViewContext<Self>,
10634 ) {
10635 let selection = self.selections.newest::<Point>(cx);
10636
10637 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10638 let range = if selection.is_empty() {
10639 let point = selection.head().to_display_point(&display_map);
10640 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10641 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10642 .to_point(&display_map);
10643 start..end
10644 } else {
10645 selection.range()
10646 };
10647 if display_map.folds_in_range(range).next().is_some() {
10648 self.unfold_recursive(&Default::default(), cx)
10649 } else {
10650 self.fold_recursive(&Default::default(), cx)
10651 }
10652 }
10653
10654 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10655 if self.is_singleton(cx) {
10656 let mut to_fold = Vec::new();
10657 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10658 let selections = self.selections.all_adjusted(cx);
10659
10660 for selection in selections {
10661 let range = selection.range().sorted();
10662 let buffer_start_row = range.start.row;
10663
10664 if range.start.row != range.end.row {
10665 let mut found = false;
10666 let mut row = range.start.row;
10667 while row <= range.end.row {
10668 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10669 {
10670 found = true;
10671 row = crease.range().end.row + 1;
10672 to_fold.push(crease);
10673 } else {
10674 row += 1
10675 }
10676 }
10677 if found {
10678 continue;
10679 }
10680 }
10681
10682 for row in (0..=range.start.row).rev() {
10683 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10684 if crease.range().end.row >= buffer_start_row {
10685 to_fold.push(crease);
10686 if row <= range.start.row {
10687 break;
10688 }
10689 }
10690 }
10691 }
10692 }
10693
10694 self.fold_creases(to_fold, true, cx);
10695 } else {
10696 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10697 let mut folded_buffers = HashSet::default();
10698 for (_, buffer_snapshot, _) in
10699 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10700 {
10701 let buffer_id = buffer_snapshot.remote_id();
10702 if folded_buffers.insert(buffer_id) {
10703 self.fold_buffer(buffer_id, cx);
10704 }
10705 }
10706 }
10707 }
10708
10709 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10710 if !self.buffer.read(cx).is_singleton() {
10711 return;
10712 }
10713
10714 let fold_at_level = fold_at.level;
10715 let snapshot = self.buffer.read(cx).snapshot(cx);
10716 let mut to_fold = Vec::new();
10717 let mut stack = vec![(0, snapshot.max_row().0, 1)];
10718
10719 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10720 while start_row < end_row {
10721 match self
10722 .snapshot(cx)
10723 .crease_for_buffer_row(MultiBufferRow(start_row))
10724 {
10725 Some(crease) => {
10726 let nested_start_row = crease.range().start.row + 1;
10727 let nested_end_row = crease.range().end.row;
10728
10729 if current_level < fold_at_level {
10730 stack.push((nested_start_row, nested_end_row, current_level + 1));
10731 } else if current_level == fold_at_level {
10732 to_fold.push(crease);
10733 }
10734
10735 start_row = nested_end_row + 1;
10736 }
10737 None => start_row += 1,
10738 }
10739 }
10740 }
10741
10742 self.fold_creases(to_fold, true, cx);
10743 }
10744
10745 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10746 if self.buffer.read(cx).is_singleton() {
10747 let mut fold_ranges = Vec::new();
10748 let snapshot = self.buffer.read(cx).snapshot(cx);
10749
10750 for row in 0..snapshot.max_row().0 {
10751 if let Some(foldable_range) =
10752 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10753 {
10754 fold_ranges.push(foldable_range);
10755 }
10756 }
10757
10758 self.fold_creases(fold_ranges, true, cx);
10759 } else {
10760 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10761 editor
10762 .update(&mut cx, |editor, cx| {
10763 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10764 editor.fold_buffer(buffer_id, cx);
10765 }
10766 })
10767 .ok();
10768 });
10769 }
10770 }
10771
10772 pub fn fold_function_bodies(
10773 &mut self,
10774 _: &actions::FoldFunctionBodies,
10775 cx: &mut ViewContext<Self>,
10776 ) {
10777 let snapshot = self.buffer.read(cx).snapshot(cx);
10778 let Some((_, _, buffer)) = snapshot.as_singleton() else {
10779 return;
10780 };
10781 let creases = buffer
10782 .function_body_fold_ranges(0..buffer.len())
10783 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10784 .collect();
10785
10786 self.fold_creases(creases, true, cx);
10787 }
10788
10789 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10790 let mut to_fold = Vec::new();
10791 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10792 let selections = self.selections.all_adjusted(cx);
10793
10794 for selection in selections {
10795 let range = selection.range().sorted();
10796 let buffer_start_row = range.start.row;
10797
10798 if range.start.row != range.end.row {
10799 let mut found = false;
10800 for row in range.start.row..=range.end.row {
10801 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10802 found = true;
10803 to_fold.push(crease);
10804 }
10805 }
10806 if found {
10807 continue;
10808 }
10809 }
10810
10811 for row in (0..=range.start.row).rev() {
10812 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10813 if crease.range().end.row >= buffer_start_row {
10814 to_fold.push(crease);
10815 } else {
10816 break;
10817 }
10818 }
10819 }
10820 }
10821
10822 self.fold_creases(to_fold, true, cx);
10823 }
10824
10825 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10826 let buffer_row = fold_at.buffer_row;
10827 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10828
10829 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10830 let autoscroll = self
10831 .selections
10832 .all::<Point>(cx)
10833 .iter()
10834 .any(|selection| crease.range().overlaps(&selection.range()));
10835
10836 self.fold_creases(vec![crease], autoscroll, cx);
10837 }
10838 }
10839
10840 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10841 if self.is_singleton(cx) {
10842 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10843 let buffer = &display_map.buffer_snapshot;
10844 let selections = self.selections.all::<Point>(cx);
10845 let ranges = selections
10846 .iter()
10847 .map(|s| {
10848 let range = s.display_range(&display_map).sorted();
10849 let mut start = range.start.to_point(&display_map);
10850 let mut end = range.end.to_point(&display_map);
10851 start.column = 0;
10852 end.column = buffer.line_len(MultiBufferRow(end.row));
10853 start..end
10854 })
10855 .collect::<Vec<_>>();
10856
10857 self.unfold_ranges(&ranges, true, true, cx);
10858 } else {
10859 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10860 let mut unfolded_buffers = HashSet::default();
10861 for (_, buffer_snapshot, _) in
10862 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10863 {
10864 let buffer_id = buffer_snapshot.remote_id();
10865 if unfolded_buffers.insert(buffer_id) {
10866 self.unfold_buffer(buffer_id, cx);
10867 }
10868 }
10869 }
10870 }
10871
10872 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10873 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10874 let selections = self.selections.all::<Point>(cx);
10875 let ranges = selections
10876 .iter()
10877 .map(|s| {
10878 let mut range = s.display_range(&display_map).sorted();
10879 *range.start.column_mut() = 0;
10880 *range.end.column_mut() = display_map.line_len(range.end.row());
10881 let start = range.start.to_point(&display_map);
10882 let end = range.end.to_point(&display_map);
10883 start..end
10884 })
10885 .collect::<Vec<_>>();
10886
10887 self.unfold_ranges(&ranges, true, true, cx);
10888 }
10889
10890 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10891 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10892
10893 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10894 ..Point::new(
10895 unfold_at.buffer_row.0,
10896 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10897 );
10898
10899 let autoscroll = self
10900 .selections
10901 .all::<Point>(cx)
10902 .iter()
10903 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10904
10905 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10906 }
10907
10908 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10909 if self.buffer.read(cx).is_singleton() {
10910 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10911 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10912 } else {
10913 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10914 editor
10915 .update(&mut cx, |editor, cx| {
10916 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10917 editor.unfold_buffer(buffer_id, cx);
10918 }
10919 })
10920 .ok();
10921 });
10922 }
10923 }
10924
10925 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10926 let selections = self.selections.all::<Point>(cx);
10927 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10928 let line_mode = self.selections.line_mode;
10929 let ranges = selections
10930 .into_iter()
10931 .map(|s| {
10932 if line_mode {
10933 let start = Point::new(s.start.row, 0);
10934 let end = Point::new(
10935 s.end.row,
10936 display_map
10937 .buffer_snapshot
10938 .line_len(MultiBufferRow(s.end.row)),
10939 );
10940 Crease::simple(start..end, display_map.fold_placeholder.clone())
10941 } else {
10942 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10943 }
10944 })
10945 .collect::<Vec<_>>();
10946 self.fold_creases(ranges, true, cx);
10947 }
10948
10949 pub fn fold_ranges<T: ToOffset + Clone>(
10950 &mut self,
10951 ranges: Vec<Range<T>>,
10952 auto_scroll: bool,
10953 cx: &mut ViewContext<Self>,
10954 ) {
10955 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10956 let ranges = ranges
10957 .into_iter()
10958 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
10959 .collect::<Vec<_>>();
10960 self.fold_creases(ranges, auto_scroll, cx);
10961 }
10962
10963 pub fn fold_creases<T: ToOffset + Clone>(
10964 &mut self,
10965 creases: Vec<Crease<T>>,
10966 auto_scroll: bool,
10967 cx: &mut ViewContext<Self>,
10968 ) {
10969 if creases.is_empty() {
10970 return;
10971 }
10972
10973 let mut buffers_affected = HashSet::default();
10974 let multi_buffer = self.buffer().read(cx);
10975 for crease in &creases {
10976 if let Some((_, buffer, _)) =
10977 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10978 {
10979 buffers_affected.insert(buffer.read(cx).remote_id());
10980 };
10981 }
10982
10983 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10984
10985 if auto_scroll {
10986 self.request_autoscroll(Autoscroll::fit(), cx);
10987 }
10988
10989 for buffer_id in buffers_affected {
10990 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10991 }
10992
10993 cx.notify();
10994
10995 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10996 // Clear diagnostics block when folding a range that contains it.
10997 let snapshot = self.snapshot(cx);
10998 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10999 drop(snapshot);
11000 self.active_diagnostics = Some(active_diagnostics);
11001 self.dismiss_diagnostics(cx);
11002 } else {
11003 self.active_diagnostics = Some(active_diagnostics);
11004 }
11005 }
11006
11007 self.scrollbar_marker_state.dirty = true;
11008 }
11009
11010 /// Removes any folds whose ranges intersect any of the given ranges.
11011 pub fn unfold_ranges<T: ToOffset + Clone>(
11012 &mut self,
11013 ranges: &[Range<T>],
11014 inclusive: bool,
11015 auto_scroll: bool,
11016 cx: &mut ViewContext<Self>,
11017 ) {
11018 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11019 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11020 });
11021 }
11022
11023 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11024 if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
11025 return;
11026 }
11027 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11028 return;
11029 };
11030 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11031 self.display_map
11032 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
11033 cx.emit(EditorEvent::BufferFoldToggled {
11034 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11035 folded: true,
11036 });
11037 cx.notify();
11038 }
11039
11040 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11041 if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
11042 return;
11043 }
11044 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11045 return;
11046 };
11047 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11048 self.display_map.update(cx, |display_map, cx| {
11049 display_map.unfold_buffer(buffer_id, cx);
11050 });
11051 cx.emit(EditorEvent::BufferFoldToggled {
11052 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11053 folded: false,
11054 });
11055 cx.notify();
11056 }
11057
11058 pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
11059 self.display_map.read(cx).buffer_folded(buffer)
11060 }
11061
11062 /// Removes any folds with the given ranges.
11063 pub fn remove_folds_with_type<T: ToOffset + Clone>(
11064 &mut self,
11065 ranges: &[Range<T>],
11066 type_id: TypeId,
11067 auto_scroll: bool,
11068 cx: &mut ViewContext<Self>,
11069 ) {
11070 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11071 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11072 });
11073 }
11074
11075 fn remove_folds_with<T: ToOffset + Clone>(
11076 &mut self,
11077 ranges: &[Range<T>],
11078 auto_scroll: bool,
11079 cx: &mut ViewContext<Self>,
11080 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11081 ) {
11082 if ranges.is_empty() {
11083 return;
11084 }
11085
11086 let mut buffers_affected = HashSet::default();
11087 let multi_buffer = self.buffer().read(cx);
11088 for range in ranges {
11089 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11090 buffers_affected.insert(buffer.read(cx).remote_id());
11091 };
11092 }
11093
11094 self.display_map.update(cx, update);
11095
11096 if auto_scroll {
11097 self.request_autoscroll(Autoscroll::fit(), cx);
11098 }
11099
11100 for buffer_id in buffers_affected {
11101 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11102 }
11103
11104 cx.notify();
11105 self.scrollbar_marker_state.dirty = true;
11106 self.active_indent_guides_state.dirty = true;
11107 }
11108
11109 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11110 self.display_map.read(cx).fold_placeholder.clone()
11111 }
11112
11113 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11114 if hovered != self.gutter_hovered {
11115 self.gutter_hovered = hovered;
11116 cx.notify();
11117 }
11118 }
11119
11120 pub fn insert_blocks(
11121 &mut self,
11122 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11123 autoscroll: Option<Autoscroll>,
11124 cx: &mut ViewContext<Self>,
11125 ) -> Vec<CustomBlockId> {
11126 let blocks = self
11127 .display_map
11128 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11129 if let Some(autoscroll) = autoscroll {
11130 self.request_autoscroll(autoscroll, cx);
11131 }
11132 cx.notify();
11133 blocks
11134 }
11135
11136 pub fn resize_blocks(
11137 &mut self,
11138 heights: HashMap<CustomBlockId, u32>,
11139 autoscroll: Option<Autoscroll>,
11140 cx: &mut ViewContext<Self>,
11141 ) {
11142 self.display_map
11143 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11144 if let Some(autoscroll) = autoscroll {
11145 self.request_autoscroll(autoscroll, cx);
11146 }
11147 cx.notify();
11148 }
11149
11150 pub fn replace_blocks(
11151 &mut self,
11152 renderers: HashMap<CustomBlockId, RenderBlock>,
11153 autoscroll: Option<Autoscroll>,
11154 cx: &mut ViewContext<Self>,
11155 ) {
11156 self.display_map
11157 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11158 if let Some(autoscroll) = autoscroll {
11159 self.request_autoscroll(autoscroll, cx);
11160 }
11161 cx.notify();
11162 }
11163
11164 pub fn remove_blocks(
11165 &mut self,
11166 block_ids: HashSet<CustomBlockId>,
11167 autoscroll: Option<Autoscroll>,
11168 cx: &mut ViewContext<Self>,
11169 ) {
11170 self.display_map.update(cx, |display_map, cx| {
11171 display_map.remove_blocks(block_ids, cx)
11172 });
11173 if let Some(autoscroll) = autoscroll {
11174 self.request_autoscroll(autoscroll, cx);
11175 }
11176 cx.notify();
11177 }
11178
11179 pub fn row_for_block(
11180 &self,
11181 block_id: CustomBlockId,
11182 cx: &mut ViewContext<Self>,
11183 ) -> Option<DisplayRow> {
11184 self.display_map
11185 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11186 }
11187
11188 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11189 self.focused_block = Some(focused_block);
11190 }
11191
11192 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11193 self.focused_block.take()
11194 }
11195
11196 pub fn insert_creases(
11197 &mut self,
11198 creases: impl IntoIterator<Item = Crease<Anchor>>,
11199 cx: &mut ViewContext<Self>,
11200 ) -> Vec<CreaseId> {
11201 self.display_map
11202 .update(cx, |map, cx| map.insert_creases(creases, cx))
11203 }
11204
11205 pub fn remove_creases(
11206 &mut self,
11207 ids: impl IntoIterator<Item = CreaseId>,
11208 cx: &mut ViewContext<Self>,
11209 ) {
11210 self.display_map
11211 .update(cx, |map, cx| map.remove_creases(ids, cx));
11212 }
11213
11214 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11215 self.display_map
11216 .update(cx, |map, cx| map.snapshot(cx))
11217 .longest_row()
11218 }
11219
11220 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11221 self.display_map
11222 .update(cx, |map, cx| map.snapshot(cx))
11223 .max_point()
11224 }
11225
11226 pub fn text(&self, cx: &AppContext) -> String {
11227 self.buffer.read(cx).read(cx).text()
11228 }
11229
11230 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11231 let text = self.text(cx);
11232 let text = text.trim();
11233
11234 if text.is_empty() {
11235 return None;
11236 }
11237
11238 Some(text.to_string())
11239 }
11240
11241 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11242 self.transact(cx, |this, cx| {
11243 this.buffer
11244 .read(cx)
11245 .as_singleton()
11246 .expect("you can only call set_text on editors for singleton buffers")
11247 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11248 });
11249 }
11250
11251 pub fn display_text(&self, cx: &mut AppContext) -> String {
11252 self.display_map
11253 .update(cx, |map, cx| map.snapshot(cx))
11254 .text()
11255 }
11256
11257 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11258 let mut wrap_guides = smallvec::smallvec![];
11259
11260 if self.show_wrap_guides == Some(false) {
11261 return wrap_guides;
11262 }
11263
11264 let settings = self.buffer.read(cx).settings_at(0, cx);
11265 if settings.show_wrap_guides {
11266 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11267 wrap_guides.push((soft_wrap as usize, true));
11268 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11269 wrap_guides.push((soft_wrap as usize, true));
11270 }
11271 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11272 }
11273
11274 wrap_guides
11275 }
11276
11277 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11278 let settings = self.buffer.read(cx).settings_at(0, cx);
11279 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11280 match mode {
11281 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11282 SoftWrap::None
11283 }
11284 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11285 language_settings::SoftWrap::PreferredLineLength => {
11286 SoftWrap::Column(settings.preferred_line_length)
11287 }
11288 language_settings::SoftWrap::Bounded => {
11289 SoftWrap::Bounded(settings.preferred_line_length)
11290 }
11291 }
11292 }
11293
11294 pub fn set_soft_wrap_mode(
11295 &mut self,
11296 mode: language_settings::SoftWrap,
11297 cx: &mut ViewContext<Self>,
11298 ) {
11299 self.soft_wrap_mode_override = Some(mode);
11300 cx.notify();
11301 }
11302
11303 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11304 self.text_style_refinement = Some(style);
11305 }
11306
11307 /// called by the Element so we know what style we were most recently rendered with.
11308 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11309 let rem_size = cx.rem_size();
11310 self.display_map.update(cx, |map, cx| {
11311 map.set_font(
11312 style.text.font(),
11313 style.text.font_size.to_pixels(rem_size),
11314 cx,
11315 )
11316 });
11317 self.style = Some(style);
11318 }
11319
11320 pub fn style(&self) -> Option<&EditorStyle> {
11321 self.style.as_ref()
11322 }
11323
11324 // Called by the element. This method is not designed to be called outside of the editor
11325 // element's layout code because it does not notify when rewrapping is computed synchronously.
11326 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11327 self.display_map
11328 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11329 }
11330
11331 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11332 if self.soft_wrap_mode_override.is_some() {
11333 self.soft_wrap_mode_override.take();
11334 } else {
11335 let soft_wrap = match self.soft_wrap_mode(cx) {
11336 SoftWrap::GitDiff => return,
11337 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11338 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11339 language_settings::SoftWrap::None
11340 }
11341 };
11342 self.soft_wrap_mode_override = Some(soft_wrap);
11343 }
11344 cx.notify();
11345 }
11346
11347 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11348 let Some(workspace) = self.workspace() else {
11349 return;
11350 };
11351 let fs = workspace.read(cx).app_state().fs.clone();
11352 let current_show = TabBarSettings::get_global(cx).show;
11353 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11354 setting.show = Some(!current_show);
11355 });
11356 }
11357
11358 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11359 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11360 self.buffer
11361 .read(cx)
11362 .settings_at(0, cx)
11363 .indent_guides
11364 .enabled
11365 });
11366 self.show_indent_guides = Some(!currently_enabled);
11367 cx.notify();
11368 }
11369
11370 fn should_show_indent_guides(&self) -> Option<bool> {
11371 self.show_indent_guides
11372 }
11373
11374 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11375 let mut editor_settings = EditorSettings::get_global(cx).clone();
11376 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11377 EditorSettings::override_global(editor_settings, cx);
11378 }
11379
11380 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11381 self.use_relative_line_numbers
11382 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11383 }
11384
11385 pub fn toggle_relative_line_numbers(
11386 &mut self,
11387 _: &ToggleRelativeLineNumbers,
11388 cx: &mut ViewContext<Self>,
11389 ) {
11390 let is_relative = self.should_use_relative_line_numbers(cx);
11391 self.set_relative_line_number(Some(!is_relative), cx)
11392 }
11393
11394 pub fn set_relative_line_number(
11395 &mut self,
11396 is_relative: Option<bool>,
11397 cx: &mut ViewContext<Self>,
11398 ) {
11399 self.use_relative_line_numbers = is_relative;
11400 cx.notify();
11401 }
11402
11403 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11404 self.show_gutter = show_gutter;
11405 cx.notify();
11406 }
11407
11408 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11409 self.show_scrollbars = show_scrollbars;
11410 cx.notify();
11411 }
11412
11413 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11414 self.show_line_numbers = Some(show_line_numbers);
11415 cx.notify();
11416 }
11417
11418 pub fn set_show_git_diff_gutter(
11419 &mut self,
11420 show_git_diff_gutter: bool,
11421 cx: &mut ViewContext<Self>,
11422 ) {
11423 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11424 cx.notify();
11425 }
11426
11427 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11428 self.show_code_actions = Some(show_code_actions);
11429 cx.notify();
11430 }
11431
11432 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11433 self.show_runnables = Some(show_runnables);
11434 cx.notify();
11435 }
11436
11437 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11438 if self.display_map.read(cx).masked != masked {
11439 self.display_map.update(cx, |map, _| map.masked = masked);
11440 }
11441 cx.notify()
11442 }
11443
11444 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11445 self.show_wrap_guides = Some(show_wrap_guides);
11446 cx.notify();
11447 }
11448
11449 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11450 self.show_indent_guides = Some(show_indent_guides);
11451 cx.notify();
11452 }
11453
11454 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11455 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11456 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11457 if let Some(dir) = file.abs_path(cx).parent() {
11458 return Some(dir.to_owned());
11459 }
11460 }
11461
11462 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11463 return Some(project_path.path.to_path_buf());
11464 }
11465 }
11466
11467 None
11468 }
11469
11470 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11471 self.active_excerpt(cx)?
11472 .1
11473 .read(cx)
11474 .file()
11475 .and_then(|f| f.as_local())
11476 }
11477
11478 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11479 if let Some(target) = self.target_file(cx) {
11480 cx.reveal_path(&target.abs_path(cx));
11481 }
11482 }
11483
11484 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11485 if let Some(file) = self.target_file(cx) {
11486 if let Some(path) = file.abs_path(cx).to_str() {
11487 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11488 }
11489 }
11490 }
11491
11492 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11493 if let Some(file) = self.target_file(cx) {
11494 if let Some(path) = file.path().to_str() {
11495 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11496 }
11497 }
11498 }
11499
11500 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11501 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11502
11503 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11504 self.start_git_blame(true, cx);
11505 }
11506
11507 cx.notify();
11508 }
11509
11510 pub fn toggle_git_blame_inline(
11511 &mut self,
11512 _: &ToggleGitBlameInline,
11513 cx: &mut ViewContext<Self>,
11514 ) {
11515 self.toggle_git_blame_inline_internal(true, cx);
11516 cx.notify();
11517 }
11518
11519 pub fn git_blame_inline_enabled(&self) -> bool {
11520 self.git_blame_inline_enabled
11521 }
11522
11523 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11524 self.show_selection_menu = self
11525 .show_selection_menu
11526 .map(|show_selections_menu| !show_selections_menu)
11527 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11528
11529 cx.notify();
11530 }
11531
11532 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11533 self.show_selection_menu
11534 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11535 }
11536
11537 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11538 if let Some(project) = self.project.as_ref() {
11539 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11540 return;
11541 };
11542
11543 if buffer.read(cx).file().is_none() {
11544 return;
11545 }
11546
11547 let focused = self.focus_handle(cx).contains_focused(cx);
11548
11549 let project = project.clone();
11550 let blame =
11551 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11552 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11553 self.blame = Some(blame);
11554 }
11555 }
11556
11557 fn toggle_git_blame_inline_internal(
11558 &mut self,
11559 user_triggered: bool,
11560 cx: &mut ViewContext<Self>,
11561 ) {
11562 if self.git_blame_inline_enabled {
11563 self.git_blame_inline_enabled = false;
11564 self.show_git_blame_inline = false;
11565 self.show_git_blame_inline_delay_task.take();
11566 } else {
11567 self.git_blame_inline_enabled = true;
11568 self.start_git_blame_inline(user_triggered, cx);
11569 }
11570
11571 cx.notify();
11572 }
11573
11574 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11575 self.start_git_blame(user_triggered, cx);
11576
11577 if ProjectSettings::get_global(cx)
11578 .git
11579 .inline_blame_delay()
11580 .is_some()
11581 {
11582 self.start_inline_blame_timer(cx);
11583 } else {
11584 self.show_git_blame_inline = true
11585 }
11586 }
11587
11588 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11589 self.blame.as_ref()
11590 }
11591
11592 pub fn show_git_blame_gutter(&self) -> bool {
11593 self.show_git_blame_gutter
11594 }
11595
11596 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11597 self.show_git_blame_gutter && self.has_blame_entries(cx)
11598 }
11599
11600 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11601 self.show_git_blame_inline
11602 && self.focus_handle.is_focused(cx)
11603 && !self.newest_selection_head_on_empty_line(cx)
11604 && self.has_blame_entries(cx)
11605 }
11606
11607 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11608 self.blame()
11609 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11610 }
11611
11612 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11613 let cursor_anchor = self.selections.newest_anchor().head();
11614
11615 let snapshot = self.buffer.read(cx).snapshot(cx);
11616 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11617
11618 snapshot.line_len(buffer_row) == 0
11619 }
11620
11621 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11622 let buffer_and_selection = maybe!({
11623 let selection = self.selections.newest::<Point>(cx);
11624 let selection_range = selection.range();
11625
11626 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11627 (buffer, selection_range.start.row..selection_range.end.row)
11628 } else {
11629 let multi_buffer = self.buffer().read(cx);
11630 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11631 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11632
11633 let (excerpt, range) = if selection.reversed {
11634 buffer_ranges.first()
11635 } else {
11636 buffer_ranges.last()
11637 }?;
11638
11639 let snapshot = excerpt.buffer();
11640 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11641 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11642 (
11643 multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11644 selection,
11645 )
11646 };
11647
11648 Some((buffer, selection))
11649 });
11650
11651 let Some((buffer, selection)) = buffer_and_selection else {
11652 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11653 };
11654
11655 let Some(project) = self.project.as_ref() else {
11656 return Task::ready(Err(anyhow!("editor does not have project")));
11657 };
11658
11659 project.update(cx, |project, cx| {
11660 project.get_permalink_to_line(&buffer, selection, cx)
11661 })
11662 }
11663
11664 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11665 let permalink_task = self.get_permalink_to_line(cx);
11666 let workspace = self.workspace();
11667
11668 cx.spawn(|_, mut cx| async move {
11669 match permalink_task.await {
11670 Ok(permalink) => {
11671 cx.update(|cx| {
11672 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11673 })
11674 .ok();
11675 }
11676 Err(err) => {
11677 let message = format!("Failed to copy permalink: {err}");
11678
11679 Err::<(), anyhow::Error>(err).log_err();
11680
11681 if let Some(workspace) = workspace {
11682 workspace
11683 .update(&mut cx, |workspace, cx| {
11684 struct CopyPermalinkToLine;
11685
11686 workspace.show_toast(
11687 Toast::new(
11688 NotificationId::unique::<CopyPermalinkToLine>(),
11689 message,
11690 ),
11691 cx,
11692 )
11693 })
11694 .ok();
11695 }
11696 }
11697 }
11698 })
11699 .detach();
11700 }
11701
11702 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11703 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11704 if let Some(file) = self.target_file(cx) {
11705 if let Some(path) = file.path().to_str() {
11706 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11707 }
11708 }
11709 }
11710
11711 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11712 let permalink_task = self.get_permalink_to_line(cx);
11713 let workspace = self.workspace();
11714
11715 cx.spawn(|_, mut cx| async move {
11716 match permalink_task.await {
11717 Ok(permalink) => {
11718 cx.update(|cx| {
11719 cx.open_url(permalink.as_ref());
11720 })
11721 .ok();
11722 }
11723 Err(err) => {
11724 let message = format!("Failed to open permalink: {err}");
11725
11726 Err::<(), anyhow::Error>(err).log_err();
11727
11728 if let Some(workspace) = workspace {
11729 workspace
11730 .update(&mut cx, |workspace, cx| {
11731 struct OpenPermalinkToLine;
11732
11733 workspace.show_toast(
11734 Toast::new(
11735 NotificationId::unique::<OpenPermalinkToLine>(),
11736 message,
11737 ),
11738 cx,
11739 )
11740 })
11741 .ok();
11742 }
11743 }
11744 }
11745 })
11746 .detach();
11747 }
11748
11749 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11750 self.insert_uuid(UuidVersion::V4, cx);
11751 }
11752
11753 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11754 self.insert_uuid(UuidVersion::V7, cx);
11755 }
11756
11757 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11758 self.transact(cx, |this, cx| {
11759 let edits = this
11760 .selections
11761 .all::<Point>(cx)
11762 .into_iter()
11763 .map(|selection| {
11764 let uuid = match version {
11765 UuidVersion::V4 => uuid::Uuid::new_v4(),
11766 UuidVersion::V7 => uuid::Uuid::now_v7(),
11767 };
11768
11769 (selection.range(), uuid.to_string())
11770 });
11771 this.edit(edits, cx);
11772 this.refresh_inline_completion(true, false, cx);
11773 });
11774 }
11775
11776 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11777 /// last highlight added will be used.
11778 ///
11779 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11780 pub fn highlight_rows<T: 'static>(
11781 &mut self,
11782 range: Range<Anchor>,
11783 color: Hsla,
11784 should_autoscroll: bool,
11785 cx: &mut ViewContext<Self>,
11786 ) {
11787 let snapshot = self.buffer().read(cx).snapshot(cx);
11788 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11789 let ix = row_highlights.binary_search_by(|highlight| {
11790 Ordering::Equal
11791 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11792 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11793 });
11794
11795 if let Err(mut ix) = ix {
11796 let index = post_inc(&mut self.highlight_order);
11797
11798 // If this range intersects with the preceding highlight, then merge it with
11799 // the preceding highlight. Otherwise insert a new highlight.
11800 let mut merged = false;
11801 if ix > 0 {
11802 let prev_highlight = &mut row_highlights[ix - 1];
11803 if prev_highlight
11804 .range
11805 .end
11806 .cmp(&range.start, &snapshot)
11807 .is_ge()
11808 {
11809 ix -= 1;
11810 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11811 prev_highlight.range.end = range.end;
11812 }
11813 merged = true;
11814 prev_highlight.index = index;
11815 prev_highlight.color = color;
11816 prev_highlight.should_autoscroll = should_autoscroll;
11817 }
11818 }
11819
11820 if !merged {
11821 row_highlights.insert(
11822 ix,
11823 RowHighlight {
11824 range: range.clone(),
11825 index,
11826 color,
11827 should_autoscroll,
11828 },
11829 );
11830 }
11831
11832 // If any of the following highlights intersect with this one, merge them.
11833 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11834 let highlight = &row_highlights[ix];
11835 if next_highlight
11836 .range
11837 .start
11838 .cmp(&highlight.range.end, &snapshot)
11839 .is_le()
11840 {
11841 if next_highlight
11842 .range
11843 .end
11844 .cmp(&highlight.range.end, &snapshot)
11845 .is_gt()
11846 {
11847 row_highlights[ix].range.end = next_highlight.range.end;
11848 }
11849 row_highlights.remove(ix + 1);
11850 } else {
11851 break;
11852 }
11853 }
11854 }
11855 }
11856
11857 /// Remove any highlighted row ranges of the given type that intersect the
11858 /// given ranges.
11859 pub fn remove_highlighted_rows<T: 'static>(
11860 &mut self,
11861 ranges_to_remove: Vec<Range<Anchor>>,
11862 cx: &mut ViewContext<Self>,
11863 ) {
11864 let snapshot = self.buffer().read(cx).snapshot(cx);
11865 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11866 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11867 row_highlights.retain(|highlight| {
11868 while let Some(range_to_remove) = ranges_to_remove.peek() {
11869 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11870 Ordering::Less | Ordering::Equal => {
11871 ranges_to_remove.next();
11872 }
11873 Ordering::Greater => {
11874 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11875 Ordering::Less | Ordering::Equal => {
11876 return false;
11877 }
11878 Ordering::Greater => break,
11879 }
11880 }
11881 }
11882 }
11883
11884 true
11885 })
11886 }
11887
11888 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11889 pub fn clear_row_highlights<T: 'static>(&mut self) {
11890 self.highlighted_rows.remove(&TypeId::of::<T>());
11891 }
11892
11893 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11894 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11895 self.highlighted_rows
11896 .get(&TypeId::of::<T>())
11897 .map_or(&[] as &[_], |vec| vec.as_slice())
11898 .iter()
11899 .map(|highlight| (highlight.range.clone(), highlight.color))
11900 }
11901
11902 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11903 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
11904 /// Allows to ignore certain kinds of highlights.
11905 pub fn highlighted_display_rows(
11906 &mut self,
11907 cx: &mut WindowContext,
11908 ) -> BTreeMap<DisplayRow, Hsla> {
11909 let snapshot = self.snapshot(cx);
11910 let mut used_highlight_orders = HashMap::default();
11911 self.highlighted_rows
11912 .iter()
11913 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11914 .fold(
11915 BTreeMap::<DisplayRow, Hsla>::new(),
11916 |mut unique_rows, highlight| {
11917 let start = highlight.range.start.to_display_point(&snapshot);
11918 let end = highlight.range.end.to_display_point(&snapshot);
11919 let start_row = start.row().0;
11920 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11921 && end.column() == 0
11922 {
11923 end.row().0.saturating_sub(1)
11924 } else {
11925 end.row().0
11926 };
11927 for row in start_row..=end_row {
11928 let used_index =
11929 used_highlight_orders.entry(row).or_insert(highlight.index);
11930 if highlight.index >= *used_index {
11931 *used_index = highlight.index;
11932 unique_rows.insert(DisplayRow(row), highlight.color);
11933 }
11934 }
11935 unique_rows
11936 },
11937 )
11938 }
11939
11940 pub fn highlighted_display_row_for_autoscroll(
11941 &self,
11942 snapshot: &DisplaySnapshot,
11943 ) -> Option<DisplayRow> {
11944 self.highlighted_rows
11945 .values()
11946 .flat_map(|highlighted_rows| highlighted_rows.iter())
11947 .filter_map(|highlight| {
11948 if highlight.should_autoscroll {
11949 Some(highlight.range.start.to_display_point(snapshot).row())
11950 } else {
11951 None
11952 }
11953 })
11954 .min()
11955 }
11956
11957 pub fn set_search_within_ranges(
11958 &mut self,
11959 ranges: &[Range<Anchor>],
11960 cx: &mut ViewContext<Self>,
11961 ) {
11962 self.highlight_background::<SearchWithinRange>(
11963 ranges,
11964 |colors| colors.editor_document_highlight_read_background,
11965 cx,
11966 )
11967 }
11968
11969 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11970 self.breadcrumb_header = Some(new_header);
11971 }
11972
11973 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11974 self.clear_background_highlights::<SearchWithinRange>(cx);
11975 }
11976
11977 pub fn highlight_background<T: 'static>(
11978 &mut self,
11979 ranges: &[Range<Anchor>],
11980 color_fetcher: fn(&ThemeColors) -> Hsla,
11981 cx: &mut ViewContext<Self>,
11982 ) {
11983 self.background_highlights
11984 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11985 self.scrollbar_marker_state.dirty = true;
11986 cx.notify();
11987 }
11988
11989 pub fn clear_background_highlights<T: 'static>(
11990 &mut self,
11991 cx: &mut ViewContext<Self>,
11992 ) -> Option<BackgroundHighlight> {
11993 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11994 if !text_highlights.1.is_empty() {
11995 self.scrollbar_marker_state.dirty = true;
11996 cx.notify();
11997 }
11998 Some(text_highlights)
11999 }
12000
12001 pub fn highlight_gutter<T: 'static>(
12002 &mut self,
12003 ranges: &[Range<Anchor>],
12004 color_fetcher: fn(&AppContext) -> Hsla,
12005 cx: &mut ViewContext<Self>,
12006 ) {
12007 self.gutter_highlights
12008 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12009 cx.notify();
12010 }
12011
12012 pub fn clear_gutter_highlights<T: 'static>(
12013 &mut self,
12014 cx: &mut ViewContext<Self>,
12015 ) -> Option<GutterHighlight> {
12016 cx.notify();
12017 self.gutter_highlights.remove(&TypeId::of::<T>())
12018 }
12019
12020 #[cfg(feature = "test-support")]
12021 pub fn all_text_background_highlights(
12022 &mut self,
12023 cx: &mut ViewContext<Self>,
12024 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12025 let snapshot = self.snapshot(cx);
12026 let buffer = &snapshot.buffer_snapshot;
12027 let start = buffer.anchor_before(0);
12028 let end = buffer.anchor_after(buffer.len());
12029 let theme = cx.theme().colors();
12030 self.background_highlights_in_range(start..end, &snapshot, theme)
12031 }
12032
12033 #[cfg(feature = "test-support")]
12034 pub fn search_background_highlights(
12035 &mut self,
12036 cx: &mut ViewContext<Self>,
12037 ) -> Vec<Range<Point>> {
12038 let snapshot = self.buffer().read(cx).snapshot(cx);
12039
12040 let highlights = self
12041 .background_highlights
12042 .get(&TypeId::of::<items::BufferSearchHighlights>());
12043
12044 if let Some((_color, ranges)) = highlights {
12045 ranges
12046 .iter()
12047 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12048 .collect_vec()
12049 } else {
12050 vec![]
12051 }
12052 }
12053
12054 fn document_highlights_for_position<'a>(
12055 &'a self,
12056 position: Anchor,
12057 buffer: &'a MultiBufferSnapshot,
12058 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12059 let read_highlights = self
12060 .background_highlights
12061 .get(&TypeId::of::<DocumentHighlightRead>())
12062 .map(|h| &h.1);
12063 let write_highlights = self
12064 .background_highlights
12065 .get(&TypeId::of::<DocumentHighlightWrite>())
12066 .map(|h| &h.1);
12067 let left_position = position.bias_left(buffer);
12068 let right_position = position.bias_right(buffer);
12069 read_highlights
12070 .into_iter()
12071 .chain(write_highlights)
12072 .flat_map(move |ranges| {
12073 let start_ix = match ranges.binary_search_by(|probe| {
12074 let cmp = probe.end.cmp(&left_position, buffer);
12075 if cmp.is_ge() {
12076 Ordering::Greater
12077 } else {
12078 Ordering::Less
12079 }
12080 }) {
12081 Ok(i) | Err(i) => i,
12082 };
12083
12084 ranges[start_ix..]
12085 .iter()
12086 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12087 })
12088 }
12089
12090 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12091 self.background_highlights
12092 .get(&TypeId::of::<T>())
12093 .map_or(false, |(_, highlights)| !highlights.is_empty())
12094 }
12095
12096 pub fn background_highlights_in_range(
12097 &self,
12098 search_range: Range<Anchor>,
12099 display_snapshot: &DisplaySnapshot,
12100 theme: &ThemeColors,
12101 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12102 let mut results = Vec::new();
12103 for (color_fetcher, ranges) in self.background_highlights.values() {
12104 let color = color_fetcher(theme);
12105 let start_ix = match ranges.binary_search_by(|probe| {
12106 let cmp = probe
12107 .end
12108 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12109 if cmp.is_gt() {
12110 Ordering::Greater
12111 } else {
12112 Ordering::Less
12113 }
12114 }) {
12115 Ok(i) | Err(i) => i,
12116 };
12117 for range in &ranges[start_ix..] {
12118 if range
12119 .start
12120 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12121 .is_ge()
12122 {
12123 break;
12124 }
12125
12126 let start = range.start.to_display_point(display_snapshot);
12127 let end = range.end.to_display_point(display_snapshot);
12128 results.push((start..end, color))
12129 }
12130 }
12131 results
12132 }
12133
12134 pub fn background_highlight_row_ranges<T: 'static>(
12135 &self,
12136 search_range: Range<Anchor>,
12137 display_snapshot: &DisplaySnapshot,
12138 count: usize,
12139 ) -> Vec<RangeInclusive<DisplayPoint>> {
12140 let mut results = Vec::new();
12141 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12142 return vec![];
12143 };
12144
12145 let start_ix = match ranges.binary_search_by(|probe| {
12146 let cmp = probe
12147 .end
12148 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12149 if cmp.is_gt() {
12150 Ordering::Greater
12151 } else {
12152 Ordering::Less
12153 }
12154 }) {
12155 Ok(i) | Err(i) => i,
12156 };
12157 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12158 if let (Some(start_display), Some(end_display)) = (start, end) {
12159 results.push(
12160 start_display.to_display_point(display_snapshot)
12161 ..=end_display.to_display_point(display_snapshot),
12162 );
12163 }
12164 };
12165 let mut start_row: Option<Point> = None;
12166 let mut end_row: Option<Point> = None;
12167 if ranges.len() > count {
12168 return Vec::new();
12169 }
12170 for range in &ranges[start_ix..] {
12171 if range
12172 .start
12173 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12174 .is_ge()
12175 {
12176 break;
12177 }
12178 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12179 if let Some(current_row) = &end_row {
12180 if end.row == current_row.row {
12181 continue;
12182 }
12183 }
12184 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12185 if start_row.is_none() {
12186 assert_eq!(end_row, None);
12187 start_row = Some(start);
12188 end_row = Some(end);
12189 continue;
12190 }
12191 if let Some(current_end) = end_row.as_mut() {
12192 if start.row > current_end.row + 1 {
12193 push_region(start_row, end_row);
12194 start_row = Some(start);
12195 end_row = Some(end);
12196 } else {
12197 // Merge two hunks.
12198 *current_end = end;
12199 }
12200 } else {
12201 unreachable!();
12202 }
12203 }
12204 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12205 push_region(start_row, end_row);
12206 results
12207 }
12208
12209 pub fn gutter_highlights_in_range(
12210 &self,
12211 search_range: Range<Anchor>,
12212 display_snapshot: &DisplaySnapshot,
12213 cx: &AppContext,
12214 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12215 let mut results = Vec::new();
12216 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12217 let color = color_fetcher(cx);
12218 let start_ix = match ranges.binary_search_by(|probe| {
12219 let cmp = probe
12220 .end
12221 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12222 if cmp.is_gt() {
12223 Ordering::Greater
12224 } else {
12225 Ordering::Less
12226 }
12227 }) {
12228 Ok(i) | Err(i) => i,
12229 };
12230 for range in &ranges[start_ix..] {
12231 if range
12232 .start
12233 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12234 .is_ge()
12235 {
12236 break;
12237 }
12238
12239 let start = range.start.to_display_point(display_snapshot);
12240 let end = range.end.to_display_point(display_snapshot);
12241 results.push((start..end, color))
12242 }
12243 }
12244 results
12245 }
12246
12247 /// Get the text ranges corresponding to the redaction query
12248 pub fn redacted_ranges(
12249 &self,
12250 search_range: Range<Anchor>,
12251 display_snapshot: &DisplaySnapshot,
12252 cx: &WindowContext,
12253 ) -> Vec<Range<DisplayPoint>> {
12254 display_snapshot
12255 .buffer_snapshot
12256 .redacted_ranges(search_range, |file| {
12257 if let Some(file) = file {
12258 file.is_private()
12259 && EditorSettings::get(
12260 Some(SettingsLocation {
12261 worktree_id: file.worktree_id(cx),
12262 path: file.path().as_ref(),
12263 }),
12264 cx,
12265 )
12266 .redact_private_values
12267 } else {
12268 false
12269 }
12270 })
12271 .map(|range| {
12272 range.start.to_display_point(display_snapshot)
12273 ..range.end.to_display_point(display_snapshot)
12274 })
12275 .collect()
12276 }
12277
12278 pub fn highlight_text<T: 'static>(
12279 &mut self,
12280 ranges: Vec<Range<Anchor>>,
12281 style: HighlightStyle,
12282 cx: &mut ViewContext<Self>,
12283 ) {
12284 self.display_map.update(cx, |map, _| {
12285 map.highlight_text(TypeId::of::<T>(), ranges, style)
12286 });
12287 cx.notify();
12288 }
12289
12290 pub(crate) fn highlight_inlays<T: 'static>(
12291 &mut self,
12292 highlights: Vec<InlayHighlight>,
12293 style: HighlightStyle,
12294 cx: &mut ViewContext<Self>,
12295 ) {
12296 self.display_map.update(cx, |map, _| {
12297 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12298 });
12299 cx.notify();
12300 }
12301
12302 pub fn text_highlights<'a, T: 'static>(
12303 &'a self,
12304 cx: &'a AppContext,
12305 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12306 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12307 }
12308
12309 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12310 let cleared = self
12311 .display_map
12312 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12313 if cleared {
12314 cx.notify();
12315 }
12316 }
12317
12318 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12319 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12320 && self.focus_handle.is_focused(cx)
12321 }
12322
12323 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12324 self.show_cursor_when_unfocused = is_enabled;
12325 cx.notify();
12326 }
12327
12328 pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12329 self.project
12330 .as_ref()
12331 .map(|project| project.read(cx).lsp_store())
12332 }
12333
12334 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12335 cx.notify();
12336 }
12337
12338 fn on_buffer_event(
12339 &mut self,
12340 multibuffer: Model<MultiBuffer>,
12341 event: &multi_buffer::Event,
12342 cx: &mut ViewContext<Self>,
12343 ) {
12344 match event {
12345 multi_buffer::Event::Edited {
12346 singleton_buffer_edited,
12347 edited_buffer: buffer_edited,
12348 } => {
12349 self.scrollbar_marker_state.dirty = true;
12350 self.active_indent_guides_state.dirty = true;
12351 self.refresh_active_diagnostics(cx);
12352 self.refresh_code_actions(cx);
12353 if self.has_active_inline_completion() {
12354 self.update_visible_inline_completion(cx);
12355 }
12356 if let Some(buffer) = buffer_edited {
12357 let buffer_id = buffer.read(cx).remote_id();
12358 if !self.registered_buffers.contains_key(&buffer_id) {
12359 if let Some(lsp_store) = self.lsp_store(cx) {
12360 lsp_store.update(cx, |lsp_store, cx| {
12361 self.registered_buffers.insert(
12362 buffer_id,
12363 lsp_store.register_buffer_with_language_servers(&buffer, cx),
12364 );
12365 })
12366 }
12367 }
12368 }
12369 cx.emit(EditorEvent::BufferEdited);
12370 cx.emit(SearchEvent::MatchesInvalidated);
12371 if *singleton_buffer_edited {
12372 if let Some(project) = &self.project {
12373 let project = project.read(cx);
12374 #[allow(clippy::mutable_key_type)]
12375 let languages_affected = multibuffer
12376 .read(cx)
12377 .all_buffers()
12378 .into_iter()
12379 .filter_map(|buffer| {
12380 let buffer = buffer.read(cx);
12381 let language = buffer.language()?;
12382 if project.is_local()
12383 && project
12384 .language_servers_for_local_buffer(buffer, cx)
12385 .count()
12386 == 0
12387 {
12388 None
12389 } else {
12390 Some(language)
12391 }
12392 })
12393 .cloned()
12394 .collect::<HashSet<_>>();
12395 if !languages_affected.is_empty() {
12396 self.refresh_inlay_hints(
12397 InlayHintRefreshReason::BufferEdited(languages_affected),
12398 cx,
12399 );
12400 }
12401 }
12402 }
12403
12404 let Some(project) = &self.project else { return };
12405 let (telemetry, is_via_ssh) = {
12406 let project = project.read(cx);
12407 let telemetry = project.client().telemetry().clone();
12408 let is_via_ssh = project.is_via_ssh();
12409 (telemetry, is_via_ssh)
12410 };
12411 refresh_linked_ranges(self, cx);
12412 telemetry.log_edit_event("editor", is_via_ssh);
12413 }
12414 multi_buffer::Event::ExcerptsAdded {
12415 buffer,
12416 predecessor,
12417 excerpts,
12418 } => {
12419 self.tasks_update_task = Some(self.refresh_runnables(cx));
12420 let buffer_id = buffer.read(cx).remote_id();
12421 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12422 if let Some(project) = &self.project {
12423 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12424 }
12425 }
12426 cx.emit(EditorEvent::ExcerptsAdded {
12427 buffer: buffer.clone(),
12428 predecessor: *predecessor,
12429 excerpts: excerpts.clone(),
12430 });
12431 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12432 }
12433 multi_buffer::Event::ExcerptsRemoved { ids } => {
12434 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12435 let buffer = self.buffer.read(cx);
12436 self.registered_buffers
12437 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12438 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12439 }
12440 multi_buffer::Event::ExcerptsEdited { ids } => {
12441 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12442 }
12443 multi_buffer::Event::ExcerptsExpanded { ids } => {
12444 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12445 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12446 }
12447 multi_buffer::Event::Reparsed(buffer_id) => {
12448 self.tasks_update_task = Some(self.refresh_runnables(cx));
12449
12450 cx.emit(EditorEvent::Reparsed(*buffer_id));
12451 }
12452 multi_buffer::Event::LanguageChanged(buffer_id) => {
12453 linked_editing_ranges::refresh_linked_ranges(self, cx);
12454 cx.emit(EditorEvent::Reparsed(*buffer_id));
12455 cx.notify();
12456 }
12457 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12458 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12459 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12460 cx.emit(EditorEvent::TitleChanged)
12461 }
12462 // multi_buffer::Event::DiffBaseChanged => {
12463 // self.scrollbar_marker_state.dirty = true;
12464 // cx.emit(EditorEvent::DiffBaseChanged);
12465 // cx.notify();
12466 // }
12467 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12468 multi_buffer::Event::DiagnosticsUpdated => {
12469 self.refresh_active_diagnostics(cx);
12470 self.scrollbar_marker_state.dirty = true;
12471 cx.notify();
12472 }
12473 _ => {}
12474 };
12475 }
12476
12477 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12478 cx.notify();
12479 }
12480
12481 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12482 self.tasks_update_task = Some(self.refresh_runnables(cx));
12483 self.refresh_inline_completion(true, false, cx);
12484 self.refresh_inlay_hints(
12485 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12486 self.selections.newest_anchor().head(),
12487 &self.buffer.read(cx).snapshot(cx),
12488 cx,
12489 )),
12490 cx,
12491 );
12492
12493 let old_cursor_shape = self.cursor_shape;
12494
12495 {
12496 let editor_settings = EditorSettings::get_global(cx);
12497 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12498 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12499 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12500 }
12501
12502 if old_cursor_shape != self.cursor_shape {
12503 cx.emit(EditorEvent::CursorShapeChanged);
12504 }
12505
12506 let project_settings = ProjectSettings::get_global(cx);
12507 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12508
12509 if self.mode == EditorMode::Full {
12510 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12511 if self.git_blame_inline_enabled != inline_blame_enabled {
12512 self.toggle_git_blame_inline_internal(false, cx);
12513 }
12514 }
12515
12516 cx.notify();
12517 }
12518
12519 pub fn set_searchable(&mut self, searchable: bool) {
12520 self.searchable = searchable;
12521 }
12522
12523 pub fn searchable(&self) -> bool {
12524 self.searchable
12525 }
12526
12527 fn open_proposed_changes_editor(
12528 &mut self,
12529 _: &OpenProposedChangesEditor,
12530 cx: &mut ViewContext<Self>,
12531 ) {
12532 let Some(workspace) = self.workspace() else {
12533 cx.propagate();
12534 return;
12535 };
12536
12537 let selections = self.selections.all::<usize>(cx);
12538 let multi_buffer = self.buffer.read(cx);
12539 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12540 let mut new_selections_by_buffer = HashMap::default();
12541 for selection in selections {
12542 for (excerpt, range) in
12543 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12544 {
12545 let mut range = range.to_point(excerpt.buffer());
12546 range.start.column = 0;
12547 range.end.column = excerpt.buffer().line_len(range.end.row);
12548 new_selections_by_buffer
12549 .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12550 .or_insert(Vec::new())
12551 .push(range)
12552 }
12553 }
12554
12555 let proposed_changes_buffers = new_selections_by_buffer
12556 .into_iter()
12557 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12558 .collect::<Vec<_>>();
12559 let proposed_changes_editor = cx.new_view(|cx| {
12560 ProposedChangesEditor::new(
12561 "Proposed changes",
12562 proposed_changes_buffers,
12563 self.project.clone(),
12564 cx,
12565 )
12566 });
12567
12568 cx.window_context().defer(move |cx| {
12569 workspace.update(cx, |workspace, cx| {
12570 workspace.active_pane().update(cx, |pane, cx| {
12571 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12572 });
12573 });
12574 });
12575 }
12576
12577 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12578 self.open_excerpts_common(None, true, cx)
12579 }
12580
12581 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12582 self.open_excerpts_common(None, false, cx)
12583 }
12584
12585 fn open_excerpts_common(
12586 &mut self,
12587 jump_data: Option<JumpData>,
12588 split: bool,
12589 cx: &mut ViewContext<Self>,
12590 ) {
12591 let Some(workspace) = self.workspace() else {
12592 cx.propagate();
12593 return;
12594 };
12595
12596 if self.buffer.read(cx).is_singleton() {
12597 cx.propagate();
12598 return;
12599 }
12600
12601 let mut new_selections_by_buffer = HashMap::default();
12602 match &jump_data {
12603 Some(JumpData::MultiBufferPoint {
12604 excerpt_id,
12605 position,
12606 anchor,
12607 line_offset_from_top,
12608 }) => {
12609 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12610 if let Some(buffer) = multi_buffer_snapshot
12611 .buffer_id_for_excerpt(*excerpt_id)
12612 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12613 {
12614 let buffer_snapshot = buffer.read(cx).snapshot();
12615 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12616 language::ToPoint::to_point(anchor, &buffer_snapshot)
12617 } else {
12618 buffer_snapshot.clip_point(*position, Bias::Left)
12619 };
12620 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12621 new_selections_by_buffer.insert(
12622 buffer,
12623 (
12624 vec![jump_to_offset..jump_to_offset],
12625 Some(*line_offset_from_top),
12626 ),
12627 );
12628 }
12629 }
12630 Some(JumpData::MultiBufferRow {
12631 row,
12632 line_offset_from_top,
12633 }) => {
12634 let point = MultiBufferPoint::new(row.0, 0);
12635 if let Some((buffer, buffer_point, _)) =
12636 self.buffer.read(cx).point_to_buffer_point(point, cx)
12637 {
12638 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12639 new_selections_by_buffer
12640 .entry(buffer)
12641 .or_insert((Vec::new(), Some(*line_offset_from_top)))
12642 .0
12643 .push(buffer_offset..buffer_offset)
12644 }
12645 }
12646 None => {
12647 let selections = self.selections.all::<usize>(cx);
12648 let multi_buffer = self.buffer.read(cx);
12649 for selection in selections {
12650 for (excerpt, mut range) in multi_buffer
12651 .snapshot(cx)
12652 .range_to_buffer_ranges(selection.range())
12653 {
12654 // When editing branch buffers, jump to the corresponding location
12655 // in their base buffer.
12656 let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12657 let buffer = buffer_handle.read(cx);
12658 if let Some(base_buffer) = buffer.base_buffer() {
12659 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12660 buffer_handle = base_buffer;
12661 }
12662
12663 if selection.reversed {
12664 mem::swap(&mut range.start, &mut range.end);
12665 }
12666 new_selections_by_buffer
12667 .entry(buffer_handle)
12668 .or_insert((Vec::new(), None))
12669 .0
12670 .push(range)
12671 }
12672 }
12673 }
12674 }
12675
12676 if new_selections_by_buffer.is_empty() {
12677 return;
12678 }
12679
12680 // We defer the pane interaction because we ourselves are a workspace item
12681 // and activating a new item causes the pane to call a method on us reentrantly,
12682 // which panics if we're on the stack.
12683 cx.window_context().defer(move |cx| {
12684 workspace.update(cx, |workspace, cx| {
12685 let pane = if split {
12686 workspace.adjacent_pane(cx)
12687 } else {
12688 workspace.active_pane().clone()
12689 };
12690
12691 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12692 let editor = buffer
12693 .read(cx)
12694 .file()
12695 .is_none()
12696 .then(|| {
12697 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12698 // so `workspace.open_project_item` will never find them, always opening a new editor.
12699 // Instead, we try to activate the existing editor in the pane first.
12700 let (editor, pane_item_index) =
12701 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12702 let editor = item.downcast::<Editor>()?;
12703 let singleton_buffer =
12704 editor.read(cx).buffer().read(cx).as_singleton()?;
12705 if singleton_buffer == buffer {
12706 Some((editor, i))
12707 } else {
12708 None
12709 }
12710 })?;
12711 pane.update(cx, |pane, cx| {
12712 pane.activate_item(pane_item_index, true, true, cx)
12713 });
12714 Some(editor)
12715 })
12716 .flatten()
12717 .unwrap_or_else(|| {
12718 workspace.open_project_item::<Self>(
12719 pane.clone(),
12720 buffer,
12721 true,
12722 true,
12723 cx,
12724 )
12725 });
12726
12727 editor.update(cx, |editor, cx| {
12728 let autoscroll = match scroll_offset {
12729 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12730 None => Autoscroll::newest(),
12731 };
12732 let nav_history = editor.nav_history.take();
12733 editor.change_selections(Some(autoscroll), cx, |s| {
12734 s.select_ranges(ranges);
12735 });
12736 editor.nav_history = nav_history;
12737 });
12738 }
12739 })
12740 });
12741 }
12742
12743 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12744 let snapshot = self.buffer.read(cx).read(cx);
12745 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12746 Some(
12747 ranges
12748 .iter()
12749 .map(move |range| {
12750 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12751 })
12752 .collect(),
12753 )
12754 }
12755
12756 fn selection_replacement_ranges(
12757 &self,
12758 range: Range<OffsetUtf16>,
12759 cx: &mut AppContext,
12760 ) -> Vec<Range<OffsetUtf16>> {
12761 let selections = self.selections.all::<OffsetUtf16>(cx);
12762 let newest_selection = selections
12763 .iter()
12764 .max_by_key(|selection| selection.id)
12765 .unwrap();
12766 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12767 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12768 let snapshot = self.buffer.read(cx).read(cx);
12769 selections
12770 .into_iter()
12771 .map(|mut selection| {
12772 selection.start.0 =
12773 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12774 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12775 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12776 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12777 })
12778 .collect()
12779 }
12780
12781 fn report_editor_event(
12782 &self,
12783 event_type: &'static str,
12784 file_extension: Option<String>,
12785 cx: &AppContext,
12786 ) {
12787 if cfg!(any(test, feature = "test-support")) {
12788 return;
12789 }
12790
12791 let Some(project) = &self.project else { return };
12792
12793 // If None, we are in a file without an extension
12794 let file = self
12795 .buffer
12796 .read(cx)
12797 .as_singleton()
12798 .and_then(|b| b.read(cx).file());
12799 let file_extension = file_extension.or(file
12800 .as_ref()
12801 .and_then(|file| Path::new(file.file_name(cx)).extension())
12802 .and_then(|e| e.to_str())
12803 .map(|a| a.to_string()));
12804
12805 let vim_mode = cx
12806 .global::<SettingsStore>()
12807 .raw_user_settings()
12808 .get("vim_mode")
12809 == Some(&serde_json::Value::Bool(true));
12810
12811 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12812 == language::language_settings::InlineCompletionProvider::Copilot;
12813 let copilot_enabled_for_language = self
12814 .buffer
12815 .read(cx)
12816 .settings_at(0, cx)
12817 .show_inline_completions;
12818
12819 let project = project.read(cx);
12820 telemetry::event!(
12821 event_type,
12822 file_extension,
12823 vim_mode,
12824 copilot_enabled,
12825 copilot_enabled_for_language,
12826 is_via_ssh = project.is_via_ssh(),
12827 );
12828 }
12829
12830 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12831 /// with each line being an array of {text, highlight} objects.
12832 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12833 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12834 return;
12835 };
12836
12837 #[derive(Serialize)]
12838 struct Chunk<'a> {
12839 text: String,
12840 highlight: Option<&'a str>,
12841 }
12842
12843 let snapshot = buffer.read(cx).snapshot();
12844 let range = self
12845 .selected_text_range(false, cx)
12846 .and_then(|selection| {
12847 if selection.range.is_empty() {
12848 None
12849 } else {
12850 Some(selection.range)
12851 }
12852 })
12853 .unwrap_or_else(|| 0..snapshot.len());
12854
12855 let chunks = snapshot.chunks(range, true);
12856 let mut lines = Vec::new();
12857 let mut line: VecDeque<Chunk> = VecDeque::new();
12858
12859 let Some(style) = self.style.as_ref() else {
12860 return;
12861 };
12862
12863 for chunk in chunks {
12864 let highlight = chunk
12865 .syntax_highlight_id
12866 .and_then(|id| id.name(&style.syntax));
12867 let mut chunk_lines = chunk.text.split('\n').peekable();
12868 while let Some(text) = chunk_lines.next() {
12869 let mut merged_with_last_token = false;
12870 if let Some(last_token) = line.back_mut() {
12871 if last_token.highlight == highlight {
12872 last_token.text.push_str(text);
12873 merged_with_last_token = true;
12874 }
12875 }
12876
12877 if !merged_with_last_token {
12878 line.push_back(Chunk {
12879 text: text.into(),
12880 highlight,
12881 });
12882 }
12883
12884 if chunk_lines.peek().is_some() {
12885 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12886 line.pop_front();
12887 }
12888 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12889 line.pop_back();
12890 }
12891
12892 lines.push(mem::take(&mut line));
12893 }
12894 }
12895 }
12896
12897 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12898 return;
12899 };
12900 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12901 }
12902
12903 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12904 self.request_autoscroll(Autoscroll::newest(), cx);
12905 let position = self.selections.newest_display(cx).start;
12906 mouse_context_menu::deploy_context_menu(self, None, position, cx);
12907 }
12908
12909 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12910 &self.inlay_hint_cache
12911 }
12912
12913 pub fn replay_insert_event(
12914 &mut self,
12915 text: &str,
12916 relative_utf16_range: Option<Range<isize>>,
12917 cx: &mut ViewContext<Self>,
12918 ) {
12919 if !self.input_enabled {
12920 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12921 return;
12922 }
12923 if let Some(relative_utf16_range) = relative_utf16_range {
12924 let selections = self.selections.all::<OffsetUtf16>(cx);
12925 self.change_selections(None, cx, |s| {
12926 let new_ranges = selections.into_iter().map(|range| {
12927 let start = OffsetUtf16(
12928 range
12929 .head()
12930 .0
12931 .saturating_add_signed(relative_utf16_range.start),
12932 );
12933 let end = OffsetUtf16(
12934 range
12935 .head()
12936 .0
12937 .saturating_add_signed(relative_utf16_range.end),
12938 );
12939 start..end
12940 });
12941 s.select_ranges(new_ranges);
12942 });
12943 }
12944
12945 self.handle_input(text, cx);
12946 }
12947
12948 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12949 let Some(provider) = self.semantics_provider.as_ref() else {
12950 return false;
12951 };
12952
12953 let mut supports = false;
12954 self.buffer().read(cx).for_each_buffer(|buffer| {
12955 supports |= provider.supports_inlay_hints(buffer, cx);
12956 });
12957 supports
12958 }
12959
12960 pub fn focus(&self, cx: &mut WindowContext) {
12961 cx.focus(&self.focus_handle)
12962 }
12963
12964 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12965 self.focus_handle.is_focused(cx)
12966 }
12967
12968 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12969 cx.emit(EditorEvent::Focused);
12970
12971 if let Some(descendant) = self
12972 .last_focused_descendant
12973 .take()
12974 .and_then(|descendant| descendant.upgrade())
12975 {
12976 cx.focus(&descendant);
12977 } else {
12978 if let Some(blame) = self.blame.as_ref() {
12979 blame.update(cx, GitBlame::focus)
12980 }
12981
12982 self.blink_manager.update(cx, BlinkManager::enable);
12983 self.show_cursor_names(cx);
12984 self.buffer.update(cx, |buffer, cx| {
12985 buffer.finalize_last_transaction(cx);
12986 if self.leader_peer_id.is_none() {
12987 buffer.set_active_selections(
12988 &self.selections.disjoint_anchors(),
12989 self.selections.line_mode,
12990 self.cursor_shape,
12991 cx,
12992 );
12993 }
12994 });
12995 }
12996 }
12997
12998 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12999 cx.emit(EditorEvent::FocusedIn)
13000 }
13001
13002 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13003 if event.blurred != self.focus_handle {
13004 self.last_focused_descendant = Some(event.blurred);
13005 }
13006 }
13007
13008 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13009 self.blink_manager.update(cx, BlinkManager::disable);
13010 self.buffer
13011 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13012
13013 if let Some(blame) = self.blame.as_ref() {
13014 blame.update(cx, GitBlame::blur)
13015 }
13016 if !self.hover_state.focused(cx) {
13017 hide_hover(self, cx);
13018 }
13019
13020 self.hide_context_menu(cx);
13021 cx.emit(EditorEvent::Blurred);
13022 cx.notify();
13023 }
13024
13025 pub fn register_action<A: Action>(
13026 &mut self,
13027 listener: impl Fn(&A, &mut WindowContext) + 'static,
13028 ) -> Subscription {
13029 let id = self.next_editor_action_id.post_inc();
13030 let listener = Arc::new(listener);
13031 self.editor_actions.borrow_mut().insert(
13032 id,
13033 Box::new(move |cx| {
13034 let cx = cx.window_context();
13035 let listener = listener.clone();
13036 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13037 let action = action.downcast_ref().unwrap();
13038 if phase == DispatchPhase::Bubble {
13039 listener(action, cx)
13040 }
13041 })
13042 }),
13043 );
13044
13045 let editor_actions = self.editor_actions.clone();
13046 Subscription::new(move || {
13047 editor_actions.borrow_mut().remove(&id);
13048 })
13049 }
13050
13051 pub fn file_header_size(&self) -> u32 {
13052 FILE_HEADER_HEIGHT
13053 }
13054
13055 pub fn revert(
13056 &mut self,
13057 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13058 cx: &mut ViewContext<Self>,
13059 ) {
13060 self.buffer().update(cx, |multi_buffer, cx| {
13061 for (buffer_id, changes) in revert_changes {
13062 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13063 buffer.update(cx, |buffer, cx| {
13064 buffer.edit(
13065 changes.into_iter().map(|(range, text)| {
13066 (range, text.to_string().map(Arc::<str>::from))
13067 }),
13068 None,
13069 cx,
13070 );
13071 });
13072 }
13073 }
13074 });
13075 self.change_selections(None, cx, |selections| selections.refresh());
13076 }
13077
13078 pub fn to_pixel_point(
13079 &mut self,
13080 source: multi_buffer::Anchor,
13081 editor_snapshot: &EditorSnapshot,
13082 cx: &mut ViewContext<Self>,
13083 ) -> Option<gpui::Point<Pixels>> {
13084 let source_point = source.to_display_point(editor_snapshot);
13085 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13086 }
13087
13088 pub fn display_to_pixel_point(
13089 &self,
13090 source: DisplayPoint,
13091 editor_snapshot: &EditorSnapshot,
13092 cx: &WindowContext,
13093 ) -> Option<gpui::Point<Pixels>> {
13094 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13095 let text_layout_details = self.text_layout_details(cx);
13096 let scroll_top = text_layout_details
13097 .scroll_anchor
13098 .scroll_position(editor_snapshot)
13099 .y;
13100
13101 if source.row().as_f32() < scroll_top.floor() {
13102 return None;
13103 }
13104 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13105 let source_y = line_height * (source.row().as_f32() - scroll_top);
13106 Some(gpui::Point::new(source_x, source_y))
13107 }
13108
13109 pub fn has_active_completions_menu(&self) -> bool {
13110 self.context_menu.borrow().as_ref().map_or(false, |menu| {
13111 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13112 })
13113 }
13114
13115 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13116 self.addons
13117 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13118 }
13119
13120 pub fn unregister_addon<T: Addon>(&mut self) {
13121 self.addons.remove(&std::any::TypeId::of::<T>());
13122 }
13123
13124 pub fn addon<T: Addon>(&self) -> Option<&T> {
13125 let type_id = std::any::TypeId::of::<T>();
13126 self.addons
13127 .get(&type_id)
13128 .and_then(|item| item.to_any().downcast_ref::<T>())
13129 }
13130
13131 pub fn add_change_set(
13132 &mut self,
13133 change_set: Model<BufferChangeSet>,
13134 cx: &mut ViewContext<Self>,
13135 ) {
13136 self.diff_map.add_change_set(change_set, cx);
13137 }
13138
13139 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13140 let text_layout_details = self.text_layout_details(cx);
13141 let style = &text_layout_details.editor_style;
13142 let font_id = cx.text_system().resolve_font(&style.text.font());
13143 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13144 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13145
13146 let em_width = cx
13147 .text_system()
13148 .typographic_bounds(font_id, font_size, 'm')
13149 .unwrap()
13150 .size
13151 .width;
13152
13153 gpui::Point::new(em_width, line_height)
13154 }
13155}
13156
13157fn get_unstaged_changes_for_buffers(
13158 project: &Model<Project>,
13159 buffers: impl IntoIterator<Item = Model<Buffer>>,
13160 cx: &mut ViewContext<Editor>,
13161) {
13162 let mut tasks = Vec::new();
13163 project.update(cx, |project, cx| {
13164 for buffer in buffers {
13165 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13166 }
13167 });
13168 cx.spawn(|this, mut cx| async move {
13169 let change_sets = futures::future::join_all(tasks).await;
13170 this.update(&mut cx, |this, cx| {
13171 for change_set in change_sets {
13172 if let Some(change_set) = change_set.log_err() {
13173 this.diff_map.add_change_set(change_set, cx);
13174 }
13175 }
13176 })
13177 .ok();
13178 })
13179 .detach();
13180}
13181
13182fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13183 let tab_size = tab_size.get() as usize;
13184 let mut width = offset;
13185
13186 for ch in text.chars() {
13187 width += if ch == '\t' {
13188 tab_size - (width % tab_size)
13189 } else {
13190 1
13191 };
13192 }
13193
13194 width - offset
13195}
13196
13197#[cfg(test)]
13198mod tests {
13199 use super::*;
13200
13201 #[test]
13202 fn test_string_size_with_expanded_tabs() {
13203 let nz = |val| NonZeroU32::new(val).unwrap();
13204 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13205 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13206 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13207 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13208 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13209 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13210 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13211 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13212 }
13213}
13214
13215/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13216struct WordBreakingTokenizer<'a> {
13217 input: &'a str,
13218}
13219
13220impl<'a> WordBreakingTokenizer<'a> {
13221 fn new(input: &'a str) -> Self {
13222 Self { input }
13223 }
13224}
13225
13226fn is_char_ideographic(ch: char) -> bool {
13227 use unicode_script::Script::*;
13228 use unicode_script::UnicodeScript;
13229 matches!(ch.script(), Han | Tangut | Yi)
13230}
13231
13232fn is_grapheme_ideographic(text: &str) -> bool {
13233 text.chars().any(is_char_ideographic)
13234}
13235
13236fn is_grapheme_whitespace(text: &str) -> bool {
13237 text.chars().any(|x| x.is_whitespace())
13238}
13239
13240fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13241 text.chars().next().map_or(false, |ch| {
13242 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13243 })
13244}
13245
13246#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13247struct WordBreakToken<'a> {
13248 token: &'a str,
13249 grapheme_len: usize,
13250 is_whitespace: bool,
13251}
13252
13253impl<'a> Iterator for WordBreakingTokenizer<'a> {
13254 /// Yields a span, the count of graphemes in the token, and whether it was
13255 /// whitespace. Note that it also breaks at word boundaries.
13256 type Item = WordBreakToken<'a>;
13257
13258 fn next(&mut self) -> Option<Self::Item> {
13259 use unicode_segmentation::UnicodeSegmentation;
13260 if self.input.is_empty() {
13261 return None;
13262 }
13263
13264 let mut iter = self.input.graphemes(true).peekable();
13265 let mut offset = 0;
13266 let mut graphemes = 0;
13267 if let Some(first_grapheme) = iter.next() {
13268 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13269 offset += first_grapheme.len();
13270 graphemes += 1;
13271 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13272 if let Some(grapheme) = iter.peek().copied() {
13273 if should_stay_with_preceding_ideograph(grapheme) {
13274 offset += grapheme.len();
13275 graphemes += 1;
13276 }
13277 }
13278 } else {
13279 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13280 let mut next_word_bound = words.peek().copied();
13281 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13282 next_word_bound = words.next();
13283 }
13284 while let Some(grapheme) = iter.peek().copied() {
13285 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13286 break;
13287 };
13288 if is_grapheme_whitespace(grapheme) != is_whitespace {
13289 break;
13290 };
13291 offset += grapheme.len();
13292 graphemes += 1;
13293 iter.next();
13294 }
13295 }
13296 let token = &self.input[..offset];
13297 self.input = &self.input[offset..];
13298 if is_whitespace {
13299 Some(WordBreakToken {
13300 token: " ",
13301 grapheme_len: 1,
13302 is_whitespace: true,
13303 })
13304 } else {
13305 Some(WordBreakToken {
13306 token,
13307 grapheme_len: graphemes,
13308 is_whitespace: false,
13309 })
13310 }
13311 } else {
13312 None
13313 }
13314 }
13315}
13316
13317#[test]
13318fn test_word_breaking_tokenizer() {
13319 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13320 ("", &[]),
13321 (" ", &[(" ", 1, true)]),
13322 ("Ʒ", &[("Ʒ", 1, false)]),
13323 ("Ǽ", &[("Ǽ", 1, false)]),
13324 ("⋑", &[("⋑", 1, false)]),
13325 ("⋑⋑", &[("⋑⋑", 2, false)]),
13326 (
13327 "原理,进而",
13328 &[
13329 ("原", 1, false),
13330 ("理,", 2, false),
13331 ("进", 1, false),
13332 ("而", 1, false),
13333 ],
13334 ),
13335 (
13336 "hello world",
13337 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13338 ),
13339 (
13340 "hello, world",
13341 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13342 ),
13343 (
13344 " hello world",
13345 &[
13346 (" ", 1, true),
13347 ("hello", 5, false),
13348 (" ", 1, true),
13349 ("world", 5, false),
13350 ],
13351 ),
13352 (
13353 "这是什么 \n 钢笔",
13354 &[
13355 ("这", 1, false),
13356 ("是", 1, false),
13357 ("什", 1, false),
13358 ("么", 1, false),
13359 (" ", 1, true),
13360 ("钢", 1, false),
13361 ("笔", 1, false),
13362 ],
13363 ),
13364 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13365 ];
13366
13367 for (input, result) in tests {
13368 assert_eq!(
13369 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13370 result
13371 .iter()
13372 .copied()
13373 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13374 token,
13375 grapheme_len,
13376 is_whitespace,
13377 })
13378 .collect::<Vec<_>>()
13379 );
13380 }
13381}
13382
13383fn wrap_with_prefix(
13384 line_prefix: String,
13385 unwrapped_text: String,
13386 wrap_column: usize,
13387 tab_size: NonZeroU32,
13388) -> String {
13389 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13390 let mut wrapped_text = String::new();
13391 let mut current_line = line_prefix.clone();
13392
13393 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13394 let mut current_line_len = line_prefix_len;
13395 for WordBreakToken {
13396 token,
13397 grapheme_len,
13398 is_whitespace,
13399 } in tokenizer
13400 {
13401 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13402 wrapped_text.push_str(current_line.trim_end());
13403 wrapped_text.push('\n');
13404 current_line.truncate(line_prefix.len());
13405 current_line_len = line_prefix_len;
13406 if !is_whitespace {
13407 current_line.push_str(token);
13408 current_line_len += grapheme_len;
13409 }
13410 } else if !is_whitespace {
13411 current_line.push_str(token);
13412 current_line_len += grapheme_len;
13413 } else if current_line_len != line_prefix_len {
13414 current_line.push(' ');
13415 current_line_len += 1;
13416 }
13417 }
13418
13419 if !current_line.is_empty() {
13420 wrapped_text.push_str(¤t_line);
13421 }
13422 wrapped_text
13423}
13424
13425#[test]
13426fn test_wrap_with_prefix() {
13427 assert_eq!(
13428 wrap_with_prefix(
13429 "# ".to_string(),
13430 "abcdefg".to_string(),
13431 4,
13432 NonZeroU32::new(4).unwrap()
13433 ),
13434 "# abcdefg"
13435 );
13436 assert_eq!(
13437 wrap_with_prefix(
13438 "".to_string(),
13439 "\thello world".to_string(),
13440 8,
13441 NonZeroU32::new(4).unwrap()
13442 ),
13443 "hello\nworld"
13444 );
13445 assert_eq!(
13446 wrap_with_prefix(
13447 "// ".to_string(),
13448 "xx \nyy zz aa bb cc".to_string(),
13449 12,
13450 NonZeroU32::new(4).unwrap()
13451 ),
13452 "// xx yy zz\n// aa bb cc"
13453 );
13454 assert_eq!(
13455 wrap_with_prefix(
13456 String::new(),
13457 "这是什么 \n 钢笔".to_string(),
13458 3,
13459 NonZeroU32::new(4).unwrap()
13460 ),
13461 "这是什\n么 钢\n笔"
13462 );
13463}
13464
13465fn hunks_for_selections(
13466 snapshot: &EditorSnapshot,
13467 selections: &[Selection<Point>],
13468) -> Vec<MultiBufferDiffHunk> {
13469 hunks_for_ranges(
13470 selections.iter().map(|selection| selection.range()),
13471 snapshot,
13472 )
13473}
13474
13475pub fn hunks_for_ranges(
13476 ranges: impl Iterator<Item = Range<Point>>,
13477 snapshot: &EditorSnapshot,
13478) -> Vec<MultiBufferDiffHunk> {
13479 let mut hunks = Vec::new();
13480 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13481 HashMap::default();
13482 for query_range in ranges {
13483 let query_rows =
13484 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13485 for hunk in snapshot.diff_map.diff_hunks_in_range(
13486 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13487 &snapshot.buffer_snapshot,
13488 ) {
13489 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13490 // when the caret is just above or just below the deleted hunk.
13491 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13492 let related_to_selection = if allow_adjacent {
13493 hunk.row_range.overlaps(&query_rows)
13494 || hunk.row_range.start == query_rows.end
13495 || hunk.row_range.end == query_rows.start
13496 } else {
13497 hunk.row_range.overlaps(&query_rows)
13498 };
13499 if related_to_selection {
13500 if !processed_buffer_rows
13501 .entry(hunk.buffer_id)
13502 .or_default()
13503 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13504 {
13505 continue;
13506 }
13507 hunks.push(hunk);
13508 }
13509 }
13510 }
13511
13512 hunks
13513}
13514
13515pub trait CollaborationHub {
13516 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13517 fn user_participant_indices<'a>(
13518 &self,
13519 cx: &'a AppContext,
13520 ) -> &'a HashMap<u64, ParticipantIndex>;
13521 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13522}
13523
13524impl CollaborationHub for Model<Project> {
13525 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13526 self.read(cx).collaborators()
13527 }
13528
13529 fn user_participant_indices<'a>(
13530 &self,
13531 cx: &'a AppContext,
13532 ) -> &'a HashMap<u64, ParticipantIndex> {
13533 self.read(cx).user_store().read(cx).participant_indices()
13534 }
13535
13536 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13537 let this = self.read(cx);
13538 let user_ids = this.collaborators().values().map(|c| c.user_id);
13539 this.user_store().read_with(cx, |user_store, cx| {
13540 user_store.participant_names(user_ids, cx)
13541 })
13542 }
13543}
13544
13545pub trait SemanticsProvider {
13546 fn hover(
13547 &self,
13548 buffer: &Model<Buffer>,
13549 position: text::Anchor,
13550 cx: &mut AppContext,
13551 ) -> Option<Task<Vec<project::Hover>>>;
13552
13553 fn inlay_hints(
13554 &self,
13555 buffer_handle: Model<Buffer>,
13556 range: Range<text::Anchor>,
13557 cx: &mut AppContext,
13558 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13559
13560 fn resolve_inlay_hint(
13561 &self,
13562 hint: InlayHint,
13563 buffer_handle: Model<Buffer>,
13564 server_id: LanguageServerId,
13565 cx: &mut AppContext,
13566 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13567
13568 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13569
13570 fn document_highlights(
13571 &self,
13572 buffer: &Model<Buffer>,
13573 position: text::Anchor,
13574 cx: &mut AppContext,
13575 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13576
13577 fn definitions(
13578 &self,
13579 buffer: &Model<Buffer>,
13580 position: text::Anchor,
13581 kind: GotoDefinitionKind,
13582 cx: &mut AppContext,
13583 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13584
13585 fn range_for_rename(
13586 &self,
13587 buffer: &Model<Buffer>,
13588 position: text::Anchor,
13589 cx: &mut AppContext,
13590 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13591
13592 fn perform_rename(
13593 &self,
13594 buffer: &Model<Buffer>,
13595 position: text::Anchor,
13596 new_name: String,
13597 cx: &mut AppContext,
13598 ) -> Option<Task<Result<ProjectTransaction>>>;
13599}
13600
13601pub trait CompletionProvider {
13602 fn completions(
13603 &self,
13604 buffer: &Model<Buffer>,
13605 buffer_position: text::Anchor,
13606 trigger: CompletionContext,
13607 cx: &mut ViewContext<Editor>,
13608 ) -> Task<Result<Vec<Completion>>>;
13609
13610 fn resolve_completions(
13611 &self,
13612 buffer: Model<Buffer>,
13613 completion_indices: Vec<usize>,
13614 completions: Rc<RefCell<Box<[Completion]>>>,
13615 cx: &mut ViewContext<Editor>,
13616 ) -> Task<Result<bool>>;
13617
13618 fn apply_additional_edits_for_completion(
13619 &self,
13620 _buffer: Model<Buffer>,
13621 _completions: Rc<RefCell<Box<[Completion]>>>,
13622 _completion_index: usize,
13623 _push_to_history: bool,
13624 _cx: &mut ViewContext<Editor>,
13625 ) -> Task<Result<Option<language::Transaction>>> {
13626 Task::ready(Ok(None))
13627 }
13628
13629 fn is_completion_trigger(
13630 &self,
13631 buffer: &Model<Buffer>,
13632 position: language::Anchor,
13633 text: &str,
13634 trigger_in_words: bool,
13635 cx: &mut ViewContext<Editor>,
13636 ) -> bool;
13637
13638 fn sort_completions(&self) -> bool {
13639 true
13640 }
13641}
13642
13643pub trait CodeActionProvider {
13644 fn id(&self) -> Arc<str>;
13645
13646 fn code_actions(
13647 &self,
13648 buffer: &Model<Buffer>,
13649 range: Range<text::Anchor>,
13650 cx: &mut WindowContext,
13651 ) -> Task<Result<Vec<CodeAction>>>;
13652
13653 fn apply_code_action(
13654 &self,
13655 buffer_handle: Model<Buffer>,
13656 action: CodeAction,
13657 excerpt_id: ExcerptId,
13658 push_to_history: bool,
13659 cx: &mut WindowContext,
13660 ) -> Task<Result<ProjectTransaction>>;
13661}
13662
13663impl CodeActionProvider for Model<Project> {
13664 fn id(&self) -> Arc<str> {
13665 "project".into()
13666 }
13667
13668 fn code_actions(
13669 &self,
13670 buffer: &Model<Buffer>,
13671 range: Range<text::Anchor>,
13672 cx: &mut WindowContext,
13673 ) -> Task<Result<Vec<CodeAction>>> {
13674 self.update(cx, |project, cx| {
13675 project.code_actions(buffer, range, None, cx)
13676 })
13677 }
13678
13679 fn apply_code_action(
13680 &self,
13681 buffer_handle: Model<Buffer>,
13682 action: CodeAction,
13683 _excerpt_id: ExcerptId,
13684 push_to_history: bool,
13685 cx: &mut WindowContext,
13686 ) -> Task<Result<ProjectTransaction>> {
13687 self.update(cx, |project, cx| {
13688 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13689 })
13690 }
13691}
13692
13693fn snippet_completions(
13694 project: &Project,
13695 buffer: &Model<Buffer>,
13696 buffer_position: text::Anchor,
13697 cx: &mut AppContext,
13698) -> Task<Result<Vec<Completion>>> {
13699 let language = buffer.read(cx).language_at(buffer_position);
13700 let language_name = language.as_ref().map(|language| language.lsp_id());
13701 let snippet_store = project.snippets().read(cx);
13702 let snippets = snippet_store.snippets_for(language_name, cx);
13703
13704 if snippets.is_empty() {
13705 return Task::ready(Ok(vec![]));
13706 }
13707 let snapshot = buffer.read(cx).text_snapshot();
13708 let chars: String = snapshot
13709 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13710 .collect();
13711
13712 let scope = language.map(|language| language.default_scope());
13713 let executor = cx.background_executor().clone();
13714
13715 cx.background_executor().spawn(async move {
13716 let classifier = CharClassifier::new(scope).for_completion(true);
13717 let mut last_word = chars
13718 .chars()
13719 .take_while(|c| classifier.is_word(*c))
13720 .collect::<String>();
13721 last_word = last_word.chars().rev().collect();
13722
13723 if last_word.is_empty() {
13724 return Ok(vec![]);
13725 }
13726
13727 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13728 let to_lsp = |point: &text::Anchor| {
13729 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13730 point_to_lsp(end)
13731 };
13732 let lsp_end = to_lsp(&buffer_position);
13733
13734 let candidates = snippets
13735 .iter()
13736 .enumerate()
13737 .flat_map(|(ix, snippet)| {
13738 snippet
13739 .prefix
13740 .iter()
13741 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13742 })
13743 .collect::<Vec<StringMatchCandidate>>();
13744
13745 let mut matches = fuzzy::match_strings(
13746 &candidates,
13747 &last_word,
13748 last_word.chars().any(|c| c.is_uppercase()),
13749 100,
13750 &Default::default(),
13751 executor,
13752 )
13753 .await;
13754
13755 // Remove all candidates where the query's start does not match the start of any word in the candidate
13756 if let Some(query_start) = last_word.chars().next() {
13757 matches.retain(|string_match| {
13758 split_words(&string_match.string).any(|word| {
13759 // Check that the first codepoint of the word as lowercase matches the first
13760 // codepoint of the query as lowercase
13761 word.chars()
13762 .flat_map(|codepoint| codepoint.to_lowercase())
13763 .zip(query_start.to_lowercase())
13764 .all(|(word_cp, query_cp)| word_cp == query_cp)
13765 })
13766 });
13767 }
13768
13769 let matched_strings = matches
13770 .into_iter()
13771 .map(|m| m.string)
13772 .collect::<HashSet<_>>();
13773
13774 let result: Vec<Completion> = snippets
13775 .into_iter()
13776 .filter_map(|snippet| {
13777 let matching_prefix = snippet
13778 .prefix
13779 .iter()
13780 .find(|prefix| matched_strings.contains(*prefix))?;
13781 let start = as_offset - last_word.len();
13782 let start = snapshot.anchor_before(start);
13783 let range = start..buffer_position;
13784 let lsp_start = to_lsp(&start);
13785 let lsp_range = lsp::Range {
13786 start: lsp_start,
13787 end: lsp_end,
13788 };
13789 Some(Completion {
13790 old_range: range,
13791 new_text: snippet.body.clone(),
13792 resolved: false,
13793 label: CodeLabel {
13794 text: matching_prefix.clone(),
13795 runs: vec![],
13796 filter_range: 0..matching_prefix.len(),
13797 },
13798 server_id: LanguageServerId(usize::MAX),
13799 documentation: snippet.description.clone().map(Documentation::SingleLine),
13800 lsp_completion: lsp::CompletionItem {
13801 label: snippet.prefix.first().unwrap().clone(),
13802 kind: Some(CompletionItemKind::SNIPPET),
13803 label_details: snippet.description.as_ref().map(|description| {
13804 lsp::CompletionItemLabelDetails {
13805 detail: Some(description.clone()),
13806 description: None,
13807 }
13808 }),
13809 insert_text_format: Some(InsertTextFormat::SNIPPET),
13810 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13811 lsp::InsertReplaceEdit {
13812 new_text: snippet.body.clone(),
13813 insert: lsp_range,
13814 replace: lsp_range,
13815 },
13816 )),
13817 filter_text: Some(snippet.body.clone()),
13818 sort_text: Some(char::MAX.to_string()),
13819 ..Default::default()
13820 },
13821 confirm: None,
13822 })
13823 })
13824 .collect();
13825
13826 Ok(result)
13827 })
13828}
13829
13830impl CompletionProvider for Model<Project> {
13831 fn completions(
13832 &self,
13833 buffer: &Model<Buffer>,
13834 buffer_position: text::Anchor,
13835 options: CompletionContext,
13836 cx: &mut ViewContext<Editor>,
13837 ) -> Task<Result<Vec<Completion>>> {
13838 self.update(cx, |project, cx| {
13839 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13840 let project_completions = project.completions(buffer, buffer_position, options, cx);
13841 cx.background_executor().spawn(async move {
13842 let mut completions = project_completions.await?;
13843 let snippets_completions = snippets.await?;
13844 completions.extend(snippets_completions);
13845 Ok(completions)
13846 })
13847 })
13848 }
13849
13850 fn resolve_completions(
13851 &self,
13852 buffer: Model<Buffer>,
13853 completion_indices: Vec<usize>,
13854 completions: Rc<RefCell<Box<[Completion]>>>,
13855 cx: &mut ViewContext<Editor>,
13856 ) -> Task<Result<bool>> {
13857 self.update(cx, |project, cx| {
13858 project.lsp_store().update(cx, |lsp_store, cx| {
13859 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13860 })
13861 })
13862 }
13863
13864 fn apply_additional_edits_for_completion(
13865 &self,
13866 buffer: Model<Buffer>,
13867 completions: Rc<RefCell<Box<[Completion]>>>,
13868 completion_index: usize,
13869 push_to_history: bool,
13870 cx: &mut ViewContext<Editor>,
13871 ) -> Task<Result<Option<language::Transaction>>> {
13872 self.update(cx, |project, cx| {
13873 project.lsp_store().update(cx, |lsp_store, cx| {
13874 lsp_store.apply_additional_edits_for_completion(
13875 buffer,
13876 completions,
13877 completion_index,
13878 push_to_history,
13879 cx,
13880 )
13881 })
13882 })
13883 }
13884
13885 fn is_completion_trigger(
13886 &self,
13887 buffer: &Model<Buffer>,
13888 position: language::Anchor,
13889 text: &str,
13890 trigger_in_words: bool,
13891 cx: &mut ViewContext<Editor>,
13892 ) -> bool {
13893 let mut chars = text.chars();
13894 let char = if let Some(char) = chars.next() {
13895 char
13896 } else {
13897 return false;
13898 };
13899 if chars.next().is_some() {
13900 return false;
13901 }
13902
13903 let buffer = buffer.read(cx);
13904 let snapshot = buffer.snapshot();
13905 if !snapshot.settings_at(position, cx).show_completions_on_input {
13906 return false;
13907 }
13908 let classifier = snapshot.char_classifier_at(position).for_completion(true);
13909 if trigger_in_words && classifier.is_word(char) {
13910 return true;
13911 }
13912
13913 buffer.completion_triggers().contains(text)
13914 }
13915}
13916
13917impl SemanticsProvider for Model<Project> {
13918 fn hover(
13919 &self,
13920 buffer: &Model<Buffer>,
13921 position: text::Anchor,
13922 cx: &mut AppContext,
13923 ) -> Option<Task<Vec<project::Hover>>> {
13924 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13925 }
13926
13927 fn document_highlights(
13928 &self,
13929 buffer: &Model<Buffer>,
13930 position: text::Anchor,
13931 cx: &mut AppContext,
13932 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13933 Some(self.update(cx, |project, cx| {
13934 project.document_highlights(buffer, position, cx)
13935 }))
13936 }
13937
13938 fn definitions(
13939 &self,
13940 buffer: &Model<Buffer>,
13941 position: text::Anchor,
13942 kind: GotoDefinitionKind,
13943 cx: &mut AppContext,
13944 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13945 Some(self.update(cx, |project, cx| match kind {
13946 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13947 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13948 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13949 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13950 }))
13951 }
13952
13953 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13954 // TODO: make this work for remote projects
13955 self.read(cx)
13956 .language_servers_for_local_buffer(buffer.read(cx), cx)
13957 .any(
13958 |(_, server)| match server.capabilities().inlay_hint_provider {
13959 Some(lsp::OneOf::Left(enabled)) => enabled,
13960 Some(lsp::OneOf::Right(_)) => true,
13961 None => false,
13962 },
13963 )
13964 }
13965
13966 fn inlay_hints(
13967 &self,
13968 buffer_handle: Model<Buffer>,
13969 range: Range<text::Anchor>,
13970 cx: &mut AppContext,
13971 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13972 Some(self.update(cx, |project, cx| {
13973 project.inlay_hints(buffer_handle, range, cx)
13974 }))
13975 }
13976
13977 fn resolve_inlay_hint(
13978 &self,
13979 hint: InlayHint,
13980 buffer_handle: Model<Buffer>,
13981 server_id: LanguageServerId,
13982 cx: &mut AppContext,
13983 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13984 Some(self.update(cx, |project, cx| {
13985 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13986 }))
13987 }
13988
13989 fn range_for_rename(
13990 &self,
13991 buffer: &Model<Buffer>,
13992 position: text::Anchor,
13993 cx: &mut AppContext,
13994 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13995 Some(self.update(cx, |project, cx| {
13996 let buffer = buffer.clone();
13997 let task = project.prepare_rename(buffer.clone(), position, cx);
13998 cx.spawn(|_, mut cx| async move {
13999 Ok(match task.await? {
14000 PrepareRenameResponse::Success(range) => Some(range),
14001 PrepareRenameResponse::InvalidPosition => None,
14002 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
14003 // Fallback on using TreeSitter info to determine identifier range
14004 buffer.update(&mut cx, |buffer, _| {
14005 let snapshot = buffer.snapshot();
14006 let (range, kind) = snapshot.surrounding_word(position);
14007 if kind != Some(CharKind::Word) {
14008 return None;
14009 }
14010 Some(
14011 snapshot.anchor_before(range.start)
14012 ..snapshot.anchor_after(range.end),
14013 )
14014 })?
14015 }
14016 })
14017 })
14018 }))
14019 }
14020
14021 fn perform_rename(
14022 &self,
14023 buffer: &Model<Buffer>,
14024 position: text::Anchor,
14025 new_name: String,
14026 cx: &mut AppContext,
14027 ) -> Option<Task<Result<ProjectTransaction>>> {
14028 Some(self.update(cx, |project, cx| {
14029 project.perform_rename(buffer.clone(), position, new_name, cx)
14030 }))
14031 }
14032}
14033
14034fn inlay_hint_settings(
14035 location: Anchor,
14036 snapshot: &MultiBufferSnapshot,
14037 cx: &mut ViewContext<Editor>,
14038) -> InlayHintSettings {
14039 let file = snapshot.file_at(location);
14040 let language = snapshot.language_at(location).map(|l| l.name());
14041 language_settings(language, file, cx).inlay_hints
14042}
14043
14044fn consume_contiguous_rows(
14045 contiguous_row_selections: &mut Vec<Selection<Point>>,
14046 selection: &Selection<Point>,
14047 display_map: &DisplaySnapshot,
14048 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14049) -> (MultiBufferRow, MultiBufferRow) {
14050 contiguous_row_selections.push(selection.clone());
14051 let start_row = MultiBufferRow(selection.start.row);
14052 let mut end_row = ending_row(selection, display_map);
14053
14054 while let Some(next_selection) = selections.peek() {
14055 if next_selection.start.row <= end_row.0 {
14056 end_row = ending_row(next_selection, display_map);
14057 contiguous_row_selections.push(selections.next().unwrap().clone());
14058 } else {
14059 break;
14060 }
14061 }
14062 (start_row, end_row)
14063}
14064
14065fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14066 if next_selection.end.column > 0 || next_selection.is_empty() {
14067 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14068 } else {
14069 MultiBufferRow(next_selection.end.row)
14070 }
14071}
14072
14073impl EditorSnapshot {
14074 pub fn remote_selections_in_range<'a>(
14075 &'a self,
14076 range: &'a Range<Anchor>,
14077 collaboration_hub: &dyn CollaborationHub,
14078 cx: &'a AppContext,
14079 ) -> impl 'a + Iterator<Item = RemoteSelection> {
14080 let participant_names = collaboration_hub.user_names(cx);
14081 let participant_indices = collaboration_hub.user_participant_indices(cx);
14082 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14083 let collaborators_by_replica_id = collaborators_by_peer_id
14084 .iter()
14085 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14086 .collect::<HashMap<_, _>>();
14087 self.buffer_snapshot
14088 .selections_in_range(range, false)
14089 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14090 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14091 let participant_index = participant_indices.get(&collaborator.user_id).copied();
14092 let user_name = participant_names.get(&collaborator.user_id).cloned();
14093 Some(RemoteSelection {
14094 replica_id,
14095 selection,
14096 cursor_shape,
14097 line_mode,
14098 participant_index,
14099 peer_id: collaborator.peer_id,
14100 user_name,
14101 })
14102 })
14103 }
14104
14105 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14106 self.display_snapshot.buffer_snapshot.language_at(position)
14107 }
14108
14109 pub fn is_focused(&self) -> bool {
14110 self.is_focused
14111 }
14112
14113 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14114 self.placeholder_text.as_ref()
14115 }
14116
14117 pub fn scroll_position(&self) -> gpui::Point<f32> {
14118 self.scroll_anchor.scroll_position(&self.display_snapshot)
14119 }
14120
14121 fn gutter_dimensions(
14122 &self,
14123 font_id: FontId,
14124 font_size: Pixels,
14125 em_width: Pixels,
14126 em_advance: Pixels,
14127 max_line_number_width: Pixels,
14128 cx: &AppContext,
14129 ) -> GutterDimensions {
14130 if !self.show_gutter {
14131 return GutterDimensions::default();
14132 }
14133 let descent = cx.text_system().descent(font_id, font_size);
14134
14135 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14136 matches!(
14137 ProjectSettings::get_global(cx).git.git_gutter,
14138 Some(GitGutterSetting::TrackedFiles)
14139 )
14140 });
14141 let gutter_settings = EditorSettings::get_global(cx).gutter;
14142 let show_line_numbers = self
14143 .show_line_numbers
14144 .unwrap_or(gutter_settings.line_numbers);
14145 let line_gutter_width = if show_line_numbers {
14146 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14147 let min_width_for_number_on_gutter = em_advance * 4.0;
14148 max_line_number_width.max(min_width_for_number_on_gutter)
14149 } else {
14150 0.0.into()
14151 };
14152
14153 let show_code_actions = self
14154 .show_code_actions
14155 .unwrap_or(gutter_settings.code_actions);
14156
14157 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14158
14159 let git_blame_entries_width =
14160 self.git_blame_gutter_max_author_length
14161 .map(|max_author_length| {
14162 // Length of the author name, but also space for the commit hash,
14163 // the spacing and the timestamp.
14164 let max_char_count = max_author_length
14165 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14166 + 7 // length of commit sha
14167 + 14 // length of max relative timestamp ("60 minutes ago")
14168 + 4; // gaps and margins
14169
14170 em_advance * max_char_count
14171 });
14172
14173 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14174 left_padding += if show_code_actions || show_runnables {
14175 em_width * 3.0
14176 } else if show_git_gutter && show_line_numbers {
14177 em_width * 2.0
14178 } else if show_git_gutter || show_line_numbers {
14179 em_width
14180 } else {
14181 px(0.)
14182 };
14183
14184 let right_padding = if gutter_settings.folds && show_line_numbers {
14185 em_width * 4.0
14186 } else if gutter_settings.folds {
14187 em_width * 3.0
14188 } else if show_line_numbers {
14189 em_width
14190 } else {
14191 px(0.)
14192 };
14193
14194 GutterDimensions {
14195 left_padding,
14196 right_padding,
14197 width: line_gutter_width + left_padding + right_padding,
14198 margin: -descent,
14199 git_blame_entries_width,
14200 }
14201 }
14202
14203 pub fn render_crease_toggle(
14204 &self,
14205 buffer_row: MultiBufferRow,
14206 row_contains_cursor: bool,
14207 editor: View<Editor>,
14208 cx: &mut WindowContext,
14209 ) -> Option<AnyElement> {
14210 let folded = self.is_line_folded(buffer_row);
14211 let mut is_foldable = false;
14212
14213 if let Some(crease) = self
14214 .crease_snapshot
14215 .query_row(buffer_row, &self.buffer_snapshot)
14216 {
14217 is_foldable = true;
14218 match crease {
14219 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14220 if let Some(render_toggle) = render_toggle {
14221 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14222 if folded {
14223 editor.update(cx, |editor, cx| {
14224 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14225 });
14226 } else {
14227 editor.update(cx, |editor, cx| {
14228 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14229 });
14230 }
14231 });
14232 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14233 }
14234 }
14235 }
14236 }
14237
14238 is_foldable |= self.starts_indent(buffer_row);
14239
14240 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14241 Some(
14242 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14243 .toggle_state(folded)
14244 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14245 if folded {
14246 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14247 } else {
14248 this.fold_at(&FoldAt { buffer_row }, cx);
14249 }
14250 }))
14251 .into_any_element(),
14252 )
14253 } else {
14254 None
14255 }
14256 }
14257
14258 pub fn render_crease_trailer(
14259 &self,
14260 buffer_row: MultiBufferRow,
14261 cx: &mut WindowContext,
14262 ) -> Option<AnyElement> {
14263 let folded = self.is_line_folded(buffer_row);
14264 if let Crease::Inline { render_trailer, .. } = self
14265 .crease_snapshot
14266 .query_row(buffer_row, &self.buffer_snapshot)?
14267 {
14268 let render_trailer = render_trailer.as_ref()?;
14269 Some(render_trailer(buffer_row, folded, cx))
14270 } else {
14271 None
14272 }
14273 }
14274}
14275
14276impl Deref for EditorSnapshot {
14277 type Target = DisplaySnapshot;
14278
14279 fn deref(&self) -> &Self::Target {
14280 &self.display_snapshot
14281 }
14282}
14283
14284#[derive(Clone, Debug, PartialEq, Eq)]
14285pub enum EditorEvent {
14286 InputIgnored {
14287 text: Arc<str>,
14288 },
14289 InputHandled {
14290 utf16_range_to_replace: Option<Range<isize>>,
14291 text: Arc<str>,
14292 },
14293 ExcerptsAdded {
14294 buffer: Model<Buffer>,
14295 predecessor: ExcerptId,
14296 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14297 },
14298 ExcerptsRemoved {
14299 ids: Vec<ExcerptId>,
14300 },
14301 BufferFoldToggled {
14302 ids: Vec<ExcerptId>,
14303 folded: bool,
14304 },
14305 ExcerptsEdited {
14306 ids: Vec<ExcerptId>,
14307 },
14308 ExcerptsExpanded {
14309 ids: Vec<ExcerptId>,
14310 },
14311 BufferEdited,
14312 Edited {
14313 transaction_id: clock::Lamport,
14314 },
14315 Reparsed(BufferId),
14316 Focused,
14317 FocusedIn,
14318 Blurred,
14319 DirtyChanged,
14320 Saved,
14321 TitleChanged,
14322 DiffBaseChanged,
14323 SelectionsChanged {
14324 local: bool,
14325 },
14326 ScrollPositionChanged {
14327 local: bool,
14328 autoscroll: bool,
14329 },
14330 Closed,
14331 TransactionUndone {
14332 transaction_id: clock::Lamport,
14333 },
14334 TransactionBegun {
14335 transaction_id: clock::Lamport,
14336 },
14337 Reloaded,
14338 CursorShapeChanged,
14339}
14340
14341impl EventEmitter<EditorEvent> for Editor {}
14342
14343impl FocusableView for Editor {
14344 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14345 self.focus_handle.clone()
14346 }
14347}
14348
14349impl Render for Editor {
14350 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14351 let settings = ThemeSettings::get_global(cx);
14352
14353 let mut text_style = match self.mode {
14354 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14355 color: cx.theme().colors().editor_foreground,
14356 font_family: settings.ui_font.family.clone(),
14357 font_features: settings.ui_font.features.clone(),
14358 font_fallbacks: settings.ui_font.fallbacks.clone(),
14359 font_size: rems(0.875).into(),
14360 font_weight: settings.ui_font.weight,
14361 line_height: relative(settings.buffer_line_height.value()),
14362 ..Default::default()
14363 },
14364 EditorMode::Full => TextStyle {
14365 color: cx.theme().colors().editor_foreground,
14366 font_family: settings.buffer_font.family.clone(),
14367 font_features: settings.buffer_font.features.clone(),
14368 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14369 font_size: settings.buffer_font_size(cx).into(),
14370 font_weight: settings.buffer_font.weight,
14371 line_height: relative(settings.buffer_line_height.value()),
14372 ..Default::default()
14373 },
14374 };
14375 if let Some(text_style_refinement) = &self.text_style_refinement {
14376 text_style.refine(text_style_refinement)
14377 }
14378
14379 let background = match self.mode {
14380 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14381 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14382 EditorMode::Full => cx.theme().colors().editor_background,
14383 };
14384
14385 EditorElement::new(
14386 cx.view(),
14387 EditorStyle {
14388 background,
14389 local_player: cx.theme().players().local(),
14390 text: text_style,
14391 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14392 syntax: cx.theme().syntax().clone(),
14393 status: cx.theme().status().clone(),
14394 inlay_hints_style: make_inlay_hints_style(cx),
14395 inline_completion_styles: make_suggestion_styles(cx),
14396 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14397 },
14398 )
14399 }
14400}
14401
14402impl ViewInputHandler for Editor {
14403 fn text_for_range(
14404 &mut self,
14405 range_utf16: Range<usize>,
14406 adjusted_range: &mut Option<Range<usize>>,
14407 cx: &mut ViewContext<Self>,
14408 ) -> Option<String> {
14409 let snapshot = self.buffer.read(cx).read(cx);
14410 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14411 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14412 if (start.0..end.0) != range_utf16 {
14413 adjusted_range.replace(start.0..end.0);
14414 }
14415 Some(snapshot.text_for_range(start..end).collect())
14416 }
14417
14418 fn selected_text_range(
14419 &mut self,
14420 ignore_disabled_input: bool,
14421 cx: &mut ViewContext<Self>,
14422 ) -> Option<UTF16Selection> {
14423 // Prevent the IME menu from appearing when holding down an alphabetic key
14424 // while input is disabled.
14425 if !ignore_disabled_input && !self.input_enabled {
14426 return None;
14427 }
14428
14429 let selection = self.selections.newest::<OffsetUtf16>(cx);
14430 let range = selection.range();
14431
14432 Some(UTF16Selection {
14433 range: range.start.0..range.end.0,
14434 reversed: selection.reversed,
14435 })
14436 }
14437
14438 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14439 let snapshot = self.buffer.read(cx).read(cx);
14440 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14441 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14442 }
14443
14444 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14445 self.clear_highlights::<InputComposition>(cx);
14446 self.ime_transaction.take();
14447 }
14448
14449 fn replace_text_in_range(
14450 &mut self,
14451 range_utf16: Option<Range<usize>>,
14452 text: &str,
14453 cx: &mut ViewContext<Self>,
14454 ) {
14455 if !self.input_enabled {
14456 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14457 return;
14458 }
14459
14460 self.transact(cx, |this, cx| {
14461 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14462 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14463 Some(this.selection_replacement_ranges(range_utf16, cx))
14464 } else {
14465 this.marked_text_ranges(cx)
14466 };
14467
14468 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14469 let newest_selection_id = this.selections.newest_anchor().id;
14470 this.selections
14471 .all::<OffsetUtf16>(cx)
14472 .iter()
14473 .zip(ranges_to_replace.iter())
14474 .find_map(|(selection, range)| {
14475 if selection.id == newest_selection_id {
14476 Some(
14477 (range.start.0 as isize - selection.head().0 as isize)
14478 ..(range.end.0 as isize - selection.head().0 as isize),
14479 )
14480 } else {
14481 None
14482 }
14483 })
14484 });
14485
14486 cx.emit(EditorEvent::InputHandled {
14487 utf16_range_to_replace: range_to_replace,
14488 text: text.into(),
14489 });
14490
14491 if let Some(new_selected_ranges) = new_selected_ranges {
14492 this.change_selections(None, cx, |selections| {
14493 selections.select_ranges(new_selected_ranges)
14494 });
14495 this.backspace(&Default::default(), cx);
14496 }
14497
14498 this.handle_input(text, cx);
14499 });
14500
14501 if let Some(transaction) = self.ime_transaction {
14502 self.buffer.update(cx, |buffer, cx| {
14503 buffer.group_until_transaction(transaction, cx);
14504 });
14505 }
14506
14507 self.unmark_text(cx);
14508 }
14509
14510 fn replace_and_mark_text_in_range(
14511 &mut self,
14512 range_utf16: Option<Range<usize>>,
14513 text: &str,
14514 new_selected_range_utf16: Option<Range<usize>>,
14515 cx: &mut ViewContext<Self>,
14516 ) {
14517 if !self.input_enabled {
14518 return;
14519 }
14520
14521 let transaction = self.transact(cx, |this, cx| {
14522 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14523 let snapshot = this.buffer.read(cx).read(cx);
14524 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14525 for marked_range in &mut marked_ranges {
14526 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14527 marked_range.start.0 += relative_range_utf16.start;
14528 marked_range.start =
14529 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14530 marked_range.end =
14531 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14532 }
14533 }
14534 Some(marked_ranges)
14535 } else if let Some(range_utf16) = range_utf16 {
14536 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14537 Some(this.selection_replacement_ranges(range_utf16, cx))
14538 } else {
14539 None
14540 };
14541
14542 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14543 let newest_selection_id = this.selections.newest_anchor().id;
14544 this.selections
14545 .all::<OffsetUtf16>(cx)
14546 .iter()
14547 .zip(ranges_to_replace.iter())
14548 .find_map(|(selection, range)| {
14549 if selection.id == newest_selection_id {
14550 Some(
14551 (range.start.0 as isize - selection.head().0 as isize)
14552 ..(range.end.0 as isize - selection.head().0 as isize),
14553 )
14554 } else {
14555 None
14556 }
14557 })
14558 });
14559
14560 cx.emit(EditorEvent::InputHandled {
14561 utf16_range_to_replace: range_to_replace,
14562 text: text.into(),
14563 });
14564
14565 if let Some(ranges) = ranges_to_replace {
14566 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14567 }
14568
14569 let marked_ranges = {
14570 let snapshot = this.buffer.read(cx).read(cx);
14571 this.selections
14572 .disjoint_anchors()
14573 .iter()
14574 .map(|selection| {
14575 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14576 })
14577 .collect::<Vec<_>>()
14578 };
14579
14580 if text.is_empty() {
14581 this.unmark_text(cx);
14582 } else {
14583 this.highlight_text::<InputComposition>(
14584 marked_ranges.clone(),
14585 HighlightStyle {
14586 underline: Some(UnderlineStyle {
14587 thickness: px(1.),
14588 color: None,
14589 wavy: false,
14590 }),
14591 ..Default::default()
14592 },
14593 cx,
14594 );
14595 }
14596
14597 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14598 let use_autoclose = this.use_autoclose;
14599 let use_auto_surround = this.use_auto_surround;
14600 this.set_use_autoclose(false);
14601 this.set_use_auto_surround(false);
14602 this.handle_input(text, cx);
14603 this.set_use_autoclose(use_autoclose);
14604 this.set_use_auto_surround(use_auto_surround);
14605
14606 if let Some(new_selected_range) = new_selected_range_utf16 {
14607 let snapshot = this.buffer.read(cx).read(cx);
14608 let new_selected_ranges = marked_ranges
14609 .into_iter()
14610 .map(|marked_range| {
14611 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14612 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14613 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14614 snapshot.clip_offset_utf16(new_start, Bias::Left)
14615 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14616 })
14617 .collect::<Vec<_>>();
14618
14619 drop(snapshot);
14620 this.change_selections(None, cx, |selections| {
14621 selections.select_ranges(new_selected_ranges)
14622 });
14623 }
14624 });
14625
14626 self.ime_transaction = self.ime_transaction.or(transaction);
14627 if let Some(transaction) = self.ime_transaction {
14628 self.buffer.update(cx, |buffer, cx| {
14629 buffer.group_until_transaction(transaction, cx);
14630 });
14631 }
14632
14633 if self.text_highlights::<InputComposition>(cx).is_none() {
14634 self.ime_transaction.take();
14635 }
14636 }
14637
14638 fn bounds_for_range(
14639 &mut self,
14640 range_utf16: Range<usize>,
14641 element_bounds: gpui::Bounds<Pixels>,
14642 cx: &mut ViewContext<Self>,
14643 ) -> Option<gpui::Bounds<Pixels>> {
14644 let text_layout_details = self.text_layout_details(cx);
14645 let gpui::Point {
14646 x: em_width,
14647 y: line_height,
14648 } = self.character_size(cx);
14649
14650 let snapshot = self.snapshot(cx);
14651 let scroll_position = snapshot.scroll_position();
14652 let scroll_left = scroll_position.x * em_width;
14653
14654 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14655 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14656 + self.gutter_dimensions.width
14657 + self.gutter_dimensions.margin;
14658 let y = line_height * (start.row().as_f32() - scroll_position.y);
14659
14660 Some(Bounds {
14661 origin: element_bounds.origin + point(x, y),
14662 size: size(em_width, line_height),
14663 })
14664 }
14665}
14666
14667trait SelectionExt {
14668 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14669 fn spanned_rows(
14670 &self,
14671 include_end_if_at_line_start: bool,
14672 map: &DisplaySnapshot,
14673 ) -> Range<MultiBufferRow>;
14674}
14675
14676impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14677 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14678 let start = self
14679 .start
14680 .to_point(&map.buffer_snapshot)
14681 .to_display_point(map);
14682 let end = self
14683 .end
14684 .to_point(&map.buffer_snapshot)
14685 .to_display_point(map);
14686 if self.reversed {
14687 end..start
14688 } else {
14689 start..end
14690 }
14691 }
14692
14693 fn spanned_rows(
14694 &self,
14695 include_end_if_at_line_start: bool,
14696 map: &DisplaySnapshot,
14697 ) -> Range<MultiBufferRow> {
14698 let start = self.start.to_point(&map.buffer_snapshot);
14699 let mut end = self.end.to_point(&map.buffer_snapshot);
14700 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14701 end.row -= 1;
14702 }
14703
14704 let buffer_start = map.prev_line_boundary(start).0;
14705 let buffer_end = map.next_line_boundary(end).0;
14706 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14707 }
14708}
14709
14710impl<T: InvalidationRegion> InvalidationStack<T> {
14711 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14712 where
14713 S: Clone + ToOffset,
14714 {
14715 while let Some(region) = self.last() {
14716 let all_selections_inside_invalidation_ranges =
14717 if selections.len() == region.ranges().len() {
14718 selections
14719 .iter()
14720 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14721 .all(|(selection, invalidation_range)| {
14722 let head = selection.head().to_offset(buffer);
14723 invalidation_range.start <= head && invalidation_range.end >= head
14724 })
14725 } else {
14726 false
14727 };
14728
14729 if all_selections_inside_invalidation_ranges {
14730 break;
14731 } else {
14732 self.pop();
14733 }
14734 }
14735 }
14736}
14737
14738impl<T> Default for InvalidationStack<T> {
14739 fn default() -> Self {
14740 Self(Default::default())
14741 }
14742}
14743
14744impl<T> Deref for InvalidationStack<T> {
14745 type Target = Vec<T>;
14746
14747 fn deref(&self) -> &Self::Target {
14748 &self.0
14749 }
14750}
14751
14752impl<T> DerefMut for InvalidationStack<T> {
14753 fn deref_mut(&mut self) -> &mut Self::Target {
14754 &mut self.0
14755 }
14756}
14757
14758impl InvalidationRegion for SnippetState {
14759 fn ranges(&self) -> &[Range<Anchor>] {
14760 &self.ranges[self.active_index]
14761 }
14762}
14763
14764pub fn diagnostic_block_renderer(
14765 diagnostic: Diagnostic,
14766 max_message_rows: Option<u8>,
14767 allow_closing: bool,
14768 _is_valid: bool,
14769) -> RenderBlock {
14770 let (text_without_backticks, code_ranges) =
14771 highlight_diagnostic_message(&diagnostic, max_message_rows);
14772
14773 Arc::new(move |cx: &mut BlockContext| {
14774 let group_id: SharedString = cx.block_id.to_string().into();
14775
14776 let mut text_style = cx.text_style().clone();
14777 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14778 let theme_settings = ThemeSettings::get_global(cx);
14779 text_style.font_family = theme_settings.buffer_font.family.clone();
14780 text_style.font_style = theme_settings.buffer_font.style;
14781 text_style.font_features = theme_settings.buffer_font.features.clone();
14782 text_style.font_weight = theme_settings.buffer_font.weight;
14783
14784 let multi_line_diagnostic = diagnostic.message.contains('\n');
14785
14786 let buttons = |diagnostic: &Diagnostic| {
14787 if multi_line_diagnostic {
14788 v_flex()
14789 } else {
14790 h_flex()
14791 }
14792 .when(allow_closing, |div| {
14793 div.children(diagnostic.is_primary.then(|| {
14794 IconButton::new("close-block", IconName::XCircle)
14795 .icon_color(Color::Muted)
14796 .size(ButtonSize::Compact)
14797 .style(ButtonStyle::Transparent)
14798 .visible_on_hover(group_id.clone())
14799 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14800 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14801 }))
14802 })
14803 .child(
14804 IconButton::new("copy-block", IconName::Copy)
14805 .icon_color(Color::Muted)
14806 .size(ButtonSize::Compact)
14807 .style(ButtonStyle::Transparent)
14808 .visible_on_hover(group_id.clone())
14809 .on_click({
14810 let message = diagnostic.message.clone();
14811 move |_click, cx| {
14812 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14813 }
14814 })
14815 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14816 )
14817 };
14818
14819 let icon_size = buttons(&diagnostic)
14820 .into_any_element()
14821 .layout_as_root(AvailableSpace::min_size(), cx);
14822
14823 h_flex()
14824 .id(cx.block_id)
14825 .group(group_id.clone())
14826 .relative()
14827 .size_full()
14828 .block_mouse_down()
14829 .pl(cx.gutter_dimensions.width)
14830 .w(cx.max_width - cx.gutter_dimensions.full_width())
14831 .child(
14832 div()
14833 .flex()
14834 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14835 .flex_shrink(),
14836 )
14837 .child(buttons(&diagnostic))
14838 .child(div().flex().flex_shrink_0().child(
14839 StyledText::new(text_without_backticks.clone()).with_highlights(
14840 &text_style,
14841 code_ranges.iter().map(|range| {
14842 (
14843 range.clone(),
14844 HighlightStyle {
14845 font_weight: Some(FontWeight::BOLD),
14846 ..Default::default()
14847 },
14848 )
14849 }),
14850 ),
14851 ))
14852 .into_any_element()
14853 })
14854}
14855
14856fn inline_completion_edit_text(
14857 editor_snapshot: &EditorSnapshot,
14858 edits: &Vec<(Range<Anchor>, String)>,
14859 include_deletions: bool,
14860 cx: &WindowContext,
14861) -> InlineCompletionText {
14862 let edit_start = edits
14863 .first()
14864 .unwrap()
14865 .0
14866 .start
14867 .to_display_point(editor_snapshot);
14868
14869 let mut text = String::new();
14870 let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14871 let mut highlights = Vec::new();
14872 for (old_range, new_text) in edits {
14873 let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14874 text.extend(
14875 editor_snapshot
14876 .buffer_snapshot
14877 .chunks(offset..old_offset_range.start, false)
14878 .map(|chunk| chunk.text),
14879 );
14880 offset = old_offset_range.end;
14881
14882 let start = text.len();
14883 let color = if include_deletions && new_text.is_empty() {
14884 text.extend(
14885 editor_snapshot
14886 .buffer_snapshot
14887 .chunks(old_offset_range.start..offset, false)
14888 .map(|chunk| chunk.text),
14889 );
14890 cx.theme().status().deleted_background
14891 } else {
14892 text.push_str(new_text);
14893 cx.theme().status().created_background
14894 };
14895 let end = text.len();
14896
14897 highlights.push((
14898 start..end,
14899 HighlightStyle {
14900 background_color: Some(color),
14901 ..Default::default()
14902 },
14903 ));
14904 }
14905
14906 let edit_end = edits
14907 .last()
14908 .unwrap()
14909 .0
14910 .end
14911 .to_display_point(editor_snapshot);
14912 let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14913 .to_offset(editor_snapshot, Bias::Right);
14914 text.extend(
14915 editor_snapshot
14916 .buffer_snapshot
14917 .chunks(offset..end_of_line, false)
14918 .map(|chunk| chunk.text),
14919 );
14920
14921 InlineCompletionText::Edit {
14922 text: text.into(),
14923 highlights,
14924 }
14925}
14926
14927pub fn highlight_diagnostic_message(
14928 diagnostic: &Diagnostic,
14929 mut max_message_rows: Option<u8>,
14930) -> (SharedString, Vec<Range<usize>>) {
14931 let mut text_without_backticks = String::new();
14932 let mut code_ranges = Vec::new();
14933
14934 if let Some(source) = &diagnostic.source {
14935 text_without_backticks.push_str(source);
14936 code_ranges.push(0..source.len());
14937 text_without_backticks.push_str(": ");
14938 }
14939
14940 let mut prev_offset = 0;
14941 let mut in_code_block = false;
14942 let has_row_limit = max_message_rows.is_some();
14943 let mut newline_indices = diagnostic
14944 .message
14945 .match_indices('\n')
14946 .filter(|_| has_row_limit)
14947 .map(|(ix, _)| ix)
14948 .fuse()
14949 .peekable();
14950
14951 for (quote_ix, _) in diagnostic
14952 .message
14953 .match_indices('`')
14954 .chain([(diagnostic.message.len(), "")])
14955 {
14956 let mut first_newline_ix = None;
14957 let mut last_newline_ix = None;
14958 while let Some(newline_ix) = newline_indices.peek() {
14959 if *newline_ix < quote_ix {
14960 if first_newline_ix.is_none() {
14961 first_newline_ix = Some(*newline_ix);
14962 }
14963 last_newline_ix = Some(*newline_ix);
14964
14965 if let Some(rows_left) = &mut max_message_rows {
14966 if *rows_left == 0 {
14967 break;
14968 } else {
14969 *rows_left -= 1;
14970 }
14971 }
14972 let _ = newline_indices.next();
14973 } else {
14974 break;
14975 }
14976 }
14977 let prev_len = text_without_backticks.len();
14978 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14979 text_without_backticks.push_str(new_text);
14980 if in_code_block {
14981 code_ranges.push(prev_len..text_without_backticks.len());
14982 }
14983 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14984 in_code_block = !in_code_block;
14985 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14986 text_without_backticks.push_str("...");
14987 break;
14988 }
14989 }
14990
14991 (text_without_backticks.into(), code_ranges)
14992}
14993
14994fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14995 match severity {
14996 DiagnosticSeverity::ERROR => colors.error,
14997 DiagnosticSeverity::WARNING => colors.warning,
14998 DiagnosticSeverity::INFORMATION => colors.info,
14999 DiagnosticSeverity::HINT => colors.info,
15000 _ => colors.ignored,
15001 }
15002}
15003
15004pub fn styled_runs_for_code_label<'a>(
15005 label: &'a CodeLabel,
15006 syntax_theme: &'a theme::SyntaxTheme,
15007) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15008 let fade_out = HighlightStyle {
15009 fade_out: Some(0.35),
15010 ..Default::default()
15011 };
15012
15013 let mut prev_end = label.filter_range.end;
15014 label
15015 .runs
15016 .iter()
15017 .enumerate()
15018 .flat_map(move |(ix, (range, highlight_id))| {
15019 let style = if let Some(style) = highlight_id.style(syntax_theme) {
15020 style
15021 } else {
15022 return Default::default();
15023 };
15024 let mut muted_style = style;
15025 muted_style.highlight(fade_out);
15026
15027 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15028 if range.start >= label.filter_range.end {
15029 if range.start > prev_end {
15030 runs.push((prev_end..range.start, fade_out));
15031 }
15032 runs.push((range.clone(), muted_style));
15033 } else if range.end <= label.filter_range.end {
15034 runs.push((range.clone(), style));
15035 } else {
15036 runs.push((range.start..label.filter_range.end, style));
15037 runs.push((label.filter_range.end..range.end, muted_style));
15038 }
15039 prev_end = cmp::max(prev_end, range.end);
15040
15041 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15042 runs.push((prev_end..label.text.len(), fade_out));
15043 }
15044
15045 runs
15046 })
15047}
15048
15049pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15050 let mut prev_index = 0;
15051 let mut prev_codepoint: Option<char> = None;
15052 text.char_indices()
15053 .chain([(text.len(), '\0')])
15054 .filter_map(move |(index, codepoint)| {
15055 let prev_codepoint = prev_codepoint.replace(codepoint)?;
15056 let is_boundary = index == text.len()
15057 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15058 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15059 if is_boundary {
15060 let chunk = &text[prev_index..index];
15061 prev_index = index;
15062 Some(chunk)
15063 } else {
15064 None
15065 }
15066 })
15067}
15068
15069pub trait RangeToAnchorExt: Sized {
15070 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15071
15072 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15073 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15074 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15075 }
15076}
15077
15078impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15079 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15080 let start_offset = self.start.to_offset(snapshot);
15081 let end_offset = self.end.to_offset(snapshot);
15082 if start_offset == end_offset {
15083 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15084 } else {
15085 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15086 }
15087 }
15088}
15089
15090pub trait RowExt {
15091 fn as_f32(&self) -> f32;
15092
15093 fn next_row(&self) -> Self;
15094
15095 fn previous_row(&self) -> Self;
15096
15097 fn minus(&self, other: Self) -> u32;
15098}
15099
15100impl RowExt for DisplayRow {
15101 fn as_f32(&self) -> f32 {
15102 self.0 as f32
15103 }
15104
15105 fn next_row(&self) -> Self {
15106 Self(self.0 + 1)
15107 }
15108
15109 fn previous_row(&self) -> Self {
15110 Self(self.0.saturating_sub(1))
15111 }
15112
15113 fn minus(&self, other: Self) -> u32 {
15114 self.0 - other.0
15115 }
15116}
15117
15118impl RowExt for MultiBufferRow {
15119 fn as_f32(&self) -> f32 {
15120 self.0 as f32
15121 }
15122
15123 fn next_row(&self) -> Self {
15124 Self(self.0 + 1)
15125 }
15126
15127 fn previous_row(&self) -> Self {
15128 Self(self.0.saturating_sub(1))
15129 }
15130
15131 fn minus(&self, other: Self) -> u32 {
15132 self.0 - other.0
15133 }
15134}
15135
15136trait RowRangeExt {
15137 type Row;
15138
15139 fn len(&self) -> usize;
15140
15141 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15142}
15143
15144impl RowRangeExt for Range<MultiBufferRow> {
15145 type Row = MultiBufferRow;
15146
15147 fn len(&self) -> usize {
15148 (self.end.0 - self.start.0) as usize
15149 }
15150
15151 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15152 (self.start.0..self.end.0).map(MultiBufferRow)
15153 }
15154}
15155
15156impl RowRangeExt for Range<DisplayRow> {
15157 type Row = DisplayRow;
15158
15159 fn len(&self) -> usize {
15160 (self.end.0 - self.start.0) as usize
15161 }
15162
15163 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15164 (self.start.0..self.end.0).map(DisplayRow)
15165 }
15166}
15167
15168fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15169 if hunk.diff_base_byte_range.is_empty() {
15170 DiffHunkStatus::Added
15171 } else if hunk.row_range.is_empty() {
15172 DiffHunkStatus::Removed
15173 } else {
15174 DiffHunkStatus::Modified
15175 }
15176}
15177
15178/// If select range has more than one line, we
15179/// just point the cursor to range.start.
15180fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15181 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15182 range
15183 } else {
15184 range.start..range.start
15185 }
15186}
15187
15188pub struct KillRing(ClipboardItem);
15189impl Global for KillRing {}
15190
15191const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);