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;
72
73use code_context_menus::{
74 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
75 CompletionsMenu, ContextMenuOrigin,
76};
77use git::blame::GitBlame;
78use gpui::{
79 div, impl_actions, linear_color_stop, linear_gradient, point, prelude::*, pulsating_between,
80 px, relative, size, Action, Animation, AnimationExt, AnyElement, App, AsyncWindowContext,
81 AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context, DispatchPhase, ElementId,
82 Entity, EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId,
83 FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Modifiers, MouseButton,
84 MouseDownEvent, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled,
85 StyledText, 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 CompletionDocumentation, CursorShape, Diagnostic, EditPreview, HighlightedText, IndentKind,
100 IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
101 TransactionId, 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, TakeUntilExt, 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 cx.activate(true);
336 Editor::new_file(workspace, &Default::default(), window, cx)
337 },
338 )
339 .detach();
340 }
341 });
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
468pub(crate) enum EditDisplayMode {
469 TabAccept(bool),
470 DiffPopover,
471 Inline,
472}
473
474enum InlineCompletion {
475 Edit {
476 edits: Vec<(Range<Anchor>, String)>,
477 edit_preview: Option<EditPreview>,
478 display_mode: EditDisplayMode,
479 snapshot: BufferSnapshot,
480 },
481 Move {
482 target: Anchor,
483 range_around_target: Range<text::Anchor>,
484 snapshot: BufferSnapshot,
485 },
486}
487
488struct InlineCompletionState {
489 inlay_ids: Vec<InlayId>,
490 completion: InlineCompletion,
491 invalidation_range: Range<Anchor>,
492}
493
494impl InlineCompletionState {
495 pub fn is_move(&self) -> bool {
496 match &self.completion {
497 InlineCompletion::Move { .. } => true,
498 _ => false,
499 }
500 }
501}
502
503enum InlineCompletionHighlight {}
504
505pub enum MenuInlineCompletionsPolicy {
506 Never,
507 ByProvider,
508}
509
510#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
511struct EditorActionId(usize);
512
513impl EditorActionId {
514 pub fn post_inc(&mut self) -> Self {
515 let answer = self.0;
516
517 *self = Self(answer + 1);
518
519 Self(answer)
520 }
521}
522
523// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
524// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
525
526type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
527type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
528
529#[derive(Default)]
530struct ScrollbarMarkerState {
531 scrollbar_size: Size<Pixels>,
532 dirty: bool,
533 markers: Arc<[PaintQuad]>,
534 pending_refresh: Option<Task<Result<()>>>,
535}
536
537impl ScrollbarMarkerState {
538 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
539 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
540 }
541}
542
543#[derive(Clone, Debug)]
544struct RunnableTasks {
545 templates: Vec<(TaskSourceKind, TaskTemplate)>,
546 offset: MultiBufferOffset,
547 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
548 column: u32,
549 // Values of all named captures, including those starting with '_'
550 extra_variables: HashMap<String, String>,
551 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
552 context_range: Range<BufferOffset>,
553}
554
555impl RunnableTasks {
556 fn resolve<'a>(
557 &'a self,
558 cx: &'a task::TaskContext,
559 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
560 self.templates.iter().filter_map(|(kind, template)| {
561 template
562 .resolve_task(&kind.to_id_base(), cx)
563 .map(|task| (kind.clone(), task))
564 })
565 }
566}
567
568#[derive(Clone)]
569struct ResolvedTasks {
570 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
571 position: Anchor,
572}
573#[derive(Copy, Clone, Debug)]
574struct MultiBufferOffset(usize);
575#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
576struct BufferOffset(usize);
577
578// Addons allow storing per-editor state in other crates (e.g. Vim)
579pub trait Addon: 'static {
580 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
581
582 fn to_any(&self) -> &dyn std::any::Any;
583}
584
585#[derive(Debug, Copy, Clone, PartialEq, Eq)]
586pub enum IsVimMode {
587 Yes,
588 No,
589}
590
591/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
592///
593/// See the [module level documentation](self) for more information.
594pub struct Editor {
595 focus_handle: FocusHandle,
596 last_focused_descendant: Option<WeakFocusHandle>,
597 /// The text buffer being edited
598 buffer: Entity<MultiBuffer>,
599 /// Map of how text in the buffer should be displayed.
600 /// Handles soft wraps, folds, fake inlay text insertions, etc.
601 pub display_map: Entity<DisplayMap>,
602 pub selections: SelectionsCollection,
603 pub scroll_manager: ScrollManager,
604 /// When inline assist editors are linked, they all render cursors because
605 /// typing enters text into each of them, even the ones that aren't focused.
606 pub(crate) show_cursor_when_unfocused: bool,
607 columnar_selection_tail: Option<Anchor>,
608 add_selections_state: Option<AddSelectionsState>,
609 select_next_state: Option<SelectNextState>,
610 select_prev_state: Option<SelectNextState>,
611 selection_history: SelectionHistory,
612 autoclose_regions: Vec<AutocloseRegion>,
613 snippet_stack: InvalidationStack<SnippetState>,
614 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
615 ime_transaction: Option<TransactionId>,
616 active_diagnostics: Option<ActiveDiagnosticGroup>,
617 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
618
619 // TODO: make this a access method
620 pub project: Option<Entity<Project>>,
621 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
622 completion_provider: Option<Box<dyn CompletionProvider>>,
623 collaboration_hub: Option<Box<dyn CollaborationHub>>,
624 blink_manager: Entity<BlinkManager>,
625 show_cursor_names: bool,
626 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
627 pub show_local_selections: bool,
628 mode: EditorMode,
629 show_breadcrumbs: bool,
630 show_gutter: bool,
631 show_scrollbars: bool,
632 show_line_numbers: Option<bool>,
633 use_relative_line_numbers: Option<bool>,
634 show_git_diff_gutter: Option<bool>,
635 show_code_actions: Option<bool>,
636 show_runnables: Option<bool>,
637 show_wrap_guides: Option<bool>,
638 show_indent_guides: Option<bool>,
639 placeholder_text: Option<Arc<str>>,
640 highlight_order: usize,
641 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
642 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
643 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
644 scrollbar_marker_state: ScrollbarMarkerState,
645 active_indent_guides_state: ActiveIndentGuidesState,
646 nav_history: Option<ItemNavHistory>,
647 context_menu: RefCell<Option<CodeContextMenu>>,
648 mouse_context_menu: Option<MouseContextMenu>,
649 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
650 signature_help_state: SignatureHelpState,
651 auto_signature_help: Option<bool>,
652 find_all_references_task_sources: Vec<Anchor>,
653 next_completion_id: CompletionId,
654 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
655 code_actions_task: Option<Task<Result<()>>>,
656 document_highlights_task: Option<Task<()>>,
657 linked_editing_range_task: Option<Task<Option<()>>>,
658 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
659 pending_rename: Option<RenameState>,
660 searchable: bool,
661 cursor_shape: CursorShape,
662 current_line_highlight: Option<CurrentLineHighlight>,
663 collapse_matches: bool,
664 autoindent_mode: Option<AutoindentMode>,
665 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
666 input_enabled: bool,
667 use_modal_editing: bool,
668 read_only: bool,
669 leader_peer_id: Option<PeerId>,
670 remote_id: Option<ViewId>,
671 hover_state: HoverState,
672 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
673 gutter_hovered: bool,
674 hovered_link_state: Option<HoveredLinkState>,
675 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
676 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
677 active_inline_completion: Option<InlineCompletionState>,
678 /// Used to prevent flickering as the user types while the menu is open
679 stale_inline_completion_in_menu: Option<InlineCompletionState>,
680 // enable_inline_completions is a switch that Vim can use to disable
681 // edit predictions based on its mode.
682 enable_inline_completions: bool,
683 show_inline_completions_override: Option<bool>,
684 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
685 inlay_hint_cache: InlayHintCache,
686 next_inlay_id: usize,
687 _subscriptions: Vec<Subscription>,
688 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
689 gutter_dimensions: GutterDimensions,
690 style: Option<EditorStyle>,
691 text_style_refinement: Option<TextStyleRefinement>,
692 next_editor_action_id: EditorActionId,
693 editor_actions:
694 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
695 use_autoclose: bool,
696 use_auto_surround: bool,
697 auto_replace_emoji_shortcode: bool,
698 show_git_blame_gutter: bool,
699 show_git_blame_inline: bool,
700 show_git_blame_inline_delay_task: Option<Task<()>>,
701 git_blame_inline_enabled: bool,
702 serialize_dirty_buffers: bool,
703 show_selection_menu: Option<bool>,
704 blame: Option<Entity<GitBlame>>,
705 blame_subscription: Option<Subscription>,
706 custom_context_menu: Option<
707 Box<
708 dyn 'static
709 + Fn(
710 &mut Self,
711 DisplayPoint,
712 &mut Window,
713 &mut Context<Self>,
714 ) -> Option<Entity<ui::ContextMenu>>,
715 >,
716 >,
717 last_bounds: Option<Bounds<Pixels>>,
718 expect_bounds_change: Option<Bounds<Pixels>>,
719 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
720 tasks_update_task: Option<Task<()>>,
721 in_project_search: bool,
722 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
723 breadcrumb_header: Option<String>,
724 focused_block: Option<FocusedBlock>,
725 next_scroll_position: NextScrollCursorCenterTopBottom,
726 addons: HashMap<TypeId, Box<dyn Addon>>,
727 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
728 selection_mark_mode: bool,
729 toggle_fold_multiple_buffers: Task<()>,
730 _scroll_cursor_center_top_bottom_task: Task<()>,
731}
732
733#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
734enum NextScrollCursorCenterTopBottom {
735 #[default]
736 Center,
737 Top,
738 Bottom,
739}
740
741impl NextScrollCursorCenterTopBottom {
742 fn next(&self) -> Self {
743 match self {
744 Self::Center => Self::Top,
745 Self::Top => Self::Bottom,
746 Self::Bottom => Self::Center,
747 }
748 }
749}
750
751#[derive(Clone)]
752pub struct EditorSnapshot {
753 pub mode: EditorMode,
754 show_gutter: bool,
755 show_line_numbers: Option<bool>,
756 show_git_diff_gutter: Option<bool>,
757 show_code_actions: Option<bool>,
758 show_runnables: Option<bool>,
759 git_blame_gutter_max_author_length: Option<usize>,
760 pub display_snapshot: DisplaySnapshot,
761 pub placeholder_text: Option<Arc<str>>,
762 is_focused: bool,
763 scroll_anchor: ScrollAnchor,
764 ongoing_scroll: OngoingScroll,
765 current_line_highlight: CurrentLineHighlight,
766 gutter_hovered: bool,
767}
768
769const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
770
771#[derive(Default, Debug, Clone, Copy)]
772pub struct GutterDimensions {
773 pub left_padding: Pixels,
774 pub right_padding: Pixels,
775 pub width: Pixels,
776 pub margin: Pixels,
777 pub git_blame_entries_width: Option<Pixels>,
778}
779
780impl GutterDimensions {
781 /// The full width of the space taken up by the gutter.
782 pub fn full_width(&self) -> Pixels {
783 self.margin + self.width
784 }
785
786 /// The width of the space reserved for the fold indicators,
787 /// use alongside 'justify_end' and `gutter_width` to
788 /// right align content with the line numbers
789 pub fn fold_area_width(&self) -> Pixels {
790 self.margin + self.right_padding
791 }
792}
793
794#[derive(Debug)]
795pub struct RemoteSelection {
796 pub replica_id: ReplicaId,
797 pub selection: Selection<Anchor>,
798 pub cursor_shape: CursorShape,
799 pub peer_id: PeerId,
800 pub line_mode: bool,
801 pub participant_index: Option<ParticipantIndex>,
802 pub user_name: Option<SharedString>,
803}
804
805#[derive(Clone, Debug)]
806struct SelectionHistoryEntry {
807 selections: Arc<[Selection<Anchor>]>,
808 select_next_state: Option<SelectNextState>,
809 select_prev_state: Option<SelectNextState>,
810 add_selections_state: Option<AddSelectionsState>,
811}
812
813enum SelectionHistoryMode {
814 Normal,
815 Undoing,
816 Redoing,
817}
818
819#[derive(Clone, PartialEq, Eq, Hash)]
820struct HoveredCursor {
821 replica_id: u16,
822 selection_id: usize,
823}
824
825impl Default for SelectionHistoryMode {
826 fn default() -> Self {
827 Self::Normal
828 }
829}
830
831#[derive(Default)]
832struct SelectionHistory {
833 #[allow(clippy::type_complexity)]
834 selections_by_transaction:
835 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
836 mode: SelectionHistoryMode,
837 undo_stack: VecDeque<SelectionHistoryEntry>,
838 redo_stack: VecDeque<SelectionHistoryEntry>,
839}
840
841impl SelectionHistory {
842 fn insert_transaction(
843 &mut self,
844 transaction_id: TransactionId,
845 selections: Arc<[Selection<Anchor>]>,
846 ) {
847 self.selections_by_transaction
848 .insert(transaction_id, (selections, None));
849 }
850
851 #[allow(clippy::type_complexity)]
852 fn transaction(
853 &self,
854 transaction_id: TransactionId,
855 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
856 self.selections_by_transaction.get(&transaction_id)
857 }
858
859 #[allow(clippy::type_complexity)]
860 fn transaction_mut(
861 &mut self,
862 transaction_id: TransactionId,
863 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
864 self.selections_by_transaction.get_mut(&transaction_id)
865 }
866
867 fn push(&mut self, entry: SelectionHistoryEntry) {
868 if !entry.selections.is_empty() {
869 match self.mode {
870 SelectionHistoryMode::Normal => {
871 self.push_undo(entry);
872 self.redo_stack.clear();
873 }
874 SelectionHistoryMode::Undoing => self.push_redo(entry),
875 SelectionHistoryMode::Redoing => self.push_undo(entry),
876 }
877 }
878 }
879
880 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
881 if self
882 .undo_stack
883 .back()
884 .map_or(true, |e| e.selections != entry.selections)
885 {
886 self.undo_stack.push_back(entry);
887 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
888 self.undo_stack.pop_front();
889 }
890 }
891 }
892
893 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
894 if self
895 .redo_stack
896 .back()
897 .map_or(true, |e| e.selections != entry.selections)
898 {
899 self.redo_stack.push_back(entry);
900 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
901 self.redo_stack.pop_front();
902 }
903 }
904 }
905}
906
907struct RowHighlight {
908 index: usize,
909 range: Range<Anchor>,
910 color: Hsla,
911 should_autoscroll: bool,
912}
913
914#[derive(Clone, Debug)]
915struct AddSelectionsState {
916 above: bool,
917 stack: Vec<usize>,
918}
919
920#[derive(Clone)]
921struct SelectNextState {
922 query: AhoCorasick,
923 wordwise: bool,
924 done: bool,
925}
926
927impl std::fmt::Debug for SelectNextState {
928 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
929 f.debug_struct(std::any::type_name::<Self>())
930 .field("wordwise", &self.wordwise)
931 .field("done", &self.done)
932 .finish()
933 }
934}
935
936#[derive(Debug)]
937struct AutocloseRegion {
938 selection_id: usize,
939 range: Range<Anchor>,
940 pair: BracketPair,
941}
942
943#[derive(Debug)]
944struct SnippetState {
945 ranges: Vec<Vec<Range<Anchor>>>,
946 active_index: usize,
947 choices: Vec<Option<Vec<String>>>,
948}
949
950#[doc(hidden)]
951pub struct RenameState {
952 pub range: Range<Anchor>,
953 pub old_name: Arc<str>,
954 pub editor: Entity<Editor>,
955 block_id: CustomBlockId,
956}
957
958struct InvalidationStack<T>(Vec<T>);
959
960struct RegisteredInlineCompletionProvider {
961 provider: Arc<dyn InlineCompletionProviderHandle>,
962 _subscription: Subscription,
963}
964
965#[derive(Debug)]
966struct ActiveDiagnosticGroup {
967 primary_range: Range<Anchor>,
968 primary_message: String,
969 group_id: usize,
970 blocks: HashMap<CustomBlockId, Diagnostic>,
971 is_valid: bool,
972}
973
974#[derive(Serialize, Deserialize, Clone, Debug)]
975pub struct ClipboardSelection {
976 pub len: usize,
977 pub is_entire_line: bool,
978 pub first_line_indent: u32,
979}
980
981#[derive(Debug)]
982pub(crate) struct NavigationData {
983 cursor_anchor: Anchor,
984 cursor_position: Point,
985 scroll_anchor: ScrollAnchor,
986 scroll_top_row: u32,
987}
988
989#[derive(Debug, Clone, Copy, PartialEq, Eq)]
990pub enum GotoDefinitionKind {
991 Symbol,
992 Declaration,
993 Type,
994 Implementation,
995}
996
997#[derive(Debug, Clone)]
998enum InlayHintRefreshReason {
999 Toggle(bool),
1000 SettingsChange(InlayHintSettings),
1001 NewLinesShown,
1002 BufferEdited(HashSet<Arc<Language>>),
1003 RefreshRequested,
1004 ExcerptsRemoved(Vec<ExcerptId>),
1005}
1006
1007impl InlayHintRefreshReason {
1008 fn description(&self) -> &'static str {
1009 match self {
1010 Self::Toggle(_) => "toggle",
1011 Self::SettingsChange(_) => "settings change",
1012 Self::NewLinesShown => "new lines shown",
1013 Self::BufferEdited(_) => "buffer edited",
1014 Self::RefreshRequested => "refresh requested",
1015 Self::ExcerptsRemoved(_) => "excerpts removed",
1016 }
1017 }
1018}
1019
1020pub enum FormatTarget {
1021 Buffers,
1022 Ranges(Vec<Range<MultiBufferPoint>>),
1023}
1024
1025pub(crate) struct FocusedBlock {
1026 id: BlockId,
1027 focus_handle: WeakFocusHandle,
1028}
1029
1030#[derive(Clone)]
1031enum JumpData {
1032 MultiBufferRow {
1033 row: MultiBufferRow,
1034 line_offset_from_top: u32,
1035 },
1036 MultiBufferPoint {
1037 excerpt_id: ExcerptId,
1038 position: Point,
1039 anchor: text::Anchor,
1040 line_offset_from_top: u32,
1041 },
1042}
1043
1044pub enum MultibufferSelectionMode {
1045 First,
1046 All,
1047}
1048
1049impl Editor {
1050 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1051 let buffer = cx.new(|cx| Buffer::local("", cx));
1052 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1053 Self::new(
1054 EditorMode::SingleLine { auto_width: false },
1055 buffer,
1056 None,
1057 false,
1058 window,
1059 cx,
1060 )
1061 }
1062
1063 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1064 let buffer = cx.new(|cx| Buffer::local("", cx));
1065 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1066 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1067 }
1068
1069 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1070 let buffer = cx.new(|cx| Buffer::local("", cx));
1071 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1072 Self::new(
1073 EditorMode::SingleLine { auto_width: true },
1074 buffer,
1075 None,
1076 false,
1077 window,
1078 cx,
1079 )
1080 }
1081
1082 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1083 let buffer = cx.new(|cx| Buffer::local("", cx));
1084 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1085 Self::new(
1086 EditorMode::AutoHeight { max_lines },
1087 buffer,
1088 None,
1089 false,
1090 window,
1091 cx,
1092 )
1093 }
1094
1095 pub fn for_buffer(
1096 buffer: Entity<Buffer>,
1097 project: Option<Entity<Project>>,
1098 window: &mut Window,
1099 cx: &mut Context<Self>,
1100 ) -> Self {
1101 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1102 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1103 }
1104
1105 pub fn for_multibuffer(
1106 buffer: Entity<MultiBuffer>,
1107 project: Option<Entity<Project>>,
1108 show_excerpt_controls: bool,
1109 window: &mut Window,
1110 cx: &mut Context<Self>,
1111 ) -> Self {
1112 Self::new(
1113 EditorMode::Full,
1114 buffer,
1115 project,
1116 show_excerpt_controls,
1117 window,
1118 cx,
1119 )
1120 }
1121
1122 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1123 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1124 let mut clone = Self::new(
1125 self.mode,
1126 self.buffer.clone(),
1127 self.project.clone(),
1128 show_excerpt_controls,
1129 window,
1130 cx,
1131 );
1132 self.display_map.update(cx, |display_map, cx| {
1133 let snapshot = display_map.snapshot(cx);
1134 clone.display_map.update(cx, |display_map, cx| {
1135 display_map.set_state(&snapshot, cx);
1136 });
1137 });
1138 clone.selections.clone_state(&self.selections);
1139 clone.scroll_manager.clone_state(&self.scroll_manager);
1140 clone.searchable = self.searchable;
1141 clone
1142 }
1143
1144 pub fn new(
1145 mode: EditorMode,
1146 buffer: Entity<MultiBuffer>,
1147 project: Option<Entity<Project>>,
1148 show_excerpt_controls: bool,
1149 window: &mut Window,
1150 cx: &mut Context<Self>,
1151 ) -> Self {
1152 let style = window.text_style();
1153 let font_size = style.font_size.to_pixels(window.rem_size());
1154 let editor = cx.entity().downgrade();
1155 let fold_placeholder = FoldPlaceholder {
1156 constrain_width: true,
1157 render: Arc::new(move |fold_id, fold_range, _, cx| {
1158 let editor = editor.clone();
1159 div()
1160 .id(fold_id)
1161 .bg(cx.theme().colors().ghost_element_background)
1162 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1163 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1164 .rounded_sm()
1165 .size_full()
1166 .cursor_pointer()
1167 .child("⋯")
1168 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1169 .on_click(move |_, _window, cx| {
1170 editor
1171 .update(cx, |editor, cx| {
1172 editor.unfold_ranges(
1173 &[fold_range.start..fold_range.end],
1174 true,
1175 false,
1176 cx,
1177 );
1178 cx.stop_propagation();
1179 })
1180 .ok();
1181 })
1182 .into_any()
1183 }),
1184 merge_adjacent: true,
1185 ..Default::default()
1186 };
1187 let display_map = cx.new(|cx| {
1188 DisplayMap::new(
1189 buffer.clone(),
1190 style.font(),
1191 font_size,
1192 None,
1193 show_excerpt_controls,
1194 FILE_HEADER_HEIGHT,
1195 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1196 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1197 fold_placeholder,
1198 cx,
1199 )
1200 });
1201
1202 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1203
1204 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1205
1206 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1207 .then(|| language_settings::SoftWrap::None);
1208
1209 let mut project_subscriptions = Vec::new();
1210 if mode == EditorMode::Full {
1211 if let Some(project) = project.as_ref() {
1212 if buffer.read(cx).is_singleton() {
1213 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1214 cx.emit(EditorEvent::TitleChanged);
1215 }));
1216 }
1217 project_subscriptions.push(cx.subscribe_in(
1218 project,
1219 window,
1220 |editor, _, event, window, cx| {
1221 if let project::Event::RefreshInlayHints = event {
1222 editor
1223 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1224 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1225 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1226 let focus_handle = editor.focus_handle(cx);
1227 if focus_handle.is_focused(window) {
1228 let snapshot = buffer.read(cx).snapshot();
1229 for (range, snippet) in snippet_edits {
1230 let editor_range =
1231 language::range_from_lsp(*range).to_offset(&snapshot);
1232 editor
1233 .insert_snippet(
1234 &[editor_range],
1235 snippet.clone(),
1236 window,
1237 cx,
1238 )
1239 .ok();
1240 }
1241 }
1242 }
1243 }
1244 },
1245 ));
1246 if let Some(task_inventory) = project
1247 .read(cx)
1248 .task_store()
1249 .read(cx)
1250 .task_inventory()
1251 .cloned()
1252 {
1253 project_subscriptions.push(cx.observe_in(
1254 &task_inventory,
1255 window,
1256 |editor, _, window, cx| {
1257 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1258 },
1259 ));
1260 }
1261 }
1262 }
1263
1264 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1265
1266 let inlay_hint_settings =
1267 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1268 let focus_handle = cx.focus_handle();
1269 cx.on_focus(&focus_handle, window, Self::handle_focus)
1270 .detach();
1271 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1272 .detach();
1273 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1274 .detach();
1275 cx.on_blur(&focus_handle, window, Self::handle_blur)
1276 .detach();
1277
1278 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1279 Some(false)
1280 } else {
1281 None
1282 };
1283
1284 let mut code_action_providers = Vec::new();
1285 if let Some(project) = project.clone() {
1286 get_unstaged_changes_for_buffers(
1287 &project,
1288 buffer.read(cx).all_buffers(),
1289 buffer.clone(),
1290 cx,
1291 );
1292 code_action_providers.push(Rc::new(project) as Rc<_>);
1293 }
1294
1295 let mut this = Self {
1296 focus_handle,
1297 show_cursor_when_unfocused: false,
1298 last_focused_descendant: None,
1299 buffer: buffer.clone(),
1300 display_map: display_map.clone(),
1301 selections,
1302 scroll_manager: ScrollManager::new(cx),
1303 columnar_selection_tail: None,
1304 add_selections_state: None,
1305 select_next_state: None,
1306 select_prev_state: None,
1307 selection_history: Default::default(),
1308 autoclose_regions: Default::default(),
1309 snippet_stack: Default::default(),
1310 select_larger_syntax_node_stack: Vec::new(),
1311 ime_transaction: Default::default(),
1312 active_diagnostics: None,
1313 soft_wrap_mode_override,
1314 completion_provider: project.clone().map(|project| Box::new(project) as _),
1315 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1316 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1317 project,
1318 blink_manager: blink_manager.clone(),
1319 show_local_selections: true,
1320 show_scrollbars: true,
1321 mode,
1322 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1323 show_gutter: mode == EditorMode::Full,
1324 show_line_numbers: None,
1325 use_relative_line_numbers: None,
1326 show_git_diff_gutter: None,
1327 show_code_actions: None,
1328 show_runnables: None,
1329 show_wrap_guides: None,
1330 show_indent_guides,
1331 placeholder_text: None,
1332 highlight_order: 0,
1333 highlighted_rows: HashMap::default(),
1334 background_highlights: Default::default(),
1335 gutter_highlights: TreeMap::default(),
1336 scrollbar_marker_state: ScrollbarMarkerState::default(),
1337 active_indent_guides_state: ActiveIndentGuidesState::default(),
1338 nav_history: None,
1339 context_menu: RefCell::new(None),
1340 mouse_context_menu: None,
1341 completion_tasks: Default::default(),
1342 signature_help_state: SignatureHelpState::default(),
1343 auto_signature_help: None,
1344 find_all_references_task_sources: Vec::new(),
1345 next_completion_id: 0,
1346 next_inlay_id: 0,
1347 code_action_providers,
1348 available_code_actions: Default::default(),
1349 code_actions_task: Default::default(),
1350 document_highlights_task: Default::default(),
1351 linked_editing_range_task: Default::default(),
1352 pending_rename: Default::default(),
1353 searchable: true,
1354 cursor_shape: EditorSettings::get_global(cx)
1355 .cursor_shape
1356 .unwrap_or_default(),
1357 current_line_highlight: None,
1358 autoindent_mode: Some(AutoindentMode::EachLine),
1359 collapse_matches: false,
1360 workspace: None,
1361 input_enabled: true,
1362 use_modal_editing: mode == EditorMode::Full,
1363 read_only: false,
1364 use_autoclose: true,
1365 use_auto_surround: true,
1366 auto_replace_emoji_shortcode: false,
1367 leader_peer_id: None,
1368 remote_id: None,
1369 hover_state: Default::default(),
1370 pending_mouse_down: None,
1371 hovered_link_state: Default::default(),
1372 inline_completion_provider: None,
1373 active_inline_completion: None,
1374 stale_inline_completion_in_menu: None,
1375 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1376
1377 gutter_hovered: false,
1378 pixel_position_of_newest_cursor: None,
1379 last_bounds: None,
1380 expect_bounds_change: None,
1381 gutter_dimensions: GutterDimensions::default(),
1382 style: None,
1383 show_cursor_names: false,
1384 hovered_cursors: Default::default(),
1385 next_editor_action_id: EditorActionId::default(),
1386 editor_actions: Rc::default(),
1387 show_inline_completions_override: None,
1388 enable_inline_completions: true,
1389 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1390 custom_context_menu: None,
1391 show_git_blame_gutter: false,
1392 show_git_blame_inline: false,
1393 show_selection_menu: None,
1394 show_git_blame_inline_delay_task: None,
1395 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1396 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1397 .session
1398 .restore_unsaved_buffers,
1399 blame: None,
1400 blame_subscription: None,
1401 tasks: Default::default(),
1402 _subscriptions: vec![
1403 cx.observe(&buffer, Self::on_buffer_changed),
1404 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1405 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1406 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1407 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1408 cx.observe_window_activation(window, |editor, window, cx| {
1409 let active = window.is_window_active();
1410 editor.blink_manager.update(cx, |blink_manager, cx| {
1411 if active {
1412 blink_manager.enable(cx);
1413 } else {
1414 blink_manager.disable(cx);
1415 }
1416 });
1417 }),
1418 ],
1419 tasks_update_task: None,
1420 linked_edit_ranges: Default::default(),
1421 in_project_search: false,
1422 previous_search_ranges: None,
1423 breadcrumb_header: None,
1424 focused_block: None,
1425 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1426 addons: HashMap::default(),
1427 registered_buffers: HashMap::default(),
1428 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1429 selection_mark_mode: false,
1430 toggle_fold_multiple_buffers: Task::ready(()),
1431 text_style_refinement: None,
1432 };
1433 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1434 this._subscriptions.extend(project_subscriptions);
1435
1436 this.end_selection(window, cx);
1437 this.scroll_manager.show_scrollbar(window, cx);
1438
1439 if mode == EditorMode::Full {
1440 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1441 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1442
1443 if this.git_blame_inline_enabled {
1444 this.git_blame_inline_enabled = true;
1445 this.start_git_blame_inline(false, window, cx);
1446 }
1447
1448 if let Some(buffer) = buffer.read(cx).as_singleton() {
1449 if let Some(project) = this.project.as_ref() {
1450 let lsp_store = project.read(cx).lsp_store();
1451 let handle = lsp_store.update(cx, |lsp_store, cx| {
1452 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1453 });
1454 this.registered_buffers
1455 .insert(buffer.read(cx).remote_id(), handle);
1456 }
1457 }
1458 }
1459
1460 this.report_editor_event("Editor Opened", None, cx);
1461 this
1462 }
1463
1464 pub fn mouse_menu_is_focused(&self, window: &mut Window, cx: &mut App) -> bool {
1465 self.mouse_context_menu
1466 .as_ref()
1467 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1468 }
1469
1470 fn key_context(&self, window: &mut Window, cx: &mut Context<Self>) -> KeyContext {
1471 let mut key_context = KeyContext::new_with_defaults();
1472 key_context.add("Editor");
1473 let mode = match self.mode {
1474 EditorMode::SingleLine { .. } => "single_line",
1475 EditorMode::AutoHeight { .. } => "auto_height",
1476 EditorMode::Full => "full",
1477 };
1478
1479 if EditorSettings::jupyter_enabled(cx) {
1480 key_context.add("jupyter");
1481 }
1482
1483 key_context.set("mode", mode);
1484 if self.pending_rename.is_some() {
1485 key_context.add("renaming");
1486 }
1487 match self.context_menu.borrow().as_ref() {
1488 Some(CodeContextMenu::Completions(_)) => {
1489 key_context.add("menu");
1490 key_context.add("showing_completions");
1491 }
1492 Some(CodeContextMenu::CodeActions(_)) => {
1493 key_context.add("menu");
1494 key_context.add("showing_code_actions")
1495 }
1496 None => {}
1497 }
1498
1499 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1500 if !self.focus_handle(cx).contains_focused(window, cx)
1501 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1502 {
1503 for addon in self.addons.values() {
1504 addon.extend_key_context(&mut key_context, cx)
1505 }
1506 }
1507
1508 if let Some(extension) = self
1509 .buffer
1510 .read(cx)
1511 .as_singleton()
1512 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1513 {
1514 key_context.set("extension", extension.to_string());
1515 }
1516
1517 if self.has_active_inline_completion() {
1518 key_context.add("copilot_suggestion");
1519 key_context.add("inline_completion");
1520 }
1521
1522 if self.selection_mark_mode {
1523 key_context.add("selection_mode");
1524 }
1525
1526 key_context
1527 }
1528
1529 pub fn new_file(
1530 workspace: &mut Workspace,
1531 _: &workspace::NewFile,
1532 window: &mut Window,
1533 cx: &mut Context<Workspace>,
1534 ) {
1535 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1536 "Failed to create buffer",
1537 window,
1538 cx,
1539 |e, _, _| match e.error_code() {
1540 ErrorCode::RemoteUpgradeRequired => Some(format!(
1541 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1542 e.error_tag("required").unwrap_or("the latest version")
1543 )),
1544 _ => None,
1545 },
1546 );
1547 }
1548
1549 pub fn new_in_workspace(
1550 workspace: &mut Workspace,
1551 window: &mut Window,
1552 cx: &mut Context<Workspace>,
1553 ) -> Task<Result<Entity<Editor>>> {
1554 let project = workspace.project().clone();
1555 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1556
1557 cx.spawn_in(window, |workspace, mut cx| async move {
1558 let buffer = create.await?;
1559 workspace.update_in(&mut cx, |workspace, window, cx| {
1560 let editor =
1561 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1562 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1563 editor
1564 })
1565 })
1566 }
1567
1568 fn new_file_vertical(
1569 workspace: &mut Workspace,
1570 _: &workspace::NewFileSplitVertical,
1571 window: &mut Window,
1572 cx: &mut Context<Workspace>,
1573 ) {
1574 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1575 }
1576
1577 fn new_file_horizontal(
1578 workspace: &mut Workspace,
1579 _: &workspace::NewFileSplitHorizontal,
1580 window: &mut Window,
1581 cx: &mut Context<Workspace>,
1582 ) {
1583 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1584 }
1585
1586 fn new_file_in_direction(
1587 workspace: &mut Workspace,
1588 direction: SplitDirection,
1589 window: &mut Window,
1590 cx: &mut Context<Workspace>,
1591 ) {
1592 let project = workspace.project().clone();
1593 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1594
1595 cx.spawn_in(window, |workspace, mut cx| async move {
1596 let buffer = create.await?;
1597 workspace.update_in(&mut cx, move |workspace, window, cx| {
1598 workspace.split_item(
1599 direction,
1600 Box::new(
1601 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1602 ),
1603 window,
1604 cx,
1605 )
1606 })?;
1607 anyhow::Ok(())
1608 })
1609 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1610 match e.error_code() {
1611 ErrorCode::RemoteUpgradeRequired => Some(format!(
1612 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1613 e.error_tag("required").unwrap_or("the latest version")
1614 )),
1615 _ => None,
1616 }
1617 });
1618 }
1619
1620 pub fn leader_peer_id(&self) -> Option<PeerId> {
1621 self.leader_peer_id
1622 }
1623
1624 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1625 &self.buffer
1626 }
1627
1628 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1629 self.workspace.as_ref()?.0.upgrade()
1630 }
1631
1632 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1633 self.buffer().read(cx).title(cx)
1634 }
1635
1636 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1637 let git_blame_gutter_max_author_length = self
1638 .render_git_blame_gutter(cx)
1639 .then(|| {
1640 if let Some(blame) = self.blame.as_ref() {
1641 let max_author_length =
1642 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1643 Some(max_author_length)
1644 } else {
1645 None
1646 }
1647 })
1648 .flatten();
1649
1650 EditorSnapshot {
1651 mode: self.mode,
1652 show_gutter: self.show_gutter,
1653 show_line_numbers: self.show_line_numbers,
1654 show_git_diff_gutter: self.show_git_diff_gutter,
1655 show_code_actions: self.show_code_actions,
1656 show_runnables: self.show_runnables,
1657 git_blame_gutter_max_author_length,
1658 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1659 scroll_anchor: self.scroll_manager.anchor(),
1660 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1661 placeholder_text: self.placeholder_text.clone(),
1662 is_focused: self.focus_handle.is_focused(window),
1663 current_line_highlight: self
1664 .current_line_highlight
1665 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1666 gutter_hovered: self.gutter_hovered,
1667 }
1668 }
1669
1670 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1671 self.buffer.read(cx).language_at(point, cx)
1672 }
1673
1674 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1675 self.buffer.read(cx).read(cx).file_at(point).cloned()
1676 }
1677
1678 pub fn active_excerpt(
1679 &self,
1680 cx: &App,
1681 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1682 self.buffer
1683 .read(cx)
1684 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1685 }
1686
1687 pub fn mode(&self) -> EditorMode {
1688 self.mode
1689 }
1690
1691 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1692 self.collaboration_hub.as_deref()
1693 }
1694
1695 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1696 self.collaboration_hub = Some(hub);
1697 }
1698
1699 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1700 self.in_project_search = in_project_search;
1701 }
1702
1703 pub fn set_custom_context_menu(
1704 &mut self,
1705 f: impl 'static
1706 + Fn(
1707 &mut Self,
1708 DisplayPoint,
1709 &mut Window,
1710 &mut Context<Self>,
1711 ) -> Option<Entity<ui::ContextMenu>>,
1712 ) {
1713 self.custom_context_menu = Some(Box::new(f))
1714 }
1715
1716 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1717 self.completion_provider = provider;
1718 }
1719
1720 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1721 self.semantics_provider.clone()
1722 }
1723
1724 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1725 self.semantics_provider = provider;
1726 }
1727
1728 pub fn set_inline_completion_provider<T>(
1729 &mut self,
1730 provider: Option<Entity<T>>,
1731 window: &mut Window,
1732 cx: &mut Context<Self>,
1733 ) where
1734 T: InlineCompletionProvider,
1735 {
1736 self.inline_completion_provider =
1737 provider.map(|provider| RegisteredInlineCompletionProvider {
1738 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1739 if this.focus_handle.is_focused(window) {
1740 this.update_visible_inline_completion(window, cx);
1741 }
1742 }),
1743 provider: Arc::new(provider),
1744 });
1745 self.refresh_inline_completion(false, false, window, cx);
1746 }
1747
1748 pub fn placeholder_text(&self) -> Option<&str> {
1749 self.placeholder_text.as_deref()
1750 }
1751
1752 pub fn set_placeholder_text(
1753 &mut self,
1754 placeholder_text: impl Into<Arc<str>>,
1755 cx: &mut Context<Self>,
1756 ) {
1757 let placeholder_text = Some(placeholder_text.into());
1758 if self.placeholder_text != placeholder_text {
1759 self.placeholder_text = placeholder_text;
1760 cx.notify();
1761 }
1762 }
1763
1764 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1765 self.cursor_shape = cursor_shape;
1766
1767 // Disrupt blink for immediate user feedback that the cursor shape has changed
1768 self.blink_manager.update(cx, BlinkManager::show_cursor);
1769
1770 cx.notify();
1771 }
1772
1773 pub fn set_current_line_highlight(
1774 &mut self,
1775 current_line_highlight: Option<CurrentLineHighlight>,
1776 ) {
1777 self.current_line_highlight = current_line_highlight;
1778 }
1779
1780 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1781 self.collapse_matches = collapse_matches;
1782 }
1783
1784 pub fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1785 let buffers = self.buffer.read(cx).all_buffers();
1786 let Some(lsp_store) = self.lsp_store(cx) else {
1787 return;
1788 };
1789 lsp_store.update(cx, |lsp_store, cx| {
1790 for buffer in buffers {
1791 self.registered_buffers
1792 .entry(buffer.read(cx).remote_id())
1793 .or_insert_with(|| {
1794 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1795 });
1796 }
1797 })
1798 }
1799
1800 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1801 if self.collapse_matches {
1802 return range.start..range.start;
1803 }
1804 range.clone()
1805 }
1806
1807 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1808 if self.display_map.read(cx).clip_at_line_ends != clip {
1809 self.display_map
1810 .update(cx, |map, _| map.clip_at_line_ends = clip);
1811 }
1812 }
1813
1814 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1815 self.input_enabled = input_enabled;
1816 }
1817
1818 pub fn set_inline_completions_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
1819 self.enable_inline_completions = enabled;
1820 if !self.enable_inline_completions {
1821 self.take_active_inline_completion(cx);
1822 cx.notify();
1823 }
1824 }
1825
1826 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1827 self.menu_inline_completions_policy = value;
1828 }
1829
1830 pub fn set_autoindent(&mut self, autoindent: bool) {
1831 if autoindent {
1832 self.autoindent_mode = Some(AutoindentMode::EachLine);
1833 } else {
1834 self.autoindent_mode = None;
1835 }
1836 }
1837
1838 pub fn read_only(&self, cx: &App) -> bool {
1839 self.read_only || self.buffer.read(cx).read_only()
1840 }
1841
1842 pub fn set_read_only(&mut self, read_only: bool) {
1843 self.read_only = read_only;
1844 }
1845
1846 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1847 self.use_autoclose = autoclose;
1848 }
1849
1850 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1851 self.use_auto_surround = auto_surround;
1852 }
1853
1854 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1855 self.auto_replace_emoji_shortcode = auto_replace;
1856 }
1857
1858 pub fn toggle_inline_completions(
1859 &mut self,
1860 _: &ToggleInlineCompletions,
1861 window: &mut Window,
1862 cx: &mut Context<Self>,
1863 ) {
1864 if self.show_inline_completions_override.is_some() {
1865 self.set_show_inline_completions(None, window, cx);
1866 } else {
1867 let cursor = self.selections.newest_anchor().head();
1868 if let Some((buffer, cursor_buffer_position)) =
1869 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1870 {
1871 let show_inline_completions =
1872 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
1873 self.set_show_inline_completions(Some(show_inline_completions), window, cx);
1874 }
1875 }
1876 }
1877
1878 pub fn set_show_inline_completions(
1879 &mut self,
1880 show_inline_completions: Option<bool>,
1881 window: &mut Window,
1882 cx: &mut Context<Self>,
1883 ) {
1884 self.show_inline_completions_override = show_inline_completions;
1885 self.refresh_inline_completion(false, true, window, cx);
1886 }
1887
1888 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
1889 let cursor = self.selections.newest_anchor().head();
1890 if let Some((buffer, buffer_position)) =
1891 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1892 {
1893 self.should_show_inline_completions(&buffer, buffer_position, cx)
1894 } else {
1895 false
1896 }
1897 }
1898
1899 fn should_show_inline_completions(
1900 &self,
1901 buffer: &Entity<Buffer>,
1902 buffer_position: language::Anchor,
1903 cx: &App,
1904 ) -> bool {
1905 if !self.snippet_stack.is_empty() {
1906 return false;
1907 }
1908
1909 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
1910 return false;
1911 }
1912
1913 if let Some(provider) = self.inline_completion_provider() {
1914 if let Some(show_inline_completions) = self.show_inline_completions_override {
1915 show_inline_completions
1916 } else {
1917 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
1918 }
1919 } else {
1920 false
1921 }
1922 }
1923
1924 fn inline_completions_disabled_in_scope(
1925 &self,
1926 buffer: &Entity<Buffer>,
1927 buffer_position: language::Anchor,
1928 cx: &App,
1929 ) -> bool {
1930 let snapshot = buffer.read(cx).snapshot();
1931 let settings = snapshot.settings_at(buffer_position, cx);
1932
1933 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1934 return false;
1935 };
1936
1937 scope.override_name().map_or(false, |scope_name| {
1938 settings
1939 .inline_completions_disabled_in
1940 .iter()
1941 .any(|s| s == scope_name)
1942 })
1943 }
1944
1945 pub fn set_use_modal_editing(&mut self, to: bool) {
1946 self.use_modal_editing = to;
1947 }
1948
1949 pub fn use_modal_editing(&self) -> bool {
1950 self.use_modal_editing
1951 }
1952
1953 fn selections_did_change(
1954 &mut self,
1955 local: bool,
1956 old_cursor_position: &Anchor,
1957 show_completions: bool,
1958 window: &mut Window,
1959 cx: &mut Context<Self>,
1960 ) {
1961 window.invalidate_character_coordinates();
1962
1963 // Copy selections to primary selection buffer
1964 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1965 if local {
1966 let selections = self.selections.all::<usize>(cx);
1967 let buffer_handle = self.buffer.read(cx).read(cx);
1968
1969 let mut text = String::new();
1970 for (index, selection) in selections.iter().enumerate() {
1971 let text_for_selection = buffer_handle
1972 .text_for_range(selection.start..selection.end)
1973 .collect::<String>();
1974
1975 text.push_str(&text_for_selection);
1976 if index != selections.len() - 1 {
1977 text.push('\n');
1978 }
1979 }
1980
1981 if !text.is_empty() {
1982 cx.write_to_primary(ClipboardItem::new_string(text));
1983 }
1984 }
1985
1986 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
1987 self.buffer.update(cx, |buffer, cx| {
1988 buffer.set_active_selections(
1989 &self.selections.disjoint_anchors(),
1990 self.selections.line_mode,
1991 self.cursor_shape,
1992 cx,
1993 )
1994 });
1995 }
1996 let display_map = self
1997 .display_map
1998 .update(cx, |display_map, cx| display_map.snapshot(cx));
1999 let buffer = &display_map.buffer_snapshot;
2000 self.add_selections_state = None;
2001 self.select_next_state = None;
2002 self.select_prev_state = None;
2003 self.select_larger_syntax_node_stack.clear();
2004 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2005 self.snippet_stack
2006 .invalidate(&self.selections.disjoint_anchors(), buffer);
2007 self.take_rename(false, window, cx);
2008
2009 let new_cursor_position = self.selections.newest_anchor().head();
2010
2011 self.push_to_nav_history(
2012 *old_cursor_position,
2013 Some(new_cursor_position.to_point(buffer)),
2014 cx,
2015 );
2016
2017 if local {
2018 let new_cursor_position = self.selections.newest_anchor().head();
2019 let mut context_menu = self.context_menu.borrow_mut();
2020 let completion_menu = match context_menu.as_ref() {
2021 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2022 _ => {
2023 *context_menu = None;
2024 None
2025 }
2026 };
2027
2028 if let Some(completion_menu) = completion_menu {
2029 let cursor_position = new_cursor_position.to_offset(buffer);
2030 let (word_range, kind) =
2031 buffer.surrounding_word(completion_menu.initial_position, true);
2032 if kind == Some(CharKind::Word)
2033 && word_range.to_inclusive().contains(&cursor_position)
2034 {
2035 let mut completion_menu = completion_menu.clone();
2036 drop(context_menu);
2037
2038 let query = Self::completion_query(buffer, cursor_position);
2039 cx.spawn(move |this, mut cx| async move {
2040 completion_menu
2041 .filter(query.as_deref(), cx.background_executor().clone())
2042 .await;
2043
2044 this.update(&mut cx, |this, cx| {
2045 let mut context_menu = this.context_menu.borrow_mut();
2046 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2047 else {
2048 return;
2049 };
2050
2051 if menu.id > completion_menu.id {
2052 return;
2053 }
2054
2055 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2056 drop(context_menu);
2057 cx.notify();
2058 })
2059 })
2060 .detach();
2061
2062 if show_completions {
2063 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2064 }
2065 } else {
2066 drop(context_menu);
2067 self.hide_context_menu(window, cx);
2068 }
2069 } else {
2070 drop(context_menu);
2071 }
2072
2073 hide_hover(self, cx);
2074
2075 if old_cursor_position.to_display_point(&display_map).row()
2076 != new_cursor_position.to_display_point(&display_map).row()
2077 {
2078 self.available_code_actions.take();
2079 }
2080 self.refresh_code_actions(window, cx);
2081 self.refresh_document_highlights(cx);
2082 refresh_matching_bracket_highlights(self, window, cx);
2083 self.update_visible_inline_completion(window, cx);
2084 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2085 if self.git_blame_inline_enabled {
2086 self.start_inline_blame_timer(window, cx);
2087 }
2088 }
2089
2090 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2091 cx.emit(EditorEvent::SelectionsChanged { local });
2092
2093 if self.selections.disjoint_anchors().len() == 1 {
2094 cx.emit(SearchEvent::ActiveMatchChanged)
2095 }
2096 cx.notify();
2097 }
2098
2099 pub fn change_selections<R>(
2100 &mut self,
2101 autoscroll: Option<Autoscroll>,
2102 window: &mut Window,
2103 cx: &mut Context<Self>,
2104 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2105 ) -> R {
2106 self.change_selections_inner(autoscroll, true, window, cx, change)
2107 }
2108
2109 pub fn change_selections_inner<R>(
2110 &mut self,
2111 autoscroll: Option<Autoscroll>,
2112 request_completions: bool,
2113 window: &mut Window,
2114 cx: &mut Context<Self>,
2115 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2116 ) -> R {
2117 let old_cursor_position = self.selections.newest_anchor().head();
2118 self.push_to_selection_history();
2119
2120 let (changed, result) = self.selections.change_with(cx, change);
2121
2122 if changed {
2123 if let Some(autoscroll) = autoscroll {
2124 self.request_autoscroll(autoscroll, cx);
2125 }
2126 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2127
2128 if self.should_open_signature_help_automatically(
2129 &old_cursor_position,
2130 self.signature_help_state.backspace_pressed(),
2131 cx,
2132 ) {
2133 self.show_signature_help(&ShowSignatureHelp, window, cx);
2134 }
2135 self.signature_help_state.set_backspace_pressed(false);
2136 }
2137
2138 result
2139 }
2140
2141 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2142 where
2143 I: IntoIterator<Item = (Range<S>, T)>,
2144 S: ToOffset,
2145 T: Into<Arc<str>>,
2146 {
2147 if self.read_only(cx) {
2148 return;
2149 }
2150
2151 self.buffer
2152 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2153 }
2154
2155 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2156 where
2157 I: IntoIterator<Item = (Range<S>, T)>,
2158 S: ToOffset,
2159 T: Into<Arc<str>>,
2160 {
2161 if self.read_only(cx) {
2162 return;
2163 }
2164
2165 self.buffer.update(cx, |buffer, cx| {
2166 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2167 });
2168 }
2169
2170 pub fn edit_with_block_indent<I, S, T>(
2171 &mut self,
2172 edits: I,
2173 original_indent_columns: Vec<u32>,
2174 cx: &mut Context<Self>,
2175 ) where
2176 I: IntoIterator<Item = (Range<S>, T)>,
2177 S: ToOffset,
2178 T: Into<Arc<str>>,
2179 {
2180 if self.read_only(cx) {
2181 return;
2182 }
2183
2184 self.buffer.update(cx, |buffer, cx| {
2185 buffer.edit(
2186 edits,
2187 Some(AutoindentMode::Block {
2188 original_indent_columns,
2189 }),
2190 cx,
2191 )
2192 });
2193 }
2194
2195 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2196 self.hide_context_menu(window, cx);
2197
2198 match phase {
2199 SelectPhase::Begin {
2200 position,
2201 add,
2202 click_count,
2203 } => self.begin_selection(position, add, click_count, window, cx),
2204 SelectPhase::BeginColumnar {
2205 position,
2206 goal_column,
2207 reset,
2208 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2209 SelectPhase::Extend {
2210 position,
2211 click_count,
2212 } => self.extend_selection(position, click_count, window, cx),
2213 SelectPhase::Update {
2214 position,
2215 goal_column,
2216 scroll_delta,
2217 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2218 SelectPhase::End => self.end_selection(window, cx),
2219 }
2220 }
2221
2222 fn extend_selection(
2223 &mut self,
2224 position: DisplayPoint,
2225 click_count: usize,
2226 window: &mut Window,
2227 cx: &mut Context<Self>,
2228 ) {
2229 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2230 let tail = self.selections.newest::<usize>(cx).tail();
2231 self.begin_selection(position, false, click_count, window, cx);
2232
2233 let position = position.to_offset(&display_map, Bias::Left);
2234 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2235
2236 let mut pending_selection = self
2237 .selections
2238 .pending_anchor()
2239 .expect("extend_selection not called with pending selection");
2240 if position >= tail {
2241 pending_selection.start = tail_anchor;
2242 } else {
2243 pending_selection.end = tail_anchor;
2244 pending_selection.reversed = true;
2245 }
2246
2247 let mut pending_mode = self.selections.pending_mode().unwrap();
2248 match &mut pending_mode {
2249 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2250 _ => {}
2251 }
2252
2253 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2254 s.set_pending(pending_selection, pending_mode)
2255 });
2256 }
2257
2258 fn begin_selection(
2259 &mut self,
2260 position: DisplayPoint,
2261 add: bool,
2262 click_count: usize,
2263 window: &mut Window,
2264 cx: &mut Context<Self>,
2265 ) {
2266 if !self.focus_handle.is_focused(window) {
2267 self.last_focused_descendant = None;
2268 window.focus(&self.focus_handle);
2269 }
2270
2271 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2272 let buffer = &display_map.buffer_snapshot;
2273 let newest_selection = self.selections.newest_anchor().clone();
2274 let position = display_map.clip_point(position, Bias::Left);
2275
2276 let start;
2277 let end;
2278 let mode;
2279 let mut auto_scroll;
2280 match click_count {
2281 1 => {
2282 start = buffer.anchor_before(position.to_point(&display_map));
2283 end = start;
2284 mode = SelectMode::Character;
2285 auto_scroll = true;
2286 }
2287 2 => {
2288 let range = movement::surrounding_word(&display_map, position);
2289 start = buffer.anchor_before(range.start.to_point(&display_map));
2290 end = buffer.anchor_before(range.end.to_point(&display_map));
2291 mode = SelectMode::Word(start..end);
2292 auto_scroll = true;
2293 }
2294 3 => {
2295 let position = display_map
2296 .clip_point(position, Bias::Left)
2297 .to_point(&display_map);
2298 let line_start = display_map.prev_line_boundary(position).0;
2299 let next_line_start = buffer.clip_point(
2300 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2301 Bias::Left,
2302 );
2303 start = buffer.anchor_before(line_start);
2304 end = buffer.anchor_before(next_line_start);
2305 mode = SelectMode::Line(start..end);
2306 auto_scroll = true;
2307 }
2308 _ => {
2309 start = buffer.anchor_before(0);
2310 end = buffer.anchor_before(buffer.len());
2311 mode = SelectMode::All;
2312 auto_scroll = false;
2313 }
2314 }
2315 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2316
2317 let point_to_delete: Option<usize> = {
2318 let selected_points: Vec<Selection<Point>> =
2319 self.selections.disjoint_in_range(start..end, cx);
2320
2321 if !add || click_count > 1 {
2322 None
2323 } else if !selected_points.is_empty() {
2324 Some(selected_points[0].id)
2325 } else {
2326 let clicked_point_already_selected =
2327 self.selections.disjoint.iter().find(|selection| {
2328 selection.start.to_point(buffer) == start.to_point(buffer)
2329 || selection.end.to_point(buffer) == end.to_point(buffer)
2330 });
2331
2332 clicked_point_already_selected.map(|selection| selection.id)
2333 }
2334 };
2335
2336 let selections_count = self.selections.count();
2337
2338 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2339 if let Some(point_to_delete) = point_to_delete {
2340 s.delete(point_to_delete);
2341
2342 if selections_count == 1 {
2343 s.set_pending_anchor_range(start..end, mode);
2344 }
2345 } else {
2346 if !add {
2347 s.clear_disjoint();
2348 } else if click_count > 1 {
2349 s.delete(newest_selection.id)
2350 }
2351
2352 s.set_pending_anchor_range(start..end, mode);
2353 }
2354 });
2355 }
2356
2357 fn begin_columnar_selection(
2358 &mut self,
2359 position: DisplayPoint,
2360 goal_column: u32,
2361 reset: bool,
2362 window: &mut Window,
2363 cx: &mut Context<Self>,
2364 ) {
2365 if !self.focus_handle.is_focused(window) {
2366 self.last_focused_descendant = None;
2367 window.focus(&self.focus_handle);
2368 }
2369
2370 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2371
2372 if reset {
2373 let pointer_position = display_map
2374 .buffer_snapshot
2375 .anchor_before(position.to_point(&display_map));
2376
2377 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2378 s.clear_disjoint();
2379 s.set_pending_anchor_range(
2380 pointer_position..pointer_position,
2381 SelectMode::Character,
2382 );
2383 });
2384 }
2385
2386 let tail = self.selections.newest::<Point>(cx).tail();
2387 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2388
2389 if !reset {
2390 self.select_columns(
2391 tail.to_display_point(&display_map),
2392 position,
2393 goal_column,
2394 &display_map,
2395 window,
2396 cx,
2397 );
2398 }
2399 }
2400
2401 fn update_selection(
2402 &mut self,
2403 position: DisplayPoint,
2404 goal_column: u32,
2405 scroll_delta: gpui::Point<f32>,
2406 window: &mut Window,
2407 cx: &mut Context<Self>,
2408 ) {
2409 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2410
2411 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2412 let tail = tail.to_display_point(&display_map);
2413 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2414 } else if let Some(mut pending) = self.selections.pending_anchor() {
2415 let buffer = self.buffer.read(cx).snapshot(cx);
2416 let head;
2417 let tail;
2418 let mode = self.selections.pending_mode().unwrap();
2419 match &mode {
2420 SelectMode::Character => {
2421 head = position.to_point(&display_map);
2422 tail = pending.tail().to_point(&buffer);
2423 }
2424 SelectMode::Word(original_range) => {
2425 let original_display_range = original_range.start.to_display_point(&display_map)
2426 ..original_range.end.to_display_point(&display_map);
2427 let original_buffer_range = original_display_range.start.to_point(&display_map)
2428 ..original_display_range.end.to_point(&display_map);
2429 if movement::is_inside_word(&display_map, position)
2430 || original_display_range.contains(&position)
2431 {
2432 let word_range = movement::surrounding_word(&display_map, position);
2433 if word_range.start < original_display_range.start {
2434 head = word_range.start.to_point(&display_map);
2435 } else {
2436 head = word_range.end.to_point(&display_map);
2437 }
2438 } else {
2439 head = position.to_point(&display_map);
2440 }
2441
2442 if head <= original_buffer_range.start {
2443 tail = original_buffer_range.end;
2444 } else {
2445 tail = original_buffer_range.start;
2446 }
2447 }
2448 SelectMode::Line(original_range) => {
2449 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2450
2451 let position = display_map
2452 .clip_point(position, Bias::Left)
2453 .to_point(&display_map);
2454 let line_start = display_map.prev_line_boundary(position).0;
2455 let next_line_start = buffer.clip_point(
2456 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2457 Bias::Left,
2458 );
2459
2460 if line_start < original_range.start {
2461 head = line_start
2462 } else {
2463 head = next_line_start
2464 }
2465
2466 if head <= original_range.start {
2467 tail = original_range.end;
2468 } else {
2469 tail = original_range.start;
2470 }
2471 }
2472 SelectMode::All => {
2473 return;
2474 }
2475 };
2476
2477 if head < tail {
2478 pending.start = buffer.anchor_before(head);
2479 pending.end = buffer.anchor_before(tail);
2480 pending.reversed = true;
2481 } else {
2482 pending.start = buffer.anchor_before(tail);
2483 pending.end = buffer.anchor_before(head);
2484 pending.reversed = false;
2485 }
2486
2487 self.change_selections(None, window, cx, |s| {
2488 s.set_pending(pending, mode);
2489 });
2490 } else {
2491 log::error!("update_selection dispatched with no pending selection");
2492 return;
2493 }
2494
2495 self.apply_scroll_delta(scroll_delta, window, cx);
2496 cx.notify();
2497 }
2498
2499 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2500 self.columnar_selection_tail.take();
2501 if self.selections.pending_anchor().is_some() {
2502 let selections = self.selections.all::<usize>(cx);
2503 self.change_selections(None, window, cx, |s| {
2504 s.select(selections);
2505 s.clear_pending();
2506 });
2507 }
2508 }
2509
2510 fn select_columns(
2511 &mut self,
2512 tail: DisplayPoint,
2513 head: DisplayPoint,
2514 goal_column: u32,
2515 display_map: &DisplaySnapshot,
2516 window: &mut Window,
2517 cx: &mut Context<Self>,
2518 ) {
2519 let start_row = cmp::min(tail.row(), head.row());
2520 let end_row = cmp::max(tail.row(), head.row());
2521 let start_column = cmp::min(tail.column(), goal_column);
2522 let end_column = cmp::max(tail.column(), goal_column);
2523 let reversed = start_column < tail.column();
2524
2525 let selection_ranges = (start_row.0..=end_row.0)
2526 .map(DisplayRow)
2527 .filter_map(|row| {
2528 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2529 let start = display_map
2530 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2531 .to_point(display_map);
2532 let end = display_map
2533 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2534 .to_point(display_map);
2535 if reversed {
2536 Some(end..start)
2537 } else {
2538 Some(start..end)
2539 }
2540 } else {
2541 None
2542 }
2543 })
2544 .collect::<Vec<_>>();
2545
2546 self.change_selections(None, window, cx, |s| {
2547 s.select_ranges(selection_ranges);
2548 });
2549 cx.notify();
2550 }
2551
2552 pub fn has_pending_nonempty_selection(&self) -> bool {
2553 let pending_nonempty_selection = match self.selections.pending_anchor() {
2554 Some(Selection { start, end, .. }) => start != end,
2555 None => false,
2556 };
2557
2558 pending_nonempty_selection
2559 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2560 }
2561
2562 pub fn has_pending_selection(&self) -> bool {
2563 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2564 }
2565
2566 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2567 self.selection_mark_mode = false;
2568
2569 if self.clear_expanded_diff_hunks(cx) {
2570 cx.notify();
2571 return;
2572 }
2573 if self.dismiss_menus_and_popups(true, window, cx) {
2574 return;
2575 }
2576
2577 if self.mode == EditorMode::Full
2578 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2579 {
2580 return;
2581 }
2582
2583 cx.propagate();
2584 }
2585
2586 pub fn dismiss_menus_and_popups(
2587 &mut self,
2588 should_report_inline_completion_event: bool,
2589 window: &mut Window,
2590 cx: &mut Context<Self>,
2591 ) -> bool {
2592 if self.take_rename(false, window, cx).is_some() {
2593 return true;
2594 }
2595
2596 if hide_hover(self, cx) {
2597 return true;
2598 }
2599
2600 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2601 return true;
2602 }
2603
2604 if self.hide_context_menu(window, cx).is_some() {
2605 return true;
2606 }
2607
2608 if self.mouse_context_menu.take().is_some() {
2609 return true;
2610 }
2611
2612 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2613 return true;
2614 }
2615
2616 if self.snippet_stack.pop().is_some() {
2617 return true;
2618 }
2619
2620 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2621 self.dismiss_diagnostics(cx);
2622 return true;
2623 }
2624
2625 false
2626 }
2627
2628 fn linked_editing_ranges_for(
2629 &self,
2630 selection: Range<text::Anchor>,
2631 cx: &App,
2632 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2633 if self.linked_edit_ranges.is_empty() {
2634 return None;
2635 }
2636 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2637 selection.end.buffer_id.and_then(|end_buffer_id| {
2638 if selection.start.buffer_id != Some(end_buffer_id) {
2639 return None;
2640 }
2641 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2642 let snapshot = buffer.read(cx).snapshot();
2643 self.linked_edit_ranges
2644 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2645 .map(|ranges| (ranges, snapshot, buffer))
2646 })?;
2647 use text::ToOffset as TO;
2648 // find offset from the start of current range to current cursor position
2649 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2650
2651 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2652 let start_difference = start_offset - start_byte_offset;
2653 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2654 let end_difference = end_offset - start_byte_offset;
2655 // Current range has associated linked ranges.
2656 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2657 for range in linked_ranges.iter() {
2658 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2659 let end_offset = start_offset + end_difference;
2660 let start_offset = start_offset + start_difference;
2661 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2662 continue;
2663 }
2664 if self.selections.disjoint_anchor_ranges().any(|s| {
2665 if s.start.buffer_id != selection.start.buffer_id
2666 || s.end.buffer_id != selection.end.buffer_id
2667 {
2668 return false;
2669 }
2670 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2671 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2672 }) {
2673 continue;
2674 }
2675 let start = buffer_snapshot.anchor_after(start_offset);
2676 let end = buffer_snapshot.anchor_after(end_offset);
2677 linked_edits
2678 .entry(buffer.clone())
2679 .or_default()
2680 .push(start..end);
2681 }
2682 Some(linked_edits)
2683 }
2684
2685 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2686 let text: Arc<str> = text.into();
2687
2688 if self.read_only(cx) {
2689 return;
2690 }
2691
2692 let selections = self.selections.all_adjusted(cx);
2693 let mut bracket_inserted = false;
2694 let mut edits = Vec::new();
2695 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2696 let mut new_selections = Vec::with_capacity(selections.len());
2697 let mut new_autoclose_regions = Vec::new();
2698 let snapshot = self.buffer.read(cx).read(cx);
2699
2700 for (selection, autoclose_region) in
2701 self.selections_with_autoclose_regions(selections, &snapshot)
2702 {
2703 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2704 // Determine if the inserted text matches the opening or closing
2705 // bracket of any of this language's bracket pairs.
2706 let mut bracket_pair = None;
2707 let mut is_bracket_pair_start = false;
2708 let mut is_bracket_pair_end = false;
2709 if !text.is_empty() {
2710 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2711 // and they are removing the character that triggered IME popup.
2712 for (pair, enabled) in scope.brackets() {
2713 if !pair.close && !pair.surround {
2714 continue;
2715 }
2716
2717 if enabled && pair.start.ends_with(text.as_ref()) {
2718 let prefix_len = pair.start.len() - text.len();
2719 let preceding_text_matches_prefix = prefix_len == 0
2720 || (selection.start.column >= (prefix_len as u32)
2721 && snapshot.contains_str_at(
2722 Point::new(
2723 selection.start.row,
2724 selection.start.column - (prefix_len as u32),
2725 ),
2726 &pair.start[..prefix_len],
2727 ));
2728 if preceding_text_matches_prefix {
2729 bracket_pair = Some(pair.clone());
2730 is_bracket_pair_start = true;
2731 break;
2732 }
2733 }
2734 if pair.end.as_str() == text.as_ref() {
2735 bracket_pair = Some(pair.clone());
2736 is_bracket_pair_end = true;
2737 break;
2738 }
2739 }
2740 }
2741
2742 if let Some(bracket_pair) = bracket_pair {
2743 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2744 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2745 let auto_surround =
2746 self.use_auto_surround && snapshot_settings.use_auto_surround;
2747 if selection.is_empty() {
2748 if is_bracket_pair_start {
2749 // If the inserted text is a suffix of an opening bracket and the
2750 // selection is preceded by the rest of the opening bracket, then
2751 // insert the closing bracket.
2752 let following_text_allows_autoclose = snapshot
2753 .chars_at(selection.start)
2754 .next()
2755 .map_or(true, |c| scope.should_autoclose_before(c));
2756
2757 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2758 && bracket_pair.start.len() == 1
2759 {
2760 let target = bracket_pair.start.chars().next().unwrap();
2761 let current_line_count = snapshot
2762 .reversed_chars_at(selection.start)
2763 .take_while(|&c| c != '\n')
2764 .filter(|&c| c == target)
2765 .count();
2766 current_line_count % 2 == 1
2767 } else {
2768 false
2769 };
2770
2771 if autoclose
2772 && bracket_pair.close
2773 && following_text_allows_autoclose
2774 && !is_closing_quote
2775 {
2776 let anchor = snapshot.anchor_before(selection.end);
2777 new_selections.push((selection.map(|_| anchor), text.len()));
2778 new_autoclose_regions.push((
2779 anchor,
2780 text.len(),
2781 selection.id,
2782 bracket_pair.clone(),
2783 ));
2784 edits.push((
2785 selection.range(),
2786 format!("{}{}", text, bracket_pair.end).into(),
2787 ));
2788 bracket_inserted = true;
2789 continue;
2790 }
2791 }
2792
2793 if let Some(region) = autoclose_region {
2794 // If the selection is followed by an auto-inserted closing bracket,
2795 // then don't insert that closing bracket again; just move the selection
2796 // past the closing bracket.
2797 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2798 && text.as_ref() == region.pair.end.as_str();
2799 if should_skip {
2800 let anchor = snapshot.anchor_after(selection.end);
2801 new_selections
2802 .push((selection.map(|_| anchor), region.pair.end.len()));
2803 continue;
2804 }
2805 }
2806
2807 let always_treat_brackets_as_autoclosed = snapshot
2808 .settings_at(selection.start, cx)
2809 .always_treat_brackets_as_autoclosed;
2810 if always_treat_brackets_as_autoclosed
2811 && is_bracket_pair_end
2812 && snapshot.contains_str_at(selection.end, text.as_ref())
2813 {
2814 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2815 // and the inserted text is a closing bracket and the selection is followed
2816 // by the closing bracket then move the selection past the closing bracket.
2817 let anchor = snapshot.anchor_after(selection.end);
2818 new_selections.push((selection.map(|_| anchor), text.len()));
2819 continue;
2820 }
2821 }
2822 // If an opening bracket is 1 character long and is typed while
2823 // text is selected, then surround that text with the bracket pair.
2824 else if auto_surround
2825 && bracket_pair.surround
2826 && is_bracket_pair_start
2827 && bracket_pair.start.chars().count() == 1
2828 {
2829 edits.push((selection.start..selection.start, text.clone()));
2830 edits.push((
2831 selection.end..selection.end,
2832 bracket_pair.end.as_str().into(),
2833 ));
2834 bracket_inserted = true;
2835 new_selections.push((
2836 Selection {
2837 id: selection.id,
2838 start: snapshot.anchor_after(selection.start),
2839 end: snapshot.anchor_before(selection.end),
2840 reversed: selection.reversed,
2841 goal: selection.goal,
2842 },
2843 0,
2844 ));
2845 continue;
2846 }
2847 }
2848 }
2849
2850 if self.auto_replace_emoji_shortcode
2851 && selection.is_empty()
2852 && text.as_ref().ends_with(':')
2853 {
2854 if let Some(possible_emoji_short_code) =
2855 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2856 {
2857 if !possible_emoji_short_code.is_empty() {
2858 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2859 let emoji_shortcode_start = Point::new(
2860 selection.start.row,
2861 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2862 );
2863
2864 // Remove shortcode from buffer
2865 edits.push((
2866 emoji_shortcode_start..selection.start,
2867 "".to_string().into(),
2868 ));
2869 new_selections.push((
2870 Selection {
2871 id: selection.id,
2872 start: snapshot.anchor_after(emoji_shortcode_start),
2873 end: snapshot.anchor_before(selection.start),
2874 reversed: selection.reversed,
2875 goal: selection.goal,
2876 },
2877 0,
2878 ));
2879
2880 // Insert emoji
2881 let selection_start_anchor = snapshot.anchor_after(selection.start);
2882 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2883 edits.push((selection.start..selection.end, emoji.to_string().into()));
2884
2885 continue;
2886 }
2887 }
2888 }
2889 }
2890
2891 // If not handling any auto-close operation, then just replace the selected
2892 // text with the given input and move the selection to the end of the
2893 // newly inserted text.
2894 let anchor = snapshot.anchor_after(selection.end);
2895 if !self.linked_edit_ranges.is_empty() {
2896 let start_anchor = snapshot.anchor_before(selection.start);
2897
2898 let is_word_char = text.chars().next().map_or(true, |char| {
2899 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2900 classifier.is_word(char)
2901 });
2902
2903 if is_word_char {
2904 if let Some(ranges) = self
2905 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2906 {
2907 for (buffer, edits) in ranges {
2908 linked_edits
2909 .entry(buffer.clone())
2910 .or_default()
2911 .extend(edits.into_iter().map(|range| (range, text.clone())));
2912 }
2913 }
2914 }
2915 }
2916
2917 new_selections.push((selection.map(|_| anchor), 0));
2918 edits.push((selection.start..selection.end, text.clone()));
2919 }
2920
2921 drop(snapshot);
2922
2923 self.transact(window, cx, |this, window, cx| {
2924 this.buffer.update(cx, |buffer, cx| {
2925 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2926 });
2927 for (buffer, edits) in linked_edits {
2928 buffer.update(cx, |buffer, cx| {
2929 let snapshot = buffer.snapshot();
2930 let edits = edits
2931 .into_iter()
2932 .map(|(range, text)| {
2933 use text::ToPoint as TP;
2934 let end_point = TP::to_point(&range.end, &snapshot);
2935 let start_point = TP::to_point(&range.start, &snapshot);
2936 (start_point..end_point, text)
2937 })
2938 .sorted_by_key(|(range, _)| range.start)
2939 .collect::<Vec<_>>();
2940 buffer.edit(edits, None, cx);
2941 })
2942 }
2943 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2944 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2945 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2946 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2947 .zip(new_selection_deltas)
2948 .map(|(selection, delta)| Selection {
2949 id: selection.id,
2950 start: selection.start + delta,
2951 end: selection.end + delta,
2952 reversed: selection.reversed,
2953 goal: SelectionGoal::None,
2954 })
2955 .collect::<Vec<_>>();
2956
2957 let mut i = 0;
2958 for (position, delta, selection_id, pair) in new_autoclose_regions {
2959 let position = position.to_offset(&map.buffer_snapshot) + delta;
2960 let start = map.buffer_snapshot.anchor_before(position);
2961 let end = map.buffer_snapshot.anchor_after(position);
2962 while let Some(existing_state) = this.autoclose_regions.get(i) {
2963 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2964 Ordering::Less => i += 1,
2965 Ordering::Greater => break,
2966 Ordering::Equal => {
2967 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2968 Ordering::Less => i += 1,
2969 Ordering::Equal => break,
2970 Ordering::Greater => break,
2971 }
2972 }
2973 }
2974 }
2975 this.autoclose_regions.insert(
2976 i,
2977 AutocloseRegion {
2978 selection_id,
2979 range: start..end,
2980 pair,
2981 },
2982 );
2983 }
2984
2985 let had_active_inline_completion = this.has_active_inline_completion();
2986 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
2987 s.select(new_selections)
2988 });
2989
2990 if !bracket_inserted {
2991 if let Some(on_type_format_task) =
2992 this.trigger_on_type_formatting(text.to_string(), window, cx)
2993 {
2994 on_type_format_task.detach_and_log_err(cx);
2995 }
2996 }
2997
2998 let editor_settings = EditorSettings::get_global(cx);
2999 if bracket_inserted
3000 && (editor_settings.auto_signature_help
3001 || editor_settings.show_signature_help_after_edits)
3002 {
3003 this.show_signature_help(&ShowSignatureHelp, window, cx);
3004 }
3005
3006 let trigger_in_words =
3007 this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
3008 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3009 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3010 this.refresh_inline_completion(true, false, window, cx);
3011 });
3012 }
3013
3014 fn find_possible_emoji_shortcode_at_position(
3015 snapshot: &MultiBufferSnapshot,
3016 position: Point,
3017 ) -> Option<String> {
3018 let mut chars = Vec::new();
3019 let mut found_colon = false;
3020 for char in snapshot.reversed_chars_at(position).take(100) {
3021 // Found a possible emoji shortcode in the middle of the buffer
3022 if found_colon {
3023 if char.is_whitespace() {
3024 chars.reverse();
3025 return Some(chars.iter().collect());
3026 }
3027 // If the previous character is not a whitespace, we are in the middle of a word
3028 // and we only want to complete the shortcode if the word is made up of other emojis
3029 let mut containing_word = String::new();
3030 for ch in snapshot
3031 .reversed_chars_at(position)
3032 .skip(chars.len() + 1)
3033 .take(100)
3034 {
3035 if ch.is_whitespace() {
3036 break;
3037 }
3038 containing_word.push(ch);
3039 }
3040 let containing_word = containing_word.chars().rev().collect::<String>();
3041 if util::word_consists_of_emojis(containing_word.as_str()) {
3042 chars.reverse();
3043 return Some(chars.iter().collect());
3044 }
3045 }
3046
3047 if char.is_whitespace() || !char.is_ascii() {
3048 return None;
3049 }
3050 if char == ':' {
3051 found_colon = true;
3052 } else {
3053 chars.push(char);
3054 }
3055 }
3056 // Found a possible emoji shortcode at the beginning of the buffer
3057 chars.reverse();
3058 Some(chars.iter().collect())
3059 }
3060
3061 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3062 self.transact(window, cx, |this, window, cx| {
3063 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3064 let selections = this.selections.all::<usize>(cx);
3065 let multi_buffer = this.buffer.read(cx);
3066 let buffer = multi_buffer.snapshot(cx);
3067 selections
3068 .iter()
3069 .map(|selection| {
3070 let start_point = selection.start.to_point(&buffer);
3071 let mut indent =
3072 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3073 indent.len = cmp::min(indent.len, start_point.column);
3074 let start = selection.start;
3075 let end = selection.end;
3076 let selection_is_empty = start == end;
3077 let language_scope = buffer.language_scope_at(start);
3078 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3079 &language_scope
3080 {
3081 let leading_whitespace_len = buffer
3082 .reversed_chars_at(start)
3083 .take_while(|c| c.is_whitespace() && *c != '\n')
3084 .map(|c| c.len_utf8())
3085 .sum::<usize>();
3086
3087 let trailing_whitespace_len = buffer
3088 .chars_at(end)
3089 .take_while(|c| c.is_whitespace() && *c != '\n')
3090 .map(|c| c.len_utf8())
3091 .sum::<usize>();
3092
3093 let insert_extra_newline =
3094 language.brackets().any(|(pair, enabled)| {
3095 let pair_start = pair.start.trim_end();
3096 let pair_end = pair.end.trim_start();
3097
3098 enabled
3099 && pair.newline
3100 && buffer.contains_str_at(
3101 end + trailing_whitespace_len,
3102 pair_end,
3103 )
3104 && buffer.contains_str_at(
3105 (start - leading_whitespace_len)
3106 .saturating_sub(pair_start.len()),
3107 pair_start,
3108 )
3109 });
3110
3111 // Comment extension on newline is allowed only for cursor selections
3112 let comment_delimiter = maybe!({
3113 if !selection_is_empty {
3114 return None;
3115 }
3116
3117 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3118 return None;
3119 }
3120
3121 let delimiters = language.line_comment_prefixes();
3122 let max_len_of_delimiter =
3123 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3124 let (snapshot, range) =
3125 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3126
3127 let mut index_of_first_non_whitespace = 0;
3128 let comment_candidate = snapshot
3129 .chars_for_range(range)
3130 .skip_while(|c| {
3131 let should_skip = c.is_whitespace();
3132 if should_skip {
3133 index_of_first_non_whitespace += 1;
3134 }
3135 should_skip
3136 })
3137 .take(max_len_of_delimiter)
3138 .collect::<String>();
3139 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3140 comment_candidate.starts_with(comment_prefix.as_ref())
3141 })?;
3142 let cursor_is_placed_after_comment_marker =
3143 index_of_first_non_whitespace + comment_prefix.len()
3144 <= start_point.column as usize;
3145 if cursor_is_placed_after_comment_marker {
3146 Some(comment_prefix.clone())
3147 } else {
3148 None
3149 }
3150 });
3151 (comment_delimiter, insert_extra_newline)
3152 } else {
3153 (None, false)
3154 };
3155
3156 let capacity_for_delimiter = comment_delimiter
3157 .as_deref()
3158 .map(str::len)
3159 .unwrap_or_default();
3160 let mut new_text =
3161 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3162 new_text.push('\n');
3163 new_text.extend(indent.chars());
3164 if let Some(delimiter) = &comment_delimiter {
3165 new_text.push_str(delimiter);
3166 }
3167 if insert_extra_newline {
3168 new_text = new_text.repeat(2);
3169 }
3170
3171 let anchor = buffer.anchor_after(end);
3172 let new_selection = selection.map(|_| anchor);
3173 (
3174 (start..end, new_text),
3175 (insert_extra_newline, new_selection),
3176 )
3177 })
3178 .unzip()
3179 };
3180
3181 this.edit_with_autoindent(edits, cx);
3182 let buffer = this.buffer.read(cx).snapshot(cx);
3183 let new_selections = selection_fixup_info
3184 .into_iter()
3185 .map(|(extra_newline_inserted, new_selection)| {
3186 let mut cursor = new_selection.end.to_point(&buffer);
3187 if extra_newline_inserted {
3188 cursor.row -= 1;
3189 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3190 }
3191 new_selection.map(|_| cursor)
3192 })
3193 .collect();
3194
3195 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3196 s.select(new_selections)
3197 });
3198 this.refresh_inline_completion(true, false, window, cx);
3199 });
3200 }
3201
3202 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3203 let buffer = self.buffer.read(cx);
3204 let snapshot = buffer.snapshot(cx);
3205
3206 let mut edits = Vec::new();
3207 let mut rows = Vec::new();
3208
3209 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3210 let cursor = selection.head();
3211 let row = cursor.row;
3212
3213 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3214
3215 let newline = "\n".to_string();
3216 edits.push((start_of_line..start_of_line, newline));
3217
3218 rows.push(row + rows_inserted as u32);
3219 }
3220
3221 self.transact(window, cx, |editor, window, cx| {
3222 editor.edit(edits, cx);
3223
3224 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3225 let mut index = 0;
3226 s.move_cursors_with(|map, _, _| {
3227 let row = rows[index];
3228 index += 1;
3229
3230 let point = Point::new(row, 0);
3231 let boundary = map.next_line_boundary(point).1;
3232 let clipped = map.clip_point(boundary, Bias::Left);
3233
3234 (clipped, SelectionGoal::None)
3235 });
3236 });
3237
3238 let mut indent_edits = Vec::new();
3239 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3240 for row in rows {
3241 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3242 for (row, indent) in indents {
3243 if indent.len == 0 {
3244 continue;
3245 }
3246
3247 let text = match indent.kind {
3248 IndentKind::Space => " ".repeat(indent.len as usize),
3249 IndentKind::Tab => "\t".repeat(indent.len as usize),
3250 };
3251 let point = Point::new(row.0, 0);
3252 indent_edits.push((point..point, text));
3253 }
3254 }
3255 editor.edit(indent_edits, cx);
3256 });
3257 }
3258
3259 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3260 let buffer = self.buffer.read(cx);
3261 let snapshot = buffer.snapshot(cx);
3262
3263 let mut edits = Vec::new();
3264 let mut rows = Vec::new();
3265 let mut rows_inserted = 0;
3266
3267 for selection in self.selections.all_adjusted(cx) {
3268 let cursor = selection.head();
3269 let row = cursor.row;
3270
3271 let point = Point::new(row + 1, 0);
3272 let start_of_line = snapshot.clip_point(point, Bias::Left);
3273
3274 let newline = "\n".to_string();
3275 edits.push((start_of_line..start_of_line, newline));
3276
3277 rows_inserted += 1;
3278 rows.push(row + rows_inserted);
3279 }
3280
3281 self.transact(window, cx, |editor, window, cx| {
3282 editor.edit(edits, cx);
3283
3284 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3285 let mut index = 0;
3286 s.move_cursors_with(|map, _, _| {
3287 let row = rows[index];
3288 index += 1;
3289
3290 let point = Point::new(row, 0);
3291 let boundary = map.next_line_boundary(point).1;
3292 let clipped = map.clip_point(boundary, Bias::Left);
3293
3294 (clipped, SelectionGoal::None)
3295 });
3296 });
3297
3298 let mut indent_edits = Vec::new();
3299 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3300 for row in rows {
3301 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3302 for (row, indent) in indents {
3303 if indent.len == 0 {
3304 continue;
3305 }
3306
3307 let text = match indent.kind {
3308 IndentKind::Space => " ".repeat(indent.len as usize),
3309 IndentKind::Tab => "\t".repeat(indent.len as usize),
3310 };
3311 let point = Point::new(row.0, 0);
3312 indent_edits.push((point..point, text));
3313 }
3314 }
3315 editor.edit(indent_edits, cx);
3316 });
3317 }
3318
3319 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3320 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3321 original_indent_columns: Vec::new(),
3322 });
3323 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3324 }
3325
3326 fn insert_with_autoindent_mode(
3327 &mut self,
3328 text: &str,
3329 autoindent_mode: Option<AutoindentMode>,
3330 window: &mut Window,
3331 cx: &mut Context<Self>,
3332 ) {
3333 if self.read_only(cx) {
3334 return;
3335 }
3336
3337 let text: Arc<str> = text.into();
3338 self.transact(window, cx, |this, window, cx| {
3339 let old_selections = this.selections.all_adjusted(cx);
3340 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3341 let anchors = {
3342 let snapshot = buffer.read(cx);
3343 old_selections
3344 .iter()
3345 .map(|s| {
3346 let anchor = snapshot.anchor_after(s.head());
3347 s.map(|_| anchor)
3348 })
3349 .collect::<Vec<_>>()
3350 };
3351 buffer.edit(
3352 old_selections
3353 .iter()
3354 .map(|s| (s.start..s.end, text.clone())),
3355 autoindent_mode,
3356 cx,
3357 );
3358 anchors
3359 });
3360
3361 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3362 s.select_anchors(selection_anchors);
3363 });
3364
3365 cx.notify();
3366 });
3367 }
3368
3369 fn trigger_completion_on_input(
3370 &mut self,
3371 text: &str,
3372 trigger_in_words: bool,
3373 window: &mut Window,
3374 cx: &mut Context<Self>,
3375 ) {
3376 if self.is_completion_trigger(text, trigger_in_words, cx) {
3377 self.show_completions(
3378 &ShowCompletions {
3379 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3380 },
3381 window,
3382 cx,
3383 );
3384 } else {
3385 self.hide_context_menu(window, cx);
3386 }
3387 }
3388
3389 fn is_completion_trigger(
3390 &self,
3391 text: &str,
3392 trigger_in_words: bool,
3393 cx: &mut Context<Self>,
3394 ) -> bool {
3395 let position = self.selections.newest_anchor().head();
3396 let multibuffer = self.buffer.read(cx);
3397 let Some(buffer) = position
3398 .buffer_id
3399 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3400 else {
3401 return false;
3402 };
3403
3404 if let Some(completion_provider) = &self.completion_provider {
3405 completion_provider.is_completion_trigger(
3406 &buffer,
3407 position.text_anchor,
3408 text,
3409 trigger_in_words,
3410 cx,
3411 )
3412 } else {
3413 false
3414 }
3415 }
3416
3417 /// If any empty selections is touching the start of its innermost containing autoclose
3418 /// region, expand it to select the brackets.
3419 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3420 let selections = self.selections.all::<usize>(cx);
3421 let buffer = self.buffer.read(cx).read(cx);
3422 let new_selections = self
3423 .selections_with_autoclose_regions(selections, &buffer)
3424 .map(|(mut selection, region)| {
3425 if !selection.is_empty() {
3426 return selection;
3427 }
3428
3429 if let Some(region) = region {
3430 let mut range = region.range.to_offset(&buffer);
3431 if selection.start == range.start && range.start >= region.pair.start.len() {
3432 range.start -= region.pair.start.len();
3433 if buffer.contains_str_at(range.start, ®ion.pair.start)
3434 && buffer.contains_str_at(range.end, ®ion.pair.end)
3435 {
3436 range.end += region.pair.end.len();
3437 selection.start = range.start;
3438 selection.end = range.end;
3439
3440 return selection;
3441 }
3442 }
3443 }
3444
3445 let always_treat_brackets_as_autoclosed = buffer
3446 .settings_at(selection.start, cx)
3447 .always_treat_brackets_as_autoclosed;
3448
3449 if !always_treat_brackets_as_autoclosed {
3450 return selection;
3451 }
3452
3453 if let Some(scope) = buffer.language_scope_at(selection.start) {
3454 for (pair, enabled) in scope.brackets() {
3455 if !enabled || !pair.close {
3456 continue;
3457 }
3458
3459 if buffer.contains_str_at(selection.start, &pair.end) {
3460 let pair_start_len = pair.start.len();
3461 if buffer.contains_str_at(
3462 selection.start.saturating_sub(pair_start_len),
3463 &pair.start,
3464 ) {
3465 selection.start -= pair_start_len;
3466 selection.end += pair.end.len();
3467
3468 return selection;
3469 }
3470 }
3471 }
3472 }
3473
3474 selection
3475 })
3476 .collect();
3477
3478 drop(buffer);
3479 self.change_selections(None, window, cx, |selections| {
3480 selections.select(new_selections)
3481 });
3482 }
3483
3484 /// Iterate the given selections, and for each one, find the smallest surrounding
3485 /// autoclose region. This uses the ordering of the selections and the autoclose
3486 /// regions to avoid repeated comparisons.
3487 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3488 &'a self,
3489 selections: impl IntoIterator<Item = Selection<D>>,
3490 buffer: &'a MultiBufferSnapshot,
3491 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3492 let mut i = 0;
3493 let mut regions = self.autoclose_regions.as_slice();
3494 selections.into_iter().map(move |selection| {
3495 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3496
3497 let mut enclosing = None;
3498 while let Some(pair_state) = regions.get(i) {
3499 if pair_state.range.end.to_offset(buffer) < range.start {
3500 regions = ®ions[i + 1..];
3501 i = 0;
3502 } else if pair_state.range.start.to_offset(buffer) > range.end {
3503 break;
3504 } else {
3505 if pair_state.selection_id == selection.id {
3506 enclosing = Some(pair_state);
3507 }
3508 i += 1;
3509 }
3510 }
3511
3512 (selection, enclosing)
3513 })
3514 }
3515
3516 /// Remove any autoclose regions that no longer contain their selection.
3517 fn invalidate_autoclose_regions(
3518 &mut self,
3519 mut selections: &[Selection<Anchor>],
3520 buffer: &MultiBufferSnapshot,
3521 ) {
3522 self.autoclose_regions.retain(|state| {
3523 let mut i = 0;
3524 while let Some(selection) = selections.get(i) {
3525 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3526 selections = &selections[1..];
3527 continue;
3528 }
3529 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3530 break;
3531 }
3532 if selection.id == state.selection_id {
3533 return true;
3534 } else {
3535 i += 1;
3536 }
3537 }
3538 false
3539 });
3540 }
3541
3542 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3543 let offset = position.to_offset(buffer);
3544 let (word_range, kind) = buffer.surrounding_word(offset, true);
3545 if offset > word_range.start && kind == Some(CharKind::Word) {
3546 Some(
3547 buffer
3548 .text_for_range(word_range.start..offset)
3549 .collect::<String>(),
3550 )
3551 } else {
3552 None
3553 }
3554 }
3555
3556 pub fn toggle_inlay_hints(
3557 &mut self,
3558 _: &ToggleInlayHints,
3559 _: &mut Window,
3560 cx: &mut Context<Self>,
3561 ) {
3562 self.refresh_inlay_hints(
3563 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3564 cx,
3565 );
3566 }
3567
3568 pub fn inlay_hints_enabled(&self) -> bool {
3569 self.inlay_hint_cache.enabled
3570 }
3571
3572 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3573 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3574 return;
3575 }
3576
3577 let reason_description = reason.description();
3578 let ignore_debounce = matches!(
3579 reason,
3580 InlayHintRefreshReason::SettingsChange(_)
3581 | InlayHintRefreshReason::Toggle(_)
3582 | InlayHintRefreshReason::ExcerptsRemoved(_)
3583 );
3584 let (invalidate_cache, required_languages) = match reason {
3585 InlayHintRefreshReason::Toggle(enabled) => {
3586 self.inlay_hint_cache.enabled = enabled;
3587 if enabled {
3588 (InvalidationStrategy::RefreshRequested, None)
3589 } else {
3590 self.inlay_hint_cache.clear();
3591 self.splice_inlays(
3592 &self
3593 .visible_inlay_hints(cx)
3594 .iter()
3595 .map(|inlay| inlay.id)
3596 .collect::<Vec<InlayId>>(),
3597 Vec::new(),
3598 cx,
3599 );
3600 return;
3601 }
3602 }
3603 InlayHintRefreshReason::SettingsChange(new_settings) => {
3604 match self.inlay_hint_cache.update_settings(
3605 &self.buffer,
3606 new_settings,
3607 self.visible_inlay_hints(cx),
3608 cx,
3609 ) {
3610 ControlFlow::Break(Some(InlaySplice {
3611 to_remove,
3612 to_insert,
3613 })) => {
3614 self.splice_inlays(&to_remove, to_insert, cx);
3615 return;
3616 }
3617 ControlFlow::Break(None) => return,
3618 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3619 }
3620 }
3621 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3622 if let Some(InlaySplice {
3623 to_remove,
3624 to_insert,
3625 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3626 {
3627 self.splice_inlays(&to_remove, to_insert, cx);
3628 }
3629 return;
3630 }
3631 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3632 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3633 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3634 }
3635 InlayHintRefreshReason::RefreshRequested => {
3636 (InvalidationStrategy::RefreshRequested, None)
3637 }
3638 };
3639
3640 if let Some(InlaySplice {
3641 to_remove,
3642 to_insert,
3643 }) = self.inlay_hint_cache.spawn_hint_refresh(
3644 reason_description,
3645 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3646 invalidate_cache,
3647 ignore_debounce,
3648 cx,
3649 ) {
3650 self.splice_inlays(&to_remove, to_insert, cx);
3651 }
3652 }
3653
3654 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3655 self.display_map
3656 .read(cx)
3657 .current_inlays()
3658 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3659 .cloned()
3660 .collect()
3661 }
3662
3663 pub fn excerpts_for_inlay_hints_query(
3664 &self,
3665 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3666 cx: &mut Context<Editor>,
3667 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3668 let Some(project) = self.project.as_ref() else {
3669 return HashMap::default();
3670 };
3671 let project = project.read(cx);
3672 let multi_buffer = self.buffer().read(cx);
3673 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3674 let multi_buffer_visible_start = self
3675 .scroll_manager
3676 .anchor()
3677 .anchor
3678 .to_point(&multi_buffer_snapshot);
3679 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3680 multi_buffer_visible_start
3681 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3682 Bias::Left,
3683 );
3684 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3685 multi_buffer_snapshot
3686 .range_to_buffer_ranges(multi_buffer_visible_range)
3687 .into_iter()
3688 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3689 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3690 let buffer_file = project::File::from_dyn(buffer.file())?;
3691 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3692 let worktree_entry = buffer_worktree
3693 .read(cx)
3694 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3695 if worktree_entry.is_ignored {
3696 return None;
3697 }
3698
3699 let language = buffer.language()?;
3700 if let Some(restrict_to_languages) = restrict_to_languages {
3701 if !restrict_to_languages.contains(language) {
3702 return None;
3703 }
3704 }
3705 Some((
3706 excerpt_id,
3707 (
3708 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3709 buffer.version().clone(),
3710 excerpt_visible_range,
3711 ),
3712 ))
3713 })
3714 .collect()
3715 }
3716
3717 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3718 TextLayoutDetails {
3719 text_system: window.text_system().clone(),
3720 editor_style: self.style.clone().unwrap(),
3721 rem_size: window.rem_size(),
3722 scroll_anchor: self.scroll_manager.anchor(),
3723 visible_rows: self.visible_line_count(),
3724 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3725 }
3726 }
3727
3728 pub fn splice_inlays(
3729 &self,
3730 to_remove: &[InlayId],
3731 to_insert: Vec<Inlay>,
3732 cx: &mut Context<Self>,
3733 ) {
3734 self.display_map.update(cx, |display_map, cx| {
3735 display_map.splice_inlays(to_remove, to_insert, cx)
3736 });
3737 cx.notify();
3738 }
3739
3740 fn trigger_on_type_formatting(
3741 &self,
3742 input: String,
3743 window: &mut Window,
3744 cx: &mut Context<Self>,
3745 ) -> Option<Task<Result<()>>> {
3746 if input.len() != 1 {
3747 return None;
3748 }
3749
3750 let project = self.project.as_ref()?;
3751 let position = self.selections.newest_anchor().head();
3752 let (buffer, buffer_position) = self
3753 .buffer
3754 .read(cx)
3755 .text_anchor_for_position(position, cx)?;
3756
3757 let settings = language_settings::language_settings(
3758 buffer
3759 .read(cx)
3760 .language_at(buffer_position)
3761 .map(|l| l.name()),
3762 buffer.read(cx).file(),
3763 cx,
3764 );
3765 if !settings.use_on_type_format {
3766 return None;
3767 }
3768
3769 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3770 // hence we do LSP request & edit on host side only — add formats to host's history.
3771 let push_to_lsp_host_history = true;
3772 // If this is not the host, append its history with new edits.
3773 let push_to_client_history = project.read(cx).is_via_collab();
3774
3775 let on_type_formatting = project.update(cx, |project, cx| {
3776 project.on_type_format(
3777 buffer.clone(),
3778 buffer_position,
3779 input,
3780 push_to_lsp_host_history,
3781 cx,
3782 )
3783 });
3784 Some(cx.spawn_in(window, |editor, mut cx| async move {
3785 if let Some(transaction) = on_type_formatting.await? {
3786 if push_to_client_history {
3787 buffer
3788 .update(&mut cx, |buffer, _| {
3789 buffer.push_transaction(transaction, Instant::now());
3790 })
3791 .ok();
3792 }
3793 editor.update(&mut cx, |editor, cx| {
3794 editor.refresh_document_highlights(cx);
3795 })?;
3796 }
3797 Ok(())
3798 }))
3799 }
3800
3801 pub fn show_completions(
3802 &mut self,
3803 options: &ShowCompletions,
3804 window: &mut Window,
3805 cx: &mut Context<Self>,
3806 ) {
3807 if self.pending_rename.is_some() {
3808 return;
3809 }
3810
3811 let Some(provider) = self.completion_provider.as_ref() else {
3812 return;
3813 };
3814
3815 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3816 return;
3817 }
3818
3819 let position = self.selections.newest_anchor().head();
3820 if position.diff_base_anchor.is_some() {
3821 return;
3822 }
3823 let (buffer, buffer_position) =
3824 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3825 output
3826 } else {
3827 return;
3828 };
3829 let show_completion_documentation = buffer
3830 .read(cx)
3831 .snapshot()
3832 .settings_at(buffer_position, cx)
3833 .show_completion_documentation;
3834
3835 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3836
3837 let trigger_kind = match &options.trigger {
3838 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3839 CompletionTriggerKind::TRIGGER_CHARACTER
3840 }
3841 _ => CompletionTriggerKind::INVOKED,
3842 };
3843 let completion_context = CompletionContext {
3844 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3845 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3846 Some(String::from(trigger))
3847 } else {
3848 None
3849 }
3850 }),
3851 trigger_kind,
3852 };
3853 let completions =
3854 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3855 let sort_completions = provider.sort_completions();
3856
3857 let id = post_inc(&mut self.next_completion_id);
3858 let task = cx.spawn_in(window, |editor, mut cx| {
3859 async move {
3860 editor.update(&mut cx, |this, _| {
3861 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3862 })?;
3863 let completions = completions.await.log_err();
3864 let menu = if let Some(completions) = completions {
3865 let mut menu = CompletionsMenu::new(
3866 id,
3867 sort_completions,
3868 show_completion_documentation,
3869 position,
3870 buffer.clone(),
3871 completions.into(),
3872 );
3873
3874 menu.filter(query.as_deref(), cx.background_executor().clone())
3875 .await;
3876
3877 menu.visible().then_some(menu)
3878 } else {
3879 None
3880 };
3881
3882 editor.update_in(&mut cx, |editor, window, cx| {
3883 match editor.context_menu.borrow().as_ref() {
3884 None => {}
3885 Some(CodeContextMenu::Completions(prev_menu)) => {
3886 if prev_menu.id > id {
3887 return;
3888 }
3889 }
3890 _ => return,
3891 }
3892
3893 if editor.focus_handle.is_focused(window) && menu.is_some() {
3894 let mut menu = menu.unwrap();
3895 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3896
3897 *editor.context_menu.borrow_mut() =
3898 Some(CodeContextMenu::Completions(menu));
3899
3900 if editor.show_inline_completions_in_menu(cx) {
3901 editor.update_visible_inline_completion(window, cx);
3902 } else {
3903 editor.discard_inline_completion(false, cx);
3904 }
3905
3906 cx.notify();
3907 } else if editor.completion_tasks.len() <= 1 {
3908 // If there are no more completion tasks and the last menu was
3909 // empty, we should hide it.
3910 let was_hidden = editor.hide_context_menu(window, cx).is_none();
3911 // If it was already hidden and we don't show inline
3912 // completions in the menu, we should also show the
3913 // inline-completion when available.
3914 if was_hidden && editor.show_inline_completions_in_menu(cx) {
3915 editor.update_visible_inline_completion(window, cx);
3916 }
3917 }
3918 })?;
3919
3920 Ok::<_, anyhow::Error>(())
3921 }
3922 .log_err()
3923 });
3924
3925 self.completion_tasks.push((id, task));
3926 }
3927
3928 pub fn confirm_completion(
3929 &mut self,
3930 action: &ConfirmCompletion,
3931 window: &mut Window,
3932 cx: &mut Context<Self>,
3933 ) -> Option<Task<Result<()>>> {
3934 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
3935 }
3936
3937 pub fn compose_completion(
3938 &mut self,
3939 action: &ComposeCompletion,
3940 window: &mut Window,
3941 cx: &mut Context<Self>,
3942 ) -> Option<Task<Result<()>>> {
3943 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
3944 }
3945
3946 fn toggle_zed_predict_onboarding(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3947 window.dispatch_action(zed_actions::OpenZedPredictOnboarding.boxed_clone(), cx);
3948 }
3949
3950 fn do_completion(
3951 &mut self,
3952 item_ix: Option<usize>,
3953 intent: CompletionIntent,
3954 window: &mut Window,
3955 cx: &mut Context<Editor>,
3956 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3957 use language::ToOffset as _;
3958
3959 let completions_menu =
3960 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
3961 menu
3962 } else {
3963 return None;
3964 };
3965
3966 let entries = completions_menu.entries.borrow();
3967 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
3968 if self.show_inline_completions_in_menu(cx) {
3969 self.discard_inline_completion(true, cx);
3970 }
3971 let candidate_id = mat.candidate_id;
3972 drop(entries);
3973
3974 let buffer_handle = completions_menu.buffer;
3975 let completion = completions_menu
3976 .completions
3977 .borrow()
3978 .get(candidate_id)?
3979 .clone();
3980 cx.stop_propagation();
3981
3982 let snippet;
3983 let text;
3984
3985 if completion.is_snippet() {
3986 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3987 text = snippet.as_ref().unwrap().text.clone();
3988 } else {
3989 snippet = None;
3990 text = completion.new_text.clone();
3991 };
3992 let selections = self.selections.all::<usize>(cx);
3993 let buffer = buffer_handle.read(cx);
3994 let old_range = completion.old_range.to_offset(buffer);
3995 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3996
3997 let newest_selection = self.selections.newest_anchor();
3998 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3999 return None;
4000 }
4001
4002 let lookbehind = newest_selection
4003 .start
4004 .text_anchor
4005 .to_offset(buffer)
4006 .saturating_sub(old_range.start);
4007 let lookahead = old_range
4008 .end
4009 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4010 let mut common_prefix_len = old_text
4011 .bytes()
4012 .zip(text.bytes())
4013 .take_while(|(a, b)| a == b)
4014 .count();
4015
4016 let snapshot = self.buffer.read(cx).snapshot(cx);
4017 let mut range_to_replace: Option<Range<isize>> = None;
4018 let mut ranges = Vec::new();
4019 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4020 for selection in &selections {
4021 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4022 let start = selection.start.saturating_sub(lookbehind);
4023 let end = selection.end + lookahead;
4024 if selection.id == newest_selection.id {
4025 range_to_replace = Some(
4026 ((start + common_prefix_len) as isize - selection.start as isize)
4027 ..(end as isize - selection.start as isize),
4028 );
4029 }
4030 ranges.push(start + common_prefix_len..end);
4031 } else {
4032 common_prefix_len = 0;
4033 ranges.clear();
4034 ranges.extend(selections.iter().map(|s| {
4035 if s.id == newest_selection.id {
4036 range_to_replace = Some(
4037 old_range.start.to_offset_utf16(&snapshot).0 as isize
4038 - selection.start as isize
4039 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4040 - selection.start as isize,
4041 );
4042 old_range.clone()
4043 } else {
4044 s.start..s.end
4045 }
4046 }));
4047 break;
4048 }
4049 if !self.linked_edit_ranges.is_empty() {
4050 let start_anchor = snapshot.anchor_before(selection.head());
4051 let end_anchor = snapshot.anchor_after(selection.tail());
4052 if let Some(ranges) = self
4053 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4054 {
4055 for (buffer, edits) in ranges {
4056 linked_edits.entry(buffer.clone()).or_default().extend(
4057 edits
4058 .into_iter()
4059 .map(|range| (range, text[common_prefix_len..].to_owned())),
4060 );
4061 }
4062 }
4063 }
4064 }
4065 let text = &text[common_prefix_len..];
4066
4067 cx.emit(EditorEvent::InputHandled {
4068 utf16_range_to_replace: range_to_replace,
4069 text: text.into(),
4070 });
4071
4072 self.transact(window, cx, |this, window, cx| {
4073 if let Some(mut snippet) = snippet {
4074 snippet.text = text.to_string();
4075 for tabstop in snippet
4076 .tabstops
4077 .iter_mut()
4078 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4079 {
4080 tabstop.start -= common_prefix_len as isize;
4081 tabstop.end -= common_prefix_len as isize;
4082 }
4083
4084 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4085 } else {
4086 this.buffer.update(cx, |buffer, cx| {
4087 buffer.edit(
4088 ranges.iter().map(|range| (range.clone(), text)),
4089 this.autoindent_mode.clone(),
4090 cx,
4091 );
4092 });
4093 }
4094 for (buffer, edits) in linked_edits {
4095 buffer.update(cx, |buffer, cx| {
4096 let snapshot = buffer.snapshot();
4097 let edits = edits
4098 .into_iter()
4099 .map(|(range, text)| {
4100 use text::ToPoint as TP;
4101 let end_point = TP::to_point(&range.end, &snapshot);
4102 let start_point = TP::to_point(&range.start, &snapshot);
4103 (start_point..end_point, text)
4104 })
4105 .sorted_by_key(|(range, _)| range.start)
4106 .collect::<Vec<_>>();
4107 buffer.edit(edits, None, cx);
4108 })
4109 }
4110
4111 this.refresh_inline_completion(true, false, window, cx);
4112 });
4113
4114 let show_new_completions_on_confirm = completion
4115 .confirm
4116 .as_ref()
4117 .map_or(false, |confirm| confirm(intent, window, cx));
4118 if show_new_completions_on_confirm {
4119 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4120 }
4121
4122 let provider = self.completion_provider.as_ref()?;
4123 drop(completion);
4124 let apply_edits = provider.apply_additional_edits_for_completion(
4125 buffer_handle,
4126 completions_menu.completions.clone(),
4127 candidate_id,
4128 true,
4129 cx,
4130 );
4131
4132 let editor_settings = EditorSettings::get_global(cx);
4133 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4134 // After the code completion is finished, users often want to know what signatures are needed.
4135 // so we should automatically call signature_help
4136 self.show_signature_help(&ShowSignatureHelp, window, cx);
4137 }
4138
4139 Some(cx.foreground_executor().spawn(async move {
4140 apply_edits.await?;
4141 Ok(())
4142 }))
4143 }
4144
4145 pub fn toggle_code_actions(
4146 &mut self,
4147 action: &ToggleCodeActions,
4148 window: &mut Window,
4149 cx: &mut Context<Self>,
4150 ) {
4151 let mut context_menu = self.context_menu.borrow_mut();
4152 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4153 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4154 // Toggle if we're selecting the same one
4155 *context_menu = None;
4156 cx.notify();
4157 return;
4158 } else {
4159 // Otherwise, clear it and start a new one
4160 *context_menu = None;
4161 cx.notify();
4162 }
4163 }
4164 drop(context_menu);
4165 let snapshot = self.snapshot(window, cx);
4166 let deployed_from_indicator = action.deployed_from_indicator;
4167 let mut task = self.code_actions_task.take();
4168 let action = action.clone();
4169 cx.spawn_in(window, |editor, mut cx| async move {
4170 while let Some(prev_task) = task {
4171 prev_task.await.log_err();
4172 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4173 }
4174
4175 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4176 if editor.focus_handle.is_focused(window) {
4177 let multibuffer_point = action
4178 .deployed_from_indicator
4179 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4180 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4181 let (buffer, buffer_row) = snapshot
4182 .buffer_snapshot
4183 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4184 .and_then(|(buffer_snapshot, range)| {
4185 editor
4186 .buffer
4187 .read(cx)
4188 .buffer(buffer_snapshot.remote_id())
4189 .map(|buffer| (buffer, range.start.row))
4190 })?;
4191 let (_, code_actions) = editor
4192 .available_code_actions
4193 .clone()
4194 .and_then(|(location, code_actions)| {
4195 let snapshot = location.buffer.read(cx).snapshot();
4196 let point_range = location.range.to_point(&snapshot);
4197 let point_range = point_range.start.row..=point_range.end.row;
4198 if point_range.contains(&buffer_row) {
4199 Some((location, code_actions))
4200 } else {
4201 None
4202 }
4203 })
4204 .unzip();
4205 let buffer_id = buffer.read(cx).remote_id();
4206 let tasks = editor
4207 .tasks
4208 .get(&(buffer_id, buffer_row))
4209 .map(|t| Arc::new(t.to_owned()));
4210 if tasks.is_none() && code_actions.is_none() {
4211 return None;
4212 }
4213
4214 editor.completion_tasks.clear();
4215 editor.discard_inline_completion(false, cx);
4216 let task_context =
4217 tasks
4218 .as_ref()
4219 .zip(editor.project.clone())
4220 .map(|(tasks, project)| {
4221 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4222 });
4223
4224 Some(cx.spawn_in(window, |editor, mut cx| async move {
4225 let task_context = match task_context {
4226 Some(task_context) => task_context.await,
4227 None => None,
4228 };
4229 let resolved_tasks =
4230 tasks.zip(task_context).map(|(tasks, task_context)| {
4231 Rc::new(ResolvedTasks {
4232 templates: tasks.resolve(&task_context).collect(),
4233 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4234 multibuffer_point.row,
4235 tasks.column,
4236 )),
4237 })
4238 });
4239 let spawn_straight_away = resolved_tasks
4240 .as_ref()
4241 .map_or(false, |tasks| tasks.templates.len() == 1)
4242 && code_actions
4243 .as_ref()
4244 .map_or(true, |actions| actions.is_empty());
4245 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4246 *editor.context_menu.borrow_mut() =
4247 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4248 buffer,
4249 actions: CodeActionContents {
4250 tasks: resolved_tasks,
4251 actions: code_actions,
4252 },
4253 selected_item: Default::default(),
4254 scroll_handle: UniformListScrollHandle::default(),
4255 deployed_from_indicator,
4256 }));
4257 if spawn_straight_away {
4258 if let Some(task) = editor.confirm_code_action(
4259 &ConfirmCodeAction { item_ix: Some(0) },
4260 window,
4261 cx,
4262 ) {
4263 cx.notify();
4264 return task;
4265 }
4266 }
4267 cx.notify();
4268 Task::ready(Ok(()))
4269 }) {
4270 task.await
4271 } else {
4272 Ok(())
4273 }
4274 }))
4275 } else {
4276 Some(Task::ready(Ok(())))
4277 }
4278 })?;
4279 if let Some(task) = spawned_test_task {
4280 task.await?;
4281 }
4282
4283 Ok::<_, anyhow::Error>(())
4284 })
4285 .detach_and_log_err(cx);
4286 }
4287
4288 pub fn confirm_code_action(
4289 &mut self,
4290 action: &ConfirmCodeAction,
4291 window: &mut Window,
4292 cx: &mut Context<Self>,
4293 ) -> Option<Task<Result<()>>> {
4294 let actions_menu =
4295 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4296 menu
4297 } else {
4298 return None;
4299 };
4300 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4301 let action = actions_menu.actions.get(action_ix)?;
4302 let title = action.label();
4303 let buffer = actions_menu.buffer;
4304 let workspace = self.workspace()?;
4305
4306 match action {
4307 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4308 workspace.update(cx, |workspace, cx| {
4309 workspace::tasks::schedule_resolved_task(
4310 workspace,
4311 task_source_kind,
4312 resolved_task,
4313 false,
4314 cx,
4315 );
4316
4317 Some(Task::ready(Ok(())))
4318 })
4319 }
4320 CodeActionsItem::CodeAction {
4321 excerpt_id,
4322 action,
4323 provider,
4324 } => {
4325 let apply_code_action =
4326 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4327 let workspace = workspace.downgrade();
4328 Some(cx.spawn_in(window, |editor, cx| async move {
4329 let project_transaction = apply_code_action.await?;
4330 Self::open_project_transaction(
4331 &editor,
4332 workspace,
4333 project_transaction,
4334 title,
4335 cx,
4336 )
4337 .await
4338 }))
4339 }
4340 }
4341 }
4342
4343 pub async fn open_project_transaction(
4344 this: &WeakEntity<Editor>,
4345 workspace: WeakEntity<Workspace>,
4346 transaction: ProjectTransaction,
4347 title: String,
4348 mut cx: AsyncWindowContext,
4349 ) -> Result<()> {
4350 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4351 cx.update(|_, cx| {
4352 entries.sort_unstable_by_key(|(buffer, _)| {
4353 buffer.read(cx).file().map(|f| f.path().clone())
4354 });
4355 })?;
4356
4357 // If the project transaction's edits are all contained within this editor, then
4358 // avoid opening a new editor to display them.
4359
4360 if let Some((buffer, transaction)) = entries.first() {
4361 if entries.len() == 1 {
4362 let excerpt = this.update(&mut cx, |editor, cx| {
4363 editor
4364 .buffer()
4365 .read(cx)
4366 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4367 })?;
4368 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4369 if excerpted_buffer == *buffer {
4370 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4371 let excerpt_range = excerpt_range.to_offset(buffer);
4372 buffer
4373 .edited_ranges_for_transaction::<usize>(transaction)
4374 .all(|range| {
4375 excerpt_range.start <= range.start
4376 && excerpt_range.end >= range.end
4377 })
4378 })?;
4379
4380 if all_edits_within_excerpt {
4381 return Ok(());
4382 }
4383 }
4384 }
4385 }
4386 } else {
4387 return Ok(());
4388 }
4389
4390 let mut ranges_to_highlight = Vec::new();
4391 let excerpt_buffer = cx.new(|cx| {
4392 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4393 for (buffer_handle, transaction) in &entries {
4394 let buffer = buffer_handle.read(cx);
4395 ranges_to_highlight.extend(
4396 multibuffer.push_excerpts_with_context_lines(
4397 buffer_handle.clone(),
4398 buffer
4399 .edited_ranges_for_transaction::<usize>(transaction)
4400 .collect(),
4401 DEFAULT_MULTIBUFFER_CONTEXT,
4402 cx,
4403 ),
4404 );
4405 }
4406 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4407 multibuffer
4408 })?;
4409
4410 workspace.update_in(&mut cx, |workspace, window, cx| {
4411 let project = workspace.project().clone();
4412 let editor = cx
4413 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4414 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4415 editor.update(cx, |editor, cx| {
4416 editor.highlight_background::<Self>(
4417 &ranges_to_highlight,
4418 |theme| theme.editor_highlighted_line_background,
4419 cx,
4420 );
4421 });
4422 })?;
4423
4424 Ok(())
4425 }
4426
4427 pub fn clear_code_action_providers(&mut self) {
4428 self.code_action_providers.clear();
4429 self.available_code_actions.take();
4430 }
4431
4432 pub fn add_code_action_provider(
4433 &mut self,
4434 provider: Rc<dyn CodeActionProvider>,
4435 window: &mut Window,
4436 cx: &mut Context<Self>,
4437 ) {
4438 if self
4439 .code_action_providers
4440 .iter()
4441 .any(|existing_provider| existing_provider.id() == provider.id())
4442 {
4443 return;
4444 }
4445
4446 self.code_action_providers.push(provider);
4447 self.refresh_code_actions(window, cx);
4448 }
4449
4450 pub fn remove_code_action_provider(
4451 &mut self,
4452 id: Arc<str>,
4453 window: &mut Window,
4454 cx: &mut Context<Self>,
4455 ) {
4456 self.code_action_providers
4457 .retain(|provider| provider.id() != id);
4458 self.refresh_code_actions(window, cx);
4459 }
4460
4461 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4462 let buffer = self.buffer.read(cx);
4463 let newest_selection = self.selections.newest_anchor().clone();
4464 if newest_selection.head().diff_base_anchor.is_some() {
4465 return None;
4466 }
4467 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4468 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4469 if start_buffer != end_buffer {
4470 return None;
4471 }
4472
4473 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4474 cx.background_executor()
4475 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4476 .await;
4477
4478 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4479 let providers = this.code_action_providers.clone();
4480 let tasks = this
4481 .code_action_providers
4482 .iter()
4483 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4484 .collect::<Vec<_>>();
4485 (providers, tasks)
4486 })?;
4487
4488 let mut actions = Vec::new();
4489 for (provider, provider_actions) in
4490 providers.into_iter().zip(future::join_all(tasks).await)
4491 {
4492 if let Some(provider_actions) = provider_actions.log_err() {
4493 actions.extend(provider_actions.into_iter().map(|action| {
4494 AvailableCodeAction {
4495 excerpt_id: newest_selection.start.excerpt_id,
4496 action,
4497 provider: provider.clone(),
4498 }
4499 }));
4500 }
4501 }
4502
4503 this.update(&mut cx, |this, cx| {
4504 this.available_code_actions = if actions.is_empty() {
4505 None
4506 } else {
4507 Some((
4508 Location {
4509 buffer: start_buffer,
4510 range: start..end,
4511 },
4512 actions.into(),
4513 ))
4514 };
4515 cx.notify();
4516 })
4517 }));
4518 None
4519 }
4520
4521 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4522 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4523 self.show_git_blame_inline = false;
4524
4525 self.show_git_blame_inline_delay_task =
4526 Some(cx.spawn_in(window, |this, mut cx| async move {
4527 cx.background_executor().timer(delay).await;
4528
4529 this.update(&mut cx, |this, cx| {
4530 this.show_git_blame_inline = true;
4531 cx.notify();
4532 })
4533 .log_err();
4534 }));
4535 }
4536 }
4537
4538 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4539 if self.pending_rename.is_some() {
4540 return None;
4541 }
4542
4543 let provider = self.semantics_provider.clone()?;
4544 let buffer = self.buffer.read(cx);
4545 let newest_selection = self.selections.newest_anchor().clone();
4546 let cursor_position = newest_selection.head();
4547 let (cursor_buffer, cursor_buffer_position) =
4548 buffer.text_anchor_for_position(cursor_position, cx)?;
4549 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4550 if cursor_buffer != tail_buffer {
4551 return None;
4552 }
4553 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4554 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4555 cx.background_executor()
4556 .timer(Duration::from_millis(debounce))
4557 .await;
4558
4559 let highlights = if let Some(highlights) = cx
4560 .update(|cx| {
4561 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4562 })
4563 .ok()
4564 .flatten()
4565 {
4566 highlights.await.log_err()
4567 } else {
4568 None
4569 };
4570
4571 if let Some(highlights) = highlights {
4572 this.update(&mut cx, |this, cx| {
4573 if this.pending_rename.is_some() {
4574 return;
4575 }
4576
4577 let buffer_id = cursor_position.buffer_id;
4578 let buffer = this.buffer.read(cx);
4579 if !buffer
4580 .text_anchor_for_position(cursor_position, cx)
4581 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4582 {
4583 return;
4584 }
4585
4586 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4587 let mut write_ranges = Vec::new();
4588 let mut read_ranges = Vec::new();
4589 for highlight in highlights {
4590 for (excerpt_id, excerpt_range) in
4591 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4592 {
4593 let start = highlight
4594 .range
4595 .start
4596 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4597 let end = highlight
4598 .range
4599 .end
4600 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4601 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4602 continue;
4603 }
4604
4605 let range = Anchor {
4606 buffer_id,
4607 excerpt_id,
4608 text_anchor: start,
4609 diff_base_anchor: None,
4610 }..Anchor {
4611 buffer_id,
4612 excerpt_id,
4613 text_anchor: end,
4614 diff_base_anchor: None,
4615 };
4616 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4617 write_ranges.push(range);
4618 } else {
4619 read_ranges.push(range);
4620 }
4621 }
4622 }
4623
4624 this.highlight_background::<DocumentHighlightRead>(
4625 &read_ranges,
4626 |theme| theme.editor_document_highlight_read_background,
4627 cx,
4628 );
4629 this.highlight_background::<DocumentHighlightWrite>(
4630 &write_ranges,
4631 |theme| theme.editor_document_highlight_write_background,
4632 cx,
4633 );
4634 cx.notify();
4635 })
4636 .log_err();
4637 }
4638 }));
4639 None
4640 }
4641
4642 pub fn refresh_inline_completion(
4643 &mut self,
4644 debounce: bool,
4645 user_requested: bool,
4646 window: &mut Window,
4647 cx: &mut Context<Self>,
4648 ) -> Option<()> {
4649 let provider = self.inline_completion_provider()?;
4650 let cursor = self.selections.newest_anchor().head();
4651 let (buffer, cursor_buffer_position) =
4652 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4653
4654 if !user_requested
4655 && (!self.enable_inline_completions
4656 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4657 || !self.is_focused(window)
4658 || buffer.read(cx).is_empty())
4659 {
4660 self.discard_inline_completion(false, cx);
4661 return None;
4662 }
4663
4664 self.update_visible_inline_completion(window, cx);
4665 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4666 Some(())
4667 }
4668
4669 fn cycle_inline_completion(
4670 &mut self,
4671 direction: Direction,
4672 window: &mut Window,
4673 cx: &mut Context<Self>,
4674 ) -> Option<()> {
4675 let provider = self.inline_completion_provider()?;
4676 let cursor = self.selections.newest_anchor().head();
4677 let (buffer, cursor_buffer_position) =
4678 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4679 if !self.enable_inline_completions
4680 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4681 {
4682 return None;
4683 }
4684
4685 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4686 self.update_visible_inline_completion(window, cx);
4687
4688 Some(())
4689 }
4690
4691 pub fn show_inline_completion(
4692 &mut self,
4693 _: &ShowInlineCompletion,
4694 window: &mut Window,
4695 cx: &mut Context<Self>,
4696 ) {
4697 if !self.has_active_inline_completion() {
4698 self.refresh_inline_completion(false, true, window, cx);
4699 return;
4700 }
4701
4702 self.update_visible_inline_completion(window, cx);
4703 }
4704
4705 pub fn display_cursor_names(
4706 &mut self,
4707 _: &DisplayCursorNames,
4708 window: &mut Window,
4709 cx: &mut Context<Self>,
4710 ) {
4711 self.show_cursor_names(window, cx);
4712 }
4713
4714 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4715 self.show_cursor_names = true;
4716 cx.notify();
4717 cx.spawn_in(window, |this, mut cx| async move {
4718 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4719 this.update(&mut cx, |this, cx| {
4720 this.show_cursor_names = false;
4721 cx.notify()
4722 })
4723 .ok()
4724 })
4725 .detach();
4726 }
4727
4728 pub fn next_inline_completion(
4729 &mut self,
4730 _: &NextInlineCompletion,
4731 window: &mut Window,
4732 cx: &mut Context<Self>,
4733 ) {
4734 if self.has_active_inline_completion() {
4735 self.cycle_inline_completion(Direction::Next, window, cx);
4736 } else {
4737 let is_copilot_disabled = self
4738 .refresh_inline_completion(false, true, window, cx)
4739 .is_none();
4740 if is_copilot_disabled {
4741 cx.propagate();
4742 }
4743 }
4744 }
4745
4746 pub fn previous_inline_completion(
4747 &mut self,
4748 _: &PreviousInlineCompletion,
4749 window: &mut Window,
4750 cx: &mut Context<Self>,
4751 ) {
4752 if self.has_active_inline_completion() {
4753 self.cycle_inline_completion(Direction::Prev, window, cx);
4754 } else {
4755 let is_copilot_disabled = self
4756 .refresh_inline_completion(false, true, window, cx)
4757 .is_none();
4758 if is_copilot_disabled {
4759 cx.propagate();
4760 }
4761 }
4762 }
4763
4764 pub fn accept_inline_completion(
4765 &mut self,
4766 _: &AcceptInlineCompletion,
4767 window: &mut Window,
4768 cx: &mut Context<Self>,
4769 ) {
4770 let buffer = self.buffer.read(cx);
4771 let snapshot = buffer.snapshot(cx);
4772 let selection = self.selections.newest_adjusted(cx);
4773 let cursor = selection.head();
4774 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
4775 let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
4776 if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
4777 {
4778 if cursor.column < suggested_indent.len
4779 && cursor.column <= current_indent.len
4780 && current_indent.len <= suggested_indent.len
4781 {
4782 self.tab(&Default::default(), window, cx);
4783 return;
4784 }
4785 }
4786
4787 if self.show_inline_completions_in_menu(cx) {
4788 self.hide_context_menu(window, cx);
4789 }
4790
4791 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4792 return;
4793 };
4794
4795 self.report_inline_completion_event(true, cx);
4796
4797 match &active_inline_completion.completion {
4798 InlineCompletion::Move { target, .. } => {
4799 let target = *target;
4800 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
4801 selections.select_anchor_ranges([target..target]);
4802 });
4803 }
4804 InlineCompletion::Edit { edits, .. } => {
4805 if let Some(provider) = self.inline_completion_provider() {
4806 provider.accept(cx);
4807 }
4808
4809 let snapshot = self.buffer.read(cx).snapshot(cx);
4810 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4811
4812 self.buffer.update(cx, |buffer, cx| {
4813 buffer.edit(edits.iter().cloned(), None, cx)
4814 });
4815
4816 self.change_selections(None, window, cx, |s| {
4817 s.select_anchor_ranges([last_edit_end..last_edit_end])
4818 });
4819
4820 self.update_visible_inline_completion(window, cx);
4821 if self.active_inline_completion.is_none() {
4822 self.refresh_inline_completion(true, true, window, cx);
4823 }
4824
4825 cx.notify();
4826 }
4827 }
4828 }
4829
4830 pub fn accept_partial_inline_completion(
4831 &mut self,
4832 _: &AcceptPartialInlineCompletion,
4833 window: &mut Window,
4834 cx: &mut Context<Self>,
4835 ) {
4836 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4837 return;
4838 };
4839 if self.selections.count() != 1 {
4840 return;
4841 }
4842
4843 self.report_inline_completion_event(true, cx);
4844
4845 match &active_inline_completion.completion {
4846 InlineCompletion::Move { target, .. } => {
4847 let target = *target;
4848 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
4849 selections.select_anchor_ranges([target..target]);
4850 });
4851 }
4852 InlineCompletion::Edit { edits, .. } => {
4853 // Find an insertion that starts at the cursor position.
4854 let snapshot = self.buffer.read(cx).snapshot(cx);
4855 let cursor_offset = self.selections.newest::<usize>(cx).head();
4856 let insertion = edits.iter().find_map(|(range, text)| {
4857 let range = range.to_offset(&snapshot);
4858 if range.is_empty() && range.start == cursor_offset {
4859 Some(text)
4860 } else {
4861 None
4862 }
4863 });
4864
4865 if let Some(text) = insertion {
4866 let mut partial_completion = text
4867 .chars()
4868 .by_ref()
4869 .take_while(|c| c.is_alphabetic())
4870 .collect::<String>();
4871 if partial_completion.is_empty() {
4872 partial_completion = text
4873 .chars()
4874 .by_ref()
4875 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4876 .collect::<String>();
4877 }
4878
4879 cx.emit(EditorEvent::InputHandled {
4880 utf16_range_to_replace: None,
4881 text: partial_completion.clone().into(),
4882 });
4883
4884 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
4885
4886 self.refresh_inline_completion(true, true, window, cx);
4887 cx.notify();
4888 } else {
4889 self.accept_inline_completion(&Default::default(), window, cx);
4890 }
4891 }
4892 }
4893 }
4894
4895 fn discard_inline_completion(
4896 &mut self,
4897 should_report_inline_completion_event: bool,
4898 cx: &mut Context<Self>,
4899 ) -> bool {
4900 if should_report_inline_completion_event {
4901 self.report_inline_completion_event(false, cx);
4902 }
4903
4904 if let Some(provider) = self.inline_completion_provider() {
4905 provider.discard(cx);
4906 }
4907
4908 self.take_active_inline_completion(cx)
4909 }
4910
4911 fn report_inline_completion_event(&self, accepted: bool, cx: &App) {
4912 let Some(provider) = self.inline_completion_provider() else {
4913 return;
4914 };
4915
4916 let Some((_, buffer, _)) = self
4917 .buffer
4918 .read(cx)
4919 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4920 else {
4921 return;
4922 };
4923
4924 let extension = buffer
4925 .read(cx)
4926 .file()
4927 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4928
4929 let event_type = match accepted {
4930 true => "Edit Prediction Accepted",
4931 false => "Edit Prediction Discarded",
4932 };
4933 telemetry::event!(
4934 event_type,
4935 provider = provider.name(),
4936 suggestion_accepted = accepted,
4937 file_extension = extension,
4938 );
4939 }
4940
4941 pub fn has_active_inline_completion(&self) -> bool {
4942 self.active_inline_completion.is_some()
4943 }
4944
4945 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
4946 let Some(active_inline_completion) = self.active_inline_completion.take() else {
4947 return false;
4948 };
4949
4950 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
4951 self.clear_highlights::<InlineCompletionHighlight>(cx);
4952 self.stale_inline_completion_in_menu = Some(active_inline_completion);
4953 true
4954 }
4955
4956 pub fn is_previewing_inline_completion(&self) -> bool {
4957 matches!(
4958 self.context_menu.borrow().as_ref(),
4959 Some(CodeContextMenu::Completions(menu)) if !menu.is_empty() && menu.previewing_inline_completion
4960 )
4961 }
4962
4963 fn update_inline_completion_preview(
4964 &mut self,
4965 modifiers: &Modifiers,
4966 window: &mut Window,
4967 cx: &mut Context<Self>,
4968 ) {
4969 // Moves jump directly with a preview step
4970
4971 if self
4972 .active_inline_completion
4973 .as_ref()
4974 .map_or(true, |c| c.is_move())
4975 {
4976 cx.notify();
4977 return;
4978 }
4979
4980 if !self.show_inline_completions_in_menu(cx) {
4981 return;
4982 }
4983
4984 let mut menu_borrow = self.context_menu.borrow_mut();
4985
4986 let Some(CodeContextMenu::Completions(completions_menu)) = menu_borrow.as_mut() else {
4987 return;
4988 };
4989
4990 if completions_menu.is_empty()
4991 || completions_menu.previewing_inline_completion == modifiers.alt
4992 {
4993 return;
4994 }
4995
4996 completions_menu.set_previewing_inline_completion(modifiers.alt);
4997 drop(menu_borrow);
4998 self.update_visible_inline_completion(window, cx);
4999 }
5000
5001 fn update_visible_inline_completion(
5002 &mut self,
5003 _window: &mut Window,
5004 cx: &mut Context<Self>,
5005 ) -> Option<()> {
5006 let selection = self.selections.newest_anchor();
5007 let cursor = selection.head();
5008 let multibuffer = self.buffer.read(cx).snapshot(cx);
5009 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5010 let excerpt_id = cursor.excerpt_id;
5011
5012 let show_in_menu = self.show_inline_completions_in_menu(cx);
5013 let completions_menu_has_precedence = !show_in_menu
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 snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5063
5064 let mut inlay_ids = Vec::new();
5065 let invalidation_row_range;
5066 let move_invalidation_row_range = if cursor_row < edit_start_row {
5067 Some(cursor_row..edit_end_row)
5068 } else if cursor_row > edit_end_row {
5069 Some(edit_start_row..cursor_row)
5070 } else {
5071 None
5072 };
5073 let completion = if let Some(move_invalidation_row_range) = move_invalidation_row_range {
5074 invalidation_row_range = move_invalidation_row_range;
5075 let target = first_edit_start;
5076 let target_point = text::ToPoint::to_point(&target.text_anchor, &snapshot);
5077 // TODO: Base this off of TreeSitter or word boundaries?
5078 let target_excerpt_begin = snapshot.anchor_before(snapshot.clip_point(
5079 Point::new(target_point.row, target_point.column.saturating_sub(20)),
5080 Bias::Left,
5081 ));
5082 let target_excerpt_end = snapshot.anchor_after(snapshot.clip_point(
5083 Point::new(target_point.row, target_point.column + 20),
5084 Bias::Right,
5085 ));
5086 let range_around_target = target_excerpt_begin..target_excerpt_end;
5087 InlineCompletion::Move {
5088 target,
5089 range_around_target,
5090 snapshot,
5091 }
5092 } else {
5093 if !show_in_menu || !self.has_active_completions_menu() {
5094 if edits
5095 .iter()
5096 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5097 {
5098 let mut inlays = Vec::new();
5099 for (range, new_text) in &edits {
5100 let inlay = Inlay::inline_completion(
5101 post_inc(&mut self.next_inlay_id),
5102 range.start,
5103 new_text.as_str(),
5104 );
5105 inlay_ids.push(inlay.id);
5106 inlays.push(inlay);
5107 }
5108
5109 self.splice_inlays(&[], inlays, cx);
5110 } else {
5111 let background_color = cx.theme().status().deleted_background;
5112 self.highlight_text::<InlineCompletionHighlight>(
5113 edits.iter().map(|(range, _)| range.clone()).collect(),
5114 HighlightStyle {
5115 background_color: Some(background_color),
5116 ..Default::default()
5117 },
5118 cx,
5119 );
5120 }
5121 }
5122
5123 invalidation_row_range = edit_start_row..edit_end_row;
5124
5125 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5126 if provider.show_tab_accept_marker() {
5127 EditDisplayMode::TabAccept(self.is_previewing_inline_completion())
5128 } else {
5129 EditDisplayMode::Inline
5130 }
5131 } else {
5132 EditDisplayMode::DiffPopover
5133 };
5134
5135 InlineCompletion::Edit {
5136 edits,
5137 edit_preview: inline_completion.edit_preview,
5138 display_mode,
5139 snapshot,
5140 }
5141 };
5142
5143 let invalidation_range = multibuffer
5144 .anchor_before(Point::new(invalidation_row_range.start, 0))
5145 ..multibuffer.anchor_after(Point::new(
5146 invalidation_row_range.end,
5147 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5148 ));
5149
5150 self.stale_inline_completion_in_menu = None;
5151 self.active_inline_completion = Some(InlineCompletionState {
5152 inlay_ids,
5153 completion,
5154 invalidation_range,
5155 });
5156
5157 cx.notify();
5158
5159 Some(())
5160 }
5161
5162 pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5163 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5164 }
5165
5166 fn show_inline_completions_in_menu(&self, cx: &App) -> bool {
5167 let by_provider = matches!(
5168 self.menu_inline_completions_policy,
5169 MenuInlineCompletionsPolicy::ByProvider
5170 );
5171
5172 by_provider
5173 && EditorSettings::get_global(cx).show_inline_completions_in_menu
5174 && self
5175 .inline_completion_provider()
5176 .map_or(false, |provider| provider.show_completions_in_menu())
5177 }
5178
5179 fn render_code_actions_indicator(
5180 &self,
5181 _style: &EditorStyle,
5182 row: DisplayRow,
5183 is_active: bool,
5184 cx: &mut Context<Self>,
5185 ) -> Option<IconButton> {
5186 if self.available_code_actions.is_some() {
5187 Some(
5188 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5189 .shape(ui::IconButtonShape::Square)
5190 .icon_size(IconSize::XSmall)
5191 .icon_color(Color::Muted)
5192 .toggle_state(is_active)
5193 .tooltip({
5194 let focus_handle = self.focus_handle.clone();
5195 move |window, cx| {
5196 Tooltip::for_action_in(
5197 "Toggle Code Actions",
5198 &ToggleCodeActions {
5199 deployed_from_indicator: None,
5200 },
5201 &focus_handle,
5202 window,
5203 cx,
5204 )
5205 }
5206 })
5207 .on_click(cx.listener(move |editor, _e, window, cx| {
5208 window.focus(&editor.focus_handle(cx));
5209 editor.toggle_code_actions(
5210 &ToggleCodeActions {
5211 deployed_from_indicator: Some(row),
5212 },
5213 window,
5214 cx,
5215 );
5216 })),
5217 )
5218 } else {
5219 None
5220 }
5221 }
5222
5223 fn clear_tasks(&mut self) {
5224 self.tasks.clear()
5225 }
5226
5227 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5228 if self.tasks.insert(key, value).is_some() {
5229 // This case should hopefully be rare, but just in case...
5230 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5231 }
5232 }
5233
5234 fn build_tasks_context(
5235 project: &Entity<Project>,
5236 buffer: &Entity<Buffer>,
5237 buffer_row: u32,
5238 tasks: &Arc<RunnableTasks>,
5239 cx: &mut Context<Self>,
5240 ) -> Task<Option<task::TaskContext>> {
5241 let position = Point::new(buffer_row, tasks.column);
5242 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5243 let location = Location {
5244 buffer: buffer.clone(),
5245 range: range_start..range_start,
5246 };
5247 // Fill in the environmental variables from the tree-sitter captures
5248 let mut captured_task_variables = TaskVariables::default();
5249 for (capture_name, value) in tasks.extra_variables.clone() {
5250 captured_task_variables.insert(
5251 task::VariableName::Custom(capture_name.into()),
5252 value.clone(),
5253 );
5254 }
5255 project.update(cx, |project, cx| {
5256 project.task_store().update(cx, |task_store, cx| {
5257 task_store.task_context_for_location(captured_task_variables, location, cx)
5258 })
5259 })
5260 }
5261
5262 pub fn spawn_nearest_task(
5263 &mut self,
5264 action: &SpawnNearestTask,
5265 window: &mut Window,
5266 cx: &mut Context<Self>,
5267 ) {
5268 let Some((workspace, _)) = self.workspace.clone() else {
5269 return;
5270 };
5271 let Some(project) = self.project.clone() else {
5272 return;
5273 };
5274
5275 // Try to find a closest, enclosing node using tree-sitter that has a
5276 // task
5277 let Some((buffer, buffer_row, tasks)) = self
5278 .find_enclosing_node_task(cx)
5279 // Or find the task that's closest in row-distance.
5280 .or_else(|| self.find_closest_task(cx))
5281 else {
5282 return;
5283 };
5284
5285 let reveal_strategy = action.reveal;
5286 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5287 cx.spawn_in(window, |_, mut cx| async move {
5288 let context = task_context.await?;
5289 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5290
5291 let resolved = resolved_task.resolved.as_mut()?;
5292 resolved.reveal = reveal_strategy;
5293
5294 workspace
5295 .update(&mut cx, |workspace, cx| {
5296 workspace::tasks::schedule_resolved_task(
5297 workspace,
5298 task_source_kind,
5299 resolved_task,
5300 false,
5301 cx,
5302 );
5303 })
5304 .ok()
5305 })
5306 .detach();
5307 }
5308
5309 fn find_closest_task(
5310 &mut self,
5311 cx: &mut Context<Self>,
5312 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5313 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5314
5315 let ((buffer_id, row), tasks) = self
5316 .tasks
5317 .iter()
5318 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5319
5320 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5321 let tasks = Arc::new(tasks.to_owned());
5322 Some((buffer, *row, tasks))
5323 }
5324
5325 fn find_enclosing_node_task(
5326 &mut self,
5327 cx: &mut Context<Self>,
5328 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5329 let snapshot = self.buffer.read(cx).snapshot(cx);
5330 let offset = self.selections.newest::<usize>(cx).head();
5331 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5332 let buffer_id = excerpt.buffer().remote_id();
5333
5334 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5335 let mut cursor = layer.node().walk();
5336
5337 while cursor.goto_first_child_for_byte(offset).is_some() {
5338 if cursor.node().end_byte() == offset {
5339 cursor.goto_next_sibling();
5340 }
5341 }
5342
5343 // Ascend to the smallest ancestor that contains the range and has a task.
5344 loop {
5345 let node = cursor.node();
5346 let node_range = node.byte_range();
5347 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5348
5349 // Check if this node contains our offset
5350 if node_range.start <= offset && node_range.end >= offset {
5351 // If it contains offset, check for task
5352 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5353 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5354 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5355 }
5356 }
5357
5358 if !cursor.goto_parent() {
5359 break;
5360 }
5361 }
5362 None
5363 }
5364
5365 fn render_run_indicator(
5366 &self,
5367 _style: &EditorStyle,
5368 is_active: bool,
5369 row: DisplayRow,
5370 cx: &mut Context<Self>,
5371 ) -> IconButton {
5372 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5373 .shape(ui::IconButtonShape::Square)
5374 .icon_size(IconSize::XSmall)
5375 .icon_color(Color::Muted)
5376 .toggle_state(is_active)
5377 .on_click(cx.listener(move |editor, _e, window, cx| {
5378 window.focus(&editor.focus_handle(cx));
5379 editor.toggle_code_actions(
5380 &ToggleCodeActions {
5381 deployed_from_indicator: Some(row),
5382 },
5383 window,
5384 cx,
5385 );
5386 }))
5387 }
5388
5389 pub fn context_menu_visible(&self) -> bool {
5390 self.context_menu
5391 .borrow()
5392 .as_ref()
5393 .map_or(false, |menu| menu.visible())
5394 }
5395
5396 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5397 self.context_menu
5398 .borrow()
5399 .as_ref()
5400 .map(|menu| menu.origin())
5401 }
5402
5403 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5404 px(32.)
5405 }
5406
5407 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5408 if self.read_only(cx) {
5409 cx.theme().players().read_only()
5410 } else {
5411 self.style.as_ref().unwrap().local_player
5412 }
5413 }
5414
5415 #[allow(clippy::too_many_arguments)]
5416 fn render_edit_prediction_cursor_popover(
5417 &self,
5418 min_width: Pixels,
5419 max_width: Pixels,
5420 cursor_point: Point,
5421 line_layouts: &[LineWithInvisibles],
5422 style: &EditorStyle,
5423 accept_keystroke: &gpui::Keystroke,
5424 window: &Window,
5425 cx: &mut Context<Editor>,
5426 ) -> Option<AnyElement> {
5427 let provider = self.inline_completion_provider.as_ref()?;
5428
5429 if provider.provider.needs_terms_acceptance(cx) {
5430 return Some(
5431 h_flex()
5432 .h(self.edit_prediction_cursor_popover_height())
5433 .min_w(min_width)
5434 .flex_1()
5435 .px_2()
5436 .gap_3()
5437 .elevation_2(cx)
5438 .hover(|style| style.bg(cx.theme().colors().element_hover))
5439 .id("accept-terms")
5440 .cursor_pointer()
5441 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5442 .on_click(cx.listener(|this, _event, window, cx| {
5443 cx.stop_propagation();
5444 this.toggle_zed_predict_onboarding(window, cx)
5445 }))
5446 .child(
5447 h_flex()
5448 .w_full()
5449 .gap_2()
5450 .child(Icon::new(IconName::ZedPredict))
5451 .child(Label::new("Accept Terms of Service"))
5452 .child(div().w_full())
5453 .child(Icon::new(IconName::ArrowUpRight))
5454 .into_any_element(),
5455 )
5456 .into_any(),
5457 );
5458 }
5459
5460 let is_refreshing = provider.provider.is_refreshing(cx);
5461
5462 fn pending_completion_container() -> Div {
5463 h_flex()
5464 .flex_1()
5465 .gap_3()
5466 .child(Icon::new(IconName::ZedPredict))
5467 }
5468
5469 let completion = match &self.active_inline_completion {
5470 Some(completion) => self.render_edit_prediction_cursor_popover_preview(
5471 completion,
5472 cursor_point,
5473 line_layouts,
5474 style,
5475 cx,
5476 )?,
5477
5478 None if is_refreshing => match &self.stale_inline_completion_in_menu {
5479 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
5480 stale_completion,
5481 cursor_point,
5482 line_layouts,
5483 style,
5484 cx,
5485 )?,
5486
5487 None => {
5488 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
5489 }
5490 },
5491
5492 None => pending_completion_container().child(Label::new("No Prediction")),
5493 };
5494
5495 let buffer_font = theme::ThemeSettings::get_global(cx).buffer_font.clone();
5496 let completion = completion.font(buffer_font.clone());
5497
5498 let completion = if is_refreshing {
5499 completion
5500 .with_animation(
5501 "loading-completion",
5502 Animation::new(Duration::from_secs(2))
5503 .repeat()
5504 .with_easing(pulsating_between(0.4, 0.8)),
5505 |label, delta| label.opacity(delta),
5506 )
5507 .into_any_element()
5508 } else {
5509 completion.into_any_element()
5510 };
5511
5512 let has_completion = self.active_inline_completion.is_some();
5513
5514 let is_move = self
5515 .active_inline_completion
5516 .as_ref()
5517 .map_or(false, |c| c.is_move());
5518
5519 Some(
5520 h_flex()
5521 .h(self.edit_prediction_cursor_popover_height())
5522 .min_w(min_width)
5523 .max_w(max_width)
5524 .flex_1()
5525 .px_2()
5526 .gap_3()
5527 .elevation_2(cx)
5528 .child(completion)
5529 .child(
5530 h_flex()
5531 .border_l_1()
5532 .border_color(cx.theme().colors().border_variant)
5533 .pl_2()
5534 .child(
5535 h_flex()
5536 .font(buffer_font.clone())
5537 .p_1()
5538 .rounded_sm()
5539 .children(ui::render_modifiers(
5540 &accept_keystroke.modifiers,
5541 PlatformStyle::platform(),
5542 if window.modifiers() == accept_keystroke.modifiers {
5543 Some(Color::Accent)
5544 } else {
5545 None
5546 },
5547 !is_move,
5548 )),
5549 )
5550 .opacity(if has_completion { 1.0 } else { 0.1 })
5551 .child(if is_move {
5552 div()
5553 .child(ui::Key::new(&accept_keystroke.key, None))
5554 .font(buffer_font.clone())
5555 .into_any()
5556 } else {
5557 Label::new("Preview").color(Color::Muted).into_any_element()
5558 }),
5559 )
5560 .into_any(),
5561 )
5562 }
5563
5564 fn render_edit_prediction_cursor_popover_preview(
5565 &self,
5566 completion: &InlineCompletionState,
5567 cursor_point: Point,
5568 line_layouts: &[LineWithInvisibles],
5569 style: &EditorStyle,
5570 cx: &mut Context<Editor>,
5571 ) -> Option<Div> {
5572 use text::ToPoint as _;
5573
5574 fn render_relative_row_jump(
5575 prefix: impl Into<String>,
5576 current_row: u32,
5577 target_row: u32,
5578 ) -> Div {
5579 let (row_diff, arrow) = if target_row < current_row {
5580 (current_row - target_row, IconName::ArrowUp)
5581 } else {
5582 (target_row - current_row, IconName::ArrowDown)
5583 };
5584
5585 h_flex()
5586 .child(
5587 Label::new(format!("{}{}", prefix.into(), row_diff))
5588 .color(Color::Muted)
5589 .size(LabelSize::Small),
5590 )
5591 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
5592 }
5593
5594 match &completion.completion {
5595 InlineCompletion::Edit {
5596 edits,
5597 edit_preview,
5598 snapshot,
5599 display_mode: _,
5600 } => {
5601 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
5602
5603 let highlighted_edits = crate::inline_completion_edit_text(
5604 &snapshot,
5605 &edits,
5606 edit_preview.as_ref()?,
5607 true,
5608 cx,
5609 );
5610
5611 let len_total = highlighted_edits.text.len();
5612 let first_line = &highlighted_edits.text
5613 [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
5614 let first_line_len = first_line.len();
5615
5616 let first_highlight_start = highlighted_edits
5617 .highlights
5618 .first()
5619 .map_or(0, |(range, _)| range.start);
5620 let drop_prefix_len = first_line
5621 .char_indices()
5622 .find(|(_, c)| !c.is_whitespace())
5623 .map_or(first_highlight_start, |(ix, _)| {
5624 ix.min(first_highlight_start)
5625 });
5626
5627 let preview_text = &first_line[drop_prefix_len..];
5628 let preview_len = preview_text.len();
5629 let highlights = highlighted_edits
5630 .highlights
5631 .into_iter()
5632 .take_until(|(range, _)| range.start > first_line_len)
5633 .map(|(range, style)| {
5634 (
5635 range.start - drop_prefix_len
5636 ..(range.end - drop_prefix_len).min(preview_len),
5637 style,
5638 )
5639 });
5640
5641 let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
5642 .with_highlights(&style.text, highlights);
5643
5644 let preview = h_flex()
5645 .gap_1()
5646 .child(styled_text)
5647 .when(len_total > first_line_len, |parent| parent.child("…"));
5648
5649 let left = if first_edit_row != cursor_point.row {
5650 render_relative_row_jump("", cursor_point.row, first_edit_row)
5651 .into_any_element()
5652 } else {
5653 Icon::new(IconName::ZedPredict).into_any_element()
5654 };
5655
5656 Some(h_flex().flex_1().gap_3().child(left).child(preview))
5657 }
5658
5659 InlineCompletion::Move {
5660 target,
5661 range_around_target,
5662 snapshot,
5663 } => {
5664 let highlighted_text = snapshot.highlighted_text_for_range(
5665 range_around_target.clone(),
5666 None,
5667 &style.syntax,
5668 );
5669 let cursor_color = self.current_user_player_color(cx).cursor;
5670
5671 let start_point = range_around_target.start.to_point(&snapshot);
5672 let end_point = range_around_target.end.to_point(&snapshot);
5673 let target_point = target.text_anchor.to_point(&snapshot);
5674
5675 let cursor_relative_position =
5676 line_layouts.get(start_point.row as usize).map(|line| {
5677 let start_column_x = line.x_for_index(start_point.column as usize);
5678 let target_column_x = line.x_for_index(target_point.column as usize);
5679 target_column_x - start_column_x
5680 });
5681
5682 let fade_before = start_point.column > 0;
5683 let fade_after = end_point.column < snapshot.line_len(end_point.row);
5684
5685 let background = cx.theme().colors().elevated_surface_background;
5686
5687 Some(
5688 h_flex()
5689 .gap_3()
5690 .flex_1()
5691 .child(render_relative_row_jump(
5692 "Jump ",
5693 cursor_point.row,
5694 target.text_anchor.to_point(&snapshot).row,
5695 ))
5696 .when(!highlighted_text.text.is_empty(), |parent| {
5697 parent.child(
5698 h_flex()
5699 .relative()
5700 .child(highlighted_text.to_styled_text(&style.text))
5701 .when(fade_before, |parent| {
5702 parent.child(
5703 div().absolute().top_0().left_0().w_4().h_full().bg(
5704 linear_gradient(
5705 90.,
5706 linear_color_stop(background, 0.),
5707 linear_color_stop(background.opacity(0.), 1.),
5708 ),
5709 ),
5710 )
5711 })
5712 .when(fade_after, |parent| {
5713 parent.child(
5714 div().absolute().top_0().right_0().w_4().h_full().bg(
5715 linear_gradient(
5716 -90.,
5717 linear_color_stop(background, 0.),
5718 linear_color_stop(background.opacity(0.), 1.),
5719 ),
5720 ),
5721 )
5722 })
5723 .when_some(cursor_relative_position, |parent, position| {
5724 parent.child(
5725 div()
5726 .w(px(2.))
5727 .h_full()
5728 .bg(cursor_color)
5729 .absolute()
5730 .top_0()
5731 .left(position),
5732 )
5733 }),
5734 )
5735 }),
5736 )
5737 }
5738 }
5739 }
5740
5741 fn render_context_menu(
5742 &self,
5743 style: &EditorStyle,
5744 max_height_in_lines: u32,
5745 y_flipped: bool,
5746 window: &mut Window,
5747 cx: &mut Context<Editor>,
5748 ) -> Option<AnyElement> {
5749 let menu = self.context_menu.borrow();
5750 let menu = menu.as_ref()?;
5751 if !menu.visible() {
5752 return None;
5753 };
5754 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
5755 }
5756
5757 fn render_context_menu_aside(
5758 &self,
5759 style: &EditorStyle,
5760 max_size: Size<Pixels>,
5761 cx: &mut Context<Editor>,
5762 ) -> Option<AnyElement> {
5763 self.context_menu.borrow().as_ref().and_then(|menu| {
5764 if menu.visible() {
5765 menu.render_aside(
5766 style,
5767 max_size,
5768 self.workspace.as_ref().map(|(w, _)| w.clone()),
5769 cx,
5770 )
5771 } else {
5772 None
5773 }
5774 })
5775 }
5776
5777 fn hide_context_menu(
5778 &mut self,
5779 window: &mut Window,
5780 cx: &mut Context<Self>,
5781 ) -> Option<CodeContextMenu> {
5782 cx.notify();
5783 self.completion_tasks.clear();
5784 let context_menu = self.context_menu.borrow_mut().take();
5785 self.stale_inline_completion_in_menu.take();
5786 if context_menu.is_some() {
5787 self.update_visible_inline_completion(window, cx);
5788 }
5789 context_menu
5790 }
5791
5792 fn show_snippet_choices(
5793 &mut self,
5794 choices: &Vec<String>,
5795 selection: Range<Anchor>,
5796 cx: &mut Context<Self>,
5797 ) {
5798 if selection.start.buffer_id.is_none() {
5799 return;
5800 }
5801 let buffer_id = selection.start.buffer_id.unwrap();
5802 let buffer = self.buffer().read(cx).buffer(buffer_id);
5803 let id = post_inc(&mut self.next_completion_id);
5804
5805 if let Some(buffer) = buffer {
5806 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5807 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5808 ));
5809 }
5810 }
5811
5812 pub fn insert_snippet(
5813 &mut self,
5814 insertion_ranges: &[Range<usize>],
5815 snippet: Snippet,
5816 window: &mut Window,
5817 cx: &mut Context<Self>,
5818 ) -> Result<()> {
5819 struct Tabstop<T> {
5820 is_end_tabstop: bool,
5821 ranges: Vec<Range<T>>,
5822 choices: Option<Vec<String>>,
5823 }
5824
5825 let tabstops = self.buffer.update(cx, |buffer, cx| {
5826 let snippet_text: Arc<str> = snippet.text.clone().into();
5827 buffer.edit(
5828 insertion_ranges
5829 .iter()
5830 .cloned()
5831 .map(|range| (range, snippet_text.clone())),
5832 Some(AutoindentMode::EachLine),
5833 cx,
5834 );
5835
5836 let snapshot = &*buffer.read(cx);
5837 let snippet = &snippet;
5838 snippet
5839 .tabstops
5840 .iter()
5841 .map(|tabstop| {
5842 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5843 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5844 });
5845 let mut tabstop_ranges = tabstop
5846 .ranges
5847 .iter()
5848 .flat_map(|tabstop_range| {
5849 let mut delta = 0_isize;
5850 insertion_ranges.iter().map(move |insertion_range| {
5851 let insertion_start = insertion_range.start as isize + delta;
5852 delta +=
5853 snippet.text.len() as isize - insertion_range.len() as isize;
5854
5855 let start = ((insertion_start + tabstop_range.start) as usize)
5856 .min(snapshot.len());
5857 let end = ((insertion_start + tabstop_range.end) as usize)
5858 .min(snapshot.len());
5859 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5860 })
5861 })
5862 .collect::<Vec<_>>();
5863 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5864
5865 Tabstop {
5866 is_end_tabstop,
5867 ranges: tabstop_ranges,
5868 choices: tabstop.choices.clone(),
5869 }
5870 })
5871 .collect::<Vec<_>>()
5872 });
5873 if let Some(tabstop) = tabstops.first() {
5874 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
5875 s.select_ranges(tabstop.ranges.iter().cloned());
5876 });
5877
5878 if let Some(choices) = &tabstop.choices {
5879 if let Some(selection) = tabstop.ranges.first() {
5880 self.show_snippet_choices(choices, selection.clone(), cx)
5881 }
5882 }
5883
5884 // If we're already at the last tabstop and it's at the end of the snippet,
5885 // we're done, we don't need to keep the state around.
5886 if !tabstop.is_end_tabstop {
5887 let choices = tabstops
5888 .iter()
5889 .map(|tabstop| tabstop.choices.clone())
5890 .collect();
5891
5892 let ranges = tabstops
5893 .into_iter()
5894 .map(|tabstop| tabstop.ranges)
5895 .collect::<Vec<_>>();
5896
5897 self.snippet_stack.push(SnippetState {
5898 active_index: 0,
5899 ranges,
5900 choices,
5901 });
5902 }
5903
5904 // Check whether the just-entered snippet ends with an auto-closable bracket.
5905 if self.autoclose_regions.is_empty() {
5906 let snapshot = self.buffer.read(cx).snapshot(cx);
5907 for selection in &mut self.selections.all::<Point>(cx) {
5908 let selection_head = selection.head();
5909 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5910 continue;
5911 };
5912
5913 let mut bracket_pair = None;
5914 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5915 let prev_chars = snapshot
5916 .reversed_chars_at(selection_head)
5917 .collect::<String>();
5918 for (pair, enabled) in scope.brackets() {
5919 if enabled
5920 && pair.close
5921 && prev_chars.starts_with(pair.start.as_str())
5922 && next_chars.starts_with(pair.end.as_str())
5923 {
5924 bracket_pair = Some(pair.clone());
5925 break;
5926 }
5927 }
5928 if let Some(pair) = bracket_pair {
5929 let start = snapshot.anchor_after(selection_head);
5930 let end = snapshot.anchor_after(selection_head);
5931 self.autoclose_regions.push(AutocloseRegion {
5932 selection_id: selection.id,
5933 range: start..end,
5934 pair,
5935 });
5936 }
5937 }
5938 }
5939 }
5940 Ok(())
5941 }
5942
5943 pub fn move_to_next_snippet_tabstop(
5944 &mut self,
5945 window: &mut Window,
5946 cx: &mut Context<Self>,
5947 ) -> bool {
5948 self.move_to_snippet_tabstop(Bias::Right, window, cx)
5949 }
5950
5951 pub fn move_to_prev_snippet_tabstop(
5952 &mut self,
5953 window: &mut Window,
5954 cx: &mut Context<Self>,
5955 ) -> bool {
5956 self.move_to_snippet_tabstop(Bias::Left, window, cx)
5957 }
5958
5959 pub fn move_to_snippet_tabstop(
5960 &mut self,
5961 bias: Bias,
5962 window: &mut Window,
5963 cx: &mut Context<Self>,
5964 ) -> bool {
5965 if let Some(mut snippet) = self.snippet_stack.pop() {
5966 match bias {
5967 Bias::Left => {
5968 if snippet.active_index > 0 {
5969 snippet.active_index -= 1;
5970 } else {
5971 self.snippet_stack.push(snippet);
5972 return false;
5973 }
5974 }
5975 Bias::Right => {
5976 if snippet.active_index + 1 < snippet.ranges.len() {
5977 snippet.active_index += 1;
5978 } else {
5979 self.snippet_stack.push(snippet);
5980 return false;
5981 }
5982 }
5983 }
5984 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5985 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
5986 s.select_anchor_ranges(current_ranges.iter().cloned())
5987 });
5988
5989 if let Some(choices) = &snippet.choices[snippet.active_index] {
5990 if let Some(selection) = current_ranges.first() {
5991 self.show_snippet_choices(&choices, selection.clone(), cx);
5992 }
5993 }
5994
5995 // If snippet state is not at the last tabstop, push it back on the stack
5996 if snippet.active_index + 1 < snippet.ranges.len() {
5997 self.snippet_stack.push(snippet);
5998 }
5999 return true;
6000 }
6001 }
6002
6003 false
6004 }
6005
6006 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6007 self.transact(window, cx, |this, window, cx| {
6008 this.select_all(&SelectAll, window, cx);
6009 this.insert("", window, cx);
6010 });
6011 }
6012
6013 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6014 self.transact(window, cx, |this, window, cx| {
6015 this.select_autoclose_pair(window, cx);
6016 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6017 if !this.linked_edit_ranges.is_empty() {
6018 let selections = this.selections.all::<MultiBufferPoint>(cx);
6019 let snapshot = this.buffer.read(cx).snapshot(cx);
6020
6021 for selection in selections.iter() {
6022 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6023 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6024 if selection_start.buffer_id != selection_end.buffer_id {
6025 continue;
6026 }
6027 if let Some(ranges) =
6028 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6029 {
6030 for (buffer, entries) in ranges {
6031 linked_ranges.entry(buffer).or_default().extend(entries);
6032 }
6033 }
6034 }
6035 }
6036
6037 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6038 if !this.selections.line_mode {
6039 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6040 for selection in &mut selections {
6041 if selection.is_empty() {
6042 let old_head = selection.head();
6043 let mut new_head =
6044 movement::left(&display_map, old_head.to_display_point(&display_map))
6045 .to_point(&display_map);
6046 if let Some((buffer, line_buffer_range)) = display_map
6047 .buffer_snapshot
6048 .buffer_line_for_row(MultiBufferRow(old_head.row))
6049 {
6050 let indent_size =
6051 buffer.indent_size_for_line(line_buffer_range.start.row);
6052 let indent_len = match indent_size.kind {
6053 IndentKind::Space => {
6054 buffer.settings_at(line_buffer_range.start, cx).tab_size
6055 }
6056 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6057 };
6058 if old_head.column <= indent_size.len && old_head.column > 0 {
6059 let indent_len = indent_len.get();
6060 new_head = cmp::min(
6061 new_head,
6062 MultiBufferPoint::new(
6063 old_head.row,
6064 ((old_head.column - 1) / indent_len) * indent_len,
6065 ),
6066 );
6067 }
6068 }
6069
6070 selection.set_head(new_head, SelectionGoal::None);
6071 }
6072 }
6073 }
6074
6075 this.signature_help_state.set_backspace_pressed(true);
6076 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6077 s.select(selections)
6078 });
6079 this.insert("", window, cx);
6080 let empty_str: Arc<str> = Arc::from("");
6081 for (buffer, edits) in linked_ranges {
6082 let snapshot = buffer.read(cx).snapshot();
6083 use text::ToPoint as TP;
6084
6085 let edits = edits
6086 .into_iter()
6087 .map(|range| {
6088 let end_point = TP::to_point(&range.end, &snapshot);
6089 let mut start_point = TP::to_point(&range.start, &snapshot);
6090
6091 if end_point == start_point {
6092 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6093 .saturating_sub(1);
6094 start_point =
6095 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6096 };
6097
6098 (start_point..end_point, empty_str.clone())
6099 })
6100 .sorted_by_key(|(range, _)| range.start)
6101 .collect::<Vec<_>>();
6102 buffer.update(cx, |this, cx| {
6103 this.edit(edits, None, cx);
6104 })
6105 }
6106 this.refresh_inline_completion(true, false, window, cx);
6107 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6108 });
6109 }
6110
6111 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6112 self.transact(window, cx, |this, window, cx| {
6113 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6114 let line_mode = s.line_mode;
6115 s.move_with(|map, selection| {
6116 if selection.is_empty() && !line_mode {
6117 let cursor = movement::right(map, selection.head());
6118 selection.end = cursor;
6119 selection.reversed = true;
6120 selection.goal = SelectionGoal::None;
6121 }
6122 })
6123 });
6124 this.insert("", window, cx);
6125 this.refresh_inline_completion(true, false, window, cx);
6126 });
6127 }
6128
6129 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6130 if self.move_to_prev_snippet_tabstop(window, cx) {
6131 return;
6132 }
6133
6134 self.outdent(&Outdent, window, cx);
6135 }
6136
6137 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6138 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6139 return;
6140 }
6141
6142 let mut selections = self.selections.all_adjusted(cx);
6143 let buffer = self.buffer.read(cx);
6144 let snapshot = buffer.snapshot(cx);
6145 let rows_iter = selections.iter().map(|s| s.head().row);
6146 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6147
6148 let mut edits = Vec::new();
6149 let mut prev_edited_row = 0;
6150 let mut row_delta = 0;
6151 for selection in &mut selections {
6152 if selection.start.row != prev_edited_row {
6153 row_delta = 0;
6154 }
6155 prev_edited_row = selection.end.row;
6156
6157 // If the selection is non-empty, then increase the indentation of the selected lines.
6158 if !selection.is_empty() {
6159 row_delta =
6160 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6161 continue;
6162 }
6163
6164 // If the selection is empty and the cursor is in the leading whitespace before the
6165 // suggested indentation, then auto-indent the line.
6166 let cursor = selection.head();
6167 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6168 if let Some(suggested_indent) =
6169 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6170 {
6171 if cursor.column < suggested_indent.len
6172 && cursor.column <= current_indent.len
6173 && current_indent.len <= suggested_indent.len
6174 {
6175 selection.start = Point::new(cursor.row, suggested_indent.len);
6176 selection.end = selection.start;
6177 if row_delta == 0 {
6178 edits.extend(Buffer::edit_for_indent_size_adjustment(
6179 cursor.row,
6180 current_indent,
6181 suggested_indent,
6182 ));
6183 row_delta = suggested_indent.len - current_indent.len;
6184 }
6185 continue;
6186 }
6187 }
6188
6189 // Otherwise, insert a hard or soft tab.
6190 let settings = buffer.settings_at(cursor, cx);
6191 let tab_size = if settings.hard_tabs {
6192 IndentSize::tab()
6193 } else {
6194 let tab_size = settings.tab_size.get();
6195 let char_column = snapshot
6196 .text_for_range(Point::new(cursor.row, 0)..cursor)
6197 .flat_map(str::chars)
6198 .count()
6199 + row_delta as usize;
6200 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6201 IndentSize::spaces(chars_to_next_tab_stop)
6202 };
6203 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6204 selection.end = selection.start;
6205 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6206 row_delta += tab_size.len;
6207 }
6208
6209 self.transact(window, cx, |this, window, cx| {
6210 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6211 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6212 s.select(selections)
6213 });
6214 this.refresh_inline_completion(true, false, window, cx);
6215 });
6216 }
6217
6218 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6219 if self.read_only(cx) {
6220 return;
6221 }
6222 let mut selections = self.selections.all::<Point>(cx);
6223 let mut prev_edited_row = 0;
6224 let mut row_delta = 0;
6225 let mut edits = Vec::new();
6226 let buffer = self.buffer.read(cx);
6227 let snapshot = buffer.snapshot(cx);
6228 for selection in &mut selections {
6229 if selection.start.row != prev_edited_row {
6230 row_delta = 0;
6231 }
6232 prev_edited_row = selection.end.row;
6233
6234 row_delta =
6235 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6236 }
6237
6238 self.transact(window, cx, |this, window, cx| {
6239 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6240 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6241 s.select(selections)
6242 });
6243 });
6244 }
6245
6246 fn indent_selection(
6247 buffer: &MultiBuffer,
6248 snapshot: &MultiBufferSnapshot,
6249 selection: &mut Selection<Point>,
6250 edits: &mut Vec<(Range<Point>, String)>,
6251 delta_for_start_row: u32,
6252 cx: &App,
6253 ) -> u32 {
6254 let settings = buffer.settings_at(selection.start, cx);
6255 let tab_size = settings.tab_size.get();
6256 let indent_kind = if settings.hard_tabs {
6257 IndentKind::Tab
6258 } else {
6259 IndentKind::Space
6260 };
6261 let mut start_row = selection.start.row;
6262 let mut end_row = selection.end.row + 1;
6263
6264 // If a selection ends at the beginning of a line, don't indent
6265 // that last line.
6266 if selection.end.column == 0 && selection.end.row > selection.start.row {
6267 end_row -= 1;
6268 }
6269
6270 // Avoid re-indenting a row that has already been indented by a
6271 // previous selection, but still update this selection's column
6272 // to reflect that indentation.
6273 if delta_for_start_row > 0 {
6274 start_row += 1;
6275 selection.start.column += delta_for_start_row;
6276 if selection.end.row == selection.start.row {
6277 selection.end.column += delta_for_start_row;
6278 }
6279 }
6280
6281 let mut delta_for_end_row = 0;
6282 let has_multiple_rows = start_row + 1 != end_row;
6283 for row in start_row..end_row {
6284 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6285 let indent_delta = match (current_indent.kind, indent_kind) {
6286 (IndentKind::Space, IndentKind::Space) => {
6287 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6288 IndentSize::spaces(columns_to_next_tab_stop)
6289 }
6290 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6291 (_, IndentKind::Tab) => IndentSize::tab(),
6292 };
6293
6294 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6295 0
6296 } else {
6297 selection.start.column
6298 };
6299 let row_start = Point::new(row, start);
6300 edits.push((
6301 row_start..row_start,
6302 indent_delta.chars().collect::<String>(),
6303 ));
6304
6305 // Update this selection's endpoints to reflect the indentation.
6306 if row == selection.start.row {
6307 selection.start.column += indent_delta.len;
6308 }
6309 if row == selection.end.row {
6310 selection.end.column += indent_delta.len;
6311 delta_for_end_row = indent_delta.len;
6312 }
6313 }
6314
6315 if selection.start.row == selection.end.row {
6316 delta_for_start_row + delta_for_end_row
6317 } else {
6318 delta_for_end_row
6319 }
6320 }
6321
6322 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6323 if self.read_only(cx) {
6324 return;
6325 }
6326 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6327 let selections = self.selections.all::<Point>(cx);
6328 let mut deletion_ranges = Vec::new();
6329 let mut last_outdent = None;
6330 {
6331 let buffer = self.buffer.read(cx);
6332 let snapshot = buffer.snapshot(cx);
6333 for selection in &selections {
6334 let settings = buffer.settings_at(selection.start, cx);
6335 let tab_size = settings.tab_size.get();
6336 let mut rows = selection.spanned_rows(false, &display_map);
6337
6338 // Avoid re-outdenting a row that has already been outdented by a
6339 // previous selection.
6340 if let Some(last_row) = last_outdent {
6341 if last_row == rows.start {
6342 rows.start = rows.start.next_row();
6343 }
6344 }
6345 let has_multiple_rows = rows.len() > 1;
6346 for row in rows.iter_rows() {
6347 let indent_size = snapshot.indent_size_for_line(row);
6348 if indent_size.len > 0 {
6349 let deletion_len = match indent_size.kind {
6350 IndentKind::Space => {
6351 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6352 if columns_to_prev_tab_stop == 0 {
6353 tab_size
6354 } else {
6355 columns_to_prev_tab_stop
6356 }
6357 }
6358 IndentKind::Tab => 1,
6359 };
6360 let start = if has_multiple_rows
6361 || deletion_len > selection.start.column
6362 || indent_size.len < selection.start.column
6363 {
6364 0
6365 } else {
6366 selection.start.column - deletion_len
6367 };
6368 deletion_ranges.push(
6369 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6370 );
6371 last_outdent = Some(row);
6372 }
6373 }
6374 }
6375 }
6376
6377 self.transact(window, cx, |this, window, cx| {
6378 this.buffer.update(cx, |buffer, cx| {
6379 let empty_str: Arc<str> = Arc::default();
6380 buffer.edit(
6381 deletion_ranges
6382 .into_iter()
6383 .map(|range| (range, empty_str.clone())),
6384 None,
6385 cx,
6386 );
6387 });
6388 let selections = this.selections.all::<usize>(cx);
6389 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6390 s.select(selections)
6391 });
6392 });
6393 }
6394
6395 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6396 if self.read_only(cx) {
6397 return;
6398 }
6399 let selections = self
6400 .selections
6401 .all::<usize>(cx)
6402 .into_iter()
6403 .map(|s| s.range());
6404
6405 self.transact(window, cx, |this, window, cx| {
6406 this.buffer.update(cx, |buffer, cx| {
6407 buffer.autoindent_ranges(selections, cx);
6408 });
6409 let selections = this.selections.all::<usize>(cx);
6410 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6411 s.select(selections)
6412 });
6413 });
6414 }
6415
6416 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6417 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6418 let selections = self.selections.all::<Point>(cx);
6419
6420 let mut new_cursors = Vec::new();
6421 let mut edit_ranges = Vec::new();
6422 let mut selections = selections.iter().peekable();
6423 while let Some(selection) = selections.next() {
6424 let mut rows = selection.spanned_rows(false, &display_map);
6425 let goal_display_column = selection.head().to_display_point(&display_map).column();
6426
6427 // Accumulate contiguous regions of rows that we want to delete.
6428 while let Some(next_selection) = selections.peek() {
6429 let next_rows = next_selection.spanned_rows(false, &display_map);
6430 if next_rows.start <= rows.end {
6431 rows.end = next_rows.end;
6432 selections.next().unwrap();
6433 } else {
6434 break;
6435 }
6436 }
6437
6438 let buffer = &display_map.buffer_snapshot;
6439 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6440 let edit_end;
6441 let cursor_buffer_row;
6442 if buffer.max_point().row >= rows.end.0 {
6443 // If there's a line after the range, delete the \n from the end of the row range
6444 // and position the cursor on the next line.
6445 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6446 cursor_buffer_row = rows.end;
6447 } else {
6448 // If there isn't a line after the range, delete the \n from the line before the
6449 // start of the row range and position the cursor there.
6450 edit_start = edit_start.saturating_sub(1);
6451 edit_end = buffer.len();
6452 cursor_buffer_row = rows.start.previous_row();
6453 }
6454
6455 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6456 *cursor.column_mut() =
6457 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6458
6459 new_cursors.push((
6460 selection.id,
6461 buffer.anchor_after(cursor.to_point(&display_map)),
6462 ));
6463 edit_ranges.push(edit_start..edit_end);
6464 }
6465
6466 self.transact(window, cx, |this, window, cx| {
6467 let buffer = this.buffer.update(cx, |buffer, cx| {
6468 let empty_str: Arc<str> = Arc::default();
6469 buffer.edit(
6470 edit_ranges
6471 .into_iter()
6472 .map(|range| (range, empty_str.clone())),
6473 None,
6474 cx,
6475 );
6476 buffer.snapshot(cx)
6477 });
6478 let new_selections = new_cursors
6479 .into_iter()
6480 .map(|(id, cursor)| {
6481 let cursor = cursor.to_point(&buffer);
6482 Selection {
6483 id,
6484 start: cursor,
6485 end: cursor,
6486 reversed: false,
6487 goal: SelectionGoal::None,
6488 }
6489 })
6490 .collect();
6491
6492 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6493 s.select(new_selections);
6494 });
6495 });
6496 }
6497
6498 pub fn join_lines_impl(
6499 &mut self,
6500 insert_whitespace: bool,
6501 window: &mut Window,
6502 cx: &mut Context<Self>,
6503 ) {
6504 if self.read_only(cx) {
6505 return;
6506 }
6507 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6508 for selection in self.selections.all::<Point>(cx) {
6509 let start = MultiBufferRow(selection.start.row);
6510 // Treat single line selections as if they include the next line. Otherwise this action
6511 // would do nothing for single line selections individual cursors.
6512 let end = if selection.start.row == selection.end.row {
6513 MultiBufferRow(selection.start.row + 1)
6514 } else {
6515 MultiBufferRow(selection.end.row)
6516 };
6517
6518 if let Some(last_row_range) = row_ranges.last_mut() {
6519 if start <= last_row_range.end {
6520 last_row_range.end = end;
6521 continue;
6522 }
6523 }
6524 row_ranges.push(start..end);
6525 }
6526
6527 let snapshot = self.buffer.read(cx).snapshot(cx);
6528 let mut cursor_positions = Vec::new();
6529 for row_range in &row_ranges {
6530 let anchor = snapshot.anchor_before(Point::new(
6531 row_range.end.previous_row().0,
6532 snapshot.line_len(row_range.end.previous_row()),
6533 ));
6534 cursor_positions.push(anchor..anchor);
6535 }
6536
6537 self.transact(window, cx, |this, window, cx| {
6538 for row_range in row_ranges.into_iter().rev() {
6539 for row in row_range.iter_rows().rev() {
6540 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6541 let next_line_row = row.next_row();
6542 let indent = snapshot.indent_size_for_line(next_line_row);
6543 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6544
6545 let replace =
6546 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6547 " "
6548 } else {
6549 ""
6550 };
6551
6552 this.buffer.update(cx, |buffer, cx| {
6553 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6554 });
6555 }
6556 }
6557
6558 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6559 s.select_anchor_ranges(cursor_positions)
6560 });
6561 });
6562 }
6563
6564 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6565 self.join_lines_impl(true, window, cx);
6566 }
6567
6568 pub fn sort_lines_case_sensitive(
6569 &mut self,
6570 _: &SortLinesCaseSensitive,
6571 window: &mut Window,
6572 cx: &mut Context<Self>,
6573 ) {
6574 self.manipulate_lines(window, cx, |lines| lines.sort())
6575 }
6576
6577 pub fn sort_lines_case_insensitive(
6578 &mut self,
6579 _: &SortLinesCaseInsensitive,
6580 window: &mut Window,
6581 cx: &mut Context<Self>,
6582 ) {
6583 self.manipulate_lines(window, cx, |lines| {
6584 lines.sort_by_key(|line| line.to_lowercase())
6585 })
6586 }
6587
6588 pub fn unique_lines_case_insensitive(
6589 &mut self,
6590 _: &UniqueLinesCaseInsensitive,
6591 window: &mut Window,
6592 cx: &mut Context<Self>,
6593 ) {
6594 self.manipulate_lines(window, cx, |lines| {
6595 let mut seen = HashSet::default();
6596 lines.retain(|line| seen.insert(line.to_lowercase()));
6597 })
6598 }
6599
6600 pub fn unique_lines_case_sensitive(
6601 &mut self,
6602 _: &UniqueLinesCaseSensitive,
6603 window: &mut Window,
6604 cx: &mut Context<Self>,
6605 ) {
6606 self.manipulate_lines(window, cx, |lines| {
6607 let mut seen = HashSet::default();
6608 lines.retain(|line| seen.insert(*line));
6609 })
6610 }
6611
6612 pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
6613 let mut revert_changes = HashMap::default();
6614 let snapshot = self.snapshot(window, cx);
6615 for hunk in snapshot
6616 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
6617 {
6618 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6619 }
6620 if !revert_changes.is_empty() {
6621 self.transact(window, cx, |editor, window, cx| {
6622 editor.revert(revert_changes, window, cx);
6623 });
6624 }
6625 }
6626
6627 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
6628 let Some(project) = self.project.clone() else {
6629 return;
6630 };
6631 self.reload(project, window, cx)
6632 .detach_and_notify_err(window, cx);
6633 }
6634
6635 pub fn revert_selected_hunks(
6636 &mut self,
6637 _: &RevertSelectedHunks,
6638 window: &mut Window,
6639 cx: &mut Context<Self>,
6640 ) {
6641 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
6642 self.revert_hunks_in_ranges(selections, window, cx);
6643 }
6644
6645 fn revert_hunks_in_ranges(
6646 &mut self,
6647 ranges: impl Iterator<Item = Range<Point>>,
6648 window: &mut Window,
6649 cx: &mut Context<Editor>,
6650 ) {
6651 let mut revert_changes = HashMap::default();
6652 let snapshot = self.snapshot(window, cx);
6653 for hunk in &snapshot.hunks_for_ranges(ranges) {
6654 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6655 }
6656 if !revert_changes.is_empty() {
6657 self.transact(window, cx, |editor, window, cx| {
6658 editor.revert(revert_changes, window, cx);
6659 });
6660 }
6661 }
6662
6663 pub fn open_active_item_in_terminal(
6664 &mut self,
6665 _: &OpenInTerminal,
6666 window: &mut Window,
6667 cx: &mut Context<Self>,
6668 ) {
6669 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6670 let project_path = buffer.read(cx).project_path(cx)?;
6671 let project = self.project.as_ref()?.read(cx);
6672 let entry = project.entry_for_path(&project_path, cx)?;
6673 let parent = match &entry.canonical_path {
6674 Some(canonical_path) => canonical_path.to_path_buf(),
6675 None => project.absolute_path(&project_path, cx)?,
6676 }
6677 .parent()?
6678 .to_path_buf();
6679 Some(parent)
6680 }) {
6681 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
6682 }
6683 }
6684
6685 pub fn prepare_revert_change(
6686 &self,
6687 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6688 hunk: &MultiBufferDiffHunk,
6689 cx: &mut App,
6690 ) -> Option<()> {
6691 let buffer = self.buffer.read(cx);
6692 let change_set = buffer.change_set_for(hunk.buffer_id)?;
6693 let buffer = buffer.buffer(hunk.buffer_id)?;
6694 let buffer = buffer.read(cx);
6695 let original_text = change_set
6696 .read(cx)
6697 .base_text
6698 .as_ref()?
6699 .as_rope()
6700 .slice(hunk.diff_base_byte_range.clone());
6701 let buffer_snapshot = buffer.snapshot();
6702 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6703 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6704 probe
6705 .0
6706 .start
6707 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6708 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6709 }) {
6710 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6711 Some(())
6712 } else {
6713 None
6714 }
6715 }
6716
6717 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
6718 self.manipulate_lines(window, cx, |lines| lines.reverse())
6719 }
6720
6721 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
6722 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
6723 }
6724
6725 fn manipulate_lines<Fn>(
6726 &mut self,
6727 window: &mut Window,
6728 cx: &mut Context<Self>,
6729 mut callback: Fn,
6730 ) where
6731 Fn: FnMut(&mut Vec<&str>),
6732 {
6733 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6734 let buffer = self.buffer.read(cx).snapshot(cx);
6735
6736 let mut edits = Vec::new();
6737
6738 let selections = self.selections.all::<Point>(cx);
6739 let mut selections = selections.iter().peekable();
6740 let mut contiguous_row_selections = Vec::new();
6741 let mut new_selections = Vec::new();
6742 let mut added_lines = 0;
6743 let mut removed_lines = 0;
6744
6745 while let Some(selection) = selections.next() {
6746 let (start_row, end_row) = consume_contiguous_rows(
6747 &mut contiguous_row_selections,
6748 selection,
6749 &display_map,
6750 &mut selections,
6751 );
6752
6753 let start_point = Point::new(start_row.0, 0);
6754 let end_point = Point::new(
6755 end_row.previous_row().0,
6756 buffer.line_len(end_row.previous_row()),
6757 );
6758 let text = buffer
6759 .text_for_range(start_point..end_point)
6760 .collect::<String>();
6761
6762 let mut lines = text.split('\n').collect_vec();
6763
6764 let lines_before = lines.len();
6765 callback(&mut lines);
6766 let lines_after = lines.len();
6767
6768 edits.push((start_point..end_point, lines.join("\n")));
6769
6770 // Selections must change based on added and removed line count
6771 let start_row =
6772 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6773 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6774 new_selections.push(Selection {
6775 id: selection.id,
6776 start: start_row,
6777 end: end_row,
6778 goal: SelectionGoal::None,
6779 reversed: selection.reversed,
6780 });
6781
6782 if lines_after > lines_before {
6783 added_lines += lines_after - lines_before;
6784 } else if lines_before > lines_after {
6785 removed_lines += lines_before - lines_after;
6786 }
6787 }
6788
6789 self.transact(window, cx, |this, window, cx| {
6790 let buffer = this.buffer.update(cx, |buffer, cx| {
6791 buffer.edit(edits, None, cx);
6792 buffer.snapshot(cx)
6793 });
6794
6795 // Recalculate offsets on newly edited buffer
6796 let new_selections = new_selections
6797 .iter()
6798 .map(|s| {
6799 let start_point = Point::new(s.start.0, 0);
6800 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6801 Selection {
6802 id: s.id,
6803 start: buffer.point_to_offset(start_point),
6804 end: buffer.point_to_offset(end_point),
6805 goal: s.goal,
6806 reversed: s.reversed,
6807 }
6808 })
6809 .collect();
6810
6811 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6812 s.select(new_selections);
6813 });
6814
6815 this.request_autoscroll(Autoscroll::fit(), cx);
6816 });
6817 }
6818
6819 pub fn convert_to_upper_case(
6820 &mut self,
6821 _: &ConvertToUpperCase,
6822 window: &mut Window,
6823 cx: &mut Context<Self>,
6824 ) {
6825 self.manipulate_text(window, cx, |text| text.to_uppercase())
6826 }
6827
6828 pub fn convert_to_lower_case(
6829 &mut self,
6830 _: &ConvertToLowerCase,
6831 window: &mut Window,
6832 cx: &mut Context<Self>,
6833 ) {
6834 self.manipulate_text(window, cx, |text| text.to_lowercase())
6835 }
6836
6837 pub fn convert_to_title_case(
6838 &mut self,
6839 _: &ConvertToTitleCase,
6840 window: &mut Window,
6841 cx: &mut Context<Self>,
6842 ) {
6843 self.manipulate_text(window, cx, |text| {
6844 text.split('\n')
6845 .map(|line| line.to_case(Case::Title))
6846 .join("\n")
6847 })
6848 }
6849
6850 pub fn convert_to_snake_case(
6851 &mut self,
6852 _: &ConvertToSnakeCase,
6853 window: &mut Window,
6854 cx: &mut Context<Self>,
6855 ) {
6856 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
6857 }
6858
6859 pub fn convert_to_kebab_case(
6860 &mut self,
6861 _: &ConvertToKebabCase,
6862 window: &mut Window,
6863 cx: &mut Context<Self>,
6864 ) {
6865 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
6866 }
6867
6868 pub fn convert_to_upper_camel_case(
6869 &mut self,
6870 _: &ConvertToUpperCamelCase,
6871 window: &mut Window,
6872 cx: &mut Context<Self>,
6873 ) {
6874 self.manipulate_text(window, cx, |text| {
6875 text.split('\n')
6876 .map(|line| line.to_case(Case::UpperCamel))
6877 .join("\n")
6878 })
6879 }
6880
6881 pub fn convert_to_lower_camel_case(
6882 &mut self,
6883 _: &ConvertToLowerCamelCase,
6884 window: &mut Window,
6885 cx: &mut Context<Self>,
6886 ) {
6887 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
6888 }
6889
6890 pub fn convert_to_opposite_case(
6891 &mut self,
6892 _: &ConvertToOppositeCase,
6893 window: &mut Window,
6894 cx: &mut Context<Self>,
6895 ) {
6896 self.manipulate_text(window, cx, |text| {
6897 text.chars()
6898 .fold(String::with_capacity(text.len()), |mut t, c| {
6899 if c.is_uppercase() {
6900 t.extend(c.to_lowercase());
6901 } else {
6902 t.extend(c.to_uppercase());
6903 }
6904 t
6905 })
6906 })
6907 }
6908
6909 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
6910 where
6911 Fn: FnMut(&str) -> String,
6912 {
6913 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6914 let buffer = self.buffer.read(cx).snapshot(cx);
6915
6916 let mut new_selections = Vec::new();
6917 let mut edits = Vec::new();
6918 let mut selection_adjustment = 0i32;
6919
6920 for selection in self.selections.all::<usize>(cx) {
6921 let selection_is_empty = selection.is_empty();
6922
6923 let (start, end) = if selection_is_empty {
6924 let word_range = movement::surrounding_word(
6925 &display_map,
6926 selection.start.to_display_point(&display_map),
6927 );
6928 let start = word_range.start.to_offset(&display_map, Bias::Left);
6929 let end = word_range.end.to_offset(&display_map, Bias::Left);
6930 (start, end)
6931 } else {
6932 (selection.start, selection.end)
6933 };
6934
6935 let text = buffer.text_for_range(start..end).collect::<String>();
6936 let old_length = text.len() as i32;
6937 let text = callback(&text);
6938
6939 new_selections.push(Selection {
6940 start: (start as i32 - selection_adjustment) as usize,
6941 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6942 goal: SelectionGoal::None,
6943 ..selection
6944 });
6945
6946 selection_adjustment += old_length - text.len() as i32;
6947
6948 edits.push((start..end, text));
6949 }
6950
6951 self.transact(window, cx, |this, window, cx| {
6952 this.buffer.update(cx, |buffer, cx| {
6953 buffer.edit(edits, None, cx);
6954 });
6955
6956 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6957 s.select(new_selections);
6958 });
6959
6960 this.request_autoscroll(Autoscroll::fit(), cx);
6961 });
6962 }
6963
6964 pub fn duplicate(
6965 &mut self,
6966 upwards: bool,
6967 whole_lines: bool,
6968 window: &mut Window,
6969 cx: &mut Context<Self>,
6970 ) {
6971 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6972 let buffer = &display_map.buffer_snapshot;
6973 let selections = self.selections.all::<Point>(cx);
6974
6975 let mut edits = Vec::new();
6976 let mut selections_iter = selections.iter().peekable();
6977 while let Some(selection) = selections_iter.next() {
6978 let mut rows = selection.spanned_rows(false, &display_map);
6979 // duplicate line-wise
6980 if whole_lines || selection.start == selection.end {
6981 // Avoid duplicating the same lines twice.
6982 while let Some(next_selection) = selections_iter.peek() {
6983 let next_rows = next_selection.spanned_rows(false, &display_map);
6984 if next_rows.start < rows.end {
6985 rows.end = next_rows.end;
6986 selections_iter.next().unwrap();
6987 } else {
6988 break;
6989 }
6990 }
6991
6992 // Copy the text from the selected row region and splice it either at the start
6993 // or end of the region.
6994 let start = Point::new(rows.start.0, 0);
6995 let end = Point::new(
6996 rows.end.previous_row().0,
6997 buffer.line_len(rows.end.previous_row()),
6998 );
6999 let text = buffer
7000 .text_for_range(start..end)
7001 .chain(Some("\n"))
7002 .collect::<String>();
7003 let insert_location = if upwards {
7004 Point::new(rows.end.0, 0)
7005 } else {
7006 start
7007 };
7008 edits.push((insert_location..insert_location, text));
7009 } else {
7010 // duplicate character-wise
7011 let start = selection.start;
7012 let end = selection.end;
7013 let text = buffer.text_for_range(start..end).collect::<String>();
7014 edits.push((selection.end..selection.end, text));
7015 }
7016 }
7017
7018 self.transact(window, cx, |this, _, cx| {
7019 this.buffer.update(cx, |buffer, cx| {
7020 buffer.edit(edits, None, cx);
7021 });
7022
7023 this.request_autoscroll(Autoscroll::fit(), cx);
7024 });
7025 }
7026
7027 pub fn duplicate_line_up(
7028 &mut self,
7029 _: &DuplicateLineUp,
7030 window: &mut Window,
7031 cx: &mut Context<Self>,
7032 ) {
7033 self.duplicate(true, true, window, cx);
7034 }
7035
7036 pub fn duplicate_line_down(
7037 &mut self,
7038 _: &DuplicateLineDown,
7039 window: &mut Window,
7040 cx: &mut Context<Self>,
7041 ) {
7042 self.duplicate(false, true, window, cx);
7043 }
7044
7045 pub fn duplicate_selection(
7046 &mut self,
7047 _: &DuplicateSelection,
7048 window: &mut Window,
7049 cx: &mut Context<Self>,
7050 ) {
7051 self.duplicate(false, false, window, cx);
7052 }
7053
7054 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7055 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7056 let buffer = self.buffer.read(cx).snapshot(cx);
7057
7058 let mut edits = Vec::new();
7059 let mut unfold_ranges = Vec::new();
7060 let mut refold_creases = Vec::new();
7061
7062 let selections = self.selections.all::<Point>(cx);
7063 let mut selections = selections.iter().peekable();
7064 let mut contiguous_row_selections = Vec::new();
7065 let mut new_selections = Vec::new();
7066
7067 while let Some(selection) = selections.next() {
7068 // Find all the selections that span a contiguous row range
7069 let (start_row, end_row) = consume_contiguous_rows(
7070 &mut contiguous_row_selections,
7071 selection,
7072 &display_map,
7073 &mut selections,
7074 );
7075
7076 // Move the text spanned by the row range to be before the line preceding the row range
7077 if start_row.0 > 0 {
7078 let range_to_move = Point::new(
7079 start_row.previous_row().0,
7080 buffer.line_len(start_row.previous_row()),
7081 )
7082 ..Point::new(
7083 end_row.previous_row().0,
7084 buffer.line_len(end_row.previous_row()),
7085 );
7086 let insertion_point = display_map
7087 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7088 .0;
7089
7090 // Don't move lines across excerpts
7091 if buffer
7092 .excerpt_containing(insertion_point..range_to_move.end)
7093 .is_some()
7094 {
7095 let text = buffer
7096 .text_for_range(range_to_move.clone())
7097 .flat_map(|s| s.chars())
7098 .skip(1)
7099 .chain(['\n'])
7100 .collect::<String>();
7101
7102 edits.push((
7103 buffer.anchor_after(range_to_move.start)
7104 ..buffer.anchor_before(range_to_move.end),
7105 String::new(),
7106 ));
7107 let insertion_anchor = buffer.anchor_after(insertion_point);
7108 edits.push((insertion_anchor..insertion_anchor, text));
7109
7110 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7111
7112 // Move selections up
7113 new_selections.extend(contiguous_row_selections.drain(..).map(
7114 |mut selection| {
7115 selection.start.row -= row_delta;
7116 selection.end.row -= row_delta;
7117 selection
7118 },
7119 ));
7120
7121 // Move folds up
7122 unfold_ranges.push(range_to_move.clone());
7123 for fold in display_map.folds_in_range(
7124 buffer.anchor_before(range_to_move.start)
7125 ..buffer.anchor_after(range_to_move.end),
7126 ) {
7127 let mut start = fold.range.start.to_point(&buffer);
7128 let mut end = fold.range.end.to_point(&buffer);
7129 start.row -= row_delta;
7130 end.row -= row_delta;
7131 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7132 }
7133 }
7134 }
7135
7136 // If we didn't move line(s), preserve the existing selections
7137 new_selections.append(&mut contiguous_row_selections);
7138 }
7139
7140 self.transact(window, cx, |this, window, cx| {
7141 this.unfold_ranges(&unfold_ranges, true, true, cx);
7142 this.buffer.update(cx, |buffer, cx| {
7143 for (range, text) in edits {
7144 buffer.edit([(range, text)], None, cx);
7145 }
7146 });
7147 this.fold_creases(refold_creases, true, window, cx);
7148 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7149 s.select(new_selections);
7150 })
7151 });
7152 }
7153
7154 pub fn move_line_down(
7155 &mut self,
7156 _: &MoveLineDown,
7157 window: &mut Window,
7158 cx: &mut Context<Self>,
7159 ) {
7160 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7161 let buffer = self.buffer.read(cx).snapshot(cx);
7162
7163 let mut edits = Vec::new();
7164 let mut unfold_ranges = Vec::new();
7165 let mut refold_creases = Vec::new();
7166
7167 let selections = self.selections.all::<Point>(cx);
7168 let mut selections = selections.iter().peekable();
7169 let mut contiguous_row_selections = Vec::new();
7170 let mut new_selections = Vec::new();
7171
7172 while let Some(selection) = selections.next() {
7173 // Find all the selections that span a contiguous row range
7174 let (start_row, end_row) = consume_contiguous_rows(
7175 &mut contiguous_row_selections,
7176 selection,
7177 &display_map,
7178 &mut selections,
7179 );
7180
7181 // Move the text spanned by the row range to be after the last line of the row range
7182 if end_row.0 <= buffer.max_point().row {
7183 let range_to_move =
7184 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7185 let insertion_point = display_map
7186 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7187 .0;
7188
7189 // Don't move lines across excerpt boundaries
7190 if buffer
7191 .excerpt_containing(range_to_move.start..insertion_point)
7192 .is_some()
7193 {
7194 let mut text = String::from("\n");
7195 text.extend(buffer.text_for_range(range_to_move.clone()));
7196 text.pop(); // Drop trailing newline
7197 edits.push((
7198 buffer.anchor_after(range_to_move.start)
7199 ..buffer.anchor_before(range_to_move.end),
7200 String::new(),
7201 ));
7202 let insertion_anchor = buffer.anchor_after(insertion_point);
7203 edits.push((insertion_anchor..insertion_anchor, text));
7204
7205 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7206
7207 // Move selections down
7208 new_selections.extend(contiguous_row_selections.drain(..).map(
7209 |mut selection| {
7210 selection.start.row += row_delta;
7211 selection.end.row += row_delta;
7212 selection
7213 },
7214 ));
7215
7216 // Move folds down
7217 unfold_ranges.push(range_to_move.clone());
7218 for fold in display_map.folds_in_range(
7219 buffer.anchor_before(range_to_move.start)
7220 ..buffer.anchor_after(range_to_move.end),
7221 ) {
7222 let mut start = fold.range.start.to_point(&buffer);
7223 let mut end = fold.range.end.to_point(&buffer);
7224 start.row += row_delta;
7225 end.row += row_delta;
7226 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7227 }
7228 }
7229 }
7230
7231 // If we didn't move line(s), preserve the existing selections
7232 new_selections.append(&mut contiguous_row_selections);
7233 }
7234
7235 self.transact(window, cx, |this, window, cx| {
7236 this.unfold_ranges(&unfold_ranges, true, true, cx);
7237 this.buffer.update(cx, |buffer, cx| {
7238 for (range, text) in edits {
7239 buffer.edit([(range, text)], None, cx);
7240 }
7241 });
7242 this.fold_creases(refold_creases, true, window, cx);
7243 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7244 s.select(new_selections)
7245 });
7246 });
7247 }
7248
7249 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7250 let text_layout_details = &self.text_layout_details(window);
7251 self.transact(window, cx, |this, window, cx| {
7252 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7253 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7254 let line_mode = s.line_mode;
7255 s.move_with(|display_map, selection| {
7256 if !selection.is_empty() || line_mode {
7257 return;
7258 }
7259
7260 let mut head = selection.head();
7261 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7262 if head.column() == display_map.line_len(head.row()) {
7263 transpose_offset = display_map
7264 .buffer_snapshot
7265 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7266 }
7267
7268 if transpose_offset == 0 {
7269 return;
7270 }
7271
7272 *head.column_mut() += 1;
7273 head = display_map.clip_point(head, Bias::Right);
7274 let goal = SelectionGoal::HorizontalPosition(
7275 display_map
7276 .x_for_display_point(head, text_layout_details)
7277 .into(),
7278 );
7279 selection.collapse_to(head, goal);
7280
7281 let transpose_start = display_map
7282 .buffer_snapshot
7283 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7284 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7285 let transpose_end = display_map
7286 .buffer_snapshot
7287 .clip_offset(transpose_offset + 1, Bias::Right);
7288 if let Some(ch) =
7289 display_map.buffer_snapshot.chars_at(transpose_start).next()
7290 {
7291 edits.push((transpose_start..transpose_offset, String::new()));
7292 edits.push((transpose_end..transpose_end, ch.to_string()));
7293 }
7294 }
7295 });
7296 edits
7297 });
7298 this.buffer
7299 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7300 let selections = this.selections.all::<usize>(cx);
7301 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7302 s.select(selections);
7303 });
7304 });
7305 }
7306
7307 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7308 self.rewrap_impl(IsVimMode::No, cx)
7309 }
7310
7311 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7312 let buffer = self.buffer.read(cx).snapshot(cx);
7313 let selections = self.selections.all::<Point>(cx);
7314 let mut selections = selections.iter().peekable();
7315
7316 let mut edits = Vec::new();
7317 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7318
7319 while let Some(selection) = selections.next() {
7320 let mut start_row = selection.start.row;
7321 let mut end_row = selection.end.row;
7322
7323 // Skip selections that overlap with a range that has already been rewrapped.
7324 let selection_range = start_row..end_row;
7325 if rewrapped_row_ranges
7326 .iter()
7327 .any(|range| range.overlaps(&selection_range))
7328 {
7329 continue;
7330 }
7331
7332 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7333
7334 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7335 match language_scope.language_name().as_ref() {
7336 "Markdown" | "Plain Text" => {
7337 should_rewrap = true;
7338 }
7339 _ => {}
7340 }
7341 }
7342
7343 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7344
7345 // Since not all lines in the selection may be at the same indent
7346 // level, choose the indent size that is the most common between all
7347 // of the lines.
7348 //
7349 // If there is a tie, we use the deepest indent.
7350 let (indent_size, indent_end) = {
7351 let mut indent_size_occurrences = HashMap::default();
7352 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7353
7354 for row in start_row..=end_row {
7355 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7356 rows_by_indent_size.entry(indent).or_default().push(row);
7357 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7358 }
7359
7360 let indent_size = indent_size_occurrences
7361 .into_iter()
7362 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7363 .map(|(indent, _)| indent)
7364 .unwrap_or_default();
7365 let row = rows_by_indent_size[&indent_size][0];
7366 let indent_end = Point::new(row, indent_size.len);
7367
7368 (indent_size, indent_end)
7369 };
7370
7371 let mut line_prefix = indent_size.chars().collect::<String>();
7372
7373 if let Some(comment_prefix) =
7374 buffer
7375 .language_scope_at(selection.head())
7376 .and_then(|language| {
7377 language
7378 .line_comment_prefixes()
7379 .iter()
7380 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7381 .cloned()
7382 })
7383 {
7384 line_prefix.push_str(&comment_prefix);
7385 should_rewrap = true;
7386 }
7387
7388 if !should_rewrap {
7389 continue;
7390 }
7391
7392 if selection.is_empty() {
7393 'expand_upwards: while start_row > 0 {
7394 let prev_row = start_row - 1;
7395 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7396 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7397 {
7398 start_row = prev_row;
7399 } else {
7400 break 'expand_upwards;
7401 }
7402 }
7403
7404 'expand_downwards: while end_row < buffer.max_point().row {
7405 let next_row = end_row + 1;
7406 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7407 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7408 {
7409 end_row = next_row;
7410 } else {
7411 break 'expand_downwards;
7412 }
7413 }
7414 }
7415
7416 let start = Point::new(start_row, 0);
7417 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7418 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7419 let Some(lines_without_prefixes) = selection_text
7420 .lines()
7421 .map(|line| {
7422 line.strip_prefix(&line_prefix)
7423 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7424 .ok_or_else(|| {
7425 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7426 })
7427 })
7428 .collect::<Result<Vec<_>, _>>()
7429 .log_err()
7430 else {
7431 continue;
7432 };
7433
7434 let wrap_column = buffer
7435 .settings_at(Point::new(start_row, 0), cx)
7436 .preferred_line_length as usize;
7437 let wrapped_text = wrap_with_prefix(
7438 line_prefix,
7439 lines_without_prefixes.join(" "),
7440 wrap_column,
7441 tab_size,
7442 );
7443
7444 // TODO: should always use char-based diff while still supporting cursor behavior that
7445 // matches vim.
7446 let diff = match is_vim_mode {
7447 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7448 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7449 };
7450 let mut offset = start.to_offset(&buffer);
7451 let mut moved_since_edit = true;
7452
7453 for change in diff.iter_all_changes() {
7454 let value = change.value();
7455 match change.tag() {
7456 ChangeTag::Equal => {
7457 offset += value.len();
7458 moved_since_edit = true;
7459 }
7460 ChangeTag::Delete => {
7461 let start = buffer.anchor_after(offset);
7462 let end = buffer.anchor_before(offset + value.len());
7463
7464 if moved_since_edit {
7465 edits.push((start..end, String::new()));
7466 } else {
7467 edits.last_mut().unwrap().0.end = end;
7468 }
7469
7470 offset += value.len();
7471 moved_since_edit = false;
7472 }
7473 ChangeTag::Insert => {
7474 if moved_since_edit {
7475 let anchor = buffer.anchor_after(offset);
7476 edits.push((anchor..anchor, value.to_string()));
7477 } else {
7478 edits.last_mut().unwrap().1.push_str(value);
7479 }
7480
7481 moved_since_edit = false;
7482 }
7483 }
7484 }
7485
7486 rewrapped_row_ranges.push(start_row..=end_row);
7487 }
7488
7489 self.buffer
7490 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7491 }
7492
7493 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7494 let mut text = String::new();
7495 let buffer = self.buffer.read(cx).snapshot(cx);
7496 let mut selections = self.selections.all::<Point>(cx);
7497 let mut clipboard_selections = Vec::with_capacity(selections.len());
7498 {
7499 let max_point = buffer.max_point();
7500 let mut is_first = true;
7501 for selection in &mut selections {
7502 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7503 if is_entire_line {
7504 selection.start = Point::new(selection.start.row, 0);
7505 if !selection.is_empty() && selection.end.column == 0 {
7506 selection.end = cmp::min(max_point, selection.end);
7507 } else {
7508 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7509 }
7510 selection.goal = SelectionGoal::None;
7511 }
7512 if is_first {
7513 is_first = false;
7514 } else {
7515 text += "\n";
7516 }
7517 let mut len = 0;
7518 for chunk in buffer.text_for_range(selection.start..selection.end) {
7519 text.push_str(chunk);
7520 len += chunk.len();
7521 }
7522 clipboard_selections.push(ClipboardSelection {
7523 len,
7524 is_entire_line,
7525 first_line_indent: buffer
7526 .indent_size_for_line(MultiBufferRow(selection.start.row))
7527 .len,
7528 });
7529 }
7530 }
7531
7532 self.transact(window, cx, |this, window, cx| {
7533 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7534 s.select(selections);
7535 });
7536 this.insert("", window, cx);
7537 });
7538 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7539 }
7540
7541 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
7542 let item = self.cut_common(window, cx);
7543 cx.write_to_clipboard(item);
7544 }
7545
7546 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
7547 self.change_selections(None, window, cx, |s| {
7548 s.move_with(|snapshot, sel| {
7549 if sel.is_empty() {
7550 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7551 }
7552 });
7553 });
7554 let item = self.cut_common(window, cx);
7555 cx.set_global(KillRing(item))
7556 }
7557
7558 pub fn kill_ring_yank(
7559 &mut self,
7560 _: &KillRingYank,
7561 window: &mut Window,
7562 cx: &mut Context<Self>,
7563 ) {
7564 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7565 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7566 (kill_ring.text().to_string(), kill_ring.metadata_json())
7567 } else {
7568 return;
7569 }
7570 } else {
7571 return;
7572 };
7573 self.do_paste(&text, metadata, false, window, cx);
7574 }
7575
7576 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
7577 let selections = self.selections.all::<Point>(cx);
7578 let buffer = self.buffer.read(cx).read(cx);
7579 let mut text = String::new();
7580
7581 let mut clipboard_selections = Vec::with_capacity(selections.len());
7582 {
7583 let max_point = buffer.max_point();
7584 let mut is_first = true;
7585 for selection in selections.iter() {
7586 let mut start = selection.start;
7587 let mut end = selection.end;
7588 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7589 if is_entire_line {
7590 start = Point::new(start.row, 0);
7591 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7592 }
7593 if is_first {
7594 is_first = false;
7595 } else {
7596 text += "\n";
7597 }
7598 let mut len = 0;
7599 for chunk in buffer.text_for_range(start..end) {
7600 text.push_str(chunk);
7601 len += chunk.len();
7602 }
7603 clipboard_selections.push(ClipboardSelection {
7604 len,
7605 is_entire_line,
7606 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7607 });
7608 }
7609 }
7610
7611 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7612 text,
7613 clipboard_selections,
7614 ));
7615 }
7616
7617 pub fn do_paste(
7618 &mut self,
7619 text: &String,
7620 clipboard_selections: Option<Vec<ClipboardSelection>>,
7621 handle_entire_lines: bool,
7622 window: &mut Window,
7623 cx: &mut Context<Self>,
7624 ) {
7625 if self.read_only(cx) {
7626 return;
7627 }
7628
7629 let clipboard_text = Cow::Borrowed(text);
7630
7631 self.transact(window, cx, |this, window, cx| {
7632 if let Some(mut clipboard_selections) = clipboard_selections {
7633 let old_selections = this.selections.all::<usize>(cx);
7634 let all_selections_were_entire_line =
7635 clipboard_selections.iter().all(|s| s.is_entire_line);
7636 let first_selection_indent_column =
7637 clipboard_selections.first().map(|s| s.first_line_indent);
7638 if clipboard_selections.len() != old_selections.len() {
7639 clipboard_selections.drain(..);
7640 }
7641 let cursor_offset = this.selections.last::<usize>(cx).head();
7642 let mut auto_indent_on_paste = true;
7643
7644 this.buffer.update(cx, |buffer, cx| {
7645 let snapshot = buffer.read(cx);
7646 auto_indent_on_paste =
7647 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7648
7649 let mut start_offset = 0;
7650 let mut edits = Vec::new();
7651 let mut original_indent_columns = Vec::new();
7652 for (ix, selection) in old_selections.iter().enumerate() {
7653 let to_insert;
7654 let entire_line;
7655 let original_indent_column;
7656 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7657 let end_offset = start_offset + clipboard_selection.len;
7658 to_insert = &clipboard_text[start_offset..end_offset];
7659 entire_line = clipboard_selection.is_entire_line;
7660 start_offset = end_offset + 1;
7661 original_indent_column = Some(clipboard_selection.first_line_indent);
7662 } else {
7663 to_insert = clipboard_text.as_str();
7664 entire_line = all_selections_were_entire_line;
7665 original_indent_column = first_selection_indent_column
7666 }
7667
7668 // If the corresponding selection was empty when this slice of the
7669 // clipboard text was written, then the entire line containing the
7670 // selection was copied. If this selection is also currently empty,
7671 // then paste the line before the current line of the buffer.
7672 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7673 let column = selection.start.to_point(&snapshot).column as usize;
7674 let line_start = selection.start - column;
7675 line_start..line_start
7676 } else {
7677 selection.range()
7678 };
7679
7680 edits.push((range, to_insert));
7681 original_indent_columns.extend(original_indent_column);
7682 }
7683 drop(snapshot);
7684
7685 buffer.edit(
7686 edits,
7687 if auto_indent_on_paste {
7688 Some(AutoindentMode::Block {
7689 original_indent_columns,
7690 })
7691 } else {
7692 None
7693 },
7694 cx,
7695 );
7696 });
7697
7698 let selections = this.selections.all::<usize>(cx);
7699 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7700 s.select(selections)
7701 });
7702 } else {
7703 this.insert(&clipboard_text, window, cx);
7704 }
7705 });
7706 }
7707
7708 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
7709 if let Some(item) = cx.read_from_clipboard() {
7710 let entries = item.entries();
7711
7712 match entries.first() {
7713 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7714 // of all the pasted entries.
7715 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7716 .do_paste(
7717 clipboard_string.text(),
7718 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7719 true,
7720 window,
7721 cx,
7722 ),
7723 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
7724 }
7725 }
7726 }
7727
7728 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
7729 if self.read_only(cx) {
7730 return;
7731 }
7732
7733 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7734 if let Some((selections, _)) =
7735 self.selection_history.transaction(transaction_id).cloned()
7736 {
7737 self.change_selections(None, window, cx, |s| {
7738 s.select_anchors(selections.to_vec());
7739 });
7740 }
7741 self.request_autoscroll(Autoscroll::fit(), cx);
7742 self.unmark_text(window, cx);
7743 self.refresh_inline_completion(true, false, window, cx);
7744 cx.emit(EditorEvent::Edited { transaction_id });
7745 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7746 }
7747 }
7748
7749 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
7750 if self.read_only(cx) {
7751 return;
7752 }
7753
7754 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7755 if let Some((_, Some(selections))) =
7756 self.selection_history.transaction(transaction_id).cloned()
7757 {
7758 self.change_selections(None, window, cx, |s| {
7759 s.select_anchors(selections.to_vec());
7760 });
7761 }
7762 self.request_autoscroll(Autoscroll::fit(), cx);
7763 self.unmark_text(window, cx);
7764 self.refresh_inline_completion(true, false, window, cx);
7765 cx.emit(EditorEvent::Edited { transaction_id });
7766 }
7767 }
7768
7769 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
7770 self.buffer
7771 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7772 }
7773
7774 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
7775 self.buffer
7776 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7777 }
7778
7779 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
7780 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7781 let line_mode = s.line_mode;
7782 s.move_with(|map, selection| {
7783 let cursor = if selection.is_empty() && !line_mode {
7784 movement::left(map, selection.start)
7785 } else {
7786 selection.start
7787 };
7788 selection.collapse_to(cursor, SelectionGoal::None);
7789 });
7790 })
7791 }
7792
7793 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
7794 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7795 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7796 })
7797 }
7798
7799 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
7800 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7801 let line_mode = s.line_mode;
7802 s.move_with(|map, selection| {
7803 let cursor = if selection.is_empty() && !line_mode {
7804 movement::right(map, selection.end)
7805 } else {
7806 selection.end
7807 };
7808 selection.collapse_to(cursor, SelectionGoal::None)
7809 });
7810 })
7811 }
7812
7813 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
7814 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7815 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7816 })
7817 }
7818
7819 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
7820 if self.take_rename(true, window, cx).is_some() {
7821 return;
7822 }
7823
7824 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7825 cx.propagate();
7826 return;
7827 }
7828
7829 let text_layout_details = &self.text_layout_details(window);
7830 let selection_count = self.selections.count();
7831 let first_selection = self.selections.first_anchor();
7832
7833 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7834 let line_mode = s.line_mode;
7835 s.move_with(|map, selection| {
7836 if !selection.is_empty() && !line_mode {
7837 selection.goal = SelectionGoal::None;
7838 }
7839 let (cursor, goal) = movement::up(
7840 map,
7841 selection.start,
7842 selection.goal,
7843 false,
7844 text_layout_details,
7845 );
7846 selection.collapse_to(cursor, goal);
7847 });
7848 });
7849
7850 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7851 {
7852 cx.propagate();
7853 }
7854 }
7855
7856 pub fn move_up_by_lines(
7857 &mut self,
7858 action: &MoveUpByLines,
7859 window: &mut Window,
7860 cx: &mut Context<Self>,
7861 ) {
7862 if self.take_rename(true, window, cx).is_some() {
7863 return;
7864 }
7865
7866 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7867 cx.propagate();
7868 return;
7869 }
7870
7871 let text_layout_details = &self.text_layout_details(window);
7872
7873 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7874 let line_mode = s.line_mode;
7875 s.move_with(|map, selection| {
7876 if !selection.is_empty() && !line_mode {
7877 selection.goal = SelectionGoal::None;
7878 }
7879 let (cursor, goal) = movement::up_by_rows(
7880 map,
7881 selection.start,
7882 action.lines,
7883 selection.goal,
7884 false,
7885 text_layout_details,
7886 );
7887 selection.collapse_to(cursor, goal);
7888 });
7889 })
7890 }
7891
7892 pub fn move_down_by_lines(
7893 &mut self,
7894 action: &MoveDownByLines,
7895 window: &mut Window,
7896 cx: &mut Context<Self>,
7897 ) {
7898 if self.take_rename(true, window, cx).is_some() {
7899 return;
7900 }
7901
7902 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7903 cx.propagate();
7904 return;
7905 }
7906
7907 let text_layout_details = &self.text_layout_details(window);
7908
7909 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7910 let line_mode = s.line_mode;
7911 s.move_with(|map, selection| {
7912 if !selection.is_empty() && !line_mode {
7913 selection.goal = SelectionGoal::None;
7914 }
7915 let (cursor, goal) = movement::down_by_rows(
7916 map,
7917 selection.start,
7918 action.lines,
7919 selection.goal,
7920 false,
7921 text_layout_details,
7922 );
7923 selection.collapse_to(cursor, goal);
7924 });
7925 })
7926 }
7927
7928 pub fn select_down_by_lines(
7929 &mut self,
7930 action: &SelectDownByLines,
7931 window: &mut Window,
7932 cx: &mut Context<Self>,
7933 ) {
7934 let text_layout_details = &self.text_layout_details(window);
7935 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7936 s.move_heads_with(|map, head, goal| {
7937 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7938 })
7939 })
7940 }
7941
7942 pub fn select_up_by_lines(
7943 &mut self,
7944 action: &SelectUpByLines,
7945 window: &mut Window,
7946 cx: &mut Context<Self>,
7947 ) {
7948 let text_layout_details = &self.text_layout_details(window);
7949 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7950 s.move_heads_with(|map, head, goal| {
7951 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7952 })
7953 })
7954 }
7955
7956 pub fn select_page_up(
7957 &mut self,
7958 _: &SelectPageUp,
7959 window: &mut Window,
7960 cx: &mut Context<Self>,
7961 ) {
7962 let Some(row_count) = self.visible_row_count() else {
7963 return;
7964 };
7965
7966 let text_layout_details = &self.text_layout_details(window);
7967
7968 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7969 s.move_heads_with(|map, head, goal| {
7970 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7971 })
7972 })
7973 }
7974
7975 pub fn move_page_up(
7976 &mut self,
7977 action: &MovePageUp,
7978 window: &mut Window,
7979 cx: &mut Context<Self>,
7980 ) {
7981 if self.take_rename(true, window, cx).is_some() {
7982 return;
7983 }
7984
7985 if self
7986 .context_menu
7987 .borrow_mut()
7988 .as_mut()
7989 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7990 .unwrap_or(false)
7991 {
7992 return;
7993 }
7994
7995 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7996 cx.propagate();
7997 return;
7998 }
7999
8000 let Some(row_count) = self.visible_row_count() else {
8001 return;
8002 };
8003
8004 let autoscroll = if action.center_cursor {
8005 Autoscroll::center()
8006 } else {
8007 Autoscroll::fit()
8008 };
8009
8010 let text_layout_details = &self.text_layout_details(window);
8011
8012 self.change_selections(Some(autoscroll), window, cx, |s| {
8013 let line_mode = s.line_mode;
8014 s.move_with(|map, selection| {
8015 if !selection.is_empty() && !line_mode {
8016 selection.goal = SelectionGoal::None;
8017 }
8018 let (cursor, goal) = movement::up_by_rows(
8019 map,
8020 selection.end,
8021 row_count,
8022 selection.goal,
8023 false,
8024 text_layout_details,
8025 );
8026 selection.collapse_to(cursor, goal);
8027 });
8028 });
8029 }
8030
8031 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8032 let text_layout_details = &self.text_layout_details(window);
8033 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8034 s.move_heads_with(|map, head, goal| {
8035 movement::up(map, head, goal, false, text_layout_details)
8036 })
8037 })
8038 }
8039
8040 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8041 self.take_rename(true, window, cx);
8042
8043 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8044 cx.propagate();
8045 return;
8046 }
8047
8048 let text_layout_details = &self.text_layout_details(window);
8049 let selection_count = self.selections.count();
8050 let first_selection = self.selections.first_anchor();
8051
8052 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8053 let line_mode = s.line_mode;
8054 s.move_with(|map, selection| {
8055 if !selection.is_empty() && !line_mode {
8056 selection.goal = SelectionGoal::None;
8057 }
8058 let (cursor, goal) = movement::down(
8059 map,
8060 selection.end,
8061 selection.goal,
8062 false,
8063 text_layout_details,
8064 );
8065 selection.collapse_to(cursor, goal);
8066 });
8067 });
8068
8069 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8070 {
8071 cx.propagate();
8072 }
8073 }
8074
8075 pub fn select_page_down(
8076 &mut self,
8077 _: &SelectPageDown,
8078 window: &mut Window,
8079 cx: &mut Context<Self>,
8080 ) {
8081 let Some(row_count) = self.visible_row_count() else {
8082 return;
8083 };
8084
8085 let text_layout_details = &self.text_layout_details(window);
8086
8087 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8088 s.move_heads_with(|map, head, goal| {
8089 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8090 })
8091 })
8092 }
8093
8094 pub fn move_page_down(
8095 &mut self,
8096 action: &MovePageDown,
8097 window: &mut Window,
8098 cx: &mut Context<Self>,
8099 ) {
8100 if self.take_rename(true, window, cx).is_some() {
8101 return;
8102 }
8103
8104 if self
8105 .context_menu
8106 .borrow_mut()
8107 .as_mut()
8108 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8109 .unwrap_or(false)
8110 {
8111 return;
8112 }
8113
8114 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8115 cx.propagate();
8116 return;
8117 }
8118
8119 let Some(row_count) = self.visible_row_count() else {
8120 return;
8121 };
8122
8123 let autoscroll = if action.center_cursor {
8124 Autoscroll::center()
8125 } else {
8126 Autoscroll::fit()
8127 };
8128
8129 let text_layout_details = &self.text_layout_details(window);
8130 self.change_selections(Some(autoscroll), window, cx, |s| {
8131 let line_mode = s.line_mode;
8132 s.move_with(|map, selection| {
8133 if !selection.is_empty() && !line_mode {
8134 selection.goal = SelectionGoal::None;
8135 }
8136 let (cursor, goal) = movement::down_by_rows(
8137 map,
8138 selection.end,
8139 row_count,
8140 selection.goal,
8141 false,
8142 text_layout_details,
8143 );
8144 selection.collapse_to(cursor, goal);
8145 });
8146 });
8147 }
8148
8149 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8150 let text_layout_details = &self.text_layout_details(window);
8151 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8152 s.move_heads_with(|map, head, goal| {
8153 movement::down(map, head, goal, false, text_layout_details)
8154 })
8155 });
8156 }
8157
8158 pub fn context_menu_first(
8159 &mut self,
8160 _: &ContextMenuFirst,
8161 _window: &mut Window,
8162 cx: &mut Context<Self>,
8163 ) {
8164 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8165 context_menu.select_first(self.completion_provider.as_deref(), cx);
8166 }
8167 }
8168
8169 pub fn context_menu_prev(
8170 &mut self,
8171 _: &ContextMenuPrev,
8172 _window: &mut Window,
8173 cx: &mut Context<Self>,
8174 ) {
8175 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8176 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8177 }
8178 }
8179
8180 pub fn context_menu_next(
8181 &mut self,
8182 _: &ContextMenuNext,
8183 _window: &mut Window,
8184 cx: &mut Context<Self>,
8185 ) {
8186 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8187 context_menu.select_next(self.completion_provider.as_deref(), cx);
8188 }
8189 }
8190
8191 pub fn context_menu_last(
8192 &mut self,
8193 _: &ContextMenuLast,
8194 _window: &mut Window,
8195 cx: &mut Context<Self>,
8196 ) {
8197 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8198 context_menu.select_last(self.completion_provider.as_deref(), cx);
8199 }
8200 }
8201
8202 pub fn move_to_previous_word_start(
8203 &mut self,
8204 _: &MoveToPreviousWordStart,
8205 window: &mut Window,
8206 cx: &mut Context<Self>,
8207 ) {
8208 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8209 s.move_cursors_with(|map, head, _| {
8210 (
8211 movement::previous_word_start(map, head),
8212 SelectionGoal::None,
8213 )
8214 });
8215 })
8216 }
8217
8218 pub fn move_to_previous_subword_start(
8219 &mut self,
8220 _: &MoveToPreviousSubwordStart,
8221 window: &mut Window,
8222 cx: &mut Context<Self>,
8223 ) {
8224 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8225 s.move_cursors_with(|map, head, _| {
8226 (
8227 movement::previous_subword_start(map, head),
8228 SelectionGoal::None,
8229 )
8230 });
8231 })
8232 }
8233
8234 pub fn select_to_previous_word_start(
8235 &mut self,
8236 _: &SelectToPreviousWordStart,
8237 window: &mut Window,
8238 cx: &mut Context<Self>,
8239 ) {
8240 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8241 s.move_heads_with(|map, head, _| {
8242 (
8243 movement::previous_word_start(map, head),
8244 SelectionGoal::None,
8245 )
8246 });
8247 })
8248 }
8249
8250 pub fn select_to_previous_subword_start(
8251 &mut self,
8252 _: &SelectToPreviousSubwordStart,
8253 window: &mut Window,
8254 cx: &mut Context<Self>,
8255 ) {
8256 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8257 s.move_heads_with(|map, head, _| {
8258 (
8259 movement::previous_subword_start(map, head),
8260 SelectionGoal::None,
8261 )
8262 });
8263 })
8264 }
8265
8266 pub fn delete_to_previous_word_start(
8267 &mut self,
8268 action: &DeleteToPreviousWordStart,
8269 window: &mut Window,
8270 cx: &mut Context<Self>,
8271 ) {
8272 self.transact(window, cx, |this, window, cx| {
8273 this.select_autoclose_pair(window, cx);
8274 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8275 let line_mode = s.line_mode;
8276 s.move_with(|map, selection| {
8277 if selection.is_empty() && !line_mode {
8278 let cursor = if action.ignore_newlines {
8279 movement::previous_word_start(map, selection.head())
8280 } else {
8281 movement::previous_word_start_or_newline(map, selection.head())
8282 };
8283 selection.set_head(cursor, SelectionGoal::None);
8284 }
8285 });
8286 });
8287 this.insert("", window, cx);
8288 });
8289 }
8290
8291 pub fn delete_to_previous_subword_start(
8292 &mut self,
8293 _: &DeleteToPreviousSubwordStart,
8294 window: &mut Window,
8295 cx: &mut Context<Self>,
8296 ) {
8297 self.transact(window, cx, |this, window, cx| {
8298 this.select_autoclose_pair(window, cx);
8299 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8300 let line_mode = s.line_mode;
8301 s.move_with(|map, selection| {
8302 if selection.is_empty() && !line_mode {
8303 let cursor = movement::previous_subword_start(map, selection.head());
8304 selection.set_head(cursor, SelectionGoal::None);
8305 }
8306 });
8307 });
8308 this.insert("", window, cx);
8309 });
8310 }
8311
8312 pub fn move_to_next_word_end(
8313 &mut self,
8314 _: &MoveToNextWordEnd,
8315 window: &mut Window,
8316 cx: &mut Context<Self>,
8317 ) {
8318 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8319 s.move_cursors_with(|map, head, _| {
8320 (movement::next_word_end(map, head), SelectionGoal::None)
8321 });
8322 })
8323 }
8324
8325 pub fn move_to_next_subword_end(
8326 &mut self,
8327 _: &MoveToNextSubwordEnd,
8328 window: &mut Window,
8329 cx: &mut Context<Self>,
8330 ) {
8331 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8332 s.move_cursors_with(|map, head, _| {
8333 (movement::next_subword_end(map, head), SelectionGoal::None)
8334 });
8335 })
8336 }
8337
8338 pub fn select_to_next_word_end(
8339 &mut self,
8340 _: &SelectToNextWordEnd,
8341 window: &mut Window,
8342 cx: &mut Context<Self>,
8343 ) {
8344 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8345 s.move_heads_with(|map, head, _| {
8346 (movement::next_word_end(map, head), SelectionGoal::None)
8347 });
8348 })
8349 }
8350
8351 pub fn select_to_next_subword_end(
8352 &mut self,
8353 _: &SelectToNextSubwordEnd,
8354 window: &mut Window,
8355 cx: &mut Context<Self>,
8356 ) {
8357 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8358 s.move_heads_with(|map, head, _| {
8359 (movement::next_subword_end(map, head), SelectionGoal::None)
8360 });
8361 })
8362 }
8363
8364 pub fn delete_to_next_word_end(
8365 &mut self,
8366 action: &DeleteToNextWordEnd,
8367 window: &mut Window,
8368 cx: &mut Context<Self>,
8369 ) {
8370 self.transact(window, cx, |this, window, cx| {
8371 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8372 let line_mode = s.line_mode;
8373 s.move_with(|map, selection| {
8374 if selection.is_empty() && !line_mode {
8375 let cursor = if action.ignore_newlines {
8376 movement::next_word_end(map, selection.head())
8377 } else {
8378 movement::next_word_end_or_newline(map, selection.head())
8379 };
8380 selection.set_head(cursor, SelectionGoal::None);
8381 }
8382 });
8383 });
8384 this.insert("", window, cx);
8385 });
8386 }
8387
8388 pub fn delete_to_next_subword_end(
8389 &mut self,
8390 _: &DeleteToNextSubwordEnd,
8391 window: &mut Window,
8392 cx: &mut Context<Self>,
8393 ) {
8394 self.transact(window, cx, |this, window, cx| {
8395 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8396 s.move_with(|map, selection| {
8397 if selection.is_empty() {
8398 let cursor = movement::next_subword_end(map, selection.head());
8399 selection.set_head(cursor, SelectionGoal::None);
8400 }
8401 });
8402 });
8403 this.insert("", window, cx);
8404 });
8405 }
8406
8407 pub fn move_to_beginning_of_line(
8408 &mut self,
8409 action: &MoveToBeginningOfLine,
8410 window: &mut Window,
8411 cx: &mut Context<Self>,
8412 ) {
8413 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8414 s.move_cursors_with(|map, head, _| {
8415 (
8416 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8417 SelectionGoal::None,
8418 )
8419 });
8420 })
8421 }
8422
8423 pub fn select_to_beginning_of_line(
8424 &mut self,
8425 action: &SelectToBeginningOfLine,
8426 window: &mut Window,
8427 cx: &mut Context<Self>,
8428 ) {
8429 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8430 s.move_heads_with(|map, head, _| {
8431 (
8432 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8433 SelectionGoal::None,
8434 )
8435 });
8436 });
8437 }
8438
8439 pub fn delete_to_beginning_of_line(
8440 &mut self,
8441 _: &DeleteToBeginningOfLine,
8442 window: &mut Window,
8443 cx: &mut Context<Self>,
8444 ) {
8445 self.transact(window, cx, |this, window, cx| {
8446 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8447 s.move_with(|_, selection| {
8448 selection.reversed = true;
8449 });
8450 });
8451
8452 this.select_to_beginning_of_line(
8453 &SelectToBeginningOfLine {
8454 stop_at_soft_wraps: false,
8455 },
8456 window,
8457 cx,
8458 );
8459 this.backspace(&Backspace, window, cx);
8460 });
8461 }
8462
8463 pub fn move_to_end_of_line(
8464 &mut self,
8465 action: &MoveToEndOfLine,
8466 window: &mut Window,
8467 cx: &mut Context<Self>,
8468 ) {
8469 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8470 s.move_cursors_with(|map, head, _| {
8471 (
8472 movement::line_end(map, head, action.stop_at_soft_wraps),
8473 SelectionGoal::None,
8474 )
8475 });
8476 })
8477 }
8478
8479 pub fn select_to_end_of_line(
8480 &mut self,
8481 action: &SelectToEndOfLine,
8482 window: &mut Window,
8483 cx: &mut Context<Self>,
8484 ) {
8485 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8486 s.move_heads_with(|map, head, _| {
8487 (
8488 movement::line_end(map, head, action.stop_at_soft_wraps),
8489 SelectionGoal::None,
8490 )
8491 });
8492 })
8493 }
8494
8495 pub fn delete_to_end_of_line(
8496 &mut self,
8497 _: &DeleteToEndOfLine,
8498 window: &mut Window,
8499 cx: &mut Context<Self>,
8500 ) {
8501 self.transact(window, cx, |this, window, cx| {
8502 this.select_to_end_of_line(
8503 &SelectToEndOfLine {
8504 stop_at_soft_wraps: false,
8505 },
8506 window,
8507 cx,
8508 );
8509 this.delete(&Delete, window, cx);
8510 });
8511 }
8512
8513 pub fn cut_to_end_of_line(
8514 &mut self,
8515 _: &CutToEndOfLine,
8516 window: &mut Window,
8517 cx: &mut Context<Self>,
8518 ) {
8519 self.transact(window, cx, |this, window, cx| {
8520 this.select_to_end_of_line(
8521 &SelectToEndOfLine {
8522 stop_at_soft_wraps: false,
8523 },
8524 window,
8525 cx,
8526 );
8527 this.cut(&Cut, window, cx);
8528 });
8529 }
8530
8531 pub fn move_to_start_of_paragraph(
8532 &mut self,
8533 _: &MoveToStartOfParagraph,
8534 window: &mut Window,
8535 cx: &mut Context<Self>,
8536 ) {
8537 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8538 cx.propagate();
8539 return;
8540 }
8541
8542 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8543 s.move_with(|map, selection| {
8544 selection.collapse_to(
8545 movement::start_of_paragraph(map, selection.head(), 1),
8546 SelectionGoal::None,
8547 )
8548 });
8549 })
8550 }
8551
8552 pub fn move_to_end_of_paragraph(
8553 &mut self,
8554 _: &MoveToEndOfParagraph,
8555 window: &mut Window,
8556 cx: &mut Context<Self>,
8557 ) {
8558 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8559 cx.propagate();
8560 return;
8561 }
8562
8563 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8564 s.move_with(|map, selection| {
8565 selection.collapse_to(
8566 movement::end_of_paragraph(map, selection.head(), 1),
8567 SelectionGoal::None,
8568 )
8569 });
8570 })
8571 }
8572
8573 pub fn select_to_start_of_paragraph(
8574 &mut self,
8575 _: &SelectToStartOfParagraph,
8576 window: &mut Window,
8577 cx: &mut Context<Self>,
8578 ) {
8579 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8580 cx.propagate();
8581 return;
8582 }
8583
8584 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8585 s.move_heads_with(|map, head, _| {
8586 (
8587 movement::start_of_paragraph(map, head, 1),
8588 SelectionGoal::None,
8589 )
8590 });
8591 })
8592 }
8593
8594 pub fn select_to_end_of_paragraph(
8595 &mut self,
8596 _: &SelectToEndOfParagraph,
8597 window: &mut Window,
8598 cx: &mut Context<Self>,
8599 ) {
8600 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8601 cx.propagate();
8602 return;
8603 }
8604
8605 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8606 s.move_heads_with(|map, head, _| {
8607 (
8608 movement::end_of_paragraph(map, head, 1),
8609 SelectionGoal::None,
8610 )
8611 });
8612 })
8613 }
8614
8615 pub fn move_to_beginning(
8616 &mut self,
8617 _: &MoveToBeginning,
8618 window: &mut Window,
8619 cx: &mut Context<Self>,
8620 ) {
8621 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8622 cx.propagate();
8623 return;
8624 }
8625
8626 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8627 s.select_ranges(vec![0..0]);
8628 });
8629 }
8630
8631 pub fn select_to_beginning(
8632 &mut self,
8633 _: &SelectToBeginning,
8634 window: &mut Window,
8635 cx: &mut Context<Self>,
8636 ) {
8637 let mut selection = self.selections.last::<Point>(cx);
8638 selection.set_head(Point::zero(), SelectionGoal::None);
8639
8640 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8641 s.select(vec![selection]);
8642 });
8643 }
8644
8645 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
8646 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8647 cx.propagate();
8648 return;
8649 }
8650
8651 let cursor = self.buffer.read(cx).read(cx).len();
8652 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8653 s.select_ranges(vec![cursor..cursor])
8654 });
8655 }
8656
8657 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8658 self.nav_history = nav_history;
8659 }
8660
8661 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8662 self.nav_history.as_ref()
8663 }
8664
8665 fn push_to_nav_history(
8666 &mut self,
8667 cursor_anchor: Anchor,
8668 new_position: Option<Point>,
8669 cx: &mut Context<Self>,
8670 ) {
8671 if let Some(nav_history) = self.nav_history.as_mut() {
8672 let buffer = self.buffer.read(cx).read(cx);
8673 let cursor_position = cursor_anchor.to_point(&buffer);
8674 let scroll_state = self.scroll_manager.anchor();
8675 let scroll_top_row = scroll_state.top_row(&buffer);
8676 drop(buffer);
8677
8678 if let Some(new_position) = new_position {
8679 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8680 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8681 return;
8682 }
8683 }
8684
8685 nav_history.push(
8686 Some(NavigationData {
8687 cursor_anchor,
8688 cursor_position,
8689 scroll_anchor: scroll_state,
8690 scroll_top_row,
8691 }),
8692 cx,
8693 );
8694 }
8695 }
8696
8697 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
8698 let buffer = self.buffer.read(cx).snapshot(cx);
8699 let mut selection = self.selections.first::<usize>(cx);
8700 selection.set_head(buffer.len(), SelectionGoal::None);
8701 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8702 s.select(vec![selection]);
8703 });
8704 }
8705
8706 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
8707 let end = self.buffer.read(cx).read(cx).len();
8708 self.change_selections(None, window, cx, |s| {
8709 s.select_ranges(vec![0..end]);
8710 });
8711 }
8712
8713 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
8714 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8715 let mut selections = self.selections.all::<Point>(cx);
8716 let max_point = display_map.buffer_snapshot.max_point();
8717 for selection in &mut selections {
8718 let rows = selection.spanned_rows(true, &display_map);
8719 selection.start = Point::new(rows.start.0, 0);
8720 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8721 selection.reversed = false;
8722 }
8723 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8724 s.select(selections);
8725 });
8726 }
8727
8728 pub fn split_selection_into_lines(
8729 &mut self,
8730 _: &SplitSelectionIntoLines,
8731 window: &mut Window,
8732 cx: &mut Context<Self>,
8733 ) {
8734 let mut to_unfold = Vec::new();
8735 let mut new_selection_ranges = Vec::new();
8736 {
8737 let selections = self.selections.all::<Point>(cx);
8738 let buffer = self.buffer.read(cx).read(cx);
8739 for selection in selections {
8740 for row in selection.start.row..selection.end.row {
8741 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8742 new_selection_ranges.push(cursor..cursor);
8743 }
8744 new_selection_ranges.push(selection.end..selection.end);
8745 to_unfold.push(selection.start..selection.end);
8746 }
8747 }
8748 self.unfold_ranges(&to_unfold, true, true, cx);
8749 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8750 s.select_ranges(new_selection_ranges);
8751 });
8752 }
8753
8754 pub fn add_selection_above(
8755 &mut self,
8756 _: &AddSelectionAbove,
8757 window: &mut Window,
8758 cx: &mut Context<Self>,
8759 ) {
8760 self.add_selection(true, window, cx);
8761 }
8762
8763 pub fn add_selection_below(
8764 &mut self,
8765 _: &AddSelectionBelow,
8766 window: &mut Window,
8767 cx: &mut Context<Self>,
8768 ) {
8769 self.add_selection(false, window, cx);
8770 }
8771
8772 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
8773 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8774 let mut selections = self.selections.all::<Point>(cx);
8775 let text_layout_details = self.text_layout_details(window);
8776 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8777 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8778 let range = oldest_selection.display_range(&display_map).sorted();
8779
8780 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8781 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8782 let positions = start_x.min(end_x)..start_x.max(end_x);
8783
8784 selections.clear();
8785 let mut stack = Vec::new();
8786 for row in range.start.row().0..=range.end.row().0 {
8787 if let Some(selection) = self.selections.build_columnar_selection(
8788 &display_map,
8789 DisplayRow(row),
8790 &positions,
8791 oldest_selection.reversed,
8792 &text_layout_details,
8793 ) {
8794 stack.push(selection.id);
8795 selections.push(selection);
8796 }
8797 }
8798
8799 if above {
8800 stack.reverse();
8801 }
8802
8803 AddSelectionsState { above, stack }
8804 });
8805
8806 let last_added_selection = *state.stack.last().unwrap();
8807 let mut new_selections = Vec::new();
8808 if above == state.above {
8809 let end_row = if above {
8810 DisplayRow(0)
8811 } else {
8812 display_map.max_point().row()
8813 };
8814
8815 'outer: for selection in selections {
8816 if selection.id == last_added_selection {
8817 let range = selection.display_range(&display_map).sorted();
8818 debug_assert_eq!(range.start.row(), range.end.row());
8819 let mut row = range.start.row();
8820 let positions =
8821 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8822 px(start)..px(end)
8823 } else {
8824 let start_x =
8825 display_map.x_for_display_point(range.start, &text_layout_details);
8826 let end_x =
8827 display_map.x_for_display_point(range.end, &text_layout_details);
8828 start_x.min(end_x)..start_x.max(end_x)
8829 };
8830
8831 while row != end_row {
8832 if above {
8833 row.0 -= 1;
8834 } else {
8835 row.0 += 1;
8836 }
8837
8838 if let Some(new_selection) = self.selections.build_columnar_selection(
8839 &display_map,
8840 row,
8841 &positions,
8842 selection.reversed,
8843 &text_layout_details,
8844 ) {
8845 state.stack.push(new_selection.id);
8846 if above {
8847 new_selections.push(new_selection);
8848 new_selections.push(selection);
8849 } else {
8850 new_selections.push(selection);
8851 new_selections.push(new_selection);
8852 }
8853
8854 continue 'outer;
8855 }
8856 }
8857 }
8858
8859 new_selections.push(selection);
8860 }
8861 } else {
8862 new_selections = selections;
8863 new_selections.retain(|s| s.id != last_added_selection);
8864 state.stack.pop();
8865 }
8866
8867 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8868 s.select(new_selections);
8869 });
8870 if state.stack.len() > 1 {
8871 self.add_selections_state = Some(state);
8872 }
8873 }
8874
8875 pub fn select_next_match_internal(
8876 &mut self,
8877 display_map: &DisplaySnapshot,
8878 replace_newest: bool,
8879 autoscroll: Option<Autoscroll>,
8880 window: &mut Window,
8881 cx: &mut Context<Self>,
8882 ) -> Result<()> {
8883 fn select_next_match_ranges(
8884 this: &mut Editor,
8885 range: Range<usize>,
8886 replace_newest: bool,
8887 auto_scroll: Option<Autoscroll>,
8888 window: &mut Window,
8889 cx: &mut Context<Editor>,
8890 ) {
8891 this.unfold_ranges(&[range.clone()], false, true, cx);
8892 this.change_selections(auto_scroll, window, cx, |s| {
8893 if replace_newest {
8894 s.delete(s.newest_anchor().id);
8895 }
8896 s.insert_range(range.clone());
8897 });
8898 }
8899
8900 let buffer = &display_map.buffer_snapshot;
8901 let mut selections = self.selections.all::<usize>(cx);
8902 if let Some(mut select_next_state) = self.select_next_state.take() {
8903 let query = &select_next_state.query;
8904 if !select_next_state.done {
8905 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8906 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8907 let mut next_selected_range = None;
8908
8909 let bytes_after_last_selection =
8910 buffer.bytes_in_range(last_selection.end..buffer.len());
8911 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8912 let query_matches = query
8913 .stream_find_iter(bytes_after_last_selection)
8914 .map(|result| (last_selection.end, result))
8915 .chain(
8916 query
8917 .stream_find_iter(bytes_before_first_selection)
8918 .map(|result| (0, result)),
8919 );
8920
8921 for (start_offset, query_match) in query_matches {
8922 let query_match = query_match.unwrap(); // can only fail due to I/O
8923 let offset_range =
8924 start_offset + query_match.start()..start_offset + query_match.end();
8925 let display_range = offset_range.start.to_display_point(display_map)
8926 ..offset_range.end.to_display_point(display_map);
8927
8928 if !select_next_state.wordwise
8929 || (!movement::is_inside_word(display_map, display_range.start)
8930 && !movement::is_inside_word(display_map, display_range.end))
8931 {
8932 // TODO: This is n^2, because we might check all the selections
8933 if !selections
8934 .iter()
8935 .any(|selection| selection.range().overlaps(&offset_range))
8936 {
8937 next_selected_range = Some(offset_range);
8938 break;
8939 }
8940 }
8941 }
8942
8943 if let Some(next_selected_range) = next_selected_range {
8944 select_next_match_ranges(
8945 self,
8946 next_selected_range,
8947 replace_newest,
8948 autoscroll,
8949 window,
8950 cx,
8951 );
8952 } else {
8953 select_next_state.done = true;
8954 }
8955 }
8956
8957 self.select_next_state = Some(select_next_state);
8958 } else {
8959 let mut only_carets = true;
8960 let mut same_text_selected = true;
8961 let mut selected_text = None;
8962
8963 let mut selections_iter = selections.iter().peekable();
8964 while let Some(selection) = selections_iter.next() {
8965 if selection.start != selection.end {
8966 only_carets = false;
8967 }
8968
8969 if same_text_selected {
8970 if selected_text.is_none() {
8971 selected_text =
8972 Some(buffer.text_for_range(selection.range()).collect::<String>());
8973 }
8974
8975 if let Some(next_selection) = selections_iter.peek() {
8976 if next_selection.range().len() == selection.range().len() {
8977 let next_selected_text = buffer
8978 .text_for_range(next_selection.range())
8979 .collect::<String>();
8980 if Some(next_selected_text) != selected_text {
8981 same_text_selected = false;
8982 selected_text = None;
8983 }
8984 } else {
8985 same_text_selected = false;
8986 selected_text = None;
8987 }
8988 }
8989 }
8990 }
8991
8992 if only_carets {
8993 for selection in &mut selections {
8994 let word_range = movement::surrounding_word(
8995 display_map,
8996 selection.start.to_display_point(display_map),
8997 );
8998 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8999 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9000 selection.goal = SelectionGoal::None;
9001 selection.reversed = false;
9002 select_next_match_ranges(
9003 self,
9004 selection.start..selection.end,
9005 replace_newest,
9006 autoscroll,
9007 window,
9008 cx,
9009 );
9010 }
9011
9012 if selections.len() == 1 {
9013 let selection = selections
9014 .last()
9015 .expect("ensured that there's only one selection");
9016 let query = buffer
9017 .text_for_range(selection.start..selection.end)
9018 .collect::<String>();
9019 let is_empty = query.is_empty();
9020 let select_state = SelectNextState {
9021 query: AhoCorasick::new(&[query])?,
9022 wordwise: true,
9023 done: is_empty,
9024 };
9025 self.select_next_state = Some(select_state);
9026 } else {
9027 self.select_next_state = None;
9028 }
9029 } else if let Some(selected_text) = selected_text {
9030 self.select_next_state = Some(SelectNextState {
9031 query: AhoCorasick::new(&[selected_text])?,
9032 wordwise: false,
9033 done: false,
9034 });
9035 self.select_next_match_internal(
9036 display_map,
9037 replace_newest,
9038 autoscroll,
9039 window,
9040 cx,
9041 )?;
9042 }
9043 }
9044 Ok(())
9045 }
9046
9047 pub fn select_all_matches(
9048 &mut self,
9049 _action: &SelectAllMatches,
9050 window: &mut Window,
9051 cx: &mut Context<Self>,
9052 ) -> Result<()> {
9053 self.push_to_selection_history();
9054 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9055
9056 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9057 let Some(select_next_state) = self.select_next_state.as_mut() else {
9058 return Ok(());
9059 };
9060 if select_next_state.done {
9061 return Ok(());
9062 }
9063
9064 let mut new_selections = self.selections.all::<usize>(cx);
9065
9066 let buffer = &display_map.buffer_snapshot;
9067 let query_matches = select_next_state
9068 .query
9069 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9070
9071 for query_match in query_matches {
9072 let query_match = query_match.unwrap(); // can only fail due to I/O
9073 let offset_range = query_match.start()..query_match.end();
9074 let display_range = offset_range.start.to_display_point(&display_map)
9075 ..offset_range.end.to_display_point(&display_map);
9076
9077 if !select_next_state.wordwise
9078 || (!movement::is_inside_word(&display_map, display_range.start)
9079 && !movement::is_inside_word(&display_map, display_range.end))
9080 {
9081 self.selections.change_with(cx, |selections| {
9082 new_selections.push(Selection {
9083 id: selections.new_selection_id(),
9084 start: offset_range.start,
9085 end: offset_range.end,
9086 reversed: false,
9087 goal: SelectionGoal::None,
9088 });
9089 });
9090 }
9091 }
9092
9093 new_selections.sort_by_key(|selection| selection.start);
9094 let mut ix = 0;
9095 while ix + 1 < new_selections.len() {
9096 let current_selection = &new_selections[ix];
9097 let next_selection = &new_selections[ix + 1];
9098 if current_selection.range().overlaps(&next_selection.range()) {
9099 if current_selection.id < next_selection.id {
9100 new_selections.remove(ix + 1);
9101 } else {
9102 new_selections.remove(ix);
9103 }
9104 } else {
9105 ix += 1;
9106 }
9107 }
9108
9109 let reversed = self.selections.oldest::<usize>(cx).reversed;
9110
9111 for selection in new_selections.iter_mut() {
9112 selection.reversed = reversed;
9113 }
9114
9115 select_next_state.done = true;
9116 self.unfold_ranges(
9117 &new_selections
9118 .iter()
9119 .map(|selection| selection.range())
9120 .collect::<Vec<_>>(),
9121 false,
9122 false,
9123 cx,
9124 );
9125 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9126 selections.select(new_selections)
9127 });
9128
9129 Ok(())
9130 }
9131
9132 pub fn select_next(
9133 &mut self,
9134 action: &SelectNext,
9135 window: &mut Window,
9136 cx: &mut Context<Self>,
9137 ) -> Result<()> {
9138 self.push_to_selection_history();
9139 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9140 self.select_next_match_internal(
9141 &display_map,
9142 action.replace_newest,
9143 Some(Autoscroll::newest()),
9144 window,
9145 cx,
9146 )?;
9147 Ok(())
9148 }
9149
9150 pub fn select_previous(
9151 &mut self,
9152 action: &SelectPrevious,
9153 window: &mut Window,
9154 cx: &mut Context<Self>,
9155 ) -> Result<()> {
9156 self.push_to_selection_history();
9157 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9158 let buffer = &display_map.buffer_snapshot;
9159 let mut selections = self.selections.all::<usize>(cx);
9160 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9161 let query = &select_prev_state.query;
9162 if !select_prev_state.done {
9163 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9164 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9165 let mut next_selected_range = None;
9166 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9167 let bytes_before_last_selection =
9168 buffer.reversed_bytes_in_range(0..last_selection.start);
9169 let bytes_after_first_selection =
9170 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9171 let query_matches = query
9172 .stream_find_iter(bytes_before_last_selection)
9173 .map(|result| (last_selection.start, result))
9174 .chain(
9175 query
9176 .stream_find_iter(bytes_after_first_selection)
9177 .map(|result| (buffer.len(), result)),
9178 );
9179 for (end_offset, query_match) in query_matches {
9180 let query_match = query_match.unwrap(); // can only fail due to I/O
9181 let offset_range =
9182 end_offset - query_match.end()..end_offset - query_match.start();
9183 let display_range = offset_range.start.to_display_point(&display_map)
9184 ..offset_range.end.to_display_point(&display_map);
9185
9186 if !select_prev_state.wordwise
9187 || (!movement::is_inside_word(&display_map, display_range.start)
9188 && !movement::is_inside_word(&display_map, display_range.end))
9189 {
9190 next_selected_range = Some(offset_range);
9191 break;
9192 }
9193 }
9194
9195 if let Some(next_selected_range) = next_selected_range {
9196 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9197 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9198 if action.replace_newest {
9199 s.delete(s.newest_anchor().id);
9200 }
9201 s.insert_range(next_selected_range);
9202 });
9203 } else {
9204 select_prev_state.done = true;
9205 }
9206 }
9207
9208 self.select_prev_state = Some(select_prev_state);
9209 } else {
9210 let mut only_carets = true;
9211 let mut same_text_selected = true;
9212 let mut selected_text = None;
9213
9214 let mut selections_iter = selections.iter().peekable();
9215 while let Some(selection) = selections_iter.next() {
9216 if selection.start != selection.end {
9217 only_carets = false;
9218 }
9219
9220 if same_text_selected {
9221 if selected_text.is_none() {
9222 selected_text =
9223 Some(buffer.text_for_range(selection.range()).collect::<String>());
9224 }
9225
9226 if let Some(next_selection) = selections_iter.peek() {
9227 if next_selection.range().len() == selection.range().len() {
9228 let next_selected_text = buffer
9229 .text_for_range(next_selection.range())
9230 .collect::<String>();
9231 if Some(next_selected_text) != selected_text {
9232 same_text_selected = false;
9233 selected_text = None;
9234 }
9235 } else {
9236 same_text_selected = false;
9237 selected_text = None;
9238 }
9239 }
9240 }
9241 }
9242
9243 if only_carets {
9244 for selection in &mut selections {
9245 let word_range = movement::surrounding_word(
9246 &display_map,
9247 selection.start.to_display_point(&display_map),
9248 );
9249 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9250 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9251 selection.goal = SelectionGoal::None;
9252 selection.reversed = false;
9253 }
9254 if selections.len() == 1 {
9255 let selection = selections
9256 .last()
9257 .expect("ensured that there's only one selection");
9258 let query = buffer
9259 .text_for_range(selection.start..selection.end)
9260 .collect::<String>();
9261 let is_empty = query.is_empty();
9262 let select_state = SelectNextState {
9263 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9264 wordwise: true,
9265 done: is_empty,
9266 };
9267 self.select_prev_state = Some(select_state);
9268 } else {
9269 self.select_prev_state = None;
9270 }
9271
9272 self.unfold_ranges(
9273 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9274 false,
9275 true,
9276 cx,
9277 );
9278 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9279 s.select(selections);
9280 });
9281 } else if let Some(selected_text) = selected_text {
9282 self.select_prev_state = Some(SelectNextState {
9283 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9284 wordwise: false,
9285 done: false,
9286 });
9287 self.select_previous(action, window, cx)?;
9288 }
9289 }
9290 Ok(())
9291 }
9292
9293 pub fn toggle_comments(
9294 &mut self,
9295 action: &ToggleComments,
9296 window: &mut Window,
9297 cx: &mut Context<Self>,
9298 ) {
9299 if self.read_only(cx) {
9300 return;
9301 }
9302 let text_layout_details = &self.text_layout_details(window);
9303 self.transact(window, cx, |this, window, cx| {
9304 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9305 let mut edits = Vec::new();
9306 let mut selection_edit_ranges = Vec::new();
9307 let mut last_toggled_row = None;
9308 let snapshot = this.buffer.read(cx).read(cx);
9309 let empty_str: Arc<str> = Arc::default();
9310 let mut suffixes_inserted = Vec::new();
9311 let ignore_indent = action.ignore_indent;
9312
9313 fn comment_prefix_range(
9314 snapshot: &MultiBufferSnapshot,
9315 row: MultiBufferRow,
9316 comment_prefix: &str,
9317 comment_prefix_whitespace: &str,
9318 ignore_indent: bool,
9319 ) -> Range<Point> {
9320 let indent_size = if ignore_indent {
9321 0
9322 } else {
9323 snapshot.indent_size_for_line(row).len
9324 };
9325
9326 let start = Point::new(row.0, indent_size);
9327
9328 let mut line_bytes = snapshot
9329 .bytes_in_range(start..snapshot.max_point())
9330 .flatten()
9331 .copied();
9332
9333 // If this line currently begins with the line comment prefix, then record
9334 // the range containing the prefix.
9335 if line_bytes
9336 .by_ref()
9337 .take(comment_prefix.len())
9338 .eq(comment_prefix.bytes())
9339 {
9340 // Include any whitespace that matches the comment prefix.
9341 let matching_whitespace_len = line_bytes
9342 .zip(comment_prefix_whitespace.bytes())
9343 .take_while(|(a, b)| a == b)
9344 .count() as u32;
9345 let end = Point::new(
9346 start.row,
9347 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9348 );
9349 start..end
9350 } else {
9351 start..start
9352 }
9353 }
9354
9355 fn comment_suffix_range(
9356 snapshot: &MultiBufferSnapshot,
9357 row: MultiBufferRow,
9358 comment_suffix: &str,
9359 comment_suffix_has_leading_space: bool,
9360 ) -> Range<Point> {
9361 let end = Point::new(row.0, snapshot.line_len(row));
9362 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9363
9364 let mut line_end_bytes = snapshot
9365 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9366 .flatten()
9367 .copied();
9368
9369 let leading_space_len = if suffix_start_column > 0
9370 && line_end_bytes.next() == Some(b' ')
9371 && comment_suffix_has_leading_space
9372 {
9373 1
9374 } else {
9375 0
9376 };
9377
9378 // If this line currently begins with the line comment prefix, then record
9379 // the range containing the prefix.
9380 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9381 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9382 start..end
9383 } else {
9384 end..end
9385 }
9386 }
9387
9388 // TODO: Handle selections that cross excerpts
9389 for selection in &mut selections {
9390 let start_column = snapshot
9391 .indent_size_for_line(MultiBufferRow(selection.start.row))
9392 .len;
9393 let language = if let Some(language) =
9394 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9395 {
9396 language
9397 } else {
9398 continue;
9399 };
9400
9401 selection_edit_ranges.clear();
9402
9403 // If multiple selections contain a given row, avoid processing that
9404 // row more than once.
9405 let mut start_row = MultiBufferRow(selection.start.row);
9406 if last_toggled_row == Some(start_row) {
9407 start_row = start_row.next_row();
9408 }
9409 let end_row =
9410 if selection.end.row > selection.start.row && selection.end.column == 0 {
9411 MultiBufferRow(selection.end.row - 1)
9412 } else {
9413 MultiBufferRow(selection.end.row)
9414 };
9415 last_toggled_row = Some(end_row);
9416
9417 if start_row > end_row {
9418 continue;
9419 }
9420
9421 // If the language has line comments, toggle those.
9422 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9423
9424 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9425 if ignore_indent {
9426 full_comment_prefixes = full_comment_prefixes
9427 .into_iter()
9428 .map(|s| Arc::from(s.trim_end()))
9429 .collect();
9430 }
9431
9432 if !full_comment_prefixes.is_empty() {
9433 let first_prefix = full_comment_prefixes
9434 .first()
9435 .expect("prefixes is non-empty");
9436 let prefix_trimmed_lengths = full_comment_prefixes
9437 .iter()
9438 .map(|p| p.trim_end_matches(' ').len())
9439 .collect::<SmallVec<[usize; 4]>>();
9440
9441 let mut all_selection_lines_are_comments = true;
9442
9443 for row in start_row.0..=end_row.0 {
9444 let row = MultiBufferRow(row);
9445 if start_row < end_row && snapshot.is_line_blank(row) {
9446 continue;
9447 }
9448
9449 let prefix_range = full_comment_prefixes
9450 .iter()
9451 .zip(prefix_trimmed_lengths.iter().copied())
9452 .map(|(prefix, trimmed_prefix_len)| {
9453 comment_prefix_range(
9454 snapshot.deref(),
9455 row,
9456 &prefix[..trimmed_prefix_len],
9457 &prefix[trimmed_prefix_len..],
9458 ignore_indent,
9459 )
9460 })
9461 .max_by_key(|range| range.end.column - range.start.column)
9462 .expect("prefixes is non-empty");
9463
9464 if prefix_range.is_empty() {
9465 all_selection_lines_are_comments = false;
9466 }
9467
9468 selection_edit_ranges.push(prefix_range);
9469 }
9470
9471 if all_selection_lines_are_comments {
9472 edits.extend(
9473 selection_edit_ranges
9474 .iter()
9475 .cloned()
9476 .map(|range| (range, empty_str.clone())),
9477 );
9478 } else {
9479 let min_column = selection_edit_ranges
9480 .iter()
9481 .map(|range| range.start.column)
9482 .min()
9483 .unwrap_or(0);
9484 edits.extend(selection_edit_ranges.iter().map(|range| {
9485 let position = Point::new(range.start.row, min_column);
9486 (position..position, first_prefix.clone())
9487 }));
9488 }
9489 } else if let Some((full_comment_prefix, comment_suffix)) =
9490 language.block_comment_delimiters()
9491 {
9492 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9493 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9494 let prefix_range = comment_prefix_range(
9495 snapshot.deref(),
9496 start_row,
9497 comment_prefix,
9498 comment_prefix_whitespace,
9499 ignore_indent,
9500 );
9501 let suffix_range = comment_suffix_range(
9502 snapshot.deref(),
9503 end_row,
9504 comment_suffix.trim_start_matches(' '),
9505 comment_suffix.starts_with(' '),
9506 );
9507
9508 if prefix_range.is_empty() || suffix_range.is_empty() {
9509 edits.push((
9510 prefix_range.start..prefix_range.start,
9511 full_comment_prefix.clone(),
9512 ));
9513 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9514 suffixes_inserted.push((end_row, comment_suffix.len()));
9515 } else {
9516 edits.push((prefix_range, empty_str.clone()));
9517 edits.push((suffix_range, empty_str.clone()));
9518 }
9519 } else {
9520 continue;
9521 }
9522 }
9523
9524 drop(snapshot);
9525 this.buffer.update(cx, |buffer, cx| {
9526 buffer.edit(edits, None, cx);
9527 });
9528
9529 // Adjust selections so that they end before any comment suffixes that
9530 // were inserted.
9531 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9532 let mut selections = this.selections.all::<Point>(cx);
9533 let snapshot = this.buffer.read(cx).read(cx);
9534 for selection in &mut selections {
9535 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9536 match row.cmp(&MultiBufferRow(selection.end.row)) {
9537 Ordering::Less => {
9538 suffixes_inserted.next();
9539 continue;
9540 }
9541 Ordering::Greater => break,
9542 Ordering::Equal => {
9543 if selection.end.column == snapshot.line_len(row) {
9544 if selection.is_empty() {
9545 selection.start.column -= suffix_len as u32;
9546 }
9547 selection.end.column -= suffix_len as u32;
9548 }
9549 break;
9550 }
9551 }
9552 }
9553 }
9554
9555 drop(snapshot);
9556 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9557 s.select(selections)
9558 });
9559
9560 let selections = this.selections.all::<Point>(cx);
9561 let selections_on_single_row = selections.windows(2).all(|selections| {
9562 selections[0].start.row == selections[1].start.row
9563 && selections[0].end.row == selections[1].end.row
9564 && selections[0].start.row == selections[0].end.row
9565 });
9566 let selections_selecting = selections
9567 .iter()
9568 .any(|selection| selection.start != selection.end);
9569 let advance_downwards = action.advance_downwards
9570 && selections_on_single_row
9571 && !selections_selecting
9572 && !matches!(this.mode, EditorMode::SingleLine { .. });
9573
9574 if advance_downwards {
9575 let snapshot = this.buffer.read(cx).snapshot(cx);
9576
9577 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9578 s.move_cursors_with(|display_snapshot, display_point, _| {
9579 let mut point = display_point.to_point(display_snapshot);
9580 point.row += 1;
9581 point = snapshot.clip_point(point, Bias::Left);
9582 let display_point = point.to_display_point(display_snapshot);
9583 let goal = SelectionGoal::HorizontalPosition(
9584 display_snapshot
9585 .x_for_display_point(display_point, text_layout_details)
9586 .into(),
9587 );
9588 (display_point, goal)
9589 })
9590 });
9591 }
9592 });
9593 }
9594
9595 pub fn select_enclosing_symbol(
9596 &mut self,
9597 _: &SelectEnclosingSymbol,
9598 window: &mut Window,
9599 cx: &mut Context<Self>,
9600 ) {
9601 let buffer = self.buffer.read(cx).snapshot(cx);
9602 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9603
9604 fn update_selection(
9605 selection: &Selection<usize>,
9606 buffer_snap: &MultiBufferSnapshot,
9607 ) -> Option<Selection<usize>> {
9608 let cursor = selection.head();
9609 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9610 for symbol in symbols.iter().rev() {
9611 let start = symbol.range.start.to_offset(buffer_snap);
9612 let end = symbol.range.end.to_offset(buffer_snap);
9613 let new_range = start..end;
9614 if start < selection.start || end > selection.end {
9615 return Some(Selection {
9616 id: selection.id,
9617 start: new_range.start,
9618 end: new_range.end,
9619 goal: SelectionGoal::None,
9620 reversed: selection.reversed,
9621 });
9622 }
9623 }
9624 None
9625 }
9626
9627 let mut selected_larger_symbol = false;
9628 let new_selections = old_selections
9629 .iter()
9630 .map(|selection| match update_selection(selection, &buffer) {
9631 Some(new_selection) => {
9632 if new_selection.range() != selection.range() {
9633 selected_larger_symbol = true;
9634 }
9635 new_selection
9636 }
9637 None => selection.clone(),
9638 })
9639 .collect::<Vec<_>>();
9640
9641 if selected_larger_symbol {
9642 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9643 s.select(new_selections);
9644 });
9645 }
9646 }
9647
9648 pub fn select_larger_syntax_node(
9649 &mut self,
9650 _: &SelectLargerSyntaxNode,
9651 window: &mut Window,
9652 cx: &mut Context<Self>,
9653 ) {
9654 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9655 let buffer = self.buffer.read(cx).snapshot(cx);
9656 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9657
9658 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9659 let mut selected_larger_node = false;
9660 let new_selections = old_selections
9661 .iter()
9662 .map(|selection| {
9663 let old_range = selection.start..selection.end;
9664 let mut new_range = old_range.clone();
9665 let mut new_node = None;
9666 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
9667 {
9668 new_node = Some(node);
9669 new_range = containing_range;
9670 if !display_map.intersects_fold(new_range.start)
9671 && !display_map.intersects_fold(new_range.end)
9672 {
9673 break;
9674 }
9675 }
9676
9677 if let Some(node) = new_node {
9678 // Log the ancestor, to support using this action as a way to explore TreeSitter
9679 // nodes. Parent and grandparent are also logged because this operation will not
9680 // visit nodes that have the same range as their parent.
9681 log::info!("Node: {node:?}");
9682 let parent = node.parent();
9683 log::info!("Parent: {parent:?}");
9684 let grandparent = parent.and_then(|x| x.parent());
9685 log::info!("Grandparent: {grandparent:?}");
9686 }
9687
9688 selected_larger_node |= new_range != old_range;
9689 Selection {
9690 id: selection.id,
9691 start: new_range.start,
9692 end: new_range.end,
9693 goal: SelectionGoal::None,
9694 reversed: selection.reversed,
9695 }
9696 })
9697 .collect::<Vec<_>>();
9698
9699 if selected_larger_node {
9700 stack.push(old_selections);
9701 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9702 s.select(new_selections);
9703 });
9704 }
9705 self.select_larger_syntax_node_stack = stack;
9706 }
9707
9708 pub fn select_smaller_syntax_node(
9709 &mut self,
9710 _: &SelectSmallerSyntaxNode,
9711 window: &mut Window,
9712 cx: &mut Context<Self>,
9713 ) {
9714 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9715 if let Some(selections) = stack.pop() {
9716 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9717 s.select(selections.to_vec());
9718 });
9719 }
9720 self.select_larger_syntax_node_stack = stack;
9721 }
9722
9723 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
9724 if !EditorSettings::get_global(cx).gutter.runnables {
9725 self.clear_tasks();
9726 return Task::ready(());
9727 }
9728 let project = self.project.as_ref().map(Entity::downgrade);
9729 cx.spawn_in(window, |this, mut cx| async move {
9730 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
9731 let Some(project) = project.and_then(|p| p.upgrade()) else {
9732 return;
9733 };
9734 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9735 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9736 }) else {
9737 return;
9738 };
9739
9740 let hide_runnables = project
9741 .update(&mut cx, |project, cx| {
9742 // Do not display any test indicators in non-dev server remote projects.
9743 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9744 })
9745 .unwrap_or(true);
9746 if hide_runnables {
9747 return;
9748 }
9749 let new_rows =
9750 cx.background_executor()
9751 .spawn({
9752 let snapshot = display_snapshot.clone();
9753 async move {
9754 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9755 }
9756 })
9757 .await;
9758
9759 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9760 this.update(&mut cx, |this, _| {
9761 this.clear_tasks();
9762 for (key, value) in rows {
9763 this.insert_tasks(key, value);
9764 }
9765 })
9766 .ok();
9767 })
9768 }
9769 fn fetch_runnable_ranges(
9770 snapshot: &DisplaySnapshot,
9771 range: Range<Anchor>,
9772 ) -> Vec<language::RunnableRange> {
9773 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9774 }
9775
9776 fn runnable_rows(
9777 project: Entity<Project>,
9778 snapshot: DisplaySnapshot,
9779 runnable_ranges: Vec<RunnableRange>,
9780 mut cx: AsyncWindowContext,
9781 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9782 runnable_ranges
9783 .into_iter()
9784 .filter_map(|mut runnable| {
9785 let tasks = cx
9786 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9787 .ok()?;
9788 if tasks.is_empty() {
9789 return None;
9790 }
9791
9792 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9793
9794 let row = snapshot
9795 .buffer_snapshot
9796 .buffer_line_for_row(MultiBufferRow(point.row))?
9797 .1
9798 .start
9799 .row;
9800
9801 let context_range =
9802 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9803 Some((
9804 (runnable.buffer_id, row),
9805 RunnableTasks {
9806 templates: tasks,
9807 offset: MultiBufferOffset(runnable.run_range.start),
9808 context_range,
9809 column: point.column,
9810 extra_variables: runnable.extra_captures,
9811 },
9812 ))
9813 })
9814 .collect()
9815 }
9816
9817 fn templates_with_tags(
9818 project: &Entity<Project>,
9819 runnable: &mut Runnable,
9820 cx: &mut App,
9821 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9822 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9823 let (worktree_id, file) = project
9824 .buffer_for_id(runnable.buffer, cx)
9825 .and_then(|buffer| buffer.read(cx).file())
9826 .map(|file| (file.worktree_id(cx), file.clone()))
9827 .unzip();
9828
9829 (
9830 project.task_store().read(cx).task_inventory().cloned(),
9831 worktree_id,
9832 file,
9833 )
9834 });
9835
9836 let tags = mem::take(&mut runnable.tags);
9837 let mut tags: Vec<_> = tags
9838 .into_iter()
9839 .flat_map(|tag| {
9840 let tag = tag.0.clone();
9841 inventory
9842 .as_ref()
9843 .into_iter()
9844 .flat_map(|inventory| {
9845 inventory.read(cx).list_tasks(
9846 file.clone(),
9847 Some(runnable.language.clone()),
9848 worktree_id,
9849 cx,
9850 )
9851 })
9852 .filter(move |(_, template)| {
9853 template.tags.iter().any(|source_tag| source_tag == &tag)
9854 })
9855 })
9856 .sorted_by_key(|(kind, _)| kind.to_owned())
9857 .collect();
9858 if let Some((leading_tag_source, _)) = tags.first() {
9859 // Strongest source wins; if we have worktree tag binding, prefer that to
9860 // global and language bindings;
9861 // if we have a global binding, prefer that to language binding.
9862 let first_mismatch = tags
9863 .iter()
9864 .position(|(tag_source, _)| tag_source != leading_tag_source);
9865 if let Some(index) = first_mismatch {
9866 tags.truncate(index);
9867 }
9868 }
9869
9870 tags
9871 }
9872
9873 pub fn move_to_enclosing_bracket(
9874 &mut self,
9875 _: &MoveToEnclosingBracket,
9876 window: &mut Window,
9877 cx: &mut Context<Self>,
9878 ) {
9879 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9880 s.move_offsets_with(|snapshot, selection| {
9881 let Some(enclosing_bracket_ranges) =
9882 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9883 else {
9884 return;
9885 };
9886
9887 let mut best_length = usize::MAX;
9888 let mut best_inside = false;
9889 let mut best_in_bracket_range = false;
9890 let mut best_destination = None;
9891 for (open, close) in enclosing_bracket_ranges {
9892 let close = close.to_inclusive();
9893 let length = close.end() - open.start;
9894 let inside = selection.start >= open.end && selection.end <= *close.start();
9895 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9896 || close.contains(&selection.head());
9897
9898 // If best is next to a bracket and current isn't, skip
9899 if !in_bracket_range && best_in_bracket_range {
9900 continue;
9901 }
9902
9903 // Prefer smaller lengths unless best is inside and current isn't
9904 if length > best_length && (best_inside || !inside) {
9905 continue;
9906 }
9907
9908 best_length = length;
9909 best_inside = inside;
9910 best_in_bracket_range = in_bracket_range;
9911 best_destination = Some(
9912 if close.contains(&selection.start) && close.contains(&selection.end) {
9913 if inside {
9914 open.end
9915 } else {
9916 open.start
9917 }
9918 } else if inside {
9919 *close.start()
9920 } else {
9921 *close.end()
9922 },
9923 );
9924 }
9925
9926 if let Some(destination) = best_destination {
9927 selection.collapse_to(destination, SelectionGoal::None);
9928 }
9929 })
9930 });
9931 }
9932
9933 pub fn undo_selection(
9934 &mut self,
9935 _: &UndoSelection,
9936 window: &mut Window,
9937 cx: &mut Context<Self>,
9938 ) {
9939 self.end_selection(window, cx);
9940 self.selection_history.mode = SelectionHistoryMode::Undoing;
9941 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9942 self.change_selections(None, window, cx, |s| {
9943 s.select_anchors(entry.selections.to_vec())
9944 });
9945 self.select_next_state = entry.select_next_state;
9946 self.select_prev_state = entry.select_prev_state;
9947 self.add_selections_state = entry.add_selections_state;
9948 self.request_autoscroll(Autoscroll::newest(), cx);
9949 }
9950 self.selection_history.mode = SelectionHistoryMode::Normal;
9951 }
9952
9953 pub fn redo_selection(
9954 &mut self,
9955 _: &RedoSelection,
9956 window: &mut Window,
9957 cx: &mut Context<Self>,
9958 ) {
9959 self.end_selection(window, cx);
9960 self.selection_history.mode = SelectionHistoryMode::Redoing;
9961 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9962 self.change_selections(None, window, cx, |s| {
9963 s.select_anchors(entry.selections.to_vec())
9964 });
9965 self.select_next_state = entry.select_next_state;
9966 self.select_prev_state = entry.select_prev_state;
9967 self.add_selections_state = entry.add_selections_state;
9968 self.request_autoscroll(Autoscroll::newest(), cx);
9969 }
9970 self.selection_history.mode = SelectionHistoryMode::Normal;
9971 }
9972
9973 pub fn expand_excerpts(
9974 &mut self,
9975 action: &ExpandExcerpts,
9976 _: &mut Window,
9977 cx: &mut Context<Self>,
9978 ) {
9979 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9980 }
9981
9982 pub fn expand_excerpts_down(
9983 &mut self,
9984 action: &ExpandExcerptsDown,
9985 _: &mut Window,
9986 cx: &mut Context<Self>,
9987 ) {
9988 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9989 }
9990
9991 pub fn expand_excerpts_up(
9992 &mut self,
9993 action: &ExpandExcerptsUp,
9994 _: &mut Window,
9995 cx: &mut Context<Self>,
9996 ) {
9997 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9998 }
9999
10000 pub fn expand_excerpts_for_direction(
10001 &mut self,
10002 lines: u32,
10003 direction: ExpandExcerptDirection,
10004
10005 cx: &mut Context<Self>,
10006 ) {
10007 let selections = self.selections.disjoint_anchors();
10008
10009 let lines = if lines == 0 {
10010 EditorSettings::get_global(cx).expand_excerpt_lines
10011 } else {
10012 lines
10013 };
10014
10015 self.buffer.update(cx, |buffer, cx| {
10016 let snapshot = buffer.snapshot(cx);
10017 let mut excerpt_ids = selections
10018 .iter()
10019 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10020 .collect::<Vec<_>>();
10021 excerpt_ids.sort();
10022 excerpt_ids.dedup();
10023 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10024 })
10025 }
10026
10027 pub fn expand_excerpt(
10028 &mut self,
10029 excerpt: ExcerptId,
10030 direction: ExpandExcerptDirection,
10031 cx: &mut Context<Self>,
10032 ) {
10033 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10034 self.buffer.update(cx, |buffer, cx| {
10035 buffer.expand_excerpts([excerpt], lines, direction, cx)
10036 })
10037 }
10038
10039 pub fn go_to_singleton_buffer_point(
10040 &mut self,
10041 point: Point,
10042 window: &mut Window,
10043 cx: &mut Context<Self>,
10044 ) {
10045 self.go_to_singleton_buffer_range(point..point, window, cx);
10046 }
10047
10048 pub fn go_to_singleton_buffer_range(
10049 &mut self,
10050 range: Range<Point>,
10051 window: &mut Window,
10052 cx: &mut Context<Self>,
10053 ) {
10054 let multibuffer = self.buffer().read(cx);
10055 let Some(buffer) = multibuffer.as_singleton() else {
10056 return;
10057 };
10058 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10059 return;
10060 };
10061 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10062 return;
10063 };
10064 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10065 s.select_anchor_ranges([start..end])
10066 });
10067 }
10068
10069 fn go_to_diagnostic(
10070 &mut self,
10071 _: &GoToDiagnostic,
10072 window: &mut Window,
10073 cx: &mut Context<Self>,
10074 ) {
10075 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10076 }
10077
10078 fn go_to_prev_diagnostic(
10079 &mut self,
10080 _: &GoToPrevDiagnostic,
10081 window: &mut Window,
10082 cx: &mut Context<Self>,
10083 ) {
10084 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10085 }
10086
10087 pub fn go_to_diagnostic_impl(
10088 &mut self,
10089 direction: Direction,
10090 window: &mut Window,
10091 cx: &mut Context<Self>,
10092 ) {
10093 let buffer = self.buffer.read(cx).snapshot(cx);
10094 let selection = self.selections.newest::<usize>(cx);
10095
10096 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10097 if direction == Direction::Next {
10098 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10099 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10100 return;
10101 };
10102 self.activate_diagnostics(
10103 buffer_id,
10104 popover.local_diagnostic.diagnostic.group_id,
10105 window,
10106 cx,
10107 );
10108 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10109 let primary_range_start = active_diagnostics.primary_range.start;
10110 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10111 let mut new_selection = s.newest_anchor().clone();
10112 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10113 s.select_anchors(vec![new_selection.clone()]);
10114 });
10115 self.refresh_inline_completion(false, true, window, cx);
10116 }
10117 return;
10118 }
10119 }
10120
10121 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10122 active_diagnostics
10123 .primary_range
10124 .to_offset(&buffer)
10125 .to_inclusive()
10126 });
10127 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10128 if active_primary_range.contains(&selection.head()) {
10129 *active_primary_range.start()
10130 } else {
10131 selection.head()
10132 }
10133 } else {
10134 selection.head()
10135 };
10136 let snapshot = self.snapshot(window, cx);
10137 loop {
10138 let mut diagnostics;
10139 if direction == Direction::Prev {
10140 diagnostics = buffer
10141 .diagnostics_in_range::<_, usize>(0..search_start)
10142 .collect::<Vec<_>>();
10143 diagnostics.reverse();
10144 } else {
10145 diagnostics = buffer
10146 .diagnostics_in_range::<_, usize>(search_start..buffer.len())
10147 .collect::<Vec<_>>();
10148 };
10149 let group = diagnostics
10150 .into_iter()
10151 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10152 // relies on diagnostics_in_range to return diagnostics with the same starting range to
10153 // be sorted in a stable way
10154 // skip until we are at current active diagnostic, if it exists
10155 .skip_while(|entry| {
10156 let is_in_range = match direction {
10157 Direction::Prev => entry.range.end > search_start,
10158 Direction::Next => entry.range.start < search_start,
10159 };
10160 is_in_range
10161 && self
10162 .active_diagnostics
10163 .as_ref()
10164 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
10165 })
10166 .find_map(|entry| {
10167 if entry.diagnostic.is_primary
10168 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
10169 && entry.range.start != entry.range.end
10170 // if we match with the active diagnostic, skip it
10171 && Some(entry.diagnostic.group_id)
10172 != self.active_diagnostics.as_ref().map(|d| d.group_id)
10173 {
10174 Some((entry.range, entry.diagnostic.group_id))
10175 } else {
10176 None
10177 }
10178 });
10179
10180 if let Some((primary_range, group_id)) = group {
10181 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10182 return;
10183 };
10184 self.activate_diagnostics(buffer_id, group_id, window, cx);
10185 if self.active_diagnostics.is_some() {
10186 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10187 s.select(vec![Selection {
10188 id: selection.id,
10189 start: primary_range.start,
10190 end: primary_range.start,
10191 reversed: false,
10192 goal: SelectionGoal::None,
10193 }]);
10194 });
10195 self.refresh_inline_completion(false, true, window, cx);
10196 }
10197 break;
10198 } else {
10199 // Cycle around to the start of the buffer, potentially moving back to the start of
10200 // the currently active diagnostic.
10201 active_primary_range.take();
10202 if direction == Direction::Prev {
10203 if search_start == buffer.len() {
10204 break;
10205 } else {
10206 search_start = buffer.len();
10207 }
10208 } else if search_start == 0 {
10209 break;
10210 } else {
10211 search_start = 0;
10212 }
10213 }
10214 }
10215 }
10216
10217 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10218 let snapshot = self.snapshot(window, cx);
10219 let selection = self.selections.newest::<Point>(cx);
10220 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10221 }
10222
10223 fn go_to_hunk_after_position(
10224 &mut self,
10225 snapshot: &EditorSnapshot,
10226 position: Point,
10227 window: &mut Window,
10228 cx: &mut Context<Editor>,
10229 ) -> Option<MultiBufferDiffHunk> {
10230 let mut hunk = snapshot
10231 .buffer_snapshot
10232 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10233 .find(|hunk| hunk.row_range.start.0 > position.row);
10234 if hunk.is_none() {
10235 hunk = snapshot
10236 .buffer_snapshot
10237 .diff_hunks_in_range(Point::zero()..position)
10238 .find(|hunk| hunk.row_range.end.0 < position.row)
10239 }
10240 if let Some(hunk) = &hunk {
10241 let destination = Point::new(hunk.row_range.start.0, 0);
10242 self.unfold_ranges(&[destination..destination], false, false, cx);
10243 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10244 s.select_ranges(vec![destination..destination]);
10245 });
10246 }
10247
10248 hunk
10249 }
10250
10251 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10252 let snapshot = self.snapshot(window, cx);
10253 let selection = self.selections.newest::<Point>(cx);
10254 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10255 }
10256
10257 fn go_to_hunk_before_position(
10258 &mut self,
10259 snapshot: &EditorSnapshot,
10260 position: Point,
10261 window: &mut Window,
10262 cx: &mut Context<Editor>,
10263 ) -> Option<MultiBufferDiffHunk> {
10264 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10265 if hunk.is_none() {
10266 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10267 }
10268 if let Some(hunk) = &hunk {
10269 let destination = Point::new(hunk.row_range.start.0, 0);
10270 self.unfold_ranges(&[destination..destination], false, false, cx);
10271 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10272 s.select_ranges(vec![destination..destination]);
10273 });
10274 }
10275
10276 hunk
10277 }
10278
10279 pub fn go_to_definition(
10280 &mut self,
10281 _: &GoToDefinition,
10282 window: &mut Window,
10283 cx: &mut Context<Self>,
10284 ) -> Task<Result<Navigated>> {
10285 let definition =
10286 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10287 cx.spawn_in(window, |editor, mut cx| async move {
10288 if definition.await? == Navigated::Yes {
10289 return Ok(Navigated::Yes);
10290 }
10291 match editor.update_in(&mut cx, |editor, window, cx| {
10292 editor.find_all_references(&FindAllReferences, window, cx)
10293 })? {
10294 Some(references) => references.await,
10295 None => Ok(Navigated::No),
10296 }
10297 })
10298 }
10299
10300 pub fn go_to_declaration(
10301 &mut self,
10302 _: &GoToDeclaration,
10303 window: &mut Window,
10304 cx: &mut Context<Self>,
10305 ) -> Task<Result<Navigated>> {
10306 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10307 }
10308
10309 pub fn go_to_declaration_split(
10310 &mut self,
10311 _: &GoToDeclaration,
10312 window: &mut Window,
10313 cx: &mut Context<Self>,
10314 ) -> Task<Result<Navigated>> {
10315 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10316 }
10317
10318 pub fn go_to_implementation(
10319 &mut self,
10320 _: &GoToImplementation,
10321 window: &mut Window,
10322 cx: &mut Context<Self>,
10323 ) -> Task<Result<Navigated>> {
10324 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10325 }
10326
10327 pub fn go_to_implementation_split(
10328 &mut self,
10329 _: &GoToImplementationSplit,
10330 window: &mut Window,
10331 cx: &mut Context<Self>,
10332 ) -> Task<Result<Navigated>> {
10333 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10334 }
10335
10336 pub fn go_to_type_definition(
10337 &mut self,
10338 _: &GoToTypeDefinition,
10339 window: &mut Window,
10340 cx: &mut Context<Self>,
10341 ) -> Task<Result<Navigated>> {
10342 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10343 }
10344
10345 pub fn go_to_definition_split(
10346 &mut self,
10347 _: &GoToDefinitionSplit,
10348 window: &mut Window,
10349 cx: &mut Context<Self>,
10350 ) -> Task<Result<Navigated>> {
10351 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10352 }
10353
10354 pub fn go_to_type_definition_split(
10355 &mut self,
10356 _: &GoToTypeDefinitionSplit,
10357 window: &mut Window,
10358 cx: &mut Context<Self>,
10359 ) -> Task<Result<Navigated>> {
10360 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10361 }
10362
10363 fn go_to_definition_of_kind(
10364 &mut self,
10365 kind: GotoDefinitionKind,
10366 split: bool,
10367 window: &mut Window,
10368 cx: &mut Context<Self>,
10369 ) -> Task<Result<Navigated>> {
10370 let Some(provider) = self.semantics_provider.clone() else {
10371 return Task::ready(Ok(Navigated::No));
10372 };
10373 let head = self.selections.newest::<usize>(cx).head();
10374 let buffer = self.buffer.read(cx);
10375 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10376 text_anchor
10377 } else {
10378 return Task::ready(Ok(Navigated::No));
10379 };
10380
10381 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10382 return Task::ready(Ok(Navigated::No));
10383 };
10384
10385 cx.spawn_in(window, |editor, mut cx| async move {
10386 let definitions = definitions.await?;
10387 let navigated = editor
10388 .update_in(&mut cx, |editor, window, cx| {
10389 editor.navigate_to_hover_links(
10390 Some(kind),
10391 definitions
10392 .into_iter()
10393 .filter(|location| {
10394 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10395 })
10396 .map(HoverLink::Text)
10397 .collect::<Vec<_>>(),
10398 split,
10399 window,
10400 cx,
10401 )
10402 })?
10403 .await?;
10404 anyhow::Ok(navigated)
10405 })
10406 }
10407
10408 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10409 let selection = self.selections.newest_anchor();
10410 let head = selection.head();
10411 let tail = selection.tail();
10412
10413 let Some((buffer, start_position)) =
10414 self.buffer.read(cx).text_anchor_for_position(head, cx)
10415 else {
10416 return;
10417 };
10418
10419 let end_position = if head != tail {
10420 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10421 return;
10422 };
10423 Some(pos)
10424 } else {
10425 None
10426 };
10427
10428 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10429 let url = if let Some(end_pos) = end_position {
10430 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10431 } else {
10432 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10433 };
10434
10435 if let Some(url) = url {
10436 editor.update(&mut cx, |_, cx| {
10437 cx.open_url(&url);
10438 })
10439 } else {
10440 Ok(())
10441 }
10442 });
10443
10444 url_finder.detach();
10445 }
10446
10447 pub fn open_selected_filename(
10448 &mut self,
10449 _: &OpenSelectedFilename,
10450 window: &mut Window,
10451 cx: &mut Context<Self>,
10452 ) {
10453 let Some(workspace) = self.workspace() else {
10454 return;
10455 };
10456
10457 let position = self.selections.newest_anchor().head();
10458
10459 let Some((buffer, buffer_position)) =
10460 self.buffer.read(cx).text_anchor_for_position(position, cx)
10461 else {
10462 return;
10463 };
10464
10465 let project = self.project.clone();
10466
10467 cx.spawn_in(window, |_, mut cx| async move {
10468 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10469
10470 if let Some((_, path)) = result {
10471 workspace
10472 .update_in(&mut cx, |workspace, window, cx| {
10473 workspace.open_resolved_path(path, window, cx)
10474 })?
10475 .await?;
10476 }
10477 anyhow::Ok(())
10478 })
10479 .detach();
10480 }
10481
10482 pub(crate) fn navigate_to_hover_links(
10483 &mut self,
10484 kind: Option<GotoDefinitionKind>,
10485 mut definitions: Vec<HoverLink>,
10486 split: bool,
10487 window: &mut Window,
10488 cx: &mut Context<Editor>,
10489 ) -> Task<Result<Navigated>> {
10490 // If there is one definition, just open it directly
10491 if definitions.len() == 1 {
10492 let definition = definitions.pop().unwrap();
10493
10494 enum TargetTaskResult {
10495 Location(Option<Location>),
10496 AlreadyNavigated,
10497 }
10498
10499 let target_task = match definition {
10500 HoverLink::Text(link) => {
10501 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10502 }
10503 HoverLink::InlayHint(lsp_location, server_id) => {
10504 let computation =
10505 self.compute_target_location(lsp_location, server_id, window, cx);
10506 cx.background_executor().spawn(async move {
10507 let location = computation.await?;
10508 Ok(TargetTaskResult::Location(location))
10509 })
10510 }
10511 HoverLink::Url(url) => {
10512 cx.open_url(&url);
10513 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10514 }
10515 HoverLink::File(path) => {
10516 if let Some(workspace) = self.workspace() {
10517 cx.spawn_in(window, |_, mut cx| async move {
10518 workspace
10519 .update_in(&mut cx, |workspace, window, cx| {
10520 workspace.open_resolved_path(path, window, cx)
10521 })?
10522 .await
10523 .map(|_| TargetTaskResult::AlreadyNavigated)
10524 })
10525 } else {
10526 Task::ready(Ok(TargetTaskResult::Location(None)))
10527 }
10528 }
10529 };
10530 cx.spawn_in(window, |editor, mut cx| async move {
10531 let target = match target_task.await.context("target resolution task")? {
10532 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10533 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10534 TargetTaskResult::Location(Some(target)) => target,
10535 };
10536
10537 editor.update_in(&mut cx, |editor, window, cx| {
10538 let Some(workspace) = editor.workspace() else {
10539 return Navigated::No;
10540 };
10541 let pane = workspace.read(cx).active_pane().clone();
10542
10543 let range = target.range.to_point(target.buffer.read(cx));
10544 let range = editor.range_for_match(&range);
10545 let range = collapse_multiline_range(range);
10546
10547 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10548 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10549 } else {
10550 window.defer(cx, move |window, cx| {
10551 let target_editor: Entity<Self> =
10552 workspace.update(cx, |workspace, cx| {
10553 let pane = if split {
10554 workspace.adjacent_pane(window, cx)
10555 } else {
10556 workspace.active_pane().clone()
10557 };
10558
10559 workspace.open_project_item(
10560 pane,
10561 target.buffer.clone(),
10562 true,
10563 true,
10564 window,
10565 cx,
10566 )
10567 });
10568 target_editor.update(cx, |target_editor, cx| {
10569 // When selecting a definition in a different buffer, disable the nav history
10570 // to avoid creating a history entry at the previous cursor location.
10571 pane.update(cx, |pane, _| pane.disable_history());
10572 target_editor.go_to_singleton_buffer_range(range, window, cx);
10573 pane.update(cx, |pane, _| pane.enable_history());
10574 });
10575 });
10576 }
10577 Navigated::Yes
10578 })
10579 })
10580 } else if !definitions.is_empty() {
10581 cx.spawn_in(window, |editor, mut cx| async move {
10582 let (title, location_tasks, workspace) = editor
10583 .update_in(&mut cx, |editor, window, cx| {
10584 let tab_kind = match kind {
10585 Some(GotoDefinitionKind::Implementation) => "Implementations",
10586 _ => "Definitions",
10587 };
10588 let title = definitions
10589 .iter()
10590 .find_map(|definition| match definition {
10591 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10592 let buffer = origin.buffer.read(cx);
10593 format!(
10594 "{} for {}",
10595 tab_kind,
10596 buffer
10597 .text_for_range(origin.range.clone())
10598 .collect::<String>()
10599 )
10600 }),
10601 HoverLink::InlayHint(_, _) => None,
10602 HoverLink::Url(_) => None,
10603 HoverLink::File(_) => None,
10604 })
10605 .unwrap_or(tab_kind.to_string());
10606 let location_tasks = definitions
10607 .into_iter()
10608 .map(|definition| match definition {
10609 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10610 HoverLink::InlayHint(lsp_location, server_id) => editor
10611 .compute_target_location(lsp_location, server_id, window, cx),
10612 HoverLink::Url(_) => Task::ready(Ok(None)),
10613 HoverLink::File(_) => Task::ready(Ok(None)),
10614 })
10615 .collect::<Vec<_>>();
10616 (title, location_tasks, editor.workspace().clone())
10617 })
10618 .context("location tasks preparation")?;
10619
10620 let locations = future::join_all(location_tasks)
10621 .await
10622 .into_iter()
10623 .filter_map(|location| location.transpose())
10624 .collect::<Result<_>>()
10625 .context("location tasks")?;
10626
10627 let Some(workspace) = workspace else {
10628 return Ok(Navigated::No);
10629 };
10630 let opened = workspace
10631 .update_in(&mut cx, |workspace, window, cx| {
10632 Self::open_locations_in_multibuffer(
10633 workspace,
10634 locations,
10635 title,
10636 split,
10637 MultibufferSelectionMode::First,
10638 window,
10639 cx,
10640 )
10641 })
10642 .ok();
10643
10644 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10645 })
10646 } else {
10647 Task::ready(Ok(Navigated::No))
10648 }
10649 }
10650
10651 fn compute_target_location(
10652 &self,
10653 lsp_location: lsp::Location,
10654 server_id: LanguageServerId,
10655 window: &mut Window,
10656 cx: &mut Context<Self>,
10657 ) -> Task<anyhow::Result<Option<Location>>> {
10658 let Some(project) = self.project.clone() else {
10659 return Task::ready(Ok(None));
10660 };
10661
10662 cx.spawn_in(window, move |editor, mut cx| async move {
10663 let location_task = editor.update(&mut cx, |_, cx| {
10664 project.update(cx, |project, cx| {
10665 let language_server_name = project
10666 .language_server_statuses(cx)
10667 .find(|(id, _)| server_id == *id)
10668 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10669 language_server_name.map(|language_server_name| {
10670 project.open_local_buffer_via_lsp(
10671 lsp_location.uri.clone(),
10672 server_id,
10673 language_server_name,
10674 cx,
10675 )
10676 })
10677 })
10678 })?;
10679 let location = match location_task {
10680 Some(task) => Some({
10681 let target_buffer_handle = task.await.context("open local buffer")?;
10682 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10683 let target_start = target_buffer
10684 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10685 let target_end = target_buffer
10686 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10687 target_buffer.anchor_after(target_start)
10688 ..target_buffer.anchor_before(target_end)
10689 })?;
10690 Location {
10691 buffer: target_buffer_handle,
10692 range,
10693 }
10694 }),
10695 None => None,
10696 };
10697 Ok(location)
10698 })
10699 }
10700
10701 pub fn find_all_references(
10702 &mut self,
10703 _: &FindAllReferences,
10704 window: &mut Window,
10705 cx: &mut Context<Self>,
10706 ) -> Option<Task<Result<Navigated>>> {
10707 let selection = self.selections.newest::<usize>(cx);
10708 let multi_buffer = self.buffer.read(cx);
10709 let head = selection.head();
10710
10711 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10712 let head_anchor = multi_buffer_snapshot.anchor_at(
10713 head,
10714 if head < selection.tail() {
10715 Bias::Right
10716 } else {
10717 Bias::Left
10718 },
10719 );
10720
10721 match self
10722 .find_all_references_task_sources
10723 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10724 {
10725 Ok(_) => {
10726 log::info!(
10727 "Ignoring repeated FindAllReferences invocation with the position of already running task"
10728 );
10729 return None;
10730 }
10731 Err(i) => {
10732 self.find_all_references_task_sources.insert(i, head_anchor);
10733 }
10734 }
10735
10736 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10737 let workspace = self.workspace()?;
10738 let project = workspace.read(cx).project().clone();
10739 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10740 Some(cx.spawn_in(window, |editor, mut cx| async move {
10741 let _cleanup = defer({
10742 let mut cx = cx.clone();
10743 move || {
10744 let _ = editor.update(&mut cx, |editor, _| {
10745 if let Ok(i) =
10746 editor
10747 .find_all_references_task_sources
10748 .binary_search_by(|anchor| {
10749 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10750 })
10751 {
10752 editor.find_all_references_task_sources.remove(i);
10753 }
10754 });
10755 }
10756 });
10757
10758 let locations = references.await?;
10759 if locations.is_empty() {
10760 return anyhow::Ok(Navigated::No);
10761 }
10762
10763 workspace.update_in(&mut cx, |workspace, window, cx| {
10764 let title = locations
10765 .first()
10766 .as_ref()
10767 .map(|location| {
10768 let buffer = location.buffer.read(cx);
10769 format!(
10770 "References to `{}`",
10771 buffer
10772 .text_for_range(location.range.clone())
10773 .collect::<String>()
10774 )
10775 })
10776 .unwrap();
10777 Self::open_locations_in_multibuffer(
10778 workspace,
10779 locations,
10780 title,
10781 false,
10782 MultibufferSelectionMode::First,
10783 window,
10784 cx,
10785 );
10786 Navigated::Yes
10787 })
10788 }))
10789 }
10790
10791 /// Opens a multibuffer with the given project locations in it
10792 pub fn open_locations_in_multibuffer(
10793 workspace: &mut Workspace,
10794 mut locations: Vec<Location>,
10795 title: String,
10796 split: bool,
10797 multibuffer_selection_mode: MultibufferSelectionMode,
10798 window: &mut Window,
10799 cx: &mut Context<Workspace>,
10800 ) {
10801 // If there are multiple definitions, open them in a multibuffer
10802 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10803 let mut locations = locations.into_iter().peekable();
10804 let mut ranges = Vec::new();
10805 let capability = workspace.project().read(cx).capability();
10806
10807 let excerpt_buffer = cx.new(|cx| {
10808 let mut multibuffer = MultiBuffer::new(capability);
10809 while let Some(location) = locations.next() {
10810 let buffer = location.buffer.read(cx);
10811 let mut ranges_for_buffer = Vec::new();
10812 let range = location.range.to_offset(buffer);
10813 ranges_for_buffer.push(range.clone());
10814
10815 while let Some(next_location) = locations.peek() {
10816 if next_location.buffer == location.buffer {
10817 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10818 locations.next();
10819 } else {
10820 break;
10821 }
10822 }
10823
10824 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10825 ranges.extend(multibuffer.push_excerpts_with_context_lines(
10826 location.buffer.clone(),
10827 ranges_for_buffer,
10828 DEFAULT_MULTIBUFFER_CONTEXT,
10829 cx,
10830 ))
10831 }
10832
10833 multibuffer.with_title(title)
10834 });
10835
10836 let editor = cx.new(|cx| {
10837 Editor::for_multibuffer(
10838 excerpt_buffer,
10839 Some(workspace.project().clone()),
10840 true,
10841 window,
10842 cx,
10843 )
10844 });
10845 editor.update(cx, |editor, cx| {
10846 match multibuffer_selection_mode {
10847 MultibufferSelectionMode::First => {
10848 if let Some(first_range) = ranges.first() {
10849 editor.change_selections(None, window, cx, |selections| {
10850 selections.clear_disjoint();
10851 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10852 });
10853 }
10854 editor.highlight_background::<Self>(
10855 &ranges,
10856 |theme| theme.editor_highlighted_line_background,
10857 cx,
10858 );
10859 }
10860 MultibufferSelectionMode::All => {
10861 editor.change_selections(None, window, cx, |selections| {
10862 selections.clear_disjoint();
10863 selections.select_anchor_ranges(ranges);
10864 });
10865 }
10866 }
10867 editor.register_buffers_with_language_servers(cx);
10868 });
10869
10870 let item = Box::new(editor);
10871 let item_id = item.item_id();
10872
10873 if split {
10874 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
10875 } else {
10876 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10877 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10878 pane.close_current_preview_item(window, cx)
10879 } else {
10880 None
10881 }
10882 });
10883 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
10884 }
10885 workspace.active_pane().update(cx, |pane, cx| {
10886 pane.set_preview_item_id(Some(item_id), cx);
10887 });
10888 }
10889
10890 pub fn rename(
10891 &mut self,
10892 _: &Rename,
10893 window: &mut Window,
10894 cx: &mut Context<Self>,
10895 ) -> Option<Task<Result<()>>> {
10896 use language::ToOffset as _;
10897
10898 let provider = self.semantics_provider.clone()?;
10899 let selection = self.selections.newest_anchor().clone();
10900 let (cursor_buffer, cursor_buffer_position) = self
10901 .buffer
10902 .read(cx)
10903 .text_anchor_for_position(selection.head(), cx)?;
10904 let (tail_buffer, cursor_buffer_position_end) = self
10905 .buffer
10906 .read(cx)
10907 .text_anchor_for_position(selection.tail(), cx)?;
10908 if tail_buffer != cursor_buffer {
10909 return None;
10910 }
10911
10912 let snapshot = cursor_buffer.read(cx).snapshot();
10913 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10914 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10915 let prepare_rename = provider
10916 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10917 .unwrap_or_else(|| Task::ready(Ok(None)));
10918 drop(snapshot);
10919
10920 Some(cx.spawn_in(window, |this, mut cx| async move {
10921 let rename_range = if let Some(range) = prepare_rename.await? {
10922 Some(range)
10923 } else {
10924 this.update(&mut cx, |this, cx| {
10925 let buffer = this.buffer.read(cx).snapshot(cx);
10926 let mut buffer_highlights = this
10927 .document_highlights_for_position(selection.head(), &buffer)
10928 .filter(|highlight| {
10929 highlight.start.excerpt_id == selection.head().excerpt_id
10930 && highlight.end.excerpt_id == selection.head().excerpt_id
10931 });
10932 buffer_highlights
10933 .next()
10934 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10935 })?
10936 };
10937 if let Some(rename_range) = rename_range {
10938 this.update_in(&mut cx, |this, window, cx| {
10939 let snapshot = cursor_buffer.read(cx).snapshot();
10940 let rename_buffer_range = rename_range.to_offset(&snapshot);
10941 let cursor_offset_in_rename_range =
10942 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10943 let cursor_offset_in_rename_range_end =
10944 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10945
10946 this.take_rename(false, window, cx);
10947 let buffer = this.buffer.read(cx).read(cx);
10948 let cursor_offset = selection.head().to_offset(&buffer);
10949 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10950 let rename_end = rename_start + rename_buffer_range.len();
10951 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10952 let mut old_highlight_id = None;
10953 let old_name: Arc<str> = buffer
10954 .chunks(rename_start..rename_end, true)
10955 .map(|chunk| {
10956 if old_highlight_id.is_none() {
10957 old_highlight_id = chunk.syntax_highlight_id;
10958 }
10959 chunk.text
10960 })
10961 .collect::<String>()
10962 .into();
10963
10964 drop(buffer);
10965
10966 // Position the selection in the rename editor so that it matches the current selection.
10967 this.show_local_selections = false;
10968 let rename_editor = cx.new(|cx| {
10969 let mut editor = Editor::single_line(window, cx);
10970 editor.buffer.update(cx, |buffer, cx| {
10971 buffer.edit([(0..0, old_name.clone())], None, cx)
10972 });
10973 let rename_selection_range = match cursor_offset_in_rename_range
10974 .cmp(&cursor_offset_in_rename_range_end)
10975 {
10976 Ordering::Equal => {
10977 editor.select_all(&SelectAll, window, cx);
10978 return editor;
10979 }
10980 Ordering::Less => {
10981 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10982 }
10983 Ordering::Greater => {
10984 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10985 }
10986 };
10987 if rename_selection_range.end > old_name.len() {
10988 editor.select_all(&SelectAll, window, cx);
10989 } else {
10990 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10991 s.select_ranges([rename_selection_range]);
10992 });
10993 }
10994 editor
10995 });
10996 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10997 if e == &EditorEvent::Focused {
10998 cx.emit(EditorEvent::FocusedIn)
10999 }
11000 })
11001 .detach();
11002
11003 let write_highlights =
11004 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11005 let read_highlights =
11006 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11007 let ranges = write_highlights
11008 .iter()
11009 .flat_map(|(_, ranges)| ranges.iter())
11010 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11011 .cloned()
11012 .collect();
11013
11014 this.highlight_text::<Rename>(
11015 ranges,
11016 HighlightStyle {
11017 fade_out: Some(0.6),
11018 ..Default::default()
11019 },
11020 cx,
11021 );
11022 let rename_focus_handle = rename_editor.focus_handle(cx);
11023 window.focus(&rename_focus_handle);
11024 let block_id = this.insert_blocks(
11025 [BlockProperties {
11026 style: BlockStyle::Flex,
11027 placement: BlockPlacement::Below(range.start),
11028 height: 1,
11029 render: Arc::new({
11030 let rename_editor = rename_editor.clone();
11031 move |cx: &mut BlockContext| {
11032 let mut text_style = cx.editor_style.text.clone();
11033 if let Some(highlight_style) = old_highlight_id
11034 .and_then(|h| h.style(&cx.editor_style.syntax))
11035 {
11036 text_style = text_style.highlight(highlight_style);
11037 }
11038 div()
11039 .block_mouse_down()
11040 .pl(cx.anchor_x)
11041 .child(EditorElement::new(
11042 &rename_editor,
11043 EditorStyle {
11044 background: cx.theme().system().transparent,
11045 local_player: cx.editor_style.local_player,
11046 text: text_style,
11047 scrollbar_width: cx.editor_style.scrollbar_width,
11048 syntax: cx.editor_style.syntax.clone(),
11049 status: cx.editor_style.status.clone(),
11050 inlay_hints_style: HighlightStyle {
11051 font_weight: Some(FontWeight::BOLD),
11052 ..make_inlay_hints_style(cx.app)
11053 },
11054 inline_completion_styles: make_suggestion_styles(
11055 cx.app,
11056 ),
11057 ..EditorStyle::default()
11058 },
11059 ))
11060 .into_any_element()
11061 }
11062 }),
11063 priority: 0,
11064 }],
11065 Some(Autoscroll::fit()),
11066 cx,
11067 )[0];
11068 this.pending_rename = Some(RenameState {
11069 range,
11070 old_name,
11071 editor: rename_editor,
11072 block_id,
11073 });
11074 })?;
11075 }
11076
11077 Ok(())
11078 }))
11079 }
11080
11081 pub fn confirm_rename(
11082 &mut self,
11083 _: &ConfirmRename,
11084 window: &mut Window,
11085 cx: &mut Context<Self>,
11086 ) -> Option<Task<Result<()>>> {
11087 let rename = self.take_rename(false, window, cx)?;
11088 let workspace = self.workspace()?.downgrade();
11089 let (buffer, start) = self
11090 .buffer
11091 .read(cx)
11092 .text_anchor_for_position(rename.range.start, cx)?;
11093 let (end_buffer, _) = self
11094 .buffer
11095 .read(cx)
11096 .text_anchor_for_position(rename.range.end, cx)?;
11097 if buffer != end_buffer {
11098 return None;
11099 }
11100
11101 let old_name = rename.old_name;
11102 let new_name = rename.editor.read(cx).text(cx);
11103
11104 let rename = self.semantics_provider.as_ref()?.perform_rename(
11105 &buffer,
11106 start,
11107 new_name.clone(),
11108 cx,
11109 )?;
11110
11111 Some(cx.spawn_in(window, |editor, mut cx| async move {
11112 let project_transaction = rename.await?;
11113 Self::open_project_transaction(
11114 &editor,
11115 workspace,
11116 project_transaction,
11117 format!("Rename: {} → {}", old_name, new_name),
11118 cx.clone(),
11119 )
11120 .await?;
11121
11122 editor.update(&mut cx, |editor, cx| {
11123 editor.refresh_document_highlights(cx);
11124 })?;
11125 Ok(())
11126 }))
11127 }
11128
11129 fn take_rename(
11130 &mut self,
11131 moving_cursor: bool,
11132 window: &mut Window,
11133 cx: &mut Context<Self>,
11134 ) -> Option<RenameState> {
11135 let rename = self.pending_rename.take()?;
11136 if rename.editor.focus_handle(cx).is_focused(window) {
11137 window.focus(&self.focus_handle);
11138 }
11139
11140 self.remove_blocks(
11141 [rename.block_id].into_iter().collect(),
11142 Some(Autoscroll::fit()),
11143 cx,
11144 );
11145 self.clear_highlights::<Rename>(cx);
11146 self.show_local_selections = true;
11147
11148 if moving_cursor {
11149 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11150 editor.selections.newest::<usize>(cx).head()
11151 });
11152
11153 // Update the selection to match the position of the selection inside
11154 // the rename editor.
11155 let snapshot = self.buffer.read(cx).read(cx);
11156 let rename_range = rename.range.to_offset(&snapshot);
11157 let cursor_in_editor = snapshot
11158 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11159 .min(rename_range.end);
11160 drop(snapshot);
11161
11162 self.change_selections(None, window, cx, |s| {
11163 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11164 });
11165 } else {
11166 self.refresh_document_highlights(cx);
11167 }
11168
11169 Some(rename)
11170 }
11171
11172 pub fn pending_rename(&self) -> Option<&RenameState> {
11173 self.pending_rename.as_ref()
11174 }
11175
11176 fn format(
11177 &mut self,
11178 _: &Format,
11179 window: &mut Window,
11180 cx: &mut Context<Self>,
11181 ) -> Option<Task<Result<()>>> {
11182 let project = match &self.project {
11183 Some(project) => project.clone(),
11184 None => return None,
11185 };
11186
11187 Some(self.perform_format(
11188 project,
11189 FormatTrigger::Manual,
11190 FormatTarget::Buffers,
11191 window,
11192 cx,
11193 ))
11194 }
11195
11196 fn format_selections(
11197 &mut self,
11198 _: &FormatSelections,
11199 window: &mut Window,
11200 cx: &mut Context<Self>,
11201 ) -> Option<Task<Result<()>>> {
11202 let project = match &self.project {
11203 Some(project) => project.clone(),
11204 None => return None,
11205 };
11206
11207 let ranges = self
11208 .selections
11209 .all_adjusted(cx)
11210 .into_iter()
11211 .map(|selection| selection.range())
11212 .collect_vec();
11213
11214 Some(self.perform_format(
11215 project,
11216 FormatTrigger::Manual,
11217 FormatTarget::Ranges(ranges),
11218 window,
11219 cx,
11220 ))
11221 }
11222
11223 fn perform_format(
11224 &mut self,
11225 project: Entity<Project>,
11226 trigger: FormatTrigger,
11227 target: FormatTarget,
11228 window: &mut Window,
11229 cx: &mut Context<Self>,
11230 ) -> Task<Result<()>> {
11231 let buffer = self.buffer.clone();
11232 let (buffers, target) = match target {
11233 FormatTarget::Buffers => {
11234 let mut buffers = buffer.read(cx).all_buffers();
11235 if trigger == FormatTrigger::Save {
11236 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11237 }
11238 (buffers, LspFormatTarget::Buffers)
11239 }
11240 FormatTarget::Ranges(selection_ranges) => {
11241 let multi_buffer = buffer.read(cx);
11242 let snapshot = multi_buffer.read(cx);
11243 let mut buffers = HashSet::default();
11244 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11245 BTreeMap::new();
11246 for selection_range in selection_ranges {
11247 for (buffer, buffer_range, _) in
11248 snapshot.range_to_buffer_ranges(selection_range)
11249 {
11250 let buffer_id = buffer.remote_id();
11251 let start = buffer.anchor_before(buffer_range.start);
11252 let end = buffer.anchor_after(buffer_range.end);
11253 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11254 buffer_id_to_ranges
11255 .entry(buffer_id)
11256 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11257 .or_insert_with(|| vec![start..end]);
11258 }
11259 }
11260 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11261 }
11262 };
11263
11264 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11265 let format = project.update(cx, |project, cx| {
11266 project.format(buffers, target, true, trigger, cx)
11267 });
11268
11269 cx.spawn_in(window, |_, mut cx| async move {
11270 let transaction = futures::select_biased! {
11271 () = timeout => {
11272 log::warn!("timed out waiting for formatting");
11273 None
11274 }
11275 transaction = format.log_err().fuse() => transaction,
11276 };
11277
11278 buffer
11279 .update(&mut cx, |buffer, cx| {
11280 if let Some(transaction) = transaction {
11281 if !buffer.is_singleton() {
11282 buffer.push_transaction(&transaction.0, cx);
11283 }
11284 }
11285
11286 cx.notify();
11287 })
11288 .ok();
11289
11290 Ok(())
11291 })
11292 }
11293
11294 fn restart_language_server(
11295 &mut self,
11296 _: &RestartLanguageServer,
11297 _: &mut Window,
11298 cx: &mut Context<Self>,
11299 ) {
11300 if let Some(project) = self.project.clone() {
11301 self.buffer.update(cx, |multi_buffer, cx| {
11302 project.update(cx, |project, cx| {
11303 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11304 });
11305 })
11306 }
11307 }
11308
11309 fn cancel_language_server_work(
11310 &mut self,
11311 _: &actions::CancelLanguageServerWork,
11312 _: &mut Window,
11313 cx: &mut Context<Self>,
11314 ) {
11315 if let Some(project) = self.project.clone() {
11316 self.buffer.update(cx, |multi_buffer, cx| {
11317 project.update(cx, |project, cx| {
11318 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
11319 });
11320 })
11321 }
11322 }
11323
11324 fn show_character_palette(
11325 &mut self,
11326 _: &ShowCharacterPalette,
11327 window: &mut Window,
11328 _: &mut Context<Self>,
11329 ) {
11330 window.show_character_palette();
11331 }
11332
11333 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11334 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11335 let buffer = self.buffer.read(cx).snapshot(cx);
11336 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11337 let is_valid = buffer
11338 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone())
11339 .any(|entry| {
11340 entry.diagnostic.is_primary
11341 && !entry.range.is_empty()
11342 && entry.range.start == primary_range_start
11343 && entry.diagnostic.message == active_diagnostics.primary_message
11344 });
11345
11346 if is_valid != active_diagnostics.is_valid {
11347 active_diagnostics.is_valid = is_valid;
11348 let mut new_styles = HashMap::default();
11349 for (block_id, diagnostic) in &active_diagnostics.blocks {
11350 new_styles.insert(
11351 *block_id,
11352 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11353 );
11354 }
11355 self.display_map.update(cx, |display_map, _cx| {
11356 display_map.replace_blocks(new_styles)
11357 });
11358 }
11359 }
11360 }
11361
11362 fn activate_diagnostics(
11363 &mut self,
11364 buffer_id: BufferId,
11365 group_id: usize,
11366 window: &mut Window,
11367 cx: &mut Context<Self>,
11368 ) {
11369 self.dismiss_diagnostics(cx);
11370 let snapshot = self.snapshot(window, cx);
11371 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11372 let buffer = self.buffer.read(cx).snapshot(cx);
11373
11374 let mut primary_range = None;
11375 let mut primary_message = None;
11376 let diagnostic_group = buffer
11377 .diagnostic_group(buffer_id, group_id)
11378 .filter_map(|entry| {
11379 let start = entry.range.start;
11380 let end = entry.range.end;
11381 if snapshot.is_line_folded(MultiBufferRow(start.row))
11382 && (start.row == end.row
11383 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11384 {
11385 return None;
11386 }
11387 if entry.diagnostic.is_primary {
11388 primary_range = Some(entry.range.clone());
11389 primary_message = Some(entry.diagnostic.message.clone());
11390 }
11391 Some(entry)
11392 })
11393 .collect::<Vec<_>>();
11394 let primary_range = primary_range?;
11395 let primary_message = primary_message?;
11396
11397 let blocks = display_map
11398 .insert_blocks(
11399 diagnostic_group.iter().map(|entry| {
11400 let diagnostic = entry.diagnostic.clone();
11401 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11402 BlockProperties {
11403 style: BlockStyle::Fixed,
11404 placement: BlockPlacement::Below(
11405 buffer.anchor_after(entry.range.start),
11406 ),
11407 height: message_height,
11408 render: diagnostic_block_renderer(diagnostic, None, true, true),
11409 priority: 0,
11410 }
11411 }),
11412 cx,
11413 )
11414 .into_iter()
11415 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11416 .collect();
11417
11418 Some(ActiveDiagnosticGroup {
11419 primary_range: buffer.anchor_before(primary_range.start)
11420 ..buffer.anchor_after(primary_range.end),
11421 primary_message,
11422 group_id,
11423 blocks,
11424 is_valid: true,
11425 })
11426 });
11427 }
11428
11429 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11430 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11431 self.display_map.update(cx, |display_map, cx| {
11432 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11433 });
11434 cx.notify();
11435 }
11436 }
11437
11438 pub fn set_selections_from_remote(
11439 &mut self,
11440 selections: Vec<Selection<Anchor>>,
11441 pending_selection: Option<Selection<Anchor>>,
11442 window: &mut Window,
11443 cx: &mut Context<Self>,
11444 ) {
11445 let old_cursor_position = self.selections.newest_anchor().head();
11446 self.selections.change_with(cx, |s| {
11447 s.select_anchors(selections);
11448 if let Some(pending_selection) = pending_selection {
11449 s.set_pending(pending_selection, SelectMode::Character);
11450 } else {
11451 s.clear_pending();
11452 }
11453 });
11454 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11455 }
11456
11457 fn push_to_selection_history(&mut self) {
11458 self.selection_history.push(SelectionHistoryEntry {
11459 selections: self.selections.disjoint_anchors(),
11460 select_next_state: self.select_next_state.clone(),
11461 select_prev_state: self.select_prev_state.clone(),
11462 add_selections_state: self.add_selections_state.clone(),
11463 });
11464 }
11465
11466 pub fn transact(
11467 &mut self,
11468 window: &mut Window,
11469 cx: &mut Context<Self>,
11470 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11471 ) -> Option<TransactionId> {
11472 self.start_transaction_at(Instant::now(), window, cx);
11473 update(self, window, cx);
11474 self.end_transaction_at(Instant::now(), cx)
11475 }
11476
11477 pub fn start_transaction_at(
11478 &mut self,
11479 now: Instant,
11480 window: &mut Window,
11481 cx: &mut Context<Self>,
11482 ) {
11483 self.end_selection(window, cx);
11484 if let Some(tx_id) = self
11485 .buffer
11486 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11487 {
11488 self.selection_history
11489 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11490 cx.emit(EditorEvent::TransactionBegun {
11491 transaction_id: tx_id,
11492 })
11493 }
11494 }
11495
11496 pub fn end_transaction_at(
11497 &mut self,
11498 now: Instant,
11499 cx: &mut Context<Self>,
11500 ) -> Option<TransactionId> {
11501 if let Some(transaction_id) = self
11502 .buffer
11503 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11504 {
11505 if let Some((_, end_selections)) =
11506 self.selection_history.transaction_mut(transaction_id)
11507 {
11508 *end_selections = Some(self.selections.disjoint_anchors());
11509 } else {
11510 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11511 }
11512
11513 cx.emit(EditorEvent::Edited { transaction_id });
11514 Some(transaction_id)
11515 } else {
11516 None
11517 }
11518 }
11519
11520 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11521 if self.selection_mark_mode {
11522 self.change_selections(None, window, cx, |s| {
11523 s.move_with(|_, sel| {
11524 sel.collapse_to(sel.head(), SelectionGoal::None);
11525 });
11526 })
11527 }
11528 self.selection_mark_mode = true;
11529 cx.notify();
11530 }
11531
11532 pub fn swap_selection_ends(
11533 &mut self,
11534 _: &actions::SwapSelectionEnds,
11535 window: &mut Window,
11536 cx: &mut Context<Self>,
11537 ) {
11538 self.change_selections(None, window, cx, |s| {
11539 s.move_with(|_, sel| {
11540 if sel.start != sel.end {
11541 sel.reversed = !sel.reversed
11542 }
11543 });
11544 });
11545 self.request_autoscroll(Autoscroll::newest(), cx);
11546 cx.notify();
11547 }
11548
11549 pub fn toggle_fold(
11550 &mut self,
11551 _: &actions::ToggleFold,
11552 window: &mut Window,
11553 cx: &mut Context<Self>,
11554 ) {
11555 if self.is_singleton(cx) {
11556 let selection = self.selections.newest::<Point>(cx);
11557
11558 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11559 let range = if selection.is_empty() {
11560 let point = selection.head().to_display_point(&display_map);
11561 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11562 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11563 .to_point(&display_map);
11564 start..end
11565 } else {
11566 selection.range()
11567 };
11568 if display_map.folds_in_range(range).next().is_some() {
11569 self.unfold_lines(&Default::default(), window, cx)
11570 } else {
11571 self.fold(&Default::default(), window, cx)
11572 }
11573 } else {
11574 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11575 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11576 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11577 .map(|(snapshot, _, _)| snapshot.remote_id())
11578 .collect();
11579
11580 for buffer_id in buffer_ids {
11581 if self.is_buffer_folded(buffer_id, cx) {
11582 self.unfold_buffer(buffer_id, cx);
11583 } else {
11584 self.fold_buffer(buffer_id, cx);
11585 }
11586 }
11587 }
11588 }
11589
11590 pub fn toggle_fold_recursive(
11591 &mut self,
11592 _: &actions::ToggleFoldRecursive,
11593 window: &mut Window,
11594 cx: &mut Context<Self>,
11595 ) {
11596 let selection = self.selections.newest::<Point>(cx);
11597
11598 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11599 let range = if selection.is_empty() {
11600 let point = selection.head().to_display_point(&display_map);
11601 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11602 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11603 .to_point(&display_map);
11604 start..end
11605 } else {
11606 selection.range()
11607 };
11608 if display_map.folds_in_range(range).next().is_some() {
11609 self.unfold_recursive(&Default::default(), window, cx)
11610 } else {
11611 self.fold_recursive(&Default::default(), window, cx)
11612 }
11613 }
11614
11615 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11616 if self.is_singleton(cx) {
11617 let mut to_fold = Vec::new();
11618 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11619 let selections = self.selections.all_adjusted(cx);
11620
11621 for selection in selections {
11622 let range = selection.range().sorted();
11623 let buffer_start_row = range.start.row;
11624
11625 if range.start.row != range.end.row {
11626 let mut found = false;
11627 let mut row = range.start.row;
11628 while row <= range.end.row {
11629 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11630 {
11631 found = true;
11632 row = crease.range().end.row + 1;
11633 to_fold.push(crease);
11634 } else {
11635 row += 1
11636 }
11637 }
11638 if found {
11639 continue;
11640 }
11641 }
11642
11643 for row in (0..=range.start.row).rev() {
11644 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11645 if crease.range().end.row >= buffer_start_row {
11646 to_fold.push(crease);
11647 if row <= range.start.row {
11648 break;
11649 }
11650 }
11651 }
11652 }
11653 }
11654
11655 self.fold_creases(to_fold, true, window, cx);
11656 } else {
11657 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11658
11659 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11660 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11661 .map(|(snapshot, _, _)| snapshot.remote_id())
11662 .collect();
11663 for buffer_id in buffer_ids {
11664 self.fold_buffer(buffer_id, cx);
11665 }
11666 }
11667 }
11668
11669 fn fold_at_level(
11670 &mut self,
11671 fold_at: &FoldAtLevel,
11672 window: &mut Window,
11673 cx: &mut Context<Self>,
11674 ) {
11675 if !self.buffer.read(cx).is_singleton() {
11676 return;
11677 }
11678
11679 let fold_at_level = fold_at.level;
11680 let snapshot = self.buffer.read(cx).snapshot(cx);
11681 let mut to_fold = Vec::new();
11682 let mut stack = vec![(0, snapshot.max_row().0, 1)];
11683
11684 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11685 while start_row < end_row {
11686 match self
11687 .snapshot(window, cx)
11688 .crease_for_buffer_row(MultiBufferRow(start_row))
11689 {
11690 Some(crease) => {
11691 let nested_start_row = crease.range().start.row + 1;
11692 let nested_end_row = crease.range().end.row;
11693
11694 if current_level < fold_at_level {
11695 stack.push((nested_start_row, nested_end_row, current_level + 1));
11696 } else if current_level == fold_at_level {
11697 to_fold.push(crease);
11698 }
11699
11700 start_row = nested_end_row + 1;
11701 }
11702 None => start_row += 1,
11703 }
11704 }
11705 }
11706
11707 self.fold_creases(to_fold, true, window, cx);
11708 }
11709
11710 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11711 if self.buffer.read(cx).is_singleton() {
11712 let mut fold_ranges = Vec::new();
11713 let snapshot = self.buffer.read(cx).snapshot(cx);
11714
11715 for row in 0..snapshot.max_row().0 {
11716 if let Some(foldable_range) = self
11717 .snapshot(window, cx)
11718 .crease_for_buffer_row(MultiBufferRow(row))
11719 {
11720 fold_ranges.push(foldable_range);
11721 }
11722 }
11723
11724 self.fold_creases(fold_ranges, true, window, cx);
11725 } else {
11726 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11727 editor
11728 .update_in(&mut cx, |editor, _, cx| {
11729 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11730 editor.fold_buffer(buffer_id, cx);
11731 }
11732 })
11733 .ok();
11734 });
11735 }
11736 }
11737
11738 pub fn fold_function_bodies(
11739 &mut self,
11740 _: &actions::FoldFunctionBodies,
11741 window: &mut Window,
11742 cx: &mut Context<Self>,
11743 ) {
11744 let snapshot = self.buffer.read(cx).snapshot(cx);
11745
11746 let ranges = snapshot
11747 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11748 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11749 .collect::<Vec<_>>();
11750
11751 let creases = ranges
11752 .into_iter()
11753 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11754 .collect();
11755
11756 self.fold_creases(creases, true, window, cx);
11757 }
11758
11759 pub fn fold_recursive(
11760 &mut self,
11761 _: &actions::FoldRecursive,
11762 window: &mut Window,
11763 cx: &mut Context<Self>,
11764 ) {
11765 let mut to_fold = Vec::new();
11766 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11767 let selections = self.selections.all_adjusted(cx);
11768
11769 for selection in selections {
11770 let range = selection.range().sorted();
11771 let buffer_start_row = range.start.row;
11772
11773 if range.start.row != range.end.row {
11774 let mut found = false;
11775 for row in range.start.row..=range.end.row {
11776 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11777 found = true;
11778 to_fold.push(crease);
11779 }
11780 }
11781 if found {
11782 continue;
11783 }
11784 }
11785
11786 for row in (0..=range.start.row).rev() {
11787 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11788 if crease.range().end.row >= buffer_start_row {
11789 to_fold.push(crease);
11790 } else {
11791 break;
11792 }
11793 }
11794 }
11795 }
11796
11797 self.fold_creases(to_fold, true, window, cx);
11798 }
11799
11800 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11801 let buffer_row = fold_at.buffer_row;
11802 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11803
11804 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11805 let autoscroll = self
11806 .selections
11807 .all::<Point>(cx)
11808 .iter()
11809 .any(|selection| crease.range().overlaps(&selection.range()));
11810
11811 self.fold_creases(vec![crease], autoscroll, window, cx);
11812 }
11813 }
11814
11815 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
11816 if self.is_singleton(cx) {
11817 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11818 let buffer = &display_map.buffer_snapshot;
11819 let selections = self.selections.all::<Point>(cx);
11820 let ranges = selections
11821 .iter()
11822 .map(|s| {
11823 let range = s.display_range(&display_map).sorted();
11824 let mut start = range.start.to_point(&display_map);
11825 let mut end = range.end.to_point(&display_map);
11826 start.column = 0;
11827 end.column = buffer.line_len(MultiBufferRow(end.row));
11828 start..end
11829 })
11830 .collect::<Vec<_>>();
11831
11832 self.unfold_ranges(&ranges, true, true, cx);
11833 } else {
11834 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11835 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11836 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11837 .map(|(snapshot, _, _)| snapshot.remote_id())
11838 .collect();
11839 for buffer_id in buffer_ids {
11840 self.unfold_buffer(buffer_id, cx);
11841 }
11842 }
11843 }
11844
11845 pub fn unfold_recursive(
11846 &mut self,
11847 _: &UnfoldRecursive,
11848 _window: &mut Window,
11849 cx: &mut Context<Self>,
11850 ) {
11851 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11852 let selections = self.selections.all::<Point>(cx);
11853 let ranges = selections
11854 .iter()
11855 .map(|s| {
11856 let mut range = s.display_range(&display_map).sorted();
11857 *range.start.column_mut() = 0;
11858 *range.end.column_mut() = display_map.line_len(range.end.row());
11859 let start = range.start.to_point(&display_map);
11860 let end = range.end.to_point(&display_map);
11861 start..end
11862 })
11863 .collect::<Vec<_>>();
11864
11865 self.unfold_ranges(&ranges, true, true, cx);
11866 }
11867
11868 pub fn unfold_at(
11869 &mut self,
11870 unfold_at: &UnfoldAt,
11871 _window: &mut Window,
11872 cx: &mut Context<Self>,
11873 ) {
11874 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11875
11876 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11877 ..Point::new(
11878 unfold_at.buffer_row.0,
11879 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11880 );
11881
11882 let autoscroll = self
11883 .selections
11884 .all::<Point>(cx)
11885 .iter()
11886 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11887
11888 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
11889 }
11890
11891 pub fn unfold_all(
11892 &mut self,
11893 _: &actions::UnfoldAll,
11894 _window: &mut Window,
11895 cx: &mut Context<Self>,
11896 ) {
11897 if self.buffer.read(cx).is_singleton() {
11898 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11899 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11900 } else {
11901 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
11902 editor
11903 .update(&mut cx, |editor, cx| {
11904 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11905 editor.unfold_buffer(buffer_id, cx);
11906 }
11907 })
11908 .ok();
11909 });
11910 }
11911 }
11912
11913 pub fn fold_selected_ranges(
11914 &mut self,
11915 _: &FoldSelectedRanges,
11916 window: &mut Window,
11917 cx: &mut Context<Self>,
11918 ) {
11919 let selections = self.selections.all::<Point>(cx);
11920 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11921 let line_mode = self.selections.line_mode;
11922 let ranges = selections
11923 .into_iter()
11924 .map(|s| {
11925 if line_mode {
11926 let start = Point::new(s.start.row, 0);
11927 let end = Point::new(
11928 s.end.row,
11929 display_map
11930 .buffer_snapshot
11931 .line_len(MultiBufferRow(s.end.row)),
11932 );
11933 Crease::simple(start..end, display_map.fold_placeholder.clone())
11934 } else {
11935 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11936 }
11937 })
11938 .collect::<Vec<_>>();
11939 self.fold_creases(ranges, true, window, cx);
11940 }
11941
11942 pub fn fold_ranges<T: ToOffset + Clone>(
11943 &mut self,
11944 ranges: Vec<Range<T>>,
11945 auto_scroll: bool,
11946 window: &mut Window,
11947 cx: &mut Context<Self>,
11948 ) {
11949 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11950 let ranges = ranges
11951 .into_iter()
11952 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
11953 .collect::<Vec<_>>();
11954 self.fold_creases(ranges, auto_scroll, window, cx);
11955 }
11956
11957 pub fn fold_creases<T: ToOffset + Clone>(
11958 &mut self,
11959 creases: Vec<Crease<T>>,
11960 auto_scroll: bool,
11961 window: &mut Window,
11962 cx: &mut Context<Self>,
11963 ) {
11964 if creases.is_empty() {
11965 return;
11966 }
11967
11968 let mut buffers_affected = HashSet::default();
11969 let multi_buffer = self.buffer().read(cx);
11970 for crease in &creases {
11971 if let Some((_, buffer, _)) =
11972 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11973 {
11974 buffers_affected.insert(buffer.read(cx).remote_id());
11975 };
11976 }
11977
11978 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11979
11980 if auto_scroll {
11981 self.request_autoscroll(Autoscroll::fit(), cx);
11982 }
11983
11984 cx.notify();
11985
11986 if let Some(active_diagnostics) = self.active_diagnostics.take() {
11987 // Clear diagnostics block when folding a range that contains it.
11988 let snapshot = self.snapshot(window, cx);
11989 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11990 drop(snapshot);
11991 self.active_diagnostics = Some(active_diagnostics);
11992 self.dismiss_diagnostics(cx);
11993 } else {
11994 self.active_diagnostics = Some(active_diagnostics);
11995 }
11996 }
11997
11998 self.scrollbar_marker_state.dirty = true;
11999 }
12000
12001 /// Removes any folds whose ranges intersect any of the given ranges.
12002 pub fn unfold_ranges<T: ToOffset + Clone>(
12003 &mut self,
12004 ranges: &[Range<T>],
12005 inclusive: bool,
12006 auto_scroll: bool,
12007 cx: &mut Context<Self>,
12008 ) {
12009 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12010 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12011 });
12012 }
12013
12014 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12015 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12016 return;
12017 }
12018 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12019 self.display_map
12020 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12021 cx.emit(EditorEvent::BufferFoldToggled {
12022 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12023 folded: true,
12024 });
12025 cx.notify();
12026 }
12027
12028 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12029 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12030 return;
12031 }
12032 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12033 self.display_map.update(cx, |display_map, cx| {
12034 display_map.unfold_buffer(buffer_id, cx);
12035 });
12036 cx.emit(EditorEvent::BufferFoldToggled {
12037 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12038 folded: false,
12039 });
12040 cx.notify();
12041 }
12042
12043 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12044 self.display_map.read(cx).is_buffer_folded(buffer)
12045 }
12046
12047 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12048 self.display_map.read(cx).folded_buffers()
12049 }
12050
12051 /// Removes any folds with the given ranges.
12052 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12053 &mut self,
12054 ranges: &[Range<T>],
12055 type_id: TypeId,
12056 auto_scroll: bool,
12057 cx: &mut Context<Self>,
12058 ) {
12059 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12060 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12061 });
12062 }
12063
12064 fn remove_folds_with<T: ToOffset + Clone>(
12065 &mut self,
12066 ranges: &[Range<T>],
12067 auto_scroll: bool,
12068 cx: &mut Context<Self>,
12069 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12070 ) {
12071 if ranges.is_empty() {
12072 return;
12073 }
12074
12075 let mut buffers_affected = HashSet::default();
12076 let multi_buffer = self.buffer().read(cx);
12077 for range in ranges {
12078 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12079 buffers_affected.insert(buffer.read(cx).remote_id());
12080 };
12081 }
12082
12083 self.display_map.update(cx, update);
12084
12085 if auto_scroll {
12086 self.request_autoscroll(Autoscroll::fit(), cx);
12087 }
12088
12089 cx.notify();
12090 self.scrollbar_marker_state.dirty = true;
12091 self.active_indent_guides_state.dirty = true;
12092 }
12093
12094 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12095 self.display_map.read(cx).fold_placeholder.clone()
12096 }
12097
12098 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12099 self.buffer.update(cx, |buffer, cx| {
12100 buffer.set_all_diff_hunks_expanded(cx);
12101 });
12102 }
12103
12104 pub fn expand_all_diff_hunks(
12105 &mut self,
12106 _: &ExpandAllHunkDiffs,
12107 _window: &mut Window,
12108 cx: &mut Context<Self>,
12109 ) {
12110 self.buffer.update(cx, |buffer, cx| {
12111 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12112 });
12113 }
12114
12115 pub fn toggle_selected_diff_hunks(
12116 &mut self,
12117 _: &ToggleSelectedDiffHunks,
12118 _window: &mut Window,
12119 cx: &mut Context<Self>,
12120 ) {
12121 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12122 self.toggle_diff_hunks_in_ranges(ranges, cx);
12123 }
12124
12125 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12126 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12127 self.buffer
12128 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12129 }
12130
12131 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12132 self.buffer.update(cx, |buffer, cx| {
12133 let ranges = vec![Anchor::min()..Anchor::max()];
12134 if !buffer.all_diff_hunks_expanded()
12135 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12136 {
12137 buffer.collapse_diff_hunks(ranges, cx);
12138 true
12139 } else {
12140 false
12141 }
12142 })
12143 }
12144
12145 fn toggle_diff_hunks_in_ranges(
12146 &mut self,
12147 ranges: Vec<Range<Anchor>>,
12148 cx: &mut Context<'_, Editor>,
12149 ) {
12150 self.buffer.update(cx, |buffer, cx| {
12151 if buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx) {
12152 buffer.collapse_diff_hunks(ranges, cx)
12153 } else {
12154 buffer.expand_diff_hunks(ranges, cx)
12155 }
12156 })
12157 }
12158
12159 pub(crate) fn apply_all_diff_hunks(
12160 &mut self,
12161 _: &ApplyAllDiffHunks,
12162 window: &mut Window,
12163 cx: &mut Context<Self>,
12164 ) {
12165 let buffers = self.buffer.read(cx).all_buffers();
12166 for branch_buffer in buffers {
12167 branch_buffer.update(cx, |branch_buffer, cx| {
12168 branch_buffer.merge_into_base(Vec::new(), cx);
12169 });
12170 }
12171
12172 if let Some(project) = self.project.clone() {
12173 self.save(true, project, window, cx).detach_and_log_err(cx);
12174 }
12175 }
12176
12177 pub(crate) fn apply_selected_diff_hunks(
12178 &mut self,
12179 _: &ApplyDiffHunk,
12180 window: &mut Window,
12181 cx: &mut Context<Self>,
12182 ) {
12183 let snapshot = self.snapshot(window, cx);
12184 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12185 let mut ranges_by_buffer = HashMap::default();
12186 self.transact(window, cx, |editor, _window, cx| {
12187 for hunk in hunks {
12188 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12189 ranges_by_buffer
12190 .entry(buffer.clone())
12191 .or_insert_with(Vec::new)
12192 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12193 }
12194 }
12195
12196 for (buffer, ranges) in ranges_by_buffer {
12197 buffer.update(cx, |buffer, cx| {
12198 buffer.merge_into_base(ranges, cx);
12199 });
12200 }
12201 });
12202
12203 if let Some(project) = self.project.clone() {
12204 self.save(true, project, window, cx).detach_and_log_err(cx);
12205 }
12206 }
12207
12208 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12209 if hovered != self.gutter_hovered {
12210 self.gutter_hovered = hovered;
12211 cx.notify();
12212 }
12213 }
12214
12215 pub fn insert_blocks(
12216 &mut self,
12217 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12218 autoscroll: Option<Autoscroll>,
12219 cx: &mut Context<Self>,
12220 ) -> Vec<CustomBlockId> {
12221 let blocks = self
12222 .display_map
12223 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12224 if let Some(autoscroll) = autoscroll {
12225 self.request_autoscroll(autoscroll, cx);
12226 }
12227 cx.notify();
12228 blocks
12229 }
12230
12231 pub fn resize_blocks(
12232 &mut self,
12233 heights: HashMap<CustomBlockId, u32>,
12234 autoscroll: Option<Autoscroll>,
12235 cx: &mut Context<Self>,
12236 ) {
12237 self.display_map
12238 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12239 if let Some(autoscroll) = autoscroll {
12240 self.request_autoscroll(autoscroll, cx);
12241 }
12242 cx.notify();
12243 }
12244
12245 pub fn replace_blocks(
12246 &mut self,
12247 renderers: HashMap<CustomBlockId, RenderBlock>,
12248 autoscroll: Option<Autoscroll>,
12249 cx: &mut Context<Self>,
12250 ) {
12251 self.display_map
12252 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12253 if let Some(autoscroll) = autoscroll {
12254 self.request_autoscroll(autoscroll, cx);
12255 }
12256 cx.notify();
12257 }
12258
12259 pub fn remove_blocks(
12260 &mut self,
12261 block_ids: HashSet<CustomBlockId>,
12262 autoscroll: Option<Autoscroll>,
12263 cx: &mut Context<Self>,
12264 ) {
12265 self.display_map.update(cx, |display_map, cx| {
12266 display_map.remove_blocks(block_ids, cx)
12267 });
12268 if let Some(autoscroll) = autoscroll {
12269 self.request_autoscroll(autoscroll, cx);
12270 }
12271 cx.notify();
12272 }
12273
12274 pub fn row_for_block(
12275 &self,
12276 block_id: CustomBlockId,
12277 cx: &mut Context<Self>,
12278 ) -> Option<DisplayRow> {
12279 self.display_map
12280 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12281 }
12282
12283 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12284 self.focused_block = Some(focused_block);
12285 }
12286
12287 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12288 self.focused_block.take()
12289 }
12290
12291 pub fn insert_creases(
12292 &mut self,
12293 creases: impl IntoIterator<Item = Crease<Anchor>>,
12294 cx: &mut Context<Self>,
12295 ) -> Vec<CreaseId> {
12296 self.display_map
12297 .update(cx, |map, cx| map.insert_creases(creases, cx))
12298 }
12299
12300 pub fn remove_creases(
12301 &mut self,
12302 ids: impl IntoIterator<Item = CreaseId>,
12303 cx: &mut Context<Self>,
12304 ) {
12305 self.display_map
12306 .update(cx, |map, cx| map.remove_creases(ids, cx));
12307 }
12308
12309 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12310 self.display_map
12311 .update(cx, |map, cx| map.snapshot(cx))
12312 .longest_row()
12313 }
12314
12315 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12316 self.display_map
12317 .update(cx, |map, cx| map.snapshot(cx))
12318 .max_point()
12319 }
12320
12321 pub fn text(&self, cx: &App) -> String {
12322 self.buffer.read(cx).read(cx).text()
12323 }
12324
12325 pub fn is_empty(&self, cx: &App) -> bool {
12326 self.buffer.read(cx).read(cx).is_empty()
12327 }
12328
12329 pub fn text_option(&self, cx: &App) -> Option<String> {
12330 let text = self.text(cx);
12331 let text = text.trim();
12332
12333 if text.is_empty() {
12334 return None;
12335 }
12336
12337 Some(text.to_string())
12338 }
12339
12340 pub fn set_text(
12341 &mut self,
12342 text: impl Into<Arc<str>>,
12343 window: &mut Window,
12344 cx: &mut Context<Self>,
12345 ) {
12346 self.transact(window, cx, |this, _, cx| {
12347 this.buffer
12348 .read(cx)
12349 .as_singleton()
12350 .expect("you can only call set_text on editors for singleton buffers")
12351 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12352 });
12353 }
12354
12355 pub fn display_text(&self, cx: &mut App) -> String {
12356 self.display_map
12357 .update(cx, |map, cx| map.snapshot(cx))
12358 .text()
12359 }
12360
12361 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12362 let mut wrap_guides = smallvec::smallvec![];
12363
12364 if self.show_wrap_guides == Some(false) {
12365 return wrap_guides;
12366 }
12367
12368 let settings = self.buffer.read(cx).settings_at(0, cx);
12369 if settings.show_wrap_guides {
12370 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12371 wrap_guides.push((soft_wrap as usize, true));
12372 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12373 wrap_guides.push((soft_wrap as usize, true));
12374 }
12375 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12376 }
12377
12378 wrap_guides
12379 }
12380
12381 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12382 let settings = self.buffer.read(cx).settings_at(0, cx);
12383 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12384 match mode {
12385 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12386 SoftWrap::None
12387 }
12388 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12389 language_settings::SoftWrap::PreferredLineLength => {
12390 SoftWrap::Column(settings.preferred_line_length)
12391 }
12392 language_settings::SoftWrap::Bounded => {
12393 SoftWrap::Bounded(settings.preferred_line_length)
12394 }
12395 }
12396 }
12397
12398 pub fn set_soft_wrap_mode(
12399 &mut self,
12400 mode: language_settings::SoftWrap,
12401
12402 cx: &mut Context<Self>,
12403 ) {
12404 self.soft_wrap_mode_override = Some(mode);
12405 cx.notify();
12406 }
12407
12408 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12409 self.text_style_refinement = Some(style);
12410 }
12411
12412 /// called by the Element so we know what style we were most recently rendered with.
12413 pub(crate) fn set_style(
12414 &mut self,
12415 style: EditorStyle,
12416 window: &mut Window,
12417 cx: &mut Context<Self>,
12418 ) {
12419 let rem_size = window.rem_size();
12420 self.display_map.update(cx, |map, cx| {
12421 map.set_font(
12422 style.text.font(),
12423 style.text.font_size.to_pixels(rem_size),
12424 cx,
12425 )
12426 });
12427 self.style = Some(style);
12428 }
12429
12430 pub fn style(&self) -> Option<&EditorStyle> {
12431 self.style.as_ref()
12432 }
12433
12434 // Called by the element. This method is not designed to be called outside of the editor
12435 // element's layout code because it does not notify when rewrapping is computed synchronously.
12436 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12437 self.display_map
12438 .update(cx, |map, cx| map.set_wrap_width(width, cx))
12439 }
12440
12441 pub fn set_soft_wrap(&mut self) {
12442 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12443 }
12444
12445 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12446 if self.soft_wrap_mode_override.is_some() {
12447 self.soft_wrap_mode_override.take();
12448 } else {
12449 let soft_wrap = match self.soft_wrap_mode(cx) {
12450 SoftWrap::GitDiff => return,
12451 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12452 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12453 language_settings::SoftWrap::None
12454 }
12455 };
12456 self.soft_wrap_mode_override = Some(soft_wrap);
12457 }
12458 cx.notify();
12459 }
12460
12461 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12462 let Some(workspace) = self.workspace() else {
12463 return;
12464 };
12465 let fs = workspace.read(cx).app_state().fs.clone();
12466 let current_show = TabBarSettings::get_global(cx).show;
12467 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12468 setting.show = Some(!current_show);
12469 });
12470 }
12471
12472 pub fn toggle_indent_guides(
12473 &mut self,
12474 _: &ToggleIndentGuides,
12475 _: &mut Window,
12476 cx: &mut Context<Self>,
12477 ) {
12478 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12479 self.buffer
12480 .read(cx)
12481 .settings_at(0, cx)
12482 .indent_guides
12483 .enabled
12484 });
12485 self.show_indent_guides = Some(!currently_enabled);
12486 cx.notify();
12487 }
12488
12489 fn should_show_indent_guides(&self) -> Option<bool> {
12490 self.show_indent_guides
12491 }
12492
12493 pub fn toggle_line_numbers(
12494 &mut self,
12495 _: &ToggleLineNumbers,
12496 _: &mut Window,
12497 cx: &mut Context<Self>,
12498 ) {
12499 let mut editor_settings = EditorSettings::get_global(cx).clone();
12500 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12501 EditorSettings::override_global(editor_settings, cx);
12502 }
12503
12504 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12505 self.use_relative_line_numbers
12506 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12507 }
12508
12509 pub fn toggle_relative_line_numbers(
12510 &mut self,
12511 _: &ToggleRelativeLineNumbers,
12512 _: &mut Window,
12513 cx: &mut Context<Self>,
12514 ) {
12515 let is_relative = self.should_use_relative_line_numbers(cx);
12516 self.set_relative_line_number(Some(!is_relative), cx)
12517 }
12518
12519 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12520 self.use_relative_line_numbers = is_relative;
12521 cx.notify();
12522 }
12523
12524 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12525 self.show_gutter = show_gutter;
12526 cx.notify();
12527 }
12528
12529 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12530 self.show_scrollbars = show_scrollbars;
12531 cx.notify();
12532 }
12533
12534 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12535 self.show_line_numbers = Some(show_line_numbers);
12536 cx.notify();
12537 }
12538
12539 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12540 self.show_git_diff_gutter = Some(show_git_diff_gutter);
12541 cx.notify();
12542 }
12543
12544 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12545 self.show_code_actions = Some(show_code_actions);
12546 cx.notify();
12547 }
12548
12549 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12550 self.show_runnables = Some(show_runnables);
12551 cx.notify();
12552 }
12553
12554 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12555 if self.display_map.read(cx).masked != masked {
12556 self.display_map.update(cx, |map, _| map.masked = masked);
12557 }
12558 cx.notify()
12559 }
12560
12561 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12562 self.show_wrap_guides = Some(show_wrap_guides);
12563 cx.notify();
12564 }
12565
12566 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12567 self.show_indent_guides = Some(show_indent_guides);
12568 cx.notify();
12569 }
12570
12571 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12572 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12573 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12574 if let Some(dir) = file.abs_path(cx).parent() {
12575 return Some(dir.to_owned());
12576 }
12577 }
12578
12579 if let Some(project_path) = buffer.read(cx).project_path(cx) {
12580 return Some(project_path.path.to_path_buf());
12581 }
12582 }
12583
12584 None
12585 }
12586
12587 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12588 self.active_excerpt(cx)?
12589 .1
12590 .read(cx)
12591 .file()
12592 .and_then(|f| f.as_local())
12593 }
12594
12595 fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12596 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12597 let project_path = buffer.read(cx).project_path(cx)?;
12598 let project = self.project.as_ref()?.read(cx);
12599 project.absolute_path(&project_path, cx)
12600 })
12601 }
12602
12603 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12604 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12605 let project_path = buffer.read(cx).project_path(cx)?;
12606 let project = self.project.as_ref()?.read(cx);
12607 let entry = project.entry_for_path(&project_path, cx)?;
12608 let path = entry.path.to_path_buf();
12609 Some(path)
12610 })
12611 }
12612
12613 pub fn reveal_in_finder(
12614 &mut self,
12615 _: &RevealInFileManager,
12616 _window: &mut Window,
12617 cx: &mut Context<Self>,
12618 ) {
12619 if let Some(target) = self.target_file(cx) {
12620 cx.reveal_path(&target.abs_path(cx));
12621 }
12622 }
12623
12624 pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12625 if let Some(path) = self.target_file_abs_path(cx) {
12626 if let Some(path) = path.to_str() {
12627 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12628 }
12629 }
12630 }
12631
12632 pub fn copy_relative_path(
12633 &mut self,
12634 _: &CopyRelativePath,
12635 _window: &mut Window,
12636 cx: &mut Context<Self>,
12637 ) {
12638 if let Some(path) = self.target_file_path(cx) {
12639 if let Some(path) = path.to_str() {
12640 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12641 }
12642 }
12643 }
12644
12645 pub fn toggle_git_blame(
12646 &mut self,
12647 _: &ToggleGitBlame,
12648 window: &mut Window,
12649 cx: &mut Context<Self>,
12650 ) {
12651 self.show_git_blame_gutter = !self.show_git_blame_gutter;
12652
12653 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12654 self.start_git_blame(true, window, cx);
12655 }
12656
12657 cx.notify();
12658 }
12659
12660 pub fn toggle_git_blame_inline(
12661 &mut self,
12662 _: &ToggleGitBlameInline,
12663 window: &mut Window,
12664 cx: &mut Context<Self>,
12665 ) {
12666 self.toggle_git_blame_inline_internal(true, window, cx);
12667 cx.notify();
12668 }
12669
12670 pub fn git_blame_inline_enabled(&self) -> bool {
12671 self.git_blame_inline_enabled
12672 }
12673
12674 pub fn toggle_selection_menu(
12675 &mut self,
12676 _: &ToggleSelectionMenu,
12677 _: &mut Window,
12678 cx: &mut Context<Self>,
12679 ) {
12680 self.show_selection_menu = self
12681 .show_selection_menu
12682 .map(|show_selections_menu| !show_selections_menu)
12683 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12684
12685 cx.notify();
12686 }
12687
12688 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12689 self.show_selection_menu
12690 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12691 }
12692
12693 fn start_git_blame(
12694 &mut self,
12695 user_triggered: bool,
12696 window: &mut Window,
12697 cx: &mut Context<Self>,
12698 ) {
12699 if let Some(project) = self.project.as_ref() {
12700 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12701 return;
12702 };
12703
12704 if buffer.read(cx).file().is_none() {
12705 return;
12706 }
12707
12708 let focused = self.focus_handle(cx).contains_focused(window, cx);
12709
12710 let project = project.clone();
12711 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12712 self.blame_subscription =
12713 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12714 self.blame = Some(blame);
12715 }
12716 }
12717
12718 fn toggle_git_blame_inline_internal(
12719 &mut self,
12720 user_triggered: bool,
12721 window: &mut Window,
12722 cx: &mut Context<Self>,
12723 ) {
12724 if self.git_blame_inline_enabled {
12725 self.git_blame_inline_enabled = false;
12726 self.show_git_blame_inline = false;
12727 self.show_git_blame_inline_delay_task.take();
12728 } else {
12729 self.git_blame_inline_enabled = true;
12730 self.start_git_blame_inline(user_triggered, window, cx);
12731 }
12732
12733 cx.notify();
12734 }
12735
12736 fn start_git_blame_inline(
12737 &mut self,
12738 user_triggered: bool,
12739 window: &mut Window,
12740 cx: &mut Context<Self>,
12741 ) {
12742 self.start_git_blame(user_triggered, window, cx);
12743
12744 if ProjectSettings::get_global(cx)
12745 .git
12746 .inline_blame_delay()
12747 .is_some()
12748 {
12749 self.start_inline_blame_timer(window, cx);
12750 } else {
12751 self.show_git_blame_inline = true
12752 }
12753 }
12754
12755 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12756 self.blame.as_ref()
12757 }
12758
12759 pub fn show_git_blame_gutter(&self) -> bool {
12760 self.show_git_blame_gutter
12761 }
12762
12763 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12764 self.show_git_blame_gutter && self.has_blame_entries(cx)
12765 }
12766
12767 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12768 self.show_git_blame_inline
12769 && self.focus_handle.is_focused(window)
12770 && !self.newest_selection_head_on_empty_line(cx)
12771 && self.has_blame_entries(cx)
12772 }
12773
12774 fn has_blame_entries(&self, cx: &App) -> bool {
12775 self.blame()
12776 .map_or(false, |blame| blame.read(cx).has_generated_entries())
12777 }
12778
12779 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12780 let cursor_anchor = self.selections.newest_anchor().head();
12781
12782 let snapshot = self.buffer.read(cx).snapshot(cx);
12783 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12784
12785 snapshot.line_len(buffer_row) == 0
12786 }
12787
12788 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12789 let buffer_and_selection = maybe!({
12790 let selection = self.selections.newest::<Point>(cx);
12791 let selection_range = selection.range();
12792
12793 let multi_buffer = self.buffer().read(cx);
12794 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12795 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12796
12797 let (buffer, range, _) = if selection.reversed {
12798 buffer_ranges.first()
12799 } else {
12800 buffer_ranges.last()
12801 }?;
12802
12803 let selection = text::ToPoint::to_point(&range.start, &buffer).row
12804 ..text::ToPoint::to_point(&range.end, &buffer).row;
12805 Some((
12806 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
12807 selection,
12808 ))
12809 });
12810
12811 let Some((buffer, selection)) = buffer_and_selection else {
12812 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12813 };
12814
12815 let Some(project) = self.project.as_ref() else {
12816 return Task::ready(Err(anyhow!("editor does not have project")));
12817 };
12818
12819 project.update(cx, |project, cx| {
12820 project.get_permalink_to_line(&buffer, selection, cx)
12821 })
12822 }
12823
12824 pub fn copy_permalink_to_line(
12825 &mut self,
12826 _: &CopyPermalinkToLine,
12827 window: &mut Window,
12828 cx: &mut Context<Self>,
12829 ) {
12830 let permalink_task = self.get_permalink_to_line(cx);
12831 let workspace = self.workspace();
12832
12833 cx.spawn_in(window, |_, mut cx| async move {
12834 match permalink_task.await {
12835 Ok(permalink) => {
12836 cx.update(|_, cx| {
12837 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12838 })
12839 .ok();
12840 }
12841 Err(err) => {
12842 let message = format!("Failed to copy permalink: {err}");
12843
12844 Err::<(), anyhow::Error>(err).log_err();
12845
12846 if let Some(workspace) = workspace {
12847 workspace
12848 .update_in(&mut cx, |workspace, _, cx| {
12849 struct CopyPermalinkToLine;
12850
12851 workspace.show_toast(
12852 Toast::new(
12853 NotificationId::unique::<CopyPermalinkToLine>(),
12854 message,
12855 ),
12856 cx,
12857 )
12858 })
12859 .ok();
12860 }
12861 }
12862 }
12863 })
12864 .detach();
12865 }
12866
12867 pub fn copy_file_location(
12868 &mut self,
12869 _: &CopyFileLocation,
12870 _: &mut Window,
12871 cx: &mut Context<Self>,
12872 ) {
12873 let selection = self.selections.newest::<Point>(cx).start.row + 1;
12874 if let Some(file) = self.target_file(cx) {
12875 if let Some(path) = file.path().to_str() {
12876 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
12877 }
12878 }
12879 }
12880
12881 pub fn open_permalink_to_line(
12882 &mut self,
12883 _: &OpenPermalinkToLine,
12884 window: &mut Window,
12885 cx: &mut Context<Self>,
12886 ) {
12887 let permalink_task = self.get_permalink_to_line(cx);
12888 let workspace = self.workspace();
12889
12890 cx.spawn_in(window, |_, mut cx| async move {
12891 match permalink_task.await {
12892 Ok(permalink) => {
12893 cx.update(|_, cx| {
12894 cx.open_url(permalink.as_ref());
12895 })
12896 .ok();
12897 }
12898 Err(err) => {
12899 let message = format!("Failed to open permalink: {err}");
12900
12901 Err::<(), anyhow::Error>(err).log_err();
12902
12903 if let Some(workspace) = workspace {
12904 workspace
12905 .update(&mut cx, |workspace, cx| {
12906 struct OpenPermalinkToLine;
12907
12908 workspace.show_toast(
12909 Toast::new(
12910 NotificationId::unique::<OpenPermalinkToLine>(),
12911 message,
12912 ),
12913 cx,
12914 )
12915 })
12916 .ok();
12917 }
12918 }
12919 }
12920 })
12921 .detach();
12922 }
12923
12924 pub fn insert_uuid_v4(
12925 &mut self,
12926 _: &InsertUuidV4,
12927 window: &mut Window,
12928 cx: &mut Context<Self>,
12929 ) {
12930 self.insert_uuid(UuidVersion::V4, window, cx);
12931 }
12932
12933 pub fn insert_uuid_v7(
12934 &mut self,
12935 _: &InsertUuidV7,
12936 window: &mut Window,
12937 cx: &mut Context<Self>,
12938 ) {
12939 self.insert_uuid(UuidVersion::V7, window, cx);
12940 }
12941
12942 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
12943 self.transact(window, cx, |this, window, cx| {
12944 let edits = this
12945 .selections
12946 .all::<Point>(cx)
12947 .into_iter()
12948 .map(|selection| {
12949 let uuid = match version {
12950 UuidVersion::V4 => uuid::Uuid::new_v4(),
12951 UuidVersion::V7 => uuid::Uuid::now_v7(),
12952 };
12953
12954 (selection.range(), uuid.to_string())
12955 });
12956 this.edit(edits, cx);
12957 this.refresh_inline_completion(true, false, window, cx);
12958 });
12959 }
12960
12961 pub fn open_selections_in_multibuffer(
12962 &mut self,
12963 _: &OpenSelectionsInMultibuffer,
12964 window: &mut Window,
12965 cx: &mut Context<Self>,
12966 ) {
12967 let multibuffer = self.buffer.read(cx);
12968
12969 let Some(buffer) = multibuffer.as_singleton() else {
12970 return;
12971 };
12972
12973 let Some(workspace) = self.workspace() else {
12974 return;
12975 };
12976
12977 let locations = self
12978 .selections
12979 .disjoint_anchors()
12980 .iter()
12981 .map(|range| Location {
12982 buffer: buffer.clone(),
12983 range: range.start.text_anchor..range.end.text_anchor,
12984 })
12985 .collect::<Vec<_>>();
12986
12987 let title = multibuffer.title(cx).to_string();
12988
12989 cx.spawn_in(window, |_, mut cx| async move {
12990 workspace.update_in(&mut cx, |workspace, window, cx| {
12991 Self::open_locations_in_multibuffer(
12992 workspace,
12993 locations,
12994 format!("Selections for '{title}'"),
12995 false,
12996 MultibufferSelectionMode::All,
12997 window,
12998 cx,
12999 );
13000 })
13001 })
13002 .detach();
13003 }
13004
13005 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13006 /// last highlight added will be used.
13007 ///
13008 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13009 pub fn highlight_rows<T: 'static>(
13010 &mut self,
13011 range: Range<Anchor>,
13012 color: Hsla,
13013 should_autoscroll: bool,
13014 cx: &mut Context<Self>,
13015 ) {
13016 let snapshot = self.buffer().read(cx).snapshot(cx);
13017 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13018 let ix = row_highlights.binary_search_by(|highlight| {
13019 Ordering::Equal
13020 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13021 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13022 });
13023
13024 if let Err(mut ix) = ix {
13025 let index = post_inc(&mut self.highlight_order);
13026
13027 // If this range intersects with the preceding highlight, then merge it with
13028 // the preceding highlight. Otherwise insert a new highlight.
13029 let mut merged = false;
13030 if ix > 0 {
13031 let prev_highlight = &mut row_highlights[ix - 1];
13032 if prev_highlight
13033 .range
13034 .end
13035 .cmp(&range.start, &snapshot)
13036 .is_ge()
13037 {
13038 ix -= 1;
13039 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13040 prev_highlight.range.end = range.end;
13041 }
13042 merged = true;
13043 prev_highlight.index = index;
13044 prev_highlight.color = color;
13045 prev_highlight.should_autoscroll = should_autoscroll;
13046 }
13047 }
13048
13049 if !merged {
13050 row_highlights.insert(
13051 ix,
13052 RowHighlight {
13053 range: range.clone(),
13054 index,
13055 color,
13056 should_autoscroll,
13057 },
13058 );
13059 }
13060
13061 // If any of the following highlights intersect with this one, merge them.
13062 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13063 let highlight = &row_highlights[ix];
13064 if next_highlight
13065 .range
13066 .start
13067 .cmp(&highlight.range.end, &snapshot)
13068 .is_le()
13069 {
13070 if next_highlight
13071 .range
13072 .end
13073 .cmp(&highlight.range.end, &snapshot)
13074 .is_gt()
13075 {
13076 row_highlights[ix].range.end = next_highlight.range.end;
13077 }
13078 row_highlights.remove(ix + 1);
13079 } else {
13080 break;
13081 }
13082 }
13083 }
13084 }
13085
13086 /// Remove any highlighted row ranges of the given type that intersect the
13087 /// given ranges.
13088 pub fn remove_highlighted_rows<T: 'static>(
13089 &mut self,
13090 ranges_to_remove: Vec<Range<Anchor>>,
13091 cx: &mut Context<Self>,
13092 ) {
13093 let snapshot = self.buffer().read(cx).snapshot(cx);
13094 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13095 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13096 row_highlights.retain(|highlight| {
13097 while let Some(range_to_remove) = ranges_to_remove.peek() {
13098 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13099 Ordering::Less | Ordering::Equal => {
13100 ranges_to_remove.next();
13101 }
13102 Ordering::Greater => {
13103 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13104 Ordering::Less | Ordering::Equal => {
13105 return false;
13106 }
13107 Ordering::Greater => break,
13108 }
13109 }
13110 }
13111 }
13112
13113 true
13114 })
13115 }
13116
13117 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13118 pub fn clear_row_highlights<T: 'static>(&mut self) {
13119 self.highlighted_rows.remove(&TypeId::of::<T>());
13120 }
13121
13122 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13123 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13124 self.highlighted_rows
13125 .get(&TypeId::of::<T>())
13126 .map_or(&[] as &[_], |vec| vec.as_slice())
13127 .iter()
13128 .map(|highlight| (highlight.range.clone(), highlight.color))
13129 }
13130
13131 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13132 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13133 /// Allows to ignore certain kinds of highlights.
13134 pub fn highlighted_display_rows(
13135 &self,
13136 window: &mut Window,
13137 cx: &mut App,
13138 ) -> BTreeMap<DisplayRow, Hsla> {
13139 let snapshot = self.snapshot(window, cx);
13140 let mut used_highlight_orders = HashMap::default();
13141 self.highlighted_rows
13142 .iter()
13143 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13144 .fold(
13145 BTreeMap::<DisplayRow, Hsla>::new(),
13146 |mut unique_rows, highlight| {
13147 let start = highlight.range.start.to_display_point(&snapshot);
13148 let end = highlight.range.end.to_display_point(&snapshot);
13149 let start_row = start.row().0;
13150 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13151 && end.column() == 0
13152 {
13153 end.row().0.saturating_sub(1)
13154 } else {
13155 end.row().0
13156 };
13157 for row in start_row..=end_row {
13158 let used_index =
13159 used_highlight_orders.entry(row).or_insert(highlight.index);
13160 if highlight.index >= *used_index {
13161 *used_index = highlight.index;
13162 unique_rows.insert(DisplayRow(row), highlight.color);
13163 }
13164 }
13165 unique_rows
13166 },
13167 )
13168 }
13169
13170 pub fn highlighted_display_row_for_autoscroll(
13171 &self,
13172 snapshot: &DisplaySnapshot,
13173 ) -> Option<DisplayRow> {
13174 self.highlighted_rows
13175 .values()
13176 .flat_map(|highlighted_rows| highlighted_rows.iter())
13177 .filter_map(|highlight| {
13178 if highlight.should_autoscroll {
13179 Some(highlight.range.start.to_display_point(snapshot).row())
13180 } else {
13181 None
13182 }
13183 })
13184 .min()
13185 }
13186
13187 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13188 self.highlight_background::<SearchWithinRange>(
13189 ranges,
13190 |colors| colors.editor_document_highlight_read_background,
13191 cx,
13192 )
13193 }
13194
13195 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13196 self.breadcrumb_header = Some(new_header);
13197 }
13198
13199 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13200 self.clear_background_highlights::<SearchWithinRange>(cx);
13201 }
13202
13203 pub fn highlight_background<T: 'static>(
13204 &mut self,
13205 ranges: &[Range<Anchor>],
13206 color_fetcher: fn(&ThemeColors) -> Hsla,
13207 cx: &mut Context<Self>,
13208 ) {
13209 self.background_highlights
13210 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13211 self.scrollbar_marker_state.dirty = true;
13212 cx.notify();
13213 }
13214
13215 pub fn clear_background_highlights<T: 'static>(
13216 &mut self,
13217 cx: &mut Context<Self>,
13218 ) -> Option<BackgroundHighlight> {
13219 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13220 if !text_highlights.1.is_empty() {
13221 self.scrollbar_marker_state.dirty = true;
13222 cx.notify();
13223 }
13224 Some(text_highlights)
13225 }
13226
13227 pub fn highlight_gutter<T: 'static>(
13228 &mut self,
13229 ranges: &[Range<Anchor>],
13230 color_fetcher: fn(&App) -> Hsla,
13231 cx: &mut Context<Self>,
13232 ) {
13233 self.gutter_highlights
13234 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13235 cx.notify();
13236 }
13237
13238 pub fn clear_gutter_highlights<T: 'static>(
13239 &mut self,
13240 cx: &mut Context<Self>,
13241 ) -> Option<GutterHighlight> {
13242 cx.notify();
13243 self.gutter_highlights.remove(&TypeId::of::<T>())
13244 }
13245
13246 #[cfg(feature = "test-support")]
13247 pub fn all_text_background_highlights(
13248 &self,
13249 window: &mut Window,
13250 cx: &mut Context<Self>,
13251 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13252 let snapshot = self.snapshot(window, cx);
13253 let buffer = &snapshot.buffer_snapshot;
13254 let start = buffer.anchor_before(0);
13255 let end = buffer.anchor_after(buffer.len());
13256 let theme = cx.theme().colors();
13257 self.background_highlights_in_range(start..end, &snapshot, theme)
13258 }
13259
13260 #[cfg(feature = "test-support")]
13261 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13262 let snapshot = self.buffer().read(cx).snapshot(cx);
13263
13264 let highlights = self
13265 .background_highlights
13266 .get(&TypeId::of::<items::BufferSearchHighlights>());
13267
13268 if let Some((_color, ranges)) = highlights {
13269 ranges
13270 .iter()
13271 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13272 .collect_vec()
13273 } else {
13274 vec![]
13275 }
13276 }
13277
13278 fn document_highlights_for_position<'a>(
13279 &'a self,
13280 position: Anchor,
13281 buffer: &'a MultiBufferSnapshot,
13282 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13283 let read_highlights = self
13284 .background_highlights
13285 .get(&TypeId::of::<DocumentHighlightRead>())
13286 .map(|h| &h.1);
13287 let write_highlights = self
13288 .background_highlights
13289 .get(&TypeId::of::<DocumentHighlightWrite>())
13290 .map(|h| &h.1);
13291 let left_position = position.bias_left(buffer);
13292 let right_position = position.bias_right(buffer);
13293 read_highlights
13294 .into_iter()
13295 .chain(write_highlights)
13296 .flat_map(move |ranges| {
13297 let start_ix = match ranges.binary_search_by(|probe| {
13298 let cmp = probe.end.cmp(&left_position, buffer);
13299 if cmp.is_ge() {
13300 Ordering::Greater
13301 } else {
13302 Ordering::Less
13303 }
13304 }) {
13305 Ok(i) | Err(i) => i,
13306 };
13307
13308 ranges[start_ix..]
13309 .iter()
13310 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13311 })
13312 }
13313
13314 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13315 self.background_highlights
13316 .get(&TypeId::of::<T>())
13317 .map_or(false, |(_, highlights)| !highlights.is_empty())
13318 }
13319
13320 pub fn background_highlights_in_range(
13321 &self,
13322 search_range: Range<Anchor>,
13323 display_snapshot: &DisplaySnapshot,
13324 theme: &ThemeColors,
13325 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13326 let mut results = Vec::new();
13327 for (color_fetcher, ranges) in self.background_highlights.values() {
13328 let color = color_fetcher(theme);
13329 let start_ix = match ranges.binary_search_by(|probe| {
13330 let cmp = probe
13331 .end
13332 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13333 if cmp.is_gt() {
13334 Ordering::Greater
13335 } else {
13336 Ordering::Less
13337 }
13338 }) {
13339 Ok(i) | Err(i) => i,
13340 };
13341 for range in &ranges[start_ix..] {
13342 if range
13343 .start
13344 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13345 .is_ge()
13346 {
13347 break;
13348 }
13349
13350 let start = range.start.to_display_point(display_snapshot);
13351 let end = range.end.to_display_point(display_snapshot);
13352 results.push((start..end, color))
13353 }
13354 }
13355 results
13356 }
13357
13358 pub fn background_highlight_row_ranges<T: 'static>(
13359 &self,
13360 search_range: Range<Anchor>,
13361 display_snapshot: &DisplaySnapshot,
13362 count: usize,
13363 ) -> Vec<RangeInclusive<DisplayPoint>> {
13364 let mut results = Vec::new();
13365 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13366 return vec![];
13367 };
13368
13369 let start_ix = match ranges.binary_search_by(|probe| {
13370 let cmp = probe
13371 .end
13372 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13373 if cmp.is_gt() {
13374 Ordering::Greater
13375 } else {
13376 Ordering::Less
13377 }
13378 }) {
13379 Ok(i) | Err(i) => i,
13380 };
13381 let mut push_region = |start: Option<Point>, end: Option<Point>| {
13382 if let (Some(start_display), Some(end_display)) = (start, end) {
13383 results.push(
13384 start_display.to_display_point(display_snapshot)
13385 ..=end_display.to_display_point(display_snapshot),
13386 );
13387 }
13388 };
13389 let mut start_row: Option<Point> = None;
13390 let mut end_row: Option<Point> = None;
13391 if ranges.len() > count {
13392 return Vec::new();
13393 }
13394 for range in &ranges[start_ix..] {
13395 if range
13396 .start
13397 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13398 .is_ge()
13399 {
13400 break;
13401 }
13402 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13403 if let Some(current_row) = &end_row {
13404 if end.row == current_row.row {
13405 continue;
13406 }
13407 }
13408 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13409 if start_row.is_none() {
13410 assert_eq!(end_row, None);
13411 start_row = Some(start);
13412 end_row = Some(end);
13413 continue;
13414 }
13415 if let Some(current_end) = end_row.as_mut() {
13416 if start.row > current_end.row + 1 {
13417 push_region(start_row, end_row);
13418 start_row = Some(start);
13419 end_row = Some(end);
13420 } else {
13421 // Merge two hunks.
13422 *current_end = end;
13423 }
13424 } else {
13425 unreachable!();
13426 }
13427 }
13428 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13429 push_region(start_row, end_row);
13430 results
13431 }
13432
13433 pub fn gutter_highlights_in_range(
13434 &self,
13435 search_range: Range<Anchor>,
13436 display_snapshot: &DisplaySnapshot,
13437 cx: &App,
13438 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13439 let mut results = Vec::new();
13440 for (color_fetcher, ranges) in self.gutter_highlights.values() {
13441 let color = color_fetcher(cx);
13442 let start_ix = match ranges.binary_search_by(|probe| {
13443 let cmp = probe
13444 .end
13445 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13446 if cmp.is_gt() {
13447 Ordering::Greater
13448 } else {
13449 Ordering::Less
13450 }
13451 }) {
13452 Ok(i) | Err(i) => i,
13453 };
13454 for range in &ranges[start_ix..] {
13455 if range
13456 .start
13457 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13458 .is_ge()
13459 {
13460 break;
13461 }
13462
13463 let start = range.start.to_display_point(display_snapshot);
13464 let end = range.end.to_display_point(display_snapshot);
13465 results.push((start..end, color))
13466 }
13467 }
13468 results
13469 }
13470
13471 /// Get the text ranges corresponding to the redaction query
13472 pub fn redacted_ranges(
13473 &self,
13474 search_range: Range<Anchor>,
13475 display_snapshot: &DisplaySnapshot,
13476 cx: &App,
13477 ) -> Vec<Range<DisplayPoint>> {
13478 display_snapshot
13479 .buffer_snapshot
13480 .redacted_ranges(search_range, |file| {
13481 if let Some(file) = file {
13482 file.is_private()
13483 && EditorSettings::get(
13484 Some(SettingsLocation {
13485 worktree_id: file.worktree_id(cx),
13486 path: file.path().as_ref(),
13487 }),
13488 cx,
13489 )
13490 .redact_private_values
13491 } else {
13492 false
13493 }
13494 })
13495 .map(|range| {
13496 range.start.to_display_point(display_snapshot)
13497 ..range.end.to_display_point(display_snapshot)
13498 })
13499 .collect()
13500 }
13501
13502 pub fn highlight_text<T: 'static>(
13503 &mut self,
13504 ranges: Vec<Range<Anchor>>,
13505 style: HighlightStyle,
13506 cx: &mut Context<Self>,
13507 ) {
13508 self.display_map.update(cx, |map, _| {
13509 map.highlight_text(TypeId::of::<T>(), ranges, style)
13510 });
13511 cx.notify();
13512 }
13513
13514 pub(crate) fn highlight_inlays<T: 'static>(
13515 &mut self,
13516 highlights: Vec<InlayHighlight>,
13517 style: HighlightStyle,
13518 cx: &mut Context<Self>,
13519 ) {
13520 self.display_map.update(cx, |map, _| {
13521 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13522 });
13523 cx.notify();
13524 }
13525
13526 pub fn text_highlights<'a, T: 'static>(
13527 &'a self,
13528 cx: &'a App,
13529 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13530 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13531 }
13532
13533 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13534 let cleared = self
13535 .display_map
13536 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13537 if cleared {
13538 cx.notify();
13539 }
13540 }
13541
13542 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13543 (self.read_only(cx) || self.blink_manager.read(cx).visible())
13544 && self.focus_handle.is_focused(window)
13545 }
13546
13547 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13548 self.show_cursor_when_unfocused = is_enabled;
13549 cx.notify();
13550 }
13551
13552 pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13553 self.project
13554 .as_ref()
13555 .map(|project| project.read(cx).lsp_store())
13556 }
13557
13558 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13559 cx.notify();
13560 }
13561
13562 fn on_buffer_event(
13563 &mut self,
13564 multibuffer: &Entity<MultiBuffer>,
13565 event: &multi_buffer::Event,
13566 window: &mut Window,
13567 cx: &mut Context<Self>,
13568 ) {
13569 match event {
13570 multi_buffer::Event::Edited {
13571 singleton_buffer_edited,
13572 edited_buffer: buffer_edited,
13573 } => {
13574 self.scrollbar_marker_state.dirty = true;
13575 self.active_indent_guides_state.dirty = true;
13576 self.refresh_active_diagnostics(cx);
13577 self.refresh_code_actions(window, cx);
13578 if self.has_active_inline_completion() {
13579 self.update_visible_inline_completion(window, cx);
13580 }
13581 if let Some(buffer) = buffer_edited {
13582 let buffer_id = buffer.read(cx).remote_id();
13583 if !self.registered_buffers.contains_key(&buffer_id) {
13584 if let Some(lsp_store) = self.lsp_store(cx) {
13585 lsp_store.update(cx, |lsp_store, cx| {
13586 self.registered_buffers.insert(
13587 buffer_id,
13588 lsp_store.register_buffer_with_language_servers(&buffer, cx),
13589 );
13590 })
13591 }
13592 }
13593 }
13594 cx.emit(EditorEvent::BufferEdited);
13595 cx.emit(SearchEvent::MatchesInvalidated);
13596 if *singleton_buffer_edited {
13597 if let Some(project) = &self.project {
13598 let project = project.read(cx);
13599 #[allow(clippy::mutable_key_type)]
13600 let languages_affected = multibuffer
13601 .read(cx)
13602 .all_buffers()
13603 .into_iter()
13604 .filter_map(|buffer| {
13605 let buffer = buffer.read(cx);
13606 let language = buffer.language()?;
13607 if project.is_local()
13608 && project
13609 .language_servers_for_local_buffer(buffer, cx)
13610 .count()
13611 == 0
13612 {
13613 None
13614 } else {
13615 Some(language)
13616 }
13617 })
13618 .cloned()
13619 .collect::<HashSet<_>>();
13620 if !languages_affected.is_empty() {
13621 self.refresh_inlay_hints(
13622 InlayHintRefreshReason::BufferEdited(languages_affected),
13623 cx,
13624 );
13625 }
13626 }
13627 }
13628
13629 let Some(project) = &self.project else { return };
13630 let (telemetry, is_via_ssh) = {
13631 let project = project.read(cx);
13632 let telemetry = project.client().telemetry().clone();
13633 let is_via_ssh = project.is_via_ssh();
13634 (telemetry, is_via_ssh)
13635 };
13636 refresh_linked_ranges(self, window, cx);
13637 telemetry.log_edit_event("editor", is_via_ssh);
13638 }
13639 multi_buffer::Event::ExcerptsAdded {
13640 buffer,
13641 predecessor,
13642 excerpts,
13643 } => {
13644 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13645 let buffer_id = buffer.read(cx).remote_id();
13646 if self.buffer.read(cx).change_set_for(buffer_id).is_none() {
13647 if let Some(project) = &self.project {
13648 get_unstaged_changes_for_buffers(
13649 project,
13650 [buffer.clone()],
13651 self.buffer.clone(),
13652 cx,
13653 );
13654 }
13655 }
13656 cx.emit(EditorEvent::ExcerptsAdded {
13657 buffer: buffer.clone(),
13658 predecessor: *predecessor,
13659 excerpts: excerpts.clone(),
13660 });
13661 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13662 }
13663 multi_buffer::Event::ExcerptsRemoved { ids } => {
13664 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13665 let buffer = self.buffer.read(cx);
13666 self.registered_buffers
13667 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13668 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13669 }
13670 multi_buffer::Event::ExcerptsEdited { ids } => {
13671 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13672 }
13673 multi_buffer::Event::ExcerptsExpanded { ids } => {
13674 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13675 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13676 }
13677 multi_buffer::Event::Reparsed(buffer_id) => {
13678 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13679
13680 cx.emit(EditorEvent::Reparsed(*buffer_id));
13681 }
13682 multi_buffer::Event::DiffHunksToggled => {
13683 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13684 }
13685 multi_buffer::Event::LanguageChanged(buffer_id) => {
13686 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13687 cx.emit(EditorEvent::Reparsed(*buffer_id));
13688 cx.notify();
13689 }
13690 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13691 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13692 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13693 cx.emit(EditorEvent::TitleChanged)
13694 }
13695 // multi_buffer::Event::DiffBaseChanged => {
13696 // self.scrollbar_marker_state.dirty = true;
13697 // cx.emit(EditorEvent::DiffBaseChanged);
13698 // cx.notify();
13699 // }
13700 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13701 multi_buffer::Event::DiagnosticsUpdated => {
13702 self.refresh_active_diagnostics(cx);
13703 self.scrollbar_marker_state.dirty = true;
13704 cx.notify();
13705 }
13706 _ => {}
13707 };
13708 }
13709
13710 fn on_display_map_changed(
13711 &mut self,
13712 _: Entity<DisplayMap>,
13713 _: &mut Window,
13714 cx: &mut Context<Self>,
13715 ) {
13716 cx.notify();
13717 }
13718
13719 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13720 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13721 self.refresh_inline_completion(true, false, window, cx);
13722 self.refresh_inlay_hints(
13723 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13724 self.selections.newest_anchor().head(),
13725 &self.buffer.read(cx).snapshot(cx),
13726 cx,
13727 )),
13728 cx,
13729 );
13730
13731 let old_cursor_shape = self.cursor_shape;
13732
13733 {
13734 let editor_settings = EditorSettings::get_global(cx);
13735 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13736 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13737 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13738 }
13739
13740 if old_cursor_shape != self.cursor_shape {
13741 cx.emit(EditorEvent::CursorShapeChanged);
13742 }
13743
13744 let project_settings = ProjectSettings::get_global(cx);
13745 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13746
13747 if self.mode == EditorMode::Full {
13748 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13749 if self.git_blame_inline_enabled != inline_blame_enabled {
13750 self.toggle_git_blame_inline_internal(false, window, cx);
13751 }
13752 }
13753
13754 cx.notify();
13755 }
13756
13757 pub fn set_searchable(&mut self, searchable: bool) {
13758 self.searchable = searchable;
13759 }
13760
13761 pub fn searchable(&self) -> bool {
13762 self.searchable
13763 }
13764
13765 fn open_proposed_changes_editor(
13766 &mut self,
13767 _: &OpenProposedChangesEditor,
13768 window: &mut Window,
13769 cx: &mut Context<Self>,
13770 ) {
13771 let Some(workspace) = self.workspace() else {
13772 cx.propagate();
13773 return;
13774 };
13775
13776 let selections = self.selections.all::<usize>(cx);
13777 let multi_buffer = self.buffer.read(cx);
13778 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13779 let mut new_selections_by_buffer = HashMap::default();
13780 for selection in selections {
13781 for (buffer, range, _) in
13782 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13783 {
13784 let mut range = range.to_point(buffer);
13785 range.start.column = 0;
13786 range.end.column = buffer.line_len(range.end.row);
13787 new_selections_by_buffer
13788 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13789 .or_insert(Vec::new())
13790 .push(range)
13791 }
13792 }
13793
13794 let proposed_changes_buffers = new_selections_by_buffer
13795 .into_iter()
13796 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13797 .collect::<Vec<_>>();
13798 let proposed_changes_editor = cx.new(|cx| {
13799 ProposedChangesEditor::new(
13800 "Proposed changes",
13801 proposed_changes_buffers,
13802 self.project.clone(),
13803 window,
13804 cx,
13805 )
13806 });
13807
13808 window.defer(cx, move |window, cx| {
13809 workspace.update(cx, |workspace, cx| {
13810 workspace.active_pane().update(cx, |pane, cx| {
13811 pane.add_item(
13812 Box::new(proposed_changes_editor),
13813 true,
13814 true,
13815 None,
13816 window,
13817 cx,
13818 );
13819 });
13820 });
13821 });
13822 }
13823
13824 pub fn open_excerpts_in_split(
13825 &mut self,
13826 _: &OpenExcerptsSplit,
13827 window: &mut Window,
13828 cx: &mut Context<Self>,
13829 ) {
13830 self.open_excerpts_common(None, true, window, cx)
13831 }
13832
13833 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
13834 self.open_excerpts_common(None, false, window, cx)
13835 }
13836
13837 fn open_excerpts_common(
13838 &mut self,
13839 jump_data: Option<JumpData>,
13840 split: bool,
13841 window: &mut Window,
13842 cx: &mut Context<Self>,
13843 ) {
13844 let Some(workspace) = self.workspace() else {
13845 cx.propagate();
13846 return;
13847 };
13848
13849 if self.buffer.read(cx).is_singleton() {
13850 cx.propagate();
13851 return;
13852 }
13853
13854 let mut new_selections_by_buffer = HashMap::default();
13855 match &jump_data {
13856 Some(JumpData::MultiBufferPoint {
13857 excerpt_id,
13858 position,
13859 anchor,
13860 line_offset_from_top,
13861 }) => {
13862 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13863 if let Some(buffer) = multi_buffer_snapshot
13864 .buffer_id_for_excerpt(*excerpt_id)
13865 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
13866 {
13867 let buffer_snapshot = buffer.read(cx).snapshot();
13868 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
13869 language::ToPoint::to_point(anchor, &buffer_snapshot)
13870 } else {
13871 buffer_snapshot.clip_point(*position, Bias::Left)
13872 };
13873 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
13874 new_selections_by_buffer.insert(
13875 buffer,
13876 (
13877 vec![jump_to_offset..jump_to_offset],
13878 Some(*line_offset_from_top),
13879 ),
13880 );
13881 }
13882 }
13883 Some(JumpData::MultiBufferRow {
13884 row,
13885 line_offset_from_top,
13886 }) => {
13887 let point = MultiBufferPoint::new(row.0, 0);
13888 if let Some((buffer, buffer_point, _)) =
13889 self.buffer.read(cx).point_to_buffer_point(point, cx)
13890 {
13891 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
13892 new_selections_by_buffer
13893 .entry(buffer)
13894 .or_insert((Vec::new(), Some(*line_offset_from_top)))
13895 .0
13896 .push(buffer_offset..buffer_offset)
13897 }
13898 }
13899 None => {
13900 let selections = self.selections.all::<usize>(cx);
13901 let multi_buffer = self.buffer.read(cx);
13902 for selection in selections {
13903 for (buffer, mut range, _) in multi_buffer
13904 .snapshot(cx)
13905 .range_to_buffer_ranges(selection.range())
13906 {
13907 // When editing branch buffers, jump to the corresponding location
13908 // in their base buffer.
13909 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
13910 let buffer = buffer_handle.read(cx);
13911 if let Some(base_buffer) = buffer.base_buffer() {
13912 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
13913 buffer_handle = base_buffer;
13914 }
13915
13916 if selection.reversed {
13917 mem::swap(&mut range.start, &mut range.end);
13918 }
13919 new_selections_by_buffer
13920 .entry(buffer_handle)
13921 .or_insert((Vec::new(), None))
13922 .0
13923 .push(range)
13924 }
13925 }
13926 }
13927 }
13928
13929 if new_selections_by_buffer.is_empty() {
13930 return;
13931 }
13932
13933 // We defer the pane interaction because we ourselves are a workspace item
13934 // and activating a new item causes the pane to call a method on us reentrantly,
13935 // which panics if we're on the stack.
13936 window.defer(cx, move |window, cx| {
13937 workspace.update(cx, |workspace, cx| {
13938 let pane = if split {
13939 workspace.adjacent_pane(window, cx)
13940 } else {
13941 workspace.active_pane().clone()
13942 };
13943
13944 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
13945 let editor = buffer
13946 .read(cx)
13947 .file()
13948 .is_none()
13949 .then(|| {
13950 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
13951 // so `workspace.open_project_item` will never find them, always opening a new editor.
13952 // Instead, we try to activate the existing editor in the pane first.
13953 let (editor, pane_item_index) =
13954 pane.read(cx).items().enumerate().find_map(|(i, item)| {
13955 let editor = item.downcast::<Editor>()?;
13956 let singleton_buffer =
13957 editor.read(cx).buffer().read(cx).as_singleton()?;
13958 if singleton_buffer == buffer {
13959 Some((editor, i))
13960 } else {
13961 None
13962 }
13963 })?;
13964 pane.update(cx, |pane, cx| {
13965 pane.activate_item(pane_item_index, true, true, window, cx)
13966 });
13967 Some(editor)
13968 })
13969 .flatten()
13970 .unwrap_or_else(|| {
13971 workspace.open_project_item::<Self>(
13972 pane.clone(),
13973 buffer,
13974 true,
13975 true,
13976 window,
13977 cx,
13978 )
13979 });
13980
13981 editor.update(cx, |editor, cx| {
13982 let autoscroll = match scroll_offset {
13983 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
13984 None => Autoscroll::newest(),
13985 };
13986 let nav_history = editor.nav_history.take();
13987 editor.change_selections(Some(autoscroll), window, cx, |s| {
13988 s.select_ranges(ranges);
13989 });
13990 editor.nav_history = nav_history;
13991 });
13992 }
13993 })
13994 });
13995 }
13996
13997 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
13998 let snapshot = self.buffer.read(cx).read(cx);
13999 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14000 Some(
14001 ranges
14002 .iter()
14003 .map(move |range| {
14004 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14005 })
14006 .collect(),
14007 )
14008 }
14009
14010 fn selection_replacement_ranges(
14011 &self,
14012 range: Range<OffsetUtf16>,
14013 cx: &mut App,
14014 ) -> Vec<Range<OffsetUtf16>> {
14015 let selections = self.selections.all::<OffsetUtf16>(cx);
14016 let newest_selection = selections
14017 .iter()
14018 .max_by_key(|selection| selection.id)
14019 .unwrap();
14020 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14021 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14022 let snapshot = self.buffer.read(cx).read(cx);
14023 selections
14024 .into_iter()
14025 .map(|mut selection| {
14026 selection.start.0 =
14027 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14028 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14029 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14030 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14031 })
14032 .collect()
14033 }
14034
14035 fn report_editor_event(
14036 &self,
14037 event_type: &'static str,
14038 file_extension: Option<String>,
14039 cx: &App,
14040 ) {
14041 if cfg!(any(test, feature = "test-support")) {
14042 return;
14043 }
14044
14045 let Some(project) = &self.project else { return };
14046
14047 // If None, we are in a file without an extension
14048 let file = self
14049 .buffer
14050 .read(cx)
14051 .as_singleton()
14052 .and_then(|b| b.read(cx).file());
14053 let file_extension = file_extension.or(file
14054 .as_ref()
14055 .and_then(|file| Path::new(file.file_name(cx)).extension())
14056 .and_then(|e| e.to_str())
14057 .map(|a| a.to_string()));
14058
14059 let vim_mode = cx
14060 .global::<SettingsStore>()
14061 .raw_user_settings()
14062 .get("vim_mode")
14063 == Some(&serde_json::Value::Bool(true));
14064
14065 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
14066 == language::language_settings::InlineCompletionProvider::Copilot;
14067 let copilot_enabled_for_language = self
14068 .buffer
14069 .read(cx)
14070 .settings_at(0, cx)
14071 .show_inline_completions;
14072
14073 let project = project.read(cx);
14074 telemetry::event!(
14075 event_type,
14076 file_extension,
14077 vim_mode,
14078 copilot_enabled,
14079 copilot_enabled_for_language,
14080 is_via_ssh = project.is_via_ssh(),
14081 );
14082 }
14083
14084 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14085 /// with each line being an array of {text, highlight} objects.
14086 fn copy_highlight_json(
14087 &mut self,
14088 _: &CopyHighlightJson,
14089 window: &mut Window,
14090 cx: &mut Context<Self>,
14091 ) {
14092 #[derive(Serialize)]
14093 struct Chunk<'a> {
14094 text: String,
14095 highlight: Option<&'a str>,
14096 }
14097
14098 let snapshot = self.buffer.read(cx).snapshot(cx);
14099 let range = self
14100 .selected_text_range(false, window, cx)
14101 .and_then(|selection| {
14102 if selection.range.is_empty() {
14103 None
14104 } else {
14105 Some(selection.range)
14106 }
14107 })
14108 .unwrap_or_else(|| 0..snapshot.len());
14109
14110 let chunks = snapshot.chunks(range, true);
14111 let mut lines = Vec::new();
14112 let mut line: VecDeque<Chunk> = VecDeque::new();
14113
14114 let Some(style) = self.style.as_ref() else {
14115 return;
14116 };
14117
14118 for chunk in chunks {
14119 let highlight = chunk
14120 .syntax_highlight_id
14121 .and_then(|id| id.name(&style.syntax));
14122 let mut chunk_lines = chunk.text.split('\n').peekable();
14123 while let Some(text) = chunk_lines.next() {
14124 let mut merged_with_last_token = false;
14125 if let Some(last_token) = line.back_mut() {
14126 if last_token.highlight == highlight {
14127 last_token.text.push_str(text);
14128 merged_with_last_token = true;
14129 }
14130 }
14131
14132 if !merged_with_last_token {
14133 line.push_back(Chunk {
14134 text: text.into(),
14135 highlight,
14136 });
14137 }
14138
14139 if chunk_lines.peek().is_some() {
14140 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14141 line.pop_front();
14142 }
14143 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14144 line.pop_back();
14145 }
14146
14147 lines.push(mem::take(&mut line));
14148 }
14149 }
14150 }
14151
14152 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14153 return;
14154 };
14155 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14156 }
14157
14158 pub fn open_context_menu(
14159 &mut self,
14160 _: &OpenContextMenu,
14161 window: &mut Window,
14162 cx: &mut Context<Self>,
14163 ) {
14164 self.request_autoscroll(Autoscroll::newest(), cx);
14165 let position = self.selections.newest_display(cx).start;
14166 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14167 }
14168
14169 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14170 &self.inlay_hint_cache
14171 }
14172
14173 pub fn replay_insert_event(
14174 &mut self,
14175 text: &str,
14176 relative_utf16_range: Option<Range<isize>>,
14177 window: &mut Window,
14178 cx: &mut Context<Self>,
14179 ) {
14180 if !self.input_enabled {
14181 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14182 return;
14183 }
14184 if let Some(relative_utf16_range) = relative_utf16_range {
14185 let selections = self.selections.all::<OffsetUtf16>(cx);
14186 self.change_selections(None, window, cx, |s| {
14187 let new_ranges = selections.into_iter().map(|range| {
14188 let start = OffsetUtf16(
14189 range
14190 .head()
14191 .0
14192 .saturating_add_signed(relative_utf16_range.start),
14193 );
14194 let end = OffsetUtf16(
14195 range
14196 .head()
14197 .0
14198 .saturating_add_signed(relative_utf16_range.end),
14199 );
14200 start..end
14201 });
14202 s.select_ranges(new_ranges);
14203 });
14204 }
14205
14206 self.handle_input(text, window, cx);
14207 }
14208
14209 pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14210 let Some(provider) = self.semantics_provider.as_ref() else {
14211 return false;
14212 };
14213
14214 let mut supports = false;
14215 self.buffer().read(cx).for_each_buffer(|buffer| {
14216 supports |= provider.supports_inlay_hints(buffer, cx);
14217 });
14218 supports
14219 }
14220 pub fn is_focused(&self, window: &mut Window) -> bool {
14221 self.focus_handle.is_focused(window)
14222 }
14223
14224 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14225 cx.emit(EditorEvent::Focused);
14226
14227 if let Some(descendant) = self
14228 .last_focused_descendant
14229 .take()
14230 .and_then(|descendant| descendant.upgrade())
14231 {
14232 window.focus(&descendant);
14233 } else {
14234 if let Some(blame) = self.blame.as_ref() {
14235 blame.update(cx, GitBlame::focus)
14236 }
14237
14238 self.blink_manager.update(cx, BlinkManager::enable);
14239 self.show_cursor_names(window, cx);
14240 self.buffer.update(cx, |buffer, cx| {
14241 buffer.finalize_last_transaction(cx);
14242 if self.leader_peer_id.is_none() {
14243 buffer.set_active_selections(
14244 &self.selections.disjoint_anchors(),
14245 self.selections.line_mode,
14246 self.cursor_shape,
14247 cx,
14248 );
14249 }
14250 });
14251 }
14252 }
14253
14254 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14255 cx.emit(EditorEvent::FocusedIn)
14256 }
14257
14258 fn handle_focus_out(
14259 &mut self,
14260 event: FocusOutEvent,
14261 _window: &mut Window,
14262 _cx: &mut Context<Self>,
14263 ) {
14264 if event.blurred != self.focus_handle {
14265 self.last_focused_descendant = Some(event.blurred);
14266 }
14267 }
14268
14269 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14270 self.blink_manager.update(cx, BlinkManager::disable);
14271 self.buffer
14272 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14273
14274 if let Some(blame) = self.blame.as_ref() {
14275 blame.update(cx, GitBlame::blur)
14276 }
14277 if !self.hover_state.focused(window, cx) {
14278 hide_hover(self, cx);
14279 }
14280
14281 self.hide_context_menu(window, cx);
14282 cx.emit(EditorEvent::Blurred);
14283 cx.notify();
14284 }
14285
14286 pub fn register_action<A: Action>(
14287 &mut self,
14288 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14289 ) -> Subscription {
14290 let id = self.next_editor_action_id.post_inc();
14291 let listener = Arc::new(listener);
14292 self.editor_actions.borrow_mut().insert(
14293 id,
14294 Box::new(move |window, _| {
14295 let listener = listener.clone();
14296 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14297 let action = action.downcast_ref().unwrap();
14298 if phase == DispatchPhase::Bubble {
14299 listener(action, window, cx)
14300 }
14301 })
14302 }),
14303 );
14304
14305 let editor_actions = self.editor_actions.clone();
14306 Subscription::new(move || {
14307 editor_actions.borrow_mut().remove(&id);
14308 })
14309 }
14310
14311 pub fn file_header_size(&self) -> u32 {
14312 FILE_HEADER_HEIGHT
14313 }
14314
14315 pub fn revert(
14316 &mut self,
14317 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14318 window: &mut Window,
14319 cx: &mut Context<Self>,
14320 ) {
14321 self.buffer().update(cx, |multi_buffer, cx| {
14322 for (buffer_id, changes) in revert_changes {
14323 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14324 buffer.update(cx, |buffer, cx| {
14325 buffer.edit(
14326 changes.into_iter().map(|(range, text)| {
14327 (range, text.to_string().map(Arc::<str>::from))
14328 }),
14329 None,
14330 cx,
14331 );
14332 });
14333 }
14334 }
14335 });
14336 self.change_selections(None, window, cx, |selections| selections.refresh());
14337 }
14338
14339 pub fn to_pixel_point(
14340 &self,
14341 source: multi_buffer::Anchor,
14342 editor_snapshot: &EditorSnapshot,
14343 window: &mut Window,
14344 ) -> Option<gpui::Point<Pixels>> {
14345 let source_point = source.to_display_point(editor_snapshot);
14346 self.display_to_pixel_point(source_point, editor_snapshot, window)
14347 }
14348
14349 pub fn display_to_pixel_point(
14350 &self,
14351 source: DisplayPoint,
14352 editor_snapshot: &EditorSnapshot,
14353 window: &mut Window,
14354 ) -> Option<gpui::Point<Pixels>> {
14355 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14356 let text_layout_details = self.text_layout_details(window);
14357 let scroll_top = text_layout_details
14358 .scroll_anchor
14359 .scroll_position(editor_snapshot)
14360 .y;
14361
14362 if source.row().as_f32() < scroll_top.floor() {
14363 return None;
14364 }
14365 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14366 let source_y = line_height * (source.row().as_f32() - scroll_top);
14367 Some(gpui::Point::new(source_x, source_y))
14368 }
14369
14370 pub fn has_active_completions_menu(&self) -> bool {
14371 self.context_menu.borrow().as_ref().map_or(false, |menu| {
14372 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14373 })
14374 }
14375
14376 pub fn register_addon<T: Addon>(&mut self, instance: T) {
14377 self.addons
14378 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14379 }
14380
14381 pub fn unregister_addon<T: Addon>(&mut self) {
14382 self.addons.remove(&std::any::TypeId::of::<T>());
14383 }
14384
14385 pub fn addon<T: Addon>(&self) -> Option<&T> {
14386 let type_id = std::any::TypeId::of::<T>();
14387 self.addons
14388 .get(&type_id)
14389 .and_then(|item| item.to_any().downcast_ref::<T>())
14390 }
14391
14392 fn character_size(&self, window: &mut Window) -> gpui::Point<Pixels> {
14393 let text_layout_details = self.text_layout_details(window);
14394 let style = &text_layout_details.editor_style;
14395 let font_id = window.text_system().resolve_font(&style.text.font());
14396 let font_size = style.text.font_size.to_pixels(window.rem_size());
14397 let line_height = style.text.line_height_in_pixels(window.rem_size());
14398 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14399
14400 gpui::Point::new(em_width, line_height)
14401 }
14402}
14403
14404fn get_unstaged_changes_for_buffers(
14405 project: &Entity<Project>,
14406 buffers: impl IntoIterator<Item = Entity<Buffer>>,
14407 buffer: Entity<MultiBuffer>,
14408 cx: &mut App,
14409) {
14410 let mut tasks = Vec::new();
14411 project.update(cx, |project, cx| {
14412 for buffer in buffers {
14413 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
14414 }
14415 });
14416 cx.spawn(|mut cx| async move {
14417 let change_sets = futures::future::join_all(tasks).await;
14418 buffer
14419 .update(&mut cx, |buffer, cx| {
14420 for change_set in change_sets {
14421 if let Some(change_set) = change_set.log_err() {
14422 buffer.add_change_set(change_set, cx);
14423 }
14424 }
14425 })
14426 .ok();
14427 })
14428 .detach();
14429}
14430
14431fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14432 let tab_size = tab_size.get() as usize;
14433 let mut width = offset;
14434
14435 for ch in text.chars() {
14436 width += if ch == '\t' {
14437 tab_size - (width % tab_size)
14438 } else {
14439 1
14440 };
14441 }
14442
14443 width - offset
14444}
14445
14446#[cfg(test)]
14447mod tests {
14448 use super::*;
14449
14450 #[test]
14451 fn test_string_size_with_expanded_tabs() {
14452 let nz = |val| NonZeroU32::new(val).unwrap();
14453 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14454 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14455 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14456 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14457 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14458 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14459 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14460 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14461 }
14462}
14463
14464/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14465struct WordBreakingTokenizer<'a> {
14466 input: &'a str,
14467}
14468
14469impl<'a> WordBreakingTokenizer<'a> {
14470 fn new(input: &'a str) -> Self {
14471 Self { input }
14472 }
14473}
14474
14475fn is_char_ideographic(ch: char) -> bool {
14476 use unicode_script::Script::*;
14477 use unicode_script::UnicodeScript;
14478 matches!(ch.script(), Han | Tangut | Yi)
14479}
14480
14481fn is_grapheme_ideographic(text: &str) -> bool {
14482 text.chars().any(is_char_ideographic)
14483}
14484
14485fn is_grapheme_whitespace(text: &str) -> bool {
14486 text.chars().any(|x| x.is_whitespace())
14487}
14488
14489fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14490 text.chars().next().map_or(false, |ch| {
14491 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14492 })
14493}
14494
14495#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14496struct WordBreakToken<'a> {
14497 token: &'a str,
14498 grapheme_len: usize,
14499 is_whitespace: bool,
14500}
14501
14502impl<'a> Iterator for WordBreakingTokenizer<'a> {
14503 /// Yields a span, the count of graphemes in the token, and whether it was
14504 /// whitespace. Note that it also breaks at word boundaries.
14505 type Item = WordBreakToken<'a>;
14506
14507 fn next(&mut self) -> Option<Self::Item> {
14508 use unicode_segmentation::UnicodeSegmentation;
14509 if self.input.is_empty() {
14510 return None;
14511 }
14512
14513 let mut iter = self.input.graphemes(true).peekable();
14514 let mut offset = 0;
14515 let mut graphemes = 0;
14516 if let Some(first_grapheme) = iter.next() {
14517 let is_whitespace = is_grapheme_whitespace(first_grapheme);
14518 offset += first_grapheme.len();
14519 graphemes += 1;
14520 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14521 if let Some(grapheme) = iter.peek().copied() {
14522 if should_stay_with_preceding_ideograph(grapheme) {
14523 offset += grapheme.len();
14524 graphemes += 1;
14525 }
14526 }
14527 } else {
14528 let mut words = self.input[offset..].split_word_bound_indices().peekable();
14529 let mut next_word_bound = words.peek().copied();
14530 if next_word_bound.map_or(false, |(i, _)| i == 0) {
14531 next_word_bound = words.next();
14532 }
14533 while let Some(grapheme) = iter.peek().copied() {
14534 if next_word_bound.map_or(false, |(i, _)| i == offset) {
14535 break;
14536 };
14537 if is_grapheme_whitespace(grapheme) != is_whitespace {
14538 break;
14539 };
14540 offset += grapheme.len();
14541 graphemes += 1;
14542 iter.next();
14543 }
14544 }
14545 let token = &self.input[..offset];
14546 self.input = &self.input[offset..];
14547 if is_whitespace {
14548 Some(WordBreakToken {
14549 token: " ",
14550 grapheme_len: 1,
14551 is_whitespace: true,
14552 })
14553 } else {
14554 Some(WordBreakToken {
14555 token,
14556 grapheme_len: graphemes,
14557 is_whitespace: false,
14558 })
14559 }
14560 } else {
14561 None
14562 }
14563 }
14564}
14565
14566#[test]
14567fn test_word_breaking_tokenizer() {
14568 let tests: &[(&str, &[(&str, usize, bool)])] = &[
14569 ("", &[]),
14570 (" ", &[(" ", 1, true)]),
14571 ("Ʒ", &[("Ʒ", 1, false)]),
14572 ("Ǽ", &[("Ǽ", 1, false)]),
14573 ("⋑", &[("⋑", 1, false)]),
14574 ("⋑⋑", &[("⋑⋑", 2, false)]),
14575 (
14576 "原理,进而",
14577 &[
14578 ("原", 1, false),
14579 ("理,", 2, false),
14580 ("进", 1, false),
14581 ("而", 1, false),
14582 ],
14583 ),
14584 (
14585 "hello world",
14586 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14587 ),
14588 (
14589 "hello, world",
14590 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14591 ),
14592 (
14593 " hello world",
14594 &[
14595 (" ", 1, true),
14596 ("hello", 5, false),
14597 (" ", 1, true),
14598 ("world", 5, false),
14599 ],
14600 ),
14601 (
14602 "这是什么 \n 钢笔",
14603 &[
14604 ("这", 1, false),
14605 ("是", 1, false),
14606 ("什", 1, false),
14607 ("么", 1, false),
14608 (" ", 1, true),
14609 ("钢", 1, false),
14610 ("笔", 1, false),
14611 ],
14612 ),
14613 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14614 ];
14615
14616 for (input, result) in tests {
14617 assert_eq!(
14618 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14619 result
14620 .iter()
14621 .copied()
14622 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14623 token,
14624 grapheme_len,
14625 is_whitespace,
14626 })
14627 .collect::<Vec<_>>()
14628 );
14629 }
14630}
14631
14632fn wrap_with_prefix(
14633 line_prefix: String,
14634 unwrapped_text: String,
14635 wrap_column: usize,
14636 tab_size: NonZeroU32,
14637) -> String {
14638 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14639 let mut wrapped_text = String::new();
14640 let mut current_line = line_prefix.clone();
14641
14642 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14643 let mut current_line_len = line_prefix_len;
14644 for WordBreakToken {
14645 token,
14646 grapheme_len,
14647 is_whitespace,
14648 } in tokenizer
14649 {
14650 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14651 wrapped_text.push_str(current_line.trim_end());
14652 wrapped_text.push('\n');
14653 current_line.truncate(line_prefix.len());
14654 current_line_len = line_prefix_len;
14655 if !is_whitespace {
14656 current_line.push_str(token);
14657 current_line_len += grapheme_len;
14658 }
14659 } else if !is_whitespace {
14660 current_line.push_str(token);
14661 current_line_len += grapheme_len;
14662 } else if current_line_len != line_prefix_len {
14663 current_line.push(' ');
14664 current_line_len += 1;
14665 }
14666 }
14667
14668 if !current_line.is_empty() {
14669 wrapped_text.push_str(¤t_line);
14670 }
14671 wrapped_text
14672}
14673
14674#[test]
14675fn test_wrap_with_prefix() {
14676 assert_eq!(
14677 wrap_with_prefix(
14678 "# ".to_string(),
14679 "abcdefg".to_string(),
14680 4,
14681 NonZeroU32::new(4).unwrap()
14682 ),
14683 "# abcdefg"
14684 );
14685 assert_eq!(
14686 wrap_with_prefix(
14687 "".to_string(),
14688 "\thello world".to_string(),
14689 8,
14690 NonZeroU32::new(4).unwrap()
14691 ),
14692 "hello\nworld"
14693 );
14694 assert_eq!(
14695 wrap_with_prefix(
14696 "// ".to_string(),
14697 "xx \nyy zz aa bb cc".to_string(),
14698 12,
14699 NonZeroU32::new(4).unwrap()
14700 ),
14701 "// xx yy zz\n// aa bb cc"
14702 );
14703 assert_eq!(
14704 wrap_with_prefix(
14705 String::new(),
14706 "这是什么 \n 钢笔".to_string(),
14707 3,
14708 NonZeroU32::new(4).unwrap()
14709 ),
14710 "这是什\n么 钢\n笔"
14711 );
14712}
14713
14714pub trait CollaborationHub {
14715 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14716 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14717 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14718}
14719
14720impl CollaborationHub for Entity<Project> {
14721 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14722 self.read(cx).collaborators()
14723 }
14724
14725 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14726 self.read(cx).user_store().read(cx).participant_indices()
14727 }
14728
14729 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14730 let this = self.read(cx);
14731 let user_ids = this.collaborators().values().map(|c| c.user_id);
14732 this.user_store().read_with(cx, |user_store, cx| {
14733 user_store.participant_names(user_ids, cx)
14734 })
14735 }
14736}
14737
14738pub trait SemanticsProvider {
14739 fn hover(
14740 &self,
14741 buffer: &Entity<Buffer>,
14742 position: text::Anchor,
14743 cx: &mut App,
14744 ) -> Option<Task<Vec<project::Hover>>>;
14745
14746 fn inlay_hints(
14747 &self,
14748 buffer_handle: Entity<Buffer>,
14749 range: Range<text::Anchor>,
14750 cx: &mut App,
14751 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14752
14753 fn resolve_inlay_hint(
14754 &self,
14755 hint: InlayHint,
14756 buffer_handle: Entity<Buffer>,
14757 server_id: LanguageServerId,
14758 cx: &mut App,
14759 ) -> Option<Task<anyhow::Result<InlayHint>>>;
14760
14761 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
14762
14763 fn document_highlights(
14764 &self,
14765 buffer: &Entity<Buffer>,
14766 position: text::Anchor,
14767 cx: &mut App,
14768 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14769
14770 fn definitions(
14771 &self,
14772 buffer: &Entity<Buffer>,
14773 position: text::Anchor,
14774 kind: GotoDefinitionKind,
14775 cx: &mut App,
14776 ) -> Option<Task<Result<Vec<LocationLink>>>>;
14777
14778 fn range_for_rename(
14779 &self,
14780 buffer: &Entity<Buffer>,
14781 position: text::Anchor,
14782 cx: &mut App,
14783 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14784
14785 fn perform_rename(
14786 &self,
14787 buffer: &Entity<Buffer>,
14788 position: text::Anchor,
14789 new_name: String,
14790 cx: &mut App,
14791 ) -> Option<Task<Result<ProjectTransaction>>>;
14792}
14793
14794pub trait CompletionProvider {
14795 fn completions(
14796 &self,
14797 buffer: &Entity<Buffer>,
14798 buffer_position: text::Anchor,
14799 trigger: CompletionContext,
14800 window: &mut Window,
14801 cx: &mut Context<Editor>,
14802 ) -> Task<Result<Vec<Completion>>>;
14803
14804 fn resolve_completions(
14805 &self,
14806 buffer: Entity<Buffer>,
14807 completion_indices: Vec<usize>,
14808 completions: Rc<RefCell<Box<[Completion]>>>,
14809 cx: &mut Context<Editor>,
14810 ) -> Task<Result<bool>>;
14811
14812 fn apply_additional_edits_for_completion(
14813 &self,
14814 _buffer: Entity<Buffer>,
14815 _completions: Rc<RefCell<Box<[Completion]>>>,
14816 _completion_index: usize,
14817 _push_to_history: bool,
14818 _cx: &mut Context<Editor>,
14819 ) -> Task<Result<Option<language::Transaction>>> {
14820 Task::ready(Ok(None))
14821 }
14822
14823 fn is_completion_trigger(
14824 &self,
14825 buffer: &Entity<Buffer>,
14826 position: language::Anchor,
14827 text: &str,
14828 trigger_in_words: bool,
14829 cx: &mut Context<Editor>,
14830 ) -> bool;
14831
14832 fn sort_completions(&self) -> bool {
14833 true
14834 }
14835}
14836
14837pub trait CodeActionProvider {
14838 fn id(&self) -> Arc<str>;
14839
14840 fn code_actions(
14841 &self,
14842 buffer: &Entity<Buffer>,
14843 range: Range<text::Anchor>,
14844 window: &mut Window,
14845 cx: &mut App,
14846 ) -> Task<Result<Vec<CodeAction>>>;
14847
14848 fn apply_code_action(
14849 &self,
14850 buffer_handle: Entity<Buffer>,
14851 action: CodeAction,
14852 excerpt_id: ExcerptId,
14853 push_to_history: bool,
14854 window: &mut Window,
14855 cx: &mut App,
14856 ) -> Task<Result<ProjectTransaction>>;
14857}
14858
14859impl CodeActionProvider for Entity<Project> {
14860 fn id(&self) -> Arc<str> {
14861 "project".into()
14862 }
14863
14864 fn code_actions(
14865 &self,
14866 buffer: &Entity<Buffer>,
14867 range: Range<text::Anchor>,
14868 _window: &mut Window,
14869 cx: &mut App,
14870 ) -> Task<Result<Vec<CodeAction>>> {
14871 self.update(cx, |project, cx| {
14872 project.code_actions(buffer, range, None, cx)
14873 })
14874 }
14875
14876 fn apply_code_action(
14877 &self,
14878 buffer_handle: Entity<Buffer>,
14879 action: CodeAction,
14880 _excerpt_id: ExcerptId,
14881 push_to_history: bool,
14882 _window: &mut Window,
14883 cx: &mut App,
14884 ) -> Task<Result<ProjectTransaction>> {
14885 self.update(cx, |project, cx| {
14886 project.apply_code_action(buffer_handle, action, push_to_history, cx)
14887 })
14888 }
14889}
14890
14891fn snippet_completions(
14892 project: &Project,
14893 buffer: &Entity<Buffer>,
14894 buffer_position: text::Anchor,
14895 cx: &mut App,
14896) -> Task<Result<Vec<Completion>>> {
14897 let language = buffer.read(cx).language_at(buffer_position);
14898 let language_name = language.as_ref().map(|language| language.lsp_id());
14899 let snippet_store = project.snippets().read(cx);
14900 let snippets = snippet_store.snippets_for(language_name, cx);
14901
14902 if snippets.is_empty() {
14903 return Task::ready(Ok(vec![]));
14904 }
14905 let snapshot = buffer.read(cx).text_snapshot();
14906 let chars: String = snapshot
14907 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
14908 .collect();
14909
14910 let scope = language.map(|language| language.default_scope());
14911 let executor = cx.background_executor().clone();
14912
14913 cx.background_executor().spawn(async move {
14914 let classifier = CharClassifier::new(scope).for_completion(true);
14915 let mut last_word = chars
14916 .chars()
14917 .take_while(|c| classifier.is_word(*c))
14918 .collect::<String>();
14919 last_word = last_word.chars().rev().collect();
14920
14921 if last_word.is_empty() {
14922 return Ok(vec![]);
14923 }
14924
14925 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
14926 let to_lsp = |point: &text::Anchor| {
14927 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
14928 point_to_lsp(end)
14929 };
14930 let lsp_end = to_lsp(&buffer_position);
14931
14932 let candidates = snippets
14933 .iter()
14934 .enumerate()
14935 .flat_map(|(ix, snippet)| {
14936 snippet
14937 .prefix
14938 .iter()
14939 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
14940 })
14941 .collect::<Vec<StringMatchCandidate>>();
14942
14943 let mut matches = fuzzy::match_strings(
14944 &candidates,
14945 &last_word,
14946 last_word.chars().any(|c| c.is_uppercase()),
14947 100,
14948 &Default::default(),
14949 executor,
14950 )
14951 .await;
14952
14953 // Remove all candidates where the query's start does not match the start of any word in the candidate
14954 if let Some(query_start) = last_word.chars().next() {
14955 matches.retain(|string_match| {
14956 split_words(&string_match.string).any(|word| {
14957 // Check that the first codepoint of the word as lowercase matches the first
14958 // codepoint of the query as lowercase
14959 word.chars()
14960 .flat_map(|codepoint| codepoint.to_lowercase())
14961 .zip(query_start.to_lowercase())
14962 .all(|(word_cp, query_cp)| word_cp == query_cp)
14963 })
14964 });
14965 }
14966
14967 let matched_strings = matches
14968 .into_iter()
14969 .map(|m| m.string)
14970 .collect::<HashSet<_>>();
14971
14972 let result: Vec<Completion> = snippets
14973 .into_iter()
14974 .filter_map(|snippet| {
14975 let matching_prefix = snippet
14976 .prefix
14977 .iter()
14978 .find(|prefix| matched_strings.contains(*prefix))?;
14979 let start = as_offset - last_word.len();
14980 let start = snapshot.anchor_before(start);
14981 let range = start..buffer_position;
14982 let lsp_start = to_lsp(&start);
14983 let lsp_range = lsp::Range {
14984 start: lsp_start,
14985 end: lsp_end,
14986 };
14987 Some(Completion {
14988 old_range: range,
14989 new_text: snippet.body.clone(),
14990 resolved: false,
14991 label: CodeLabel {
14992 text: matching_prefix.clone(),
14993 runs: vec![],
14994 filter_range: 0..matching_prefix.len(),
14995 },
14996 server_id: LanguageServerId(usize::MAX),
14997 documentation: snippet
14998 .description
14999 .clone()
15000 .map(CompletionDocumentation::SingleLine),
15001 lsp_completion: lsp::CompletionItem {
15002 label: snippet.prefix.first().unwrap().clone(),
15003 kind: Some(CompletionItemKind::SNIPPET),
15004 label_details: snippet.description.as_ref().map(|description| {
15005 lsp::CompletionItemLabelDetails {
15006 detail: Some(description.clone()),
15007 description: None,
15008 }
15009 }),
15010 insert_text_format: Some(InsertTextFormat::SNIPPET),
15011 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15012 lsp::InsertReplaceEdit {
15013 new_text: snippet.body.clone(),
15014 insert: lsp_range,
15015 replace: lsp_range,
15016 },
15017 )),
15018 filter_text: Some(snippet.body.clone()),
15019 sort_text: Some(char::MAX.to_string()),
15020 ..Default::default()
15021 },
15022 confirm: None,
15023 })
15024 })
15025 .collect();
15026
15027 Ok(result)
15028 })
15029}
15030
15031impl CompletionProvider for Entity<Project> {
15032 fn completions(
15033 &self,
15034 buffer: &Entity<Buffer>,
15035 buffer_position: text::Anchor,
15036 options: CompletionContext,
15037 _window: &mut Window,
15038 cx: &mut Context<Editor>,
15039 ) -> Task<Result<Vec<Completion>>> {
15040 self.update(cx, |project, cx| {
15041 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15042 let project_completions = project.completions(buffer, buffer_position, options, cx);
15043 cx.background_executor().spawn(async move {
15044 let mut completions = project_completions.await?;
15045 let snippets_completions = snippets.await?;
15046 completions.extend(snippets_completions);
15047 Ok(completions)
15048 })
15049 })
15050 }
15051
15052 fn resolve_completions(
15053 &self,
15054 buffer: Entity<Buffer>,
15055 completion_indices: Vec<usize>,
15056 completions: Rc<RefCell<Box<[Completion]>>>,
15057 cx: &mut Context<Editor>,
15058 ) -> Task<Result<bool>> {
15059 self.update(cx, |project, cx| {
15060 project.lsp_store().update(cx, |lsp_store, cx| {
15061 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15062 })
15063 })
15064 }
15065
15066 fn apply_additional_edits_for_completion(
15067 &self,
15068 buffer: Entity<Buffer>,
15069 completions: Rc<RefCell<Box<[Completion]>>>,
15070 completion_index: usize,
15071 push_to_history: bool,
15072 cx: &mut Context<Editor>,
15073 ) -> Task<Result<Option<language::Transaction>>> {
15074 self.update(cx, |project, cx| {
15075 project.lsp_store().update(cx, |lsp_store, cx| {
15076 lsp_store.apply_additional_edits_for_completion(
15077 buffer,
15078 completions,
15079 completion_index,
15080 push_to_history,
15081 cx,
15082 )
15083 })
15084 })
15085 }
15086
15087 fn is_completion_trigger(
15088 &self,
15089 buffer: &Entity<Buffer>,
15090 position: language::Anchor,
15091 text: &str,
15092 trigger_in_words: bool,
15093 cx: &mut Context<Editor>,
15094 ) -> bool {
15095 let mut chars = text.chars();
15096 let char = if let Some(char) = chars.next() {
15097 char
15098 } else {
15099 return false;
15100 };
15101 if chars.next().is_some() {
15102 return false;
15103 }
15104
15105 let buffer = buffer.read(cx);
15106 let snapshot = buffer.snapshot();
15107 if !snapshot.settings_at(position, cx).show_completions_on_input {
15108 return false;
15109 }
15110 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15111 if trigger_in_words && classifier.is_word(char) {
15112 return true;
15113 }
15114
15115 buffer.completion_triggers().contains(text)
15116 }
15117}
15118
15119impl SemanticsProvider for Entity<Project> {
15120 fn hover(
15121 &self,
15122 buffer: &Entity<Buffer>,
15123 position: text::Anchor,
15124 cx: &mut App,
15125 ) -> Option<Task<Vec<project::Hover>>> {
15126 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15127 }
15128
15129 fn document_highlights(
15130 &self,
15131 buffer: &Entity<Buffer>,
15132 position: text::Anchor,
15133 cx: &mut App,
15134 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15135 Some(self.update(cx, |project, cx| {
15136 project.document_highlights(buffer, position, cx)
15137 }))
15138 }
15139
15140 fn definitions(
15141 &self,
15142 buffer: &Entity<Buffer>,
15143 position: text::Anchor,
15144 kind: GotoDefinitionKind,
15145 cx: &mut App,
15146 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15147 Some(self.update(cx, |project, cx| match kind {
15148 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15149 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15150 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15151 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15152 }))
15153 }
15154
15155 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15156 // TODO: make this work for remote projects
15157 self.read(cx)
15158 .language_servers_for_local_buffer(buffer.read(cx), cx)
15159 .any(
15160 |(_, server)| match server.capabilities().inlay_hint_provider {
15161 Some(lsp::OneOf::Left(enabled)) => enabled,
15162 Some(lsp::OneOf::Right(_)) => true,
15163 None => false,
15164 },
15165 )
15166 }
15167
15168 fn inlay_hints(
15169 &self,
15170 buffer_handle: Entity<Buffer>,
15171 range: Range<text::Anchor>,
15172 cx: &mut App,
15173 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15174 Some(self.update(cx, |project, cx| {
15175 project.inlay_hints(buffer_handle, range, cx)
15176 }))
15177 }
15178
15179 fn resolve_inlay_hint(
15180 &self,
15181 hint: InlayHint,
15182 buffer_handle: Entity<Buffer>,
15183 server_id: LanguageServerId,
15184 cx: &mut App,
15185 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15186 Some(self.update(cx, |project, cx| {
15187 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15188 }))
15189 }
15190
15191 fn range_for_rename(
15192 &self,
15193 buffer: &Entity<Buffer>,
15194 position: text::Anchor,
15195 cx: &mut App,
15196 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15197 Some(self.update(cx, |project, cx| {
15198 let buffer = buffer.clone();
15199 let task = project.prepare_rename(buffer.clone(), position, cx);
15200 cx.spawn(|_, mut cx| async move {
15201 Ok(match task.await? {
15202 PrepareRenameResponse::Success(range) => Some(range),
15203 PrepareRenameResponse::InvalidPosition => None,
15204 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15205 // Fallback on using TreeSitter info to determine identifier range
15206 buffer.update(&mut cx, |buffer, _| {
15207 let snapshot = buffer.snapshot();
15208 let (range, kind) = snapshot.surrounding_word(position);
15209 if kind != Some(CharKind::Word) {
15210 return None;
15211 }
15212 Some(
15213 snapshot.anchor_before(range.start)
15214 ..snapshot.anchor_after(range.end),
15215 )
15216 })?
15217 }
15218 })
15219 })
15220 }))
15221 }
15222
15223 fn perform_rename(
15224 &self,
15225 buffer: &Entity<Buffer>,
15226 position: text::Anchor,
15227 new_name: String,
15228 cx: &mut App,
15229 ) -> Option<Task<Result<ProjectTransaction>>> {
15230 Some(self.update(cx, |project, cx| {
15231 project.perform_rename(buffer.clone(), position, new_name, cx)
15232 }))
15233 }
15234}
15235
15236fn inlay_hint_settings(
15237 location: Anchor,
15238 snapshot: &MultiBufferSnapshot,
15239 cx: &mut Context<Editor>,
15240) -> InlayHintSettings {
15241 let file = snapshot.file_at(location);
15242 let language = snapshot.language_at(location).map(|l| l.name());
15243 language_settings(language, file, cx).inlay_hints
15244}
15245
15246fn consume_contiguous_rows(
15247 contiguous_row_selections: &mut Vec<Selection<Point>>,
15248 selection: &Selection<Point>,
15249 display_map: &DisplaySnapshot,
15250 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15251) -> (MultiBufferRow, MultiBufferRow) {
15252 contiguous_row_selections.push(selection.clone());
15253 let start_row = MultiBufferRow(selection.start.row);
15254 let mut end_row = ending_row(selection, display_map);
15255
15256 while let Some(next_selection) = selections.peek() {
15257 if next_selection.start.row <= end_row.0 {
15258 end_row = ending_row(next_selection, display_map);
15259 contiguous_row_selections.push(selections.next().unwrap().clone());
15260 } else {
15261 break;
15262 }
15263 }
15264 (start_row, end_row)
15265}
15266
15267fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15268 if next_selection.end.column > 0 || next_selection.is_empty() {
15269 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15270 } else {
15271 MultiBufferRow(next_selection.end.row)
15272 }
15273}
15274
15275impl EditorSnapshot {
15276 pub fn remote_selections_in_range<'a>(
15277 &'a self,
15278 range: &'a Range<Anchor>,
15279 collaboration_hub: &dyn CollaborationHub,
15280 cx: &'a App,
15281 ) -> impl 'a + Iterator<Item = RemoteSelection> {
15282 let participant_names = collaboration_hub.user_names(cx);
15283 let participant_indices = collaboration_hub.user_participant_indices(cx);
15284 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15285 let collaborators_by_replica_id = collaborators_by_peer_id
15286 .iter()
15287 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15288 .collect::<HashMap<_, _>>();
15289 self.buffer_snapshot
15290 .selections_in_range(range, false)
15291 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15292 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15293 let participant_index = participant_indices.get(&collaborator.user_id).copied();
15294 let user_name = participant_names.get(&collaborator.user_id).cloned();
15295 Some(RemoteSelection {
15296 replica_id,
15297 selection,
15298 cursor_shape,
15299 line_mode,
15300 participant_index,
15301 peer_id: collaborator.peer_id,
15302 user_name,
15303 })
15304 })
15305 }
15306
15307 pub fn hunks_for_ranges(
15308 &self,
15309 ranges: impl Iterator<Item = Range<Point>>,
15310 ) -> Vec<MultiBufferDiffHunk> {
15311 let mut hunks = Vec::new();
15312 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15313 HashMap::default();
15314 for query_range in ranges {
15315 let query_rows =
15316 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15317 for hunk in self.buffer_snapshot.diff_hunks_in_range(
15318 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15319 ) {
15320 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15321 // when the caret is just above or just below the deleted hunk.
15322 let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15323 let related_to_selection = if allow_adjacent {
15324 hunk.row_range.overlaps(&query_rows)
15325 || hunk.row_range.start == query_rows.end
15326 || hunk.row_range.end == query_rows.start
15327 } else {
15328 hunk.row_range.overlaps(&query_rows)
15329 };
15330 if related_to_selection {
15331 if !processed_buffer_rows
15332 .entry(hunk.buffer_id)
15333 .or_default()
15334 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15335 {
15336 continue;
15337 }
15338 hunks.push(hunk);
15339 }
15340 }
15341 }
15342
15343 hunks
15344 }
15345
15346 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15347 self.display_snapshot.buffer_snapshot.language_at(position)
15348 }
15349
15350 pub fn is_focused(&self) -> bool {
15351 self.is_focused
15352 }
15353
15354 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15355 self.placeholder_text.as_ref()
15356 }
15357
15358 pub fn scroll_position(&self) -> gpui::Point<f32> {
15359 self.scroll_anchor.scroll_position(&self.display_snapshot)
15360 }
15361
15362 fn gutter_dimensions(
15363 &self,
15364 font_id: FontId,
15365 font_size: Pixels,
15366 max_line_number_width: Pixels,
15367 cx: &App,
15368 ) -> Option<GutterDimensions> {
15369 if !self.show_gutter {
15370 return None;
15371 }
15372
15373 let descent = cx.text_system().descent(font_id, font_size);
15374 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15375 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15376
15377 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15378 matches!(
15379 ProjectSettings::get_global(cx).git.git_gutter,
15380 Some(GitGutterSetting::TrackedFiles)
15381 )
15382 });
15383 let gutter_settings = EditorSettings::get_global(cx).gutter;
15384 let show_line_numbers = self
15385 .show_line_numbers
15386 .unwrap_or(gutter_settings.line_numbers);
15387 let line_gutter_width = if show_line_numbers {
15388 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15389 let min_width_for_number_on_gutter = em_advance * 4.0;
15390 max_line_number_width.max(min_width_for_number_on_gutter)
15391 } else {
15392 0.0.into()
15393 };
15394
15395 let show_code_actions = self
15396 .show_code_actions
15397 .unwrap_or(gutter_settings.code_actions);
15398
15399 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15400
15401 let git_blame_entries_width =
15402 self.git_blame_gutter_max_author_length
15403 .map(|max_author_length| {
15404 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15405
15406 /// The number of characters to dedicate to gaps and margins.
15407 const SPACING_WIDTH: usize = 4;
15408
15409 let max_char_count = max_author_length
15410 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15411 + ::git::SHORT_SHA_LENGTH
15412 + MAX_RELATIVE_TIMESTAMP.len()
15413 + SPACING_WIDTH;
15414
15415 em_advance * max_char_count
15416 });
15417
15418 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15419 left_padding += if show_code_actions || show_runnables {
15420 em_width * 3.0
15421 } else if show_git_gutter && show_line_numbers {
15422 em_width * 2.0
15423 } else if show_git_gutter || show_line_numbers {
15424 em_width
15425 } else {
15426 px(0.)
15427 };
15428
15429 let right_padding = if gutter_settings.folds && show_line_numbers {
15430 em_width * 4.0
15431 } else if gutter_settings.folds {
15432 em_width * 3.0
15433 } else if show_line_numbers {
15434 em_width
15435 } else {
15436 px(0.)
15437 };
15438
15439 Some(GutterDimensions {
15440 left_padding,
15441 right_padding,
15442 width: line_gutter_width + left_padding + right_padding,
15443 margin: -descent,
15444 git_blame_entries_width,
15445 })
15446 }
15447
15448 pub fn render_crease_toggle(
15449 &self,
15450 buffer_row: MultiBufferRow,
15451 row_contains_cursor: bool,
15452 editor: Entity<Editor>,
15453 window: &mut Window,
15454 cx: &mut App,
15455 ) -> Option<AnyElement> {
15456 let folded = self.is_line_folded(buffer_row);
15457 let mut is_foldable = false;
15458
15459 if let Some(crease) = self
15460 .crease_snapshot
15461 .query_row(buffer_row, &self.buffer_snapshot)
15462 {
15463 is_foldable = true;
15464 match crease {
15465 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15466 if let Some(render_toggle) = render_toggle {
15467 let toggle_callback =
15468 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15469 if folded {
15470 editor.update(cx, |editor, cx| {
15471 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15472 });
15473 } else {
15474 editor.update(cx, |editor, cx| {
15475 editor.unfold_at(
15476 &crate::UnfoldAt { buffer_row },
15477 window,
15478 cx,
15479 )
15480 });
15481 }
15482 });
15483 return Some((render_toggle)(
15484 buffer_row,
15485 folded,
15486 toggle_callback,
15487 window,
15488 cx,
15489 ));
15490 }
15491 }
15492 }
15493 }
15494
15495 is_foldable |= self.starts_indent(buffer_row);
15496
15497 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15498 Some(
15499 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15500 .toggle_state(folded)
15501 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15502 if folded {
15503 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15504 } else {
15505 this.fold_at(&FoldAt { buffer_row }, window, cx);
15506 }
15507 }))
15508 .into_any_element(),
15509 )
15510 } else {
15511 None
15512 }
15513 }
15514
15515 pub fn render_crease_trailer(
15516 &self,
15517 buffer_row: MultiBufferRow,
15518 window: &mut Window,
15519 cx: &mut App,
15520 ) -> Option<AnyElement> {
15521 let folded = self.is_line_folded(buffer_row);
15522 if let Crease::Inline { render_trailer, .. } = self
15523 .crease_snapshot
15524 .query_row(buffer_row, &self.buffer_snapshot)?
15525 {
15526 let render_trailer = render_trailer.as_ref()?;
15527 Some(render_trailer(buffer_row, folded, window, cx))
15528 } else {
15529 None
15530 }
15531 }
15532}
15533
15534impl Deref for EditorSnapshot {
15535 type Target = DisplaySnapshot;
15536
15537 fn deref(&self) -> &Self::Target {
15538 &self.display_snapshot
15539 }
15540}
15541
15542#[derive(Clone, Debug, PartialEq, Eq)]
15543pub enum EditorEvent {
15544 InputIgnored {
15545 text: Arc<str>,
15546 },
15547 InputHandled {
15548 utf16_range_to_replace: Option<Range<isize>>,
15549 text: Arc<str>,
15550 },
15551 ExcerptsAdded {
15552 buffer: Entity<Buffer>,
15553 predecessor: ExcerptId,
15554 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15555 },
15556 ExcerptsRemoved {
15557 ids: Vec<ExcerptId>,
15558 },
15559 BufferFoldToggled {
15560 ids: Vec<ExcerptId>,
15561 folded: bool,
15562 },
15563 ExcerptsEdited {
15564 ids: Vec<ExcerptId>,
15565 },
15566 ExcerptsExpanded {
15567 ids: Vec<ExcerptId>,
15568 },
15569 BufferEdited,
15570 Edited {
15571 transaction_id: clock::Lamport,
15572 },
15573 Reparsed(BufferId),
15574 Focused,
15575 FocusedIn,
15576 Blurred,
15577 DirtyChanged,
15578 Saved,
15579 TitleChanged,
15580 DiffBaseChanged,
15581 SelectionsChanged {
15582 local: bool,
15583 },
15584 ScrollPositionChanged {
15585 local: bool,
15586 autoscroll: bool,
15587 },
15588 Closed,
15589 TransactionUndone {
15590 transaction_id: clock::Lamport,
15591 },
15592 TransactionBegun {
15593 transaction_id: clock::Lamport,
15594 },
15595 Reloaded,
15596 CursorShapeChanged,
15597}
15598
15599impl EventEmitter<EditorEvent> for Editor {}
15600
15601impl Focusable for Editor {
15602 fn focus_handle(&self, _cx: &App) -> FocusHandle {
15603 self.focus_handle.clone()
15604 }
15605}
15606
15607impl Render for Editor {
15608 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15609 let settings = ThemeSettings::get_global(cx);
15610
15611 let mut text_style = match self.mode {
15612 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15613 color: cx.theme().colors().editor_foreground,
15614 font_family: settings.ui_font.family.clone(),
15615 font_features: settings.ui_font.features.clone(),
15616 font_fallbacks: settings.ui_font.fallbacks.clone(),
15617 font_size: rems(0.875).into(),
15618 font_weight: settings.ui_font.weight,
15619 line_height: relative(settings.buffer_line_height.value()),
15620 ..Default::default()
15621 },
15622 EditorMode::Full => TextStyle {
15623 color: cx.theme().colors().editor_foreground,
15624 font_family: settings.buffer_font.family.clone(),
15625 font_features: settings.buffer_font.features.clone(),
15626 font_fallbacks: settings.buffer_font.fallbacks.clone(),
15627 font_size: settings.buffer_font_size().into(),
15628 font_weight: settings.buffer_font.weight,
15629 line_height: relative(settings.buffer_line_height.value()),
15630 ..Default::default()
15631 },
15632 };
15633 if let Some(text_style_refinement) = &self.text_style_refinement {
15634 text_style.refine(text_style_refinement)
15635 }
15636
15637 let background = match self.mode {
15638 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15639 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15640 EditorMode::Full => cx.theme().colors().editor_background,
15641 };
15642
15643 EditorElement::new(
15644 &cx.entity(),
15645 EditorStyle {
15646 background,
15647 local_player: cx.theme().players().local(),
15648 text: text_style,
15649 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15650 syntax: cx.theme().syntax().clone(),
15651 status: cx.theme().status().clone(),
15652 inlay_hints_style: make_inlay_hints_style(cx),
15653 inline_completion_styles: make_suggestion_styles(cx),
15654 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15655 },
15656 )
15657 }
15658}
15659
15660impl EntityInputHandler for Editor {
15661 fn text_for_range(
15662 &mut self,
15663 range_utf16: Range<usize>,
15664 adjusted_range: &mut Option<Range<usize>>,
15665 _: &mut Window,
15666 cx: &mut Context<Self>,
15667 ) -> Option<String> {
15668 let snapshot = self.buffer.read(cx).read(cx);
15669 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15670 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15671 if (start.0..end.0) != range_utf16 {
15672 adjusted_range.replace(start.0..end.0);
15673 }
15674 Some(snapshot.text_for_range(start..end).collect())
15675 }
15676
15677 fn selected_text_range(
15678 &mut self,
15679 ignore_disabled_input: bool,
15680 _: &mut Window,
15681 cx: &mut Context<Self>,
15682 ) -> Option<UTF16Selection> {
15683 // Prevent the IME menu from appearing when holding down an alphabetic key
15684 // while input is disabled.
15685 if !ignore_disabled_input && !self.input_enabled {
15686 return None;
15687 }
15688
15689 let selection = self.selections.newest::<OffsetUtf16>(cx);
15690 let range = selection.range();
15691
15692 Some(UTF16Selection {
15693 range: range.start.0..range.end.0,
15694 reversed: selection.reversed,
15695 })
15696 }
15697
15698 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15699 let snapshot = self.buffer.read(cx).read(cx);
15700 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15701 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15702 }
15703
15704 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15705 self.clear_highlights::<InputComposition>(cx);
15706 self.ime_transaction.take();
15707 }
15708
15709 fn replace_text_in_range(
15710 &mut self,
15711 range_utf16: Option<Range<usize>>,
15712 text: &str,
15713 window: &mut Window,
15714 cx: &mut Context<Self>,
15715 ) {
15716 if !self.input_enabled {
15717 cx.emit(EditorEvent::InputIgnored { text: text.into() });
15718 return;
15719 }
15720
15721 self.transact(window, cx, |this, window, cx| {
15722 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15723 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15724 Some(this.selection_replacement_ranges(range_utf16, cx))
15725 } else {
15726 this.marked_text_ranges(cx)
15727 };
15728
15729 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15730 let newest_selection_id = this.selections.newest_anchor().id;
15731 this.selections
15732 .all::<OffsetUtf16>(cx)
15733 .iter()
15734 .zip(ranges_to_replace.iter())
15735 .find_map(|(selection, range)| {
15736 if selection.id == newest_selection_id {
15737 Some(
15738 (range.start.0 as isize - selection.head().0 as isize)
15739 ..(range.end.0 as isize - selection.head().0 as isize),
15740 )
15741 } else {
15742 None
15743 }
15744 })
15745 });
15746
15747 cx.emit(EditorEvent::InputHandled {
15748 utf16_range_to_replace: range_to_replace,
15749 text: text.into(),
15750 });
15751
15752 if let Some(new_selected_ranges) = new_selected_ranges {
15753 this.change_selections(None, window, cx, |selections| {
15754 selections.select_ranges(new_selected_ranges)
15755 });
15756 this.backspace(&Default::default(), window, cx);
15757 }
15758
15759 this.handle_input(text, window, cx);
15760 });
15761
15762 if let Some(transaction) = self.ime_transaction {
15763 self.buffer.update(cx, |buffer, cx| {
15764 buffer.group_until_transaction(transaction, cx);
15765 });
15766 }
15767
15768 self.unmark_text(window, cx);
15769 }
15770
15771 fn replace_and_mark_text_in_range(
15772 &mut self,
15773 range_utf16: Option<Range<usize>>,
15774 text: &str,
15775 new_selected_range_utf16: Option<Range<usize>>,
15776 window: &mut Window,
15777 cx: &mut Context<Self>,
15778 ) {
15779 if !self.input_enabled {
15780 return;
15781 }
15782
15783 let transaction = self.transact(window, cx, |this, window, cx| {
15784 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15785 let snapshot = this.buffer.read(cx).read(cx);
15786 if let Some(relative_range_utf16) = range_utf16.as_ref() {
15787 for marked_range in &mut marked_ranges {
15788 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15789 marked_range.start.0 += relative_range_utf16.start;
15790 marked_range.start =
15791 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15792 marked_range.end =
15793 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15794 }
15795 }
15796 Some(marked_ranges)
15797 } else if let Some(range_utf16) = range_utf16 {
15798 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15799 Some(this.selection_replacement_ranges(range_utf16, cx))
15800 } else {
15801 None
15802 };
15803
15804 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
15805 let newest_selection_id = this.selections.newest_anchor().id;
15806 this.selections
15807 .all::<OffsetUtf16>(cx)
15808 .iter()
15809 .zip(ranges_to_replace.iter())
15810 .find_map(|(selection, range)| {
15811 if selection.id == newest_selection_id {
15812 Some(
15813 (range.start.0 as isize - selection.head().0 as isize)
15814 ..(range.end.0 as isize - selection.head().0 as isize),
15815 )
15816 } else {
15817 None
15818 }
15819 })
15820 });
15821
15822 cx.emit(EditorEvent::InputHandled {
15823 utf16_range_to_replace: range_to_replace,
15824 text: text.into(),
15825 });
15826
15827 if let Some(ranges) = ranges_to_replace {
15828 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
15829 }
15830
15831 let marked_ranges = {
15832 let snapshot = this.buffer.read(cx).read(cx);
15833 this.selections
15834 .disjoint_anchors()
15835 .iter()
15836 .map(|selection| {
15837 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
15838 })
15839 .collect::<Vec<_>>()
15840 };
15841
15842 if text.is_empty() {
15843 this.unmark_text(window, cx);
15844 } else {
15845 this.highlight_text::<InputComposition>(
15846 marked_ranges.clone(),
15847 HighlightStyle {
15848 underline: Some(UnderlineStyle {
15849 thickness: px(1.),
15850 color: None,
15851 wavy: false,
15852 }),
15853 ..Default::default()
15854 },
15855 cx,
15856 );
15857 }
15858
15859 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
15860 let use_autoclose = this.use_autoclose;
15861 let use_auto_surround = this.use_auto_surround;
15862 this.set_use_autoclose(false);
15863 this.set_use_auto_surround(false);
15864 this.handle_input(text, window, cx);
15865 this.set_use_autoclose(use_autoclose);
15866 this.set_use_auto_surround(use_auto_surround);
15867
15868 if let Some(new_selected_range) = new_selected_range_utf16 {
15869 let snapshot = this.buffer.read(cx).read(cx);
15870 let new_selected_ranges = marked_ranges
15871 .into_iter()
15872 .map(|marked_range| {
15873 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
15874 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
15875 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
15876 snapshot.clip_offset_utf16(new_start, Bias::Left)
15877 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
15878 })
15879 .collect::<Vec<_>>();
15880
15881 drop(snapshot);
15882 this.change_selections(None, window, cx, |selections| {
15883 selections.select_ranges(new_selected_ranges)
15884 });
15885 }
15886 });
15887
15888 self.ime_transaction = self.ime_transaction.or(transaction);
15889 if let Some(transaction) = self.ime_transaction {
15890 self.buffer.update(cx, |buffer, cx| {
15891 buffer.group_until_transaction(transaction, cx);
15892 });
15893 }
15894
15895 if self.text_highlights::<InputComposition>(cx).is_none() {
15896 self.ime_transaction.take();
15897 }
15898 }
15899
15900 fn bounds_for_range(
15901 &mut self,
15902 range_utf16: Range<usize>,
15903 element_bounds: gpui::Bounds<Pixels>,
15904 window: &mut Window,
15905 cx: &mut Context<Self>,
15906 ) -> Option<gpui::Bounds<Pixels>> {
15907 let text_layout_details = self.text_layout_details(window);
15908 let gpui::Point {
15909 x: em_width,
15910 y: line_height,
15911 } = self.character_size(window);
15912
15913 let snapshot = self.snapshot(window, cx);
15914 let scroll_position = snapshot.scroll_position();
15915 let scroll_left = scroll_position.x * em_width;
15916
15917 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
15918 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
15919 + self.gutter_dimensions.width
15920 + self.gutter_dimensions.margin;
15921 let y = line_height * (start.row().as_f32() - scroll_position.y);
15922
15923 Some(Bounds {
15924 origin: element_bounds.origin + point(x, y),
15925 size: size(em_width, line_height),
15926 })
15927 }
15928}
15929
15930trait SelectionExt {
15931 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
15932 fn spanned_rows(
15933 &self,
15934 include_end_if_at_line_start: bool,
15935 map: &DisplaySnapshot,
15936 ) -> Range<MultiBufferRow>;
15937}
15938
15939impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
15940 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
15941 let start = self
15942 .start
15943 .to_point(&map.buffer_snapshot)
15944 .to_display_point(map);
15945 let end = self
15946 .end
15947 .to_point(&map.buffer_snapshot)
15948 .to_display_point(map);
15949 if self.reversed {
15950 end..start
15951 } else {
15952 start..end
15953 }
15954 }
15955
15956 fn spanned_rows(
15957 &self,
15958 include_end_if_at_line_start: bool,
15959 map: &DisplaySnapshot,
15960 ) -> Range<MultiBufferRow> {
15961 let start = self.start.to_point(&map.buffer_snapshot);
15962 let mut end = self.end.to_point(&map.buffer_snapshot);
15963 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
15964 end.row -= 1;
15965 }
15966
15967 let buffer_start = map.prev_line_boundary(start).0;
15968 let buffer_end = map.next_line_boundary(end).0;
15969 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
15970 }
15971}
15972
15973impl<T: InvalidationRegion> InvalidationStack<T> {
15974 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
15975 where
15976 S: Clone + ToOffset,
15977 {
15978 while let Some(region) = self.last() {
15979 let all_selections_inside_invalidation_ranges =
15980 if selections.len() == region.ranges().len() {
15981 selections
15982 .iter()
15983 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
15984 .all(|(selection, invalidation_range)| {
15985 let head = selection.head().to_offset(buffer);
15986 invalidation_range.start <= head && invalidation_range.end >= head
15987 })
15988 } else {
15989 false
15990 };
15991
15992 if all_selections_inside_invalidation_ranges {
15993 break;
15994 } else {
15995 self.pop();
15996 }
15997 }
15998 }
15999}
16000
16001impl<T> Default for InvalidationStack<T> {
16002 fn default() -> Self {
16003 Self(Default::default())
16004 }
16005}
16006
16007impl<T> Deref for InvalidationStack<T> {
16008 type Target = Vec<T>;
16009
16010 fn deref(&self) -> &Self::Target {
16011 &self.0
16012 }
16013}
16014
16015impl<T> DerefMut for InvalidationStack<T> {
16016 fn deref_mut(&mut self) -> &mut Self::Target {
16017 &mut self.0
16018 }
16019}
16020
16021impl InvalidationRegion for SnippetState {
16022 fn ranges(&self) -> &[Range<Anchor>] {
16023 &self.ranges[self.active_index]
16024 }
16025}
16026
16027pub fn diagnostic_block_renderer(
16028 diagnostic: Diagnostic,
16029 max_message_rows: Option<u8>,
16030 allow_closing: bool,
16031 _is_valid: bool,
16032) -> RenderBlock {
16033 let (text_without_backticks, code_ranges) =
16034 highlight_diagnostic_message(&diagnostic, max_message_rows);
16035
16036 Arc::new(move |cx: &mut BlockContext| {
16037 let group_id: SharedString = cx.block_id.to_string().into();
16038
16039 let mut text_style = cx.window.text_style().clone();
16040 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16041 let theme_settings = ThemeSettings::get_global(cx);
16042 text_style.font_family = theme_settings.buffer_font.family.clone();
16043 text_style.font_style = theme_settings.buffer_font.style;
16044 text_style.font_features = theme_settings.buffer_font.features.clone();
16045 text_style.font_weight = theme_settings.buffer_font.weight;
16046
16047 let multi_line_diagnostic = diagnostic.message.contains('\n');
16048
16049 let buttons = |diagnostic: &Diagnostic| {
16050 if multi_line_diagnostic {
16051 v_flex()
16052 } else {
16053 h_flex()
16054 }
16055 .when(allow_closing, |div| {
16056 div.children(diagnostic.is_primary.then(|| {
16057 IconButton::new("close-block", IconName::XCircle)
16058 .icon_color(Color::Muted)
16059 .size(ButtonSize::Compact)
16060 .style(ButtonStyle::Transparent)
16061 .visible_on_hover(group_id.clone())
16062 .on_click(move |_click, window, cx| {
16063 window.dispatch_action(Box::new(Cancel), cx)
16064 })
16065 .tooltip(|window, cx| {
16066 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16067 })
16068 }))
16069 })
16070 .child(
16071 IconButton::new("copy-block", IconName::Copy)
16072 .icon_color(Color::Muted)
16073 .size(ButtonSize::Compact)
16074 .style(ButtonStyle::Transparent)
16075 .visible_on_hover(group_id.clone())
16076 .on_click({
16077 let message = diagnostic.message.clone();
16078 move |_click, _, cx| {
16079 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16080 }
16081 })
16082 .tooltip(Tooltip::text("Copy diagnostic message")),
16083 )
16084 };
16085
16086 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16087 AvailableSpace::min_size(),
16088 cx.window,
16089 cx.app,
16090 );
16091
16092 h_flex()
16093 .id(cx.block_id)
16094 .group(group_id.clone())
16095 .relative()
16096 .size_full()
16097 .block_mouse_down()
16098 .pl(cx.gutter_dimensions.width)
16099 .w(cx.max_width - cx.gutter_dimensions.full_width())
16100 .child(
16101 div()
16102 .flex()
16103 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16104 .flex_shrink(),
16105 )
16106 .child(buttons(&diagnostic))
16107 .child(div().flex().flex_shrink_0().child(
16108 StyledText::new(text_without_backticks.clone()).with_highlights(
16109 &text_style,
16110 code_ranges.iter().map(|range| {
16111 (
16112 range.clone(),
16113 HighlightStyle {
16114 font_weight: Some(FontWeight::BOLD),
16115 ..Default::default()
16116 },
16117 )
16118 }),
16119 ),
16120 ))
16121 .into_any_element()
16122 })
16123}
16124
16125fn inline_completion_edit_text(
16126 current_snapshot: &BufferSnapshot,
16127 edits: &[(Range<Anchor>, String)],
16128 edit_preview: &EditPreview,
16129 include_deletions: bool,
16130 cx: &App,
16131) -> HighlightedText {
16132 let edits = edits
16133 .iter()
16134 .map(|(anchor, text)| {
16135 (
16136 anchor.start.text_anchor..anchor.end.text_anchor,
16137 text.clone(),
16138 )
16139 })
16140 .collect::<Vec<_>>();
16141
16142 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16143}
16144
16145pub fn highlight_diagnostic_message(
16146 diagnostic: &Diagnostic,
16147 mut max_message_rows: Option<u8>,
16148) -> (SharedString, Vec<Range<usize>>) {
16149 let mut text_without_backticks = String::new();
16150 let mut code_ranges = Vec::new();
16151
16152 if let Some(source) = &diagnostic.source {
16153 text_without_backticks.push_str(source);
16154 code_ranges.push(0..source.len());
16155 text_without_backticks.push_str(": ");
16156 }
16157
16158 let mut prev_offset = 0;
16159 let mut in_code_block = false;
16160 let has_row_limit = max_message_rows.is_some();
16161 let mut newline_indices = diagnostic
16162 .message
16163 .match_indices('\n')
16164 .filter(|_| has_row_limit)
16165 .map(|(ix, _)| ix)
16166 .fuse()
16167 .peekable();
16168
16169 for (quote_ix, _) in diagnostic
16170 .message
16171 .match_indices('`')
16172 .chain([(diagnostic.message.len(), "")])
16173 {
16174 let mut first_newline_ix = None;
16175 let mut last_newline_ix = None;
16176 while let Some(newline_ix) = newline_indices.peek() {
16177 if *newline_ix < quote_ix {
16178 if first_newline_ix.is_none() {
16179 first_newline_ix = Some(*newline_ix);
16180 }
16181 last_newline_ix = Some(*newline_ix);
16182
16183 if let Some(rows_left) = &mut max_message_rows {
16184 if *rows_left == 0 {
16185 break;
16186 } else {
16187 *rows_left -= 1;
16188 }
16189 }
16190 let _ = newline_indices.next();
16191 } else {
16192 break;
16193 }
16194 }
16195 let prev_len = text_without_backticks.len();
16196 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16197 text_without_backticks.push_str(new_text);
16198 if in_code_block {
16199 code_ranges.push(prev_len..text_without_backticks.len());
16200 }
16201 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16202 in_code_block = !in_code_block;
16203 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16204 text_without_backticks.push_str("...");
16205 break;
16206 }
16207 }
16208
16209 (text_without_backticks.into(), code_ranges)
16210}
16211
16212fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16213 match severity {
16214 DiagnosticSeverity::ERROR => colors.error,
16215 DiagnosticSeverity::WARNING => colors.warning,
16216 DiagnosticSeverity::INFORMATION => colors.info,
16217 DiagnosticSeverity::HINT => colors.info,
16218 _ => colors.ignored,
16219 }
16220}
16221
16222pub fn styled_runs_for_code_label<'a>(
16223 label: &'a CodeLabel,
16224 syntax_theme: &'a theme::SyntaxTheme,
16225) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16226 let fade_out = HighlightStyle {
16227 fade_out: Some(0.35),
16228 ..Default::default()
16229 };
16230
16231 let mut prev_end = label.filter_range.end;
16232 label
16233 .runs
16234 .iter()
16235 .enumerate()
16236 .flat_map(move |(ix, (range, highlight_id))| {
16237 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16238 style
16239 } else {
16240 return Default::default();
16241 };
16242 let mut muted_style = style;
16243 muted_style.highlight(fade_out);
16244
16245 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16246 if range.start >= label.filter_range.end {
16247 if range.start > prev_end {
16248 runs.push((prev_end..range.start, fade_out));
16249 }
16250 runs.push((range.clone(), muted_style));
16251 } else if range.end <= label.filter_range.end {
16252 runs.push((range.clone(), style));
16253 } else {
16254 runs.push((range.start..label.filter_range.end, style));
16255 runs.push((label.filter_range.end..range.end, muted_style));
16256 }
16257 prev_end = cmp::max(prev_end, range.end);
16258
16259 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16260 runs.push((prev_end..label.text.len(), fade_out));
16261 }
16262
16263 runs
16264 })
16265}
16266
16267pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16268 let mut prev_index = 0;
16269 let mut prev_codepoint: Option<char> = None;
16270 text.char_indices()
16271 .chain([(text.len(), '\0')])
16272 .filter_map(move |(index, codepoint)| {
16273 let prev_codepoint = prev_codepoint.replace(codepoint)?;
16274 let is_boundary = index == text.len()
16275 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16276 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16277 if is_boundary {
16278 let chunk = &text[prev_index..index];
16279 prev_index = index;
16280 Some(chunk)
16281 } else {
16282 None
16283 }
16284 })
16285}
16286
16287pub trait RangeToAnchorExt: Sized {
16288 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16289
16290 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16291 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16292 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16293 }
16294}
16295
16296impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16297 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16298 let start_offset = self.start.to_offset(snapshot);
16299 let end_offset = self.end.to_offset(snapshot);
16300 if start_offset == end_offset {
16301 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16302 } else {
16303 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16304 }
16305 }
16306}
16307
16308pub trait RowExt {
16309 fn as_f32(&self) -> f32;
16310
16311 fn next_row(&self) -> Self;
16312
16313 fn previous_row(&self) -> Self;
16314
16315 fn minus(&self, other: Self) -> u32;
16316}
16317
16318impl RowExt for DisplayRow {
16319 fn as_f32(&self) -> f32 {
16320 self.0 as f32
16321 }
16322
16323 fn next_row(&self) -> Self {
16324 Self(self.0 + 1)
16325 }
16326
16327 fn previous_row(&self) -> Self {
16328 Self(self.0.saturating_sub(1))
16329 }
16330
16331 fn minus(&self, other: Self) -> u32 {
16332 self.0 - other.0
16333 }
16334}
16335
16336impl RowExt for MultiBufferRow {
16337 fn as_f32(&self) -> f32 {
16338 self.0 as f32
16339 }
16340
16341 fn next_row(&self) -> Self {
16342 Self(self.0 + 1)
16343 }
16344
16345 fn previous_row(&self) -> Self {
16346 Self(self.0.saturating_sub(1))
16347 }
16348
16349 fn minus(&self, other: Self) -> u32 {
16350 self.0 - other.0
16351 }
16352}
16353
16354trait RowRangeExt {
16355 type Row;
16356
16357 fn len(&self) -> usize;
16358
16359 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16360}
16361
16362impl RowRangeExt for Range<MultiBufferRow> {
16363 type Row = MultiBufferRow;
16364
16365 fn len(&self) -> usize {
16366 (self.end.0 - self.start.0) as usize
16367 }
16368
16369 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16370 (self.start.0..self.end.0).map(MultiBufferRow)
16371 }
16372}
16373
16374impl RowRangeExt for Range<DisplayRow> {
16375 type Row = DisplayRow;
16376
16377 fn len(&self) -> usize {
16378 (self.end.0 - self.start.0) as usize
16379 }
16380
16381 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16382 (self.start.0..self.end.0).map(DisplayRow)
16383 }
16384}
16385
16386/// If select range has more than one line, we
16387/// just point the cursor to range.start.
16388fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16389 if range.start.row == range.end.row {
16390 range
16391 } else {
16392 range.start..range.start
16393 }
16394}
16395pub struct KillRing(ClipboardItem);
16396impl Global for KillRing {}
16397
16398const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16399
16400fn all_edits_insertions_or_deletions(
16401 edits: &Vec<(Range<Anchor>, String)>,
16402 snapshot: &MultiBufferSnapshot,
16403) -> bool {
16404 let mut all_insertions = true;
16405 let mut all_deletions = true;
16406
16407 for (range, new_text) in edits.iter() {
16408 let range_is_empty = range.to_offset(&snapshot).is_empty();
16409 let text_is_empty = new_text.is_empty();
16410
16411 if range_is_empty != text_is_empty {
16412 if range_is_empty {
16413 all_deletions = false;
16414 } else {
16415 all_insertions = false;
16416 }
16417 } else {
16418 return false;
16419 }
16420
16421 if !all_insertions && !all_deletions {
16422 return false;
16423 }
16424 }
16425 all_insertions || all_deletions
16426}