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 indent_guides;
29mod inlay_hint_cache;
30pub mod items;
31mod linked_editing_ranges;
32mod lsp_ext;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod proposed_changes_editor;
37mod rust_analyzer_ext;
38pub mod scroll;
39mod selections_collection;
40pub mod tasks;
41
42#[cfg(test)]
43mod editor_tests;
44#[cfg(test)]
45mod inline_completion_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50use ::git::diff::DiffHunkStatus;
51pub(crate) use actions::*;
52pub use actions::{OpenExcerpts, OpenExcerptsSplit};
53use aho_corasick::AhoCorasick;
54use anyhow::{anyhow, Context as _, Result};
55use blink_manager::BlinkManager;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{
63 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
64};
65pub use editor_settings_controls::*;
66use element::LineWithInvisibles;
67pub use element::{
68 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
69};
70use futures::{future, FutureExt};
71use fuzzy::StringMatchCandidate;
72use zed_predict_tos::ZedPredictTos;
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, App,
81 AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context,
82 DispatchPhase, ElementId, Entity, EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent,
83 Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext,
84 MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText,
85 Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
86 UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
87};
88use highlight_matching_bracket::refresh_matching_bracket_highlights;
89use hover_popover::{hide_hover, HoverState};
90use indent_guides::ActiveIndentGuidesState;
91use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
92pub use inline_completion::Direction;
93use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
94pub use items::MAX_TAB_TITLE_LEN;
95use itertools::Itertools;
96use language::{
97 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
98 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
99 CursorShape, Diagnostic, Documentation, EditPreview, HighlightedEdits, IndentKind, IndentSize,
100 Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject, TransactionId,
101 TreeSitterOptions,
102};
103use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
104use linked_editing_ranges::refresh_linked_ranges;
105use mouse_context_menu::MouseContextMenu;
106pub use proposed_changes_editor::{
107 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
108};
109use similar::{ChangeTag, TextDiff};
110use std::iter::Peekable;
111use task::{ResolvedTask, TaskTemplate, TaskVariables};
112
113use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
114pub use lsp::CompletionContext;
115use lsp::{
116 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
117 LanguageServerId, LanguageServerName,
118};
119
120use language::BufferSnapshot;
121use movement::TextLayoutDetails;
122pub use multi_buffer::{
123 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
124 ToOffset, ToPoint,
125};
126use multi_buffer::{
127 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
128};
129use project::{
130 lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
131 project_settings::{GitGutterSetting, ProjectSettings},
132 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
133 LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
134};
135use rand::prelude::*;
136use rpc::{proto::*, ErrorExt};
137use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
138use selections_collection::{
139 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
140};
141use serde::{Deserialize, Serialize};
142use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
143use smallvec::SmallVec;
144use snippet::Snippet;
145use std::{
146 any::TypeId,
147 borrow::Cow,
148 cell::RefCell,
149 cmp::{self, Ordering, Reverse},
150 mem,
151 num::NonZeroU32,
152 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
153 path::{Path, PathBuf},
154 rc::Rc,
155 sync::Arc,
156 time::{Duration, Instant},
157};
158pub use sum_tree::Bias;
159use sum_tree::TreeMap;
160use text::{BufferId, OffsetUtf16, Rope};
161use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
162use ui::{
163 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
164 Tooltip,
165};
166use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
167use workspace::item::{ItemHandle, PreviewTabsSettings};
168use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
169use workspace::{
170 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
171};
172use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
173
174use crate::hover_links::{find_url, find_url_from_range};
175use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
176
177pub const FILE_HEADER_HEIGHT: u32 = 2;
178pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
179pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
180pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
181const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
182const MAX_LINE_LEN: usize = 1024;
183const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
184const MAX_SELECTION_HISTORY_LEN: usize = 1024;
185pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
186#[doc(hidden)]
187pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
188
189pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
190pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
191
192pub fn render_parsed_markdown(
193 element_id: impl Into<ElementId>,
194 parsed: &language::ParsedMarkdown,
195 editor_style: &EditorStyle,
196 workspace: Option<WeakEntity<Workspace>>,
197 cx: &mut App,
198) -> InteractiveText {
199 let code_span_background_color = cx
200 .theme()
201 .colors()
202 .editor_document_highlight_read_background;
203
204 let highlights = gpui::combine_highlights(
205 parsed.highlights.iter().filter_map(|(range, highlight)| {
206 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
207 Some((range.clone(), highlight))
208 }),
209 parsed
210 .regions
211 .iter()
212 .zip(&parsed.region_ranges)
213 .filter_map(|(region, range)| {
214 if region.code {
215 Some((
216 range.clone(),
217 HighlightStyle {
218 background_color: Some(code_span_background_color),
219 ..Default::default()
220 },
221 ))
222 } else {
223 None
224 }
225 }),
226 );
227
228 let mut links = Vec::new();
229 let mut link_ranges = Vec::new();
230 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
231 if let Some(link) = region.link.clone() {
232 links.push(link);
233 link_ranges.push(range.clone());
234 }
235 }
236
237 InteractiveText::new(
238 element_id,
239 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
240 )
241 .on_click(
242 link_ranges,
243 move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
244 markdown::Link::Web { url } => cx.open_url(url),
245 markdown::Link::Path { path } => {
246 if let Some(workspace) = &workspace {
247 _ = workspace.update(cx, |workspace, cx| {
248 workspace
249 .open_abs_path(path.clone(), false, window, cx)
250 .detach();
251 });
252 }
253 }
254 },
255 )
256}
257
258#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
259pub enum InlayId {
260 InlineCompletion(usize),
261 Hint(usize),
262}
263
264impl InlayId {
265 fn id(&self) -> usize {
266 match self {
267 Self::InlineCompletion(id) => *id,
268 Self::Hint(id) => *id,
269 }
270 }
271}
272
273enum DocumentHighlightRead {}
274enum DocumentHighlightWrite {}
275enum InputComposition {}
276
277#[derive(Debug, Copy, Clone, PartialEq, Eq)]
278pub enum Navigated {
279 Yes,
280 No,
281}
282
283impl Navigated {
284 pub fn from_bool(yes: bool) -> Navigated {
285 if yes {
286 Navigated::Yes
287 } else {
288 Navigated::No
289 }
290 }
291}
292
293pub fn init_settings(cx: &mut App) {
294 EditorSettings::register(cx);
295}
296
297pub fn init(cx: &mut App) {
298 init_settings(cx);
299
300 workspace::register_project_item::<Editor>(cx);
301 workspace::FollowableViewRegistry::register::<Editor>(cx);
302 workspace::register_serializable_item::<Editor>(cx);
303
304 cx.observe_new(
305 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
306 workspace.register_action(Editor::new_file);
307 workspace.register_action(Editor::new_file_vertical);
308 workspace.register_action(Editor::new_file_horizontal);
309 },
310 )
311 .detach();
312
313 cx.on_action(move |_: &workspace::NewFile, cx| {
314 let app_state = workspace::AppState::global(cx);
315 if let Some(app_state) = app_state.upgrade() {
316 workspace::open_new(
317 Default::default(),
318 app_state,
319 cx,
320 |workspace, window, cx| {
321 Editor::new_file(workspace, &Default::default(), window, cx)
322 },
323 )
324 .detach();
325 }
326 });
327 cx.on_action(move |_: &workspace::NewWindow, cx| {
328 let app_state = workspace::AppState::global(cx);
329 if let Some(app_state) = app_state.upgrade() {
330 workspace::open_new(
331 Default::default(),
332 app_state,
333 cx,
334 |workspace, window, cx| {
335 Editor::new_file(workspace, &Default::default(), window, cx)
336 },
337 )
338 .detach();
339 }
340 });
341 git::project_diff::init(cx);
342}
343
344pub struct SearchWithinRange;
345
346trait InvalidationRegion {
347 fn ranges(&self) -> &[Range<Anchor>];
348}
349
350#[derive(Clone, Debug, PartialEq)]
351pub enum SelectPhase {
352 Begin {
353 position: DisplayPoint,
354 add: bool,
355 click_count: usize,
356 },
357 BeginColumnar {
358 position: DisplayPoint,
359 reset: bool,
360 goal_column: u32,
361 },
362 Extend {
363 position: DisplayPoint,
364 click_count: usize,
365 },
366 Update {
367 position: DisplayPoint,
368 goal_column: u32,
369 scroll_delta: gpui::Point<f32>,
370 },
371 End,
372}
373
374#[derive(Clone, Debug)]
375pub enum SelectMode {
376 Character,
377 Word(Range<Anchor>),
378 Line(Range<Anchor>),
379 All,
380}
381
382#[derive(Copy, Clone, PartialEq, Eq, Debug)]
383pub enum EditorMode {
384 SingleLine { auto_width: bool },
385 AutoHeight { max_lines: usize },
386 Full,
387}
388
389#[derive(Copy, Clone, Debug)]
390pub enum SoftWrap {
391 /// Prefer not to wrap at all.
392 ///
393 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
394 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
395 GitDiff,
396 /// Prefer a single line generally, unless an overly long line is encountered.
397 None,
398 /// Soft wrap lines that exceed the editor width.
399 EditorWidth,
400 /// Soft wrap lines at the preferred line length.
401 Column(u32),
402 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
403 Bounded(u32),
404}
405
406#[derive(Clone)]
407pub struct EditorStyle {
408 pub background: Hsla,
409 pub local_player: PlayerColor,
410 pub text: TextStyle,
411 pub scrollbar_width: Pixels,
412 pub syntax: Arc<SyntaxTheme>,
413 pub status: StatusColors,
414 pub inlay_hints_style: HighlightStyle,
415 pub inline_completion_styles: InlineCompletionStyles,
416 pub unnecessary_code_fade: f32,
417}
418
419impl Default for EditorStyle {
420 fn default() -> Self {
421 Self {
422 background: Hsla::default(),
423 local_player: PlayerColor::default(),
424 text: TextStyle::default(),
425 scrollbar_width: Pixels::default(),
426 syntax: Default::default(),
427 // HACK: Status colors don't have a real default.
428 // We should look into removing the status colors from the editor
429 // style and retrieve them directly from the theme.
430 status: StatusColors::dark(),
431 inlay_hints_style: HighlightStyle::default(),
432 inline_completion_styles: InlineCompletionStyles {
433 insertion: HighlightStyle::default(),
434 whitespace: HighlightStyle::default(),
435 },
436 unnecessary_code_fade: Default::default(),
437 }
438 }
439}
440
441pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
442 let show_background = language_settings::language_settings(None, None, cx)
443 .inlay_hints
444 .show_background;
445
446 HighlightStyle {
447 color: Some(cx.theme().status().hint),
448 background_color: show_background.then(|| cx.theme().status().hint_background),
449 ..HighlightStyle::default()
450 }
451}
452
453pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
454 InlineCompletionStyles {
455 insertion: HighlightStyle {
456 color: Some(cx.theme().status().predictive),
457 ..HighlightStyle::default()
458 },
459 whitespace: HighlightStyle {
460 background_color: Some(cx.theme().status().created_background),
461 ..HighlightStyle::default()
462 },
463 }
464}
465
466type CompletionId = usize;
467
468#[derive(Debug, Clone)]
469enum InlineCompletionMenuHint {
470 Loading,
471 Loaded { text: InlineCompletionText },
472 PendingTermsAcceptance,
473 None,
474}
475
476impl InlineCompletionMenuHint {
477 pub fn label(&self) -> &'static str {
478 match self {
479 InlineCompletionMenuHint::Loading | InlineCompletionMenuHint::Loaded { .. } => {
480 "Edit Prediction"
481 }
482 InlineCompletionMenuHint::PendingTermsAcceptance => "Accept Terms of Service",
483 InlineCompletionMenuHint::None => "No Prediction",
484 }
485 }
486}
487
488#[derive(Clone, Debug)]
489enum InlineCompletionText {
490 Move(SharedString),
491 Edit(HighlightedEdits),
492}
493
494pub(crate) enum EditDisplayMode {
495 TabAccept,
496 DiffPopover,
497 Inline,
498}
499
500enum InlineCompletion {
501 Edit {
502 edits: Vec<(Range<Anchor>, String)>,
503 edit_preview: Option<EditPreview>,
504 display_mode: EditDisplayMode,
505 snapshot: BufferSnapshot,
506 },
507 Move(Anchor),
508}
509
510struct InlineCompletionState {
511 inlay_ids: Vec<InlayId>,
512 completion: InlineCompletion,
513 invalidation_range: Range<Anchor>,
514}
515
516enum InlineCompletionHighlight {}
517
518pub enum MenuInlineCompletionsPolicy {
519 Never,
520 ByProvider,
521}
522
523#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
524struct EditorActionId(usize);
525
526impl EditorActionId {
527 pub fn post_inc(&mut self) -> Self {
528 let answer = self.0;
529
530 *self = Self(answer + 1);
531
532 Self(answer)
533 }
534}
535
536// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
537// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
538
539type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
540type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
541
542#[derive(Default)]
543struct ScrollbarMarkerState {
544 scrollbar_size: Size<Pixels>,
545 dirty: bool,
546 markers: Arc<[PaintQuad]>,
547 pending_refresh: Option<Task<Result<()>>>,
548}
549
550impl ScrollbarMarkerState {
551 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
552 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
553 }
554}
555
556#[derive(Clone, Debug)]
557struct RunnableTasks {
558 templates: Vec<(TaskSourceKind, TaskTemplate)>,
559 offset: MultiBufferOffset,
560 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
561 column: u32,
562 // Values of all named captures, including those starting with '_'
563 extra_variables: HashMap<String, String>,
564 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
565 context_range: Range<BufferOffset>,
566}
567
568impl RunnableTasks {
569 fn resolve<'a>(
570 &'a self,
571 cx: &'a task::TaskContext,
572 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
573 self.templates.iter().filter_map(|(kind, template)| {
574 template
575 .resolve_task(&kind.to_id_base(), cx)
576 .map(|task| (kind.clone(), task))
577 })
578 }
579}
580
581#[derive(Clone)]
582struct ResolvedTasks {
583 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
584 position: Anchor,
585}
586#[derive(Copy, Clone, Debug)]
587struct MultiBufferOffset(usize);
588#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
589struct BufferOffset(usize);
590
591// Addons allow storing per-editor state in other crates (e.g. Vim)
592pub trait Addon: 'static {
593 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
594
595 fn to_any(&self) -> &dyn std::any::Any;
596}
597
598#[derive(Debug, Copy, Clone, PartialEq, Eq)]
599pub enum IsVimMode {
600 Yes,
601 No,
602}
603
604/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
605///
606/// See the [module level documentation](self) for more information.
607pub struct Editor {
608 focus_handle: FocusHandle,
609 last_focused_descendant: Option<WeakFocusHandle>,
610 /// The text buffer being edited
611 buffer: Entity<MultiBuffer>,
612 /// Map of how text in the buffer should be displayed.
613 /// Handles soft wraps, folds, fake inlay text insertions, etc.
614 pub display_map: Entity<DisplayMap>,
615 pub selections: SelectionsCollection,
616 pub scroll_manager: ScrollManager,
617 /// When inline assist editors are linked, they all render cursors because
618 /// typing enters text into each of them, even the ones that aren't focused.
619 pub(crate) show_cursor_when_unfocused: bool,
620 columnar_selection_tail: Option<Anchor>,
621 add_selections_state: Option<AddSelectionsState>,
622 select_next_state: Option<SelectNextState>,
623 select_prev_state: Option<SelectNextState>,
624 selection_history: SelectionHistory,
625 autoclose_regions: Vec<AutocloseRegion>,
626 snippet_stack: InvalidationStack<SnippetState>,
627 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
628 ime_transaction: Option<TransactionId>,
629 active_diagnostics: Option<ActiveDiagnosticGroup>,
630 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
631
632 project: Option<Entity<Project>>,
633 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
634 completion_provider: Option<Box<dyn CompletionProvider>>,
635 collaboration_hub: Option<Box<dyn CollaborationHub>>,
636 blink_manager: Entity<BlinkManager>,
637 show_cursor_names: bool,
638 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
639 pub show_local_selections: bool,
640 mode: EditorMode,
641 show_breadcrumbs: bool,
642 show_gutter: bool,
643 show_scrollbars: bool,
644 show_line_numbers: Option<bool>,
645 use_relative_line_numbers: Option<bool>,
646 show_git_diff_gutter: Option<bool>,
647 show_code_actions: Option<bool>,
648 show_runnables: Option<bool>,
649 show_wrap_guides: Option<bool>,
650 show_indent_guides: Option<bool>,
651 placeholder_text: Option<Arc<str>>,
652 highlight_order: usize,
653 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
654 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
655 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
656 scrollbar_marker_state: ScrollbarMarkerState,
657 active_indent_guides_state: ActiveIndentGuidesState,
658 nav_history: Option<ItemNavHistory>,
659 context_menu: RefCell<Option<CodeContextMenu>>,
660 mouse_context_menu: Option<MouseContextMenu>,
661 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
662 signature_help_state: SignatureHelpState,
663 auto_signature_help: Option<bool>,
664 find_all_references_task_sources: Vec<Anchor>,
665 next_completion_id: CompletionId,
666 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
667 code_actions_task: Option<Task<Result<()>>>,
668 document_highlights_task: Option<Task<()>>,
669 linked_editing_range_task: Option<Task<Option<()>>>,
670 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
671 pending_rename: Option<RenameState>,
672 searchable: bool,
673 cursor_shape: CursorShape,
674 current_line_highlight: Option<CurrentLineHighlight>,
675 collapse_matches: bool,
676 autoindent_mode: Option<AutoindentMode>,
677 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
678 input_enabled: bool,
679 use_modal_editing: bool,
680 read_only: bool,
681 leader_peer_id: Option<PeerId>,
682 remote_id: Option<ViewId>,
683 hover_state: HoverState,
684 gutter_hovered: bool,
685 hovered_link_state: Option<HoveredLinkState>,
686 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
687 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
688 active_inline_completion: Option<InlineCompletionState>,
689 // enable_inline_completions is a switch that Vim can use to disable
690 // inline completions based on its mode.
691 enable_inline_completions: bool,
692 show_inline_completions_override: Option<bool>,
693 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
694 inlay_hint_cache: InlayHintCache,
695 next_inlay_id: usize,
696 _subscriptions: Vec<Subscription>,
697 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
698 gutter_dimensions: GutterDimensions,
699 style: Option<EditorStyle>,
700 text_style_refinement: Option<TextStyleRefinement>,
701 next_editor_action_id: EditorActionId,
702 editor_actions:
703 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
704 use_autoclose: bool,
705 use_auto_surround: bool,
706 auto_replace_emoji_shortcode: bool,
707 show_git_blame_gutter: bool,
708 show_git_blame_inline: bool,
709 show_git_blame_inline_delay_task: Option<Task<()>>,
710 git_blame_inline_enabled: bool,
711 serialize_dirty_buffers: bool,
712 show_selection_menu: Option<bool>,
713 blame: Option<Entity<GitBlame>>,
714 blame_subscription: Option<Subscription>,
715 custom_context_menu: Option<
716 Box<
717 dyn 'static
718 + Fn(
719 &mut Self,
720 DisplayPoint,
721 &mut Window,
722 &mut Context<Self>,
723 ) -> Option<Entity<ui::ContextMenu>>,
724 >,
725 >,
726 last_bounds: Option<Bounds<Pixels>>,
727 expect_bounds_change: Option<Bounds<Pixels>>,
728 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
729 tasks_update_task: Option<Task<()>>,
730 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
731 breadcrumb_header: Option<String>,
732 focused_block: Option<FocusedBlock>,
733 next_scroll_position: NextScrollCursorCenterTopBottom,
734 addons: HashMap<TypeId, Box<dyn Addon>>,
735 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
736 selection_mark_mode: bool,
737 toggle_fold_multiple_buffers: Task<()>,
738 _scroll_cursor_center_top_bottom_task: Task<()>,
739}
740
741#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
742enum NextScrollCursorCenterTopBottom {
743 #[default]
744 Center,
745 Top,
746 Bottom,
747}
748
749impl NextScrollCursorCenterTopBottom {
750 fn next(&self) -> Self {
751 match self {
752 Self::Center => Self::Top,
753 Self::Top => Self::Bottom,
754 Self::Bottom => Self::Center,
755 }
756 }
757}
758
759#[derive(Clone)]
760pub struct EditorSnapshot {
761 pub mode: EditorMode,
762 show_gutter: bool,
763 show_line_numbers: Option<bool>,
764 show_git_diff_gutter: Option<bool>,
765 show_code_actions: Option<bool>,
766 show_runnables: Option<bool>,
767 git_blame_gutter_max_author_length: Option<usize>,
768 pub display_snapshot: DisplaySnapshot,
769 pub placeholder_text: Option<Arc<str>>,
770 is_focused: bool,
771 scroll_anchor: ScrollAnchor,
772 ongoing_scroll: OngoingScroll,
773 current_line_highlight: CurrentLineHighlight,
774 gutter_hovered: bool,
775}
776
777const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
778
779#[derive(Default, Debug, Clone, Copy)]
780pub struct GutterDimensions {
781 pub left_padding: Pixels,
782 pub right_padding: Pixels,
783 pub width: Pixels,
784 pub margin: Pixels,
785 pub git_blame_entries_width: Option<Pixels>,
786}
787
788impl GutterDimensions {
789 /// The full width of the space taken up by the gutter.
790 pub fn full_width(&self) -> Pixels {
791 self.margin + self.width
792 }
793
794 /// The width of the space reserved for the fold indicators,
795 /// use alongside 'justify_end' and `gutter_width` to
796 /// right align content with the line numbers
797 pub fn fold_area_width(&self) -> Pixels {
798 self.margin + self.right_padding
799 }
800}
801
802#[derive(Debug)]
803pub struct RemoteSelection {
804 pub replica_id: ReplicaId,
805 pub selection: Selection<Anchor>,
806 pub cursor_shape: CursorShape,
807 pub peer_id: PeerId,
808 pub line_mode: bool,
809 pub participant_index: Option<ParticipantIndex>,
810 pub user_name: Option<SharedString>,
811}
812
813#[derive(Clone, Debug)]
814struct SelectionHistoryEntry {
815 selections: Arc<[Selection<Anchor>]>,
816 select_next_state: Option<SelectNextState>,
817 select_prev_state: Option<SelectNextState>,
818 add_selections_state: Option<AddSelectionsState>,
819}
820
821enum SelectionHistoryMode {
822 Normal,
823 Undoing,
824 Redoing,
825}
826
827#[derive(Clone, PartialEq, Eq, Hash)]
828struct HoveredCursor {
829 replica_id: u16,
830 selection_id: usize,
831}
832
833impl Default for SelectionHistoryMode {
834 fn default() -> Self {
835 Self::Normal
836 }
837}
838
839#[derive(Default)]
840struct SelectionHistory {
841 #[allow(clippy::type_complexity)]
842 selections_by_transaction:
843 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
844 mode: SelectionHistoryMode,
845 undo_stack: VecDeque<SelectionHistoryEntry>,
846 redo_stack: VecDeque<SelectionHistoryEntry>,
847}
848
849impl SelectionHistory {
850 fn insert_transaction(
851 &mut self,
852 transaction_id: TransactionId,
853 selections: Arc<[Selection<Anchor>]>,
854 ) {
855 self.selections_by_transaction
856 .insert(transaction_id, (selections, None));
857 }
858
859 #[allow(clippy::type_complexity)]
860 fn transaction(
861 &self,
862 transaction_id: TransactionId,
863 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
864 self.selections_by_transaction.get(&transaction_id)
865 }
866
867 #[allow(clippy::type_complexity)]
868 fn transaction_mut(
869 &mut self,
870 transaction_id: TransactionId,
871 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
872 self.selections_by_transaction.get_mut(&transaction_id)
873 }
874
875 fn push(&mut self, entry: SelectionHistoryEntry) {
876 if !entry.selections.is_empty() {
877 match self.mode {
878 SelectionHistoryMode::Normal => {
879 self.push_undo(entry);
880 self.redo_stack.clear();
881 }
882 SelectionHistoryMode::Undoing => self.push_redo(entry),
883 SelectionHistoryMode::Redoing => self.push_undo(entry),
884 }
885 }
886 }
887
888 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
889 if self
890 .undo_stack
891 .back()
892 .map_or(true, |e| e.selections != entry.selections)
893 {
894 self.undo_stack.push_back(entry);
895 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
896 self.undo_stack.pop_front();
897 }
898 }
899 }
900
901 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
902 if self
903 .redo_stack
904 .back()
905 .map_or(true, |e| e.selections != entry.selections)
906 {
907 self.redo_stack.push_back(entry);
908 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
909 self.redo_stack.pop_front();
910 }
911 }
912 }
913}
914
915struct RowHighlight {
916 index: usize,
917 range: Range<Anchor>,
918 color: Hsla,
919 should_autoscroll: bool,
920}
921
922#[derive(Clone, Debug)]
923struct AddSelectionsState {
924 above: bool,
925 stack: Vec<usize>,
926}
927
928#[derive(Clone)]
929struct SelectNextState {
930 query: AhoCorasick,
931 wordwise: bool,
932 done: bool,
933}
934
935impl std::fmt::Debug for SelectNextState {
936 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
937 f.debug_struct(std::any::type_name::<Self>())
938 .field("wordwise", &self.wordwise)
939 .field("done", &self.done)
940 .finish()
941 }
942}
943
944#[derive(Debug)]
945struct AutocloseRegion {
946 selection_id: usize,
947 range: Range<Anchor>,
948 pair: BracketPair,
949}
950
951#[derive(Debug)]
952struct SnippetState {
953 ranges: Vec<Vec<Range<Anchor>>>,
954 active_index: usize,
955 choices: Vec<Option<Vec<String>>>,
956}
957
958#[doc(hidden)]
959pub struct RenameState {
960 pub range: Range<Anchor>,
961 pub old_name: Arc<str>,
962 pub editor: Entity<Editor>,
963 block_id: CustomBlockId,
964}
965
966struct InvalidationStack<T>(Vec<T>);
967
968struct RegisteredInlineCompletionProvider {
969 provider: Arc<dyn InlineCompletionProviderHandle>,
970 _subscription: Subscription,
971}
972
973#[derive(Debug)]
974struct ActiveDiagnosticGroup {
975 primary_range: Range<Anchor>,
976 primary_message: String,
977 group_id: usize,
978 blocks: HashMap<CustomBlockId, Diagnostic>,
979 is_valid: bool,
980}
981
982#[derive(Serialize, Deserialize, Clone, Debug)]
983pub struct ClipboardSelection {
984 pub len: usize,
985 pub is_entire_line: bool,
986 pub first_line_indent: u32,
987}
988
989#[derive(Debug)]
990pub(crate) struct NavigationData {
991 cursor_anchor: Anchor,
992 cursor_position: Point,
993 scroll_anchor: ScrollAnchor,
994 scroll_top_row: u32,
995}
996
997#[derive(Debug, Clone, Copy, PartialEq, Eq)]
998pub enum GotoDefinitionKind {
999 Symbol,
1000 Declaration,
1001 Type,
1002 Implementation,
1003}
1004
1005#[derive(Debug, Clone)]
1006enum InlayHintRefreshReason {
1007 Toggle(bool),
1008 SettingsChange(InlayHintSettings),
1009 NewLinesShown,
1010 BufferEdited(HashSet<Arc<Language>>),
1011 RefreshRequested,
1012 ExcerptsRemoved(Vec<ExcerptId>),
1013}
1014
1015impl InlayHintRefreshReason {
1016 fn description(&self) -> &'static str {
1017 match self {
1018 Self::Toggle(_) => "toggle",
1019 Self::SettingsChange(_) => "settings change",
1020 Self::NewLinesShown => "new lines shown",
1021 Self::BufferEdited(_) => "buffer edited",
1022 Self::RefreshRequested => "refresh requested",
1023 Self::ExcerptsRemoved(_) => "excerpts removed",
1024 }
1025 }
1026}
1027
1028pub enum FormatTarget {
1029 Buffers,
1030 Ranges(Vec<Range<MultiBufferPoint>>),
1031}
1032
1033pub(crate) struct FocusedBlock {
1034 id: BlockId,
1035 focus_handle: WeakFocusHandle,
1036}
1037
1038#[derive(Clone)]
1039enum JumpData {
1040 MultiBufferRow {
1041 row: MultiBufferRow,
1042 line_offset_from_top: u32,
1043 },
1044 MultiBufferPoint {
1045 excerpt_id: ExcerptId,
1046 position: Point,
1047 anchor: text::Anchor,
1048 line_offset_from_top: u32,
1049 },
1050}
1051
1052pub enum MultibufferSelectionMode {
1053 First,
1054 All,
1055}
1056
1057impl Editor {
1058 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1059 let buffer = cx.new(|cx| Buffer::local("", cx));
1060 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1061 Self::new(
1062 EditorMode::SingleLine { auto_width: false },
1063 buffer,
1064 None,
1065 false,
1066 window,
1067 cx,
1068 )
1069 }
1070
1071 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1072 let buffer = cx.new(|cx| Buffer::local("", cx));
1073 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1074 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1075 }
1076
1077 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1078 let buffer = cx.new(|cx| Buffer::local("", cx));
1079 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1080 Self::new(
1081 EditorMode::SingleLine { auto_width: true },
1082 buffer,
1083 None,
1084 false,
1085 window,
1086 cx,
1087 )
1088 }
1089
1090 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1091 let buffer = cx.new(|cx| Buffer::local("", cx));
1092 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1093 Self::new(
1094 EditorMode::AutoHeight { max_lines },
1095 buffer,
1096 None,
1097 false,
1098 window,
1099 cx,
1100 )
1101 }
1102
1103 pub fn for_buffer(
1104 buffer: Entity<Buffer>,
1105 project: Option<Entity<Project>>,
1106 window: &mut Window,
1107 cx: &mut Context<Self>,
1108 ) -> Self {
1109 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1110 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1111 }
1112
1113 pub fn for_multibuffer(
1114 buffer: Entity<MultiBuffer>,
1115 project: Option<Entity<Project>>,
1116 show_excerpt_controls: bool,
1117 window: &mut Window,
1118 cx: &mut Context<Self>,
1119 ) -> Self {
1120 Self::new(
1121 EditorMode::Full,
1122 buffer,
1123 project,
1124 show_excerpt_controls,
1125 window,
1126 cx,
1127 )
1128 }
1129
1130 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1131 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1132 let mut clone = Self::new(
1133 self.mode,
1134 self.buffer.clone(),
1135 self.project.clone(),
1136 show_excerpt_controls,
1137 window,
1138 cx,
1139 );
1140 self.display_map.update(cx, |display_map, cx| {
1141 let snapshot = display_map.snapshot(cx);
1142 clone.display_map.update(cx, |display_map, cx| {
1143 display_map.set_state(&snapshot, cx);
1144 });
1145 });
1146 clone.selections.clone_state(&self.selections);
1147 clone.scroll_manager.clone_state(&self.scroll_manager);
1148 clone.searchable = self.searchable;
1149 clone
1150 }
1151
1152 pub fn new(
1153 mode: EditorMode,
1154 buffer: Entity<MultiBuffer>,
1155 project: Option<Entity<Project>>,
1156 show_excerpt_controls: bool,
1157 window: &mut Window,
1158 cx: &mut Context<Self>,
1159 ) -> Self {
1160 let style = window.text_style();
1161 let font_size = style.font_size.to_pixels(window.rem_size());
1162 let editor = cx.entity().downgrade();
1163 let fold_placeholder = FoldPlaceholder {
1164 constrain_width: true,
1165 render: Arc::new(move |fold_id, fold_range, _, cx| {
1166 let editor = editor.clone();
1167 div()
1168 .id(fold_id)
1169 .bg(cx.theme().colors().ghost_element_background)
1170 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1171 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1172 .rounded_sm()
1173 .size_full()
1174 .cursor_pointer()
1175 .child("⋯")
1176 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1177 .on_click(move |_, _window, cx| {
1178 editor
1179 .update(cx, |editor, cx| {
1180 editor.unfold_ranges(
1181 &[fold_range.start..fold_range.end],
1182 true,
1183 false,
1184 cx,
1185 );
1186 cx.stop_propagation();
1187 })
1188 .ok();
1189 })
1190 .into_any()
1191 }),
1192 merge_adjacent: true,
1193 ..Default::default()
1194 };
1195 let display_map = cx.new(|cx| {
1196 DisplayMap::new(
1197 buffer.clone(),
1198 style.font(),
1199 font_size,
1200 None,
1201 show_excerpt_controls,
1202 FILE_HEADER_HEIGHT,
1203 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1204 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1205 fold_placeholder,
1206 cx,
1207 )
1208 });
1209
1210 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1211
1212 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1213
1214 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1215 .then(|| language_settings::SoftWrap::None);
1216
1217 let mut project_subscriptions = Vec::new();
1218 if mode == EditorMode::Full {
1219 if let Some(project) = project.as_ref() {
1220 if buffer.read(cx).is_singleton() {
1221 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1222 cx.emit(EditorEvent::TitleChanged);
1223 }));
1224 }
1225 project_subscriptions.push(cx.subscribe_in(
1226 project,
1227 window,
1228 |editor, _, event, window, cx| {
1229 if let project::Event::RefreshInlayHints = event {
1230 editor
1231 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1232 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1233 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1234 let focus_handle = editor.focus_handle(cx);
1235 if focus_handle.is_focused(window) {
1236 let snapshot = buffer.read(cx).snapshot();
1237 for (range, snippet) in snippet_edits {
1238 let editor_range =
1239 language::range_from_lsp(*range).to_offset(&snapshot);
1240 editor
1241 .insert_snippet(
1242 &[editor_range],
1243 snippet.clone(),
1244 window,
1245 cx,
1246 )
1247 .ok();
1248 }
1249 }
1250 }
1251 }
1252 },
1253 ));
1254 if let Some(task_inventory) = project
1255 .read(cx)
1256 .task_store()
1257 .read(cx)
1258 .task_inventory()
1259 .cloned()
1260 {
1261 project_subscriptions.push(cx.observe_in(
1262 &task_inventory,
1263 window,
1264 |editor, _, window, cx| {
1265 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1266 },
1267 ));
1268 }
1269 }
1270 }
1271
1272 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1273
1274 let inlay_hint_settings =
1275 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1276 let focus_handle = cx.focus_handle();
1277 cx.on_focus(&focus_handle, window, Self::handle_focus)
1278 .detach();
1279 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1280 .detach();
1281 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1282 .detach();
1283 cx.on_blur(&focus_handle, window, Self::handle_blur)
1284 .detach();
1285
1286 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1287 Some(false)
1288 } else {
1289 None
1290 };
1291
1292 let mut code_action_providers = Vec::new();
1293 if let Some(project) = project.clone() {
1294 get_unstaged_changes_for_buffers(
1295 &project,
1296 buffer.read(cx).all_buffers(),
1297 buffer.clone(),
1298 cx,
1299 );
1300 code_action_providers.push(Rc::new(project) as Rc<_>);
1301 }
1302
1303 let mut this = Self {
1304 focus_handle,
1305 show_cursor_when_unfocused: false,
1306 last_focused_descendant: None,
1307 buffer: buffer.clone(),
1308 display_map: display_map.clone(),
1309 selections,
1310 scroll_manager: ScrollManager::new(cx),
1311 columnar_selection_tail: None,
1312 add_selections_state: None,
1313 select_next_state: None,
1314 select_prev_state: None,
1315 selection_history: Default::default(),
1316 autoclose_regions: Default::default(),
1317 snippet_stack: Default::default(),
1318 select_larger_syntax_node_stack: Vec::new(),
1319 ime_transaction: Default::default(),
1320 active_diagnostics: None,
1321 soft_wrap_mode_override,
1322 completion_provider: project.clone().map(|project| Box::new(project) as _),
1323 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1324 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1325 project,
1326 blink_manager: blink_manager.clone(),
1327 show_local_selections: true,
1328 show_scrollbars: true,
1329 mode,
1330 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1331 show_gutter: mode == EditorMode::Full,
1332 show_line_numbers: None,
1333 use_relative_line_numbers: None,
1334 show_git_diff_gutter: None,
1335 show_code_actions: None,
1336 show_runnables: None,
1337 show_wrap_guides: None,
1338 show_indent_guides,
1339 placeholder_text: None,
1340 highlight_order: 0,
1341 highlighted_rows: HashMap::default(),
1342 background_highlights: Default::default(),
1343 gutter_highlights: TreeMap::default(),
1344 scrollbar_marker_state: ScrollbarMarkerState::default(),
1345 active_indent_guides_state: ActiveIndentGuidesState::default(),
1346 nav_history: None,
1347 context_menu: RefCell::new(None),
1348 mouse_context_menu: None,
1349 completion_tasks: Default::default(),
1350 signature_help_state: SignatureHelpState::default(),
1351 auto_signature_help: None,
1352 find_all_references_task_sources: Vec::new(),
1353 next_completion_id: 0,
1354 next_inlay_id: 0,
1355 code_action_providers,
1356 available_code_actions: Default::default(),
1357 code_actions_task: Default::default(),
1358 document_highlights_task: Default::default(),
1359 linked_editing_range_task: Default::default(),
1360 pending_rename: Default::default(),
1361 searchable: true,
1362 cursor_shape: EditorSettings::get_global(cx)
1363 .cursor_shape
1364 .unwrap_or_default(),
1365 current_line_highlight: None,
1366 autoindent_mode: Some(AutoindentMode::EachLine),
1367 collapse_matches: false,
1368 workspace: None,
1369 input_enabled: true,
1370 use_modal_editing: mode == EditorMode::Full,
1371 read_only: false,
1372 use_autoclose: true,
1373 use_auto_surround: true,
1374 auto_replace_emoji_shortcode: false,
1375 leader_peer_id: None,
1376 remote_id: None,
1377 hover_state: Default::default(),
1378 hovered_link_state: Default::default(),
1379 inline_completion_provider: None,
1380 active_inline_completion: None,
1381 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1382
1383 gutter_hovered: false,
1384 pixel_position_of_newest_cursor: None,
1385 last_bounds: None,
1386 expect_bounds_change: None,
1387 gutter_dimensions: GutterDimensions::default(),
1388 style: None,
1389 show_cursor_names: false,
1390 hovered_cursors: Default::default(),
1391 next_editor_action_id: EditorActionId::default(),
1392 editor_actions: Rc::default(),
1393 show_inline_completions_override: None,
1394 enable_inline_completions: true,
1395 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1396 custom_context_menu: None,
1397 show_git_blame_gutter: false,
1398 show_git_blame_inline: false,
1399 show_selection_menu: None,
1400 show_git_blame_inline_delay_task: None,
1401 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1402 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1403 .session
1404 .restore_unsaved_buffers,
1405 blame: None,
1406 blame_subscription: None,
1407 tasks: Default::default(),
1408 _subscriptions: vec![
1409 cx.observe(&buffer, Self::on_buffer_changed),
1410 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1411 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1412 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1413 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1414 cx.observe_window_activation(window, |editor, window, cx| {
1415 let active = window.is_window_active();
1416 editor.blink_manager.update(cx, |blink_manager, cx| {
1417 if active {
1418 blink_manager.enable(cx);
1419 } else {
1420 blink_manager.disable(cx);
1421 }
1422 });
1423 }),
1424 ],
1425 tasks_update_task: None,
1426 linked_edit_ranges: Default::default(),
1427 previous_search_ranges: None,
1428 breadcrumb_header: None,
1429 focused_block: None,
1430 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1431 addons: HashMap::default(),
1432 registered_buffers: HashMap::default(),
1433 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1434 selection_mark_mode: false,
1435 toggle_fold_multiple_buffers: Task::ready(()),
1436 text_style_refinement: None,
1437 };
1438 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1439 this._subscriptions.extend(project_subscriptions);
1440
1441 this.end_selection(window, cx);
1442 this.scroll_manager.show_scrollbar(window, cx);
1443
1444 if mode == EditorMode::Full {
1445 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1446 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1447
1448 if this.git_blame_inline_enabled {
1449 this.git_blame_inline_enabled = true;
1450 this.start_git_blame_inline(false, window, cx);
1451 }
1452
1453 if let Some(buffer) = buffer.read(cx).as_singleton() {
1454 if let Some(project) = this.project.as_ref() {
1455 let lsp_store = project.read(cx).lsp_store();
1456 let handle = lsp_store.update(cx, |lsp_store, cx| {
1457 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1458 });
1459 this.registered_buffers
1460 .insert(buffer.read(cx).remote_id(), handle);
1461 }
1462 }
1463 }
1464
1465 this.report_editor_event("Editor Opened", None, cx);
1466 this
1467 }
1468
1469 pub fn mouse_menu_is_focused(&self, window: &mut Window, cx: &mut App) -> bool {
1470 self.mouse_context_menu
1471 .as_ref()
1472 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1473 }
1474
1475 fn key_context(&self, window: &mut Window, cx: &mut Context<Self>) -> KeyContext {
1476 let mut key_context = KeyContext::new_with_defaults();
1477 key_context.add("Editor");
1478 let mode = match self.mode {
1479 EditorMode::SingleLine { .. } => "single_line",
1480 EditorMode::AutoHeight { .. } => "auto_height",
1481 EditorMode::Full => "full",
1482 };
1483
1484 if EditorSettings::jupyter_enabled(cx) {
1485 key_context.add("jupyter");
1486 }
1487
1488 key_context.set("mode", mode);
1489 if self.pending_rename.is_some() {
1490 key_context.add("renaming");
1491 }
1492 match self.context_menu.borrow().as_ref() {
1493 Some(CodeContextMenu::Completions(_)) => {
1494 key_context.add("menu");
1495 key_context.add("showing_completions")
1496 }
1497 Some(CodeContextMenu::CodeActions(_)) => {
1498 key_context.add("menu");
1499 key_context.add("showing_code_actions")
1500 }
1501 None => {}
1502 }
1503
1504 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1505 if !self.focus_handle(cx).contains_focused(window, cx)
1506 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1507 {
1508 for addon in self.addons.values() {
1509 addon.extend_key_context(&mut key_context, cx)
1510 }
1511 }
1512
1513 if let Some(extension) = self
1514 .buffer
1515 .read(cx)
1516 .as_singleton()
1517 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1518 {
1519 key_context.set("extension", extension.to_string());
1520 }
1521
1522 if self.has_active_inline_completion() {
1523 key_context.add("copilot_suggestion");
1524 key_context.add("inline_completion");
1525 }
1526
1527 if self.selection_mark_mode {
1528 key_context.add("selection_mode");
1529 }
1530
1531 key_context
1532 }
1533
1534 pub fn new_file(
1535 workspace: &mut Workspace,
1536 _: &workspace::NewFile,
1537 window: &mut Window,
1538 cx: &mut Context<Workspace>,
1539 ) {
1540 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1541 "Failed to create buffer",
1542 window,
1543 cx,
1544 |e, _, _| match e.error_code() {
1545 ErrorCode::RemoteUpgradeRequired => Some(format!(
1546 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1547 e.error_tag("required").unwrap_or("the latest version")
1548 )),
1549 _ => None,
1550 },
1551 );
1552 }
1553
1554 pub fn new_in_workspace(
1555 workspace: &mut Workspace,
1556 window: &mut Window,
1557 cx: &mut Context<Workspace>,
1558 ) -> Task<Result<Entity<Editor>>> {
1559 let project = workspace.project().clone();
1560 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1561
1562 cx.spawn_in(window, |workspace, mut cx| async move {
1563 let buffer = create.await?;
1564 workspace.update_in(&mut cx, |workspace, window, cx| {
1565 let editor =
1566 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1567 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1568 editor
1569 })
1570 })
1571 }
1572
1573 fn new_file_vertical(
1574 workspace: &mut Workspace,
1575 _: &workspace::NewFileSplitVertical,
1576 window: &mut Window,
1577 cx: &mut Context<Workspace>,
1578 ) {
1579 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1580 }
1581
1582 fn new_file_horizontal(
1583 workspace: &mut Workspace,
1584 _: &workspace::NewFileSplitHorizontal,
1585 window: &mut Window,
1586 cx: &mut Context<Workspace>,
1587 ) {
1588 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1589 }
1590
1591 fn new_file_in_direction(
1592 workspace: &mut Workspace,
1593 direction: SplitDirection,
1594 window: &mut Window,
1595 cx: &mut Context<Workspace>,
1596 ) {
1597 let project = workspace.project().clone();
1598 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1599
1600 cx.spawn_in(window, |workspace, mut cx| async move {
1601 let buffer = create.await?;
1602 workspace.update_in(&mut cx, move |workspace, window, cx| {
1603 workspace.split_item(
1604 direction,
1605 Box::new(
1606 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1607 ),
1608 window,
1609 cx,
1610 )
1611 })?;
1612 anyhow::Ok(())
1613 })
1614 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1615 match e.error_code() {
1616 ErrorCode::RemoteUpgradeRequired => Some(format!(
1617 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1618 e.error_tag("required").unwrap_or("the latest version")
1619 )),
1620 _ => None,
1621 }
1622 });
1623 }
1624
1625 pub fn leader_peer_id(&self) -> Option<PeerId> {
1626 self.leader_peer_id
1627 }
1628
1629 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1630 &self.buffer
1631 }
1632
1633 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1634 self.workspace.as_ref()?.0.upgrade()
1635 }
1636
1637 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1638 self.buffer().read(cx).title(cx)
1639 }
1640
1641 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1642 let git_blame_gutter_max_author_length = self
1643 .render_git_blame_gutter(cx)
1644 .then(|| {
1645 if let Some(blame) = self.blame.as_ref() {
1646 let max_author_length =
1647 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1648 Some(max_author_length)
1649 } else {
1650 None
1651 }
1652 })
1653 .flatten();
1654
1655 EditorSnapshot {
1656 mode: self.mode,
1657 show_gutter: self.show_gutter,
1658 show_line_numbers: self.show_line_numbers,
1659 show_git_diff_gutter: self.show_git_diff_gutter,
1660 show_code_actions: self.show_code_actions,
1661 show_runnables: self.show_runnables,
1662 git_blame_gutter_max_author_length,
1663 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1664 scroll_anchor: self.scroll_manager.anchor(),
1665 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1666 placeholder_text: self.placeholder_text.clone(),
1667 is_focused: self.focus_handle.is_focused(window),
1668 current_line_highlight: self
1669 .current_line_highlight
1670 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1671 gutter_hovered: self.gutter_hovered,
1672 }
1673 }
1674
1675 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1676 self.buffer.read(cx).language_at(point, cx)
1677 }
1678
1679 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1680 self.buffer.read(cx).read(cx).file_at(point).cloned()
1681 }
1682
1683 pub fn active_excerpt(
1684 &self,
1685 cx: &App,
1686 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1687 self.buffer
1688 .read(cx)
1689 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1690 }
1691
1692 pub fn mode(&self) -> EditorMode {
1693 self.mode
1694 }
1695
1696 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1697 self.collaboration_hub.as_deref()
1698 }
1699
1700 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1701 self.collaboration_hub = Some(hub);
1702 }
1703
1704 pub fn set_custom_context_menu(
1705 &mut self,
1706 f: impl 'static
1707 + Fn(
1708 &mut Self,
1709 DisplayPoint,
1710 &mut Window,
1711 &mut Context<Self>,
1712 ) -> Option<Entity<ui::ContextMenu>>,
1713 ) {
1714 self.custom_context_menu = Some(Box::new(f))
1715 }
1716
1717 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1718 self.completion_provider = provider;
1719 }
1720
1721 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1722 self.semantics_provider.clone()
1723 }
1724
1725 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1726 self.semantics_provider = provider;
1727 }
1728
1729 pub fn set_inline_completion_provider<T>(
1730 &mut self,
1731 provider: Option<Entity<T>>,
1732 window: &mut Window,
1733 cx: &mut Context<Self>,
1734 ) where
1735 T: InlineCompletionProvider,
1736 {
1737 self.inline_completion_provider =
1738 provider.map(|provider| RegisteredInlineCompletionProvider {
1739 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1740 if this.focus_handle.is_focused(window) {
1741 this.update_visible_inline_completion(window, cx);
1742 }
1743 }),
1744 provider: Arc::new(provider),
1745 });
1746 self.refresh_inline_completion(false, false, window, cx);
1747 }
1748
1749 pub fn placeholder_text(&self) -> Option<&str> {
1750 self.placeholder_text.as_deref()
1751 }
1752
1753 pub fn set_placeholder_text(
1754 &mut self,
1755 placeholder_text: impl Into<Arc<str>>,
1756 cx: &mut Context<Self>,
1757 ) {
1758 let placeholder_text = Some(placeholder_text.into());
1759 if self.placeholder_text != placeholder_text {
1760 self.placeholder_text = placeholder_text;
1761 cx.notify();
1762 }
1763 }
1764
1765 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1766 self.cursor_shape = cursor_shape;
1767
1768 // Disrupt blink for immediate user feedback that the cursor shape has changed
1769 self.blink_manager.update(cx, BlinkManager::show_cursor);
1770
1771 cx.notify();
1772 }
1773
1774 pub fn set_current_line_highlight(
1775 &mut self,
1776 current_line_highlight: Option<CurrentLineHighlight>,
1777 ) {
1778 self.current_line_highlight = current_line_highlight;
1779 }
1780
1781 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1782 self.collapse_matches = collapse_matches;
1783 }
1784
1785 pub fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1786 let buffers = self.buffer.read(cx).all_buffers();
1787 let Some(lsp_store) = self.lsp_store(cx) else {
1788 return;
1789 };
1790 lsp_store.update(cx, |lsp_store, cx| {
1791 for buffer in buffers {
1792 self.registered_buffers
1793 .entry(buffer.read(cx).remote_id())
1794 .or_insert_with(|| {
1795 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1796 });
1797 }
1798 })
1799 }
1800
1801 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1802 if self.collapse_matches {
1803 return range.start..range.start;
1804 }
1805 range.clone()
1806 }
1807
1808 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1809 if self.display_map.read(cx).clip_at_line_ends != clip {
1810 self.display_map
1811 .update(cx, |map, _| map.clip_at_line_ends = clip);
1812 }
1813 }
1814
1815 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1816 self.input_enabled = input_enabled;
1817 }
1818
1819 pub fn set_inline_completions_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
1820 self.enable_inline_completions = enabled;
1821 if !self.enable_inline_completions {
1822 self.take_active_inline_completion(cx);
1823 cx.notify();
1824 }
1825 }
1826
1827 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1828 self.menu_inline_completions_policy = value;
1829 }
1830
1831 pub fn set_autoindent(&mut self, autoindent: bool) {
1832 if autoindent {
1833 self.autoindent_mode = Some(AutoindentMode::EachLine);
1834 } else {
1835 self.autoindent_mode = None;
1836 }
1837 }
1838
1839 pub fn read_only(&self, cx: &App) -> bool {
1840 self.read_only || self.buffer.read(cx).read_only()
1841 }
1842
1843 pub fn set_read_only(&mut self, read_only: bool) {
1844 self.read_only = read_only;
1845 }
1846
1847 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1848 self.use_autoclose = autoclose;
1849 }
1850
1851 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1852 self.use_auto_surround = auto_surround;
1853 }
1854
1855 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1856 self.auto_replace_emoji_shortcode = auto_replace;
1857 }
1858
1859 pub fn toggle_inline_completions(
1860 &mut self,
1861 _: &ToggleInlineCompletions,
1862 window: &mut Window,
1863 cx: &mut Context<Self>,
1864 ) {
1865 if self.show_inline_completions_override.is_some() {
1866 self.set_show_inline_completions(None, window, cx);
1867 } else {
1868 let cursor = self.selections.newest_anchor().head();
1869 if let Some((buffer, cursor_buffer_position)) =
1870 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1871 {
1872 let show_inline_completions =
1873 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
1874 self.set_show_inline_completions(Some(show_inline_completions), window, cx);
1875 }
1876 }
1877 }
1878
1879 pub fn set_show_inline_completions(
1880 &mut self,
1881 show_inline_completions: Option<bool>,
1882 window: &mut Window,
1883 cx: &mut Context<Self>,
1884 ) {
1885 self.show_inline_completions_override = show_inline_completions;
1886 self.refresh_inline_completion(false, true, window, cx);
1887 }
1888
1889 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
1890 let cursor = self.selections.newest_anchor().head();
1891 if let Some((buffer, buffer_position)) =
1892 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1893 {
1894 self.should_show_inline_completions(&buffer, buffer_position, cx)
1895 } else {
1896 false
1897 }
1898 }
1899
1900 fn should_show_inline_completions(
1901 &self,
1902 buffer: &Entity<Buffer>,
1903 buffer_position: language::Anchor,
1904 cx: &App,
1905 ) -> bool {
1906 if !self.snippet_stack.is_empty() {
1907 return false;
1908 }
1909
1910 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
1911 return false;
1912 }
1913
1914 if let Some(provider) = self.inline_completion_provider() {
1915 if let Some(show_inline_completions) = self.show_inline_completions_override {
1916 show_inline_completions
1917 } else {
1918 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
1919 }
1920 } else {
1921 false
1922 }
1923 }
1924
1925 fn inline_completions_disabled_in_scope(
1926 &self,
1927 buffer: &Entity<Buffer>,
1928 buffer_position: language::Anchor,
1929 cx: &App,
1930 ) -> bool {
1931 let snapshot = buffer.read(cx).snapshot();
1932 let settings = snapshot.settings_at(buffer_position, cx);
1933
1934 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1935 return false;
1936 };
1937
1938 scope.override_name().map_or(false, |scope_name| {
1939 settings
1940 .inline_completions_disabled_in
1941 .iter()
1942 .any(|s| s == scope_name)
1943 })
1944 }
1945
1946 pub fn set_use_modal_editing(&mut self, to: bool) {
1947 self.use_modal_editing = to;
1948 }
1949
1950 pub fn use_modal_editing(&self) -> bool {
1951 self.use_modal_editing
1952 }
1953
1954 fn selections_did_change(
1955 &mut self,
1956 local: bool,
1957 old_cursor_position: &Anchor,
1958 show_completions: bool,
1959 window: &mut Window,
1960 cx: &mut Context<Self>,
1961 ) {
1962 window.invalidate_character_coordinates();
1963
1964 // Copy selections to primary selection buffer
1965 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1966 if local {
1967 let selections = self.selections.all::<usize>(cx);
1968 let buffer_handle = self.buffer.read(cx).read(cx);
1969
1970 let mut text = String::new();
1971 for (index, selection) in selections.iter().enumerate() {
1972 let text_for_selection = buffer_handle
1973 .text_for_range(selection.start..selection.end)
1974 .collect::<String>();
1975
1976 text.push_str(&text_for_selection);
1977 if index != selections.len() - 1 {
1978 text.push('\n');
1979 }
1980 }
1981
1982 if !text.is_empty() {
1983 cx.write_to_primary(ClipboardItem::new_string(text));
1984 }
1985 }
1986
1987 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
1988 self.buffer.update(cx, |buffer, cx| {
1989 buffer.set_active_selections(
1990 &self.selections.disjoint_anchors(),
1991 self.selections.line_mode,
1992 self.cursor_shape,
1993 cx,
1994 )
1995 });
1996 }
1997 let display_map = self
1998 .display_map
1999 .update(cx, |display_map, cx| display_map.snapshot(cx));
2000 let buffer = &display_map.buffer_snapshot;
2001 self.add_selections_state = None;
2002 self.select_next_state = None;
2003 self.select_prev_state = None;
2004 self.select_larger_syntax_node_stack.clear();
2005 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2006 self.snippet_stack
2007 .invalidate(&self.selections.disjoint_anchors(), buffer);
2008 self.take_rename(false, window, cx);
2009
2010 let new_cursor_position = self.selections.newest_anchor().head();
2011
2012 self.push_to_nav_history(
2013 *old_cursor_position,
2014 Some(new_cursor_position.to_point(buffer)),
2015 cx,
2016 );
2017
2018 if local {
2019 let new_cursor_position = self.selections.newest_anchor().head();
2020 let mut context_menu = self.context_menu.borrow_mut();
2021 let completion_menu = match context_menu.as_ref() {
2022 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2023 _ => {
2024 *context_menu = None;
2025 None
2026 }
2027 };
2028
2029 if let Some(completion_menu) = completion_menu {
2030 let cursor_position = new_cursor_position.to_offset(buffer);
2031 let (word_range, kind) =
2032 buffer.surrounding_word(completion_menu.initial_position, true);
2033 if kind == Some(CharKind::Word)
2034 && word_range.to_inclusive().contains(&cursor_position)
2035 {
2036 let mut completion_menu = completion_menu.clone();
2037 drop(context_menu);
2038
2039 let query = Self::completion_query(buffer, cursor_position);
2040 cx.spawn(move |this, mut cx| async move {
2041 completion_menu
2042 .filter(query.as_deref(), cx.background_executor().clone())
2043 .await;
2044
2045 this.update(&mut cx, |this, cx| {
2046 let mut context_menu = this.context_menu.borrow_mut();
2047 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2048 else {
2049 return;
2050 };
2051
2052 if menu.id > completion_menu.id {
2053 return;
2054 }
2055
2056 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2057 drop(context_menu);
2058 cx.notify();
2059 })
2060 })
2061 .detach();
2062
2063 if show_completions {
2064 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2065 }
2066 } else {
2067 drop(context_menu);
2068 self.hide_context_menu(window, cx);
2069 }
2070 } else {
2071 drop(context_menu);
2072 }
2073
2074 hide_hover(self, cx);
2075
2076 if old_cursor_position.to_display_point(&display_map).row()
2077 != new_cursor_position.to_display_point(&display_map).row()
2078 {
2079 self.available_code_actions.take();
2080 }
2081 self.refresh_code_actions(window, cx);
2082 self.refresh_document_highlights(cx);
2083 refresh_matching_bracket_highlights(self, window, cx);
2084 self.update_visible_inline_completion(window, cx);
2085 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2086 if self.git_blame_inline_enabled {
2087 self.start_inline_blame_timer(window, cx);
2088 }
2089 }
2090
2091 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2092 cx.emit(EditorEvent::SelectionsChanged { local });
2093
2094 if self.selections.disjoint_anchors().len() == 1 {
2095 cx.emit(SearchEvent::ActiveMatchChanged)
2096 }
2097 cx.notify();
2098 }
2099
2100 pub fn change_selections<R>(
2101 &mut self,
2102 autoscroll: Option<Autoscroll>,
2103 window: &mut Window,
2104 cx: &mut Context<Self>,
2105 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2106 ) -> R {
2107 self.change_selections_inner(autoscroll, true, window, cx, change)
2108 }
2109
2110 pub fn change_selections_inner<R>(
2111 &mut self,
2112 autoscroll: Option<Autoscroll>,
2113 request_completions: bool,
2114 window: &mut Window,
2115 cx: &mut Context<Self>,
2116 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2117 ) -> R {
2118 let old_cursor_position = self.selections.newest_anchor().head();
2119 self.push_to_selection_history();
2120
2121 let (changed, result) = self.selections.change_with(cx, change);
2122
2123 if changed {
2124 if let Some(autoscroll) = autoscroll {
2125 self.request_autoscroll(autoscroll, cx);
2126 }
2127 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2128
2129 if self.should_open_signature_help_automatically(
2130 &old_cursor_position,
2131 self.signature_help_state.backspace_pressed(),
2132 cx,
2133 ) {
2134 self.show_signature_help(&ShowSignatureHelp, window, cx);
2135 }
2136 self.signature_help_state.set_backspace_pressed(false);
2137 }
2138
2139 result
2140 }
2141
2142 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2143 where
2144 I: IntoIterator<Item = (Range<S>, T)>,
2145 S: ToOffset,
2146 T: Into<Arc<str>>,
2147 {
2148 if self.read_only(cx) {
2149 return;
2150 }
2151
2152 self.buffer
2153 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2154 }
2155
2156 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2157 where
2158 I: IntoIterator<Item = (Range<S>, T)>,
2159 S: ToOffset,
2160 T: Into<Arc<str>>,
2161 {
2162 if self.read_only(cx) {
2163 return;
2164 }
2165
2166 self.buffer.update(cx, |buffer, cx| {
2167 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2168 });
2169 }
2170
2171 pub fn edit_with_block_indent<I, S, T>(
2172 &mut self,
2173 edits: I,
2174 original_indent_columns: Vec<u32>,
2175 cx: &mut Context<Self>,
2176 ) where
2177 I: IntoIterator<Item = (Range<S>, T)>,
2178 S: ToOffset,
2179 T: Into<Arc<str>>,
2180 {
2181 if self.read_only(cx) {
2182 return;
2183 }
2184
2185 self.buffer.update(cx, |buffer, cx| {
2186 buffer.edit(
2187 edits,
2188 Some(AutoindentMode::Block {
2189 original_indent_columns,
2190 }),
2191 cx,
2192 )
2193 });
2194 }
2195
2196 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2197 self.hide_context_menu(window, cx);
2198
2199 match phase {
2200 SelectPhase::Begin {
2201 position,
2202 add,
2203 click_count,
2204 } => self.begin_selection(position, add, click_count, window, cx),
2205 SelectPhase::BeginColumnar {
2206 position,
2207 goal_column,
2208 reset,
2209 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2210 SelectPhase::Extend {
2211 position,
2212 click_count,
2213 } => self.extend_selection(position, click_count, window, cx),
2214 SelectPhase::Update {
2215 position,
2216 goal_column,
2217 scroll_delta,
2218 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2219 SelectPhase::End => self.end_selection(window, cx),
2220 }
2221 }
2222
2223 fn extend_selection(
2224 &mut self,
2225 position: DisplayPoint,
2226 click_count: usize,
2227 window: &mut Window,
2228 cx: &mut Context<Self>,
2229 ) {
2230 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2231 let tail = self.selections.newest::<usize>(cx).tail();
2232 self.begin_selection(position, false, click_count, window, cx);
2233
2234 let position = position.to_offset(&display_map, Bias::Left);
2235 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2236
2237 let mut pending_selection = self
2238 .selections
2239 .pending_anchor()
2240 .expect("extend_selection not called with pending selection");
2241 if position >= tail {
2242 pending_selection.start = tail_anchor;
2243 } else {
2244 pending_selection.end = tail_anchor;
2245 pending_selection.reversed = true;
2246 }
2247
2248 let mut pending_mode = self.selections.pending_mode().unwrap();
2249 match &mut pending_mode {
2250 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2251 _ => {}
2252 }
2253
2254 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2255 s.set_pending(pending_selection, pending_mode)
2256 });
2257 }
2258
2259 fn begin_selection(
2260 &mut self,
2261 position: DisplayPoint,
2262 add: bool,
2263 click_count: usize,
2264 window: &mut Window,
2265 cx: &mut Context<Self>,
2266 ) {
2267 if !self.focus_handle.is_focused(window) {
2268 self.last_focused_descendant = None;
2269 window.focus(&self.focus_handle);
2270 }
2271
2272 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2273 let buffer = &display_map.buffer_snapshot;
2274 let newest_selection = self.selections.newest_anchor().clone();
2275 let position = display_map.clip_point(position, Bias::Left);
2276
2277 let start;
2278 let end;
2279 let mode;
2280 let mut auto_scroll;
2281 match click_count {
2282 1 => {
2283 start = buffer.anchor_before(position.to_point(&display_map));
2284 end = start;
2285 mode = SelectMode::Character;
2286 auto_scroll = true;
2287 }
2288 2 => {
2289 let range = movement::surrounding_word(&display_map, position);
2290 start = buffer.anchor_before(range.start.to_point(&display_map));
2291 end = buffer.anchor_before(range.end.to_point(&display_map));
2292 mode = SelectMode::Word(start..end);
2293 auto_scroll = true;
2294 }
2295 3 => {
2296 let position = display_map
2297 .clip_point(position, Bias::Left)
2298 .to_point(&display_map);
2299 let line_start = display_map.prev_line_boundary(position).0;
2300 let next_line_start = buffer.clip_point(
2301 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2302 Bias::Left,
2303 );
2304 start = buffer.anchor_before(line_start);
2305 end = buffer.anchor_before(next_line_start);
2306 mode = SelectMode::Line(start..end);
2307 auto_scroll = true;
2308 }
2309 _ => {
2310 start = buffer.anchor_before(0);
2311 end = buffer.anchor_before(buffer.len());
2312 mode = SelectMode::All;
2313 auto_scroll = false;
2314 }
2315 }
2316 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2317
2318 let point_to_delete: Option<usize> = {
2319 let selected_points: Vec<Selection<Point>> =
2320 self.selections.disjoint_in_range(start..end, cx);
2321
2322 if !add || click_count > 1 {
2323 None
2324 } else if !selected_points.is_empty() {
2325 Some(selected_points[0].id)
2326 } else {
2327 let clicked_point_already_selected =
2328 self.selections.disjoint.iter().find(|selection| {
2329 selection.start.to_point(buffer) == start.to_point(buffer)
2330 || selection.end.to_point(buffer) == end.to_point(buffer)
2331 });
2332
2333 clicked_point_already_selected.map(|selection| selection.id)
2334 }
2335 };
2336
2337 let selections_count = self.selections.count();
2338
2339 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2340 if let Some(point_to_delete) = point_to_delete {
2341 s.delete(point_to_delete);
2342
2343 if selections_count == 1 {
2344 s.set_pending_anchor_range(start..end, mode);
2345 }
2346 } else {
2347 if !add {
2348 s.clear_disjoint();
2349 } else if click_count > 1 {
2350 s.delete(newest_selection.id)
2351 }
2352
2353 s.set_pending_anchor_range(start..end, mode);
2354 }
2355 });
2356 }
2357
2358 fn begin_columnar_selection(
2359 &mut self,
2360 position: DisplayPoint,
2361 goal_column: u32,
2362 reset: bool,
2363 window: &mut Window,
2364 cx: &mut Context<Self>,
2365 ) {
2366 if !self.focus_handle.is_focused(window) {
2367 self.last_focused_descendant = None;
2368 window.focus(&self.focus_handle);
2369 }
2370
2371 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2372
2373 if reset {
2374 let pointer_position = display_map
2375 .buffer_snapshot
2376 .anchor_before(position.to_point(&display_map));
2377
2378 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2379 s.clear_disjoint();
2380 s.set_pending_anchor_range(
2381 pointer_position..pointer_position,
2382 SelectMode::Character,
2383 );
2384 });
2385 }
2386
2387 let tail = self.selections.newest::<Point>(cx).tail();
2388 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2389
2390 if !reset {
2391 self.select_columns(
2392 tail.to_display_point(&display_map),
2393 position,
2394 goal_column,
2395 &display_map,
2396 window,
2397 cx,
2398 );
2399 }
2400 }
2401
2402 fn update_selection(
2403 &mut self,
2404 position: DisplayPoint,
2405 goal_column: u32,
2406 scroll_delta: gpui::Point<f32>,
2407 window: &mut Window,
2408 cx: &mut Context<Self>,
2409 ) {
2410 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2411
2412 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2413 let tail = tail.to_display_point(&display_map);
2414 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2415 } else if let Some(mut pending) = self.selections.pending_anchor() {
2416 let buffer = self.buffer.read(cx).snapshot(cx);
2417 let head;
2418 let tail;
2419 let mode = self.selections.pending_mode().unwrap();
2420 match &mode {
2421 SelectMode::Character => {
2422 head = position.to_point(&display_map);
2423 tail = pending.tail().to_point(&buffer);
2424 }
2425 SelectMode::Word(original_range) => {
2426 let original_display_range = original_range.start.to_display_point(&display_map)
2427 ..original_range.end.to_display_point(&display_map);
2428 let original_buffer_range = original_display_range.start.to_point(&display_map)
2429 ..original_display_range.end.to_point(&display_map);
2430 if movement::is_inside_word(&display_map, position)
2431 || original_display_range.contains(&position)
2432 {
2433 let word_range = movement::surrounding_word(&display_map, position);
2434 if word_range.start < original_display_range.start {
2435 head = word_range.start.to_point(&display_map);
2436 } else {
2437 head = word_range.end.to_point(&display_map);
2438 }
2439 } else {
2440 head = position.to_point(&display_map);
2441 }
2442
2443 if head <= original_buffer_range.start {
2444 tail = original_buffer_range.end;
2445 } else {
2446 tail = original_buffer_range.start;
2447 }
2448 }
2449 SelectMode::Line(original_range) => {
2450 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2451
2452 let position = display_map
2453 .clip_point(position, Bias::Left)
2454 .to_point(&display_map);
2455 let line_start = display_map.prev_line_boundary(position).0;
2456 let next_line_start = buffer.clip_point(
2457 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2458 Bias::Left,
2459 );
2460
2461 if line_start < original_range.start {
2462 head = line_start
2463 } else {
2464 head = next_line_start
2465 }
2466
2467 if head <= original_range.start {
2468 tail = original_range.end;
2469 } else {
2470 tail = original_range.start;
2471 }
2472 }
2473 SelectMode::All => {
2474 return;
2475 }
2476 };
2477
2478 if head < tail {
2479 pending.start = buffer.anchor_before(head);
2480 pending.end = buffer.anchor_before(tail);
2481 pending.reversed = true;
2482 } else {
2483 pending.start = buffer.anchor_before(tail);
2484 pending.end = buffer.anchor_before(head);
2485 pending.reversed = false;
2486 }
2487
2488 self.change_selections(None, window, cx, |s| {
2489 s.set_pending(pending, mode);
2490 });
2491 } else {
2492 log::error!("update_selection dispatched with no pending selection");
2493 return;
2494 }
2495
2496 self.apply_scroll_delta(scroll_delta, window, cx);
2497 cx.notify();
2498 }
2499
2500 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2501 self.columnar_selection_tail.take();
2502 if self.selections.pending_anchor().is_some() {
2503 let selections = self.selections.all::<usize>(cx);
2504 self.change_selections(None, window, cx, |s| {
2505 s.select(selections);
2506 s.clear_pending();
2507 });
2508 }
2509 }
2510
2511 fn select_columns(
2512 &mut self,
2513 tail: DisplayPoint,
2514 head: DisplayPoint,
2515 goal_column: u32,
2516 display_map: &DisplaySnapshot,
2517 window: &mut Window,
2518 cx: &mut Context<Self>,
2519 ) {
2520 let start_row = cmp::min(tail.row(), head.row());
2521 let end_row = cmp::max(tail.row(), head.row());
2522 let start_column = cmp::min(tail.column(), goal_column);
2523 let end_column = cmp::max(tail.column(), goal_column);
2524 let reversed = start_column < tail.column();
2525
2526 let selection_ranges = (start_row.0..=end_row.0)
2527 .map(DisplayRow)
2528 .filter_map(|row| {
2529 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2530 let start = display_map
2531 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2532 .to_point(display_map);
2533 let end = display_map
2534 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2535 .to_point(display_map);
2536 if reversed {
2537 Some(end..start)
2538 } else {
2539 Some(start..end)
2540 }
2541 } else {
2542 None
2543 }
2544 })
2545 .collect::<Vec<_>>();
2546
2547 self.change_selections(None, window, cx, |s| {
2548 s.select_ranges(selection_ranges);
2549 });
2550 cx.notify();
2551 }
2552
2553 pub fn has_pending_nonempty_selection(&self) -> bool {
2554 let pending_nonempty_selection = match self.selections.pending_anchor() {
2555 Some(Selection { start, end, .. }) => start != end,
2556 None => false,
2557 };
2558
2559 pending_nonempty_selection
2560 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2561 }
2562
2563 pub fn has_pending_selection(&self) -> bool {
2564 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2565 }
2566
2567 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2568 self.selection_mark_mode = false;
2569
2570 if self.clear_expanded_diff_hunks(cx) {
2571 cx.notify();
2572 return;
2573 }
2574 if self.dismiss_menus_and_popups(true, window, cx) {
2575 return;
2576 }
2577
2578 if self.mode == EditorMode::Full
2579 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2580 {
2581 return;
2582 }
2583
2584 cx.propagate();
2585 }
2586
2587 pub fn dismiss_menus_and_popups(
2588 &mut self,
2589 should_report_inline_completion_event: bool,
2590 window: &mut Window,
2591 cx: &mut Context<Self>,
2592 ) -> bool {
2593 if self.take_rename(false, window, cx).is_some() {
2594 return true;
2595 }
2596
2597 if hide_hover(self, cx) {
2598 return true;
2599 }
2600
2601 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2602 return true;
2603 }
2604
2605 if self.hide_context_menu(window, cx).is_some() {
2606 if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
2607 self.update_visible_inline_completion(window, cx);
2608 }
2609 return true;
2610 }
2611
2612 if self.mouse_context_menu.take().is_some() {
2613 return true;
2614 }
2615
2616 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2617 return true;
2618 }
2619
2620 if self.snippet_stack.pop().is_some() {
2621 return true;
2622 }
2623
2624 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2625 self.dismiss_diagnostics(cx);
2626 return true;
2627 }
2628
2629 false
2630 }
2631
2632 fn linked_editing_ranges_for(
2633 &self,
2634 selection: Range<text::Anchor>,
2635 cx: &App,
2636 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2637 if self.linked_edit_ranges.is_empty() {
2638 return None;
2639 }
2640 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2641 selection.end.buffer_id.and_then(|end_buffer_id| {
2642 if selection.start.buffer_id != Some(end_buffer_id) {
2643 return None;
2644 }
2645 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2646 let snapshot = buffer.read(cx).snapshot();
2647 self.linked_edit_ranges
2648 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2649 .map(|ranges| (ranges, snapshot, buffer))
2650 })?;
2651 use text::ToOffset as TO;
2652 // find offset from the start of current range to current cursor position
2653 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2654
2655 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2656 let start_difference = start_offset - start_byte_offset;
2657 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2658 let end_difference = end_offset - start_byte_offset;
2659 // Current range has associated linked ranges.
2660 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2661 for range in linked_ranges.iter() {
2662 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2663 let end_offset = start_offset + end_difference;
2664 let start_offset = start_offset + start_difference;
2665 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2666 continue;
2667 }
2668 if self.selections.disjoint_anchor_ranges().any(|s| {
2669 if s.start.buffer_id != selection.start.buffer_id
2670 || s.end.buffer_id != selection.end.buffer_id
2671 {
2672 return false;
2673 }
2674 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2675 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2676 }) {
2677 continue;
2678 }
2679 let start = buffer_snapshot.anchor_after(start_offset);
2680 let end = buffer_snapshot.anchor_after(end_offset);
2681 linked_edits
2682 .entry(buffer.clone())
2683 .or_default()
2684 .push(start..end);
2685 }
2686 Some(linked_edits)
2687 }
2688
2689 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2690 let text: Arc<str> = text.into();
2691
2692 if self.read_only(cx) {
2693 return;
2694 }
2695
2696 let selections = self.selections.all_adjusted(cx);
2697 let mut bracket_inserted = false;
2698 let mut edits = Vec::new();
2699 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2700 let mut new_selections = Vec::with_capacity(selections.len());
2701 let mut new_autoclose_regions = Vec::new();
2702 let snapshot = self.buffer.read(cx).read(cx);
2703
2704 for (selection, autoclose_region) in
2705 self.selections_with_autoclose_regions(selections, &snapshot)
2706 {
2707 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2708 // Determine if the inserted text matches the opening or closing
2709 // bracket of any of this language's bracket pairs.
2710 let mut bracket_pair = None;
2711 let mut is_bracket_pair_start = false;
2712 let mut is_bracket_pair_end = false;
2713 if !text.is_empty() {
2714 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2715 // and they are removing the character that triggered IME popup.
2716 for (pair, enabled) in scope.brackets() {
2717 if !pair.close && !pair.surround {
2718 continue;
2719 }
2720
2721 if enabled && pair.start.ends_with(text.as_ref()) {
2722 let prefix_len = pair.start.len() - text.len();
2723 let preceding_text_matches_prefix = prefix_len == 0
2724 || (selection.start.column >= (prefix_len as u32)
2725 && snapshot.contains_str_at(
2726 Point::new(
2727 selection.start.row,
2728 selection.start.column - (prefix_len as u32),
2729 ),
2730 &pair.start[..prefix_len],
2731 ));
2732 if preceding_text_matches_prefix {
2733 bracket_pair = Some(pair.clone());
2734 is_bracket_pair_start = true;
2735 break;
2736 }
2737 }
2738 if pair.end.as_str() == text.as_ref() {
2739 bracket_pair = Some(pair.clone());
2740 is_bracket_pair_end = true;
2741 break;
2742 }
2743 }
2744 }
2745
2746 if let Some(bracket_pair) = bracket_pair {
2747 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2748 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2749 let auto_surround =
2750 self.use_auto_surround && snapshot_settings.use_auto_surround;
2751 if selection.is_empty() {
2752 if is_bracket_pair_start {
2753 // If the inserted text is a suffix of an opening bracket and the
2754 // selection is preceded by the rest of the opening bracket, then
2755 // insert the closing bracket.
2756 let following_text_allows_autoclose = snapshot
2757 .chars_at(selection.start)
2758 .next()
2759 .map_or(true, |c| scope.should_autoclose_before(c));
2760
2761 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2762 && bracket_pair.start.len() == 1
2763 {
2764 let target = bracket_pair.start.chars().next().unwrap();
2765 let current_line_count = snapshot
2766 .reversed_chars_at(selection.start)
2767 .take_while(|&c| c != '\n')
2768 .filter(|&c| c == target)
2769 .count();
2770 current_line_count % 2 == 1
2771 } else {
2772 false
2773 };
2774
2775 if autoclose
2776 && bracket_pair.close
2777 && following_text_allows_autoclose
2778 && !is_closing_quote
2779 {
2780 let anchor = snapshot.anchor_before(selection.end);
2781 new_selections.push((selection.map(|_| anchor), text.len()));
2782 new_autoclose_regions.push((
2783 anchor,
2784 text.len(),
2785 selection.id,
2786 bracket_pair.clone(),
2787 ));
2788 edits.push((
2789 selection.range(),
2790 format!("{}{}", text, bracket_pair.end).into(),
2791 ));
2792 bracket_inserted = true;
2793 continue;
2794 }
2795 }
2796
2797 if let Some(region) = autoclose_region {
2798 // If the selection is followed by an auto-inserted closing bracket,
2799 // then don't insert that closing bracket again; just move the selection
2800 // past the closing bracket.
2801 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2802 && text.as_ref() == region.pair.end.as_str();
2803 if should_skip {
2804 let anchor = snapshot.anchor_after(selection.end);
2805 new_selections
2806 .push((selection.map(|_| anchor), region.pair.end.len()));
2807 continue;
2808 }
2809 }
2810
2811 let always_treat_brackets_as_autoclosed = snapshot
2812 .settings_at(selection.start, cx)
2813 .always_treat_brackets_as_autoclosed;
2814 if always_treat_brackets_as_autoclosed
2815 && is_bracket_pair_end
2816 && snapshot.contains_str_at(selection.end, text.as_ref())
2817 {
2818 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2819 // and the inserted text is a closing bracket and the selection is followed
2820 // by the closing bracket then move the selection past the closing bracket.
2821 let anchor = snapshot.anchor_after(selection.end);
2822 new_selections.push((selection.map(|_| anchor), text.len()));
2823 continue;
2824 }
2825 }
2826 // If an opening bracket is 1 character long and is typed while
2827 // text is selected, then surround that text with the bracket pair.
2828 else if auto_surround
2829 && bracket_pair.surround
2830 && is_bracket_pair_start
2831 && bracket_pair.start.chars().count() == 1
2832 {
2833 edits.push((selection.start..selection.start, text.clone()));
2834 edits.push((
2835 selection.end..selection.end,
2836 bracket_pair.end.as_str().into(),
2837 ));
2838 bracket_inserted = true;
2839 new_selections.push((
2840 Selection {
2841 id: selection.id,
2842 start: snapshot.anchor_after(selection.start),
2843 end: snapshot.anchor_before(selection.end),
2844 reversed: selection.reversed,
2845 goal: selection.goal,
2846 },
2847 0,
2848 ));
2849 continue;
2850 }
2851 }
2852 }
2853
2854 if self.auto_replace_emoji_shortcode
2855 && selection.is_empty()
2856 && text.as_ref().ends_with(':')
2857 {
2858 if let Some(possible_emoji_short_code) =
2859 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2860 {
2861 if !possible_emoji_short_code.is_empty() {
2862 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2863 let emoji_shortcode_start = Point::new(
2864 selection.start.row,
2865 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2866 );
2867
2868 // Remove shortcode from buffer
2869 edits.push((
2870 emoji_shortcode_start..selection.start,
2871 "".to_string().into(),
2872 ));
2873 new_selections.push((
2874 Selection {
2875 id: selection.id,
2876 start: snapshot.anchor_after(emoji_shortcode_start),
2877 end: snapshot.anchor_before(selection.start),
2878 reversed: selection.reversed,
2879 goal: selection.goal,
2880 },
2881 0,
2882 ));
2883
2884 // Insert emoji
2885 let selection_start_anchor = snapshot.anchor_after(selection.start);
2886 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2887 edits.push((selection.start..selection.end, emoji.to_string().into()));
2888
2889 continue;
2890 }
2891 }
2892 }
2893 }
2894
2895 // If not handling any auto-close operation, then just replace the selected
2896 // text with the given input and move the selection to the end of the
2897 // newly inserted text.
2898 let anchor = snapshot.anchor_after(selection.end);
2899 if !self.linked_edit_ranges.is_empty() {
2900 let start_anchor = snapshot.anchor_before(selection.start);
2901
2902 let is_word_char = text.chars().next().map_or(true, |char| {
2903 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2904 classifier.is_word(char)
2905 });
2906
2907 if is_word_char {
2908 if let Some(ranges) = self
2909 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2910 {
2911 for (buffer, edits) in ranges {
2912 linked_edits
2913 .entry(buffer.clone())
2914 .or_default()
2915 .extend(edits.into_iter().map(|range| (range, text.clone())));
2916 }
2917 }
2918 }
2919 }
2920
2921 new_selections.push((selection.map(|_| anchor), 0));
2922 edits.push((selection.start..selection.end, text.clone()));
2923 }
2924
2925 drop(snapshot);
2926
2927 self.transact(window, cx, |this, window, cx| {
2928 this.buffer.update(cx, |buffer, cx| {
2929 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2930 });
2931 for (buffer, edits) in linked_edits {
2932 buffer.update(cx, |buffer, cx| {
2933 let snapshot = buffer.snapshot();
2934 let edits = edits
2935 .into_iter()
2936 .map(|(range, text)| {
2937 use text::ToPoint as TP;
2938 let end_point = TP::to_point(&range.end, &snapshot);
2939 let start_point = TP::to_point(&range.start, &snapshot);
2940 (start_point..end_point, text)
2941 })
2942 .sorted_by_key(|(range, _)| range.start)
2943 .collect::<Vec<_>>();
2944 buffer.edit(edits, None, cx);
2945 })
2946 }
2947 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2948 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2949 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2950 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2951 .zip(new_selection_deltas)
2952 .map(|(selection, delta)| Selection {
2953 id: selection.id,
2954 start: selection.start + delta,
2955 end: selection.end + delta,
2956 reversed: selection.reversed,
2957 goal: SelectionGoal::None,
2958 })
2959 .collect::<Vec<_>>();
2960
2961 let mut i = 0;
2962 for (position, delta, selection_id, pair) in new_autoclose_regions {
2963 let position = position.to_offset(&map.buffer_snapshot) + delta;
2964 let start = map.buffer_snapshot.anchor_before(position);
2965 let end = map.buffer_snapshot.anchor_after(position);
2966 while let Some(existing_state) = this.autoclose_regions.get(i) {
2967 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2968 Ordering::Less => i += 1,
2969 Ordering::Greater => break,
2970 Ordering::Equal => {
2971 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2972 Ordering::Less => i += 1,
2973 Ordering::Equal => break,
2974 Ordering::Greater => break,
2975 }
2976 }
2977 }
2978 }
2979 this.autoclose_regions.insert(
2980 i,
2981 AutocloseRegion {
2982 selection_id,
2983 range: start..end,
2984 pair,
2985 },
2986 );
2987 }
2988
2989 let had_active_inline_completion = this.has_active_inline_completion();
2990 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
2991 s.select(new_selections)
2992 });
2993
2994 if !bracket_inserted {
2995 if let Some(on_type_format_task) =
2996 this.trigger_on_type_formatting(text.to_string(), window, cx)
2997 {
2998 on_type_format_task.detach_and_log_err(cx);
2999 }
3000 }
3001
3002 let editor_settings = EditorSettings::get_global(cx);
3003 if bracket_inserted
3004 && (editor_settings.auto_signature_help
3005 || editor_settings.show_signature_help_after_edits)
3006 {
3007 this.show_signature_help(&ShowSignatureHelp, window, cx);
3008 }
3009
3010 let trigger_in_words =
3011 this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
3012 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3013 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3014 this.refresh_inline_completion(true, false, window, cx);
3015 });
3016 }
3017
3018 fn find_possible_emoji_shortcode_at_position(
3019 snapshot: &MultiBufferSnapshot,
3020 position: Point,
3021 ) -> Option<String> {
3022 let mut chars = Vec::new();
3023 let mut found_colon = false;
3024 for char in snapshot.reversed_chars_at(position).take(100) {
3025 // Found a possible emoji shortcode in the middle of the buffer
3026 if found_colon {
3027 if char.is_whitespace() {
3028 chars.reverse();
3029 return Some(chars.iter().collect());
3030 }
3031 // If the previous character is not a whitespace, we are in the middle of a word
3032 // and we only want to complete the shortcode if the word is made up of other emojis
3033 let mut containing_word = String::new();
3034 for ch in snapshot
3035 .reversed_chars_at(position)
3036 .skip(chars.len() + 1)
3037 .take(100)
3038 {
3039 if ch.is_whitespace() {
3040 break;
3041 }
3042 containing_word.push(ch);
3043 }
3044 let containing_word = containing_word.chars().rev().collect::<String>();
3045 if util::word_consists_of_emojis(containing_word.as_str()) {
3046 chars.reverse();
3047 return Some(chars.iter().collect());
3048 }
3049 }
3050
3051 if char.is_whitespace() || !char.is_ascii() {
3052 return None;
3053 }
3054 if char == ':' {
3055 found_colon = true;
3056 } else {
3057 chars.push(char);
3058 }
3059 }
3060 // Found a possible emoji shortcode at the beginning of the buffer
3061 chars.reverse();
3062 Some(chars.iter().collect())
3063 }
3064
3065 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3066 self.transact(window, cx, |this, window, cx| {
3067 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3068 let selections = this.selections.all::<usize>(cx);
3069 let multi_buffer = this.buffer.read(cx);
3070 let buffer = multi_buffer.snapshot(cx);
3071 selections
3072 .iter()
3073 .map(|selection| {
3074 let start_point = selection.start.to_point(&buffer);
3075 let mut indent =
3076 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3077 indent.len = cmp::min(indent.len, start_point.column);
3078 let start = selection.start;
3079 let end = selection.end;
3080 let selection_is_empty = start == end;
3081 let language_scope = buffer.language_scope_at(start);
3082 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3083 &language_scope
3084 {
3085 let leading_whitespace_len = buffer
3086 .reversed_chars_at(start)
3087 .take_while(|c| c.is_whitespace() && *c != '\n')
3088 .map(|c| c.len_utf8())
3089 .sum::<usize>();
3090
3091 let trailing_whitespace_len = buffer
3092 .chars_at(end)
3093 .take_while(|c| c.is_whitespace() && *c != '\n')
3094 .map(|c| c.len_utf8())
3095 .sum::<usize>();
3096
3097 let insert_extra_newline =
3098 language.brackets().any(|(pair, enabled)| {
3099 let pair_start = pair.start.trim_end();
3100 let pair_end = pair.end.trim_start();
3101
3102 enabled
3103 && pair.newline
3104 && buffer.contains_str_at(
3105 end + trailing_whitespace_len,
3106 pair_end,
3107 )
3108 && buffer.contains_str_at(
3109 (start - leading_whitespace_len)
3110 .saturating_sub(pair_start.len()),
3111 pair_start,
3112 )
3113 });
3114
3115 // Comment extension on newline is allowed only for cursor selections
3116 let comment_delimiter = maybe!({
3117 if !selection_is_empty {
3118 return None;
3119 }
3120
3121 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3122 return None;
3123 }
3124
3125 let delimiters = language.line_comment_prefixes();
3126 let max_len_of_delimiter =
3127 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3128 let (snapshot, range) =
3129 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3130
3131 let mut index_of_first_non_whitespace = 0;
3132 let comment_candidate = snapshot
3133 .chars_for_range(range)
3134 .skip_while(|c| {
3135 let should_skip = c.is_whitespace();
3136 if should_skip {
3137 index_of_first_non_whitespace += 1;
3138 }
3139 should_skip
3140 })
3141 .take(max_len_of_delimiter)
3142 .collect::<String>();
3143 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3144 comment_candidate.starts_with(comment_prefix.as_ref())
3145 })?;
3146 let cursor_is_placed_after_comment_marker =
3147 index_of_first_non_whitespace + comment_prefix.len()
3148 <= start_point.column as usize;
3149 if cursor_is_placed_after_comment_marker {
3150 Some(comment_prefix.clone())
3151 } else {
3152 None
3153 }
3154 });
3155 (comment_delimiter, insert_extra_newline)
3156 } else {
3157 (None, false)
3158 };
3159
3160 let capacity_for_delimiter = comment_delimiter
3161 .as_deref()
3162 .map(str::len)
3163 .unwrap_or_default();
3164 let mut new_text =
3165 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3166 new_text.push('\n');
3167 new_text.extend(indent.chars());
3168 if let Some(delimiter) = &comment_delimiter {
3169 new_text.push_str(delimiter);
3170 }
3171 if insert_extra_newline {
3172 new_text = new_text.repeat(2);
3173 }
3174
3175 let anchor = buffer.anchor_after(end);
3176 let new_selection = selection.map(|_| anchor);
3177 (
3178 (start..end, new_text),
3179 (insert_extra_newline, new_selection),
3180 )
3181 })
3182 .unzip()
3183 };
3184
3185 this.edit_with_autoindent(edits, cx);
3186 let buffer = this.buffer.read(cx).snapshot(cx);
3187 let new_selections = selection_fixup_info
3188 .into_iter()
3189 .map(|(extra_newline_inserted, new_selection)| {
3190 let mut cursor = new_selection.end.to_point(&buffer);
3191 if extra_newline_inserted {
3192 cursor.row -= 1;
3193 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3194 }
3195 new_selection.map(|_| cursor)
3196 })
3197 .collect();
3198
3199 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3200 s.select(new_selections)
3201 });
3202 this.refresh_inline_completion(true, false, window, cx);
3203 });
3204 }
3205
3206 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3207 let buffer = self.buffer.read(cx);
3208 let snapshot = buffer.snapshot(cx);
3209
3210 let mut edits = Vec::new();
3211 let mut rows = Vec::new();
3212
3213 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3214 let cursor = selection.head();
3215 let row = cursor.row;
3216
3217 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3218
3219 let newline = "\n".to_string();
3220 edits.push((start_of_line..start_of_line, newline));
3221
3222 rows.push(row + rows_inserted as u32);
3223 }
3224
3225 self.transact(window, cx, |editor, window, cx| {
3226 editor.edit(edits, cx);
3227
3228 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3229 let mut index = 0;
3230 s.move_cursors_with(|map, _, _| {
3231 let row = rows[index];
3232 index += 1;
3233
3234 let point = Point::new(row, 0);
3235 let boundary = map.next_line_boundary(point).1;
3236 let clipped = map.clip_point(boundary, Bias::Left);
3237
3238 (clipped, SelectionGoal::None)
3239 });
3240 });
3241
3242 let mut indent_edits = Vec::new();
3243 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3244 for row in rows {
3245 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3246 for (row, indent) in indents {
3247 if indent.len == 0 {
3248 continue;
3249 }
3250
3251 let text = match indent.kind {
3252 IndentKind::Space => " ".repeat(indent.len as usize),
3253 IndentKind::Tab => "\t".repeat(indent.len as usize),
3254 };
3255 let point = Point::new(row.0, 0);
3256 indent_edits.push((point..point, text));
3257 }
3258 }
3259 editor.edit(indent_edits, cx);
3260 });
3261 }
3262
3263 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3264 let buffer = self.buffer.read(cx);
3265 let snapshot = buffer.snapshot(cx);
3266
3267 let mut edits = Vec::new();
3268 let mut rows = Vec::new();
3269 let mut rows_inserted = 0;
3270
3271 for selection in self.selections.all_adjusted(cx) {
3272 let cursor = selection.head();
3273 let row = cursor.row;
3274
3275 let point = Point::new(row + 1, 0);
3276 let start_of_line = snapshot.clip_point(point, Bias::Left);
3277
3278 let newline = "\n".to_string();
3279 edits.push((start_of_line..start_of_line, newline));
3280
3281 rows_inserted += 1;
3282 rows.push(row + rows_inserted);
3283 }
3284
3285 self.transact(window, cx, |editor, window, cx| {
3286 editor.edit(edits, cx);
3287
3288 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3289 let mut index = 0;
3290 s.move_cursors_with(|map, _, _| {
3291 let row = rows[index];
3292 index += 1;
3293
3294 let point = Point::new(row, 0);
3295 let boundary = map.next_line_boundary(point).1;
3296 let clipped = map.clip_point(boundary, Bias::Left);
3297
3298 (clipped, SelectionGoal::None)
3299 });
3300 });
3301
3302 let mut indent_edits = Vec::new();
3303 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3304 for row in rows {
3305 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3306 for (row, indent) in indents {
3307 if indent.len == 0 {
3308 continue;
3309 }
3310
3311 let text = match indent.kind {
3312 IndentKind::Space => " ".repeat(indent.len as usize),
3313 IndentKind::Tab => "\t".repeat(indent.len as usize),
3314 };
3315 let point = Point::new(row.0, 0);
3316 indent_edits.push((point..point, text));
3317 }
3318 }
3319 editor.edit(indent_edits, cx);
3320 });
3321 }
3322
3323 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3324 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3325 original_indent_columns: Vec::new(),
3326 });
3327 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3328 }
3329
3330 fn insert_with_autoindent_mode(
3331 &mut self,
3332 text: &str,
3333 autoindent_mode: Option<AutoindentMode>,
3334 window: &mut Window,
3335 cx: &mut Context<Self>,
3336 ) {
3337 if self.read_only(cx) {
3338 return;
3339 }
3340
3341 let text: Arc<str> = text.into();
3342 self.transact(window, cx, |this, window, cx| {
3343 let old_selections = this.selections.all_adjusted(cx);
3344 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3345 let anchors = {
3346 let snapshot = buffer.read(cx);
3347 old_selections
3348 .iter()
3349 .map(|s| {
3350 let anchor = snapshot.anchor_after(s.head());
3351 s.map(|_| anchor)
3352 })
3353 .collect::<Vec<_>>()
3354 };
3355 buffer.edit(
3356 old_selections
3357 .iter()
3358 .map(|s| (s.start..s.end, text.clone())),
3359 autoindent_mode,
3360 cx,
3361 );
3362 anchors
3363 });
3364
3365 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3366 s.select_anchors(selection_anchors);
3367 });
3368
3369 cx.notify();
3370 });
3371 }
3372
3373 fn trigger_completion_on_input(
3374 &mut self,
3375 text: &str,
3376 trigger_in_words: bool,
3377 window: &mut Window,
3378 cx: &mut Context<Self>,
3379 ) {
3380 if self.is_completion_trigger(text, trigger_in_words, cx) {
3381 self.show_completions(
3382 &ShowCompletions {
3383 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3384 },
3385 window,
3386 cx,
3387 );
3388 } else {
3389 self.hide_context_menu(window, cx);
3390 }
3391 }
3392
3393 fn is_completion_trigger(
3394 &self,
3395 text: &str,
3396 trigger_in_words: bool,
3397 cx: &mut Context<Self>,
3398 ) -> bool {
3399 let position = self.selections.newest_anchor().head();
3400 let multibuffer = self.buffer.read(cx);
3401 let Some(buffer) = position
3402 .buffer_id
3403 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3404 else {
3405 return false;
3406 };
3407
3408 if let Some(completion_provider) = &self.completion_provider {
3409 completion_provider.is_completion_trigger(
3410 &buffer,
3411 position.text_anchor,
3412 text,
3413 trigger_in_words,
3414 cx,
3415 )
3416 } else {
3417 false
3418 }
3419 }
3420
3421 /// If any empty selections is touching the start of its innermost containing autoclose
3422 /// region, expand it to select the brackets.
3423 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3424 let selections = self.selections.all::<usize>(cx);
3425 let buffer = self.buffer.read(cx).read(cx);
3426 let new_selections = self
3427 .selections_with_autoclose_regions(selections, &buffer)
3428 .map(|(mut selection, region)| {
3429 if !selection.is_empty() {
3430 return selection;
3431 }
3432
3433 if let Some(region) = region {
3434 let mut range = region.range.to_offset(&buffer);
3435 if selection.start == range.start && range.start >= region.pair.start.len() {
3436 range.start -= region.pair.start.len();
3437 if buffer.contains_str_at(range.start, ®ion.pair.start)
3438 && buffer.contains_str_at(range.end, ®ion.pair.end)
3439 {
3440 range.end += region.pair.end.len();
3441 selection.start = range.start;
3442 selection.end = range.end;
3443
3444 return selection;
3445 }
3446 }
3447 }
3448
3449 let always_treat_brackets_as_autoclosed = buffer
3450 .settings_at(selection.start, cx)
3451 .always_treat_brackets_as_autoclosed;
3452
3453 if !always_treat_brackets_as_autoclosed {
3454 return selection;
3455 }
3456
3457 if let Some(scope) = buffer.language_scope_at(selection.start) {
3458 for (pair, enabled) in scope.brackets() {
3459 if !enabled || !pair.close {
3460 continue;
3461 }
3462
3463 if buffer.contains_str_at(selection.start, &pair.end) {
3464 let pair_start_len = pair.start.len();
3465 if buffer.contains_str_at(
3466 selection.start.saturating_sub(pair_start_len),
3467 &pair.start,
3468 ) {
3469 selection.start -= pair_start_len;
3470 selection.end += pair.end.len();
3471
3472 return selection;
3473 }
3474 }
3475 }
3476 }
3477
3478 selection
3479 })
3480 .collect();
3481
3482 drop(buffer);
3483 self.change_selections(None, window, cx, |selections| {
3484 selections.select(new_selections)
3485 });
3486 }
3487
3488 /// Iterate the given selections, and for each one, find the smallest surrounding
3489 /// autoclose region. This uses the ordering of the selections and the autoclose
3490 /// regions to avoid repeated comparisons.
3491 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3492 &'a self,
3493 selections: impl IntoIterator<Item = Selection<D>>,
3494 buffer: &'a MultiBufferSnapshot,
3495 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3496 let mut i = 0;
3497 let mut regions = self.autoclose_regions.as_slice();
3498 selections.into_iter().map(move |selection| {
3499 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3500
3501 let mut enclosing = None;
3502 while let Some(pair_state) = regions.get(i) {
3503 if pair_state.range.end.to_offset(buffer) < range.start {
3504 regions = ®ions[i + 1..];
3505 i = 0;
3506 } else if pair_state.range.start.to_offset(buffer) > range.end {
3507 break;
3508 } else {
3509 if pair_state.selection_id == selection.id {
3510 enclosing = Some(pair_state);
3511 }
3512 i += 1;
3513 }
3514 }
3515
3516 (selection, enclosing)
3517 })
3518 }
3519
3520 /// Remove any autoclose regions that no longer contain their selection.
3521 fn invalidate_autoclose_regions(
3522 &mut self,
3523 mut selections: &[Selection<Anchor>],
3524 buffer: &MultiBufferSnapshot,
3525 ) {
3526 self.autoclose_regions.retain(|state| {
3527 let mut i = 0;
3528 while let Some(selection) = selections.get(i) {
3529 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3530 selections = &selections[1..];
3531 continue;
3532 }
3533 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3534 break;
3535 }
3536 if selection.id == state.selection_id {
3537 return true;
3538 } else {
3539 i += 1;
3540 }
3541 }
3542 false
3543 });
3544 }
3545
3546 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3547 let offset = position.to_offset(buffer);
3548 let (word_range, kind) = buffer.surrounding_word(offset, true);
3549 if offset > word_range.start && kind == Some(CharKind::Word) {
3550 Some(
3551 buffer
3552 .text_for_range(word_range.start..offset)
3553 .collect::<String>(),
3554 )
3555 } else {
3556 None
3557 }
3558 }
3559
3560 pub fn toggle_inlay_hints(
3561 &mut self,
3562 _: &ToggleInlayHints,
3563 _: &mut Window,
3564 cx: &mut Context<Self>,
3565 ) {
3566 self.refresh_inlay_hints(
3567 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3568 cx,
3569 );
3570 }
3571
3572 pub fn inlay_hints_enabled(&self) -> bool {
3573 self.inlay_hint_cache.enabled
3574 }
3575
3576 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3577 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3578 return;
3579 }
3580
3581 let reason_description = reason.description();
3582 let ignore_debounce = matches!(
3583 reason,
3584 InlayHintRefreshReason::SettingsChange(_)
3585 | InlayHintRefreshReason::Toggle(_)
3586 | InlayHintRefreshReason::ExcerptsRemoved(_)
3587 );
3588 let (invalidate_cache, required_languages) = match reason {
3589 InlayHintRefreshReason::Toggle(enabled) => {
3590 self.inlay_hint_cache.enabled = enabled;
3591 if enabled {
3592 (InvalidationStrategy::RefreshRequested, None)
3593 } else {
3594 self.inlay_hint_cache.clear();
3595 self.splice_inlays(
3596 self.visible_inlay_hints(cx)
3597 .iter()
3598 .map(|inlay| inlay.id)
3599 .collect(),
3600 Vec::new(),
3601 cx,
3602 );
3603 return;
3604 }
3605 }
3606 InlayHintRefreshReason::SettingsChange(new_settings) => {
3607 match self.inlay_hint_cache.update_settings(
3608 &self.buffer,
3609 new_settings,
3610 self.visible_inlay_hints(cx),
3611 cx,
3612 ) {
3613 ControlFlow::Break(Some(InlaySplice {
3614 to_remove,
3615 to_insert,
3616 })) => {
3617 self.splice_inlays(to_remove, to_insert, cx);
3618 return;
3619 }
3620 ControlFlow::Break(None) => return,
3621 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3622 }
3623 }
3624 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3625 if let Some(InlaySplice {
3626 to_remove,
3627 to_insert,
3628 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3629 {
3630 self.splice_inlays(to_remove, to_insert, cx);
3631 }
3632 return;
3633 }
3634 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3635 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3636 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3637 }
3638 InlayHintRefreshReason::RefreshRequested => {
3639 (InvalidationStrategy::RefreshRequested, None)
3640 }
3641 };
3642
3643 if let Some(InlaySplice {
3644 to_remove,
3645 to_insert,
3646 }) = self.inlay_hint_cache.spawn_hint_refresh(
3647 reason_description,
3648 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3649 invalidate_cache,
3650 ignore_debounce,
3651 cx,
3652 ) {
3653 self.splice_inlays(to_remove, to_insert, cx);
3654 }
3655 }
3656
3657 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3658 self.display_map
3659 .read(cx)
3660 .current_inlays()
3661 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3662 .cloned()
3663 .collect()
3664 }
3665
3666 pub fn excerpts_for_inlay_hints_query(
3667 &self,
3668 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3669 cx: &mut Context<Editor>,
3670 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3671 let Some(project) = self.project.as_ref() else {
3672 return HashMap::default();
3673 };
3674 let project = project.read(cx);
3675 let multi_buffer = self.buffer().read(cx);
3676 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3677 let multi_buffer_visible_start = self
3678 .scroll_manager
3679 .anchor()
3680 .anchor
3681 .to_point(&multi_buffer_snapshot);
3682 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3683 multi_buffer_visible_start
3684 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3685 Bias::Left,
3686 );
3687 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3688 multi_buffer_snapshot
3689 .range_to_buffer_ranges(multi_buffer_visible_range)
3690 .into_iter()
3691 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3692 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3693 let buffer_file = project::File::from_dyn(buffer.file())?;
3694 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3695 let worktree_entry = buffer_worktree
3696 .read(cx)
3697 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3698 if worktree_entry.is_ignored {
3699 return None;
3700 }
3701
3702 let language = buffer.language()?;
3703 if let Some(restrict_to_languages) = restrict_to_languages {
3704 if !restrict_to_languages.contains(language) {
3705 return None;
3706 }
3707 }
3708 Some((
3709 excerpt_id,
3710 (
3711 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3712 buffer.version().clone(),
3713 excerpt_visible_range,
3714 ),
3715 ))
3716 })
3717 .collect()
3718 }
3719
3720 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3721 TextLayoutDetails {
3722 text_system: window.text_system().clone(),
3723 editor_style: self.style.clone().unwrap(),
3724 rem_size: window.rem_size(),
3725 scroll_anchor: self.scroll_manager.anchor(),
3726 visible_rows: self.visible_line_count(),
3727 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3728 }
3729 }
3730
3731 pub fn splice_inlays(
3732 &self,
3733 to_remove: Vec<InlayId>,
3734 to_insert: Vec<Inlay>,
3735 cx: &mut Context<Self>,
3736 ) {
3737 self.display_map.update(cx, |display_map, cx| {
3738 display_map.splice_inlays(to_remove, to_insert, cx)
3739 });
3740 cx.notify();
3741 }
3742
3743 fn trigger_on_type_formatting(
3744 &self,
3745 input: String,
3746 window: &mut Window,
3747 cx: &mut Context<Self>,
3748 ) -> Option<Task<Result<()>>> {
3749 if input.len() != 1 {
3750 return None;
3751 }
3752
3753 let project = self.project.as_ref()?;
3754 let position = self.selections.newest_anchor().head();
3755 let (buffer, buffer_position) = self
3756 .buffer
3757 .read(cx)
3758 .text_anchor_for_position(position, cx)?;
3759
3760 let settings = language_settings::language_settings(
3761 buffer
3762 .read(cx)
3763 .language_at(buffer_position)
3764 .map(|l| l.name()),
3765 buffer.read(cx).file(),
3766 cx,
3767 );
3768 if !settings.use_on_type_format {
3769 return None;
3770 }
3771
3772 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3773 // hence we do LSP request & edit on host side only — add formats to host's history.
3774 let push_to_lsp_host_history = true;
3775 // If this is not the host, append its history with new edits.
3776 let push_to_client_history = project.read(cx).is_via_collab();
3777
3778 let on_type_formatting = project.update(cx, |project, cx| {
3779 project.on_type_format(
3780 buffer.clone(),
3781 buffer_position,
3782 input,
3783 push_to_lsp_host_history,
3784 cx,
3785 )
3786 });
3787 Some(cx.spawn_in(window, |editor, mut cx| async move {
3788 if let Some(transaction) = on_type_formatting.await? {
3789 if push_to_client_history {
3790 buffer
3791 .update(&mut cx, |buffer, _| {
3792 buffer.push_transaction(transaction, Instant::now());
3793 })
3794 .ok();
3795 }
3796 editor.update(&mut cx, |editor, cx| {
3797 editor.refresh_document_highlights(cx);
3798 })?;
3799 }
3800 Ok(())
3801 }))
3802 }
3803
3804 pub fn show_completions(
3805 &mut self,
3806 options: &ShowCompletions,
3807 window: &mut Window,
3808 cx: &mut Context<Self>,
3809 ) {
3810 if self.pending_rename.is_some() {
3811 return;
3812 }
3813
3814 let Some(provider) = self.completion_provider.as_ref() else {
3815 return;
3816 };
3817
3818 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3819 return;
3820 }
3821
3822 let position = self.selections.newest_anchor().head();
3823 if position.diff_base_anchor.is_some() {
3824 return;
3825 }
3826 let (buffer, buffer_position) =
3827 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3828 output
3829 } else {
3830 return;
3831 };
3832 let show_completion_documentation = buffer
3833 .read(cx)
3834 .snapshot()
3835 .settings_at(buffer_position, cx)
3836 .show_completion_documentation;
3837
3838 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3839
3840 let trigger_kind = match &options.trigger {
3841 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3842 CompletionTriggerKind::TRIGGER_CHARACTER
3843 }
3844 _ => CompletionTriggerKind::INVOKED,
3845 };
3846 let completion_context = CompletionContext {
3847 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3848 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3849 Some(String::from(trigger))
3850 } else {
3851 None
3852 }
3853 }),
3854 trigger_kind,
3855 };
3856 let completions =
3857 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3858 let sort_completions = provider.sort_completions();
3859
3860 let id = post_inc(&mut self.next_completion_id);
3861 let task = cx.spawn_in(window, |editor, mut cx| {
3862 async move {
3863 editor.update(&mut cx, |this, _| {
3864 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3865 })?;
3866 let completions = completions.await.log_err();
3867 let menu = if let Some(completions) = completions {
3868 let mut menu = CompletionsMenu::new(
3869 id,
3870 sort_completions,
3871 show_completion_documentation,
3872 position,
3873 buffer.clone(),
3874 completions.into(),
3875 );
3876
3877 menu.filter(query.as_deref(), cx.background_executor().clone())
3878 .await;
3879
3880 menu.visible().then_some(menu)
3881 } else {
3882 None
3883 };
3884
3885 editor.update_in(&mut cx, |editor, window, cx| {
3886 match editor.context_menu.borrow().as_ref() {
3887 None => {}
3888 Some(CodeContextMenu::Completions(prev_menu)) => {
3889 if prev_menu.id > id {
3890 return;
3891 }
3892 }
3893 _ => return,
3894 }
3895
3896 if editor.focus_handle.is_focused(window) && menu.is_some() {
3897 let mut menu = menu.unwrap();
3898 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3899
3900 if editor.show_inline_completions_in_menu(cx) {
3901 if let Some(hint) = editor.inline_completion_menu_hint(window, cx) {
3902 menu.show_inline_completion_hint(hint);
3903 }
3904 } else {
3905 editor.discard_inline_completion(false, cx);
3906 }
3907
3908 *editor.context_menu.borrow_mut() =
3909 Some(CodeContextMenu::Completions(menu));
3910
3911 cx.notify();
3912 } else if editor.completion_tasks.len() <= 1 {
3913 // If there are no more completion tasks and the last menu was
3914 // empty, we should hide it.
3915 let was_hidden = editor.hide_context_menu(window, cx).is_none();
3916 // If it was already hidden and we don't show inline
3917 // completions in the menu, we should also show the
3918 // inline-completion when available.
3919 if was_hidden && editor.show_inline_completions_in_menu(cx) {
3920 editor.update_visible_inline_completion(window, cx);
3921 }
3922 }
3923 })?;
3924
3925 Ok::<_, anyhow::Error>(())
3926 }
3927 .log_err()
3928 });
3929
3930 self.completion_tasks.push((id, task));
3931 }
3932
3933 pub fn confirm_completion(
3934 &mut self,
3935 action: &ConfirmCompletion,
3936 window: &mut Window,
3937 cx: &mut Context<Self>,
3938 ) -> Option<Task<Result<()>>> {
3939 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
3940 }
3941
3942 pub fn compose_completion(
3943 &mut self,
3944 action: &ComposeCompletion,
3945 window: &mut Window,
3946 cx: &mut Context<Self>,
3947 ) -> Option<Task<Result<()>>> {
3948 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
3949 }
3950
3951 fn toggle_zed_predict_tos(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3952 let (Some(workspace), Some(project)) = (self.workspace(), self.project.as_ref()) else {
3953 return;
3954 };
3955
3956 ZedPredictTos::toggle(workspace, project.read(cx).user_store().clone(), window, cx);
3957 }
3958
3959 fn do_completion(
3960 &mut self,
3961 item_ix: Option<usize>,
3962 intent: CompletionIntent,
3963 window: &mut Window,
3964 cx: &mut Context<Editor>,
3965 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3966 use language::ToOffset as _;
3967
3968 {
3969 let context_menu = self.context_menu.borrow();
3970 if let CodeContextMenu::Completions(menu) = context_menu.as_ref()? {
3971 let entries = menu.entries.borrow();
3972 let entry = entries.get(item_ix.unwrap_or(menu.selected_item));
3973 match entry {
3974 Some(CompletionEntry::InlineCompletionHint(
3975 InlineCompletionMenuHint::Loading,
3976 )) => return Some(Task::ready(Ok(()))),
3977 Some(CompletionEntry::InlineCompletionHint(InlineCompletionMenuHint::None)) => {
3978 drop(entries);
3979 drop(context_menu);
3980 self.context_menu_next(&Default::default(), window, cx);
3981 return Some(Task::ready(Ok(())));
3982 }
3983 Some(CompletionEntry::InlineCompletionHint(
3984 InlineCompletionMenuHint::PendingTermsAcceptance,
3985 )) => {
3986 drop(entries);
3987 drop(context_menu);
3988 self.toggle_zed_predict_tos(window, cx);
3989 return Some(Task::ready(Ok(())));
3990 }
3991 _ => {}
3992 }
3993 }
3994 }
3995
3996 let completions_menu =
3997 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
3998 menu
3999 } else {
4000 return None;
4001 };
4002
4003 let entries = completions_menu.entries.borrow();
4004 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4005 let mat = match mat {
4006 CompletionEntry::InlineCompletionHint(_) => {
4007 self.accept_inline_completion(&AcceptInlineCompletion, window, cx);
4008 cx.stop_propagation();
4009 return Some(Task::ready(Ok(())));
4010 }
4011 CompletionEntry::Match(mat) => {
4012 if self.show_inline_completions_in_menu(cx) {
4013 self.discard_inline_completion(true, cx);
4014 }
4015 mat
4016 }
4017 };
4018 let candidate_id = mat.candidate_id;
4019 drop(entries);
4020
4021 let buffer_handle = completions_menu.buffer;
4022 let completion = completions_menu
4023 .completions
4024 .borrow()
4025 .get(candidate_id)?
4026 .clone();
4027 cx.stop_propagation();
4028
4029 let snippet;
4030 let text;
4031
4032 if completion.is_snippet() {
4033 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4034 text = snippet.as_ref().unwrap().text.clone();
4035 } else {
4036 snippet = None;
4037 text = completion.new_text.clone();
4038 };
4039 let selections = self.selections.all::<usize>(cx);
4040 let buffer = buffer_handle.read(cx);
4041 let old_range = completion.old_range.to_offset(buffer);
4042 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4043
4044 let newest_selection = self.selections.newest_anchor();
4045 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4046 return None;
4047 }
4048
4049 let lookbehind = newest_selection
4050 .start
4051 .text_anchor
4052 .to_offset(buffer)
4053 .saturating_sub(old_range.start);
4054 let lookahead = old_range
4055 .end
4056 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4057 let mut common_prefix_len = old_text
4058 .bytes()
4059 .zip(text.bytes())
4060 .take_while(|(a, b)| a == b)
4061 .count();
4062
4063 let snapshot = self.buffer.read(cx).snapshot(cx);
4064 let mut range_to_replace: Option<Range<isize>> = None;
4065 let mut ranges = Vec::new();
4066 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4067 for selection in &selections {
4068 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4069 let start = selection.start.saturating_sub(lookbehind);
4070 let end = selection.end + lookahead;
4071 if selection.id == newest_selection.id {
4072 range_to_replace = Some(
4073 ((start + common_prefix_len) as isize - selection.start as isize)
4074 ..(end as isize - selection.start as isize),
4075 );
4076 }
4077 ranges.push(start + common_prefix_len..end);
4078 } else {
4079 common_prefix_len = 0;
4080 ranges.clear();
4081 ranges.extend(selections.iter().map(|s| {
4082 if s.id == newest_selection.id {
4083 range_to_replace = Some(
4084 old_range.start.to_offset_utf16(&snapshot).0 as isize
4085 - selection.start as isize
4086 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4087 - selection.start as isize,
4088 );
4089 old_range.clone()
4090 } else {
4091 s.start..s.end
4092 }
4093 }));
4094 break;
4095 }
4096 if !self.linked_edit_ranges.is_empty() {
4097 let start_anchor = snapshot.anchor_before(selection.head());
4098 let end_anchor = snapshot.anchor_after(selection.tail());
4099 if let Some(ranges) = self
4100 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4101 {
4102 for (buffer, edits) in ranges {
4103 linked_edits.entry(buffer.clone()).or_default().extend(
4104 edits
4105 .into_iter()
4106 .map(|range| (range, text[common_prefix_len..].to_owned())),
4107 );
4108 }
4109 }
4110 }
4111 }
4112 let text = &text[common_prefix_len..];
4113
4114 cx.emit(EditorEvent::InputHandled {
4115 utf16_range_to_replace: range_to_replace,
4116 text: text.into(),
4117 });
4118
4119 self.transact(window, cx, |this, window, cx| {
4120 if let Some(mut snippet) = snippet {
4121 snippet.text = text.to_string();
4122 for tabstop in snippet
4123 .tabstops
4124 .iter_mut()
4125 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4126 {
4127 tabstop.start -= common_prefix_len as isize;
4128 tabstop.end -= common_prefix_len as isize;
4129 }
4130
4131 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4132 } else {
4133 this.buffer.update(cx, |buffer, cx| {
4134 buffer.edit(
4135 ranges.iter().map(|range| (range.clone(), text)),
4136 this.autoindent_mode.clone(),
4137 cx,
4138 );
4139 });
4140 }
4141 for (buffer, edits) in linked_edits {
4142 buffer.update(cx, |buffer, cx| {
4143 let snapshot = buffer.snapshot();
4144 let edits = edits
4145 .into_iter()
4146 .map(|(range, text)| {
4147 use text::ToPoint as TP;
4148 let end_point = TP::to_point(&range.end, &snapshot);
4149 let start_point = TP::to_point(&range.start, &snapshot);
4150 (start_point..end_point, text)
4151 })
4152 .sorted_by_key(|(range, _)| range.start)
4153 .collect::<Vec<_>>();
4154 buffer.edit(edits, None, cx);
4155 })
4156 }
4157
4158 this.refresh_inline_completion(true, false, window, cx);
4159 });
4160
4161 let show_new_completions_on_confirm = completion
4162 .confirm
4163 .as_ref()
4164 .map_or(false, |confirm| confirm(intent, window, cx));
4165 if show_new_completions_on_confirm {
4166 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4167 }
4168
4169 let provider = self.completion_provider.as_ref()?;
4170 drop(completion);
4171 let apply_edits = provider.apply_additional_edits_for_completion(
4172 buffer_handle,
4173 completions_menu.completions.clone(),
4174 candidate_id,
4175 true,
4176 cx,
4177 );
4178
4179 let editor_settings = EditorSettings::get_global(cx);
4180 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4181 // After the code completion is finished, users often want to know what signatures are needed.
4182 // so we should automatically call signature_help
4183 self.show_signature_help(&ShowSignatureHelp, window, cx);
4184 }
4185
4186 Some(cx.foreground_executor().spawn(async move {
4187 apply_edits.await?;
4188 Ok(())
4189 }))
4190 }
4191
4192 pub fn toggle_code_actions(
4193 &mut self,
4194 action: &ToggleCodeActions,
4195 window: &mut Window,
4196 cx: &mut Context<Self>,
4197 ) {
4198 let mut context_menu = self.context_menu.borrow_mut();
4199 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4200 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4201 // Toggle if we're selecting the same one
4202 *context_menu = None;
4203 cx.notify();
4204 return;
4205 } else {
4206 // Otherwise, clear it and start a new one
4207 *context_menu = None;
4208 cx.notify();
4209 }
4210 }
4211 drop(context_menu);
4212 let snapshot = self.snapshot(window, cx);
4213 let deployed_from_indicator = action.deployed_from_indicator;
4214 let mut task = self.code_actions_task.take();
4215 let action = action.clone();
4216 cx.spawn_in(window, |editor, mut cx| async move {
4217 while let Some(prev_task) = task {
4218 prev_task.await.log_err();
4219 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4220 }
4221
4222 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4223 if editor.focus_handle.is_focused(window) {
4224 let multibuffer_point = action
4225 .deployed_from_indicator
4226 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4227 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4228 let (buffer, buffer_row) = snapshot
4229 .buffer_snapshot
4230 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4231 .and_then(|(buffer_snapshot, range)| {
4232 editor
4233 .buffer
4234 .read(cx)
4235 .buffer(buffer_snapshot.remote_id())
4236 .map(|buffer| (buffer, range.start.row))
4237 })?;
4238 let (_, code_actions) = editor
4239 .available_code_actions
4240 .clone()
4241 .and_then(|(location, code_actions)| {
4242 let snapshot = location.buffer.read(cx).snapshot();
4243 let point_range = location.range.to_point(&snapshot);
4244 let point_range = point_range.start.row..=point_range.end.row;
4245 if point_range.contains(&buffer_row) {
4246 Some((location, code_actions))
4247 } else {
4248 None
4249 }
4250 })
4251 .unzip();
4252 let buffer_id = buffer.read(cx).remote_id();
4253 let tasks = editor
4254 .tasks
4255 .get(&(buffer_id, buffer_row))
4256 .map(|t| Arc::new(t.to_owned()));
4257 if tasks.is_none() && code_actions.is_none() {
4258 return None;
4259 }
4260
4261 editor.completion_tasks.clear();
4262 editor.discard_inline_completion(false, cx);
4263 let task_context =
4264 tasks
4265 .as_ref()
4266 .zip(editor.project.clone())
4267 .map(|(tasks, project)| {
4268 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4269 });
4270
4271 Some(cx.spawn_in(window, |editor, mut cx| async move {
4272 let task_context = match task_context {
4273 Some(task_context) => task_context.await,
4274 None => None,
4275 };
4276 let resolved_tasks =
4277 tasks.zip(task_context).map(|(tasks, task_context)| {
4278 Rc::new(ResolvedTasks {
4279 templates: tasks.resolve(&task_context).collect(),
4280 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4281 multibuffer_point.row,
4282 tasks.column,
4283 )),
4284 })
4285 });
4286 let spawn_straight_away = resolved_tasks
4287 .as_ref()
4288 .map_or(false, |tasks| tasks.templates.len() == 1)
4289 && code_actions
4290 .as_ref()
4291 .map_or(true, |actions| actions.is_empty());
4292 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4293 *editor.context_menu.borrow_mut() =
4294 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4295 buffer,
4296 actions: CodeActionContents {
4297 tasks: resolved_tasks,
4298 actions: code_actions,
4299 },
4300 selected_item: Default::default(),
4301 scroll_handle: UniformListScrollHandle::default(),
4302 deployed_from_indicator,
4303 }));
4304 if spawn_straight_away {
4305 if let Some(task) = editor.confirm_code_action(
4306 &ConfirmCodeAction { item_ix: Some(0) },
4307 window,
4308 cx,
4309 ) {
4310 cx.notify();
4311 return task;
4312 }
4313 }
4314 cx.notify();
4315 Task::ready(Ok(()))
4316 }) {
4317 task.await
4318 } else {
4319 Ok(())
4320 }
4321 }))
4322 } else {
4323 Some(Task::ready(Ok(())))
4324 }
4325 })?;
4326 if let Some(task) = spawned_test_task {
4327 task.await?;
4328 }
4329
4330 Ok::<_, anyhow::Error>(())
4331 })
4332 .detach_and_log_err(cx);
4333 }
4334
4335 pub fn confirm_code_action(
4336 &mut self,
4337 action: &ConfirmCodeAction,
4338 window: &mut Window,
4339 cx: &mut Context<Self>,
4340 ) -> Option<Task<Result<()>>> {
4341 let actions_menu =
4342 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4343 menu
4344 } else {
4345 return None;
4346 };
4347 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4348 let action = actions_menu.actions.get(action_ix)?;
4349 let title = action.label();
4350 let buffer = actions_menu.buffer;
4351 let workspace = self.workspace()?;
4352
4353 match action {
4354 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4355 workspace.update(cx, |workspace, cx| {
4356 workspace::tasks::schedule_resolved_task(
4357 workspace,
4358 task_source_kind,
4359 resolved_task,
4360 false,
4361 cx,
4362 );
4363
4364 Some(Task::ready(Ok(())))
4365 })
4366 }
4367 CodeActionsItem::CodeAction {
4368 excerpt_id,
4369 action,
4370 provider,
4371 } => {
4372 let apply_code_action =
4373 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4374 let workspace = workspace.downgrade();
4375 Some(cx.spawn_in(window, |editor, cx| async move {
4376 let project_transaction = apply_code_action.await?;
4377 Self::open_project_transaction(
4378 &editor,
4379 workspace,
4380 project_transaction,
4381 title,
4382 cx,
4383 )
4384 .await
4385 }))
4386 }
4387 }
4388 }
4389
4390 pub async fn open_project_transaction(
4391 this: &WeakEntity<Editor>,
4392 workspace: WeakEntity<Workspace>,
4393 transaction: ProjectTransaction,
4394 title: String,
4395 mut cx: AsyncWindowContext,
4396 ) -> Result<()> {
4397 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4398 cx.update(|_, cx| {
4399 entries.sort_unstable_by_key(|(buffer, _)| {
4400 buffer.read(cx).file().map(|f| f.path().clone())
4401 });
4402 })?;
4403
4404 // If the project transaction's edits are all contained within this editor, then
4405 // avoid opening a new editor to display them.
4406
4407 if let Some((buffer, transaction)) = entries.first() {
4408 if entries.len() == 1 {
4409 let excerpt = this.update(&mut cx, |editor, cx| {
4410 editor
4411 .buffer()
4412 .read(cx)
4413 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4414 })?;
4415 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4416 if excerpted_buffer == *buffer {
4417 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4418 let excerpt_range = excerpt_range.to_offset(buffer);
4419 buffer
4420 .edited_ranges_for_transaction::<usize>(transaction)
4421 .all(|range| {
4422 excerpt_range.start <= range.start
4423 && excerpt_range.end >= range.end
4424 })
4425 })?;
4426
4427 if all_edits_within_excerpt {
4428 return Ok(());
4429 }
4430 }
4431 }
4432 }
4433 } else {
4434 return Ok(());
4435 }
4436
4437 let mut ranges_to_highlight = Vec::new();
4438 let excerpt_buffer = cx.new(|cx| {
4439 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4440 for (buffer_handle, transaction) in &entries {
4441 let buffer = buffer_handle.read(cx);
4442 ranges_to_highlight.extend(
4443 multibuffer.push_excerpts_with_context_lines(
4444 buffer_handle.clone(),
4445 buffer
4446 .edited_ranges_for_transaction::<usize>(transaction)
4447 .collect(),
4448 DEFAULT_MULTIBUFFER_CONTEXT,
4449 cx,
4450 ),
4451 );
4452 }
4453 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4454 multibuffer
4455 })?;
4456
4457 workspace.update_in(&mut cx, |workspace, window, cx| {
4458 let project = workspace.project().clone();
4459 let editor = cx
4460 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4461 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4462 editor.update(cx, |editor, cx| {
4463 editor.highlight_background::<Self>(
4464 &ranges_to_highlight,
4465 |theme| theme.editor_highlighted_line_background,
4466 cx,
4467 );
4468 });
4469 })?;
4470
4471 Ok(())
4472 }
4473
4474 pub fn clear_code_action_providers(&mut self) {
4475 self.code_action_providers.clear();
4476 self.available_code_actions.take();
4477 }
4478
4479 pub fn add_code_action_provider(
4480 &mut self,
4481 provider: Rc<dyn CodeActionProvider>,
4482 window: &mut Window,
4483 cx: &mut Context<Self>,
4484 ) {
4485 if self
4486 .code_action_providers
4487 .iter()
4488 .any(|existing_provider| existing_provider.id() == provider.id())
4489 {
4490 return;
4491 }
4492
4493 self.code_action_providers.push(provider);
4494 self.refresh_code_actions(window, cx);
4495 }
4496
4497 pub fn remove_code_action_provider(
4498 &mut self,
4499 id: Arc<str>,
4500 window: &mut Window,
4501 cx: &mut Context<Self>,
4502 ) {
4503 self.code_action_providers
4504 .retain(|provider| provider.id() != id);
4505 self.refresh_code_actions(window, cx);
4506 }
4507
4508 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4509 let buffer = self.buffer.read(cx);
4510 let newest_selection = self.selections.newest_anchor().clone();
4511 if newest_selection.head().diff_base_anchor.is_some() {
4512 return None;
4513 }
4514 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4515 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4516 if start_buffer != end_buffer {
4517 return None;
4518 }
4519
4520 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4521 cx.background_executor()
4522 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4523 .await;
4524
4525 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4526 let providers = this.code_action_providers.clone();
4527 let tasks = this
4528 .code_action_providers
4529 .iter()
4530 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4531 .collect::<Vec<_>>();
4532 (providers, tasks)
4533 })?;
4534
4535 let mut actions = Vec::new();
4536 for (provider, provider_actions) in
4537 providers.into_iter().zip(future::join_all(tasks).await)
4538 {
4539 if let Some(provider_actions) = provider_actions.log_err() {
4540 actions.extend(provider_actions.into_iter().map(|action| {
4541 AvailableCodeAction {
4542 excerpt_id: newest_selection.start.excerpt_id,
4543 action,
4544 provider: provider.clone(),
4545 }
4546 }));
4547 }
4548 }
4549
4550 this.update(&mut cx, |this, cx| {
4551 this.available_code_actions = if actions.is_empty() {
4552 None
4553 } else {
4554 Some((
4555 Location {
4556 buffer: start_buffer,
4557 range: start..end,
4558 },
4559 actions.into(),
4560 ))
4561 };
4562 cx.notify();
4563 })
4564 }));
4565 None
4566 }
4567
4568 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4569 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4570 self.show_git_blame_inline = false;
4571
4572 self.show_git_blame_inline_delay_task =
4573 Some(cx.spawn_in(window, |this, mut cx| async move {
4574 cx.background_executor().timer(delay).await;
4575
4576 this.update(&mut cx, |this, cx| {
4577 this.show_git_blame_inline = true;
4578 cx.notify();
4579 })
4580 .log_err();
4581 }));
4582 }
4583 }
4584
4585 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4586 if self.pending_rename.is_some() {
4587 return None;
4588 }
4589
4590 let provider = self.semantics_provider.clone()?;
4591 let buffer = self.buffer.read(cx);
4592 let newest_selection = self.selections.newest_anchor().clone();
4593 let cursor_position = newest_selection.head();
4594 let (cursor_buffer, cursor_buffer_position) =
4595 buffer.text_anchor_for_position(cursor_position, cx)?;
4596 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4597 if cursor_buffer != tail_buffer {
4598 return None;
4599 }
4600 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4601 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4602 cx.background_executor()
4603 .timer(Duration::from_millis(debounce))
4604 .await;
4605
4606 let highlights = if let Some(highlights) = cx
4607 .update(|cx| {
4608 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4609 })
4610 .ok()
4611 .flatten()
4612 {
4613 highlights.await.log_err()
4614 } else {
4615 None
4616 };
4617
4618 if let Some(highlights) = highlights {
4619 this.update(&mut cx, |this, cx| {
4620 if this.pending_rename.is_some() {
4621 return;
4622 }
4623
4624 let buffer_id = cursor_position.buffer_id;
4625 let buffer = this.buffer.read(cx);
4626 if !buffer
4627 .text_anchor_for_position(cursor_position, cx)
4628 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4629 {
4630 return;
4631 }
4632
4633 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4634 let mut write_ranges = Vec::new();
4635 let mut read_ranges = Vec::new();
4636 for highlight in highlights {
4637 for (excerpt_id, excerpt_range) in
4638 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4639 {
4640 let start = highlight
4641 .range
4642 .start
4643 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4644 let end = highlight
4645 .range
4646 .end
4647 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4648 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4649 continue;
4650 }
4651
4652 let range = Anchor {
4653 buffer_id,
4654 excerpt_id,
4655 text_anchor: start,
4656 diff_base_anchor: None,
4657 }..Anchor {
4658 buffer_id,
4659 excerpt_id,
4660 text_anchor: end,
4661 diff_base_anchor: None,
4662 };
4663 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4664 write_ranges.push(range);
4665 } else {
4666 read_ranges.push(range);
4667 }
4668 }
4669 }
4670
4671 this.highlight_background::<DocumentHighlightRead>(
4672 &read_ranges,
4673 |theme| theme.editor_document_highlight_read_background,
4674 cx,
4675 );
4676 this.highlight_background::<DocumentHighlightWrite>(
4677 &write_ranges,
4678 |theme| theme.editor_document_highlight_write_background,
4679 cx,
4680 );
4681 cx.notify();
4682 })
4683 .log_err();
4684 }
4685 }));
4686 None
4687 }
4688
4689 pub fn refresh_inline_completion(
4690 &mut self,
4691 debounce: bool,
4692 user_requested: bool,
4693 window: &mut Window,
4694 cx: &mut Context<Self>,
4695 ) -> Option<()> {
4696 let provider = self.inline_completion_provider()?;
4697 let cursor = self.selections.newest_anchor().head();
4698 let (buffer, cursor_buffer_position) =
4699 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4700
4701 if !user_requested
4702 && (!self.enable_inline_completions
4703 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4704 || !self.is_focused(window)
4705 || buffer.read(cx).is_empty())
4706 {
4707 self.discard_inline_completion(false, cx);
4708 return None;
4709 }
4710
4711 self.update_visible_inline_completion(window, cx);
4712 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4713 Some(())
4714 }
4715
4716 fn cycle_inline_completion(
4717 &mut self,
4718 direction: Direction,
4719 window: &mut Window,
4720 cx: &mut Context<Self>,
4721 ) -> Option<()> {
4722 let provider = self.inline_completion_provider()?;
4723 let cursor = self.selections.newest_anchor().head();
4724 let (buffer, cursor_buffer_position) =
4725 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4726 if !self.enable_inline_completions
4727 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4728 {
4729 return None;
4730 }
4731
4732 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4733 self.update_visible_inline_completion(window, cx);
4734
4735 Some(())
4736 }
4737
4738 pub fn show_inline_completion(
4739 &mut self,
4740 _: &ShowInlineCompletion,
4741 window: &mut Window,
4742 cx: &mut Context<Self>,
4743 ) {
4744 if !self.has_active_inline_completion() {
4745 self.refresh_inline_completion(false, true, window, cx);
4746 return;
4747 }
4748
4749 self.update_visible_inline_completion(window, cx);
4750 }
4751
4752 pub fn display_cursor_names(
4753 &mut self,
4754 _: &DisplayCursorNames,
4755 window: &mut Window,
4756 cx: &mut Context<Self>,
4757 ) {
4758 self.show_cursor_names(window, cx);
4759 }
4760
4761 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4762 self.show_cursor_names = true;
4763 cx.notify();
4764 cx.spawn_in(window, |this, mut cx| async move {
4765 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4766 this.update(&mut cx, |this, cx| {
4767 this.show_cursor_names = false;
4768 cx.notify()
4769 })
4770 .ok()
4771 })
4772 .detach();
4773 }
4774
4775 pub fn next_inline_completion(
4776 &mut self,
4777 _: &NextInlineCompletion,
4778 window: &mut Window,
4779 cx: &mut Context<Self>,
4780 ) {
4781 if self.has_active_inline_completion() {
4782 self.cycle_inline_completion(Direction::Next, window, cx);
4783 } else {
4784 let is_copilot_disabled = self
4785 .refresh_inline_completion(false, true, window, cx)
4786 .is_none();
4787 if is_copilot_disabled {
4788 cx.propagate();
4789 }
4790 }
4791 }
4792
4793 pub fn previous_inline_completion(
4794 &mut self,
4795 _: &PreviousInlineCompletion,
4796 window: &mut Window,
4797 cx: &mut Context<Self>,
4798 ) {
4799 if self.has_active_inline_completion() {
4800 self.cycle_inline_completion(Direction::Prev, window, cx);
4801 } else {
4802 let is_copilot_disabled = self
4803 .refresh_inline_completion(false, true, window, cx)
4804 .is_none();
4805 if is_copilot_disabled {
4806 cx.propagate();
4807 }
4808 }
4809 }
4810
4811 pub fn accept_inline_completion(
4812 &mut self,
4813 _: &AcceptInlineCompletion,
4814 window: &mut Window,
4815 cx: &mut Context<Self>,
4816 ) {
4817 let buffer = self.buffer.read(cx);
4818 let snapshot = buffer.snapshot(cx);
4819 let selection = self.selections.newest_adjusted(cx);
4820 let cursor = selection.head();
4821 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
4822 let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
4823 if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
4824 {
4825 if cursor.column < suggested_indent.len
4826 && cursor.column <= current_indent.len
4827 && current_indent.len <= suggested_indent.len
4828 {
4829 self.tab(&Default::default(), window, cx);
4830 return;
4831 }
4832 }
4833
4834 if self.show_inline_completions_in_menu(cx) {
4835 self.hide_context_menu(window, cx);
4836 }
4837
4838 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4839 return;
4840 };
4841
4842 self.report_inline_completion_event(true, cx);
4843
4844 match &active_inline_completion.completion {
4845 InlineCompletion::Move(position) => {
4846 let position = *position;
4847 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
4848 selections.select_anchor_ranges([position..position]);
4849 });
4850 }
4851 InlineCompletion::Edit { edits, .. } => {
4852 if let Some(provider) = self.inline_completion_provider() {
4853 provider.accept(cx);
4854 }
4855
4856 let snapshot = self.buffer.read(cx).snapshot(cx);
4857 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4858
4859 self.buffer.update(cx, |buffer, cx| {
4860 buffer.edit(edits.iter().cloned(), None, cx)
4861 });
4862
4863 self.change_selections(None, window, cx, |s| {
4864 s.select_anchor_ranges([last_edit_end..last_edit_end])
4865 });
4866
4867 self.update_visible_inline_completion(window, cx);
4868 if self.active_inline_completion.is_none() {
4869 self.refresh_inline_completion(true, true, window, cx);
4870 }
4871
4872 cx.notify();
4873 }
4874 }
4875 }
4876
4877 pub fn accept_partial_inline_completion(
4878 &mut self,
4879 _: &AcceptPartialInlineCompletion,
4880 window: &mut Window,
4881 cx: &mut Context<Self>,
4882 ) {
4883 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4884 return;
4885 };
4886 if self.selections.count() != 1 {
4887 return;
4888 }
4889
4890 self.report_inline_completion_event(true, cx);
4891
4892 match &active_inline_completion.completion {
4893 InlineCompletion::Move(position) => {
4894 let position = *position;
4895 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
4896 selections.select_anchor_ranges([position..position]);
4897 });
4898 }
4899 InlineCompletion::Edit { edits, .. } => {
4900 // Find an insertion that starts at the cursor position.
4901 let snapshot = self.buffer.read(cx).snapshot(cx);
4902 let cursor_offset = self.selections.newest::<usize>(cx).head();
4903 let insertion = edits.iter().find_map(|(range, text)| {
4904 let range = range.to_offset(&snapshot);
4905 if range.is_empty() && range.start == cursor_offset {
4906 Some(text)
4907 } else {
4908 None
4909 }
4910 });
4911
4912 if let Some(text) = insertion {
4913 let mut partial_completion = text
4914 .chars()
4915 .by_ref()
4916 .take_while(|c| c.is_alphabetic())
4917 .collect::<String>();
4918 if partial_completion.is_empty() {
4919 partial_completion = text
4920 .chars()
4921 .by_ref()
4922 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4923 .collect::<String>();
4924 }
4925
4926 cx.emit(EditorEvent::InputHandled {
4927 utf16_range_to_replace: None,
4928 text: partial_completion.clone().into(),
4929 });
4930
4931 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
4932
4933 self.refresh_inline_completion(true, true, window, cx);
4934 cx.notify();
4935 } else {
4936 self.accept_inline_completion(&Default::default(), window, cx);
4937 }
4938 }
4939 }
4940 }
4941
4942 fn discard_inline_completion(
4943 &mut self,
4944 should_report_inline_completion_event: bool,
4945 cx: &mut Context<Self>,
4946 ) -> bool {
4947 if should_report_inline_completion_event {
4948 self.report_inline_completion_event(false, cx);
4949 }
4950
4951 if let Some(provider) = self.inline_completion_provider() {
4952 provider.discard(cx);
4953 }
4954
4955 self.take_active_inline_completion(cx).is_some()
4956 }
4957
4958 fn report_inline_completion_event(&self, accepted: bool, cx: &App) {
4959 let Some(provider) = self.inline_completion_provider() else {
4960 return;
4961 };
4962
4963 let Some((_, buffer, _)) = self
4964 .buffer
4965 .read(cx)
4966 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4967 else {
4968 return;
4969 };
4970
4971 let extension = buffer
4972 .read(cx)
4973 .file()
4974 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4975
4976 let event_type = match accepted {
4977 true => "Inline Completion Accepted",
4978 false => "Inline Completion Discarded",
4979 };
4980 telemetry::event!(
4981 event_type,
4982 provider = provider.name(),
4983 suggestion_accepted = accepted,
4984 file_extension = extension,
4985 );
4986 }
4987
4988 pub fn has_active_inline_completion(&self) -> bool {
4989 self.active_inline_completion.is_some()
4990 }
4991
4992 fn take_active_inline_completion(
4993 &mut self,
4994 cx: &mut Context<Self>,
4995 ) -> Option<InlineCompletion> {
4996 let active_inline_completion = self.active_inline_completion.take()?;
4997 self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
4998 self.clear_highlights::<InlineCompletionHighlight>(cx);
4999 Some(active_inline_completion.completion)
5000 }
5001
5002 fn update_visible_inline_completion(
5003 &mut self,
5004 window: &mut Window,
5005 cx: &mut Context<Self>,
5006 ) -> Option<()> {
5007 let selection = self.selections.newest_anchor();
5008 let cursor = selection.head();
5009 let multibuffer = self.buffer.read(cx).snapshot(cx);
5010 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5011 let excerpt_id = cursor.excerpt_id;
5012
5013 let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
5014 && (self.context_menu.borrow().is_some()
5015 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5016 if completions_menu_has_precedence
5017 || !offset_selection.is_empty()
5018 || !self.enable_inline_completions
5019 || self
5020 .active_inline_completion
5021 .as_ref()
5022 .map_or(false, |completion| {
5023 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5024 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5025 !invalidation_range.contains(&offset_selection.head())
5026 })
5027 {
5028 self.discard_inline_completion(false, cx);
5029 return None;
5030 }
5031
5032 self.take_active_inline_completion(cx);
5033 let provider = self.inline_completion_provider()?;
5034
5035 let (buffer, cursor_buffer_position) =
5036 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5037
5038 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5039 let edits = inline_completion
5040 .edits
5041 .into_iter()
5042 .flat_map(|(range, new_text)| {
5043 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5044 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5045 Some((start..end, new_text))
5046 })
5047 .collect::<Vec<_>>();
5048 if edits.is_empty() {
5049 return None;
5050 }
5051
5052 let first_edit_start = edits.first().unwrap().0.start;
5053 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5054 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5055
5056 let last_edit_end = edits.last().unwrap().0.end;
5057 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5058 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5059
5060 let cursor_row = cursor.to_point(&multibuffer).row;
5061
5062 let mut inlay_ids = Vec::new();
5063 let invalidation_row_range;
5064 let completion = if cursor_row < edit_start_row {
5065 invalidation_row_range = cursor_row..edit_end_row;
5066 InlineCompletion::Move(first_edit_start)
5067 } else if cursor_row > edit_end_row {
5068 invalidation_row_range = edit_start_row..cursor_row;
5069 InlineCompletion::Move(first_edit_start)
5070 } else {
5071 if edits
5072 .iter()
5073 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5074 {
5075 let mut inlays = Vec::new();
5076 for (range, new_text) in &edits {
5077 let inlay = Inlay::inline_completion(
5078 post_inc(&mut self.next_inlay_id),
5079 range.start,
5080 new_text.as_str(),
5081 );
5082 inlay_ids.push(inlay.id);
5083 inlays.push(inlay);
5084 }
5085
5086 self.splice_inlays(vec![], inlays, cx);
5087 } else {
5088 let background_color = cx.theme().status().deleted_background;
5089 self.highlight_text::<InlineCompletionHighlight>(
5090 edits.iter().map(|(range, _)| range.clone()).collect(),
5091 HighlightStyle {
5092 background_color: Some(background_color),
5093 ..Default::default()
5094 },
5095 cx,
5096 );
5097 }
5098
5099 invalidation_row_range = edit_start_row..edit_end_row;
5100
5101 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5102 if provider.show_tab_accept_marker()
5103 && first_edit_start_point.row == last_edit_end_point.row
5104 && !edits.iter().any(|(_, edit)| edit.contains('\n'))
5105 {
5106 EditDisplayMode::TabAccept
5107 } else {
5108 EditDisplayMode::Inline
5109 }
5110 } else {
5111 EditDisplayMode::DiffPopover
5112 };
5113
5114 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5115
5116 InlineCompletion::Edit {
5117 edits,
5118 edit_preview: inline_completion.edit_preview,
5119 display_mode,
5120 snapshot,
5121 }
5122 };
5123
5124 let invalidation_range = multibuffer
5125 .anchor_before(Point::new(invalidation_row_range.start, 0))
5126 ..multibuffer.anchor_after(Point::new(
5127 invalidation_row_range.end,
5128 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5129 ));
5130
5131 self.active_inline_completion = Some(InlineCompletionState {
5132 inlay_ids,
5133 completion,
5134 invalidation_range,
5135 });
5136
5137 if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
5138 if let Some(hint) = self.inline_completion_menu_hint(window, cx) {
5139 match self.context_menu.borrow_mut().as_mut() {
5140 Some(CodeContextMenu::Completions(menu)) => {
5141 menu.show_inline_completion_hint(hint);
5142 }
5143 _ => {}
5144 }
5145 }
5146 }
5147
5148 cx.notify();
5149
5150 Some(())
5151 }
5152
5153 fn inline_completion_menu_hint(
5154 &self,
5155 window: &mut Window,
5156 cx: &mut Context<Self>,
5157 ) -> Option<InlineCompletionMenuHint> {
5158 let provider = self.inline_completion_provider()?;
5159 if self.has_active_inline_completion() {
5160 let editor_snapshot = self.snapshot(window, cx);
5161
5162 let text = match &self.active_inline_completion.as_ref()?.completion {
5163 InlineCompletion::Edit {
5164 edits,
5165 edit_preview,
5166 display_mode: _,
5167 snapshot,
5168 } => edit_preview
5169 .as_ref()
5170 .and_then(|edit_preview| {
5171 inline_completion_edit_text(&snapshot, &edits, edit_preview, true, cx)
5172 })
5173 .map(InlineCompletionText::Edit),
5174 InlineCompletion::Move(target) => {
5175 let target_point =
5176 target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
5177 let target_line = target_point.row + 1;
5178 Some(InlineCompletionText::Move(
5179 format!("Jump to edit in line {}", target_line).into(),
5180 ))
5181 }
5182 };
5183
5184 Some(InlineCompletionMenuHint::Loaded { text: text? })
5185 } else if provider.is_refreshing(cx) {
5186 Some(InlineCompletionMenuHint::Loading)
5187 } else if provider.needs_terms_acceptance(cx) {
5188 Some(InlineCompletionMenuHint::PendingTermsAcceptance)
5189 } else {
5190 Some(InlineCompletionMenuHint::None)
5191 }
5192 }
5193
5194 pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5195 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5196 }
5197
5198 fn show_inline_completions_in_menu(&self, cx: &App) -> bool {
5199 let by_provider = matches!(
5200 self.menu_inline_completions_policy,
5201 MenuInlineCompletionsPolicy::ByProvider
5202 );
5203
5204 by_provider
5205 && EditorSettings::get_global(cx).show_inline_completions_in_menu
5206 && self
5207 .inline_completion_provider()
5208 .map_or(false, |provider| provider.show_completions_in_menu())
5209 }
5210
5211 fn render_code_actions_indicator(
5212 &self,
5213 _style: &EditorStyle,
5214 row: DisplayRow,
5215 is_active: bool,
5216 cx: &mut Context<Self>,
5217 ) -> Option<IconButton> {
5218 if self.available_code_actions.is_some() {
5219 Some(
5220 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5221 .shape(ui::IconButtonShape::Square)
5222 .icon_size(IconSize::XSmall)
5223 .icon_color(Color::Muted)
5224 .toggle_state(is_active)
5225 .tooltip({
5226 let focus_handle = self.focus_handle.clone();
5227 move |window, cx| {
5228 Tooltip::for_action_in(
5229 "Toggle Code Actions",
5230 &ToggleCodeActions {
5231 deployed_from_indicator: None,
5232 },
5233 &focus_handle,
5234 window,
5235 cx,
5236 )
5237 }
5238 })
5239 .on_click(cx.listener(move |editor, _e, window, cx| {
5240 window.focus(&editor.focus_handle(cx));
5241 editor.toggle_code_actions(
5242 &ToggleCodeActions {
5243 deployed_from_indicator: Some(row),
5244 },
5245 window,
5246 cx,
5247 );
5248 })),
5249 )
5250 } else {
5251 None
5252 }
5253 }
5254
5255 fn clear_tasks(&mut self) {
5256 self.tasks.clear()
5257 }
5258
5259 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5260 if self.tasks.insert(key, value).is_some() {
5261 // This case should hopefully be rare, but just in case...
5262 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5263 }
5264 }
5265
5266 fn build_tasks_context(
5267 project: &Entity<Project>,
5268 buffer: &Entity<Buffer>,
5269 buffer_row: u32,
5270 tasks: &Arc<RunnableTasks>,
5271 cx: &mut Context<Self>,
5272 ) -> Task<Option<task::TaskContext>> {
5273 let position = Point::new(buffer_row, tasks.column);
5274 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5275 let location = Location {
5276 buffer: buffer.clone(),
5277 range: range_start..range_start,
5278 };
5279 // Fill in the environmental variables from the tree-sitter captures
5280 let mut captured_task_variables = TaskVariables::default();
5281 for (capture_name, value) in tasks.extra_variables.clone() {
5282 captured_task_variables.insert(
5283 task::VariableName::Custom(capture_name.into()),
5284 value.clone(),
5285 );
5286 }
5287 project.update(cx, |project, cx| {
5288 project.task_store().update(cx, |task_store, cx| {
5289 task_store.task_context_for_location(captured_task_variables, location, cx)
5290 })
5291 })
5292 }
5293
5294 pub fn spawn_nearest_task(
5295 &mut self,
5296 action: &SpawnNearestTask,
5297 window: &mut Window,
5298 cx: &mut Context<Self>,
5299 ) {
5300 let Some((workspace, _)) = self.workspace.clone() else {
5301 return;
5302 };
5303 let Some(project) = self.project.clone() else {
5304 return;
5305 };
5306
5307 // Try to find a closest, enclosing node using tree-sitter that has a
5308 // task
5309 let Some((buffer, buffer_row, tasks)) = self
5310 .find_enclosing_node_task(cx)
5311 // Or find the task that's closest in row-distance.
5312 .or_else(|| self.find_closest_task(cx))
5313 else {
5314 return;
5315 };
5316
5317 let reveal_strategy = action.reveal;
5318 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5319 cx.spawn_in(window, |_, mut cx| async move {
5320 let context = task_context.await?;
5321 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5322
5323 let resolved = resolved_task.resolved.as_mut()?;
5324 resolved.reveal = reveal_strategy;
5325
5326 workspace
5327 .update(&mut cx, |workspace, cx| {
5328 workspace::tasks::schedule_resolved_task(
5329 workspace,
5330 task_source_kind,
5331 resolved_task,
5332 false,
5333 cx,
5334 );
5335 })
5336 .ok()
5337 })
5338 .detach();
5339 }
5340
5341 fn find_closest_task(
5342 &mut self,
5343 cx: &mut Context<Self>,
5344 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5345 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5346
5347 let ((buffer_id, row), tasks) = self
5348 .tasks
5349 .iter()
5350 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5351
5352 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5353 let tasks = Arc::new(tasks.to_owned());
5354 Some((buffer, *row, tasks))
5355 }
5356
5357 fn find_enclosing_node_task(
5358 &mut self,
5359 cx: &mut Context<Self>,
5360 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5361 let snapshot = self.buffer.read(cx).snapshot(cx);
5362 let offset = self.selections.newest::<usize>(cx).head();
5363 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5364 let buffer_id = excerpt.buffer().remote_id();
5365
5366 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5367 let mut cursor = layer.node().walk();
5368
5369 while cursor.goto_first_child_for_byte(offset).is_some() {
5370 if cursor.node().end_byte() == offset {
5371 cursor.goto_next_sibling();
5372 }
5373 }
5374
5375 // Ascend to the smallest ancestor that contains the range and has a task.
5376 loop {
5377 let node = cursor.node();
5378 let node_range = node.byte_range();
5379 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5380
5381 // Check if this node contains our offset
5382 if node_range.start <= offset && node_range.end >= offset {
5383 // If it contains offset, check for task
5384 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5385 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5386 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5387 }
5388 }
5389
5390 if !cursor.goto_parent() {
5391 break;
5392 }
5393 }
5394 None
5395 }
5396
5397 fn render_run_indicator(
5398 &self,
5399 _style: &EditorStyle,
5400 is_active: bool,
5401 row: DisplayRow,
5402 cx: &mut Context<Self>,
5403 ) -> IconButton {
5404 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5405 .shape(ui::IconButtonShape::Square)
5406 .icon_size(IconSize::XSmall)
5407 .icon_color(Color::Muted)
5408 .toggle_state(is_active)
5409 .on_click(cx.listener(move |editor, _e, window, cx| {
5410 window.focus(&editor.focus_handle(cx));
5411 editor.toggle_code_actions(
5412 &ToggleCodeActions {
5413 deployed_from_indicator: Some(row),
5414 },
5415 window,
5416 cx,
5417 );
5418 }))
5419 }
5420
5421 #[cfg(any(test, feature = "test-support"))]
5422 pub fn context_menu_visible(&self) -> bool {
5423 self.context_menu
5424 .borrow()
5425 .as_ref()
5426 .map_or(false, |menu| menu.visible())
5427 }
5428
5429 #[cfg(feature = "test-support")]
5430 pub fn context_menu_contains_inline_completion(&self) -> bool {
5431 self.context_menu
5432 .borrow()
5433 .as_ref()
5434 .map_or(false, |menu| match menu {
5435 CodeContextMenu::Completions(menu) => {
5436 menu.entries.borrow().first().map_or(false, |entry| {
5437 matches!(entry, CompletionEntry::InlineCompletionHint(_))
5438 })
5439 }
5440 CodeContextMenu::CodeActions(_) => false,
5441 })
5442 }
5443
5444 fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
5445 self.context_menu
5446 .borrow()
5447 .as_ref()
5448 .map(|menu| menu.origin(cursor_position))
5449 }
5450
5451 fn render_context_menu(
5452 &self,
5453 style: &EditorStyle,
5454 max_height_in_lines: u32,
5455 y_flipped: bool,
5456 window: &mut Window,
5457 cx: &mut Context<Editor>,
5458 ) -> Option<AnyElement> {
5459 self.context_menu.borrow().as_ref().and_then(|menu| {
5460 if menu.visible() {
5461 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
5462 } else {
5463 None
5464 }
5465 })
5466 }
5467
5468 fn render_context_menu_aside(
5469 &self,
5470 style: &EditorStyle,
5471 max_size: Size<Pixels>,
5472 cx: &mut Context<Editor>,
5473 ) -> Option<AnyElement> {
5474 self.context_menu.borrow().as_ref().and_then(|menu| {
5475 if menu.visible() {
5476 menu.render_aside(
5477 style,
5478 max_size,
5479 self.workspace.as_ref().map(|(w, _)| w.clone()),
5480 cx,
5481 )
5482 } else {
5483 None
5484 }
5485 })
5486 }
5487
5488 fn hide_context_menu(
5489 &mut self,
5490 window: &mut Window,
5491 cx: &mut Context<Self>,
5492 ) -> Option<CodeContextMenu> {
5493 cx.notify();
5494 self.completion_tasks.clear();
5495 let context_menu = self.context_menu.borrow_mut().take();
5496 if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
5497 self.update_visible_inline_completion(window, cx);
5498 }
5499 context_menu
5500 }
5501
5502 fn show_snippet_choices(
5503 &mut self,
5504 choices: &Vec<String>,
5505 selection: Range<Anchor>,
5506 cx: &mut Context<Self>,
5507 ) {
5508 if selection.start.buffer_id.is_none() {
5509 return;
5510 }
5511 let buffer_id = selection.start.buffer_id.unwrap();
5512 let buffer = self.buffer().read(cx).buffer(buffer_id);
5513 let id = post_inc(&mut self.next_completion_id);
5514
5515 if let Some(buffer) = buffer {
5516 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5517 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5518 ));
5519 }
5520 }
5521
5522 pub fn insert_snippet(
5523 &mut self,
5524 insertion_ranges: &[Range<usize>],
5525 snippet: Snippet,
5526 window: &mut Window,
5527 cx: &mut Context<Self>,
5528 ) -> Result<()> {
5529 struct Tabstop<T> {
5530 is_end_tabstop: bool,
5531 ranges: Vec<Range<T>>,
5532 choices: Option<Vec<String>>,
5533 }
5534
5535 let tabstops = self.buffer.update(cx, |buffer, cx| {
5536 let snippet_text: Arc<str> = snippet.text.clone().into();
5537 buffer.edit(
5538 insertion_ranges
5539 .iter()
5540 .cloned()
5541 .map(|range| (range, snippet_text.clone())),
5542 Some(AutoindentMode::EachLine),
5543 cx,
5544 );
5545
5546 let snapshot = &*buffer.read(cx);
5547 let snippet = &snippet;
5548 snippet
5549 .tabstops
5550 .iter()
5551 .map(|tabstop| {
5552 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5553 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5554 });
5555 let mut tabstop_ranges = tabstop
5556 .ranges
5557 .iter()
5558 .flat_map(|tabstop_range| {
5559 let mut delta = 0_isize;
5560 insertion_ranges.iter().map(move |insertion_range| {
5561 let insertion_start = insertion_range.start as isize + delta;
5562 delta +=
5563 snippet.text.len() as isize - insertion_range.len() as isize;
5564
5565 let start = ((insertion_start + tabstop_range.start) as usize)
5566 .min(snapshot.len());
5567 let end = ((insertion_start + tabstop_range.end) as usize)
5568 .min(snapshot.len());
5569 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5570 })
5571 })
5572 .collect::<Vec<_>>();
5573 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5574
5575 Tabstop {
5576 is_end_tabstop,
5577 ranges: tabstop_ranges,
5578 choices: tabstop.choices.clone(),
5579 }
5580 })
5581 .collect::<Vec<_>>()
5582 });
5583 if let Some(tabstop) = tabstops.first() {
5584 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
5585 s.select_ranges(tabstop.ranges.iter().cloned());
5586 });
5587
5588 if let Some(choices) = &tabstop.choices {
5589 if let Some(selection) = tabstop.ranges.first() {
5590 self.show_snippet_choices(choices, selection.clone(), cx)
5591 }
5592 }
5593
5594 // If we're already at the last tabstop and it's at the end of the snippet,
5595 // we're done, we don't need to keep the state around.
5596 if !tabstop.is_end_tabstop {
5597 let choices = tabstops
5598 .iter()
5599 .map(|tabstop| tabstop.choices.clone())
5600 .collect();
5601
5602 let ranges = tabstops
5603 .into_iter()
5604 .map(|tabstop| tabstop.ranges)
5605 .collect::<Vec<_>>();
5606
5607 self.snippet_stack.push(SnippetState {
5608 active_index: 0,
5609 ranges,
5610 choices,
5611 });
5612 }
5613
5614 // Check whether the just-entered snippet ends with an auto-closable bracket.
5615 if self.autoclose_regions.is_empty() {
5616 let snapshot = self.buffer.read(cx).snapshot(cx);
5617 for selection in &mut self.selections.all::<Point>(cx) {
5618 let selection_head = selection.head();
5619 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5620 continue;
5621 };
5622
5623 let mut bracket_pair = None;
5624 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5625 let prev_chars = snapshot
5626 .reversed_chars_at(selection_head)
5627 .collect::<String>();
5628 for (pair, enabled) in scope.brackets() {
5629 if enabled
5630 && pair.close
5631 && prev_chars.starts_with(pair.start.as_str())
5632 && next_chars.starts_with(pair.end.as_str())
5633 {
5634 bracket_pair = Some(pair.clone());
5635 break;
5636 }
5637 }
5638 if let Some(pair) = bracket_pair {
5639 let start = snapshot.anchor_after(selection_head);
5640 let end = snapshot.anchor_after(selection_head);
5641 self.autoclose_regions.push(AutocloseRegion {
5642 selection_id: selection.id,
5643 range: start..end,
5644 pair,
5645 });
5646 }
5647 }
5648 }
5649 }
5650 Ok(())
5651 }
5652
5653 pub fn move_to_next_snippet_tabstop(
5654 &mut self,
5655 window: &mut Window,
5656 cx: &mut Context<Self>,
5657 ) -> bool {
5658 self.move_to_snippet_tabstop(Bias::Right, window, cx)
5659 }
5660
5661 pub fn move_to_prev_snippet_tabstop(
5662 &mut self,
5663 window: &mut Window,
5664 cx: &mut Context<Self>,
5665 ) -> bool {
5666 self.move_to_snippet_tabstop(Bias::Left, window, cx)
5667 }
5668
5669 pub fn move_to_snippet_tabstop(
5670 &mut self,
5671 bias: Bias,
5672 window: &mut Window,
5673 cx: &mut Context<Self>,
5674 ) -> bool {
5675 if let Some(mut snippet) = self.snippet_stack.pop() {
5676 match bias {
5677 Bias::Left => {
5678 if snippet.active_index > 0 {
5679 snippet.active_index -= 1;
5680 } else {
5681 self.snippet_stack.push(snippet);
5682 return false;
5683 }
5684 }
5685 Bias::Right => {
5686 if snippet.active_index + 1 < snippet.ranges.len() {
5687 snippet.active_index += 1;
5688 } else {
5689 self.snippet_stack.push(snippet);
5690 return false;
5691 }
5692 }
5693 }
5694 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5695 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
5696 s.select_anchor_ranges(current_ranges.iter().cloned())
5697 });
5698
5699 if let Some(choices) = &snippet.choices[snippet.active_index] {
5700 if let Some(selection) = current_ranges.first() {
5701 self.show_snippet_choices(&choices, selection.clone(), cx);
5702 }
5703 }
5704
5705 // If snippet state is not at the last tabstop, push it back on the stack
5706 if snippet.active_index + 1 < snippet.ranges.len() {
5707 self.snippet_stack.push(snippet);
5708 }
5709 return true;
5710 }
5711 }
5712
5713 false
5714 }
5715
5716 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5717 self.transact(window, cx, |this, window, cx| {
5718 this.select_all(&SelectAll, window, cx);
5719 this.insert("", window, cx);
5720 });
5721 }
5722
5723 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
5724 self.transact(window, cx, |this, window, cx| {
5725 this.select_autoclose_pair(window, cx);
5726 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5727 if !this.linked_edit_ranges.is_empty() {
5728 let selections = this.selections.all::<MultiBufferPoint>(cx);
5729 let snapshot = this.buffer.read(cx).snapshot(cx);
5730
5731 for selection in selections.iter() {
5732 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5733 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5734 if selection_start.buffer_id != selection_end.buffer_id {
5735 continue;
5736 }
5737 if let Some(ranges) =
5738 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5739 {
5740 for (buffer, entries) in ranges {
5741 linked_ranges.entry(buffer).or_default().extend(entries);
5742 }
5743 }
5744 }
5745 }
5746
5747 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5748 if !this.selections.line_mode {
5749 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5750 for selection in &mut selections {
5751 if selection.is_empty() {
5752 let old_head = selection.head();
5753 let mut new_head =
5754 movement::left(&display_map, old_head.to_display_point(&display_map))
5755 .to_point(&display_map);
5756 if let Some((buffer, line_buffer_range)) = display_map
5757 .buffer_snapshot
5758 .buffer_line_for_row(MultiBufferRow(old_head.row))
5759 {
5760 let indent_size =
5761 buffer.indent_size_for_line(line_buffer_range.start.row);
5762 let indent_len = match indent_size.kind {
5763 IndentKind::Space => {
5764 buffer.settings_at(line_buffer_range.start, cx).tab_size
5765 }
5766 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5767 };
5768 if old_head.column <= indent_size.len && old_head.column > 0 {
5769 let indent_len = indent_len.get();
5770 new_head = cmp::min(
5771 new_head,
5772 MultiBufferPoint::new(
5773 old_head.row,
5774 ((old_head.column - 1) / indent_len) * indent_len,
5775 ),
5776 );
5777 }
5778 }
5779
5780 selection.set_head(new_head, SelectionGoal::None);
5781 }
5782 }
5783 }
5784
5785 this.signature_help_state.set_backspace_pressed(true);
5786 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
5787 s.select(selections)
5788 });
5789 this.insert("", window, cx);
5790 let empty_str: Arc<str> = Arc::from("");
5791 for (buffer, edits) in linked_ranges {
5792 let snapshot = buffer.read(cx).snapshot();
5793 use text::ToPoint as TP;
5794
5795 let edits = edits
5796 .into_iter()
5797 .map(|range| {
5798 let end_point = TP::to_point(&range.end, &snapshot);
5799 let mut start_point = TP::to_point(&range.start, &snapshot);
5800
5801 if end_point == start_point {
5802 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5803 .saturating_sub(1);
5804 start_point =
5805 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
5806 };
5807
5808 (start_point..end_point, empty_str.clone())
5809 })
5810 .sorted_by_key(|(range, _)| range.start)
5811 .collect::<Vec<_>>();
5812 buffer.update(cx, |this, cx| {
5813 this.edit(edits, None, cx);
5814 })
5815 }
5816 this.refresh_inline_completion(true, false, window, cx);
5817 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
5818 });
5819 }
5820
5821 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
5822 self.transact(window, cx, |this, window, cx| {
5823 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
5824 let line_mode = s.line_mode;
5825 s.move_with(|map, selection| {
5826 if selection.is_empty() && !line_mode {
5827 let cursor = movement::right(map, selection.head());
5828 selection.end = cursor;
5829 selection.reversed = true;
5830 selection.goal = SelectionGoal::None;
5831 }
5832 })
5833 });
5834 this.insert("", window, cx);
5835 this.refresh_inline_completion(true, false, window, cx);
5836 });
5837 }
5838
5839 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
5840 if self.move_to_prev_snippet_tabstop(window, cx) {
5841 return;
5842 }
5843
5844 self.outdent(&Outdent, window, cx);
5845 }
5846
5847 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
5848 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
5849 return;
5850 }
5851
5852 let mut selections = self.selections.all_adjusted(cx);
5853 let buffer = self.buffer.read(cx);
5854 let snapshot = buffer.snapshot(cx);
5855 let rows_iter = selections.iter().map(|s| s.head().row);
5856 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5857
5858 let mut edits = Vec::new();
5859 let mut prev_edited_row = 0;
5860 let mut row_delta = 0;
5861 for selection in &mut selections {
5862 if selection.start.row != prev_edited_row {
5863 row_delta = 0;
5864 }
5865 prev_edited_row = selection.end.row;
5866
5867 // If the selection is non-empty, then increase the indentation of the selected lines.
5868 if !selection.is_empty() {
5869 row_delta =
5870 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5871 continue;
5872 }
5873
5874 // If the selection is empty and the cursor is in the leading whitespace before the
5875 // suggested indentation, then auto-indent the line.
5876 let cursor = selection.head();
5877 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5878 if let Some(suggested_indent) =
5879 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5880 {
5881 if cursor.column < suggested_indent.len
5882 && cursor.column <= current_indent.len
5883 && current_indent.len <= suggested_indent.len
5884 {
5885 selection.start = Point::new(cursor.row, suggested_indent.len);
5886 selection.end = selection.start;
5887 if row_delta == 0 {
5888 edits.extend(Buffer::edit_for_indent_size_adjustment(
5889 cursor.row,
5890 current_indent,
5891 suggested_indent,
5892 ));
5893 row_delta = suggested_indent.len - current_indent.len;
5894 }
5895 continue;
5896 }
5897 }
5898
5899 // Otherwise, insert a hard or soft tab.
5900 let settings = buffer.settings_at(cursor, cx);
5901 let tab_size = if settings.hard_tabs {
5902 IndentSize::tab()
5903 } else {
5904 let tab_size = settings.tab_size.get();
5905 let char_column = snapshot
5906 .text_for_range(Point::new(cursor.row, 0)..cursor)
5907 .flat_map(str::chars)
5908 .count()
5909 + row_delta as usize;
5910 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5911 IndentSize::spaces(chars_to_next_tab_stop)
5912 };
5913 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5914 selection.end = selection.start;
5915 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5916 row_delta += tab_size.len;
5917 }
5918
5919 self.transact(window, cx, |this, window, cx| {
5920 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5921 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
5922 s.select(selections)
5923 });
5924 this.refresh_inline_completion(true, false, window, cx);
5925 });
5926 }
5927
5928 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
5929 if self.read_only(cx) {
5930 return;
5931 }
5932 let mut selections = self.selections.all::<Point>(cx);
5933 let mut prev_edited_row = 0;
5934 let mut row_delta = 0;
5935 let mut edits = Vec::new();
5936 let buffer = self.buffer.read(cx);
5937 let snapshot = buffer.snapshot(cx);
5938 for selection in &mut selections {
5939 if selection.start.row != prev_edited_row {
5940 row_delta = 0;
5941 }
5942 prev_edited_row = selection.end.row;
5943
5944 row_delta =
5945 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5946 }
5947
5948 self.transact(window, cx, |this, window, cx| {
5949 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5950 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
5951 s.select(selections)
5952 });
5953 });
5954 }
5955
5956 fn indent_selection(
5957 buffer: &MultiBuffer,
5958 snapshot: &MultiBufferSnapshot,
5959 selection: &mut Selection<Point>,
5960 edits: &mut Vec<(Range<Point>, String)>,
5961 delta_for_start_row: u32,
5962 cx: &App,
5963 ) -> u32 {
5964 let settings = buffer.settings_at(selection.start, cx);
5965 let tab_size = settings.tab_size.get();
5966 let indent_kind = if settings.hard_tabs {
5967 IndentKind::Tab
5968 } else {
5969 IndentKind::Space
5970 };
5971 let mut start_row = selection.start.row;
5972 let mut end_row = selection.end.row + 1;
5973
5974 // If a selection ends at the beginning of a line, don't indent
5975 // that last line.
5976 if selection.end.column == 0 && selection.end.row > selection.start.row {
5977 end_row -= 1;
5978 }
5979
5980 // Avoid re-indenting a row that has already been indented by a
5981 // previous selection, but still update this selection's column
5982 // to reflect that indentation.
5983 if delta_for_start_row > 0 {
5984 start_row += 1;
5985 selection.start.column += delta_for_start_row;
5986 if selection.end.row == selection.start.row {
5987 selection.end.column += delta_for_start_row;
5988 }
5989 }
5990
5991 let mut delta_for_end_row = 0;
5992 let has_multiple_rows = start_row + 1 != end_row;
5993 for row in start_row..end_row {
5994 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5995 let indent_delta = match (current_indent.kind, indent_kind) {
5996 (IndentKind::Space, IndentKind::Space) => {
5997 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5998 IndentSize::spaces(columns_to_next_tab_stop)
5999 }
6000 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6001 (_, IndentKind::Tab) => IndentSize::tab(),
6002 };
6003
6004 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6005 0
6006 } else {
6007 selection.start.column
6008 };
6009 let row_start = Point::new(row, start);
6010 edits.push((
6011 row_start..row_start,
6012 indent_delta.chars().collect::<String>(),
6013 ));
6014
6015 // Update this selection's endpoints to reflect the indentation.
6016 if row == selection.start.row {
6017 selection.start.column += indent_delta.len;
6018 }
6019 if row == selection.end.row {
6020 selection.end.column += indent_delta.len;
6021 delta_for_end_row = indent_delta.len;
6022 }
6023 }
6024
6025 if selection.start.row == selection.end.row {
6026 delta_for_start_row + delta_for_end_row
6027 } else {
6028 delta_for_end_row
6029 }
6030 }
6031
6032 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6033 if self.read_only(cx) {
6034 return;
6035 }
6036 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6037 let selections = self.selections.all::<Point>(cx);
6038 let mut deletion_ranges = Vec::new();
6039 let mut last_outdent = None;
6040 {
6041 let buffer = self.buffer.read(cx);
6042 let snapshot = buffer.snapshot(cx);
6043 for selection in &selections {
6044 let settings = buffer.settings_at(selection.start, cx);
6045 let tab_size = settings.tab_size.get();
6046 let mut rows = selection.spanned_rows(false, &display_map);
6047
6048 // Avoid re-outdenting a row that has already been outdented by a
6049 // previous selection.
6050 if let Some(last_row) = last_outdent {
6051 if last_row == rows.start {
6052 rows.start = rows.start.next_row();
6053 }
6054 }
6055 let has_multiple_rows = rows.len() > 1;
6056 for row in rows.iter_rows() {
6057 let indent_size = snapshot.indent_size_for_line(row);
6058 if indent_size.len > 0 {
6059 let deletion_len = match indent_size.kind {
6060 IndentKind::Space => {
6061 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6062 if columns_to_prev_tab_stop == 0 {
6063 tab_size
6064 } else {
6065 columns_to_prev_tab_stop
6066 }
6067 }
6068 IndentKind::Tab => 1,
6069 };
6070 let start = if has_multiple_rows
6071 || deletion_len > selection.start.column
6072 || indent_size.len < selection.start.column
6073 {
6074 0
6075 } else {
6076 selection.start.column - deletion_len
6077 };
6078 deletion_ranges.push(
6079 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6080 );
6081 last_outdent = Some(row);
6082 }
6083 }
6084 }
6085 }
6086
6087 self.transact(window, cx, |this, window, cx| {
6088 this.buffer.update(cx, |buffer, cx| {
6089 let empty_str: Arc<str> = Arc::default();
6090 buffer.edit(
6091 deletion_ranges
6092 .into_iter()
6093 .map(|range| (range, empty_str.clone())),
6094 None,
6095 cx,
6096 );
6097 });
6098 let selections = this.selections.all::<usize>(cx);
6099 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6100 s.select(selections)
6101 });
6102 });
6103 }
6104
6105 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6106 if self.read_only(cx) {
6107 return;
6108 }
6109 let selections = self
6110 .selections
6111 .all::<usize>(cx)
6112 .into_iter()
6113 .map(|s| s.range());
6114
6115 self.transact(window, cx, |this, window, cx| {
6116 this.buffer.update(cx, |buffer, cx| {
6117 buffer.autoindent_ranges(selections, cx);
6118 });
6119 let selections = this.selections.all::<usize>(cx);
6120 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6121 s.select(selections)
6122 });
6123 });
6124 }
6125
6126 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6127 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6128 let selections = self.selections.all::<Point>(cx);
6129
6130 let mut new_cursors = Vec::new();
6131 let mut edit_ranges = Vec::new();
6132 let mut selections = selections.iter().peekable();
6133 while let Some(selection) = selections.next() {
6134 let mut rows = selection.spanned_rows(false, &display_map);
6135 let goal_display_column = selection.head().to_display_point(&display_map).column();
6136
6137 // Accumulate contiguous regions of rows that we want to delete.
6138 while let Some(next_selection) = selections.peek() {
6139 let next_rows = next_selection.spanned_rows(false, &display_map);
6140 if next_rows.start <= rows.end {
6141 rows.end = next_rows.end;
6142 selections.next().unwrap();
6143 } else {
6144 break;
6145 }
6146 }
6147
6148 let buffer = &display_map.buffer_snapshot;
6149 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6150 let edit_end;
6151 let cursor_buffer_row;
6152 if buffer.max_point().row >= rows.end.0 {
6153 // If there's a line after the range, delete the \n from the end of the row range
6154 // and position the cursor on the next line.
6155 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6156 cursor_buffer_row = rows.end;
6157 } else {
6158 // If there isn't a line after the range, delete the \n from the line before the
6159 // start of the row range and position the cursor there.
6160 edit_start = edit_start.saturating_sub(1);
6161 edit_end = buffer.len();
6162 cursor_buffer_row = rows.start.previous_row();
6163 }
6164
6165 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6166 *cursor.column_mut() =
6167 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6168
6169 new_cursors.push((
6170 selection.id,
6171 buffer.anchor_after(cursor.to_point(&display_map)),
6172 ));
6173 edit_ranges.push(edit_start..edit_end);
6174 }
6175
6176 self.transact(window, cx, |this, window, cx| {
6177 let buffer = this.buffer.update(cx, |buffer, cx| {
6178 let empty_str: Arc<str> = Arc::default();
6179 buffer.edit(
6180 edit_ranges
6181 .into_iter()
6182 .map(|range| (range, empty_str.clone())),
6183 None,
6184 cx,
6185 );
6186 buffer.snapshot(cx)
6187 });
6188 let new_selections = new_cursors
6189 .into_iter()
6190 .map(|(id, cursor)| {
6191 let cursor = cursor.to_point(&buffer);
6192 Selection {
6193 id,
6194 start: cursor,
6195 end: cursor,
6196 reversed: false,
6197 goal: SelectionGoal::None,
6198 }
6199 })
6200 .collect();
6201
6202 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6203 s.select(new_selections);
6204 });
6205 });
6206 }
6207
6208 pub fn join_lines_impl(
6209 &mut self,
6210 insert_whitespace: bool,
6211 window: &mut Window,
6212 cx: &mut Context<Self>,
6213 ) {
6214 if self.read_only(cx) {
6215 return;
6216 }
6217 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6218 for selection in self.selections.all::<Point>(cx) {
6219 let start = MultiBufferRow(selection.start.row);
6220 // Treat single line selections as if they include the next line. Otherwise this action
6221 // would do nothing for single line selections individual cursors.
6222 let end = if selection.start.row == selection.end.row {
6223 MultiBufferRow(selection.start.row + 1)
6224 } else {
6225 MultiBufferRow(selection.end.row)
6226 };
6227
6228 if let Some(last_row_range) = row_ranges.last_mut() {
6229 if start <= last_row_range.end {
6230 last_row_range.end = end;
6231 continue;
6232 }
6233 }
6234 row_ranges.push(start..end);
6235 }
6236
6237 let snapshot = self.buffer.read(cx).snapshot(cx);
6238 let mut cursor_positions = Vec::new();
6239 for row_range in &row_ranges {
6240 let anchor = snapshot.anchor_before(Point::new(
6241 row_range.end.previous_row().0,
6242 snapshot.line_len(row_range.end.previous_row()),
6243 ));
6244 cursor_positions.push(anchor..anchor);
6245 }
6246
6247 self.transact(window, cx, |this, window, cx| {
6248 for row_range in row_ranges.into_iter().rev() {
6249 for row in row_range.iter_rows().rev() {
6250 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6251 let next_line_row = row.next_row();
6252 let indent = snapshot.indent_size_for_line(next_line_row);
6253 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6254
6255 let replace =
6256 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6257 " "
6258 } else {
6259 ""
6260 };
6261
6262 this.buffer.update(cx, |buffer, cx| {
6263 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6264 });
6265 }
6266 }
6267
6268 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6269 s.select_anchor_ranges(cursor_positions)
6270 });
6271 });
6272 }
6273
6274 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6275 self.join_lines_impl(true, window, cx);
6276 }
6277
6278 pub fn sort_lines_case_sensitive(
6279 &mut self,
6280 _: &SortLinesCaseSensitive,
6281 window: &mut Window,
6282 cx: &mut Context<Self>,
6283 ) {
6284 self.manipulate_lines(window, cx, |lines| lines.sort())
6285 }
6286
6287 pub fn sort_lines_case_insensitive(
6288 &mut self,
6289 _: &SortLinesCaseInsensitive,
6290 window: &mut Window,
6291 cx: &mut Context<Self>,
6292 ) {
6293 self.manipulate_lines(window, cx, |lines| {
6294 lines.sort_by_key(|line| line.to_lowercase())
6295 })
6296 }
6297
6298 pub fn unique_lines_case_insensitive(
6299 &mut self,
6300 _: &UniqueLinesCaseInsensitive,
6301 window: &mut Window,
6302 cx: &mut Context<Self>,
6303 ) {
6304 self.manipulate_lines(window, cx, |lines| {
6305 let mut seen = HashSet::default();
6306 lines.retain(|line| seen.insert(line.to_lowercase()));
6307 })
6308 }
6309
6310 pub fn unique_lines_case_sensitive(
6311 &mut self,
6312 _: &UniqueLinesCaseSensitive,
6313 window: &mut Window,
6314 cx: &mut Context<Self>,
6315 ) {
6316 self.manipulate_lines(window, cx, |lines| {
6317 let mut seen = HashSet::default();
6318 lines.retain(|line| seen.insert(*line));
6319 })
6320 }
6321
6322 pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
6323 let mut revert_changes = HashMap::default();
6324 let snapshot = self.snapshot(window, cx);
6325 for hunk in snapshot
6326 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
6327 {
6328 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6329 }
6330 if !revert_changes.is_empty() {
6331 self.transact(window, cx, |editor, window, cx| {
6332 editor.revert(revert_changes, window, cx);
6333 });
6334 }
6335 }
6336
6337 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
6338 let Some(project) = self.project.clone() else {
6339 return;
6340 };
6341 self.reload(project, window, cx)
6342 .detach_and_notify_err(window, cx);
6343 }
6344
6345 pub fn revert_selected_hunks(
6346 &mut self,
6347 _: &RevertSelectedHunks,
6348 window: &mut Window,
6349 cx: &mut Context<Self>,
6350 ) {
6351 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
6352 self.revert_hunks_in_ranges(selections, window, cx);
6353 }
6354
6355 fn revert_hunks_in_ranges(
6356 &mut self,
6357 ranges: impl Iterator<Item = Range<Point>>,
6358 window: &mut Window,
6359 cx: &mut Context<Editor>,
6360 ) {
6361 let mut revert_changes = HashMap::default();
6362 let snapshot = self.snapshot(window, cx);
6363 for hunk in &snapshot.hunks_for_ranges(ranges) {
6364 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6365 }
6366 if !revert_changes.is_empty() {
6367 self.transact(window, cx, |editor, window, cx| {
6368 editor.revert(revert_changes, window, cx);
6369 });
6370 }
6371 }
6372
6373 pub fn open_active_item_in_terminal(
6374 &mut self,
6375 _: &OpenInTerminal,
6376 window: &mut Window,
6377 cx: &mut Context<Self>,
6378 ) {
6379 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6380 let project_path = buffer.read(cx).project_path(cx)?;
6381 let project = self.project.as_ref()?.read(cx);
6382 let entry = project.entry_for_path(&project_path, cx)?;
6383 let parent = match &entry.canonical_path {
6384 Some(canonical_path) => canonical_path.to_path_buf(),
6385 None => project.absolute_path(&project_path, cx)?,
6386 }
6387 .parent()?
6388 .to_path_buf();
6389 Some(parent)
6390 }) {
6391 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
6392 }
6393 }
6394
6395 pub fn prepare_revert_change(
6396 &self,
6397 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6398 hunk: &MultiBufferDiffHunk,
6399 cx: &mut App,
6400 ) -> Option<()> {
6401 let buffer = self.buffer.read(cx);
6402 let change_set = buffer.change_set_for(hunk.buffer_id)?;
6403 let buffer = buffer.buffer(hunk.buffer_id)?;
6404 let buffer = buffer.read(cx);
6405 let original_text = change_set
6406 .read(cx)
6407 .base_text
6408 .as_ref()?
6409 .as_rope()
6410 .slice(hunk.diff_base_byte_range.clone());
6411 let buffer_snapshot = buffer.snapshot();
6412 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6413 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6414 probe
6415 .0
6416 .start
6417 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6418 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6419 }) {
6420 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6421 Some(())
6422 } else {
6423 None
6424 }
6425 }
6426
6427 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
6428 self.manipulate_lines(window, cx, |lines| lines.reverse())
6429 }
6430
6431 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
6432 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
6433 }
6434
6435 fn manipulate_lines<Fn>(
6436 &mut self,
6437 window: &mut Window,
6438 cx: &mut Context<Self>,
6439 mut callback: Fn,
6440 ) where
6441 Fn: FnMut(&mut Vec<&str>),
6442 {
6443 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6444 let buffer = self.buffer.read(cx).snapshot(cx);
6445
6446 let mut edits = Vec::new();
6447
6448 let selections = self.selections.all::<Point>(cx);
6449 let mut selections = selections.iter().peekable();
6450 let mut contiguous_row_selections = Vec::new();
6451 let mut new_selections = Vec::new();
6452 let mut added_lines = 0;
6453 let mut removed_lines = 0;
6454
6455 while let Some(selection) = selections.next() {
6456 let (start_row, end_row) = consume_contiguous_rows(
6457 &mut contiguous_row_selections,
6458 selection,
6459 &display_map,
6460 &mut selections,
6461 );
6462
6463 let start_point = Point::new(start_row.0, 0);
6464 let end_point = Point::new(
6465 end_row.previous_row().0,
6466 buffer.line_len(end_row.previous_row()),
6467 );
6468 let text = buffer
6469 .text_for_range(start_point..end_point)
6470 .collect::<String>();
6471
6472 let mut lines = text.split('\n').collect_vec();
6473
6474 let lines_before = lines.len();
6475 callback(&mut lines);
6476 let lines_after = lines.len();
6477
6478 edits.push((start_point..end_point, lines.join("\n")));
6479
6480 // Selections must change based on added and removed line count
6481 let start_row =
6482 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6483 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6484 new_selections.push(Selection {
6485 id: selection.id,
6486 start: start_row,
6487 end: end_row,
6488 goal: SelectionGoal::None,
6489 reversed: selection.reversed,
6490 });
6491
6492 if lines_after > lines_before {
6493 added_lines += lines_after - lines_before;
6494 } else if lines_before > lines_after {
6495 removed_lines += lines_before - lines_after;
6496 }
6497 }
6498
6499 self.transact(window, cx, |this, window, cx| {
6500 let buffer = this.buffer.update(cx, |buffer, cx| {
6501 buffer.edit(edits, None, cx);
6502 buffer.snapshot(cx)
6503 });
6504
6505 // Recalculate offsets on newly edited buffer
6506 let new_selections = new_selections
6507 .iter()
6508 .map(|s| {
6509 let start_point = Point::new(s.start.0, 0);
6510 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6511 Selection {
6512 id: s.id,
6513 start: buffer.point_to_offset(start_point),
6514 end: buffer.point_to_offset(end_point),
6515 goal: s.goal,
6516 reversed: s.reversed,
6517 }
6518 })
6519 .collect();
6520
6521 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6522 s.select(new_selections);
6523 });
6524
6525 this.request_autoscroll(Autoscroll::fit(), cx);
6526 });
6527 }
6528
6529 pub fn convert_to_upper_case(
6530 &mut self,
6531 _: &ConvertToUpperCase,
6532 window: &mut Window,
6533 cx: &mut Context<Self>,
6534 ) {
6535 self.manipulate_text(window, cx, |text| text.to_uppercase())
6536 }
6537
6538 pub fn convert_to_lower_case(
6539 &mut self,
6540 _: &ConvertToLowerCase,
6541 window: &mut Window,
6542 cx: &mut Context<Self>,
6543 ) {
6544 self.manipulate_text(window, cx, |text| text.to_lowercase())
6545 }
6546
6547 pub fn convert_to_title_case(
6548 &mut self,
6549 _: &ConvertToTitleCase,
6550 window: &mut Window,
6551 cx: &mut Context<Self>,
6552 ) {
6553 self.manipulate_text(window, cx, |text| {
6554 text.split('\n')
6555 .map(|line| line.to_case(Case::Title))
6556 .join("\n")
6557 })
6558 }
6559
6560 pub fn convert_to_snake_case(
6561 &mut self,
6562 _: &ConvertToSnakeCase,
6563 window: &mut Window,
6564 cx: &mut Context<Self>,
6565 ) {
6566 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
6567 }
6568
6569 pub fn convert_to_kebab_case(
6570 &mut self,
6571 _: &ConvertToKebabCase,
6572 window: &mut Window,
6573 cx: &mut Context<Self>,
6574 ) {
6575 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
6576 }
6577
6578 pub fn convert_to_upper_camel_case(
6579 &mut self,
6580 _: &ConvertToUpperCamelCase,
6581 window: &mut Window,
6582 cx: &mut Context<Self>,
6583 ) {
6584 self.manipulate_text(window, cx, |text| {
6585 text.split('\n')
6586 .map(|line| line.to_case(Case::UpperCamel))
6587 .join("\n")
6588 })
6589 }
6590
6591 pub fn convert_to_lower_camel_case(
6592 &mut self,
6593 _: &ConvertToLowerCamelCase,
6594 window: &mut Window,
6595 cx: &mut Context<Self>,
6596 ) {
6597 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
6598 }
6599
6600 pub fn convert_to_opposite_case(
6601 &mut self,
6602 _: &ConvertToOppositeCase,
6603 window: &mut Window,
6604 cx: &mut Context<Self>,
6605 ) {
6606 self.manipulate_text(window, cx, |text| {
6607 text.chars()
6608 .fold(String::with_capacity(text.len()), |mut t, c| {
6609 if c.is_uppercase() {
6610 t.extend(c.to_lowercase());
6611 } else {
6612 t.extend(c.to_uppercase());
6613 }
6614 t
6615 })
6616 })
6617 }
6618
6619 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
6620 where
6621 Fn: FnMut(&str) -> String,
6622 {
6623 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6624 let buffer = self.buffer.read(cx).snapshot(cx);
6625
6626 let mut new_selections = Vec::new();
6627 let mut edits = Vec::new();
6628 let mut selection_adjustment = 0i32;
6629
6630 for selection in self.selections.all::<usize>(cx) {
6631 let selection_is_empty = selection.is_empty();
6632
6633 let (start, end) = if selection_is_empty {
6634 let word_range = movement::surrounding_word(
6635 &display_map,
6636 selection.start.to_display_point(&display_map),
6637 );
6638 let start = word_range.start.to_offset(&display_map, Bias::Left);
6639 let end = word_range.end.to_offset(&display_map, Bias::Left);
6640 (start, end)
6641 } else {
6642 (selection.start, selection.end)
6643 };
6644
6645 let text = buffer.text_for_range(start..end).collect::<String>();
6646 let old_length = text.len() as i32;
6647 let text = callback(&text);
6648
6649 new_selections.push(Selection {
6650 start: (start as i32 - selection_adjustment) as usize,
6651 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6652 goal: SelectionGoal::None,
6653 ..selection
6654 });
6655
6656 selection_adjustment += old_length - text.len() as i32;
6657
6658 edits.push((start..end, text));
6659 }
6660
6661 self.transact(window, cx, |this, window, cx| {
6662 this.buffer.update(cx, |buffer, cx| {
6663 buffer.edit(edits, None, cx);
6664 });
6665
6666 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6667 s.select(new_selections);
6668 });
6669
6670 this.request_autoscroll(Autoscroll::fit(), cx);
6671 });
6672 }
6673
6674 pub fn duplicate(
6675 &mut self,
6676 upwards: bool,
6677 whole_lines: bool,
6678 window: &mut Window,
6679 cx: &mut Context<Self>,
6680 ) {
6681 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6682 let buffer = &display_map.buffer_snapshot;
6683 let selections = self.selections.all::<Point>(cx);
6684
6685 let mut edits = Vec::new();
6686 let mut selections_iter = selections.iter().peekable();
6687 while let Some(selection) = selections_iter.next() {
6688 let mut rows = selection.spanned_rows(false, &display_map);
6689 // duplicate line-wise
6690 if whole_lines || selection.start == selection.end {
6691 // Avoid duplicating the same lines twice.
6692 while let Some(next_selection) = selections_iter.peek() {
6693 let next_rows = next_selection.spanned_rows(false, &display_map);
6694 if next_rows.start < rows.end {
6695 rows.end = next_rows.end;
6696 selections_iter.next().unwrap();
6697 } else {
6698 break;
6699 }
6700 }
6701
6702 // Copy the text from the selected row region and splice it either at the start
6703 // or end of the region.
6704 let start = Point::new(rows.start.0, 0);
6705 let end = Point::new(
6706 rows.end.previous_row().0,
6707 buffer.line_len(rows.end.previous_row()),
6708 );
6709 let text = buffer
6710 .text_for_range(start..end)
6711 .chain(Some("\n"))
6712 .collect::<String>();
6713 let insert_location = if upwards {
6714 Point::new(rows.end.0, 0)
6715 } else {
6716 start
6717 };
6718 edits.push((insert_location..insert_location, text));
6719 } else {
6720 // duplicate character-wise
6721 let start = selection.start;
6722 let end = selection.end;
6723 let text = buffer.text_for_range(start..end).collect::<String>();
6724 edits.push((selection.end..selection.end, text));
6725 }
6726 }
6727
6728 self.transact(window, cx, |this, _, cx| {
6729 this.buffer.update(cx, |buffer, cx| {
6730 buffer.edit(edits, None, cx);
6731 });
6732
6733 this.request_autoscroll(Autoscroll::fit(), cx);
6734 });
6735 }
6736
6737 pub fn duplicate_line_up(
6738 &mut self,
6739 _: &DuplicateLineUp,
6740 window: &mut Window,
6741 cx: &mut Context<Self>,
6742 ) {
6743 self.duplicate(true, true, window, cx);
6744 }
6745
6746 pub fn duplicate_line_down(
6747 &mut self,
6748 _: &DuplicateLineDown,
6749 window: &mut Window,
6750 cx: &mut Context<Self>,
6751 ) {
6752 self.duplicate(false, true, window, cx);
6753 }
6754
6755 pub fn duplicate_selection(
6756 &mut self,
6757 _: &DuplicateSelection,
6758 window: &mut Window,
6759 cx: &mut Context<Self>,
6760 ) {
6761 self.duplicate(false, false, window, cx);
6762 }
6763
6764 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
6765 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6766 let buffer = self.buffer.read(cx).snapshot(cx);
6767
6768 let mut edits = Vec::new();
6769 let mut unfold_ranges = Vec::new();
6770 let mut refold_creases = Vec::new();
6771
6772 let selections = self.selections.all::<Point>(cx);
6773 let mut selections = selections.iter().peekable();
6774 let mut contiguous_row_selections = Vec::new();
6775 let mut new_selections = Vec::new();
6776
6777 while let Some(selection) = selections.next() {
6778 // Find all the selections that span a contiguous row range
6779 let (start_row, end_row) = consume_contiguous_rows(
6780 &mut contiguous_row_selections,
6781 selection,
6782 &display_map,
6783 &mut selections,
6784 );
6785
6786 // Move the text spanned by the row range to be before the line preceding the row range
6787 if start_row.0 > 0 {
6788 let range_to_move = Point::new(
6789 start_row.previous_row().0,
6790 buffer.line_len(start_row.previous_row()),
6791 )
6792 ..Point::new(
6793 end_row.previous_row().0,
6794 buffer.line_len(end_row.previous_row()),
6795 );
6796 let insertion_point = display_map
6797 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6798 .0;
6799
6800 // Don't move lines across excerpts
6801 if buffer
6802 .excerpt_containing(insertion_point..range_to_move.end)
6803 .is_some()
6804 {
6805 let text = buffer
6806 .text_for_range(range_to_move.clone())
6807 .flat_map(|s| s.chars())
6808 .skip(1)
6809 .chain(['\n'])
6810 .collect::<String>();
6811
6812 edits.push((
6813 buffer.anchor_after(range_to_move.start)
6814 ..buffer.anchor_before(range_to_move.end),
6815 String::new(),
6816 ));
6817 let insertion_anchor = buffer.anchor_after(insertion_point);
6818 edits.push((insertion_anchor..insertion_anchor, text));
6819
6820 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6821
6822 // Move selections up
6823 new_selections.extend(contiguous_row_selections.drain(..).map(
6824 |mut selection| {
6825 selection.start.row -= row_delta;
6826 selection.end.row -= row_delta;
6827 selection
6828 },
6829 ));
6830
6831 // Move folds up
6832 unfold_ranges.push(range_to_move.clone());
6833 for fold in display_map.folds_in_range(
6834 buffer.anchor_before(range_to_move.start)
6835 ..buffer.anchor_after(range_to_move.end),
6836 ) {
6837 let mut start = fold.range.start.to_point(&buffer);
6838 let mut end = fold.range.end.to_point(&buffer);
6839 start.row -= row_delta;
6840 end.row -= row_delta;
6841 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6842 }
6843 }
6844 }
6845
6846 // If we didn't move line(s), preserve the existing selections
6847 new_selections.append(&mut contiguous_row_selections);
6848 }
6849
6850 self.transact(window, cx, |this, window, cx| {
6851 this.unfold_ranges(&unfold_ranges, true, true, cx);
6852 this.buffer.update(cx, |buffer, cx| {
6853 for (range, text) in edits {
6854 buffer.edit([(range, text)], None, cx);
6855 }
6856 });
6857 this.fold_creases(refold_creases, true, window, cx);
6858 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6859 s.select(new_selections);
6860 })
6861 });
6862 }
6863
6864 pub fn move_line_down(
6865 &mut self,
6866 _: &MoveLineDown,
6867 window: &mut Window,
6868 cx: &mut Context<Self>,
6869 ) {
6870 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6871 let buffer = self.buffer.read(cx).snapshot(cx);
6872
6873 let mut edits = Vec::new();
6874 let mut unfold_ranges = Vec::new();
6875 let mut refold_creases = Vec::new();
6876
6877 let selections = self.selections.all::<Point>(cx);
6878 let mut selections = selections.iter().peekable();
6879 let mut contiguous_row_selections = Vec::new();
6880 let mut new_selections = Vec::new();
6881
6882 while let Some(selection) = selections.next() {
6883 // Find all the selections that span a contiguous row range
6884 let (start_row, end_row) = consume_contiguous_rows(
6885 &mut contiguous_row_selections,
6886 selection,
6887 &display_map,
6888 &mut selections,
6889 );
6890
6891 // Move the text spanned by the row range to be after the last line of the row range
6892 if end_row.0 <= buffer.max_point().row {
6893 let range_to_move =
6894 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6895 let insertion_point = display_map
6896 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6897 .0;
6898
6899 // Don't move lines across excerpt boundaries
6900 if buffer
6901 .excerpt_containing(range_to_move.start..insertion_point)
6902 .is_some()
6903 {
6904 let mut text = String::from("\n");
6905 text.extend(buffer.text_for_range(range_to_move.clone()));
6906 text.pop(); // Drop trailing newline
6907 edits.push((
6908 buffer.anchor_after(range_to_move.start)
6909 ..buffer.anchor_before(range_to_move.end),
6910 String::new(),
6911 ));
6912 let insertion_anchor = buffer.anchor_after(insertion_point);
6913 edits.push((insertion_anchor..insertion_anchor, text));
6914
6915 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6916
6917 // Move selections down
6918 new_selections.extend(contiguous_row_selections.drain(..).map(
6919 |mut selection| {
6920 selection.start.row += row_delta;
6921 selection.end.row += row_delta;
6922 selection
6923 },
6924 ));
6925
6926 // Move folds down
6927 unfold_ranges.push(range_to_move.clone());
6928 for fold in display_map.folds_in_range(
6929 buffer.anchor_before(range_to_move.start)
6930 ..buffer.anchor_after(range_to_move.end),
6931 ) {
6932 let mut start = fold.range.start.to_point(&buffer);
6933 let mut end = fold.range.end.to_point(&buffer);
6934 start.row += row_delta;
6935 end.row += row_delta;
6936 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6937 }
6938 }
6939 }
6940
6941 // If we didn't move line(s), preserve the existing selections
6942 new_selections.append(&mut contiguous_row_selections);
6943 }
6944
6945 self.transact(window, cx, |this, window, cx| {
6946 this.unfold_ranges(&unfold_ranges, true, true, cx);
6947 this.buffer.update(cx, |buffer, cx| {
6948 for (range, text) in edits {
6949 buffer.edit([(range, text)], None, cx);
6950 }
6951 });
6952 this.fold_creases(refold_creases, true, window, cx);
6953 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6954 s.select(new_selections)
6955 });
6956 });
6957 }
6958
6959 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
6960 let text_layout_details = &self.text_layout_details(window);
6961 self.transact(window, cx, |this, window, cx| {
6962 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6963 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6964 let line_mode = s.line_mode;
6965 s.move_with(|display_map, selection| {
6966 if !selection.is_empty() || line_mode {
6967 return;
6968 }
6969
6970 let mut head = selection.head();
6971 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6972 if head.column() == display_map.line_len(head.row()) {
6973 transpose_offset = display_map
6974 .buffer_snapshot
6975 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6976 }
6977
6978 if transpose_offset == 0 {
6979 return;
6980 }
6981
6982 *head.column_mut() += 1;
6983 head = display_map.clip_point(head, Bias::Right);
6984 let goal = SelectionGoal::HorizontalPosition(
6985 display_map
6986 .x_for_display_point(head, text_layout_details)
6987 .into(),
6988 );
6989 selection.collapse_to(head, goal);
6990
6991 let transpose_start = display_map
6992 .buffer_snapshot
6993 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6994 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6995 let transpose_end = display_map
6996 .buffer_snapshot
6997 .clip_offset(transpose_offset + 1, Bias::Right);
6998 if let Some(ch) =
6999 display_map.buffer_snapshot.chars_at(transpose_start).next()
7000 {
7001 edits.push((transpose_start..transpose_offset, String::new()));
7002 edits.push((transpose_end..transpose_end, ch.to_string()));
7003 }
7004 }
7005 });
7006 edits
7007 });
7008 this.buffer
7009 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7010 let selections = this.selections.all::<usize>(cx);
7011 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7012 s.select(selections);
7013 });
7014 });
7015 }
7016
7017 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7018 self.rewrap_impl(IsVimMode::No, cx)
7019 }
7020
7021 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7022 let buffer = self.buffer.read(cx).snapshot(cx);
7023 let selections = self.selections.all::<Point>(cx);
7024 let mut selections = selections.iter().peekable();
7025
7026 let mut edits = Vec::new();
7027 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7028
7029 while let Some(selection) = selections.next() {
7030 let mut start_row = selection.start.row;
7031 let mut end_row = selection.end.row;
7032
7033 // Skip selections that overlap with a range that has already been rewrapped.
7034 let selection_range = start_row..end_row;
7035 if rewrapped_row_ranges
7036 .iter()
7037 .any(|range| range.overlaps(&selection_range))
7038 {
7039 continue;
7040 }
7041
7042 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7043
7044 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7045 match language_scope.language_name().as_ref() {
7046 "Markdown" | "Plain Text" => {
7047 should_rewrap = true;
7048 }
7049 _ => {}
7050 }
7051 }
7052
7053 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7054
7055 // Since not all lines in the selection may be at the same indent
7056 // level, choose the indent size that is the most common between all
7057 // of the lines.
7058 //
7059 // If there is a tie, we use the deepest indent.
7060 let (indent_size, indent_end) = {
7061 let mut indent_size_occurrences = HashMap::default();
7062 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7063
7064 for row in start_row..=end_row {
7065 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7066 rows_by_indent_size.entry(indent).or_default().push(row);
7067 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7068 }
7069
7070 let indent_size = indent_size_occurrences
7071 .into_iter()
7072 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7073 .map(|(indent, _)| indent)
7074 .unwrap_or_default();
7075 let row = rows_by_indent_size[&indent_size][0];
7076 let indent_end = Point::new(row, indent_size.len);
7077
7078 (indent_size, indent_end)
7079 };
7080
7081 let mut line_prefix = indent_size.chars().collect::<String>();
7082
7083 if let Some(comment_prefix) =
7084 buffer
7085 .language_scope_at(selection.head())
7086 .and_then(|language| {
7087 language
7088 .line_comment_prefixes()
7089 .iter()
7090 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7091 .cloned()
7092 })
7093 {
7094 line_prefix.push_str(&comment_prefix);
7095 should_rewrap = true;
7096 }
7097
7098 if !should_rewrap {
7099 continue;
7100 }
7101
7102 if selection.is_empty() {
7103 'expand_upwards: while start_row > 0 {
7104 let prev_row = start_row - 1;
7105 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7106 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7107 {
7108 start_row = prev_row;
7109 } else {
7110 break 'expand_upwards;
7111 }
7112 }
7113
7114 'expand_downwards: while end_row < buffer.max_point().row {
7115 let next_row = end_row + 1;
7116 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7117 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7118 {
7119 end_row = next_row;
7120 } else {
7121 break 'expand_downwards;
7122 }
7123 }
7124 }
7125
7126 let start = Point::new(start_row, 0);
7127 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7128 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7129 let Some(lines_without_prefixes) = selection_text
7130 .lines()
7131 .map(|line| {
7132 line.strip_prefix(&line_prefix)
7133 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7134 .ok_or_else(|| {
7135 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7136 })
7137 })
7138 .collect::<Result<Vec<_>, _>>()
7139 .log_err()
7140 else {
7141 continue;
7142 };
7143
7144 let wrap_column = buffer
7145 .settings_at(Point::new(start_row, 0), cx)
7146 .preferred_line_length as usize;
7147 let wrapped_text = wrap_with_prefix(
7148 line_prefix,
7149 lines_without_prefixes.join(" "),
7150 wrap_column,
7151 tab_size,
7152 );
7153
7154 // TODO: should always use char-based diff while still supporting cursor behavior that
7155 // matches vim.
7156 let diff = match is_vim_mode {
7157 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7158 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7159 };
7160 let mut offset = start.to_offset(&buffer);
7161 let mut moved_since_edit = true;
7162
7163 for change in diff.iter_all_changes() {
7164 let value = change.value();
7165 match change.tag() {
7166 ChangeTag::Equal => {
7167 offset += value.len();
7168 moved_since_edit = true;
7169 }
7170 ChangeTag::Delete => {
7171 let start = buffer.anchor_after(offset);
7172 let end = buffer.anchor_before(offset + value.len());
7173
7174 if moved_since_edit {
7175 edits.push((start..end, String::new()));
7176 } else {
7177 edits.last_mut().unwrap().0.end = end;
7178 }
7179
7180 offset += value.len();
7181 moved_since_edit = false;
7182 }
7183 ChangeTag::Insert => {
7184 if moved_since_edit {
7185 let anchor = buffer.anchor_after(offset);
7186 edits.push((anchor..anchor, value.to_string()));
7187 } else {
7188 edits.last_mut().unwrap().1.push_str(value);
7189 }
7190
7191 moved_since_edit = false;
7192 }
7193 }
7194 }
7195
7196 rewrapped_row_ranges.push(start_row..=end_row);
7197 }
7198
7199 self.buffer
7200 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7201 }
7202
7203 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7204 let mut text = String::new();
7205 let buffer = self.buffer.read(cx).snapshot(cx);
7206 let mut selections = self.selections.all::<Point>(cx);
7207 let mut clipboard_selections = Vec::with_capacity(selections.len());
7208 {
7209 let max_point = buffer.max_point();
7210 let mut is_first = true;
7211 for selection in &mut selections {
7212 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7213 if is_entire_line {
7214 selection.start = Point::new(selection.start.row, 0);
7215 if !selection.is_empty() && selection.end.column == 0 {
7216 selection.end = cmp::min(max_point, selection.end);
7217 } else {
7218 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7219 }
7220 selection.goal = SelectionGoal::None;
7221 }
7222 if is_first {
7223 is_first = false;
7224 } else {
7225 text += "\n";
7226 }
7227 let mut len = 0;
7228 for chunk in buffer.text_for_range(selection.start..selection.end) {
7229 text.push_str(chunk);
7230 len += chunk.len();
7231 }
7232 clipboard_selections.push(ClipboardSelection {
7233 len,
7234 is_entire_line,
7235 first_line_indent: buffer
7236 .indent_size_for_line(MultiBufferRow(selection.start.row))
7237 .len,
7238 });
7239 }
7240 }
7241
7242 self.transact(window, cx, |this, window, cx| {
7243 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7244 s.select(selections);
7245 });
7246 this.insert("", window, cx);
7247 });
7248 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7249 }
7250
7251 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
7252 let item = self.cut_common(window, cx);
7253 cx.write_to_clipboard(item);
7254 }
7255
7256 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
7257 self.change_selections(None, window, cx, |s| {
7258 s.move_with(|snapshot, sel| {
7259 if sel.is_empty() {
7260 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7261 }
7262 });
7263 });
7264 let item = self.cut_common(window, cx);
7265 cx.set_global(KillRing(item))
7266 }
7267
7268 pub fn kill_ring_yank(
7269 &mut self,
7270 _: &KillRingYank,
7271 window: &mut Window,
7272 cx: &mut Context<Self>,
7273 ) {
7274 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7275 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7276 (kill_ring.text().to_string(), kill_ring.metadata_json())
7277 } else {
7278 return;
7279 }
7280 } else {
7281 return;
7282 };
7283 self.do_paste(&text, metadata, false, window, cx);
7284 }
7285
7286 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
7287 let selections = self.selections.all::<Point>(cx);
7288 let buffer = self.buffer.read(cx).read(cx);
7289 let mut text = String::new();
7290
7291 let mut clipboard_selections = Vec::with_capacity(selections.len());
7292 {
7293 let max_point = buffer.max_point();
7294 let mut is_first = true;
7295 for selection in selections.iter() {
7296 let mut start = selection.start;
7297 let mut end = selection.end;
7298 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7299 if is_entire_line {
7300 start = Point::new(start.row, 0);
7301 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7302 }
7303 if is_first {
7304 is_first = false;
7305 } else {
7306 text += "\n";
7307 }
7308 let mut len = 0;
7309 for chunk in buffer.text_for_range(start..end) {
7310 text.push_str(chunk);
7311 len += chunk.len();
7312 }
7313 clipboard_selections.push(ClipboardSelection {
7314 len,
7315 is_entire_line,
7316 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7317 });
7318 }
7319 }
7320
7321 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7322 text,
7323 clipboard_selections,
7324 ));
7325 }
7326
7327 pub fn do_paste(
7328 &mut self,
7329 text: &String,
7330 clipboard_selections: Option<Vec<ClipboardSelection>>,
7331 handle_entire_lines: bool,
7332 window: &mut Window,
7333 cx: &mut Context<Self>,
7334 ) {
7335 if self.read_only(cx) {
7336 return;
7337 }
7338
7339 let clipboard_text = Cow::Borrowed(text);
7340
7341 self.transact(window, cx, |this, window, cx| {
7342 if let Some(mut clipboard_selections) = clipboard_selections {
7343 let old_selections = this.selections.all::<usize>(cx);
7344 let all_selections_were_entire_line =
7345 clipboard_selections.iter().all(|s| s.is_entire_line);
7346 let first_selection_indent_column =
7347 clipboard_selections.first().map(|s| s.first_line_indent);
7348 if clipboard_selections.len() != old_selections.len() {
7349 clipboard_selections.drain(..);
7350 }
7351 let cursor_offset = this.selections.last::<usize>(cx).head();
7352 let mut auto_indent_on_paste = true;
7353
7354 this.buffer.update(cx, |buffer, cx| {
7355 let snapshot = buffer.read(cx);
7356 auto_indent_on_paste =
7357 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7358
7359 let mut start_offset = 0;
7360 let mut edits = Vec::new();
7361 let mut original_indent_columns = Vec::new();
7362 for (ix, selection) in old_selections.iter().enumerate() {
7363 let to_insert;
7364 let entire_line;
7365 let original_indent_column;
7366 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7367 let end_offset = start_offset + clipboard_selection.len;
7368 to_insert = &clipboard_text[start_offset..end_offset];
7369 entire_line = clipboard_selection.is_entire_line;
7370 start_offset = end_offset + 1;
7371 original_indent_column = Some(clipboard_selection.first_line_indent);
7372 } else {
7373 to_insert = clipboard_text.as_str();
7374 entire_line = all_selections_were_entire_line;
7375 original_indent_column = first_selection_indent_column
7376 }
7377
7378 // If the corresponding selection was empty when this slice of the
7379 // clipboard text was written, then the entire line containing the
7380 // selection was copied. If this selection is also currently empty,
7381 // then paste the line before the current line of the buffer.
7382 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7383 let column = selection.start.to_point(&snapshot).column as usize;
7384 let line_start = selection.start - column;
7385 line_start..line_start
7386 } else {
7387 selection.range()
7388 };
7389
7390 edits.push((range, to_insert));
7391 original_indent_columns.extend(original_indent_column);
7392 }
7393 drop(snapshot);
7394
7395 buffer.edit(
7396 edits,
7397 if auto_indent_on_paste {
7398 Some(AutoindentMode::Block {
7399 original_indent_columns,
7400 })
7401 } else {
7402 None
7403 },
7404 cx,
7405 );
7406 });
7407
7408 let selections = this.selections.all::<usize>(cx);
7409 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7410 s.select(selections)
7411 });
7412 } else {
7413 this.insert(&clipboard_text, window, cx);
7414 }
7415 });
7416 }
7417
7418 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
7419 if let Some(item) = cx.read_from_clipboard() {
7420 let entries = item.entries();
7421
7422 match entries.first() {
7423 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7424 // of all the pasted entries.
7425 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7426 .do_paste(
7427 clipboard_string.text(),
7428 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7429 true,
7430 window,
7431 cx,
7432 ),
7433 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
7434 }
7435 }
7436 }
7437
7438 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
7439 if self.read_only(cx) {
7440 return;
7441 }
7442
7443 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7444 if let Some((selections, _)) =
7445 self.selection_history.transaction(transaction_id).cloned()
7446 {
7447 self.change_selections(None, window, cx, |s| {
7448 s.select_anchors(selections.to_vec());
7449 });
7450 }
7451 self.request_autoscroll(Autoscroll::fit(), cx);
7452 self.unmark_text(window, cx);
7453 self.refresh_inline_completion(true, false, window, cx);
7454 cx.emit(EditorEvent::Edited { transaction_id });
7455 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7456 }
7457 }
7458
7459 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
7460 if self.read_only(cx) {
7461 return;
7462 }
7463
7464 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7465 if let Some((_, Some(selections))) =
7466 self.selection_history.transaction(transaction_id).cloned()
7467 {
7468 self.change_selections(None, window, cx, |s| {
7469 s.select_anchors(selections.to_vec());
7470 });
7471 }
7472 self.request_autoscroll(Autoscroll::fit(), cx);
7473 self.unmark_text(window, cx);
7474 self.refresh_inline_completion(true, false, window, cx);
7475 cx.emit(EditorEvent::Edited { transaction_id });
7476 }
7477 }
7478
7479 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
7480 self.buffer
7481 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7482 }
7483
7484 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
7485 self.buffer
7486 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7487 }
7488
7489 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
7490 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7491 let line_mode = s.line_mode;
7492 s.move_with(|map, selection| {
7493 let cursor = if selection.is_empty() && !line_mode {
7494 movement::left(map, selection.start)
7495 } else {
7496 selection.start
7497 };
7498 selection.collapse_to(cursor, SelectionGoal::None);
7499 });
7500 })
7501 }
7502
7503 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
7504 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7505 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7506 })
7507 }
7508
7509 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
7510 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7511 let line_mode = s.line_mode;
7512 s.move_with(|map, selection| {
7513 let cursor = if selection.is_empty() && !line_mode {
7514 movement::right(map, selection.end)
7515 } else {
7516 selection.end
7517 };
7518 selection.collapse_to(cursor, SelectionGoal::None)
7519 });
7520 })
7521 }
7522
7523 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
7524 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7525 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7526 })
7527 }
7528
7529 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
7530 if self.take_rename(true, window, cx).is_some() {
7531 return;
7532 }
7533
7534 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7535 cx.propagate();
7536 return;
7537 }
7538
7539 let text_layout_details = &self.text_layout_details(window);
7540 let selection_count = self.selections.count();
7541 let first_selection = self.selections.first_anchor();
7542
7543 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7544 let line_mode = s.line_mode;
7545 s.move_with(|map, selection| {
7546 if !selection.is_empty() && !line_mode {
7547 selection.goal = SelectionGoal::None;
7548 }
7549 let (cursor, goal) = movement::up(
7550 map,
7551 selection.start,
7552 selection.goal,
7553 false,
7554 text_layout_details,
7555 );
7556 selection.collapse_to(cursor, goal);
7557 });
7558 });
7559
7560 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7561 {
7562 cx.propagate();
7563 }
7564 }
7565
7566 pub fn move_up_by_lines(
7567 &mut self,
7568 action: &MoveUpByLines,
7569 window: &mut Window,
7570 cx: &mut Context<Self>,
7571 ) {
7572 if self.take_rename(true, window, cx).is_some() {
7573 return;
7574 }
7575
7576 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7577 cx.propagate();
7578 return;
7579 }
7580
7581 let text_layout_details = &self.text_layout_details(window);
7582
7583 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7584 let line_mode = s.line_mode;
7585 s.move_with(|map, selection| {
7586 if !selection.is_empty() && !line_mode {
7587 selection.goal = SelectionGoal::None;
7588 }
7589 let (cursor, goal) = movement::up_by_rows(
7590 map,
7591 selection.start,
7592 action.lines,
7593 selection.goal,
7594 false,
7595 text_layout_details,
7596 );
7597 selection.collapse_to(cursor, goal);
7598 });
7599 })
7600 }
7601
7602 pub fn move_down_by_lines(
7603 &mut self,
7604 action: &MoveDownByLines,
7605 window: &mut Window,
7606 cx: &mut Context<Self>,
7607 ) {
7608 if self.take_rename(true, window, cx).is_some() {
7609 return;
7610 }
7611
7612 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7613 cx.propagate();
7614 return;
7615 }
7616
7617 let text_layout_details = &self.text_layout_details(window);
7618
7619 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7620 let line_mode = s.line_mode;
7621 s.move_with(|map, selection| {
7622 if !selection.is_empty() && !line_mode {
7623 selection.goal = SelectionGoal::None;
7624 }
7625 let (cursor, goal) = movement::down_by_rows(
7626 map,
7627 selection.start,
7628 action.lines,
7629 selection.goal,
7630 false,
7631 text_layout_details,
7632 );
7633 selection.collapse_to(cursor, goal);
7634 });
7635 })
7636 }
7637
7638 pub fn select_down_by_lines(
7639 &mut self,
7640 action: &SelectDownByLines,
7641 window: &mut Window,
7642 cx: &mut Context<Self>,
7643 ) {
7644 let text_layout_details = &self.text_layout_details(window);
7645 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7646 s.move_heads_with(|map, head, goal| {
7647 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7648 })
7649 })
7650 }
7651
7652 pub fn select_up_by_lines(
7653 &mut self,
7654 action: &SelectUpByLines,
7655 window: &mut Window,
7656 cx: &mut Context<Self>,
7657 ) {
7658 let text_layout_details = &self.text_layout_details(window);
7659 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7660 s.move_heads_with(|map, head, goal| {
7661 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7662 })
7663 })
7664 }
7665
7666 pub fn select_page_up(
7667 &mut self,
7668 _: &SelectPageUp,
7669 window: &mut Window,
7670 cx: &mut Context<Self>,
7671 ) {
7672 let Some(row_count) = self.visible_row_count() else {
7673 return;
7674 };
7675
7676 let text_layout_details = &self.text_layout_details(window);
7677
7678 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7679 s.move_heads_with(|map, head, goal| {
7680 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7681 })
7682 })
7683 }
7684
7685 pub fn move_page_up(
7686 &mut self,
7687 action: &MovePageUp,
7688 window: &mut Window,
7689 cx: &mut Context<Self>,
7690 ) {
7691 if self.take_rename(true, window, cx).is_some() {
7692 return;
7693 }
7694
7695 if self
7696 .context_menu
7697 .borrow_mut()
7698 .as_mut()
7699 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7700 .unwrap_or(false)
7701 {
7702 return;
7703 }
7704
7705 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7706 cx.propagate();
7707 return;
7708 }
7709
7710 let Some(row_count) = self.visible_row_count() else {
7711 return;
7712 };
7713
7714 let autoscroll = if action.center_cursor {
7715 Autoscroll::center()
7716 } else {
7717 Autoscroll::fit()
7718 };
7719
7720 let text_layout_details = &self.text_layout_details(window);
7721
7722 self.change_selections(Some(autoscroll), window, cx, |s| {
7723 let line_mode = s.line_mode;
7724 s.move_with(|map, selection| {
7725 if !selection.is_empty() && !line_mode {
7726 selection.goal = SelectionGoal::None;
7727 }
7728 let (cursor, goal) = movement::up_by_rows(
7729 map,
7730 selection.end,
7731 row_count,
7732 selection.goal,
7733 false,
7734 text_layout_details,
7735 );
7736 selection.collapse_to(cursor, goal);
7737 });
7738 });
7739 }
7740
7741 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
7742 let text_layout_details = &self.text_layout_details(window);
7743 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7744 s.move_heads_with(|map, head, goal| {
7745 movement::up(map, head, goal, false, text_layout_details)
7746 })
7747 })
7748 }
7749
7750 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
7751 self.take_rename(true, window, cx);
7752
7753 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7754 cx.propagate();
7755 return;
7756 }
7757
7758 let text_layout_details = &self.text_layout_details(window);
7759 let selection_count = self.selections.count();
7760 let first_selection = self.selections.first_anchor();
7761
7762 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7763 let line_mode = s.line_mode;
7764 s.move_with(|map, selection| {
7765 if !selection.is_empty() && !line_mode {
7766 selection.goal = SelectionGoal::None;
7767 }
7768 let (cursor, goal) = movement::down(
7769 map,
7770 selection.end,
7771 selection.goal,
7772 false,
7773 text_layout_details,
7774 );
7775 selection.collapse_to(cursor, goal);
7776 });
7777 });
7778
7779 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7780 {
7781 cx.propagate();
7782 }
7783 }
7784
7785 pub fn select_page_down(
7786 &mut self,
7787 _: &SelectPageDown,
7788 window: &mut Window,
7789 cx: &mut Context<Self>,
7790 ) {
7791 let Some(row_count) = self.visible_row_count() else {
7792 return;
7793 };
7794
7795 let text_layout_details = &self.text_layout_details(window);
7796
7797 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7798 s.move_heads_with(|map, head, goal| {
7799 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7800 })
7801 })
7802 }
7803
7804 pub fn move_page_down(
7805 &mut self,
7806 action: &MovePageDown,
7807 window: &mut Window,
7808 cx: &mut Context<Self>,
7809 ) {
7810 if self.take_rename(true, window, cx).is_some() {
7811 return;
7812 }
7813
7814 if self
7815 .context_menu
7816 .borrow_mut()
7817 .as_mut()
7818 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7819 .unwrap_or(false)
7820 {
7821 return;
7822 }
7823
7824 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7825 cx.propagate();
7826 return;
7827 }
7828
7829 let Some(row_count) = self.visible_row_count() else {
7830 return;
7831 };
7832
7833 let autoscroll = if action.center_cursor {
7834 Autoscroll::center()
7835 } else {
7836 Autoscroll::fit()
7837 };
7838
7839 let text_layout_details = &self.text_layout_details(window);
7840 self.change_selections(Some(autoscroll), window, cx, |s| {
7841 let line_mode = s.line_mode;
7842 s.move_with(|map, selection| {
7843 if !selection.is_empty() && !line_mode {
7844 selection.goal = SelectionGoal::None;
7845 }
7846 let (cursor, goal) = movement::down_by_rows(
7847 map,
7848 selection.end,
7849 row_count,
7850 selection.goal,
7851 false,
7852 text_layout_details,
7853 );
7854 selection.collapse_to(cursor, goal);
7855 });
7856 });
7857 }
7858
7859 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
7860 let text_layout_details = &self.text_layout_details(window);
7861 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7862 s.move_heads_with(|map, head, goal| {
7863 movement::down(map, head, goal, false, text_layout_details)
7864 })
7865 });
7866 }
7867
7868 pub fn context_menu_first(
7869 &mut self,
7870 _: &ContextMenuFirst,
7871 _window: &mut Window,
7872 cx: &mut Context<Self>,
7873 ) {
7874 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7875 context_menu.select_first(self.completion_provider.as_deref(), cx);
7876 }
7877 }
7878
7879 pub fn context_menu_prev(
7880 &mut self,
7881 _: &ContextMenuPrev,
7882 _window: &mut Window,
7883 cx: &mut Context<Self>,
7884 ) {
7885 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7886 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7887 }
7888 }
7889
7890 pub fn context_menu_next(
7891 &mut self,
7892 _: &ContextMenuNext,
7893 _window: &mut Window,
7894 cx: &mut Context<Self>,
7895 ) {
7896 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7897 context_menu.select_next(self.completion_provider.as_deref(), cx);
7898 }
7899 }
7900
7901 pub fn context_menu_last(
7902 &mut self,
7903 _: &ContextMenuLast,
7904 _window: &mut Window,
7905 cx: &mut Context<Self>,
7906 ) {
7907 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7908 context_menu.select_last(self.completion_provider.as_deref(), cx);
7909 }
7910 }
7911
7912 pub fn move_to_previous_word_start(
7913 &mut self,
7914 _: &MoveToPreviousWordStart,
7915 window: &mut Window,
7916 cx: &mut Context<Self>,
7917 ) {
7918 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7919 s.move_cursors_with(|map, head, _| {
7920 (
7921 movement::previous_word_start(map, head),
7922 SelectionGoal::None,
7923 )
7924 });
7925 })
7926 }
7927
7928 pub fn move_to_previous_subword_start(
7929 &mut self,
7930 _: &MoveToPreviousSubwordStart,
7931 window: &mut Window,
7932 cx: &mut Context<Self>,
7933 ) {
7934 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7935 s.move_cursors_with(|map, head, _| {
7936 (
7937 movement::previous_subword_start(map, head),
7938 SelectionGoal::None,
7939 )
7940 });
7941 })
7942 }
7943
7944 pub fn select_to_previous_word_start(
7945 &mut self,
7946 _: &SelectToPreviousWordStart,
7947 window: &mut Window,
7948 cx: &mut Context<Self>,
7949 ) {
7950 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7951 s.move_heads_with(|map, head, _| {
7952 (
7953 movement::previous_word_start(map, head),
7954 SelectionGoal::None,
7955 )
7956 });
7957 })
7958 }
7959
7960 pub fn select_to_previous_subword_start(
7961 &mut self,
7962 _: &SelectToPreviousSubwordStart,
7963 window: &mut Window,
7964 cx: &mut Context<Self>,
7965 ) {
7966 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7967 s.move_heads_with(|map, head, _| {
7968 (
7969 movement::previous_subword_start(map, head),
7970 SelectionGoal::None,
7971 )
7972 });
7973 })
7974 }
7975
7976 pub fn delete_to_previous_word_start(
7977 &mut self,
7978 action: &DeleteToPreviousWordStart,
7979 window: &mut Window,
7980 cx: &mut Context<Self>,
7981 ) {
7982 self.transact(window, cx, |this, window, cx| {
7983 this.select_autoclose_pair(window, cx);
7984 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7985 let line_mode = s.line_mode;
7986 s.move_with(|map, selection| {
7987 if selection.is_empty() && !line_mode {
7988 let cursor = if action.ignore_newlines {
7989 movement::previous_word_start(map, selection.head())
7990 } else {
7991 movement::previous_word_start_or_newline(map, selection.head())
7992 };
7993 selection.set_head(cursor, SelectionGoal::None);
7994 }
7995 });
7996 });
7997 this.insert("", window, cx);
7998 });
7999 }
8000
8001 pub fn delete_to_previous_subword_start(
8002 &mut self,
8003 _: &DeleteToPreviousSubwordStart,
8004 window: &mut Window,
8005 cx: &mut Context<Self>,
8006 ) {
8007 self.transact(window, cx, |this, window, cx| {
8008 this.select_autoclose_pair(window, cx);
8009 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8010 let line_mode = s.line_mode;
8011 s.move_with(|map, selection| {
8012 if selection.is_empty() && !line_mode {
8013 let cursor = movement::previous_subword_start(map, selection.head());
8014 selection.set_head(cursor, SelectionGoal::None);
8015 }
8016 });
8017 });
8018 this.insert("", window, cx);
8019 });
8020 }
8021
8022 pub fn move_to_next_word_end(
8023 &mut self,
8024 _: &MoveToNextWordEnd,
8025 window: &mut Window,
8026 cx: &mut Context<Self>,
8027 ) {
8028 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8029 s.move_cursors_with(|map, head, _| {
8030 (movement::next_word_end(map, head), SelectionGoal::None)
8031 });
8032 })
8033 }
8034
8035 pub fn move_to_next_subword_end(
8036 &mut self,
8037 _: &MoveToNextSubwordEnd,
8038 window: &mut Window,
8039 cx: &mut Context<Self>,
8040 ) {
8041 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8042 s.move_cursors_with(|map, head, _| {
8043 (movement::next_subword_end(map, head), SelectionGoal::None)
8044 });
8045 })
8046 }
8047
8048 pub fn select_to_next_word_end(
8049 &mut self,
8050 _: &SelectToNextWordEnd,
8051 window: &mut Window,
8052 cx: &mut Context<Self>,
8053 ) {
8054 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8055 s.move_heads_with(|map, head, _| {
8056 (movement::next_word_end(map, head), SelectionGoal::None)
8057 });
8058 })
8059 }
8060
8061 pub fn select_to_next_subword_end(
8062 &mut self,
8063 _: &SelectToNextSubwordEnd,
8064 window: &mut Window,
8065 cx: &mut Context<Self>,
8066 ) {
8067 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8068 s.move_heads_with(|map, head, _| {
8069 (movement::next_subword_end(map, head), SelectionGoal::None)
8070 });
8071 })
8072 }
8073
8074 pub fn delete_to_next_word_end(
8075 &mut self,
8076 action: &DeleteToNextWordEnd,
8077 window: &mut Window,
8078 cx: &mut Context<Self>,
8079 ) {
8080 self.transact(window, cx, |this, window, cx| {
8081 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8082 let line_mode = s.line_mode;
8083 s.move_with(|map, selection| {
8084 if selection.is_empty() && !line_mode {
8085 let cursor = if action.ignore_newlines {
8086 movement::next_word_end(map, selection.head())
8087 } else {
8088 movement::next_word_end_or_newline(map, selection.head())
8089 };
8090 selection.set_head(cursor, SelectionGoal::None);
8091 }
8092 });
8093 });
8094 this.insert("", window, cx);
8095 });
8096 }
8097
8098 pub fn delete_to_next_subword_end(
8099 &mut self,
8100 _: &DeleteToNextSubwordEnd,
8101 window: &mut Window,
8102 cx: &mut Context<Self>,
8103 ) {
8104 self.transact(window, cx, |this, window, cx| {
8105 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8106 s.move_with(|map, selection| {
8107 if selection.is_empty() {
8108 let cursor = movement::next_subword_end(map, selection.head());
8109 selection.set_head(cursor, SelectionGoal::None);
8110 }
8111 });
8112 });
8113 this.insert("", window, cx);
8114 });
8115 }
8116
8117 pub fn move_to_beginning_of_line(
8118 &mut self,
8119 action: &MoveToBeginningOfLine,
8120 window: &mut Window,
8121 cx: &mut Context<Self>,
8122 ) {
8123 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8124 s.move_cursors_with(|map, head, _| {
8125 (
8126 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8127 SelectionGoal::None,
8128 )
8129 });
8130 })
8131 }
8132
8133 pub fn select_to_beginning_of_line(
8134 &mut self,
8135 action: &SelectToBeginningOfLine,
8136 window: &mut Window,
8137 cx: &mut Context<Self>,
8138 ) {
8139 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8140 s.move_heads_with(|map, head, _| {
8141 (
8142 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8143 SelectionGoal::None,
8144 )
8145 });
8146 });
8147 }
8148
8149 pub fn delete_to_beginning_of_line(
8150 &mut self,
8151 _: &DeleteToBeginningOfLine,
8152 window: &mut Window,
8153 cx: &mut Context<Self>,
8154 ) {
8155 self.transact(window, cx, |this, window, cx| {
8156 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8157 s.move_with(|_, selection| {
8158 selection.reversed = true;
8159 });
8160 });
8161
8162 this.select_to_beginning_of_line(
8163 &SelectToBeginningOfLine {
8164 stop_at_soft_wraps: false,
8165 },
8166 window,
8167 cx,
8168 );
8169 this.backspace(&Backspace, window, cx);
8170 });
8171 }
8172
8173 pub fn move_to_end_of_line(
8174 &mut self,
8175 action: &MoveToEndOfLine,
8176 window: &mut Window,
8177 cx: &mut Context<Self>,
8178 ) {
8179 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8180 s.move_cursors_with(|map, head, _| {
8181 (
8182 movement::line_end(map, head, action.stop_at_soft_wraps),
8183 SelectionGoal::None,
8184 )
8185 });
8186 })
8187 }
8188
8189 pub fn select_to_end_of_line(
8190 &mut self,
8191 action: &SelectToEndOfLine,
8192 window: &mut Window,
8193 cx: &mut Context<Self>,
8194 ) {
8195 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8196 s.move_heads_with(|map, head, _| {
8197 (
8198 movement::line_end(map, head, action.stop_at_soft_wraps),
8199 SelectionGoal::None,
8200 )
8201 });
8202 })
8203 }
8204
8205 pub fn delete_to_end_of_line(
8206 &mut self,
8207 _: &DeleteToEndOfLine,
8208 window: &mut Window,
8209 cx: &mut Context<Self>,
8210 ) {
8211 self.transact(window, cx, |this, window, cx| {
8212 this.select_to_end_of_line(
8213 &SelectToEndOfLine {
8214 stop_at_soft_wraps: false,
8215 },
8216 window,
8217 cx,
8218 );
8219 this.delete(&Delete, window, cx);
8220 });
8221 }
8222
8223 pub fn cut_to_end_of_line(
8224 &mut self,
8225 _: &CutToEndOfLine,
8226 window: &mut Window,
8227 cx: &mut Context<Self>,
8228 ) {
8229 self.transact(window, cx, |this, window, cx| {
8230 this.select_to_end_of_line(
8231 &SelectToEndOfLine {
8232 stop_at_soft_wraps: false,
8233 },
8234 window,
8235 cx,
8236 );
8237 this.cut(&Cut, window, cx);
8238 });
8239 }
8240
8241 pub fn move_to_start_of_paragraph(
8242 &mut self,
8243 _: &MoveToStartOfParagraph,
8244 window: &mut Window,
8245 cx: &mut Context<Self>,
8246 ) {
8247 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8248 cx.propagate();
8249 return;
8250 }
8251
8252 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8253 s.move_with(|map, selection| {
8254 selection.collapse_to(
8255 movement::start_of_paragraph(map, selection.head(), 1),
8256 SelectionGoal::None,
8257 )
8258 });
8259 })
8260 }
8261
8262 pub fn move_to_end_of_paragraph(
8263 &mut self,
8264 _: &MoveToEndOfParagraph,
8265 window: &mut Window,
8266 cx: &mut Context<Self>,
8267 ) {
8268 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8269 cx.propagate();
8270 return;
8271 }
8272
8273 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8274 s.move_with(|map, selection| {
8275 selection.collapse_to(
8276 movement::end_of_paragraph(map, selection.head(), 1),
8277 SelectionGoal::None,
8278 )
8279 });
8280 })
8281 }
8282
8283 pub fn select_to_start_of_paragraph(
8284 &mut self,
8285 _: &SelectToStartOfParagraph,
8286 window: &mut Window,
8287 cx: &mut Context<Self>,
8288 ) {
8289 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8290 cx.propagate();
8291 return;
8292 }
8293
8294 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8295 s.move_heads_with(|map, head, _| {
8296 (
8297 movement::start_of_paragraph(map, head, 1),
8298 SelectionGoal::None,
8299 )
8300 });
8301 })
8302 }
8303
8304 pub fn select_to_end_of_paragraph(
8305 &mut self,
8306 _: &SelectToEndOfParagraph,
8307 window: &mut Window,
8308 cx: &mut Context<Self>,
8309 ) {
8310 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8311 cx.propagate();
8312 return;
8313 }
8314
8315 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8316 s.move_heads_with(|map, head, _| {
8317 (
8318 movement::end_of_paragraph(map, head, 1),
8319 SelectionGoal::None,
8320 )
8321 });
8322 })
8323 }
8324
8325 pub fn move_to_beginning(
8326 &mut self,
8327 _: &MoveToBeginning,
8328 window: &mut Window,
8329 cx: &mut Context<Self>,
8330 ) {
8331 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8332 cx.propagate();
8333 return;
8334 }
8335
8336 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8337 s.select_ranges(vec![0..0]);
8338 });
8339 }
8340
8341 pub fn select_to_beginning(
8342 &mut self,
8343 _: &SelectToBeginning,
8344 window: &mut Window,
8345 cx: &mut Context<Self>,
8346 ) {
8347 let mut selection = self.selections.last::<Point>(cx);
8348 selection.set_head(Point::zero(), SelectionGoal::None);
8349
8350 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8351 s.select(vec![selection]);
8352 });
8353 }
8354
8355 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
8356 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8357 cx.propagate();
8358 return;
8359 }
8360
8361 let cursor = self.buffer.read(cx).read(cx).len();
8362 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8363 s.select_ranges(vec![cursor..cursor])
8364 });
8365 }
8366
8367 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8368 self.nav_history = nav_history;
8369 }
8370
8371 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8372 self.nav_history.as_ref()
8373 }
8374
8375 fn push_to_nav_history(
8376 &mut self,
8377 cursor_anchor: Anchor,
8378 new_position: Option<Point>,
8379 cx: &mut Context<Self>,
8380 ) {
8381 if let Some(nav_history) = self.nav_history.as_mut() {
8382 let buffer = self.buffer.read(cx).read(cx);
8383 let cursor_position = cursor_anchor.to_point(&buffer);
8384 let scroll_state = self.scroll_manager.anchor();
8385 let scroll_top_row = scroll_state.top_row(&buffer);
8386 drop(buffer);
8387
8388 if let Some(new_position) = new_position {
8389 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8390 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8391 return;
8392 }
8393 }
8394
8395 nav_history.push(
8396 Some(NavigationData {
8397 cursor_anchor,
8398 cursor_position,
8399 scroll_anchor: scroll_state,
8400 scroll_top_row,
8401 }),
8402 cx,
8403 );
8404 }
8405 }
8406
8407 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
8408 let buffer = self.buffer.read(cx).snapshot(cx);
8409 let mut selection = self.selections.first::<usize>(cx);
8410 selection.set_head(buffer.len(), SelectionGoal::None);
8411 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8412 s.select(vec![selection]);
8413 });
8414 }
8415
8416 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
8417 let end = self.buffer.read(cx).read(cx).len();
8418 self.change_selections(None, window, cx, |s| {
8419 s.select_ranges(vec![0..end]);
8420 });
8421 }
8422
8423 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
8424 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8425 let mut selections = self.selections.all::<Point>(cx);
8426 let max_point = display_map.buffer_snapshot.max_point();
8427 for selection in &mut selections {
8428 let rows = selection.spanned_rows(true, &display_map);
8429 selection.start = Point::new(rows.start.0, 0);
8430 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8431 selection.reversed = false;
8432 }
8433 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8434 s.select(selections);
8435 });
8436 }
8437
8438 pub fn split_selection_into_lines(
8439 &mut self,
8440 _: &SplitSelectionIntoLines,
8441 window: &mut Window,
8442 cx: &mut Context<Self>,
8443 ) {
8444 let mut to_unfold = Vec::new();
8445 let mut new_selection_ranges = Vec::new();
8446 {
8447 let selections = self.selections.all::<Point>(cx);
8448 let buffer = self.buffer.read(cx).read(cx);
8449 for selection in selections {
8450 for row in selection.start.row..selection.end.row {
8451 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8452 new_selection_ranges.push(cursor..cursor);
8453 }
8454 new_selection_ranges.push(selection.end..selection.end);
8455 to_unfold.push(selection.start..selection.end);
8456 }
8457 }
8458 self.unfold_ranges(&to_unfold, true, true, cx);
8459 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8460 s.select_ranges(new_selection_ranges);
8461 });
8462 }
8463
8464 pub fn add_selection_above(
8465 &mut self,
8466 _: &AddSelectionAbove,
8467 window: &mut Window,
8468 cx: &mut Context<Self>,
8469 ) {
8470 self.add_selection(true, window, cx);
8471 }
8472
8473 pub fn add_selection_below(
8474 &mut self,
8475 _: &AddSelectionBelow,
8476 window: &mut Window,
8477 cx: &mut Context<Self>,
8478 ) {
8479 self.add_selection(false, window, cx);
8480 }
8481
8482 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
8483 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8484 let mut selections = self.selections.all::<Point>(cx);
8485 let text_layout_details = self.text_layout_details(window);
8486 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8487 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8488 let range = oldest_selection.display_range(&display_map).sorted();
8489
8490 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8491 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8492 let positions = start_x.min(end_x)..start_x.max(end_x);
8493
8494 selections.clear();
8495 let mut stack = Vec::new();
8496 for row in range.start.row().0..=range.end.row().0 {
8497 if let Some(selection) = self.selections.build_columnar_selection(
8498 &display_map,
8499 DisplayRow(row),
8500 &positions,
8501 oldest_selection.reversed,
8502 &text_layout_details,
8503 ) {
8504 stack.push(selection.id);
8505 selections.push(selection);
8506 }
8507 }
8508
8509 if above {
8510 stack.reverse();
8511 }
8512
8513 AddSelectionsState { above, stack }
8514 });
8515
8516 let last_added_selection = *state.stack.last().unwrap();
8517 let mut new_selections = Vec::new();
8518 if above == state.above {
8519 let end_row = if above {
8520 DisplayRow(0)
8521 } else {
8522 display_map.max_point().row()
8523 };
8524
8525 'outer: for selection in selections {
8526 if selection.id == last_added_selection {
8527 let range = selection.display_range(&display_map).sorted();
8528 debug_assert_eq!(range.start.row(), range.end.row());
8529 let mut row = range.start.row();
8530 let positions =
8531 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8532 px(start)..px(end)
8533 } else {
8534 let start_x =
8535 display_map.x_for_display_point(range.start, &text_layout_details);
8536 let end_x =
8537 display_map.x_for_display_point(range.end, &text_layout_details);
8538 start_x.min(end_x)..start_x.max(end_x)
8539 };
8540
8541 while row != end_row {
8542 if above {
8543 row.0 -= 1;
8544 } else {
8545 row.0 += 1;
8546 }
8547
8548 if let Some(new_selection) = self.selections.build_columnar_selection(
8549 &display_map,
8550 row,
8551 &positions,
8552 selection.reversed,
8553 &text_layout_details,
8554 ) {
8555 state.stack.push(new_selection.id);
8556 if above {
8557 new_selections.push(new_selection);
8558 new_selections.push(selection);
8559 } else {
8560 new_selections.push(selection);
8561 new_selections.push(new_selection);
8562 }
8563
8564 continue 'outer;
8565 }
8566 }
8567 }
8568
8569 new_selections.push(selection);
8570 }
8571 } else {
8572 new_selections = selections;
8573 new_selections.retain(|s| s.id != last_added_selection);
8574 state.stack.pop();
8575 }
8576
8577 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8578 s.select(new_selections);
8579 });
8580 if state.stack.len() > 1 {
8581 self.add_selections_state = Some(state);
8582 }
8583 }
8584
8585 pub fn select_next_match_internal(
8586 &mut self,
8587 display_map: &DisplaySnapshot,
8588 replace_newest: bool,
8589 autoscroll: Option<Autoscroll>,
8590 window: &mut Window,
8591 cx: &mut Context<Self>,
8592 ) -> Result<()> {
8593 fn select_next_match_ranges(
8594 this: &mut Editor,
8595 range: Range<usize>,
8596 replace_newest: bool,
8597 auto_scroll: Option<Autoscroll>,
8598 window: &mut Window,
8599 cx: &mut Context<Editor>,
8600 ) {
8601 this.unfold_ranges(&[range.clone()], false, true, cx);
8602 this.change_selections(auto_scroll, window, cx, |s| {
8603 if replace_newest {
8604 s.delete(s.newest_anchor().id);
8605 }
8606 s.insert_range(range.clone());
8607 });
8608 }
8609
8610 let buffer = &display_map.buffer_snapshot;
8611 let mut selections = self.selections.all::<usize>(cx);
8612 if let Some(mut select_next_state) = self.select_next_state.take() {
8613 let query = &select_next_state.query;
8614 if !select_next_state.done {
8615 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8616 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8617 let mut next_selected_range = None;
8618
8619 let bytes_after_last_selection =
8620 buffer.bytes_in_range(last_selection.end..buffer.len());
8621 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8622 let query_matches = query
8623 .stream_find_iter(bytes_after_last_selection)
8624 .map(|result| (last_selection.end, result))
8625 .chain(
8626 query
8627 .stream_find_iter(bytes_before_first_selection)
8628 .map(|result| (0, result)),
8629 );
8630
8631 for (start_offset, query_match) in query_matches {
8632 let query_match = query_match.unwrap(); // can only fail due to I/O
8633 let offset_range =
8634 start_offset + query_match.start()..start_offset + query_match.end();
8635 let display_range = offset_range.start.to_display_point(display_map)
8636 ..offset_range.end.to_display_point(display_map);
8637
8638 if !select_next_state.wordwise
8639 || (!movement::is_inside_word(display_map, display_range.start)
8640 && !movement::is_inside_word(display_map, display_range.end))
8641 {
8642 // TODO: This is n^2, because we might check all the selections
8643 if !selections
8644 .iter()
8645 .any(|selection| selection.range().overlaps(&offset_range))
8646 {
8647 next_selected_range = Some(offset_range);
8648 break;
8649 }
8650 }
8651 }
8652
8653 if let Some(next_selected_range) = next_selected_range {
8654 select_next_match_ranges(
8655 self,
8656 next_selected_range,
8657 replace_newest,
8658 autoscroll,
8659 window,
8660 cx,
8661 );
8662 } else {
8663 select_next_state.done = true;
8664 }
8665 }
8666
8667 self.select_next_state = Some(select_next_state);
8668 } else {
8669 let mut only_carets = true;
8670 let mut same_text_selected = true;
8671 let mut selected_text = None;
8672
8673 let mut selections_iter = selections.iter().peekable();
8674 while let Some(selection) = selections_iter.next() {
8675 if selection.start != selection.end {
8676 only_carets = false;
8677 }
8678
8679 if same_text_selected {
8680 if selected_text.is_none() {
8681 selected_text =
8682 Some(buffer.text_for_range(selection.range()).collect::<String>());
8683 }
8684
8685 if let Some(next_selection) = selections_iter.peek() {
8686 if next_selection.range().len() == selection.range().len() {
8687 let next_selected_text = buffer
8688 .text_for_range(next_selection.range())
8689 .collect::<String>();
8690 if Some(next_selected_text) != selected_text {
8691 same_text_selected = false;
8692 selected_text = None;
8693 }
8694 } else {
8695 same_text_selected = false;
8696 selected_text = None;
8697 }
8698 }
8699 }
8700 }
8701
8702 if only_carets {
8703 for selection in &mut selections {
8704 let word_range = movement::surrounding_word(
8705 display_map,
8706 selection.start.to_display_point(display_map),
8707 );
8708 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8709 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8710 selection.goal = SelectionGoal::None;
8711 selection.reversed = false;
8712 select_next_match_ranges(
8713 self,
8714 selection.start..selection.end,
8715 replace_newest,
8716 autoscroll,
8717 window,
8718 cx,
8719 );
8720 }
8721
8722 if selections.len() == 1 {
8723 let selection = selections
8724 .last()
8725 .expect("ensured that there's only one selection");
8726 let query = buffer
8727 .text_for_range(selection.start..selection.end)
8728 .collect::<String>();
8729 let is_empty = query.is_empty();
8730 let select_state = SelectNextState {
8731 query: AhoCorasick::new(&[query])?,
8732 wordwise: true,
8733 done: is_empty,
8734 };
8735 self.select_next_state = Some(select_state);
8736 } else {
8737 self.select_next_state = None;
8738 }
8739 } else if let Some(selected_text) = selected_text {
8740 self.select_next_state = Some(SelectNextState {
8741 query: AhoCorasick::new(&[selected_text])?,
8742 wordwise: false,
8743 done: false,
8744 });
8745 self.select_next_match_internal(
8746 display_map,
8747 replace_newest,
8748 autoscroll,
8749 window,
8750 cx,
8751 )?;
8752 }
8753 }
8754 Ok(())
8755 }
8756
8757 pub fn select_all_matches(
8758 &mut self,
8759 _action: &SelectAllMatches,
8760 window: &mut Window,
8761 cx: &mut Context<Self>,
8762 ) -> Result<()> {
8763 self.push_to_selection_history();
8764 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8765
8766 self.select_next_match_internal(&display_map, false, None, window, cx)?;
8767 let Some(select_next_state) = self.select_next_state.as_mut() else {
8768 return Ok(());
8769 };
8770 if select_next_state.done {
8771 return Ok(());
8772 }
8773
8774 let mut new_selections = self.selections.all::<usize>(cx);
8775
8776 let buffer = &display_map.buffer_snapshot;
8777 let query_matches = select_next_state
8778 .query
8779 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8780
8781 for query_match in query_matches {
8782 let query_match = query_match.unwrap(); // can only fail due to I/O
8783 let offset_range = query_match.start()..query_match.end();
8784 let display_range = offset_range.start.to_display_point(&display_map)
8785 ..offset_range.end.to_display_point(&display_map);
8786
8787 if !select_next_state.wordwise
8788 || (!movement::is_inside_word(&display_map, display_range.start)
8789 && !movement::is_inside_word(&display_map, display_range.end))
8790 {
8791 self.selections.change_with(cx, |selections| {
8792 new_selections.push(Selection {
8793 id: selections.new_selection_id(),
8794 start: offset_range.start,
8795 end: offset_range.end,
8796 reversed: false,
8797 goal: SelectionGoal::None,
8798 });
8799 });
8800 }
8801 }
8802
8803 new_selections.sort_by_key(|selection| selection.start);
8804 let mut ix = 0;
8805 while ix + 1 < new_selections.len() {
8806 let current_selection = &new_selections[ix];
8807 let next_selection = &new_selections[ix + 1];
8808 if current_selection.range().overlaps(&next_selection.range()) {
8809 if current_selection.id < next_selection.id {
8810 new_selections.remove(ix + 1);
8811 } else {
8812 new_selections.remove(ix);
8813 }
8814 } else {
8815 ix += 1;
8816 }
8817 }
8818
8819 select_next_state.done = true;
8820 self.unfold_ranges(
8821 &new_selections
8822 .iter()
8823 .map(|selection| selection.range())
8824 .collect::<Vec<_>>(),
8825 false,
8826 false,
8827 cx,
8828 );
8829 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
8830 selections.select(new_selections)
8831 });
8832
8833 Ok(())
8834 }
8835
8836 pub fn select_next(
8837 &mut self,
8838 action: &SelectNext,
8839 window: &mut Window,
8840 cx: &mut Context<Self>,
8841 ) -> Result<()> {
8842 self.push_to_selection_history();
8843 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8844 self.select_next_match_internal(
8845 &display_map,
8846 action.replace_newest,
8847 Some(Autoscroll::newest()),
8848 window,
8849 cx,
8850 )?;
8851 Ok(())
8852 }
8853
8854 pub fn select_previous(
8855 &mut self,
8856 action: &SelectPrevious,
8857 window: &mut Window,
8858 cx: &mut Context<Self>,
8859 ) -> Result<()> {
8860 self.push_to_selection_history();
8861 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8862 let buffer = &display_map.buffer_snapshot;
8863 let mut selections = self.selections.all::<usize>(cx);
8864 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8865 let query = &select_prev_state.query;
8866 if !select_prev_state.done {
8867 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8868 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8869 let mut next_selected_range = None;
8870 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8871 let bytes_before_last_selection =
8872 buffer.reversed_bytes_in_range(0..last_selection.start);
8873 let bytes_after_first_selection =
8874 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8875 let query_matches = query
8876 .stream_find_iter(bytes_before_last_selection)
8877 .map(|result| (last_selection.start, result))
8878 .chain(
8879 query
8880 .stream_find_iter(bytes_after_first_selection)
8881 .map(|result| (buffer.len(), result)),
8882 );
8883 for (end_offset, query_match) in query_matches {
8884 let query_match = query_match.unwrap(); // can only fail due to I/O
8885 let offset_range =
8886 end_offset - query_match.end()..end_offset - query_match.start();
8887 let display_range = offset_range.start.to_display_point(&display_map)
8888 ..offset_range.end.to_display_point(&display_map);
8889
8890 if !select_prev_state.wordwise
8891 || (!movement::is_inside_word(&display_map, display_range.start)
8892 && !movement::is_inside_word(&display_map, display_range.end))
8893 {
8894 next_selected_range = Some(offset_range);
8895 break;
8896 }
8897 }
8898
8899 if let Some(next_selected_range) = next_selected_range {
8900 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8901 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
8902 if action.replace_newest {
8903 s.delete(s.newest_anchor().id);
8904 }
8905 s.insert_range(next_selected_range);
8906 });
8907 } else {
8908 select_prev_state.done = true;
8909 }
8910 }
8911
8912 self.select_prev_state = Some(select_prev_state);
8913 } else {
8914 let mut only_carets = true;
8915 let mut same_text_selected = true;
8916 let mut selected_text = None;
8917
8918 let mut selections_iter = selections.iter().peekable();
8919 while let Some(selection) = selections_iter.next() {
8920 if selection.start != selection.end {
8921 only_carets = false;
8922 }
8923
8924 if same_text_selected {
8925 if selected_text.is_none() {
8926 selected_text =
8927 Some(buffer.text_for_range(selection.range()).collect::<String>());
8928 }
8929
8930 if let Some(next_selection) = selections_iter.peek() {
8931 if next_selection.range().len() == selection.range().len() {
8932 let next_selected_text = buffer
8933 .text_for_range(next_selection.range())
8934 .collect::<String>();
8935 if Some(next_selected_text) != selected_text {
8936 same_text_selected = false;
8937 selected_text = None;
8938 }
8939 } else {
8940 same_text_selected = false;
8941 selected_text = None;
8942 }
8943 }
8944 }
8945 }
8946
8947 if only_carets {
8948 for selection in &mut selections {
8949 let word_range = movement::surrounding_word(
8950 &display_map,
8951 selection.start.to_display_point(&display_map),
8952 );
8953 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8954 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8955 selection.goal = SelectionGoal::None;
8956 selection.reversed = false;
8957 }
8958 if selections.len() == 1 {
8959 let selection = selections
8960 .last()
8961 .expect("ensured that there's only one selection");
8962 let query = buffer
8963 .text_for_range(selection.start..selection.end)
8964 .collect::<String>();
8965 let is_empty = query.is_empty();
8966 let select_state = SelectNextState {
8967 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8968 wordwise: true,
8969 done: is_empty,
8970 };
8971 self.select_prev_state = Some(select_state);
8972 } else {
8973 self.select_prev_state = None;
8974 }
8975
8976 self.unfold_ranges(
8977 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8978 false,
8979 true,
8980 cx,
8981 );
8982 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
8983 s.select(selections);
8984 });
8985 } else if let Some(selected_text) = selected_text {
8986 self.select_prev_state = Some(SelectNextState {
8987 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8988 wordwise: false,
8989 done: false,
8990 });
8991 self.select_previous(action, window, cx)?;
8992 }
8993 }
8994 Ok(())
8995 }
8996
8997 pub fn toggle_comments(
8998 &mut self,
8999 action: &ToggleComments,
9000 window: &mut Window,
9001 cx: &mut Context<Self>,
9002 ) {
9003 if self.read_only(cx) {
9004 return;
9005 }
9006 let text_layout_details = &self.text_layout_details(window);
9007 self.transact(window, cx, |this, window, cx| {
9008 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9009 let mut edits = Vec::new();
9010 let mut selection_edit_ranges = Vec::new();
9011 let mut last_toggled_row = None;
9012 let snapshot = this.buffer.read(cx).read(cx);
9013 let empty_str: Arc<str> = Arc::default();
9014 let mut suffixes_inserted = Vec::new();
9015 let ignore_indent = action.ignore_indent;
9016
9017 fn comment_prefix_range(
9018 snapshot: &MultiBufferSnapshot,
9019 row: MultiBufferRow,
9020 comment_prefix: &str,
9021 comment_prefix_whitespace: &str,
9022 ignore_indent: bool,
9023 ) -> Range<Point> {
9024 let indent_size = if ignore_indent {
9025 0
9026 } else {
9027 snapshot.indent_size_for_line(row).len
9028 };
9029
9030 let start = Point::new(row.0, indent_size);
9031
9032 let mut line_bytes = snapshot
9033 .bytes_in_range(start..snapshot.max_point())
9034 .flatten()
9035 .copied();
9036
9037 // If this line currently begins with the line comment prefix, then record
9038 // the range containing the prefix.
9039 if line_bytes
9040 .by_ref()
9041 .take(comment_prefix.len())
9042 .eq(comment_prefix.bytes())
9043 {
9044 // Include any whitespace that matches the comment prefix.
9045 let matching_whitespace_len = line_bytes
9046 .zip(comment_prefix_whitespace.bytes())
9047 .take_while(|(a, b)| a == b)
9048 .count() as u32;
9049 let end = Point::new(
9050 start.row,
9051 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9052 );
9053 start..end
9054 } else {
9055 start..start
9056 }
9057 }
9058
9059 fn comment_suffix_range(
9060 snapshot: &MultiBufferSnapshot,
9061 row: MultiBufferRow,
9062 comment_suffix: &str,
9063 comment_suffix_has_leading_space: bool,
9064 ) -> Range<Point> {
9065 let end = Point::new(row.0, snapshot.line_len(row));
9066 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9067
9068 let mut line_end_bytes = snapshot
9069 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9070 .flatten()
9071 .copied();
9072
9073 let leading_space_len = if suffix_start_column > 0
9074 && line_end_bytes.next() == Some(b' ')
9075 && comment_suffix_has_leading_space
9076 {
9077 1
9078 } else {
9079 0
9080 };
9081
9082 // If this line currently begins with the line comment prefix, then record
9083 // the range containing the prefix.
9084 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9085 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9086 start..end
9087 } else {
9088 end..end
9089 }
9090 }
9091
9092 // TODO: Handle selections that cross excerpts
9093 for selection in &mut selections {
9094 let start_column = snapshot
9095 .indent_size_for_line(MultiBufferRow(selection.start.row))
9096 .len;
9097 let language = if let Some(language) =
9098 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9099 {
9100 language
9101 } else {
9102 continue;
9103 };
9104
9105 selection_edit_ranges.clear();
9106
9107 // If multiple selections contain a given row, avoid processing that
9108 // row more than once.
9109 let mut start_row = MultiBufferRow(selection.start.row);
9110 if last_toggled_row == Some(start_row) {
9111 start_row = start_row.next_row();
9112 }
9113 let end_row =
9114 if selection.end.row > selection.start.row && selection.end.column == 0 {
9115 MultiBufferRow(selection.end.row - 1)
9116 } else {
9117 MultiBufferRow(selection.end.row)
9118 };
9119 last_toggled_row = Some(end_row);
9120
9121 if start_row > end_row {
9122 continue;
9123 }
9124
9125 // If the language has line comments, toggle those.
9126 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9127
9128 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9129 if ignore_indent {
9130 full_comment_prefixes = full_comment_prefixes
9131 .into_iter()
9132 .map(|s| Arc::from(s.trim_end()))
9133 .collect();
9134 }
9135
9136 if !full_comment_prefixes.is_empty() {
9137 let first_prefix = full_comment_prefixes
9138 .first()
9139 .expect("prefixes is non-empty");
9140 let prefix_trimmed_lengths = full_comment_prefixes
9141 .iter()
9142 .map(|p| p.trim_end_matches(' ').len())
9143 .collect::<SmallVec<[usize; 4]>>();
9144
9145 let mut all_selection_lines_are_comments = true;
9146
9147 for row in start_row.0..=end_row.0 {
9148 let row = MultiBufferRow(row);
9149 if start_row < end_row && snapshot.is_line_blank(row) {
9150 continue;
9151 }
9152
9153 let prefix_range = full_comment_prefixes
9154 .iter()
9155 .zip(prefix_trimmed_lengths.iter().copied())
9156 .map(|(prefix, trimmed_prefix_len)| {
9157 comment_prefix_range(
9158 snapshot.deref(),
9159 row,
9160 &prefix[..trimmed_prefix_len],
9161 &prefix[trimmed_prefix_len..],
9162 ignore_indent,
9163 )
9164 })
9165 .max_by_key(|range| range.end.column - range.start.column)
9166 .expect("prefixes is non-empty");
9167
9168 if prefix_range.is_empty() {
9169 all_selection_lines_are_comments = false;
9170 }
9171
9172 selection_edit_ranges.push(prefix_range);
9173 }
9174
9175 if all_selection_lines_are_comments {
9176 edits.extend(
9177 selection_edit_ranges
9178 .iter()
9179 .cloned()
9180 .map(|range| (range, empty_str.clone())),
9181 );
9182 } else {
9183 let min_column = selection_edit_ranges
9184 .iter()
9185 .map(|range| range.start.column)
9186 .min()
9187 .unwrap_or(0);
9188 edits.extend(selection_edit_ranges.iter().map(|range| {
9189 let position = Point::new(range.start.row, min_column);
9190 (position..position, first_prefix.clone())
9191 }));
9192 }
9193 } else if let Some((full_comment_prefix, comment_suffix)) =
9194 language.block_comment_delimiters()
9195 {
9196 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9197 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9198 let prefix_range = comment_prefix_range(
9199 snapshot.deref(),
9200 start_row,
9201 comment_prefix,
9202 comment_prefix_whitespace,
9203 ignore_indent,
9204 );
9205 let suffix_range = comment_suffix_range(
9206 snapshot.deref(),
9207 end_row,
9208 comment_suffix.trim_start_matches(' '),
9209 comment_suffix.starts_with(' '),
9210 );
9211
9212 if prefix_range.is_empty() || suffix_range.is_empty() {
9213 edits.push((
9214 prefix_range.start..prefix_range.start,
9215 full_comment_prefix.clone(),
9216 ));
9217 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9218 suffixes_inserted.push((end_row, comment_suffix.len()));
9219 } else {
9220 edits.push((prefix_range, empty_str.clone()));
9221 edits.push((suffix_range, empty_str.clone()));
9222 }
9223 } else {
9224 continue;
9225 }
9226 }
9227
9228 drop(snapshot);
9229 this.buffer.update(cx, |buffer, cx| {
9230 buffer.edit(edits, None, cx);
9231 });
9232
9233 // Adjust selections so that they end before any comment suffixes that
9234 // were inserted.
9235 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9236 let mut selections = this.selections.all::<Point>(cx);
9237 let snapshot = this.buffer.read(cx).read(cx);
9238 for selection in &mut selections {
9239 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9240 match row.cmp(&MultiBufferRow(selection.end.row)) {
9241 Ordering::Less => {
9242 suffixes_inserted.next();
9243 continue;
9244 }
9245 Ordering::Greater => break,
9246 Ordering::Equal => {
9247 if selection.end.column == snapshot.line_len(row) {
9248 if selection.is_empty() {
9249 selection.start.column -= suffix_len as u32;
9250 }
9251 selection.end.column -= suffix_len as u32;
9252 }
9253 break;
9254 }
9255 }
9256 }
9257 }
9258
9259 drop(snapshot);
9260 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9261 s.select(selections)
9262 });
9263
9264 let selections = this.selections.all::<Point>(cx);
9265 let selections_on_single_row = selections.windows(2).all(|selections| {
9266 selections[0].start.row == selections[1].start.row
9267 && selections[0].end.row == selections[1].end.row
9268 && selections[0].start.row == selections[0].end.row
9269 });
9270 let selections_selecting = selections
9271 .iter()
9272 .any(|selection| selection.start != selection.end);
9273 let advance_downwards = action.advance_downwards
9274 && selections_on_single_row
9275 && !selections_selecting
9276 && !matches!(this.mode, EditorMode::SingleLine { .. });
9277
9278 if advance_downwards {
9279 let snapshot = this.buffer.read(cx).snapshot(cx);
9280
9281 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9282 s.move_cursors_with(|display_snapshot, display_point, _| {
9283 let mut point = display_point.to_point(display_snapshot);
9284 point.row += 1;
9285 point = snapshot.clip_point(point, Bias::Left);
9286 let display_point = point.to_display_point(display_snapshot);
9287 let goal = SelectionGoal::HorizontalPosition(
9288 display_snapshot
9289 .x_for_display_point(display_point, text_layout_details)
9290 .into(),
9291 );
9292 (display_point, goal)
9293 })
9294 });
9295 }
9296 });
9297 }
9298
9299 pub fn select_enclosing_symbol(
9300 &mut self,
9301 _: &SelectEnclosingSymbol,
9302 window: &mut Window,
9303 cx: &mut Context<Self>,
9304 ) {
9305 let buffer = self.buffer.read(cx).snapshot(cx);
9306 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9307
9308 fn update_selection(
9309 selection: &Selection<usize>,
9310 buffer_snap: &MultiBufferSnapshot,
9311 ) -> Option<Selection<usize>> {
9312 let cursor = selection.head();
9313 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9314 for symbol in symbols.iter().rev() {
9315 let start = symbol.range.start.to_offset(buffer_snap);
9316 let end = symbol.range.end.to_offset(buffer_snap);
9317 let new_range = start..end;
9318 if start < selection.start || end > selection.end {
9319 return Some(Selection {
9320 id: selection.id,
9321 start: new_range.start,
9322 end: new_range.end,
9323 goal: SelectionGoal::None,
9324 reversed: selection.reversed,
9325 });
9326 }
9327 }
9328 None
9329 }
9330
9331 let mut selected_larger_symbol = false;
9332 let new_selections = old_selections
9333 .iter()
9334 .map(|selection| match update_selection(selection, &buffer) {
9335 Some(new_selection) => {
9336 if new_selection.range() != selection.range() {
9337 selected_larger_symbol = true;
9338 }
9339 new_selection
9340 }
9341 None => selection.clone(),
9342 })
9343 .collect::<Vec<_>>();
9344
9345 if selected_larger_symbol {
9346 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9347 s.select(new_selections);
9348 });
9349 }
9350 }
9351
9352 pub fn select_larger_syntax_node(
9353 &mut self,
9354 _: &SelectLargerSyntaxNode,
9355 window: &mut Window,
9356 cx: &mut Context<Self>,
9357 ) {
9358 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9359 let buffer = self.buffer.read(cx).snapshot(cx);
9360 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9361
9362 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9363 let mut selected_larger_node = false;
9364 let new_selections = old_selections
9365 .iter()
9366 .map(|selection| {
9367 let old_range = selection.start..selection.end;
9368 let mut new_range = old_range.clone();
9369 let mut new_node = None;
9370 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
9371 {
9372 new_node = Some(node);
9373 new_range = containing_range;
9374 if !display_map.intersects_fold(new_range.start)
9375 && !display_map.intersects_fold(new_range.end)
9376 {
9377 break;
9378 }
9379 }
9380
9381 if let Some(node) = new_node {
9382 // Log the ancestor, to support using this action as a way to explore TreeSitter
9383 // nodes. Parent and grandparent are also logged because this operation will not
9384 // visit nodes that have the same range as their parent.
9385 log::info!("Node: {node:?}");
9386 let parent = node.parent();
9387 log::info!("Parent: {parent:?}");
9388 let grandparent = parent.and_then(|x| x.parent());
9389 log::info!("Grandparent: {grandparent:?}");
9390 }
9391
9392 selected_larger_node |= new_range != old_range;
9393 Selection {
9394 id: selection.id,
9395 start: new_range.start,
9396 end: new_range.end,
9397 goal: SelectionGoal::None,
9398 reversed: selection.reversed,
9399 }
9400 })
9401 .collect::<Vec<_>>();
9402
9403 if selected_larger_node {
9404 stack.push(old_selections);
9405 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9406 s.select(new_selections);
9407 });
9408 }
9409 self.select_larger_syntax_node_stack = stack;
9410 }
9411
9412 pub fn select_smaller_syntax_node(
9413 &mut self,
9414 _: &SelectSmallerSyntaxNode,
9415 window: &mut Window,
9416 cx: &mut Context<Self>,
9417 ) {
9418 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9419 if let Some(selections) = stack.pop() {
9420 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9421 s.select(selections.to_vec());
9422 });
9423 }
9424 self.select_larger_syntax_node_stack = stack;
9425 }
9426
9427 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
9428 if !EditorSettings::get_global(cx).gutter.runnables {
9429 self.clear_tasks();
9430 return Task::ready(());
9431 }
9432 let project = self.project.as_ref().map(Entity::downgrade);
9433 cx.spawn_in(window, |this, mut cx| async move {
9434 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
9435 let Some(project) = project.and_then(|p| p.upgrade()) else {
9436 return;
9437 };
9438 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9439 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9440 }) else {
9441 return;
9442 };
9443
9444 let hide_runnables = project
9445 .update(&mut cx, |project, cx| {
9446 // Do not display any test indicators in non-dev server remote projects.
9447 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9448 })
9449 .unwrap_or(true);
9450 if hide_runnables {
9451 return;
9452 }
9453 let new_rows =
9454 cx.background_executor()
9455 .spawn({
9456 let snapshot = display_snapshot.clone();
9457 async move {
9458 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9459 }
9460 })
9461 .await;
9462
9463 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9464 this.update(&mut cx, |this, _| {
9465 this.clear_tasks();
9466 for (key, value) in rows {
9467 this.insert_tasks(key, value);
9468 }
9469 })
9470 .ok();
9471 })
9472 }
9473 fn fetch_runnable_ranges(
9474 snapshot: &DisplaySnapshot,
9475 range: Range<Anchor>,
9476 ) -> Vec<language::RunnableRange> {
9477 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9478 }
9479
9480 fn runnable_rows(
9481 project: Entity<Project>,
9482 snapshot: DisplaySnapshot,
9483 runnable_ranges: Vec<RunnableRange>,
9484 mut cx: AsyncWindowContext,
9485 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9486 runnable_ranges
9487 .into_iter()
9488 .filter_map(|mut runnable| {
9489 let tasks = cx
9490 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9491 .ok()?;
9492 if tasks.is_empty() {
9493 return None;
9494 }
9495
9496 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9497
9498 let row = snapshot
9499 .buffer_snapshot
9500 .buffer_line_for_row(MultiBufferRow(point.row))?
9501 .1
9502 .start
9503 .row;
9504
9505 let context_range =
9506 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9507 Some((
9508 (runnable.buffer_id, row),
9509 RunnableTasks {
9510 templates: tasks,
9511 offset: MultiBufferOffset(runnable.run_range.start),
9512 context_range,
9513 column: point.column,
9514 extra_variables: runnable.extra_captures,
9515 },
9516 ))
9517 })
9518 .collect()
9519 }
9520
9521 fn templates_with_tags(
9522 project: &Entity<Project>,
9523 runnable: &mut Runnable,
9524 cx: &mut App,
9525 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9526 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9527 let (worktree_id, file) = project
9528 .buffer_for_id(runnable.buffer, cx)
9529 .and_then(|buffer| buffer.read(cx).file())
9530 .map(|file| (file.worktree_id(cx), file.clone()))
9531 .unzip();
9532
9533 (
9534 project.task_store().read(cx).task_inventory().cloned(),
9535 worktree_id,
9536 file,
9537 )
9538 });
9539
9540 let tags = mem::take(&mut runnable.tags);
9541 let mut tags: Vec<_> = tags
9542 .into_iter()
9543 .flat_map(|tag| {
9544 let tag = tag.0.clone();
9545 inventory
9546 .as_ref()
9547 .into_iter()
9548 .flat_map(|inventory| {
9549 inventory.read(cx).list_tasks(
9550 file.clone(),
9551 Some(runnable.language.clone()),
9552 worktree_id,
9553 cx,
9554 )
9555 })
9556 .filter(move |(_, template)| {
9557 template.tags.iter().any(|source_tag| source_tag == &tag)
9558 })
9559 })
9560 .sorted_by_key(|(kind, _)| kind.to_owned())
9561 .collect();
9562 if let Some((leading_tag_source, _)) = tags.first() {
9563 // Strongest source wins; if we have worktree tag binding, prefer that to
9564 // global and language bindings;
9565 // if we have a global binding, prefer that to language binding.
9566 let first_mismatch = tags
9567 .iter()
9568 .position(|(tag_source, _)| tag_source != leading_tag_source);
9569 if let Some(index) = first_mismatch {
9570 tags.truncate(index);
9571 }
9572 }
9573
9574 tags
9575 }
9576
9577 pub fn move_to_enclosing_bracket(
9578 &mut self,
9579 _: &MoveToEnclosingBracket,
9580 window: &mut Window,
9581 cx: &mut Context<Self>,
9582 ) {
9583 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9584 s.move_offsets_with(|snapshot, selection| {
9585 let Some(enclosing_bracket_ranges) =
9586 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9587 else {
9588 return;
9589 };
9590
9591 let mut best_length = usize::MAX;
9592 let mut best_inside = false;
9593 let mut best_in_bracket_range = false;
9594 let mut best_destination = None;
9595 for (open, close) in enclosing_bracket_ranges {
9596 let close = close.to_inclusive();
9597 let length = close.end() - open.start;
9598 let inside = selection.start >= open.end && selection.end <= *close.start();
9599 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9600 || close.contains(&selection.head());
9601
9602 // If best is next to a bracket and current isn't, skip
9603 if !in_bracket_range && best_in_bracket_range {
9604 continue;
9605 }
9606
9607 // Prefer smaller lengths unless best is inside and current isn't
9608 if length > best_length && (best_inside || !inside) {
9609 continue;
9610 }
9611
9612 best_length = length;
9613 best_inside = inside;
9614 best_in_bracket_range = in_bracket_range;
9615 best_destination = Some(
9616 if close.contains(&selection.start) && close.contains(&selection.end) {
9617 if inside {
9618 open.end
9619 } else {
9620 open.start
9621 }
9622 } else if inside {
9623 *close.start()
9624 } else {
9625 *close.end()
9626 },
9627 );
9628 }
9629
9630 if let Some(destination) = best_destination {
9631 selection.collapse_to(destination, SelectionGoal::None);
9632 }
9633 })
9634 });
9635 }
9636
9637 pub fn undo_selection(
9638 &mut self,
9639 _: &UndoSelection,
9640 window: &mut Window,
9641 cx: &mut Context<Self>,
9642 ) {
9643 self.end_selection(window, cx);
9644 self.selection_history.mode = SelectionHistoryMode::Undoing;
9645 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9646 self.change_selections(None, window, cx, |s| {
9647 s.select_anchors(entry.selections.to_vec())
9648 });
9649 self.select_next_state = entry.select_next_state;
9650 self.select_prev_state = entry.select_prev_state;
9651 self.add_selections_state = entry.add_selections_state;
9652 self.request_autoscroll(Autoscroll::newest(), cx);
9653 }
9654 self.selection_history.mode = SelectionHistoryMode::Normal;
9655 }
9656
9657 pub fn redo_selection(
9658 &mut self,
9659 _: &RedoSelection,
9660 window: &mut Window,
9661 cx: &mut Context<Self>,
9662 ) {
9663 self.end_selection(window, cx);
9664 self.selection_history.mode = SelectionHistoryMode::Redoing;
9665 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9666 self.change_selections(None, window, cx, |s| {
9667 s.select_anchors(entry.selections.to_vec())
9668 });
9669 self.select_next_state = entry.select_next_state;
9670 self.select_prev_state = entry.select_prev_state;
9671 self.add_selections_state = entry.add_selections_state;
9672 self.request_autoscroll(Autoscroll::newest(), cx);
9673 }
9674 self.selection_history.mode = SelectionHistoryMode::Normal;
9675 }
9676
9677 pub fn expand_excerpts(
9678 &mut self,
9679 action: &ExpandExcerpts,
9680 _: &mut Window,
9681 cx: &mut Context<Self>,
9682 ) {
9683 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9684 }
9685
9686 pub fn expand_excerpts_down(
9687 &mut self,
9688 action: &ExpandExcerptsDown,
9689 _: &mut Window,
9690 cx: &mut Context<Self>,
9691 ) {
9692 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9693 }
9694
9695 pub fn expand_excerpts_up(
9696 &mut self,
9697 action: &ExpandExcerptsUp,
9698 _: &mut Window,
9699 cx: &mut Context<Self>,
9700 ) {
9701 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9702 }
9703
9704 pub fn expand_excerpts_for_direction(
9705 &mut self,
9706 lines: u32,
9707 direction: ExpandExcerptDirection,
9708
9709 cx: &mut Context<Self>,
9710 ) {
9711 let selections = self.selections.disjoint_anchors();
9712
9713 let lines = if lines == 0 {
9714 EditorSettings::get_global(cx).expand_excerpt_lines
9715 } else {
9716 lines
9717 };
9718
9719 self.buffer.update(cx, |buffer, cx| {
9720 let snapshot = buffer.snapshot(cx);
9721 let mut excerpt_ids = selections
9722 .iter()
9723 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
9724 .collect::<Vec<_>>();
9725 excerpt_ids.sort();
9726 excerpt_ids.dedup();
9727 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
9728 })
9729 }
9730
9731 pub fn expand_excerpt(
9732 &mut self,
9733 excerpt: ExcerptId,
9734 direction: ExpandExcerptDirection,
9735 cx: &mut Context<Self>,
9736 ) {
9737 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9738 self.buffer.update(cx, |buffer, cx| {
9739 buffer.expand_excerpts([excerpt], lines, direction, cx)
9740 })
9741 }
9742
9743 pub fn go_to_singleton_buffer_point(
9744 &mut self,
9745 point: Point,
9746 window: &mut Window,
9747 cx: &mut Context<Self>,
9748 ) {
9749 self.go_to_singleton_buffer_range(point..point, window, cx);
9750 }
9751
9752 pub fn go_to_singleton_buffer_range(
9753 &mut self,
9754 range: Range<Point>,
9755 window: &mut Window,
9756 cx: &mut Context<Self>,
9757 ) {
9758 let multibuffer = self.buffer().read(cx);
9759 let Some(buffer) = multibuffer.as_singleton() else {
9760 return;
9761 };
9762 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
9763 return;
9764 };
9765 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
9766 return;
9767 };
9768 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
9769 s.select_anchor_ranges([start..end])
9770 });
9771 }
9772
9773 fn go_to_diagnostic(
9774 &mut self,
9775 _: &GoToDiagnostic,
9776 window: &mut Window,
9777 cx: &mut Context<Self>,
9778 ) {
9779 self.go_to_diagnostic_impl(Direction::Next, window, cx)
9780 }
9781
9782 fn go_to_prev_diagnostic(
9783 &mut self,
9784 _: &GoToPrevDiagnostic,
9785 window: &mut Window,
9786 cx: &mut Context<Self>,
9787 ) {
9788 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
9789 }
9790
9791 pub fn go_to_diagnostic_impl(
9792 &mut self,
9793 direction: Direction,
9794 window: &mut Window,
9795 cx: &mut Context<Self>,
9796 ) {
9797 let buffer = self.buffer.read(cx).snapshot(cx);
9798 let selection = self.selections.newest::<usize>(cx);
9799
9800 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9801 if direction == Direction::Next {
9802 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9803 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
9804 return;
9805 };
9806 self.activate_diagnostics(
9807 buffer_id,
9808 popover.local_diagnostic.diagnostic.group_id,
9809 window,
9810 cx,
9811 );
9812 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
9813 let primary_range_start = active_diagnostics.primary_range.start;
9814 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9815 let mut new_selection = s.newest_anchor().clone();
9816 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
9817 s.select_anchors(vec![new_selection.clone()]);
9818 });
9819 self.refresh_inline_completion(false, true, window, cx);
9820 }
9821 return;
9822 }
9823 }
9824
9825 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9826 active_diagnostics
9827 .primary_range
9828 .to_offset(&buffer)
9829 .to_inclusive()
9830 });
9831 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9832 if active_primary_range.contains(&selection.head()) {
9833 *active_primary_range.start()
9834 } else {
9835 selection.head()
9836 }
9837 } else {
9838 selection.head()
9839 };
9840 let snapshot = self.snapshot(window, cx);
9841 loop {
9842 let mut diagnostics;
9843 if direction == Direction::Prev {
9844 diagnostics = buffer
9845 .diagnostics_in_range::<_, usize>(0..search_start)
9846 .collect::<Vec<_>>();
9847 diagnostics.reverse();
9848 } else {
9849 diagnostics = buffer
9850 .diagnostics_in_range::<_, usize>(search_start..buffer.len())
9851 .collect::<Vec<_>>();
9852 };
9853 let group = diagnostics
9854 .into_iter()
9855 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
9856 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9857 // be sorted in a stable way
9858 // skip until we are at current active diagnostic, if it exists
9859 .skip_while(|entry| {
9860 let is_in_range = match direction {
9861 Direction::Prev => entry.range.end > search_start,
9862 Direction::Next => entry.range.start < search_start,
9863 };
9864 is_in_range
9865 && self
9866 .active_diagnostics
9867 .as_ref()
9868 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9869 })
9870 .find_map(|entry| {
9871 if entry.diagnostic.is_primary
9872 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9873 && entry.range.start != entry.range.end
9874 // if we match with the active diagnostic, skip it
9875 && Some(entry.diagnostic.group_id)
9876 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9877 {
9878 Some((entry.range, entry.diagnostic.group_id))
9879 } else {
9880 None
9881 }
9882 });
9883
9884 if let Some((primary_range, group_id)) = group {
9885 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
9886 return;
9887 };
9888 self.activate_diagnostics(buffer_id, group_id, window, cx);
9889 if self.active_diagnostics.is_some() {
9890 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9891 s.select(vec![Selection {
9892 id: selection.id,
9893 start: primary_range.start,
9894 end: primary_range.start,
9895 reversed: false,
9896 goal: SelectionGoal::None,
9897 }]);
9898 });
9899 self.refresh_inline_completion(false, true, window, cx);
9900 }
9901 break;
9902 } else {
9903 // Cycle around to the start of the buffer, potentially moving back to the start of
9904 // the currently active diagnostic.
9905 active_primary_range.take();
9906 if direction == Direction::Prev {
9907 if search_start == buffer.len() {
9908 break;
9909 } else {
9910 search_start = buffer.len();
9911 }
9912 } else if search_start == 0 {
9913 break;
9914 } else {
9915 search_start = 0;
9916 }
9917 }
9918 }
9919 }
9920
9921 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
9922 let snapshot = self.snapshot(window, cx);
9923 let selection = self.selections.newest::<Point>(cx);
9924 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
9925 }
9926
9927 fn go_to_hunk_after_position(
9928 &mut self,
9929 snapshot: &EditorSnapshot,
9930 position: Point,
9931 window: &mut Window,
9932 cx: &mut Context<Editor>,
9933 ) -> Option<MultiBufferDiffHunk> {
9934 let mut hunk = snapshot
9935 .buffer_snapshot
9936 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
9937 .find(|hunk| hunk.row_range.start.0 > position.row);
9938 if hunk.is_none() {
9939 hunk = snapshot
9940 .buffer_snapshot
9941 .diff_hunks_in_range(Point::zero()..position)
9942 .find(|hunk| hunk.row_range.end.0 < position.row)
9943 }
9944 if let Some(hunk) = &hunk {
9945 let destination = Point::new(hunk.row_range.start.0, 0);
9946 self.unfold_ranges(&[destination..destination], false, false, cx);
9947 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9948 s.select_ranges(vec![destination..destination]);
9949 });
9950 }
9951
9952 hunk
9953 }
9954
9955 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
9956 let snapshot = self.snapshot(window, cx);
9957 let selection = self.selections.newest::<Point>(cx);
9958 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
9959 }
9960
9961 fn go_to_hunk_before_position(
9962 &mut self,
9963 snapshot: &EditorSnapshot,
9964 position: Point,
9965 window: &mut Window,
9966 cx: &mut Context<Editor>,
9967 ) -> Option<MultiBufferDiffHunk> {
9968 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
9969 if hunk.is_none() {
9970 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
9971 }
9972 if let Some(hunk) = &hunk {
9973 let destination = Point::new(hunk.row_range.start.0, 0);
9974 self.unfold_ranges(&[destination..destination], false, false, cx);
9975 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9976 s.select_ranges(vec![destination..destination]);
9977 });
9978 }
9979
9980 hunk
9981 }
9982
9983 pub fn go_to_definition(
9984 &mut self,
9985 _: &GoToDefinition,
9986 window: &mut Window,
9987 cx: &mut Context<Self>,
9988 ) -> Task<Result<Navigated>> {
9989 let definition =
9990 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
9991 cx.spawn_in(window, |editor, mut cx| async move {
9992 if definition.await? == Navigated::Yes {
9993 return Ok(Navigated::Yes);
9994 }
9995 match editor.update_in(&mut cx, |editor, window, cx| {
9996 editor.find_all_references(&FindAllReferences, window, cx)
9997 })? {
9998 Some(references) => references.await,
9999 None => Ok(Navigated::No),
10000 }
10001 })
10002 }
10003
10004 pub fn go_to_declaration(
10005 &mut self,
10006 _: &GoToDeclaration,
10007 window: &mut Window,
10008 cx: &mut Context<Self>,
10009 ) -> Task<Result<Navigated>> {
10010 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10011 }
10012
10013 pub fn go_to_declaration_split(
10014 &mut self,
10015 _: &GoToDeclaration,
10016 window: &mut Window,
10017 cx: &mut Context<Self>,
10018 ) -> Task<Result<Navigated>> {
10019 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10020 }
10021
10022 pub fn go_to_implementation(
10023 &mut self,
10024 _: &GoToImplementation,
10025 window: &mut Window,
10026 cx: &mut Context<Self>,
10027 ) -> Task<Result<Navigated>> {
10028 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10029 }
10030
10031 pub fn go_to_implementation_split(
10032 &mut self,
10033 _: &GoToImplementationSplit,
10034 window: &mut Window,
10035 cx: &mut Context<Self>,
10036 ) -> Task<Result<Navigated>> {
10037 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10038 }
10039
10040 pub fn go_to_type_definition(
10041 &mut self,
10042 _: &GoToTypeDefinition,
10043 window: &mut Window,
10044 cx: &mut Context<Self>,
10045 ) -> Task<Result<Navigated>> {
10046 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10047 }
10048
10049 pub fn go_to_definition_split(
10050 &mut self,
10051 _: &GoToDefinitionSplit,
10052 window: &mut Window,
10053 cx: &mut Context<Self>,
10054 ) -> Task<Result<Navigated>> {
10055 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10056 }
10057
10058 pub fn go_to_type_definition_split(
10059 &mut self,
10060 _: &GoToTypeDefinitionSplit,
10061 window: &mut Window,
10062 cx: &mut Context<Self>,
10063 ) -> Task<Result<Navigated>> {
10064 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10065 }
10066
10067 fn go_to_definition_of_kind(
10068 &mut self,
10069 kind: GotoDefinitionKind,
10070 split: bool,
10071 window: &mut Window,
10072 cx: &mut Context<Self>,
10073 ) -> Task<Result<Navigated>> {
10074 let Some(provider) = self.semantics_provider.clone() else {
10075 return Task::ready(Ok(Navigated::No));
10076 };
10077 let head = self.selections.newest::<usize>(cx).head();
10078 let buffer = self.buffer.read(cx);
10079 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10080 text_anchor
10081 } else {
10082 return Task::ready(Ok(Navigated::No));
10083 };
10084
10085 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10086 return Task::ready(Ok(Navigated::No));
10087 };
10088
10089 cx.spawn_in(window, |editor, mut cx| async move {
10090 let definitions = definitions.await?;
10091 let navigated = editor
10092 .update_in(&mut cx, |editor, window, cx| {
10093 editor.navigate_to_hover_links(
10094 Some(kind),
10095 definitions
10096 .into_iter()
10097 .filter(|location| {
10098 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10099 })
10100 .map(HoverLink::Text)
10101 .collect::<Vec<_>>(),
10102 split,
10103 window,
10104 cx,
10105 )
10106 })?
10107 .await?;
10108 anyhow::Ok(navigated)
10109 })
10110 }
10111
10112 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10113 let selection = self.selections.newest_anchor();
10114 let head = selection.head();
10115 let tail = selection.tail();
10116
10117 let Some((buffer, start_position)) =
10118 self.buffer.read(cx).text_anchor_for_position(head, cx)
10119 else {
10120 return;
10121 };
10122
10123 let end_position = if head != tail {
10124 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10125 return;
10126 };
10127 Some(pos)
10128 } else {
10129 None
10130 };
10131
10132 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10133 let url = if let Some(end_pos) = end_position {
10134 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10135 } else {
10136 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10137 };
10138
10139 if let Some(url) = url {
10140 editor.update(&mut cx, |_, cx| {
10141 cx.open_url(&url);
10142 })
10143 } else {
10144 Ok(())
10145 }
10146 });
10147
10148 url_finder.detach();
10149 }
10150
10151 pub fn open_selected_filename(
10152 &mut self,
10153 _: &OpenSelectedFilename,
10154 window: &mut Window,
10155 cx: &mut Context<Self>,
10156 ) {
10157 let Some(workspace) = self.workspace() else {
10158 return;
10159 };
10160
10161 let position = self.selections.newest_anchor().head();
10162
10163 let Some((buffer, buffer_position)) =
10164 self.buffer.read(cx).text_anchor_for_position(position, cx)
10165 else {
10166 return;
10167 };
10168
10169 let project = self.project.clone();
10170
10171 cx.spawn_in(window, |_, mut cx| async move {
10172 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10173
10174 if let Some((_, path)) = result {
10175 workspace
10176 .update_in(&mut cx, |workspace, window, cx| {
10177 workspace.open_resolved_path(path, window, cx)
10178 })?
10179 .await?;
10180 }
10181 anyhow::Ok(())
10182 })
10183 .detach();
10184 }
10185
10186 pub(crate) fn navigate_to_hover_links(
10187 &mut self,
10188 kind: Option<GotoDefinitionKind>,
10189 mut definitions: Vec<HoverLink>,
10190 split: bool,
10191 window: &mut Window,
10192 cx: &mut Context<Editor>,
10193 ) -> Task<Result<Navigated>> {
10194 // If there is one definition, just open it directly
10195 if definitions.len() == 1 {
10196 let definition = definitions.pop().unwrap();
10197
10198 enum TargetTaskResult {
10199 Location(Option<Location>),
10200 AlreadyNavigated,
10201 }
10202
10203 let target_task = match definition {
10204 HoverLink::Text(link) => {
10205 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10206 }
10207 HoverLink::InlayHint(lsp_location, server_id) => {
10208 let computation =
10209 self.compute_target_location(lsp_location, server_id, window, cx);
10210 cx.background_executor().spawn(async move {
10211 let location = computation.await?;
10212 Ok(TargetTaskResult::Location(location))
10213 })
10214 }
10215 HoverLink::Url(url) => {
10216 cx.open_url(&url);
10217 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10218 }
10219 HoverLink::File(path) => {
10220 if let Some(workspace) = self.workspace() {
10221 cx.spawn_in(window, |_, mut cx| async move {
10222 workspace
10223 .update_in(&mut cx, |workspace, window, cx| {
10224 workspace.open_resolved_path(path, window, cx)
10225 })?
10226 .await
10227 .map(|_| TargetTaskResult::AlreadyNavigated)
10228 })
10229 } else {
10230 Task::ready(Ok(TargetTaskResult::Location(None)))
10231 }
10232 }
10233 };
10234 cx.spawn_in(window, |editor, mut cx| async move {
10235 let target = match target_task.await.context("target resolution task")? {
10236 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10237 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10238 TargetTaskResult::Location(Some(target)) => target,
10239 };
10240
10241 editor.update_in(&mut cx, |editor, window, cx| {
10242 let Some(workspace) = editor.workspace() else {
10243 return Navigated::No;
10244 };
10245 let pane = workspace.read(cx).active_pane().clone();
10246
10247 let range = target.range.to_point(target.buffer.read(cx));
10248 let range = editor.range_for_match(&range);
10249 let range = collapse_multiline_range(range);
10250
10251 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10252 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10253 } else {
10254 window.defer(cx, move |window, cx| {
10255 let target_editor: Entity<Self> =
10256 workspace.update(cx, |workspace, cx| {
10257 let pane = if split {
10258 workspace.adjacent_pane(window, cx)
10259 } else {
10260 workspace.active_pane().clone()
10261 };
10262
10263 workspace.open_project_item(
10264 pane,
10265 target.buffer.clone(),
10266 true,
10267 true,
10268 window,
10269 cx,
10270 )
10271 });
10272 target_editor.update(cx, |target_editor, cx| {
10273 // When selecting a definition in a different buffer, disable the nav history
10274 // to avoid creating a history entry at the previous cursor location.
10275 pane.update(cx, |pane, _| pane.disable_history());
10276 target_editor.go_to_singleton_buffer_range(range, window, cx);
10277 pane.update(cx, |pane, _| pane.enable_history());
10278 });
10279 });
10280 }
10281 Navigated::Yes
10282 })
10283 })
10284 } else if !definitions.is_empty() {
10285 cx.spawn_in(window, |editor, mut cx| async move {
10286 let (title, location_tasks, workspace) = editor
10287 .update_in(&mut cx, |editor, window, cx| {
10288 let tab_kind = match kind {
10289 Some(GotoDefinitionKind::Implementation) => "Implementations",
10290 _ => "Definitions",
10291 };
10292 let title = definitions
10293 .iter()
10294 .find_map(|definition| match definition {
10295 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10296 let buffer = origin.buffer.read(cx);
10297 format!(
10298 "{} for {}",
10299 tab_kind,
10300 buffer
10301 .text_for_range(origin.range.clone())
10302 .collect::<String>()
10303 )
10304 }),
10305 HoverLink::InlayHint(_, _) => None,
10306 HoverLink::Url(_) => None,
10307 HoverLink::File(_) => None,
10308 })
10309 .unwrap_or(tab_kind.to_string());
10310 let location_tasks = definitions
10311 .into_iter()
10312 .map(|definition| match definition {
10313 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10314 HoverLink::InlayHint(lsp_location, server_id) => editor
10315 .compute_target_location(lsp_location, server_id, window, cx),
10316 HoverLink::Url(_) => Task::ready(Ok(None)),
10317 HoverLink::File(_) => Task::ready(Ok(None)),
10318 })
10319 .collect::<Vec<_>>();
10320 (title, location_tasks, editor.workspace().clone())
10321 })
10322 .context("location tasks preparation")?;
10323
10324 let locations = future::join_all(location_tasks)
10325 .await
10326 .into_iter()
10327 .filter_map(|location| location.transpose())
10328 .collect::<Result<_>>()
10329 .context("location tasks")?;
10330
10331 let Some(workspace) = workspace else {
10332 return Ok(Navigated::No);
10333 };
10334 let opened = workspace
10335 .update_in(&mut cx, |workspace, window, cx| {
10336 Self::open_locations_in_multibuffer(
10337 workspace,
10338 locations,
10339 title,
10340 split,
10341 MultibufferSelectionMode::First,
10342 window,
10343 cx,
10344 )
10345 })
10346 .ok();
10347
10348 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10349 })
10350 } else {
10351 Task::ready(Ok(Navigated::No))
10352 }
10353 }
10354
10355 fn compute_target_location(
10356 &self,
10357 lsp_location: lsp::Location,
10358 server_id: LanguageServerId,
10359 window: &mut Window,
10360 cx: &mut Context<Self>,
10361 ) -> Task<anyhow::Result<Option<Location>>> {
10362 let Some(project) = self.project.clone() else {
10363 return Task::ready(Ok(None));
10364 };
10365
10366 cx.spawn_in(window, move |editor, mut cx| async move {
10367 let location_task = editor.update(&mut cx, |_, cx| {
10368 project.update(cx, |project, cx| {
10369 let language_server_name = project
10370 .language_server_statuses(cx)
10371 .find(|(id, _)| server_id == *id)
10372 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10373 language_server_name.map(|language_server_name| {
10374 project.open_local_buffer_via_lsp(
10375 lsp_location.uri.clone(),
10376 server_id,
10377 language_server_name,
10378 cx,
10379 )
10380 })
10381 })
10382 })?;
10383 let location = match location_task {
10384 Some(task) => Some({
10385 let target_buffer_handle = task.await.context("open local buffer")?;
10386 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10387 let target_start = target_buffer
10388 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10389 let target_end = target_buffer
10390 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10391 target_buffer.anchor_after(target_start)
10392 ..target_buffer.anchor_before(target_end)
10393 })?;
10394 Location {
10395 buffer: target_buffer_handle,
10396 range,
10397 }
10398 }),
10399 None => None,
10400 };
10401 Ok(location)
10402 })
10403 }
10404
10405 pub fn find_all_references(
10406 &mut self,
10407 _: &FindAllReferences,
10408 window: &mut Window,
10409 cx: &mut Context<Self>,
10410 ) -> Option<Task<Result<Navigated>>> {
10411 let selection = self.selections.newest::<usize>(cx);
10412 let multi_buffer = self.buffer.read(cx);
10413 let head = selection.head();
10414
10415 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10416 let head_anchor = multi_buffer_snapshot.anchor_at(
10417 head,
10418 if head < selection.tail() {
10419 Bias::Right
10420 } else {
10421 Bias::Left
10422 },
10423 );
10424
10425 match self
10426 .find_all_references_task_sources
10427 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10428 {
10429 Ok(_) => {
10430 log::info!(
10431 "Ignoring repeated FindAllReferences invocation with the position of already running task"
10432 );
10433 return None;
10434 }
10435 Err(i) => {
10436 self.find_all_references_task_sources.insert(i, head_anchor);
10437 }
10438 }
10439
10440 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10441 let workspace = self.workspace()?;
10442 let project = workspace.read(cx).project().clone();
10443 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10444 Some(cx.spawn_in(window, |editor, mut cx| async move {
10445 let _cleanup = defer({
10446 let mut cx = cx.clone();
10447 move || {
10448 let _ = editor.update(&mut cx, |editor, _| {
10449 if let Ok(i) =
10450 editor
10451 .find_all_references_task_sources
10452 .binary_search_by(|anchor| {
10453 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10454 })
10455 {
10456 editor.find_all_references_task_sources.remove(i);
10457 }
10458 });
10459 }
10460 });
10461
10462 let locations = references.await?;
10463 if locations.is_empty() {
10464 return anyhow::Ok(Navigated::No);
10465 }
10466
10467 workspace.update_in(&mut cx, |workspace, window, cx| {
10468 let title = locations
10469 .first()
10470 .as_ref()
10471 .map(|location| {
10472 let buffer = location.buffer.read(cx);
10473 format!(
10474 "References to `{}`",
10475 buffer
10476 .text_for_range(location.range.clone())
10477 .collect::<String>()
10478 )
10479 })
10480 .unwrap();
10481 Self::open_locations_in_multibuffer(
10482 workspace,
10483 locations,
10484 title,
10485 false,
10486 MultibufferSelectionMode::First,
10487 window,
10488 cx,
10489 );
10490 Navigated::Yes
10491 })
10492 }))
10493 }
10494
10495 /// Opens a multibuffer with the given project locations in it
10496 pub fn open_locations_in_multibuffer(
10497 workspace: &mut Workspace,
10498 mut locations: Vec<Location>,
10499 title: String,
10500 split: bool,
10501 multibuffer_selection_mode: MultibufferSelectionMode,
10502 window: &mut Window,
10503 cx: &mut Context<Workspace>,
10504 ) {
10505 // If there are multiple definitions, open them in a multibuffer
10506 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10507 let mut locations = locations.into_iter().peekable();
10508 let mut ranges = Vec::new();
10509 let capability = workspace.project().read(cx).capability();
10510
10511 let excerpt_buffer = cx.new(|cx| {
10512 let mut multibuffer = MultiBuffer::new(capability);
10513 while let Some(location) = locations.next() {
10514 let buffer = location.buffer.read(cx);
10515 let mut ranges_for_buffer = Vec::new();
10516 let range = location.range.to_offset(buffer);
10517 ranges_for_buffer.push(range.clone());
10518
10519 while let Some(next_location) = locations.peek() {
10520 if next_location.buffer == location.buffer {
10521 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10522 locations.next();
10523 } else {
10524 break;
10525 }
10526 }
10527
10528 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10529 ranges.extend(multibuffer.push_excerpts_with_context_lines(
10530 location.buffer.clone(),
10531 ranges_for_buffer,
10532 DEFAULT_MULTIBUFFER_CONTEXT,
10533 cx,
10534 ))
10535 }
10536
10537 multibuffer.with_title(title)
10538 });
10539
10540 let editor = cx.new(|cx| {
10541 Editor::for_multibuffer(
10542 excerpt_buffer,
10543 Some(workspace.project().clone()),
10544 true,
10545 window,
10546 cx,
10547 )
10548 });
10549 editor.update(cx, |editor, cx| {
10550 match multibuffer_selection_mode {
10551 MultibufferSelectionMode::First => {
10552 if let Some(first_range) = ranges.first() {
10553 editor.change_selections(None, window, cx, |selections| {
10554 selections.clear_disjoint();
10555 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10556 });
10557 }
10558 editor.highlight_background::<Self>(
10559 &ranges,
10560 |theme| theme.editor_highlighted_line_background,
10561 cx,
10562 );
10563 }
10564 MultibufferSelectionMode::All => {
10565 editor.change_selections(None, window, cx, |selections| {
10566 selections.clear_disjoint();
10567 selections.select_anchor_ranges(ranges);
10568 });
10569 }
10570 }
10571 editor.register_buffers_with_language_servers(cx);
10572 });
10573
10574 let item = Box::new(editor);
10575 let item_id = item.item_id();
10576
10577 if split {
10578 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
10579 } else {
10580 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10581 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10582 pane.close_current_preview_item(window, cx)
10583 } else {
10584 None
10585 }
10586 });
10587 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
10588 }
10589 workspace.active_pane().update(cx, |pane, cx| {
10590 pane.set_preview_item_id(Some(item_id), cx);
10591 });
10592 }
10593
10594 pub fn rename(
10595 &mut self,
10596 _: &Rename,
10597 window: &mut Window,
10598 cx: &mut Context<Self>,
10599 ) -> Option<Task<Result<()>>> {
10600 use language::ToOffset as _;
10601
10602 let provider = self.semantics_provider.clone()?;
10603 let selection = self.selections.newest_anchor().clone();
10604 let (cursor_buffer, cursor_buffer_position) = self
10605 .buffer
10606 .read(cx)
10607 .text_anchor_for_position(selection.head(), cx)?;
10608 let (tail_buffer, cursor_buffer_position_end) = self
10609 .buffer
10610 .read(cx)
10611 .text_anchor_for_position(selection.tail(), cx)?;
10612 if tail_buffer != cursor_buffer {
10613 return None;
10614 }
10615
10616 let snapshot = cursor_buffer.read(cx).snapshot();
10617 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10618 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10619 let prepare_rename = provider
10620 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10621 .unwrap_or_else(|| Task::ready(Ok(None)));
10622 drop(snapshot);
10623
10624 Some(cx.spawn_in(window, |this, mut cx| async move {
10625 let rename_range = if let Some(range) = prepare_rename.await? {
10626 Some(range)
10627 } else {
10628 this.update(&mut cx, |this, cx| {
10629 let buffer = this.buffer.read(cx).snapshot(cx);
10630 let mut buffer_highlights = this
10631 .document_highlights_for_position(selection.head(), &buffer)
10632 .filter(|highlight| {
10633 highlight.start.excerpt_id == selection.head().excerpt_id
10634 && highlight.end.excerpt_id == selection.head().excerpt_id
10635 });
10636 buffer_highlights
10637 .next()
10638 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10639 })?
10640 };
10641 if let Some(rename_range) = rename_range {
10642 this.update_in(&mut cx, |this, window, cx| {
10643 let snapshot = cursor_buffer.read(cx).snapshot();
10644 let rename_buffer_range = rename_range.to_offset(&snapshot);
10645 let cursor_offset_in_rename_range =
10646 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10647 let cursor_offset_in_rename_range_end =
10648 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10649
10650 this.take_rename(false, window, cx);
10651 let buffer = this.buffer.read(cx).read(cx);
10652 let cursor_offset = selection.head().to_offset(&buffer);
10653 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10654 let rename_end = rename_start + rename_buffer_range.len();
10655 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10656 let mut old_highlight_id = None;
10657 let old_name: Arc<str> = buffer
10658 .chunks(rename_start..rename_end, true)
10659 .map(|chunk| {
10660 if old_highlight_id.is_none() {
10661 old_highlight_id = chunk.syntax_highlight_id;
10662 }
10663 chunk.text
10664 })
10665 .collect::<String>()
10666 .into();
10667
10668 drop(buffer);
10669
10670 // Position the selection in the rename editor so that it matches the current selection.
10671 this.show_local_selections = false;
10672 let rename_editor = cx.new(|cx| {
10673 let mut editor = Editor::single_line(window, cx);
10674 editor.buffer.update(cx, |buffer, cx| {
10675 buffer.edit([(0..0, old_name.clone())], None, cx)
10676 });
10677 let rename_selection_range = match cursor_offset_in_rename_range
10678 .cmp(&cursor_offset_in_rename_range_end)
10679 {
10680 Ordering::Equal => {
10681 editor.select_all(&SelectAll, window, cx);
10682 return editor;
10683 }
10684 Ordering::Less => {
10685 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10686 }
10687 Ordering::Greater => {
10688 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10689 }
10690 };
10691 if rename_selection_range.end > old_name.len() {
10692 editor.select_all(&SelectAll, window, cx);
10693 } else {
10694 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10695 s.select_ranges([rename_selection_range]);
10696 });
10697 }
10698 editor
10699 });
10700 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10701 if e == &EditorEvent::Focused {
10702 cx.emit(EditorEvent::FocusedIn)
10703 }
10704 })
10705 .detach();
10706
10707 let write_highlights =
10708 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10709 let read_highlights =
10710 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10711 let ranges = write_highlights
10712 .iter()
10713 .flat_map(|(_, ranges)| ranges.iter())
10714 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10715 .cloned()
10716 .collect();
10717
10718 this.highlight_text::<Rename>(
10719 ranges,
10720 HighlightStyle {
10721 fade_out: Some(0.6),
10722 ..Default::default()
10723 },
10724 cx,
10725 );
10726 let rename_focus_handle = rename_editor.focus_handle(cx);
10727 window.focus(&rename_focus_handle);
10728 let block_id = this.insert_blocks(
10729 [BlockProperties {
10730 style: BlockStyle::Flex,
10731 placement: BlockPlacement::Below(range.start),
10732 height: 1,
10733 render: Arc::new({
10734 let rename_editor = rename_editor.clone();
10735 move |cx: &mut BlockContext| {
10736 let mut text_style = cx.editor_style.text.clone();
10737 if let Some(highlight_style) = old_highlight_id
10738 .and_then(|h| h.style(&cx.editor_style.syntax))
10739 {
10740 text_style = text_style.highlight(highlight_style);
10741 }
10742 div()
10743 .block_mouse_down()
10744 .pl(cx.anchor_x)
10745 .child(EditorElement::new(
10746 &rename_editor,
10747 EditorStyle {
10748 background: cx.theme().system().transparent,
10749 local_player: cx.editor_style.local_player,
10750 text: text_style,
10751 scrollbar_width: cx.editor_style.scrollbar_width,
10752 syntax: cx.editor_style.syntax.clone(),
10753 status: cx.editor_style.status.clone(),
10754 inlay_hints_style: HighlightStyle {
10755 font_weight: Some(FontWeight::BOLD),
10756 ..make_inlay_hints_style(cx.app)
10757 },
10758 inline_completion_styles: make_suggestion_styles(
10759 cx.app,
10760 ),
10761 ..EditorStyle::default()
10762 },
10763 ))
10764 .into_any_element()
10765 }
10766 }),
10767 priority: 0,
10768 }],
10769 Some(Autoscroll::fit()),
10770 cx,
10771 )[0];
10772 this.pending_rename = Some(RenameState {
10773 range,
10774 old_name,
10775 editor: rename_editor,
10776 block_id,
10777 });
10778 })?;
10779 }
10780
10781 Ok(())
10782 }))
10783 }
10784
10785 pub fn confirm_rename(
10786 &mut self,
10787 _: &ConfirmRename,
10788 window: &mut Window,
10789 cx: &mut Context<Self>,
10790 ) -> Option<Task<Result<()>>> {
10791 let rename = self.take_rename(false, window, cx)?;
10792 let workspace = self.workspace()?.downgrade();
10793 let (buffer, start) = self
10794 .buffer
10795 .read(cx)
10796 .text_anchor_for_position(rename.range.start, cx)?;
10797 let (end_buffer, _) = self
10798 .buffer
10799 .read(cx)
10800 .text_anchor_for_position(rename.range.end, cx)?;
10801 if buffer != end_buffer {
10802 return None;
10803 }
10804
10805 let old_name = rename.old_name;
10806 let new_name = rename.editor.read(cx).text(cx);
10807
10808 let rename = self.semantics_provider.as_ref()?.perform_rename(
10809 &buffer,
10810 start,
10811 new_name.clone(),
10812 cx,
10813 )?;
10814
10815 Some(cx.spawn_in(window, |editor, mut cx| async move {
10816 let project_transaction = rename.await?;
10817 Self::open_project_transaction(
10818 &editor,
10819 workspace,
10820 project_transaction,
10821 format!("Rename: {} → {}", old_name, new_name),
10822 cx.clone(),
10823 )
10824 .await?;
10825
10826 editor.update(&mut cx, |editor, cx| {
10827 editor.refresh_document_highlights(cx);
10828 })?;
10829 Ok(())
10830 }))
10831 }
10832
10833 fn take_rename(
10834 &mut self,
10835 moving_cursor: bool,
10836 window: &mut Window,
10837 cx: &mut Context<Self>,
10838 ) -> Option<RenameState> {
10839 let rename = self.pending_rename.take()?;
10840 if rename.editor.focus_handle(cx).is_focused(window) {
10841 window.focus(&self.focus_handle);
10842 }
10843
10844 self.remove_blocks(
10845 [rename.block_id].into_iter().collect(),
10846 Some(Autoscroll::fit()),
10847 cx,
10848 );
10849 self.clear_highlights::<Rename>(cx);
10850 self.show_local_selections = true;
10851
10852 if moving_cursor {
10853 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10854 editor.selections.newest::<usize>(cx).head()
10855 });
10856
10857 // Update the selection to match the position of the selection inside
10858 // the rename editor.
10859 let snapshot = self.buffer.read(cx).read(cx);
10860 let rename_range = rename.range.to_offset(&snapshot);
10861 let cursor_in_editor = snapshot
10862 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10863 .min(rename_range.end);
10864 drop(snapshot);
10865
10866 self.change_selections(None, window, cx, |s| {
10867 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10868 });
10869 } else {
10870 self.refresh_document_highlights(cx);
10871 }
10872
10873 Some(rename)
10874 }
10875
10876 pub fn pending_rename(&self) -> Option<&RenameState> {
10877 self.pending_rename.as_ref()
10878 }
10879
10880 fn format(
10881 &mut self,
10882 _: &Format,
10883 window: &mut Window,
10884 cx: &mut Context<Self>,
10885 ) -> Option<Task<Result<()>>> {
10886 let project = match &self.project {
10887 Some(project) => project.clone(),
10888 None => return None,
10889 };
10890
10891 Some(self.perform_format(
10892 project,
10893 FormatTrigger::Manual,
10894 FormatTarget::Buffers,
10895 window,
10896 cx,
10897 ))
10898 }
10899
10900 fn format_selections(
10901 &mut self,
10902 _: &FormatSelections,
10903 window: &mut Window,
10904 cx: &mut Context<Self>,
10905 ) -> Option<Task<Result<()>>> {
10906 let project = match &self.project {
10907 Some(project) => project.clone(),
10908 None => return None,
10909 };
10910
10911 let ranges = self
10912 .selections
10913 .all_adjusted(cx)
10914 .into_iter()
10915 .map(|selection| selection.range())
10916 .collect_vec();
10917
10918 Some(self.perform_format(
10919 project,
10920 FormatTrigger::Manual,
10921 FormatTarget::Ranges(ranges),
10922 window,
10923 cx,
10924 ))
10925 }
10926
10927 fn perform_format(
10928 &mut self,
10929 project: Entity<Project>,
10930 trigger: FormatTrigger,
10931 target: FormatTarget,
10932 window: &mut Window,
10933 cx: &mut Context<Self>,
10934 ) -> Task<Result<()>> {
10935 let buffer = self.buffer.clone();
10936 let (buffers, target) = match target {
10937 FormatTarget::Buffers => {
10938 let mut buffers = buffer.read(cx).all_buffers();
10939 if trigger == FormatTrigger::Save {
10940 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10941 }
10942 (buffers, LspFormatTarget::Buffers)
10943 }
10944 FormatTarget::Ranges(selection_ranges) => {
10945 let multi_buffer = buffer.read(cx);
10946 let snapshot = multi_buffer.read(cx);
10947 let mut buffers = HashSet::default();
10948 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
10949 BTreeMap::new();
10950 for selection_range in selection_ranges {
10951 for (buffer, buffer_range, _) in
10952 snapshot.range_to_buffer_ranges(selection_range)
10953 {
10954 let buffer_id = buffer.remote_id();
10955 let start = buffer.anchor_before(buffer_range.start);
10956 let end = buffer.anchor_after(buffer_range.end);
10957 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
10958 buffer_id_to_ranges
10959 .entry(buffer_id)
10960 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
10961 .or_insert_with(|| vec![start..end]);
10962 }
10963 }
10964 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
10965 }
10966 };
10967
10968 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10969 let format = project.update(cx, |project, cx| {
10970 project.format(buffers, target, true, trigger, cx)
10971 });
10972
10973 cx.spawn_in(window, |_, mut cx| async move {
10974 let transaction = futures::select_biased! {
10975 () = timeout => {
10976 log::warn!("timed out waiting for formatting");
10977 None
10978 }
10979 transaction = format.log_err().fuse() => transaction,
10980 };
10981
10982 buffer
10983 .update(&mut cx, |buffer, cx| {
10984 if let Some(transaction) = transaction {
10985 if !buffer.is_singleton() {
10986 buffer.push_transaction(&transaction.0, cx);
10987 }
10988 }
10989
10990 cx.notify();
10991 })
10992 .ok();
10993
10994 Ok(())
10995 })
10996 }
10997
10998 fn restart_language_server(
10999 &mut self,
11000 _: &RestartLanguageServer,
11001 _: &mut Window,
11002 cx: &mut Context<Self>,
11003 ) {
11004 if let Some(project) = self.project.clone() {
11005 self.buffer.update(cx, |multi_buffer, cx| {
11006 project.update(cx, |project, cx| {
11007 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11008 });
11009 })
11010 }
11011 }
11012
11013 fn cancel_language_server_work(
11014 &mut self,
11015 _: &actions::CancelLanguageServerWork,
11016 _: &mut Window,
11017 cx: &mut Context<Self>,
11018 ) {
11019 if let Some(project) = self.project.clone() {
11020 self.buffer.update(cx, |multi_buffer, cx| {
11021 project.update(cx, |project, cx| {
11022 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
11023 });
11024 })
11025 }
11026 }
11027
11028 fn show_character_palette(
11029 &mut self,
11030 _: &ShowCharacterPalette,
11031 window: &mut Window,
11032 _: &mut Context<Self>,
11033 ) {
11034 window.show_character_palette();
11035 }
11036
11037 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11038 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11039 let buffer = self.buffer.read(cx).snapshot(cx);
11040 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11041 let is_valid = buffer
11042 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone())
11043 .any(|entry| {
11044 entry.diagnostic.is_primary
11045 && !entry.range.is_empty()
11046 && entry.range.start == primary_range_start
11047 && entry.diagnostic.message == active_diagnostics.primary_message
11048 });
11049
11050 if is_valid != active_diagnostics.is_valid {
11051 active_diagnostics.is_valid = is_valid;
11052 let mut new_styles = HashMap::default();
11053 for (block_id, diagnostic) in &active_diagnostics.blocks {
11054 new_styles.insert(
11055 *block_id,
11056 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11057 );
11058 }
11059 self.display_map.update(cx, |display_map, _cx| {
11060 display_map.replace_blocks(new_styles)
11061 });
11062 }
11063 }
11064 }
11065
11066 fn activate_diagnostics(
11067 &mut self,
11068 buffer_id: BufferId,
11069 group_id: usize,
11070 window: &mut Window,
11071 cx: &mut Context<Self>,
11072 ) {
11073 self.dismiss_diagnostics(cx);
11074 let snapshot = self.snapshot(window, cx);
11075 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11076 let buffer = self.buffer.read(cx).snapshot(cx);
11077
11078 let mut primary_range = None;
11079 let mut primary_message = None;
11080 let diagnostic_group = buffer
11081 .diagnostic_group(buffer_id, group_id)
11082 .filter_map(|entry| {
11083 let start = entry.range.start;
11084 let end = entry.range.end;
11085 if snapshot.is_line_folded(MultiBufferRow(start.row))
11086 && (start.row == end.row
11087 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11088 {
11089 return None;
11090 }
11091 if entry.diagnostic.is_primary {
11092 primary_range = Some(entry.range.clone());
11093 primary_message = Some(entry.diagnostic.message.clone());
11094 }
11095 Some(entry)
11096 })
11097 .collect::<Vec<_>>();
11098 let primary_range = primary_range?;
11099 let primary_message = primary_message?;
11100
11101 let blocks = display_map
11102 .insert_blocks(
11103 diagnostic_group.iter().map(|entry| {
11104 let diagnostic = entry.diagnostic.clone();
11105 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11106 BlockProperties {
11107 style: BlockStyle::Fixed,
11108 placement: BlockPlacement::Below(
11109 buffer.anchor_after(entry.range.start),
11110 ),
11111 height: message_height,
11112 render: diagnostic_block_renderer(diagnostic, None, true, true),
11113 priority: 0,
11114 }
11115 }),
11116 cx,
11117 )
11118 .into_iter()
11119 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11120 .collect();
11121
11122 Some(ActiveDiagnosticGroup {
11123 primary_range: buffer.anchor_before(primary_range.start)
11124 ..buffer.anchor_after(primary_range.end),
11125 primary_message,
11126 group_id,
11127 blocks,
11128 is_valid: true,
11129 })
11130 });
11131 }
11132
11133 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11134 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11135 self.display_map.update(cx, |display_map, cx| {
11136 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11137 });
11138 cx.notify();
11139 }
11140 }
11141
11142 pub fn set_selections_from_remote(
11143 &mut self,
11144 selections: Vec<Selection<Anchor>>,
11145 pending_selection: Option<Selection<Anchor>>,
11146 window: &mut Window,
11147 cx: &mut Context<Self>,
11148 ) {
11149 let old_cursor_position = self.selections.newest_anchor().head();
11150 self.selections.change_with(cx, |s| {
11151 s.select_anchors(selections);
11152 if let Some(pending_selection) = pending_selection {
11153 s.set_pending(pending_selection, SelectMode::Character);
11154 } else {
11155 s.clear_pending();
11156 }
11157 });
11158 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11159 }
11160
11161 fn push_to_selection_history(&mut self) {
11162 self.selection_history.push(SelectionHistoryEntry {
11163 selections: self.selections.disjoint_anchors(),
11164 select_next_state: self.select_next_state.clone(),
11165 select_prev_state: self.select_prev_state.clone(),
11166 add_selections_state: self.add_selections_state.clone(),
11167 });
11168 }
11169
11170 pub fn transact(
11171 &mut self,
11172 window: &mut Window,
11173 cx: &mut Context<Self>,
11174 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11175 ) -> Option<TransactionId> {
11176 self.start_transaction_at(Instant::now(), window, cx);
11177 update(self, window, cx);
11178 self.end_transaction_at(Instant::now(), cx)
11179 }
11180
11181 pub fn start_transaction_at(
11182 &mut self,
11183 now: Instant,
11184 window: &mut Window,
11185 cx: &mut Context<Self>,
11186 ) {
11187 self.end_selection(window, cx);
11188 if let Some(tx_id) = self
11189 .buffer
11190 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11191 {
11192 self.selection_history
11193 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11194 cx.emit(EditorEvent::TransactionBegun {
11195 transaction_id: tx_id,
11196 })
11197 }
11198 }
11199
11200 pub fn end_transaction_at(
11201 &mut self,
11202 now: Instant,
11203 cx: &mut Context<Self>,
11204 ) -> Option<TransactionId> {
11205 if let Some(transaction_id) = self
11206 .buffer
11207 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11208 {
11209 if let Some((_, end_selections)) =
11210 self.selection_history.transaction_mut(transaction_id)
11211 {
11212 *end_selections = Some(self.selections.disjoint_anchors());
11213 } else {
11214 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11215 }
11216
11217 cx.emit(EditorEvent::Edited { transaction_id });
11218 Some(transaction_id)
11219 } else {
11220 None
11221 }
11222 }
11223
11224 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11225 if self.selection_mark_mode {
11226 self.change_selections(None, window, cx, |s| {
11227 s.move_with(|_, sel| {
11228 sel.collapse_to(sel.head(), SelectionGoal::None);
11229 });
11230 })
11231 }
11232 self.selection_mark_mode = true;
11233 cx.notify();
11234 }
11235
11236 pub fn swap_selection_ends(
11237 &mut self,
11238 _: &actions::SwapSelectionEnds,
11239 window: &mut Window,
11240 cx: &mut Context<Self>,
11241 ) {
11242 self.change_selections(None, window, cx, |s| {
11243 s.move_with(|_, sel| {
11244 if sel.start != sel.end {
11245 sel.reversed = !sel.reversed
11246 }
11247 });
11248 });
11249 self.request_autoscroll(Autoscroll::newest(), cx);
11250 cx.notify();
11251 }
11252
11253 pub fn toggle_fold(
11254 &mut self,
11255 _: &actions::ToggleFold,
11256 window: &mut Window,
11257 cx: &mut Context<Self>,
11258 ) {
11259 if self.is_singleton(cx) {
11260 let selection = self.selections.newest::<Point>(cx);
11261
11262 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11263 let range = if selection.is_empty() {
11264 let point = selection.head().to_display_point(&display_map);
11265 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11266 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11267 .to_point(&display_map);
11268 start..end
11269 } else {
11270 selection.range()
11271 };
11272 if display_map.folds_in_range(range).next().is_some() {
11273 self.unfold_lines(&Default::default(), window, cx)
11274 } else {
11275 self.fold(&Default::default(), window, cx)
11276 }
11277 } else {
11278 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11279 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11280 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11281 .map(|(snapshot, _, _)| snapshot.remote_id())
11282 .collect();
11283
11284 for buffer_id in buffer_ids {
11285 if self.is_buffer_folded(buffer_id, cx) {
11286 self.unfold_buffer(buffer_id, cx);
11287 } else {
11288 self.fold_buffer(buffer_id, cx);
11289 }
11290 }
11291 }
11292 }
11293
11294 pub fn toggle_fold_recursive(
11295 &mut self,
11296 _: &actions::ToggleFoldRecursive,
11297 window: &mut Window,
11298 cx: &mut Context<Self>,
11299 ) {
11300 let selection = self.selections.newest::<Point>(cx);
11301
11302 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11303 let range = if selection.is_empty() {
11304 let point = selection.head().to_display_point(&display_map);
11305 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11306 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11307 .to_point(&display_map);
11308 start..end
11309 } else {
11310 selection.range()
11311 };
11312 if display_map.folds_in_range(range).next().is_some() {
11313 self.unfold_recursive(&Default::default(), window, cx)
11314 } else {
11315 self.fold_recursive(&Default::default(), window, cx)
11316 }
11317 }
11318
11319 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11320 if self.is_singleton(cx) {
11321 let mut to_fold = Vec::new();
11322 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11323 let selections = self.selections.all_adjusted(cx);
11324
11325 for selection in selections {
11326 let range = selection.range().sorted();
11327 let buffer_start_row = range.start.row;
11328
11329 if range.start.row != range.end.row {
11330 let mut found = false;
11331 let mut row = range.start.row;
11332 while row <= range.end.row {
11333 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11334 {
11335 found = true;
11336 row = crease.range().end.row + 1;
11337 to_fold.push(crease);
11338 } else {
11339 row += 1
11340 }
11341 }
11342 if found {
11343 continue;
11344 }
11345 }
11346
11347 for row in (0..=range.start.row).rev() {
11348 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11349 if crease.range().end.row >= buffer_start_row {
11350 to_fold.push(crease);
11351 if row <= range.start.row {
11352 break;
11353 }
11354 }
11355 }
11356 }
11357 }
11358
11359 self.fold_creases(to_fold, true, window, cx);
11360 } else {
11361 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11362
11363 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11364 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11365 .map(|(snapshot, _, _)| snapshot.remote_id())
11366 .collect();
11367 for buffer_id in buffer_ids {
11368 self.fold_buffer(buffer_id, cx);
11369 }
11370 }
11371 }
11372
11373 fn fold_at_level(
11374 &mut self,
11375 fold_at: &FoldAtLevel,
11376 window: &mut Window,
11377 cx: &mut Context<Self>,
11378 ) {
11379 if !self.buffer.read(cx).is_singleton() {
11380 return;
11381 }
11382
11383 let fold_at_level = fold_at.level;
11384 let snapshot = self.buffer.read(cx).snapshot(cx);
11385 let mut to_fold = Vec::new();
11386 let mut stack = vec![(0, snapshot.max_row().0, 1)];
11387
11388 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11389 while start_row < end_row {
11390 match self
11391 .snapshot(window, cx)
11392 .crease_for_buffer_row(MultiBufferRow(start_row))
11393 {
11394 Some(crease) => {
11395 let nested_start_row = crease.range().start.row + 1;
11396 let nested_end_row = crease.range().end.row;
11397
11398 if current_level < fold_at_level {
11399 stack.push((nested_start_row, nested_end_row, current_level + 1));
11400 } else if current_level == fold_at_level {
11401 to_fold.push(crease);
11402 }
11403
11404 start_row = nested_end_row + 1;
11405 }
11406 None => start_row += 1,
11407 }
11408 }
11409 }
11410
11411 self.fold_creases(to_fold, true, window, cx);
11412 }
11413
11414 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11415 if self.buffer.read(cx).is_singleton() {
11416 let mut fold_ranges = Vec::new();
11417 let snapshot = self.buffer.read(cx).snapshot(cx);
11418
11419 for row in 0..snapshot.max_row().0 {
11420 if let Some(foldable_range) = self
11421 .snapshot(window, cx)
11422 .crease_for_buffer_row(MultiBufferRow(row))
11423 {
11424 fold_ranges.push(foldable_range);
11425 }
11426 }
11427
11428 self.fold_creases(fold_ranges, true, window, cx);
11429 } else {
11430 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11431 editor
11432 .update_in(&mut cx, |editor, _, cx| {
11433 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11434 editor.fold_buffer(buffer_id, cx);
11435 }
11436 })
11437 .ok();
11438 });
11439 }
11440 }
11441
11442 pub fn fold_function_bodies(
11443 &mut self,
11444 _: &actions::FoldFunctionBodies,
11445 window: &mut Window,
11446 cx: &mut Context<Self>,
11447 ) {
11448 let snapshot = self.buffer.read(cx).snapshot(cx);
11449
11450 let ranges = snapshot
11451 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11452 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11453 .collect::<Vec<_>>();
11454
11455 let creases = ranges
11456 .into_iter()
11457 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11458 .collect();
11459
11460 self.fold_creases(creases, true, window, cx);
11461 }
11462
11463 pub fn fold_recursive(
11464 &mut self,
11465 _: &actions::FoldRecursive,
11466 window: &mut Window,
11467 cx: &mut Context<Self>,
11468 ) {
11469 let mut to_fold = Vec::new();
11470 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11471 let selections = self.selections.all_adjusted(cx);
11472
11473 for selection in selections {
11474 let range = selection.range().sorted();
11475 let buffer_start_row = range.start.row;
11476
11477 if range.start.row != range.end.row {
11478 let mut found = false;
11479 for row in range.start.row..=range.end.row {
11480 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11481 found = true;
11482 to_fold.push(crease);
11483 }
11484 }
11485 if found {
11486 continue;
11487 }
11488 }
11489
11490 for row in (0..=range.start.row).rev() {
11491 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11492 if crease.range().end.row >= buffer_start_row {
11493 to_fold.push(crease);
11494 } else {
11495 break;
11496 }
11497 }
11498 }
11499 }
11500
11501 self.fold_creases(to_fold, true, window, cx);
11502 }
11503
11504 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11505 let buffer_row = fold_at.buffer_row;
11506 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11507
11508 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11509 let autoscroll = self
11510 .selections
11511 .all::<Point>(cx)
11512 .iter()
11513 .any(|selection| crease.range().overlaps(&selection.range()));
11514
11515 self.fold_creases(vec![crease], autoscroll, window, cx);
11516 }
11517 }
11518
11519 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
11520 if self.is_singleton(cx) {
11521 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11522 let buffer = &display_map.buffer_snapshot;
11523 let selections = self.selections.all::<Point>(cx);
11524 let ranges = selections
11525 .iter()
11526 .map(|s| {
11527 let range = s.display_range(&display_map).sorted();
11528 let mut start = range.start.to_point(&display_map);
11529 let mut end = range.end.to_point(&display_map);
11530 start.column = 0;
11531 end.column = buffer.line_len(MultiBufferRow(end.row));
11532 start..end
11533 })
11534 .collect::<Vec<_>>();
11535
11536 self.unfold_ranges(&ranges, true, true, cx);
11537 } else {
11538 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11539 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11540 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11541 .map(|(snapshot, _, _)| snapshot.remote_id())
11542 .collect();
11543 for buffer_id in buffer_ids {
11544 self.unfold_buffer(buffer_id, cx);
11545 }
11546 }
11547 }
11548
11549 pub fn unfold_recursive(
11550 &mut self,
11551 _: &UnfoldRecursive,
11552 _window: &mut Window,
11553 cx: &mut Context<Self>,
11554 ) {
11555 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11556 let selections = self.selections.all::<Point>(cx);
11557 let ranges = selections
11558 .iter()
11559 .map(|s| {
11560 let mut range = s.display_range(&display_map).sorted();
11561 *range.start.column_mut() = 0;
11562 *range.end.column_mut() = display_map.line_len(range.end.row());
11563 let start = range.start.to_point(&display_map);
11564 let end = range.end.to_point(&display_map);
11565 start..end
11566 })
11567 .collect::<Vec<_>>();
11568
11569 self.unfold_ranges(&ranges, true, true, cx);
11570 }
11571
11572 pub fn unfold_at(
11573 &mut self,
11574 unfold_at: &UnfoldAt,
11575 _window: &mut Window,
11576 cx: &mut Context<Self>,
11577 ) {
11578 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11579
11580 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11581 ..Point::new(
11582 unfold_at.buffer_row.0,
11583 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11584 );
11585
11586 let autoscroll = self
11587 .selections
11588 .all::<Point>(cx)
11589 .iter()
11590 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11591
11592 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
11593 }
11594
11595 pub fn unfold_all(
11596 &mut self,
11597 _: &actions::UnfoldAll,
11598 _window: &mut Window,
11599 cx: &mut Context<Self>,
11600 ) {
11601 if self.buffer.read(cx).is_singleton() {
11602 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11603 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11604 } else {
11605 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
11606 editor
11607 .update(&mut cx, |editor, cx| {
11608 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11609 editor.unfold_buffer(buffer_id, cx);
11610 }
11611 })
11612 .ok();
11613 });
11614 }
11615 }
11616
11617 pub fn fold_selected_ranges(
11618 &mut self,
11619 _: &FoldSelectedRanges,
11620 window: &mut Window,
11621 cx: &mut Context<Self>,
11622 ) {
11623 let selections = self.selections.all::<Point>(cx);
11624 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11625 let line_mode = self.selections.line_mode;
11626 let ranges = selections
11627 .into_iter()
11628 .map(|s| {
11629 if line_mode {
11630 let start = Point::new(s.start.row, 0);
11631 let end = Point::new(
11632 s.end.row,
11633 display_map
11634 .buffer_snapshot
11635 .line_len(MultiBufferRow(s.end.row)),
11636 );
11637 Crease::simple(start..end, display_map.fold_placeholder.clone())
11638 } else {
11639 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11640 }
11641 })
11642 .collect::<Vec<_>>();
11643 self.fold_creases(ranges, true, window, cx);
11644 }
11645
11646 pub fn fold_ranges<T: ToOffset + Clone>(
11647 &mut self,
11648 ranges: Vec<Range<T>>,
11649 auto_scroll: bool,
11650 window: &mut Window,
11651 cx: &mut Context<Self>,
11652 ) {
11653 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11654 let ranges = ranges
11655 .into_iter()
11656 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
11657 .collect::<Vec<_>>();
11658 self.fold_creases(ranges, auto_scroll, window, cx);
11659 }
11660
11661 pub fn fold_creases<T: ToOffset + Clone>(
11662 &mut self,
11663 creases: Vec<Crease<T>>,
11664 auto_scroll: bool,
11665 window: &mut Window,
11666 cx: &mut Context<Self>,
11667 ) {
11668 if creases.is_empty() {
11669 return;
11670 }
11671
11672 let mut buffers_affected = HashSet::default();
11673 let multi_buffer = self.buffer().read(cx);
11674 for crease in &creases {
11675 if let Some((_, buffer, _)) =
11676 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11677 {
11678 buffers_affected.insert(buffer.read(cx).remote_id());
11679 };
11680 }
11681
11682 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11683
11684 if auto_scroll {
11685 self.request_autoscroll(Autoscroll::fit(), cx);
11686 }
11687
11688 cx.notify();
11689
11690 if let Some(active_diagnostics) = self.active_diagnostics.take() {
11691 // Clear diagnostics block when folding a range that contains it.
11692 let snapshot = self.snapshot(window, cx);
11693 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11694 drop(snapshot);
11695 self.active_diagnostics = Some(active_diagnostics);
11696 self.dismiss_diagnostics(cx);
11697 } else {
11698 self.active_diagnostics = Some(active_diagnostics);
11699 }
11700 }
11701
11702 self.scrollbar_marker_state.dirty = true;
11703 }
11704
11705 /// Removes any folds whose ranges intersect any of the given ranges.
11706 pub fn unfold_ranges<T: ToOffset + Clone>(
11707 &mut self,
11708 ranges: &[Range<T>],
11709 inclusive: bool,
11710 auto_scroll: bool,
11711 cx: &mut Context<Self>,
11712 ) {
11713 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11714 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11715 });
11716 }
11717
11718 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
11719 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
11720 return;
11721 }
11722 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11723 return;
11724 };
11725 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11726 self.display_map
11727 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
11728 cx.emit(EditorEvent::BufferFoldToggled {
11729 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11730 folded: true,
11731 });
11732 cx.notify();
11733 }
11734
11735 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
11736 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
11737 return;
11738 }
11739 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11740 return;
11741 };
11742 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11743 self.display_map.update(cx, |display_map, cx| {
11744 display_map.unfold_buffer(buffer_id, cx);
11745 });
11746 cx.emit(EditorEvent::BufferFoldToggled {
11747 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11748 folded: false,
11749 });
11750 cx.notify();
11751 }
11752
11753 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
11754 self.display_map.read(cx).is_buffer_folded(buffer)
11755 }
11756
11757 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
11758 self.display_map.read(cx).folded_buffers()
11759 }
11760
11761 /// Removes any folds with the given ranges.
11762 pub fn remove_folds_with_type<T: ToOffset + Clone>(
11763 &mut self,
11764 ranges: &[Range<T>],
11765 type_id: TypeId,
11766 auto_scroll: bool,
11767 cx: &mut Context<Self>,
11768 ) {
11769 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11770 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11771 });
11772 }
11773
11774 fn remove_folds_with<T: ToOffset + Clone>(
11775 &mut self,
11776 ranges: &[Range<T>],
11777 auto_scroll: bool,
11778 cx: &mut Context<Self>,
11779 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
11780 ) {
11781 if ranges.is_empty() {
11782 return;
11783 }
11784
11785 let mut buffers_affected = HashSet::default();
11786 let multi_buffer = self.buffer().read(cx);
11787 for range in ranges {
11788 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11789 buffers_affected.insert(buffer.read(cx).remote_id());
11790 };
11791 }
11792
11793 self.display_map.update(cx, update);
11794
11795 if auto_scroll {
11796 self.request_autoscroll(Autoscroll::fit(), cx);
11797 }
11798
11799 cx.notify();
11800 self.scrollbar_marker_state.dirty = true;
11801 self.active_indent_guides_state.dirty = true;
11802 }
11803
11804 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
11805 self.display_map.read(cx).fold_placeholder.clone()
11806 }
11807
11808 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
11809 self.buffer.update(cx, |buffer, cx| {
11810 buffer.set_all_diff_hunks_expanded(cx);
11811 });
11812 }
11813
11814 pub fn expand_all_diff_hunks(
11815 &mut self,
11816 _: &ExpandAllHunkDiffs,
11817 _window: &mut Window,
11818 cx: &mut Context<Self>,
11819 ) {
11820 self.buffer.update(cx, |buffer, cx| {
11821 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
11822 });
11823 }
11824
11825 pub fn toggle_selected_diff_hunks(
11826 &mut self,
11827 _: &ToggleSelectedDiffHunks,
11828 _window: &mut Window,
11829 cx: &mut Context<Self>,
11830 ) {
11831 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
11832 self.toggle_diff_hunks_in_ranges(ranges, cx);
11833 }
11834
11835 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
11836 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
11837 self.buffer
11838 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
11839 }
11840
11841 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
11842 self.buffer.update(cx, |buffer, cx| {
11843 let ranges = vec![Anchor::min()..Anchor::max()];
11844 if !buffer.all_diff_hunks_expanded()
11845 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
11846 {
11847 buffer.collapse_diff_hunks(ranges, cx);
11848 true
11849 } else {
11850 false
11851 }
11852 })
11853 }
11854
11855 fn toggle_diff_hunks_in_ranges(
11856 &mut self,
11857 ranges: Vec<Range<Anchor>>,
11858 cx: &mut Context<'_, Editor>,
11859 ) {
11860 self.buffer.update(cx, |buffer, cx| {
11861 if buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx) {
11862 buffer.collapse_diff_hunks(ranges, cx)
11863 } else {
11864 buffer.expand_diff_hunks(ranges, cx)
11865 }
11866 })
11867 }
11868
11869 pub(crate) fn apply_all_diff_hunks(
11870 &mut self,
11871 _: &ApplyAllDiffHunks,
11872 window: &mut Window,
11873 cx: &mut Context<Self>,
11874 ) {
11875 let buffers = self.buffer.read(cx).all_buffers();
11876 for branch_buffer in buffers {
11877 branch_buffer.update(cx, |branch_buffer, cx| {
11878 branch_buffer.merge_into_base(Vec::new(), cx);
11879 });
11880 }
11881
11882 if let Some(project) = self.project.clone() {
11883 self.save(true, project, window, cx).detach_and_log_err(cx);
11884 }
11885 }
11886
11887 pub(crate) fn apply_selected_diff_hunks(
11888 &mut self,
11889 _: &ApplyDiffHunk,
11890 window: &mut Window,
11891 cx: &mut Context<Self>,
11892 ) {
11893 let snapshot = self.snapshot(window, cx);
11894 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
11895 let mut ranges_by_buffer = HashMap::default();
11896 self.transact(window, cx, |editor, _window, cx| {
11897 for hunk in hunks {
11898 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
11899 ranges_by_buffer
11900 .entry(buffer.clone())
11901 .or_insert_with(Vec::new)
11902 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
11903 }
11904 }
11905
11906 for (buffer, ranges) in ranges_by_buffer {
11907 buffer.update(cx, |buffer, cx| {
11908 buffer.merge_into_base(ranges, cx);
11909 });
11910 }
11911 });
11912
11913 if let Some(project) = self.project.clone() {
11914 self.save(true, project, window, cx).detach_and_log_err(cx);
11915 }
11916 }
11917
11918 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
11919 if hovered != self.gutter_hovered {
11920 self.gutter_hovered = hovered;
11921 cx.notify();
11922 }
11923 }
11924
11925 pub fn insert_blocks(
11926 &mut self,
11927 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11928 autoscroll: Option<Autoscroll>,
11929 cx: &mut Context<Self>,
11930 ) -> Vec<CustomBlockId> {
11931 let blocks = self
11932 .display_map
11933 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11934 if let Some(autoscroll) = autoscroll {
11935 self.request_autoscroll(autoscroll, cx);
11936 }
11937 cx.notify();
11938 blocks
11939 }
11940
11941 pub fn resize_blocks(
11942 &mut self,
11943 heights: HashMap<CustomBlockId, u32>,
11944 autoscroll: Option<Autoscroll>,
11945 cx: &mut Context<Self>,
11946 ) {
11947 self.display_map
11948 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11949 if let Some(autoscroll) = autoscroll {
11950 self.request_autoscroll(autoscroll, cx);
11951 }
11952 cx.notify();
11953 }
11954
11955 pub fn replace_blocks(
11956 &mut self,
11957 renderers: HashMap<CustomBlockId, RenderBlock>,
11958 autoscroll: Option<Autoscroll>,
11959 cx: &mut Context<Self>,
11960 ) {
11961 self.display_map
11962 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11963 if let Some(autoscroll) = autoscroll {
11964 self.request_autoscroll(autoscroll, cx);
11965 }
11966 cx.notify();
11967 }
11968
11969 pub fn remove_blocks(
11970 &mut self,
11971 block_ids: HashSet<CustomBlockId>,
11972 autoscroll: Option<Autoscroll>,
11973 cx: &mut Context<Self>,
11974 ) {
11975 self.display_map.update(cx, |display_map, cx| {
11976 display_map.remove_blocks(block_ids, cx)
11977 });
11978 if let Some(autoscroll) = autoscroll {
11979 self.request_autoscroll(autoscroll, cx);
11980 }
11981 cx.notify();
11982 }
11983
11984 pub fn row_for_block(
11985 &self,
11986 block_id: CustomBlockId,
11987 cx: &mut Context<Self>,
11988 ) -> Option<DisplayRow> {
11989 self.display_map
11990 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11991 }
11992
11993 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11994 self.focused_block = Some(focused_block);
11995 }
11996
11997 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11998 self.focused_block.take()
11999 }
12000
12001 pub fn insert_creases(
12002 &mut self,
12003 creases: impl IntoIterator<Item = Crease<Anchor>>,
12004 cx: &mut Context<Self>,
12005 ) -> Vec<CreaseId> {
12006 self.display_map
12007 .update(cx, |map, cx| map.insert_creases(creases, cx))
12008 }
12009
12010 pub fn remove_creases(
12011 &mut self,
12012 ids: impl IntoIterator<Item = CreaseId>,
12013 cx: &mut Context<Self>,
12014 ) {
12015 self.display_map
12016 .update(cx, |map, cx| map.remove_creases(ids, cx));
12017 }
12018
12019 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12020 self.display_map
12021 .update(cx, |map, cx| map.snapshot(cx))
12022 .longest_row()
12023 }
12024
12025 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12026 self.display_map
12027 .update(cx, |map, cx| map.snapshot(cx))
12028 .max_point()
12029 }
12030
12031 pub fn text(&self, cx: &App) -> String {
12032 self.buffer.read(cx).read(cx).text()
12033 }
12034
12035 pub fn text_option(&self, cx: &App) -> Option<String> {
12036 let text = self.text(cx);
12037 let text = text.trim();
12038
12039 if text.is_empty() {
12040 return None;
12041 }
12042
12043 Some(text.to_string())
12044 }
12045
12046 pub fn set_text(
12047 &mut self,
12048 text: impl Into<Arc<str>>,
12049 window: &mut Window,
12050 cx: &mut Context<Self>,
12051 ) {
12052 self.transact(window, cx, |this, _, cx| {
12053 this.buffer
12054 .read(cx)
12055 .as_singleton()
12056 .expect("you can only call set_text on editors for singleton buffers")
12057 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12058 });
12059 }
12060
12061 pub fn display_text(&self, cx: &mut App) -> String {
12062 self.display_map
12063 .update(cx, |map, cx| map.snapshot(cx))
12064 .text()
12065 }
12066
12067 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12068 let mut wrap_guides = smallvec::smallvec![];
12069
12070 if self.show_wrap_guides == Some(false) {
12071 return wrap_guides;
12072 }
12073
12074 let settings = self.buffer.read(cx).settings_at(0, cx);
12075 if settings.show_wrap_guides {
12076 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12077 wrap_guides.push((soft_wrap as usize, true));
12078 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12079 wrap_guides.push((soft_wrap as usize, true));
12080 }
12081 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12082 }
12083
12084 wrap_guides
12085 }
12086
12087 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12088 let settings = self.buffer.read(cx).settings_at(0, cx);
12089 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12090 match mode {
12091 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12092 SoftWrap::None
12093 }
12094 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12095 language_settings::SoftWrap::PreferredLineLength => {
12096 SoftWrap::Column(settings.preferred_line_length)
12097 }
12098 language_settings::SoftWrap::Bounded => {
12099 SoftWrap::Bounded(settings.preferred_line_length)
12100 }
12101 }
12102 }
12103
12104 pub fn set_soft_wrap_mode(
12105 &mut self,
12106 mode: language_settings::SoftWrap,
12107
12108 cx: &mut Context<Self>,
12109 ) {
12110 self.soft_wrap_mode_override = Some(mode);
12111 cx.notify();
12112 }
12113
12114 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12115 self.text_style_refinement = Some(style);
12116 }
12117
12118 /// called by the Element so we know what style we were most recently rendered with.
12119 pub(crate) fn set_style(
12120 &mut self,
12121 style: EditorStyle,
12122 window: &mut Window,
12123 cx: &mut Context<Self>,
12124 ) {
12125 let rem_size = window.rem_size();
12126 self.display_map.update(cx, |map, cx| {
12127 map.set_font(
12128 style.text.font(),
12129 style.text.font_size.to_pixels(rem_size),
12130 cx,
12131 )
12132 });
12133 self.style = Some(style);
12134 }
12135
12136 pub fn style(&self) -> Option<&EditorStyle> {
12137 self.style.as_ref()
12138 }
12139
12140 // Called by the element. This method is not designed to be called outside of the editor
12141 // element's layout code because it does not notify when rewrapping is computed synchronously.
12142 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12143 self.display_map
12144 .update(cx, |map, cx| map.set_wrap_width(width, cx))
12145 }
12146
12147 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12148 if self.soft_wrap_mode_override.is_some() {
12149 self.soft_wrap_mode_override.take();
12150 } else {
12151 let soft_wrap = match self.soft_wrap_mode(cx) {
12152 SoftWrap::GitDiff => return,
12153 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12154 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12155 language_settings::SoftWrap::None
12156 }
12157 };
12158 self.soft_wrap_mode_override = Some(soft_wrap);
12159 }
12160 cx.notify();
12161 }
12162
12163 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12164 let Some(workspace) = self.workspace() else {
12165 return;
12166 };
12167 let fs = workspace.read(cx).app_state().fs.clone();
12168 let current_show = TabBarSettings::get_global(cx).show;
12169 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12170 setting.show = Some(!current_show);
12171 });
12172 }
12173
12174 pub fn toggle_indent_guides(
12175 &mut self,
12176 _: &ToggleIndentGuides,
12177 _: &mut Window,
12178 cx: &mut Context<Self>,
12179 ) {
12180 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12181 self.buffer
12182 .read(cx)
12183 .settings_at(0, cx)
12184 .indent_guides
12185 .enabled
12186 });
12187 self.show_indent_guides = Some(!currently_enabled);
12188 cx.notify();
12189 }
12190
12191 fn should_show_indent_guides(&self) -> Option<bool> {
12192 self.show_indent_guides
12193 }
12194
12195 pub fn toggle_line_numbers(
12196 &mut self,
12197 _: &ToggleLineNumbers,
12198 _: &mut Window,
12199 cx: &mut Context<Self>,
12200 ) {
12201 let mut editor_settings = EditorSettings::get_global(cx).clone();
12202 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12203 EditorSettings::override_global(editor_settings, cx);
12204 }
12205
12206 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12207 self.use_relative_line_numbers
12208 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12209 }
12210
12211 pub fn toggle_relative_line_numbers(
12212 &mut self,
12213 _: &ToggleRelativeLineNumbers,
12214 _: &mut Window,
12215 cx: &mut Context<Self>,
12216 ) {
12217 let is_relative = self.should_use_relative_line_numbers(cx);
12218 self.set_relative_line_number(Some(!is_relative), cx)
12219 }
12220
12221 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12222 self.use_relative_line_numbers = is_relative;
12223 cx.notify();
12224 }
12225
12226 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12227 self.show_gutter = show_gutter;
12228 cx.notify();
12229 }
12230
12231 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12232 self.show_scrollbars = show_scrollbars;
12233 cx.notify();
12234 }
12235
12236 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12237 self.show_line_numbers = Some(show_line_numbers);
12238 cx.notify();
12239 }
12240
12241 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12242 self.show_git_diff_gutter = Some(show_git_diff_gutter);
12243 cx.notify();
12244 }
12245
12246 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12247 self.show_code_actions = Some(show_code_actions);
12248 cx.notify();
12249 }
12250
12251 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12252 self.show_runnables = Some(show_runnables);
12253 cx.notify();
12254 }
12255
12256 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12257 if self.display_map.read(cx).masked != masked {
12258 self.display_map.update(cx, |map, _| map.masked = masked);
12259 }
12260 cx.notify()
12261 }
12262
12263 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12264 self.show_wrap_guides = Some(show_wrap_guides);
12265 cx.notify();
12266 }
12267
12268 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12269 self.show_indent_guides = Some(show_indent_guides);
12270 cx.notify();
12271 }
12272
12273 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12274 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12275 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12276 if let Some(dir) = file.abs_path(cx).parent() {
12277 return Some(dir.to_owned());
12278 }
12279 }
12280
12281 if let Some(project_path) = buffer.read(cx).project_path(cx) {
12282 return Some(project_path.path.to_path_buf());
12283 }
12284 }
12285
12286 None
12287 }
12288
12289 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12290 self.active_excerpt(cx)?
12291 .1
12292 .read(cx)
12293 .file()
12294 .and_then(|f| f.as_local())
12295 }
12296
12297 fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12298 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12299 let project_path = buffer.read(cx).project_path(cx)?;
12300 let project = self.project.as_ref()?.read(cx);
12301 project.absolute_path(&project_path, cx)
12302 })
12303 }
12304
12305 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12306 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12307 let project_path = buffer.read(cx).project_path(cx)?;
12308 let project = self.project.as_ref()?.read(cx);
12309 let entry = project.entry_for_path(&project_path, cx)?;
12310 let path = entry.path.to_path_buf();
12311 Some(path)
12312 })
12313 }
12314
12315 pub fn reveal_in_finder(
12316 &mut self,
12317 _: &RevealInFileManager,
12318 _window: &mut Window,
12319 cx: &mut Context<Self>,
12320 ) {
12321 if let Some(target) = self.target_file(cx) {
12322 cx.reveal_path(&target.abs_path(cx));
12323 }
12324 }
12325
12326 pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12327 if let Some(path) = self.target_file_abs_path(cx) {
12328 if let Some(path) = path.to_str() {
12329 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12330 }
12331 }
12332 }
12333
12334 pub fn copy_relative_path(
12335 &mut self,
12336 _: &CopyRelativePath,
12337 _window: &mut Window,
12338 cx: &mut Context<Self>,
12339 ) {
12340 if let Some(path) = self.target_file_path(cx) {
12341 if let Some(path) = path.to_str() {
12342 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12343 }
12344 }
12345 }
12346
12347 pub fn toggle_git_blame(
12348 &mut self,
12349 _: &ToggleGitBlame,
12350 window: &mut Window,
12351 cx: &mut Context<Self>,
12352 ) {
12353 self.show_git_blame_gutter = !self.show_git_blame_gutter;
12354
12355 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12356 self.start_git_blame(true, window, cx);
12357 }
12358
12359 cx.notify();
12360 }
12361
12362 pub fn toggle_git_blame_inline(
12363 &mut self,
12364 _: &ToggleGitBlameInline,
12365 window: &mut Window,
12366 cx: &mut Context<Self>,
12367 ) {
12368 self.toggle_git_blame_inline_internal(true, window, cx);
12369 cx.notify();
12370 }
12371
12372 pub fn git_blame_inline_enabled(&self) -> bool {
12373 self.git_blame_inline_enabled
12374 }
12375
12376 pub fn toggle_selection_menu(
12377 &mut self,
12378 _: &ToggleSelectionMenu,
12379 _: &mut Window,
12380 cx: &mut Context<Self>,
12381 ) {
12382 self.show_selection_menu = self
12383 .show_selection_menu
12384 .map(|show_selections_menu| !show_selections_menu)
12385 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12386
12387 cx.notify();
12388 }
12389
12390 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12391 self.show_selection_menu
12392 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12393 }
12394
12395 fn start_git_blame(
12396 &mut self,
12397 user_triggered: bool,
12398 window: &mut Window,
12399 cx: &mut Context<Self>,
12400 ) {
12401 if let Some(project) = self.project.as_ref() {
12402 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12403 return;
12404 };
12405
12406 if buffer.read(cx).file().is_none() {
12407 return;
12408 }
12409
12410 let focused = self.focus_handle(cx).contains_focused(window, cx);
12411
12412 let project = project.clone();
12413 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12414 self.blame_subscription =
12415 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12416 self.blame = Some(blame);
12417 }
12418 }
12419
12420 fn toggle_git_blame_inline_internal(
12421 &mut self,
12422 user_triggered: bool,
12423 window: &mut Window,
12424 cx: &mut Context<Self>,
12425 ) {
12426 if self.git_blame_inline_enabled {
12427 self.git_blame_inline_enabled = false;
12428 self.show_git_blame_inline = false;
12429 self.show_git_blame_inline_delay_task.take();
12430 } else {
12431 self.git_blame_inline_enabled = true;
12432 self.start_git_blame_inline(user_triggered, window, cx);
12433 }
12434
12435 cx.notify();
12436 }
12437
12438 fn start_git_blame_inline(
12439 &mut self,
12440 user_triggered: bool,
12441 window: &mut Window,
12442 cx: &mut Context<Self>,
12443 ) {
12444 self.start_git_blame(user_triggered, window, cx);
12445
12446 if ProjectSettings::get_global(cx)
12447 .git
12448 .inline_blame_delay()
12449 .is_some()
12450 {
12451 self.start_inline_blame_timer(window, cx);
12452 } else {
12453 self.show_git_blame_inline = true
12454 }
12455 }
12456
12457 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12458 self.blame.as_ref()
12459 }
12460
12461 pub fn show_git_blame_gutter(&self) -> bool {
12462 self.show_git_blame_gutter
12463 }
12464
12465 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12466 self.show_git_blame_gutter && self.has_blame_entries(cx)
12467 }
12468
12469 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12470 self.show_git_blame_inline
12471 && self.focus_handle.is_focused(window)
12472 && !self.newest_selection_head_on_empty_line(cx)
12473 && self.has_blame_entries(cx)
12474 }
12475
12476 fn has_blame_entries(&self, cx: &App) -> bool {
12477 self.blame()
12478 .map_or(false, |blame| blame.read(cx).has_generated_entries())
12479 }
12480
12481 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12482 let cursor_anchor = self.selections.newest_anchor().head();
12483
12484 let snapshot = self.buffer.read(cx).snapshot(cx);
12485 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12486
12487 snapshot.line_len(buffer_row) == 0
12488 }
12489
12490 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12491 let buffer_and_selection = maybe!({
12492 let selection = self.selections.newest::<Point>(cx);
12493 let selection_range = selection.range();
12494
12495 let multi_buffer = self.buffer().read(cx);
12496 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12497 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12498
12499 let (buffer, range, _) = if selection.reversed {
12500 buffer_ranges.first()
12501 } else {
12502 buffer_ranges.last()
12503 }?;
12504
12505 let selection = text::ToPoint::to_point(&range.start, &buffer).row
12506 ..text::ToPoint::to_point(&range.end, &buffer).row;
12507 Some((
12508 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
12509 selection,
12510 ))
12511 });
12512
12513 let Some((buffer, selection)) = buffer_and_selection else {
12514 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12515 };
12516
12517 let Some(project) = self.project.as_ref() else {
12518 return Task::ready(Err(anyhow!("editor does not have project")));
12519 };
12520
12521 project.update(cx, |project, cx| {
12522 project.get_permalink_to_line(&buffer, selection, cx)
12523 })
12524 }
12525
12526 pub fn copy_permalink_to_line(
12527 &mut self,
12528 _: &CopyPermalinkToLine,
12529 window: &mut Window,
12530 cx: &mut Context<Self>,
12531 ) {
12532 let permalink_task = self.get_permalink_to_line(cx);
12533 let workspace = self.workspace();
12534
12535 cx.spawn_in(window, |_, mut cx| async move {
12536 match permalink_task.await {
12537 Ok(permalink) => {
12538 cx.update(|_, cx| {
12539 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12540 })
12541 .ok();
12542 }
12543 Err(err) => {
12544 let message = format!("Failed to copy permalink: {err}");
12545
12546 Err::<(), anyhow::Error>(err).log_err();
12547
12548 if let Some(workspace) = workspace {
12549 workspace
12550 .update_in(&mut cx, |workspace, _, cx| {
12551 struct CopyPermalinkToLine;
12552
12553 workspace.show_toast(
12554 Toast::new(
12555 NotificationId::unique::<CopyPermalinkToLine>(),
12556 message,
12557 ),
12558 cx,
12559 )
12560 })
12561 .ok();
12562 }
12563 }
12564 }
12565 })
12566 .detach();
12567 }
12568
12569 pub fn copy_file_location(
12570 &mut self,
12571 _: &CopyFileLocation,
12572 _: &mut Window,
12573 cx: &mut Context<Self>,
12574 ) {
12575 let selection = self.selections.newest::<Point>(cx).start.row + 1;
12576 if let Some(file) = self.target_file(cx) {
12577 if let Some(path) = file.path().to_str() {
12578 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
12579 }
12580 }
12581 }
12582
12583 pub fn open_permalink_to_line(
12584 &mut self,
12585 _: &OpenPermalinkToLine,
12586 window: &mut Window,
12587 cx: &mut Context<Self>,
12588 ) {
12589 let permalink_task = self.get_permalink_to_line(cx);
12590 let workspace = self.workspace();
12591
12592 cx.spawn_in(window, |_, mut cx| async move {
12593 match permalink_task.await {
12594 Ok(permalink) => {
12595 cx.update(|_, cx| {
12596 cx.open_url(permalink.as_ref());
12597 })
12598 .ok();
12599 }
12600 Err(err) => {
12601 let message = format!("Failed to open permalink: {err}");
12602
12603 Err::<(), anyhow::Error>(err).log_err();
12604
12605 if let Some(workspace) = workspace {
12606 workspace
12607 .update(&mut cx, |workspace, cx| {
12608 struct OpenPermalinkToLine;
12609
12610 workspace.show_toast(
12611 Toast::new(
12612 NotificationId::unique::<OpenPermalinkToLine>(),
12613 message,
12614 ),
12615 cx,
12616 )
12617 })
12618 .ok();
12619 }
12620 }
12621 }
12622 })
12623 .detach();
12624 }
12625
12626 pub fn insert_uuid_v4(
12627 &mut self,
12628 _: &InsertUuidV4,
12629 window: &mut Window,
12630 cx: &mut Context<Self>,
12631 ) {
12632 self.insert_uuid(UuidVersion::V4, window, cx);
12633 }
12634
12635 pub fn insert_uuid_v7(
12636 &mut self,
12637 _: &InsertUuidV7,
12638 window: &mut Window,
12639 cx: &mut Context<Self>,
12640 ) {
12641 self.insert_uuid(UuidVersion::V7, window, cx);
12642 }
12643
12644 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
12645 self.transact(window, cx, |this, window, cx| {
12646 let edits = this
12647 .selections
12648 .all::<Point>(cx)
12649 .into_iter()
12650 .map(|selection| {
12651 let uuid = match version {
12652 UuidVersion::V4 => uuid::Uuid::new_v4(),
12653 UuidVersion::V7 => uuid::Uuid::now_v7(),
12654 };
12655
12656 (selection.range(), uuid.to_string())
12657 });
12658 this.edit(edits, cx);
12659 this.refresh_inline_completion(true, false, window, cx);
12660 });
12661 }
12662
12663 pub fn open_selections_in_multibuffer(
12664 &mut self,
12665 _: &OpenSelectionsInMultibuffer,
12666 window: &mut Window,
12667 cx: &mut Context<Self>,
12668 ) {
12669 let multibuffer = self.buffer.read(cx);
12670
12671 let Some(buffer) = multibuffer.as_singleton() else {
12672 return;
12673 };
12674
12675 let Some(workspace) = self.workspace() else {
12676 return;
12677 };
12678
12679 let locations = self
12680 .selections
12681 .disjoint_anchors()
12682 .iter()
12683 .map(|range| Location {
12684 buffer: buffer.clone(),
12685 range: range.start.text_anchor..range.end.text_anchor,
12686 })
12687 .collect::<Vec<_>>();
12688
12689 let title = multibuffer.title(cx).to_string();
12690
12691 cx.spawn_in(window, |_, mut cx| async move {
12692 workspace.update_in(&mut cx, |workspace, window, cx| {
12693 Self::open_locations_in_multibuffer(
12694 workspace,
12695 locations,
12696 format!("Selections for '{title}'"),
12697 false,
12698 MultibufferSelectionMode::All,
12699 window,
12700 cx,
12701 );
12702 })
12703 })
12704 .detach();
12705 }
12706
12707 /// Adds a row highlight for the given range. If a row has multiple highlights, the
12708 /// last highlight added will be used.
12709 ///
12710 /// If the range ends at the beginning of a line, then that line will not be highlighted.
12711 pub fn highlight_rows<T: 'static>(
12712 &mut self,
12713 range: Range<Anchor>,
12714 color: Hsla,
12715 should_autoscroll: bool,
12716 cx: &mut Context<Self>,
12717 ) {
12718 let snapshot = self.buffer().read(cx).snapshot(cx);
12719 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12720 let ix = row_highlights.binary_search_by(|highlight| {
12721 Ordering::Equal
12722 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
12723 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
12724 });
12725
12726 if let Err(mut ix) = ix {
12727 let index = post_inc(&mut self.highlight_order);
12728
12729 // If this range intersects with the preceding highlight, then merge it with
12730 // the preceding highlight. Otherwise insert a new highlight.
12731 let mut merged = false;
12732 if ix > 0 {
12733 let prev_highlight = &mut row_highlights[ix - 1];
12734 if prev_highlight
12735 .range
12736 .end
12737 .cmp(&range.start, &snapshot)
12738 .is_ge()
12739 {
12740 ix -= 1;
12741 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12742 prev_highlight.range.end = range.end;
12743 }
12744 merged = true;
12745 prev_highlight.index = index;
12746 prev_highlight.color = color;
12747 prev_highlight.should_autoscroll = should_autoscroll;
12748 }
12749 }
12750
12751 if !merged {
12752 row_highlights.insert(
12753 ix,
12754 RowHighlight {
12755 range: range.clone(),
12756 index,
12757 color,
12758 should_autoscroll,
12759 },
12760 );
12761 }
12762
12763 // If any of the following highlights intersect with this one, merge them.
12764 while let Some(next_highlight) = row_highlights.get(ix + 1) {
12765 let highlight = &row_highlights[ix];
12766 if next_highlight
12767 .range
12768 .start
12769 .cmp(&highlight.range.end, &snapshot)
12770 .is_le()
12771 {
12772 if next_highlight
12773 .range
12774 .end
12775 .cmp(&highlight.range.end, &snapshot)
12776 .is_gt()
12777 {
12778 row_highlights[ix].range.end = next_highlight.range.end;
12779 }
12780 row_highlights.remove(ix + 1);
12781 } else {
12782 break;
12783 }
12784 }
12785 }
12786 }
12787
12788 /// Remove any highlighted row ranges of the given type that intersect the
12789 /// given ranges.
12790 pub fn remove_highlighted_rows<T: 'static>(
12791 &mut self,
12792 ranges_to_remove: Vec<Range<Anchor>>,
12793 cx: &mut Context<Self>,
12794 ) {
12795 let snapshot = self.buffer().read(cx).snapshot(cx);
12796 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12797 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
12798 row_highlights.retain(|highlight| {
12799 while let Some(range_to_remove) = ranges_to_remove.peek() {
12800 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
12801 Ordering::Less | Ordering::Equal => {
12802 ranges_to_remove.next();
12803 }
12804 Ordering::Greater => {
12805 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
12806 Ordering::Less | Ordering::Equal => {
12807 return false;
12808 }
12809 Ordering::Greater => break,
12810 }
12811 }
12812 }
12813 }
12814
12815 true
12816 })
12817 }
12818
12819 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
12820 pub fn clear_row_highlights<T: 'static>(&mut self) {
12821 self.highlighted_rows.remove(&TypeId::of::<T>());
12822 }
12823
12824 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
12825 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
12826 self.highlighted_rows
12827 .get(&TypeId::of::<T>())
12828 .map_or(&[] as &[_], |vec| vec.as_slice())
12829 .iter()
12830 .map(|highlight| (highlight.range.clone(), highlight.color))
12831 }
12832
12833 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
12834 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
12835 /// Allows to ignore certain kinds of highlights.
12836 pub fn highlighted_display_rows(
12837 &self,
12838 window: &mut Window,
12839 cx: &mut App,
12840 ) -> BTreeMap<DisplayRow, Hsla> {
12841 let snapshot = self.snapshot(window, cx);
12842 let mut used_highlight_orders = HashMap::default();
12843 self.highlighted_rows
12844 .iter()
12845 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
12846 .fold(
12847 BTreeMap::<DisplayRow, Hsla>::new(),
12848 |mut unique_rows, highlight| {
12849 let start = highlight.range.start.to_display_point(&snapshot);
12850 let end = highlight.range.end.to_display_point(&snapshot);
12851 let start_row = start.row().0;
12852 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
12853 && end.column() == 0
12854 {
12855 end.row().0.saturating_sub(1)
12856 } else {
12857 end.row().0
12858 };
12859 for row in start_row..=end_row {
12860 let used_index =
12861 used_highlight_orders.entry(row).or_insert(highlight.index);
12862 if highlight.index >= *used_index {
12863 *used_index = highlight.index;
12864 unique_rows.insert(DisplayRow(row), highlight.color);
12865 }
12866 }
12867 unique_rows
12868 },
12869 )
12870 }
12871
12872 pub fn highlighted_display_row_for_autoscroll(
12873 &self,
12874 snapshot: &DisplaySnapshot,
12875 ) -> Option<DisplayRow> {
12876 self.highlighted_rows
12877 .values()
12878 .flat_map(|highlighted_rows| highlighted_rows.iter())
12879 .filter_map(|highlight| {
12880 if highlight.should_autoscroll {
12881 Some(highlight.range.start.to_display_point(snapshot).row())
12882 } else {
12883 None
12884 }
12885 })
12886 .min()
12887 }
12888
12889 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
12890 self.highlight_background::<SearchWithinRange>(
12891 ranges,
12892 |colors| colors.editor_document_highlight_read_background,
12893 cx,
12894 )
12895 }
12896
12897 pub fn set_breadcrumb_header(&mut self, new_header: String) {
12898 self.breadcrumb_header = Some(new_header);
12899 }
12900
12901 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
12902 self.clear_background_highlights::<SearchWithinRange>(cx);
12903 }
12904
12905 pub fn highlight_background<T: 'static>(
12906 &mut self,
12907 ranges: &[Range<Anchor>],
12908 color_fetcher: fn(&ThemeColors) -> Hsla,
12909 cx: &mut Context<Self>,
12910 ) {
12911 self.background_highlights
12912 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12913 self.scrollbar_marker_state.dirty = true;
12914 cx.notify();
12915 }
12916
12917 pub fn clear_background_highlights<T: 'static>(
12918 &mut self,
12919 cx: &mut Context<Self>,
12920 ) -> Option<BackgroundHighlight> {
12921 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12922 if !text_highlights.1.is_empty() {
12923 self.scrollbar_marker_state.dirty = true;
12924 cx.notify();
12925 }
12926 Some(text_highlights)
12927 }
12928
12929 pub fn highlight_gutter<T: 'static>(
12930 &mut self,
12931 ranges: &[Range<Anchor>],
12932 color_fetcher: fn(&App) -> Hsla,
12933 cx: &mut Context<Self>,
12934 ) {
12935 self.gutter_highlights
12936 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12937 cx.notify();
12938 }
12939
12940 pub fn clear_gutter_highlights<T: 'static>(
12941 &mut self,
12942 cx: &mut Context<Self>,
12943 ) -> Option<GutterHighlight> {
12944 cx.notify();
12945 self.gutter_highlights.remove(&TypeId::of::<T>())
12946 }
12947
12948 #[cfg(feature = "test-support")]
12949 pub fn all_text_background_highlights(
12950 &self,
12951 window: &mut Window,
12952 cx: &mut Context<Self>,
12953 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12954 let snapshot = self.snapshot(window, cx);
12955 let buffer = &snapshot.buffer_snapshot;
12956 let start = buffer.anchor_before(0);
12957 let end = buffer.anchor_after(buffer.len());
12958 let theme = cx.theme().colors();
12959 self.background_highlights_in_range(start..end, &snapshot, theme)
12960 }
12961
12962 #[cfg(feature = "test-support")]
12963 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
12964 let snapshot = self.buffer().read(cx).snapshot(cx);
12965
12966 let highlights = self
12967 .background_highlights
12968 .get(&TypeId::of::<items::BufferSearchHighlights>());
12969
12970 if let Some((_color, ranges)) = highlights {
12971 ranges
12972 .iter()
12973 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12974 .collect_vec()
12975 } else {
12976 vec![]
12977 }
12978 }
12979
12980 fn document_highlights_for_position<'a>(
12981 &'a self,
12982 position: Anchor,
12983 buffer: &'a MultiBufferSnapshot,
12984 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12985 let read_highlights = self
12986 .background_highlights
12987 .get(&TypeId::of::<DocumentHighlightRead>())
12988 .map(|h| &h.1);
12989 let write_highlights = self
12990 .background_highlights
12991 .get(&TypeId::of::<DocumentHighlightWrite>())
12992 .map(|h| &h.1);
12993 let left_position = position.bias_left(buffer);
12994 let right_position = position.bias_right(buffer);
12995 read_highlights
12996 .into_iter()
12997 .chain(write_highlights)
12998 .flat_map(move |ranges| {
12999 let start_ix = match ranges.binary_search_by(|probe| {
13000 let cmp = probe.end.cmp(&left_position, buffer);
13001 if cmp.is_ge() {
13002 Ordering::Greater
13003 } else {
13004 Ordering::Less
13005 }
13006 }) {
13007 Ok(i) | Err(i) => i,
13008 };
13009
13010 ranges[start_ix..]
13011 .iter()
13012 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13013 })
13014 }
13015
13016 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13017 self.background_highlights
13018 .get(&TypeId::of::<T>())
13019 .map_or(false, |(_, highlights)| !highlights.is_empty())
13020 }
13021
13022 pub fn background_highlights_in_range(
13023 &self,
13024 search_range: Range<Anchor>,
13025 display_snapshot: &DisplaySnapshot,
13026 theme: &ThemeColors,
13027 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13028 let mut results = Vec::new();
13029 for (color_fetcher, ranges) in self.background_highlights.values() {
13030 let color = color_fetcher(theme);
13031 let start_ix = match ranges.binary_search_by(|probe| {
13032 let cmp = probe
13033 .end
13034 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13035 if cmp.is_gt() {
13036 Ordering::Greater
13037 } else {
13038 Ordering::Less
13039 }
13040 }) {
13041 Ok(i) | Err(i) => i,
13042 };
13043 for range in &ranges[start_ix..] {
13044 if range
13045 .start
13046 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13047 .is_ge()
13048 {
13049 break;
13050 }
13051
13052 let start = range.start.to_display_point(display_snapshot);
13053 let end = range.end.to_display_point(display_snapshot);
13054 results.push((start..end, color))
13055 }
13056 }
13057 results
13058 }
13059
13060 pub fn background_highlight_row_ranges<T: 'static>(
13061 &self,
13062 search_range: Range<Anchor>,
13063 display_snapshot: &DisplaySnapshot,
13064 count: usize,
13065 ) -> Vec<RangeInclusive<DisplayPoint>> {
13066 let mut results = Vec::new();
13067 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13068 return vec![];
13069 };
13070
13071 let start_ix = match ranges.binary_search_by(|probe| {
13072 let cmp = probe
13073 .end
13074 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13075 if cmp.is_gt() {
13076 Ordering::Greater
13077 } else {
13078 Ordering::Less
13079 }
13080 }) {
13081 Ok(i) | Err(i) => i,
13082 };
13083 let mut push_region = |start: Option<Point>, end: Option<Point>| {
13084 if let (Some(start_display), Some(end_display)) = (start, end) {
13085 results.push(
13086 start_display.to_display_point(display_snapshot)
13087 ..=end_display.to_display_point(display_snapshot),
13088 );
13089 }
13090 };
13091 let mut start_row: Option<Point> = None;
13092 let mut end_row: Option<Point> = None;
13093 if ranges.len() > count {
13094 return Vec::new();
13095 }
13096 for range in &ranges[start_ix..] {
13097 if range
13098 .start
13099 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13100 .is_ge()
13101 {
13102 break;
13103 }
13104 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13105 if let Some(current_row) = &end_row {
13106 if end.row == current_row.row {
13107 continue;
13108 }
13109 }
13110 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13111 if start_row.is_none() {
13112 assert_eq!(end_row, None);
13113 start_row = Some(start);
13114 end_row = Some(end);
13115 continue;
13116 }
13117 if let Some(current_end) = end_row.as_mut() {
13118 if start.row > current_end.row + 1 {
13119 push_region(start_row, end_row);
13120 start_row = Some(start);
13121 end_row = Some(end);
13122 } else {
13123 // Merge two hunks.
13124 *current_end = end;
13125 }
13126 } else {
13127 unreachable!();
13128 }
13129 }
13130 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13131 push_region(start_row, end_row);
13132 results
13133 }
13134
13135 pub fn gutter_highlights_in_range(
13136 &self,
13137 search_range: Range<Anchor>,
13138 display_snapshot: &DisplaySnapshot,
13139 cx: &App,
13140 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13141 let mut results = Vec::new();
13142 for (color_fetcher, ranges) in self.gutter_highlights.values() {
13143 let color = color_fetcher(cx);
13144 let start_ix = match ranges.binary_search_by(|probe| {
13145 let cmp = probe
13146 .end
13147 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13148 if cmp.is_gt() {
13149 Ordering::Greater
13150 } else {
13151 Ordering::Less
13152 }
13153 }) {
13154 Ok(i) | Err(i) => i,
13155 };
13156 for range in &ranges[start_ix..] {
13157 if range
13158 .start
13159 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13160 .is_ge()
13161 {
13162 break;
13163 }
13164
13165 let start = range.start.to_display_point(display_snapshot);
13166 let end = range.end.to_display_point(display_snapshot);
13167 results.push((start..end, color))
13168 }
13169 }
13170 results
13171 }
13172
13173 /// Get the text ranges corresponding to the redaction query
13174 pub fn redacted_ranges(
13175 &self,
13176 search_range: Range<Anchor>,
13177 display_snapshot: &DisplaySnapshot,
13178 cx: &App,
13179 ) -> Vec<Range<DisplayPoint>> {
13180 display_snapshot
13181 .buffer_snapshot
13182 .redacted_ranges(search_range, |file| {
13183 if let Some(file) = file {
13184 file.is_private()
13185 && EditorSettings::get(
13186 Some(SettingsLocation {
13187 worktree_id: file.worktree_id(cx),
13188 path: file.path().as_ref(),
13189 }),
13190 cx,
13191 )
13192 .redact_private_values
13193 } else {
13194 false
13195 }
13196 })
13197 .map(|range| {
13198 range.start.to_display_point(display_snapshot)
13199 ..range.end.to_display_point(display_snapshot)
13200 })
13201 .collect()
13202 }
13203
13204 pub fn highlight_text<T: 'static>(
13205 &mut self,
13206 ranges: Vec<Range<Anchor>>,
13207 style: HighlightStyle,
13208 cx: &mut Context<Self>,
13209 ) {
13210 self.display_map.update(cx, |map, _| {
13211 map.highlight_text(TypeId::of::<T>(), ranges, style)
13212 });
13213 cx.notify();
13214 }
13215
13216 pub(crate) fn highlight_inlays<T: 'static>(
13217 &mut self,
13218 highlights: Vec<InlayHighlight>,
13219 style: HighlightStyle,
13220 cx: &mut Context<Self>,
13221 ) {
13222 self.display_map.update(cx, |map, _| {
13223 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13224 });
13225 cx.notify();
13226 }
13227
13228 pub fn text_highlights<'a, T: 'static>(
13229 &'a self,
13230 cx: &'a App,
13231 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13232 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13233 }
13234
13235 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13236 let cleared = self
13237 .display_map
13238 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13239 if cleared {
13240 cx.notify();
13241 }
13242 }
13243
13244 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13245 (self.read_only(cx) || self.blink_manager.read(cx).visible())
13246 && self.focus_handle.is_focused(window)
13247 }
13248
13249 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13250 self.show_cursor_when_unfocused = is_enabled;
13251 cx.notify();
13252 }
13253
13254 pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13255 self.project
13256 .as_ref()
13257 .map(|project| project.read(cx).lsp_store())
13258 }
13259
13260 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13261 cx.notify();
13262 }
13263
13264 fn on_buffer_event(
13265 &mut self,
13266 multibuffer: &Entity<MultiBuffer>,
13267 event: &multi_buffer::Event,
13268 window: &mut Window,
13269 cx: &mut Context<Self>,
13270 ) {
13271 match event {
13272 multi_buffer::Event::Edited {
13273 singleton_buffer_edited,
13274 edited_buffer: buffer_edited,
13275 } => {
13276 self.scrollbar_marker_state.dirty = true;
13277 self.active_indent_guides_state.dirty = true;
13278 self.refresh_active_diagnostics(cx);
13279 self.refresh_code_actions(window, cx);
13280 if self.has_active_inline_completion() {
13281 self.update_visible_inline_completion(window, cx);
13282 }
13283 if let Some(buffer) = buffer_edited {
13284 let buffer_id = buffer.read(cx).remote_id();
13285 if !self.registered_buffers.contains_key(&buffer_id) {
13286 if let Some(lsp_store) = self.lsp_store(cx) {
13287 lsp_store.update(cx, |lsp_store, cx| {
13288 self.registered_buffers.insert(
13289 buffer_id,
13290 lsp_store.register_buffer_with_language_servers(&buffer, cx),
13291 );
13292 })
13293 }
13294 }
13295 }
13296 cx.emit(EditorEvent::BufferEdited);
13297 cx.emit(SearchEvent::MatchesInvalidated);
13298 if *singleton_buffer_edited {
13299 if let Some(project) = &self.project {
13300 #[allow(clippy::mutable_key_type)]
13301 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
13302 multibuffer
13303 .all_buffers()
13304 .into_iter()
13305 .filter_map(|buffer| {
13306 buffer.update(cx, |buffer, cx| {
13307 let language = buffer.language()?;
13308 let should_discard = project.update(cx, |project, cx| {
13309 project.is_local()
13310 && project.for_language_servers_for_local_buffer(
13311 buffer,
13312 |it| it.count() == 0,
13313 cx,
13314 )
13315 });
13316 should_discard.not().then_some(language.clone())
13317 })
13318 })
13319 .collect::<HashSet<_>>()
13320 });
13321 if !languages_affected.is_empty() {
13322 self.refresh_inlay_hints(
13323 InlayHintRefreshReason::BufferEdited(languages_affected),
13324 cx,
13325 );
13326 }
13327 }
13328 }
13329
13330 let Some(project) = &self.project else { return };
13331 let (telemetry, is_via_ssh) = {
13332 let project = project.read(cx);
13333 let telemetry = project.client().telemetry().clone();
13334 let is_via_ssh = project.is_via_ssh();
13335 (telemetry, is_via_ssh)
13336 };
13337 refresh_linked_ranges(self, window, cx);
13338 telemetry.log_edit_event("editor", is_via_ssh);
13339 }
13340 multi_buffer::Event::ExcerptsAdded {
13341 buffer,
13342 predecessor,
13343 excerpts,
13344 } => {
13345 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13346 let buffer_id = buffer.read(cx).remote_id();
13347 if self.buffer.read(cx).change_set_for(buffer_id).is_none() {
13348 if let Some(project) = &self.project {
13349 get_unstaged_changes_for_buffers(
13350 project,
13351 [buffer.clone()],
13352 self.buffer.clone(),
13353 cx,
13354 );
13355 }
13356 }
13357 cx.emit(EditorEvent::ExcerptsAdded {
13358 buffer: buffer.clone(),
13359 predecessor: *predecessor,
13360 excerpts: excerpts.clone(),
13361 });
13362 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13363 }
13364 multi_buffer::Event::ExcerptsRemoved { ids } => {
13365 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13366 let buffer = self.buffer.read(cx);
13367 self.registered_buffers
13368 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13369 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13370 }
13371 multi_buffer::Event::ExcerptsEdited { ids } => {
13372 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13373 }
13374 multi_buffer::Event::ExcerptsExpanded { ids } => {
13375 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13376 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13377 }
13378 multi_buffer::Event::Reparsed(buffer_id) => {
13379 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13380
13381 cx.emit(EditorEvent::Reparsed(*buffer_id));
13382 }
13383 multi_buffer::Event::DiffHunksToggled => {
13384 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13385 }
13386 multi_buffer::Event::LanguageChanged(buffer_id) => {
13387 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13388 cx.emit(EditorEvent::Reparsed(*buffer_id));
13389 cx.notify();
13390 }
13391 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13392 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13393 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13394 cx.emit(EditorEvent::TitleChanged)
13395 }
13396 // multi_buffer::Event::DiffBaseChanged => {
13397 // self.scrollbar_marker_state.dirty = true;
13398 // cx.emit(EditorEvent::DiffBaseChanged);
13399 // cx.notify();
13400 // }
13401 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13402 multi_buffer::Event::DiagnosticsUpdated => {
13403 self.refresh_active_diagnostics(cx);
13404 self.scrollbar_marker_state.dirty = true;
13405 cx.notify();
13406 }
13407 _ => {}
13408 };
13409 }
13410
13411 fn on_display_map_changed(
13412 &mut self,
13413 _: Entity<DisplayMap>,
13414 _: &mut Window,
13415 cx: &mut Context<Self>,
13416 ) {
13417 cx.notify();
13418 }
13419
13420 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13421 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13422 self.refresh_inline_completion(true, false, window, cx);
13423 self.refresh_inlay_hints(
13424 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13425 self.selections.newest_anchor().head(),
13426 &self.buffer.read(cx).snapshot(cx),
13427 cx,
13428 )),
13429 cx,
13430 );
13431
13432 let old_cursor_shape = self.cursor_shape;
13433
13434 {
13435 let editor_settings = EditorSettings::get_global(cx);
13436 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13437 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13438 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13439 }
13440
13441 if old_cursor_shape != self.cursor_shape {
13442 cx.emit(EditorEvent::CursorShapeChanged);
13443 }
13444
13445 let project_settings = ProjectSettings::get_global(cx);
13446 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13447
13448 if self.mode == EditorMode::Full {
13449 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13450 if self.git_blame_inline_enabled != inline_blame_enabled {
13451 self.toggle_git_blame_inline_internal(false, window, cx);
13452 }
13453 }
13454
13455 cx.notify();
13456 }
13457
13458 pub fn set_searchable(&mut self, searchable: bool) {
13459 self.searchable = searchable;
13460 }
13461
13462 pub fn searchable(&self) -> bool {
13463 self.searchable
13464 }
13465
13466 fn open_proposed_changes_editor(
13467 &mut self,
13468 _: &OpenProposedChangesEditor,
13469 window: &mut Window,
13470 cx: &mut Context<Self>,
13471 ) {
13472 let Some(workspace) = self.workspace() else {
13473 cx.propagate();
13474 return;
13475 };
13476
13477 let selections = self.selections.all::<usize>(cx);
13478 let multi_buffer = self.buffer.read(cx);
13479 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13480 let mut new_selections_by_buffer = HashMap::default();
13481 for selection in selections {
13482 for (buffer, range, _) in
13483 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13484 {
13485 let mut range = range.to_point(buffer);
13486 range.start.column = 0;
13487 range.end.column = buffer.line_len(range.end.row);
13488 new_selections_by_buffer
13489 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13490 .or_insert(Vec::new())
13491 .push(range)
13492 }
13493 }
13494
13495 let proposed_changes_buffers = new_selections_by_buffer
13496 .into_iter()
13497 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13498 .collect::<Vec<_>>();
13499 let proposed_changes_editor = cx.new(|cx| {
13500 ProposedChangesEditor::new(
13501 "Proposed changes",
13502 proposed_changes_buffers,
13503 self.project.clone(),
13504 window,
13505 cx,
13506 )
13507 });
13508
13509 window.defer(cx, move |window, cx| {
13510 workspace.update(cx, |workspace, cx| {
13511 workspace.active_pane().update(cx, |pane, cx| {
13512 pane.add_item(
13513 Box::new(proposed_changes_editor),
13514 true,
13515 true,
13516 None,
13517 window,
13518 cx,
13519 );
13520 });
13521 });
13522 });
13523 }
13524
13525 pub fn open_excerpts_in_split(
13526 &mut self,
13527 _: &OpenExcerptsSplit,
13528 window: &mut Window,
13529 cx: &mut Context<Self>,
13530 ) {
13531 self.open_excerpts_common(None, true, window, cx)
13532 }
13533
13534 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
13535 self.open_excerpts_common(None, false, window, cx)
13536 }
13537
13538 fn open_excerpts_common(
13539 &mut self,
13540 jump_data: Option<JumpData>,
13541 split: bool,
13542 window: &mut Window,
13543 cx: &mut Context<Self>,
13544 ) {
13545 let Some(workspace) = self.workspace() else {
13546 cx.propagate();
13547 return;
13548 };
13549
13550 if self.buffer.read(cx).is_singleton() {
13551 cx.propagate();
13552 return;
13553 }
13554
13555 let mut new_selections_by_buffer = HashMap::default();
13556 match &jump_data {
13557 Some(JumpData::MultiBufferPoint {
13558 excerpt_id,
13559 position,
13560 anchor,
13561 line_offset_from_top,
13562 }) => {
13563 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13564 if let Some(buffer) = multi_buffer_snapshot
13565 .buffer_id_for_excerpt(*excerpt_id)
13566 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
13567 {
13568 let buffer_snapshot = buffer.read(cx).snapshot();
13569 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
13570 language::ToPoint::to_point(anchor, &buffer_snapshot)
13571 } else {
13572 buffer_snapshot.clip_point(*position, Bias::Left)
13573 };
13574 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
13575 new_selections_by_buffer.insert(
13576 buffer,
13577 (
13578 vec![jump_to_offset..jump_to_offset],
13579 Some(*line_offset_from_top),
13580 ),
13581 );
13582 }
13583 }
13584 Some(JumpData::MultiBufferRow {
13585 row,
13586 line_offset_from_top,
13587 }) => {
13588 let point = MultiBufferPoint::new(row.0, 0);
13589 if let Some((buffer, buffer_point, _)) =
13590 self.buffer.read(cx).point_to_buffer_point(point, cx)
13591 {
13592 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
13593 new_selections_by_buffer
13594 .entry(buffer)
13595 .or_insert((Vec::new(), Some(*line_offset_from_top)))
13596 .0
13597 .push(buffer_offset..buffer_offset)
13598 }
13599 }
13600 None => {
13601 let selections = self.selections.all::<usize>(cx);
13602 let multi_buffer = self.buffer.read(cx);
13603 for selection in selections {
13604 for (buffer, mut range, _) in multi_buffer
13605 .snapshot(cx)
13606 .range_to_buffer_ranges(selection.range())
13607 {
13608 // When editing branch buffers, jump to the corresponding location
13609 // in their base buffer.
13610 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
13611 let buffer = buffer_handle.read(cx);
13612 if let Some(base_buffer) = buffer.base_buffer() {
13613 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
13614 buffer_handle = base_buffer;
13615 }
13616
13617 if selection.reversed {
13618 mem::swap(&mut range.start, &mut range.end);
13619 }
13620 new_selections_by_buffer
13621 .entry(buffer_handle)
13622 .or_insert((Vec::new(), None))
13623 .0
13624 .push(range)
13625 }
13626 }
13627 }
13628 }
13629
13630 if new_selections_by_buffer.is_empty() {
13631 return;
13632 }
13633
13634 // We defer the pane interaction because we ourselves are a workspace item
13635 // and activating a new item causes the pane to call a method on us reentrantly,
13636 // which panics if we're on the stack.
13637 window.defer(cx, move |window, cx| {
13638 workspace.update(cx, |workspace, cx| {
13639 let pane = if split {
13640 workspace.adjacent_pane(window, cx)
13641 } else {
13642 workspace.active_pane().clone()
13643 };
13644
13645 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
13646 let editor = buffer
13647 .read(cx)
13648 .file()
13649 .is_none()
13650 .then(|| {
13651 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
13652 // so `workspace.open_project_item` will never find them, always opening a new editor.
13653 // Instead, we try to activate the existing editor in the pane first.
13654 let (editor, pane_item_index) =
13655 pane.read(cx).items().enumerate().find_map(|(i, item)| {
13656 let editor = item.downcast::<Editor>()?;
13657 let singleton_buffer =
13658 editor.read(cx).buffer().read(cx).as_singleton()?;
13659 if singleton_buffer == buffer {
13660 Some((editor, i))
13661 } else {
13662 None
13663 }
13664 })?;
13665 pane.update(cx, |pane, cx| {
13666 pane.activate_item(pane_item_index, true, true, window, cx)
13667 });
13668 Some(editor)
13669 })
13670 .flatten()
13671 .unwrap_or_else(|| {
13672 workspace.open_project_item::<Self>(
13673 pane.clone(),
13674 buffer,
13675 true,
13676 true,
13677 window,
13678 cx,
13679 )
13680 });
13681
13682 editor.update(cx, |editor, cx| {
13683 let autoscroll = match scroll_offset {
13684 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
13685 None => Autoscroll::newest(),
13686 };
13687 let nav_history = editor.nav_history.take();
13688 editor.change_selections(Some(autoscroll), window, cx, |s| {
13689 s.select_ranges(ranges);
13690 });
13691 editor.nav_history = nav_history;
13692 });
13693 }
13694 })
13695 });
13696 }
13697
13698 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
13699 let snapshot = self.buffer.read(cx).read(cx);
13700 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
13701 Some(
13702 ranges
13703 .iter()
13704 .map(move |range| {
13705 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
13706 })
13707 .collect(),
13708 )
13709 }
13710
13711 fn selection_replacement_ranges(
13712 &self,
13713 range: Range<OffsetUtf16>,
13714 cx: &mut App,
13715 ) -> Vec<Range<OffsetUtf16>> {
13716 let selections = self.selections.all::<OffsetUtf16>(cx);
13717 let newest_selection = selections
13718 .iter()
13719 .max_by_key(|selection| selection.id)
13720 .unwrap();
13721 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
13722 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
13723 let snapshot = self.buffer.read(cx).read(cx);
13724 selections
13725 .into_iter()
13726 .map(|mut selection| {
13727 selection.start.0 =
13728 (selection.start.0 as isize).saturating_add(start_delta) as usize;
13729 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
13730 snapshot.clip_offset_utf16(selection.start, Bias::Left)
13731 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
13732 })
13733 .collect()
13734 }
13735
13736 fn report_editor_event(
13737 &self,
13738 event_type: &'static str,
13739 file_extension: Option<String>,
13740 cx: &App,
13741 ) {
13742 if cfg!(any(test, feature = "test-support")) {
13743 return;
13744 }
13745
13746 let Some(project) = &self.project else { return };
13747
13748 // If None, we are in a file without an extension
13749 let file = self
13750 .buffer
13751 .read(cx)
13752 .as_singleton()
13753 .and_then(|b| b.read(cx).file());
13754 let file_extension = file_extension.or(file
13755 .as_ref()
13756 .and_then(|file| Path::new(file.file_name(cx)).extension())
13757 .and_then(|e| e.to_str())
13758 .map(|a| a.to_string()));
13759
13760 let vim_mode = cx
13761 .global::<SettingsStore>()
13762 .raw_user_settings()
13763 .get("vim_mode")
13764 == Some(&serde_json::Value::Bool(true));
13765
13766 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
13767 == language::language_settings::InlineCompletionProvider::Copilot;
13768 let copilot_enabled_for_language = self
13769 .buffer
13770 .read(cx)
13771 .settings_at(0, cx)
13772 .show_inline_completions;
13773
13774 let project = project.read(cx);
13775 telemetry::event!(
13776 event_type,
13777 file_extension,
13778 vim_mode,
13779 copilot_enabled,
13780 copilot_enabled_for_language,
13781 is_via_ssh = project.is_via_ssh(),
13782 );
13783 }
13784
13785 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
13786 /// with each line being an array of {text, highlight} objects.
13787 fn copy_highlight_json(
13788 &mut self,
13789 _: &CopyHighlightJson,
13790 window: &mut Window,
13791 cx: &mut Context<Self>,
13792 ) {
13793 #[derive(Serialize)]
13794 struct Chunk<'a> {
13795 text: String,
13796 highlight: Option<&'a str>,
13797 }
13798
13799 let snapshot = self.buffer.read(cx).snapshot(cx);
13800 let range = self
13801 .selected_text_range(false, window, cx)
13802 .and_then(|selection| {
13803 if selection.range.is_empty() {
13804 None
13805 } else {
13806 Some(selection.range)
13807 }
13808 })
13809 .unwrap_or_else(|| 0..snapshot.len());
13810
13811 let chunks = snapshot.chunks(range, true);
13812 let mut lines = Vec::new();
13813 let mut line: VecDeque<Chunk> = VecDeque::new();
13814
13815 let Some(style) = self.style.as_ref() else {
13816 return;
13817 };
13818
13819 for chunk in chunks {
13820 let highlight = chunk
13821 .syntax_highlight_id
13822 .and_then(|id| id.name(&style.syntax));
13823 let mut chunk_lines = chunk.text.split('\n').peekable();
13824 while let Some(text) = chunk_lines.next() {
13825 let mut merged_with_last_token = false;
13826 if let Some(last_token) = line.back_mut() {
13827 if last_token.highlight == highlight {
13828 last_token.text.push_str(text);
13829 merged_with_last_token = true;
13830 }
13831 }
13832
13833 if !merged_with_last_token {
13834 line.push_back(Chunk {
13835 text: text.into(),
13836 highlight,
13837 });
13838 }
13839
13840 if chunk_lines.peek().is_some() {
13841 if line.len() > 1 && line.front().unwrap().text.is_empty() {
13842 line.pop_front();
13843 }
13844 if line.len() > 1 && line.back().unwrap().text.is_empty() {
13845 line.pop_back();
13846 }
13847
13848 lines.push(mem::take(&mut line));
13849 }
13850 }
13851 }
13852
13853 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
13854 return;
13855 };
13856 cx.write_to_clipboard(ClipboardItem::new_string(lines));
13857 }
13858
13859 pub fn open_context_menu(
13860 &mut self,
13861 _: &OpenContextMenu,
13862 window: &mut Window,
13863 cx: &mut Context<Self>,
13864 ) {
13865 self.request_autoscroll(Autoscroll::newest(), cx);
13866 let position = self.selections.newest_display(cx).start;
13867 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
13868 }
13869
13870 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
13871 &self.inlay_hint_cache
13872 }
13873
13874 pub fn replay_insert_event(
13875 &mut self,
13876 text: &str,
13877 relative_utf16_range: Option<Range<isize>>,
13878 window: &mut Window,
13879 cx: &mut Context<Self>,
13880 ) {
13881 if !self.input_enabled {
13882 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13883 return;
13884 }
13885 if let Some(relative_utf16_range) = relative_utf16_range {
13886 let selections = self.selections.all::<OffsetUtf16>(cx);
13887 self.change_selections(None, window, cx, |s| {
13888 let new_ranges = selections.into_iter().map(|range| {
13889 let start = OffsetUtf16(
13890 range
13891 .head()
13892 .0
13893 .saturating_add_signed(relative_utf16_range.start),
13894 );
13895 let end = OffsetUtf16(
13896 range
13897 .head()
13898 .0
13899 .saturating_add_signed(relative_utf16_range.end),
13900 );
13901 start..end
13902 });
13903 s.select_ranges(new_ranges);
13904 });
13905 }
13906
13907 self.handle_input(text, window, cx);
13908 }
13909
13910 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
13911 let Some(provider) = self.semantics_provider.as_ref() else {
13912 return false;
13913 };
13914
13915 let mut supports = false;
13916 self.buffer().update(cx, |this, cx| {
13917 this.for_each_buffer(|buffer| {
13918 supports |= provider.supports_inlay_hints(buffer, cx);
13919 })
13920 });
13921
13922 supports
13923 }
13924 pub fn is_focused(&self, window: &mut Window) -> bool {
13925 self.focus_handle.is_focused(window)
13926 }
13927
13928 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13929 cx.emit(EditorEvent::Focused);
13930
13931 if let Some(descendant) = self
13932 .last_focused_descendant
13933 .take()
13934 .and_then(|descendant| descendant.upgrade())
13935 {
13936 window.focus(&descendant);
13937 } else {
13938 if let Some(blame) = self.blame.as_ref() {
13939 blame.update(cx, GitBlame::focus)
13940 }
13941
13942 self.blink_manager.update(cx, BlinkManager::enable);
13943 self.show_cursor_names(window, cx);
13944 self.buffer.update(cx, |buffer, cx| {
13945 buffer.finalize_last_transaction(cx);
13946 if self.leader_peer_id.is_none() {
13947 buffer.set_active_selections(
13948 &self.selections.disjoint_anchors(),
13949 self.selections.line_mode,
13950 self.cursor_shape,
13951 cx,
13952 );
13953 }
13954 });
13955 }
13956 }
13957
13958 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
13959 cx.emit(EditorEvent::FocusedIn)
13960 }
13961
13962 fn handle_focus_out(
13963 &mut self,
13964 event: FocusOutEvent,
13965 _window: &mut Window,
13966 _cx: &mut Context<Self>,
13967 ) {
13968 if event.blurred != self.focus_handle {
13969 self.last_focused_descendant = Some(event.blurred);
13970 }
13971 }
13972
13973 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13974 self.blink_manager.update(cx, BlinkManager::disable);
13975 self.buffer
13976 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13977
13978 if let Some(blame) = self.blame.as_ref() {
13979 blame.update(cx, GitBlame::blur)
13980 }
13981 if !self.hover_state.focused(window, cx) {
13982 hide_hover(self, cx);
13983 }
13984
13985 self.hide_context_menu(window, cx);
13986 cx.emit(EditorEvent::Blurred);
13987 cx.notify();
13988 }
13989
13990 pub fn register_action<A: Action>(
13991 &mut self,
13992 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
13993 ) -> Subscription {
13994 let id = self.next_editor_action_id.post_inc();
13995 let listener = Arc::new(listener);
13996 self.editor_actions.borrow_mut().insert(
13997 id,
13998 Box::new(move |window, _| {
13999 let listener = listener.clone();
14000 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14001 let action = action.downcast_ref().unwrap();
14002 if phase == DispatchPhase::Bubble {
14003 listener(action, window, cx)
14004 }
14005 })
14006 }),
14007 );
14008
14009 let editor_actions = self.editor_actions.clone();
14010 Subscription::new(move || {
14011 editor_actions.borrow_mut().remove(&id);
14012 })
14013 }
14014
14015 pub fn file_header_size(&self) -> u32 {
14016 FILE_HEADER_HEIGHT
14017 }
14018
14019 pub fn revert(
14020 &mut self,
14021 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14022 window: &mut Window,
14023 cx: &mut Context<Self>,
14024 ) {
14025 self.buffer().update(cx, |multi_buffer, cx| {
14026 for (buffer_id, changes) in revert_changes {
14027 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14028 buffer.update(cx, |buffer, cx| {
14029 buffer.edit(
14030 changes.into_iter().map(|(range, text)| {
14031 (range, text.to_string().map(Arc::<str>::from))
14032 }),
14033 None,
14034 cx,
14035 );
14036 });
14037 }
14038 }
14039 });
14040 self.change_selections(None, window, cx, |selections| selections.refresh());
14041 }
14042
14043 pub fn to_pixel_point(
14044 &self,
14045 source: multi_buffer::Anchor,
14046 editor_snapshot: &EditorSnapshot,
14047 window: &mut Window,
14048 ) -> Option<gpui::Point<Pixels>> {
14049 let source_point = source.to_display_point(editor_snapshot);
14050 self.display_to_pixel_point(source_point, editor_snapshot, window)
14051 }
14052
14053 pub fn display_to_pixel_point(
14054 &self,
14055 source: DisplayPoint,
14056 editor_snapshot: &EditorSnapshot,
14057 window: &mut Window,
14058 ) -> Option<gpui::Point<Pixels>> {
14059 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14060 let text_layout_details = self.text_layout_details(window);
14061 let scroll_top = text_layout_details
14062 .scroll_anchor
14063 .scroll_position(editor_snapshot)
14064 .y;
14065
14066 if source.row().as_f32() < scroll_top.floor() {
14067 return None;
14068 }
14069 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14070 let source_y = line_height * (source.row().as_f32() - scroll_top);
14071 Some(gpui::Point::new(source_x, source_y))
14072 }
14073
14074 pub fn has_active_completions_menu(&self) -> bool {
14075 self.context_menu.borrow().as_ref().map_or(false, |menu| {
14076 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14077 })
14078 }
14079
14080 pub fn register_addon<T: Addon>(&mut self, instance: T) {
14081 self.addons
14082 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14083 }
14084
14085 pub fn unregister_addon<T: Addon>(&mut self) {
14086 self.addons.remove(&std::any::TypeId::of::<T>());
14087 }
14088
14089 pub fn addon<T: Addon>(&self) -> Option<&T> {
14090 let type_id = std::any::TypeId::of::<T>();
14091 self.addons
14092 .get(&type_id)
14093 .and_then(|item| item.to_any().downcast_ref::<T>())
14094 }
14095
14096 fn character_size(&self, window: &mut Window) -> gpui::Point<Pixels> {
14097 let text_layout_details = self.text_layout_details(window);
14098 let style = &text_layout_details.editor_style;
14099 let font_id = window.text_system().resolve_font(&style.text.font());
14100 let font_size = style.text.font_size.to_pixels(window.rem_size());
14101 let line_height = style.text.line_height_in_pixels(window.rem_size());
14102
14103 let em_width = window
14104 .text_system()
14105 .typographic_bounds(font_id, font_size, 'm')
14106 .unwrap()
14107 .size
14108 .width;
14109
14110 gpui::Point::new(em_width, line_height)
14111 }
14112}
14113
14114fn get_unstaged_changes_for_buffers(
14115 project: &Entity<Project>,
14116 buffers: impl IntoIterator<Item = Entity<Buffer>>,
14117 buffer: Entity<MultiBuffer>,
14118 cx: &mut App,
14119) {
14120 let mut tasks = Vec::new();
14121 project.update(cx, |project, cx| {
14122 for buffer in buffers {
14123 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
14124 }
14125 });
14126 cx.spawn(|mut cx| async move {
14127 let change_sets = futures::future::join_all(tasks).await;
14128 buffer
14129 .update(&mut cx, |buffer, cx| {
14130 for change_set in change_sets {
14131 if let Some(change_set) = change_set.log_err() {
14132 buffer.add_change_set(change_set, cx);
14133 }
14134 }
14135 })
14136 .ok();
14137 })
14138 .detach();
14139}
14140
14141fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14142 let tab_size = tab_size.get() as usize;
14143 let mut width = offset;
14144
14145 for ch in text.chars() {
14146 width += if ch == '\t' {
14147 tab_size - (width % tab_size)
14148 } else {
14149 1
14150 };
14151 }
14152
14153 width - offset
14154}
14155
14156#[cfg(test)]
14157mod tests {
14158 use super::*;
14159
14160 #[test]
14161 fn test_string_size_with_expanded_tabs() {
14162 let nz = |val| NonZeroU32::new(val).unwrap();
14163 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14164 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14165 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14166 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14167 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14168 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14169 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14170 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14171 }
14172}
14173
14174/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14175struct WordBreakingTokenizer<'a> {
14176 input: &'a str,
14177}
14178
14179impl<'a> WordBreakingTokenizer<'a> {
14180 fn new(input: &'a str) -> Self {
14181 Self { input }
14182 }
14183}
14184
14185fn is_char_ideographic(ch: char) -> bool {
14186 use unicode_script::Script::*;
14187 use unicode_script::UnicodeScript;
14188 matches!(ch.script(), Han | Tangut | Yi)
14189}
14190
14191fn is_grapheme_ideographic(text: &str) -> bool {
14192 text.chars().any(is_char_ideographic)
14193}
14194
14195fn is_grapheme_whitespace(text: &str) -> bool {
14196 text.chars().any(|x| x.is_whitespace())
14197}
14198
14199fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14200 text.chars().next().map_or(false, |ch| {
14201 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14202 })
14203}
14204
14205#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14206struct WordBreakToken<'a> {
14207 token: &'a str,
14208 grapheme_len: usize,
14209 is_whitespace: bool,
14210}
14211
14212impl<'a> Iterator for WordBreakingTokenizer<'a> {
14213 /// Yields a span, the count of graphemes in the token, and whether it was
14214 /// whitespace. Note that it also breaks at word boundaries.
14215 type Item = WordBreakToken<'a>;
14216
14217 fn next(&mut self) -> Option<Self::Item> {
14218 use unicode_segmentation::UnicodeSegmentation;
14219 if self.input.is_empty() {
14220 return None;
14221 }
14222
14223 let mut iter = self.input.graphemes(true).peekable();
14224 let mut offset = 0;
14225 let mut graphemes = 0;
14226 if let Some(first_grapheme) = iter.next() {
14227 let is_whitespace = is_grapheme_whitespace(first_grapheme);
14228 offset += first_grapheme.len();
14229 graphemes += 1;
14230 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14231 if let Some(grapheme) = iter.peek().copied() {
14232 if should_stay_with_preceding_ideograph(grapheme) {
14233 offset += grapheme.len();
14234 graphemes += 1;
14235 }
14236 }
14237 } else {
14238 let mut words = self.input[offset..].split_word_bound_indices().peekable();
14239 let mut next_word_bound = words.peek().copied();
14240 if next_word_bound.map_or(false, |(i, _)| i == 0) {
14241 next_word_bound = words.next();
14242 }
14243 while let Some(grapheme) = iter.peek().copied() {
14244 if next_word_bound.map_or(false, |(i, _)| i == offset) {
14245 break;
14246 };
14247 if is_grapheme_whitespace(grapheme) != is_whitespace {
14248 break;
14249 };
14250 offset += grapheme.len();
14251 graphemes += 1;
14252 iter.next();
14253 }
14254 }
14255 let token = &self.input[..offset];
14256 self.input = &self.input[offset..];
14257 if is_whitespace {
14258 Some(WordBreakToken {
14259 token: " ",
14260 grapheme_len: 1,
14261 is_whitespace: true,
14262 })
14263 } else {
14264 Some(WordBreakToken {
14265 token,
14266 grapheme_len: graphemes,
14267 is_whitespace: false,
14268 })
14269 }
14270 } else {
14271 None
14272 }
14273 }
14274}
14275
14276#[test]
14277fn test_word_breaking_tokenizer() {
14278 let tests: &[(&str, &[(&str, usize, bool)])] = &[
14279 ("", &[]),
14280 (" ", &[(" ", 1, true)]),
14281 ("Ʒ", &[("Ʒ", 1, false)]),
14282 ("Ǽ", &[("Ǽ", 1, false)]),
14283 ("⋑", &[("⋑", 1, false)]),
14284 ("⋑⋑", &[("⋑⋑", 2, false)]),
14285 (
14286 "原理,进而",
14287 &[
14288 ("原", 1, false),
14289 ("理,", 2, false),
14290 ("进", 1, false),
14291 ("而", 1, false),
14292 ],
14293 ),
14294 (
14295 "hello world",
14296 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14297 ),
14298 (
14299 "hello, world",
14300 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14301 ),
14302 (
14303 " hello world",
14304 &[
14305 (" ", 1, true),
14306 ("hello", 5, false),
14307 (" ", 1, true),
14308 ("world", 5, false),
14309 ],
14310 ),
14311 (
14312 "这是什么 \n 钢笔",
14313 &[
14314 ("这", 1, false),
14315 ("是", 1, false),
14316 ("什", 1, false),
14317 ("么", 1, false),
14318 (" ", 1, true),
14319 ("钢", 1, false),
14320 ("笔", 1, false),
14321 ],
14322 ),
14323 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14324 ];
14325
14326 for (input, result) in tests {
14327 assert_eq!(
14328 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14329 result
14330 .iter()
14331 .copied()
14332 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14333 token,
14334 grapheme_len,
14335 is_whitespace,
14336 })
14337 .collect::<Vec<_>>()
14338 );
14339 }
14340}
14341
14342fn wrap_with_prefix(
14343 line_prefix: String,
14344 unwrapped_text: String,
14345 wrap_column: usize,
14346 tab_size: NonZeroU32,
14347) -> String {
14348 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14349 let mut wrapped_text = String::new();
14350 let mut current_line = line_prefix.clone();
14351
14352 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14353 let mut current_line_len = line_prefix_len;
14354 for WordBreakToken {
14355 token,
14356 grapheme_len,
14357 is_whitespace,
14358 } in tokenizer
14359 {
14360 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14361 wrapped_text.push_str(current_line.trim_end());
14362 wrapped_text.push('\n');
14363 current_line.truncate(line_prefix.len());
14364 current_line_len = line_prefix_len;
14365 if !is_whitespace {
14366 current_line.push_str(token);
14367 current_line_len += grapheme_len;
14368 }
14369 } else if !is_whitespace {
14370 current_line.push_str(token);
14371 current_line_len += grapheme_len;
14372 } else if current_line_len != line_prefix_len {
14373 current_line.push(' ');
14374 current_line_len += 1;
14375 }
14376 }
14377
14378 if !current_line.is_empty() {
14379 wrapped_text.push_str(¤t_line);
14380 }
14381 wrapped_text
14382}
14383
14384#[test]
14385fn test_wrap_with_prefix() {
14386 assert_eq!(
14387 wrap_with_prefix(
14388 "# ".to_string(),
14389 "abcdefg".to_string(),
14390 4,
14391 NonZeroU32::new(4).unwrap()
14392 ),
14393 "# abcdefg"
14394 );
14395 assert_eq!(
14396 wrap_with_prefix(
14397 "".to_string(),
14398 "\thello world".to_string(),
14399 8,
14400 NonZeroU32::new(4).unwrap()
14401 ),
14402 "hello\nworld"
14403 );
14404 assert_eq!(
14405 wrap_with_prefix(
14406 "// ".to_string(),
14407 "xx \nyy zz aa bb cc".to_string(),
14408 12,
14409 NonZeroU32::new(4).unwrap()
14410 ),
14411 "// xx yy zz\n// aa bb cc"
14412 );
14413 assert_eq!(
14414 wrap_with_prefix(
14415 String::new(),
14416 "这是什么 \n 钢笔".to_string(),
14417 3,
14418 NonZeroU32::new(4).unwrap()
14419 ),
14420 "这是什\n么 钢\n笔"
14421 );
14422}
14423
14424pub trait CollaborationHub {
14425 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14426 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14427 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14428}
14429
14430impl CollaborationHub for Entity<Project> {
14431 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14432 self.read(cx).collaborators()
14433 }
14434
14435 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14436 self.read(cx).user_store().read(cx).participant_indices()
14437 }
14438
14439 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14440 let this = self.read(cx);
14441 let user_ids = this.collaborators().values().map(|c| c.user_id);
14442 this.user_store().read_with(cx, |user_store, cx| {
14443 user_store.participant_names(user_ids, cx)
14444 })
14445 }
14446}
14447
14448pub trait SemanticsProvider {
14449 fn hover(
14450 &self,
14451 buffer: &Entity<Buffer>,
14452 position: text::Anchor,
14453 cx: &mut App,
14454 ) -> Option<Task<Vec<project::Hover>>>;
14455
14456 fn inlay_hints(
14457 &self,
14458 buffer_handle: Entity<Buffer>,
14459 range: Range<text::Anchor>,
14460 cx: &mut App,
14461 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14462
14463 fn resolve_inlay_hint(
14464 &self,
14465 hint: InlayHint,
14466 buffer_handle: Entity<Buffer>,
14467 server_id: LanguageServerId,
14468 cx: &mut App,
14469 ) -> Option<Task<anyhow::Result<InlayHint>>>;
14470
14471 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
14472
14473 fn document_highlights(
14474 &self,
14475 buffer: &Entity<Buffer>,
14476 position: text::Anchor,
14477 cx: &mut App,
14478 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14479
14480 fn definitions(
14481 &self,
14482 buffer: &Entity<Buffer>,
14483 position: text::Anchor,
14484 kind: GotoDefinitionKind,
14485 cx: &mut App,
14486 ) -> Option<Task<Result<Vec<LocationLink>>>>;
14487
14488 fn range_for_rename(
14489 &self,
14490 buffer: &Entity<Buffer>,
14491 position: text::Anchor,
14492 cx: &mut App,
14493 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14494
14495 fn perform_rename(
14496 &self,
14497 buffer: &Entity<Buffer>,
14498 position: text::Anchor,
14499 new_name: String,
14500 cx: &mut App,
14501 ) -> Option<Task<Result<ProjectTransaction>>>;
14502}
14503
14504pub trait CompletionProvider {
14505 fn completions(
14506 &self,
14507 buffer: &Entity<Buffer>,
14508 buffer_position: text::Anchor,
14509 trigger: CompletionContext,
14510 window: &mut Window,
14511 cx: &mut Context<Editor>,
14512 ) -> Task<Result<Vec<Completion>>>;
14513
14514 fn resolve_completions(
14515 &self,
14516 buffer: Entity<Buffer>,
14517 completion_indices: Vec<usize>,
14518 completions: Rc<RefCell<Box<[Completion]>>>,
14519 cx: &mut Context<Editor>,
14520 ) -> Task<Result<bool>>;
14521
14522 fn apply_additional_edits_for_completion(
14523 &self,
14524 _buffer: Entity<Buffer>,
14525 _completions: Rc<RefCell<Box<[Completion]>>>,
14526 _completion_index: usize,
14527 _push_to_history: bool,
14528 _cx: &mut Context<Editor>,
14529 ) -> Task<Result<Option<language::Transaction>>> {
14530 Task::ready(Ok(None))
14531 }
14532
14533 fn is_completion_trigger(
14534 &self,
14535 buffer: &Entity<Buffer>,
14536 position: language::Anchor,
14537 text: &str,
14538 trigger_in_words: bool,
14539 cx: &mut Context<Editor>,
14540 ) -> bool;
14541
14542 fn sort_completions(&self) -> bool {
14543 true
14544 }
14545}
14546
14547pub trait CodeActionProvider {
14548 fn id(&self) -> Arc<str>;
14549
14550 fn code_actions(
14551 &self,
14552 buffer: &Entity<Buffer>,
14553 range: Range<text::Anchor>,
14554 window: &mut Window,
14555 cx: &mut App,
14556 ) -> Task<Result<Vec<CodeAction>>>;
14557
14558 fn apply_code_action(
14559 &self,
14560 buffer_handle: Entity<Buffer>,
14561 action: CodeAction,
14562 excerpt_id: ExcerptId,
14563 push_to_history: bool,
14564 window: &mut Window,
14565 cx: &mut App,
14566 ) -> Task<Result<ProjectTransaction>>;
14567}
14568
14569impl CodeActionProvider for Entity<Project> {
14570 fn id(&self) -> Arc<str> {
14571 "project".into()
14572 }
14573
14574 fn code_actions(
14575 &self,
14576 buffer: &Entity<Buffer>,
14577 range: Range<text::Anchor>,
14578 _window: &mut Window,
14579 cx: &mut App,
14580 ) -> Task<Result<Vec<CodeAction>>> {
14581 self.update(cx, |project, cx| {
14582 project.code_actions(buffer, range, None, cx)
14583 })
14584 }
14585
14586 fn apply_code_action(
14587 &self,
14588 buffer_handle: Entity<Buffer>,
14589 action: CodeAction,
14590 _excerpt_id: ExcerptId,
14591 push_to_history: bool,
14592 _window: &mut Window,
14593 cx: &mut App,
14594 ) -> Task<Result<ProjectTransaction>> {
14595 self.update(cx, |project, cx| {
14596 project.apply_code_action(buffer_handle, action, push_to_history, cx)
14597 })
14598 }
14599}
14600
14601fn snippet_completions(
14602 project: &Project,
14603 buffer: &Entity<Buffer>,
14604 buffer_position: text::Anchor,
14605 cx: &mut App,
14606) -> Task<Result<Vec<Completion>>> {
14607 let language = buffer.read(cx).language_at(buffer_position);
14608 let language_name = language.as_ref().map(|language| language.lsp_id());
14609 let snippet_store = project.snippets().read(cx);
14610 let snippets = snippet_store.snippets_for(language_name, cx);
14611
14612 if snippets.is_empty() {
14613 return Task::ready(Ok(vec![]));
14614 }
14615 let snapshot = buffer.read(cx).text_snapshot();
14616 let chars: String = snapshot
14617 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
14618 .collect();
14619
14620 let scope = language.map(|language| language.default_scope());
14621 let executor = cx.background_executor().clone();
14622
14623 cx.background_executor().spawn(async move {
14624 let classifier = CharClassifier::new(scope).for_completion(true);
14625 let mut last_word = chars
14626 .chars()
14627 .take_while(|c| classifier.is_word(*c))
14628 .collect::<String>();
14629 last_word = last_word.chars().rev().collect();
14630
14631 if last_word.is_empty() {
14632 return Ok(vec![]);
14633 }
14634
14635 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
14636 let to_lsp = |point: &text::Anchor| {
14637 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
14638 point_to_lsp(end)
14639 };
14640 let lsp_end = to_lsp(&buffer_position);
14641
14642 let candidates = snippets
14643 .iter()
14644 .enumerate()
14645 .flat_map(|(ix, snippet)| {
14646 snippet
14647 .prefix
14648 .iter()
14649 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
14650 })
14651 .collect::<Vec<StringMatchCandidate>>();
14652
14653 let mut matches = fuzzy::match_strings(
14654 &candidates,
14655 &last_word,
14656 last_word.chars().any(|c| c.is_uppercase()),
14657 100,
14658 &Default::default(),
14659 executor,
14660 )
14661 .await;
14662
14663 // Remove all candidates where the query's start does not match the start of any word in the candidate
14664 if let Some(query_start) = last_word.chars().next() {
14665 matches.retain(|string_match| {
14666 split_words(&string_match.string).any(|word| {
14667 // Check that the first codepoint of the word as lowercase matches the first
14668 // codepoint of the query as lowercase
14669 word.chars()
14670 .flat_map(|codepoint| codepoint.to_lowercase())
14671 .zip(query_start.to_lowercase())
14672 .all(|(word_cp, query_cp)| word_cp == query_cp)
14673 })
14674 });
14675 }
14676
14677 let matched_strings = matches
14678 .into_iter()
14679 .map(|m| m.string)
14680 .collect::<HashSet<_>>();
14681
14682 let result: Vec<Completion> = snippets
14683 .into_iter()
14684 .filter_map(|snippet| {
14685 let matching_prefix = snippet
14686 .prefix
14687 .iter()
14688 .find(|prefix| matched_strings.contains(*prefix))?;
14689 let start = as_offset - last_word.len();
14690 let start = snapshot.anchor_before(start);
14691 let range = start..buffer_position;
14692 let lsp_start = to_lsp(&start);
14693 let lsp_range = lsp::Range {
14694 start: lsp_start,
14695 end: lsp_end,
14696 };
14697 Some(Completion {
14698 old_range: range,
14699 new_text: snippet.body.clone(),
14700 resolved: false,
14701 label: CodeLabel {
14702 text: matching_prefix.clone(),
14703 runs: vec![],
14704 filter_range: 0..matching_prefix.len(),
14705 },
14706 server_id: LanguageServerId(usize::MAX),
14707 documentation: snippet.description.clone().map(Documentation::SingleLine),
14708 lsp_completion: lsp::CompletionItem {
14709 label: snippet.prefix.first().unwrap().clone(),
14710 kind: Some(CompletionItemKind::SNIPPET),
14711 label_details: snippet.description.as_ref().map(|description| {
14712 lsp::CompletionItemLabelDetails {
14713 detail: Some(description.clone()),
14714 description: None,
14715 }
14716 }),
14717 insert_text_format: Some(InsertTextFormat::SNIPPET),
14718 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
14719 lsp::InsertReplaceEdit {
14720 new_text: snippet.body.clone(),
14721 insert: lsp_range,
14722 replace: lsp_range,
14723 },
14724 )),
14725 filter_text: Some(snippet.body.clone()),
14726 sort_text: Some(char::MAX.to_string()),
14727 ..Default::default()
14728 },
14729 confirm: None,
14730 })
14731 })
14732 .collect();
14733
14734 Ok(result)
14735 })
14736}
14737
14738impl CompletionProvider for Entity<Project> {
14739 fn completions(
14740 &self,
14741 buffer: &Entity<Buffer>,
14742 buffer_position: text::Anchor,
14743 options: CompletionContext,
14744 _window: &mut Window,
14745 cx: &mut Context<Editor>,
14746 ) -> Task<Result<Vec<Completion>>> {
14747 self.update(cx, |project, cx| {
14748 let snippets = snippet_completions(project, buffer, buffer_position, cx);
14749 let project_completions = project.completions(buffer, buffer_position, options, cx);
14750 cx.background_executor().spawn(async move {
14751 let mut completions = project_completions.await?;
14752 let snippets_completions = snippets.await?;
14753 completions.extend(snippets_completions);
14754 Ok(completions)
14755 })
14756 })
14757 }
14758
14759 fn resolve_completions(
14760 &self,
14761 buffer: Entity<Buffer>,
14762 completion_indices: Vec<usize>,
14763 completions: Rc<RefCell<Box<[Completion]>>>,
14764 cx: &mut Context<Editor>,
14765 ) -> Task<Result<bool>> {
14766 self.update(cx, |project, cx| {
14767 project.lsp_store().update(cx, |lsp_store, cx| {
14768 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
14769 })
14770 })
14771 }
14772
14773 fn apply_additional_edits_for_completion(
14774 &self,
14775 buffer: Entity<Buffer>,
14776 completions: Rc<RefCell<Box<[Completion]>>>,
14777 completion_index: usize,
14778 push_to_history: bool,
14779 cx: &mut Context<Editor>,
14780 ) -> Task<Result<Option<language::Transaction>>> {
14781 self.update(cx, |project, cx| {
14782 project.lsp_store().update(cx, |lsp_store, cx| {
14783 lsp_store.apply_additional_edits_for_completion(
14784 buffer,
14785 completions,
14786 completion_index,
14787 push_to_history,
14788 cx,
14789 )
14790 })
14791 })
14792 }
14793
14794 fn is_completion_trigger(
14795 &self,
14796 buffer: &Entity<Buffer>,
14797 position: language::Anchor,
14798 text: &str,
14799 trigger_in_words: bool,
14800 cx: &mut Context<Editor>,
14801 ) -> bool {
14802 let mut chars = text.chars();
14803 let char = if let Some(char) = chars.next() {
14804 char
14805 } else {
14806 return false;
14807 };
14808 if chars.next().is_some() {
14809 return false;
14810 }
14811
14812 let buffer = buffer.read(cx);
14813 let snapshot = buffer.snapshot();
14814 if !snapshot.settings_at(position, cx).show_completions_on_input {
14815 return false;
14816 }
14817 let classifier = snapshot.char_classifier_at(position).for_completion(true);
14818 if trigger_in_words && classifier.is_word(char) {
14819 return true;
14820 }
14821
14822 buffer.completion_triggers().contains(text)
14823 }
14824}
14825
14826impl SemanticsProvider for Entity<Project> {
14827 fn hover(
14828 &self,
14829 buffer: &Entity<Buffer>,
14830 position: text::Anchor,
14831 cx: &mut App,
14832 ) -> Option<Task<Vec<project::Hover>>> {
14833 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
14834 }
14835
14836 fn document_highlights(
14837 &self,
14838 buffer: &Entity<Buffer>,
14839 position: text::Anchor,
14840 cx: &mut App,
14841 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
14842 Some(self.update(cx, |project, cx| {
14843 project.document_highlights(buffer, position, cx)
14844 }))
14845 }
14846
14847 fn definitions(
14848 &self,
14849 buffer: &Entity<Buffer>,
14850 position: text::Anchor,
14851 kind: GotoDefinitionKind,
14852 cx: &mut App,
14853 ) -> Option<Task<Result<Vec<LocationLink>>>> {
14854 Some(self.update(cx, |project, cx| match kind {
14855 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
14856 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
14857 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
14858 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
14859 }))
14860 }
14861
14862 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
14863 // TODO: make this work for remote projects
14864 buffer.update(cx, |buffer, cx| {
14865 self.update(cx, |this, cx| {
14866 this.for_language_servers_for_local_buffer(
14867 buffer,
14868 |mut it| {
14869 it.any(
14870 |(_, server)| match server.capabilities().inlay_hint_provider {
14871 Some(lsp::OneOf::Left(enabled)) => enabled,
14872 Some(lsp::OneOf::Right(_)) => true,
14873 None => false,
14874 },
14875 )
14876 },
14877 cx,
14878 )
14879 })
14880 })
14881 }
14882
14883 fn inlay_hints(
14884 &self,
14885 buffer_handle: Entity<Buffer>,
14886 range: Range<text::Anchor>,
14887 cx: &mut App,
14888 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
14889 Some(self.update(cx, |project, cx| {
14890 project.inlay_hints(buffer_handle, range, cx)
14891 }))
14892 }
14893
14894 fn resolve_inlay_hint(
14895 &self,
14896 hint: InlayHint,
14897 buffer_handle: Entity<Buffer>,
14898 server_id: LanguageServerId,
14899 cx: &mut App,
14900 ) -> Option<Task<anyhow::Result<InlayHint>>> {
14901 Some(self.update(cx, |project, cx| {
14902 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14903 }))
14904 }
14905
14906 fn range_for_rename(
14907 &self,
14908 buffer: &Entity<Buffer>,
14909 position: text::Anchor,
14910 cx: &mut App,
14911 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14912 Some(self.update(cx, |project, cx| {
14913 let buffer = buffer.clone();
14914 let task = project.prepare_rename(buffer.clone(), position, cx);
14915 cx.spawn(|_, mut cx| async move {
14916 Ok(match task.await? {
14917 PrepareRenameResponse::Success(range) => Some(range),
14918 PrepareRenameResponse::InvalidPosition => None,
14919 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
14920 // Fallback on using TreeSitter info to determine identifier range
14921 buffer.update(&mut cx, |buffer, _| {
14922 let snapshot = buffer.snapshot();
14923 let (range, kind) = snapshot.surrounding_word(position);
14924 if kind != Some(CharKind::Word) {
14925 return None;
14926 }
14927 Some(
14928 snapshot.anchor_before(range.start)
14929 ..snapshot.anchor_after(range.end),
14930 )
14931 })?
14932 }
14933 })
14934 })
14935 }))
14936 }
14937
14938 fn perform_rename(
14939 &self,
14940 buffer: &Entity<Buffer>,
14941 position: text::Anchor,
14942 new_name: String,
14943 cx: &mut App,
14944 ) -> Option<Task<Result<ProjectTransaction>>> {
14945 Some(self.update(cx, |project, cx| {
14946 project.perform_rename(buffer.clone(), position, new_name, cx)
14947 }))
14948 }
14949}
14950
14951fn inlay_hint_settings(
14952 location: Anchor,
14953 snapshot: &MultiBufferSnapshot,
14954 cx: &mut Context<Editor>,
14955) -> InlayHintSettings {
14956 let file = snapshot.file_at(location);
14957 let language = snapshot.language_at(location).map(|l| l.name());
14958 language_settings(language, file, cx).inlay_hints
14959}
14960
14961fn consume_contiguous_rows(
14962 contiguous_row_selections: &mut Vec<Selection<Point>>,
14963 selection: &Selection<Point>,
14964 display_map: &DisplaySnapshot,
14965 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14966) -> (MultiBufferRow, MultiBufferRow) {
14967 contiguous_row_selections.push(selection.clone());
14968 let start_row = MultiBufferRow(selection.start.row);
14969 let mut end_row = ending_row(selection, display_map);
14970
14971 while let Some(next_selection) = selections.peek() {
14972 if next_selection.start.row <= end_row.0 {
14973 end_row = ending_row(next_selection, display_map);
14974 contiguous_row_selections.push(selections.next().unwrap().clone());
14975 } else {
14976 break;
14977 }
14978 }
14979 (start_row, end_row)
14980}
14981
14982fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14983 if next_selection.end.column > 0 || next_selection.is_empty() {
14984 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14985 } else {
14986 MultiBufferRow(next_selection.end.row)
14987 }
14988}
14989
14990impl EditorSnapshot {
14991 pub fn remote_selections_in_range<'a>(
14992 &'a self,
14993 range: &'a Range<Anchor>,
14994 collaboration_hub: &dyn CollaborationHub,
14995 cx: &'a App,
14996 ) -> impl 'a + Iterator<Item = RemoteSelection> {
14997 let participant_names = collaboration_hub.user_names(cx);
14998 let participant_indices = collaboration_hub.user_participant_indices(cx);
14999 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15000 let collaborators_by_replica_id = collaborators_by_peer_id
15001 .iter()
15002 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15003 .collect::<HashMap<_, _>>();
15004 self.buffer_snapshot
15005 .selections_in_range(range, false)
15006 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15007 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15008 let participant_index = participant_indices.get(&collaborator.user_id).copied();
15009 let user_name = participant_names.get(&collaborator.user_id).cloned();
15010 Some(RemoteSelection {
15011 replica_id,
15012 selection,
15013 cursor_shape,
15014 line_mode,
15015 participant_index,
15016 peer_id: collaborator.peer_id,
15017 user_name,
15018 })
15019 })
15020 }
15021
15022 pub fn hunks_for_ranges(
15023 &self,
15024 ranges: impl Iterator<Item = Range<Point>>,
15025 ) -> Vec<MultiBufferDiffHunk> {
15026 let mut hunks = Vec::new();
15027 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15028 HashMap::default();
15029 for query_range in ranges {
15030 let query_rows =
15031 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15032 for hunk in self.buffer_snapshot.diff_hunks_in_range(
15033 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15034 ) {
15035 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15036 // when the caret is just above or just below the deleted hunk.
15037 let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15038 let related_to_selection = if allow_adjacent {
15039 hunk.row_range.overlaps(&query_rows)
15040 || hunk.row_range.start == query_rows.end
15041 || hunk.row_range.end == query_rows.start
15042 } else {
15043 hunk.row_range.overlaps(&query_rows)
15044 };
15045 if related_to_selection {
15046 if !processed_buffer_rows
15047 .entry(hunk.buffer_id)
15048 .or_default()
15049 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15050 {
15051 continue;
15052 }
15053 hunks.push(hunk);
15054 }
15055 }
15056 }
15057
15058 hunks
15059 }
15060
15061 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15062 self.display_snapshot.buffer_snapshot.language_at(position)
15063 }
15064
15065 pub fn is_focused(&self) -> bool {
15066 self.is_focused
15067 }
15068
15069 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15070 self.placeholder_text.as_ref()
15071 }
15072
15073 pub fn scroll_position(&self) -> gpui::Point<f32> {
15074 self.scroll_anchor.scroll_position(&self.display_snapshot)
15075 }
15076
15077 fn gutter_dimensions(
15078 &self,
15079 font_id: FontId,
15080 font_size: Pixels,
15081 em_width: Pixels,
15082 em_advance: Pixels,
15083 max_line_number_width: Pixels,
15084 cx: &App,
15085 ) -> GutterDimensions {
15086 if !self.show_gutter {
15087 return GutterDimensions::default();
15088 }
15089 let descent = cx.text_system().descent(font_id, font_size);
15090
15091 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15092 matches!(
15093 ProjectSettings::get_global(cx).git.git_gutter,
15094 Some(GitGutterSetting::TrackedFiles)
15095 )
15096 });
15097 let gutter_settings = EditorSettings::get_global(cx).gutter;
15098 let show_line_numbers = self
15099 .show_line_numbers
15100 .unwrap_or(gutter_settings.line_numbers);
15101 let line_gutter_width = if show_line_numbers {
15102 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15103 let min_width_for_number_on_gutter = em_advance * 4.0;
15104 max_line_number_width.max(min_width_for_number_on_gutter)
15105 } else {
15106 0.0.into()
15107 };
15108
15109 let show_code_actions = self
15110 .show_code_actions
15111 .unwrap_or(gutter_settings.code_actions);
15112
15113 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15114
15115 let git_blame_entries_width =
15116 self.git_blame_gutter_max_author_length
15117 .map(|max_author_length| {
15118 // Length of the author name, but also space for the commit hash,
15119 // the spacing and the timestamp.
15120 let max_char_count = max_author_length
15121 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15122 + 7 // length of commit sha
15123 + 14 // length of max relative timestamp ("60 minutes ago")
15124 + 4; // gaps and margins
15125
15126 em_advance * max_char_count
15127 });
15128
15129 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15130 left_padding += if show_code_actions || show_runnables {
15131 em_width * 3.0
15132 } else if show_git_gutter && show_line_numbers {
15133 em_width * 2.0
15134 } else if show_git_gutter || show_line_numbers {
15135 em_width
15136 } else {
15137 px(0.)
15138 };
15139
15140 let right_padding = if gutter_settings.folds && show_line_numbers {
15141 em_width * 4.0
15142 } else if gutter_settings.folds {
15143 em_width * 3.0
15144 } else if show_line_numbers {
15145 em_width
15146 } else {
15147 px(0.)
15148 };
15149
15150 GutterDimensions {
15151 left_padding,
15152 right_padding,
15153 width: line_gutter_width + left_padding + right_padding,
15154 margin: -descent,
15155 git_blame_entries_width,
15156 }
15157 }
15158
15159 pub fn render_crease_toggle(
15160 &self,
15161 buffer_row: MultiBufferRow,
15162 row_contains_cursor: bool,
15163 editor: Entity<Editor>,
15164 window: &mut Window,
15165 cx: &mut App,
15166 ) -> Option<AnyElement> {
15167 let folded = self.is_line_folded(buffer_row);
15168 let mut is_foldable = false;
15169
15170 if let Some(crease) = self
15171 .crease_snapshot
15172 .query_row(buffer_row, &self.buffer_snapshot)
15173 {
15174 is_foldable = true;
15175 match crease {
15176 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15177 if let Some(render_toggle) = render_toggle {
15178 let toggle_callback =
15179 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15180 if folded {
15181 editor.update(cx, |editor, cx| {
15182 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15183 });
15184 } else {
15185 editor.update(cx, |editor, cx| {
15186 editor.unfold_at(
15187 &crate::UnfoldAt { buffer_row },
15188 window,
15189 cx,
15190 )
15191 });
15192 }
15193 });
15194 return Some((render_toggle)(
15195 buffer_row,
15196 folded,
15197 toggle_callback,
15198 window,
15199 cx,
15200 ));
15201 }
15202 }
15203 }
15204 }
15205
15206 is_foldable |= self.starts_indent(buffer_row);
15207
15208 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15209 Some(
15210 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15211 .toggle_state(folded)
15212 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15213 if folded {
15214 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15215 } else {
15216 this.fold_at(&FoldAt { buffer_row }, window, cx);
15217 }
15218 }))
15219 .into_any_element(),
15220 )
15221 } else {
15222 None
15223 }
15224 }
15225
15226 pub fn render_crease_trailer(
15227 &self,
15228 buffer_row: MultiBufferRow,
15229 window: &mut Window,
15230 cx: &mut App,
15231 ) -> Option<AnyElement> {
15232 let folded = self.is_line_folded(buffer_row);
15233 if let Crease::Inline { render_trailer, .. } = self
15234 .crease_snapshot
15235 .query_row(buffer_row, &self.buffer_snapshot)?
15236 {
15237 let render_trailer = render_trailer.as_ref()?;
15238 Some(render_trailer(buffer_row, folded, window, cx))
15239 } else {
15240 None
15241 }
15242 }
15243}
15244
15245impl Deref for EditorSnapshot {
15246 type Target = DisplaySnapshot;
15247
15248 fn deref(&self) -> &Self::Target {
15249 &self.display_snapshot
15250 }
15251}
15252
15253#[derive(Clone, Debug, PartialEq, Eq)]
15254pub enum EditorEvent {
15255 InputIgnored {
15256 text: Arc<str>,
15257 },
15258 InputHandled {
15259 utf16_range_to_replace: Option<Range<isize>>,
15260 text: Arc<str>,
15261 },
15262 ExcerptsAdded {
15263 buffer: Entity<Buffer>,
15264 predecessor: ExcerptId,
15265 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15266 },
15267 ExcerptsRemoved {
15268 ids: Vec<ExcerptId>,
15269 },
15270 BufferFoldToggled {
15271 ids: Vec<ExcerptId>,
15272 folded: bool,
15273 },
15274 ExcerptsEdited {
15275 ids: Vec<ExcerptId>,
15276 },
15277 ExcerptsExpanded {
15278 ids: Vec<ExcerptId>,
15279 },
15280 BufferEdited,
15281 Edited {
15282 transaction_id: clock::Lamport,
15283 },
15284 Reparsed(BufferId),
15285 Focused,
15286 FocusedIn,
15287 Blurred,
15288 DirtyChanged,
15289 Saved,
15290 TitleChanged,
15291 DiffBaseChanged,
15292 SelectionsChanged {
15293 local: bool,
15294 },
15295 ScrollPositionChanged {
15296 local: bool,
15297 autoscroll: bool,
15298 },
15299 Closed,
15300 TransactionUndone {
15301 transaction_id: clock::Lamport,
15302 },
15303 TransactionBegun {
15304 transaction_id: clock::Lamport,
15305 },
15306 Reloaded,
15307 CursorShapeChanged,
15308}
15309
15310impl EventEmitter<EditorEvent> for Editor {}
15311
15312impl Focusable for Editor {
15313 fn focus_handle(&self, _cx: &App) -> FocusHandle {
15314 self.focus_handle.clone()
15315 }
15316}
15317
15318impl Render for Editor {
15319 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15320 let settings = ThemeSettings::get_global(cx);
15321
15322 let mut text_style = match self.mode {
15323 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15324 color: cx.theme().colors().editor_foreground,
15325 font_family: settings.ui_font.family.clone(),
15326 font_features: settings.ui_font.features.clone(),
15327 font_fallbacks: settings.ui_font.fallbacks.clone(),
15328 font_size: rems(0.875).into(),
15329 font_weight: settings.ui_font.weight,
15330 line_height: relative(settings.buffer_line_height.value()),
15331 ..Default::default()
15332 },
15333 EditorMode::Full => TextStyle {
15334 color: cx.theme().colors().editor_foreground,
15335 font_family: settings.buffer_font.family.clone(),
15336 font_features: settings.buffer_font.features.clone(),
15337 font_fallbacks: settings.buffer_font.fallbacks.clone(),
15338 font_size: settings.buffer_font_size().into(),
15339 font_weight: settings.buffer_font.weight,
15340 line_height: relative(settings.buffer_line_height.value()),
15341 ..Default::default()
15342 },
15343 };
15344 if let Some(text_style_refinement) = &self.text_style_refinement {
15345 text_style.refine(text_style_refinement)
15346 }
15347
15348 let background = match self.mode {
15349 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15350 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15351 EditorMode::Full => cx.theme().colors().editor_background,
15352 };
15353
15354 EditorElement::new(
15355 &cx.entity(),
15356 EditorStyle {
15357 background,
15358 local_player: cx.theme().players().local(),
15359 text: text_style,
15360 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15361 syntax: cx.theme().syntax().clone(),
15362 status: cx.theme().status().clone(),
15363 inlay_hints_style: make_inlay_hints_style(cx),
15364 inline_completion_styles: make_suggestion_styles(cx),
15365 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15366 },
15367 )
15368 }
15369}
15370
15371impl EntityInputHandler for Editor {
15372 fn text_for_range(
15373 &mut self,
15374 range_utf16: Range<usize>,
15375 adjusted_range: &mut Option<Range<usize>>,
15376 _: &mut Window,
15377 cx: &mut Context<Self>,
15378 ) -> Option<String> {
15379 let snapshot = self.buffer.read(cx).read(cx);
15380 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15381 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15382 if (start.0..end.0) != range_utf16 {
15383 adjusted_range.replace(start.0..end.0);
15384 }
15385 Some(snapshot.text_for_range(start..end).collect())
15386 }
15387
15388 fn selected_text_range(
15389 &mut self,
15390 ignore_disabled_input: bool,
15391 _: &mut Window,
15392 cx: &mut Context<Self>,
15393 ) -> Option<UTF16Selection> {
15394 // Prevent the IME menu from appearing when holding down an alphabetic key
15395 // while input is disabled.
15396 if !ignore_disabled_input && !self.input_enabled {
15397 return None;
15398 }
15399
15400 let selection = self.selections.newest::<OffsetUtf16>(cx);
15401 let range = selection.range();
15402
15403 Some(UTF16Selection {
15404 range: range.start.0..range.end.0,
15405 reversed: selection.reversed,
15406 })
15407 }
15408
15409 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15410 let snapshot = self.buffer.read(cx).read(cx);
15411 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15412 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15413 }
15414
15415 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15416 self.clear_highlights::<InputComposition>(cx);
15417 self.ime_transaction.take();
15418 }
15419
15420 fn replace_text_in_range(
15421 &mut self,
15422 range_utf16: Option<Range<usize>>,
15423 text: &str,
15424 window: &mut Window,
15425 cx: &mut Context<Self>,
15426 ) {
15427 if !self.input_enabled {
15428 cx.emit(EditorEvent::InputIgnored { text: text.into() });
15429 return;
15430 }
15431
15432 self.transact(window, cx, |this, window, cx| {
15433 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15434 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15435 Some(this.selection_replacement_ranges(range_utf16, cx))
15436 } else {
15437 this.marked_text_ranges(cx)
15438 };
15439
15440 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15441 let newest_selection_id = this.selections.newest_anchor().id;
15442 this.selections
15443 .all::<OffsetUtf16>(cx)
15444 .iter()
15445 .zip(ranges_to_replace.iter())
15446 .find_map(|(selection, range)| {
15447 if selection.id == newest_selection_id {
15448 Some(
15449 (range.start.0 as isize - selection.head().0 as isize)
15450 ..(range.end.0 as isize - selection.head().0 as isize),
15451 )
15452 } else {
15453 None
15454 }
15455 })
15456 });
15457
15458 cx.emit(EditorEvent::InputHandled {
15459 utf16_range_to_replace: range_to_replace,
15460 text: text.into(),
15461 });
15462
15463 if let Some(new_selected_ranges) = new_selected_ranges {
15464 this.change_selections(None, window, cx, |selections| {
15465 selections.select_ranges(new_selected_ranges)
15466 });
15467 this.backspace(&Default::default(), window, cx);
15468 }
15469
15470 this.handle_input(text, window, cx);
15471 });
15472
15473 if let Some(transaction) = self.ime_transaction {
15474 self.buffer.update(cx, |buffer, cx| {
15475 buffer.group_until_transaction(transaction, cx);
15476 });
15477 }
15478
15479 self.unmark_text(window, cx);
15480 }
15481
15482 fn replace_and_mark_text_in_range(
15483 &mut self,
15484 range_utf16: Option<Range<usize>>,
15485 text: &str,
15486 new_selected_range_utf16: Option<Range<usize>>,
15487 window: &mut Window,
15488 cx: &mut Context<Self>,
15489 ) {
15490 if !self.input_enabled {
15491 return;
15492 }
15493
15494 let transaction = self.transact(window, cx, |this, window, cx| {
15495 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15496 let snapshot = this.buffer.read(cx).read(cx);
15497 if let Some(relative_range_utf16) = range_utf16.as_ref() {
15498 for marked_range in &mut marked_ranges {
15499 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15500 marked_range.start.0 += relative_range_utf16.start;
15501 marked_range.start =
15502 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15503 marked_range.end =
15504 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15505 }
15506 }
15507 Some(marked_ranges)
15508 } else if let Some(range_utf16) = range_utf16 {
15509 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15510 Some(this.selection_replacement_ranges(range_utf16, cx))
15511 } else {
15512 None
15513 };
15514
15515 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
15516 let newest_selection_id = this.selections.newest_anchor().id;
15517 this.selections
15518 .all::<OffsetUtf16>(cx)
15519 .iter()
15520 .zip(ranges_to_replace.iter())
15521 .find_map(|(selection, range)| {
15522 if selection.id == newest_selection_id {
15523 Some(
15524 (range.start.0 as isize - selection.head().0 as isize)
15525 ..(range.end.0 as isize - selection.head().0 as isize),
15526 )
15527 } else {
15528 None
15529 }
15530 })
15531 });
15532
15533 cx.emit(EditorEvent::InputHandled {
15534 utf16_range_to_replace: range_to_replace,
15535 text: text.into(),
15536 });
15537
15538 if let Some(ranges) = ranges_to_replace {
15539 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
15540 }
15541
15542 let marked_ranges = {
15543 let snapshot = this.buffer.read(cx).read(cx);
15544 this.selections
15545 .disjoint_anchors()
15546 .iter()
15547 .map(|selection| {
15548 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
15549 })
15550 .collect::<Vec<_>>()
15551 };
15552
15553 if text.is_empty() {
15554 this.unmark_text(window, cx);
15555 } else {
15556 this.highlight_text::<InputComposition>(
15557 marked_ranges.clone(),
15558 HighlightStyle {
15559 underline: Some(UnderlineStyle {
15560 thickness: px(1.),
15561 color: None,
15562 wavy: false,
15563 }),
15564 ..Default::default()
15565 },
15566 cx,
15567 );
15568 }
15569
15570 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
15571 let use_autoclose = this.use_autoclose;
15572 let use_auto_surround = this.use_auto_surround;
15573 this.set_use_autoclose(false);
15574 this.set_use_auto_surround(false);
15575 this.handle_input(text, window, cx);
15576 this.set_use_autoclose(use_autoclose);
15577 this.set_use_auto_surround(use_auto_surround);
15578
15579 if let Some(new_selected_range) = new_selected_range_utf16 {
15580 let snapshot = this.buffer.read(cx).read(cx);
15581 let new_selected_ranges = marked_ranges
15582 .into_iter()
15583 .map(|marked_range| {
15584 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
15585 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
15586 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
15587 snapshot.clip_offset_utf16(new_start, Bias::Left)
15588 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
15589 })
15590 .collect::<Vec<_>>();
15591
15592 drop(snapshot);
15593 this.change_selections(None, window, cx, |selections| {
15594 selections.select_ranges(new_selected_ranges)
15595 });
15596 }
15597 });
15598
15599 self.ime_transaction = self.ime_transaction.or(transaction);
15600 if let Some(transaction) = self.ime_transaction {
15601 self.buffer.update(cx, |buffer, cx| {
15602 buffer.group_until_transaction(transaction, cx);
15603 });
15604 }
15605
15606 if self.text_highlights::<InputComposition>(cx).is_none() {
15607 self.ime_transaction.take();
15608 }
15609 }
15610
15611 fn bounds_for_range(
15612 &mut self,
15613 range_utf16: Range<usize>,
15614 element_bounds: gpui::Bounds<Pixels>,
15615 window: &mut Window,
15616 cx: &mut Context<Self>,
15617 ) -> Option<gpui::Bounds<Pixels>> {
15618 let text_layout_details = self.text_layout_details(window);
15619 let gpui::Point {
15620 x: em_width,
15621 y: line_height,
15622 } = self.character_size(window);
15623
15624 let snapshot = self.snapshot(window, cx);
15625 let scroll_position = snapshot.scroll_position();
15626 let scroll_left = scroll_position.x * em_width;
15627
15628 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
15629 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
15630 + self.gutter_dimensions.width
15631 + self.gutter_dimensions.margin;
15632 let y = line_height * (start.row().as_f32() - scroll_position.y);
15633
15634 Some(Bounds {
15635 origin: element_bounds.origin + point(x, y),
15636 size: size(em_width, line_height),
15637 })
15638 }
15639}
15640
15641trait SelectionExt {
15642 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
15643 fn spanned_rows(
15644 &self,
15645 include_end_if_at_line_start: bool,
15646 map: &DisplaySnapshot,
15647 ) -> Range<MultiBufferRow>;
15648}
15649
15650impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
15651 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
15652 let start = self
15653 .start
15654 .to_point(&map.buffer_snapshot)
15655 .to_display_point(map);
15656 let end = self
15657 .end
15658 .to_point(&map.buffer_snapshot)
15659 .to_display_point(map);
15660 if self.reversed {
15661 end..start
15662 } else {
15663 start..end
15664 }
15665 }
15666
15667 fn spanned_rows(
15668 &self,
15669 include_end_if_at_line_start: bool,
15670 map: &DisplaySnapshot,
15671 ) -> Range<MultiBufferRow> {
15672 let start = self.start.to_point(&map.buffer_snapshot);
15673 let mut end = self.end.to_point(&map.buffer_snapshot);
15674 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
15675 end.row -= 1;
15676 }
15677
15678 let buffer_start = map.prev_line_boundary(start).0;
15679 let buffer_end = map.next_line_boundary(end).0;
15680 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
15681 }
15682}
15683
15684impl<T: InvalidationRegion> InvalidationStack<T> {
15685 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
15686 where
15687 S: Clone + ToOffset,
15688 {
15689 while let Some(region) = self.last() {
15690 let all_selections_inside_invalidation_ranges =
15691 if selections.len() == region.ranges().len() {
15692 selections
15693 .iter()
15694 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
15695 .all(|(selection, invalidation_range)| {
15696 let head = selection.head().to_offset(buffer);
15697 invalidation_range.start <= head && invalidation_range.end >= head
15698 })
15699 } else {
15700 false
15701 };
15702
15703 if all_selections_inside_invalidation_ranges {
15704 break;
15705 } else {
15706 self.pop();
15707 }
15708 }
15709 }
15710}
15711
15712impl<T> Default for InvalidationStack<T> {
15713 fn default() -> Self {
15714 Self(Default::default())
15715 }
15716}
15717
15718impl<T> Deref for InvalidationStack<T> {
15719 type Target = Vec<T>;
15720
15721 fn deref(&self) -> &Self::Target {
15722 &self.0
15723 }
15724}
15725
15726impl<T> DerefMut for InvalidationStack<T> {
15727 fn deref_mut(&mut self) -> &mut Self::Target {
15728 &mut self.0
15729 }
15730}
15731
15732impl InvalidationRegion for SnippetState {
15733 fn ranges(&self) -> &[Range<Anchor>] {
15734 &self.ranges[self.active_index]
15735 }
15736}
15737
15738pub fn diagnostic_block_renderer(
15739 diagnostic: Diagnostic,
15740 max_message_rows: Option<u8>,
15741 allow_closing: bool,
15742 _is_valid: bool,
15743) -> RenderBlock {
15744 let (text_without_backticks, code_ranges) =
15745 highlight_diagnostic_message(&diagnostic, max_message_rows);
15746
15747 Arc::new(move |cx: &mut BlockContext| {
15748 let group_id: SharedString = cx.block_id.to_string().into();
15749
15750 let mut text_style = cx.window.text_style().clone();
15751 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
15752 let theme_settings = ThemeSettings::get_global(cx);
15753 text_style.font_family = theme_settings.buffer_font.family.clone();
15754 text_style.font_style = theme_settings.buffer_font.style;
15755 text_style.font_features = theme_settings.buffer_font.features.clone();
15756 text_style.font_weight = theme_settings.buffer_font.weight;
15757
15758 let multi_line_diagnostic = diagnostic.message.contains('\n');
15759
15760 let buttons = |diagnostic: &Diagnostic| {
15761 if multi_line_diagnostic {
15762 v_flex()
15763 } else {
15764 h_flex()
15765 }
15766 .when(allow_closing, |div| {
15767 div.children(diagnostic.is_primary.then(|| {
15768 IconButton::new("close-block", IconName::XCircle)
15769 .icon_color(Color::Muted)
15770 .size(ButtonSize::Compact)
15771 .style(ButtonStyle::Transparent)
15772 .visible_on_hover(group_id.clone())
15773 .on_click(move |_click, window, cx| {
15774 window.dispatch_action(Box::new(Cancel), cx)
15775 })
15776 .tooltip(|window, cx| {
15777 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
15778 })
15779 }))
15780 })
15781 .child(
15782 IconButton::new("copy-block", IconName::Copy)
15783 .icon_color(Color::Muted)
15784 .size(ButtonSize::Compact)
15785 .style(ButtonStyle::Transparent)
15786 .visible_on_hover(group_id.clone())
15787 .on_click({
15788 let message = diagnostic.message.clone();
15789 move |_click, _, cx| {
15790 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
15791 }
15792 })
15793 .tooltip(Tooltip::text("Copy diagnostic message")),
15794 )
15795 };
15796
15797 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
15798 AvailableSpace::min_size(),
15799 cx.window,
15800 cx.app,
15801 );
15802
15803 h_flex()
15804 .id(cx.block_id)
15805 .group(group_id.clone())
15806 .relative()
15807 .size_full()
15808 .block_mouse_down()
15809 .pl(cx.gutter_dimensions.width)
15810 .w(cx.max_width - cx.gutter_dimensions.full_width())
15811 .child(
15812 div()
15813 .flex()
15814 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
15815 .flex_shrink(),
15816 )
15817 .child(buttons(&diagnostic))
15818 .child(div().flex().flex_shrink_0().child(
15819 StyledText::new(text_without_backticks.clone()).with_highlights(
15820 &text_style,
15821 code_ranges.iter().map(|range| {
15822 (
15823 range.clone(),
15824 HighlightStyle {
15825 font_weight: Some(FontWeight::BOLD),
15826 ..Default::default()
15827 },
15828 )
15829 }),
15830 ),
15831 ))
15832 .into_any_element()
15833 })
15834}
15835
15836fn inline_completion_edit_text(
15837 current_snapshot: &BufferSnapshot,
15838 edits: &[(Range<Anchor>, String)],
15839 edit_preview: &EditPreview,
15840 include_deletions: bool,
15841 cx: &App,
15842) -> Option<HighlightedEdits> {
15843 let edits = edits
15844 .iter()
15845 .map(|(anchor, text)| {
15846 (
15847 anchor.start.text_anchor..anchor.end.text_anchor,
15848 text.clone(),
15849 )
15850 })
15851 .collect::<Vec<_>>();
15852
15853 Some(edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx))
15854}
15855
15856pub fn highlight_diagnostic_message(
15857 diagnostic: &Diagnostic,
15858 mut max_message_rows: Option<u8>,
15859) -> (SharedString, Vec<Range<usize>>) {
15860 let mut text_without_backticks = String::new();
15861 let mut code_ranges = Vec::new();
15862
15863 if let Some(source) = &diagnostic.source {
15864 text_without_backticks.push_str(source);
15865 code_ranges.push(0..source.len());
15866 text_without_backticks.push_str(": ");
15867 }
15868
15869 let mut prev_offset = 0;
15870 let mut in_code_block = false;
15871 let has_row_limit = max_message_rows.is_some();
15872 let mut newline_indices = diagnostic
15873 .message
15874 .match_indices('\n')
15875 .filter(|_| has_row_limit)
15876 .map(|(ix, _)| ix)
15877 .fuse()
15878 .peekable();
15879
15880 for (quote_ix, _) in diagnostic
15881 .message
15882 .match_indices('`')
15883 .chain([(diagnostic.message.len(), "")])
15884 {
15885 let mut first_newline_ix = None;
15886 let mut last_newline_ix = None;
15887 while let Some(newline_ix) = newline_indices.peek() {
15888 if *newline_ix < quote_ix {
15889 if first_newline_ix.is_none() {
15890 first_newline_ix = Some(*newline_ix);
15891 }
15892 last_newline_ix = Some(*newline_ix);
15893
15894 if let Some(rows_left) = &mut max_message_rows {
15895 if *rows_left == 0 {
15896 break;
15897 } else {
15898 *rows_left -= 1;
15899 }
15900 }
15901 let _ = newline_indices.next();
15902 } else {
15903 break;
15904 }
15905 }
15906 let prev_len = text_without_backticks.len();
15907 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
15908 text_without_backticks.push_str(new_text);
15909 if in_code_block {
15910 code_ranges.push(prev_len..text_without_backticks.len());
15911 }
15912 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
15913 in_code_block = !in_code_block;
15914 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
15915 text_without_backticks.push_str("...");
15916 break;
15917 }
15918 }
15919
15920 (text_without_backticks.into(), code_ranges)
15921}
15922
15923fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
15924 match severity {
15925 DiagnosticSeverity::ERROR => colors.error,
15926 DiagnosticSeverity::WARNING => colors.warning,
15927 DiagnosticSeverity::INFORMATION => colors.info,
15928 DiagnosticSeverity::HINT => colors.info,
15929 _ => colors.ignored,
15930 }
15931}
15932
15933pub fn styled_runs_for_code_label<'a>(
15934 label: &'a CodeLabel,
15935 syntax_theme: &'a theme::SyntaxTheme,
15936) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15937 let fade_out = HighlightStyle {
15938 fade_out: Some(0.35),
15939 ..Default::default()
15940 };
15941
15942 let mut prev_end = label.filter_range.end;
15943 label
15944 .runs
15945 .iter()
15946 .enumerate()
15947 .flat_map(move |(ix, (range, highlight_id))| {
15948 let style = if let Some(style) = highlight_id.style(syntax_theme) {
15949 style
15950 } else {
15951 return Default::default();
15952 };
15953 let mut muted_style = style;
15954 muted_style.highlight(fade_out);
15955
15956 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15957 if range.start >= label.filter_range.end {
15958 if range.start > prev_end {
15959 runs.push((prev_end..range.start, fade_out));
15960 }
15961 runs.push((range.clone(), muted_style));
15962 } else if range.end <= label.filter_range.end {
15963 runs.push((range.clone(), style));
15964 } else {
15965 runs.push((range.start..label.filter_range.end, style));
15966 runs.push((label.filter_range.end..range.end, muted_style));
15967 }
15968 prev_end = cmp::max(prev_end, range.end);
15969
15970 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15971 runs.push((prev_end..label.text.len(), fade_out));
15972 }
15973
15974 runs
15975 })
15976}
15977
15978pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15979 let mut prev_index = 0;
15980 let mut prev_codepoint: Option<char> = None;
15981 text.char_indices()
15982 .chain([(text.len(), '\0')])
15983 .filter_map(move |(index, codepoint)| {
15984 let prev_codepoint = prev_codepoint.replace(codepoint)?;
15985 let is_boundary = index == text.len()
15986 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15987 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15988 if is_boundary {
15989 let chunk = &text[prev_index..index];
15990 prev_index = index;
15991 Some(chunk)
15992 } else {
15993 None
15994 }
15995 })
15996}
15997
15998pub trait RangeToAnchorExt: Sized {
15999 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16000
16001 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16002 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16003 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16004 }
16005}
16006
16007impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16008 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16009 let start_offset = self.start.to_offset(snapshot);
16010 let end_offset = self.end.to_offset(snapshot);
16011 if start_offset == end_offset {
16012 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16013 } else {
16014 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16015 }
16016 }
16017}
16018
16019pub trait RowExt {
16020 fn as_f32(&self) -> f32;
16021
16022 fn next_row(&self) -> Self;
16023
16024 fn previous_row(&self) -> Self;
16025
16026 fn minus(&self, other: Self) -> u32;
16027}
16028
16029impl RowExt for DisplayRow {
16030 fn as_f32(&self) -> f32 {
16031 self.0 as f32
16032 }
16033
16034 fn next_row(&self) -> Self {
16035 Self(self.0 + 1)
16036 }
16037
16038 fn previous_row(&self) -> Self {
16039 Self(self.0.saturating_sub(1))
16040 }
16041
16042 fn minus(&self, other: Self) -> u32 {
16043 self.0 - other.0
16044 }
16045}
16046
16047impl RowExt for MultiBufferRow {
16048 fn as_f32(&self) -> f32 {
16049 self.0 as f32
16050 }
16051
16052 fn next_row(&self) -> Self {
16053 Self(self.0 + 1)
16054 }
16055
16056 fn previous_row(&self) -> Self {
16057 Self(self.0.saturating_sub(1))
16058 }
16059
16060 fn minus(&self, other: Self) -> u32 {
16061 self.0 - other.0
16062 }
16063}
16064
16065trait RowRangeExt {
16066 type Row;
16067
16068 fn len(&self) -> usize;
16069
16070 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16071}
16072
16073impl RowRangeExt for Range<MultiBufferRow> {
16074 type Row = MultiBufferRow;
16075
16076 fn len(&self) -> usize {
16077 (self.end.0 - self.start.0) as usize
16078 }
16079
16080 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16081 (self.start.0..self.end.0).map(MultiBufferRow)
16082 }
16083}
16084
16085impl RowRangeExt for Range<DisplayRow> {
16086 type Row = DisplayRow;
16087
16088 fn len(&self) -> usize {
16089 (self.end.0 - self.start.0) as usize
16090 }
16091
16092 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16093 (self.start.0..self.end.0).map(DisplayRow)
16094 }
16095}
16096
16097/// If select range has more than one line, we
16098/// just point the cursor to range.start.
16099fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16100 if range.start.row == range.end.row {
16101 range
16102 } else {
16103 range.start..range.start
16104 }
16105}
16106pub struct KillRing(ClipboardItem);
16107impl Global for KillRing {}
16108
16109const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16110
16111fn all_edits_insertions_or_deletions(
16112 edits: &Vec<(Range<Anchor>, String)>,
16113 snapshot: &MultiBufferSnapshot,
16114) -> bool {
16115 let mut all_insertions = true;
16116 let mut all_deletions = true;
16117
16118 for (range, new_text) in edits.iter() {
16119 let range_is_empty = range.to_offset(&snapshot).is_empty();
16120 let text_is_empty = new_text.is_empty();
16121
16122 if range_is_empty != text_is_empty {
16123 if range_is_empty {
16124 all_deletions = false;
16125 } else {
16126 all_insertions = false;
16127 }
16128 } else {
16129 return false;
16130 }
16131
16132 if !all_insertions && !all_deletions {
16133 return false;
16134 }
16135 }
16136 all_insertions || all_deletions
16137}