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::*;
66pub use element::{
67 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
68};
69use element::{LineWithInvisibles, PositionMap};
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 show_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 last_position_map: Option<Rc<PositionMap>>,
719 expect_bounds_change: Option<Bounds<Pixels>>,
720 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
721 tasks_update_task: Option<Task<()>>,
722 in_project_search: bool,
723 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
724 breadcrumb_header: Option<String>,
725 focused_block: Option<FocusedBlock>,
726 next_scroll_position: NextScrollCursorCenterTopBottom,
727 addons: HashMap<TypeId, Box<dyn Addon>>,
728 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
729 selection_mark_mode: bool,
730 toggle_fold_multiple_buffers: Task<()>,
731 _scroll_cursor_center_top_bottom_task: Task<()>,
732}
733
734#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
735enum NextScrollCursorCenterTopBottom {
736 #[default]
737 Center,
738 Top,
739 Bottom,
740}
741
742impl NextScrollCursorCenterTopBottom {
743 fn next(&self) -> Self {
744 match self {
745 Self::Center => Self::Top,
746 Self::Top => Self::Bottom,
747 Self::Bottom => Self::Center,
748 }
749 }
750}
751
752#[derive(Clone)]
753pub struct EditorSnapshot {
754 pub mode: EditorMode,
755 show_gutter: bool,
756 show_line_numbers: Option<bool>,
757 show_git_diff_gutter: Option<bool>,
758 show_code_actions: Option<bool>,
759 show_runnables: Option<bool>,
760 git_blame_gutter_max_author_length: Option<usize>,
761 pub display_snapshot: DisplaySnapshot,
762 pub placeholder_text: Option<Arc<str>>,
763 is_focused: bool,
764 scroll_anchor: ScrollAnchor,
765 ongoing_scroll: OngoingScroll,
766 current_line_highlight: CurrentLineHighlight,
767 gutter_hovered: bool,
768}
769
770const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
771
772#[derive(Default, Debug, Clone, Copy)]
773pub struct GutterDimensions {
774 pub left_padding: Pixels,
775 pub right_padding: Pixels,
776 pub width: Pixels,
777 pub margin: Pixels,
778 pub git_blame_entries_width: Option<Pixels>,
779}
780
781impl GutterDimensions {
782 /// The full width of the space taken up by the gutter.
783 pub fn full_width(&self) -> Pixels {
784 self.margin + self.width
785 }
786
787 /// The width of the space reserved for the fold indicators,
788 /// use alongside 'justify_end' and `gutter_width` to
789 /// right align content with the line numbers
790 pub fn fold_area_width(&self) -> Pixels {
791 self.margin + self.right_padding
792 }
793}
794
795#[derive(Debug)]
796pub struct RemoteSelection {
797 pub replica_id: ReplicaId,
798 pub selection: Selection<Anchor>,
799 pub cursor_shape: CursorShape,
800 pub peer_id: PeerId,
801 pub line_mode: bool,
802 pub participant_index: Option<ParticipantIndex>,
803 pub user_name: Option<SharedString>,
804}
805
806#[derive(Clone, Debug)]
807struct SelectionHistoryEntry {
808 selections: Arc<[Selection<Anchor>]>,
809 select_next_state: Option<SelectNextState>,
810 select_prev_state: Option<SelectNextState>,
811 add_selections_state: Option<AddSelectionsState>,
812}
813
814enum SelectionHistoryMode {
815 Normal,
816 Undoing,
817 Redoing,
818}
819
820#[derive(Clone, PartialEq, Eq, Hash)]
821struct HoveredCursor {
822 replica_id: u16,
823 selection_id: usize,
824}
825
826impl Default for SelectionHistoryMode {
827 fn default() -> Self {
828 Self::Normal
829 }
830}
831
832#[derive(Default)]
833struct SelectionHistory {
834 #[allow(clippy::type_complexity)]
835 selections_by_transaction:
836 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
837 mode: SelectionHistoryMode,
838 undo_stack: VecDeque<SelectionHistoryEntry>,
839 redo_stack: VecDeque<SelectionHistoryEntry>,
840}
841
842impl SelectionHistory {
843 fn insert_transaction(
844 &mut self,
845 transaction_id: TransactionId,
846 selections: Arc<[Selection<Anchor>]>,
847 ) {
848 self.selections_by_transaction
849 .insert(transaction_id, (selections, None));
850 }
851
852 #[allow(clippy::type_complexity)]
853 fn transaction(
854 &self,
855 transaction_id: TransactionId,
856 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
857 self.selections_by_transaction.get(&transaction_id)
858 }
859
860 #[allow(clippy::type_complexity)]
861 fn transaction_mut(
862 &mut self,
863 transaction_id: TransactionId,
864 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
865 self.selections_by_transaction.get_mut(&transaction_id)
866 }
867
868 fn push(&mut self, entry: SelectionHistoryEntry) {
869 if !entry.selections.is_empty() {
870 match self.mode {
871 SelectionHistoryMode::Normal => {
872 self.push_undo(entry);
873 self.redo_stack.clear();
874 }
875 SelectionHistoryMode::Undoing => self.push_redo(entry),
876 SelectionHistoryMode::Redoing => self.push_undo(entry),
877 }
878 }
879 }
880
881 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
882 if self
883 .undo_stack
884 .back()
885 .map_or(true, |e| e.selections != entry.selections)
886 {
887 self.undo_stack.push_back(entry);
888 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
889 self.undo_stack.pop_front();
890 }
891 }
892 }
893
894 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
895 if self
896 .redo_stack
897 .back()
898 .map_or(true, |e| e.selections != entry.selections)
899 {
900 self.redo_stack.push_back(entry);
901 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
902 self.redo_stack.pop_front();
903 }
904 }
905 }
906}
907
908struct RowHighlight {
909 index: usize,
910 range: Range<Anchor>,
911 color: Hsla,
912 should_autoscroll: bool,
913}
914
915#[derive(Clone, Debug)]
916struct AddSelectionsState {
917 above: bool,
918 stack: Vec<usize>,
919}
920
921#[derive(Clone)]
922struct SelectNextState {
923 query: AhoCorasick,
924 wordwise: bool,
925 done: bool,
926}
927
928impl std::fmt::Debug for SelectNextState {
929 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
930 f.debug_struct(std::any::type_name::<Self>())
931 .field("wordwise", &self.wordwise)
932 .field("done", &self.done)
933 .finish()
934 }
935}
936
937#[derive(Debug)]
938struct AutocloseRegion {
939 selection_id: usize,
940 range: Range<Anchor>,
941 pair: BracketPair,
942}
943
944#[derive(Debug)]
945struct SnippetState {
946 ranges: Vec<Vec<Range<Anchor>>>,
947 active_index: usize,
948 choices: Vec<Option<Vec<String>>>,
949}
950
951#[doc(hidden)]
952pub struct RenameState {
953 pub range: Range<Anchor>,
954 pub old_name: Arc<str>,
955 pub editor: Entity<Editor>,
956 block_id: CustomBlockId,
957}
958
959struct InvalidationStack<T>(Vec<T>);
960
961struct RegisteredInlineCompletionProvider {
962 provider: Arc<dyn InlineCompletionProviderHandle>,
963 _subscription: Subscription,
964}
965
966#[derive(Debug)]
967struct ActiveDiagnosticGroup {
968 primary_range: Range<Anchor>,
969 primary_message: String,
970 group_id: usize,
971 blocks: HashMap<CustomBlockId, Diagnostic>,
972 is_valid: bool,
973}
974
975#[derive(Serialize, Deserialize, Clone, Debug)]
976pub struct ClipboardSelection {
977 pub len: usize,
978 pub is_entire_line: bool,
979 pub first_line_indent: u32,
980}
981
982#[derive(Debug)]
983pub(crate) struct NavigationData {
984 cursor_anchor: Anchor,
985 cursor_position: Point,
986 scroll_anchor: ScrollAnchor,
987 scroll_top_row: u32,
988}
989
990#[derive(Debug, Clone, Copy, PartialEq, Eq)]
991pub enum GotoDefinitionKind {
992 Symbol,
993 Declaration,
994 Type,
995 Implementation,
996}
997
998#[derive(Debug, Clone)]
999enum InlayHintRefreshReason {
1000 Toggle(bool),
1001 SettingsChange(InlayHintSettings),
1002 NewLinesShown,
1003 BufferEdited(HashSet<Arc<Language>>),
1004 RefreshRequested,
1005 ExcerptsRemoved(Vec<ExcerptId>),
1006}
1007
1008impl InlayHintRefreshReason {
1009 fn description(&self) -> &'static str {
1010 match self {
1011 Self::Toggle(_) => "toggle",
1012 Self::SettingsChange(_) => "settings change",
1013 Self::NewLinesShown => "new lines shown",
1014 Self::BufferEdited(_) => "buffer edited",
1015 Self::RefreshRequested => "refresh requested",
1016 Self::ExcerptsRemoved(_) => "excerpts removed",
1017 }
1018 }
1019}
1020
1021pub enum FormatTarget {
1022 Buffers,
1023 Ranges(Vec<Range<MultiBufferPoint>>),
1024}
1025
1026pub(crate) struct FocusedBlock {
1027 id: BlockId,
1028 focus_handle: WeakFocusHandle,
1029}
1030
1031#[derive(Clone)]
1032enum JumpData {
1033 MultiBufferRow {
1034 row: MultiBufferRow,
1035 line_offset_from_top: u32,
1036 },
1037 MultiBufferPoint {
1038 excerpt_id: ExcerptId,
1039 position: Point,
1040 anchor: text::Anchor,
1041 line_offset_from_top: u32,
1042 },
1043}
1044
1045pub enum MultibufferSelectionMode {
1046 First,
1047 All,
1048}
1049
1050impl Editor {
1051 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1052 let buffer = cx.new(|cx| Buffer::local("", cx));
1053 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1054 Self::new(
1055 EditorMode::SingleLine { auto_width: false },
1056 buffer,
1057 None,
1058 false,
1059 window,
1060 cx,
1061 )
1062 }
1063
1064 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1065 let buffer = cx.new(|cx| Buffer::local("", cx));
1066 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1067 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1068 }
1069
1070 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1071 let buffer = cx.new(|cx| Buffer::local("", cx));
1072 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1073 Self::new(
1074 EditorMode::SingleLine { auto_width: true },
1075 buffer,
1076 None,
1077 false,
1078 window,
1079 cx,
1080 )
1081 }
1082
1083 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1084 let buffer = cx.new(|cx| Buffer::local("", cx));
1085 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1086 Self::new(
1087 EditorMode::AutoHeight { max_lines },
1088 buffer,
1089 None,
1090 false,
1091 window,
1092 cx,
1093 )
1094 }
1095
1096 pub fn for_buffer(
1097 buffer: Entity<Buffer>,
1098 project: Option<Entity<Project>>,
1099 window: &mut Window,
1100 cx: &mut Context<Self>,
1101 ) -> Self {
1102 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1103 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1104 }
1105
1106 pub fn for_multibuffer(
1107 buffer: Entity<MultiBuffer>,
1108 project: Option<Entity<Project>>,
1109 show_excerpt_controls: bool,
1110 window: &mut Window,
1111 cx: &mut Context<Self>,
1112 ) -> Self {
1113 Self::new(
1114 EditorMode::Full,
1115 buffer,
1116 project,
1117 show_excerpt_controls,
1118 window,
1119 cx,
1120 )
1121 }
1122
1123 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1124 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1125 let mut clone = Self::new(
1126 self.mode,
1127 self.buffer.clone(),
1128 self.project.clone(),
1129 show_excerpt_controls,
1130 window,
1131 cx,
1132 );
1133 self.display_map.update(cx, |display_map, cx| {
1134 let snapshot = display_map.snapshot(cx);
1135 clone.display_map.update(cx, |display_map, cx| {
1136 display_map.set_state(&snapshot, cx);
1137 });
1138 });
1139 clone.selections.clone_state(&self.selections);
1140 clone.scroll_manager.clone_state(&self.scroll_manager);
1141 clone.searchable = self.searchable;
1142 clone
1143 }
1144
1145 pub fn new(
1146 mode: EditorMode,
1147 buffer: Entity<MultiBuffer>,
1148 project: Option<Entity<Project>>,
1149 show_excerpt_controls: bool,
1150 window: &mut Window,
1151 cx: &mut Context<Self>,
1152 ) -> Self {
1153 let style = window.text_style();
1154 let font_size = style.font_size.to_pixels(window.rem_size());
1155 let editor = cx.entity().downgrade();
1156 let fold_placeholder = FoldPlaceholder {
1157 constrain_width: true,
1158 render: Arc::new(move |fold_id, fold_range, _, cx| {
1159 let editor = editor.clone();
1160 div()
1161 .id(fold_id)
1162 .bg(cx.theme().colors().ghost_element_background)
1163 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1164 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1165 .rounded_sm()
1166 .size_full()
1167 .cursor_pointer()
1168 .child("⋯")
1169 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1170 .on_click(move |_, _window, cx| {
1171 editor
1172 .update(cx, |editor, cx| {
1173 editor.unfold_ranges(
1174 &[fold_range.start..fold_range.end],
1175 true,
1176 false,
1177 cx,
1178 );
1179 cx.stop_propagation();
1180 })
1181 .ok();
1182 })
1183 .into_any()
1184 }),
1185 merge_adjacent: true,
1186 ..Default::default()
1187 };
1188 let display_map = cx.new(|cx| {
1189 DisplayMap::new(
1190 buffer.clone(),
1191 style.font(),
1192 font_size,
1193 None,
1194 show_excerpt_controls,
1195 FILE_HEADER_HEIGHT,
1196 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1197 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1198 fold_placeholder,
1199 cx,
1200 )
1201 });
1202
1203 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1204
1205 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1206
1207 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1208 .then(|| language_settings::SoftWrap::None);
1209
1210 let mut project_subscriptions = Vec::new();
1211 if mode == EditorMode::Full {
1212 if let Some(project) = project.as_ref() {
1213 if buffer.read(cx).is_singleton() {
1214 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1215 cx.emit(EditorEvent::TitleChanged);
1216 }));
1217 }
1218 project_subscriptions.push(cx.subscribe_in(
1219 project,
1220 window,
1221 |editor, _, event, window, cx| {
1222 if let project::Event::RefreshInlayHints = event {
1223 editor
1224 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1225 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1226 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1227 let focus_handle = editor.focus_handle(cx);
1228 if focus_handle.is_focused(window) {
1229 let snapshot = buffer.read(cx).snapshot();
1230 for (range, snippet) in snippet_edits {
1231 let editor_range =
1232 language::range_from_lsp(*range).to_offset(&snapshot);
1233 editor
1234 .insert_snippet(
1235 &[editor_range],
1236 snippet.clone(),
1237 window,
1238 cx,
1239 )
1240 .ok();
1241 }
1242 }
1243 }
1244 }
1245 },
1246 ));
1247 if let Some(task_inventory) = project
1248 .read(cx)
1249 .task_store()
1250 .read(cx)
1251 .task_inventory()
1252 .cloned()
1253 {
1254 project_subscriptions.push(cx.observe_in(
1255 &task_inventory,
1256 window,
1257 |editor, _, window, cx| {
1258 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1259 },
1260 ));
1261 }
1262 }
1263 }
1264
1265 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1266
1267 let inlay_hint_settings =
1268 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1269 let focus_handle = cx.focus_handle();
1270 cx.on_focus(&focus_handle, window, Self::handle_focus)
1271 .detach();
1272 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1273 .detach();
1274 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1275 .detach();
1276 cx.on_blur(&focus_handle, window, Self::handle_blur)
1277 .detach();
1278
1279 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1280 Some(false)
1281 } else {
1282 None
1283 };
1284
1285 let mut code_action_providers = Vec::new();
1286 if let Some(project) = project.clone() {
1287 get_unstaged_changes_for_buffers(
1288 &project,
1289 buffer.read(cx).all_buffers(),
1290 buffer.clone(),
1291 cx,
1292 );
1293 code_action_providers.push(Rc::new(project) as Rc<_>);
1294 }
1295
1296 let mut this = Self {
1297 focus_handle,
1298 show_cursor_when_unfocused: false,
1299 last_focused_descendant: None,
1300 buffer: buffer.clone(),
1301 display_map: display_map.clone(),
1302 selections,
1303 scroll_manager: ScrollManager::new(cx),
1304 columnar_selection_tail: None,
1305 add_selections_state: None,
1306 select_next_state: None,
1307 select_prev_state: None,
1308 selection_history: Default::default(),
1309 autoclose_regions: Default::default(),
1310 snippet_stack: Default::default(),
1311 select_larger_syntax_node_stack: Vec::new(),
1312 ime_transaction: Default::default(),
1313 active_diagnostics: None,
1314 soft_wrap_mode_override,
1315 completion_provider: project.clone().map(|project| Box::new(project) as _),
1316 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1317 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1318 project,
1319 blink_manager: blink_manager.clone(),
1320 show_local_selections: true,
1321 show_scrollbars: true,
1322 mode,
1323 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1324 show_gutter: mode == EditorMode::Full,
1325 show_line_numbers: None,
1326 use_relative_line_numbers: None,
1327 show_git_diff_gutter: None,
1328 show_code_actions: None,
1329 show_runnables: None,
1330 show_wrap_guides: None,
1331 show_indent_guides,
1332 placeholder_text: None,
1333 highlight_order: 0,
1334 highlighted_rows: HashMap::default(),
1335 background_highlights: Default::default(),
1336 gutter_highlights: TreeMap::default(),
1337 scrollbar_marker_state: ScrollbarMarkerState::default(),
1338 active_indent_guides_state: ActiveIndentGuidesState::default(),
1339 nav_history: None,
1340 context_menu: RefCell::new(None),
1341 mouse_context_menu: None,
1342 completion_tasks: Default::default(),
1343 signature_help_state: SignatureHelpState::default(),
1344 auto_signature_help: None,
1345 find_all_references_task_sources: Vec::new(),
1346 next_completion_id: 0,
1347 next_inlay_id: 0,
1348 code_action_providers,
1349 available_code_actions: Default::default(),
1350 code_actions_task: Default::default(),
1351 document_highlights_task: Default::default(),
1352 linked_editing_range_task: Default::default(),
1353 pending_rename: Default::default(),
1354 searchable: true,
1355 cursor_shape: EditorSettings::get_global(cx)
1356 .cursor_shape
1357 .unwrap_or_default(),
1358 current_line_highlight: None,
1359 autoindent_mode: Some(AutoindentMode::EachLine),
1360 collapse_matches: false,
1361 workspace: None,
1362 input_enabled: true,
1363 use_modal_editing: mode == EditorMode::Full,
1364 read_only: false,
1365 use_autoclose: true,
1366 use_auto_surround: true,
1367 auto_replace_emoji_shortcode: false,
1368 leader_peer_id: None,
1369 remote_id: None,
1370 hover_state: Default::default(),
1371 pending_mouse_down: None,
1372 hovered_link_state: Default::default(),
1373 inline_completion_provider: None,
1374 active_inline_completion: None,
1375 stale_inline_completion_in_menu: None,
1376 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1377
1378 gutter_hovered: false,
1379 pixel_position_of_newest_cursor: None,
1380 last_bounds: None,
1381 last_position_map: None,
1382 expect_bounds_change: None,
1383 gutter_dimensions: GutterDimensions::default(),
1384 style: None,
1385 show_cursor_names: false,
1386 hovered_cursors: Default::default(),
1387 next_editor_action_id: EditorActionId::default(),
1388 editor_actions: Rc::default(),
1389 show_inline_completions_override: None,
1390 show_inline_completions: true,
1391 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1392 custom_context_menu: None,
1393 show_git_blame_gutter: false,
1394 show_git_blame_inline: false,
1395 show_selection_menu: None,
1396 show_git_blame_inline_delay_task: None,
1397 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1398 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1399 .session
1400 .restore_unsaved_buffers,
1401 blame: None,
1402 blame_subscription: None,
1403 tasks: Default::default(),
1404 _subscriptions: vec![
1405 cx.observe(&buffer, Self::on_buffer_changed),
1406 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1407 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1408 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1409 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1410 cx.observe_window_activation(window, |editor, window, cx| {
1411 let active = window.is_window_active();
1412 editor.blink_manager.update(cx, |blink_manager, cx| {
1413 if active {
1414 blink_manager.enable(cx);
1415 } else {
1416 blink_manager.disable(cx);
1417 }
1418 });
1419 }),
1420 ],
1421 tasks_update_task: None,
1422 linked_edit_ranges: Default::default(),
1423 in_project_search: false,
1424 previous_search_ranges: None,
1425 breadcrumb_header: None,
1426 focused_block: None,
1427 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1428 addons: HashMap::default(),
1429 registered_buffers: HashMap::default(),
1430 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1431 selection_mark_mode: false,
1432 toggle_fold_multiple_buffers: Task::ready(()),
1433 text_style_refinement: None,
1434 };
1435 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1436 this._subscriptions.extend(project_subscriptions);
1437
1438 this.end_selection(window, cx);
1439 this.scroll_manager.show_scrollbar(window, cx);
1440
1441 if mode == EditorMode::Full {
1442 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1443 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1444
1445 if this.git_blame_inline_enabled {
1446 this.git_blame_inline_enabled = true;
1447 this.start_git_blame_inline(false, window, cx);
1448 }
1449
1450 if let Some(buffer) = buffer.read(cx).as_singleton() {
1451 if let Some(project) = this.project.as_ref() {
1452 let lsp_store = project.read(cx).lsp_store();
1453 let handle = lsp_store.update(cx, |lsp_store, cx| {
1454 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1455 });
1456 this.registered_buffers
1457 .insert(buffer.read(cx).remote_id(), handle);
1458 }
1459 }
1460 }
1461
1462 this.report_editor_event("Editor Opened", None, cx);
1463 this
1464 }
1465
1466 pub fn mouse_menu_is_focused(&self, window: &mut Window, cx: &mut App) -> bool {
1467 self.mouse_context_menu
1468 .as_ref()
1469 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1470 }
1471
1472 fn key_context(&self, window: &mut Window, cx: &mut Context<Self>) -> KeyContext {
1473 let mut key_context = KeyContext::new_with_defaults();
1474 key_context.add("Editor");
1475 let mode = match self.mode {
1476 EditorMode::SingleLine { .. } => "single_line",
1477 EditorMode::AutoHeight { .. } => "auto_height",
1478 EditorMode::Full => "full",
1479 };
1480
1481 if EditorSettings::jupyter_enabled(cx) {
1482 key_context.add("jupyter");
1483 }
1484
1485 key_context.set("mode", mode);
1486 if self.pending_rename.is_some() {
1487 key_context.add("renaming");
1488 }
1489 match self.context_menu.borrow().as_ref() {
1490 Some(CodeContextMenu::Completions(_)) => {
1491 key_context.add("menu");
1492 key_context.add("showing_completions");
1493 }
1494 Some(CodeContextMenu::CodeActions(_)) => {
1495 key_context.add("menu");
1496 key_context.add("showing_code_actions")
1497 }
1498 None => {}
1499 }
1500
1501 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1502 if !self.focus_handle(cx).contains_focused(window, cx)
1503 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1504 {
1505 for addon in self.addons.values() {
1506 addon.extend_key_context(&mut key_context, cx)
1507 }
1508 }
1509
1510 if let Some(extension) = self
1511 .buffer
1512 .read(cx)
1513 .as_singleton()
1514 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1515 {
1516 key_context.set("extension", extension.to_string());
1517 }
1518
1519 if self.has_active_inline_completion() {
1520 key_context.add("copilot_suggestion");
1521 key_context.add("inline_completion");
1522 }
1523
1524 if self.selection_mark_mode {
1525 key_context.add("selection_mode");
1526 }
1527
1528 key_context
1529 }
1530
1531 pub fn new_file(
1532 workspace: &mut Workspace,
1533 _: &workspace::NewFile,
1534 window: &mut Window,
1535 cx: &mut Context<Workspace>,
1536 ) {
1537 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1538 "Failed to create buffer",
1539 window,
1540 cx,
1541 |e, _, _| match e.error_code() {
1542 ErrorCode::RemoteUpgradeRequired => Some(format!(
1543 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1544 e.error_tag("required").unwrap_or("the latest version")
1545 )),
1546 _ => None,
1547 },
1548 );
1549 }
1550
1551 pub fn new_in_workspace(
1552 workspace: &mut Workspace,
1553 window: &mut Window,
1554 cx: &mut Context<Workspace>,
1555 ) -> Task<Result<Entity<Editor>>> {
1556 let project = workspace.project().clone();
1557 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1558
1559 cx.spawn_in(window, |workspace, mut cx| async move {
1560 let buffer = create.await?;
1561 workspace.update_in(&mut cx, |workspace, window, cx| {
1562 let editor =
1563 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1564 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1565 editor
1566 })
1567 })
1568 }
1569
1570 fn new_file_vertical(
1571 workspace: &mut Workspace,
1572 _: &workspace::NewFileSplitVertical,
1573 window: &mut Window,
1574 cx: &mut Context<Workspace>,
1575 ) {
1576 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1577 }
1578
1579 fn new_file_horizontal(
1580 workspace: &mut Workspace,
1581 _: &workspace::NewFileSplitHorizontal,
1582 window: &mut Window,
1583 cx: &mut Context<Workspace>,
1584 ) {
1585 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1586 }
1587
1588 fn new_file_in_direction(
1589 workspace: &mut Workspace,
1590 direction: SplitDirection,
1591 window: &mut Window,
1592 cx: &mut Context<Workspace>,
1593 ) {
1594 let project = workspace.project().clone();
1595 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1596
1597 cx.spawn_in(window, |workspace, mut cx| async move {
1598 let buffer = create.await?;
1599 workspace.update_in(&mut cx, move |workspace, window, cx| {
1600 workspace.split_item(
1601 direction,
1602 Box::new(
1603 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1604 ),
1605 window,
1606 cx,
1607 )
1608 })?;
1609 anyhow::Ok(())
1610 })
1611 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1612 match e.error_code() {
1613 ErrorCode::RemoteUpgradeRequired => Some(format!(
1614 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1615 e.error_tag("required").unwrap_or("the latest version")
1616 )),
1617 _ => None,
1618 }
1619 });
1620 }
1621
1622 pub fn leader_peer_id(&self) -> Option<PeerId> {
1623 self.leader_peer_id
1624 }
1625
1626 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1627 &self.buffer
1628 }
1629
1630 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1631 self.workspace.as_ref()?.0.upgrade()
1632 }
1633
1634 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1635 self.buffer().read(cx).title(cx)
1636 }
1637
1638 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1639 let git_blame_gutter_max_author_length = self
1640 .render_git_blame_gutter(cx)
1641 .then(|| {
1642 if let Some(blame) = self.blame.as_ref() {
1643 let max_author_length =
1644 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1645 Some(max_author_length)
1646 } else {
1647 None
1648 }
1649 })
1650 .flatten();
1651
1652 EditorSnapshot {
1653 mode: self.mode,
1654 show_gutter: self.show_gutter,
1655 show_line_numbers: self.show_line_numbers,
1656 show_git_diff_gutter: self.show_git_diff_gutter,
1657 show_code_actions: self.show_code_actions,
1658 show_runnables: self.show_runnables,
1659 git_blame_gutter_max_author_length,
1660 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1661 scroll_anchor: self.scroll_manager.anchor(),
1662 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1663 placeholder_text: self.placeholder_text.clone(),
1664 is_focused: self.focus_handle.is_focused(window),
1665 current_line_highlight: self
1666 .current_line_highlight
1667 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1668 gutter_hovered: self.gutter_hovered,
1669 }
1670 }
1671
1672 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1673 self.buffer.read(cx).language_at(point, cx)
1674 }
1675
1676 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1677 self.buffer.read(cx).read(cx).file_at(point).cloned()
1678 }
1679
1680 pub fn active_excerpt(
1681 &self,
1682 cx: &App,
1683 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1684 self.buffer
1685 .read(cx)
1686 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1687 }
1688
1689 pub fn mode(&self) -> EditorMode {
1690 self.mode
1691 }
1692
1693 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1694 self.collaboration_hub.as_deref()
1695 }
1696
1697 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1698 self.collaboration_hub = Some(hub);
1699 }
1700
1701 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1702 self.in_project_search = in_project_search;
1703 }
1704
1705 pub fn set_custom_context_menu(
1706 &mut self,
1707 f: impl 'static
1708 + Fn(
1709 &mut Self,
1710 DisplayPoint,
1711 &mut Window,
1712 &mut Context<Self>,
1713 ) -> Option<Entity<ui::ContextMenu>>,
1714 ) {
1715 self.custom_context_menu = Some(Box::new(f))
1716 }
1717
1718 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1719 self.completion_provider = provider;
1720 }
1721
1722 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1723 self.semantics_provider.clone()
1724 }
1725
1726 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1727 self.semantics_provider = provider;
1728 }
1729
1730 pub fn set_inline_completion_provider<T>(
1731 &mut self,
1732 provider: Option<Entity<T>>,
1733 window: &mut Window,
1734 cx: &mut Context<Self>,
1735 ) where
1736 T: InlineCompletionProvider,
1737 {
1738 self.inline_completion_provider =
1739 provider.map(|provider| RegisteredInlineCompletionProvider {
1740 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1741 if this.focus_handle.is_focused(window) {
1742 this.update_visible_inline_completion(window, cx);
1743 }
1744 }),
1745 provider: Arc::new(provider),
1746 });
1747 self.refresh_inline_completion(false, false, window, cx);
1748 }
1749
1750 pub fn placeholder_text(&self) -> Option<&str> {
1751 self.placeholder_text.as_deref()
1752 }
1753
1754 pub fn set_placeholder_text(
1755 &mut self,
1756 placeholder_text: impl Into<Arc<str>>,
1757 cx: &mut Context<Self>,
1758 ) {
1759 let placeholder_text = Some(placeholder_text.into());
1760 if self.placeholder_text != placeholder_text {
1761 self.placeholder_text = placeholder_text;
1762 cx.notify();
1763 }
1764 }
1765
1766 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1767 self.cursor_shape = cursor_shape;
1768
1769 // Disrupt blink for immediate user feedback that the cursor shape has changed
1770 self.blink_manager.update(cx, BlinkManager::show_cursor);
1771
1772 cx.notify();
1773 }
1774
1775 pub fn set_current_line_highlight(
1776 &mut self,
1777 current_line_highlight: Option<CurrentLineHighlight>,
1778 ) {
1779 self.current_line_highlight = current_line_highlight;
1780 }
1781
1782 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1783 self.collapse_matches = collapse_matches;
1784 }
1785
1786 pub fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1787 let buffers = self.buffer.read(cx).all_buffers();
1788 let Some(lsp_store) = self.lsp_store(cx) else {
1789 return;
1790 };
1791 lsp_store.update(cx, |lsp_store, cx| {
1792 for buffer in buffers {
1793 self.registered_buffers
1794 .entry(buffer.read(cx).remote_id())
1795 .or_insert_with(|| {
1796 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1797 });
1798 }
1799 })
1800 }
1801
1802 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1803 if self.collapse_matches {
1804 return range.start..range.start;
1805 }
1806 range.clone()
1807 }
1808
1809 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1810 if self.display_map.read(cx).clip_at_line_ends != clip {
1811 self.display_map
1812 .update(cx, |map, _| map.clip_at_line_ends = clip);
1813 }
1814 }
1815
1816 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1817 self.input_enabled = input_enabled;
1818 }
1819
1820 pub fn set_show_inline_completions_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
1821 self.show_inline_completions = enabled;
1822 if !self.show_inline_completions {
1823 self.take_active_inline_completion(cx);
1824 cx.notify();
1825 }
1826 }
1827
1828 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1829 self.menu_inline_completions_policy = value;
1830 }
1831
1832 pub fn set_autoindent(&mut self, autoindent: bool) {
1833 if autoindent {
1834 self.autoindent_mode = Some(AutoindentMode::EachLine);
1835 } else {
1836 self.autoindent_mode = None;
1837 }
1838 }
1839
1840 pub fn read_only(&self, cx: &App) -> bool {
1841 self.read_only || self.buffer.read(cx).read_only()
1842 }
1843
1844 pub fn set_read_only(&mut self, read_only: bool) {
1845 self.read_only = read_only;
1846 }
1847
1848 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1849 self.use_autoclose = autoclose;
1850 }
1851
1852 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1853 self.use_auto_surround = auto_surround;
1854 }
1855
1856 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1857 self.auto_replace_emoji_shortcode = auto_replace;
1858 }
1859
1860 pub fn toggle_inline_completions(
1861 &mut self,
1862 _: &ToggleInlineCompletions,
1863 window: &mut Window,
1864 cx: &mut Context<Self>,
1865 ) {
1866 if self.show_inline_completions_override.is_some() {
1867 self.set_show_inline_completions(None, window, cx);
1868 } else {
1869 let cursor = self.selections.newest_anchor().head();
1870 if let Some((buffer, cursor_buffer_position)) =
1871 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1872 {
1873 let show_inline_completions = !self.should_show_inline_completions_in_buffer(
1874 &buffer,
1875 cursor_buffer_position,
1876 cx,
1877 );
1878 self.set_show_inline_completions(Some(show_inline_completions), window, cx);
1879 }
1880 }
1881 }
1882
1883 pub fn set_show_inline_completions(
1884 &mut self,
1885 show_inline_completions: Option<bool>,
1886 window: &mut Window,
1887 cx: &mut Context<Self>,
1888 ) {
1889 self.show_inline_completions_override = show_inline_completions;
1890 self.refresh_inline_completion(false, true, window, cx);
1891 }
1892
1893 fn inline_completions_disabled_in_scope(
1894 &self,
1895 buffer: &Entity<Buffer>,
1896 buffer_position: language::Anchor,
1897 cx: &App,
1898 ) -> bool {
1899 let snapshot = buffer.read(cx).snapshot();
1900 let settings = snapshot.settings_at(buffer_position, cx);
1901
1902 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1903 return false;
1904 };
1905
1906 scope.override_name().map_or(false, |scope_name| {
1907 settings
1908 .inline_completions_disabled_in
1909 .iter()
1910 .any(|s| s == scope_name)
1911 })
1912 }
1913
1914 pub fn set_use_modal_editing(&mut self, to: bool) {
1915 self.use_modal_editing = to;
1916 }
1917
1918 pub fn use_modal_editing(&self) -> bool {
1919 self.use_modal_editing
1920 }
1921
1922 fn selections_did_change(
1923 &mut self,
1924 local: bool,
1925 old_cursor_position: &Anchor,
1926 show_completions: bool,
1927 window: &mut Window,
1928 cx: &mut Context<Self>,
1929 ) {
1930 window.invalidate_character_coordinates();
1931
1932 // Copy selections to primary selection buffer
1933 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1934 if local {
1935 let selections = self.selections.all::<usize>(cx);
1936 let buffer_handle = self.buffer.read(cx).read(cx);
1937
1938 let mut text = String::new();
1939 for (index, selection) in selections.iter().enumerate() {
1940 let text_for_selection = buffer_handle
1941 .text_for_range(selection.start..selection.end)
1942 .collect::<String>();
1943
1944 text.push_str(&text_for_selection);
1945 if index != selections.len() - 1 {
1946 text.push('\n');
1947 }
1948 }
1949
1950 if !text.is_empty() {
1951 cx.write_to_primary(ClipboardItem::new_string(text));
1952 }
1953 }
1954
1955 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
1956 self.buffer.update(cx, |buffer, cx| {
1957 buffer.set_active_selections(
1958 &self.selections.disjoint_anchors(),
1959 self.selections.line_mode,
1960 self.cursor_shape,
1961 cx,
1962 )
1963 });
1964 }
1965 let display_map = self
1966 .display_map
1967 .update(cx, |display_map, cx| display_map.snapshot(cx));
1968 let buffer = &display_map.buffer_snapshot;
1969 self.add_selections_state = None;
1970 self.select_next_state = None;
1971 self.select_prev_state = None;
1972 self.select_larger_syntax_node_stack.clear();
1973 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1974 self.snippet_stack
1975 .invalidate(&self.selections.disjoint_anchors(), buffer);
1976 self.take_rename(false, window, cx);
1977
1978 let new_cursor_position = self.selections.newest_anchor().head();
1979
1980 self.push_to_nav_history(
1981 *old_cursor_position,
1982 Some(new_cursor_position.to_point(buffer)),
1983 cx,
1984 );
1985
1986 if local {
1987 let new_cursor_position = self.selections.newest_anchor().head();
1988 let mut context_menu = self.context_menu.borrow_mut();
1989 let completion_menu = match context_menu.as_ref() {
1990 Some(CodeContextMenu::Completions(menu)) => Some(menu),
1991 _ => {
1992 *context_menu = None;
1993 None
1994 }
1995 };
1996
1997 if let Some(completion_menu) = completion_menu {
1998 let cursor_position = new_cursor_position.to_offset(buffer);
1999 let (word_range, kind) =
2000 buffer.surrounding_word(completion_menu.initial_position, true);
2001 if kind == Some(CharKind::Word)
2002 && word_range.to_inclusive().contains(&cursor_position)
2003 {
2004 let mut completion_menu = completion_menu.clone();
2005 drop(context_menu);
2006
2007 let query = Self::completion_query(buffer, cursor_position);
2008 cx.spawn(move |this, mut cx| async move {
2009 completion_menu
2010 .filter(query.as_deref(), cx.background_executor().clone())
2011 .await;
2012
2013 this.update(&mut cx, |this, cx| {
2014 let mut context_menu = this.context_menu.borrow_mut();
2015 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2016 else {
2017 return;
2018 };
2019
2020 if menu.id > completion_menu.id {
2021 return;
2022 }
2023
2024 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2025 drop(context_menu);
2026 cx.notify();
2027 })
2028 })
2029 .detach();
2030
2031 if show_completions {
2032 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2033 }
2034 } else {
2035 drop(context_menu);
2036 self.hide_context_menu(window, cx);
2037 }
2038 } else {
2039 drop(context_menu);
2040 }
2041
2042 hide_hover(self, cx);
2043
2044 if old_cursor_position.to_display_point(&display_map).row()
2045 != new_cursor_position.to_display_point(&display_map).row()
2046 {
2047 self.available_code_actions.take();
2048 }
2049 self.refresh_code_actions(window, cx);
2050 self.refresh_document_highlights(cx);
2051 refresh_matching_bracket_highlights(self, window, cx);
2052 self.update_visible_inline_completion(window, cx);
2053 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2054 if self.git_blame_inline_enabled {
2055 self.start_inline_blame_timer(window, cx);
2056 }
2057 }
2058
2059 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2060 cx.emit(EditorEvent::SelectionsChanged { local });
2061
2062 if self.selections.disjoint_anchors().len() == 1 {
2063 cx.emit(SearchEvent::ActiveMatchChanged)
2064 }
2065 cx.notify();
2066 }
2067
2068 pub fn change_selections<R>(
2069 &mut self,
2070 autoscroll: Option<Autoscroll>,
2071 window: &mut Window,
2072 cx: &mut Context<Self>,
2073 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2074 ) -> R {
2075 self.change_selections_inner(autoscroll, true, window, cx, change)
2076 }
2077
2078 pub fn change_selections_inner<R>(
2079 &mut self,
2080 autoscroll: Option<Autoscroll>,
2081 request_completions: bool,
2082 window: &mut Window,
2083 cx: &mut Context<Self>,
2084 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2085 ) -> R {
2086 let old_cursor_position = self.selections.newest_anchor().head();
2087 self.push_to_selection_history();
2088
2089 let (changed, result) = self.selections.change_with(cx, change);
2090
2091 if changed {
2092 if let Some(autoscroll) = autoscroll {
2093 self.request_autoscroll(autoscroll, cx);
2094 }
2095 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2096
2097 if self.should_open_signature_help_automatically(
2098 &old_cursor_position,
2099 self.signature_help_state.backspace_pressed(),
2100 cx,
2101 ) {
2102 self.show_signature_help(&ShowSignatureHelp, window, cx);
2103 }
2104 self.signature_help_state.set_backspace_pressed(false);
2105 }
2106
2107 result
2108 }
2109
2110 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2111 where
2112 I: IntoIterator<Item = (Range<S>, T)>,
2113 S: ToOffset,
2114 T: Into<Arc<str>>,
2115 {
2116 if self.read_only(cx) {
2117 return;
2118 }
2119
2120 self.buffer
2121 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2122 }
2123
2124 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2125 where
2126 I: IntoIterator<Item = (Range<S>, T)>,
2127 S: ToOffset,
2128 T: Into<Arc<str>>,
2129 {
2130 if self.read_only(cx) {
2131 return;
2132 }
2133
2134 self.buffer.update(cx, |buffer, cx| {
2135 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2136 });
2137 }
2138
2139 pub fn edit_with_block_indent<I, S, T>(
2140 &mut self,
2141 edits: I,
2142 original_indent_columns: Vec<u32>,
2143 cx: &mut Context<Self>,
2144 ) where
2145 I: IntoIterator<Item = (Range<S>, T)>,
2146 S: ToOffset,
2147 T: Into<Arc<str>>,
2148 {
2149 if self.read_only(cx) {
2150 return;
2151 }
2152
2153 self.buffer.update(cx, |buffer, cx| {
2154 buffer.edit(
2155 edits,
2156 Some(AutoindentMode::Block {
2157 original_indent_columns,
2158 }),
2159 cx,
2160 )
2161 });
2162 }
2163
2164 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2165 self.hide_context_menu(window, cx);
2166
2167 match phase {
2168 SelectPhase::Begin {
2169 position,
2170 add,
2171 click_count,
2172 } => self.begin_selection(position, add, click_count, window, cx),
2173 SelectPhase::BeginColumnar {
2174 position,
2175 goal_column,
2176 reset,
2177 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2178 SelectPhase::Extend {
2179 position,
2180 click_count,
2181 } => self.extend_selection(position, click_count, window, cx),
2182 SelectPhase::Update {
2183 position,
2184 goal_column,
2185 scroll_delta,
2186 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2187 SelectPhase::End => self.end_selection(window, cx),
2188 }
2189 }
2190
2191 fn extend_selection(
2192 &mut self,
2193 position: DisplayPoint,
2194 click_count: usize,
2195 window: &mut Window,
2196 cx: &mut Context<Self>,
2197 ) {
2198 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2199 let tail = self.selections.newest::<usize>(cx).tail();
2200 self.begin_selection(position, false, click_count, window, cx);
2201
2202 let position = position.to_offset(&display_map, Bias::Left);
2203 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2204
2205 let mut pending_selection = self
2206 .selections
2207 .pending_anchor()
2208 .expect("extend_selection not called with pending selection");
2209 if position >= tail {
2210 pending_selection.start = tail_anchor;
2211 } else {
2212 pending_selection.end = tail_anchor;
2213 pending_selection.reversed = true;
2214 }
2215
2216 let mut pending_mode = self.selections.pending_mode().unwrap();
2217 match &mut pending_mode {
2218 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2219 _ => {}
2220 }
2221
2222 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2223 s.set_pending(pending_selection, pending_mode)
2224 });
2225 }
2226
2227 fn begin_selection(
2228 &mut self,
2229 position: DisplayPoint,
2230 add: bool,
2231 click_count: usize,
2232 window: &mut Window,
2233 cx: &mut Context<Self>,
2234 ) {
2235 if !self.focus_handle.is_focused(window) {
2236 self.last_focused_descendant = None;
2237 window.focus(&self.focus_handle);
2238 }
2239
2240 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2241 let buffer = &display_map.buffer_snapshot;
2242 let newest_selection = self.selections.newest_anchor().clone();
2243 let position = display_map.clip_point(position, Bias::Left);
2244
2245 let start;
2246 let end;
2247 let mode;
2248 let mut auto_scroll;
2249 match click_count {
2250 1 => {
2251 start = buffer.anchor_before(position.to_point(&display_map));
2252 end = start;
2253 mode = SelectMode::Character;
2254 auto_scroll = true;
2255 }
2256 2 => {
2257 let range = movement::surrounding_word(&display_map, position);
2258 start = buffer.anchor_before(range.start.to_point(&display_map));
2259 end = buffer.anchor_before(range.end.to_point(&display_map));
2260 mode = SelectMode::Word(start..end);
2261 auto_scroll = true;
2262 }
2263 3 => {
2264 let position = display_map
2265 .clip_point(position, Bias::Left)
2266 .to_point(&display_map);
2267 let line_start = display_map.prev_line_boundary(position).0;
2268 let next_line_start = buffer.clip_point(
2269 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2270 Bias::Left,
2271 );
2272 start = buffer.anchor_before(line_start);
2273 end = buffer.anchor_before(next_line_start);
2274 mode = SelectMode::Line(start..end);
2275 auto_scroll = true;
2276 }
2277 _ => {
2278 start = buffer.anchor_before(0);
2279 end = buffer.anchor_before(buffer.len());
2280 mode = SelectMode::All;
2281 auto_scroll = false;
2282 }
2283 }
2284 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2285
2286 let point_to_delete: Option<usize> = {
2287 let selected_points: Vec<Selection<Point>> =
2288 self.selections.disjoint_in_range(start..end, cx);
2289
2290 if !add || click_count > 1 {
2291 None
2292 } else if !selected_points.is_empty() {
2293 Some(selected_points[0].id)
2294 } else {
2295 let clicked_point_already_selected =
2296 self.selections.disjoint.iter().find(|selection| {
2297 selection.start.to_point(buffer) == start.to_point(buffer)
2298 || selection.end.to_point(buffer) == end.to_point(buffer)
2299 });
2300
2301 clicked_point_already_selected.map(|selection| selection.id)
2302 }
2303 };
2304
2305 let selections_count = self.selections.count();
2306
2307 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2308 if let Some(point_to_delete) = point_to_delete {
2309 s.delete(point_to_delete);
2310
2311 if selections_count == 1 {
2312 s.set_pending_anchor_range(start..end, mode);
2313 }
2314 } else {
2315 if !add {
2316 s.clear_disjoint();
2317 } else if click_count > 1 {
2318 s.delete(newest_selection.id)
2319 }
2320
2321 s.set_pending_anchor_range(start..end, mode);
2322 }
2323 });
2324 }
2325
2326 fn begin_columnar_selection(
2327 &mut self,
2328 position: DisplayPoint,
2329 goal_column: u32,
2330 reset: bool,
2331 window: &mut Window,
2332 cx: &mut Context<Self>,
2333 ) {
2334 if !self.focus_handle.is_focused(window) {
2335 self.last_focused_descendant = None;
2336 window.focus(&self.focus_handle);
2337 }
2338
2339 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2340
2341 if reset {
2342 let pointer_position = display_map
2343 .buffer_snapshot
2344 .anchor_before(position.to_point(&display_map));
2345
2346 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2347 s.clear_disjoint();
2348 s.set_pending_anchor_range(
2349 pointer_position..pointer_position,
2350 SelectMode::Character,
2351 );
2352 });
2353 }
2354
2355 let tail = self.selections.newest::<Point>(cx).tail();
2356 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2357
2358 if !reset {
2359 self.select_columns(
2360 tail.to_display_point(&display_map),
2361 position,
2362 goal_column,
2363 &display_map,
2364 window,
2365 cx,
2366 );
2367 }
2368 }
2369
2370 fn update_selection(
2371 &mut self,
2372 position: DisplayPoint,
2373 goal_column: u32,
2374 scroll_delta: gpui::Point<f32>,
2375 window: &mut Window,
2376 cx: &mut Context<Self>,
2377 ) {
2378 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2379
2380 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2381 let tail = tail.to_display_point(&display_map);
2382 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2383 } else if let Some(mut pending) = self.selections.pending_anchor() {
2384 let buffer = self.buffer.read(cx).snapshot(cx);
2385 let head;
2386 let tail;
2387 let mode = self.selections.pending_mode().unwrap();
2388 match &mode {
2389 SelectMode::Character => {
2390 head = position.to_point(&display_map);
2391 tail = pending.tail().to_point(&buffer);
2392 }
2393 SelectMode::Word(original_range) => {
2394 let original_display_range = original_range.start.to_display_point(&display_map)
2395 ..original_range.end.to_display_point(&display_map);
2396 let original_buffer_range = original_display_range.start.to_point(&display_map)
2397 ..original_display_range.end.to_point(&display_map);
2398 if movement::is_inside_word(&display_map, position)
2399 || original_display_range.contains(&position)
2400 {
2401 let word_range = movement::surrounding_word(&display_map, position);
2402 if word_range.start < original_display_range.start {
2403 head = word_range.start.to_point(&display_map);
2404 } else {
2405 head = word_range.end.to_point(&display_map);
2406 }
2407 } else {
2408 head = position.to_point(&display_map);
2409 }
2410
2411 if head <= original_buffer_range.start {
2412 tail = original_buffer_range.end;
2413 } else {
2414 tail = original_buffer_range.start;
2415 }
2416 }
2417 SelectMode::Line(original_range) => {
2418 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2419
2420 let position = display_map
2421 .clip_point(position, Bias::Left)
2422 .to_point(&display_map);
2423 let line_start = display_map.prev_line_boundary(position).0;
2424 let next_line_start = buffer.clip_point(
2425 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2426 Bias::Left,
2427 );
2428
2429 if line_start < original_range.start {
2430 head = line_start
2431 } else {
2432 head = next_line_start
2433 }
2434
2435 if head <= original_range.start {
2436 tail = original_range.end;
2437 } else {
2438 tail = original_range.start;
2439 }
2440 }
2441 SelectMode::All => {
2442 return;
2443 }
2444 };
2445
2446 if head < tail {
2447 pending.start = buffer.anchor_before(head);
2448 pending.end = buffer.anchor_before(tail);
2449 pending.reversed = true;
2450 } else {
2451 pending.start = buffer.anchor_before(tail);
2452 pending.end = buffer.anchor_before(head);
2453 pending.reversed = false;
2454 }
2455
2456 self.change_selections(None, window, cx, |s| {
2457 s.set_pending(pending, mode);
2458 });
2459 } else {
2460 log::error!("update_selection dispatched with no pending selection");
2461 return;
2462 }
2463
2464 self.apply_scroll_delta(scroll_delta, window, cx);
2465 cx.notify();
2466 }
2467
2468 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2469 self.columnar_selection_tail.take();
2470 if self.selections.pending_anchor().is_some() {
2471 let selections = self.selections.all::<usize>(cx);
2472 self.change_selections(None, window, cx, |s| {
2473 s.select(selections);
2474 s.clear_pending();
2475 });
2476 }
2477 }
2478
2479 fn select_columns(
2480 &mut self,
2481 tail: DisplayPoint,
2482 head: DisplayPoint,
2483 goal_column: u32,
2484 display_map: &DisplaySnapshot,
2485 window: &mut Window,
2486 cx: &mut Context<Self>,
2487 ) {
2488 let start_row = cmp::min(tail.row(), head.row());
2489 let end_row = cmp::max(tail.row(), head.row());
2490 let start_column = cmp::min(tail.column(), goal_column);
2491 let end_column = cmp::max(tail.column(), goal_column);
2492 let reversed = start_column < tail.column();
2493
2494 let selection_ranges = (start_row.0..=end_row.0)
2495 .map(DisplayRow)
2496 .filter_map(|row| {
2497 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2498 let start = display_map
2499 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2500 .to_point(display_map);
2501 let end = display_map
2502 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2503 .to_point(display_map);
2504 if reversed {
2505 Some(end..start)
2506 } else {
2507 Some(start..end)
2508 }
2509 } else {
2510 None
2511 }
2512 })
2513 .collect::<Vec<_>>();
2514
2515 self.change_selections(None, window, cx, |s| {
2516 s.select_ranges(selection_ranges);
2517 });
2518 cx.notify();
2519 }
2520
2521 pub fn has_pending_nonempty_selection(&self) -> bool {
2522 let pending_nonempty_selection = match self.selections.pending_anchor() {
2523 Some(Selection { start, end, .. }) => start != end,
2524 None => false,
2525 };
2526
2527 pending_nonempty_selection
2528 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2529 }
2530
2531 pub fn has_pending_selection(&self) -> bool {
2532 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2533 }
2534
2535 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2536 self.selection_mark_mode = false;
2537
2538 if self.clear_expanded_diff_hunks(cx) {
2539 cx.notify();
2540 return;
2541 }
2542 if self.dismiss_menus_and_popups(true, window, cx) {
2543 return;
2544 }
2545
2546 if self.mode == EditorMode::Full
2547 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2548 {
2549 return;
2550 }
2551
2552 cx.propagate();
2553 }
2554
2555 pub fn dismiss_menus_and_popups(
2556 &mut self,
2557 should_report_inline_completion_event: bool,
2558 window: &mut Window,
2559 cx: &mut Context<Self>,
2560 ) -> bool {
2561 if self.take_rename(false, window, cx).is_some() {
2562 return true;
2563 }
2564
2565 if hide_hover(self, cx) {
2566 return true;
2567 }
2568
2569 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2570 return true;
2571 }
2572
2573 if self.hide_context_menu(window, cx).is_some() {
2574 return true;
2575 }
2576
2577 if self.mouse_context_menu.take().is_some() {
2578 return true;
2579 }
2580
2581 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2582 return true;
2583 }
2584
2585 if self.snippet_stack.pop().is_some() {
2586 return true;
2587 }
2588
2589 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2590 self.dismiss_diagnostics(cx);
2591 return true;
2592 }
2593
2594 false
2595 }
2596
2597 fn linked_editing_ranges_for(
2598 &self,
2599 selection: Range<text::Anchor>,
2600 cx: &App,
2601 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2602 if self.linked_edit_ranges.is_empty() {
2603 return None;
2604 }
2605 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2606 selection.end.buffer_id.and_then(|end_buffer_id| {
2607 if selection.start.buffer_id != Some(end_buffer_id) {
2608 return None;
2609 }
2610 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2611 let snapshot = buffer.read(cx).snapshot();
2612 self.linked_edit_ranges
2613 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2614 .map(|ranges| (ranges, snapshot, buffer))
2615 })?;
2616 use text::ToOffset as TO;
2617 // find offset from the start of current range to current cursor position
2618 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2619
2620 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2621 let start_difference = start_offset - start_byte_offset;
2622 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2623 let end_difference = end_offset - start_byte_offset;
2624 // Current range has associated linked ranges.
2625 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2626 for range in linked_ranges.iter() {
2627 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2628 let end_offset = start_offset + end_difference;
2629 let start_offset = start_offset + start_difference;
2630 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2631 continue;
2632 }
2633 if self.selections.disjoint_anchor_ranges().any(|s| {
2634 if s.start.buffer_id != selection.start.buffer_id
2635 || s.end.buffer_id != selection.end.buffer_id
2636 {
2637 return false;
2638 }
2639 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2640 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2641 }) {
2642 continue;
2643 }
2644 let start = buffer_snapshot.anchor_after(start_offset);
2645 let end = buffer_snapshot.anchor_after(end_offset);
2646 linked_edits
2647 .entry(buffer.clone())
2648 .or_default()
2649 .push(start..end);
2650 }
2651 Some(linked_edits)
2652 }
2653
2654 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2655 let text: Arc<str> = text.into();
2656
2657 if self.read_only(cx) {
2658 return;
2659 }
2660
2661 let selections = self.selections.all_adjusted(cx);
2662 let mut bracket_inserted = false;
2663 let mut edits = Vec::new();
2664 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2665 let mut new_selections = Vec::with_capacity(selections.len());
2666 let mut new_autoclose_regions = Vec::new();
2667 let snapshot = self.buffer.read(cx).read(cx);
2668
2669 for (selection, autoclose_region) in
2670 self.selections_with_autoclose_regions(selections, &snapshot)
2671 {
2672 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2673 // Determine if the inserted text matches the opening or closing
2674 // bracket of any of this language's bracket pairs.
2675 let mut bracket_pair = None;
2676 let mut is_bracket_pair_start = false;
2677 let mut is_bracket_pair_end = false;
2678 if !text.is_empty() {
2679 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2680 // and they are removing the character that triggered IME popup.
2681 for (pair, enabled) in scope.brackets() {
2682 if !pair.close && !pair.surround {
2683 continue;
2684 }
2685
2686 if enabled && pair.start.ends_with(text.as_ref()) {
2687 let prefix_len = pair.start.len() - text.len();
2688 let preceding_text_matches_prefix = prefix_len == 0
2689 || (selection.start.column >= (prefix_len as u32)
2690 && snapshot.contains_str_at(
2691 Point::new(
2692 selection.start.row,
2693 selection.start.column - (prefix_len as u32),
2694 ),
2695 &pair.start[..prefix_len],
2696 ));
2697 if preceding_text_matches_prefix {
2698 bracket_pair = Some(pair.clone());
2699 is_bracket_pair_start = true;
2700 break;
2701 }
2702 }
2703 if pair.end.as_str() == text.as_ref() {
2704 bracket_pair = Some(pair.clone());
2705 is_bracket_pair_end = true;
2706 break;
2707 }
2708 }
2709 }
2710
2711 if let Some(bracket_pair) = bracket_pair {
2712 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2713 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2714 let auto_surround =
2715 self.use_auto_surround && snapshot_settings.use_auto_surround;
2716 if selection.is_empty() {
2717 if is_bracket_pair_start {
2718 // If the inserted text is a suffix of an opening bracket and the
2719 // selection is preceded by the rest of the opening bracket, then
2720 // insert the closing bracket.
2721 let following_text_allows_autoclose = snapshot
2722 .chars_at(selection.start)
2723 .next()
2724 .map_or(true, |c| scope.should_autoclose_before(c));
2725
2726 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2727 && bracket_pair.start.len() == 1
2728 {
2729 let target = bracket_pair.start.chars().next().unwrap();
2730 let current_line_count = snapshot
2731 .reversed_chars_at(selection.start)
2732 .take_while(|&c| c != '\n')
2733 .filter(|&c| c == target)
2734 .count();
2735 current_line_count % 2 == 1
2736 } else {
2737 false
2738 };
2739
2740 if autoclose
2741 && bracket_pair.close
2742 && following_text_allows_autoclose
2743 && !is_closing_quote
2744 {
2745 let anchor = snapshot.anchor_before(selection.end);
2746 new_selections.push((selection.map(|_| anchor), text.len()));
2747 new_autoclose_regions.push((
2748 anchor,
2749 text.len(),
2750 selection.id,
2751 bracket_pair.clone(),
2752 ));
2753 edits.push((
2754 selection.range(),
2755 format!("{}{}", text, bracket_pair.end).into(),
2756 ));
2757 bracket_inserted = true;
2758 continue;
2759 }
2760 }
2761
2762 if let Some(region) = autoclose_region {
2763 // If the selection is followed by an auto-inserted closing bracket,
2764 // then don't insert that closing bracket again; just move the selection
2765 // past the closing bracket.
2766 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2767 && text.as_ref() == region.pair.end.as_str();
2768 if should_skip {
2769 let anchor = snapshot.anchor_after(selection.end);
2770 new_selections
2771 .push((selection.map(|_| anchor), region.pair.end.len()));
2772 continue;
2773 }
2774 }
2775
2776 let always_treat_brackets_as_autoclosed = snapshot
2777 .settings_at(selection.start, cx)
2778 .always_treat_brackets_as_autoclosed;
2779 if always_treat_brackets_as_autoclosed
2780 && is_bracket_pair_end
2781 && snapshot.contains_str_at(selection.end, text.as_ref())
2782 {
2783 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2784 // and the inserted text is a closing bracket and the selection is followed
2785 // by the closing bracket then move the selection past the closing bracket.
2786 let anchor = snapshot.anchor_after(selection.end);
2787 new_selections.push((selection.map(|_| anchor), text.len()));
2788 continue;
2789 }
2790 }
2791 // If an opening bracket is 1 character long and is typed while
2792 // text is selected, then surround that text with the bracket pair.
2793 else if auto_surround
2794 && bracket_pair.surround
2795 && is_bracket_pair_start
2796 && bracket_pair.start.chars().count() == 1
2797 {
2798 edits.push((selection.start..selection.start, text.clone()));
2799 edits.push((
2800 selection.end..selection.end,
2801 bracket_pair.end.as_str().into(),
2802 ));
2803 bracket_inserted = true;
2804 new_selections.push((
2805 Selection {
2806 id: selection.id,
2807 start: snapshot.anchor_after(selection.start),
2808 end: snapshot.anchor_before(selection.end),
2809 reversed: selection.reversed,
2810 goal: selection.goal,
2811 },
2812 0,
2813 ));
2814 continue;
2815 }
2816 }
2817 }
2818
2819 if self.auto_replace_emoji_shortcode
2820 && selection.is_empty()
2821 && text.as_ref().ends_with(':')
2822 {
2823 if let Some(possible_emoji_short_code) =
2824 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2825 {
2826 if !possible_emoji_short_code.is_empty() {
2827 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2828 let emoji_shortcode_start = Point::new(
2829 selection.start.row,
2830 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2831 );
2832
2833 // Remove shortcode from buffer
2834 edits.push((
2835 emoji_shortcode_start..selection.start,
2836 "".to_string().into(),
2837 ));
2838 new_selections.push((
2839 Selection {
2840 id: selection.id,
2841 start: snapshot.anchor_after(emoji_shortcode_start),
2842 end: snapshot.anchor_before(selection.start),
2843 reversed: selection.reversed,
2844 goal: selection.goal,
2845 },
2846 0,
2847 ));
2848
2849 // Insert emoji
2850 let selection_start_anchor = snapshot.anchor_after(selection.start);
2851 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2852 edits.push((selection.start..selection.end, emoji.to_string().into()));
2853
2854 continue;
2855 }
2856 }
2857 }
2858 }
2859
2860 // If not handling any auto-close operation, then just replace the selected
2861 // text with the given input and move the selection to the end of the
2862 // newly inserted text.
2863 let anchor = snapshot.anchor_after(selection.end);
2864 if !self.linked_edit_ranges.is_empty() {
2865 let start_anchor = snapshot.anchor_before(selection.start);
2866
2867 let is_word_char = text.chars().next().map_or(true, |char| {
2868 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2869 classifier.is_word(char)
2870 });
2871
2872 if is_word_char {
2873 if let Some(ranges) = self
2874 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2875 {
2876 for (buffer, edits) in ranges {
2877 linked_edits
2878 .entry(buffer.clone())
2879 .or_default()
2880 .extend(edits.into_iter().map(|range| (range, text.clone())));
2881 }
2882 }
2883 }
2884 }
2885
2886 new_selections.push((selection.map(|_| anchor), 0));
2887 edits.push((selection.start..selection.end, text.clone()));
2888 }
2889
2890 drop(snapshot);
2891
2892 self.transact(window, cx, |this, window, cx| {
2893 this.buffer.update(cx, |buffer, cx| {
2894 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2895 });
2896 for (buffer, edits) in linked_edits {
2897 buffer.update(cx, |buffer, cx| {
2898 let snapshot = buffer.snapshot();
2899 let edits = edits
2900 .into_iter()
2901 .map(|(range, text)| {
2902 use text::ToPoint as TP;
2903 let end_point = TP::to_point(&range.end, &snapshot);
2904 let start_point = TP::to_point(&range.start, &snapshot);
2905 (start_point..end_point, text)
2906 })
2907 .sorted_by_key(|(range, _)| range.start)
2908 .collect::<Vec<_>>();
2909 buffer.edit(edits, None, cx);
2910 })
2911 }
2912 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2913 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2914 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2915 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2916 .zip(new_selection_deltas)
2917 .map(|(selection, delta)| Selection {
2918 id: selection.id,
2919 start: selection.start + delta,
2920 end: selection.end + delta,
2921 reversed: selection.reversed,
2922 goal: SelectionGoal::None,
2923 })
2924 .collect::<Vec<_>>();
2925
2926 let mut i = 0;
2927 for (position, delta, selection_id, pair) in new_autoclose_regions {
2928 let position = position.to_offset(&map.buffer_snapshot) + delta;
2929 let start = map.buffer_snapshot.anchor_before(position);
2930 let end = map.buffer_snapshot.anchor_after(position);
2931 while let Some(existing_state) = this.autoclose_regions.get(i) {
2932 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2933 Ordering::Less => i += 1,
2934 Ordering::Greater => break,
2935 Ordering::Equal => {
2936 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2937 Ordering::Less => i += 1,
2938 Ordering::Equal => break,
2939 Ordering::Greater => break,
2940 }
2941 }
2942 }
2943 }
2944 this.autoclose_regions.insert(
2945 i,
2946 AutocloseRegion {
2947 selection_id,
2948 range: start..end,
2949 pair,
2950 },
2951 );
2952 }
2953
2954 let had_active_inline_completion = this.has_active_inline_completion();
2955 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
2956 s.select(new_selections)
2957 });
2958
2959 if !bracket_inserted {
2960 if let Some(on_type_format_task) =
2961 this.trigger_on_type_formatting(text.to_string(), window, cx)
2962 {
2963 on_type_format_task.detach_and_log_err(cx);
2964 }
2965 }
2966
2967 let editor_settings = EditorSettings::get_global(cx);
2968 if bracket_inserted
2969 && (editor_settings.auto_signature_help
2970 || editor_settings.show_signature_help_after_edits)
2971 {
2972 this.show_signature_help(&ShowSignatureHelp, window, cx);
2973 }
2974
2975 let trigger_in_words =
2976 this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
2977 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
2978 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
2979 this.refresh_inline_completion(true, false, window, cx);
2980 });
2981 }
2982
2983 fn find_possible_emoji_shortcode_at_position(
2984 snapshot: &MultiBufferSnapshot,
2985 position: Point,
2986 ) -> Option<String> {
2987 let mut chars = Vec::new();
2988 let mut found_colon = false;
2989 for char in snapshot.reversed_chars_at(position).take(100) {
2990 // Found a possible emoji shortcode in the middle of the buffer
2991 if found_colon {
2992 if char.is_whitespace() {
2993 chars.reverse();
2994 return Some(chars.iter().collect());
2995 }
2996 // If the previous character is not a whitespace, we are in the middle of a word
2997 // and we only want to complete the shortcode if the word is made up of other emojis
2998 let mut containing_word = String::new();
2999 for ch in snapshot
3000 .reversed_chars_at(position)
3001 .skip(chars.len() + 1)
3002 .take(100)
3003 {
3004 if ch.is_whitespace() {
3005 break;
3006 }
3007 containing_word.push(ch);
3008 }
3009 let containing_word = containing_word.chars().rev().collect::<String>();
3010 if util::word_consists_of_emojis(containing_word.as_str()) {
3011 chars.reverse();
3012 return Some(chars.iter().collect());
3013 }
3014 }
3015
3016 if char.is_whitespace() || !char.is_ascii() {
3017 return None;
3018 }
3019 if char == ':' {
3020 found_colon = true;
3021 } else {
3022 chars.push(char);
3023 }
3024 }
3025 // Found a possible emoji shortcode at the beginning of the buffer
3026 chars.reverse();
3027 Some(chars.iter().collect())
3028 }
3029
3030 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3031 self.transact(window, cx, |this, window, cx| {
3032 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3033 let selections = this.selections.all::<usize>(cx);
3034 let multi_buffer = this.buffer.read(cx);
3035 let buffer = multi_buffer.snapshot(cx);
3036 selections
3037 .iter()
3038 .map(|selection| {
3039 let start_point = selection.start.to_point(&buffer);
3040 let mut indent =
3041 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3042 indent.len = cmp::min(indent.len, start_point.column);
3043 let start = selection.start;
3044 let end = selection.end;
3045 let selection_is_empty = start == end;
3046 let language_scope = buffer.language_scope_at(start);
3047 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3048 &language_scope
3049 {
3050 let leading_whitespace_len = buffer
3051 .reversed_chars_at(start)
3052 .take_while(|c| c.is_whitespace() && *c != '\n')
3053 .map(|c| c.len_utf8())
3054 .sum::<usize>();
3055
3056 let trailing_whitespace_len = buffer
3057 .chars_at(end)
3058 .take_while(|c| c.is_whitespace() && *c != '\n')
3059 .map(|c| c.len_utf8())
3060 .sum::<usize>();
3061
3062 let insert_extra_newline =
3063 language.brackets().any(|(pair, enabled)| {
3064 let pair_start = pair.start.trim_end();
3065 let pair_end = pair.end.trim_start();
3066
3067 enabled
3068 && pair.newline
3069 && buffer.contains_str_at(
3070 end + trailing_whitespace_len,
3071 pair_end,
3072 )
3073 && buffer.contains_str_at(
3074 (start - leading_whitespace_len)
3075 .saturating_sub(pair_start.len()),
3076 pair_start,
3077 )
3078 });
3079
3080 // Comment extension on newline is allowed only for cursor selections
3081 let comment_delimiter = maybe!({
3082 if !selection_is_empty {
3083 return None;
3084 }
3085
3086 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3087 return None;
3088 }
3089
3090 let delimiters = language.line_comment_prefixes();
3091 let max_len_of_delimiter =
3092 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3093 let (snapshot, range) =
3094 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3095
3096 let mut index_of_first_non_whitespace = 0;
3097 let comment_candidate = snapshot
3098 .chars_for_range(range)
3099 .skip_while(|c| {
3100 let should_skip = c.is_whitespace();
3101 if should_skip {
3102 index_of_first_non_whitespace += 1;
3103 }
3104 should_skip
3105 })
3106 .take(max_len_of_delimiter)
3107 .collect::<String>();
3108 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3109 comment_candidate.starts_with(comment_prefix.as_ref())
3110 })?;
3111 let cursor_is_placed_after_comment_marker =
3112 index_of_first_non_whitespace + comment_prefix.len()
3113 <= start_point.column as usize;
3114 if cursor_is_placed_after_comment_marker {
3115 Some(comment_prefix.clone())
3116 } else {
3117 None
3118 }
3119 });
3120 (comment_delimiter, insert_extra_newline)
3121 } else {
3122 (None, false)
3123 };
3124
3125 let capacity_for_delimiter = comment_delimiter
3126 .as_deref()
3127 .map(str::len)
3128 .unwrap_or_default();
3129 let mut new_text =
3130 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3131 new_text.push('\n');
3132 new_text.extend(indent.chars());
3133 if let Some(delimiter) = &comment_delimiter {
3134 new_text.push_str(delimiter);
3135 }
3136 if insert_extra_newline {
3137 new_text = new_text.repeat(2);
3138 }
3139
3140 let anchor = buffer.anchor_after(end);
3141 let new_selection = selection.map(|_| anchor);
3142 (
3143 (start..end, new_text),
3144 (insert_extra_newline, new_selection),
3145 )
3146 })
3147 .unzip()
3148 };
3149
3150 this.edit_with_autoindent(edits, cx);
3151 let buffer = this.buffer.read(cx).snapshot(cx);
3152 let new_selections = selection_fixup_info
3153 .into_iter()
3154 .map(|(extra_newline_inserted, new_selection)| {
3155 let mut cursor = new_selection.end.to_point(&buffer);
3156 if extra_newline_inserted {
3157 cursor.row -= 1;
3158 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3159 }
3160 new_selection.map(|_| cursor)
3161 })
3162 .collect();
3163
3164 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3165 s.select(new_selections)
3166 });
3167 this.refresh_inline_completion(true, false, window, cx);
3168 });
3169 }
3170
3171 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3172 let buffer = self.buffer.read(cx);
3173 let snapshot = buffer.snapshot(cx);
3174
3175 let mut edits = Vec::new();
3176 let mut rows = Vec::new();
3177
3178 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3179 let cursor = selection.head();
3180 let row = cursor.row;
3181
3182 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3183
3184 let newline = "\n".to_string();
3185 edits.push((start_of_line..start_of_line, newline));
3186
3187 rows.push(row + rows_inserted as u32);
3188 }
3189
3190 self.transact(window, cx, |editor, window, cx| {
3191 editor.edit(edits, cx);
3192
3193 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3194 let mut index = 0;
3195 s.move_cursors_with(|map, _, _| {
3196 let row = rows[index];
3197 index += 1;
3198
3199 let point = Point::new(row, 0);
3200 let boundary = map.next_line_boundary(point).1;
3201 let clipped = map.clip_point(boundary, Bias::Left);
3202
3203 (clipped, SelectionGoal::None)
3204 });
3205 });
3206
3207 let mut indent_edits = Vec::new();
3208 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3209 for row in rows {
3210 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3211 for (row, indent) in indents {
3212 if indent.len == 0 {
3213 continue;
3214 }
3215
3216 let text = match indent.kind {
3217 IndentKind::Space => " ".repeat(indent.len as usize),
3218 IndentKind::Tab => "\t".repeat(indent.len as usize),
3219 };
3220 let point = Point::new(row.0, 0);
3221 indent_edits.push((point..point, text));
3222 }
3223 }
3224 editor.edit(indent_edits, cx);
3225 });
3226 }
3227
3228 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3229 let buffer = self.buffer.read(cx);
3230 let snapshot = buffer.snapshot(cx);
3231
3232 let mut edits = Vec::new();
3233 let mut rows = Vec::new();
3234 let mut rows_inserted = 0;
3235
3236 for selection in self.selections.all_adjusted(cx) {
3237 let cursor = selection.head();
3238 let row = cursor.row;
3239
3240 let point = Point::new(row + 1, 0);
3241 let start_of_line = snapshot.clip_point(point, Bias::Left);
3242
3243 let newline = "\n".to_string();
3244 edits.push((start_of_line..start_of_line, newline));
3245
3246 rows_inserted += 1;
3247 rows.push(row + rows_inserted);
3248 }
3249
3250 self.transact(window, cx, |editor, window, cx| {
3251 editor.edit(edits, cx);
3252
3253 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3254 let mut index = 0;
3255 s.move_cursors_with(|map, _, _| {
3256 let row = rows[index];
3257 index += 1;
3258
3259 let point = Point::new(row, 0);
3260 let boundary = map.next_line_boundary(point).1;
3261 let clipped = map.clip_point(boundary, Bias::Left);
3262
3263 (clipped, SelectionGoal::None)
3264 });
3265 });
3266
3267 let mut indent_edits = Vec::new();
3268 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3269 for row in rows {
3270 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3271 for (row, indent) in indents {
3272 if indent.len == 0 {
3273 continue;
3274 }
3275
3276 let text = match indent.kind {
3277 IndentKind::Space => " ".repeat(indent.len as usize),
3278 IndentKind::Tab => "\t".repeat(indent.len as usize),
3279 };
3280 let point = Point::new(row.0, 0);
3281 indent_edits.push((point..point, text));
3282 }
3283 }
3284 editor.edit(indent_edits, cx);
3285 });
3286 }
3287
3288 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3289 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3290 original_indent_columns: Vec::new(),
3291 });
3292 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3293 }
3294
3295 fn insert_with_autoindent_mode(
3296 &mut self,
3297 text: &str,
3298 autoindent_mode: Option<AutoindentMode>,
3299 window: &mut Window,
3300 cx: &mut Context<Self>,
3301 ) {
3302 if self.read_only(cx) {
3303 return;
3304 }
3305
3306 let text: Arc<str> = text.into();
3307 self.transact(window, cx, |this, window, cx| {
3308 let old_selections = this.selections.all_adjusted(cx);
3309 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3310 let anchors = {
3311 let snapshot = buffer.read(cx);
3312 old_selections
3313 .iter()
3314 .map(|s| {
3315 let anchor = snapshot.anchor_after(s.head());
3316 s.map(|_| anchor)
3317 })
3318 .collect::<Vec<_>>()
3319 };
3320 buffer.edit(
3321 old_selections
3322 .iter()
3323 .map(|s| (s.start..s.end, text.clone())),
3324 autoindent_mode,
3325 cx,
3326 );
3327 anchors
3328 });
3329
3330 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3331 s.select_anchors(selection_anchors);
3332 });
3333
3334 cx.notify();
3335 });
3336 }
3337
3338 fn trigger_completion_on_input(
3339 &mut self,
3340 text: &str,
3341 trigger_in_words: bool,
3342 window: &mut Window,
3343 cx: &mut Context<Self>,
3344 ) {
3345 if self.is_completion_trigger(text, trigger_in_words, cx) {
3346 self.show_completions(
3347 &ShowCompletions {
3348 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3349 },
3350 window,
3351 cx,
3352 );
3353 } else {
3354 self.hide_context_menu(window, cx);
3355 }
3356 }
3357
3358 fn is_completion_trigger(
3359 &self,
3360 text: &str,
3361 trigger_in_words: bool,
3362 cx: &mut Context<Self>,
3363 ) -> bool {
3364 let position = self.selections.newest_anchor().head();
3365 let multibuffer = self.buffer.read(cx);
3366 let Some(buffer) = position
3367 .buffer_id
3368 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3369 else {
3370 return false;
3371 };
3372
3373 if let Some(completion_provider) = &self.completion_provider {
3374 completion_provider.is_completion_trigger(
3375 &buffer,
3376 position.text_anchor,
3377 text,
3378 trigger_in_words,
3379 cx,
3380 )
3381 } else {
3382 false
3383 }
3384 }
3385
3386 /// If any empty selections is touching the start of its innermost containing autoclose
3387 /// region, expand it to select the brackets.
3388 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3389 let selections = self.selections.all::<usize>(cx);
3390 let buffer = self.buffer.read(cx).read(cx);
3391 let new_selections = self
3392 .selections_with_autoclose_regions(selections, &buffer)
3393 .map(|(mut selection, region)| {
3394 if !selection.is_empty() {
3395 return selection;
3396 }
3397
3398 if let Some(region) = region {
3399 let mut range = region.range.to_offset(&buffer);
3400 if selection.start == range.start && range.start >= region.pair.start.len() {
3401 range.start -= region.pair.start.len();
3402 if buffer.contains_str_at(range.start, ®ion.pair.start)
3403 && buffer.contains_str_at(range.end, ®ion.pair.end)
3404 {
3405 range.end += region.pair.end.len();
3406 selection.start = range.start;
3407 selection.end = range.end;
3408
3409 return selection;
3410 }
3411 }
3412 }
3413
3414 let always_treat_brackets_as_autoclosed = buffer
3415 .settings_at(selection.start, cx)
3416 .always_treat_brackets_as_autoclosed;
3417
3418 if !always_treat_brackets_as_autoclosed {
3419 return selection;
3420 }
3421
3422 if let Some(scope) = buffer.language_scope_at(selection.start) {
3423 for (pair, enabled) in scope.brackets() {
3424 if !enabled || !pair.close {
3425 continue;
3426 }
3427
3428 if buffer.contains_str_at(selection.start, &pair.end) {
3429 let pair_start_len = pair.start.len();
3430 if buffer.contains_str_at(
3431 selection.start.saturating_sub(pair_start_len),
3432 &pair.start,
3433 ) {
3434 selection.start -= pair_start_len;
3435 selection.end += pair.end.len();
3436
3437 return selection;
3438 }
3439 }
3440 }
3441 }
3442
3443 selection
3444 })
3445 .collect();
3446
3447 drop(buffer);
3448 self.change_selections(None, window, cx, |selections| {
3449 selections.select(new_selections)
3450 });
3451 }
3452
3453 /// Iterate the given selections, and for each one, find the smallest surrounding
3454 /// autoclose region. This uses the ordering of the selections and the autoclose
3455 /// regions to avoid repeated comparisons.
3456 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3457 &'a self,
3458 selections: impl IntoIterator<Item = Selection<D>>,
3459 buffer: &'a MultiBufferSnapshot,
3460 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3461 let mut i = 0;
3462 let mut regions = self.autoclose_regions.as_slice();
3463 selections.into_iter().map(move |selection| {
3464 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3465
3466 let mut enclosing = None;
3467 while let Some(pair_state) = regions.get(i) {
3468 if pair_state.range.end.to_offset(buffer) < range.start {
3469 regions = ®ions[i + 1..];
3470 i = 0;
3471 } else if pair_state.range.start.to_offset(buffer) > range.end {
3472 break;
3473 } else {
3474 if pair_state.selection_id == selection.id {
3475 enclosing = Some(pair_state);
3476 }
3477 i += 1;
3478 }
3479 }
3480
3481 (selection, enclosing)
3482 })
3483 }
3484
3485 /// Remove any autoclose regions that no longer contain their selection.
3486 fn invalidate_autoclose_regions(
3487 &mut self,
3488 mut selections: &[Selection<Anchor>],
3489 buffer: &MultiBufferSnapshot,
3490 ) {
3491 self.autoclose_regions.retain(|state| {
3492 let mut i = 0;
3493 while let Some(selection) = selections.get(i) {
3494 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3495 selections = &selections[1..];
3496 continue;
3497 }
3498 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3499 break;
3500 }
3501 if selection.id == state.selection_id {
3502 return true;
3503 } else {
3504 i += 1;
3505 }
3506 }
3507 false
3508 });
3509 }
3510
3511 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3512 let offset = position.to_offset(buffer);
3513 let (word_range, kind) = buffer.surrounding_word(offset, true);
3514 if offset > word_range.start && kind == Some(CharKind::Word) {
3515 Some(
3516 buffer
3517 .text_for_range(word_range.start..offset)
3518 .collect::<String>(),
3519 )
3520 } else {
3521 None
3522 }
3523 }
3524
3525 pub fn toggle_inlay_hints(
3526 &mut self,
3527 _: &ToggleInlayHints,
3528 _: &mut Window,
3529 cx: &mut Context<Self>,
3530 ) {
3531 self.refresh_inlay_hints(
3532 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3533 cx,
3534 );
3535 }
3536
3537 pub fn inlay_hints_enabled(&self) -> bool {
3538 self.inlay_hint_cache.enabled
3539 }
3540
3541 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3542 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3543 return;
3544 }
3545
3546 let reason_description = reason.description();
3547 let ignore_debounce = matches!(
3548 reason,
3549 InlayHintRefreshReason::SettingsChange(_)
3550 | InlayHintRefreshReason::Toggle(_)
3551 | InlayHintRefreshReason::ExcerptsRemoved(_)
3552 );
3553 let (invalidate_cache, required_languages) = match reason {
3554 InlayHintRefreshReason::Toggle(enabled) => {
3555 self.inlay_hint_cache.enabled = enabled;
3556 if enabled {
3557 (InvalidationStrategy::RefreshRequested, None)
3558 } else {
3559 self.inlay_hint_cache.clear();
3560 self.splice_inlays(
3561 &self
3562 .visible_inlay_hints(cx)
3563 .iter()
3564 .map(|inlay| inlay.id)
3565 .collect::<Vec<InlayId>>(),
3566 Vec::new(),
3567 cx,
3568 );
3569 return;
3570 }
3571 }
3572 InlayHintRefreshReason::SettingsChange(new_settings) => {
3573 match self.inlay_hint_cache.update_settings(
3574 &self.buffer,
3575 new_settings,
3576 self.visible_inlay_hints(cx),
3577 cx,
3578 ) {
3579 ControlFlow::Break(Some(InlaySplice {
3580 to_remove,
3581 to_insert,
3582 })) => {
3583 self.splice_inlays(&to_remove, to_insert, cx);
3584 return;
3585 }
3586 ControlFlow::Break(None) => return,
3587 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3588 }
3589 }
3590 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3591 if let Some(InlaySplice {
3592 to_remove,
3593 to_insert,
3594 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3595 {
3596 self.splice_inlays(&to_remove, to_insert, cx);
3597 }
3598 return;
3599 }
3600 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3601 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3602 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3603 }
3604 InlayHintRefreshReason::RefreshRequested => {
3605 (InvalidationStrategy::RefreshRequested, None)
3606 }
3607 };
3608
3609 if let Some(InlaySplice {
3610 to_remove,
3611 to_insert,
3612 }) = self.inlay_hint_cache.spawn_hint_refresh(
3613 reason_description,
3614 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3615 invalidate_cache,
3616 ignore_debounce,
3617 cx,
3618 ) {
3619 self.splice_inlays(&to_remove, to_insert, cx);
3620 }
3621 }
3622
3623 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3624 self.display_map
3625 .read(cx)
3626 .current_inlays()
3627 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3628 .cloned()
3629 .collect()
3630 }
3631
3632 pub fn excerpts_for_inlay_hints_query(
3633 &self,
3634 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3635 cx: &mut Context<Editor>,
3636 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3637 let Some(project) = self.project.as_ref() else {
3638 return HashMap::default();
3639 };
3640 let project = project.read(cx);
3641 let multi_buffer = self.buffer().read(cx);
3642 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3643 let multi_buffer_visible_start = self
3644 .scroll_manager
3645 .anchor()
3646 .anchor
3647 .to_point(&multi_buffer_snapshot);
3648 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3649 multi_buffer_visible_start
3650 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3651 Bias::Left,
3652 );
3653 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3654 multi_buffer_snapshot
3655 .range_to_buffer_ranges(multi_buffer_visible_range)
3656 .into_iter()
3657 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3658 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3659 let buffer_file = project::File::from_dyn(buffer.file())?;
3660 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3661 let worktree_entry = buffer_worktree
3662 .read(cx)
3663 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3664 if worktree_entry.is_ignored {
3665 return None;
3666 }
3667
3668 let language = buffer.language()?;
3669 if let Some(restrict_to_languages) = restrict_to_languages {
3670 if !restrict_to_languages.contains(language) {
3671 return None;
3672 }
3673 }
3674 Some((
3675 excerpt_id,
3676 (
3677 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3678 buffer.version().clone(),
3679 excerpt_visible_range,
3680 ),
3681 ))
3682 })
3683 .collect()
3684 }
3685
3686 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3687 TextLayoutDetails {
3688 text_system: window.text_system().clone(),
3689 editor_style: self.style.clone().unwrap(),
3690 rem_size: window.rem_size(),
3691 scroll_anchor: self.scroll_manager.anchor(),
3692 visible_rows: self.visible_line_count(),
3693 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3694 }
3695 }
3696
3697 pub fn splice_inlays(
3698 &self,
3699 to_remove: &[InlayId],
3700 to_insert: Vec<Inlay>,
3701 cx: &mut Context<Self>,
3702 ) {
3703 self.display_map.update(cx, |display_map, cx| {
3704 display_map.splice_inlays(to_remove, to_insert, cx)
3705 });
3706 cx.notify();
3707 }
3708
3709 fn trigger_on_type_formatting(
3710 &self,
3711 input: String,
3712 window: &mut Window,
3713 cx: &mut Context<Self>,
3714 ) -> Option<Task<Result<()>>> {
3715 if input.len() != 1 {
3716 return None;
3717 }
3718
3719 let project = self.project.as_ref()?;
3720 let position = self.selections.newest_anchor().head();
3721 let (buffer, buffer_position) = self
3722 .buffer
3723 .read(cx)
3724 .text_anchor_for_position(position, cx)?;
3725
3726 let settings = language_settings::language_settings(
3727 buffer
3728 .read(cx)
3729 .language_at(buffer_position)
3730 .map(|l| l.name()),
3731 buffer.read(cx).file(),
3732 cx,
3733 );
3734 if !settings.use_on_type_format {
3735 return None;
3736 }
3737
3738 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3739 // hence we do LSP request & edit on host side only — add formats to host's history.
3740 let push_to_lsp_host_history = true;
3741 // If this is not the host, append its history with new edits.
3742 let push_to_client_history = project.read(cx).is_via_collab();
3743
3744 let on_type_formatting = project.update(cx, |project, cx| {
3745 project.on_type_format(
3746 buffer.clone(),
3747 buffer_position,
3748 input,
3749 push_to_lsp_host_history,
3750 cx,
3751 )
3752 });
3753 Some(cx.spawn_in(window, |editor, mut cx| async move {
3754 if let Some(transaction) = on_type_formatting.await? {
3755 if push_to_client_history {
3756 buffer
3757 .update(&mut cx, |buffer, _| {
3758 buffer.push_transaction(transaction, Instant::now());
3759 })
3760 .ok();
3761 }
3762 editor.update(&mut cx, |editor, cx| {
3763 editor.refresh_document_highlights(cx);
3764 })?;
3765 }
3766 Ok(())
3767 }))
3768 }
3769
3770 pub fn show_completions(
3771 &mut self,
3772 options: &ShowCompletions,
3773 window: &mut Window,
3774 cx: &mut Context<Self>,
3775 ) {
3776 if self.pending_rename.is_some() {
3777 return;
3778 }
3779
3780 let Some(provider) = self.completion_provider.as_ref() else {
3781 return;
3782 };
3783
3784 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3785 return;
3786 }
3787
3788 let position = self.selections.newest_anchor().head();
3789 if position.diff_base_anchor.is_some() {
3790 return;
3791 }
3792 let (buffer, buffer_position) =
3793 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3794 output
3795 } else {
3796 return;
3797 };
3798 let show_completion_documentation = buffer
3799 .read(cx)
3800 .snapshot()
3801 .settings_at(buffer_position, cx)
3802 .show_completion_documentation;
3803
3804 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3805
3806 let trigger_kind = match &options.trigger {
3807 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3808 CompletionTriggerKind::TRIGGER_CHARACTER
3809 }
3810 _ => CompletionTriggerKind::INVOKED,
3811 };
3812 let completion_context = CompletionContext {
3813 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3814 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3815 Some(String::from(trigger))
3816 } else {
3817 None
3818 }
3819 }),
3820 trigger_kind,
3821 };
3822 let completions =
3823 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3824 let sort_completions = provider.sort_completions();
3825
3826 let id = post_inc(&mut self.next_completion_id);
3827 let task = cx.spawn_in(window, |editor, mut cx| {
3828 async move {
3829 editor.update(&mut cx, |this, _| {
3830 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3831 })?;
3832 let completions = completions.await.log_err();
3833 let menu = if let Some(completions) = completions {
3834 let mut menu = CompletionsMenu::new(
3835 id,
3836 sort_completions,
3837 show_completion_documentation,
3838 position,
3839 buffer.clone(),
3840 completions.into(),
3841 );
3842
3843 menu.filter(query.as_deref(), cx.background_executor().clone())
3844 .await;
3845
3846 menu.visible().then_some(menu)
3847 } else {
3848 None
3849 };
3850
3851 editor.update_in(&mut cx, |editor, window, cx| {
3852 match editor.context_menu.borrow().as_ref() {
3853 None => {}
3854 Some(CodeContextMenu::Completions(prev_menu)) => {
3855 if prev_menu.id > id {
3856 return;
3857 }
3858 }
3859 _ => return,
3860 }
3861
3862 if editor.focus_handle.is_focused(window) && menu.is_some() {
3863 let mut menu = menu.unwrap();
3864 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3865
3866 *editor.context_menu.borrow_mut() =
3867 Some(CodeContextMenu::Completions(menu));
3868
3869 if editor.show_inline_completions_in_menu(cx) {
3870 editor.update_visible_inline_completion(window, cx);
3871 } else {
3872 editor.discard_inline_completion(false, cx);
3873 }
3874
3875 cx.notify();
3876 } else if editor.completion_tasks.len() <= 1 {
3877 // If there are no more completion tasks and the last menu was
3878 // empty, we should hide it.
3879 let was_hidden = editor.hide_context_menu(window, cx).is_none();
3880 // If it was already hidden and we don't show inline
3881 // completions in the menu, we should also show the
3882 // inline-completion when available.
3883 if was_hidden && editor.show_inline_completions_in_menu(cx) {
3884 editor.update_visible_inline_completion(window, cx);
3885 }
3886 }
3887 })?;
3888
3889 Ok::<_, anyhow::Error>(())
3890 }
3891 .log_err()
3892 });
3893
3894 self.completion_tasks.push((id, task));
3895 }
3896
3897 pub fn confirm_completion(
3898 &mut self,
3899 action: &ConfirmCompletion,
3900 window: &mut Window,
3901 cx: &mut Context<Self>,
3902 ) -> Option<Task<Result<()>>> {
3903 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
3904 }
3905
3906 pub fn compose_completion(
3907 &mut self,
3908 action: &ComposeCompletion,
3909 window: &mut Window,
3910 cx: &mut Context<Self>,
3911 ) -> Option<Task<Result<()>>> {
3912 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
3913 }
3914
3915 fn do_completion(
3916 &mut self,
3917 item_ix: Option<usize>,
3918 intent: CompletionIntent,
3919 window: &mut Window,
3920 cx: &mut Context<Editor>,
3921 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3922 use language::ToOffset as _;
3923
3924 let completions_menu =
3925 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
3926 menu
3927 } else {
3928 return None;
3929 };
3930
3931 let entries = completions_menu.entries.borrow();
3932 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
3933 if self.show_inline_completions_in_menu(cx) {
3934 self.discard_inline_completion(true, cx);
3935 }
3936 let candidate_id = mat.candidate_id;
3937 drop(entries);
3938
3939 let buffer_handle = completions_menu.buffer;
3940 let completion = completions_menu
3941 .completions
3942 .borrow()
3943 .get(candidate_id)?
3944 .clone();
3945 cx.stop_propagation();
3946
3947 let snippet;
3948 let text;
3949
3950 if completion.is_snippet() {
3951 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3952 text = snippet.as_ref().unwrap().text.clone();
3953 } else {
3954 snippet = None;
3955 text = completion.new_text.clone();
3956 };
3957 let selections = self.selections.all::<usize>(cx);
3958 let buffer = buffer_handle.read(cx);
3959 let old_range = completion.old_range.to_offset(buffer);
3960 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3961
3962 let newest_selection = self.selections.newest_anchor();
3963 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3964 return None;
3965 }
3966
3967 let lookbehind = newest_selection
3968 .start
3969 .text_anchor
3970 .to_offset(buffer)
3971 .saturating_sub(old_range.start);
3972 let lookahead = old_range
3973 .end
3974 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3975 let mut common_prefix_len = old_text
3976 .bytes()
3977 .zip(text.bytes())
3978 .take_while(|(a, b)| a == b)
3979 .count();
3980
3981 let snapshot = self.buffer.read(cx).snapshot(cx);
3982 let mut range_to_replace: Option<Range<isize>> = None;
3983 let mut ranges = Vec::new();
3984 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3985 for selection in &selections {
3986 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3987 let start = selection.start.saturating_sub(lookbehind);
3988 let end = selection.end + lookahead;
3989 if selection.id == newest_selection.id {
3990 range_to_replace = Some(
3991 ((start + common_prefix_len) as isize - selection.start as isize)
3992 ..(end as isize - selection.start as isize),
3993 );
3994 }
3995 ranges.push(start + common_prefix_len..end);
3996 } else {
3997 common_prefix_len = 0;
3998 ranges.clear();
3999 ranges.extend(selections.iter().map(|s| {
4000 if s.id == newest_selection.id {
4001 range_to_replace = Some(
4002 old_range.start.to_offset_utf16(&snapshot).0 as isize
4003 - selection.start as isize
4004 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4005 - selection.start as isize,
4006 );
4007 old_range.clone()
4008 } else {
4009 s.start..s.end
4010 }
4011 }));
4012 break;
4013 }
4014 if !self.linked_edit_ranges.is_empty() {
4015 let start_anchor = snapshot.anchor_before(selection.head());
4016 let end_anchor = snapshot.anchor_after(selection.tail());
4017 if let Some(ranges) = self
4018 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4019 {
4020 for (buffer, edits) in ranges {
4021 linked_edits.entry(buffer.clone()).or_default().extend(
4022 edits
4023 .into_iter()
4024 .map(|range| (range, text[common_prefix_len..].to_owned())),
4025 );
4026 }
4027 }
4028 }
4029 }
4030 let text = &text[common_prefix_len..];
4031
4032 cx.emit(EditorEvent::InputHandled {
4033 utf16_range_to_replace: range_to_replace,
4034 text: text.into(),
4035 });
4036
4037 self.transact(window, cx, |this, window, cx| {
4038 if let Some(mut snippet) = snippet {
4039 snippet.text = text.to_string();
4040 for tabstop in snippet
4041 .tabstops
4042 .iter_mut()
4043 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4044 {
4045 tabstop.start -= common_prefix_len as isize;
4046 tabstop.end -= common_prefix_len as isize;
4047 }
4048
4049 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4050 } else {
4051 this.buffer.update(cx, |buffer, cx| {
4052 buffer.edit(
4053 ranges.iter().map(|range| (range.clone(), text)),
4054 this.autoindent_mode.clone(),
4055 cx,
4056 );
4057 });
4058 }
4059 for (buffer, edits) in linked_edits {
4060 buffer.update(cx, |buffer, cx| {
4061 let snapshot = buffer.snapshot();
4062 let edits = edits
4063 .into_iter()
4064 .map(|(range, text)| {
4065 use text::ToPoint as TP;
4066 let end_point = TP::to_point(&range.end, &snapshot);
4067 let start_point = TP::to_point(&range.start, &snapshot);
4068 (start_point..end_point, text)
4069 })
4070 .sorted_by_key(|(range, _)| range.start)
4071 .collect::<Vec<_>>();
4072 buffer.edit(edits, None, cx);
4073 })
4074 }
4075
4076 this.refresh_inline_completion(true, false, window, cx);
4077 });
4078
4079 let show_new_completions_on_confirm = completion
4080 .confirm
4081 .as_ref()
4082 .map_or(false, |confirm| confirm(intent, window, cx));
4083 if show_new_completions_on_confirm {
4084 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4085 }
4086
4087 let provider = self.completion_provider.as_ref()?;
4088 drop(completion);
4089 let apply_edits = provider.apply_additional_edits_for_completion(
4090 buffer_handle,
4091 completions_menu.completions.clone(),
4092 candidate_id,
4093 true,
4094 cx,
4095 );
4096
4097 let editor_settings = EditorSettings::get_global(cx);
4098 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4099 // After the code completion is finished, users often want to know what signatures are needed.
4100 // so we should automatically call signature_help
4101 self.show_signature_help(&ShowSignatureHelp, window, cx);
4102 }
4103
4104 Some(cx.foreground_executor().spawn(async move {
4105 apply_edits.await?;
4106 Ok(())
4107 }))
4108 }
4109
4110 pub fn toggle_code_actions(
4111 &mut self,
4112 action: &ToggleCodeActions,
4113 window: &mut Window,
4114 cx: &mut Context<Self>,
4115 ) {
4116 let mut context_menu = self.context_menu.borrow_mut();
4117 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4118 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4119 // Toggle if we're selecting the same one
4120 *context_menu = None;
4121 cx.notify();
4122 return;
4123 } else {
4124 // Otherwise, clear it and start a new one
4125 *context_menu = None;
4126 cx.notify();
4127 }
4128 }
4129 drop(context_menu);
4130 let snapshot = self.snapshot(window, cx);
4131 let deployed_from_indicator = action.deployed_from_indicator;
4132 let mut task = self.code_actions_task.take();
4133 let action = action.clone();
4134 cx.spawn_in(window, |editor, mut cx| async move {
4135 while let Some(prev_task) = task {
4136 prev_task.await.log_err();
4137 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4138 }
4139
4140 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4141 if editor.focus_handle.is_focused(window) {
4142 let multibuffer_point = action
4143 .deployed_from_indicator
4144 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4145 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4146 let (buffer, buffer_row) = snapshot
4147 .buffer_snapshot
4148 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4149 .and_then(|(buffer_snapshot, range)| {
4150 editor
4151 .buffer
4152 .read(cx)
4153 .buffer(buffer_snapshot.remote_id())
4154 .map(|buffer| (buffer, range.start.row))
4155 })?;
4156 let (_, code_actions) = editor
4157 .available_code_actions
4158 .clone()
4159 .and_then(|(location, code_actions)| {
4160 let snapshot = location.buffer.read(cx).snapshot();
4161 let point_range = location.range.to_point(&snapshot);
4162 let point_range = point_range.start.row..=point_range.end.row;
4163 if point_range.contains(&buffer_row) {
4164 Some((location, code_actions))
4165 } else {
4166 None
4167 }
4168 })
4169 .unzip();
4170 let buffer_id = buffer.read(cx).remote_id();
4171 let tasks = editor
4172 .tasks
4173 .get(&(buffer_id, buffer_row))
4174 .map(|t| Arc::new(t.to_owned()));
4175 if tasks.is_none() && code_actions.is_none() {
4176 return None;
4177 }
4178
4179 editor.completion_tasks.clear();
4180 editor.discard_inline_completion(false, cx);
4181 let task_context =
4182 tasks
4183 .as_ref()
4184 .zip(editor.project.clone())
4185 .map(|(tasks, project)| {
4186 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4187 });
4188
4189 Some(cx.spawn_in(window, |editor, mut cx| async move {
4190 let task_context = match task_context {
4191 Some(task_context) => task_context.await,
4192 None => None,
4193 };
4194 let resolved_tasks =
4195 tasks.zip(task_context).map(|(tasks, task_context)| {
4196 Rc::new(ResolvedTasks {
4197 templates: tasks.resolve(&task_context).collect(),
4198 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4199 multibuffer_point.row,
4200 tasks.column,
4201 )),
4202 })
4203 });
4204 let spawn_straight_away = resolved_tasks
4205 .as_ref()
4206 .map_or(false, |tasks| tasks.templates.len() == 1)
4207 && code_actions
4208 .as_ref()
4209 .map_or(true, |actions| actions.is_empty());
4210 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4211 *editor.context_menu.borrow_mut() =
4212 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4213 buffer,
4214 actions: CodeActionContents {
4215 tasks: resolved_tasks,
4216 actions: code_actions,
4217 },
4218 selected_item: Default::default(),
4219 scroll_handle: UniformListScrollHandle::default(),
4220 deployed_from_indicator,
4221 }));
4222 if spawn_straight_away {
4223 if let Some(task) = editor.confirm_code_action(
4224 &ConfirmCodeAction { item_ix: Some(0) },
4225 window,
4226 cx,
4227 ) {
4228 cx.notify();
4229 return task;
4230 }
4231 }
4232 cx.notify();
4233 Task::ready(Ok(()))
4234 }) {
4235 task.await
4236 } else {
4237 Ok(())
4238 }
4239 }))
4240 } else {
4241 Some(Task::ready(Ok(())))
4242 }
4243 })?;
4244 if let Some(task) = spawned_test_task {
4245 task.await?;
4246 }
4247
4248 Ok::<_, anyhow::Error>(())
4249 })
4250 .detach_and_log_err(cx);
4251 }
4252
4253 pub fn confirm_code_action(
4254 &mut self,
4255 action: &ConfirmCodeAction,
4256 window: &mut Window,
4257 cx: &mut Context<Self>,
4258 ) -> Option<Task<Result<()>>> {
4259 let actions_menu =
4260 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4261 menu
4262 } else {
4263 return None;
4264 };
4265 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4266 let action = actions_menu.actions.get(action_ix)?;
4267 let title = action.label();
4268 let buffer = actions_menu.buffer;
4269 let workspace = self.workspace()?;
4270
4271 match action {
4272 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4273 workspace.update(cx, |workspace, cx| {
4274 workspace::tasks::schedule_resolved_task(
4275 workspace,
4276 task_source_kind,
4277 resolved_task,
4278 false,
4279 cx,
4280 );
4281
4282 Some(Task::ready(Ok(())))
4283 })
4284 }
4285 CodeActionsItem::CodeAction {
4286 excerpt_id,
4287 action,
4288 provider,
4289 } => {
4290 let apply_code_action =
4291 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4292 let workspace = workspace.downgrade();
4293 Some(cx.spawn_in(window, |editor, cx| async move {
4294 let project_transaction = apply_code_action.await?;
4295 Self::open_project_transaction(
4296 &editor,
4297 workspace,
4298 project_transaction,
4299 title,
4300 cx,
4301 )
4302 .await
4303 }))
4304 }
4305 }
4306 }
4307
4308 pub async fn open_project_transaction(
4309 this: &WeakEntity<Editor>,
4310 workspace: WeakEntity<Workspace>,
4311 transaction: ProjectTransaction,
4312 title: String,
4313 mut cx: AsyncWindowContext,
4314 ) -> Result<()> {
4315 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4316 cx.update(|_, cx| {
4317 entries.sort_unstable_by_key(|(buffer, _)| {
4318 buffer.read(cx).file().map(|f| f.path().clone())
4319 });
4320 })?;
4321
4322 // If the project transaction's edits are all contained within this editor, then
4323 // avoid opening a new editor to display them.
4324
4325 if let Some((buffer, transaction)) = entries.first() {
4326 if entries.len() == 1 {
4327 let excerpt = this.update(&mut cx, |editor, cx| {
4328 editor
4329 .buffer()
4330 .read(cx)
4331 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4332 })?;
4333 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4334 if excerpted_buffer == *buffer {
4335 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4336 let excerpt_range = excerpt_range.to_offset(buffer);
4337 buffer
4338 .edited_ranges_for_transaction::<usize>(transaction)
4339 .all(|range| {
4340 excerpt_range.start <= range.start
4341 && excerpt_range.end >= range.end
4342 })
4343 })?;
4344
4345 if all_edits_within_excerpt {
4346 return Ok(());
4347 }
4348 }
4349 }
4350 }
4351 } else {
4352 return Ok(());
4353 }
4354
4355 let mut ranges_to_highlight = Vec::new();
4356 let excerpt_buffer = cx.new(|cx| {
4357 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4358 for (buffer_handle, transaction) in &entries {
4359 let buffer = buffer_handle.read(cx);
4360 ranges_to_highlight.extend(
4361 multibuffer.push_excerpts_with_context_lines(
4362 buffer_handle.clone(),
4363 buffer
4364 .edited_ranges_for_transaction::<usize>(transaction)
4365 .collect(),
4366 DEFAULT_MULTIBUFFER_CONTEXT,
4367 cx,
4368 ),
4369 );
4370 }
4371 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4372 multibuffer
4373 })?;
4374
4375 workspace.update_in(&mut cx, |workspace, window, cx| {
4376 let project = workspace.project().clone();
4377 let editor = cx
4378 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4379 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4380 editor.update(cx, |editor, cx| {
4381 editor.highlight_background::<Self>(
4382 &ranges_to_highlight,
4383 |theme| theme.editor_highlighted_line_background,
4384 cx,
4385 );
4386 });
4387 })?;
4388
4389 Ok(())
4390 }
4391
4392 pub fn clear_code_action_providers(&mut self) {
4393 self.code_action_providers.clear();
4394 self.available_code_actions.take();
4395 }
4396
4397 pub fn add_code_action_provider(
4398 &mut self,
4399 provider: Rc<dyn CodeActionProvider>,
4400 window: &mut Window,
4401 cx: &mut Context<Self>,
4402 ) {
4403 if self
4404 .code_action_providers
4405 .iter()
4406 .any(|existing_provider| existing_provider.id() == provider.id())
4407 {
4408 return;
4409 }
4410
4411 self.code_action_providers.push(provider);
4412 self.refresh_code_actions(window, cx);
4413 }
4414
4415 pub fn remove_code_action_provider(
4416 &mut self,
4417 id: Arc<str>,
4418 window: &mut Window,
4419 cx: &mut Context<Self>,
4420 ) {
4421 self.code_action_providers
4422 .retain(|provider| provider.id() != id);
4423 self.refresh_code_actions(window, cx);
4424 }
4425
4426 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4427 let buffer = self.buffer.read(cx);
4428 let newest_selection = self.selections.newest_anchor().clone();
4429 if newest_selection.head().diff_base_anchor.is_some() {
4430 return None;
4431 }
4432 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4433 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4434 if start_buffer != end_buffer {
4435 return None;
4436 }
4437
4438 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4439 cx.background_executor()
4440 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4441 .await;
4442
4443 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4444 let providers = this.code_action_providers.clone();
4445 let tasks = this
4446 .code_action_providers
4447 .iter()
4448 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4449 .collect::<Vec<_>>();
4450 (providers, tasks)
4451 })?;
4452
4453 let mut actions = Vec::new();
4454 for (provider, provider_actions) in
4455 providers.into_iter().zip(future::join_all(tasks).await)
4456 {
4457 if let Some(provider_actions) = provider_actions.log_err() {
4458 actions.extend(provider_actions.into_iter().map(|action| {
4459 AvailableCodeAction {
4460 excerpt_id: newest_selection.start.excerpt_id,
4461 action,
4462 provider: provider.clone(),
4463 }
4464 }));
4465 }
4466 }
4467
4468 this.update(&mut cx, |this, cx| {
4469 this.available_code_actions = if actions.is_empty() {
4470 None
4471 } else {
4472 Some((
4473 Location {
4474 buffer: start_buffer,
4475 range: start..end,
4476 },
4477 actions.into(),
4478 ))
4479 };
4480 cx.notify();
4481 })
4482 }));
4483 None
4484 }
4485
4486 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4487 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4488 self.show_git_blame_inline = false;
4489
4490 self.show_git_blame_inline_delay_task =
4491 Some(cx.spawn_in(window, |this, mut cx| async move {
4492 cx.background_executor().timer(delay).await;
4493
4494 this.update(&mut cx, |this, cx| {
4495 this.show_git_blame_inline = true;
4496 cx.notify();
4497 })
4498 .log_err();
4499 }));
4500 }
4501 }
4502
4503 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4504 if self.pending_rename.is_some() {
4505 return None;
4506 }
4507
4508 let provider = self.semantics_provider.clone()?;
4509 let buffer = self.buffer.read(cx);
4510 let newest_selection = self.selections.newest_anchor().clone();
4511 let cursor_position = newest_selection.head();
4512 let (cursor_buffer, cursor_buffer_position) =
4513 buffer.text_anchor_for_position(cursor_position, cx)?;
4514 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4515 if cursor_buffer != tail_buffer {
4516 return None;
4517 }
4518 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4519 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4520 cx.background_executor()
4521 .timer(Duration::from_millis(debounce))
4522 .await;
4523
4524 let highlights = if let Some(highlights) = cx
4525 .update(|cx| {
4526 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4527 })
4528 .ok()
4529 .flatten()
4530 {
4531 highlights.await.log_err()
4532 } else {
4533 None
4534 };
4535
4536 if let Some(highlights) = highlights {
4537 this.update(&mut cx, |this, cx| {
4538 if this.pending_rename.is_some() {
4539 return;
4540 }
4541
4542 let buffer_id = cursor_position.buffer_id;
4543 let buffer = this.buffer.read(cx);
4544 if !buffer
4545 .text_anchor_for_position(cursor_position, cx)
4546 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4547 {
4548 return;
4549 }
4550
4551 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4552 let mut write_ranges = Vec::new();
4553 let mut read_ranges = Vec::new();
4554 for highlight in highlights {
4555 for (excerpt_id, excerpt_range) in
4556 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4557 {
4558 let start = highlight
4559 .range
4560 .start
4561 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4562 let end = highlight
4563 .range
4564 .end
4565 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4566 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4567 continue;
4568 }
4569
4570 let range = Anchor {
4571 buffer_id,
4572 excerpt_id,
4573 text_anchor: start,
4574 diff_base_anchor: None,
4575 }..Anchor {
4576 buffer_id,
4577 excerpt_id,
4578 text_anchor: end,
4579 diff_base_anchor: None,
4580 };
4581 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4582 write_ranges.push(range);
4583 } else {
4584 read_ranges.push(range);
4585 }
4586 }
4587 }
4588
4589 this.highlight_background::<DocumentHighlightRead>(
4590 &read_ranges,
4591 |theme| theme.editor_document_highlight_read_background,
4592 cx,
4593 );
4594 this.highlight_background::<DocumentHighlightWrite>(
4595 &write_ranges,
4596 |theme| theme.editor_document_highlight_write_background,
4597 cx,
4598 );
4599 cx.notify();
4600 })
4601 .log_err();
4602 }
4603 }));
4604 None
4605 }
4606
4607 pub fn refresh_inline_completion(
4608 &mut self,
4609 debounce: bool,
4610 user_requested: bool,
4611 window: &mut Window,
4612 cx: &mut Context<Self>,
4613 ) -> Option<()> {
4614 let provider = self.inline_completion_provider()?;
4615 let cursor = self.selections.newest_anchor().head();
4616 let (buffer, cursor_buffer_position) =
4617 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4618
4619 if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4620 self.discard_inline_completion(false, cx);
4621 return None;
4622 }
4623
4624 if !user_requested
4625 && (!self.show_inline_completions
4626 || !self.should_show_inline_completions_in_buffer(
4627 &buffer,
4628 cursor_buffer_position,
4629 cx,
4630 )
4631 || !self.is_focused(window)
4632 || buffer.read(cx).is_empty())
4633 {
4634 self.discard_inline_completion(false, cx);
4635 return None;
4636 }
4637
4638 self.update_visible_inline_completion(window, cx);
4639 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4640 Some(())
4641 }
4642
4643 pub fn should_show_inline_completions(&self, cx: &App) -> bool {
4644 let cursor = self.selections.newest_anchor().head();
4645 if let Some((buffer, cursor_position)) =
4646 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4647 {
4648 self.should_show_inline_completions_in_buffer(&buffer, cursor_position, cx)
4649 } else {
4650 false
4651 }
4652 }
4653
4654 fn should_show_inline_completions_in_buffer(
4655 &self,
4656 buffer: &Entity<Buffer>,
4657 buffer_position: language::Anchor,
4658 cx: &App,
4659 ) -> bool {
4660 if !self.snippet_stack.is_empty() {
4661 return false;
4662 }
4663
4664 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
4665 return false;
4666 }
4667
4668 if let Some(show_inline_completions) = self.show_inline_completions_override {
4669 show_inline_completions
4670 } else {
4671 let buffer = buffer.read(cx);
4672 self.mode == EditorMode::Full
4673 && language_settings(
4674 buffer.language_at(buffer_position).map(|l| l.name()),
4675 buffer.file(),
4676 cx,
4677 )
4678 .show_inline_completions
4679 }
4680 }
4681
4682 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
4683 let cursor = self.selections.newest_anchor().head();
4684 if let Some((buffer, cursor_position)) =
4685 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4686 {
4687 self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
4688 } else {
4689 false
4690 }
4691 }
4692
4693 fn inline_completions_enabled_in_buffer(
4694 &self,
4695 buffer: &Entity<Buffer>,
4696 buffer_position: language::Anchor,
4697 cx: &App,
4698 ) -> bool {
4699 maybe!({
4700 let provider = self.inline_completion_provider()?;
4701 if !provider.is_enabled(&buffer, buffer_position, cx) {
4702 return Some(false);
4703 }
4704 let buffer = buffer.read(cx);
4705 let Some(file) = buffer.file() else {
4706 return Some(true);
4707 };
4708 let settings = all_language_settings(Some(file), cx);
4709 Some(settings.inline_completions_enabled_for_path(file.path()))
4710 })
4711 .unwrap_or(false)
4712 }
4713
4714 fn cycle_inline_completion(
4715 &mut self,
4716 direction: Direction,
4717 window: &mut Window,
4718 cx: &mut Context<Self>,
4719 ) -> Option<()> {
4720 let provider = self.inline_completion_provider()?;
4721 let cursor = self.selections.newest_anchor().head();
4722 let (buffer, cursor_buffer_position) =
4723 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4724 if !self.show_inline_completions
4725 || !self.should_show_inline_completions_in_buffer(&buffer, cursor_buffer_position, cx)
4726 {
4727 return None;
4728 }
4729
4730 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4731 self.update_visible_inline_completion(window, cx);
4732
4733 Some(())
4734 }
4735
4736 pub fn show_inline_completion(
4737 &mut self,
4738 _: &ShowInlineCompletion,
4739 window: &mut Window,
4740 cx: &mut Context<Self>,
4741 ) {
4742 if !self.has_active_inline_completion() {
4743 self.refresh_inline_completion(false, true, window, cx);
4744 return;
4745 }
4746
4747 self.update_visible_inline_completion(window, cx);
4748 }
4749
4750 pub fn display_cursor_names(
4751 &mut self,
4752 _: &DisplayCursorNames,
4753 window: &mut Window,
4754 cx: &mut Context<Self>,
4755 ) {
4756 self.show_cursor_names(window, cx);
4757 }
4758
4759 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4760 self.show_cursor_names = true;
4761 cx.notify();
4762 cx.spawn_in(window, |this, mut cx| async move {
4763 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4764 this.update(&mut cx, |this, cx| {
4765 this.show_cursor_names = false;
4766 cx.notify()
4767 })
4768 .ok()
4769 })
4770 .detach();
4771 }
4772
4773 pub fn next_inline_completion(
4774 &mut self,
4775 _: &NextInlineCompletion,
4776 window: &mut Window,
4777 cx: &mut Context<Self>,
4778 ) {
4779 if self.has_active_inline_completion() {
4780 self.cycle_inline_completion(Direction::Next, window, cx);
4781 } else {
4782 let is_copilot_disabled = self
4783 .refresh_inline_completion(false, true, window, cx)
4784 .is_none();
4785 if is_copilot_disabled {
4786 cx.propagate();
4787 }
4788 }
4789 }
4790
4791 pub fn previous_inline_completion(
4792 &mut self,
4793 _: &PreviousInlineCompletion,
4794 window: &mut Window,
4795 cx: &mut Context<Self>,
4796 ) {
4797 if self.has_active_inline_completion() {
4798 self.cycle_inline_completion(Direction::Prev, window, cx);
4799 } else {
4800 let is_copilot_disabled = self
4801 .refresh_inline_completion(false, true, window, cx)
4802 .is_none();
4803 if is_copilot_disabled {
4804 cx.propagate();
4805 }
4806 }
4807 }
4808
4809 pub fn accept_inline_completion(
4810 &mut self,
4811 _: &AcceptInlineCompletion,
4812 window: &mut Window,
4813 cx: &mut Context<Self>,
4814 ) {
4815 let buffer = self.buffer.read(cx);
4816 let snapshot = buffer.snapshot(cx);
4817 let selection = self.selections.newest_adjusted(cx);
4818 let cursor = selection.head();
4819 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
4820 let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
4821 if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
4822 {
4823 if cursor.column < suggested_indent.len
4824 && cursor.column <= current_indent.len
4825 && current_indent.len <= suggested_indent.len
4826 {
4827 self.tab(&Default::default(), window, cx);
4828 return;
4829 }
4830 }
4831
4832 if self.show_inline_completions_in_menu(cx) {
4833 self.hide_context_menu(window, cx);
4834 }
4835
4836 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4837 return;
4838 };
4839
4840 self.report_inline_completion_event(true, cx);
4841
4842 match &active_inline_completion.completion {
4843 InlineCompletion::Move { target, .. } => {
4844 let target = *target;
4845 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
4846 selections.select_anchor_ranges([target..target]);
4847 });
4848 }
4849 InlineCompletion::Edit { edits, .. } => {
4850 if let Some(provider) = self.inline_completion_provider() {
4851 provider.accept(cx);
4852 }
4853
4854 let snapshot = self.buffer.read(cx).snapshot(cx);
4855 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4856
4857 self.buffer.update(cx, |buffer, cx| {
4858 buffer.edit(edits.iter().cloned(), None, cx)
4859 });
4860
4861 self.change_selections(None, window, cx, |s| {
4862 s.select_anchor_ranges([last_edit_end..last_edit_end])
4863 });
4864
4865 self.update_visible_inline_completion(window, cx);
4866 if self.active_inline_completion.is_none() {
4867 self.refresh_inline_completion(true, true, window, cx);
4868 }
4869
4870 cx.notify();
4871 }
4872 }
4873 }
4874
4875 pub fn accept_partial_inline_completion(
4876 &mut self,
4877 _: &AcceptPartialInlineCompletion,
4878 window: &mut Window,
4879 cx: &mut Context<Self>,
4880 ) {
4881 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4882 return;
4883 };
4884 if self.selections.count() != 1 {
4885 return;
4886 }
4887
4888 self.report_inline_completion_event(true, cx);
4889
4890 match &active_inline_completion.completion {
4891 InlineCompletion::Move { target, .. } => {
4892 let target = *target;
4893 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
4894 selections.select_anchor_ranges([target..target]);
4895 });
4896 }
4897 InlineCompletion::Edit { edits, .. } => {
4898 // Find an insertion that starts at the cursor position.
4899 let snapshot = self.buffer.read(cx).snapshot(cx);
4900 let cursor_offset = self.selections.newest::<usize>(cx).head();
4901 let insertion = edits.iter().find_map(|(range, text)| {
4902 let range = range.to_offset(&snapshot);
4903 if range.is_empty() && range.start == cursor_offset {
4904 Some(text)
4905 } else {
4906 None
4907 }
4908 });
4909
4910 if let Some(text) = insertion {
4911 let mut partial_completion = text
4912 .chars()
4913 .by_ref()
4914 .take_while(|c| c.is_alphabetic())
4915 .collect::<String>();
4916 if partial_completion.is_empty() {
4917 partial_completion = text
4918 .chars()
4919 .by_ref()
4920 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4921 .collect::<String>();
4922 }
4923
4924 cx.emit(EditorEvent::InputHandled {
4925 utf16_range_to_replace: None,
4926 text: partial_completion.clone().into(),
4927 });
4928
4929 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
4930
4931 self.refresh_inline_completion(true, true, window, cx);
4932 cx.notify();
4933 } else {
4934 self.accept_inline_completion(&Default::default(), window, cx);
4935 }
4936 }
4937 }
4938 }
4939
4940 fn discard_inline_completion(
4941 &mut self,
4942 should_report_inline_completion_event: bool,
4943 cx: &mut Context<Self>,
4944 ) -> bool {
4945 if should_report_inline_completion_event {
4946 self.report_inline_completion_event(false, cx);
4947 }
4948
4949 if let Some(provider) = self.inline_completion_provider() {
4950 provider.discard(cx);
4951 }
4952
4953 self.take_active_inline_completion(cx)
4954 }
4955
4956 fn report_inline_completion_event(&self, accepted: bool, cx: &App) {
4957 let Some(provider) = self.inline_completion_provider() else {
4958 return;
4959 };
4960
4961 let Some((_, buffer, _)) = self
4962 .buffer
4963 .read(cx)
4964 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4965 else {
4966 return;
4967 };
4968
4969 let extension = buffer
4970 .read(cx)
4971 .file()
4972 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4973
4974 let event_type = match accepted {
4975 true => "Edit Prediction Accepted",
4976 false => "Edit Prediction Discarded",
4977 };
4978 telemetry::event!(
4979 event_type,
4980 provider = provider.name(),
4981 suggestion_accepted = accepted,
4982 file_extension = extension,
4983 );
4984 }
4985
4986 pub fn has_active_inline_completion(&self) -> bool {
4987 self.active_inline_completion.is_some()
4988 }
4989
4990 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
4991 let Some(active_inline_completion) = self.active_inline_completion.take() else {
4992 return false;
4993 };
4994
4995 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
4996 self.clear_highlights::<InlineCompletionHighlight>(cx);
4997 self.stale_inline_completion_in_menu = Some(active_inline_completion);
4998 true
4999 }
5000
5001 pub fn is_previewing_inline_completion(&self) -> bool {
5002 matches!(
5003 self.context_menu.borrow().as_ref(),
5004 Some(CodeContextMenu::Completions(menu)) if !menu.is_empty() && menu.previewing_inline_completion
5005 )
5006 }
5007
5008 fn update_inline_completion_preview(
5009 &mut self,
5010 modifiers: &Modifiers,
5011 window: &mut Window,
5012 cx: &mut Context<Self>,
5013 ) {
5014 // Moves jump directly with a preview step
5015
5016 if self
5017 .active_inline_completion
5018 .as_ref()
5019 .map_or(true, |c| c.is_move())
5020 {
5021 cx.notify();
5022 return;
5023 }
5024
5025 if !self.show_inline_completions_in_menu(cx) {
5026 return;
5027 }
5028
5029 let mut menu_borrow = self.context_menu.borrow_mut();
5030
5031 let Some(CodeContextMenu::Completions(completions_menu)) = menu_borrow.as_mut() else {
5032 return;
5033 };
5034
5035 if completions_menu.is_empty()
5036 || completions_menu.previewing_inline_completion == modifiers.alt
5037 {
5038 return;
5039 }
5040
5041 completions_menu.set_previewing_inline_completion(modifiers.alt);
5042 drop(menu_borrow);
5043 self.update_visible_inline_completion(window, cx);
5044 }
5045
5046 fn update_visible_inline_completion(
5047 &mut self,
5048 _window: &mut Window,
5049 cx: &mut Context<Self>,
5050 ) -> Option<()> {
5051 let selection = self.selections.newest_anchor();
5052 let cursor = selection.head();
5053 let multibuffer = self.buffer.read(cx).snapshot(cx);
5054 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5055 let excerpt_id = cursor.excerpt_id;
5056
5057 let show_in_menu = self.show_inline_completions_in_menu(cx);
5058 let completions_menu_has_precedence = !show_in_menu
5059 && (self.context_menu.borrow().is_some()
5060 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5061 if completions_menu_has_precedence
5062 || !offset_selection.is_empty()
5063 || !self.show_inline_completions
5064 || self
5065 .active_inline_completion
5066 .as_ref()
5067 .map_or(false, |completion| {
5068 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5069 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5070 !invalidation_range.contains(&offset_selection.head())
5071 })
5072 {
5073 self.discard_inline_completion(false, cx);
5074 return None;
5075 }
5076
5077 self.take_active_inline_completion(cx);
5078 let provider = self.inline_completion_provider()?;
5079
5080 let (buffer, cursor_buffer_position) =
5081 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5082
5083 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5084 let edits = inline_completion
5085 .edits
5086 .into_iter()
5087 .flat_map(|(range, new_text)| {
5088 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5089 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5090 Some((start..end, new_text))
5091 })
5092 .collect::<Vec<_>>();
5093 if edits.is_empty() {
5094 return None;
5095 }
5096
5097 let first_edit_start = edits.first().unwrap().0.start;
5098 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5099 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5100
5101 let last_edit_end = edits.last().unwrap().0.end;
5102 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5103 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5104
5105 let cursor_row = cursor.to_point(&multibuffer).row;
5106
5107 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5108
5109 let mut inlay_ids = Vec::new();
5110 let invalidation_row_range;
5111 let move_invalidation_row_range = if cursor_row < edit_start_row {
5112 Some(cursor_row..edit_end_row)
5113 } else if cursor_row > edit_end_row {
5114 Some(edit_start_row..cursor_row)
5115 } else {
5116 None
5117 };
5118 let completion = if let Some(move_invalidation_row_range) = move_invalidation_row_range {
5119 invalidation_row_range = move_invalidation_row_range;
5120 let target = first_edit_start;
5121 let target_point = text::ToPoint::to_point(&target.text_anchor, &snapshot);
5122 // TODO: Base this off of TreeSitter or word boundaries?
5123 let target_excerpt_begin = snapshot.anchor_before(snapshot.clip_point(
5124 Point::new(target_point.row, target_point.column.saturating_sub(20)),
5125 Bias::Left,
5126 ));
5127 let target_excerpt_end = snapshot.anchor_after(snapshot.clip_point(
5128 Point::new(target_point.row, target_point.column + 20),
5129 Bias::Right,
5130 ));
5131 let range_around_target = target_excerpt_begin..target_excerpt_end;
5132 InlineCompletion::Move {
5133 target,
5134 range_around_target,
5135 snapshot,
5136 }
5137 } else {
5138 if !show_in_menu || !self.has_active_completions_menu() {
5139 if edits
5140 .iter()
5141 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5142 {
5143 let mut inlays = Vec::new();
5144 for (range, new_text) in &edits {
5145 let inlay = Inlay::inline_completion(
5146 post_inc(&mut self.next_inlay_id),
5147 range.start,
5148 new_text.as_str(),
5149 );
5150 inlay_ids.push(inlay.id);
5151 inlays.push(inlay);
5152 }
5153
5154 self.splice_inlays(&[], inlays, cx);
5155 } else {
5156 let background_color = cx.theme().status().deleted_background;
5157 self.highlight_text::<InlineCompletionHighlight>(
5158 edits.iter().map(|(range, _)| range.clone()).collect(),
5159 HighlightStyle {
5160 background_color: Some(background_color),
5161 ..Default::default()
5162 },
5163 cx,
5164 );
5165 }
5166 }
5167
5168 invalidation_row_range = edit_start_row..edit_end_row;
5169
5170 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5171 if provider.show_tab_accept_marker() {
5172 EditDisplayMode::TabAccept(self.is_previewing_inline_completion())
5173 } else {
5174 EditDisplayMode::Inline
5175 }
5176 } else {
5177 EditDisplayMode::DiffPopover
5178 };
5179
5180 InlineCompletion::Edit {
5181 edits,
5182 edit_preview: inline_completion.edit_preview,
5183 display_mode,
5184 snapshot,
5185 }
5186 };
5187
5188 let invalidation_range = multibuffer
5189 .anchor_before(Point::new(invalidation_row_range.start, 0))
5190 ..multibuffer.anchor_after(Point::new(
5191 invalidation_row_range.end,
5192 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5193 ));
5194
5195 self.stale_inline_completion_in_menu = None;
5196 self.active_inline_completion = Some(InlineCompletionState {
5197 inlay_ids,
5198 completion,
5199 invalidation_range,
5200 });
5201
5202 cx.notify();
5203
5204 Some(())
5205 }
5206
5207 pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5208 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5209 }
5210
5211 fn show_inline_completions_in_menu(&self, cx: &App) -> bool {
5212 let by_provider = matches!(
5213 self.menu_inline_completions_policy,
5214 MenuInlineCompletionsPolicy::ByProvider
5215 );
5216
5217 by_provider
5218 && EditorSettings::get_global(cx).show_inline_completions_in_menu
5219 && self
5220 .inline_completion_provider()
5221 .map_or(false, |provider| provider.show_completions_in_menu())
5222 }
5223
5224 fn render_code_actions_indicator(
5225 &self,
5226 _style: &EditorStyle,
5227 row: DisplayRow,
5228 is_active: bool,
5229 cx: &mut Context<Self>,
5230 ) -> Option<IconButton> {
5231 if self.available_code_actions.is_some() {
5232 Some(
5233 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5234 .shape(ui::IconButtonShape::Square)
5235 .icon_size(IconSize::XSmall)
5236 .icon_color(Color::Muted)
5237 .toggle_state(is_active)
5238 .tooltip({
5239 let focus_handle = self.focus_handle.clone();
5240 move |window, cx| {
5241 Tooltip::for_action_in(
5242 "Toggle Code Actions",
5243 &ToggleCodeActions {
5244 deployed_from_indicator: None,
5245 },
5246 &focus_handle,
5247 window,
5248 cx,
5249 )
5250 }
5251 })
5252 .on_click(cx.listener(move |editor, _e, window, cx| {
5253 window.focus(&editor.focus_handle(cx));
5254 editor.toggle_code_actions(
5255 &ToggleCodeActions {
5256 deployed_from_indicator: Some(row),
5257 },
5258 window,
5259 cx,
5260 );
5261 })),
5262 )
5263 } else {
5264 None
5265 }
5266 }
5267
5268 fn clear_tasks(&mut self) {
5269 self.tasks.clear()
5270 }
5271
5272 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5273 if self.tasks.insert(key, value).is_some() {
5274 // This case should hopefully be rare, but just in case...
5275 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5276 }
5277 }
5278
5279 fn build_tasks_context(
5280 project: &Entity<Project>,
5281 buffer: &Entity<Buffer>,
5282 buffer_row: u32,
5283 tasks: &Arc<RunnableTasks>,
5284 cx: &mut Context<Self>,
5285 ) -> Task<Option<task::TaskContext>> {
5286 let position = Point::new(buffer_row, tasks.column);
5287 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5288 let location = Location {
5289 buffer: buffer.clone(),
5290 range: range_start..range_start,
5291 };
5292 // Fill in the environmental variables from the tree-sitter captures
5293 let mut captured_task_variables = TaskVariables::default();
5294 for (capture_name, value) in tasks.extra_variables.clone() {
5295 captured_task_variables.insert(
5296 task::VariableName::Custom(capture_name.into()),
5297 value.clone(),
5298 );
5299 }
5300 project.update(cx, |project, cx| {
5301 project.task_store().update(cx, |task_store, cx| {
5302 task_store.task_context_for_location(captured_task_variables, location, cx)
5303 })
5304 })
5305 }
5306
5307 pub fn spawn_nearest_task(
5308 &mut self,
5309 action: &SpawnNearestTask,
5310 window: &mut Window,
5311 cx: &mut Context<Self>,
5312 ) {
5313 let Some((workspace, _)) = self.workspace.clone() else {
5314 return;
5315 };
5316 let Some(project) = self.project.clone() else {
5317 return;
5318 };
5319
5320 // Try to find a closest, enclosing node using tree-sitter that has a
5321 // task
5322 let Some((buffer, buffer_row, tasks)) = self
5323 .find_enclosing_node_task(cx)
5324 // Or find the task that's closest in row-distance.
5325 .or_else(|| self.find_closest_task(cx))
5326 else {
5327 return;
5328 };
5329
5330 let reveal_strategy = action.reveal;
5331 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5332 cx.spawn_in(window, |_, mut cx| async move {
5333 let context = task_context.await?;
5334 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5335
5336 let resolved = resolved_task.resolved.as_mut()?;
5337 resolved.reveal = reveal_strategy;
5338
5339 workspace
5340 .update(&mut cx, |workspace, cx| {
5341 workspace::tasks::schedule_resolved_task(
5342 workspace,
5343 task_source_kind,
5344 resolved_task,
5345 false,
5346 cx,
5347 );
5348 })
5349 .ok()
5350 })
5351 .detach();
5352 }
5353
5354 fn find_closest_task(
5355 &mut self,
5356 cx: &mut Context<Self>,
5357 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5358 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5359
5360 let ((buffer_id, row), tasks) = self
5361 .tasks
5362 .iter()
5363 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5364
5365 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5366 let tasks = Arc::new(tasks.to_owned());
5367 Some((buffer, *row, tasks))
5368 }
5369
5370 fn find_enclosing_node_task(
5371 &mut self,
5372 cx: &mut Context<Self>,
5373 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5374 let snapshot = self.buffer.read(cx).snapshot(cx);
5375 let offset = self.selections.newest::<usize>(cx).head();
5376 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5377 let buffer_id = excerpt.buffer().remote_id();
5378
5379 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5380 let mut cursor = layer.node().walk();
5381
5382 while cursor.goto_first_child_for_byte(offset).is_some() {
5383 if cursor.node().end_byte() == offset {
5384 cursor.goto_next_sibling();
5385 }
5386 }
5387
5388 // Ascend to the smallest ancestor that contains the range and has a task.
5389 loop {
5390 let node = cursor.node();
5391 let node_range = node.byte_range();
5392 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5393
5394 // Check if this node contains our offset
5395 if node_range.start <= offset && node_range.end >= offset {
5396 // If it contains offset, check for task
5397 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5398 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5399 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5400 }
5401 }
5402
5403 if !cursor.goto_parent() {
5404 break;
5405 }
5406 }
5407 None
5408 }
5409
5410 fn render_run_indicator(
5411 &self,
5412 _style: &EditorStyle,
5413 is_active: bool,
5414 row: DisplayRow,
5415 cx: &mut Context<Self>,
5416 ) -> IconButton {
5417 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5418 .shape(ui::IconButtonShape::Square)
5419 .icon_size(IconSize::XSmall)
5420 .icon_color(Color::Muted)
5421 .toggle_state(is_active)
5422 .on_click(cx.listener(move |editor, _e, window, cx| {
5423 window.focus(&editor.focus_handle(cx));
5424 editor.toggle_code_actions(
5425 &ToggleCodeActions {
5426 deployed_from_indicator: Some(row),
5427 },
5428 window,
5429 cx,
5430 );
5431 }))
5432 }
5433
5434 pub fn context_menu_visible(&self) -> bool {
5435 self.context_menu
5436 .borrow()
5437 .as_ref()
5438 .map_or(false, |menu| menu.visible())
5439 }
5440
5441 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5442 self.context_menu
5443 .borrow()
5444 .as_ref()
5445 .map(|menu| menu.origin())
5446 }
5447
5448 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5449 px(32.)
5450 }
5451
5452 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5453 if self.read_only(cx) {
5454 cx.theme().players().read_only()
5455 } else {
5456 self.style.as_ref().unwrap().local_player
5457 }
5458 }
5459
5460 #[allow(clippy::too_many_arguments)]
5461 fn render_edit_prediction_cursor_popover(
5462 &self,
5463 min_width: Pixels,
5464 max_width: Pixels,
5465 cursor_point: Point,
5466 start_row: DisplayRow,
5467 line_layouts: &[LineWithInvisibles],
5468 style: &EditorStyle,
5469 accept_keystroke: &gpui::Keystroke,
5470 window: &Window,
5471 cx: &mut Context<Editor>,
5472 ) -> Option<AnyElement> {
5473 let provider = self.inline_completion_provider.as_ref()?;
5474
5475 if provider.provider.needs_terms_acceptance(cx) {
5476 return Some(
5477 h_flex()
5478 .h(self.edit_prediction_cursor_popover_height())
5479 .min_w(min_width)
5480 .flex_1()
5481 .px_2()
5482 .gap_3()
5483 .elevation_2(cx)
5484 .hover(|style| style.bg(cx.theme().colors().element_hover))
5485 .id("accept-terms")
5486 .cursor_pointer()
5487 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5488 .on_click(cx.listener(|this, _event, window, cx| {
5489 cx.stop_propagation();
5490 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
5491 window.dispatch_action(
5492 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
5493 cx,
5494 );
5495 }))
5496 .child(
5497 h_flex()
5498 .w_full()
5499 .gap_2()
5500 .child(Icon::new(IconName::ZedPredict))
5501 .child(Label::new("Accept Terms of Service"))
5502 .child(div().w_full())
5503 .child(Icon::new(IconName::ArrowUpRight))
5504 .into_any_element(),
5505 )
5506 .into_any(),
5507 );
5508 }
5509
5510 let is_refreshing = provider.provider.is_refreshing(cx);
5511
5512 fn pending_completion_container() -> Div {
5513 h_flex()
5514 .flex_1()
5515 .gap_3()
5516 .child(Icon::new(IconName::ZedPredict))
5517 }
5518
5519 let completion = match &self.active_inline_completion {
5520 Some(completion) => self.render_edit_prediction_cursor_popover_preview(
5521 completion,
5522 cursor_point,
5523 start_row,
5524 line_layouts,
5525 style,
5526 cx,
5527 )?,
5528
5529 None if is_refreshing => match &self.stale_inline_completion_in_menu {
5530 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
5531 stale_completion,
5532 cursor_point,
5533 start_row,
5534 line_layouts,
5535 style,
5536 cx,
5537 )?,
5538
5539 None => {
5540 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
5541 }
5542 },
5543
5544 None => pending_completion_container().child(Label::new("No Prediction")),
5545 };
5546
5547 let buffer_font = theme::ThemeSettings::get_global(cx).buffer_font.clone();
5548 let completion = completion.font(buffer_font.clone());
5549
5550 let completion = if is_refreshing {
5551 completion
5552 .with_animation(
5553 "loading-completion",
5554 Animation::new(Duration::from_secs(2))
5555 .repeat()
5556 .with_easing(pulsating_between(0.4, 0.8)),
5557 |label, delta| label.opacity(delta),
5558 )
5559 .into_any_element()
5560 } else {
5561 completion.into_any_element()
5562 };
5563
5564 let has_completion = self.active_inline_completion.is_some();
5565
5566 let is_move = self
5567 .active_inline_completion
5568 .as_ref()
5569 .map_or(false, |c| c.is_move());
5570
5571 Some(
5572 h_flex()
5573 .h(self.edit_prediction_cursor_popover_height())
5574 .min_w(min_width)
5575 .max_w(max_width)
5576 .flex_1()
5577 .px_2()
5578 .gap_3()
5579 .elevation_2(cx)
5580 .child(completion)
5581 .child(
5582 h_flex()
5583 .border_l_1()
5584 .border_color(cx.theme().colors().border_variant)
5585 .pl_2()
5586 .child(
5587 h_flex()
5588 .font(buffer_font.clone())
5589 .p_1()
5590 .rounded_sm()
5591 .children(ui::render_modifiers(
5592 &accept_keystroke.modifiers,
5593 PlatformStyle::platform(),
5594 if window.modifiers() == accept_keystroke.modifiers {
5595 Some(Color::Accent)
5596 } else {
5597 None
5598 },
5599 !is_move,
5600 )),
5601 )
5602 .opacity(if has_completion { 1.0 } else { 0.1 })
5603 .child(if is_move {
5604 div()
5605 .child(ui::Key::new(&accept_keystroke.key, None))
5606 .font(buffer_font.clone())
5607 .into_any()
5608 } else {
5609 Label::new("Preview").color(Color::Muted).into_any_element()
5610 }),
5611 )
5612 .into_any(),
5613 )
5614 }
5615
5616 fn render_edit_prediction_cursor_popover_preview(
5617 &self,
5618 completion: &InlineCompletionState,
5619 cursor_point: Point,
5620 start_row: DisplayRow,
5621 line_layouts: &[LineWithInvisibles],
5622 style: &EditorStyle,
5623 cx: &mut Context<Editor>,
5624 ) -> Option<Div> {
5625 use text::ToPoint as _;
5626
5627 fn render_relative_row_jump(
5628 prefix: impl Into<String>,
5629 current_row: u32,
5630 target_row: u32,
5631 ) -> Div {
5632 let (row_diff, arrow) = if target_row < current_row {
5633 (current_row - target_row, IconName::ArrowUp)
5634 } else {
5635 (target_row - current_row, IconName::ArrowDown)
5636 };
5637
5638 h_flex()
5639 .child(
5640 Label::new(format!("{}{}", prefix.into(), row_diff))
5641 .color(Color::Muted)
5642 .size(LabelSize::Small),
5643 )
5644 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
5645 }
5646
5647 match &completion.completion {
5648 InlineCompletion::Edit {
5649 edits,
5650 edit_preview,
5651 snapshot,
5652 display_mode: _,
5653 } => {
5654 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
5655
5656 let highlighted_edits = crate::inline_completion_edit_text(
5657 &snapshot,
5658 &edits,
5659 edit_preview.as_ref()?,
5660 true,
5661 cx,
5662 );
5663
5664 let len_total = highlighted_edits.text.len();
5665 let first_line = &highlighted_edits.text
5666 [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
5667 let first_line_len = first_line.len();
5668
5669 let first_highlight_start = highlighted_edits
5670 .highlights
5671 .first()
5672 .map_or(0, |(range, _)| range.start);
5673 let drop_prefix_len = first_line
5674 .char_indices()
5675 .find(|(_, c)| !c.is_whitespace())
5676 .map_or(first_highlight_start, |(ix, _)| {
5677 ix.min(first_highlight_start)
5678 });
5679
5680 let preview_text = &first_line[drop_prefix_len..];
5681 let preview_len = preview_text.len();
5682 let highlights = highlighted_edits
5683 .highlights
5684 .into_iter()
5685 .take_until(|(range, _)| range.start > first_line_len)
5686 .map(|(range, style)| {
5687 (
5688 range.start - drop_prefix_len
5689 ..(range.end - drop_prefix_len).min(preview_len),
5690 style,
5691 )
5692 });
5693
5694 let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
5695 .with_highlights(&style.text, highlights);
5696
5697 let preview = h_flex()
5698 .gap_1()
5699 .child(styled_text)
5700 .when(len_total > first_line_len, |parent| parent.child("…"));
5701
5702 let left = if first_edit_row != cursor_point.row {
5703 render_relative_row_jump("", cursor_point.row, first_edit_row)
5704 .into_any_element()
5705 } else {
5706 Icon::new(IconName::ZedPredict).into_any_element()
5707 };
5708
5709 Some(h_flex().flex_1().gap_3().child(left).child(preview))
5710 }
5711
5712 InlineCompletion::Move {
5713 target,
5714 range_around_target,
5715 snapshot,
5716 } => {
5717 let highlighted_text = snapshot.highlighted_text_for_range(
5718 range_around_target.clone(),
5719 None,
5720 &style.syntax,
5721 );
5722 let cursor_color = self.current_user_player_color(cx).cursor;
5723
5724 let start_point = range_around_target.start.to_point(&snapshot);
5725 let end_point = range_around_target.end.to_point(&snapshot);
5726 let target_point = target.text_anchor.to_point(&snapshot);
5727
5728 let cursor_relative_position = line_layouts
5729 .get(start_point.row.saturating_sub(start_row.0) as usize)
5730 .map(|line| {
5731 let start_column_x = line.x_for_index(start_point.column as usize);
5732 let target_column_x = line.x_for_index(target_point.column as usize);
5733 target_column_x - start_column_x
5734 });
5735
5736 let fade_before = start_point.column > 0;
5737 let fade_after = end_point.column < snapshot.line_len(end_point.row);
5738
5739 let background = cx.theme().colors().elevated_surface_background;
5740
5741 Some(
5742 h_flex()
5743 .gap_3()
5744 .flex_1()
5745 .child(render_relative_row_jump(
5746 "Jump ",
5747 cursor_point.row,
5748 target.text_anchor.to_point(&snapshot).row,
5749 ))
5750 .when(!highlighted_text.text.is_empty(), |parent| {
5751 parent.child(
5752 h_flex()
5753 .relative()
5754 .child(highlighted_text.to_styled_text(&style.text))
5755 .when(fade_before, |parent| {
5756 parent.child(
5757 div().absolute().top_0().left_0().w_4().h_full().bg(
5758 linear_gradient(
5759 90.,
5760 linear_color_stop(background, 0.),
5761 linear_color_stop(background.opacity(0.), 1.),
5762 ),
5763 ),
5764 )
5765 })
5766 .when(fade_after, |parent| {
5767 parent.child(
5768 div().absolute().top_0().right_0().w_4().h_full().bg(
5769 linear_gradient(
5770 -90.,
5771 linear_color_stop(background, 0.),
5772 linear_color_stop(background.opacity(0.), 1.),
5773 ),
5774 ),
5775 )
5776 })
5777 .when_some(cursor_relative_position, |parent, position| {
5778 parent.child(
5779 div()
5780 .w(px(2.))
5781 .h_full()
5782 .bg(cursor_color)
5783 .absolute()
5784 .top_0()
5785 .left(position),
5786 )
5787 }),
5788 )
5789 }),
5790 )
5791 }
5792 }
5793 }
5794
5795 fn render_context_menu(
5796 &self,
5797 style: &EditorStyle,
5798 max_height_in_lines: u32,
5799 y_flipped: bool,
5800 window: &mut Window,
5801 cx: &mut Context<Editor>,
5802 ) -> Option<AnyElement> {
5803 let menu = self.context_menu.borrow();
5804 let menu = menu.as_ref()?;
5805 if !menu.visible() {
5806 return None;
5807 };
5808 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
5809 }
5810
5811 fn render_context_menu_aside(
5812 &self,
5813 style: &EditorStyle,
5814 max_size: Size<Pixels>,
5815 cx: &mut Context<Editor>,
5816 ) -> Option<AnyElement> {
5817 self.context_menu.borrow().as_ref().and_then(|menu| {
5818 if menu.visible() {
5819 menu.render_aside(
5820 style,
5821 max_size,
5822 self.workspace.as_ref().map(|(w, _)| w.clone()),
5823 cx,
5824 )
5825 } else {
5826 None
5827 }
5828 })
5829 }
5830
5831 fn hide_context_menu(
5832 &mut self,
5833 window: &mut Window,
5834 cx: &mut Context<Self>,
5835 ) -> Option<CodeContextMenu> {
5836 cx.notify();
5837 self.completion_tasks.clear();
5838 let context_menu = self.context_menu.borrow_mut().take();
5839 self.stale_inline_completion_in_menu.take();
5840 if context_menu.is_some() {
5841 self.update_visible_inline_completion(window, cx);
5842 }
5843 context_menu
5844 }
5845
5846 fn show_snippet_choices(
5847 &mut self,
5848 choices: &Vec<String>,
5849 selection: Range<Anchor>,
5850 cx: &mut Context<Self>,
5851 ) {
5852 if selection.start.buffer_id.is_none() {
5853 return;
5854 }
5855 let buffer_id = selection.start.buffer_id.unwrap();
5856 let buffer = self.buffer().read(cx).buffer(buffer_id);
5857 let id = post_inc(&mut self.next_completion_id);
5858
5859 if let Some(buffer) = buffer {
5860 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5861 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5862 ));
5863 }
5864 }
5865
5866 pub fn insert_snippet(
5867 &mut self,
5868 insertion_ranges: &[Range<usize>],
5869 snippet: Snippet,
5870 window: &mut Window,
5871 cx: &mut Context<Self>,
5872 ) -> Result<()> {
5873 struct Tabstop<T> {
5874 is_end_tabstop: bool,
5875 ranges: Vec<Range<T>>,
5876 choices: Option<Vec<String>>,
5877 }
5878
5879 let tabstops = self.buffer.update(cx, |buffer, cx| {
5880 let snippet_text: Arc<str> = snippet.text.clone().into();
5881 buffer.edit(
5882 insertion_ranges
5883 .iter()
5884 .cloned()
5885 .map(|range| (range, snippet_text.clone())),
5886 Some(AutoindentMode::EachLine),
5887 cx,
5888 );
5889
5890 let snapshot = &*buffer.read(cx);
5891 let snippet = &snippet;
5892 snippet
5893 .tabstops
5894 .iter()
5895 .map(|tabstop| {
5896 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5897 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5898 });
5899 let mut tabstop_ranges = tabstop
5900 .ranges
5901 .iter()
5902 .flat_map(|tabstop_range| {
5903 let mut delta = 0_isize;
5904 insertion_ranges.iter().map(move |insertion_range| {
5905 let insertion_start = insertion_range.start as isize + delta;
5906 delta +=
5907 snippet.text.len() as isize - insertion_range.len() as isize;
5908
5909 let start = ((insertion_start + tabstop_range.start) as usize)
5910 .min(snapshot.len());
5911 let end = ((insertion_start + tabstop_range.end) as usize)
5912 .min(snapshot.len());
5913 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5914 })
5915 })
5916 .collect::<Vec<_>>();
5917 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5918
5919 Tabstop {
5920 is_end_tabstop,
5921 ranges: tabstop_ranges,
5922 choices: tabstop.choices.clone(),
5923 }
5924 })
5925 .collect::<Vec<_>>()
5926 });
5927 if let Some(tabstop) = tabstops.first() {
5928 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
5929 s.select_ranges(tabstop.ranges.iter().cloned());
5930 });
5931
5932 if let Some(choices) = &tabstop.choices {
5933 if let Some(selection) = tabstop.ranges.first() {
5934 self.show_snippet_choices(choices, selection.clone(), cx)
5935 }
5936 }
5937
5938 // If we're already at the last tabstop and it's at the end of the snippet,
5939 // we're done, we don't need to keep the state around.
5940 if !tabstop.is_end_tabstop {
5941 let choices = tabstops
5942 .iter()
5943 .map(|tabstop| tabstop.choices.clone())
5944 .collect();
5945
5946 let ranges = tabstops
5947 .into_iter()
5948 .map(|tabstop| tabstop.ranges)
5949 .collect::<Vec<_>>();
5950
5951 self.snippet_stack.push(SnippetState {
5952 active_index: 0,
5953 ranges,
5954 choices,
5955 });
5956 }
5957
5958 // Check whether the just-entered snippet ends with an auto-closable bracket.
5959 if self.autoclose_regions.is_empty() {
5960 let snapshot = self.buffer.read(cx).snapshot(cx);
5961 for selection in &mut self.selections.all::<Point>(cx) {
5962 let selection_head = selection.head();
5963 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5964 continue;
5965 };
5966
5967 let mut bracket_pair = None;
5968 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5969 let prev_chars = snapshot
5970 .reversed_chars_at(selection_head)
5971 .collect::<String>();
5972 for (pair, enabled) in scope.brackets() {
5973 if enabled
5974 && pair.close
5975 && prev_chars.starts_with(pair.start.as_str())
5976 && next_chars.starts_with(pair.end.as_str())
5977 {
5978 bracket_pair = Some(pair.clone());
5979 break;
5980 }
5981 }
5982 if let Some(pair) = bracket_pair {
5983 let start = snapshot.anchor_after(selection_head);
5984 let end = snapshot.anchor_after(selection_head);
5985 self.autoclose_regions.push(AutocloseRegion {
5986 selection_id: selection.id,
5987 range: start..end,
5988 pair,
5989 });
5990 }
5991 }
5992 }
5993 }
5994 Ok(())
5995 }
5996
5997 pub fn move_to_next_snippet_tabstop(
5998 &mut self,
5999 window: &mut Window,
6000 cx: &mut Context<Self>,
6001 ) -> bool {
6002 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6003 }
6004
6005 pub fn move_to_prev_snippet_tabstop(
6006 &mut self,
6007 window: &mut Window,
6008 cx: &mut Context<Self>,
6009 ) -> bool {
6010 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6011 }
6012
6013 pub fn move_to_snippet_tabstop(
6014 &mut self,
6015 bias: Bias,
6016 window: &mut Window,
6017 cx: &mut Context<Self>,
6018 ) -> bool {
6019 if let Some(mut snippet) = self.snippet_stack.pop() {
6020 match bias {
6021 Bias::Left => {
6022 if snippet.active_index > 0 {
6023 snippet.active_index -= 1;
6024 } else {
6025 self.snippet_stack.push(snippet);
6026 return false;
6027 }
6028 }
6029 Bias::Right => {
6030 if snippet.active_index + 1 < snippet.ranges.len() {
6031 snippet.active_index += 1;
6032 } else {
6033 self.snippet_stack.push(snippet);
6034 return false;
6035 }
6036 }
6037 }
6038 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6039 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6040 s.select_anchor_ranges(current_ranges.iter().cloned())
6041 });
6042
6043 if let Some(choices) = &snippet.choices[snippet.active_index] {
6044 if let Some(selection) = current_ranges.first() {
6045 self.show_snippet_choices(&choices, selection.clone(), cx);
6046 }
6047 }
6048
6049 // If snippet state is not at the last tabstop, push it back on the stack
6050 if snippet.active_index + 1 < snippet.ranges.len() {
6051 self.snippet_stack.push(snippet);
6052 }
6053 return true;
6054 }
6055 }
6056
6057 false
6058 }
6059
6060 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6061 self.transact(window, cx, |this, window, cx| {
6062 this.select_all(&SelectAll, window, cx);
6063 this.insert("", window, cx);
6064 });
6065 }
6066
6067 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6068 self.transact(window, cx, |this, window, cx| {
6069 this.select_autoclose_pair(window, cx);
6070 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6071 if !this.linked_edit_ranges.is_empty() {
6072 let selections = this.selections.all::<MultiBufferPoint>(cx);
6073 let snapshot = this.buffer.read(cx).snapshot(cx);
6074
6075 for selection in selections.iter() {
6076 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6077 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6078 if selection_start.buffer_id != selection_end.buffer_id {
6079 continue;
6080 }
6081 if let Some(ranges) =
6082 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6083 {
6084 for (buffer, entries) in ranges {
6085 linked_ranges.entry(buffer).or_default().extend(entries);
6086 }
6087 }
6088 }
6089 }
6090
6091 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6092 if !this.selections.line_mode {
6093 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6094 for selection in &mut selections {
6095 if selection.is_empty() {
6096 let old_head = selection.head();
6097 let mut new_head =
6098 movement::left(&display_map, old_head.to_display_point(&display_map))
6099 .to_point(&display_map);
6100 if let Some((buffer, line_buffer_range)) = display_map
6101 .buffer_snapshot
6102 .buffer_line_for_row(MultiBufferRow(old_head.row))
6103 {
6104 let indent_size =
6105 buffer.indent_size_for_line(line_buffer_range.start.row);
6106 let indent_len = match indent_size.kind {
6107 IndentKind::Space => {
6108 buffer.settings_at(line_buffer_range.start, cx).tab_size
6109 }
6110 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6111 };
6112 if old_head.column <= indent_size.len && old_head.column > 0 {
6113 let indent_len = indent_len.get();
6114 new_head = cmp::min(
6115 new_head,
6116 MultiBufferPoint::new(
6117 old_head.row,
6118 ((old_head.column - 1) / indent_len) * indent_len,
6119 ),
6120 );
6121 }
6122 }
6123
6124 selection.set_head(new_head, SelectionGoal::None);
6125 }
6126 }
6127 }
6128
6129 this.signature_help_state.set_backspace_pressed(true);
6130 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6131 s.select(selections)
6132 });
6133 this.insert("", window, cx);
6134 let empty_str: Arc<str> = Arc::from("");
6135 for (buffer, edits) in linked_ranges {
6136 let snapshot = buffer.read(cx).snapshot();
6137 use text::ToPoint as TP;
6138
6139 let edits = edits
6140 .into_iter()
6141 .map(|range| {
6142 let end_point = TP::to_point(&range.end, &snapshot);
6143 let mut start_point = TP::to_point(&range.start, &snapshot);
6144
6145 if end_point == start_point {
6146 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6147 .saturating_sub(1);
6148 start_point =
6149 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6150 };
6151
6152 (start_point..end_point, empty_str.clone())
6153 })
6154 .sorted_by_key(|(range, _)| range.start)
6155 .collect::<Vec<_>>();
6156 buffer.update(cx, |this, cx| {
6157 this.edit(edits, None, cx);
6158 })
6159 }
6160 this.refresh_inline_completion(true, false, window, cx);
6161 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6162 });
6163 }
6164
6165 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6166 self.transact(window, cx, |this, window, cx| {
6167 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6168 let line_mode = s.line_mode;
6169 s.move_with(|map, selection| {
6170 if selection.is_empty() && !line_mode {
6171 let cursor = movement::right(map, selection.head());
6172 selection.end = cursor;
6173 selection.reversed = true;
6174 selection.goal = SelectionGoal::None;
6175 }
6176 })
6177 });
6178 this.insert("", window, cx);
6179 this.refresh_inline_completion(true, false, window, cx);
6180 });
6181 }
6182
6183 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6184 if self.move_to_prev_snippet_tabstop(window, cx) {
6185 return;
6186 }
6187
6188 self.outdent(&Outdent, window, cx);
6189 }
6190
6191 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6192 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6193 return;
6194 }
6195
6196 let mut selections = self.selections.all_adjusted(cx);
6197 let buffer = self.buffer.read(cx);
6198 let snapshot = buffer.snapshot(cx);
6199 let rows_iter = selections.iter().map(|s| s.head().row);
6200 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6201
6202 let mut edits = Vec::new();
6203 let mut prev_edited_row = 0;
6204 let mut row_delta = 0;
6205 for selection in &mut selections {
6206 if selection.start.row != prev_edited_row {
6207 row_delta = 0;
6208 }
6209 prev_edited_row = selection.end.row;
6210
6211 // If the selection is non-empty, then increase the indentation of the selected lines.
6212 if !selection.is_empty() {
6213 row_delta =
6214 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6215 continue;
6216 }
6217
6218 // If the selection is empty and the cursor is in the leading whitespace before the
6219 // suggested indentation, then auto-indent the line.
6220 let cursor = selection.head();
6221 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6222 if let Some(suggested_indent) =
6223 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6224 {
6225 if cursor.column < suggested_indent.len
6226 && cursor.column <= current_indent.len
6227 && current_indent.len <= suggested_indent.len
6228 {
6229 selection.start = Point::new(cursor.row, suggested_indent.len);
6230 selection.end = selection.start;
6231 if row_delta == 0 {
6232 edits.extend(Buffer::edit_for_indent_size_adjustment(
6233 cursor.row,
6234 current_indent,
6235 suggested_indent,
6236 ));
6237 row_delta = suggested_indent.len - current_indent.len;
6238 }
6239 continue;
6240 }
6241 }
6242
6243 // Otherwise, insert a hard or soft tab.
6244 let settings = buffer.settings_at(cursor, cx);
6245 let tab_size = if settings.hard_tabs {
6246 IndentSize::tab()
6247 } else {
6248 let tab_size = settings.tab_size.get();
6249 let char_column = snapshot
6250 .text_for_range(Point::new(cursor.row, 0)..cursor)
6251 .flat_map(str::chars)
6252 .count()
6253 + row_delta as usize;
6254 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6255 IndentSize::spaces(chars_to_next_tab_stop)
6256 };
6257 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6258 selection.end = selection.start;
6259 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6260 row_delta += tab_size.len;
6261 }
6262
6263 self.transact(window, cx, |this, window, cx| {
6264 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6265 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6266 s.select(selections)
6267 });
6268 this.refresh_inline_completion(true, false, window, cx);
6269 });
6270 }
6271
6272 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6273 if self.read_only(cx) {
6274 return;
6275 }
6276 let mut selections = self.selections.all::<Point>(cx);
6277 let mut prev_edited_row = 0;
6278 let mut row_delta = 0;
6279 let mut edits = Vec::new();
6280 let buffer = self.buffer.read(cx);
6281 let snapshot = buffer.snapshot(cx);
6282 for selection in &mut selections {
6283 if selection.start.row != prev_edited_row {
6284 row_delta = 0;
6285 }
6286 prev_edited_row = selection.end.row;
6287
6288 row_delta =
6289 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6290 }
6291
6292 self.transact(window, cx, |this, window, cx| {
6293 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6294 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6295 s.select(selections)
6296 });
6297 });
6298 }
6299
6300 fn indent_selection(
6301 buffer: &MultiBuffer,
6302 snapshot: &MultiBufferSnapshot,
6303 selection: &mut Selection<Point>,
6304 edits: &mut Vec<(Range<Point>, String)>,
6305 delta_for_start_row: u32,
6306 cx: &App,
6307 ) -> u32 {
6308 let settings = buffer.settings_at(selection.start, cx);
6309 let tab_size = settings.tab_size.get();
6310 let indent_kind = if settings.hard_tabs {
6311 IndentKind::Tab
6312 } else {
6313 IndentKind::Space
6314 };
6315 let mut start_row = selection.start.row;
6316 let mut end_row = selection.end.row + 1;
6317
6318 // If a selection ends at the beginning of a line, don't indent
6319 // that last line.
6320 if selection.end.column == 0 && selection.end.row > selection.start.row {
6321 end_row -= 1;
6322 }
6323
6324 // Avoid re-indenting a row that has already been indented by a
6325 // previous selection, but still update this selection's column
6326 // to reflect that indentation.
6327 if delta_for_start_row > 0 {
6328 start_row += 1;
6329 selection.start.column += delta_for_start_row;
6330 if selection.end.row == selection.start.row {
6331 selection.end.column += delta_for_start_row;
6332 }
6333 }
6334
6335 let mut delta_for_end_row = 0;
6336 let has_multiple_rows = start_row + 1 != end_row;
6337 for row in start_row..end_row {
6338 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6339 let indent_delta = match (current_indent.kind, indent_kind) {
6340 (IndentKind::Space, IndentKind::Space) => {
6341 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6342 IndentSize::spaces(columns_to_next_tab_stop)
6343 }
6344 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6345 (_, IndentKind::Tab) => IndentSize::tab(),
6346 };
6347
6348 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6349 0
6350 } else {
6351 selection.start.column
6352 };
6353 let row_start = Point::new(row, start);
6354 edits.push((
6355 row_start..row_start,
6356 indent_delta.chars().collect::<String>(),
6357 ));
6358
6359 // Update this selection's endpoints to reflect the indentation.
6360 if row == selection.start.row {
6361 selection.start.column += indent_delta.len;
6362 }
6363 if row == selection.end.row {
6364 selection.end.column += indent_delta.len;
6365 delta_for_end_row = indent_delta.len;
6366 }
6367 }
6368
6369 if selection.start.row == selection.end.row {
6370 delta_for_start_row + delta_for_end_row
6371 } else {
6372 delta_for_end_row
6373 }
6374 }
6375
6376 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6377 if self.read_only(cx) {
6378 return;
6379 }
6380 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6381 let selections = self.selections.all::<Point>(cx);
6382 let mut deletion_ranges = Vec::new();
6383 let mut last_outdent = None;
6384 {
6385 let buffer = self.buffer.read(cx);
6386 let snapshot = buffer.snapshot(cx);
6387 for selection in &selections {
6388 let settings = buffer.settings_at(selection.start, cx);
6389 let tab_size = settings.tab_size.get();
6390 let mut rows = selection.spanned_rows(false, &display_map);
6391
6392 // Avoid re-outdenting a row that has already been outdented by a
6393 // previous selection.
6394 if let Some(last_row) = last_outdent {
6395 if last_row == rows.start {
6396 rows.start = rows.start.next_row();
6397 }
6398 }
6399 let has_multiple_rows = rows.len() > 1;
6400 for row in rows.iter_rows() {
6401 let indent_size = snapshot.indent_size_for_line(row);
6402 if indent_size.len > 0 {
6403 let deletion_len = match indent_size.kind {
6404 IndentKind::Space => {
6405 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6406 if columns_to_prev_tab_stop == 0 {
6407 tab_size
6408 } else {
6409 columns_to_prev_tab_stop
6410 }
6411 }
6412 IndentKind::Tab => 1,
6413 };
6414 let start = if has_multiple_rows
6415 || deletion_len > selection.start.column
6416 || indent_size.len < selection.start.column
6417 {
6418 0
6419 } else {
6420 selection.start.column - deletion_len
6421 };
6422 deletion_ranges.push(
6423 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6424 );
6425 last_outdent = Some(row);
6426 }
6427 }
6428 }
6429 }
6430
6431 self.transact(window, cx, |this, window, cx| {
6432 this.buffer.update(cx, |buffer, cx| {
6433 let empty_str: Arc<str> = Arc::default();
6434 buffer.edit(
6435 deletion_ranges
6436 .into_iter()
6437 .map(|range| (range, empty_str.clone())),
6438 None,
6439 cx,
6440 );
6441 });
6442 let selections = this.selections.all::<usize>(cx);
6443 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6444 s.select(selections)
6445 });
6446 });
6447 }
6448
6449 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6450 if self.read_only(cx) {
6451 return;
6452 }
6453 let selections = self
6454 .selections
6455 .all::<usize>(cx)
6456 .into_iter()
6457 .map(|s| s.range());
6458
6459 self.transact(window, cx, |this, window, cx| {
6460 this.buffer.update(cx, |buffer, cx| {
6461 buffer.autoindent_ranges(selections, cx);
6462 });
6463 let selections = this.selections.all::<usize>(cx);
6464 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6465 s.select(selections)
6466 });
6467 });
6468 }
6469
6470 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6471 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6472 let selections = self.selections.all::<Point>(cx);
6473
6474 let mut new_cursors = Vec::new();
6475 let mut edit_ranges = Vec::new();
6476 let mut selections = selections.iter().peekable();
6477 while let Some(selection) = selections.next() {
6478 let mut rows = selection.spanned_rows(false, &display_map);
6479 let goal_display_column = selection.head().to_display_point(&display_map).column();
6480
6481 // Accumulate contiguous regions of rows that we want to delete.
6482 while let Some(next_selection) = selections.peek() {
6483 let next_rows = next_selection.spanned_rows(false, &display_map);
6484 if next_rows.start <= rows.end {
6485 rows.end = next_rows.end;
6486 selections.next().unwrap();
6487 } else {
6488 break;
6489 }
6490 }
6491
6492 let buffer = &display_map.buffer_snapshot;
6493 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6494 let edit_end;
6495 let cursor_buffer_row;
6496 if buffer.max_point().row >= rows.end.0 {
6497 // If there's a line after the range, delete the \n from the end of the row range
6498 // and position the cursor on the next line.
6499 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6500 cursor_buffer_row = rows.end;
6501 } else {
6502 // If there isn't a line after the range, delete the \n from the line before the
6503 // start of the row range and position the cursor there.
6504 edit_start = edit_start.saturating_sub(1);
6505 edit_end = buffer.len();
6506 cursor_buffer_row = rows.start.previous_row();
6507 }
6508
6509 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6510 *cursor.column_mut() =
6511 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6512
6513 new_cursors.push((
6514 selection.id,
6515 buffer.anchor_after(cursor.to_point(&display_map)),
6516 ));
6517 edit_ranges.push(edit_start..edit_end);
6518 }
6519
6520 self.transact(window, cx, |this, window, cx| {
6521 let buffer = this.buffer.update(cx, |buffer, cx| {
6522 let empty_str: Arc<str> = Arc::default();
6523 buffer.edit(
6524 edit_ranges
6525 .into_iter()
6526 .map(|range| (range, empty_str.clone())),
6527 None,
6528 cx,
6529 );
6530 buffer.snapshot(cx)
6531 });
6532 let new_selections = new_cursors
6533 .into_iter()
6534 .map(|(id, cursor)| {
6535 let cursor = cursor.to_point(&buffer);
6536 Selection {
6537 id,
6538 start: cursor,
6539 end: cursor,
6540 reversed: false,
6541 goal: SelectionGoal::None,
6542 }
6543 })
6544 .collect();
6545
6546 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6547 s.select(new_selections);
6548 });
6549 });
6550 }
6551
6552 pub fn join_lines_impl(
6553 &mut self,
6554 insert_whitespace: bool,
6555 window: &mut Window,
6556 cx: &mut Context<Self>,
6557 ) {
6558 if self.read_only(cx) {
6559 return;
6560 }
6561 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6562 for selection in self.selections.all::<Point>(cx) {
6563 let start = MultiBufferRow(selection.start.row);
6564 // Treat single line selections as if they include the next line. Otherwise this action
6565 // would do nothing for single line selections individual cursors.
6566 let end = if selection.start.row == selection.end.row {
6567 MultiBufferRow(selection.start.row + 1)
6568 } else {
6569 MultiBufferRow(selection.end.row)
6570 };
6571
6572 if let Some(last_row_range) = row_ranges.last_mut() {
6573 if start <= last_row_range.end {
6574 last_row_range.end = end;
6575 continue;
6576 }
6577 }
6578 row_ranges.push(start..end);
6579 }
6580
6581 let snapshot = self.buffer.read(cx).snapshot(cx);
6582 let mut cursor_positions = Vec::new();
6583 for row_range in &row_ranges {
6584 let anchor = snapshot.anchor_before(Point::new(
6585 row_range.end.previous_row().0,
6586 snapshot.line_len(row_range.end.previous_row()),
6587 ));
6588 cursor_positions.push(anchor..anchor);
6589 }
6590
6591 self.transact(window, cx, |this, window, cx| {
6592 for row_range in row_ranges.into_iter().rev() {
6593 for row in row_range.iter_rows().rev() {
6594 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6595 let next_line_row = row.next_row();
6596 let indent = snapshot.indent_size_for_line(next_line_row);
6597 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6598
6599 let replace =
6600 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6601 " "
6602 } else {
6603 ""
6604 };
6605
6606 this.buffer.update(cx, |buffer, cx| {
6607 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6608 });
6609 }
6610 }
6611
6612 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6613 s.select_anchor_ranges(cursor_positions)
6614 });
6615 });
6616 }
6617
6618 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6619 self.join_lines_impl(true, window, cx);
6620 }
6621
6622 pub fn sort_lines_case_sensitive(
6623 &mut self,
6624 _: &SortLinesCaseSensitive,
6625 window: &mut Window,
6626 cx: &mut Context<Self>,
6627 ) {
6628 self.manipulate_lines(window, cx, |lines| lines.sort())
6629 }
6630
6631 pub fn sort_lines_case_insensitive(
6632 &mut self,
6633 _: &SortLinesCaseInsensitive,
6634 window: &mut Window,
6635 cx: &mut Context<Self>,
6636 ) {
6637 self.manipulate_lines(window, cx, |lines| {
6638 lines.sort_by_key(|line| line.to_lowercase())
6639 })
6640 }
6641
6642 pub fn unique_lines_case_insensitive(
6643 &mut self,
6644 _: &UniqueLinesCaseInsensitive,
6645 window: &mut Window,
6646 cx: &mut Context<Self>,
6647 ) {
6648 self.manipulate_lines(window, cx, |lines| {
6649 let mut seen = HashSet::default();
6650 lines.retain(|line| seen.insert(line.to_lowercase()));
6651 })
6652 }
6653
6654 pub fn unique_lines_case_sensitive(
6655 &mut self,
6656 _: &UniqueLinesCaseSensitive,
6657 window: &mut Window,
6658 cx: &mut Context<Self>,
6659 ) {
6660 self.manipulate_lines(window, cx, |lines| {
6661 let mut seen = HashSet::default();
6662 lines.retain(|line| seen.insert(*line));
6663 })
6664 }
6665
6666 pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
6667 let mut revert_changes = HashMap::default();
6668 let snapshot = self.snapshot(window, cx);
6669 for hunk in snapshot
6670 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
6671 {
6672 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6673 }
6674 if !revert_changes.is_empty() {
6675 self.transact(window, cx, |editor, window, cx| {
6676 editor.revert(revert_changes, window, cx);
6677 });
6678 }
6679 }
6680
6681 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
6682 let Some(project) = self.project.clone() else {
6683 return;
6684 };
6685 self.reload(project, window, cx)
6686 .detach_and_notify_err(window, cx);
6687 }
6688
6689 pub fn revert_selected_hunks(
6690 &mut self,
6691 _: &RevertSelectedHunks,
6692 window: &mut Window,
6693 cx: &mut Context<Self>,
6694 ) {
6695 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
6696 self.revert_hunks_in_ranges(selections, window, cx);
6697 }
6698
6699 fn revert_hunks_in_ranges(
6700 &mut self,
6701 ranges: impl Iterator<Item = Range<Point>>,
6702 window: &mut Window,
6703 cx: &mut Context<Editor>,
6704 ) {
6705 let mut revert_changes = HashMap::default();
6706 let snapshot = self.snapshot(window, cx);
6707 for hunk in &snapshot.hunks_for_ranges(ranges) {
6708 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6709 }
6710 if !revert_changes.is_empty() {
6711 self.transact(window, cx, |editor, window, cx| {
6712 editor.revert(revert_changes, window, cx);
6713 });
6714 }
6715 }
6716
6717 pub fn open_active_item_in_terminal(
6718 &mut self,
6719 _: &OpenInTerminal,
6720 window: &mut Window,
6721 cx: &mut Context<Self>,
6722 ) {
6723 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6724 let project_path = buffer.read(cx).project_path(cx)?;
6725 let project = self.project.as_ref()?.read(cx);
6726 let entry = project.entry_for_path(&project_path, cx)?;
6727 let parent = match &entry.canonical_path {
6728 Some(canonical_path) => canonical_path.to_path_buf(),
6729 None => project.absolute_path(&project_path, cx)?,
6730 }
6731 .parent()?
6732 .to_path_buf();
6733 Some(parent)
6734 }) {
6735 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
6736 }
6737 }
6738
6739 pub fn prepare_revert_change(
6740 &self,
6741 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6742 hunk: &MultiBufferDiffHunk,
6743 cx: &mut App,
6744 ) -> Option<()> {
6745 let buffer = self.buffer.read(cx);
6746 let change_set = buffer.change_set_for(hunk.buffer_id)?;
6747 let buffer = buffer.buffer(hunk.buffer_id)?;
6748 let buffer = buffer.read(cx);
6749 let original_text = change_set
6750 .read(cx)
6751 .base_text
6752 .as_ref()?
6753 .as_rope()
6754 .slice(hunk.diff_base_byte_range.clone());
6755 let buffer_snapshot = buffer.snapshot();
6756 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6757 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6758 probe
6759 .0
6760 .start
6761 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6762 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6763 }) {
6764 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6765 Some(())
6766 } else {
6767 None
6768 }
6769 }
6770
6771 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
6772 self.manipulate_lines(window, cx, |lines| lines.reverse())
6773 }
6774
6775 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
6776 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
6777 }
6778
6779 fn manipulate_lines<Fn>(
6780 &mut self,
6781 window: &mut Window,
6782 cx: &mut Context<Self>,
6783 mut callback: Fn,
6784 ) where
6785 Fn: FnMut(&mut Vec<&str>),
6786 {
6787 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6788 let buffer = self.buffer.read(cx).snapshot(cx);
6789
6790 let mut edits = Vec::new();
6791
6792 let selections = self.selections.all::<Point>(cx);
6793 let mut selections = selections.iter().peekable();
6794 let mut contiguous_row_selections = Vec::new();
6795 let mut new_selections = Vec::new();
6796 let mut added_lines = 0;
6797 let mut removed_lines = 0;
6798
6799 while let Some(selection) = selections.next() {
6800 let (start_row, end_row) = consume_contiguous_rows(
6801 &mut contiguous_row_selections,
6802 selection,
6803 &display_map,
6804 &mut selections,
6805 );
6806
6807 let start_point = Point::new(start_row.0, 0);
6808 let end_point = Point::new(
6809 end_row.previous_row().0,
6810 buffer.line_len(end_row.previous_row()),
6811 );
6812 let text = buffer
6813 .text_for_range(start_point..end_point)
6814 .collect::<String>();
6815
6816 let mut lines = text.split('\n').collect_vec();
6817
6818 let lines_before = lines.len();
6819 callback(&mut lines);
6820 let lines_after = lines.len();
6821
6822 edits.push((start_point..end_point, lines.join("\n")));
6823
6824 // Selections must change based on added and removed line count
6825 let start_row =
6826 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6827 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6828 new_selections.push(Selection {
6829 id: selection.id,
6830 start: start_row,
6831 end: end_row,
6832 goal: SelectionGoal::None,
6833 reversed: selection.reversed,
6834 });
6835
6836 if lines_after > lines_before {
6837 added_lines += lines_after - lines_before;
6838 } else if lines_before > lines_after {
6839 removed_lines += lines_before - lines_after;
6840 }
6841 }
6842
6843 self.transact(window, cx, |this, window, cx| {
6844 let buffer = this.buffer.update(cx, |buffer, cx| {
6845 buffer.edit(edits, None, cx);
6846 buffer.snapshot(cx)
6847 });
6848
6849 // Recalculate offsets on newly edited buffer
6850 let new_selections = new_selections
6851 .iter()
6852 .map(|s| {
6853 let start_point = Point::new(s.start.0, 0);
6854 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6855 Selection {
6856 id: s.id,
6857 start: buffer.point_to_offset(start_point),
6858 end: buffer.point_to_offset(end_point),
6859 goal: s.goal,
6860 reversed: s.reversed,
6861 }
6862 })
6863 .collect();
6864
6865 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6866 s.select(new_selections);
6867 });
6868
6869 this.request_autoscroll(Autoscroll::fit(), cx);
6870 });
6871 }
6872
6873 pub fn convert_to_upper_case(
6874 &mut self,
6875 _: &ConvertToUpperCase,
6876 window: &mut Window,
6877 cx: &mut Context<Self>,
6878 ) {
6879 self.manipulate_text(window, cx, |text| text.to_uppercase())
6880 }
6881
6882 pub fn convert_to_lower_case(
6883 &mut self,
6884 _: &ConvertToLowerCase,
6885 window: &mut Window,
6886 cx: &mut Context<Self>,
6887 ) {
6888 self.manipulate_text(window, cx, |text| text.to_lowercase())
6889 }
6890
6891 pub fn convert_to_title_case(
6892 &mut self,
6893 _: &ConvertToTitleCase,
6894 window: &mut Window,
6895 cx: &mut Context<Self>,
6896 ) {
6897 self.manipulate_text(window, cx, |text| {
6898 text.split('\n')
6899 .map(|line| line.to_case(Case::Title))
6900 .join("\n")
6901 })
6902 }
6903
6904 pub fn convert_to_snake_case(
6905 &mut self,
6906 _: &ConvertToSnakeCase,
6907 window: &mut Window,
6908 cx: &mut Context<Self>,
6909 ) {
6910 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
6911 }
6912
6913 pub fn convert_to_kebab_case(
6914 &mut self,
6915 _: &ConvertToKebabCase,
6916 window: &mut Window,
6917 cx: &mut Context<Self>,
6918 ) {
6919 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
6920 }
6921
6922 pub fn convert_to_upper_camel_case(
6923 &mut self,
6924 _: &ConvertToUpperCamelCase,
6925 window: &mut Window,
6926 cx: &mut Context<Self>,
6927 ) {
6928 self.manipulate_text(window, cx, |text| {
6929 text.split('\n')
6930 .map(|line| line.to_case(Case::UpperCamel))
6931 .join("\n")
6932 })
6933 }
6934
6935 pub fn convert_to_lower_camel_case(
6936 &mut self,
6937 _: &ConvertToLowerCamelCase,
6938 window: &mut Window,
6939 cx: &mut Context<Self>,
6940 ) {
6941 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
6942 }
6943
6944 pub fn convert_to_opposite_case(
6945 &mut self,
6946 _: &ConvertToOppositeCase,
6947 window: &mut Window,
6948 cx: &mut Context<Self>,
6949 ) {
6950 self.manipulate_text(window, cx, |text| {
6951 text.chars()
6952 .fold(String::with_capacity(text.len()), |mut t, c| {
6953 if c.is_uppercase() {
6954 t.extend(c.to_lowercase());
6955 } else {
6956 t.extend(c.to_uppercase());
6957 }
6958 t
6959 })
6960 })
6961 }
6962
6963 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
6964 where
6965 Fn: FnMut(&str) -> String,
6966 {
6967 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6968 let buffer = self.buffer.read(cx).snapshot(cx);
6969
6970 let mut new_selections = Vec::new();
6971 let mut edits = Vec::new();
6972 let mut selection_adjustment = 0i32;
6973
6974 for selection in self.selections.all::<usize>(cx) {
6975 let selection_is_empty = selection.is_empty();
6976
6977 let (start, end) = if selection_is_empty {
6978 let word_range = movement::surrounding_word(
6979 &display_map,
6980 selection.start.to_display_point(&display_map),
6981 );
6982 let start = word_range.start.to_offset(&display_map, Bias::Left);
6983 let end = word_range.end.to_offset(&display_map, Bias::Left);
6984 (start, end)
6985 } else {
6986 (selection.start, selection.end)
6987 };
6988
6989 let text = buffer.text_for_range(start..end).collect::<String>();
6990 let old_length = text.len() as i32;
6991 let text = callback(&text);
6992
6993 new_selections.push(Selection {
6994 start: (start as i32 - selection_adjustment) as usize,
6995 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6996 goal: SelectionGoal::None,
6997 ..selection
6998 });
6999
7000 selection_adjustment += old_length - text.len() as i32;
7001
7002 edits.push((start..end, text));
7003 }
7004
7005 self.transact(window, cx, |this, window, cx| {
7006 this.buffer.update(cx, |buffer, cx| {
7007 buffer.edit(edits, None, cx);
7008 });
7009
7010 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7011 s.select(new_selections);
7012 });
7013
7014 this.request_autoscroll(Autoscroll::fit(), cx);
7015 });
7016 }
7017
7018 pub fn duplicate(
7019 &mut self,
7020 upwards: bool,
7021 whole_lines: bool,
7022 window: &mut Window,
7023 cx: &mut Context<Self>,
7024 ) {
7025 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7026 let buffer = &display_map.buffer_snapshot;
7027 let selections = self.selections.all::<Point>(cx);
7028
7029 let mut edits = Vec::new();
7030 let mut selections_iter = selections.iter().peekable();
7031 while let Some(selection) = selections_iter.next() {
7032 let mut rows = selection.spanned_rows(false, &display_map);
7033 // duplicate line-wise
7034 if whole_lines || selection.start == selection.end {
7035 // Avoid duplicating the same lines twice.
7036 while let Some(next_selection) = selections_iter.peek() {
7037 let next_rows = next_selection.spanned_rows(false, &display_map);
7038 if next_rows.start < rows.end {
7039 rows.end = next_rows.end;
7040 selections_iter.next().unwrap();
7041 } else {
7042 break;
7043 }
7044 }
7045
7046 // Copy the text from the selected row region and splice it either at the start
7047 // or end of the region.
7048 let start = Point::new(rows.start.0, 0);
7049 let end = Point::new(
7050 rows.end.previous_row().0,
7051 buffer.line_len(rows.end.previous_row()),
7052 );
7053 let text = buffer
7054 .text_for_range(start..end)
7055 .chain(Some("\n"))
7056 .collect::<String>();
7057 let insert_location = if upwards {
7058 Point::new(rows.end.0, 0)
7059 } else {
7060 start
7061 };
7062 edits.push((insert_location..insert_location, text));
7063 } else {
7064 // duplicate character-wise
7065 let start = selection.start;
7066 let end = selection.end;
7067 let text = buffer.text_for_range(start..end).collect::<String>();
7068 edits.push((selection.end..selection.end, text));
7069 }
7070 }
7071
7072 self.transact(window, cx, |this, _, cx| {
7073 this.buffer.update(cx, |buffer, cx| {
7074 buffer.edit(edits, None, cx);
7075 });
7076
7077 this.request_autoscroll(Autoscroll::fit(), cx);
7078 });
7079 }
7080
7081 pub fn duplicate_line_up(
7082 &mut self,
7083 _: &DuplicateLineUp,
7084 window: &mut Window,
7085 cx: &mut Context<Self>,
7086 ) {
7087 self.duplicate(true, true, window, cx);
7088 }
7089
7090 pub fn duplicate_line_down(
7091 &mut self,
7092 _: &DuplicateLineDown,
7093 window: &mut Window,
7094 cx: &mut Context<Self>,
7095 ) {
7096 self.duplicate(false, true, window, cx);
7097 }
7098
7099 pub fn duplicate_selection(
7100 &mut self,
7101 _: &DuplicateSelection,
7102 window: &mut Window,
7103 cx: &mut Context<Self>,
7104 ) {
7105 self.duplicate(false, false, window, cx);
7106 }
7107
7108 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7109 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7110 let buffer = self.buffer.read(cx).snapshot(cx);
7111
7112 let mut edits = Vec::new();
7113 let mut unfold_ranges = Vec::new();
7114 let mut refold_creases = Vec::new();
7115
7116 let selections = self.selections.all::<Point>(cx);
7117 let mut selections = selections.iter().peekable();
7118 let mut contiguous_row_selections = Vec::new();
7119 let mut new_selections = Vec::new();
7120
7121 while let Some(selection) = selections.next() {
7122 // Find all the selections that span a contiguous row range
7123 let (start_row, end_row) = consume_contiguous_rows(
7124 &mut contiguous_row_selections,
7125 selection,
7126 &display_map,
7127 &mut selections,
7128 );
7129
7130 // Move the text spanned by the row range to be before the line preceding the row range
7131 if start_row.0 > 0 {
7132 let range_to_move = Point::new(
7133 start_row.previous_row().0,
7134 buffer.line_len(start_row.previous_row()),
7135 )
7136 ..Point::new(
7137 end_row.previous_row().0,
7138 buffer.line_len(end_row.previous_row()),
7139 );
7140 let insertion_point = display_map
7141 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7142 .0;
7143
7144 // Don't move lines across excerpts
7145 if buffer
7146 .excerpt_containing(insertion_point..range_to_move.end)
7147 .is_some()
7148 {
7149 let text = buffer
7150 .text_for_range(range_to_move.clone())
7151 .flat_map(|s| s.chars())
7152 .skip(1)
7153 .chain(['\n'])
7154 .collect::<String>();
7155
7156 edits.push((
7157 buffer.anchor_after(range_to_move.start)
7158 ..buffer.anchor_before(range_to_move.end),
7159 String::new(),
7160 ));
7161 let insertion_anchor = buffer.anchor_after(insertion_point);
7162 edits.push((insertion_anchor..insertion_anchor, text));
7163
7164 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7165
7166 // Move selections up
7167 new_selections.extend(contiguous_row_selections.drain(..).map(
7168 |mut selection| {
7169 selection.start.row -= row_delta;
7170 selection.end.row -= row_delta;
7171 selection
7172 },
7173 ));
7174
7175 // Move folds up
7176 unfold_ranges.push(range_to_move.clone());
7177 for fold in display_map.folds_in_range(
7178 buffer.anchor_before(range_to_move.start)
7179 ..buffer.anchor_after(range_to_move.end),
7180 ) {
7181 let mut start = fold.range.start.to_point(&buffer);
7182 let mut end = fold.range.end.to_point(&buffer);
7183 start.row -= row_delta;
7184 end.row -= row_delta;
7185 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7186 }
7187 }
7188 }
7189
7190 // If we didn't move line(s), preserve the existing selections
7191 new_selections.append(&mut contiguous_row_selections);
7192 }
7193
7194 self.transact(window, cx, |this, window, cx| {
7195 this.unfold_ranges(&unfold_ranges, true, true, cx);
7196 this.buffer.update(cx, |buffer, cx| {
7197 for (range, text) in edits {
7198 buffer.edit([(range, text)], None, cx);
7199 }
7200 });
7201 this.fold_creases(refold_creases, true, window, cx);
7202 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7203 s.select(new_selections);
7204 })
7205 });
7206 }
7207
7208 pub fn move_line_down(
7209 &mut self,
7210 _: &MoveLineDown,
7211 window: &mut Window,
7212 cx: &mut Context<Self>,
7213 ) {
7214 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7215 let buffer = self.buffer.read(cx).snapshot(cx);
7216
7217 let mut edits = Vec::new();
7218 let mut unfold_ranges = Vec::new();
7219 let mut refold_creases = Vec::new();
7220
7221 let selections = self.selections.all::<Point>(cx);
7222 let mut selections = selections.iter().peekable();
7223 let mut contiguous_row_selections = Vec::new();
7224 let mut new_selections = Vec::new();
7225
7226 while let Some(selection) = selections.next() {
7227 // Find all the selections that span a contiguous row range
7228 let (start_row, end_row) = consume_contiguous_rows(
7229 &mut contiguous_row_selections,
7230 selection,
7231 &display_map,
7232 &mut selections,
7233 );
7234
7235 // Move the text spanned by the row range to be after the last line of the row range
7236 if end_row.0 <= buffer.max_point().row {
7237 let range_to_move =
7238 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7239 let insertion_point = display_map
7240 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7241 .0;
7242
7243 // Don't move lines across excerpt boundaries
7244 if buffer
7245 .excerpt_containing(range_to_move.start..insertion_point)
7246 .is_some()
7247 {
7248 let mut text = String::from("\n");
7249 text.extend(buffer.text_for_range(range_to_move.clone()));
7250 text.pop(); // Drop trailing newline
7251 edits.push((
7252 buffer.anchor_after(range_to_move.start)
7253 ..buffer.anchor_before(range_to_move.end),
7254 String::new(),
7255 ));
7256 let insertion_anchor = buffer.anchor_after(insertion_point);
7257 edits.push((insertion_anchor..insertion_anchor, text));
7258
7259 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7260
7261 // Move selections down
7262 new_selections.extend(contiguous_row_selections.drain(..).map(
7263 |mut selection| {
7264 selection.start.row += row_delta;
7265 selection.end.row += row_delta;
7266 selection
7267 },
7268 ));
7269
7270 // Move folds down
7271 unfold_ranges.push(range_to_move.clone());
7272 for fold in display_map.folds_in_range(
7273 buffer.anchor_before(range_to_move.start)
7274 ..buffer.anchor_after(range_to_move.end),
7275 ) {
7276 let mut start = fold.range.start.to_point(&buffer);
7277 let mut end = fold.range.end.to_point(&buffer);
7278 start.row += row_delta;
7279 end.row += row_delta;
7280 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7281 }
7282 }
7283 }
7284
7285 // If we didn't move line(s), preserve the existing selections
7286 new_selections.append(&mut contiguous_row_selections);
7287 }
7288
7289 self.transact(window, cx, |this, window, cx| {
7290 this.unfold_ranges(&unfold_ranges, true, true, cx);
7291 this.buffer.update(cx, |buffer, cx| {
7292 for (range, text) in edits {
7293 buffer.edit([(range, text)], None, cx);
7294 }
7295 });
7296 this.fold_creases(refold_creases, true, window, cx);
7297 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7298 s.select(new_selections)
7299 });
7300 });
7301 }
7302
7303 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7304 let text_layout_details = &self.text_layout_details(window);
7305 self.transact(window, cx, |this, window, cx| {
7306 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7307 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7308 let line_mode = s.line_mode;
7309 s.move_with(|display_map, selection| {
7310 if !selection.is_empty() || line_mode {
7311 return;
7312 }
7313
7314 let mut head = selection.head();
7315 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7316 if head.column() == display_map.line_len(head.row()) {
7317 transpose_offset = display_map
7318 .buffer_snapshot
7319 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7320 }
7321
7322 if transpose_offset == 0 {
7323 return;
7324 }
7325
7326 *head.column_mut() += 1;
7327 head = display_map.clip_point(head, Bias::Right);
7328 let goal = SelectionGoal::HorizontalPosition(
7329 display_map
7330 .x_for_display_point(head, text_layout_details)
7331 .into(),
7332 );
7333 selection.collapse_to(head, goal);
7334
7335 let transpose_start = display_map
7336 .buffer_snapshot
7337 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7338 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7339 let transpose_end = display_map
7340 .buffer_snapshot
7341 .clip_offset(transpose_offset + 1, Bias::Right);
7342 if let Some(ch) =
7343 display_map.buffer_snapshot.chars_at(transpose_start).next()
7344 {
7345 edits.push((transpose_start..transpose_offset, String::new()));
7346 edits.push((transpose_end..transpose_end, ch.to_string()));
7347 }
7348 }
7349 });
7350 edits
7351 });
7352 this.buffer
7353 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7354 let selections = this.selections.all::<usize>(cx);
7355 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7356 s.select(selections);
7357 });
7358 });
7359 }
7360
7361 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7362 self.rewrap_impl(IsVimMode::No, cx)
7363 }
7364
7365 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7366 let buffer = self.buffer.read(cx).snapshot(cx);
7367 let selections = self.selections.all::<Point>(cx);
7368 let mut selections = selections.iter().peekable();
7369
7370 let mut edits = Vec::new();
7371 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7372
7373 while let Some(selection) = selections.next() {
7374 let mut start_row = selection.start.row;
7375 let mut end_row = selection.end.row;
7376
7377 // Skip selections that overlap with a range that has already been rewrapped.
7378 let selection_range = start_row..end_row;
7379 if rewrapped_row_ranges
7380 .iter()
7381 .any(|range| range.overlaps(&selection_range))
7382 {
7383 continue;
7384 }
7385
7386 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7387
7388 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7389 match language_scope.language_name().as_ref() {
7390 "Markdown" | "Plain Text" => {
7391 should_rewrap = true;
7392 }
7393 _ => {}
7394 }
7395 }
7396
7397 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7398
7399 // Since not all lines in the selection may be at the same indent
7400 // level, choose the indent size that is the most common between all
7401 // of the lines.
7402 //
7403 // If there is a tie, we use the deepest indent.
7404 let (indent_size, indent_end) = {
7405 let mut indent_size_occurrences = HashMap::default();
7406 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7407
7408 for row in start_row..=end_row {
7409 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7410 rows_by_indent_size.entry(indent).or_default().push(row);
7411 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7412 }
7413
7414 let indent_size = indent_size_occurrences
7415 .into_iter()
7416 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7417 .map(|(indent, _)| indent)
7418 .unwrap_or_default();
7419 let row = rows_by_indent_size[&indent_size][0];
7420 let indent_end = Point::new(row, indent_size.len);
7421
7422 (indent_size, indent_end)
7423 };
7424
7425 let mut line_prefix = indent_size.chars().collect::<String>();
7426
7427 if let Some(comment_prefix) =
7428 buffer
7429 .language_scope_at(selection.head())
7430 .and_then(|language| {
7431 language
7432 .line_comment_prefixes()
7433 .iter()
7434 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7435 .cloned()
7436 })
7437 {
7438 line_prefix.push_str(&comment_prefix);
7439 should_rewrap = true;
7440 }
7441
7442 if !should_rewrap {
7443 continue;
7444 }
7445
7446 if selection.is_empty() {
7447 'expand_upwards: while start_row > 0 {
7448 let prev_row = start_row - 1;
7449 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7450 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7451 {
7452 start_row = prev_row;
7453 } else {
7454 break 'expand_upwards;
7455 }
7456 }
7457
7458 'expand_downwards: while end_row < buffer.max_point().row {
7459 let next_row = end_row + 1;
7460 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7461 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7462 {
7463 end_row = next_row;
7464 } else {
7465 break 'expand_downwards;
7466 }
7467 }
7468 }
7469
7470 let start = Point::new(start_row, 0);
7471 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7472 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7473 let Some(lines_without_prefixes) = selection_text
7474 .lines()
7475 .map(|line| {
7476 line.strip_prefix(&line_prefix)
7477 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7478 .ok_or_else(|| {
7479 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7480 })
7481 })
7482 .collect::<Result<Vec<_>, _>>()
7483 .log_err()
7484 else {
7485 continue;
7486 };
7487
7488 let wrap_column = buffer
7489 .settings_at(Point::new(start_row, 0), cx)
7490 .preferred_line_length as usize;
7491 let wrapped_text = wrap_with_prefix(
7492 line_prefix,
7493 lines_without_prefixes.join(" "),
7494 wrap_column,
7495 tab_size,
7496 );
7497
7498 // TODO: should always use char-based diff while still supporting cursor behavior that
7499 // matches vim.
7500 let diff = match is_vim_mode {
7501 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7502 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7503 };
7504 let mut offset = start.to_offset(&buffer);
7505 let mut moved_since_edit = true;
7506
7507 for change in diff.iter_all_changes() {
7508 let value = change.value();
7509 match change.tag() {
7510 ChangeTag::Equal => {
7511 offset += value.len();
7512 moved_since_edit = true;
7513 }
7514 ChangeTag::Delete => {
7515 let start = buffer.anchor_after(offset);
7516 let end = buffer.anchor_before(offset + value.len());
7517
7518 if moved_since_edit {
7519 edits.push((start..end, String::new()));
7520 } else {
7521 edits.last_mut().unwrap().0.end = end;
7522 }
7523
7524 offset += value.len();
7525 moved_since_edit = false;
7526 }
7527 ChangeTag::Insert => {
7528 if moved_since_edit {
7529 let anchor = buffer.anchor_after(offset);
7530 edits.push((anchor..anchor, value.to_string()));
7531 } else {
7532 edits.last_mut().unwrap().1.push_str(value);
7533 }
7534
7535 moved_since_edit = false;
7536 }
7537 }
7538 }
7539
7540 rewrapped_row_ranges.push(start_row..=end_row);
7541 }
7542
7543 self.buffer
7544 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7545 }
7546
7547 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7548 let mut text = String::new();
7549 let buffer = self.buffer.read(cx).snapshot(cx);
7550 let mut selections = self.selections.all::<Point>(cx);
7551 let mut clipboard_selections = Vec::with_capacity(selections.len());
7552 {
7553 let max_point = buffer.max_point();
7554 let mut is_first = true;
7555 for selection in &mut selections {
7556 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7557 if is_entire_line {
7558 selection.start = Point::new(selection.start.row, 0);
7559 if !selection.is_empty() && selection.end.column == 0 {
7560 selection.end = cmp::min(max_point, selection.end);
7561 } else {
7562 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7563 }
7564 selection.goal = SelectionGoal::None;
7565 }
7566 if is_first {
7567 is_first = false;
7568 } else {
7569 text += "\n";
7570 }
7571 let mut len = 0;
7572 for chunk in buffer.text_for_range(selection.start..selection.end) {
7573 text.push_str(chunk);
7574 len += chunk.len();
7575 }
7576 clipboard_selections.push(ClipboardSelection {
7577 len,
7578 is_entire_line,
7579 first_line_indent: buffer
7580 .indent_size_for_line(MultiBufferRow(selection.start.row))
7581 .len,
7582 });
7583 }
7584 }
7585
7586 self.transact(window, cx, |this, window, cx| {
7587 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7588 s.select(selections);
7589 });
7590 this.insert("", window, cx);
7591 });
7592 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7593 }
7594
7595 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
7596 let item = self.cut_common(window, cx);
7597 cx.write_to_clipboard(item);
7598 }
7599
7600 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
7601 self.change_selections(None, window, cx, |s| {
7602 s.move_with(|snapshot, sel| {
7603 if sel.is_empty() {
7604 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7605 }
7606 });
7607 });
7608 let item = self.cut_common(window, cx);
7609 cx.set_global(KillRing(item))
7610 }
7611
7612 pub fn kill_ring_yank(
7613 &mut self,
7614 _: &KillRingYank,
7615 window: &mut Window,
7616 cx: &mut Context<Self>,
7617 ) {
7618 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7619 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7620 (kill_ring.text().to_string(), kill_ring.metadata_json())
7621 } else {
7622 return;
7623 }
7624 } else {
7625 return;
7626 };
7627 self.do_paste(&text, metadata, false, window, cx);
7628 }
7629
7630 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
7631 let selections = self.selections.all::<Point>(cx);
7632 let buffer = self.buffer.read(cx).read(cx);
7633 let mut text = String::new();
7634
7635 let mut clipboard_selections = Vec::with_capacity(selections.len());
7636 {
7637 let max_point = buffer.max_point();
7638 let mut is_first = true;
7639 for selection in selections.iter() {
7640 let mut start = selection.start;
7641 let mut end = selection.end;
7642 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7643 if is_entire_line {
7644 start = Point::new(start.row, 0);
7645 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7646 }
7647 if is_first {
7648 is_first = false;
7649 } else {
7650 text += "\n";
7651 }
7652 let mut len = 0;
7653 for chunk in buffer.text_for_range(start..end) {
7654 text.push_str(chunk);
7655 len += chunk.len();
7656 }
7657 clipboard_selections.push(ClipboardSelection {
7658 len,
7659 is_entire_line,
7660 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7661 });
7662 }
7663 }
7664
7665 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7666 text,
7667 clipboard_selections,
7668 ));
7669 }
7670
7671 pub fn do_paste(
7672 &mut self,
7673 text: &String,
7674 clipboard_selections: Option<Vec<ClipboardSelection>>,
7675 handle_entire_lines: bool,
7676 window: &mut Window,
7677 cx: &mut Context<Self>,
7678 ) {
7679 if self.read_only(cx) {
7680 return;
7681 }
7682
7683 let clipboard_text = Cow::Borrowed(text);
7684
7685 self.transact(window, cx, |this, window, cx| {
7686 if let Some(mut clipboard_selections) = clipboard_selections {
7687 let old_selections = this.selections.all::<usize>(cx);
7688 let all_selections_were_entire_line =
7689 clipboard_selections.iter().all(|s| s.is_entire_line);
7690 let first_selection_indent_column =
7691 clipboard_selections.first().map(|s| s.first_line_indent);
7692 if clipboard_selections.len() != old_selections.len() {
7693 clipboard_selections.drain(..);
7694 }
7695 let cursor_offset = this.selections.last::<usize>(cx).head();
7696 let mut auto_indent_on_paste = true;
7697
7698 this.buffer.update(cx, |buffer, cx| {
7699 let snapshot = buffer.read(cx);
7700 auto_indent_on_paste =
7701 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7702
7703 let mut start_offset = 0;
7704 let mut edits = Vec::new();
7705 let mut original_indent_columns = Vec::new();
7706 for (ix, selection) in old_selections.iter().enumerate() {
7707 let to_insert;
7708 let entire_line;
7709 let original_indent_column;
7710 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7711 let end_offset = start_offset + clipboard_selection.len;
7712 to_insert = &clipboard_text[start_offset..end_offset];
7713 entire_line = clipboard_selection.is_entire_line;
7714 start_offset = end_offset + 1;
7715 original_indent_column = Some(clipboard_selection.first_line_indent);
7716 } else {
7717 to_insert = clipboard_text.as_str();
7718 entire_line = all_selections_were_entire_line;
7719 original_indent_column = first_selection_indent_column
7720 }
7721
7722 // If the corresponding selection was empty when this slice of the
7723 // clipboard text was written, then the entire line containing the
7724 // selection was copied. If this selection is also currently empty,
7725 // then paste the line before the current line of the buffer.
7726 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7727 let column = selection.start.to_point(&snapshot).column as usize;
7728 let line_start = selection.start - column;
7729 line_start..line_start
7730 } else {
7731 selection.range()
7732 };
7733
7734 edits.push((range, to_insert));
7735 original_indent_columns.extend(original_indent_column);
7736 }
7737 drop(snapshot);
7738
7739 buffer.edit(
7740 edits,
7741 if auto_indent_on_paste {
7742 Some(AutoindentMode::Block {
7743 original_indent_columns,
7744 })
7745 } else {
7746 None
7747 },
7748 cx,
7749 );
7750 });
7751
7752 let selections = this.selections.all::<usize>(cx);
7753 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7754 s.select(selections)
7755 });
7756 } else {
7757 this.insert(&clipboard_text, window, cx);
7758 }
7759 });
7760 }
7761
7762 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
7763 if let Some(item) = cx.read_from_clipboard() {
7764 let entries = item.entries();
7765
7766 match entries.first() {
7767 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7768 // of all the pasted entries.
7769 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7770 .do_paste(
7771 clipboard_string.text(),
7772 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7773 true,
7774 window,
7775 cx,
7776 ),
7777 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
7778 }
7779 }
7780 }
7781
7782 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
7783 if self.read_only(cx) {
7784 return;
7785 }
7786
7787 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7788 if let Some((selections, _)) =
7789 self.selection_history.transaction(transaction_id).cloned()
7790 {
7791 self.change_selections(None, window, cx, |s| {
7792 s.select_anchors(selections.to_vec());
7793 });
7794 }
7795 self.request_autoscroll(Autoscroll::fit(), cx);
7796 self.unmark_text(window, cx);
7797 self.refresh_inline_completion(true, false, window, cx);
7798 cx.emit(EditorEvent::Edited { transaction_id });
7799 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7800 }
7801 }
7802
7803 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
7804 if self.read_only(cx) {
7805 return;
7806 }
7807
7808 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7809 if let Some((_, Some(selections))) =
7810 self.selection_history.transaction(transaction_id).cloned()
7811 {
7812 self.change_selections(None, window, cx, |s| {
7813 s.select_anchors(selections.to_vec());
7814 });
7815 }
7816 self.request_autoscroll(Autoscroll::fit(), cx);
7817 self.unmark_text(window, cx);
7818 self.refresh_inline_completion(true, false, window, cx);
7819 cx.emit(EditorEvent::Edited { transaction_id });
7820 }
7821 }
7822
7823 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
7824 self.buffer
7825 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7826 }
7827
7828 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
7829 self.buffer
7830 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7831 }
7832
7833 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
7834 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7835 let line_mode = s.line_mode;
7836 s.move_with(|map, selection| {
7837 let cursor = if selection.is_empty() && !line_mode {
7838 movement::left(map, selection.start)
7839 } else {
7840 selection.start
7841 };
7842 selection.collapse_to(cursor, SelectionGoal::None);
7843 });
7844 })
7845 }
7846
7847 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
7848 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7849 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7850 })
7851 }
7852
7853 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
7854 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7855 let line_mode = s.line_mode;
7856 s.move_with(|map, selection| {
7857 let cursor = if selection.is_empty() && !line_mode {
7858 movement::right(map, selection.end)
7859 } else {
7860 selection.end
7861 };
7862 selection.collapse_to(cursor, SelectionGoal::None)
7863 });
7864 })
7865 }
7866
7867 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
7868 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7869 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7870 })
7871 }
7872
7873 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
7874 if self.take_rename(true, window, cx).is_some() {
7875 return;
7876 }
7877
7878 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7879 cx.propagate();
7880 return;
7881 }
7882
7883 let text_layout_details = &self.text_layout_details(window);
7884 let selection_count = self.selections.count();
7885 let first_selection = self.selections.first_anchor();
7886
7887 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7888 let line_mode = s.line_mode;
7889 s.move_with(|map, selection| {
7890 if !selection.is_empty() && !line_mode {
7891 selection.goal = SelectionGoal::None;
7892 }
7893 let (cursor, goal) = movement::up(
7894 map,
7895 selection.start,
7896 selection.goal,
7897 false,
7898 text_layout_details,
7899 );
7900 selection.collapse_to(cursor, goal);
7901 });
7902 });
7903
7904 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7905 {
7906 cx.propagate();
7907 }
7908 }
7909
7910 pub fn move_up_by_lines(
7911 &mut self,
7912 action: &MoveUpByLines,
7913 window: &mut Window,
7914 cx: &mut Context<Self>,
7915 ) {
7916 if self.take_rename(true, window, cx).is_some() {
7917 return;
7918 }
7919
7920 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7921 cx.propagate();
7922 return;
7923 }
7924
7925 let text_layout_details = &self.text_layout_details(window);
7926
7927 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7928 let line_mode = s.line_mode;
7929 s.move_with(|map, selection| {
7930 if !selection.is_empty() && !line_mode {
7931 selection.goal = SelectionGoal::None;
7932 }
7933 let (cursor, goal) = movement::up_by_rows(
7934 map,
7935 selection.start,
7936 action.lines,
7937 selection.goal,
7938 false,
7939 text_layout_details,
7940 );
7941 selection.collapse_to(cursor, goal);
7942 });
7943 })
7944 }
7945
7946 pub fn move_down_by_lines(
7947 &mut self,
7948 action: &MoveDownByLines,
7949 window: &mut Window,
7950 cx: &mut Context<Self>,
7951 ) {
7952 if self.take_rename(true, window, cx).is_some() {
7953 return;
7954 }
7955
7956 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7957 cx.propagate();
7958 return;
7959 }
7960
7961 let text_layout_details = &self.text_layout_details(window);
7962
7963 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7964 let line_mode = s.line_mode;
7965 s.move_with(|map, selection| {
7966 if !selection.is_empty() && !line_mode {
7967 selection.goal = SelectionGoal::None;
7968 }
7969 let (cursor, goal) = movement::down_by_rows(
7970 map,
7971 selection.start,
7972 action.lines,
7973 selection.goal,
7974 false,
7975 text_layout_details,
7976 );
7977 selection.collapse_to(cursor, goal);
7978 });
7979 })
7980 }
7981
7982 pub fn select_down_by_lines(
7983 &mut self,
7984 action: &SelectDownByLines,
7985 window: &mut Window,
7986 cx: &mut Context<Self>,
7987 ) {
7988 let text_layout_details = &self.text_layout_details(window);
7989 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7990 s.move_heads_with(|map, head, goal| {
7991 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7992 })
7993 })
7994 }
7995
7996 pub fn select_up_by_lines(
7997 &mut self,
7998 action: &SelectUpByLines,
7999 window: &mut Window,
8000 cx: &mut Context<Self>,
8001 ) {
8002 let text_layout_details = &self.text_layout_details(window);
8003 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8004 s.move_heads_with(|map, head, goal| {
8005 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8006 })
8007 })
8008 }
8009
8010 pub fn select_page_up(
8011 &mut self,
8012 _: &SelectPageUp,
8013 window: &mut Window,
8014 cx: &mut Context<Self>,
8015 ) {
8016 let Some(row_count) = self.visible_row_count() else {
8017 return;
8018 };
8019
8020 let text_layout_details = &self.text_layout_details(window);
8021
8022 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8023 s.move_heads_with(|map, head, goal| {
8024 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8025 })
8026 })
8027 }
8028
8029 pub fn move_page_up(
8030 &mut self,
8031 action: &MovePageUp,
8032 window: &mut Window,
8033 cx: &mut Context<Self>,
8034 ) {
8035 if self.take_rename(true, window, cx).is_some() {
8036 return;
8037 }
8038
8039 if self
8040 .context_menu
8041 .borrow_mut()
8042 .as_mut()
8043 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8044 .unwrap_or(false)
8045 {
8046 return;
8047 }
8048
8049 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8050 cx.propagate();
8051 return;
8052 }
8053
8054 let Some(row_count) = self.visible_row_count() else {
8055 return;
8056 };
8057
8058 let autoscroll = if action.center_cursor {
8059 Autoscroll::center()
8060 } else {
8061 Autoscroll::fit()
8062 };
8063
8064 let text_layout_details = &self.text_layout_details(window);
8065
8066 self.change_selections(Some(autoscroll), window, cx, |s| {
8067 let line_mode = s.line_mode;
8068 s.move_with(|map, selection| {
8069 if !selection.is_empty() && !line_mode {
8070 selection.goal = SelectionGoal::None;
8071 }
8072 let (cursor, goal) = movement::up_by_rows(
8073 map,
8074 selection.end,
8075 row_count,
8076 selection.goal,
8077 false,
8078 text_layout_details,
8079 );
8080 selection.collapse_to(cursor, goal);
8081 });
8082 });
8083 }
8084
8085 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8086 let text_layout_details = &self.text_layout_details(window);
8087 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8088 s.move_heads_with(|map, head, goal| {
8089 movement::up(map, head, goal, false, text_layout_details)
8090 })
8091 })
8092 }
8093
8094 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8095 self.take_rename(true, window, cx);
8096
8097 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8098 cx.propagate();
8099 return;
8100 }
8101
8102 let text_layout_details = &self.text_layout_details(window);
8103 let selection_count = self.selections.count();
8104 let first_selection = self.selections.first_anchor();
8105
8106 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8107 let line_mode = s.line_mode;
8108 s.move_with(|map, selection| {
8109 if !selection.is_empty() && !line_mode {
8110 selection.goal = SelectionGoal::None;
8111 }
8112 let (cursor, goal) = movement::down(
8113 map,
8114 selection.end,
8115 selection.goal,
8116 false,
8117 text_layout_details,
8118 );
8119 selection.collapse_to(cursor, goal);
8120 });
8121 });
8122
8123 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8124 {
8125 cx.propagate();
8126 }
8127 }
8128
8129 pub fn select_page_down(
8130 &mut self,
8131 _: &SelectPageDown,
8132 window: &mut Window,
8133 cx: &mut Context<Self>,
8134 ) {
8135 let Some(row_count) = self.visible_row_count() else {
8136 return;
8137 };
8138
8139 let text_layout_details = &self.text_layout_details(window);
8140
8141 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8142 s.move_heads_with(|map, head, goal| {
8143 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8144 })
8145 })
8146 }
8147
8148 pub fn move_page_down(
8149 &mut self,
8150 action: &MovePageDown,
8151 window: &mut Window,
8152 cx: &mut Context<Self>,
8153 ) {
8154 if self.take_rename(true, window, cx).is_some() {
8155 return;
8156 }
8157
8158 if self
8159 .context_menu
8160 .borrow_mut()
8161 .as_mut()
8162 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8163 .unwrap_or(false)
8164 {
8165 return;
8166 }
8167
8168 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8169 cx.propagate();
8170 return;
8171 }
8172
8173 let Some(row_count) = self.visible_row_count() else {
8174 return;
8175 };
8176
8177 let autoscroll = if action.center_cursor {
8178 Autoscroll::center()
8179 } else {
8180 Autoscroll::fit()
8181 };
8182
8183 let text_layout_details = &self.text_layout_details(window);
8184 self.change_selections(Some(autoscroll), window, cx, |s| {
8185 let line_mode = s.line_mode;
8186 s.move_with(|map, selection| {
8187 if !selection.is_empty() && !line_mode {
8188 selection.goal = SelectionGoal::None;
8189 }
8190 let (cursor, goal) = movement::down_by_rows(
8191 map,
8192 selection.end,
8193 row_count,
8194 selection.goal,
8195 false,
8196 text_layout_details,
8197 );
8198 selection.collapse_to(cursor, goal);
8199 });
8200 });
8201 }
8202
8203 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8204 let text_layout_details = &self.text_layout_details(window);
8205 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8206 s.move_heads_with(|map, head, goal| {
8207 movement::down(map, head, goal, false, text_layout_details)
8208 })
8209 });
8210 }
8211
8212 pub fn context_menu_first(
8213 &mut self,
8214 _: &ContextMenuFirst,
8215 _window: &mut Window,
8216 cx: &mut Context<Self>,
8217 ) {
8218 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8219 context_menu.select_first(self.completion_provider.as_deref(), cx);
8220 }
8221 }
8222
8223 pub fn context_menu_prev(
8224 &mut self,
8225 _: &ContextMenuPrev,
8226 _window: &mut Window,
8227 cx: &mut Context<Self>,
8228 ) {
8229 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8230 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8231 }
8232 }
8233
8234 pub fn context_menu_next(
8235 &mut self,
8236 _: &ContextMenuNext,
8237 _window: &mut Window,
8238 cx: &mut Context<Self>,
8239 ) {
8240 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8241 context_menu.select_next(self.completion_provider.as_deref(), cx);
8242 }
8243 }
8244
8245 pub fn context_menu_last(
8246 &mut self,
8247 _: &ContextMenuLast,
8248 _window: &mut Window,
8249 cx: &mut Context<Self>,
8250 ) {
8251 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8252 context_menu.select_last(self.completion_provider.as_deref(), cx);
8253 }
8254 }
8255
8256 pub fn move_to_previous_word_start(
8257 &mut self,
8258 _: &MoveToPreviousWordStart,
8259 window: &mut Window,
8260 cx: &mut Context<Self>,
8261 ) {
8262 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8263 s.move_cursors_with(|map, head, _| {
8264 (
8265 movement::previous_word_start(map, head),
8266 SelectionGoal::None,
8267 )
8268 });
8269 })
8270 }
8271
8272 pub fn move_to_previous_subword_start(
8273 &mut self,
8274 _: &MoveToPreviousSubwordStart,
8275 window: &mut Window,
8276 cx: &mut Context<Self>,
8277 ) {
8278 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8279 s.move_cursors_with(|map, head, _| {
8280 (
8281 movement::previous_subword_start(map, head),
8282 SelectionGoal::None,
8283 )
8284 });
8285 })
8286 }
8287
8288 pub fn select_to_previous_word_start(
8289 &mut self,
8290 _: &SelectToPreviousWordStart,
8291 window: &mut Window,
8292 cx: &mut Context<Self>,
8293 ) {
8294 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8295 s.move_heads_with(|map, head, _| {
8296 (
8297 movement::previous_word_start(map, head),
8298 SelectionGoal::None,
8299 )
8300 });
8301 })
8302 }
8303
8304 pub fn select_to_previous_subword_start(
8305 &mut self,
8306 _: &SelectToPreviousSubwordStart,
8307 window: &mut Window,
8308 cx: &mut Context<Self>,
8309 ) {
8310 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8311 s.move_heads_with(|map, head, _| {
8312 (
8313 movement::previous_subword_start(map, head),
8314 SelectionGoal::None,
8315 )
8316 });
8317 })
8318 }
8319
8320 pub fn delete_to_previous_word_start(
8321 &mut self,
8322 action: &DeleteToPreviousWordStart,
8323 window: &mut Window,
8324 cx: &mut Context<Self>,
8325 ) {
8326 self.transact(window, cx, |this, window, cx| {
8327 this.select_autoclose_pair(window, cx);
8328 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8329 let line_mode = s.line_mode;
8330 s.move_with(|map, selection| {
8331 if selection.is_empty() && !line_mode {
8332 let cursor = if action.ignore_newlines {
8333 movement::previous_word_start(map, selection.head())
8334 } else {
8335 movement::previous_word_start_or_newline(map, selection.head())
8336 };
8337 selection.set_head(cursor, SelectionGoal::None);
8338 }
8339 });
8340 });
8341 this.insert("", window, cx);
8342 });
8343 }
8344
8345 pub fn delete_to_previous_subword_start(
8346 &mut self,
8347 _: &DeleteToPreviousSubwordStart,
8348 window: &mut Window,
8349 cx: &mut Context<Self>,
8350 ) {
8351 self.transact(window, cx, |this, window, cx| {
8352 this.select_autoclose_pair(window, cx);
8353 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8354 let line_mode = s.line_mode;
8355 s.move_with(|map, selection| {
8356 if selection.is_empty() && !line_mode {
8357 let cursor = movement::previous_subword_start(map, selection.head());
8358 selection.set_head(cursor, SelectionGoal::None);
8359 }
8360 });
8361 });
8362 this.insert("", window, cx);
8363 });
8364 }
8365
8366 pub fn move_to_next_word_end(
8367 &mut self,
8368 _: &MoveToNextWordEnd,
8369 window: &mut Window,
8370 cx: &mut Context<Self>,
8371 ) {
8372 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8373 s.move_cursors_with(|map, head, _| {
8374 (movement::next_word_end(map, head), SelectionGoal::None)
8375 });
8376 })
8377 }
8378
8379 pub fn move_to_next_subword_end(
8380 &mut self,
8381 _: &MoveToNextSubwordEnd,
8382 window: &mut Window,
8383 cx: &mut Context<Self>,
8384 ) {
8385 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8386 s.move_cursors_with(|map, head, _| {
8387 (movement::next_subword_end(map, head), SelectionGoal::None)
8388 });
8389 })
8390 }
8391
8392 pub fn select_to_next_word_end(
8393 &mut self,
8394 _: &SelectToNextWordEnd,
8395 window: &mut Window,
8396 cx: &mut Context<Self>,
8397 ) {
8398 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8399 s.move_heads_with(|map, head, _| {
8400 (movement::next_word_end(map, head), SelectionGoal::None)
8401 });
8402 })
8403 }
8404
8405 pub fn select_to_next_subword_end(
8406 &mut self,
8407 _: &SelectToNextSubwordEnd,
8408 window: &mut Window,
8409 cx: &mut Context<Self>,
8410 ) {
8411 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8412 s.move_heads_with(|map, head, _| {
8413 (movement::next_subword_end(map, head), SelectionGoal::None)
8414 });
8415 })
8416 }
8417
8418 pub fn delete_to_next_word_end(
8419 &mut self,
8420 action: &DeleteToNextWordEnd,
8421 window: &mut Window,
8422 cx: &mut Context<Self>,
8423 ) {
8424 self.transact(window, cx, |this, window, cx| {
8425 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8426 let line_mode = s.line_mode;
8427 s.move_with(|map, selection| {
8428 if selection.is_empty() && !line_mode {
8429 let cursor = if action.ignore_newlines {
8430 movement::next_word_end(map, selection.head())
8431 } else {
8432 movement::next_word_end_or_newline(map, selection.head())
8433 };
8434 selection.set_head(cursor, SelectionGoal::None);
8435 }
8436 });
8437 });
8438 this.insert("", window, cx);
8439 });
8440 }
8441
8442 pub fn delete_to_next_subword_end(
8443 &mut self,
8444 _: &DeleteToNextSubwordEnd,
8445 window: &mut Window,
8446 cx: &mut Context<Self>,
8447 ) {
8448 self.transact(window, cx, |this, window, cx| {
8449 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8450 s.move_with(|map, selection| {
8451 if selection.is_empty() {
8452 let cursor = movement::next_subword_end(map, selection.head());
8453 selection.set_head(cursor, SelectionGoal::None);
8454 }
8455 });
8456 });
8457 this.insert("", window, cx);
8458 });
8459 }
8460
8461 pub fn move_to_beginning_of_line(
8462 &mut self,
8463 action: &MoveToBeginningOfLine,
8464 window: &mut Window,
8465 cx: &mut Context<Self>,
8466 ) {
8467 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8468 s.move_cursors_with(|map, head, _| {
8469 (
8470 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8471 SelectionGoal::None,
8472 )
8473 });
8474 })
8475 }
8476
8477 pub fn select_to_beginning_of_line(
8478 &mut self,
8479 action: &SelectToBeginningOfLine,
8480 window: &mut Window,
8481 cx: &mut Context<Self>,
8482 ) {
8483 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8484 s.move_heads_with(|map, head, _| {
8485 (
8486 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8487 SelectionGoal::None,
8488 )
8489 });
8490 });
8491 }
8492
8493 pub fn delete_to_beginning_of_line(
8494 &mut self,
8495 _: &DeleteToBeginningOfLine,
8496 window: &mut Window,
8497 cx: &mut Context<Self>,
8498 ) {
8499 self.transact(window, cx, |this, window, cx| {
8500 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8501 s.move_with(|_, selection| {
8502 selection.reversed = true;
8503 });
8504 });
8505
8506 this.select_to_beginning_of_line(
8507 &SelectToBeginningOfLine {
8508 stop_at_soft_wraps: false,
8509 },
8510 window,
8511 cx,
8512 );
8513 this.backspace(&Backspace, window, cx);
8514 });
8515 }
8516
8517 pub fn move_to_end_of_line(
8518 &mut self,
8519 action: &MoveToEndOfLine,
8520 window: &mut Window,
8521 cx: &mut Context<Self>,
8522 ) {
8523 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8524 s.move_cursors_with(|map, head, _| {
8525 (
8526 movement::line_end(map, head, action.stop_at_soft_wraps),
8527 SelectionGoal::None,
8528 )
8529 });
8530 })
8531 }
8532
8533 pub fn select_to_end_of_line(
8534 &mut self,
8535 action: &SelectToEndOfLine,
8536 window: &mut Window,
8537 cx: &mut Context<Self>,
8538 ) {
8539 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8540 s.move_heads_with(|map, head, _| {
8541 (
8542 movement::line_end(map, head, action.stop_at_soft_wraps),
8543 SelectionGoal::None,
8544 )
8545 });
8546 })
8547 }
8548
8549 pub fn delete_to_end_of_line(
8550 &mut self,
8551 _: &DeleteToEndOfLine,
8552 window: &mut Window,
8553 cx: &mut Context<Self>,
8554 ) {
8555 self.transact(window, cx, |this, window, cx| {
8556 this.select_to_end_of_line(
8557 &SelectToEndOfLine {
8558 stop_at_soft_wraps: false,
8559 },
8560 window,
8561 cx,
8562 );
8563 this.delete(&Delete, window, cx);
8564 });
8565 }
8566
8567 pub fn cut_to_end_of_line(
8568 &mut self,
8569 _: &CutToEndOfLine,
8570 window: &mut Window,
8571 cx: &mut Context<Self>,
8572 ) {
8573 self.transact(window, cx, |this, window, cx| {
8574 this.select_to_end_of_line(
8575 &SelectToEndOfLine {
8576 stop_at_soft_wraps: false,
8577 },
8578 window,
8579 cx,
8580 );
8581 this.cut(&Cut, window, cx);
8582 });
8583 }
8584
8585 pub fn move_to_start_of_paragraph(
8586 &mut self,
8587 _: &MoveToStartOfParagraph,
8588 window: &mut Window,
8589 cx: &mut Context<Self>,
8590 ) {
8591 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8592 cx.propagate();
8593 return;
8594 }
8595
8596 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8597 s.move_with(|map, selection| {
8598 selection.collapse_to(
8599 movement::start_of_paragraph(map, selection.head(), 1),
8600 SelectionGoal::None,
8601 )
8602 });
8603 })
8604 }
8605
8606 pub fn move_to_end_of_paragraph(
8607 &mut self,
8608 _: &MoveToEndOfParagraph,
8609 window: &mut Window,
8610 cx: &mut Context<Self>,
8611 ) {
8612 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8613 cx.propagate();
8614 return;
8615 }
8616
8617 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8618 s.move_with(|map, selection| {
8619 selection.collapse_to(
8620 movement::end_of_paragraph(map, selection.head(), 1),
8621 SelectionGoal::None,
8622 )
8623 });
8624 })
8625 }
8626
8627 pub fn select_to_start_of_paragraph(
8628 &mut self,
8629 _: &SelectToStartOfParagraph,
8630 window: &mut Window,
8631 cx: &mut Context<Self>,
8632 ) {
8633 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8634 cx.propagate();
8635 return;
8636 }
8637
8638 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8639 s.move_heads_with(|map, head, _| {
8640 (
8641 movement::start_of_paragraph(map, head, 1),
8642 SelectionGoal::None,
8643 )
8644 });
8645 })
8646 }
8647
8648 pub fn select_to_end_of_paragraph(
8649 &mut self,
8650 _: &SelectToEndOfParagraph,
8651 window: &mut Window,
8652 cx: &mut Context<Self>,
8653 ) {
8654 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8655 cx.propagate();
8656 return;
8657 }
8658
8659 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8660 s.move_heads_with(|map, head, _| {
8661 (
8662 movement::end_of_paragraph(map, head, 1),
8663 SelectionGoal::None,
8664 )
8665 });
8666 })
8667 }
8668
8669 pub fn move_to_beginning(
8670 &mut self,
8671 _: &MoveToBeginning,
8672 window: &mut Window,
8673 cx: &mut Context<Self>,
8674 ) {
8675 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8676 cx.propagate();
8677 return;
8678 }
8679
8680 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8681 s.select_ranges(vec![0..0]);
8682 });
8683 }
8684
8685 pub fn select_to_beginning(
8686 &mut self,
8687 _: &SelectToBeginning,
8688 window: &mut Window,
8689 cx: &mut Context<Self>,
8690 ) {
8691 let mut selection = self.selections.last::<Point>(cx);
8692 selection.set_head(Point::zero(), SelectionGoal::None);
8693
8694 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8695 s.select(vec![selection]);
8696 });
8697 }
8698
8699 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
8700 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8701 cx.propagate();
8702 return;
8703 }
8704
8705 let cursor = self.buffer.read(cx).read(cx).len();
8706 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8707 s.select_ranges(vec![cursor..cursor])
8708 });
8709 }
8710
8711 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8712 self.nav_history = nav_history;
8713 }
8714
8715 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8716 self.nav_history.as_ref()
8717 }
8718
8719 fn push_to_nav_history(
8720 &mut self,
8721 cursor_anchor: Anchor,
8722 new_position: Option<Point>,
8723 cx: &mut Context<Self>,
8724 ) {
8725 if let Some(nav_history) = self.nav_history.as_mut() {
8726 let buffer = self.buffer.read(cx).read(cx);
8727 let cursor_position = cursor_anchor.to_point(&buffer);
8728 let scroll_state = self.scroll_manager.anchor();
8729 let scroll_top_row = scroll_state.top_row(&buffer);
8730 drop(buffer);
8731
8732 if let Some(new_position) = new_position {
8733 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8734 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8735 return;
8736 }
8737 }
8738
8739 nav_history.push(
8740 Some(NavigationData {
8741 cursor_anchor,
8742 cursor_position,
8743 scroll_anchor: scroll_state,
8744 scroll_top_row,
8745 }),
8746 cx,
8747 );
8748 }
8749 }
8750
8751 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
8752 let buffer = self.buffer.read(cx).snapshot(cx);
8753 let mut selection = self.selections.first::<usize>(cx);
8754 selection.set_head(buffer.len(), SelectionGoal::None);
8755 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8756 s.select(vec![selection]);
8757 });
8758 }
8759
8760 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
8761 let end = self.buffer.read(cx).read(cx).len();
8762 self.change_selections(None, window, cx, |s| {
8763 s.select_ranges(vec![0..end]);
8764 });
8765 }
8766
8767 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
8768 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8769 let mut selections = self.selections.all::<Point>(cx);
8770 let max_point = display_map.buffer_snapshot.max_point();
8771 for selection in &mut selections {
8772 let rows = selection.spanned_rows(true, &display_map);
8773 selection.start = Point::new(rows.start.0, 0);
8774 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8775 selection.reversed = false;
8776 }
8777 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8778 s.select(selections);
8779 });
8780 }
8781
8782 pub fn split_selection_into_lines(
8783 &mut self,
8784 _: &SplitSelectionIntoLines,
8785 window: &mut Window,
8786 cx: &mut Context<Self>,
8787 ) {
8788 let mut to_unfold = Vec::new();
8789 let mut new_selection_ranges = Vec::new();
8790 {
8791 let selections = self.selections.all::<Point>(cx);
8792 let buffer = self.buffer.read(cx).read(cx);
8793 for selection in selections {
8794 for row in selection.start.row..selection.end.row {
8795 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8796 new_selection_ranges.push(cursor..cursor);
8797 }
8798 new_selection_ranges.push(selection.end..selection.end);
8799 to_unfold.push(selection.start..selection.end);
8800 }
8801 }
8802 self.unfold_ranges(&to_unfold, true, true, cx);
8803 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8804 s.select_ranges(new_selection_ranges);
8805 });
8806 }
8807
8808 pub fn add_selection_above(
8809 &mut self,
8810 _: &AddSelectionAbove,
8811 window: &mut Window,
8812 cx: &mut Context<Self>,
8813 ) {
8814 self.add_selection(true, window, cx);
8815 }
8816
8817 pub fn add_selection_below(
8818 &mut self,
8819 _: &AddSelectionBelow,
8820 window: &mut Window,
8821 cx: &mut Context<Self>,
8822 ) {
8823 self.add_selection(false, window, cx);
8824 }
8825
8826 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
8827 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8828 let mut selections = self.selections.all::<Point>(cx);
8829 let text_layout_details = self.text_layout_details(window);
8830 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8831 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8832 let range = oldest_selection.display_range(&display_map).sorted();
8833
8834 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8835 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8836 let positions = start_x.min(end_x)..start_x.max(end_x);
8837
8838 selections.clear();
8839 let mut stack = Vec::new();
8840 for row in range.start.row().0..=range.end.row().0 {
8841 if let Some(selection) = self.selections.build_columnar_selection(
8842 &display_map,
8843 DisplayRow(row),
8844 &positions,
8845 oldest_selection.reversed,
8846 &text_layout_details,
8847 ) {
8848 stack.push(selection.id);
8849 selections.push(selection);
8850 }
8851 }
8852
8853 if above {
8854 stack.reverse();
8855 }
8856
8857 AddSelectionsState { above, stack }
8858 });
8859
8860 let last_added_selection = *state.stack.last().unwrap();
8861 let mut new_selections = Vec::new();
8862 if above == state.above {
8863 let end_row = if above {
8864 DisplayRow(0)
8865 } else {
8866 display_map.max_point().row()
8867 };
8868
8869 'outer: for selection in selections {
8870 if selection.id == last_added_selection {
8871 let range = selection.display_range(&display_map).sorted();
8872 debug_assert_eq!(range.start.row(), range.end.row());
8873 let mut row = range.start.row();
8874 let positions =
8875 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8876 px(start)..px(end)
8877 } else {
8878 let start_x =
8879 display_map.x_for_display_point(range.start, &text_layout_details);
8880 let end_x =
8881 display_map.x_for_display_point(range.end, &text_layout_details);
8882 start_x.min(end_x)..start_x.max(end_x)
8883 };
8884
8885 while row != end_row {
8886 if above {
8887 row.0 -= 1;
8888 } else {
8889 row.0 += 1;
8890 }
8891
8892 if let Some(new_selection) = self.selections.build_columnar_selection(
8893 &display_map,
8894 row,
8895 &positions,
8896 selection.reversed,
8897 &text_layout_details,
8898 ) {
8899 state.stack.push(new_selection.id);
8900 if above {
8901 new_selections.push(new_selection);
8902 new_selections.push(selection);
8903 } else {
8904 new_selections.push(selection);
8905 new_selections.push(new_selection);
8906 }
8907
8908 continue 'outer;
8909 }
8910 }
8911 }
8912
8913 new_selections.push(selection);
8914 }
8915 } else {
8916 new_selections = selections;
8917 new_selections.retain(|s| s.id != last_added_selection);
8918 state.stack.pop();
8919 }
8920
8921 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8922 s.select(new_selections);
8923 });
8924 if state.stack.len() > 1 {
8925 self.add_selections_state = Some(state);
8926 }
8927 }
8928
8929 pub fn select_next_match_internal(
8930 &mut self,
8931 display_map: &DisplaySnapshot,
8932 replace_newest: bool,
8933 autoscroll: Option<Autoscroll>,
8934 window: &mut Window,
8935 cx: &mut Context<Self>,
8936 ) -> Result<()> {
8937 fn select_next_match_ranges(
8938 this: &mut Editor,
8939 range: Range<usize>,
8940 replace_newest: bool,
8941 auto_scroll: Option<Autoscroll>,
8942 window: &mut Window,
8943 cx: &mut Context<Editor>,
8944 ) {
8945 this.unfold_ranges(&[range.clone()], false, true, cx);
8946 this.change_selections(auto_scroll, window, cx, |s| {
8947 if replace_newest {
8948 s.delete(s.newest_anchor().id);
8949 }
8950 s.insert_range(range.clone());
8951 });
8952 }
8953
8954 let buffer = &display_map.buffer_snapshot;
8955 let mut selections = self.selections.all::<usize>(cx);
8956 if let Some(mut select_next_state) = self.select_next_state.take() {
8957 let query = &select_next_state.query;
8958 if !select_next_state.done {
8959 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8960 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8961 let mut next_selected_range = None;
8962
8963 let bytes_after_last_selection =
8964 buffer.bytes_in_range(last_selection.end..buffer.len());
8965 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8966 let query_matches = query
8967 .stream_find_iter(bytes_after_last_selection)
8968 .map(|result| (last_selection.end, result))
8969 .chain(
8970 query
8971 .stream_find_iter(bytes_before_first_selection)
8972 .map(|result| (0, result)),
8973 );
8974
8975 for (start_offset, query_match) in query_matches {
8976 let query_match = query_match.unwrap(); // can only fail due to I/O
8977 let offset_range =
8978 start_offset + query_match.start()..start_offset + query_match.end();
8979 let display_range = offset_range.start.to_display_point(display_map)
8980 ..offset_range.end.to_display_point(display_map);
8981
8982 if !select_next_state.wordwise
8983 || (!movement::is_inside_word(display_map, display_range.start)
8984 && !movement::is_inside_word(display_map, display_range.end))
8985 {
8986 // TODO: This is n^2, because we might check all the selections
8987 if !selections
8988 .iter()
8989 .any(|selection| selection.range().overlaps(&offset_range))
8990 {
8991 next_selected_range = Some(offset_range);
8992 break;
8993 }
8994 }
8995 }
8996
8997 if let Some(next_selected_range) = next_selected_range {
8998 select_next_match_ranges(
8999 self,
9000 next_selected_range,
9001 replace_newest,
9002 autoscroll,
9003 window,
9004 cx,
9005 );
9006 } else {
9007 select_next_state.done = true;
9008 }
9009 }
9010
9011 self.select_next_state = Some(select_next_state);
9012 } else {
9013 let mut only_carets = true;
9014 let mut same_text_selected = true;
9015 let mut selected_text = None;
9016
9017 let mut selections_iter = selections.iter().peekable();
9018 while let Some(selection) = selections_iter.next() {
9019 if selection.start != selection.end {
9020 only_carets = false;
9021 }
9022
9023 if same_text_selected {
9024 if selected_text.is_none() {
9025 selected_text =
9026 Some(buffer.text_for_range(selection.range()).collect::<String>());
9027 }
9028
9029 if let Some(next_selection) = selections_iter.peek() {
9030 if next_selection.range().len() == selection.range().len() {
9031 let next_selected_text = buffer
9032 .text_for_range(next_selection.range())
9033 .collect::<String>();
9034 if Some(next_selected_text) != selected_text {
9035 same_text_selected = false;
9036 selected_text = None;
9037 }
9038 } else {
9039 same_text_selected = false;
9040 selected_text = None;
9041 }
9042 }
9043 }
9044 }
9045
9046 if only_carets {
9047 for selection in &mut selections {
9048 let word_range = movement::surrounding_word(
9049 display_map,
9050 selection.start.to_display_point(display_map),
9051 );
9052 selection.start = word_range.start.to_offset(display_map, Bias::Left);
9053 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9054 selection.goal = SelectionGoal::None;
9055 selection.reversed = false;
9056 select_next_match_ranges(
9057 self,
9058 selection.start..selection.end,
9059 replace_newest,
9060 autoscroll,
9061 window,
9062 cx,
9063 );
9064 }
9065
9066 if selections.len() == 1 {
9067 let selection = selections
9068 .last()
9069 .expect("ensured that there's only one selection");
9070 let query = buffer
9071 .text_for_range(selection.start..selection.end)
9072 .collect::<String>();
9073 let is_empty = query.is_empty();
9074 let select_state = SelectNextState {
9075 query: AhoCorasick::new(&[query])?,
9076 wordwise: true,
9077 done: is_empty,
9078 };
9079 self.select_next_state = Some(select_state);
9080 } else {
9081 self.select_next_state = None;
9082 }
9083 } else if let Some(selected_text) = selected_text {
9084 self.select_next_state = Some(SelectNextState {
9085 query: AhoCorasick::new(&[selected_text])?,
9086 wordwise: false,
9087 done: false,
9088 });
9089 self.select_next_match_internal(
9090 display_map,
9091 replace_newest,
9092 autoscroll,
9093 window,
9094 cx,
9095 )?;
9096 }
9097 }
9098 Ok(())
9099 }
9100
9101 pub fn select_all_matches(
9102 &mut self,
9103 _action: &SelectAllMatches,
9104 window: &mut Window,
9105 cx: &mut Context<Self>,
9106 ) -> Result<()> {
9107 self.push_to_selection_history();
9108 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9109
9110 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9111 let Some(select_next_state) = self.select_next_state.as_mut() else {
9112 return Ok(());
9113 };
9114 if select_next_state.done {
9115 return Ok(());
9116 }
9117
9118 let mut new_selections = self.selections.all::<usize>(cx);
9119
9120 let buffer = &display_map.buffer_snapshot;
9121 let query_matches = select_next_state
9122 .query
9123 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9124
9125 for query_match in query_matches {
9126 let query_match = query_match.unwrap(); // can only fail due to I/O
9127 let offset_range = query_match.start()..query_match.end();
9128 let display_range = offset_range.start.to_display_point(&display_map)
9129 ..offset_range.end.to_display_point(&display_map);
9130
9131 if !select_next_state.wordwise
9132 || (!movement::is_inside_word(&display_map, display_range.start)
9133 && !movement::is_inside_word(&display_map, display_range.end))
9134 {
9135 self.selections.change_with(cx, |selections| {
9136 new_selections.push(Selection {
9137 id: selections.new_selection_id(),
9138 start: offset_range.start,
9139 end: offset_range.end,
9140 reversed: false,
9141 goal: SelectionGoal::None,
9142 });
9143 });
9144 }
9145 }
9146
9147 new_selections.sort_by_key(|selection| selection.start);
9148 let mut ix = 0;
9149 while ix + 1 < new_selections.len() {
9150 let current_selection = &new_selections[ix];
9151 let next_selection = &new_selections[ix + 1];
9152 if current_selection.range().overlaps(&next_selection.range()) {
9153 if current_selection.id < next_selection.id {
9154 new_selections.remove(ix + 1);
9155 } else {
9156 new_selections.remove(ix);
9157 }
9158 } else {
9159 ix += 1;
9160 }
9161 }
9162
9163 let reversed = self.selections.oldest::<usize>(cx).reversed;
9164
9165 for selection in new_selections.iter_mut() {
9166 selection.reversed = reversed;
9167 }
9168
9169 select_next_state.done = true;
9170 self.unfold_ranges(
9171 &new_selections
9172 .iter()
9173 .map(|selection| selection.range())
9174 .collect::<Vec<_>>(),
9175 false,
9176 false,
9177 cx,
9178 );
9179 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9180 selections.select(new_selections)
9181 });
9182
9183 Ok(())
9184 }
9185
9186 pub fn select_next(
9187 &mut self,
9188 action: &SelectNext,
9189 window: &mut Window,
9190 cx: &mut Context<Self>,
9191 ) -> Result<()> {
9192 self.push_to_selection_history();
9193 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9194 self.select_next_match_internal(
9195 &display_map,
9196 action.replace_newest,
9197 Some(Autoscroll::newest()),
9198 window,
9199 cx,
9200 )?;
9201 Ok(())
9202 }
9203
9204 pub fn select_previous(
9205 &mut self,
9206 action: &SelectPrevious,
9207 window: &mut Window,
9208 cx: &mut Context<Self>,
9209 ) -> Result<()> {
9210 self.push_to_selection_history();
9211 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9212 let buffer = &display_map.buffer_snapshot;
9213 let mut selections = self.selections.all::<usize>(cx);
9214 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9215 let query = &select_prev_state.query;
9216 if !select_prev_state.done {
9217 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9218 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9219 let mut next_selected_range = None;
9220 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9221 let bytes_before_last_selection =
9222 buffer.reversed_bytes_in_range(0..last_selection.start);
9223 let bytes_after_first_selection =
9224 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9225 let query_matches = query
9226 .stream_find_iter(bytes_before_last_selection)
9227 .map(|result| (last_selection.start, result))
9228 .chain(
9229 query
9230 .stream_find_iter(bytes_after_first_selection)
9231 .map(|result| (buffer.len(), result)),
9232 );
9233 for (end_offset, query_match) in query_matches {
9234 let query_match = query_match.unwrap(); // can only fail due to I/O
9235 let offset_range =
9236 end_offset - query_match.end()..end_offset - query_match.start();
9237 let display_range = offset_range.start.to_display_point(&display_map)
9238 ..offset_range.end.to_display_point(&display_map);
9239
9240 if !select_prev_state.wordwise
9241 || (!movement::is_inside_word(&display_map, display_range.start)
9242 && !movement::is_inside_word(&display_map, display_range.end))
9243 {
9244 next_selected_range = Some(offset_range);
9245 break;
9246 }
9247 }
9248
9249 if let Some(next_selected_range) = next_selected_range {
9250 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9251 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9252 if action.replace_newest {
9253 s.delete(s.newest_anchor().id);
9254 }
9255 s.insert_range(next_selected_range);
9256 });
9257 } else {
9258 select_prev_state.done = true;
9259 }
9260 }
9261
9262 self.select_prev_state = Some(select_prev_state);
9263 } else {
9264 let mut only_carets = true;
9265 let mut same_text_selected = true;
9266 let mut selected_text = None;
9267
9268 let mut selections_iter = selections.iter().peekable();
9269 while let Some(selection) = selections_iter.next() {
9270 if selection.start != selection.end {
9271 only_carets = false;
9272 }
9273
9274 if same_text_selected {
9275 if selected_text.is_none() {
9276 selected_text =
9277 Some(buffer.text_for_range(selection.range()).collect::<String>());
9278 }
9279
9280 if let Some(next_selection) = selections_iter.peek() {
9281 if next_selection.range().len() == selection.range().len() {
9282 let next_selected_text = buffer
9283 .text_for_range(next_selection.range())
9284 .collect::<String>();
9285 if Some(next_selected_text) != selected_text {
9286 same_text_selected = false;
9287 selected_text = None;
9288 }
9289 } else {
9290 same_text_selected = false;
9291 selected_text = None;
9292 }
9293 }
9294 }
9295 }
9296
9297 if only_carets {
9298 for selection in &mut selections {
9299 let word_range = movement::surrounding_word(
9300 &display_map,
9301 selection.start.to_display_point(&display_map),
9302 );
9303 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9304 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9305 selection.goal = SelectionGoal::None;
9306 selection.reversed = false;
9307 }
9308 if selections.len() == 1 {
9309 let selection = selections
9310 .last()
9311 .expect("ensured that there's only one selection");
9312 let query = buffer
9313 .text_for_range(selection.start..selection.end)
9314 .collect::<String>();
9315 let is_empty = query.is_empty();
9316 let select_state = SelectNextState {
9317 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9318 wordwise: true,
9319 done: is_empty,
9320 };
9321 self.select_prev_state = Some(select_state);
9322 } else {
9323 self.select_prev_state = None;
9324 }
9325
9326 self.unfold_ranges(
9327 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9328 false,
9329 true,
9330 cx,
9331 );
9332 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9333 s.select(selections);
9334 });
9335 } else if let Some(selected_text) = selected_text {
9336 self.select_prev_state = Some(SelectNextState {
9337 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9338 wordwise: false,
9339 done: false,
9340 });
9341 self.select_previous(action, window, cx)?;
9342 }
9343 }
9344 Ok(())
9345 }
9346
9347 pub fn toggle_comments(
9348 &mut self,
9349 action: &ToggleComments,
9350 window: &mut Window,
9351 cx: &mut Context<Self>,
9352 ) {
9353 if self.read_only(cx) {
9354 return;
9355 }
9356 let text_layout_details = &self.text_layout_details(window);
9357 self.transact(window, cx, |this, window, cx| {
9358 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9359 let mut edits = Vec::new();
9360 let mut selection_edit_ranges = Vec::new();
9361 let mut last_toggled_row = None;
9362 let snapshot = this.buffer.read(cx).read(cx);
9363 let empty_str: Arc<str> = Arc::default();
9364 let mut suffixes_inserted = Vec::new();
9365 let ignore_indent = action.ignore_indent;
9366
9367 fn comment_prefix_range(
9368 snapshot: &MultiBufferSnapshot,
9369 row: MultiBufferRow,
9370 comment_prefix: &str,
9371 comment_prefix_whitespace: &str,
9372 ignore_indent: bool,
9373 ) -> Range<Point> {
9374 let indent_size = if ignore_indent {
9375 0
9376 } else {
9377 snapshot.indent_size_for_line(row).len
9378 };
9379
9380 let start = Point::new(row.0, indent_size);
9381
9382 let mut line_bytes = snapshot
9383 .bytes_in_range(start..snapshot.max_point())
9384 .flatten()
9385 .copied();
9386
9387 // If this line currently begins with the line comment prefix, then record
9388 // the range containing the prefix.
9389 if line_bytes
9390 .by_ref()
9391 .take(comment_prefix.len())
9392 .eq(comment_prefix.bytes())
9393 {
9394 // Include any whitespace that matches the comment prefix.
9395 let matching_whitespace_len = line_bytes
9396 .zip(comment_prefix_whitespace.bytes())
9397 .take_while(|(a, b)| a == b)
9398 .count() as u32;
9399 let end = Point::new(
9400 start.row,
9401 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9402 );
9403 start..end
9404 } else {
9405 start..start
9406 }
9407 }
9408
9409 fn comment_suffix_range(
9410 snapshot: &MultiBufferSnapshot,
9411 row: MultiBufferRow,
9412 comment_suffix: &str,
9413 comment_suffix_has_leading_space: bool,
9414 ) -> Range<Point> {
9415 let end = Point::new(row.0, snapshot.line_len(row));
9416 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9417
9418 let mut line_end_bytes = snapshot
9419 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9420 .flatten()
9421 .copied();
9422
9423 let leading_space_len = if suffix_start_column > 0
9424 && line_end_bytes.next() == Some(b' ')
9425 && comment_suffix_has_leading_space
9426 {
9427 1
9428 } else {
9429 0
9430 };
9431
9432 // If this line currently begins with the line comment prefix, then record
9433 // the range containing the prefix.
9434 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9435 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9436 start..end
9437 } else {
9438 end..end
9439 }
9440 }
9441
9442 // TODO: Handle selections that cross excerpts
9443 for selection in &mut selections {
9444 let start_column = snapshot
9445 .indent_size_for_line(MultiBufferRow(selection.start.row))
9446 .len;
9447 let language = if let Some(language) =
9448 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9449 {
9450 language
9451 } else {
9452 continue;
9453 };
9454
9455 selection_edit_ranges.clear();
9456
9457 // If multiple selections contain a given row, avoid processing that
9458 // row more than once.
9459 let mut start_row = MultiBufferRow(selection.start.row);
9460 if last_toggled_row == Some(start_row) {
9461 start_row = start_row.next_row();
9462 }
9463 let end_row =
9464 if selection.end.row > selection.start.row && selection.end.column == 0 {
9465 MultiBufferRow(selection.end.row - 1)
9466 } else {
9467 MultiBufferRow(selection.end.row)
9468 };
9469 last_toggled_row = Some(end_row);
9470
9471 if start_row > end_row {
9472 continue;
9473 }
9474
9475 // If the language has line comments, toggle those.
9476 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9477
9478 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9479 if ignore_indent {
9480 full_comment_prefixes = full_comment_prefixes
9481 .into_iter()
9482 .map(|s| Arc::from(s.trim_end()))
9483 .collect();
9484 }
9485
9486 if !full_comment_prefixes.is_empty() {
9487 let first_prefix = full_comment_prefixes
9488 .first()
9489 .expect("prefixes is non-empty");
9490 let prefix_trimmed_lengths = full_comment_prefixes
9491 .iter()
9492 .map(|p| p.trim_end_matches(' ').len())
9493 .collect::<SmallVec<[usize; 4]>>();
9494
9495 let mut all_selection_lines_are_comments = true;
9496
9497 for row in start_row.0..=end_row.0 {
9498 let row = MultiBufferRow(row);
9499 if start_row < end_row && snapshot.is_line_blank(row) {
9500 continue;
9501 }
9502
9503 let prefix_range = full_comment_prefixes
9504 .iter()
9505 .zip(prefix_trimmed_lengths.iter().copied())
9506 .map(|(prefix, trimmed_prefix_len)| {
9507 comment_prefix_range(
9508 snapshot.deref(),
9509 row,
9510 &prefix[..trimmed_prefix_len],
9511 &prefix[trimmed_prefix_len..],
9512 ignore_indent,
9513 )
9514 })
9515 .max_by_key(|range| range.end.column - range.start.column)
9516 .expect("prefixes is non-empty");
9517
9518 if prefix_range.is_empty() {
9519 all_selection_lines_are_comments = false;
9520 }
9521
9522 selection_edit_ranges.push(prefix_range);
9523 }
9524
9525 if all_selection_lines_are_comments {
9526 edits.extend(
9527 selection_edit_ranges
9528 .iter()
9529 .cloned()
9530 .map(|range| (range, empty_str.clone())),
9531 );
9532 } else {
9533 let min_column = selection_edit_ranges
9534 .iter()
9535 .map(|range| range.start.column)
9536 .min()
9537 .unwrap_or(0);
9538 edits.extend(selection_edit_ranges.iter().map(|range| {
9539 let position = Point::new(range.start.row, min_column);
9540 (position..position, first_prefix.clone())
9541 }));
9542 }
9543 } else if let Some((full_comment_prefix, comment_suffix)) =
9544 language.block_comment_delimiters()
9545 {
9546 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9547 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9548 let prefix_range = comment_prefix_range(
9549 snapshot.deref(),
9550 start_row,
9551 comment_prefix,
9552 comment_prefix_whitespace,
9553 ignore_indent,
9554 );
9555 let suffix_range = comment_suffix_range(
9556 snapshot.deref(),
9557 end_row,
9558 comment_suffix.trim_start_matches(' '),
9559 comment_suffix.starts_with(' '),
9560 );
9561
9562 if prefix_range.is_empty() || suffix_range.is_empty() {
9563 edits.push((
9564 prefix_range.start..prefix_range.start,
9565 full_comment_prefix.clone(),
9566 ));
9567 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9568 suffixes_inserted.push((end_row, comment_suffix.len()));
9569 } else {
9570 edits.push((prefix_range, empty_str.clone()));
9571 edits.push((suffix_range, empty_str.clone()));
9572 }
9573 } else {
9574 continue;
9575 }
9576 }
9577
9578 drop(snapshot);
9579 this.buffer.update(cx, |buffer, cx| {
9580 buffer.edit(edits, None, cx);
9581 });
9582
9583 // Adjust selections so that they end before any comment suffixes that
9584 // were inserted.
9585 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9586 let mut selections = this.selections.all::<Point>(cx);
9587 let snapshot = this.buffer.read(cx).read(cx);
9588 for selection in &mut selections {
9589 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9590 match row.cmp(&MultiBufferRow(selection.end.row)) {
9591 Ordering::Less => {
9592 suffixes_inserted.next();
9593 continue;
9594 }
9595 Ordering::Greater => break,
9596 Ordering::Equal => {
9597 if selection.end.column == snapshot.line_len(row) {
9598 if selection.is_empty() {
9599 selection.start.column -= suffix_len as u32;
9600 }
9601 selection.end.column -= suffix_len as u32;
9602 }
9603 break;
9604 }
9605 }
9606 }
9607 }
9608
9609 drop(snapshot);
9610 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9611 s.select(selections)
9612 });
9613
9614 let selections = this.selections.all::<Point>(cx);
9615 let selections_on_single_row = selections.windows(2).all(|selections| {
9616 selections[0].start.row == selections[1].start.row
9617 && selections[0].end.row == selections[1].end.row
9618 && selections[0].start.row == selections[0].end.row
9619 });
9620 let selections_selecting = selections
9621 .iter()
9622 .any(|selection| selection.start != selection.end);
9623 let advance_downwards = action.advance_downwards
9624 && selections_on_single_row
9625 && !selections_selecting
9626 && !matches!(this.mode, EditorMode::SingleLine { .. });
9627
9628 if advance_downwards {
9629 let snapshot = this.buffer.read(cx).snapshot(cx);
9630
9631 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9632 s.move_cursors_with(|display_snapshot, display_point, _| {
9633 let mut point = display_point.to_point(display_snapshot);
9634 point.row += 1;
9635 point = snapshot.clip_point(point, Bias::Left);
9636 let display_point = point.to_display_point(display_snapshot);
9637 let goal = SelectionGoal::HorizontalPosition(
9638 display_snapshot
9639 .x_for_display_point(display_point, text_layout_details)
9640 .into(),
9641 );
9642 (display_point, goal)
9643 })
9644 });
9645 }
9646 });
9647 }
9648
9649 pub fn select_enclosing_symbol(
9650 &mut self,
9651 _: &SelectEnclosingSymbol,
9652 window: &mut Window,
9653 cx: &mut Context<Self>,
9654 ) {
9655 let buffer = self.buffer.read(cx).snapshot(cx);
9656 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9657
9658 fn update_selection(
9659 selection: &Selection<usize>,
9660 buffer_snap: &MultiBufferSnapshot,
9661 ) -> Option<Selection<usize>> {
9662 let cursor = selection.head();
9663 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9664 for symbol in symbols.iter().rev() {
9665 let start = symbol.range.start.to_offset(buffer_snap);
9666 let end = symbol.range.end.to_offset(buffer_snap);
9667 let new_range = start..end;
9668 if start < selection.start || end > selection.end {
9669 return Some(Selection {
9670 id: selection.id,
9671 start: new_range.start,
9672 end: new_range.end,
9673 goal: SelectionGoal::None,
9674 reversed: selection.reversed,
9675 });
9676 }
9677 }
9678 None
9679 }
9680
9681 let mut selected_larger_symbol = false;
9682 let new_selections = old_selections
9683 .iter()
9684 .map(|selection| match update_selection(selection, &buffer) {
9685 Some(new_selection) => {
9686 if new_selection.range() != selection.range() {
9687 selected_larger_symbol = true;
9688 }
9689 new_selection
9690 }
9691 None => selection.clone(),
9692 })
9693 .collect::<Vec<_>>();
9694
9695 if selected_larger_symbol {
9696 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9697 s.select(new_selections);
9698 });
9699 }
9700 }
9701
9702 pub fn select_larger_syntax_node(
9703 &mut self,
9704 _: &SelectLargerSyntaxNode,
9705 window: &mut Window,
9706 cx: &mut Context<Self>,
9707 ) {
9708 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9709 let buffer = self.buffer.read(cx).snapshot(cx);
9710 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9711
9712 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9713 let mut selected_larger_node = false;
9714 let new_selections = old_selections
9715 .iter()
9716 .map(|selection| {
9717 let old_range = selection.start..selection.end;
9718 let mut new_range = old_range.clone();
9719 let mut new_node = None;
9720 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
9721 {
9722 new_node = Some(node);
9723 new_range = containing_range;
9724 if !display_map.intersects_fold(new_range.start)
9725 && !display_map.intersects_fold(new_range.end)
9726 {
9727 break;
9728 }
9729 }
9730
9731 if let Some(node) = new_node {
9732 // Log the ancestor, to support using this action as a way to explore TreeSitter
9733 // nodes. Parent and grandparent are also logged because this operation will not
9734 // visit nodes that have the same range as their parent.
9735 log::info!("Node: {node:?}");
9736 let parent = node.parent();
9737 log::info!("Parent: {parent:?}");
9738 let grandparent = parent.and_then(|x| x.parent());
9739 log::info!("Grandparent: {grandparent:?}");
9740 }
9741
9742 selected_larger_node |= new_range != old_range;
9743 Selection {
9744 id: selection.id,
9745 start: new_range.start,
9746 end: new_range.end,
9747 goal: SelectionGoal::None,
9748 reversed: selection.reversed,
9749 }
9750 })
9751 .collect::<Vec<_>>();
9752
9753 if selected_larger_node {
9754 stack.push(old_selections);
9755 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9756 s.select(new_selections);
9757 });
9758 }
9759 self.select_larger_syntax_node_stack = stack;
9760 }
9761
9762 pub fn select_smaller_syntax_node(
9763 &mut self,
9764 _: &SelectSmallerSyntaxNode,
9765 window: &mut Window,
9766 cx: &mut Context<Self>,
9767 ) {
9768 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9769 if let Some(selections) = stack.pop() {
9770 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9771 s.select(selections.to_vec());
9772 });
9773 }
9774 self.select_larger_syntax_node_stack = stack;
9775 }
9776
9777 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
9778 if !EditorSettings::get_global(cx).gutter.runnables {
9779 self.clear_tasks();
9780 return Task::ready(());
9781 }
9782 let project = self.project.as_ref().map(Entity::downgrade);
9783 cx.spawn_in(window, |this, mut cx| async move {
9784 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
9785 let Some(project) = project.and_then(|p| p.upgrade()) else {
9786 return;
9787 };
9788 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9789 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9790 }) else {
9791 return;
9792 };
9793
9794 let hide_runnables = project
9795 .update(&mut cx, |project, cx| {
9796 // Do not display any test indicators in non-dev server remote projects.
9797 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9798 })
9799 .unwrap_or(true);
9800 if hide_runnables {
9801 return;
9802 }
9803 let new_rows =
9804 cx.background_executor()
9805 .spawn({
9806 let snapshot = display_snapshot.clone();
9807 async move {
9808 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9809 }
9810 })
9811 .await;
9812
9813 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9814 this.update(&mut cx, |this, _| {
9815 this.clear_tasks();
9816 for (key, value) in rows {
9817 this.insert_tasks(key, value);
9818 }
9819 })
9820 .ok();
9821 })
9822 }
9823 fn fetch_runnable_ranges(
9824 snapshot: &DisplaySnapshot,
9825 range: Range<Anchor>,
9826 ) -> Vec<language::RunnableRange> {
9827 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9828 }
9829
9830 fn runnable_rows(
9831 project: Entity<Project>,
9832 snapshot: DisplaySnapshot,
9833 runnable_ranges: Vec<RunnableRange>,
9834 mut cx: AsyncWindowContext,
9835 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9836 runnable_ranges
9837 .into_iter()
9838 .filter_map(|mut runnable| {
9839 let tasks = cx
9840 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9841 .ok()?;
9842 if tasks.is_empty() {
9843 return None;
9844 }
9845
9846 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9847
9848 let row = snapshot
9849 .buffer_snapshot
9850 .buffer_line_for_row(MultiBufferRow(point.row))?
9851 .1
9852 .start
9853 .row;
9854
9855 let context_range =
9856 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9857 Some((
9858 (runnable.buffer_id, row),
9859 RunnableTasks {
9860 templates: tasks,
9861 offset: MultiBufferOffset(runnable.run_range.start),
9862 context_range,
9863 column: point.column,
9864 extra_variables: runnable.extra_captures,
9865 },
9866 ))
9867 })
9868 .collect()
9869 }
9870
9871 fn templates_with_tags(
9872 project: &Entity<Project>,
9873 runnable: &mut Runnable,
9874 cx: &mut App,
9875 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9876 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9877 let (worktree_id, file) = project
9878 .buffer_for_id(runnable.buffer, cx)
9879 .and_then(|buffer| buffer.read(cx).file())
9880 .map(|file| (file.worktree_id(cx), file.clone()))
9881 .unzip();
9882
9883 (
9884 project.task_store().read(cx).task_inventory().cloned(),
9885 worktree_id,
9886 file,
9887 )
9888 });
9889
9890 let tags = mem::take(&mut runnable.tags);
9891 let mut tags: Vec<_> = tags
9892 .into_iter()
9893 .flat_map(|tag| {
9894 let tag = tag.0.clone();
9895 inventory
9896 .as_ref()
9897 .into_iter()
9898 .flat_map(|inventory| {
9899 inventory.read(cx).list_tasks(
9900 file.clone(),
9901 Some(runnable.language.clone()),
9902 worktree_id,
9903 cx,
9904 )
9905 })
9906 .filter(move |(_, template)| {
9907 template.tags.iter().any(|source_tag| source_tag == &tag)
9908 })
9909 })
9910 .sorted_by_key(|(kind, _)| kind.to_owned())
9911 .collect();
9912 if let Some((leading_tag_source, _)) = tags.first() {
9913 // Strongest source wins; if we have worktree tag binding, prefer that to
9914 // global and language bindings;
9915 // if we have a global binding, prefer that to language binding.
9916 let first_mismatch = tags
9917 .iter()
9918 .position(|(tag_source, _)| tag_source != leading_tag_source);
9919 if let Some(index) = first_mismatch {
9920 tags.truncate(index);
9921 }
9922 }
9923
9924 tags
9925 }
9926
9927 pub fn move_to_enclosing_bracket(
9928 &mut self,
9929 _: &MoveToEnclosingBracket,
9930 window: &mut Window,
9931 cx: &mut Context<Self>,
9932 ) {
9933 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9934 s.move_offsets_with(|snapshot, selection| {
9935 let Some(enclosing_bracket_ranges) =
9936 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9937 else {
9938 return;
9939 };
9940
9941 let mut best_length = usize::MAX;
9942 let mut best_inside = false;
9943 let mut best_in_bracket_range = false;
9944 let mut best_destination = None;
9945 for (open, close) in enclosing_bracket_ranges {
9946 let close = close.to_inclusive();
9947 let length = close.end() - open.start;
9948 let inside = selection.start >= open.end && selection.end <= *close.start();
9949 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9950 || close.contains(&selection.head());
9951
9952 // If best is next to a bracket and current isn't, skip
9953 if !in_bracket_range && best_in_bracket_range {
9954 continue;
9955 }
9956
9957 // Prefer smaller lengths unless best is inside and current isn't
9958 if length > best_length && (best_inside || !inside) {
9959 continue;
9960 }
9961
9962 best_length = length;
9963 best_inside = inside;
9964 best_in_bracket_range = in_bracket_range;
9965 best_destination = Some(
9966 if close.contains(&selection.start) && close.contains(&selection.end) {
9967 if inside {
9968 open.end
9969 } else {
9970 open.start
9971 }
9972 } else if inside {
9973 *close.start()
9974 } else {
9975 *close.end()
9976 },
9977 );
9978 }
9979
9980 if let Some(destination) = best_destination {
9981 selection.collapse_to(destination, SelectionGoal::None);
9982 }
9983 })
9984 });
9985 }
9986
9987 pub fn undo_selection(
9988 &mut self,
9989 _: &UndoSelection,
9990 window: &mut Window,
9991 cx: &mut Context<Self>,
9992 ) {
9993 self.end_selection(window, cx);
9994 self.selection_history.mode = SelectionHistoryMode::Undoing;
9995 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9996 self.change_selections(None, window, cx, |s| {
9997 s.select_anchors(entry.selections.to_vec())
9998 });
9999 self.select_next_state = entry.select_next_state;
10000 self.select_prev_state = entry.select_prev_state;
10001 self.add_selections_state = entry.add_selections_state;
10002 self.request_autoscroll(Autoscroll::newest(), cx);
10003 }
10004 self.selection_history.mode = SelectionHistoryMode::Normal;
10005 }
10006
10007 pub fn redo_selection(
10008 &mut self,
10009 _: &RedoSelection,
10010 window: &mut Window,
10011 cx: &mut Context<Self>,
10012 ) {
10013 self.end_selection(window, cx);
10014 self.selection_history.mode = SelectionHistoryMode::Redoing;
10015 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10016 self.change_selections(None, window, cx, |s| {
10017 s.select_anchors(entry.selections.to_vec())
10018 });
10019 self.select_next_state = entry.select_next_state;
10020 self.select_prev_state = entry.select_prev_state;
10021 self.add_selections_state = entry.add_selections_state;
10022 self.request_autoscroll(Autoscroll::newest(), cx);
10023 }
10024 self.selection_history.mode = SelectionHistoryMode::Normal;
10025 }
10026
10027 pub fn expand_excerpts(
10028 &mut self,
10029 action: &ExpandExcerpts,
10030 _: &mut Window,
10031 cx: &mut Context<Self>,
10032 ) {
10033 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10034 }
10035
10036 pub fn expand_excerpts_down(
10037 &mut self,
10038 action: &ExpandExcerptsDown,
10039 _: &mut Window,
10040 cx: &mut Context<Self>,
10041 ) {
10042 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10043 }
10044
10045 pub fn expand_excerpts_up(
10046 &mut self,
10047 action: &ExpandExcerptsUp,
10048 _: &mut Window,
10049 cx: &mut Context<Self>,
10050 ) {
10051 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10052 }
10053
10054 pub fn expand_excerpts_for_direction(
10055 &mut self,
10056 lines: u32,
10057 direction: ExpandExcerptDirection,
10058
10059 cx: &mut Context<Self>,
10060 ) {
10061 let selections = self.selections.disjoint_anchors();
10062
10063 let lines = if lines == 0 {
10064 EditorSettings::get_global(cx).expand_excerpt_lines
10065 } else {
10066 lines
10067 };
10068
10069 self.buffer.update(cx, |buffer, cx| {
10070 let snapshot = buffer.snapshot(cx);
10071 let mut excerpt_ids = selections
10072 .iter()
10073 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10074 .collect::<Vec<_>>();
10075 excerpt_ids.sort();
10076 excerpt_ids.dedup();
10077 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10078 })
10079 }
10080
10081 pub fn expand_excerpt(
10082 &mut self,
10083 excerpt: ExcerptId,
10084 direction: ExpandExcerptDirection,
10085 cx: &mut Context<Self>,
10086 ) {
10087 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10088 self.buffer.update(cx, |buffer, cx| {
10089 buffer.expand_excerpts([excerpt], lines, direction, cx)
10090 })
10091 }
10092
10093 pub fn go_to_singleton_buffer_point(
10094 &mut self,
10095 point: Point,
10096 window: &mut Window,
10097 cx: &mut Context<Self>,
10098 ) {
10099 self.go_to_singleton_buffer_range(point..point, window, cx);
10100 }
10101
10102 pub fn go_to_singleton_buffer_range(
10103 &mut self,
10104 range: Range<Point>,
10105 window: &mut Window,
10106 cx: &mut Context<Self>,
10107 ) {
10108 let multibuffer = self.buffer().read(cx);
10109 let Some(buffer) = multibuffer.as_singleton() else {
10110 return;
10111 };
10112 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10113 return;
10114 };
10115 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10116 return;
10117 };
10118 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10119 s.select_anchor_ranges([start..end])
10120 });
10121 }
10122
10123 fn go_to_diagnostic(
10124 &mut self,
10125 _: &GoToDiagnostic,
10126 window: &mut Window,
10127 cx: &mut Context<Self>,
10128 ) {
10129 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10130 }
10131
10132 fn go_to_prev_diagnostic(
10133 &mut self,
10134 _: &GoToPrevDiagnostic,
10135 window: &mut Window,
10136 cx: &mut Context<Self>,
10137 ) {
10138 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10139 }
10140
10141 pub fn go_to_diagnostic_impl(
10142 &mut self,
10143 direction: Direction,
10144 window: &mut Window,
10145 cx: &mut Context<Self>,
10146 ) {
10147 let buffer = self.buffer.read(cx).snapshot(cx);
10148 let selection = self.selections.newest::<usize>(cx);
10149
10150 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10151 if direction == Direction::Next {
10152 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10153 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10154 return;
10155 };
10156 self.activate_diagnostics(
10157 buffer_id,
10158 popover.local_diagnostic.diagnostic.group_id,
10159 window,
10160 cx,
10161 );
10162 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10163 let primary_range_start = active_diagnostics.primary_range.start;
10164 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10165 let mut new_selection = s.newest_anchor().clone();
10166 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10167 s.select_anchors(vec![new_selection.clone()]);
10168 });
10169 self.refresh_inline_completion(false, true, window, cx);
10170 }
10171 return;
10172 }
10173 }
10174
10175 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10176 active_diagnostics
10177 .primary_range
10178 .to_offset(&buffer)
10179 .to_inclusive()
10180 });
10181 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10182 if active_primary_range.contains(&selection.head()) {
10183 *active_primary_range.start()
10184 } else {
10185 selection.head()
10186 }
10187 } else {
10188 selection.head()
10189 };
10190 let snapshot = self.snapshot(window, cx);
10191 loop {
10192 let mut diagnostics;
10193 if direction == Direction::Prev {
10194 diagnostics = buffer
10195 .diagnostics_in_range::<_, usize>(0..search_start)
10196 .collect::<Vec<_>>();
10197 diagnostics.reverse();
10198 } else {
10199 diagnostics = buffer
10200 .diagnostics_in_range::<_, usize>(search_start..buffer.len())
10201 .collect::<Vec<_>>();
10202 };
10203 let group = diagnostics
10204 .into_iter()
10205 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10206 // relies on diagnostics_in_range to return diagnostics with the same starting range to
10207 // be sorted in a stable way
10208 // skip until we are at current active diagnostic, if it exists
10209 .skip_while(|entry| {
10210 let is_in_range = match direction {
10211 Direction::Prev => entry.range.end > search_start,
10212 Direction::Next => entry.range.start < search_start,
10213 };
10214 is_in_range
10215 && self
10216 .active_diagnostics
10217 .as_ref()
10218 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
10219 })
10220 .find_map(|entry| {
10221 if entry.diagnostic.is_primary
10222 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
10223 && entry.range.start != entry.range.end
10224 // if we match with the active diagnostic, skip it
10225 && Some(entry.diagnostic.group_id)
10226 != self.active_diagnostics.as_ref().map(|d| d.group_id)
10227 {
10228 Some((entry.range, entry.diagnostic.group_id))
10229 } else {
10230 None
10231 }
10232 });
10233
10234 if let Some((primary_range, group_id)) = group {
10235 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10236 return;
10237 };
10238 self.activate_diagnostics(buffer_id, group_id, window, cx);
10239 if self.active_diagnostics.is_some() {
10240 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10241 s.select(vec![Selection {
10242 id: selection.id,
10243 start: primary_range.start,
10244 end: primary_range.start,
10245 reversed: false,
10246 goal: SelectionGoal::None,
10247 }]);
10248 });
10249 self.refresh_inline_completion(false, true, window, cx);
10250 }
10251 break;
10252 } else {
10253 // Cycle around to the start of the buffer, potentially moving back to the start of
10254 // the currently active diagnostic.
10255 active_primary_range.take();
10256 if direction == Direction::Prev {
10257 if search_start == buffer.len() {
10258 break;
10259 } else {
10260 search_start = buffer.len();
10261 }
10262 } else if search_start == 0 {
10263 break;
10264 } else {
10265 search_start = 0;
10266 }
10267 }
10268 }
10269 }
10270
10271 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10272 let snapshot = self.snapshot(window, cx);
10273 let selection = self.selections.newest::<Point>(cx);
10274 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10275 }
10276
10277 fn go_to_hunk_after_position(
10278 &mut self,
10279 snapshot: &EditorSnapshot,
10280 position: Point,
10281 window: &mut Window,
10282 cx: &mut Context<Editor>,
10283 ) -> Option<MultiBufferDiffHunk> {
10284 let mut hunk = snapshot
10285 .buffer_snapshot
10286 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10287 .find(|hunk| hunk.row_range.start.0 > position.row);
10288 if hunk.is_none() {
10289 hunk = snapshot
10290 .buffer_snapshot
10291 .diff_hunks_in_range(Point::zero()..position)
10292 .find(|hunk| hunk.row_range.end.0 < position.row)
10293 }
10294 if let Some(hunk) = &hunk {
10295 let destination = Point::new(hunk.row_range.start.0, 0);
10296 self.unfold_ranges(&[destination..destination], false, false, cx);
10297 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10298 s.select_ranges(vec![destination..destination]);
10299 });
10300 }
10301
10302 hunk
10303 }
10304
10305 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10306 let snapshot = self.snapshot(window, cx);
10307 let selection = self.selections.newest::<Point>(cx);
10308 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10309 }
10310
10311 fn go_to_hunk_before_position(
10312 &mut self,
10313 snapshot: &EditorSnapshot,
10314 position: Point,
10315 window: &mut Window,
10316 cx: &mut Context<Editor>,
10317 ) -> Option<MultiBufferDiffHunk> {
10318 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10319 if hunk.is_none() {
10320 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10321 }
10322 if let Some(hunk) = &hunk {
10323 let destination = Point::new(hunk.row_range.start.0, 0);
10324 self.unfold_ranges(&[destination..destination], false, false, cx);
10325 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10326 s.select_ranges(vec![destination..destination]);
10327 });
10328 }
10329
10330 hunk
10331 }
10332
10333 pub fn go_to_definition(
10334 &mut self,
10335 _: &GoToDefinition,
10336 window: &mut Window,
10337 cx: &mut Context<Self>,
10338 ) -> Task<Result<Navigated>> {
10339 let definition =
10340 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10341 cx.spawn_in(window, |editor, mut cx| async move {
10342 if definition.await? == Navigated::Yes {
10343 return Ok(Navigated::Yes);
10344 }
10345 match editor.update_in(&mut cx, |editor, window, cx| {
10346 editor.find_all_references(&FindAllReferences, window, cx)
10347 })? {
10348 Some(references) => references.await,
10349 None => Ok(Navigated::No),
10350 }
10351 })
10352 }
10353
10354 pub fn go_to_declaration(
10355 &mut self,
10356 _: &GoToDeclaration,
10357 window: &mut Window,
10358 cx: &mut Context<Self>,
10359 ) -> Task<Result<Navigated>> {
10360 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10361 }
10362
10363 pub fn go_to_declaration_split(
10364 &mut self,
10365 _: &GoToDeclaration,
10366 window: &mut Window,
10367 cx: &mut Context<Self>,
10368 ) -> Task<Result<Navigated>> {
10369 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10370 }
10371
10372 pub fn go_to_implementation(
10373 &mut self,
10374 _: &GoToImplementation,
10375 window: &mut Window,
10376 cx: &mut Context<Self>,
10377 ) -> Task<Result<Navigated>> {
10378 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10379 }
10380
10381 pub fn go_to_implementation_split(
10382 &mut self,
10383 _: &GoToImplementationSplit,
10384 window: &mut Window,
10385 cx: &mut Context<Self>,
10386 ) -> Task<Result<Navigated>> {
10387 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10388 }
10389
10390 pub fn go_to_type_definition(
10391 &mut self,
10392 _: &GoToTypeDefinition,
10393 window: &mut Window,
10394 cx: &mut Context<Self>,
10395 ) -> Task<Result<Navigated>> {
10396 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10397 }
10398
10399 pub fn go_to_definition_split(
10400 &mut self,
10401 _: &GoToDefinitionSplit,
10402 window: &mut Window,
10403 cx: &mut Context<Self>,
10404 ) -> Task<Result<Navigated>> {
10405 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10406 }
10407
10408 pub fn go_to_type_definition_split(
10409 &mut self,
10410 _: &GoToTypeDefinitionSplit,
10411 window: &mut Window,
10412 cx: &mut Context<Self>,
10413 ) -> Task<Result<Navigated>> {
10414 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10415 }
10416
10417 fn go_to_definition_of_kind(
10418 &mut self,
10419 kind: GotoDefinitionKind,
10420 split: bool,
10421 window: &mut Window,
10422 cx: &mut Context<Self>,
10423 ) -> Task<Result<Navigated>> {
10424 let Some(provider) = self.semantics_provider.clone() else {
10425 return Task::ready(Ok(Navigated::No));
10426 };
10427 let head = self.selections.newest::<usize>(cx).head();
10428 let buffer = self.buffer.read(cx);
10429 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10430 text_anchor
10431 } else {
10432 return Task::ready(Ok(Navigated::No));
10433 };
10434
10435 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10436 return Task::ready(Ok(Navigated::No));
10437 };
10438
10439 cx.spawn_in(window, |editor, mut cx| async move {
10440 let definitions = definitions.await?;
10441 let navigated = editor
10442 .update_in(&mut cx, |editor, window, cx| {
10443 editor.navigate_to_hover_links(
10444 Some(kind),
10445 definitions
10446 .into_iter()
10447 .filter(|location| {
10448 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10449 })
10450 .map(HoverLink::Text)
10451 .collect::<Vec<_>>(),
10452 split,
10453 window,
10454 cx,
10455 )
10456 })?
10457 .await?;
10458 anyhow::Ok(navigated)
10459 })
10460 }
10461
10462 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10463 let selection = self.selections.newest_anchor();
10464 let head = selection.head();
10465 let tail = selection.tail();
10466
10467 let Some((buffer, start_position)) =
10468 self.buffer.read(cx).text_anchor_for_position(head, cx)
10469 else {
10470 return;
10471 };
10472
10473 let end_position = if head != tail {
10474 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10475 return;
10476 };
10477 Some(pos)
10478 } else {
10479 None
10480 };
10481
10482 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10483 let url = if let Some(end_pos) = end_position {
10484 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10485 } else {
10486 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10487 };
10488
10489 if let Some(url) = url {
10490 editor.update(&mut cx, |_, cx| {
10491 cx.open_url(&url);
10492 })
10493 } else {
10494 Ok(())
10495 }
10496 });
10497
10498 url_finder.detach();
10499 }
10500
10501 pub fn open_selected_filename(
10502 &mut self,
10503 _: &OpenSelectedFilename,
10504 window: &mut Window,
10505 cx: &mut Context<Self>,
10506 ) {
10507 let Some(workspace) = self.workspace() else {
10508 return;
10509 };
10510
10511 let position = self.selections.newest_anchor().head();
10512
10513 let Some((buffer, buffer_position)) =
10514 self.buffer.read(cx).text_anchor_for_position(position, cx)
10515 else {
10516 return;
10517 };
10518
10519 let project = self.project.clone();
10520
10521 cx.spawn_in(window, |_, mut cx| async move {
10522 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10523
10524 if let Some((_, path)) = result {
10525 workspace
10526 .update_in(&mut cx, |workspace, window, cx| {
10527 workspace.open_resolved_path(path, window, cx)
10528 })?
10529 .await?;
10530 }
10531 anyhow::Ok(())
10532 })
10533 .detach();
10534 }
10535
10536 pub(crate) fn navigate_to_hover_links(
10537 &mut self,
10538 kind: Option<GotoDefinitionKind>,
10539 mut definitions: Vec<HoverLink>,
10540 split: bool,
10541 window: &mut Window,
10542 cx: &mut Context<Editor>,
10543 ) -> Task<Result<Navigated>> {
10544 // If there is one definition, just open it directly
10545 if definitions.len() == 1 {
10546 let definition = definitions.pop().unwrap();
10547
10548 enum TargetTaskResult {
10549 Location(Option<Location>),
10550 AlreadyNavigated,
10551 }
10552
10553 let target_task = match definition {
10554 HoverLink::Text(link) => {
10555 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10556 }
10557 HoverLink::InlayHint(lsp_location, server_id) => {
10558 let computation =
10559 self.compute_target_location(lsp_location, server_id, window, cx);
10560 cx.background_executor().spawn(async move {
10561 let location = computation.await?;
10562 Ok(TargetTaskResult::Location(location))
10563 })
10564 }
10565 HoverLink::Url(url) => {
10566 cx.open_url(&url);
10567 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10568 }
10569 HoverLink::File(path) => {
10570 if let Some(workspace) = self.workspace() {
10571 cx.spawn_in(window, |_, mut cx| async move {
10572 workspace
10573 .update_in(&mut cx, |workspace, window, cx| {
10574 workspace.open_resolved_path(path, window, cx)
10575 })?
10576 .await
10577 .map(|_| TargetTaskResult::AlreadyNavigated)
10578 })
10579 } else {
10580 Task::ready(Ok(TargetTaskResult::Location(None)))
10581 }
10582 }
10583 };
10584 cx.spawn_in(window, |editor, mut cx| async move {
10585 let target = match target_task.await.context("target resolution task")? {
10586 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10587 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10588 TargetTaskResult::Location(Some(target)) => target,
10589 };
10590
10591 editor.update_in(&mut cx, |editor, window, cx| {
10592 let Some(workspace) = editor.workspace() else {
10593 return Navigated::No;
10594 };
10595 let pane = workspace.read(cx).active_pane().clone();
10596
10597 let range = target.range.to_point(target.buffer.read(cx));
10598 let range = editor.range_for_match(&range);
10599 let range = collapse_multiline_range(range);
10600
10601 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10602 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10603 } else {
10604 window.defer(cx, move |window, cx| {
10605 let target_editor: Entity<Self> =
10606 workspace.update(cx, |workspace, cx| {
10607 let pane = if split {
10608 workspace.adjacent_pane(window, cx)
10609 } else {
10610 workspace.active_pane().clone()
10611 };
10612
10613 workspace.open_project_item(
10614 pane,
10615 target.buffer.clone(),
10616 true,
10617 true,
10618 window,
10619 cx,
10620 )
10621 });
10622 target_editor.update(cx, |target_editor, cx| {
10623 // When selecting a definition in a different buffer, disable the nav history
10624 // to avoid creating a history entry at the previous cursor location.
10625 pane.update(cx, |pane, _| pane.disable_history());
10626 target_editor.go_to_singleton_buffer_range(range, window, cx);
10627 pane.update(cx, |pane, _| pane.enable_history());
10628 });
10629 });
10630 }
10631 Navigated::Yes
10632 })
10633 })
10634 } else if !definitions.is_empty() {
10635 cx.spawn_in(window, |editor, mut cx| async move {
10636 let (title, location_tasks, workspace) = editor
10637 .update_in(&mut cx, |editor, window, cx| {
10638 let tab_kind = match kind {
10639 Some(GotoDefinitionKind::Implementation) => "Implementations",
10640 _ => "Definitions",
10641 };
10642 let title = definitions
10643 .iter()
10644 .find_map(|definition| match definition {
10645 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10646 let buffer = origin.buffer.read(cx);
10647 format!(
10648 "{} for {}",
10649 tab_kind,
10650 buffer
10651 .text_for_range(origin.range.clone())
10652 .collect::<String>()
10653 )
10654 }),
10655 HoverLink::InlayHint(_, _) => None,
10656 HoverLink::Url(_) => None,
10657 HoverLink::File(_) => None,
10658 })
10659 .unwrap_or(tab_kind.to_string());
10660 let location_tasks = definitions
10661 .into_iter()
10662 .map(|definition| match definition {
10663 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10664 HoverLink::InlayHint(lsp_location, server_id) => editor
10665 .compute_target_location(lsp_location, server_id, window, cx),
10666 HoverLink::Url(_) => Task::ready(Ok(None)),
10667 HoverLink::File(_) => Task::ready(Ok(None)),
10668 })
10669 .collect::<Vec<_>>();
10670 (title, location_tasks, editor.workspace().clone())
10671 })
10672 .context("location tasks preparation")?;
10673
10674 let locations = future::join_all(location_tasks)
10675 .await
10676 .into_iter()
10677 .filter_map(|location| location.transpose())
10678 .collect::<Result<_>>()
10679 .context("location tasks")?;
10680
10681 let Some(workspace) = workspace else {
10682 return Ok(Navigated::No);
10683 };
10684 let opened = workspace
10685 .update_in(&mut cx, |workspace, window, cx| {
10686 Self::open_locations_in_multibuffer(
10687 workspace,
10688 locations,
10689 title,
10690 split,
10691 MultibufferSelectionMode::First,
10692 window,
10693 cx,
10694 )
10695 })
10696 .ok();
10697
10698 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10699 })
10700 } else {
10701 Task::ready(Ok(Navigated::No))
10702 }
10703 }
10704
10705 fn compute_target_location(
10706 &self,
10707 lsp_location: lsp::Location,
10708 server_id: LanguageServerId,
10709 window: &mut Window,
10710 cx: &mut Context<Self>,
10711 ) -> Task<anyhow::Result<Option<Location>>> {
10712 let Some(project) = self.project.clone() else {
10713 return Task::ready(Ok(None));
10714 };
10715
10716 cx.spawn_in(window, move |editor, mut cx| async move {
10717 let location_task = editor.update(&mut cx, |_, cx| {
10718 project.update(cx, |project, cx| {
10719 let language_server_name = project
10720 .language_server_statuses(cx)
10721 .find(|(id, _)| server_id == *id)
10722 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10723 language_server_name.map(|language_server_name| {
10724 project.open_local_buffer_via_lsp(
10725 lsp_location.uri.clone(),
10726 server_id,
10727 language_server_name,
10728 cx,
10729 )
10730 })
10731 })
10732 })?;
10733 let location = match location_task {
10734 Some(task) => Some({
10735 let target_buffer_handle = task.await.context("open local buffer")?;
10736 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10737 let target_start = target_buffer
10738 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10739 let target_end = target_buffer
10740 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10741 target_buffer.anchor_after(target_start)
10742 ..target_buffer.anchor_before(target_end)
10743 })?;
10744 Location {
10745 buffer: target_buffer_handle,
10746 range,
10747 }
10748 }),
10749 None => None,
10750 };
10751 Ok(location)
10752 })
10753 }
10754
10755 pub fn find_all_references(
10756 &mut self,
10757 _: &FindAllReferences,
10758 window: &mut Window,
10759 cx: &mut Context<Self>,
10760 ) -> Option<Task<Result<Navigated>>> {
10761 let selection = self.selections.newest::<usize>(cx);
10762 let multi_buffer = self.buffer.read(cx);
10763 let head = selection.head();
10764
10765 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10766 let head_anchor = multi_buffer_snapshot.anchor_at(
10767 head,
10768 if head < selection.tail() {
10769 Bias::Right
10770 } else {
10771 Bias::Left
10772 },
10773 );
10774
10775 match self
10776 .find_all_references_task_sources
10777 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10778 {
10779 Ok(_) => {
10780 log::info!(
10781 "Ignoring repeated FindAllReferences invocation with the position of already running task"
10782 );
10783 return None;
10784 }
10785 Err(i) => {
10786 self.find_all_references_task_sources.insert(i, head_anchor);
10787 }
10788 }
10789
10790 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10791 let workspace = self.workspace()?;
10792 let project = workspace.read(cx).project().clone();
10793 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10794 Some(cx.spawn_in(window, |editor, mut cx| async move {
10795 let _cleanup = defer({
10796 let mut cx = cx.clone();
10797 move || {
10798 let _ = editor.update(&mut cx, |editor, _| {
10799 if let Ok(i) =
10800 editor
10801 .find_all_references_task_sources
10802 .binary_search_by(|anchor| {
10803 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10804 })
10805 {
10806 editor.find_all_references_task_sources.remove(i);
10807 }
10808 });
10809 }
10810 });
10811
10812 let locations = references.await?;
10813 if locations.is_empty() {
10814 return anyhow::Ok(Navigated::No);
10815 }
10816
10817 workspace.update_in(&mut cx, |workspace, window, cx| {
10818 let title = locations
10819 .first()
10820 .as_ref()
10821 .map(|location| {
10822 let buffer = location.buffer.read(cx);
10823 format!(
10824 "References to `{}`",
10825 buffer
10826 .text_for_range(location.range.clone())
10827 .collect::<String>()
10828 )
10829 })
10830 .unwrap();
10831 Self::open_locations_in_multibuffer(
10832 workspace,
10833 locations,
10834 title,
10835 false,
10836 MultibufferSelectionMode::First,
10837 window,
10838 cx,
10839 );
10840 Navigated::Yes
10841 })
10842 }))
10843 }
10844
10845 /// Opens a multibuffer with the given project locations in it
10846 pub fn open_locations_in_multibuffer(
10847 workspace: &mut Workspace,
10848 mut locations: Vec<Location>,
10849 title: String,
10850 split: bool,
10851 multibuffer_selection_mode: MultibufferSelectionMode,
10852 window: &mut Window,
10853 cx: &mut Context<Workspace>,
10854 ) {
10855 // If there are multiple definitions, open them in a multibuffer
10856 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10857 let mut locations = locations.into_iter().peekable();
10858 let mut ranges = Vec::new();
10859 let capability = workspace.project().read(cx).capability();
10860
10861 let excerpt_buffer = cx.new(|cx| {
10862 let mut multibuffer = MultiBuffer::new(capability);
10863 while let Some(location) = locations.next() {
10864 let buffer = location.buffer.read(cx);
10865 let mut ranges_for_buffer = Vec::new();
10866 let range = location.range.to_offset(buffer);
10867 ranges_for_buffer.push(range.clone());
10868
10869 while let Some(next_location) = locations.peek() {
10870 if next_location.buffer == location.buffer {
10871 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10872 locations.next();
10873 } else {
10874 break;
10875 }
10876 }
10877
10878 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10879 ranges.extend(multibuffer.push_excerpts_with_context_lines(
10880 location.buffer.clone(),
10881 ranges_for_buffer,
10882 DEFAULT_MULTIBUFFER_CONTEXT,
10883 cx,
10884 ))
10885 }
10886
10887 multibuffer.with_title(title)
10888 });
10889
10890 let editor = cx.new(|cx| {
10891 Editor::for_multibuffer(
10892 excerpt_buffer,
10893 Some(workspace.project().clone()),
10894 true,
10895 window,
10896 cx,
10897 )
10898 });
10899 editor.update(cx, |editor, cx| {
10900 match multibuffer_selection_mode {
10901 MultibufferSelectionMode::First => {
10902 if let Some(first_range) = ranges.first() {
10903 editor.change_selections(None, window, cx, |selections| {
10904 selections.clear_disjoint();
10905 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10906 });
10907 }
10908 editor.highlight_background::<Self>(
10909 &ranges,
10910 |theme| theme.editor_highlighted_line_background,
10911 cx,
10912 );
10913 }
10914 MultibufferSelectionMode::All => {
10915 editor.change_selections(None, window, cx, |selections| {
10916 selections.clear_disjoint();
10917 selections.select_anchor_ranges(ranges);
10918 });
10919 }
10920 }
10921 editor.register_buffers_with_language_servers(cx);
10922 });
10923
10924 let item = Box::new(editor);
10925 let item_id = item.item_id();
10926
10927 if split {
10928 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
10929 } else {
10930 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10931 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10932 pane.close_current_preview_item(window, cx)
10933 } else {
10934 None
10935 }
10936 });
10937 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
10938 }
10939 workspace.active_pane().update(cx, |pane, cx| {
10940 pane.set_preview_item_id(Some(item_id), cx);
10941 });
10942 }
10943
10944 pub fn rename(
10945 &mut self,
10946 _: &Rename,
10947 window: &mut Window,
10948 cx: &mut Context<Self>,
10949 ) -> Option<Task<Result<()>>> {
10950 use language::ToOffset as _;
10951
10952 let provider = self.semantics_provider.clone()?;
10953 let selection = self.selections.newest_anchor().clone();
10954 let (cursor_buffer, cursor_buffer_position) = self
10955 .buffer
10956 .read(cx)
10957 .text_anchor_for_position(selection.head(), cx)?;
10958 let (tail_buffer, cursor_buffer_position_end) = self
10959 .buffer
10960 .read(cx)
10961 .text_anchor_for_position(selection.tail(), cx)?;
10962 if tail_buffer != cursor_buffer {
10963 return None;
10964 }
10965
10966 let snapshot = cursor_buffer.read(cx).snapshot();
10967 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10968 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10969 let prepare_rename = provider
10970 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10971 .unwrap_or_else(|| Task::ready(Ok(None)));
10972 drop(snapshot);
10973
10974 Some(cx.spawn_in(window, |this, mut cx| async move {
10975 let rename_range = if let Some(range) = prepare_rename.await? {
10976 Some(range)
10977 } else {
10978 this.update(&mut cx, |this, cx| {
10979 let buffer = this.buffer.read(cx).snapshot(cx);
10980 let mut buffer_highlights = this
10981 .document_highlights_for_position(selection.head(), &buffer)
10982 .filter(|highlight| {
10983 highlight.start.excerpt_id == selection.head().excerpt_id
10984 && highlight.end.excerpt_id == selection.head().excerpt_id
10985 });
10986 buffer_highlights
10987 .next()
10988 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10989 })?
10990 };
10991 if let Some(rename_range) = rename_range {
10992 this.update_in(&mut cx, |this, window, cx| {
10993 let snapshot = cursor_buffer.read(cx).snapshot();
10994 let rename_buffer_range = rename_range.to_offset(&snapshot);
10995 let cursor_offset_in_rename_range =
10996 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10997 let cursor_offset_in_rename_range_end =
10998 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10999
11000 this.take_rename(false, window, cx);
11001 let buffer = this.buffer.read(cx).read(cx);
11002 let cursor_offset = selection.head().to_offset(&buffer);
11003 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11004 let rename_end = rename_start + rename_buffer_range.len();
11005 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11006 let mut old_highlight_id = None;
11007 let old_name: Arc<str> = buffer
11008 .chunks(rename_start..rename_end, true)
11009 .map(|chunk| {
11010 if old_highlight_id.is_none() {
11011 old_highlight_id = chunk.syntax_highlight_id;
11012 }
11013 chunk.text
11014 })
11015 .collect::<String>()
11016 .into();
11017
11018 drop(buffer);
11019
11020 // Position the selection in the rename editor so that it matches the current selection.
11021 this.show_local_selections = false;
11022 let rename_editor = cx.new(|cx| {
11023 let mut editor = Editor::single_line(window, cx);
11024 editor.buffer.update(cx, |buffer, cx| {
11025 buffer.edit([(0..0, old_name.clone())], None, cx)
11026 });
11027 let rename_selection_range = match cursor_offset_in_rename_range
11028 .cmp(&cursor_offset_in_rename_range_end)
11029 {
11030 Ordering::Equal => {
11031 editor.select_all(&SelectAll, window, cx);
11032 return editor;
11033 }
11034 Ordering::Less => {
11035 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11036 }
11037 Ordering::Greater => {
11038 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11039 }
11040 };
11041 if rename_selection_range.end > old_name.len() {
11042 editor.select_all(&SelectAll, window, cx);
11043 } else {
11044 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11045 s.select_ranges([rename_selection_range]);
11046 });
11047 }
11048 editor
11049 });
11050 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11051 if e == &EditorEvent::Focused {
11052 cx.emit(EditorEvent::FocusedIn)
11053 }
11054 })
11055 .detach();
11056
11057 let write_highlights =
11058 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11059 let read_highlights =
11060 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11061 let ranges = write_highlights
11062 .iter()
11063 .flat_map(|(_, ranges)| ranges.iter())
11064 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11065 .cloned()
11066 .collect();
11067
11068 this.highlight_text::<Rename>(
11069 ranges,
11070 HighlightStyle {
11071 fade_out: Some(0.6),
11072 ..Default::default()
11073 },
11074 cx,
11075 );
11076 let rename_focus_handle = rename_editor.focus_handle(cx);
11077 window.focus(&rename_focus_handle);
11078 let block_id = this.insert_blocks(
11079 [BlockProperties {
11080 style: BlockStyle::Flex,
11081 placement: BlockPlacement::Below(range.start),
11082 height: 1,
11083 render: Arc::new({
11084 let rename_editor = rename_editor.clone();
11085 move |cx: &mut BlockContext| {
11086 let mut text_style = cx.editor_style.text.clone();
11087 if let Some(highlight_style) = old_highlight_id
11088 .and_then(|h| h.style(&cx.editor_style.syntax))
11089 {
11090 text_style = text_style.highlight(highlight_style);
11091 }
11092 div()
11093 .block_mouse_down()
11094 .pl(cx.anchor_x)
11095 .child(EditorElement::new(
11096 &rename_editor,
11097 EditorStyle {
11098 background: cx.theme().system().transparent,
11099 local_player: cx.editor_style.local_player,
11100 text: text_style,
11101 scrollbar_width: cx.editor_style.scrollbar_width,
11102 syntax: cx.editor_style.syntax.clone(),
11103 status: cx.editor_style.status.clone(),
11104 inlay_hints_style: HighlightStyle {
11105 font_weight: Some(FontWeight::BOLD),
11106 ..make_inlay_hints_style(cx.app)
11107 },
11108 inline_completion_styles: make_suggestion_styles(
11109 cx.app,
11110 ),
11111 ..EditorStyle::default()
11112 },
11113 ))
11114 .into_any_element()
11115 }
11116 }),
11117 priority: 0,
11118 }],
11119 Some(Autoscroll::fit()),
11120 cx,
11121 )[0];
11122 this.pending_rename = Some(RenameState {
11123 range,
11124 old_name,
11125 editor: rename_editor,
11126 block_id,
11127 });
11128 })?;
11129 }
11130
11131 Ok(())
11132 }))
11133 }
11134
11135 pub fn confirm_rename(
11136 &mut self,
11137 _: &ConfirmRename,
11138 window: &mut Window,
11139 cx: &mut Context<Self>,
11140 ) -> Option<Task<Result<()>>> {
11141 let rename = self.take_rename(false, window, cx)?;
11142 let workspace = self.workspace()?.downgrade();
11143 let (buffer, start) = self
11144 .buffer
11145 .read(cx)
11146 .text_anchor_for_position(rename.range.start, cx)?;
11147 let (end_buffer, _) = self
11148 .buffer
11149 .read(cx)
11150 .text_anchor_for_position(rename.range.end, cx)?;
11151 if buffer != end_buffer {
11152 return None;
11153 }
11154
11155 let old_name = rename.old_name;
11156 let new_name = rename.editor.read(cx).text(cx);
11157
11158 let rename = self.semantics_provider.as_ref()?.perform_rename(
11159 &buffer,
11160 start,
11161 new_name.clone(),
11162 cx,
11163 )?;
11164
11165 Some(cx.spawn_in(window, |editor, mut cx| async move {
11166 let project_transaction = rename.await?;
11167 Self::open_project_transaction(
11168 &editor,
11169 workspace,
11170 project_transaction,
11171 format!("Rename: {} → {}", old_name, new_name),
11172 cx.clone(),
11173 )
11174 .await?;
11175
11176 editor.update(&mut cx, |editor, cx| {
11177 editor.refresh_document_highlights(cx);
11178 })?;
11179 Ok(())
11180 }))
11181 }
11182
11183 fn take_rename(
11184 &mut self,
11185 moving_cursor: bool,
11186 window: &mut Window,
11187 cx: &mut Context<Self>,
11188 ) -> Option<RenameState> {
11189 let rename = self.pending_rename.take()?;
11190 if rename.editor.focus_handle(cx).is_focused(window) {
11191 window.focus(&self.focus_handle);
11192 }
11193
11194 self.remove_blocks(
11195 [rename.block_id].into_iter().collect(),
11196 Some(Autoscroll::fit()),
11197 cx,
11198 );
11199 self.clear_highlights::<Rename>(cx);
11200 self.show_local_selections = true;
11201
11202 if moving_cursor {
11203 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11204 editor.selections.newest::<usize>(cx).head()
11205 });
11206
11207 // Update the selection to match the position of the selection inside
11208 // the rename editor.
11209 let snapshot = self.buffer.read(cx).read(cx);
11210 let rename_range = rename.range.to_offset(&snapshot);
11211 let cursor_in_editor = snapshot
11212 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11213 .min(rename_range.end);
11214 drop(snapshot);
11215
11216 self.change_selections(None, window, cx, |s| {
11217 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11218 });
11219 } else {
11220 self.refresh_document_highlights(cx);
11221 }
11222
11223 Some(rename)
11224 }
11225
11226 pub fn pending_rename(&self) -> Option<&RenameState> {
11227 self.pending_rename.as_ref()
11228 }
11229
11230 fn format(
11231 &mut self,
11232 _: &Format,
11233 window: &mut Window,
11234 cx: &mut Context<Self>,
11235 ) -> Option<Task<Result<()>>> {
11236 let project = match &self.project {
11237 Some(project) => project.clone(),
11238 None => return None,
11239 };
11240
11241 Some(self.perform_format(
11242 project,
11243 FormatTrigger::Manual,
11244 FormatTarget::Buffers,
11245 window,
11246 cx,
11247 ))
11248 }
11249
11250 fn format_selections(
11251 &mut self,
11252 _: &FormatSelections,
11253 window: &mut Window,
11254 cx: &mut Context<Self>,
11255 ) -> Option<Task<Result<()>>> {
11256 let project = match &self.project {
11257 Some(project) => project.clone(),
11258 None => return None,
11259 };
11260
11261 let ranges = self
11262 .selections
11263 .all_adjusted(cx)
11264 .into_iter()
11265 .map(|selection| selection.range())
11266 .collect_vec();
11267
11268 Some(self.perform_format(
11269 project,
11270 FormatTrigger::Manual,
11271 FormatTarget::Ranges(ranges),
11272 window,
11273 cx,
11274 ))
11275 }
11276
11277 fn perform_format(
11278 &mut self,
11279 project: Entity<Project>,
11280 trigger: FormatTrigger,
11281 target: FormatTarget,
11282 window: &mut Window,
11283 cx: &mut Context<Self>,
11284 ) -> Task<Result<()>> {
11285 let buffer = self.buffer.clone();
11286 let (buffers, target) = match target {
11287 FormatTarget::Buffers => {
11288 let mut buffers = buffer.read(cx).all_buffers();
11289 if trigger == FormatTrigger::Save {
11290 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11291 }
11292 (buffers, LspFormatTarget::Buffers)
11293 }
11294 FormatTarget::Ranges(selection_ranges) => {
11295 let multi_buffer = buffer.read(cx);
11296 let snapshot = multi_buffer.read(cx);
11297 let mut buffers = HashSet::default();
11298 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11299 BTreeMap::new();
11300 for selection_range in selection_ranges {
11301 for (buffer, buffer_range, _) in
11302 snapshot.range_to_buffer_ranges(selection_range)
11303 {
11304 let buffer_id = buffer.remote_id();
11305 let start = buffer.anchor_before(buffer_range.start);
11306 let end = buffer.anchor_after(buffer_range.end);
11307 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11308 buffer_id_to_ranges
11309 .entry(buffer_id)
11310 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11311 .or_insert_with(|| vec![start..end]);
11312 }
11313 }
11314 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11315 }
11316 };
11317
11318 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11319 let format = project.update(cx, |project, cx| {
11320 project.format(buffers, target, true, trigger, cx)
11321 });
11322
11323 cx.spawn_in(window, |_, mut cx| async move {
11324 let transaction = futures::select_biased! {
11325 () = timeout => {
11326 log::warn!("timed out waiting for formatting");
11327 None
11328 }
11329 transaction = format.log_err().fuse() => transaction,
11330 };
11331
11332 buffer
11333 .update(&mut cx, |buffer, cx| {
11334 if let Some(transaction) = transaction {
11335 if !buffer.is_singleton() {
11336 buffer.push_transaction(&transaction.0, cx);
11337 }
11338 }
11339
11340 cx.notify();
11341 })
11342 .ok();
11343
11344 Ok(())
11345 })
11346 }
11347
11348 fn restart_language_server(
11349 &mut self,
11350 _: &RestartLanguageServer,
11351 _: &mut Window,
11352 cx: &mut Context<Self>,
11353 ) {
11354 if let Some(project) = self.project.clone() {
11355 self.buffer.update(cx, |multi_buffer, cx| {
11356 project.update(cx, |project, cx| {
11357 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11358 });
11359 })
11360 }
11361 }
11362
11363 fn cancel_language_server_work(
11364 &mut self,
11365 _: &actions::CancelLanguageServerWork,
11366 _: &mut Window,
11367 cx: &mut Context<Self>,
11368 ) {
11369 if let Some(project) = self.project.clone() {
11370 self.buffer.update(cx, |multi_buffer, cx| {
11371 project.update(cx, |project, cx| {
11372 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
11373 });
11374 })
11375 }
11376 }
11377
11378 fn show_character_palette(
11379 &mut self,
11380 _: &ShowCharacterPalette,
11381 window: &mut Window,
11382 _: &mut Context<Self>,
11383 ) {
11384 window.show_character_palette();
11385 }
11386
11387 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11388 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11389 let buffer = self.buffer.read(cx).snapshot(cx);
11390 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11391 let is_valid = buffer
11392 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone())
11393 .any(|entry| {
11394 entry.diagnostic.is_primary
11395 && !entry.range.is_empty()
11396 && entry.range.start == primary_range_start
11397 && entry.diagnostic.message == active_diagnostics.primary_message
11398 });
11399
11400 if is_valid != active_diagnostics.is_valid {
11401 active_diagnostics.is_valid = is_valid;
11402 let mut new_styles = HashMap::default();
11403 for (block_id, diagnostic) in &active_diagnostics.blocks {
11404 new_styles.insert(
11405 *block_id,
11406 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11407 );
11408 }
11409 self.display_map.update(cx, |display_map, _cx| {
11410 display_map.replace_blocks(new_styles)
11411 });
11412 }
11413 }
11414 }
11415
11416 fn activate_diagnostics(
11417 &mut self,
11418 buffer_id: BufferId,
11419 group_id: usize,
11420 window: &mut Window,
11421 cx: &mut Context<Self>,
11422 ) {
11423 self.dismiss_diagnostics(cx);
11424 let snapshot = self.snapshot(window, cx);
11425 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11426 let buffer = self.buffer.read(cx).snapshot(cx);
11427
11428 let mut primary_range = None;
11429 let mut primary_message = None;
11430 let diagnostic_group = buffer
11431 .diagnostic_group(buffer_id, group_id)
11432 .filter_map(|entry| {
11433 let start = entry.range.start;
11434 let end = entry.range.end;
11435 if snapshot.is_line_folded(MultiBufferRow(start.row))
11436 && (start.row == end.row
11437 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11438 {
11439 return None;
11440 }
11441 if entry.diagnostic.is_primary {
11442 primary_range = Some(entry.range.clone());
11443 primary_message = Some(entry.diagnostic.message.clone());
11444 }
11445 Some(entry)
11446 })
11447 .collect::<Vec<_>>();
11448 let primary_range = primary_range?;
11449 let primary_message = primary_message?;
11450
11451 let blocks = display_map
11452 .insert_blocks(
11453 diagnostic_group.iter().map(|entry| {
11454 let diagnostic = entry.diagnostic.clone();
11455 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11456 BlockProperties {
11457 style: BlockStyle::Fixed,
11458 placement: BlockPlacement::Below(
11459 buffer.anchor_after(entry.range.start),
11460 ),
11461 height: message_height,
11462 render: diagnostic_block_renderer(diagnostic, None, true, true),
11463 priority: 0,
11464 }
11465 }),
11466 cx,
11467 )
11468 .into_iter()
11469 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11470 .collect();
11471
11472 Some(ActiveDiagnosticGroup {
11473 primary_range: buffer.anchor_before(primary_range.start)
11474 ..buffer.anchor_after(primary_range.end),
11475 primary_message,
11476 group_id,
11477 blocks,
11478 is_valid: true,
11479 })
11480 });
11481 }
11482
11483 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11484 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11485 self.display_map.update(cx, |display_map, cx| {
11486 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11487 });
11488 cx.notify();
11489 }
11490 }
11491
11492 pub fn set_selections_from_remote(
11493 &mut self,
11494 selections: Vec<Selection<Anchor>>,
11495 pending_selection: Option<Selection<Anchor>>,
11496 window: &mut Window,
11497 cx: &mut Context<Self>,
11498 ) {
11499 let old_cursor_position = self.selections.newest_anchor().head();
11500 self.selections.change_with(cx, |s| {
11501 s.select_anchors(selections);
11502 if let Some(pending_selection) = pending_selection {
11503 s.set_pending(pending_selection, SelectMode::Character);
11504 } else {
11505 s.clear_pending();
11506 }
11507 });
11508 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11509 }
11510
11511 fn push_to_selection_history(&mut self) {
11512 self.selection_history.push(SelectionHistoryEntry {
11513 selections: self.selections.disjoint_anchors(),
11514 select_next_state: self.select_next_state.clone(),
11515 select_prev_state: self.select_prev_state.clone(),
11516 add_selections_state: self.add_selections_state.clone(),
11517 });
11518 }
11519
11520 pub fn transact(
11521 &mut self,
11522 window: &mut Window,
11523 cx: &mut Context<Self>,
11524 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11525 ) -> Option<TransactionId> {
11526 self.start_transaction_at(Instant::now(), window, cx);
11527 update(self, window, cx);
11528 self.end_transaction_at(Instant::now(), cx)
11529 }
11530
11531 pub fn start_transaction_at(
11532 &mut self,
11533 now: Instant,
11534 window: &mut Window,
11535 cx: &mut Context<Self>,
11536 ) {
11537 self.end_selection(window, cx);
11538 if let Some(tx_id) = self
11539 .buffer
11540 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11541 {
11542 self.selection_history
11543 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11544 cx.emit(EditorEvent::TransactionBegun {
11545 transaction_id: tx_id,
11546 })
11547 }
11548 }
11549
11550 pub fn end_transaction_at(
11551 &mut self,
11552 now: Instant,
11553 cx: &mut Context<Self>,
11554 ) -> Option<TransactionId> {
11555 if let Some(transaction_id) = self
11556 .buffer
11557 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11558 {
11559 if let Some((_, end_selections)) =
11560 self.selection_history.transaction_mut(transaction_id)
11561 {
11562 *end_selections = Some(self.selections.disjoint_anchors());
11563 } else {
11564 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11565 }
11566
11567 cx.emit(EditorEvent::Edited { transaction_id });
11568 Some(transaction_id)
11569 } else {
11570 None
11571 }
11572 }
11573
11574 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11575 if self.selection_mark_mode {
11576 self.change_selections(None, window, cx, |s| {
11577 s.move_with(|_, sel| {
11578 sel.collapse_to(sel.head(), SelectionGoal::None);
11579 });
11580 })
11581 }
11582 self.selection_mark_mode = true;
11583 cx.notify();
11584 }
11585
11586 pub fn swap_selection_ends(
11587 &mut self,
11588 _: &actions::SwapSelectionEnds,
11589 window: &mut Window,
11590 cx: &mut Context<Self>,
11591 ) {
11592 self.change_selections(None, window, cx, |s| {
11593 s.move_with(|_, sel| {
11594 if sel.start != sel.end {
11595 sel.reversed = !sel.reversed
11596 }
11597 });
11598 });
11599 self.request_autoscroll(Autoscroll::newest(), cx);
11600 cx.notify();
11601 }
11602
11603 pub fn toggle_fold(
11604 &mut self,
11605 _: &actions::ToggleFold,
11606 window: &mut Window,
11607 cx: &mut Context<Self>,
11608 ) {
11609 if self.is_singleton(cx) {
11610 let selection = self.selections.newest::<Point>(cx);
11611
11612 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11613 let range = if selection.is_empty() {
11614 let point = selection.head().to_display_point(&display_map);
11615 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11616 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11617 .to_point(&display_map);
11618 start..end
11619 } else {
11620 selection.range()
11621 };
11622 if display_map.folds_in_range(range).next().is_some() {
11623 self.unfold_lines(&Default::default(), window, cx)
11624 } else {
11625 self.fold(&Default::default(), window, cx)
11626 }
11627 } else {
11628 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11629 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11630 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11631 .map(|(snapshot, _, _)| snapshot.remote_id())
11632 .collect();
11633
11634 for buffer_id in buffer_ids {
11635 if self.is_buffer_folded(buffer_id, cx) {
11636 self.unfold_buffer(buffer_id, cx);
11637 } else {
11638 self.fold_buffer(buffer_id, cx);
11639 }
11640 }
11641 }
11642 }
11643
11644 pub fn toggle_fold_recursive(
11645 &mut self,
11646 _: &actions::ToggleFoldRecursive,
11647 window: &mut Window,
11648 cx: &mut Context<Self>,
11649 ) {
11650 let selection = self.selections.newest::<Point>(cx);
11651
11652 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11653 let range = if selection.is_empty() {
11654 let point = selection.head().to_display_point(&display_map);
11655 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11656 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11657 .to_point(&display_map);
11658 start..end
11659 } else {
11660 selection.range()
11661 };
11662 if display_map.folds_in_range(range).next().is_some() {
11663 self.unfold_recursive(&Default::default(), window, cx)
11664 } else {
11665 self.fold_recursive(&Default::default(), window, cx)
11666 }
11667 }
11668
11669 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11670 if self.is_singleton(cx) {
11671 let mut to_fold = Vec::new();
11672 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11673 let selections = self.selections.all_adjusted(cx);
11674
11675 for selection in selections {
11676 let range = selection.range().sorted();
11677 let buffer_start_row = range.start.row;
11678
11679 if range.start.row != range.end.row {
11680 let mut found = false;
11681 let mut row = range.start.row;
11682 while row <= range.end.row {
11683 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11684 {
11685 found = true;
11686 row = crease.range().end.row + 1;
11687 to_fold.push(crease);
11688 } else {
11689 row += 1
11690 }
11691 }
11692 if found {
11693 continue;
11694 }
11695 }
11696
11697 for row in (0..=range.start.row).rev() {
11698 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11699 if crease.range().end.row >= buffer_start_row {
11700 to_fold.push(crease);
11701 if row <= range.start.row {
11702 break;
11703 }
11704 }
11705 }
11706 }
11707 }
11708
11709 self.fold_creases(to_fold, true, window, cx);
11710 } else {
11711 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11712
11713 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11714 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11715 .map(|(snapshot, _, _)| snapshot.remote_id())
11716 .collect();
11717 for buffer_id in buffer_ids {
11718 self.fold_buffer(buffer_id, cx);
11719 }
11720 }
11721 }
11722
11723 fn fold_at_level(
11724 &mut self,
11725 fold_at: &FoldAtLevel,
11726 window: &mut Window,
11727 cx: &mut Context<Self>,
11728 ) {
11729 if !self.buffer.read(cx).is_singleton() {
11730 return;
11731 }
11732
11733 let fold_at_level = fold_at.level;
11734 let snapshot = self.buffer.read(cx).snapshot(cx);
11735 let mut to_fold = Vec::new();
11736 let mut stack = vec![(0, snapshot.max_row().0, 1)];
11737
11738 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11739 while start_row < end_row {
11740 match self
11741 .snapshot(window, cx)
11742 .crease_for_buffer_row(MultiBufferRow(start_row))
11743 {
11744 Some(crease) => {
11745 let nested_start_row = crease.range().start.row + 1;
11746 let nested_end_row = crease.range().end.row;
11747
11748 if current_level < fold_at_level {
11749 stack.push((nested_start_row, nested_end_row, current_level + 1));
11750 } else if current_level == fold_at_level {
11751 to_fold.push(crease);
11752 }
11753
11754 start_row = nested_end_row + 1;
11755 }
11756 None => start_row += 1,
11757 }
11758 }
11759 }
11760
11761 self.fold_creases(to_fold, true, window, cx);
11762 }
11763
11764 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11765 if self.buffer.read(cx).is_singleton() {
11766 let mut fold_ranges = Vec::new();
11767 let snapshot = self.buffer.read(cx).snapshot(cx);
11768
11769 for row in 0..snapshot.max_row().0 {
11770 if let Some(foldable_range) = self
11771 .snapshot(window, cx)
11772 .crease_for_buffer_row(MultiBufferRow(row))
11773 {
11774 fold_ranges.push(foldable_range);
11775 }
11776 }
11777
11778 self.fold_creases(fold_ranges, true, window, cx);
11779 } else {
11780 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11781 editor
11782 .update_in(&mut cx, |editor, _, cx| {
11783 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11784 editor.fold_buffer(buffer_id, cx);
11785 }
11786 })
11787 .ok();
11788 });
11789 }
11790 }
11791
11792 pub fn fold_function_bodies(
11793 &mut self,
11794 _: &actions::FoldFunctionBodies,
11795 window: &mut Window,
11796 cx: &mut Context<Self>,
11797 ) {
11798 let snapshot = self.buffer.read(cx).snapshot(cx);
11799
11800 let ranges = snapshot
11801 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11802 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11803 .collect::<Vec<_>>();
11804
11805 let creases = ranges
11806 .into_iter()
11807 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11808 .collect();
11809
11810 self.fold_creases(creases, true, window, cx);
11811 }
11812
11813 pub fn fold_recursive(
11814 &mut self,
11815 _: &actions::FoldRecursive,
11816 window: &mut Window,
11817 cx: &mut Context<Self>,
11818 ) {
11819 let mut to_fold = Vec::new();
11820 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11821 let selections = self.selections.all_adjusted(cx);
11822
11823 for selection in selections {
11824 let range = selection.range().sorted();
11825 let buffer_start_row = range.start.row;
11826
11827 if range.start.row != range.end.row {
11828 let mut found = false;
11829 for row in range.start.row..=range.end.row {
11830 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11831 found = true;
11832 to_fold.push(crease);
11833 }
11834 }
11835 if found {
11836 continue;
11837 }
11838 }
11839
11840 for row in (0..=range.start.row).rev() {
11841 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11842 if crease.range().end.row >= buffer_start_row {
11843 to_fold.push(crease);
11844 } else {
11845 break;
11846 }
11847 }
11848 }
11849 }
11850
11851 self.fold_creases(to_fold, true, window, cx);
11852 }
11853
11854 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11855 let buffer_row = fold_at.buffer_row;
11856 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11857
11858 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11859 let autoscroll = self
11860 .selections
11861 .all::<Point>(cx)
11862 .iter()
11863 .any(|selection| crease.range().overlaps(&selection.range()));
11864
11865 self.fold_creases(vec![crease], autoscroll, window, cx);
11866 }
11867 }
11868
11869 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
11870 if self.is_singleton(cx) {
11871 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11872 let buffer = &display_map.buffer_snapshot;
11873 let selections = self.selections.all::<Point>(cx);
11874 let ranges = selections
11875 .iter()
11876 .map(|s| {
11877 let range = s.display_range(&display_map).sorted();
11878 let mut start = range.start.to_point(&display_map);
11879 let mut end = range.end.to_point(&display_map);
11880 start.column = 0;
11881 end.column = buffer.line_len(MultiBufferRow(end.row));
11882 start..end
11883 })
11884 .collect::<Vec<_>>();
11885
11886 self.unfold_ranges(&ranges, true, true, cx);
11887 } else {
11888 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11889 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11890 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11891 .map(|(snapshot, _, _)| snapshot.remote_id())
11892 .collect();
11893 for buffer_id in buffer_ids {
11894 self.unfold_buffer(buffer_id, cx);
11895 }
11896 }
11897 }
11898
11899 pub fn unfold_recursive(
11900 &mut self,
11901 _: &UnfoldRecursive,
11902 _window: &mut Window,
11903 cx: &mut Context<Self>,
11904 ) {
11905 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11906 let selections = self.selections.all::<Point>(cx);
11907 let ranges = selections
11908 .iter()
11909 .map(|s| {
11910 let mut range = s.display_range(&display_map).sorted();
11911 *range.start.column_mut() = 0;
11912 *range.end.column_mut() = display_map.line_len(range.end.row());
11913 let start = range.start.to_point(&display_map);
11914 let end = range.end.to_point(&display_map);
11915 start..end
11916 })
11917 .collect::<Vec<_>>();
11918
11919 self.unfold_ranges(&ranges, true, true, cx);
11920 }
11921
11922 pub fn unfold_at(
11923 &mut self,
11924 unfold_at: &UnfoldAt,
11925 _window: &mut Window,
11926 cx: &mut Context<Self>,
11927 ) {
11928 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11929
11930 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11931 ..Point::new(
11932 unfold_at.buffer_row.0,
11933 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11934 );
11935
11936 let autoscroll = self
11937 .selections
11938 .all::<Point>(cx)
11939 .iter()
11940 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11941
11942 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
11943 }
11944
11945 pub fn unfold_all(
11946 &mut self,
11947 _: &actions::UnfoldAll,
11948 _window: &mut Window,
11949 cx: &mut Context<Self>,
11950 ) {
11951 if self.buffer.read(cx).is_singleton() {
11952 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11953 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11954 } else {
11955 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
11956 editor
11957 .update(&mut cx, |editor, cx| {
11958 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11959 editor.unfold_buffer(buffer_id, cx);
11960 }
11961 })
11962 .ok();
11963 });
11964 }
11965 }
11966
11967 pub fn fold_selected_ranges(
11968 &mut self,
11969 _: &FoldSelectedRanges,
11970 window: &mut Window,
11971 cx: &mut Context<Self>,
11972 ) {
11973 let selections = self.selections.all::<Point>(cx);
11974 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11975 let line_mode = self.selections.line_mode;
11976 let ranges = selections
11977 .into_iter()
11978 .map(|s| {
11979 if line_mode {
11980 let start = Point::new(s.start.row, 0);
11981 let end = Point::new(
11982 s.end.row,
11983 display_map
11984 .buffer_snapshot
11985 .line_len(MultiBufferRow(s.end.row)),
11986 );
11987 Crease::simple(start..end, display_map.fold_placeholder.clone())
11988 } else {
11989 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11990 }
11991 })
11992 .collect::<Vec<_>>();
11993 self.fold_creases(ranges, true, window, cx);
11994 }
11995
11996 pub fn fold_ranges<T: ToOffset + Clone>(
11997 &mut self,
11998 ranges: Vec<Range<T>>,
11999 auto_scroll: bool,
12000 window: &mut Window,
12001 cx: &mut Context<Self>,
12002 ) {
12003 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12004 let ranges = ranges
12005 .into_iter()
12006 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12007 .collect::<Vec<_>>();
12008 self.fold_creases(ranges, auto_scroll, window, cx);
12009 }
12010
12011 pub fn fold_creases<T: ToOffset + Clone>(
12012 &mut self,
12013 creases: Vec<Crease<T>>,
12014 auto_scroll: bool,
12015 window: &mut Window,
12016 cx: &mut Context<Self>,
12017 ) {
12018 if creases.is_empty() {
12019 return;
12020 }
12021
12022 let mut buffers_affected = HashSet::default();
12023 let multi_buffer = self.buffer().read(cx);
12024 for crease in &creases {
12025 if let Some((_, buffer, _)) =
12026 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12027 {
12028 buffers_affected.insert(buffer.read(cx).remote_id());
12029 };
12030 }
12031
12032 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12033
12034 if auto_scroll {
12035 self.request_autoscroll(Autoscroll::fit(), cx);
12036 }
12037
12038 cx.notify();
12039
12040 if let Some(active_diagnostics) = self.active_diagnostics.take() {
12041 // Clear diagnostics block when folding a range that contains it.
12042 let snapshot = self.snapshot(window, cx);
12043 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12044 drop(snapshot);
12045 self.active_diagnostics = Some(active_diagnostics);
12046 self.dismiss_diagnostics(cx);
12047 } else {
12048 self.active_diagnostics = Some(active_diagnostics);
12049 }
12050 }
12051
12052 self.scrollbar_marker_state.dirty = true;
12053 }
12054
12055 /// Removes any folds whose ranges intersect any of the given ranges.
12056 pub fn unfold_ranges<T: ToOffset + Clone>(
12057 &mut self,
12058 ranges: &[Range<T>],
12059 inclusive: bool,
12060 auto_scroll: bool,
12061 cx: &mut Context<Self>,
12062 ) {
12063 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12064 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12065 });
12066 }
12067
12068 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12069 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12070 return;
12071 }
12072 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12073 self.display_map
12074 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12075 cx.emit(EditorEvent::BufferFoldToggled {
12076 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12077 folded: true,
12078 });
12079 cx.notify();
12080 }
12081
12082 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12083 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12084 return;
12085 }
12086 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12087 self.display_map.update(cx, |display_map, cx| {
12088 display_map.unfold_buffer(buffer_id, cx);
12089 });
12090 cx.emit(EditorEvent::BufferFoldToggled {
12091 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12092 folded: false,
12093 });
12094 cx.notify();
12095 }
12096
12097 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12098 self.display_map.read(cx).is_buffer_folded(buffer)
12099 }
12100
12101 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12102 self.display_map.read(cx).folded_buffers()
12103 }
12104
12105 /// Removes any folds with the given ranges.
12106 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12107 &mut self,
12108 ranges: &[Range<T>],
12109 type_id: TypeId,
12110 auto_scroll: bool,
12111 cx: &mut Context<Self>,
12112 ) {
12113 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12114 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12115 });
12116 }
12117
12118 fn remove_folds_with<T: ToOffset + Clone>(
12119 &mut self,
12120 ranges: &[Range<T>],
12121 auto_scroll: bool,
12122 cx: &mut Context<Self>,
12123 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12124 ) {
12125 if ranges.is_empty() {
12126 return;
12127 }
12128
12129 let mut buffers_affected = HashSet::default();
12130 let multi_buffer = self.buffer().read(cx);
12131 for range in ranges {
12132 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12133 buffers_affected.insert(buffer.read(cx).remote_id());
12134 };
12135 }
12136
12137 self.display_map.update(cx, update);
12138
12139 if auto_scroll {
12140 self.request_autoscroll(Autoscroll::fit(), cx);
12141 }
12142
12143 cx.notify();
12144 self.scrollbar_marker_state.dirty = true;
12145 self.active_indent_guides_state.dirty = true;
12146 }
12147
12148 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12149 self.display_map.read(cx).fold_placeholder.clone()
12150 }
12151
12152 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12153 self.buffer.update(cx, |buffer, cx| {
12154 buffer.set_all_diff_hunks_expanded(cx);
12155 });
12156 }
12157
12158 pub fn expand_all_diff_hunks(
12159 &mut self,
12160 _: &ExpandAllHunkDiffs,
12161 _window: &mut Window,
12162 cx: &mut Context<Self>,
12163 ) {
12164 self.buffer.update(cx, |buffer, cx| {
12165 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12166 });
12167 }
12168
12169 pub fn toggle_selected_diff_hunks(
12170 &mut self,
12171 _: &ToggleSelectedDiffHunks,
12172 _window: &mut Window,
12173 cx: &mut Context<Self>,
12174 ) {
12175 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12176 self.toggle_diff_hunks_in_ranges(ranges, cx);
12177 }
12178
12179 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12180 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12181 self.buffer
12182 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12183 }
12184
12185 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12186 self.buffer.update(cx, |buffer, cx| {
12187 let ranges = vec![Anchor::min()..Anchor::max()];
12188 if !buffer.all_diff_hunks_expanded()
12189 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12190 {
12191 buffer.collapse_diff_hunks(ranges, cx);
12192 true
12193 } else {
12194 false
12195 }
12196 })
12197 }
12198
12199 fn toggle_diff_hunks_in_ranges(
12200 &mut self,
12201 ranges: Vec<Range<Anchor>>,
12202 cx: &mut Context<'_, Editor>,
12203 ) {
12204 self.buffer.update(cx, |buffer, cx| {
12205 if buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx) {
12206 buffer.collapse_diff_hunks(ranges, cx)
12207 } else {
12208 buffer.expand_diff_hunks(ranges, cx)
12209 }
12210 })
12211 }
12212
12213 pub(crate) fn apply_all_diff_hunks(
12214 &mut self,
12215 _: &ApplyAllDiffHunks,
12216 window: &mut Window,
12217 cx: &mut Context<Self>,
12218 ) {
12219 let buffers = self.buffer.read(cx).all_buffers();
12220 for branch_buffer in buffers {
12221 branch_buffer.update(cx, |branch_buffer, cx| {
12222 branch_buffer.merge_into_base(Vec::new(), cx);
12223 });
12224 }
12225
12226 if let Some(project) = self.project.clone() {
12227 self.save(true, project, window, cx).detach_and_log_err(cx);
12228 }
12229 }
12230
12231 pub(crate) fn apply_selected_diff_hunks(
12232 &mut self,
12233 _: &ApplyDiffHunk,
12234 window: &mut Window,
12235 cx: &mut Context<Self>,
12236 ) {
12237 let snapshot = self.snapshot(window, cx);
12238 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12239 let mut ranges_by_buffer = HashMap::default();
12240 self.transact(window, cx, |editor, _window, cx| {
12241 for hunk in hunks {
12242 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12243 ranges_by_buffer
12244 .entry(buffer.clone())
12245 .or_insert_with(Vec::new)
12246 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12247 }
12248 }
12249
12250 for (buffer, ranges) in ranges_by_buffer {
12251 buffer.update(cx, |buffer, cx| {
12252 buffer.merge_into_base(ranges, cx);
12253 });
12254 }
12255 });
12256
12257 if let Some(project) = self.project.clone() {
12258 self.save(true, project, window, cx).detach_and_log_err(cx);
12259 }
12260 }
12261
12262 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12263 if hovered != self.gutter_hovered {
12264 self.gutter_hovered = hovered;
12265 cx.notify();
12266 }
12267 }
12268
12269 pub fn insert_blocks(
12270 &mut self,
12271 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12272 autoscroll: Option<Autoscroll>,
12273 cx: &mut Context<Self>,
12274 ) -> Vec<CustomBlockId> {
12275 let blocks = self
12276 .display_map
12277 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12278 if let Some(autoscroll) = autoscroll {
12279 self.request_autoscroll(autoscroll, cx);
12280 }
12281 cx.notify();
12282 blocks
12283 }
12284
12285 pub fn resize_blocks(
12286 &mut self,
12287 heights: HashMap<CustomBlockId, u32>,
12288 autoscroll: Option<Autoscroll>,
12289 cx: &mut Context<Self>,
12290 ) {
12291 self.display_map
12292 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12293 if let Some(autoscroll) = autoscroll {
12294 self.request_autoscroll(autoscroll, cx);
12295 }
12296 cx.notify();
12297 }
12298
12299 pub fn replace_blocks(
12300 &mut self,
12301 renderers: HashMap<CustomBlockId, RenderBlock>,
12302 autoscroll: Option<Autoscroll>,
12303 cx: &mut Context<Self>,
12304 ) {
12305 self.display_map
12306 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12307 if let Some(autoscroll) = autoscroll {
12308 self.request_autoscroll(autoscroll, cx);
12309 }
12310 cx.notify();
12311 }
12312
12313 pub fn remove_blocks(
12314 &mut self,
12315 block_ids: HashSet<CustomBlockId>,
12316 autoscroll: Option<Autoscroll>,
12317 cx: &mut Context<Self>,
12318 ) {
12319 self.display_map.update(cx, |display_map, cx| {
12320 display_map.remove_blocks(block_ids, cx)
12321 });
12322 if let Some(autoscroll) = autoscroll {
12323 self.request_autoscroll(autoscroll, cx);
12324 }
12325 cx.notify();
12326 }
12327
12328 pub fn row_for_block(
12329 &self,
12330 block_id: CustomBlockId,
12331 cx: &mut Context<Self>,
12332 ) -> Option<DisplayRow> {
12333 self.display_map
12334 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12335 }
12336
12337 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12338 self.focused_block = Some(focused_block);
12339 }
12340
12341 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12342 self.focused_block.take()
12343 }
12344
12345 pub fn insert_creases(
12346 &mut self,
12347 creases: impl IntoIterator<Item = Crease<Anchor>>,
12348 cx: &mut Context<Self>,
12349 ) -> Vec<CreaseId> {
12350 self.display_map
12351 .update(cx, |map, cx| map.insert_creases(creases, cx))
12352 }
12353
12354 pub fn remove_creases(
12355 &mut self,
12356 ids: impl IntoIterator<Item = CreaseId>,
12357 cx: &mut Context<Self>,
12358 ) {
12359 self.display_map
12360 .update(cx, |map, cx| map.remove_creases(ids, cx));
12361 }
12362
12363 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12364 self.display_map
12365 .update(cx, |map, cx| map.snapshot(cx))
12366 .longest_row()
12367 }
12368
12369 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12370 self.display_map
12371 .update(cx, |map, cx| map.snapshot(cx))
12372 .max_point()
12373 }
12374
12375 pub fn text(&self, cx: &App) -> String {
12376 self.buffer.read(cx).read(cx).text()
12377 }
12378
12379 pub fn is_empty(&self, cx: &App) -> bool {
12380 self.buffer.read(cx).read(cx).is_empty()
12381 }
12382
12383 pub fn text_option(&self, cx: &App) -> Option<String> {
12384 let text = self.text(cx);
12385 let text = text.trim();
12386
12387 if text.is_empty() {
12388 return None;
12389 }
12390
12391 Some(text.to_string())
12392 }
12393
12394 pub fn set_text(
12395 &mut self,
12396 text: impl Into<Arc<str>>,
12397 window: &mut Window,
12398 cx: &mut Context<Self>,
12399 ) {
12400 self.transact(window, cx, |this, _, cx| {
12401 this.buffer
12402 .read(cx)
12403 .as_singleton()
12404 .expect("you can only call set_text on editors for singleton buffers")
12405 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12406 });
12407 }
12408
12409 pub fn display_text(&self, cx: &mut App) -> String {
12410 self.display_map
12411 .update(cx, |map, cx| map.snapshot(cx))
12412 .text()
12413 }
12414
12415 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12416 let mut wrap_guides = smallvec::smallvec![];
12417
12418 if self.show_wrap_guides == Some(false) {
12419 return wrap_guides;
12420 }
12421
12422 let settings = self.buffer.read(cx).settings_at(0, cx);
12423 if settings.show_wrap_guides {
12424 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12425 wrap_guides.push((soft_wrap as usize, true));
12426 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12427 wrap_guides.push((soft_wrap as usize, true));
12428 }
12429 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12430 }
12431
12432 wrap_guides
12433 }
12434
12435 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12436 let settings = self.buffer.read(cx).settings_at(0, cx);
12437 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12438 match mode {
12439 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12440 SoftWrap::None
12441 }
12442 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12443 language_settings::SoftWrap::PreferredLineLength => {
12444 SoftWrap::Column(settings.preferred_line_length)
12445 }
12446 language_settings::SoftWrap::Bounded => {
12447 SoftWrap::Bounded(settings.preferred_line_length)
12448 }
12449 }
12450 }
12451
12452 pub fn set_soft_wrap_mode(
12453 &mut self,
12454 mode: language_settings::SoftWrap,
12455
12456 cx: &mut Context<Self>,
12457 ) {
12458 self.soft_wrap_mode_override = Some(mode);
12459 cx.notify();
12460 }
12461
12462 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12463 self.text_style_refinement = Some(style);
12464 }
12465
12466 /// called by the Element so we know what style we were most recently rendered with.
12467 pub(crate) fn set_style(
12468 &mut self,
12469 style: EditorStyle,
12470 window: &mut Window,
12471 cx: &mut Context<Self>,
12472 ) {
12473 let rem_size = window.rem_size();
12474 self.display_map.update(cx, |map, cx| {
12475 map.set_font(
12476 style.text.font(),
12477 style.text.font_size.to_pixels(rem_size),
12478 cx,
12479 )
12480 });
12481 self.style = Some(style);
12482 }
12483
12484 pub fn style(&self) -> Option<&EditorStyle> {
12485 self.style.as_ref()
12486 }
12487
12488 // Called by the element. This method is not designed to be called outside of the editor
12489 // element's layout code because it does not notify when rewrapping is computed synchronously.
12490 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12491 self.display_map
12492 .update(cx, |map, cx| map.set_wrap_width(width, cx))
12493 }
12494
12495 pub fn set_soft_wrap(&mut self) {
12496 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12497 }
12498
12499 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12500 if self.soft_wrap_mode_override.is_some() {
12501 self.soft_wrap_mode_override.take();
12502 } else {
12503 let soft_wrap = match self.soft_wrap_mode(cx) {
12504 SoftWrap::GitDiff => return,
12505 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12506 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12507 language_settings::SoftWrap::None
12508 }
12509 };
12510 self.soft_wrap_mode_override = Some(soft_wrap);
12511 }
12512 cx.notify();
12513 }
12514
12515 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12516 let Some(workspace) = self.workspace() else {
12517 return;
12518 };
12519 let fs = workspace.read(cx).app_state().fs.clone();
12520 let current_show = TabBarSettings::get_global(cx).show;
12521 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12522 setting.show = Some(!current_show);
12523 });
12524 }
12525
12526 pub fn toggle_indent_guides(
12527 &mut self,
12528 _: &ToggleIndentGuides,
12529 _: &mut Window,
12530 cx: &mut Context<Self>,
12531 ) {
12532 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12533 self.buffer
12534 .read(cx)
12535 .settings_at(0, cx)
12536 .indent_guides
12537 .enabled
12538 });
12539 self.show_indent_guides = Some(!currently_enabled);
12540 cx.notify();
12541 }
12542
12543 fn should_show_indent_guides(&self) -> Option<bool> {
12544 self.show_indent_guides
12545 }
12546
12547 pub fn toggle_line_numbers(
12548 &mut self,
12549 _: &ToggleLineNumbers,
12550 _: &mut Window,
12551 cx: &mut Context<Self>,
12552 ) {
12553 let mut editor_settings = EditorSettings::get_global(cx).clone();
12554 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12555 EditorSettings::override_global(editor_settings, cx);
12556 }
12557
12558 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12559 self.use_relative_line_numbers
12560 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12561 }
12562
12563 pub fn toggle_relative_line_numbers(
12564 &mut self,
12565 _: &ToggleRelativeLineNumbers,
12566 _: &mut Window,
12567 cx: &mut Context<Self>,
12568 ) {
12569 let is_relative = self.should_use_relative_line_numbers(cx);
12570 self.set_relative_line_number(Some(!is_relative), cx)
12571 }
12572
12573 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12574 self.use_relative_line_numbers = is_relative;
12575 cx.notify();
12576 }
12577
12578 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12579 self.show_gutter = show_gutter;
12580 cx.notify();
12581 }
12582
12583 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12584 self.show_scrollbars = show_scrollbars;
12585 cx.notify();
12586 }
12587
12588 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12589 self.show_line_numbers = Some(show_line_numbers);
12590 cx.notify();
12591 }
12592
12593 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12594 self.show_git_diff_gutter = Some(show_git_diff_gutter);
12595 cx.notify();
12596 }
12597
12598 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12599 self.show_code_actions = Some(show_code_actions);
12600 cx.notify();
12601 }
12602
12603 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12604 self.show_runnables = Some(show_runnables);
12605 cx.notify();
12606 }
12607
12608 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12609 if self.display_map.read(cx).masked != masked {
12610 self.display_map.update(cx, |map, _| map.masked = masked);
12611 }
12612 cx.notify()
12613 }
12614
12615 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12616 self.show_wrap_guides = Some(show_wrap_guides);
12617 cx.notify();
12618 }
12619
12620 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12621 self.show_indent_guides = Some(show_indent_guides);
12622 cx.notify();
12623 }
12624
12625 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12626 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12627 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12628 if let Some(dir) = file.abs_path(cx).parent() {
12629 return Some(dir.to_owned());
12630 }
12631 }
12632
12633 if let Some(project_path) = buffer.read(cx).project_path(cx) {
12634 return Some(project_path.path.to_path_buf());
12635 }
12636 }
12637
12638 None
12639 }
12640
12641 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12642 self.active_excerpt(cx)?
12643 .1
12644 .read(cx)
12645 .file()
12646 .and_then(|f| f.as_local())
12647 }
12648
12649 fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12650 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12651 let project_path = buffer.read(cx).project_path(cx)?;
12652 let project = self.project.as_ref()?.read(cx);
12653 project.absolute_path(&project_path, cx)
12654 })
12655 }
12656
12657 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12658 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12659 let project_path = buffer.read(cx).project_path(cx)?;
12660 let project = self.project.as_ref()?.read(cx);
12661 let entry = project.entry_for_path(&project_path, cx)?;
12662 let path = entry.path.to_path_buf();
12663 Some(path)
12664 })
12665 }
12666
12667 pub fn reveal_in_finder(
12668 &mut self,
12669 _: &RevealInFileManager,
12670 _window: &mut Window,
12671 cx: &mut Context<Self>,
12672 ) {
12673 if let Some(target) = self.target_file(cx) {
12674 cx.reveal_path(&target.abs_path(cx));
12675 }
12676 }
12677
12678 pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12679 if let Some(path) = self.target_file_abs_path(cx) {
12680 if let Some(path) = path.to_str() {
12681 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12682 }
12683 }
12684 }
12685
12686 pub fn copy_relative_path(
12687 &mut self,
12688 _: &CopyRelativePath,
12689 _window: &mut Window,
12690 cx: &mut Context<Self>,
12691 ) {
12692 if let Some(path) = self.target_file_path(cx) {
12693 if let Some(path) = path.to_str() {
12694 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12695 }
12696 }
12697 }
12698
12699 pub fn toggle_git_blame(
12700 &mut self,
12701 _: &ToggleGitBlame,
12702 window: &mut Window,
12703 cx: &mut Context<Self>,
12704 ) {
12705 self.show_git_blame_gutter = !self.show_git_blame_gutter;
12706
12707 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12708 self.start_git_blame(true, window, cx);
12709 }
12710
12711 cx.notify();
12712 }
12713
12714 pub fn toggle_git_blame_inline(
12715 &mut self,
12716 _: &ToggleGitBlameInline,
12717 window: &mut Window,
12718 cx: &mut Context<Self>,
12719 ) {
12720 self.toggle_git_blame_inline_internal(true, window, cx);
12721 cx.notify();
12722 }
12723
12724 pub fn git_blame_inline_enabled(&self) -> bool {
12725 self.git_blame_inline_enabled
12726 }
12727
12728 pub fn toggle_selection_menu(
12729 &mut self,
12730 _: &ToggleSelectionMenu,
12731 _: &mut Window,
12732 cx: &mut Context<Self>,
12733 ) {
12734 self.show_selection_menu = self
12735 .show_selection_menu
12736 .map(|show_selections_menu| !show_selections_menu)
12737 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12738
12739 cx.notify();
12740 }
12741
12742 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12743 self.show_selection_menu
12744 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12745 }
12746
12747 fn start_git_blame(
12748 &mut self,
12749 user_triggered: bool,
12750 window: &mut Window,
12751 cx: &mut Context<Self>,
12752 ) {
12753 if let Some(project) = self.project.as_ref() {
12754 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12755 return;
12756 };
12757
12758 if buffer.read(cx).file().is_none() {
12759 return;
12760 }
12761
12762 let focused = self.focus_handle(cx).contains_focused(window, cx);
12763
12764 let project = project.clone();
12765 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12766 self.blame_subscription =
12767 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12768 self.blame = Some(blame);
12769 }
12770 }
12771
12772 fn toggle_git_blame_inline_internal(
12773 &mut self,
12774 user_triggered: bool,
12775 window: &mut Window,
12776 cx: &mut Context<Self>,
12777 ) {
12778 if self.git_blame_inline_enabled {
12779 self.git_blame_inline_enabled = false;
12780 self.show_git_blame_inline = false;
12781 self.show_git_blame_inline_delay_task.take();
12782 } else {
12783 self.git_blame_inline_enabled = true;
12784 self.start_git_blame_inline(user_triggered, window, cx);
12785 }
12786
12787 cx.notify();
12788 }
12789
12790 fn start_git_blame_inline(
12791 &mut self,
12792 user_triggered: bool,
12793 window: &mut Window,
12794 cx: &mut Context<Self>,
12795 ) {
12796 self.start_git_blame(user_triggered, window, cx);
12797
12798 if ProjectSettings::get_global(cx)
12799 .git
12800 .inline_blame_delay()
12801 .is_some()
12802 {
12803 self.start_inline_blame_timer(window, cx);
12804 } else {
12805 self.show_git_blame_inline = true
12806 }
12807 }
12808
12809 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12810 self.blame.as_ref()
12811 }
12812
12813 pub fn show_git_blame_gutter(&self) -> bool {
12814 self.show_git_blame_gutter
12815 }
12816
12817 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12818 self.show_git_blame_gutter && self.has_blame_entries(cx)
12819 }
12820
12821 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12822 self.show_git_blame_inline
12823 && self.focus_handle.is_focused(window)
12824 && !self.newest_selection_head_on_empty_line(cx)
12825 && self.has_blame_entries(cx)
12826 }
12827
12828 fn has_blame_entries(&self, cx: &App) -> bool {
12829 self.blame()
12830 .map_or(false, |blame| blame.read(cx).has_generated_entries())
12831 }
12832
12833 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12834 let cursor_anchor = self.selections.newest_anchor().head();
12835
12836 let snapshot = self.buffer.read(cx).snapshot(cx);
12837 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12838
12839 snapshot.line_len(buffer_row) == 0
12840 }
12841
12842 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12843 let buffer_and_selection = maybe!({
12844 let selection = self.selections.newest::<Point>(cx);
12845 let selection_range = selection.range();
12846
12847 let multi_buffer = self.buffer().read(cx);
12848 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12849 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12850
12851 let (buffer, range, _) = if selection.reversed {
12852 buffer_ranges.first()
12853 } else {
12854 buffer_ranges.last()
12855 }?;
12856
12857 let selection = text::ToPoint::to_point(&range.start, &buffer).row
12858 ..text::ToPoint::to_point(&range.end, &buffer).row;
12859 Some((
12860 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
12861 selection,
12862 ))
12863 });
12864
12865 let Some((buffer, selection)) = buffer_and_selection else {
12866 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12867 };
12868
12869 let Some(project) = self.project.as_ref() else {
12870 return Task::ready(Err(anyhow!("editor does not have project")));
12871 };
12872
12873 project.update(cx, |project, cx| {
12874 project.get_permalink_to_line(&buffer, selection, cx)
12875 })
12876 }
12877
12878 pub fn copy_permalink_to_line(
12879 &mut self,
12880 _: &CopyPermalinkToLine,
12881 window: &mut Window,
12882 cx: &mut Context<Self>,
12883 ) {
12884 let permalink_task = self.get_permalink_to_line(cx);
12885 let workspace = self.workspace();
12886
12887 cx.spawn_in(window, |_, mut cx| async move {
12888 match permalink_task.await {
12889 Ok(permalink) => {
12890 cx.update(|_, cx| {
12891 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12892 })
12893 .ok();
12894 }
12895 Err(err) => {
12896 let message = format!("Failed to copy permalink: {err}");
12897
12898 Err::<(), anyhow::Error>(err).log_err();
12899
12900 if let Some(workspace) = workspace {
12901 workspace
12902 .update_in(&mut cx, |workspace, _, cx| {
12903 struct CopyPermalinkToLine;
12904
12905 workspace.show_toast(
12906 Toast::new(
12907 NotificationId::unique::<CopyPermalinkToLine>(),
12908 message,
12909 ),
12910 cx,
12911 )
12912 })
12913 .ok();
12914 }
12915 }
12916 }
12917 })
12918 .detach();
12919 }
12920
12921 pub fn copy_file_location(
12922 &mut self,
12923 _: &CopyFileLocation,
12924 _: &mut Window,
12925 cx: &mut Context<Self>,
12926 ) {
12927 let selection = self.selections.newest::<Point>(cx).start.row + 1;
12928 if let Some(file) = self.target_file(cx) {
12929 if let Some(path) = file.path().to_str() {
12930 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
12931 }
12932 }
12933 }
12934
12935 pub fn open_permalink_to_line(
12936 &mut self,
12937 _: &OpenPermalinkToLine,
12938 window: &mut Window,
12939 cx: &mut Context<Self>,
12940 ) {
12941 let permalink_task = self.get_permalink_to_line(cx);
12942 let workspace = self.workspace();
12943
12944 cx.spawn_in(window, |_, mut cx| async move {
12945 match permalink_task.await {
12946 Ok(permalink) => {
12947 cx.update(|_, cx| {
12948 cx.open_url(permalink.as_ref());
12949 })
12950 .ok();
12951 }
12952 Err(err) => {
12953 let message = format!("Failed to open permalink: {err}");
12954
12955 Err::<(), anyhow::Error>(err).log_err();
12956
12957 if let Some(workspace) = workspace {
12958 workspace
12959 .update(&mut cx, |workspace, cx| {
12960 struct OpenPermalinkToLine;
12961
12962 workspace.show_toast(
12963 Toast::new(
12964 NotificationId::unique::<OpenPermalinkToLine>(),
12965 message,
12966 ),
12967 cx,
12968 )
12969 })
12970 .ok();
12971 }
12972 }
12973 }
12974 })
12975 .detach();
12976 }
12977
12978 pub fn insert_uuid_v4(
12979 &mut self,
12980 _: &InsertUuidV4,
12981 window: &mut Window,
12982 cx: &mut Context<Self>,
12983 ) {
12984 self.insert_uuid(UuidVersion::V4, window, cx);
12985 }
12986
12987 pub fn insert_uuid_v7(
12988 &mut self,
12989 _: &InsertUuidV7,
12990 window: &mut Window,
12991 cx: &mut Context<Self>,
12992 ) {
12993 self.insert_uuid(UuidVersion::V7, window, cx);
12994 }
12995
12996 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
12997 self.transact(window, cx, |this, window, cx| {
12998 let edits = this
12999 .selections
13000 .all::<Point>(cx)
13001 .into_iter()
13002 .map(|selection| {
13003 let uuid = match version {
13004 UuidVersion::V4 => uuid::Uuid::new_v4(),
13005 UuidVersion::V7 => uuid::Uuid::now_v7(),
13006 };
13007
13008 (selection.range(), uuid.to_string())
13009 });
13010 this.edit(edits, cx);
13011 this.refresh_inline_completion(true, false, window, cx);
13012 });
13013 }
13014
13015 pub fn open_selections_in_multibuffer(
13016 &mut self,
13017 _: &OpenSelectionsInMultibuffer,
13018 window: &mut Window,
13019 cx: &mut Context<Self>,
13020 ) {
13021 let multibuffer = self.buffer.read(cx);
13022
13023 let Some(buffer) = multibuffer.as_singleton() else {
13024 return;
13025 };
13026
13027 let Some(workspace) = self.workspace() else {
13028 return;
13029 };
13030
13031 let locations = self
13032 .selections
13033 .disjoint_anchors()
13034 .iter()
13035 .map(|range| Location {
13036 buffer: buffer.clone(),
13037 range: range.start.text_anchor..range.end.text_anchor,
13038 })
13039 .collect::<Vec<_>>();
13040
13041 let title = multibuffer.title(cx).to_string();
13042
13043 cx.spawn_in(window, |_, mut cx| async move {
13044 workspace.update_in(&mut cx, |workspace, window, cx| {
13045 Self::open_locations_in_multibuffer(
13046 workspace,
13047 locations,
13048 format!("Selections for '{title}'"),
13049 false,
13050 MultibufferSelectionMode::All,
13051 window,
13052 cx,
13053 );
13054 })
13055 })
13056 .detach();
13057 }
13058
13059 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13060 /// last highlight added will be used.
13061 ///
13062 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13063 pub fn highlight_rows<T: 'static>(
13064 &mut self,
13065 range: Range<Anchor>,
13066 color: Hsla,
13067 should_autoscroll: bool,
13068 cx: &mut Context<Self>,
13069 ) {
13070 let snapshot = self.buffer().read(cx).snapshot(cx);
13071 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13072 let ix = row_highlights.binary_search_by(|highlight| {
13073 Ordering::Equal
13074 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13075 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13076 });
13077
13078 if let Err(mut ix) = ix {
13079 let index = post_inc(&mut self.highlight_order);
13080
13081 // If this range intersects with the preceding highlight, then merge it with
13082 // the preceding highlight. Otherwise insert a new highlight.
13083 let mut merged = false;
13084 if ix > 0 {
13085 let prev_highlight = &mut row_highlights[ix - 1];
13086 if prev_highlight
13087 .range
13088 .end
13089 .cmp(&range.start, &snapshot)
13090 .is_ge()
13091 {
13092 ix -= 1;
13093 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13094 prev_highlight.range.end = range.end;
13095 }
13096 merged = true;
13097 prev_highlight.index = index;
13098 prev_highlight.color = color;
13099 prev_highlight.should_autoscroll = should_autoscroll;
13100 }
13101 }
13102
13103 if !merged {
13104 row_highlights.insert(
13105 ix,
13106 RowHighlight {
13107 range: range.clone(),
13108 index,
13109 color,
13110 should_autoscroll,
13111 },
13112 );
13113 }
13114
13115 // If any of the following highlights intersect with this one, merge them.
13116 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13117 let highlight = &row_highlights[ix];
13118 if next_highlight
13119 .range
13120 .start
13121 .cmp(&highlight.range.end, &snapshot)
13122 .is_le()
13123 {
13124 if next_highlight
13125 .range
13126 .end
13127 .cmp(&highlight.range.end, &snapshot)
13128 .is_gt()
13129 {
13130 row_highlights[ix].range.end = next_highlight.range.end;
13131 }
13132 row_highlights.remove(ix + 1);
13133 } else {
13134 break;
13135 }
13136 }
13137 }
13138 }
13139
13140 /// Remove any highlighted row ranges of the given type that intersect the
13141 /// given ranges.
13142 pub fn remove_highlighted_rows<T: 'static>(
13143 &mut self,
13144 ranges_to_remove: Vec<Range<Anchor>>,
13145 cx: &mut Context<Self>,
13146 ) {
13147 let snapshot = self.buffer().read(cx).snapshot(cx);
13148 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13149 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13150 row_highlights.retain(|highlight| {
13151 while let Some(range_to_remove) = ranges_to_remove.peek() {
13152 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13153 Ordering::Less | Ordering::Equal => {
13154 ranges_to_remove.next();
13155 }
13156 Ordering::Greater => {
13157 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13158 Ordering::Less | Ordering::Equal => {
13159 return false;
13160 }
13161 Ordering::Greater => break,
13162 }
13163 }
13164 }
13165 }
13166
13167 true
13168 })
13169 }
13170
13171 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13172 pub fn clear_row_highlights<T: 'static>(&mut self) {
13173 self.highlighted_rows.remove(&TypeId::of::<T>());
13174 }
13175
13176 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13177 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13178 self.highlighted_rows
13179 .get(&TypeId::of::<T>())
13180 .map_or(&[] as &[_], |vec| vec.as_slice())
13181 .iter()
13182 .map(|highlight| (highlight.range.clone(), highlight.color))
13183 }
13184
13185 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13186 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13187 /// Allows to ignore certain kinds of highlights.
13188 pub fn highlighted_display_rows(
13189 &self,
13190 window: &mut Window,
13191 cx: &mut App,
13192 ) -> BTreeMap<DisplayRow, Hsla> {
13193 let snapshot = self.snapshot(window, cx);
13194 let mut used_highlight_orders = HashMap::default();
13195 self.highlighted_rows
13196 .iter()
13197 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13198 .fold(
13199 BTreeMap::<DisplayRow, Hsla>::new(),
13200 |mut unique_rows, highlight| {
13201 let start = highlight.range.start.to_display_point(&snapshot);
13202 let end = highlight.range.end.to_display_point(&snapshot);
13203 let start_row = start.row().0;
13204 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13205 && end.column() == 0
13206 {
13207 end.row().0.saturating_sub(1)
13208 } else {
13209 end.row().0
13210 };
13211 for row in start_row..=end_row {
13212 let used_index =
13213 used_highlight_orders.entry(row).or_insert(highlight.index);
13214 if highlight.index >= *used_index {
13215 *used_index = highlight.index;
13216 unique_rows.insert(DisplayRow(row), highlight.color);
13217 }
13218 }
13219 unique_rows
13220 },
13221 )
13222 }
13223
13224 pub fn highlighted_display_row_for_autoscroll(
13225 &self,
13226 snapshot: &DisplaySnapshot,
13227 ) -> Option<DisplayRow> {
13228 self.highlighted_rows
13229 .values()
13230 .flat_map(|highlighted_rows| highlighted_rows.iter())
13231 .filter_map(|highlight| {
13232 if highlight.should_autoscroll {
13233 Some(highlight.range.start.to_display_point(snapshot).row())
13234 } else {
13235 None
13236 }
13237 })
13238 .min()
13239 }
13240
13241 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13242 self.highlight_background::<SearchWithinRange>(
13243 ranges,
13244 |colors| colors.editor_document_highlight_read_background,
13245 cx,
13246 )
13247 }
13248
13249 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13250 self.breadcrumb_header = Some(new_header);
13251 }
13252
13253 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13254 self.clear_background_highlights::<SearchWithinRange>(cx);
13255 }
13256
13257 pub fn highlight_background<T: 'static>(
13258 &mut self,
13259 ranges: &[Range<Anchor>],
13260 color_fetcher: fn(&ThemeColors) -> Hsla,
13261 cx: &mut Context<Self>,
13262 ) {
13263 self.background_highlights
13264 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13265 self.scrollbar_marker_state.dirty = true;
13266 cx.notify();
13267 }
13268
13269 pub fn clear_background_highlights<T: 'static>(
13270 &mut self,
13271 cx: &mut Context<Self>,
13272 ) -> Option<BackgroundHighlight> {
13273 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13274 if !text_highlights.1.is_empty() {
13275 self.scrollbar_marker_state.dirty = true;
13276 cx.notify();
13277 }
13278 Some(text_highlights)
13279 }
13280
13281 pub fn highlight_gutter<T: 'static>(
13282 &mut self,
13283 ranges: &[Range<Anchor>],
13284 color_fetcher: fn(&App) -> Hsla,
13285 cx: &mut Context<Self>,
13286 ) {
13287 self.gutter_highlights
13288 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13289 cx.notify();
13290 }
13291
13292 pub fn clear_gutter_highlights<T: 'static>(
13293 &mut self,
13294 cx: &mut Context<Self>,
13295 ) -> Option<GutterHighlight> {
13296 cx.notify();
13297 self.gutter_highlights.remove(&TypeId::of::<T>())
13298 }
13299
13300 #[cfg(feature = "test-support")]
13301 pub fn all_text_background_highlights(
13302 &self,
13303 window: &mut Window,
13304 cx: &mut Context<Self>,
13305 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13306 let snapshot = self.snapshot(window, cx);
13307 let buffer = &snapshot.buffer_snapshot;
13308 let start = buffer.anchor_before(0);
13309 let end = buffer.anchor_after(buffer.len());
13310 let theme = cx.theme().colors();
13311 self.background_highlights_in_range(start..end, &snapshot, theme)
13312 }
13313
13314 #[cfg(feature = "test-support")]
13315 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13316 let snapshot = self.buffer().read(cx).snapshot(cx);
13317
13318 let highlights = self
13319 .background_highlights
13320 .get(&TypeId::of::<items::BufferSearchHighlights>());
13321
13322 if let Some((_color, ranges)) = highlights {
13323 ranges
13324 .iter()
13325 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13326 .collect_vec()
13327 } else {
13328 vec![]
13329 }
13330 }
13331
13332 fn document_highlights_for_position<'a>(
13333 &'a self,
13334 position: Anchor,
13335 buffer: &'a MultiBufferSnapshot,
13336 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13337 let read_highlights = self
13338 .background_highlights
13339 .get(&TypeId::of::<DocumentHighlightRead>())
13340 .map(|h| &h.1);
13341 let write_highlights = self
13342 .background_highlights
13343 .get(&TypeId::of::<DocumentHighlightWrite>())
13344 .map(|h| &h.1);
13345 let left_position = position.bias_left(buffer);
13346 let right_position = position.bias_right(buffer);
13347 read_highlights
13348 .into_iter()
13349 .chain(write_highlights)
13350 .flat_map(move |ranges| {
13351 let start_ix = match ranges.binary_search_by(|probe| {
13352 let cmp = probe.end.cmp(&left_position, buffer);
13353 if cmp.is_ge() {
13354 Ordering::Greater
13355 } else {
13356 Ordering::Less
13357 }
13358 }) {
13359 Ok(i) | Err(i) => i,
13360 };
13361
13362 ranges[start_ix..]
13363 .iter()
13364 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13365 })
13366 }
13367
13368 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13369 self.background_highlights
13370 .get(&TypeId::of::<T>())
13371 .map_or(false, |(_, highlights)| !highlights.is_empty())
13372 }
13373
13374 pub fn background_highlights_in_range(
13375 &self,
13376 search_range: Range<Anchor>,
13377 display_snapshot: &DisplaySnapshot,
13378 theme: &ThemeColors,
13379 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13380 let mut results = Vec::new();
13381 for (color_fetcher, ranges) in self.background_highlights.values() {
13382 let color = color_fetcher(theme);
13383 let start_ix = match ranges.binary_search_by(|probe| {
13384 let cmp = probe
13385 .end
13386 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13387 if cmp.is_gt() {
13388 Ordering::Greater
13389 } else {
13390 Ordering::Less
13391 }
13392 }) {
13393 Ok(i) | Err(i) => i,
13394 };
13395 for range in &ranges[start_ix..] {
13396 if range
13397 .start
13398 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13399 .is_ge()
13400 {
13401 break;
13402 }
13403
13404 let start = range.start.to_display_point(display_snapshot);
13405 let end = range.end.to_display_point(display_snapshot);
13406 results.push((start..end, color))
13407 }
13408 }
13409 results
13410 }
13411
13412 pub fn background_highlight_row_ranges<T: 'static>(
13413 &self,
13414 search_range: Range<Anchor>,
13415 display_snapshot: &DisplaySnapshot,
13416 count: usize,
13417 ) -> Vec<RangeInclusive<DisplayPoint>> {
13418 let mut results = Vec::new();
13419 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13420 return vec![];
13421 };
13422
13423 let start_ix = match ranges.binary_search_by(|probe| {
13424 let cmp = probe
13425 .end
13426 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13427 if cmp.is_gt() {
13428 Ordering::Greater
13429 } else {
13430 Ordering::Less
13431 }
13432 }) {
13433 Ok(i) | Err(i) => i,
13434 };
13435 let mut push_region = |start: Option<Point>, end: Option<Point>| {
13436 if let (Some(start_display), Some(end_display)) = (start, end) {
13437 results.push(
13438 start_display.to_display_point(display_snapshot)
13439 ..=end_display.to_display_point(display_snapshot),
13440 );
13441 }
13442 };
13443 let mut start_row: Option<Point> = None;
13444 let mut end_row: Option<Point> = None;
13445 if ranges.len() > count {
13446 return Vec::new();
13447 }
13448 for range in &ranges[start_ix..] {
13449 if range
13450 .start
13451 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13452 .is_ge()
13453 {
13454 break;
13455 }
13456 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13457 if let Some(current_row) = &end_row {
13458 if end.row == current_row.row {
13459 continue;
13460 }
13461 }
13462 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13463 if start_row.is_none() {
13464 assert_eq!(end_row, None);
13465 start_row = Some(start);
13466 end_row = Some(end);
13467 continue;
13468 }
13469 if let Some(current_end) = end_row.as_mut() {
13470 if start.row > current_end.row + 1 {
13471 push_region(start_row, end_row);
13472 start_row = Some(start);
13473 end_row = Some(end);
13474 } else {
13475 // Merge two hunks.
13476 *current_end = end;
13477 }
13478 } else {
13479 unreachable!();
13480 }
13481 }
13482 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13483 push_region(start_row, end_row);
13484 results
13485 }
13486
13487 pub fn gutter_highlights_in_range(
13488 &self,
13489 search_range: Range<Anchor>,
13490 display_snapshot: &DisplaySnapshot,
13491 cx: &App,
13492 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13493 let mut results = Vec::new();
13494 for (color_fetcher, ranges) in self.gutter_highlights.values() {
13495 let color = color_fetcher(cx);
13496 let start_ix = match ranges.binary_search_by(|probe| {
13497 let cmp = probe
13498 .end
13499 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13500 if cmp.is_gt() {
13501 Ordering::Greater
13502 } else {
13503 Ordering::Less
13504 }
13505 }) {
13506 Ok(i) | Err(i) => i,
13507 };
13508 for range in &ranges[start_ix..] {
13509 if range
13510 .start
13511 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13512 .is_ge()
13513 {
13514 break;
13515 }
13516
13517 let start = range.start.to_display_point(display_snapshot);
13518 let end = range.end.to_display_point(display_snapshot);
13519 results.push((start..end, color))
13520 }
13521 }
13522 results
13523 }
13524
13525 /// Get the text ranges corresponding to the redaction query
13526 pub fn redacted_ranges(
13527 &self,
13528 search_range: Range<Anchor>,
13529 display_snapshot: &DisplaySnapshot,
13530 cx: &App,
13531 ) -> Vec<Range<DisplayPoint>> {
13532 display_snapshot
13533 .buffer_snapshot
13534 .redacted_ranges(search_range, |file| {
13535 if let Some(file) = file {
13536 file.is_private()
13537 && EditorSettings::get(
13538 Some(SettingsLocation {
13539 worktree_id: file.worktree_id(cx),
13540 path: file.path().as_ref(),
13541 }),
13542 cx,
13543 )
13544 .redact_private_values
13545 } else {
13546 false
13547 }
13548 })
13549 .map(|range| {
13550 range.start.to_display_point(display_snapshot)
13551 ..range.end.to_display_point(display_snapshot)
13552 })
13553 .collect()
13554 }
13555
13556 pub fn highlight_text<T: 'static>(
13557 &mut self,
13558 ranges: Vec<Range<Anchor>>,
13559 style: HighlightStyle,
13560 cx: &mut Context<Self>,
13561 ) {
13562 self.display_map.update(cx, |map, _| {
13563 map.highlight_text(TypeId::of::<T>(), ranges, style)
13564 });
13565 cx.notify();
13566 }
13567
13568 pub(crate) fn highlight_inlays<T: 'static>(
13569 &mut self,
13570 highlights: Vec<InlayHighlight>,
13571 style: HighlightStyle,
13572 cx: &mut Context<Self>,
13573 ) {
13574 self.display_map.update(cx, |map, _| {
13575 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13576 });
13577 cx.notify();
13578 }
13579
13580 pub fn text_highlights<'a, T: 'static>(
13581 &'a self,
13582 cx: &'a App,
13583 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13584 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13585 }
13586
13587 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13588 let cleared = self
13589 .display_map
13590 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13591 if cleared {
13592 cx.notify();
13593 }
13594 }
13595
13596 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13597 (self.read_only(cx) || self.blink_manager.read(cx).visible())
13598 && self.focus_handle.is_focused(window)
13599 }
13600
13601 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13602 self.show_cursor_when_unfocused = is_enabled;
13603 cx.notify();
13604 }
13605
13606 pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13607 self.project
13608 .as_ref()
13609 .map(|project| project.read(cx).lsp_store())
13610 }
13611
13612 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13613 cx.notify();
13614 }
13615
13616 fn on_buffer_event(
13617 &mut self,
13618 multibuffer: &Entity<MultiBuffer>,
13619 event: &multi_buffer::Event,
13620 window: &mut Window,
13621 cx: &mut Context<Self>,
13622 ) {
13623 match event {
13624 multi_buffer::Event::Edited {
13625 singleton_buffer_edited,
13626 edited_buffer: buffer_edited,
13627 } => {
13628 self.scrollbar_marker_state.dirty = true;
13629 self.active_indent_guides_state.dirty = true;
13630 self.refresh_active_diagnostics(cx);
13631 self.refresh_code_actions(window, cx);
13632 if self.has_active_inline_completion() {
13633 self.update_visible_inline_completion(window, cx);
13634 }
13635 if let Some(buffer) = buffer_edited {
13636 let buffer_id = buffer.read(cx).remote_id();
13637 if !self.registered_buffers.contains_key(&buffer_id) {
13638 if let Some(lsp_store) = self.lsp_store(cx) {
13639 lsp_store.update(cx, |lsp_store, cx| {
13640 self.registered_buffers.insert(
13641 buffer_id,
13642 lsp_store.register_buffer_with_language_servers(&buffer, cx),
13643 );
13644 })
13645 }
13646 }
13647 }
13648 cx.emit(EditorEvent::BufferEdited);
13649 cx.emit(SearchEvent::MatchesInvalidated);
13650 if *singleton_buffer_edited {
13651 if let Some(project) = &self.project {
13652 let project = project.read(cx);
13653 #[allow(clippy::mutable_key_type)]
13654 let languages_affected = multibuffer
13655 .read(cx)
13656 .all_buffers()
13657 .into_iter()
13658 .filter_map(|buffer| {
13659 let buffer = buffer.read(cx);
13660 let language = buffer.language()?;
13661 if project.is_local()
13662 && project
13663 .language_servers_for_local_buffer(buffer, cx)
13664 .count()
13665 == 0
13666 {
13667 None
13668 } else {
13669 Some(language)
13670 }
13671 })
13672 .cloned()
13673 .collect::<HashSet<_>>();
13674 if !languages_affected.is_empty() {
13675 self.refresh_inlay_hints(
13676 InlayHintRefreshReason::BufferEdited(languages_affected),
13677 cx,
13678 );
13679 }
13680 }
13681 }
13682
13683 let Some(project) = &self.project else { return };
13684 let (telemetry, is_via_ssh) = {
13685 let project = project.read(cx);
13686 let telemetry = project.client().telemetry().clone();
13687 let is_via_ssh = project.is_via_ssh();
13688 (telemetry, is_via_ssh)
13689 };
13690 refresh_linked_ranges(self, window, cx);
13691 telemetry.log_edit_event("editor", is_via_ssh);
13692 }
13693 multi_buffer::Event::ExcerptsAdded {
13694 buffer,
13695 predecessor,
13696 excerpts,
13697 } => {
13698 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13699 let buffer_id = buffer.read(cx).remote_id();
13700 if self.buffer.read(cx).change_set_for(buffer_id).is_none() {
13701 if let Some(project) = &self.project {
13702 get_unstaged_changes_for_buffers(
13703 project,
13704 [buffer.clone()],
13705 self.buffer.clone(),
13706 cx,
13707 );
13708 }
13709 }
13710 cx.emit(EditorEvent::ExcerptsAdded {
13711 buffer: buffer.clone(),
13712 predecessor: *predecessor,
13713 excerpts: excerpts.clone(),
13714 });
13715 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13716 }
13717 multi_buffer::Event::ExcerptsRemoved { ids } => {
13718 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13719 let buffer = self.buffer.read(cx);
13720 self.registered_buffers
13721 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13722 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13723 }
13724 multi_buffer::Event::ExcerptsEdited { ids } => {
13725 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13726 }
13727 multi_buffer::Event::ExcerptsExpanded { ids } => {
13728 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13729 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13730 }
13731 multi_buffer::Event::Reparsed(buffer_id) => {
13732 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13733
13734 cx.emit(EditorEvent::Reparsed(*buffer_id));
13735 }
13736 multi_buffer::Event::DiffHunksToggled => {
13737 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13738 }
13739 multi_buffer::Event::LanguageChanged(buffer_id) => {
13740 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13741 cx.emit(EditorEvent::Reparsed(*buffer_id));
13742 cx.notify();
13743 }
13744 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13745 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13746 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13747 cx.emit(EditorEvent::TitleChanged)
13748 }
13749 // multi_buffer::Event::DiffBaseChanged => {
13750 // self.scrollbar_marker_state.dirty = true;
13751 // cx.emit(EditorEvent::DiffBaseChanged);
13752 // cx.notify();
13753 // }
13754 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13755 multi_buffer::Event::DiagnosticsUpdated => {
13756 self.refresh_active_diagnostics(cx);
13757 self.scrollbar_marker_state.dirty = true;
13758 cx.notify();
13759 }
13760 _ => {}
13761 };
13762 }
13763
13764 fn on_display_map_changed(
13765 &mut self,
13766 _: Entity<DisplayMap>,
13767 _: &mut Window,
13768 cx: &mut Context<Self>,
13769 ) {
13770 cx.notify();
13771 }
13772
13773 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13774 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13775 self.refresh_inline_completion(true, false, window, cx);
13776 self.refresh_inlay_hints(
13777 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13778 self.selections.newest_anchor().head(),
13779 &self.buffer.read(cx).snapshot(cx),
13780 cx,
13781 )),
13782 cx,
13783 );
13784
13785 let old_cursor_shape = self.cursor_shape;
13786
13787 {
13788 let editor_settings = EditorSettings::get_global(cx);
13789 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13790 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13791 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13792 }
13793
13794 if old_cursor_shape != self.cursor_shape {
13795 cx.emit(EditorEvent::CursorShapeChanged);
13796 }
13797
13798 let project_settings = ProjectSettings::get_global(cx);
13799 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13800
13801 if self.mode == EditorMode::Full {
13802 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13803 if self.git_blame_inline_enabled != inline_blame_enabled {
13804 self.toggle_git_blame_inline_internal(false, window, cx);
13805 }
13806 }
13807
13808 cx.notify();
13809 }
13810
13811 pub fn set_searchable(&mut self, searchable: bool) {
13812 self.searchable = searchable;
13813 }
13814
13815 pub fn searchable(&self) -> bool {
13816 self.searchable
13817 }
13818
13819 fn open_proposed_changes_editor(
13820 &mut self,
13821 _: &OpenProposedChangesEditor,
13822 window: &mut Window,
13823 cx: &mut Context<Self>,
13824 ) {
13825 let Some(workspace) = self.workspace() else {
13826 cx.propagate();
13827 return;
13828 };
13829
13830 let selections = self.selections.all::<usize>(cx);
13831 let multi_buffer = self.buffer.read(cx);
13832 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13833 let mut new_selections_by_buffer = HashMap::default();
13834 for selection in selections {
13835 for (buffer, range, _) in
13836 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13837 {
13838 let mut range = range.to_point(buffer);
13839 range.start.column = 0;
13840 range.end.column = buffer.line_len(range.end.row);
13841 new_selections_by_buffer
13842 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13843 .or_insert(Vec::new())
13844 .push(range)
13845 }
13846 }
13847
13848 let proposed_changes_buffers = new_selections_by_buffer
13849 .into_iter()
13850 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13851 .collect::<Vec<_>>();
13852 let proposed_changes_editor = cx.new(|cx| {
13853 ProposedChangesEditor::new(
13854 "Proposed changes",
13855 proposed_changes_buffers,
13856 self.project.clone(),
13857 window,
13858 cx,
13859 )
13860 });
13861
13862 window.defer(cx, move |window, cx| {
13863 workspace.update(cx, |workspace, cx| {
13864 workspace.active_pane().update(cx, |pane, cx| {
13865 pane.add_item(
13866 Box::new(proposed_changes_editor),
13867 true,
13868 true,
13869 None,
13870 window,
13871 cx,
13872 );
13873 });
13874 });
13875 });
13876 }
13877
13878 pub fn open_excerpts_in_split(
13879 &mut self,
13880 _: &OpenExcerptsSplit,
13881 window: &mut Window,
13882 cx: &mut Context<Self>,
13883 ) {
13884 self.open_excerpts_common(None, true, window, cx)
13885 }
13886
13887 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
13888 self.open_excerpts_common(None, false, window, cx)
13889 }
13890
13891 fn open_excerpts_common(
13892 &mut self,
13893 jump_data: Option<JumpData>,
13894 split: bool,
13895 window: &mut Window,
13896 cx: &mut Context<Self>,
13897 ) {
13898 let Some(workspace) = self.workspace() else {
13899 cx.propagate();
13900 return;
13901 };
13902
13903 if self.buffer.read(cx).is_singleton() {
13904 cx.propagate();
13905 return;
13906 }
13907
13908 let mut new_selections_by_buffer = HashMap::default();
13909 match &jump_data {
13910 Some(JumpData::MultiBufferPoint {
13911 excerpt_id,
13912 position,
13913 anchor,
13914 line_offset_from_top,
13915 }) => {
13916 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13917 if let Some(buffer) = multi_buffer_snapshot
13918 .buffer_id_for_excerpt(*excerpt_id)
13919 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
13920 {
13921 let buffer_snapshot = buffer.read(cx).snapshot();
13922 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
13923 language::ToPoint::to_point(anchor, &buffer_snapshot)
13924 } else {
13925 buffer_snapshot.clip_point(*position, Bias::Left)
13926 };
13927 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
13928 new_selections_by_buffer.insert(
13929 buffer,
13930 (
13931 vec![jump_to_offset..jump_to_offset],
13932 Some(*line_offset_from_top),
13933 ),
13934 );
13935 }
13936 }
13937 Some(JumpData::MultiBufferRow {
13938 row,
13939 line_offset_from_top,
13940 }) => {
13941 let point = MultiBufferPoint::new(row.0, 0);
13942 if let Some((buffer, buffer_point, _)) =
13943 self.buffer.read(cx).point_to_buffer_point(point, cx)
13944 {
13945 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
13946 new_selections_by_buffer
13947 .entry(buffer)
13948 .or_insert((Vec::new(), Some(*line_offset_from_top)))
13949 .0
13950 .push(buffer_offset..buffer_offset)
13951 }
13952 }
13953 None => {
13954 let selections = self.selections.all::<usize>(cx);
13955 let multi_buffer = self.buffer.read(cx);
13956 for selection in selections {
13957 for (buffer, mut range, _) in multi_buffer
13958 .snapshot(cx)
13959 .range_to_buffer_ranges(selection.range())
13960 {
13961 // When editing branch buffers, jump to the corresponding location
13962 // in their base buffer.
13963 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
13964 let buffer = buffer_handle.read(cx);
13965 if let Some(base_buffer) = buffer.base_buffer() {
13966 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
13967 buffer_handle = base_buffer;
13968 }
13969
13970 if selection.reversed {
13971 mem::swap(&mut range.start, &mut range.end);
13972 }
13973 new_selections_by_buffer
13974 .entry(buffer_handle)
13975 .or_insert((Vec::new(), None))
13976 .0
13977 .push(range)
13978 }
13979 }
13980 }
13981 }
13982
13983 if new_selections_by_buffer.is_empty() {
13984 return;
13985 }
13986
13987 // We defer the pane interaction because we ourselves are a workspace item
13988 // and activating a new item causes the pane to call a method on us reentrantly,
13989 // which panics if we're on the stack.
13990 window.defer(cx, move |window, cx| {
13991 workspace.update(cx, |workspace, cx| {
13992 let pane = if split {
13993 workspace.adjacent_pane(window, cx)
13994 } else {
13995 workspace.active_pane().clone()
13996 };
13997
13998 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
13999 let editor = buffer
14000 .read(cx)
14001 .file()
14002 .is_none()
14003 .then(|| {
14004 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14005 // so `workspace.open_project_item` will never find them, always opening a new editor.
14006 // Instead, we try to activate the existing editor in the pane first.
14007 let (editor, pane_item_index) =
14008 pane.read(cx).items().enumerate().find_map(|(i, item)| {
14009 let editor = item.downcast::<Editor>()?;
14010 let singleton_buffer =
14011 editor.read(cx).buffer().read(cx).as_singleton()?;
14012 if singleton_buffer == buffer {
14013 Some((editor, i))
14014 } else {
14015 None
14016 }
14017 })?;
14018 pane.update(cx, |pane, cx| {
14019 pane.activate_item(pane_item_index, true, true, window, cx)
14020 });
14021 Some(editor)
14022 })
14023 .flatten()
14024 .unwrap_or_else(|| {
14025 workspace.open_project_item::<Self>(
14026 pane.clone(),
14027 buffer,
14028 true,
14029 true,
14030 window,
14031 cx,
14032 )
14033 });
14034
14035 editor.update(cx, |editor, cx| {
14036 let autoscroll = match scroll_offset {
14037 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14038 None => Autoscroll::newest(),
14039 };
14040 let nav_history = editor.nav_history.take();
14041 editor.change_selections(Some(autoscroll), window, cx, |s| {
14042 s.select_ranges(ranges);
14043 });
14044 editor.nav_history = nav_history;
14045 });
14046 }
14047 })
14048 });
14049 }
14050
14051 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14052 let snapshot = self.buffer.read(cx).read(cx);
14053 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14054 Some(
14055 ranges
14056 .iter()
14057 .map(move |range| {
14058 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14059 })
14060 .collect(),
14061 )
14062 }
14063
14064 fn selection_replacement_ranges(
14065 &self,
14066 range: Range<OffsetUtf16>,
14067 cx: &mut App,
14068 ) -> Vec<Range<OffsetUtf16>> {
14069 let selections = self.selections.all::<OffsetUtf16>(cx);
14070 let newest_selection = selections
14071 .iter()
14072 .max_by_key(|selection| selection.id)
14073 .unwrap();
14074 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14075 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14076 let snapshot = self.buffer.read(cx).read(cx);
14077 selections
14078 .into_iter()
14079 .map(|mut selection| {
14080 selection.start.0 =
14081 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14082 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14083 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14084 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14085 })
14086 .collect()
14087 }
14088
14089 fn report_editor_event(
14090 &self,
14091 event_type: &'static str,
14092 file_extension: Option<String>,
14093 cx: &App,
14094 ) {
14095 if cfg!(any(test, feature = "test-support")) {
14096 return;
14097 }
14098
14099 let Some(project) = &self.project else { return };
14100
14101 // If None, we are in a file without an extension
14102 let file = self
14103 .buffer
14104 .read(cx)
14105 .as_singleton()
14106 .and_then(|b| b.read(cx).file());
14107 let file_extension = file_extension.or(file
14108 .as_ref()
14109 .and_then(|file| Path::new(file.file_name(cx)).extension())
14110 .and_then(|e| e.to_str())
14111 .map(|a| a.to_string()));
14112
14113 let vim_mode = cx
14114 .global::<SettingsStore>()
14115 .raw_user_settings()
14116 .get("vim_mode")
14117 == Some(&serde_json::Value::Bool(true));
14118
14119 let edit_predictions_provider = all_language_settings(file, cx).inline_completions.provider;
14120 let copilot_enabled = edit_predictions_provider
14121 == language::language_settings::InlineCompletionProvider::Copilot;
14122 let copilot_enabled_for_language = self
14123 .buffer
14124 .read(cx)
14125 .settings_at(0, cx)
14126 .show_inline_completions;
14127
14128 let project = project.read(cx);
14129 telemetry::event!(
14130 event_type,
14131 file_extension,
14132 vim_mode,
14133 copilot_enabled,
14134 copilot_enabled_for_language,
14135 edit_predictions_provider,
14136 is_via_ssh = project.is_via_ssh(),
14137 );
14138 }
14139
14140 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14141 /// with each line being an array of {text, highlight} objects.
14142 fn copy_highlight_json(
14143 &mut self,
14144 _: &CopyHighlightJson,
14145 window: &mut Window,
14146 cx: &mut Context<Self>,
14147 ) {
14148 #[derive(Serialize)]
14149 struct Chunk<'a> {
14150 text: String,
14151 highlight: Option<&'a str>,
14152 }
14153
14154 let snapshot = self.buffer.read(cx).snapshot(cx);
14155 let range = self
14156 .selected_text_range(false, window, cx)
14157 .and_then(|selection| {
14158 if selection.range.is_empty() {
14159 None
14160 } else {
14161 Some(selection.range)
14162 }
14163 })
14164 .unwrap_or_else(|| 0..snapshot.len());
14165
14166 let chunks = snapshot.chunks(range, true);
14167 let mut lines = Vec::new();
14168 let mut line: VecDeque<Chunk> = VecDeque::new();
14169
14170 let Some(style) = self.style.as_ref() else {
14171 return;
14172 };
14173
14174 for chunk in chunks {
14175 let highlight = chunk
14176 .syntax_highlight_id
14177 .and_then(|id| id.name(&style.syntax));
14178 let mut chunk_lines = chunk.text.split('\n').peekable();
14179 while let Some(text) = chunk_lines.next() {
14180 let mut merged_with_last_token = false;
14181 if let Some(last_token) = line.back_mut() {
14182 if last_token.highlight == highlight {
14183 last_token.text.push_str(text);
14184 merged_with_last_token = true;
14185 }
14186 }
14187
14188 if !merged_with_last_token {
14189 line.push_back(Chunk {
14190 text: text.into(),
14191 highlight,
14192 });
14193 }
14194
14195 if chunk_lines.peek().is_some() {
14196 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14197 line.pop_front();
14198 }
14199 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14200 line.pop_back();
14201 }
14202
14203 lines.push(mem::take(&mut line));
14204 }
14205 }
14206 }
14207
14208 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14209 return;
14210 };
14211 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14212 }
14213
14214 pub fn open_context_menu(
14215 &mut self,
14216 _: &OpenContextMenu,
14217 window: &mut Window,
14218 cx: &mut Context<Self>,
14219 ) {
14220 self.request_autoscroll(Autoscroll::newest(), cx);
14221 let position = self.selections.newest_display(cx).start;
14222 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14223 }
14224
14225 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14226 &self.inlay_hint_cache
14227 }
14228
14229 pub fn replay_insert_event(
14230 &mut self,
14231 text: &str,
14232 relative_utf16_range: Option<Range<isize>>,
14233 window: &mut Window,
14234 cx: &mut Context<Self>,
14235 ) {
14236 if !self.input_enabled {
14237 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14238 return;
14239 }
14240 if let Some(relative_utf16_range) = relative_utf16_range {
14241 let selections = self.selections.all::<OffsetUtf16>(cx);
14242 self.change_selections(None, window, cx, |s| {
14243 let new_ranges = selections.into_iter().map(|range| {
14244 let start = OffsetUtf16(
14245 range
14246 .head()
14247 .0
14248 .saturating_add_signed(relative_utf16_range.start),
14249 );
14250 let end = OffsetUtf16(
14251 range
14252 .head()
14253 .0
14254 .saturating_add_signed(relative_utf16_range.end),
14255 );
14256 start..end
14257 });
14258 s.select_ranges(new_ranges);
14259 });
14260 }
14261
14262 self.handle_input(text, window, cx);
14263 }
14264
14265 pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14266 let Some(provider) = self.semantics_provider.as_ref() else {
14267 return false;
14268 };
14269
14270 let mut supports = false;
14271 self.buffer().read(cx).for_each_buffer(|buffer| {
14272 supports |= provider.supports_inlay_hints(buffer, cx);
14273 });
14274 supports
14275 }
14276 pub fn is_focused(&self, window: &mut Window) -> bool {
14277 self.focus_handle.is_focused(window)
14278 }
14279
14280 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14281 cx.emit(EditorEvent::Focused);
14282
14283 if let Some(descendant) = self
14284 .last_focused_descendant
14285 .take()
14286 .and_then(|descendant| descendant.upgrade())
14287 {
14288 window.focus(&descendant);
14289 } else {
14290 if let Some(blame) = self.blame.as_ref() {
14291 blame.update(cx, GitBlame::focus)
14292 }
14293
14294 self.blink_manager.update(cx, BlinkManager::enable);
14295 self.show_cursor_names(window, cx);
14296 self.buffer.update(cx, |buffer, cx| {
14297 buffer.finalize_last_transaction(cx);
14298 if self.leader_peer_id.is_none() {
14299 buffer.set_active_selections(
14300 &self.selections.disjoint_anchors(),
14301 self.selections.line_mode,
14302 self.cursor_shape,
14303 cx,
14304 );
14305 }
14306 });
14307 }
14308 }
14309
14310 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14311 cx.emit(EditorEvent::FocusedIn)
14312 }
14313
14314 fn handle_focus_out(
14315 &mut self,
14316 event: FocusOutEvent,
14317 _window: &mut Window,
14318 _cx: &mut Context<Self>,
14319 ) {
14320 if event.blurred != self.focus_handle {
14321 self.last_focused_descendant = Some(event.blurred);
14322 }
14323 }
14324
14325 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14326 self.blink_manager.update(cx, BlinkManager::disable);
14327 self.buffer
14328 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14329
14330 if let Some(blame) = self.blame.as_ref() {
14331 blame.update(cx, GitBlame::blur)
14332 }
14333 if !self.hover_state.focused(window, cx) {
14334 hide_hover(self, cx);
14335 }
14336
14337 self.hide_context_menu(window, cx);
14338 cx.emit(EditorEvent::Blurred);
14339 cx.notify();
14340 }
14341
14342 pub fn register_action<A: Action>(
14343 &mut self,
14344 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14345 ) -> Subscription {
14346 let id = self.next_editor_action_id.post_inc();
14347 let listener = Arc::new(listener);
14348 self.editor_actions.borrow_mut().insert(
14349 id,
14350 Box::new(move |window, _| {
14351 let listener = listener.clone();
14352 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14353 let action = action.downcast_ref().unwrap();
14354 if phase == DispatchPhase::Bubble {
14355 listener(action, window, cx)
14356 }
14357 })
14358 }),
14359 );
14360
14361 let editor_actions = self.editor_actions.clone();
14362 Subscription::new(move || {
14363 editor_actions.borrow_mut().remove(&id);
14364 })
14365 }
14366
14367 pub fn file_header_size(&self) -> u32 {
14368 FILE_HEADER_HEIGHT
14369 }
14370
14371 pub fn revert(
14372 &mut self,
14373 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14374 window: &mut Window,
14375 cx: &mut Context<Self>,
14376 ) {
14377 self.buffer().update(cx, |multi_buffer, cx| {
14378 for (buffer_id, changes) in revert_changes {
14379 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14380 buffer.update(cx, |buffer, cx| {
14381 buffer.edit(
14382 changes.into_iter().map(|(range, text)| {
14383 (range, text.to_string().map(Arc::<str>::from))
14384 }),
14385 None,
14386 cx,
14387 );
14388 });
14389 }
14390 }
14391 });
14392 self.change_selections(None, window, cx, |selections| selections.refresh());
14393 }
14394
14395 pub fn to_pixel_point(
14396 &self,
14397 source: multi_buffer::Anchor,
14398 editor_snapshot: &EditorSnapshot,
14399 window: &mut Window,
14400 ) -> Option<gpui::Point<Pixels>> {
14401 let source_point = source.to_display_point(editor_snapshot);
14402 self.display_to_pixel_point(source_point, editor_snapshot, window)
14403 }
14404
14405 pub fn display_to_pixel_point(
14406 &self,
14407 source: DisplayPoint,
14408 editor_snapshot: &EditorSnapshot,
14409 window: &mut Window,
14410 ) -> Option<gpui::Point<Pixels>> {
14411 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14412 let text_layout_details = self.text_layout_details(window);
14413 let scroll_top = text_layout_details
14414 .scroll_anchor
14415 .scroll_position(editor_snapshot)
14416 .y;
14417
14418 if source.row().as_f32() < scroll_top.floor() {
14419 return None;
14420 }
14421 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14422 let source_y = line_height * (source.row().as_f32() - scroll_top);
14423 Some(gpui::Point::new(source_x, source_y))
14424 }
14425
14426 pub fn has_active_completions_menu(&self) -> bool {
14427 self.context_menu.borrow().as_ref().map_or(false, |menu| {
14428 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14429 })
14430 }
14431
14432 pub fn register_addon<T: Addon>(&mut self, instance: T) {
14433 self.addons
14434 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14435 }
14436
14437 pub fn unregister_addon<T: Addon>(&mut self) {
14438 self.addons.remove(&std::any::TypeId::of::<T>());
14439 }
14440
14441 pub fn addon<T: Addon>(&self) -> Option<&T> {
14442 let type_id = std::any::TypeId::of::<T>();
14443 self.addons
14444 .get(&type_id)
14445 .and_then(|item| item.to_any().downcast_ref::<T>())
14446 }
14447
14448 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14449 let text_layout_details = self.text_layout_details(window);
14450 let style = &text_layout_details.editor_style;
14451 let font_id = window.text_system().resolve_font(&style.text.font());
14452 let font_size = style.text.font_size.to_pixels(window.rem_size());
14453 let line_height = style.text.line_height_in_pixels(window.rem_size());
14454 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14455
14456 gpui::Size::new(em_width, line_height)
14457 }
14458}
14459
14460fn get_unstaged_changes_for_buffers(
14461 project: &Entity<Project>,
14462 buffers: impl IntoIterator<Item = Entity<Buffer>>,
14463 buffer: Entity<MultiBuffer>,
14464 cx: &mut App,
14465) {
14466 let mut tasks = Vec::new();
14467 project.update(cx, |project, cx| {
14468 for buffer in buffers {
14469 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
14470 }
14471 });
14472 cx.spawn(|mut cx| async move {
14473 let change_sets = futures::future::join_all(tasks).await;
14474 buffer
14475 .update(&mut cx, |buffer, cx| {
14476 for change_set in change_sets {
14477 if let Some(change_set) = change_set.log_err() {
14478 buffer.add_change_set(change_set, cx);
14479 }
14480 }
14481 })
14482 .ok();
14483 })
14484 .detach();
14485}
14486
14487fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14488 let tab_size = tab_size.get() as usize;
14489 let mut width = offset;
14490
14491 for ch in text.chars() {
14492 width += if ch == '\t' {
14493 tab_size - (width % tab_size)
14494 } else {
14495 1
14496 };
14497 }
14498
14499 width - offset
14500}
14501
14502#[cfg(test)]
14503mod tests {
14504 use super::*;
14505
14506 #[test]
14507 fn test_string_size_with_expanded_tabs() {
14508 let nz = |val| NonZeroU32::new(val).unwrap();
14509 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14510 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14511 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14512 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14513 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14514 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14515 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14516 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14517 }
14518}
14519
14520/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14521struct WordBreakingTokenizer<'a> {
14522 input: &'a str,
14523}
14524
14525impl<'a> WordBreakingTokenizer<'a> {
14526 fn new(input: &'a str) -> Self {
14527 Self { input }
14528 }
14529}
14530
14531fn is_char_ideographic(ch: char) -> bool {
14532 use unicode_script::Script::*;
14533 use unicode_script::UnicodeScript;
14534 matches!(ch.script(), Han | Tangut | Yi)
14535}
14536
14537fn is_grapheme_ideographic(text: &str) -> bool {
14538 text.chars().any(is_char_ideographic)
14539}
14540
14541fn is_grapheme_whitespace(text: &str) -> bool {
14542 text.chars().any(|x| x.is_whitespace())
14543}
14544
14545fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14546 text.chars().next().map_or(false, |ch| {
14547 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14548 })
14549}
14550
14551#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14552struct WordBreakToken<'a> {
14553 token: &'a str,
14554 grapheme_len: usize,
14555 is_whitespace: bool,
14556}
14557
14558impl<'a> Iterator for WordBreakingTokenizer<'a> {
14559 /// Yields a span, the count of graphemes in the token, and whether it was
14560 /// whitespace. Note that it also breaks at word boundaries.
14561 type Item = WordBreakToken<'a>;
14562
14563 fn next(&mut self) -> Option<Self::Item> {
14564 use unicode_segmentation::UnicodeSegmentation;
14565 if self.input.is_empty() {
14566 return None;
14567 }
14568
14569 let mut iter = self.input.graphemes(true).peekable();
14570 let mut offset = 0;
14571 let mut graphemes = 0;
14572 if let Some(first_grapheme) = iter.next() {
14573 let is_whitespace = is_grapheme_whitespace(first_grapheme);
14574 offset += first_grapheme.len();
14575 graphemes += 1;
14576 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14577 if let Some(grapheme) = iter.peek().copied() {
14578 if should_stay_with_preceding_ideograph(grapheme) {
14579 offset += grapheme.len();
14580 graphemes += 1;
14581 }
14582 }
14583 } else {
14584 let mut words = self.input[offset..].split_word_bound_indices().peekable();
14585 let mut next_word_bound = words.peek().copied();
14586 if next_word_bound.map_or(false, |(i, _)| i == 0) {
14587 next_word_bound = words.next();
14588 }
14589 while let Some(grapheme) = iter.peek().copied() {
14590 if next_word_bound.map_or(false, |(i, _)| i == offset) {
14591 break;
14592 };
14593 if is_grapheme_whitespace(grapheme) != is_whitespace {
14594 break;
14595 };
14596 offset += grapheme.len();
14597 graphemes += 1;
14598 iter.next();
14599 }
14600 }
14601 let token = &self.input[..offset];
14602 self.input = &self.input[offset..];
14603 if is_whitespace {
14604 Some(WordBreakToken {
14605 token: " ",
14606 grapheme_len: 1,
14607 is_whitespace: true,
14608 })
14609 } else {
14610 Some(WordBreakToken {
14611 token,
14612 grapheme_len: graphemes,
14613 is_whitespace: false,
14614 })
14615 }
14616 } else {
14617 None
14618 }
14619 }
14620}
14621
14622#[test]
14623fn test_word_breaking_tokenizer() {
14624 let tests: &[(&str, &[(&str, usize, bool)])] = &[
14625 ("", &[]),
14626 (" ", &[(" ", 1, true)]),
14627 ("Ʒ", &[("Ʒ", 1, false)]),
14628 ("Ǽ", &[("Ǽ", 1, false)]),
14629 ("⋑", &[("⋑", 1, false)]),
14630 ("⋑⋑", &[("⋑⋑", 2, false)]),
14631 (
14632 "原理,进而",
14633 &[
14634 ("原", 1, false),
14635 ("理,", 2, false),
14636 ("进", 1, false),
14637 ("而", 1, false),
14638 ],
14639 ),
14640 (
14641 "hello world",
14642 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14643 ),
14644 (
14645 "hello, world",
14646 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14647 ),
14648 (
14649 " hello world",
14650 &[
14651 (" ", 1, true),
14652 ("hello", 5, false),
14653 (" ", 1, true),
14654 ("world", 5, false),
14655 ],
14656 ),
14657 (
14658 "这是什么 \n 钢笔",
14659 &[
14660 ("这", 1, false),
14661 ("是", 1, false),
14662 ("什", 1, false),
14663 ("么", 1, false),
14664 (" ", 1, true),
14665 ("钢", 1, false),
14666 ("笔", 1, false),
14667 ],
14668 ),
14669 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14670 ];
14671
14672 for (input, result) in tests {
14673 assert_eq!(
14674 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14675 result
14676 .iter()
14677 .copied()
14678 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14679 token,
14680 grapheme_len,
14681 is_whitespace,
14682 })
14683 .collect::<Vec<_>>()
14684 );
14685 }
14686}
14687
14688fn wrap_with_prefix(
14689 line_prefix: String,
14690 unwrapped_text: String,
14691 wrap_column: usize,
14692 tab_size: NonZeroU32,
14693) -> String {
14694 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14695 let mut wrapped_text = String::new();
14696 let mut current_line = line_prefix.clone();
14697
14698 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14699 let mut current_line_len = line_prefix_len;
14700 for WordBreakToken {
14701 token,
14702 grapheme_len,
14703 is_whitespace,
14704 } in tokenizer
14705 {
14706 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14707 wrapped_text.push_str(current_line.trim_end());
14708 wrapped_text.push('\n');
14709 current_line.truncate(line_prefix.len());
14710 current_line_len = line_prefix_len;
14711 if !is_whitespace {
14712 current_line.push_str(token);
14713 current_line_len += grapheme_len;
14714 }
14715 } else if !is_whitespace {
14716 current_line.push_str(token);
14717 current_line_len += grapheme_len;
14718 } else if current_line_len != line_prefix_len {
14719 current_line.push(' ');
14720 current_line_len += 1;
14721 }
14722 }
14723
14724 if !current_line.is_empty() {
14725 wrapped_text.push_str(¤t_line);
14726 }
14727 wrapped_text
14728}
14729
14730#[test]
14731fn test_wrap_with_prefix() {
14732 assert_eq!(
14733 wrap_with_prefix(
14734 "# ".to_string(),
14735 "abcdefg".to_string(),
14736 4,
14737 NonZeroU32::new(4).unwrap()
14738 ),
14739 "# abcdefg"
14740 );
14741 assert_eq!(
14742 wrap_with_prefix(
14743 "".to_string(),
14744 "\thello world".to_string(),
14745 8,
14746 NonZeroU32::new(4).unwrap()
14747 ),
14748 "hello\nworld"
14749 );
14750 assert_eq!(
14751 wrap_with_prefix(
14752 "// ".to_string(),
14753 "xx \nyy zz aa bb cc".to_string(),
14754 12,
14755 NonZeroU32::new(4).unwrap()
14756 ),
14757 "// xx yy zz\n// aa bb cc"
14758 );
14759 assert_eq!(
14760 wrap_with_prefix(
14761 String::new(),
14762 "这是什么 \n 钢笔".to_string(),
14763 3,
14764 NonZeroU32::new(4).unwrap()
14765 ),
14766 "这是什\n么 钢\n笔"
14767 );
14768}
14769
14770pub trait CollaborationHub {
14771 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14772 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14773 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14774}
14775
14776impl CollaborationHub for Entity<Project> {
14777 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14778 self.read(cx).collaborators()
14779 }
14780
14781 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14782 self.read(cx).user_store().read(cx).participant_indices()
14783 }
14784
14785 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14786 let this = self.read(cx);
14787 let user_ids = this.collaborators().values().map(|c| c.user_id);
14788 this.user_store().read_with(cx, |user_store, cx| {
14789 user_store.participant_names(user_ids, cx)
14790 })
14791 }
14792}
14793
14794pub trait SemanticsProvider {
14795 fn hover(
14796 &self,
14797 buffer: &Entity<Buffer>,
14798 position: text::Anchor,
14799 cx: &mut App,
14800 ) -> Option<Task<Vec<project::Hover>>>;
14801
14802 fn inlay_hints(
14803 &self,
14804 buffer_handle: Entity<Buffer>,
14805 range: Range<text::Anchor>,
14806 cx: &mut App,
14807 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14808
14809 fn resolve_inlay_hint(
14810 &self,
14811 hint: InlayHint,
14812 buffer_handle: Entity<Buffer>,
14813 server_id: LanguageServerId,
14814 cx: &mut App,
14815 ) -> Option<Task<anyhow::Result<InlayHint>>>;
14816
14817 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
14818
14819 fn document_highlights(
14820 &self,
14821 buffer: &Entity<Buffer>,
14822 position: text::Anchor,
14823 cx: &mut App,
14824 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14825
14826 fn definitions(
14827 &self,
14828 buffer: &Entity<Buffer>,
14829 position: text::Anchor,
14830 kind: GotoDefinitionKind,
14831 cx: &mut App,
14832 ) -> Option<Task<Result<Vec<LocationLink>>>>;
14833
14834 fn range_for_rename(
14835 &self,
14836 buffer: &Entity<Buffer>,
14837 position: text::Anchor,
14838 cx: &mut App,
14839 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14840
14841 fn perform_rename(
14842 &self,
14843 buffer: &Entity<Buffer>,
14844 position: text::Anchor,
14845 new_name: String,
14846 cx: &mut App,
14847 ) -> Option<Task<Result<ProjectTransaction>>>;
14848}
14849
14850pub trait CompletionProvider {
14851 fn completions(
14852 &self,
14853 buffer: &Entity<Buffer>,
14854 buffer_position: text::Anchor,
14855 trigger: CompletionContext,
14856 window: &mut Window,
14857 cx: &mut Context<Editor>,
14858 ) -> Task<Result<Vec<Completion>>>;
14859
14860 fn resolve_completions(
14861 &self,
14862 buffer: Entity<Buffer>,
14863 completion_indices: Vec<usize>,
14864 completions: Rc<RefCell<Box<[Completion]>>>,
14865 cx: &mut Context<Editor>,
14866 ) -> Task<Result<bool>>;
14867
14868 fn apply_additional_edits_for_completion(
14869 &self,
14870 _buffer: Entity<Buffer>,
14871 _completions: Rc<RefCell<Box<[Completion]>>>,
14872 _completion_index: usize,
14873 _push_to_history: bool,
14874 _cx: &mut Context<Editor>,
14875 ) -> Task<Result<Option<language::Transaction>>> {
14876 Task::ready(Ok(None))
14877 }
14878
14879 fn is_completion_trigger(
14880 &self,
14881 buffer: &Entity<Buffer>,
14882 position: language::Anchor,
14883 text: &str,
14884 trigger_in_words: bool,
14885 cx: &mut Context<Editor>,
14886 ) -> bool;
14887
14888 fn sort_completions(&self) -> bool {
14889 true
14890 }
14891}
14892
14893pub trait CodeActionProvider {
14894 fn id(&self) -> Arc<str>;
14895
14896 fn code_actions(
14897 &self,
14898 buffer: &Entity<Buffer>,
14899 range: Range<text::Anchor>,
14900 window: &mut Window,
14901 cx: &mut App,
14902 ) -> Task<Result<Vec<CodeAction>>>;
14903
14904 fn apply_code_action(
14905 &self,
14906 buffer_handle: Entity<Buffer>,
14907 action: CodeAction,
14908 excerpt_id: ExcerptId,
14909 push_to_history: bool,
14910 window: &mut Window,
14911 cx: &mut App,
14912 ) -> Task<Result<ProjectTransaction>>;
14913}
14914
14915impl CodeActionProvider for Entity<Project> {
14916 fn id(&self) -> Arc<str> {
14917 "project".into()
14918 }
14919
14920 fn code_actions(
14921 &self,
14922 buffer: &Entity<Buffer>,
14923 range: Range<text::Anchor>,
14924 _window: &mut Window,
14925 cx: &mut App,
14926 ) -> Task<Result<Vec<CodeAction>>> {
14927 self.update(cx, |project, cx| {
14928 project.code_actions(buffer, range, None, cx)
14929 })
14930 }
14931
14932 fn apply_code_action(
14933 &self,
14934 buffer_handle: Entity<Buffer>,
14935 action: CodeAction,
14936 _excerpt_id: ExcerptId,
14937 push_to_history: bool,
14938 _window: &mut Window,
14939 cx: &mut App,
14940 ) -> Task<Result<ProjectTransaction>> {
14941 self.update(cx, |project, cx| {
14942 project.apply_code_action(buffer_handle, action, push_to_history, cx)
14943 })
14944 }
14945}
14946
14947fn snippet_completions(
14948 project: &Project,
14949 buffer: &Entity<Buffer>,
14950 buffer_position: text::Anchor,
14951 cx: &mut App,
14952) -> Task<Result<Vec<Completion>>> {
14953 let language = buffer.read(cx).language_at(buffer_position);
14954 let language_name = language.as_ref().map(|language| language.lsp_id());
14955 let snippet_store = project.snippets().read(cx);
14956 let snippets = snippet_store.snippets_for(language_name, cx);
14957
14958 if snippets.is_empty() {
14959 return Task::ready(Ok(vec![]));
14960 }
14961 let snapshot = buffer.read(cx).text_snapshot();
14962 let chars: String = snapshot
14963 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
14964 .collect();
14965
14966 let scope = language.map(|language| language.default_scope());
14967 let executor = cx.background_executor().clone();
14968
14969 cx.background_executor().spawn(async move {
14970 let classifier = CharClassifier::new(scope).for_completion(true);
14971 let mut last_word = chars
14972 .chars()
14973 .take_while(|c| classifier.is_word(*c))
14974 .collect::<String>();
14975 last_word = last_word.chars().rev().collect();
14976
14977 if last_word.is_empty() {
14978 return Ok(vec![]);
14979 }
14980
14981 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
14982 let to_lsp = |point: &text::Anchor| {
14983 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
14984 point_to_lsp(end)
14985 };
14986 let lsp_end = to_lsp(&buffer_position);
14987
14988 let candidates = snippets
14989 .iter()
14990 .enumerate()
14991 .flat_map(|(ix, snippet)| {
14992 snippet
14993 .prefix
14994 .iter()
14995 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
14996 })
14997 .collect::<Vec<StringMatchCandidate>>();
14998
14999 let mut matches = fuzzy::match_strings(
15000 &candidates,
15001 &last_word,
15002 last_word.chars().any(|c| c.is_uppercase()),
15003 100,
15004 &Default::default(),
15005 executor,
15006 )
15007 .await;
15008
15009 // Remove all candidates where the query's start does not match the start of any word in the candidate
15010 if let Some(query_start) = last_word.chars().next() {
15011 matches.retain(|string_match| {
15012 split_words(&string_match.string).any(|word| {
15013 // Check that the first codepoint of the word as lowercase matches the first
15014 // codepoint of the query as lowercase
15015 word.chars()
15016 .flat_map(|codepoint| codepoint.to_lowercase())
15017 .zip(query_start.to_lowercase())
15018 .all(|(word_cp, query_cp)| word_cp == query_cp)
15019 })
15020 });
15021 }
15022
15023 let matched_strings = matches
15024 .into_iter()
15025 .map(|m| m.string)
15026 .collect::<HashSet<_>>();
15027
15028 let result: Vec<Completion> = snippets
15029 .into_iter()
15030 .filter_map(|snippet| {
15031 let matching_prefix = snippet
15032 .prefix
15033 .iter()
15034 .find(|prefix| matched_strings.contains(*prefix))?;
15035 let start = as_offset - last_word.len();
15036 let start = snapshot.anchor_before(start);
15037 let range = start..buffer_position;
15038 let lsp_start = to_lsp(&start);
15039 let lsp_range = lsp::Range {
15040 start: lsp_start,
15041 end: lsp_end,
15042 };
15043 Some(Completion {
15044 old_range: range,
15045 new_text: snippet.body.clone(),
15046 resolved: false,
15047 label: CodeLabel {
15048 text: matching_prefix.clone(),
15049 runs: vec![],
15050 filter_range: 0..matching_prefix.len(),
15051 },
15052 server_id: LanguageServerId(usize::MAX),
15053 documentation: snippet
15054 .description
15055 .clone()
15056 .map(CompletionDocumentation::SingleLine),
15057 lsp_completion: lsp::CompletionItem {
15058 label: snippet.prefix.first().unwrap().clone(),
15059 kind: Some(CompletionItemKind::SNIPPET),
15060 label_details: snippet.description.as_ref().map(|description| {
15061 lsp::CompletionItemLabelDetails {
15062 detail: Some(description.clone()),
15063 description: None,
15064 }
15065 }),
15066 insert_text_format: Some(InsertTextFormat::SNIPPET),
15067 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15068 lsp::InsertReplaceEdit {
15069 new_text: snippet.body.clone(),
15070 insert: lsp_range,
15071 replace: lsp_range,
15072 },
15073 )),
15074 filter_text: Some(snippet.body.clone()),
15075 sort_text: Some(char::MAX.to_string()),
15076 ..Default::default()
15077 },
15078 confirm: None,
15079 })
15080 })
15081 .collect();
15082
15083 Ok(result)
15084 })
15085}
15086
15087impl CompletionProvider for Entity<Project> {
15088 fn completions(
15089 &self,
15090 buffer: &Entity<Buffer>,
15091 buffer_position: text::Anchor,
15092 options: CompletionContext,
15093 _window: &mut Window,
15094 cx: &mut Context<Editor>,
15095 ) -> Task<Result<Vec<Completion>>> {
15096 self.update(cx, |project, cx| {
15097 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15098 let project_completions = project.completions(buffer, buffer_position, options, cx);
15099 cx.background_executor().spawn(async move {
15100 let mut completions = project_completions.await?;
15101 let snippets_completions = snippets.await?;
15102 completions.extend(snippets_completions);
15103 Ok(completions)
15104 })
15105 })
15106 }
15107
15108 fn resolve_completions(
15109 &self,
15110 buffer: Entity<Buffer>,
15111 completion_indices: Vec<usize>,
15112 completions: Rc<RefCell<Box<[Completion]>>>,
15113 cx: &mut Context<Editor>,
15114 ) -> Task<Result<bool>> {
15115 self.update(cx, |project, cx| {
15116 project.lsp_store().update(cx, |lsp_store, cx| {
15117 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15118 })
15119 })
15120 }
15121
15122 fn apply_additional_edits_for_completion(
15123 &self,
15124 buffer: Entity<Buffer>,
15125 completions: Rc<RefCell<Box<[Completion]>>>,
15126 completion_index: usize,
15127 push_to_history: bool,
15128 cx: &mut Context<Editor>,
15129 ) -> Task<Result<Option<language::Transaction>>> {
15130 self.update(cx, |project, cx| {
15131 project.lsp_store().update(cx, |lsp_store, cx| {
15132 lsp_store.apply_additional_edits_for_completion(
15133 buffer,
15134 completions,
15135 completion_index,
15136 push_to_history,
15137 cx,
15138 )
15139 })
15140 })
15141 }
15142
15143 fn is_completion_trigger(
15144 &self,
15145 buffer: &Entity<Buffer>,
15146 position: language::Anchor,
15147 text: &str,
15148 trigger_in_words: bool,
15149 cx: &mut Context<Editor>,
15150 ) -> bool {
15151 let mut chars = text.chars();
15152 let char = if let Some(char) = chars.next() {
15153 char
15154 } else {
15155 return false;
15156 };
15157 if chars.next().is_some() {
15158 return false;
15159 }
15160
15161 let buffer = buffer.read(cx);
15162 let snapshot = buffer.snapshot();
15163 if !snapshot.settings_at(position, cx).show_completions_on_input {
15164 return false;
15165 }
15166 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15167 if trigger_in_words && classifier.is_word(char) {
15168 return true;
15169 }
15170
15171 buffer.completion_triggers().contains(text)
15172 }
15173}
15174
15175impl SemanticsProvider for Entity<Project> {
15176 fn hover(
15177 &self,
15178 buffer: &Entity<Buffer>,
15179 position: text::Anchor,
15180 cx: &mut App,
15181 ) -> Option<Task<Vec<project::Hover>>> {
15182 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15183 }
15184
15185 fn document_highlights(
15186 &self,
15187 buffer: &Entity<Buffer>,
15188 position: text::Anchor,
15189 cx: &mut App,
15190 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15191 Some(self.update(cx, |project, cx| {
15192 project.document_highlights(buffer, position, cx)
15193 }))
15194 }
15195
15196 fn definitions(
15197 &self,
15198 buffer: &Entity<Buffer>,
15199 position: text::Anchor,
15200 kind: GotoDefinitionKind,
15201 cx: &mut App,
15202 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15203 Some(self.update(cx, |project, cx| match kind {
15204 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15205 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15206 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15207 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15208 }))
15209 }
15210
15211 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15212 // TODO: make this work for remote projects
15213 self.read(cx)
15214 .language_servers_for_local_buffer(buffer.read(cx), cx)
15215 .any(
15216 |(_, server)| match server.capabilities().inlay_hint_provider {
15217 Some(lsp::OneOf::Left(enabled)) => enabled,
15218 Some(lsp::OneOf::Right(_)) => true,
15219 None => false,
15220 },
15221 )
15222 }
15223
15224 fn inlay_hints(
15225 &self,
15226 buffer_handle: Entity<Buffer>,
15227 range: Range<text::Anchor>,
15228 cx: &mut App,
15229 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15230 Some(self.update(cx, |project, cx| {
15231 project.inlay_hints(buffer_handle, range, cx)
15232 }))
15233 }
15234
15235 fn resolve_inlay_hint(
15236 &self,
15237 hint: InlayHint,
15238 buffer_handle: Entity<Buffer>,
15239 server_id: LanguageServerId,
15240 cx: &mut App,
15241 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15242 Some(self.update(cx, |project, cx| {
15243 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15244 }))
15245 }
15246
15247 fn range_for_rename(
15248 &self,
15249 buffer: &Entity<Buffer>,
15250 position: text::Anchor,
15251 cx: &mut App,
15252 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15253 Some(self.update(cx, |project, cx| {
15254 let buffer = buffer.clone();
15255 let task = project.prepare_rename(buffer.clone(), position, cx);
15256 cx.spawn(|_, mut cx| async move {
15257 Ok(match task.await? {
15258 PrepareRenameResponse::Success(range) => Some(range),
15259 PrepareRenameResponse::InvalidPosition => None,
15260 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15261 // Fallback on using TreeSitter info to determine identifier range
15262 buffer.update(&mut cx, |buffer, _| {
15263 let snapshot = buffer.snapshot();
15264 let (range, kind) = snapshot.surrounding_word(position);
15265 if kind != Some(CharKind::Word) {
15266 return None;
15267 }
15268 Some(
15269 snapshot.anchor_before(range.start)
15270 ..snapshot.anchor_after(range.end),
15271 )
15272 })?
15273 }
15274 })
15275 })
15276 }))
15277 }
15278
15279 fn perform_rename(
15280 &self,
15281 buffer: &Entity<Buffer>,
15282 position: text::Anchor,
15283 new_name: String,
15284 cx: &mut App,
15285 ) -> Option<Task<Result<ProjectTransaction>>> {
15286 Some(self.update(cx, |project, cx| {
15287 project.perform_rename(buffer.clone(), position, new_name, cx)
15288 }))
15289 }
15290}
15291
15292fn inlay_hint_settings(
15293 location: Anchor,
15294 snapshot: &MultiBufferSnapshot,
15295 cx: &mut Context<Editor>,
15296) -> InlayHintSettings {
15297 let file = snapshot.file_at(location);
15298 let language = snapshot.language_at(location).map(|l| l.name());
15299 language_settings(language, file, cx).inlay_hints
15300}
15301
15302fn consume_contiguous_rows(
15303 contiguous_row_selections: &mut Vec<Selection<Point>>,
15304 selection: &Selection<Point>,
15305 display_map: &DisplaySnapshot,
15306 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15307) -> (MultiBufferRow, MultiBufferRow) {
15308 contiguous_row_selections.push(selection.clone());
15309 let start_row = MultiBufferRow(selection.start.row);
15310 let mut end_row = ending_row(selection, display_map);
15311
15312 while let Some(next_selection) = selections.peek() {
15313 if next_selection.start.row <= end_row.0 {
15314 end_row = ending_row(next_selection, display_map);
15315 contiguous_row_selections.push(selections.next().unwrap().clone());
15316 } else {
15317 break;
15318 }
15319 }
15320 (start_row, end_row)
15321}
15322
15323fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15324 if next_selection.end.column > 0 || next_selection.is_empty() {
15325 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15326 } else {
15327 MultiBufferRow(next_selection.end.row)
15328 }
15329}
15330
15331impl EditorSnapshot {
15332 pub fn remote_selections_in_range<'a>(
15333 &'a self,
15334 range: &'a Range<Anchor>,
15335 collaboration_hub: &dyn CollaborationHub,
15336 cx: &'a App,
15337 ) -> impl 'a + Iterator<Item = RemoteSelection> {
15338 let participant_names = collaboration_hub.user_names(cx);
15339 let participant_indices = collaboration_hub.user_participant_indices(cx);
15340 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15341 let collaborators_by_replica_id = collaborators_by_peer_id
15342 .iter()
15343 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15344 .collect::<HashMap<_, _>>();
15345 self.buffer_snapshot
15346 .selections_in_range(range, false)
15347 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15348 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15349 let participant_index = participant_indices.get(&collaborator.user_id).copied();
15350 let user_name = participant_names.get(&collaborator.user_id).cloned();
15351 Some(RemoteSelection {
15352 replica_id,
15353 selection,
15354 cursor_shape,
15355 line_mode,
15356 participant_index,
15357 peer_id: collaborator.peer_id,
15358 user_name,
15359 })
15360 })
15361 }
15362
15363 pub fn hunks_for_ranges(
15364 &self,
15365 ranges: impl Iterator<Item = Range<Point>>,
15366 ) -> Vec<MultiBufferDiffHunk> {
15367 let mut hunks = Vec::new();
15368 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15369 HashMap::default();
15370 for query_range in ranges {
15371 let query_rows =
15372 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15373 for hunk in self.buffer_snapshot.diff_hunks_in_range(
15374 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15375 ) {
15376 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15377 // when the caret is just above or just below the deleted hunk.
15378 let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15379 let related_to_selection = if allow_adjacent {
15380 hunk.row_range.overlaps(&query_rows)
15381 || hunk.row_range.start == query_rows.end
15382 || hunk.row_range.end == query_rows.start
15383 } else {
15384 hunk.row_range.overlaps(&query_rows)
15385 };
15386 if related_to_selection {
15387 if !processed_buffer_rows
15388 .entry(hunk.buffer_id)
15389 .or_default()
15390 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15391 {
15392 continue;
15393 }
15394 hunks.push(hunk);
15395 }
15396 }
15397 }
15398
15399 hunks
15400 }
15401
15402 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15403 self.display_snapshot.buffer_snapshot.language_at(position)
15404 }
15405
15406 pub fn is_focused(&self) -> bool {
15407 self.is_focused
15408 }
15409
15410 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15411 self.placeholder_text.as_ref()
15412 }
15413
15414 pub fn scroll_position(&self) -> gpui::Point<f32> {
15415 self.scroll_anchor.scroll_position(&self.display_snapshot)
15416 }
15417
15418 fn gutter_dimensions(
15419 &self,
15420 font_id: FontId,
15421 font_size: Pixels,
15422 max_line_number_width: Pixels,
15423 cx: &App,
15424 ) -> Option<GutterDimensions> {
15425 if !self.show_gutter {
15426 return None;
15427 }
15428
15429 let descent = cx.text_system().descent(font_id, font_size);
15430 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15431 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15432
15433 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15434 matches!(
15435 ProjectSettings::get_global(cx).git.git_gutter,
15436 Some(GitGutterSetting::TrackedFiles)
15437 )
15438 });
15439 let gutter_settings = EditorSettings::get_global(cx).gutter;
15440 let show_line_numbers = self
15441 .show_line_numbers
15442 .unwrap_or(gutter_settings.line_numbers);
15443 let line_gutter_width = if show_line_numbers {
15444 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15445 let min_width_for_number_on_gutter = em_advance * 4.0;
15446 max_line_number_width.max(min_width_for_number_on_gutter)
15447 } else {
15448 0.0.into()
15449 };
15450
15451 let show_code_actions = self
15452 .show_code_actions
15453 .unwrap_or(gutter_settings.code_actions);
15454
15455 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15456
15457 let git_blame_entries_width =
15458 self.git_blame_gutter_max_author_length
15459 .map(|max_author_length| {
15460 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15461
15462 /// The number of characters to dedicate to gaps and margins.
15463 const SPACING_WIDTH: usize = 4;
15464
15465 let max_char_count = max_author_length
15466 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15467 + ::git::SHORT_SHA_LENGTH
15468 + MAX_RELATIVE_TIMESTAMP.len()
15469 + SPACING_WIDTH;
15470
15471 em_advance * max_char_count
15472 });
15473
15474 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15475 left_padding += if show_code_actions || show_runnables {
15476 em_width * 3.0
15477 } else if show_git_gutter && show_line_numbers {
15478 em_width * 2.0
15479 } else if show_git_gutter || show_line_numbers {
15480 em_width
15481 } else {
15482 px(0.)
15483 };
15484
15485 let right_padding = if gutter_settings.folds && show_line_numbers {
15486 em_width * 4.0
15487 } else if gutter_settings.folds {
15488 em_width * 3.0
15489 } else if show_line_numbers {
15490 em_width
15491 } else {
15492 px(0.)
15493 };
15494
15495 Some(GutterDimensions {
15496 left_padding,
15497 right_padding,
15498 width: line_gutter_width + left_padding + right_padding,
15499 margin: -descent,
15500 git_blame_entries_width,
15501 })
15502 }
15503
15504 pub fn render_crease_toggle(
15505 &self,
15506 buffer_row: MultiBufferRow,
15507 row_contains_cursor: bool,
15508 editor: Entity<Editor>,
15509 window: &mut Window,
15510 cx: &mut App,
15511 ) -> Option<AnyElement> {
15512 let folded = self.is_line_folded(buffer_row);
15513 let mut is_foldable = false;
15514
15515 if let Some(crease) = self
15516 .crease_snapshot
15517 .query_row(buffer_row, &self.buffer_snapshot)
15518 {
15519 is_foldable = true;
15520 match crease {
15521 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15522 if let Some(render_toggle) = render_toggle {
15523 let toggle_callback =
15524 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15525 if folded {
15526 editor.update(cx, |editor, cx| {
15527 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15528 });
15529 } else {
15530 editor.update(cx, |editor, cx| {
15531 editor.unfold_at(
15532 &crate::UnfoldAt { buffer_row },
15533 window,
15534 cx,
15535 )
15536 });
15537 }
15538 });
15539 return Some((render_toggle)(
15540 buffer_row,
15541 folded,
15542 toggle_callback,
15543 window,
15544 cx,
15545 ));
15546 }
15547 }
15548 }
15549 }
15550
15551 is_foldable |= self.starts_indent(buffer_row);
15552
15553 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15554 Some(
15555 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15556 .toggle_state(folded)
15557 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15558 if folded {
15559 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15560 } else {
15561 this.fold_at(&FoldAt { buffer_row }, window, cx);
15562 }
15563 }))
15564 .into_any_element(),
15565 )
15566 } else {
15567 None
15568 }
15569 }
15570
15571 pub fn render_crease_trailer(
15572 &self,
15573 buffer_row: MultiBufferRow,
15574 window: &mut Window,
15575 cx: &mut App,
15576 ) -> Option<AnyElement> {
15577 let folded = self.is_line_folded(buffer_row);
15578 if let Crease::Inline { render_trailer, .. } = self
15579 .crease_snapshot
15580 .query_row(buffer_row, &self.buffer_snapshot)?
15581 {
15582 let render_trailer = render_trailer.as_ref()?;
15583 Some(render_trailer(buffer_row, folded, window, cx))
15584 } else {
15585 None
15586 }
15587 }
15588}
15589
15590impl Deref for EditorSnapshot {
15591 type Target = DisplaySnapshot;
15592
15593 fn deref(&self) -> &Self::Target {
15594 &self.display_snapshot
15595 }
15596}
15597
15598#[derive(Clone, Debug, PartialEq, Eq)]
15599pub enum EditorEvent {
15600 InputIgnored {
15601 text: Arc<str>,
15602 },
15603 InputHandled {
15604 utf16_range_to_replace: Option<Range<isize>>,
15605 text: Arc<str>,
15606 },
15607 ExcerptsAdded {
15608 buffer: Entity<Buffer>,
15609 predecessor: ExcerptId,
15610 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15611 },
15612 ExcerptsRemoved {
15613 ids: Vec<ExcerptId>,
15614 },
15615 BufferFoldToggled {
15616 ids: Vec<ExcerptId>,
15617 folded: bool,
15618 },
15619 ExcerptsEdited {
15620 ids: Vec<ExcerptId>,
15621 },
15622 ExcerptsExpanded {
15623 ids: Vec<ExcerptId>,
15624 },
15625 BufferEdited,
15626 Edited {
15627 transaction_id: clock::Lamport,
15628 },
15629 Reparsed(BufferId),
15630 Focused,
15631 FocusedIn,
15632 Blurred,
15633 DirtyChanged,
15634 Saved,
15635 TitleChanged,
15636 DiffBaseChanged,
15637 SelectionsChanged {
15638 local: bool,
15639 },
15640 ScrollPositionChanged {
15641 local: bool,
15642 autoscroll: bool,
15643 },
15644 Closed,
15645 TransactionUndone {
15646 transaction_id: clock::Lamport,
15647 },
15648 TransactionBegun {
15649 transaction_id: clock::Lamport,
15650 },
15651 Reloaded,
15652 CursorShapeChanged,
15653}
15654
15655impl EventEmitter<EditorEvent> for Editor {}
15656
15657impl Focusable for Editor {
15658 fn focus_handle(&self, _cx: &App) -> FocusHandle {
15659 self.focus_handle.clone()
15660 }
15661}
15662
15663impl Render for Editor {
15664 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15665 let settings = ThemeSettings::get_global(cx);
15666
15667 let mut text_style = match self.mode {
15668 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15669 color: cx.theme().colors().editor_foreground,
15670 font_family: settings.ui_font.family.clone(),
15671 font_features: settings.ui_font.features.clone(),
15672 font_fallbacks: settings.ui_font.fallbacks.clone(),
15673 font_size: rems(0.875).into(),
15674 font_weight: settings.ui_font.weight,
15675 line_height: relative(settings.buffer_line_height.value()),
15676 ..Default::default()
15677 },
15678 EditorMode::Full => TextStyle {
15679 color: cx.theme().colors().editor_foreground,
15680 font_family: settings.buffer_font.family.clone(),
15681 font_features: settings.buffer_font.features.clone(),
15682 font_fallbacks: settings.buffer_font.fallbacks.clone(),
15683 font_size: settings.buffer_font_size().into(),
15684 font_weight: settings.buffer_font.weight,
15685 line_height: relative(settings.buffer_line_height.value()),
15686 ..Default::default()
15687 },
15688 };
15689 if let Some(text_style_refinement) = &self.text_style_refinement {
15690 text_style.refine(text_style_refinement)
15691 }
15692
15693 let background = match self.mode {
15694 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15695 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15696 EditorMode::Full => cx.theme().colors().editor_background,
15697 };
15698
15699 EditorElement::new(
15700 &cx.entity(),
15701 EditorStyle {
15702 background,
15703 local_player: cx.theme().players().local(),
15704 text: text_style,
15705 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15706 syntax: cx.theme().syntax().clone(),
15707 status: cx.theme().status().clone(),
15708 inlay_hints_style: make_inlay_hints_style(cx),
15709 inline_completion_styles: make_suggestion_styles(cx),
15710 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15711 },
15712 )
15713 }
15714}
15715
15716impl EntityInputHandler for Editor {
15717 fn text_for_range(
15718 &mut self,
15719 range_utf16: Range<usize>,
15720 adjusted_range: &mut Option<Range<usize>>,
15721 _: &mut Window,
15722 cx: &mut Context<Self>,
15723 ) -> Option<String> {
15724 let snapshot = self.buffer.read(cx).read(cx);
15725 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15726 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15727 if (start.0..end.0) != range_utf16 {
15728 adjusted_range.replace(start.0..end.0);
15729 }
15730 Some(snapshot.text_for_range(start..end).collect())
15731 }
15732
15733 fn selected_text_range(
15734 &mut self,
15735 ignore_disabled_input: bool,
15736 _: &mut Window,
15737 cx: &mut Context<Self>,
15738 ) -> Option<UTF16Selection> {
15739 // Prevent the IME menu from appearing when holding down an alphabetic key
15740 // while input is disabled.
15741 if !ignore_disabled_input && !self.input_enabled {
15742 return None;
15743 }
15744
15745 let selection = self.selections.newest::<OffsetUtf16>(cx);
15746 let range = selection.range();
15747
15748 Some(UTF16Selection {
15749 range: range.start.0..range.end.0,
15750 reversed: selection.reversed,
15751 })
15752 }
15753
15754 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15755 let snapshot = self.buffer.read(cx).read(cx);
15756 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15757 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15758 }
15759
15760 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15761 self.clear_highlights::<InputComposition>(cx);
15762 self.ime_transaction.take();
15763 }
15764
15765 fn replace_text_in_range(
15766 &mut self,
15767 range_utf16: Option<Range<usize>>,
15768 text: &str,
15769 window: &mut Window,
15770 cx: &mut Context<Self>,
15771 ) {
15772 if !self.input_enabled {
15773 cx.emit(EditorEvent::InputIgnored { text: text.into() });
15774 return;
15775 }
15776
15777 self.transact(window, cx, |this, window, cx| {
15778 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15779 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15780 Some(this.selection_replacement_ranges(range_utf16, cx))
15781 } else {
15782 this.marked_text_ranges(cx)
15783 };
15784
15785 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15786 let newest_selection_id = this.selections.newest_anchor().id;
15787 this.selections
15788 .all::<OffsetUtf16>(cx)
15789 .iter()
15790 .zip(ranges_to_replace.iter())
15791 .find_map(|(selection, range)| {
15792 if selection.id == newest_selection_id {
15793 Some(
15794 (range.start.0 as isize - selection.head().0 as isize)
15795 ..(range.end.0 as isize - selection.head().0 as isize),
15796 )
15797 } else {
15798 None
15799 }
15800 })
15801 });
15802
15803 cx.emit(EditorEvent::InputHandled {
15804 utf16_range_to_replace: range_to_replace,
15805 text: text.into(),
15806 });
15807
15808 if let Some(new_selected_ranges) = new_selected_ranges {
15809 this.change_selections(None, window, cx, |selections| {
15810 selections.select_ranges(new_selected_ranges)
15811 });
15812 this.backspace(&Default::default(), window, cx);
15813 }
15814
15815 this.handle_input(text, window, cx);
15816 });
15817
15818 if let Some(transaction) = self.ime_transaction {
15819 self.buffer.update(cx, |buffer, cx| {
15820 buffer.group_until_transaction(transaction, cx);
15821 });
15822 }
15823
15824 self.unmark_text(window, cx);
15825 }
15826
15827 fn replace_and_mark_text_in_range(
15828 &mut self,
15829 range_utf16: Option<Range<usize>>,
15830 text: &str,
15831 new_selected_range_utf16: Option<Range<usize>>,
15832 window: &mut Window,
15833 cx: &mut Context<Self>,
15834 ) {
15835 if !self.input_enabled {
15836 return;
15837 }
15838
15839 let transaction = self.transact(window, cx, |this, window, cx| {
15840 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15841 let snapshot = this.buffer.read(cx).read(cx);
15842 if let Some(relative_range_utf16) = range_utf16.as_ref() {
15843 for marked_range in &mut marked_ranges {
15844 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15845 marked_range.start.0 += relative_range_utf16.start;
15846 marked_range.start =
15847 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15848 marked_range.end =
15849 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15850 }
15851 }
15852 Some(marked_ranges)
15853 } else if let Some(range_utf16) = range_utf16 {
15854 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15855 Some(this.selection_replacement_ranges(range_utf16, cx))
15856 } else {
15857 None
15858 };
15859
15860 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
15861 let newest_selection_id = this.selections.newest_anchor().id;
15862 this.selections
15863 .all::<OffsetUtf16>(cx)
15864 .iter()
15865 .zip(ranges_to_replace.iter())
15866 .find_map(|(selection, range)| {
15867 if selection.id == newest_selection_id {
15868 Some(
15869 (range.start.0 as isize - selection.head().0 as isize)
15870 ..(range.end.0 as isize - selection.head().0 as isize),
15871 )
15872 } else {
15873 None
15874 }
15875 })
15876 });
15877
15878 cx.emit(EditorEvent::InputHandled {
15879 utf16_range_to_replace: range_to_replace,
15880 text: text.into(),
15881 });
15882
15883 if let Some(ranges) = ranges_to_replace {
15884 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
15885 }
15886
15887 let marked_ranges = {
15888 let snapshot = this.buffer.read(cx).read(cx);
15889 this.selections
15890 .disjoint_anchors()
15891 .iter()
15892 .map(|selection| {
15893 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
15894 })
15895 .collect::<Vec<_>>()
15896 };
15897
15898 if text.is_empty() {
15899 this.unmark_text(window, cx);
15900 } else {
15901 this.highlight_text::<InputComposition>(
15902 marked_ranges.clone(),
15903 HighlightStyle {
15904 underline: Some(UnderlineStyle {
15905 thickness: px(1.),
15906 color: None,
15907 wavy: false,
15908 }),
15909 ..Default::default()
15910 },
15911 cx,
15912 );
15913 }
15914
15915 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
15916 let use_autoclose = this.use_autoclose;
15917 let use_auto_surround = this.use_auto_surround;
15918 this.set_use_autoclose(false);
15919 this.set_use_auto_surround(false);
15920 this.handle_input(text, window, cx);
15921 this.set_use_autoclose(use_autoclose);
15922 this.set_use_auto_surround(use_auto_surround);
15923
15924 if let Some(new_selected_range) = new_selected_range_utf16 {
15925 let snapshot = this.buffer.read(cx).read(cx);
15926 let new_selected_ranges = marked_ranges
15927 .into_iter()
15928 .map(|marked_range| {
15929 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
15930 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
15931 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
15932 snapshot.clip_offset_utf16(new_start, Bias::Left)
15933 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
15934 })
15935 .collect::<Vec<_>>();
15936
15937 drop(snapshot);
15938 this.change_selections(None, window, cx, |selections| {
15939 selections.select_ranges(new_selected_ranges)
15940 });
15941 }
15942 });
15943
15944 self.ime_transaction = self.ime_transaction.or(transaction);
15945 if let Some(transaction) = self.ime_transaction {
15946 self.buffer.update(cx, |buffer, cx| {
15947 buffer.group_until_transaction(transaction, cx);
15948 });
15949 }
15950
15951 if self.text_highlights::<InputComposition>(cx).is_none() {
15952 self.ime_transaction.take();
15953 }
15954 }
15955
15956 fn bounds_for_range(
15957 &mut self,
15958 range_utf16: Range<usize>,
15959 element_bounds: gpui::Bounds<Pixels>,
15960 window: &mut Window,
15961 cx: &mut Context<Self>,
15962 ) -> Option<gpui::Bounds<Pixels>> {
15963 let text_layout_details = self.text_layout_details(window);
15964 let gpui::Size {
15965 width: em_width,
15966 height: line_height,
15967 } = self.character_size(window);
15968
15969 let snapshot = self.snapshot(window, cx);
15970 let scroll_position = snapshot.scroll_position();
15971 let scroll_left = scroll_position.x * em_width;
15972
15973 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
15974 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
15975 + self.gutter_dimensions.width
15976 + self.gutter_dimensions.margin;
15977 let y = line_height * (start.row().as_f32() - scroll_position.y);
15978
15979 Some(Bounds {
15980 origin: element_bounds.origin + point(x, y),
15981 size: size(em_width, line_height),
15982 })
15983 }
15984
15985 fn character_index_for_point(
15986 &mut self,
15987 point: gpui::Point<Pixels>,
15988 _window: &mut Window,
15989 _cx: &mut Context<Self>,
15990 ) -> Option<usize> {
15991 let position_map = self.last_position_map.as_ref()?;
15992 if !position_map.text_hitbox.contains(&point) {
15993 return None;
15994 }
15995 let display_point = position_map.point_for_position(point).previous_valid;
15996 let anchor = position_map
15997 .snapshot
15998 .display_point_to_anchor(display_point, Bias::Left);
15999 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16000 Some(utf16_offset.0)
16001 }
16002}
16003
16004trait SelectionExt {
16005 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16006 fn spanned_rows(
16007 &self,
16008 include_end_if_at_line_start: bool,
16009 map: &DisplaySnapshot,
16010 ) -> Range<MultiBufferRow>;
16011}
16012
16013impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16014 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16015 let start = self
16016 .start
16017 .to_point(&map.buffer_snapshot)
16018 .to_display_point(map);
16019 let end = self
16020 .end
16021 .to_point(&map.buffer_snapshot)
16022 .to_display_point(map);
16023 if self.reversed {
16024 end..start
16025 } else {
16026 start..end
16027 }
16028 }
16029
16030 fn spanned_rows(
16031 &self,
16032 include_end_if_at_line_start: bool,
16033 map: &DisplaySnapshot,
16034 ) -> Range<MultiBufferRow> {
16035 let start = self.start.to_point(&map.buffer_snapshot);
16036 let mut end = self.end.to_point(&map.buffer_snapshot);
16037 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16038 end.row -= 1;
16039 }
16040
16041 let buffer_start = map.prev_line_boundary(start).0;
16042 let buffer_end = map.next_line_boundary(end).0;
16043 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16044 }
16045}
16046
16047impl<T: InvalidationRegion> InvalidationStack<T> {
16048 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16049 where
16050 S: Clone + ToOffset,
16051 {
16052 while let Some(region) = self.last() {
16053 let all_selections_inside_invalidation_ranges =
16054 if selections.len() == region.ranges().len() {
16055 selections
16056 .iter()
16057 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16058 .all(|(selection, invalidation_range)| {
16059 let head = selection.head().to_offset(buffer);
16060 invalidation_range.start <= head && invalidation_range.end >= head
16061 })
16062 } else {
16063 false
16064 };
16065
16066 if all_selections_inside_invalidation_ranges {
16067 break;
16068 } else {
16069 self.pop();
16070 }
16071 }
16072 }
16073}
16074
16075impl<T> Default for InvalidationStack<T> {
16076 fn default() -> Self {
16077 Self(Default::default())
16078 }
16079}
16080
16081impl<T> Deref for InvalidationStack<T> {
16082 type Target = Vec<T>;
16083
16084 fn deref(&self) -> &Self::Target {
16085 &self.0
16086 }
16087}
16088
16089impl<T> DerefMut for InvalidationStack<T> {
16090 fn deref_mut(&mut self) -> &mut Self::Target {
16091 &mut self.0
16092 }
16093}
16094
16095impl InvalidationRegion for SnippetState {
16096 fn ranges(&self) -> &[Range<Anchor>] {
16097 &self.ranges[self.active_index]
16098 }
16099}
16100
16101pub fn diagnostic_block_renderer(
16102 diagnostic: Diagnostic,
16103 max_message_rows: Option<u8>,
16104 allow_closing: bool,
16105 _is_valid: bool,
16106) -> RenderBlock {
16107 let (text_without_backticks, code_ranges) =
16108 highlight_diagnostic_message(&diagnostic, max_message_rows);
16109
16110 Arc::new(move |cx: &mut BlockContext| {
16111 let group_id: SharedString = cx.block_id.to_string().into();
16112
16113 let mut text_style = cx.window.text_style().clone();
16114 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16115 let theme_settings = ThemeSettings::get_global(cx);
16116 text_style.font_family = theme_settings.buffer_font.family.clone();
16117 text_style.font_style = theme_settings.buffer_font.style;
16118 text_style.font_features = theme_settings.buffer_font.features.clone();
16119 text_style.font_weight = theme_settings.buffer_font.weight;
16120
16121 let multi_line_diagnostic = diagnostic.message.contains('\n');
16122
16123 let buttons = |diagnostic: &Diagnostic| {
16124 if multi_line_diagnostic {
16125 v_flex()
16126 } else {
16127 h_flex()
16128 }
16129 .when(allow_closing, |div| {
16130 div.children(diagnostic.is_primary.then(|| {
16131 IconButton::new("close-block", IconName::XCircle)
16132 .icon_color(Color::Muted)
16133 .size(ButtonSize::Compact)
16134 .style(ButtonStyle::Transparent)
16135 .visible_on_hover(group_id.clone())
16136 .on_click(move |_click, window, cx| {
16137 window.dispatch_action(Box::new(Cancel), cx)
16138 })
16139 .tooltip(|window, cx| {
16140 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16141 })
16142 }))
16143 })
16144 .child(
16145 IconButton::new("copy-block", IconName::Copy)
16146 .icon_color(Color::Muted)
16147 .size(ButtonSize::Compact)
16148 .style(ButtonStyle::Transparent)
16149 .visible_on_hover(group_id.clone())
16150 .on_click({
16151 let message = diagnostic.message.clone();
16152 move |_click, _, cx| {
16153 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16154 }
16155 })
16156 .tooltip(Tooltip::text("Copy diagnostic message")),
16157 )
16158 };
16159
16160 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16161 AvailableSpace::min_size(),
16162 cx.window,
16163 cx.app,
16164 );
16165
16166 h_flex()
16167 .id(cx.block_id)
16168 .group(group_id.clone())
16169 .relative()
16170 .size_full()
16171 .block_mouse_down()
16172 .pl(cx.gutter_dimensions.width)
16173 .w(cx.max_width - cx.gutter_dimensions.full_width())
16174 .child(
16175 div()
16176 .flex()
16177 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16178 .flex_shrink(),
16179 )
16180 .child(buttons(&diagnostic))
16181 .child(div().flex().flex_shrink_0().child(
16182 StyledText::new(text_without_backticks.clone()).with_highlights(
16183 &text_style,
16184 code_ranges.iter().map(|range| {
16185 (
16186 range.clone(),
16187 HighlightStyle {
16188 font_weight: Some(FontWeight::BOLD),
16189 ..Default::default()
16190 },
16191 )
16192 }),
16193 ),
16194 ))
16195 .into_any_element()
16196 })
16197}
16198
16199fn inline_completion_edit_text(
16200 current_snapshot: &BufferSnapshot,
16201 edits: &[(Range<Anchor>, String)],
16202 edit_preview: &EditPreview,
16203 include_deletions: bool,
16204 cx: &App,
16205) -> HighlightedText {
16206 let edits = edits
16207 .iter()
16208 .map(|(anchor, text)| {
16209 (
16210 anchor.start.text_anchor..anchor.end.text_anchor,
16211 text.clone(),
16212 )
16213 })
16214 .collect::<Vec<_>>();
16215
16216 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16217}
16218
16219pub fn highlight_diagnostic_message(
16220 diagnostic: &Diagnostic,
16221 mut max_message_rows: Option<u8>,
16222) -> (SharedString, Vec<Range<usize>>) {
16223 let mut text_without_backticks = String::new();
16224 let mut code_ranges = Vec::new();
16225
16226 if let Some(source) = &diagnostic.source {
16227 text_without_backticks.push_str(source);
16228 code_ranges.push(0..source.len());
16229 text_without_backticks.push_str(": ");
16230 }
16231
16232 let mut prev_offset = 0;
16233 let mut in_code_block = false;
16234 let has_row_limit = max_message_rows.is_some();
16235 let mut newline_indices = diagnostic
16236 .message
16237 .match_indices('\n')
16238 .filter(|_| has_row_limit)
16239 .map(|(ix, _)| ix)
16240 .fuse()
16241 .peekable();
16242
16243 for (quote_ix, _) in diagnostic
16244 .message
16245 .match_indices('`')
16246 .chain([(diagnostic.message.len(), "")])
16247 {
16248 let mut first_newline_ix = None;
16249 let mut last_newline_ix = None;
16250 while let Some(newline_ix) = newline_indices.peek() {
16251 if *newline_ix < quote_ix {
16252 if first_newline_ix.is_none() {
16253 first_newline_ix = Some(*newline_ix);
16254 }
16255 last_newline_ix = Some(*newline_ix);
16256
16257 if let Some(rows_left) = &mut max_message_rows {
16258 if *rows_left == 0 {
16259 break;
16260 } else {
16261 *rows_left -= 1;
16262 }
16263 }
16264 let _ = newline_indices.next();
16265 } else {
16266 break;
16267 }
16268 }
16269 let prev_len = text_without_backticks.len();
16270 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16271 text_without_backticks.push_str(new_text);
16272 if in_code_block {
16273 code_ranges.push(prev_len..text_without_backticks.len());
16274 }
16275 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16276 in_code_block = !in_code_block;
16277 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16278 text_without_backticks.push_str("...");
16279 break;
16280 }
16281 }
16282
16283 (text_without_backticks.into(), code_ranges)
16284}
16285
16286fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16287 match severity {
16288 DiagnosticSeverity::ERROR => colors.error,
16289 DiagnosticSeverity::WARNING => colors.warning,
16290 DiagnosticSeverity::INFORMATION => colors.info,
16291 DiagnosticSeverity::HINT => colors.info,
16292 _ => colors.ignored,
16293 }
16294}
16295
16296pub fn styled_runs_for_code_label<'a>(
16297 label: &'a CodeLabel,
16298 syntax_theme: &'a theme::SyntaxTheme,
16299) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16300 let fade_out = HighlightStyle {
16301 fade_out: Some(0.35),
16302 ..Default::default()
16303 };
16304
16305 let mut prev_end = label.filter_range.end;
16306 label
16307 .runs
16308 .iter()
16309 .enumerate()
16310 .flat_map(move |(ix, (range, highlight_id))| {
16311 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16312 style
16313 } else {
16314 return Default::default();
16315 };
16316 let mut muted_style = style;
16317 muted_style.highlight(fade_out);
16318
16319 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16320 if range.start >= label.filter_range.end {
16321 if range.start > prev_end {
16322 runs.push((prev_end..range.start, fade_out));
16323 }
16324 runs.push((range.clone(), muted_style));
16325 } else if range.end <= label.filter_range.end {
16326 runs.push((range.clone(), style));
16327 } else {
16328 runs.push((range.start..label.filter_range.end, style));
16329 runs.push((label.filter_range.end..range.end, muted_style));
16330 }
16331 prev_end = cmp::max(prev_end, range.end);
16332
16333 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16334 runs.push((prev_end..label.text.len(), fade_out));
16335 }
16336
16337 runs
16338 })
16339}
16340
16341pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16342 let mut prev_index = 0;
16343 let mut prev_codepoint: Option<char> = None;
16344 text.char_indices()
16345 .chain([(text.len(), '\0')])
16346 .filter_map(move |(index, codepoint)| {
16347 let prev_codepoint = prev_codepoint.replace(codepoint)?;
16348 let is_boundary = index == text.len()
16349 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16350 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16351 if is_boundary {
16352 let chunk = &text[prev_index..index];
16353 prev_index = index;
16354 Some(chunk)
16355 } else {
16356 None
16357 }
16358 })
16359}
16360
16361pub trait RangeToAnchorExt: Sized {
16362 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16363
16364 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16365 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16366 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16367 }
16368}
16369
16370impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16371 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16372 let start_offset = self.start.to_offset(snapshot);
16373 let end_offset = self.end.to_offset(snapshot);
16374 if start_offset == end_offset {
16375 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16376 } else {
16377 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16378 }
16379 }
16380}
16381
16382pub trait RowExt {
16383 fn as_f32(&self) -> f32;
16384
16385 fn next_row(&self) -> Self;
16386
16387 fn previous_row(&self) -> Self;
16388
16389 fn minus(&self, other: Self) -> u32;
16390}
16391
16392impl RowExt for DisplayRow {
16393 fn as_f32(&self) -> f32 {
16394 self.0 as f32
16395 }
16396
16397 fn next_row(&self) -> Self {
16398 Self(self.0 + 1)
16399 }
16400
16401 fn previous_row(&self) -> Self {
16402 Self(self.0.saturating_sub(1))
16403 }
16404
16405 fn minus(&self, other: Self) -> u32 {
16406 self.0 - other.0
16407 }
16408}
16409
16410impl RowExt for MultiBufferRow {
16411 fn as_f32(&self) -> f32 {
16412 self.0 as f32
16413 }
16414
16415 fn next_row(&self) -> Self {
16416 Self(self.0 + 1)
16417 }
16418
16419 fn previous_row(&self) -> Self {
16420 Self(self.0.saturating_sub(1))
16421 }
16422
16423 fn minus(&self, other: Self) -> u32 {
16424 self.0 - other.0
16425 }
16426}
16427
16428trait RowRangeExt {
16429 type Row;
16430
16431 fn len(&self) -> usize;
16432
16433 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16434}
16435
16436impl RowRangeExt for Range<MultiBufferRow> {
16437 type Row = MultiBufferRow;
16438
16439 fn len(&self) -> usize {
16440 (self.end.0 - self.start.0) as usize
16441 }
16442
16443 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16444 (self.start.0..self.end.0).map(MultiBufferRow)
16445 }
16446}
16447
16448impl RowRangeExt for Range<DisplayRow> {
16449 type Row = DisplayRow;
16450
16451 fn len(&self) -> usize {
16452 (self.end.0 - self.start.0) as usize
16453 }
16454
16455 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16456 (self.start.0..self.end.0).map(DisplayRow)
16457 }
16458}
16459
16460/// If select range has more than one line, we
16461/// just point the cursor to range.start.
16462fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16463 if range.start.row == range.end.row {
16464 range
16465 } else {
16466 range.start..range.start
16467 }
16468}
16469pub struct KillRing(ClipboardItem);
16470impl Global for KillRing {}
16471
16472const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16473
16474fn all_edits_insertions_or_deletions(
16475 edits: &Vec<(Range<Anchor>, String)>,
16476 snapshot: &MultiBufferSnapshot,
16477) -> bool {
16478 let mut all_insertions = true;
16479 let mut all_deletions = true;
16480
16481 for (range, new_text) in edits.iter() {
16482 let range_is_empty = range.to_offset(&snapshot).is_empty();
16483 let text_is_empty = new_text.is_empty();
16484
16485 if range_is_empty != text_is_empty {
16486 if range_is_empty {
16487 all_deletions = false;
16488 } else {
16489 all_insertions = false;
16490 }
16491 } else {
16492 return false;
16493 }
16494
16495 if !all_insertions && !all_deletions {
16496 return false;
16497 }
16498 }
16499 all_insertions || all_deletions
16500}