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, TextRun, TextStyle, TextStyleRefinement, UTF16Selection,
86 UnderlineStyle, 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, InlineCompletionPreviewMode, Language, OffsetRangeExt, Point, Selection,
101 SelectionGoal, TextObject, 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 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
128 ToOffsetUtf16,
129};
130use project::{
131 lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
132 project_settings::{GitGutterSetting, ProjectSettings},
133 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
134 LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
135};
136use rand::prelude::*;
137use rpc::{proto::*, ErrorExt};
138use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
139use selections_collection::{
140 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
141};
142use serde::{Deserialize, Serialize};
143use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
144use smallvec::SmallVec;
145use snippet::Snippet;
146use std::{
147 any::TypeId,
148 borrow::Cow,
149 cell::RefCell,
150 cmp::{self, Ordering, Reverse},
151 mem,
152 num::NonZeroU32,
153 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
154 path::{Path, PathBuf},
155 rc::Rc,
156 sync::Arc,
157 time::{Duration, Instant},
158};
159pub use sum_tree::Bias;
160use sum_tree::TreeMap;
161use text::{BufferId, OffsetUtf16, Rope};
162use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
163use ui::{
164 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
165 Tooltip,
166};
167use util::{defer, maybe, post_inc, RangeExt, ResultExt, TakeUntilExt, TryFutureExt};
168use workspace::item::{ItemHandle, PreviewTabsSettings};
169use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
170use workspace::{
171 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
172};
173use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
174
175use crate::hover_links::{find_url, find_url_from_range};
176use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
177
178pub const FILE_HEADER_HEIGHT: u32 = 2;
179pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
180pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
181pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
182const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
183const MAX_LINE_LEN: usize = 1024;
184const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
185const MAX_SELECTION_HISTORY_LEN: usize = 1024;
186pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
187#[doc(hidden)]
188pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
189
190pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
191pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
192
193pub fn render_parsed_markdown(
194 element_id: impl Into<ElementId>,
195 parsed: &language::ParsedMarkdown,
196 editor_style: &EditorStyle,
197 workspace: Option<WeakEntity<Workspace>>,
198 cx: &mut App,
199) -> InteractiveText {
200 let code_span_background_color = cx
201 .theme()
202 .colors()
203 .editor_document_highlight_read_background;
204
205 let highlights = gpui::combine_highlights(
206 parsed.highlights.iter().filter_map(|(range, highlight)| {
207 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
208 Some((range.clone(), highlight))
209 }),
210 parsed
211 .regions
212 .iter()
213 .zip(&parsed.region_ranges)
214 .filter_map(|(region, range)| {
215 if region.code {
216 Some((
217 range.clone(),
218 HighlightStyle {
219 background_color: Some(code_span_background_color),
220 ..Default::default()
221 },
222 ))
223 } else {
224 None
225 }
226 }),
227 );
228
229 let mut links = Vec::new();
230 let mut link_ranges = Vec::new();
231 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
232 if let Some(link) = region.link.clone() {
233 links.push(link);
234 link_ranges.push(range.clone());
235 }
236 }
237
238 InteractiveText::new(
239 element_id,
240 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
241 )
242 .on_click(
243 link_ranges,
244 move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
245 markdown::Link::Web { url } => cx.open_url(url),
246 markdown::Link::Path { path } => {
247 if let Some(workspace) = &workspace {
248 _ = workspace.update(cx, |workspace, cx| {
249 workspace
250 .open_abs_path(path.clone(), false, window, cx)
251 .detach();
252 });
253 }
254 }
255 },
256 )
257}
258
259#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
260pub enum InlayId {
261 InlineCompletion(usize),
262 Hint(usize),
263}
264
265impl InlayId {
266 fn id(&self) -> usize {
267 match self {
268 Self::InlineCompletion(id) => *id,
269 Self::Hint(id) => *id,
270 }
271 }
272}
273
274enum DocumentHighlightRead {}
275enum DocumentHighlightWrite {}
276enum InputComposition {}
277
278#[derive(Debug, Copy, Clone, PartialEq, Eq)]
279pub enum Navigated {
280 Yes,
281 No,
282}
283
284impl Navigated {
285 pub fn from_bool(yes: bool) -> Navigated {
286 if yes {
287 Navigated::Yes
288 } else {
289 Navigated::No
290 }
291 }
292}
293
294pub fn init_settings(cx: &mut App) {
295 EditorSettings::register(cx);
296}
297
298pub fn init(cx: &mut App) {
299 init_settings(cx);
300
301 workspace::register_project_item::<Editor>(cx);
302 workspace::FollowableViewRegistry::register::<Editor>(cx);
303 workspace::register_serializable_item::<Editor>(cx);
304
305 cx.observe_new(
306 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
307 workspace.register_action(Editor::new_file);
308 workspace.register_action(Editor::new_file_vertical);
309 workspace.register_action(Editor::new_file_horizontal);
310 workspace.register_action(Editor::cancel_language_server_work);
311 },
312 )
313 .detach();
314
315 cx.on_action(move |_: &workspace::NewFile, cx| {
316 let app_state = workspace::AppState::global(cx);
317 if let Some(app_state) = app_state.upgrade() {
318 workspace::open_new(
319 Default::default(),
320 app_state,
321 cx,
322 |workspace, window, cx| {
323 Editor::new_file(workspace, &Default::default(), window, cx)
324 },
325 )
326 .detach();
327 }
328 });
329 cx.on_action(move |_: &workspace::NewWindow, cx| {
330 let app_state = workspace::AppState::global(cx);
331 if let Some(app_state) = app_state.upgrade() {
332 workspace::open_new(
333 Default::default(),
334 app_state,
335 cx,
336 |workspace, window, cx| {
337 cx.activate(true);
338 Editor::new_file(workspace, &Default::default(), window, cx)
339 },
340 )
341 .detach();
342 }
343 });
344}
345
346pub struct SearchWithinRange;
347
348trait InvalidationRegion {
349 fn ranges(&self) -> &[Range<Anchor>];
350}
351
352#[derive(Clone, Debug, PartialEq)]
353pub enum SelectPhase {
354 Begin {
355 position: DisplayPoint,
356 add: bool,
357 click_count: usize,
358 },
359 BeginColumnar {
360 position: DisplayPoint,
361 reset: bool,
362 goal_column: u32,
363 },
364 Extend {
365 position: DisplayPoint,
366 click_count: usize,
367 },
368 Update {
369 position: DisplayPoint,
370 goal_column: u32,
371 scroll_delta: gpui::Point<f32>,
372 },
373 End,
374}
375
376#[derive(Clone, Debug)]
377pub enum SelectMode {
378 Character,
379 Word(Range<Anchor>),
380 Line(Range<Anchor>),
381 All,
382}
383
384#[derive(Copy, Clone, PartialEq, Eq, Debug)]
385pub enum EditorMode {
386 SingleLine { auto_width: bool },
387 AutoHeight { max_lines: usize },
388 Full,
389}
390
391#[derive(Copy, Clone, Debug)]
392pub enum SoftWrap {
393 /// Prefer not to wrap at all.
394 ///
395 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
396 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
397 GitDiff,
398 /// Prefer a single line generally, unless an overly long line is encountered.
399 None,
400 /// Soft wrap lines that exceed the editor width.
401 EditorWidth,
402 /// Soft wrap lines at the preferred line length.
403 Column(u32),
404 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
405 Bounded(u32),
406}
407
408#[derive(Clone)]
409pub struct EditorStyle {
410 pub background: Hsla,
411 pub local_player: PlayerColor,
412 pub text: TextStyle,
413 pub scrollbar_width: Pixels,
414 pub syntax: Arc<SyntaxTheme>,
415 pub status: StatusColors,
416 pub inlay_hints_style: HighlightStyle,
417 pub inline_completion_styles: InlineCompletionStyles,
418 pub unnecessary_code_fade: f32,
419}
420
421impl Default for EditorStyle {
422 fn default() -> Self {
423 Self {
424 background: Hsla::default(),
425 local_player: PlayerColor::default(),
426 text: TextStyle::default(),
427 scrollbar_width: Pixels::default(),
428 syntax: Default::default(),
429 // HACK: Status colors don't have a real default.
430 // We should look into removing the status colors from the editor
431 // style and retrieve them directly from the theme.
432 status: StatusColors::dark(),
433 inlay_hints_style: HighlightStyle::default(),
434 inline_completion_styles: InlineCompletionStyles {
435 insertion: HighlightStyle::default(),
436 whitespace: HighlightStyle::default(),
437 },
438 unnecessary_code_fade: Default::default(),
439 }
440 }
441}
442
443pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
444 let show_background = language_settings::language_settings(None, None, cx)
445 .inlay_hints
446 .show_background;
447
448 HighlightStyle {
449 color: Some(cx.theme().status().hint),
450 background_color: show_background.then(|| cx.theme().status().hint_background),
451 ..HighlightStyle::default()
452 }
453}
454
455pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
456 InlineCompletionStyles {
457 insertion: HighlightStyle {
458 color: Some(cx.theme().status().predictive),
459 ..HighlightStyle::default()
460 },
461 whitespace: HighlightStyle {
462 background_color: Some(cx.theme().status().created_background),
463 ..HighlightStyle::default()
464 },
465 }
466}
467
468type CompletionId = usize;
469
470pub(crate) enum EditDisplayMode {
471 TabAccept,
472 DiffPopover,
473 Inline,
474}
475
476enum InlineCompletion {
477 Edit {
478 edits: Vec<(Range<Anchor>, String)>,
479 edit_preview: Option<EditPreview>,
480 display_mode: EditDisplayMode,
481 snapshot: BufferSnapshot,
482 },
483 Move {
484 target: Anchor,
485 range_around_target: Range<text::Anchor>,
486 snapshot: BufferSnapshot,
487 },
488}
489
490struct InlineCompletionState {
491 inlay_ids: Vec<InlayId>,
492 completion: InlineCompletion,
493 invalidation_range: Range<Anchor>,
494}
495
496enum InlineCompletionHighlight {}
497
498pub enum MenuInlineCompletionsPolicy {
499 Never,
500 ByProvider,
501}
502
503#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
504struct EditorActionId(usize);
505
506impl EditorActionId {
507 pub fn post_inc(&mut self) -> Self {
508 let answer = self.0;
509
510 *self = Self(answer + 1);
511
512 Self(answer)
513 }
514}
515
516// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
517// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
518
519type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
520type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
521
522#[derive(Default)]
523struct ScrollbarMarkerState {
524 scrollbar_size: Size<Pixels>,
525 dirty: bool,
526 markers: Arc<[PaintQuad]>,
527 pending_refresh: Option<Task<Result<()>>>,
528}
529
530impl ScrollbarMarkerState {
531 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
532 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
533 }
534}
535
536#[derive(Clone, Debug)]
537struct RunnableTasks {
538 templates: Vec<(TaskSourceKind, TaskTemplate)>,
539 offset: MultiBufferOffset,
540 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
541 column: u32,
542 // Values of all named captures, including those starting with '_'
543 extra_variables: HashMap<String, String>,
544 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
545 context_range: Range<BufferOffset>,
546}
547
548impl RunnableTasks {
549 fn resolve<'a>(
550 &'a self,
551 cx: &'a task::TaskContext,
552 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
553 self.templates.iter().filter_map(|(kind, template)| {
554 template
555 .resolve_task(&kind.to_id_base(), cx)
556 .map(|task| (kind.clone(), task))
557 })
558 }
559}
560
561#[derive(Clone)]
562struct ResolvedTasks {
563 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
564 position: Anchor,
565}
566#[derive(Copy, Clone, Debug)]
567struct MultiBufferOffset(usize);
568#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
569struct BufferOffset(usize);
570
571// Addons allow storing per-editor state in other crates (e.g. Vim)
572pub trait Addon: 'static {
573 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
574
575 fn render_buffer_header_controls(
576 &self,
577 _: &ExcerptInfo,
578 _: &Window,
579 _: &App,
580 ) -> Option<AnyElement> {
581 None
582 }
583
584 fn to_any(&self) -> &dyn std::any::Any;
585}
586
587#[derive(Debug, Copy, Clone, PartialEq, Eq)]
588pub enum IsVimMode {
589 Yes,
590 No,
591}
592
593/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
594///
595/// See the [module level documentation](self) for more information.
596pub struct Editor {
597 focus_handle: FocusHandle,
598 last_focused_descendant: Option<WeakFocusHandle>,
599 /// The text buffer being edited
600 buffer: Entity<MultiBuffer>,
601 /// Map of how text in the buffer should be displayed.
602 /// Handles soft wraps, folds, fake inlay text insertions, etc.
603 pub display_map: Entity<DisplayMap>,
604 pub selections: SelectionsCollection,
605 pub scroll_manager: ScrollManager,
606 /// When inline assist editors are linked, they all render cursors because
607 /// typing enters text into each of them, even the ones that aren't focused.
608 pub(crate) show_cursor_when_unfocused: bool,
609 columnar_selection_tail: Option<Anchor>,
610 add_selections_state: Option<AddSelectionsState>,
611 select_next_state: Option<SelectNextState>,
612 select_prev_state: Option<SelectNextState>,
613 selection_history: SelectionHistory,
614 autoclose_regions: Vec<AutocloseRegion>,
615 snippet_stack: InvalidationStack<SnippetState>,
616 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
617 ime_transaction: Option<TransactionId>,
618 active_diagnostics: Option<ActiveDiagnosticGroup>,
619 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
620
621 // TODO: make this a access method
622 pub project: Option<Entity<Project>>,
623 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
624 completion_provider: Option<Box<dyn CompletionProvider>>,
625 collaboration_hub: Option<Box<dyn CollaborationHub>>,
626 blink_manager: Entity<BlinkManager>,
627 show_cursor_names: bool,
628 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
629 pub show_local_selections: bool,
630 mode: EditorMode,
631 show_breadcrumbs: bool,
632 show_gutter: bool,
633 show_scrollbars: bool,
634 show_line_numbers: Option<bool>,
635 use_relative_line_numbers: Option<bool>,
636 show_git_diff_gutter: Option<bool>,
637 show_code_actions: Option<bool>,
638 show_runnables: Option<bool>,
639 show_wrap_guides: Option<bool>,
640 show_indent_guides: Option<bool>,
641 placeholder_text: Option<Arc<str>>,
642 highlight_order: usize,
643 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
644 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
645 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
646 scrollbar_marker_state: ScrollbarMarkerState,
647 active_indent_guides_state: ActiveIndentGuidesState,
648 nav_history: Option<ItemNavHistory>,
649 context_menu: RefCell<Option<CodeContextMenu>>,
650 mouse_context_menu: Option<MouseContextMenu>,
651 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
652 signature_help_state: SignatureHelpState,
653 auto_signature_help: Option<bool>,
654 find_all_references_task_sources: Vec<Anchor>,
655 next_completion_id: CompletionId,
656 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
657 code_actions_task: Option<Task<Result<()>>>,
658 document_highlights_task: Option<Task<()>>,
659 linked_editing_range_task: Option<Task<Option<()>>>,
660 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
661 pending_rename: Option<RenameState>,
662 searchable: bool,
663 cursor_shape: CursorShape,
664 current_line_highlight: Option<CurrentLineHighlight>,
665 collapse_matches: bool,
666 autoindent_mode: Option<AutoindentMode>,
667 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
668 input_enabled: bool,
669 use_modal_editing: bool,
670 read_only: bool,
671 leader_peer_id: Option<PeerId>,
672 remote_id: Option<ViewId>,
673 hover_state: HoverState,
674 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
675 gutter_hovered: bool,
676 hovered_link_state: Option<HoveredLinkState>,
677 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
678 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
679 active_inline_completion: Option<InlineCompletionState>,
680 /// Used to prevent flickering as the user types while the menu is open
681 stale_inline_completion_in_menu: Option<InlineCompletionState>,
682 // enable_inline_completions is a switch that Vim can use to disable
683 // edit predictions based on its mode.
684 show_inline_completions: bool,
685 show_inline_completions_override: Option<bool>,
686 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
687 previewing_inline_completion: bool,
688 inlay_hint_cache: InlayHintCache,
689 next_inlay_id: usize,
690 _subscriptions: Vec<Subscription>,
691 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
692 gutter_dimensions: GutterDimensions,
693 style: Option<EditorStyle>,
694 text_style_refinement: Option<TextStyleRefinement>,
695 next_editor_action_id: EditorActionId,
696 editor_actions:
697 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
698 use_autoclose: bool,
699 use_auto_surround: bool,
700 auto_replace_emoji_shortcode: bool,
701 show_git_blame_gutter: bool,
702 show_git_blame_inline: bool,
703 show_git_blame_inline_delay_task: Option<Task<()>>,
704 git_blame_inline_enabled: bool,
705 serialize_dirty_buffers: bool,
706 show_selection_menu: Option<bool>,
707 blame: Option<Entity<GitBlame>>,
708 blame_subscription: Option<Subscription>,
709 custom_context_menu: Option<
710 Box<
711 dyn 'static
712 + Fn(
713 &mut Self,
714 DisplayPoint,
715 &mut Window,
716 &mut Context<Self>,
717 ) -> Option<Entity<ui::ContextMenu>>,
718 >,
719 >,
720 last_bounds: Option<Bounds<Pixels>>,
721 last_position_map: Option<Rc<PositionMap>>,
722 expect_bounds_change: Option<Bounds<Pixels>>,
723 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
724 tasks_update_task: Option<Task<()>>,
725 in_project_search: bool,
726 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
727 breadcrumb_header: Option<String>,
728 focused_block: Option<FocusedBlock>,
729 next_scroll_position: NextScrollCursorCenterTopBottom,
730 addons: HashMap<TypeId, Box<dyn Addon>>,
731 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
732 selection_mark_mode: bool,
733 toggle_fold_multiple_buffers: Task<()>,
734 _scroll_cursor_center_top_bottom_task: Task<()>,
735}
736
737#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
738enum NextScrollCursorCenterTopBottom {
739 #[default]
740 Center,
741 Top,
742 Bottom,
743}
744
745impl NextScrollCursorCenterTopBottom {
746 fn next(&self) -> Self {
747 match self {
748 Self::Center => Self::Top,
749 Self::Top => Self::Bottom,
750 Self::Bottom => Self::Center,
751 }
752 }
753}
754
755#[derive(Clone)]
756pub struct EditorSnapshot {
757 pub mode: EditorMode,
758 show_gutter: bool,
759 show_line_numbers: Option<bool>,
760 show_git_diff_gutter: Option<bool>,
761 show_code_actions: Option<bool>,
762 show_runnables: Option<bool>,
763 git_blame_gutter_max_author_length: Option<usize>,
764 pub display_snapshot: DisplaySnapshot,
765 pub placeholder_text: Option<Arc<str>>,
766 is_focused: bool,
767 scroll_anchor: ScrollAnchor,
768 ongoing_scroll: OngoingScroll,
769 current_line_highlight: CurrentLineHighlight,
770 gutter_hovered: bool,
771}
772
773const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
774
775#[derive(Default, Debug, Clone, Copy)]
776pub struct GutterDimensions {
777 pub left_padding: Pixels,
778 pub right_padding: Pixels,
779 pub width: Pixels,
780 pub margin: Pixels,
781 pub git_blame_entries_width: Option<Pixels>,
782}
783
784impl GutterDimensions {
785 /// The full width of the space taken up by the gutter.
786 pub fn full_width(&self) -> Pixels {
787 self.margin + self.width
788 }
789
790 /// The width of the space reserved for the fold indicators,
791 /// use alongside 'justify_end' and `gutter_width` to
792 /// right align content with the line numbers
793 pub fn fold_area_width(&self) -> Pixels {
794 self.margin + self.right_padding
795 }
796}
797
798#[derive(Debug)]
799pub struct RemoteSelection {
800 pub replica_id: ReplicaId,
801 pub selection: Selection<Anchor>,
802 pub cursor_shape: CursorShape,
803 pub peer_id: PeerId,
804 pub line_mode: bool,
805 pub participant_index: Option<ParticipantIndex>,
806 pub user_name: Option<SharedString>,
807}
808
809#[derive(Clone, Debug)]
810struct SelectionHistoryEntry {
811 selections: Arc<[Selection<Anchor>]>,
812 select_next_state: Option<SelectNextState>,
813 select_prev_state: Option<SelectNextState>,
814 add_selections_state: Option<AddSelectionsState>,
815}
816
817enum SelectionHistoryMode {
818 Normal,
819 Undoing,
820 Redoing,
821}
822
823#[derive(Clone, PartialEq, Eq, Hash)]
824struct HoveredCursor {
825 replica_id: u16,
826 selection_id: usize,
827}
828
829impl Default for SelectionHistoryMode {
830 fn default() -> Self {
831 Self::Normal
832 }
833}
834
835#[derive(Default)]
836struct SelectionHistory {
837 #[allow(clippy::type_complexity)]
838 selections_by_transaction:
839 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
840 mode: SelectionHistoryMode,
841 undo_stack: VecDeque<SelectionHistoryEntry>,
842 redo_stack: VecDeque<SelectionHistoryEntry>,
843}
844
845impl SelectionHistory {
846 fn insert_transaction(
847 &mut self,
848 transaction_id: TransactionId,
849 selections: Arc<[Selection<Anchor>]>,
850 ) {
851 self.selections_by_transaction
852 .insert(transaction_id, (selections, None));
853 }
854
855 #[allow(clippy::type_complexity)]
856 fn transaction(
857 &self,
858 transaction_id: TransactionId,
859 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
860 self.selections_by_transaction.get(&transaction_id)
861 }
862
863 #[allow(clippy::type_complexity)]
864 fn transaction_mut(
865 &mut self,
866 transaction_id: TransactionId,
867 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
868 self.selections_by_transaction.get_mut(&transaction_id)
869 }
870
871 fn push(&mut self, entry: SelectionHistoryEntry) {
872 if !entry.selections.is_empty() {
873 match self.mode {
874 SelectionHistoryMode::Normal => {
875 self.push_undo(entry);
876 self.redo_stack.clear();
877 }
878 SelectionHistoryMode::Undoing => self.push_redo(entry),
879 SelectionHistoryMode::Redoing => self.push_undo(entry),
880 }
881 }
882 }
883
884 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
885 if self
886 .undo_stack
887 .back()
888 .map_or(true, |e| e.selections != entry.selections)
889 {
890 self.undo_stack.push_back(entry);
891 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
892 self.undo_stack.pop_front();
893 }
894 }
895 }
896
897 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
898 if self
899 .redo_stack
900 .back()
901 .map_or(true, |e| e.selections != entry.selections)
902 {
903 self.redo_stack.push_back(entry);
904 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
905 self.redo_stack.pop_front();
906 }
907 }
908 }
909}
910
911struct RowHighlight {
912 index: usize,
913 range: Range<Anchor>,
914 color: Hsla,
915 should_autoscroll: bool,
916}
917
918#[derive(Clone, Debug)]
919struct AddSelectionsState {
920 above: bool,
921 stack: Vec<usize>,
922}
923
924#[derive(Clone)]
925struct SelectNextState {
926 query: AhoCorasick,
927 wordwise: bool,
928 done: bool,
929}
930
931impl std::fmt::Debug for SelectNextState {
932 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
933 f.debug_struct(std::any::type_name::<Self>())
934 .field("wordwise", &self.wordwise)
935 .field("done", &self.done)
936 .finish()
937 }
938}
939
940#[derive(Debug)]
941struct AutocloseRegion {
942 selection_id: usize,
943 range: Range<Anchor>,
944 pair: BracketPair,
945}
946
947#[derive(Debug)]
948struct SnippetState {
949 ranges: Vec<Vec<Range<Anchor>>>,
950 active_index: usize,
951 choices: Vec<Option<Vec<String>>>,
952}
953
954#[doc(hidden)]
955pub struct RenameState {
956 pub range: Range<Anchor>,
957 pub old_name: Arc<str>,
958 pub editor: Entity<Editor>,
959 block_id: CustomBlockId,
960}
961
962struct InvalidationStack<T>(Vec<T>);
963
964struct RegisteredInlineCompletionProvider {
965 provider: Arc<dyn InlineCompletionProviderHandle>,
966 _subscription: Subscription,
967}
968
969#[derive(Debug)]
970struct ActiveDiagnosticGroup {
971 primary_range: Range<Anchor>,
972 primary_message: String,
973 group_id: usize,
974 blocks: HashMap<CustomBlockId, Diagnostic>,
975 is_valid: bool,
976}
977
978#[derive(Serialize, Deserialize, Clone, Debug)]
979pub struct ClipboardSelection {
980 pub len: usize,
981 pub is_entire_line: bool,
982 pub first_line_indent: u32,
983}
984
985#[derive(Debug)]
986pub(crate) struct NavigationData {
987 cursor_anchor: Anchor,
988 cursor_position: Point,
989 scroll_anchor: ScrollAnchor,
990 scroll_top_row: u32,
991}
992
993#[derive(Debug, Clone, Copy, PartialEq, Eq)]
994pub enum GotoDefinitionKind {
995 Symbol,
996 Declaration,
997 Type,
998 Implementation,
999}
1000
1001#[derive(Debug, Clone)]
1002enum InlayHintRefreshReason {
1003 Toggle(bool),
1004 SettingsChange(InlayHintSettings),
1005 NewLinesShown,
1006 BufferEdited(HashSet<Arc<Language>>),
1007 RefreshRequested,
1008 ExcerptsRemoved(Vec<ExcerptId>),
1009}
1010
1011impl InlayHintRefreshReason {
1012 fn description(&self) -> &'static str {
1013 match self {
1014 Self::Toggle(_) => "toggle",
1015 Self::SettingsChange(_) => "settings change",
1016 Self::NewLinesShown => "new lines shown",
1017 Self::BufferEdited(_) => "buffer edited",
1018 Self::RefreshRequested => "refresh requested",
1019 Self::ExcerptsRemoved(_) => "excerpts removed",
1020 }
1021 }
1022}
1023
1024pub enum FormatTarget {
1025 Buffers,
1026 Ranges(Vec<Range<MultiBufferPoint>>),
1027}
1028
1029pub(crate) struct FocusedBlock {
1030 id: BlockId,
1031 focus_handle: WeakFocusHandle,
1032}
1033
1034#[derive(Clone)]
1035enum JumpData {
1036 MultiBufferRow {
1037 row: MultiBufferRow,
1038 line_offset_from_top: u32,
1039 },
1040 MultiBufferPoint {
1041 excerpt_id: ExcerptId,
1042 position: Point,
1043 anchor: text::Anchor,
1044 line_offset_from_top: u32,
1045 },
1046}
1047
1048pub enum MultibufferSelectionMode {
1049 First,
1050 All,
1051}
1052
1053impl Editor {
1054 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1055 let buffer = cx.new(|cx| Buffer::local("", cx));
1056 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1057 Self::new(
1058 EditorMode::SingleLine { auto_width: false },
1059 buffer,
1060 None,
1061 false,
1062 window,
1063 cx,
1064 )
1065 }
1066
1067 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1068 let buffer = cx.new(|cx| Buffer::local("", cx));
1069 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1070 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1071 }
1072
1073 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1074 let buffer = cx.new(|cx| Buffer::local("", cx));
1075 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1076 Self::new(
1077 EditorMode::SingleLine { auto_width: true },
1078 buffer,
1079 None,
1080 false,
1081 window,
1082 cx,
1083 )
1084 }
1085
1086 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1087 let buffer = cx.new(|cx| Buffer::local("", cx));
1088 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1089 Self::new(
1090 EditorMode::AutoHeight { max_lines },
1091 buffer,
1092 None,
1093 false,
1094 window,
1095 cx,
1096 )
1097 }
1098
1099 pub fn for_buffer(
1100 buffer: Entity<Buffer>,
1101 project: Option<Entity<Project>>,
1102 window: &mut Window,
1103 cx: &mut Context<Self>,
1104 ) -> Self {
1105 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1106 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1107 }
1108
1109 pub fn for_multibuffer(
1110 buffer: Entity<MultiBuffer>,
1111 project: Option<Entity<Project>>,
1112 show_excerpt_controls: bool,
1113 window: &mut Window,
1114 cx: &mut Context<Self>,
1115 ) -> Self {
1116 Self::new(
1117 EditorMode::Full,
1118 buffer,
1119 project,
1120 show_excerpt_controls,
1121 window,
1122 cx,
1123 )
1124 }
1125
1126 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1127 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1128 let mut clone = Self::new(
1129 self.mode,
1130 self.buffer.clone(),
1131 self.project.clone(),
1132 show_excerpt_controls,
1133 window,
1134 cx,
1135 );
1136 self.display_map.update(cx, |display_map, cx| {
1137 let snapshot = display_map.snapshot(cx);
1138 clone.display_map.update(cx, |display_map, cx| {
1139 display_map.set_state(&snapshot, cx);
1140 });
1141 });
1142 clone.selections.clone_state(&self.selections);
1143 clone.scroll_manager.clone_state(&self.scroll_manager);
1144 clone.searchable = self.searchable;
1145 clone
1146 }
1147
1148 pub fn new(
1149 mode: EditorMode,
1150 buffer: Entity<MultiBuffer>,
1151 project: Option<Entity<Project>>,
1152 show_excerpt_controls: bool,
1153 window: &mut Window,
1154 cx: &mut Context<Self>,
1155 ) -> Self {
1156 let style = window.text_style();
1157 let font_size = style.font_size.to_pixels(window.rem_size());
1158 let editor = cx.entity().downgrade();
1159 let fold_placeholder = FoldPlaceholder {
1160 constrain_width: true,
1161 render: Arc::new(move |fold_id, fold_range, _, cx| {
1162 let editor = editor.clone();
1163 div()
1164 .id(fold_id)
1165 .bg(cx.theme().colors().ghost_element_background)
1166 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1167 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1168 .rounded_sm()
1169 .size_full()
1170 .cursor_pointer()
1171 .child("⋯")
1172 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1173 .on_click(move |_, _window, cx| {
1174 editor
1175 .update(cx, |editor, cx| {
1176 editor.unfold_ranges(
1177 &[fold_range.start..fold_range.end],
1178 true,
1179 false,
1180 cx,
1181 );
1182 cx.stop_propagation();
1183 })
1184 .ok();
1185 })
1186 .into_any()
1187 }),
1188 merge_adjacent: true,
1189 ..Default::default()
1190 };
1191 let display_map = cx.new(|cx| {
1192 DisplayMap::new(
1193 buffer.clone(),
1194 style.font(),
1195 font_size,
1196 None,
1197 show_excerpt_controls,
1198 FILE_HEADER_HEIGHT,
1199 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1200 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1201 fold_placeholder,
1202 cx,
1203 )
1204 });
1205
1206 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1207
1208 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1209
1210 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1211 .then(|| language_settings::SoftWrap::None);
1212
1213 let mut project_subscriptions = Vec::new();
1214 if mode == EditorMode::Full {
1215 if let Some(project) = project.as_ref() {
1216 if buffer.read(cx).is_singleton() {
1217 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1218 cx.emit(EditorEvent::TitleChanged);
1219 }));
1220 }
1221 project_subscriptions.push(cx.subscribe_in(
1222 project,
1223 window,
1224 |editor, _, event, window, cx| {
1225 if let project::Event::RefreshInlayHints = event {
1226 editor
1227 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1228 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1229 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1230 let focus_handle = editor.focus_handle(cx);
1231 if focus_handle.is_focused(window) {
1232 let snapshot = buffer.read(cx).snapshot();
1233 for (range, snippet) in snippet_edits {
1234 let editor_range =
1235 language::range_from_lsp(*range).to_offset(&snapshot);
1236 editor
1237 .insert_snippet(
1238 &[editor_range],
1239 snippet.clone(),
1240 window,
1241 cx,
1242 )
1243 .ok();
1244 }
1245 }
1246 }
1247 }
1248 },
1249 ));
1250 if let Some(task_inventory) = project
1251 .read(cx)
1252 .task_store()
1253 .read(cx)
1254 .task_inventory()
1255 .cloned()
1256 {
1257 project_subscriptions.push(cx.observe_in(
1258 &task_inventory,
1259 window,
1260 |editor, _, window, cx| {
1261 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1262 },
1263 ));
1264 }
1265 }
1266 }
1267
1268 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1269
1270 let inlay_hint_settings =
1271 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1272 let focus_handle = cx.focus_handle();
1273 cx.on_focus(&focus_handle, window, Self::handle_focus)
1274 .detach();
1275 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1276 .detach();
1277 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1278 .detach();
1279 cx.on_blur(&focus_handle, window, Self::handle_blur)
1280 .detach();
1281
1282 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1283 Some(false)
1284 } else {
1285 None
1286 };
1287
1288 let mut code_action_providers = Vec::new();
1289 if let Some(project) = project.clone() {
1290 get_uncommitted_changes_for_buffer(
1291 &project,
1292 buffer.read(cx).all_buffers(),
1293 buffer.clone(),
1294 cx,
1295 );
1296 code_action_providers.push(Rc::new(project) as Rc<_>);
1297 }
1298
1299 let mut this = Self {
1300 focus_handle,
1301 show_cursor_when_unfocused: false,
1302 last_focused_descendant: None,
1303 buffer: buffer.clone(),
1304 display_map: display_map.clone(),
1305 selections,
1306 scroll_manager: ScrollManager::new(cx),
1307 columnar_selection_tail: None,
1308 add_selections_state: None,
1309 select_next_state: None,
1310 select_prev_state: None,
1311 selection_history: Default::default(),
1312 autoclose_regions: Default::default(),
1313 snippet_stack: Default::default(),
1314 select_larger_syntax_node_stack: Vec::new(),
1315 ime_transaction: Default::default(),
1316 active_diagnostics: None,
1317 soft_wrap_mode_override,
1318 completion_provider: project.clone().map(|project| Box::new(project) as _),
1319 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1320 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1321 project,
1322 blink_manager: blink_manager.clone(),
1323 show_local_selections: true,
1324 show_scrollbars: true,
1325 mode,
1326 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1327 show_gutter: mode == EditorMode::Full,
1328 show_line_numbers: None,
1329 use_relative_line_numbers: None,
1330 show_git_diff_gutter: None,
1331 show_code_actions: None,
1332 show_runnables: None,
1333 show_wrap_guides: None,
1334 show_indent_guides,
1335 placeholder_text: None,
1336 highlight_order: 0,
1337 highlighted_rows: HashMap::default(),
1338 background_highlights: Default::default(),
1339 gutter_highlights: TreeMap::default(),
1340 scrollbar_marker_state: ScrollbarMarkerState::default(),
1341 active_indent_guides_state: ActiveIndentGuidesState::default(),
1342 nav_history: None,
1343 context_menu: RefCell::new(None),
1344 mouse_context_menu: None,
1345 completion_tasks: Default::default(),
1346 signature_help_state: SignatureHelpState::default(),
1347 auto_signature_help: None,
1348 find_all_references_task_sources: Vec::new(),
1349 next_completion_id: 0,
1350 next_inlay_id: 0,
1351 code_action_providers,
1352 available_code_actions: Default::default(),
1353 code_actions_task: Default::default(),
1354 document_highlights_task: Default::default(),
1355 linked_editing_range_task: Default::default(),
1356 pending_rename: Default::default(),
1357 searchable: true,
1358 cursor_shape: EditorSettings::get_global(cx)
1359 .cursor_shape
1360 .unwrap_or_default(),
1361 current_line_highlight: None,
1362 autoindent_mode: Some(AutoindentMode::EachLine),
1363 collapse_matches: false,
1364 workspace: None,
1365 input_enabled: true,
1366 use_modal_editing: mode == EditorMode::Full,
1367 read_only: false,
1368 use_autoclose: true,
1369 use_auto_surround: true,
1370 auto_replace_emoji_shortcode: false,
1371 leader_peer_id: None,
1372 remote_id: None,
1373 hover_state: Default::default(),
1374 pending_mouse_down: None,
1375 hovered_link_state: Default::default(),
1376 inline_completion_provider: None,
1377 active_inline_completion: None,
1378 stale_inline_completion_in_menu: None,
1379 previewing_inline_completion: false,
1380 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1381
1382 gutter_hovered: false,
1383 pixel_position_of_newest_cursor: None,
1384 last_bounds: None,
1385 last_position_map: None,
1386 expect_bounds_change: None,
1387 gutter_dimensions: GutterDimensions::default(),
1388 style: None,
1389 show_cursor_names: false,
1390 hovered_cursors: Default::default(),
1391 next_editor_action_id: EditorActionId::default(),
1392 editor_actions: Rc::default(),
1393 show_inline_completions_override: None,
1394 show_inline_completions: true,
1395 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1396 custom_context_menu: None,
1397 show_git_blame_gutter: false,
1398 show_git_blame_inline: false,
1399 show_selection_menu: None,
1400 show_git_blame_inline_delay_task: None,
1401 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1402 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1403 .session
1404 .restore_unsaved_buffers,
1405 blame: None,
1406 blame_subscription: None,
1407 tasks: Default::default(),
1408 _subscriptions: vec![
1409 cx.observe(&buffer, Self::on_buffer_changed),
1410 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1411 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1412 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1413 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1414 cx.observe_window_activation(window, |editor, window, cx| {
1415 let active = window.is_window_active();
1416 editor.blink_manager.update(cx, |blink_manager, cx| {
1417 if active {
1418 blink_manager.enable(cx);
1419 } else {
1420 blink_manager.disable(cx);
1421 }
1422 });
1423 }),
1424 ],
1425 tasks_update_task: None,
1426 linked_edit_ranges: Default::default(),
1427 in_project_search: false,
1428 previous_search_ranges: None,
1429 breadcrumb_header: None,
1430 focused_block: None,
1431 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1432 addons: HashMap::default(),
1433 registered_buffers: HashMap::default(),
1434 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1435 selection_mark_mode: false,
1436 toggle_fold_multiple_buffers: Task::ready(()),
1437 text_style_refinement: None,
1438 };
1439 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1440 this._subscriptions.extend(project_subscriptions);
1441
1442 this.end_selection(window, cx);
1443 this.scroll_manager.show_scrollbar(window, cx);
1444
1445 if mode == EditorMode::Full {
1446 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1447 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1448
1449 if this.git_blame_inline_enabled {
1450 this.git_blame_inline_enabled = true;
1451 this.start_git_blame_inline(false, window, cx);
1452 }
1453
1454 if let Some(buffer) = buffer.read(cx).as_singleton() {
1455 if let Some(project) = this.project.as_ref() {
1456 let lsp_store = project.read(cx).lsp_store();
1457 let handle = lsp_store.update(cx, |lsp_store, cx| {
1458 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1459 });
1460 this.registered_buffers
1461 .insert(buffer.read(cx).remote_id(), handle);
1462 }
1463 }
1464 }
1465
1466 this.report_editor_event("Editor Opened", None, cx);
1467 this
1468 }
1469
1470 pub fn mouse_menu_is_focused(&self, window: &mut Window, cx: &mut App) -> bool {
1471 self.mouse_context_menu
1472 .as_ref()
1473 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1474 }
1475
1476 fn key_context(&self, window: &mut Window, cx: &mut Context<Self>) -> KeyContext {
1477 let mut key_context = KeyContext::new_with_defaults();
1478 key_context.add("Editor");
1479 let mode = match self.mode {
1480 EditorMode::SingleLine { .. } => "single_line",
1481 EditorMode::AutoHeight { .. } => "auto_height",
1482 EditorMode::Full => "full",
1483 };
1484
1485 if EditorSettings::jupyter_enabled(cx) {
1486 key_context.add("jupyter");
1487 }
1488
1489 key_context.set("mode", mode);
1490 if self.pending_rename.is_some() {
1491 key_context.add("renaming");
1492 }
1493
1494 let mut showing_completions = false;
1495
1496 match self.context_menu.borrow().as_ref() {
1497 Some(CodeContextMenu::Completions(_)) => {
1498 key_context.add("menu");
1499 key_context.add("showing_completions");
1500 showing_completions = true;
1501 }
1502 Some(CodeContextMenu::CodeActions(_)) => {
1503 key_context.add("menu");
1504 key_context.add("showing_code_actions")
1505 }
1506 None => {}
1507 }
1508
1509 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1510 if !self.focus_handle(cx).contains_focused(window, cx)
1511 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1512 {
1513 for addon in self.addons.values() {
1514 addon.extend_key_context(&mut key_context, cx)
1515 }
1516 }
1517
1518 if let Some(extension) = self
1519 .buffer
1520 .read(cx)
1521 .as_singleton()
1522 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1523 {
1524 key_context.set("extension", extension.to_string());
1525 }
1526
1527 if self.has_active_inline_completion() {
1528 key_context.add("copilot_suggestion");
1529 key_context.add("inline_completion");
1530
1531 if showing_completions || self.inline_completion_requires_modifier(cx) {
1532 key_context.add("inline_completion_requires_modifier");
1533 }
1534 }
1535
1536 if self.selection_mark_mode {
1537 key_context.add("selection_mode");
1538 }
1539
1540 key_context
1541 }
1542
1543 pub fn new_file(
1544 workspace: &mut Workspace,
1545 _: &workspace::NewFile,
1546 window: &mut Window,
1547 cx: &mut Context<Workspace>,
1548 ) {
1549 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1550 "Failed to create buffer",
1551 window,
1552 cx,
1553 |e, _, _| match e.error_code() {
1554 ErrorCode::RemoteUpgradeRequired => Some(format!(
1555 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1556 e.error_tag("required").unwrap_or("the latest version")
1557 )),
1558 _ => None,
1559 },
1560 );
1561 }
1562
1563 pub fn new_in_workspace(
1564 workspace: &mut Workspace,
1565 window: &mut Window,
1566 cx: &mut Context<Workspace>,
1567 ) -> Task<Result<Entity<Editor>>> {
1568 let project = workspace.project().clone();
1569 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1570
1571 cx.spawn_in(window, |workspace, mut cx| async move {
1572 let buffer = create.await?;
1573 workspace.update_in(&mut cx, |workspace, window, cx| {
1574 let editor =
1575 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1576 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1577 editor
1578 })
1579 })
1580 }
1581
1582 fn new_file_vertical(
1583 workspace: &mut Workspace,
1584 _: &workspace::NewFileSplitVertical,
1585 window: &mut Window,
1586 cx: &mut Context<Workspace>,
1587 ) {
1588 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1589 }
1590
1591 fn new_file_horizontal(
1592 workspace: &mut Workspace,
1593 _: &workspace::NewFileSplitHorizontal,
1594 window: &mut Window,
1595 cx: &mut Context<Workspace>,
1596 ) {
1597 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1598 }
1599
1600 fn new_file_in_direction(
1601 workspace: &mut Workspace,
1602 direction: SplitDirection,
1603 window: &mut Window,
1604 cx: &mut Context<Workspace>,
1605 ) {
1606 let project = workspace.project().clone();
1607 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1608
1609 cx.spawn_in(window, |workspace, mut cx| async move {
1610 let buffer = create.await?;
1611 workspace.update_in(&mut cx, move |workspace, window, cx| {
1612 workspace.split_item(
1613 direction,
1614 Box::new(
1615 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1616 ),
1617 window,
1618 cx,
1619 )
1620 })?;
1621 anyhow::Ok(())
1622 })
1623 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1624 match e.error_code() {
1625 ErrorCode::RemoteUpgradeRequired => Some(format!(
1626 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1627 e.error_tag("required").unwrap_or("the latest version")
1628 )),
1629 _ => None,
1630 }
1631 });
1632 }
1633
1634 pub fn leader_peer_id(&self) -> Option<PeerId> {
1635 self.leader_peer_id
1636 }
1637
1638 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1639 &self.buffer
1640 }
1641
1642 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1643 self.workspace.as_ref()?.0.upgrade()
1644 }
1645
1646 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1647 self.buffer().read(cx).title(cx)
1648 }
1649
1650 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1651 let git_blame_gutter_max_author_length = self
1652 .render_git_blame_gutter(cx)
1653 .then(|| {
1654 if let Some(blame) = self.blame.as_ref() {
1655 let max_author_length =
1656 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1657 Some(max_author_length)
1658 } else {
1659 None
1660 }
1661 })
1662 .flatten();
1663
1664 EditorSnapshot {
1665 mode: self.mode,
1666 show_gutter: self.show_gutter,
1667 show_line_numbers: self.show_line_numbers,
1668 show_git_diff_gutter: self.show_git_diff_gutter,
1669 show_code_actions: self.show_code_actions,
1670 show_runnables: self.show_runnables,
1671 git_blame_gutter_max_author_length,
1672 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1673 scroll_anchor: self.scroll_manager.anchor(),
1674 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1675 placeholder_text: self.placeholder_text.clone(),
1676 is_focused: self.focus_handle.is_focused(window),
1677 current_line_highlight: self
1678 .current_line_highlight
1679 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1680 gutter_hovered: self.gutter_hovered,
1681 }
1682 }
1683
1684 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1685 self.buffer.read(cx).language_at(point, cx)
1686 }
1687
1688 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1689 self.buffer.read(cx).read(cx).file_at(point).cloned()
1690 }
1691
1692 pub fn active_excerpt(
1693 &self,
1694 cx: &App,
1695 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1696 self.buffer
1697 .read(cx)
1698 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1699 }
1700
1701 pub fn mode(&self) -> EditorMode {
1702 self.mode
1703 }
1704
1705 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1706 self.collaboration_hub.as_deref()
1707 }
1708
1709 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1710 self.collaboration_hub = Some(hub);
1711 }
1712
1713 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1714 self.in_project_search = in_project_search;
1715 }
1716
1717 pub fn set_custom_context_menu(
1718 &mut self,
1719 f: impl 'static
1720 + Fn(
1721 &mut Self,
1722 DisplayPoint,
1723 &mut Window,
1724 &mut Context<Self>,
1725 ) -> Option<Entity<ui::ContextMenu>>,
1726 ) {
1727 self.custom_context_menu = Some(Box::new(f))
1728 }
1729
1730 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1731 self.completion_provider = provider;
1732 }
1733
1734 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1735 self.semantics_provider.clone()
1736 }
1737
1738 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1739 self.semantics_provider = provider;
1740 }
1741
1742 pub fn set_inline_completion_provider<T>(
1743 &mut self,
1744 provider: Option<Entity<T>>,
1745 window: &mut Window,
1746 cx: &mut Context<Self>,
1747 ) where
1748 T: InlineCompletionProvider,
1749 {
1750 self.inline_completion_provider =
1751 provider.map(|provider| RegisteredInlineCompletionProvider {
1752 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1753 if this.focus_handle.is_focused(window) {
1754 this.update_visible_inline_completion(window, cx);
1755 }
1756 }),
1757 provider: Arc::new(provider),
1758 });
1759 self.refresh_inline_completion(false, false, window, cx);
1760 }
1761
1762 pub fn placeholder_text(&self) -> Option<&str> {
1763 self.placeholder_text.as_deref()
1764 }
1765
1766 pub fn set_placeholder_text(
1767 &mut self,
1768 placeholder_text: impl Into<Arc<str>>,
1769 cx: &mut Context<Self>,
1770 ) {
1771 let placeholder_text = Some(placeholder_text.into());
1772 if self.placeholder_text != placeholder_text {
1773 self.placeholder_text = placeholder_text;
1774 cx.notify();
1775 }
1776 }
1777
1778 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1779 self.cursor_shape = cursor_shape;
1780
1781 // Disrupt blink for immediate user feedback that the cursor shape has changed
1782 self.blink_manager.update(cx, BlinkManager::show_cursor);
1783
1784 cx.notify();
1785 }
1786
1787 pub fn set_current_line_highlight(
1788 &mut self,
1789 current_line_highlight: Option<CurrentLineHighlight>,
1790 ) {
1791 self.current_line_highlight = current_line_highlight;
1792 }
1793
1794 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1795 self.collapse_matches = collapse_matches;
1796 }
1797
1798 pub fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1799 let buffers = self.buffer.read(cx).all_buffers();
1800 let Some(lsp_store) = self.lsp_store(cx) else {
1801 return;
1802 };
1803 lsp_store.update(cx, |lsp_store, cx| {
1804 for buffer in buffers {
1805 self.registered_buffers
1806 .entry(buffer.read(cx).remote_id())
1807 .or_insert_with(|| {
1808 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1809 });
1810 }
1811 })
1812 }
1813
1814 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1815 if self.collapse_matches {
1816 return range.start..range.start;
1817 }
1818 range.clone()
1819 }
1820
1821 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1822 if self.display_map.read(cx).clip_at_line_ends != clip {
1823 self.display_map
1824 .update(cx, |map, _| map.clip_at_line_ends = clip);
1825 }
1826 }
1827
1828 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1829 self.input_enabled = input_enabled;
1830 }
1831
1832 pub fn set_show_inline_completions_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
1833 self.show_inline_completions = enabled;
1834 if !self.show_inline_completions {
1835 self.take_active_inline_completion(cx);
1836 cx.notify();
1837 }
1838 }
1839
1840 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1841 self.menu_inline_completions_policy = value;
1842 }
1843
1844 pub fn set_autoindent(&mut self, autoindent: bool) {
1845 if autoindent {
1846 self.autoindent_mode = Some(AutoindentMode::EachLine);
1847 } else {
1848 self.autoindent_mode = None;
1849 }
1850 }
1851
1852 pub fn read_only(&self, cx: &App) -> bool {
1853 self.read_only || self.buffer.read(cx).read_only()
1854 }
1855
1856 pub fn set_read_only(&mut self, read_only: bool) {
1857 self.read_only = read_only;
1858 }
1859
1860 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1861 self.use_autoclose = autoclose;
1862 }
1863
1864 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1865 self.use_auto_surround = auto_surround;
1866 }
1867
1868 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1869 self.auto_replace_emoji_shortcode = auto_replace;
1870 }
1871
1872 pub fn toggle_inline_completions(
1873 &mut self,
1874 _: &ToggleInlineCompletions,
1875 window: &mut Window,
1876 cx: &mut Context<Self>,
1877 ) {
1878 if self.show_inline_completions_override.is_some() {
1879 self.set_show_inline_completions(None, window, cx);
1880 } else {
1881 let cursor = self.selections.newest_anchor().head();
1882 if let Some((buffer, cursor_buffer_position)) =
1883 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1884 {
1885 let show_inline_completions = !self.should_show_inline_completions_in_buffer(
1886 &buffer,
1887 cursor_buffer_position,
1888 cx,
1889 );
1890 self.set_show_inline_completions(Some(show_inline_completions), window, cx);
1891 }
1892 }
1893 }
1894
1895 pub fn set_show_inline_completions(
1896 &mut self,
1897 show_inline_completions: Option<bool>,
1898 window: &mut Window,
1899 cx: &mut Context<Self>,
1900 ) {
1901 self.show_inline_completions_override = show_inline_completions;
1902 self.refresh_inline_completion(false, true, window, cx);
1903 }
1904
1905 fn inline_completions_disabled_in_scope(
1906 &self,
1907 buffer: &Entity<Buffer>,
1908 buffer_position: language::Anchor,
1909 cx: &App,
1910 ) -> bool {
1911 let snapshot = buffer.read(cx).snapshot();
1912 let settings = snapshot.settings_at(buffer_position, cx);
1913
1914 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1915 return false;
1916 };
1917
1918 scope.override_name().map_or(false, |scope_name| {
1919 settings
1920 .inline_completions_disabled_in
1921 .iter()
1922 .any(|s| s == scope_name)
1923 })
1924 }
1925
1926 pub fn set_use_modal_editing(&mut self, to: bool) {
1927 self.use_modal_editing = to;
1928 }
1929
1930 pub fn use_modal_editing(&self) -> bool {
1931 self.use_modal_editing
1932 }
1933
1934 fn selections_did_change(
1935 &mut self,
1936 local: bool,
1937 old_cursor_position: &Anchor,
1938 show_completions: bool,
1939 window: &mut Window,
1940 cx: &mut Context<Self>,
1941 ) {
1942 window.invalidate_character_coordinates();
1943
1944 // Copy selections to primary selection buffer
1945 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1946 if local {
1947 let selections = self.selections.all::<usize>(cx);
1948 let buffer_handle = self.buffer.read(cx).read(cx);
1949
1950 let mut text = String::new();
1951 for (index, selection) in selections.iter().enumerate() {
1952 let text_for_selection = buffer_handle
1953 .text_for_range(selection.start..selection.end)
1954 .collect::<String>();
1955
1956 text.push_str(&text_for_selection);
1957 if index != selections.len() - 1 {
1958 text.push('\n');
1959 }
1960 }
1961
1962 if !text.is_empty() {
1963 cx.write_to_primary(ClipboardItem::new_string(text));
1964 }
1965 }
1966
1967 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
1968 self.buffer.update(cx, |buffer, cx| {
1969 buffer.set_active_selections(
1970 &self.selections.disjoint_anchors(),
1971 self.selections.line_mode,
1972 self.cursor_shape,
1973 cx,
1974 )
1975 });
1976 }
1977 let display_map = self
1978 .display_map
1979 .update(cx, |display_map, cx| display_map.snapshot(cx));
1980 let buffer = &display_map.buffer_snapshot;
1981 self.add_selections_state = None;
1982 self.select_next_state = None;
1983 self.select_prev_state = None;
1984 self.select_larger_syntax_node_stack.clear();
1985 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1986 self.snippet_stack
1987 .invalidate(&self.selections.disjoint_anchors(), buffer);
1988 self.take_rename(false, window, cx);
1989
1990 let new_cursor_position = self.selections.newest_anchor().head();
1991
1992 self.push_to_nav_history(
1993 *old_cursor_position,
1994 Some(new_cursor_position.to_point(buffer)),
1995 cx,
1996 );
1997
1998 if local {
1999 let new_cursor_position = self.selections.newest_anchor().head();
2000 let mut context_menu = self.context_menu.borrow_mut();
2001 let completion_menu = match context_menu.as_ref() {
2002 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2003 _ => {
2004 *context_menu = None;
2005 None
2006 }
2007 };
2008
2009 if let Some(completion_menu) = completion_menu {
2010 let cursor_position = new_cursor_position.to_offset(buffer);
2011 let (word_range, kind) =
2012 buffer.surrounding_word(completion_menu.initial_position, true);
2013 if kind == Some(CharKind::Word)
2014 && word_range.to_inclusive().contains(&cursor_position)
2015 {
2016 let mut completion_menu = completion_menu.clone();
2017 drop(context_menu);
2018
2019 let query = Self::completion_query(buffer, cursor_position);
2020 cx.spawn(move |this, mut cx| async move {
2021 completion_menu
2022 .filter(query.as_deref(), cx.background_executor().clone())
2023 .await;
2024
2025 this.update(&mut cx, |this, cx| {
2026 let mut context_menu = this.context_menu.borrow_mut();
2027 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2028 else {
2029 return;
2030 };
2031
2032 if menu.id > completion_menu.id {
2033 return;
2034 }
2035
2036 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2037 drop(context_menu);
2038 cx.notify();
2039 })
2040 })
2041 .detach();
2042
2043 if show_completions {
2044 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2045 }
2046 } else {
2047 drop(context_menu);
2048 self.hide_context_menu(window, cx);
2049 }
2050 } else {
2051 drop(context_menu);
2052 }
2053
2054 hide_hover(self, cx);
2055
2056 if old_cursor_position.to_display_point(&display_map).row()
2057 != new_cursor_position.to_display_point(&display_map).row()
2058 {
2059 self.available_code_actions.take();
2060 }
2061 self.refresh_code_actions(window, cx);
2062 self.refresh_document_highlights(cx);
2063 refresh_matching_bracket_highlights(self, window, cx);
2064 self.update_visible_inline_completion(window, cx);
2065 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2066 if self.git_blame_inline_enabled {
2067 self.start_inline_blame_timer(window, cx);
2068 }
2069 }
2070
2071 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2072 cx.emit(EditorEvent::SelectionsChanged { local });
2073
2074 if self.selections.disjoint_anchors().len() == 1 {
2075 cx.emit(SearchEvent::ActiveMatchChanged)
2076 }
2077 cx.notify();
2078 }
2079
2080 pub fn change_selections<R>(
2081 &mut self,
2082 autoscroll: Option<Autoscroll>,
2083 window: &mut Window,
2084 cx: &mut Context<Self>,
2085 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2086 ) -> R {
2087 self.change_selections_inner(autoscroll, true, window, cx, change)
2088 }
2089
2090 pub fn change_selections_inner<R>(
2091 &mut self,
2092 autoscroll: Option<Autoscroll>,
2093 request_completions: bool,
2094 window: &mut Window,
2095 cx: &mut Context<Self>,
2096 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2097 ) -> R {
2098 let old_cursor_position = self.selections.newest_anchor().head();
2099 self.push_to_selection_history();
2100
2101 let (changed, result) = self.selections.change_with(cx, change);
2102
2103 if changed {
2104 if let Some(autoscroll) = autoscroll {
2105 self.request_autoscroll(autoscroll, cx);
2106 }
2107 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2108
2109 if self.should_open_signature_help_automatically(
2110 &old_cursor_position,
2111 self.signature_help_state.backspace_pressed(),
2112 cx,
2113 ) {
2114 self.show_signature_help(&ShowSignatureHelp, window, cx);
2115 }
2116 self.signature_help_state.set_backspace_pressed(false);
2117 }
2118
2119 result
2120 }
2121
2122 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2123 where
2124 I: IntoIterator<Item = (Range<S>, T)>,
2125 S: ToOffset,
2126 T: Into<Arc<str>>,
2127 {
2128 if self.read_only(cx) {
2129 return;
2130 }
2131
2132 self.buffer
2133 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2134 }
2135
2136 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2137 where
2138 I: IntoIterator<Item = (Range<S>, T)>,
2139 S: ToOffset,
2140 T: Into<Arc<str>>,
2141 {
2142 if self.read_only(cx) {
2143 return;
2144 }
2145
2146 self.buffer.update(cx, |buffer, cx| {
2147 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2148 });
2149 }
2150
2151 pub fn edit_with_block_indent<I, S, T>(
2152 &mut self,
2153 edits: I,
2154 original_indent_columns: Vec<u32>,
2155 cx: &mut Context<Self>,
2156 ) where
2157 I: IntoIterator<Item = (Range<S>, T)>,
2158 S: ToOffset,
2159 T: Into<Arc<str>>,
2160 {
2161 if self.read_only(cx) {
2162 return;
2163 }
2164
2165 self.buffer.update(cx, |buffer, cx| {
2166 buffer.edit(
2167 edits,
2168 Some(AutoindentMode::Block {
2169 original_indent_columns,
2170 }),
2171 cx,
2172 )
2173 });
2174 }
2175
2176 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2177 self.hide_context_menu(window, cx);
2178
2179 match phase {
2180 SelectPhase::Begin {
2181 position,
2182 add,
2183 click_count,
2184 } => self.begin_selection(position, add, click_count, window, cx),
2185 SelectPhase::BeginColumnar {
2186 position,
2187 goal_column,
2188 reset,
2189 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2190 SelectPhase::Extend {
2191 position,
2192 click_count,
2193 } => self.extend_selection(position, click_count, window, cx),
2194 SelectPhase::Update {
2195 position,
2196 goal_column,
2197 scroll_delta,
2198 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2199 SelectPhase::End => self.end_selection(window, cx),
2200 }
2201 }
2202
2203 fn extend_selection(
2204 &mut self,
2205 position: DisplayPoint,
2206 click_count: usize,
2207 window: &mut Window,
2208 cx: &mut Context<Self>,
2209 ) {
2210 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2211 let tail = self.selections.newest::<usize>(cx).tail();
2212 self.begin_selection(position, false, click_count, window, cx);
2213
2214 let position = position.to_offset(&display_map, Bias::Left);
2215 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2216
2217 let mut pending_selection = self
2218 .selections
2219 .pending_anchor()
2220 .expect("extend_selection not called with pending selection");
2221 if position >= tail {
2222 pending_selection.start = tail_anchor;
2223 } else {
2224 pending_selection.end = tail_anchor;
2225 pending_selection.reversed = true;
2226 }
2227
2228 let mut pending_mode = self.selections.pending_mode().unwrap();
2229 match &mut pending_mode {
2230 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2231 _ => {}
2232 }
2233
2234 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2235 s.set_pending(pending_selection, pending_mode)
2236 });
2237 }
2238
2239 fn begin_selection(
2240 &mut self,
2241 position: DisplayPoint,
2242 add: bool,
2243 click_count: usize,
2244 window: &mut Window,
2245 cx: &mut Context<Self>,
2246 ) {
2247 if !self.focus_handle.is_focused(window) {
2248 self.last_focused_descendant = None;
2249 window.focus(&self.focus_handle);
2250 }
2251
2252 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2253 let buffer = &display_map.buffer_snapshot;
2254 let newest_selection = self.selections.newest_anchor().clone();
2255 let position = display_map.clip_point(position, Bias::Left);
2256
2257 let start;
2258 let end;
2259 let mode;
2260 let mut auto_scroll;
2261 match click_count {
2262 1 => {
2263 start = buffer.anchor_before(position.to_point(&display_map));
2264 end = start;
2265 mode = SelectMode::Character;
2266 auto_scroll = true;
2267 }
2268 2 => {
2269 let range = movement::surrounding_word(&display_map, position);
2270 start = buffer.anchor_before(range.start.to_point(&display_map));
2271 end = buffer.anchor_before(range.end.to_point(&display_map));
2272 mode = SelectMode::Word(start..end);
2273 auto_scroll = true;
2274 }
2275 3 => {
2276 let position = display_map
2277 .clip_point(position, Bias::Left)
2278 .to_point(&display_map);
2279 let line_start = display_map.prev_line_boundary(position).0;
2280 let next_line_start = buffer.clip_point(
2281 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2282 Bias::Left,
2283 );
2284 start = buffer.anchor_before(line_start);
2285 end = buffer.anchor_before(next_line_start);
2286 mode = SelectMode::Line(start..end);
2287 auto_scroll = true;
2288 }
2289 _ => {
2290 start = buffer.anchor_before(0);
2291 end = buffer.anchor_before(buffer.len());
2292 mode = SelectMode::All;
2293 auto_scroll = false;
2294 }
2295 }
2296 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2297
2298 let point_to_delete: Option<usize> = {
2299 let selected_points: Vec<Selection<Point>> =
2300 self.selections.disjoint_in_range(start..end, cx);
2301
2302 if !add || click_count > 1 {
2303 None
2304 } else if !selected_points.is_empty() {
2305 Some(selected_points[0].id)
2306 } else {
2307 let clicked_point_already_selected =
2308 self.selections.disjoint.iter().find(|selection| {
2309 selection.start.to_point(buffer) == start.to_point(buffer)
2310 || selection.end.to_point(buffer) == end.to_point(buffer)
2311 });
2312
2313 clicked_point_already_selected.map(|selection| selection.id)
2314 }
2315 };
2316
2317 let selections_count = self.selections.count();
2318
2319 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2320 if let Some(point_to_delete) = point_to_delete {
2321 s.delete(point_to_delete);
2322
2323 if selections_count == 1 {
2324 s.set_pending_anchor_range(start..end, mode);
2325 }
2326 } else {
2327 if !add {
2328 s.clear_disjoint();
2329 } else if click_count > 1 {
2330 s.delete(newest_selection.id)
2331 }
2332
2333 s.set_pending_anchor_range(start..end, mode);
2334 }
2335 });
2336 }
2337
2338 fn begin_columnar_selection(
2339 &mut self,
2340 position: DisplayPoint,
2341 goal_column: u32,
2342 reset: bool,
2343 window: &mut Window,
2344 cx: &mut Context<Self>,
2345 ) {
2346 if !self.focus_handle.is_focused(window) {
2347 self.last_focused_descendant = None;
2348 window.focus(&self.focus_handle);
2349 }
2350
2351 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2352
2353 if reset {
2354 let pointer_position = display_map
2355 .buffer_snapshot
2356 .anchor_before(position.to_point(&display_map));
2357
2358 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2359 s.clear_disjoint();
2360 s.set_pending_anchor_range(
2361 pointer_position..pointer_position,
2362 SelectMode::Character,
2363 );
2364 });
2365 }
2366
2367 let tail = self.selections.newest::<Point>(cx).tail();
2368 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2369
2370 if !reset {
2371 self.select_columns(
2372 tail.to_display_point(&display_map),
2373 position,
2374 goal_column,
2375 &display_map,
2376 window,
2377 cx,
2378 );
2379 }
2380 }
2381
2382 fn update_selection(
2383 &mut self,
2384 position: DisplayPoint,
2385 goal_column: u32,
2386 scroll_delta: gpui::Point<f32>,
2387 window: &mut Window,
2388 cx: &mut Context<Self>,
2389 ) {
2390 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2391
2392 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2393 let tail = tail.to_display_point(&display_map);
2394 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2395 } else if let Some(mut pending) = self.selections.pending_anchor() {
2396 let buffer = self.buffer.read(cx).snapshot(cx);
2397 let head;
2398 let tail;
2399 let mode = self.selections.pending_mode().unwrap();
2400 match &mode {
2401 SelectMode::Character => {
2402 head = position.to_point(&display_map);
2403 tail = pending.tail().to_point(&buffer);
2404 }
2405 SelectMode::Word(original_range) => {
2406 let original_display_range = original_range.start.to_display_point(&display_map)
2407 ..original_range.end.to_display_point(&display_map);
2408 let original_buffer_range = original_display_range.start.to_point(&display_map)
2409 ..original_display_range.end.to_point(&display_map);
2410 if movement::is_inside_word(&display_map, position)
2411 || original_display_range.contains(&position)
2412 {
2413 let word_range = movement::surrounding_word(&display_map, position);
2414 if word_range.start < original_display_range.start {
2415 head = word_range.start.to_point(&display_map);
2416 } else {
2417 head = word_range.end.to_point(&display_map);
2418 }
2419 } else {
2420 head = position.to_point(&display_map);
2421 }
2422
2423 if head <= original_buffer_range.start {
2424 tail = original_buffer_range.end;
2425 } else {
2426 tail = original_buffer_range.start;
2427 }
2428 }
2429 SelectMode::Line(original_range) => {
2430 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2431
2432 let position = display_map
2433 .clip_point(position, Bias::Left)
2434 .to_point(&display_map);
2435 let line_start = display_map.prev_line_boundary(position).0;
2436 let next_line_start = buffer.clip_point(
2437 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2438 Bias::Left,
2439 );
2440
2441 if line_start < original_range.start {
2442 head = line_start
2443 } else {
2444 head = next_line_start
2445 }
2446
2447 if head <= original_range.start {
2448 tail = original_range.end;
2449 } else {
2450 tail = original_range.start;
2451 }
2452 }
2453 SelectMode::All => {
2454 return;
2455 }
2456 };
2457
2458 if head < tail {
2459 pending.start = buffer.anchor_before(head);
2460 pending.end = buffer.anchor_before(tail);
2461 pending.reversed = true;
2462 } else {
2463 pending.start = buffer.anchor_before(tail);
2464 pending.end = buffer.anchor_before(head);
2465 pending.reversed = false;
2466 }
2467
2468 self.change_selections(None, window, cx, |s| {
2469 s.set_pending(pending, mode);
2470 });
2471 } else {
2472 log::error!("update_selection dispatched with no pending selection");
2473 return;
2474 }
2475
2476 self.apply_scroll_delta(scroll_delta, window, cx);
2477 cx.notify();
2478 }
2479
2480 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2481 self.columnar_selection_tail.take();
2482 if self.selections.pending_anchor().is_some() {
2483 let selections = self.selections.all::<usize>(cx);
2484 self.change_selections(None, window, cx, |s| {
2485 s.select(selections);
2486 s.clear_pending();
2487 });
2488 }
2489 }
2490
2491 fn select_columns(
2492 &mut self,
2493 tail: DisplayPoint,
2494 head: DisplayPoint,
2495 goal_column: u32,
2496 display_map: &DisplaySnapshot,
2497 window: &mut Window,
2498 cx: &mut Context<Self>,
2499 ) {
2500 let start_row = cmp::min(tail.row(), head.row());
2501 let end_row = cmp::max(tail.row(), head.row());
2502 let start_column = cmp::min(tail.column(), goal_column);
2503 let end_column = cmp::max(tail.column(), goal_column);
2504 let reversed = start_column < tail.column();
2505
2506 let selection_ranges = (start_row.0..=end_row.0)
2507 .map(DisplayRow)
2508 .filter_map(|row| {
2509 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2510 let start = display_map
2511 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2512 .to_point(display_map);
2513 let end = display_map
2514 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2515 .to_point(display_map);
2516 if reversed {
2517 Some(end..start)
2518 } else {
2519 Some(start..end)
2520 }
2521 } else {
2522 None
2523 }
2524 })
2525 .collect::<Vec<_>>();
2526
2527 self.change_selections(None, window, cx, |s| {
2528 s.select_ranges(selection_ranges);
2529 });
2530 cx.notify();
2531 }
2532
2533 pub fn has_pending_nonempty_selection(&self) -> bool {
2534 let pending_nonempty_selection = match self.selections.pending_anchor() {
2535 Some(Selection { start, end, .. }) => start != end,
2536 None => false,
2537 };
2538
2539 pending_nonempty_selection
2540 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2541 }
2542
2543 pub fn has_pending_selection(&self) -> bool {
2544 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2545 }
2546
2547 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2548 self.selection_mark_mode = false;
2549
2550 if self.clear_expanded_diff_hunks(cx) {
2551 cx.notify();
2552 return;
2553 }
2554 if self.dismiss_menus_and_popups(true, window, cx) {
2555 return;
2556 }
2557
2558 if self.mode == EditorMode::Full
2559 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2560 {
2561 return;
2562 }
2563
2564 cx.propagate();
2565 }
2566
2567 pub fn dismiss_menus_and_popups(
2568 &mut self,
2569 should_report_inline_completion_event: bool,
2570 window: &mut Window,
2571 cx: &mut Context<Self>,
2572 ) -> bool {
2573 if self.take_rename(false, window, cx).is_some() {
2574 return true;
2575 }
2576
2577 if hide_hover(self, cx) {
2578 return true;
2579 }
2580
2581 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2582 return true;
2583 }
2584
2585 if self.hide_context_menu(window, cx).is_some() {
2586 return true;
2587 }
2588
2589 if self.mouse_context_menu.take().is_some() {
2590 return true;
2591 }
2592
2593 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2594 return true;
2595 }
2596
2597 if self.snippet_stack.pop().is_some() {
2598 return true;
2599 }
2600
2601 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2602 self.dismiss_diagnostics(cx);
2603 return true;
2604 }
2605
2606 false
2607 }
2608
2609 fn linked_editing_ranges_for(
2610 &self,
2611 selection: Range<text::Anchor>,
2612 cx: &App,
2613 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2614 if self.linked_edit_ranges.is_empty() {
2615 return None;
2616 }
2617 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2618 selection.end.buffer_id.and_then(|end_buffer_id| {
2619 if selection.start.buffer_id != Some(end_buffer_id) {
2620 return None;
2621 }
2622 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2623 let snapshot = buffer.read(cx).snapshot();
2624 self.linked_edit_ranges
2625 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2626 .map(|ranges| (ranges, snapshot, buffer))
2627 })?;
2628 use text::ToOffset as TO;
2629 // find offset from the start of current range to current cursor position
2630 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2631
2632 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2633 let start_difference = start_offset - start_byte_offset;
2634 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2635 let end_difference = end_offset - start_byte_offset;
2636 // Current range has associated linked ranges.
2637 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2638 for range in linked_ranges.iter() {
2639 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2640 let end_offset = start_offset + end_difference;
2641 let start_offset = start_offset + start_difference;
2642 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2643 continue;
2644 }
2645 if self.selections.disjoint_anchor_ranges().any(|s| {
2646 if s.start.buffer_id != selection.start.buffer_id
2647 || s.end.buffer_id != selection.end.buffer_id
2648 {
2649 return false;
2650 }
2651 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2652 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2653 }) {
2654 continue;
2655 }
2656 let start = buffer_snapshot.anchor_after(start_offset);
2657 let end = buffer_snapshot.anchor_after(end_offset);
2658 linked_edits
2659 .entry(buffer.clone())
2660 .or_default()
2661 .push(start..end);
2662 }
2663 Some(linked_edits)
2664 }
2665
2666 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2667 let text: Arc<str> = text.into();
2668
2669 if self.read_only(cx) {
2670 return;
2671 }
2672
2673 let selections = self.selections.all_adjusted(cx);
2674 let mut bracket_inserted = false;
2675 let mut edits = Vec::new();
2676 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2677 let mut new_selections = Vec::with_capacity(selections.len());
2678 let mut new_autoclose_regions = Vec::new();
2679 let snapshot = self.buffer.read(cx).read(cx);
2680
2681 for (selection, autoclose_region) in
2682 self.selections_with_autoclose_regions(selections, &snapshot)
2683 {
2684 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2685 // Determine if the inserted text matches the opening or closing
2686 // bracket of any of this language's bracket pairs.
2687 let mut bracket_pair = None;
2688 let mut is_bracket_pair_start = false;
2689 let mut is_bracket_pair_end = false;
2690 if !text.is_empty() {
2691 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2692 // and they are removing the character that triggered IME popup.
2693 for (pair, enabled) in scope.brackets() {
2694 if !pair.close && !pair.surround {
2695 continue;
2696 }
2697
2698 if enabled && pair.start.ends_with(text.as_ref()) {
2699 let prefix_len = pair.start.len() - text.len();
2700 let preceding_text_matches_prefix = prefix_len == 0
2701 || (selection.start.column >= (prefix_len as u32)
2702 && snapshot.contains_str_at(
2703 Point::new(
2704 selection.start.row,
2705 selection.start.column - (prefix_len as u32),
2706 ),
2707 &pair.start[..prefix_len],
2708 ));
2709 if preceding_text_matches_prefix {
2710 bracket_pair = Some(pair.clone());
2711 is_bracket_pair_start = true;
2712 break;
2713 }
2714 }
2715 if pair.end.as_str() == text.as_ref() {
2716 bracket_pair = Some(pair.clone());
2717 is_bracket_pair_end = true;
2718 break;
2719 }
2720 }
2721 }
2722
2723 if let Some(bracket_pair) = bracket_pair {
2724 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2725 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2726 let auto_surround =
2727 self.use_auto_surround && snapshot_settings.use_auto_surround;
2728 if selection.is_empty() {
2729 if is_bracket_pair_start {
2730 // If the inserted text is a suffix of an opening bracket and the
2731 // selection is preceded by the rest of the opening bracket, then
2732 // insert the closing bracket.
2733 let following_text_allows_autoclose = snapshot
2734 .chars_at(selection.start)
2735 .next()
2736 .map_or(true, |c| scope.should_autoclose_before(c));
2737
2738 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2739 && bracket_pair.start.len() == 1
2740 {
2741 let target = bracket_pair.start.chars().next().unwrap();
2742 let current_line_count = snapshot
2743 .reversed_chars_at(selection.start)
2744 .take_while(|&c| c != '\n')
2745 .filter(|&c| c == target)
2746 .count();
2747 current_line_count % 2 == 1
2748 } else {
2749 false
2750 };
2751
2752 if autoclose
2753 && bracket_pair.close
2754 && following_text_allows_autoclose
2755 && !is_closing_quote
2756 {
2757 let anchor = snapshot.anchor_before(selection.end);
2758 new_selections.push((selection.map(|_| anchor), text.len()));
2759 new_autoclose_regions.push((
2760 anchor,
2761 text.len(),
2762 selection.id,
2763 bracket_pair.clone(),
2764 ));
2765 edits.push((
2766 selection.range(),
2767 format!("{}{}", text, bracket_pair.end).into(),
2768 ));
2769 bracket_inserted = true;
2770 continue;
2771 }
2772 }
2773
2774 if let Some(region) = autoclose_region {
2775 // If the selection is followed by an auto-inserted closing bracket,
2776 // then don't insert that closing bracket again; just move the selection
2777 // past the closing bracket.
2778 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2779 && text.as_ref() == region.pair.end.as_str();
2780 if should_skip {
2781 let anchor = snapshot.anchor_after(selection.end);
2782 new_selections
2783 .push((selection.map(|_| anchor), region.pair.end.len()));
2784 continue;
2785 }
2786 }
2787
2788 let always_treat_brackets_as_autoclosed = snapshot
2789 .settings_at(selection.start, cx)
2790 .always_treat_brackets_as_autoclosed;
2791 if always_treat_brackets_as_autoclosed
2792 && is_bracket_pair_end
2793 && snapshot.contains_str_at(selection.end, text.as_ref())
2794 {
2795 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2796 // and the inserted text is a closing bracket and the selection is followed
2797 // by the closing bracket then move the selection past the closing bracket.
2798 let anchor = snapshot.anchor_after(selection.end);
2799 new_selections.push((selection.map(|_| anchor), text.len()));
2800 continue;
2801 }
2802 }
2803 // If an opening bracket is 1 character long and is typed while
2804 // text is selected, then surround that text with the bracket pair.
2805 else if auto_surround
2806 && bracket_pair.surround
2807 && is_bracket_pair_start
2808 && bracket_pair.start.chars().count() == 1
2809 {
2810 edits.push((selection.start..selection.start, text.clone()));
2811 edits.push((
2812 selection.end..selection.end,
2813 bracket_pair.end.as_str().into(),
2814 ));
2815 bracket_inserted = true;
2816 new_selections.push((
2817 Selection {
2818 id: selection.id,
2819 start: snapshot.anchor_after(selection.start),
2820 end: snapshot.anchor_before(selection.end),
2821 reversed: selection.reversed,
2822 goal: selection.goal,
2823 },
2824 0,
2825 ));
2826 continue;
2827 }
2828 }
2829 }
2830
2831 if self.auto_replace_emoji_shortcode
2832 && selection.is_empty()
2833 && text.as_ref().ends_with(':')
2834 {
2835 if let Some(possible_emoji_short_code) =
2836 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2837 {
2838 if !possible_emoji_short_code.is_empty() {
2839 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2840 let emoji_shortcode_start = Point::new(
2841 selection.start.row,
2842 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2843 );
2844
2845 // Remove shortcode from buffer
2846 edits.push((
2847 emoji_shortcode_start..selection.start,
2848 "".to_string().into(),
2849 ));
2850 new_selections.push((
2851 Selection {
2852 id: selection.id,
2853 start: snapshot.anchor_after(emoji_shortcode_start),
2854 end: snapshot.anchor_before(selection.start),
2855 reversed: selection.reversed,
2856 goal: selection.goal,
2857 },
2858 0,
2859 ));
2860
2861 // Insert emoji
2862 let selection_start_anchor = snapshot.anchor_after(selection.start);
2863 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2864 edits.push((selection.start..selection.end, emoji.to_string().into()));
2865
2866 continue;
2867 }
2868 }
2869 }
2870 }
2871
2872 // If not handling any auto-close operation, then just replace the selected
2873 // text with the given input and move the selection to the end of the
2874 // newly inserted text.
2875 let anchor = snapshot.anchor_after(selection.end);
2876 if !self.linked_edit_ranges.is_empty() {
2877 let start_anchor = snapshot.anchor_before(selection.start);
2878
2879 let is_word_char = text.chars().next().map_or(true, |char| {
2880 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2881 classifier.is_word(char)
2882 });
2883
2884 if is_word_char {
2885 if let Some(ranges) = self
2886 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2887 {
2888 for (buffer, edits) in ranges {
2889 linked_edits
2890 .entry(buffer.clone())
2891 .or_default()
2892 .extend(edits.into_iter().map(|range| (range, text.clone())));
2893 }
2894 }
2895 }
2896 }
2897
2898 new_selections.push((selection.map(|_| anchor), 0));
2899 edits.push((selection.start..selection.end, text.clone()));
2900 }
2901
2902 drop(snapshot);
2903
2904 self.transact(window, cx, |this, window, cx| {
2905 this.buffer.update(cx, |buffer, cx| {
2906 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2907 });
2908 for (buffer, edits) in linked_edits {
2909 buffer.update(cx, |buffer, cx| {
2910 let snapshot = buffer.snapshot();
2911 let edits = edits
2912 .into_iter()
2913 .map(|(range, text)| {
2914 use text::ToPoint as TP;
2915 let end_point = TP::to_point(&range.end, &snapshot);
2916 let start_point = TP::to_point(&range.start, &snapshot);
2917 (start_point..end_point, text)
2918 })
2919 .sorted_by_key(|(range, _)| range.start)
2920 .collect::<Vec<_>>();
2921 buffer.edit(edits, None, cx);
2922 })
2923 }
2924 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2925 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2926 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2927 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2928 .zip(new_selection_deltas)
2929 .map(|(selection, delta)| Selection {
2930 id: selection.id,
2931 start: selection.start + delta,
2932 end: selection.end + delta,
2933 reversed: selection.reversed,
2934 goal: SelectionGoal::None,
2935 })
2936 .collect::<Vec<_>>();
2937
2938 let mut i = 0;
2939 for (position, delta, selection_id, pair) in new_autoclose_regions {
2940 let position = position.to_offset(&map.buffer_snapshot) + delta;
2941 let start = map.buffer_snapshot.anchor_before(position);
2942 let end = map.buffer_snapshot.anchor_after(position);
2943 while let Some(existing_state) = this.autoclose_regions.get(i) {
2944 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2945 Ordering::Less => i += 1,
2946 Ordering::Greater => break,
2947 Ordering::Equal => {
2948 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2949 Ordering::Less => i += 1,
2950 Ordering::Equal => break,
2951 Ordering::Greater => break,
2952 }
2953 }
2954 }
2955 }
2956 this.autoclose_regions.insert(
2957 i,
2958 AutocloseRegion {
2959 selection_id,
2960 range: start..end,
2961 pair,
2962 },
2963 );
2964 }
2965
2966 let had_active_inline_completion = this.has_active_inline_completion();
2967 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
2968 s.select(new_selections)
2969 });
2970
2971 if !bracket_inserted {
2972 if let Some(on_type_format_task) =
2973 this.trigger_on_type_formatting(text.to_string(), window, cx)
2974 {
2975 on_type_format_task.detach_and_log_err(cx);
2976 }
2977 }
2978
2979 let editor_settings = EditorSettings::get_global(cx);
2980 if bracket_inserted
2981 && (editor_settings.auto_signature_help
2982 || editor_settings.show_signature_help_after_edits)
2983 {
2984 this.show_signature_help(&ShowSignatureHelp, window, cx);
2985 }
2986
2987 let trigger_in_words =
2988 this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
2989 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
2990 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
2991 this.refresh_inline_completion(true, false, window, cx);
2992 });
2993 }
2994
2995 fn find_possible_emoji_shortcode_at_position(
2996 snapshot: &MultiBufferSnapshot,
2997 position: Point,
2998 ) -> Option<String> {
2999 let mut chars = Vec::new();
3000 let mut found_colon = false;
3001 for char in snapshot.reversed_chars_at(position).take(100) {
3002 // Found a possible emoji shortcode in the middle of the buffer
3003 if found_colon {
3004 if char.is_whitespace() {
3005 chars.reverse();
3006 return Some(chars.iter().collect());
3007 }
3008 // If the previous character is not a whitespace, we are in the middle of a word
3009 // and we only want to complete the shortcode if the word is made up of other emojis
3010 let mut containing_word = String::new();
3011 for ch in snapshot
3012 .reversed_chars_at(position)
3013 .skip(chars.len() + 1)
3014 .take(100)
3015 {
3016 if ch.is_whitespace() {
3017 break;
3018 }
3019 containing_word.push(ch);
3020 }
3021 let containing_word = containing_word.chars().rev().collect::<String>();
3022 if util::word_consists_of_emojis(containing_word.as_str()) {
3023 chars.reverse();
3024 return Some(chars.iter().collect());
3025 }
3026 }
3027
3028 if char.is_whitespace() || !char.is_ascii() {
3029 return None;
3030 }
3031 if char == ':' {
3032 found_colon = true;
3033 } else {
3034 chars.push(char);
3035 }
3036 }
3037 // Found a possible emoji shortcode at the beginning of the buffer
3038 chars.reverse();
3039 Some(chars.iter().collect())
3040 }
3041
3042 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3043 self.transact(window, cx, |this, window, cx| {
3044 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3045 let selections = this.selections.all::<usize>(cx);
3046 let multi_buffer = this.buffer.read(cx);
3047 let buffer = multi_buffer.snapshot(cx);
3048 selections
3049 .iter()
3050 .map(|selection| {
3051 let start_point = selection.start.to_point(&buffer);
3052 let mut indent =
3053 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3054 indent.len = cmp::min(indent.len, start_point.column);
3055 let start = selection.start;
3056 let end = selection.end;
3057 let selection_is_empty = start == end;
3058 let language_scope = buffer.language_scope_at(start);
3059 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3060 &language_scope
3061 {
3062 let leading_whitespace_len = buffer
3063 .reversed_chars_at(start)
3064 .take_while(|c| c.is_whitespace() && *c != '\n')
3065 .map(|c| c.len_utf8())
3066 .sum::<usize>();
3067
3068 let trailing_whitespace_len = buffer
3069 .chars_at(end)
3070 .take_while(|c| c.is_whitespace() && *c != '\n')
3071 .map(|c| c.len_utf8())
3072 .sum::<usize>();
3073
3074 let insert_extra_newline =
3075 language.brackets().any(|(pair, enabled)| {
3076 let pair_start = pair.start.trim_end();
3077 let pair_end = pair.end.trim_start();
3078
3079 enabled
3080 && pair.newline
3081 && buffer.contains_str_at(
3082 end + trailing_whitespace_len,
3083 pair_end,
3084 )
3085 && buffer.contains_str_at(
3086 (start - leading_whitespace_len)
3087 .saturating_sub(pair_start.len()),
3088 pair_start,
3089 )
3090 });
3091
3092 // Comment extension on newline is allowed only for cursor selections
3093 let comment_delimiter = maybe!({
3094 if !selection_is_empty {
3095 return None;
3096 }
3097
3098 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3099 return None;
3100 }
3101
3102 let delimiters = language.line_comment_prefixes();
3103 let max_len_of_delimiter =
3104 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3105 let (snapshot, range) =
3106 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3107
3108 let mut index_of_first_non_whitespace = 0;
3109 let comment_candidate = snapshot
3110 .chars_for_range(range)
3111 .skip_while(|c| {
3112 let should_skip = c.is_whitespace();
3113 if should_skip {
3114 index_of_first_non_whitespace += 1;
3115 }
3116 should_skip
3117 })
3118 .take(max_len_of_delimiter)
3119 .collect::<String>();
3120 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3121 comment_candidate.starts_with(comment_prefix.as_ref())
3122 })?;
3123 let cursor_is_placed_after_comment_marker =
3124 index_of_first_non_whitespace + comment_prefix.len()
3125 <= start_point.column as usize;
3126 if cursor_is_placed_after_comment_marker {
3127 Some(comment_prefix.clone())
3128 } else {
3129 None
3130 }
3131 });
3132 (comment_delimiter, insert_extra_newline)
3133 } else {
3134 (None, false)
3135 };
3136
3137 let capacity_for_delimiter = comment_delimiter
3138 .as_deref()
3139 .map(str::len)
3140 .unwrap_or_default();
3141 let mut new_text =
3142 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3143 new_text.push('\n');
3144 new_text.extend(indent.chars());
3145 if let Some(delimiter) = &comment_delimiter {
3146 new_text.push_str(delimiter);
3147 }
3148 if insert_extra_newline {
3149 new_text = new_text.repeat(2);
3150 }
3151
3152 let anchor = buffer.anchor_after(end);
3153 let new_selection = selection.map(|_| anchor);
3154 (
3155 (start..end, new_text),
3156 (insert_extra_newline, new_selection),
3157 )
3158 })
3159 .unzip()
3160 };
3161
3162 this.edit_with_autoindent(edits, cx);
3163 let buffer = this.buffer.read(cx).snapshot(cx);
3164 let new_selections = selection_fixup_info
3165 .into_iter()
3166 .map(|(extra_newline_inserted, new_selection)| {
3167 let mut cursor = new_selection.end.to_point(&buffer);
3168 if extra_newline_inserted {
3169 cursor.row -= 1;
3170 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3171 }
3172 new_selection.map(|_| cursor)
3173 })
3174 .collect();
3175
3176 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3177 s.select(new_selections)
3178 });
3179 this.refresh_inline_completion(true, false, window, cx);
3180 });
3181 }
3182
3183 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3184 let buffer = self.buffer.read(cx);
3185 let snapshot = buffer.snapshot(cx);
3186
3187 let mut edits = Vec::new();
3188 let mut rows = Vec::new();
3189
3190 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3191 let cursor = selection.head();
3192 let row = cursor.row;
3193
3194 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3195
3196 let newline = "\n".to_string();
3197 edits.push((start_of_line..start_of_line, newline));
3198
3199 rows.push(row + rows_inserted as u32);
3200 }
3201
3202 self.transact(window, cx, |editor, window, cx| {
3203 editor.edit(edits, cx);
3204
3205 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3206 let mut index = 0;
3207 s.move_cursors_with(|map, _, _| {
3208 let row = rows[index];
3209 index += 1;
3210
3211 let point = Point::new(row, 0);
3212 let boundary = map.next_line_boundary(point).1;
3213 let clipped = map.clip_point(boundary, Bias::Left);
3214
3215 (clipped, SelectionGoal::None)
3216 });
3217 });
3218
3219 let mut indent_edits = Vec::new();
3220 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3221 for row in rows {
3222 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3223 for (row, indent) in indents {
3224 if indent.len == 0 {
3225 continue;
3226 }
3227
3228 let text = match indent.kind {
3229 IndentKind::Space => " ".repeat(indent.len as usize),
3230 IndentKind::Tab => "\t".repeat(indent.len as usize),
3231 };
3232 let point = Point::new(row.0, 0);
3233 indent_edits.push((point..point, text));
3234 }
3235 }
3236 editor.edit(indent_edits, cx);
3237 });
3238 }
3239
3240 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3241 let buffer = self.buffer.read(cx);
3242 let snapshot = buffer.snapshot(cx);
3243
3244 let mut edits = Vec::new();
3245 let mut rows = Vec::new();
3246 let mut rows_inserted = 0;
3247
3248 for selection in self.selections.all_adjusted(cx) {
3249 let cursor = selection.head();
3250 let row = cursor.row;
3251
3252 let point = Point::new(row + 1, 0);
3253 let start_of_line = snapshot.clip_point(point, Bias::Left);
3254
3255 let newline = "\n".to_string();
3256 edits.push((start_of_line..start_of_line, newline));
3257
3258 rows_inserted += 1;
3259 rows.push(row + rows_inserted);
3260 }
3261
3262 self.transact(window, cx, |editor, window, cx| {
3263 editor.edit(edits, cx);
3264
3265 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3266 let mut index = 0;
3267 s.move_cursors_with(|map, _, _| {
3268 let row = rows[index];
3269 index += 1;
3270
3271 let point = Point::new(row, 0);
3272 let boundary = map.next_line_boundary(point).1;
3273 let clipped = map.clip_point(boundary, Bias::Left);
3274
3275 (clipped, SelectionGoal::None)
3276 });
3277 });
3278
3279 let mut indent_edits = Vec::new();
3280 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3281 for row in rows {
3282 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3283 for (row, indent) in indents {
3284 if indent.len == 0 {
3285 continue;
3286 }
3287
3288 let text = match indent.kind {
3289 IndentKind::Space => " ".repeat(indent.len as usize),
3290 IndentKind::Tab => "\t".repeat(indent.len as usize),
3291 };
3292 let point = Point::new(row.0, 0);
3293 indent_edits.push((point..point, text));
3294 }
3295 }
3296 editor.edit(indent_edits, cx);
3297 });
3298 }
3299
3300 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3301 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3302 original_indent_columns: Vec::new(),
3303 });
3304 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3305 }
3306
3307 fn insert_with_autoindent_mode(
3308 &mut self,
3309 text: &str,
3310 autoindent_mode: Option<AutoindentMode>,
3311 window: &mut Window,
3312 cx: &mut Context<Self>,
3313 ) {
3314 if self.read_only(cx) {
3315 return;
3316 }
3317
3318 let text: Arc<str> = text.into();
3319 self.transact(window, cx, |this, window, cx| {
3320 let old_selections = this.selections.all_adjusted(cx);
3321 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3322 let anchors = {
3323 let snapshot = buffer.read(cx);
3324 old_selections
3325 .iter()
3326 .map(|s| {
3327 let anchor = snapshot.anchor_after(s.head());
3328 s.map(|_| anchor)
3329 })
3330 .collect::<Vec<_>>()
3331 };
3332 buffer.edit(
3333 old_selections
3334 .iter()
3335 .map(|s| (s.start..s.end, text.clone())),
3336 autoindent_mode,
3337 cx,
3338 );
3339 anchors
3340 });
3341
3342 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3343 s.select_anchors(selection_anchors);
3344 });
3345
3346 cx.notify();
3347 });
3348 }
3349
3350 fn trigger_completion_on_input(
3351 &mut self,
3352 text: &str,
3353 trigger_in_words: bool,
3354 window: &mut Window,
3355 cx: &mut Context<Self>,
3356 ) {
3357 if self.is_completion_trigger(text, trigger_in_words, cx) {
3358 self.show_completions(
3359 &ShowCompletions {
3360 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3361 },
3362 window,
3363 cx,
3364 );
3365 } else {
3366 self.hide_context_menu(window, cx);
3367 }
3368 }
3369
3370 fn is_completion_trigger(
3371 &self,
3372 text: &str,
3373 trigger_in_words: bool,
3374 cx: &mut Context<Self>,
3375 ) -> bool {
3376 let position = self.selections.newest_anchor().head();
3377 let multibuffer = self.buffer.read(cx);
3378 let Some(buffer) = position
3379 .buffer_id
3380 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3381 else {
3382 return false;
3383 };
3384
3385 if let Some(completion_provider) = &self.completion_provider {
3386 completion_provider.is_completion_trigger(
3387 &buffer,
3388 position.text_anchor,
3389 text,
3390 trigger_in_words,
3391 cx,
3392 )
3393 } else {
3394 false
3395 }
3396 }
3397
3398 /// If any empty selections is touching the start of its innermost containing autoclose
3399 /// region, expand it to select the brackets.
3400 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3401 let selections = self.selections.all::<usize>(cx);
3402 let buffer = self.buffer.read(cx).read(cx);
3403 let new_selections = self
3404 .selections_with_autoclose_regions(selections, &buffer)
3405 .map(|(mut selection, region)| {
3406 if !selection.is_empty() {
3407 return selection;
3408 }
3409
3410 if let Some(region) = region {
3411 let mut range = region.range.to_offset(&buffer);
3412 if selection.start == range.start && range.start >= region.pair.start.len() {
3413 range.start -= region.pair.start.len();
3414 if buffer.contains_str_at(range.start, ®ion.pair.start)
3415 && buffer.contains_str_at(range.end, ®ion.pair.end)
3416 {
3417 range.end += region.pair.end.len();
3418 selection.start = range.start;
3419 selection.end = range.end;
3420
3421 return selection;
3422 }
3423 }
3424 }
3425
3426 let always_treat_brackets_as_autoclosed = buffer
3427 .settings_at(selection.start, cx)
3428 .always_treat_brackets_as_autoclosed;
3429
3430 if !always_treat_brackets_as_autoclosed {
3431 return selection;
3432 }
3433
3434 if let Some(scope) = buffer.language_scope_at(selection.start) {
3435 for (pair, enabled) in scope.brackets() {
3436 if !enabled || !pair.close {
3437 continue;
3438 }
3439
3440 if buffer.contains_str_at(selection.start, &pair.end) {
3441 let pair_start_len = pair.start.len();
3442 if buffer.contains_str_at(
3443 selection.start.saturating_sub(pair_start_len),
3444 &pair.start,
3445 ) {
3446 selection.start -= pair_start_len;
3447 selection.end += pair.end.len();
3448
3449 return selection;
3450 }
3451 }
3452 }
3453 }
3454
3455 selection
3456 })
3457 .collect();
3458
3459 drop(buffer);
3460 self.change_selections(None, window, cx, |selections| {
3461 selections.select(new_selections)
3462 });
3463 }
3464
3465 /// Iterate the given selections, and for each one, find the smallest surrounding
3466 /// autoclose region. This uses the ordering of the selections and the autoclose
3467 /// regions to avoid repeated comparisons.
3468 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3469 &'a self,
3470 selections: impl IntoIterator<Item = Selection<D>>,
3471 buffer: &'a MultiBufferSnapshot,
3472 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3473 let mut i = 0;
3474 let mut regions = self.autoclose_regions.as_slice();
3475 selections.into_iter().map(move |selection| {
3476 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3477
3478 let mut enclosing = None;
3479 while let Some(pair_state) = regions.get(i) {
3480 if pair_state.range.end.to_offset(buffer) < range.start {
3481 regions = ®ions[i + 1..];
3482 i = 0;
3483 } else if pair_state.range.start.to_offset(buffer) > range.end {
3484 break;
3485 } else {
3486 if pair_state.selection_id == selection.id {
3487 enclosing = Some(pair_state);
3488 }
3489 i += 1;
3490 }
3491 }
3492
3493 (selection, enclosing)
3494 })
3495 }
3496
3497 /// Remove any autoclose regions that no longer contain their selection.
3498 fn invalidate_autoclose_regions(
3499 &mut self,
3500 mut selections: &[Selection<Anchor>],
3501 buffer: &MultiBufferSnapshot,
3502 ) {
3503 self.autoclose_regions.retain(|state| {
3504 let mut i = 0;
3505 while let Some(selection) = selections.get(i) {
3506 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3507 selections = &selections[1..];
3508 continue;
3509 }
3510 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3511 break;
3512 }
3513 if selection.id == state.selection_id {
3514 return true;
3515 } else {
3516 i += 1;
3517 }
3518 }
3519 false
3520 });
3521 }
3522
3523 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3524 let offset = position.to_offset(buffer);
3525 let (word_range, kind) = buffer.surrounding_word(offset, true);
3526 if offset > word_range.start && kind == Some(CharKind::Word) {
3527 Some(
3528 buffer
3529 .text_for_range(word_range.start..offset)
3530 .collect::<String>(),
3531 )
3532 } else {
3533 None
3534 }
3535 }
3536
3537 pub fn toggle_inlay_hints(
3538 &mut self,
3539 _: &ToggleInlayHints,
3540 _: &mut Window,
3541 cx: &mut Context<Self>,
3542 ) {
3543 self.refresh_inlay_hints(
3544 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3545 cx,
3546 );
3547 }
3548
3549 pub fn inlay_hints_enabled(&self) -> bool {
3550 self.inlay_hint_cache.enabled
3551 }
3552
3553 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3554 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3555 return;
3556 }
3557
3558 let reason_description = reason.description();
3559 let ignore_debounce = matches!(
3560 reason,
3561 InlayHintRefreshReason::SettingsChange(_)
3562 | InlayHintRefreshReason::Toggle(_)
3563 | InlayHintRefreshReason::ExcerptsRemoved(_)
3564 );
3565 let (invalidate_cache, required_languages) = match reason {
3566 InlayHintRefreshReason::Toggle(enabled) => {
3567 self.inlay_hint_cache.enabled = enabled;
3568 if enabled {
3569 (InvalidationStrategy::RefreshRequested, None)
3570 } else {
3571 self.inlay_hint_cache.clear();
3572 self.splice_inlays(
3573 &self
3574 .visible_inlay_hints(cx)
3575 .iter()
3576 .map(|inlay| inlay.id)
3577 .collect::<Vec<InlayId>>(),
3578 Vec::new(),
3579 cx,
3580 );
3581 return;
3582 }
3583 }
3584 InlayHintRefreshReason::SettingsChange(new_settings) => {
3585 match self.inlay_hint_cache.update_settings(
3586 &self.buffer,
3587 new_settings,
3588 self.visible_inlay_hints(cx),
3589 cx,
3590 ) {
3591 ControlFlow::Break(Some(InlaySplice {
3592 to_remove,
3593 to_insert,
3594 })) => {
3595 self.splice_inlays(&to_remove, to_insert, cx);
3596 return;
3597 }
3598 ControlFlow::Break(None) => return,
3599 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3600 }
3601 }
3602 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3603 if let Some(InlaySplice {
3604 to_remove,
3605 to_insert,
3606 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3607 {
3608 self.splice_inlays(&to_remove, to_insert, cx);
3609 }
3610 return;
3611 }
3612 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3613 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3614 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3615 }
3616 InlayHintRefreshReason::RefreshRequested => {
3617 (InvalidationStrategy::RefreshRequested, None)
3618 }
3619 };
3620
3621 if let Some(InlaySplice {
3622 to_remove,
3623 to_insert,
3624 }) = self.inlay_hint_cache.spawn_hint_refresh(
3625 reason_description,
3626 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3627 invalidate_cache,
3628 ignore_debounce,
3629 cx,
3630 ) {
3631 self.splice_inlays(&to_remove, to_insert, cx);
3632 }
3633 }
3634
3635 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3636 self.display_map
3637 .read(cx)
3638 .current_inlays()
3639 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3640 .cloned()
3641 .collect()
3642 }
3643
3644 pub fn excerpts_for_inlay_hints_query(
3645 &self,
3646 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3647 cx: &mut Context<Editor>,
3648 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3649 let Some(project) = self.project.as_ref() else {
3650 return HashMap::default();
3651 };
3652 let project = project.read(cx);
3653 let multi_buffer = self.buffer().read(cx);
3654 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3655 let multi_buffer_visible_start = self
3656 .scroll_manager
3657 .anchor()
3658 .anchor
3659 .to_point(&multi_buffer_snapshot);
3660 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3661 multi_buffer_visible_start
3662 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3663 Bias::Left,
3664 );
3665 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3666 multi_buffer_snapshot
3667 .range_to_buffer_ranges(multi_buffer_visible_range)
3668 .into_iter()
3669 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3670 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3671 let buffer_file = project::File::from_dyn(buffer.file())?;
3672 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3673 let worktree_entry = buffer_worktree
3674 .read(cx)
3675 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3676 if worktree_entry.is_ignored {
3677 return None;
3678 }
3679
3680 let language = buffer.language()?;
3681 if let Some(restrict_to_languages) = restrict_to_languages {
3682 if !restrict_to_languages.contains(language) {
3683 return None;
3684 }
3685 }
3686 Some((
3687 excerpt_id,
3688 (
3689 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3690 buffer.version().clone(),
3691 excerpt_visible_range,
3692 ),
3693 ))
3694 })
3695 .collect()
3696 }
3697
3698 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3699 TextLayoutDetails {
3700 text_system: window.text_system().clone(),
3701 editor_style: self.style.clone().unwrap(),
3702 rem_size: window.rem_size(),
3703 scroll_anchor: self.scroll_manager.anchor(),
3704 visible_rows: self.visible_line_count(),
3705 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3706 }
3707 }
3708
3709 pub fn splice_inlays(
3710 &self,
3711 to_remove: &[InlayId],
3712 to_insert: Vec<Inlay>,
3713 cx: &mut Context<Self>,
3714 ) {
3715 self.display_map.update(cx, |display_map, cx| {
3716 display_map.splice_inlays(to_remove, to_insert, cx)
3717 });
3718 cx.notify();
3719 }
3720
3721 fn trigger_on_type_formatting(
3722 &self,
3723 input: String,
3724 window: &mut Window,
3725 cx: &mut Context<Self>,
3726 ) -> Option<Task<Result<()>>> {
3727 if input.len() != 1 {
3728 return None;
3729 }
3730
3731 let project = self.project.as_ref()?;
3732 let position = self.selections.newest_anchor().head();
3733 let (buffer, buffer_position) = self
3734 .buffer
3735 .read(cx)
3736 .text_anchor_for_position(position, cx)?;
3737
3738 let settings = language_settings::language_settings(
3739 buffer
3740 .read(cx)
3741 .language_at(buffer_position)
3742 .map(|l| l.name()),
3743 buffer.read(cx).file(),
3744 cx,
3745 );
3746 if !settings.use_on_type_format {
3747 return None;
3748 }
3749
3750 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3751 // hence we do LSP request & edit on host side only — add formats to host's history.
3752 let push_to_lsp_host_history = true;
3753 // If this is not the host, append its history with new edits.
3754 let push_to_client_history = project.read(cx).is_via_collab();
3755
3756 let on_type_formatting = project.update(cx, |project, cx| {
3757 project.on_type_format(
3758 buffer.clone(),
3759 buffer_position,
3760 input,
3761 push_to_lsp_host_history,
3762 cx,
3763 )
3764 });
3765 Some(cx.spawn_in(window, |editor, mut cx| async move {
3766 if let Some(transaction) = on_type_formatting.await? {
3767 if push_to_client_history {
3768 buffer
3769 .update(&mut cx, |buffer, _| {
3770 buffer.push_transaction(transaction, Instant::now());
3771 })
3772 .ok();
3773 }
3774 editor.update(&mut cx, |editor, cx| {
3775 editor.refresh_document_highlights(cx);
3776 })?;
3777 }
3778 Ok(())
3779 }))
3780 }
3781
3782 pub fn show_completions(
3783 &mut self,
3784 options: &ShowCompletions,
3785 window: &mut Window,
3786 cx: &mut Context<Self>,
3787 ) {
3788 if self.pending_rename.is_some() {
3789 return;
3790 }
3791
3792 let Some(provider) = self.completion_provider.as_ref() else {
3793 return;
3794 };
3795
3796 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3797 return;
3798 }
3799
3800 let position = self.selections.newest_anchor().head();
3801 if position.diff_base_anchor.is_some() {
3802 return;
3803 }
3804 let (buffer, buffer_position) =
3805 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3806 output
3807 } else {
3808 return;
3809 };
3810 let show_completion_documentation = buffer
3811 .read(cx)
3812 .snapshot()
3813 .settings_at(buffer_position, cx)
3814 .show_completion_documentation;
3815
3816 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3817
3818 let trigger_kind = match &options.trigger {
3819 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3820 CompletionTriggerKind::TRIGGER_CHARACTER
3821 }
3822 _ => CompletionTriggerKind::INVOKED,
3823 };
3824 let completion_context = CompletionContext {
3825 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3826 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3827 Some(String::from(trigger))
3828 } else {
3829 None
3830 }
3831 }),
3832 trigger_kind,
3833 };
3834 let completions =
3835 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3836 let sort_completions = provider.sort_completions();
3837
3838 let id = post_inc(&mut self.next_completion_id);
3839 let task = cx.spawn_in(window, |editor, mut cx| {
3840 async move {
3841 editor.update(&mut cx, |this, _| {
3842 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3843 })?;
3844 let completions = completions.await.log_err();
3845 let menu = if let Some(completions) = completions {
3846 let mut menu = CompletionsMenu::new(
3847 id,
3848 sort_completions,
3849 show_completion_documentation,
3850 position,
3851 buffer.clone(),
3852 completions.into(),
3853 );
3854
3855 menu.filter(query.as_deref(), cx.background_executor().clone())
3856 .await;
3857
3858 menu.visible().then_some(menu)
3859 } else {
3860 None
3861 };
3862
3863 editor.update_in(&mut cx, |editor, window, cx| {
3864 match editor.context_menu.borrow().as_ref() {
3865 None => {}
3866 Some(CodeContextMenu::Completions(prev_menu)) => {
3867 if prev_menu.id > id {
3868 return;
3869 }
3870 }
3871 _ => return,
3872 }
3873
3874 if editor.focus_handle.is_focused(window) && menu.is_some() {
3875 let mut menu = menu.unwrap();
3876 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3877
3878 *editor.context_menu.borrow_mut() =
3879 Some(CodeContextMenu::Completions(menu));
3880
3881 if editor.show_inline_completions_in_menu(cx) {
3882 editor.update_visible_inline_completion(window, cx);
3883 } else {
3884 editor.discard_inline_completion(false, cx);
3885 }
3886
3887 cx.notify();
3888 } else if editor.completion_tasks.len() <= 1 {
3889 // If there are no more completion tasks and the last menu was
3890 // empty, we should hide it.
3891 let was_hidden = editor.hide_context_menu(window, cx).is_none();
3892 // If it was already hidden and we don't show inline
3893 // completions in the menu, we should also show the
3894 // inline-completion when available.
3895 if was_hidden && editor.show_inline_completions_in_menu(cx) {
3896 editor.update_visible_inline_completion(window, cx);
3897 }
3898 }
3899 })?;
3900
3901 Ok::<_, anyhow::Error>(())
3902 }
3903 .log_err()
3904 });
3905
3906 self.completion_tasks.push((id, task));
3907 }
3908
3909 pub fn confirm_completion(
3910 &mut self,
3911 action: &ConfirmCompletion,
3912 window: &mut Window,
3913 cx: &mut Context<Self>,
3914 ) -> Option<Task<Result<()>>> {
3915 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
3916 }
3917
3918 pub fn compose_completion(
3919 &mut self,
3920 action: &ComposeCompletion,
3921 window: &mut Window,
3922 cx: &mut Context<Self>,
3923 ) -> Option<Task<Result<()>>> {
3924 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
3925 }
3926
3927 fn do_completion(
3928 &mut self,
3929 item_ix: Option<usize>,
3930 intent: CompletionIntent,
3931 window: &mut Window,
3932 cx: &mut Context<Editor>,
3933 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3934 use language::ToOffset as _;
3935
3936 let completions_menu =
3937 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
3938 menu
3939 } else {
3940 return None;
3941 };
3942
3943 let entries = completions_menu.entries.borrow();
3944 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
3945 if self.show_inline_completions_in_menu(cx) {
3946 self.discard_inline_completion(true, cx);
3947 }
3948 let candidate_id = mat.candidate_id;
3949 drop(entries);
3950
3951 let buffer_handle = completions_menu.buffer;
3952 let completion = completions_menu
3953 .completions
3954 .borrow()
3955 .get(candidate_id)?
3956 .clone();
3957 cx.stop_propagation();
3958
3959 let snippet;
3960 let text;
3961
3962 if completion.is_snippet() {
3963 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3964 text = snippet.as_ref().unwrap().text.clone();
3965 } else {
3966 snippet = None;
3967 text = completion.new_text.clone();
3968 };
3969 let selections = self.selections.all::<usize>(cx);
3970 let buffer = buffer_handle.read(cx);
3971 let old_range = completion.old_range.to_offset(buffer);
3972 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3973
3974 let newest_selection = self.selections.newest_anchor();
3975 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3976 return None;
3977 }
3978
3979 let lookbehind = newest_selection
3980 .start
3981 .text_anchor
3982 .to_offset(buffer)
3983 .saturating_sub(old_range.start);
3984 let lookahead = old_range
3985 .end
3986 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3987 let mut common_prefix_len = old_text
3988 .bytes()
3989 .zip(text.bytes())
3990 .take_while(|(a, b)| a == b)
3991 .count();
3992
3993 let snapshot = self.buffer.read(cx).snapshot(cx);
3994 let mut range_to_replace: Option<Range<isize>> = None;
3995 let mut ranges = Vec::new();
3996 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3997 for selection in &selections {
3998 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3999 let start = selection.start.saturating_sub(lookbehind);
4000 let end = selection.end + lookahead;
4001 if selection.id == newest_selection.id {
4002 range_to_replace = Some(
4003 ((start + common_prefix_len) as isize - selection.start as isize)
4004 ..(end as isize - selection.start as isize),
4005 );
4006 }
4007 ranges.push(start + common_prefix_len..end);
4008 } else {
4009 common_prefix_len = 0;
4010 ranges.clear();
4011 ranges.extend(selections.iter().map(|s| {
4012 if s.id == newest_selection.id {
4013 range_to_replace = Some(
4014 old_range.start.to_offset_utf16(&snapshot).0 as isize
4015 - selection.start as isize
4016 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4017 - selection.start as isize,
4018 );
4019 old_range.clone()
4020 } else {
4021 s.start..s.end
4022 }
4023 }));
4024 break;
4025 }
4026 if !self.linked_edit_ranges.is_empty() {
4027 let start_anchor = snapshot.anchor_before(selection.head());
4028 let end_anchor = snapshot.anchor_after(selection.tail());
4029 if let Some(ranges) = self
4030 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4031 {
4032 for (buffer, edits) in ranges {
4033 linked_edits.entry(buffer.clone()).or_default().extend(
4034 edits
4035 .into_iter()
4036 .map(|range| (range, text[common_prefix_len..].to_owned())),
4037 );
4038 }
4039 }
4040 }
4041 }
4042 let text = &text[common_prefix_len..];
4043
4044 cx.emit(EditorEvent::InputHandled {
4045 utf16_range_to_replace: range_to_replace,
4046 text: text.into(),
4047 });
4048
4049 self.transact(window, cx, |this, window, cx| {
4050 if let Some(mut snippet) = snippet {
4051 snippet.text = text.to_string();
4052 for tabstop in snippet
4053 .tabstops
4054 .iter_mut()
4055 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4056 {
4057 tabstop.start -= common_prefix_len as isize;
4058 tabstop.end -= common_prefix_len as isize;
4059 }
4060
4061 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4062 } else {
4063 this.buffer.update(cx, |buffer, cx| {
4064 buffer.edit(
4065 ranges.iter().map(|range| (range.clone(), text)),
4066 this.autoindent_mode.clone(),
4067 cx,
4068 );
4069 });
4070 }
4071 for (buffer, edits) in linked_edits {
4072 buffer.update(cx, |buffer, cx| {
4073 let snapshot = buffer.snapshot();
4074 let edits = edits
4075 .into_iter()
4076 .map(|(range, text)| {
4077 use text::ToPoint as TP;
4078 let end_point = TP::to_point(&range.end, &snapshot);
4079 let start_point = TP::to_point(&range.start, &snapshot);
4080 (start_point..end_point, text)
4081 })
4082 .sorted_by_key(|(range, _)| range.start)
4083 .collect::<Vec<_>>();
4084 buffer.edit(edits, None, cx);
4085 })
4086 }
4087
4088 this.refresh_inline_completion(true, false, window, cx);
4089 });
4090
4091 let show_new_completions_on_confirm = completion
4092 .confirm
4093 .as_ref()
4094 .map_or(false, |confirm| confirm(intent, window, cx));
4095 if show_new_completions_on_confirm {
4096 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4097 }
4098
4099 let provider = self.completion_provider.as_ref()?;
4100 drop(completion);
4101 let apply_edits = provider.apply_additional_edits_for_completion(
4102 buffer_handle,
4103 completions_menu.completions.clone(),
4104 candidate_id,
4105 true,
4106 cx,
4107 );
4108
4109 let editor_settings = EditorSettings::get_global(cx);
4110 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4111 // After the code completion is finished, users often want to know what signatures are needed.
4112 // so we should automatically call signature_help
4113 self.show_signature_help(&ShowSignatureHelp, window, cx);
4114 }
4115
4116 Some(cx.foreground_executor().spawn(async move {
4117 apply_edits.await?;
4118 Ok(())
4119 }))
4120 }
4121
4122 pub fn toggle_code_actions(
4123 &mut self,
4124 action: &ToggleCodeActions,
4125 window: &mut Window,
4126 cx: &mut Context<Self>,
4127 ) {
4128 let mut context_menu = self.context_menu.borrow_mut();
4129 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4130 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4131 // Toggle if we're selecting the same one
4132 *context_menu = None;
4133 cx.notify();
4134 return;
4135 } else {
4136 // Otherwise, clear it and start a new one
4137 *context_menu = None;
4138 cx.notify();
4139 }
4140 }
4141 drop(context_menu);
4142 let snapshot = self.snapshot(window, cx);
4143 let deployed_from_indicator = action.deployed_from_indicator;
4144 let mut task = self.code_actions_task.take();
4145 let action = action.clone();
4146 cx.spawn_in(window, |editor, mut cx| async move {
4147 while let Some(prev_task) = task {
4148 prev_task.await.log_err();
4149 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4150 }
4151
4152 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4153 if editor.focus_handle.is_focused(window) {
4154 let multibuffer_point = action
4155 .deployed_from_indicator
4156 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4157 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4158 let (buffer, buffer_row) = snapshot
4159 .buffer_snapshot
4160 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4161 .and_then(|(buffer_snapshot, range)| {
4162 editor
4163 .buffer
4164 .read(cx)
4165 .buffer(buffer_snapshot.remote_id())
4166 .map(|buffer| (buffer, range.start.row))
4167 })?;
4168 let (_, code_actions) = editor
4169 .available_code_actions
4170 .clone()
4171 .and_then(|(location, code_actions)| {
4172 let snapshot = location.buffer.read(cx).snapshot();
4173 let point_range = location.range.to_point(&snapshot);
4174 let point_range = point_range.start.row..=point_range.end.row;
4175 if point_range.contains(&buffer_row) {
4176 Some((location, code_actions))
4177 } else {
4178 None
4179 }
4180 })
4181 .unzip();
4182 let buffer_id = buffer.read(cx).remote_id();
4183 let tasks = editor
4184 .tasks
4185 .get(&(buffer_id, buffer_row))
4186 .map(|t| Arc::new(t.to_owned()));
4187 if tasks.is_none() && code_actions.is_none() {
4188 return None;
4189 }
4190
4191 editor.completion_tasks.clear();
4192 editor.discard_inline_completion(false, cx);
4193 let task_context =
4194 tasks
4195 .as_ref()
4196 .zip(editor.project.clone())
4197 .map(|(tasks, project)| {
4198 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4199 });
4200
4201 Some(cx.spawn_in(window, |editor, mut cx| async move {
4202 let task_context = match task_context {
4203 Some(task_context) => task_context.await,
4204 None => None,
4205 };
4206 let resolved_tasks =
4207 tasks.zip(task_context).map(|(tasks, task_context)| {
4208 Rc::new(ResolvedTasks {
4209 templates: tasks.resolve(&task_context).collect(),
4210 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4211 multibuffer_point.row,
4212 tasks.column,
4213 )),
4214 })
4215 });
4216 let spawn_straight_away = resolved_tasks
4217 .as_ref()
4218 .map_or(false, |tasks| tasks.templates.len() == 1)
4219 && code_actions
4220 .as_ref()
4221 .map_or(true, |actions| actions.is_empty());
4222 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4223 *editor.context_menu.borrow_mut() =
4224 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4225 buffer,
4226 actions: CodeActionContents {
4227 tasks: resolved_tasks,
4228 actions: code_actions,
4229 },
4230 selected_item: Default::default(),
4231 scroll_handle: UniformListScrollHandle::default(),
4232 deployed_from_indicator,
4233 }));
4234 if spawn_straight_away {
4235 if let Some(task) = editor.confirm_code_action(
4236 &ConfirmCodeAction { item_ix: Some(0) },
4237 window,
4238 cx,
4239 ) {
4240 cx.notify();
4241 return task;
4242 }
4243 }
4244 cx.notify();
4245 Task::ready(Ok(()))
4246 }) {
4247 task.await
4248 } else {
4249 Ok(())
4250 }
4251 }))
4252 } else {
4253 Some(Task::ready(Ok(())))
4254 }
4255 })?;
4256 if let Some(task) = spawned_test_task {
4257 task.await?;
4258 }
4259
4260 Ok::<_, anyhow::Error>(())
4261 })
4262 .detach_and_log_err(cx);
4263 }
4264
4265 pub fn confirm_code_action(
4266 &mut self,
4267 action: &ConfirmCodeAction,
4268 window: &mut Window,
4269 cx: &mut Context<Self>,
4270 ) -> Option<Task<Result<()>>> {
4271 let actions_menu =
4272 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4273 menu
4274 } else {
4275 return None;
4276 };
4277 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4278 let action = actions_menu.actions.get(action_ix)?;
4279 let title = action.label();
4280 let buffer = actions_menu.buffer;
4281 let workspace = self.workspace()?;
4282
4283 match action {
4284 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4285 workspace.update(cx, |workspace, cx| {
4286 workspace::tasks::schedule_resolved_task(
4287 workspace,
4288 task_source_kind,
4289 resolved_task,
4290 false,
4291 cx,
4292 );
4293
4294 Some(Task::ready(Ok(())))
4295 })
4296 }
4297 CodeActionsItem::CodeAction {
4298 excerpt_id,
4299 action,
4300 provider,
4301 } => {
4302 let apply_code_action =
4303 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4304 let workspace = workspace.downgrade();
4305 Some(cx.spawn_in(window, |editor, cx| async move {
4306 let project_transaction = apply_code_action.await?;
4307 Self::open_project_transaction(
4308 &editor,
4309 workspace,
4310 project_transaction,
4311 title,
4312 cx,
4313 )
4314 .await
4315 }))
4316 }
4317 }
4318 }
4319
4320 pub async fn open_project_transaction(
4321 this: &WeakEntity<Editor>,
4322 workspace: WeakEntity<Workspace>,
4323 transaction: ProjectTransaction,
4324 title: String,
4325 mut cx: AsyncWindowContext,
4326 ) -> Result<()> {
4327 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4328 cx.update(|_, cx| {
4329 entries.sort_unstable_by_key(|(buffer, _)| {
4330 buffer.read(cx).file().map(|f| f.path().clone())
4331 });
4332 })?;
4333
4334 // If the project transaction's edits are all contained within this editor, then
4335 // avoid opening a new editor to display them.
4336
4337 if let Some((buffer, transaction)) = entries.first() {
4338 if entries.len() == 1 {
4339 let excerpt = this.update(&mut cx, |editor, cx| {
4340 editor
4341 .buffer()
4342 .read(cx)
4343 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4344 })?;
4345 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4346 if excerpted_buffer == *buffer {
4347 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4348 let excerpt_range = excerpt_range.to_offset(buffer);
4349 buffer
4350 .edited_ranges_for_transaction::<usize>(transaction)
4351 .all(|range| {
4352 excerpt_range.start <= range.start
4353 && excerpt_range.end >= range.end
4354 })
4355 })?;
4356
4357 if all_edits_within_excerpt {
4358 return Ok(());
4359 }
4360 }
4361 }
4362 }
4363 } else {
4364 return Ok(());
4365 }
4366
4367 let mut ranges_to_highlight = Vec::new();
4368 let excerpt_buffer = cx.new(|cx| {
4369 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4370 for (buffer_handle, transaction) in &entries {
4371 let buffer = buffer_handle.read(cx);
4372 ranges_to_highlight.extend(
4373 multibuffer.push_excerpts_with_context_lines(
4374 buffer_handle.clone(),
4375 buffer
4376 .edited_ranges_for_transaction::<usize>(transaction)
4377 .collect(),
4378 DEFAULT_MULTIBUFFER_CONTEXT,
4379 cx,
4380 ),
4381 );
4382 }
4383 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4384 multibuffer
4385 })?;
4386
4387 workspace.update_in(&mut cx, |workspace, window, cx| {
4388 let project = workspace.project().clone();
4389 let editor = cx
4390 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4391 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4392 editor.update(cx, |editor, cx| {
4393 editor.highlight_background::<Self>(
4394 &ranges_to_highlight,
4395 |theme| theme.editor_highlighted_line_background,
4396 cx,
4397 );
4398 });
4399 })?;
4400
4401 Ok(())
4402 }
4403
4404 pub fn clear_code_action_providers(&mut self) {
4405 self.code_action_providers.clear();
4406 self.available_code_actions.take();
4407 }
4408
4409 pub fn add_code_action_provider(
4410 &mut self,
4411 provider: Rc<dyn CodeActionProvider>,
4412 window: &mut Window,
4413 cx: &mut Context<Self>,
4414 ) {
4415 if self
4416 .code_action_providers
4417 .iter()
4418 .any(|existing_provider| existing_provider.id() == provider.id())
4419 {
4420 return;
4421 }
4422
4423 self.code_action_providers.push(provider);
4424 self.refresh_code_actions(window, cx);
4425 }
4426
4427 pub fn remove_code_action_provider(
4428 &mut self,
4429 id: Arc<str>,
4430 window: &mut Window,
4431 cx: &mut Context<Self>,
4432 ) {
4433 self.code_action_providers
4434 .retain(|provider| provider.id() != id);
4435 self.refresh_code_actions(window, cx);
4436 }
4437
4438 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4439 let buffer = self.buffer.read(cx);
4440 let newest_selection = self.selections.newest_anchor().clone();
4441 if newest_selection.head().diff_base_anchor.is_some() {
4442 return None;
4443 }
4444 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4445 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4446 if start_buffer != end_buffer {
4447 return None;
4448 }
4449
4450 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4451 cx.background_executor()
4452 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4453 .await;
4454
4455 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4456 let providers = this.code_action_providers.clone();
4457 let tasks = this
4458 .code_action_providers
4459 .iter()
4460 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4461 .collect::<Vec<_>>();
4462 (providers, tasks)
4463 })?;
4464
4465 let mut actions = Vec::new();
4466 for (provider, provider_actions) in
4467 providers.into_iter().zip(future::join_all(tasks).await)
4468 {
4469 if let Some(provider_actions) = provider_actions.log_err() {
4470 actions.extend(provider_actions.into_iter().map(|action| {
4471 AvailableCodeAction {
4472 excerpt_id: newest_selection.start.excerpt_id,
4473 action,
4474 provider: provider.clone(),
4475 }
4476 }));
4477 }
4478 }
4479
4480 this.update(&mut cx, |this, cx| {
4481 this.available_code_actions = if actions.is_empty() {
4482 None
4483 } else {
4484 Some((
4485 Location {
4486 buffer: start_buffer,
4487 range: start..end,
4488 },
4489 actions.into(),
4490 ))
4491 };
4492 cx.notify();
4493 })
4494 }));
4495 None
4496 }
4497
4498 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4499 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4500 self.show_git_blame_inline = false;
4501
4502 self.show_git_blame_inline_delay_task =
4503 Some(cx.spawn_in(window, |this, mut cx| async move {
4504 cx.background_executor().timer(delay).await;
4505
4506 this.update(&mut cx, |this, cx| {
4507 this.show_git_blame_inline = true;
4508 cx.notify();
4509 })
4510 .log_err();
4511 }));
4512 }
4513 }
4514
4515 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4516 if self.pending_rename.is_some() {
4517 return None;
4518 }
4519
4520 let provider = self.semantics_provider.clone()?;
4521 let buffer = self.buffer.read(cx);
4522 let newest_selection = self.selections.newest_anchor().clone();
4523 let cursor_position = newest_selection.head();
4524 let (cursor_buffer, cursor_buffer_position) =
4525 buffer.text_anchor_for_position(cursor_position, cx)?;
4526 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4527 if cursor_buffer != tail_buffer {
4528 return None;
4529 }
4530 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4531 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4532 cx.background_executor()
4533 .timer(Duration::from_millis(debounce))
4534 .await;
4535
4536 let highlights = if let Some(highlights) = cx
4537 .update(|cx| {
4538 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4539 })
4540 .ok()
4541 .flatten()
4542 {
4543 highlights.await.log_err()
4544 } else {
4545 None
4546 };
4547
4548 if let Some(highlights) = highlights {
4549 this.update(&mut cx, |this, cx| {
4550 if this.pending_rename.is_some() {
4551 return;
4552 }
4553
4554 let buffer_id = cursor_position.buffer_id;
4555 let buffer = this.buffer.read(cx);
4556 if !buffer
4557 .text_anchor_for_position(cursor_position, cx)
4558 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4559 {
4560 return;
4561 }
4562
4563 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4564 let mut write_ranges = Vec::new();
4565 let mut read_ranges = Vec::new();
4566 for highlight in highlights {
4567 for (excerpt_id, excerpt_range) in
4568 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4569 {
4570 let start = highlight
4571 .range
4572 .start
4573 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4574 let end = highlight
4575 .range
4576 .end
4577 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4578 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4579 continue;
4580 }
4581
4582 let range = Anchor {
4583 buffer_id,
4584 excerpt_id,
4585 text_anchor: start,
4586 diff_base_anchor: None,
4587 }..Anchor {
4588 buffer_id,
4589 excerpt_id,
4590 text_anchor: end,
4591 diff_base_anchor: None,
4592 };
4593 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4594 write_ranges.push(range);
4595 } else {
4596 read_ranges.push(range);
4597 }
4598 }
4599 }
4600
4601 this.highlight_background::<DocumentHighlightRead>(
4602 &read_ranges,
4603 |theme| theme.editor_document_highlight_read_background,
4604 cx,
4605 );
4606 this.highlight_background::<DocumentHighlightWrite>(
4607 &write_ranges,
4608 |theme| theme.editor_document_highlight_write_background,
4609 cx,
4610 );
4611 cx.notify();
4612 })
4613 .log_err();
4614 }
4615 }));
4616 None
4617 }
4618
4619 pub fn refresh_inline_completion(
4620 &mut self,
4621 debounce: bool,
4622 user_requested: bool,
4623 window: &mut Window,
4624 cx: &mut Context<Self>,
4625 ) -> Option<()> {
4626 let provider = self.inline_completion_provider()?;
4627 let cursor = self.selections.newest_anchor().head();
4628 let (buffer, cursor_buffer_position) =
4629 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4630
4631 if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4632 self.discard_inline_completion(false, cx);
4633 return None;
4634 }
4635
4636 if !user_requested
4637 && (!self.show_inline_completions
4638 || !self.should_show_inline_completions_in_buffer(
4639 &buffer,
4640 cursor_buffer_position,
4641 cx,
4642 )
4643 || !self.is_focused(window)
4644 || buffer.read(cx).is_empty())
4645 {
4646 self.discard_inline_completion(false, cx);
4647 return None;
4648 }
4649
4650 self.update_visible_inline_completion(window, cx);
4651 provider.refresh(
4652 self.project.clone(),
4653 buffer,
4654 cursor_buffer_position,
4655 debounce,
4656 cx,
4657 );
4658 Some(())
4659 }
4660
4661 pub fn should_show_inline_completions(&self, cx: &App) -> bool {
4662 let cursor = self.selections.newest_anchor().head();
4663 if let Some((buffer, cursor_position)) =
4664 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4665 {
4666 self.should_show_inline_completions_in_buffer(&buffer, cursor_position, cx)
4667 } else {
4668 false
4669 }
4670 }
4671
4672 fn inline_completion_requires_modifier(&self, cx: &App) -> bool {
4673 let cursor = self.selections.newest_anchor().head();
4674
4675 self.buffer
4676 .read(cx)
4677 .text_anchor_for_position(cursor, cx)
4678 .map(|(buffer, _)| {
4679 all_language_settings(buffer.read(cx).file(), cx).inline_completions_preview_mode()
4680 == InlineCompletionPreviewMode::WhenHoldingModifier
4681 })
4682 .unwrap_or(false)
4683 }
4684
4685 fn should_show_inline_completions_in_buffer(
4686 &self,
4687 buffer: &Entity<Buffer>,
4688 buffer_position: language::Anchor,
4689 cx: &App,
4690 ) -> bool {
4691 if !self.snippet_stack.is_empty() {
4692 return false;
4693 }
4694
4695 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
4696 return false;
4697 }
4698
4699 if let Some(show_inline_completions) = self.show_inline_completions_override {
4700 show_inline_completions
4701 } else {
4702 let buffer = buffer.read(cx);
4703 self.mode == EditorMode::Full
4704 && language_settings(
4705 buffer.language_at(buffer_position).map(|l| l.name()),
4706 buffer.file(),
4707 cx,
4708 )
4709 .show_inline_completions
4710 }
4711 }
4712
4713 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
4714 let cursor = self.selections.newest_anchor().head();
4715 if let Some((buffer, cursor_position)) =
4716 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4717 {
4718 self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
4719 } else {
4720 false
4721 }
4722 }
4723
4724 fn inline_completions_enabled_in_buffer(
4725 &self,
4726 buffer: &Entity<Buffer>,
4727 buffer_position: language::Anchor,
4728 cx: &App,
4729 ) -> bool {
4730 maybe!({
4731 let provider = self.inline_completion_provider()?;
4732 if !provider.is_enabled(&buffer, buffer_position, cx) {
4733 return Some(false);
4734 }
4735 let buffer = buffer.read(cx);
4736 let Some(file) = buffer.file() else {
4737 return Some(true);
4738 };
4739 let settings = all_language_settings(Some(file), cx);
4740 Some(settings.inline_completions_enabled_for_path(file.path()))
4741 })
4742 .unwrap_or(false)
4743 }
4744
4745 fn cycle_inline_completion(
4746 &mut self,
4747 direction: Direction,
4748 window: &mut Window,
4749 cx: &mut Context<Self>,
4750 ) -> Option<()> {
4751 let provider = self.inline_completion_provider()?;
4752 let cursor = self.selections.newest_anchor().head();
4753 let (buffer, cursor_buffer_position) =
4754 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4755 if !self.show_inline_completions
4756 || !self.should_show_inline_completions_in_buffer(&buffer, cursor_buffer_position, cx)
4757 {
4758 return None;
4759 }
4760
4761 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4762 self.update_visible_inline_completion(window, cx);
4763
4764 Some(())
4765 }
4766
4767 pub fn show_inline_completion(
4768 &mut self,
4769 _: &ShowInlineCompletion,
4770 window: &mut Window,
4771 cx: &mut Context<Self>,
4772 ) {
4773 if !self.has_active_inline_completion() {
4774 self.refresh_inline_completion(false, true, window, cx);
4775 return;
4776 }
4777
4778 self.update_visible_inline_completion(window, cx);
4779 }
4780
4781 pub fn display_cursor_names(
4782 &mut self,
4783 _: &DisplayCursorNames,
4784 window: &mut Window,
4785 cx: &mut Context<Self>,
4786 ) {
4787 self.show_cursor_names(window, cx);
4788 }
4789
4790 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4791 self.show_cursor_names = true;
4792 cx.notify();
4793 cx.spawn_in(window, |this, mut cx| async move {
4794 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4795 this.update(&mut cx, |this, cx| {
4796 this.show_cursor_names = false;
4797 cx.notify()
4798 })
4799 .ok()
4800 })
4801 .detach();
4802 }
4803
4804 pub fn next_inline_completion(
4805 &mut self,
4806 _: &NextInlineCompletion,
4807 window: &mut Window,
4808 cx: &mut Context<Self>,
4809 ) {
4810 if self.has_active_inline_completion() {
4811 self.cycle_inline_completion(Direction::Next, window, cx);
4812 } else {
4813 let is_copilot_disabled = self
4814 .refresh_inline_completion(false, true, window, cx)
4815 .is_none();
4816 if is_copilot_disabled {
4817 cx.propagate();
4818 }
4819 }
4820 }
4821
4822 pub fn previous_inline_completion(
4823 &mut self,
4824 _: &PreviousInlineCompletion,
4825 window: &mut Window,
4826 cx: &mut Context<Self>,
4827 ) {
4828 if self.has_active_inline_completion() {
4829 self.cycle_inline_completion(Direction::Prev, window, cx);
4830 } else {
4831 let is_copilot_disabled = self
4832 .refresh_inline_completion(false, true, window, cx)
4833 .is_none();
4834 if is_copilot_disabled {
4835 cx.propagate();
4836 }
4837 }
4838 }
4839
4840 pub fn accept_inline_completion(
4841 &mut self,
4842 _: &AcceptInlineCompletion,
4843 window: &mut Window,
4844 cx: &mut Context<Self>,
4845 ) {
4846 let buffer = self.buffer.read(cx);
4847 let snapshot = buffer.snapshot(cx);
4848 let selection = self.selections.newest_adjusted(cx);
4849 let cursor = selection.head();
4850 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
4851 let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
4852 if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
4853 {
4854 if cursor.column < suggested_indent.len
4855 && cursor.column <= current_indent.len
4856 && current_indent.len <= suggested_indent.len
4857 {
4858 self.tab(&Default::default(), window, cx);
4859 return;
4860 }
4861 }
4862
4863 if self.show_inline_completions_in_menu(cx) {
4864 self.hide_context_menu(window, cx);
4865 }
4866
4867 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4868 return;
4869 };
4870
4871 self.report_inline_completion_event(true, cx);
4872
4873 match &active_inline_completion.completion {
4874 InlineCompletion::Move { target, .. } => {
4875 let target = *target;
4876 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
4877 selections.select_anchor_ranges([target..target]);
4878 });
4879 }
4880 InlineCompletion::Edit { edits, .. } => {
4881 if let Some(provider) = self.inline_completion_provider() {
4882 provider.accept(cx);
4883 }
4884
4885 let snapshot = self.buffer.read(cx).snapshot(cx);
4886 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4887
4888 self.buffer.update(cx, |buffer, cx| {
4889 buffer.edit(edits.iter().cloned(), None, cx)
4890 });
4891
4892 self.change_selections(None, window, cx, |s| {
4893 s.select_anchor_ranges([last_edit_end..last_edit_end])
4894 });
4895
4896 self.update_visible_inline_completion(window, cx);
4897 if self.active_inline_completion.is_none() {
4898 self.refresh_inline_completion(true, true, window, cx);
4899 }
4900
4901 cx.notify();
4902 }
4903 }
4904 }
4905
4906 pub fn accept_partial_inline_completion(
4907 &mut self,
4908 _: &AcceptPartialInlineCompletion,
4909 window: &mut Window,
4910 cx: &mut Context<Self>,
4911 ) {
4912 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4913 return;
4914 };
4915 if self.selections.count() != 1 {
4916 return;
4917 }
4918
4919 self.report_inline_completion_event(true, cx);
4920
4921 match &active_inline_completion.completion {
4922 InlineCompletion::Move { target, .. } => {
4923 let target = *target;
4924 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
4925 selections.select_anchor_ranges([target..target]);
4926 });
4927 }
4928 InlineCompletion::Edit { edits, .. } => {
4929 // Find an insertion that starts at the cursor position.
4930 let snapshot = self.buffer.read(cx).snapshot(cx);
4931 let cursor_offset = self.selections.newest::<usize>(cx).head();
4932 let insertion = edits.iter().find_map(|(range, text)| {
4933 let range = range.to_offset(&snapshot);
4934 if range.is_empty() && range.start == cursor_offset {
4935 Some(text)
4936 } else {
4937 None
4938 }
4939 });
4940
4941 if let Some(text) = insertion {
4942 let mut partial_completion = text
4943 .chars()
4944 .by_ref()
4945 .take_while(|c| c.is_alphabetic())
4946 .collect::<String>();
4947 if partial_completion.is_empty() {
4948 partial_completion = text
4949 .chars()
4950 .by_ref()
4951 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4952 .collect::<String>();
4953 }
4954
4955 cx.emit(EditorEvent::InputHandled {
4956 utf16_range_to_replace: None,
4957 text: partial_completion.clone().into(),
4958 });
4959
4960 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
4961
4962 self.refresh_inline_completion(true, true, window, cx);
4963 cx.notify();
4964 } else {
4965 self.accept_inline_completion(&Default::default(), window, cx);
4966 }
4967 }
4968 }
4969 }
4970
4971 fn discard_inline_completion(
4972 &mut self,
4973 should_report_inline_completion_event: bool,
4974 cx: &mut Context<Self>,
4975 ) -> bool {
4976 if should_report_inline_completion_event {
4977 self.report_inline_completion_event(false, cx);
4978 }
4979
4980 if let Some(provider) = self.inline_completion_provider() {
4981 provider.discard(cx);
4982 }
4983
4984 self.take_active_inline_completion(cx)
4985 }
4986
4987 fn report_inline_completion_event(&self, accepted: bool, cx: &App) {
4988 let Some(provider) = self.inline_completion_provider() else {
4989 return;
4990 };
4991
4992 let Some((_, buffer, _)) = self
4993 .buffer
4994 .read(cx)
4995 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4996 else {
4997 return;
4998 };
4999
5000 let extension = buffer
5001 .read(cx)
5002 .file()
5003 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5004
5005 let event_type = match accepted {
5006 true => "Edit Prediction Accepted",
5007 false => "Edit Prediction Discarded",
5008 };
5009 telemetry::event!(
5010 event_type,
5011 provider = provider.name(),
5012 suggestion_accepted = accepted,
5013 file_extension = extension,
5014 );
5015 }
5016
5017 pub fn has_active_inline_completion(&self) -> bool {
5018 self.active_inline_completion.is_some()
5019 }
5020
5021 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5022 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5023 return false;
5024 };
5025
5026 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5027 self.clear_highlights::<InlineCompletionHighlight>(cx);
5028 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5029 true
5030 }
5031
5032 /// Returns true when we're displaying the inline completion popover below the cursor
5033 /// like we are not previewing and the LSP autocomplete menu is visible
5034 /// or we are in `when_holding_modifier` mode.
5035 pub fn inline_completion_visible_in_cursor_popover(
5036 &self,
5037 has_completion: bool,
5038 cx: &App,
5039 ) -> bool {
5040 if self.previewing_inline_completion
5041 || !self.show_inline_completions_in_menu(cx)
5042 || !self.should_show_inline_completions(cx)
5043 {
5044 return false;
5045 }
5046
5047 if self.has_visible_completions_menu() {
5048 return true;
5049 }
5050
5051 has_completion && self.inline_completion_requires_modifier(cx)
5052 }
5053
5054 fn update_inline_completion_preview(
5055 &mut self,
5056 modifiers: &Modifiers,
5057 window: &mut Window,
5058 cx: &mut Context<Self>,
5059 ) {
5060 if !self.show_inline_completions_in_menu(cx) {
5061 return;
5062 }
5063
5064 self.previewing_inline_completion = modifiers.alt;
5065 self.update_visible_inline_completion(window, cx);
5066 cx.notify();
5067 }
5068
5069 fn update_visible_inline_completion(
5070 &mut self,
5071 _window: &mut Window,
5072 cx: &mut Context<Self>,
5073 ) -> Option<()> {
5074 let selection = self.selections.newest_anchor();
5075 let cursor = selection.head();
5076 let multibuffer = self.buffer.read(cx).snapshot(cx);
5077 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5078 let excerpt_id = cursor.excerpt_id;
5079
5080 let show_in_menu = self.show_inline_completions_in_menu(cx);
5081 let completions_menu_has_precedence = !show_in_menu
5082 && (self.context_menu.borrow().is_some()
5083 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5084 if completions_menu_has_precedence
5085 || !offset_selection.is_empty()
5086 || !self.show_inline_completions
5087 || self
5088 .active_inline_completion
5089 .as_ref()
5090 .map_or(false, |completion| {
5091 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5092 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5093 !invalidation_range.contains(&offset_selection.head())
5094 })
5095 {
5096 self.discard_inline_completion(false, cx);
5097 return None;
5098 }
5099
5100 self.take_active_inline_completion(cx);
5101 let provider = self.inline_completion_provider()?;
5102
5103 let (buffer, cursor_buffer_position) =
5104 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5105
5106 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5107 let edits = inline_completion
5108 .edits
5109 .into_iter()
5110 .flat_map(|(range, new_text)| {
5111 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5112 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5113 Some((start..end, new_text))
5114 })
5115 .collect::<Vec<_>>();
5116 if edits.is_empty() {
5117 return None;
5118 }
5119
5120 let first_edit_start = edits.first().unwrap().0.start;
5121 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5122 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5123
5124 let last_edit_end = edits.last().unwrap().0.end;
5125 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5126 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5127
5128 let cursor_row = cursor.to_point(&multibuffer).row;
5129
5130 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5131
5132 let mut inlay_ids = Vec::new();
5133 let invalidation_row_range;
5134 let move_invalidation_row_range = if cursor_row < edit_start_row {
5135 Some(cursor_row..edit_end_row)
5136 } else if cursor_row > edit_end_row {
5137 Some(edit_start_row..cursor_row)
5138 } else {
5139 None
5140 };
5141 let completion = if let Some(move_invalidation_row_range) = move_invalidation_row_range {
5142 invalidation_row_range = move_invalidation_row_range;
5143 let target = first_edit_start;
5144 let target_point = text::ToPoint::to_point(&target.text_anchor, &snapshot);
5145 // TODO: Base this off of TreeSitter or word boundaries?
5146 let target_excerpt_begin = snapshot.anchor_before(snapshot.clip_point(
5147 Point::new(target_point.row, target_point.column.saturating_sub(20)),
5148 Bias::Left,
5149 ));
5150 let target_excerpt_end = snapshot.anchor_after(snapshot.clip_point(
5151 Point::new(target_point.row, target_point.column + 20),
5152 Bias::Right,
5153 ));
5154 let range_around_target = target_excerpt_begin..target_excerpt_end;
5155 InlineCompletion::Move {
5156 target,
5157 range_around_target,
5158 snapshot,
5159 }
5160 } else {
5161 if !self.inline_completion_visible_in_cursor_popover(true, cx) {
5162 if edits
5163 .iter()
5164 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5165 {
5166 let mut inlays = Vec::new();
5167 for (range, new_text) in &edits {
5168 let inlay = Inlay::inline_completion(
5169 post_inc(&mut self.next_inlay_id),
5170 range.start,
5171 new_text.as_str(),
5172 );
5173 inlay_ids.push(inlay.id);
5174 inlays.push(inlay);
5175 }
5176
5177 self.splice_inlays(&[], inlays, cx);
5178 } else {
5179 let background_color = cx.theme().status().deleted_background;
5180 self.highlight_text::<InlineCompletionHighlight>(
5181 edits.iter().map(|(range, _)| range.clone()).collect(),
5182 HighlightStyle {
5183 background_color: Some(background_color),
5184 ..Default::default()
5185 },
5186 cx,
5187 );
5188 }
5189 }
5190
5191 invalidation_row_range = edit_start_row..edit_end_row;
5192
5193 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5194 if provider.show_tab_accept_marker() {
5195 EditDisplayMode::TabAccept
5196 } else {
5197 EditDisplayMode::Inline
5198 }
5199 } else {
5200 EditDisplayMode::DiffPopover
5201 };
5202
5203 InlineCompletion::Edit {
5204 edits,
5205 edit_preview: inline_completion.edit_preview,
5206 display_mode,
5207 snapshot,
5208 }
5209 };
5210
5211 let invalidation_range = multibuffer
5212 .anchor_before(Point::new(invalidation_row_range.start, 0))
5213 ..multibuffer.anchor_after(Point::new(
5214 invalidation_row_range.end,
5215 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5216 ));
5217
5218 self.stale_inline_completion_in_menu = None;
5219 self.active_inline_completion = Some(InlineCompletionState {
5220 inlay_ids,
5221 completion,
5222 invalidation_range,
5223 });
5224
5225 cx.notify();
5226
5227 Some(())
5228 }
5229
5230 pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5231 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5232 }
5233
5234 fn show_inline_completions_in_menu(&self, cx: &App) -> bool {
5235 let by_provider = matches!(
5236 self.menu_inline_completions_policy,
5237 MenuInlineCompletionsPolicy::ByProvider
5238 );
5239
5240 by_provider
5241 && EditorSettings::get_global(cx).show_inline_completions_in_menu
5242 && self
5243 .inline_completion_provider()
5244 .map_or(false, |provider| provider.show_completions_in_menu())
5245 }
5246
5247 fn render_code_actions_indicator(
5248 &self,
5249 _style: &EditorStyle,
5250 row: DisplayRow,
5251 is_active: bool,
5252 cx: &mut Context<Self>,
5253 ) -> Option<IconButton> {
5254 if self.available_code_actions.is_some() {
5255 Some(
5256 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5257 .shape(ui::IconButtonShape::Square)
5258 .icon_size(IconSize::XSmall)
5259 .icon_color(Color::Muted)
5260 .toggle_state(is_active)
5261 .tooltip({
5262 let focus_handle = self.focus_handle.clone();
5263 move |window, cx| {
5264 Tooltip::for_action_in(
5265 "Toggle Code Actions",
5266 &ToggleCodeActions {
5267 deployed_from_indicator: None,
5268 },
5269 &focus_handle,
5270 window,
5271 cx,
5272 )
5273 }
5274 })
5275 .on_click(cx.listener(move |editor, _e, window, cx| {
5276 window.focus(&editor.focus_handle(cx));
5277 editor.toggle_code_actions(
5278 &ToggleCodeActions {
5279 deployed_from_indicator: Some(row),
5280 },
5281 window,
5282 cx,
5283 );
5284 })),
5285 )
5286 } else {
5287 None
5288 }
5289 }
5290
5291 fn clear_tasks(&mut self) {
5292 self.tasks.clear()
5293 }
5294
5295 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5296 if self.tasks.insert(key, value).is_some() {
5297 // This case should hopefully be rare, but just in case...
5298 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5299 }
5300 }
5301
5302 fn build_tasks_context(
5303 project: &Entity<Project>,
5304 buffer: &Entity<Buffer>,
5305 buffer_row: u32,
5306 tasks: &Arc<RunnableTasks>,
5307 cx: &mut Context<Self>,
5308 ) -> Task<Option<task::TaskContext>> {
5309 let position = Point::new(buffer_row, tasks.column);
5310 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5311 let location = Location {
5312 buffer: buffer.clone(),
5313 range: range_start..range_start,
5314 };
5315 // Fill in the environmental variables from the tree-sitter captures
5316 let mut captured_task_variables = TaskVariables::default();
5317 for (capture_name, value) in tasks.extra_variables.clone() {
5318 captured_task_variables.insert(
5319 task::VariableName::Custom(capture_name.into()),
5320 value.clone(),
5321 );
5322 }
5323 project.update(cx, |project, cx| {
5324 project.task_store().update(cx, |task_store, cx| {
5325 task_store.task_context_for_location(captured_task_variables, location, cx)
5326 })
5327 })
5328 }
5329
5330 pub fn spawn_nearest_task(
5331 &mut self,
5332 action: &SpawnNearestTask,
5333 window: &mut Window,
5334 cx: &mut Context<Self>,
5335 ) {
5336 let Some((workspace, _)) = self.workspace.clone() else {
5337 return;
5338 };
5339 let Some(project) = self.project.clone() else {
5340 return;
5341 };
5342
5343 // Try to find a closest, enclosing node using tree-sitter that has a
5344 // task
5345 let Some((buffer, buffer_row, tasks)) = self
5346 .find_enclosing_node_task(cx)
5347 // Or find the task that's closest in row-distance.
5348 .or_else(|| self.find_closest_task(cx))
5349 else {
5350 return;
5351 };
5352
5353 let reveal_strategy = action.reveal;
5354 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5355 cx.spawn_in(window, |_, mut cx| async move {
5356 let context = task_context.await?;
5357 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5358
5359 let resolved = resolved_task.resolved.as_mut()?;
5360 resolved.reveal = reveal_strategy;
5361
5362 workspace
5363 .update(&mut cx, |workspace, cx| {
5364 workspace::tasks::schedule_resolved_task(
5365 workspace,
5366 task_source_kind,
5367 resolved_task,
5368 false,
5369 cx,
5370 );
5371 })
5372 .ok()
5373 })
5374 .detach();
5375 }
5376
5377 fn find_closest_task(
5378 &mut self,
5379 cx: &mut Context<Self>,
5380 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5381 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5382
5383 let ((buffer_id, row), tasks) = self
5384 .tasks
5385 .iter()
5386 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5387
5388 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5389 let tasks = Arc::new(tasks.to_owned());
5390 Some((buffer, *row, tasks))
5391 }
5392
5393 fn find_enclosing_node_task(
5394 &mut self,
5395 cx: &mut Context<Self>,
5396 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5397 let snapshot = self.buffer.read(cx).snapshot(cx);
5398 let offset = self.selections.newest::<usize>(cx).head();
5399 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5400 let buffer_id = excerpt.buffer().remote_id();
5401
5402 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5403 let mut cursor = layer.node().walk();
5404
5405 while cursor.goto_first_child_for_byte(offset).is_some() {
5406 if cursor.node().end_byte() == offset {
5407 cursor.goto_next_sibling();
5408 }
5409 }
5410
5411 // Ascend to the smallest ancestor that contains the range and has a task.
5412 loop {
5413 let node = cursor.node();
5414 let node_range = node.byte_range();
5415 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5416
5417 // Check if this node contains our offset
5418 if node_range.start <= offset && node_range.end >= offset {
5419 // If it contains offset, check for task
5420 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5421 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5422 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5423 }
5424 }
5425
5426 if !cursor.goto_parent() {
5427 break;
5428 }
5429 }
5430 None
5431 }
5432
5433 fn render_run_indicator(
5434 &self,
5435 _style: &EditorStyle,
5436 is_active: bool,
5437 row: DisplayRow,
5438 cx: &mut Context<Self>,
5439 ) -> IconButton {
5440 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5441 .shape(ui::IconButtonShape::Square)
5442 .icon_size(IconSize::XSmall)
5443 .icon_color(Color::Muted)
5444 .toggle_state(is_active)
5445 .on_click(cx.listener(move |editor, _e, window, cx| {
5446 window.focus(&editor.focus_handle(cx));
5447 editor.toggle_code_actions(
5448 &ToggleCodeActions {
5449 deployed_from_indicator: Some(row),
5450 },
5451 window,
5452 cx,
5453 );
5454 }))
5455 }
5456
5457 pub fn context_menu_visible(&self) -> bool {
5458 !self.previewing_inline_completion
5459 && self
5460 .context_menu
5461 .borrow()
5462 .as_ref()
5463 .map_or(false, |menu| menu.visible())
5464 }
5465
5466 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5467 self.context_menu
5468 .borrow()
5469 .as_ref()
5470 .map(|menu| menu.origin())
5471 }
5472
5473 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5474 px(30.)
5475 }
5476
5477 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5478 if self.read_only(cx) {
5479 cx.theme().players().read_only()
5480 } else {
5481 self.style.as_ref().unwrap().local_player
5482 }
5483 }
5484
5485 #[allow(clippy::too_many_arguments)]
5486 fn render_edit_prediction_cursor_popover(
5487 &self,
5488 min_width: Pixels,
5489 max_width: Pixels,
5490 cursor_point: Point,
5491 style: &EditorStyle,
5492 accept_keystroke: &gpui::Keystroke,
5493 window: &Window,
5494 cx: &mut Context<Editor>,
5495 ) -> Option<AnyElement> {
5496 let provider = self.inline_completion_provider.as_ref()?;
5497
5498 if provider.provider.needs_terms_acceptance(cx) {
5499 return Some(
5500 h_flex()
5501 .h(self.edit_prediction_cursor_popover_height())
5502 .min_w(min_width)
5503 .flex_1()
5504 .px_2()
5505 .gap_3()
5506 .elevation_2(cx)
5507 .hover(|style| style.bg(cx.theme().colors().element_hover))
5508 .id("accept-terms")
5509 .cursor_pointer()
5510 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5511 .on_click(cx.listener(|this, _event, window, cx| {
5512 cx.stop_propagation();
5513 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
5514 window.dispatch_action(
5515 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
5516 cx,
5517 );
5518 }))
5519 .child(
5520 h_flex()
5521 .w_full()
5522 .gap_2()
5523 .child(Icon::new(IconName::ZedPredict))
5524 .child(Label::new("Accept Terms of Service"))
5525 .child(div().w_full())
5526 .child(
5527 Icon::new(IconName::ArrowUpRight)
5528 .color(Color::Muted)
5529 .size(IconSize::Small),
5530 )
5531 .into_any_element(),
5532 )
5533 .into_any(),
5534 );
5535 }
5536
5537 let is_refreshing = provider.provider.is_refreshing(cx);
5538
5539 fn pending_completion_container() -> Div {
5540 h_flex()
5541 .h_full()
5542 .flex_1()
5543 .gap_2()
5544 .child(Icon::new(IconName::ZedPredict))
5545 }
5546
5547 let completion = match &self.active_inline_completion {
5548 Some(completion) => self.render_edit_prediction_cursor_popover_preview(
5549 completion,
5550 cursor_point,
5551 style,
5552 window,
5553 cx,
5554 )?,
5555
5556 None if is_refreshing => match &self.stale_inline_completion_in_menu {
5557 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
5558 stale_completion,
5559 cursor_point,
5560 style,
5561 window,
5562 cx,
5563 )?,
5564
5565 None => {
5566 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
5567 }
5568 },
5569
5570 None => pending_completion_container().child(Label::new("No Prediction")),
5571 };
5572
5573 let buffer_font = theme::ThemeSettings::get_global(cx).buffer_font.clone();
5574 let completion = completion.font(buffer_font.clone());
5575
5576 let completion = if is_refreshing {
5577 completion
5578 .with_animation(
5579 "loading-completion",
5580 Animation::new(Duration::from_secs(2))
5581 .repeat()
5582 .with_easing(pulsating_between(0.4, 0.8)),
5583 |label, delta| label.opacity(delta),
5584 )
5585 .into_any_element()
5586 } else {
5587 completion.into_any_element()
5588 };
5589
5590 let has_completion = self.active_inline_completion.is_some();
5591
5592 Some(
5593 h_flex()
5594 .h(self.edit_prediction_cursor_popover_height())
5595 .min_w(min_width)
5596 .max_w(max_width)
5597 .flex_1()
5598 .px_2()
5599 .elevation_2(cx)
5600 .child(completion)
5601 .child(ui::Divider::vertical())
5602 .child(
5603 h_flex()
5604 .h_full()
5605 .gap_1()
5606 .pl_2()
5607 .child(h_flex().font(buffer_font.clone()).gap_1().children(
5608 ui::render_modifiers(
5609 &accept_keystroke.modifiers,
5610 PlatformStyle::platform(),
5611 Some(if !has_completion {
5612 Color::Muted
5613 } else {
5614 Color::Default
5615 }),
5616 true,
5617 ),
5618 ))
5619 .child(Label::new("Preview").into_any_element())
5620 .opacity(if has_completion { 1.0 } else { 0.4 }),
5621 )
5622 .into_any(),
5623 )
5624 }
5625
5626 fn render_edit_prediction_cursor_popover_preview(
5627 &self,
5628 completion: &InlineCompletionState,
5629 cursor_point: Point,
5630 style: &EditorStyle,
5631 window: &Window,
5632 cx: &mut Context<Editor>,
5633 ) -> Option<Div> {
5634 use text::ToPoint as _;
5635
5636 fn render_relative_row_jump(
5637 prefix: impl Into<String>,
5638 current_row: u32,
5639 target_row: u32,
5640 ) -> Div {
5641 let (row_diff, arrow) = if target_row < current_row {
5642 (current_row - target_row, IconName::ArrowUp)
5643 } else {
5644 (target_row - current_row, IconName::ArrowDown)
5645 };
5646
5647 h_flex()
5648 .child(
5649 Label::new(format!("{}{}", prefix.into(), row_diff))
5650 .color(Color::Muted)
5651 .size(LabelSize::Small),
5652 )
5653 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
5654 }
5655
5656 match &completion.completion {
5657 InlineCompletion::Edit {
5658 edits,
5659 edit_preview,
5660 snapshot,
5661 display_mode: _,
5662 } => {
5663 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
5664
5665 let highlighted_edits = crate::inline_completion_edit_text(
5666 &snapshot,
5667 &edits,
5668 edit_preview.as_ref()?,
5669 true,
5670 cx,
5671 );
5672
5673 let len_total = highlighted_edits.text.len();
5674 let first_line = &highlighted_edits.text
5675 [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
5676 let first_line_len = first_line.len();
5677
5678 let first_highlight_start = highlighted_edits
5679 .highlights
5680 .first()
5681 .map_or(0, |(range, _)| range.start);
5682 let drop_prefix_len = first_line
5683 .char_indices()
5684 .find(|(_, c)| !c.is_whitespace())
5685 .map_or(first_highlight_start, |(ix, _)| {
5686 ix.min(first_highlight_start)
5687 });
5688
5689 let preview_text = &first_line[drop_prefix_len..];
5690 let preview_len = preview_text.len();
5691 let highlights = highlighted_edits
5692 .highlights
5693 .into_iter()
5694 .take_until(|(range, _)| range.start > first_line_len)
5695 .map(|(range, style)| {
5696 (
5697 range.start - drop_prefix_len
5698 ..(range.end - drop_prefix_len).min(preview_len),
5699 style,
5700 )
5701 });
5702
5703 let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
5704 .with_highlights(&style.text, highlights);
5705
5706 let preview = h_flex()
5707 .gap_1()
5708 .min_w_16()
5709 .child(styled_text)
5710 .when(len_total > first_line_len, |parent| parent.child("…"));
5711
5712 let left = if first_edit_row != cursor_point.row {
5713 render_relative_row_jump("", cursor_point.row, first_edit_row)
5714 .into_any_element()
5715 } else {
5716 Icon::new(IconName::ZedPredict).into_any_element()
5717 };
5718
5719 Some(
5720 h_flex()
5721 .h_full()
5722 .flex_1()
5723 .gap_2()
5724 .pr_1()
5725 .overflow_x_hidden()
5726 .child(left)
5727 .child(preview),
5728 )
5729 }
5730
5731 InlineCompletion::Move {
5732 target,
5733 range_around_target,
5734 snapshot,
5735 } => {
5736 let highlighted_text = snapshot.highlighted_text_for_range(
5737 range_around_target.clone(),
5738 None,
5739 &style.syntax,
5740 );
5741 let base = h_flex().gap_3().flex_1().child(render_relative_row_jump(
5742 "Jump ",
5743 cursor_point.row,
5744 target.text_anchor.to_point(&snapshot).row,
5745 ));
5746
5747 if highlighted_text.text.is_empty() {
5748 return Some(base);
5749 }
5750
5751 let cursor_color = self.current_user_player_color(cx).cursor;
5752
5753 let start_point = range_around_target.start.to_point(&snapshot);
5754 let end_point = range_around_target.end.to_point(&snapshot);
5755 let target_point = target.text_anchor.to_point(&snapshot);
5756
5757 let styled_text = highlighted_text.to_styled_text(&style.text);
5758 let text_len = highlighted_text.text.len();
5759
5760 let cursor_relative_position = window
5761 .text_system()
5762 .layout_line(
5763 highlighted_text.text,
5764 style.text.font_size.to_pixels(window.rem_size()),
5765 // We don't need to include highlights
5766 // because we are only using this for the cursor position
5767 &[TextRun {
5768 len: text_len,
5769 font: style.text.font(),
5770 color: style.text.color,
5771 background_color: None,
5772 underline: None,
5773 strikethrough: None,
5774 }],
5775 )
5776 .log_err()
5777 .map(|line| {
5778 line.x_for_index(
5779 target_point.column.saturating_sub(start_point.column) as usize
5780 )
5781 });
5782
5783 let fade_before = start_point.column > 0;
5784 let fade_after = end_point.column < snapshot.line_len(end_point.row);
5785
5786 let background = cx.theme().colors().elevated_surface_background;
5787
5788 let preview = h_flex()
5789 .relative()
5790 .child(styled_text)
5791 .when(fade_before, |parent| {
5792 parent.child(div().absolute().top_0().left_0().w_4().h_full().bg(
5793 linear_gradient(
5794 90.,
5795 linear_color_stop(background, 0.),
5796 linear_color_stop(background.opacity(0.), 1.),
5797 ),
5798 ))
5799 })
5800 .when(fade_after, |parent| {
5801 parent.child(div().absolute().top_0().right_0().w_4().h_full().bg(
5802 linear_gradient(
5803 -90.,
5804 linear_color_stop(background, 0.),
5805 linear_color_stop(background.opacity(0.), 1.),
5806 ),
5807 ))
5808 })
5809 .when_some(cursor_relative_position, |parent, position| {
5810 parent.child(
5811 div()
5812 .w(px(2.))
5813 .h_full()
5814 .bg(cursor_color)
5815 .absolute()
5816 .top_0()
5817 .left(position),
5818 )
5819 });
5820
5821 Some(base.child(preview))
5822 }
5823 }
5824 }
5825
5826 fn render_context_menu(
5827 &self,
5828 style: &EditorStyle,
5829 max_height_in_lines: u32,
5830 y_flipped: bool,
5831 window: &mut Window,
5832 cx: &mut Context<Editor>,
5833 ) -> Option<AnyElement> {
5834 let menu = self.context_menu.borrow();
5835 let menu = menu.as_ref()?;
5836 if !menu.visible() {
5837 return None;
5838 };
5839 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
5840 }
5841
5842 fn render_context_menu_aside(
5843 &self,
5844 style: &EditorStyle,
5845 max_size: Size<Pixels>,
5846 cx: &mut Context<Editor>,
5847 ) -> Option<AnyElement> {
5848 self.context_menu.borrow().as_ref().and_then(|menu| {
5849 if menu.visible() {
5850 menu.render_aside(
5851 style,
5852 max_size,
5853 self.workspace.as_ref().map(|(w, _)| w.clone()),
5854 cx,
5855 )
5856 } else {
5857 None
5858 }
5859 })
5860 }
5861
5862 fn hide_context_menu(
5863 &mut self,
5864 window: &mut Window,
5865 cx: &mut Context<Self>,
5866 ) -> Option<CodeContextMenu> {
5867 cx.notify();
5868 self.completion_tasks.clear();
5869 let context_menu = self.context_menu.borrow_mut().take();
5870 self.stale_inline_completion_in_menu.take();
5871 self.update_visible_inline_completion(window, cx);
5872 context_menu
5873 }
5874
5875 fn show_snippet_choices(
5876 &mut self,
5877 choices: &Vec<String>,
5878 selection: Range<Anchor>,
5879 cx: &mut Context<Self>,
5880 ) {
5881 if selection.start.buffer_id.is_none() {
5882 return;
5883 }
5884 let buffer_id = selection.start.buffer_id.unwrap();
5885 let buffer = self.buffer().read(cx).buffer(buffer_id);
5886 let id = post_inc(&mut self.next_completion_id);
5887
5888 if let Some(buffer) = buffer {
5889 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5890 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5891 ));
5892 }
5893 }
5894
5895 pub fn insert_snippet(
5896 &mut self,
5897 insertion_ranges: &[Range<usize>],
5898 snippet: Snippet,
5899 window: &mut Window,
5900 cx: &mut Context<Self>,
5901 ) -> Result<()> {
5902 struct Tabstop<T> {
5903 is_end_tabstop: bool,
5904 ranges: Vec<Range<T>>,
5905 choices: Option<Vec<String>>,
5906 }
5907
5908 let tabstops = self.buffer.update(cx, |buffer, cx| {
5909 let snippet_text: Arc<str> = snippet.text.clone().into();
5910 buffer.edit(
5911 insertion_ranges
5912 .iter()
5913 .cloned()
5914 .map(|range| (range, snippet_text.clone())),
5915 Some(AutoindentMode::EachLine),
5916 cx,
5917 );
5918
5919 let snapshot = &*buffer.read(cx);
5920 let snippet = &snippet;
5921 snippet
5922 .tabstops
5923 .iter()
5924 .map(|tabstop| {
5925 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5926 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5927 });
5928 let mut tabstop_ranges = tabstop
5929 .ranges
5930 .iter()
5931 .flat_map(|tabstop_range| {
5932 let mut delta = 0_isize;
5933 insertion_ranges.iter().map(move |insertion_range| {
5934 let insertion_start = insertion_range.start as isize + delta;
5935 delta +=
5936 snippet.text.len() as isize - insertion_range.len() as isize;
5937
5938 let start = ((insertion_start + tabstop_range.start) as usize)
5939 .min(snapshot.len());
5940 let end = ((insertion_start + tabstop_range.end) as usize)
5941 .min(snapshot.len());
5942 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5943 })
5944 })
5945 .collect::<Vec<_>>();
5946 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5947
5948 Tabstop {
5949 is_end_tabstop,
5950 ranges: tabstop_ranges,
5951 choices: tabstop.choices.clone(),
5952 }
5953 })
5954 .collect::<Vec<_>>()
5955 });
5956 if let Some(tabstop) = tabstops.first() {
5957 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
5958 s.select_ranges(tabstop.ranges.iter().cloned());
5959 });
5960
5961 if let Some(choices) = &tabstop.choices {
5962 if let Some(selection) = tabstop.ranges.first() {
5963 self.show_snippet_choices(choices, selection.clone(), cx)
5964 }
5965 }
5966
5967 // If we're already at the last tabstop and it's at the end of the snippet,
5968 // we're done, we don't need to keep the state around.
5969 if !tabstop.is_end_tabstop {
5970 let choices = tabstops
5971 .iter()
5972 .map(|tabstop| tabstop.choices.clone())
5973 .collect();
5974
5975 let ranges = tabstops
5976 .into_iter()
5977 .map(|tabstop| tabstop.ranges)
5978 .collect::<Vec<_>>();
5979
5980 self.snippet_stack.push(SnippetState {
5981 active_index: 0,
5982 ranges,
5983 choices,
5984 });
5985 }
5986
5987 // Check whether the just-entered snippet ends with an auto-closable bracket.
5988 if self.autoclose_regions.is_empty() {
5989 let snapshot = self.buffer.read(cx).snapshot(cx);
5990 for selection in &mut self.selections.all::<Point>(cx) {
5991 let selection_head = selection.head();
5992 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5993 continue;
5994 };
5995
5996 let mut bracket_pair = None;
5997 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5998 let prev_chars = snapshot
5999 .reversed_chars_at(selection_head)
6000 .collect::<String>();
6001 for (pair, enabled) in scope.brackets() {
6002 if enabled
6003 && pair.close
6004 && prev_chars.starts_with(pair.start.as_str())
6005 && next_chars.starts_with(pair.end.as_str())
6006 {
6007 bracket_pair = Some(pair.clone());
6008 break;
6009 }
6010 }
6011 if let Some(pair) = bracket_pair {
6012 let start = snapshot.anchor_after(selection_head);
6013 let end = snapshot.anchor_after(selection_head);
6014 self.autoclose_regions.push(AutocloseRegion {
6015 selection_id: selection.id,
6016 range: start..end,
6017 pair,
6018 });
6019 }
6020 }
6021 }
6022 }
6023 Ok(())
6024 }
6025
6026 pub fn move_to_next_snippet_tabstop(
6027 &mut self,
6028 window: &mut Window,
6029 cx: &mut Context<Self>,
6030 ) -> bool {
6031 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6032 }
6033
6034 pub fn move_to_prev_snippet_tabstop(
6035 &mut self,
6036 window: &mut Window,
6037 cx: &mut Context<Self>,
6038 ) -> bool {
6039 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6040 }
6041
6042 pub fn move_to_snippet_tabstop(
6043 &mut self,
6044 bias: Bias,
6045 window: &mut Window,
6046 cx: &mut Context<Self>,
6047 ) -> bool {
6048 if let Some(mut snippet) = self.snippet_stack.pop() {
6049 match bias {
6050 Bias::Left => {
6051 if snippet.active_index > 0 {
6052 snippet.active_index -= 1;
6053 } else {
6054 self.snippet_stack.push(snippet);
6055 return false;
6056 }
6057 }
6058 Bias::Right => {
6059 if snippet.active_index + 1 < snippet.ranges.len() {
6060 snippet.active_index += 1;
6061 } else {
6062 self.snippet_stack.push(snippet);
6063 return false;
6064 }
6065 }
6066 }
6067 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6068 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6069 s.select_anchor_ranges(current_ranges.iter().cloned())
6070 });
6071
6072 if let Some(choices) = &snippet.choices[snippet.active_index] {
6073 if let Some(selection) = current_ranges.first() {
6074 self.show_snippet_choices(&choices, selection.clone(), cx);
6075 }
6076 }
6077
6078 // If snippet state is not at the last tabstop, push it back on the stack
6079 if snippet.active_index + 1 < snippet.ranges.len() {
6080 self.snippet_stack.push(snippet);
6081 }
6082 return true;
6083 }
6084 }
6085
6086 false
6087 }
6088
6089 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6090 self.transact(window, cx, |this, window, cx| {
6091 this.select_all(&SelectAll, window, cx);
6092 this.insert("", window, cx);
6093 });
6094 }
6095
6096 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6097 self.transact(window, cx, |this, window, cx| {
6098 this.select_autoclose_pair(window, cx);
6099 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6100 if !this.linked_edit_ranges.is_empty() {
6101 let selections = this.selections.all::<MultiBufferPoint>(cx);
6102 let snapshot = this.buffer.read(cx).snapshot(cx);
6103
6104 for selection in selections.iter() {
6105 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6106 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6107 if selection_start.buffer_id != selection_end.buffer_id {
6108 continue;
6109 }
6110 if let Some(ranges) =
6111 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6112 {
6113 for (buffer, entries) in ranges {
6114 linked_ranges.entry(buffer).or_default().extend(entries);
6115 }
6116 }
6117 }
6118 }
6119
6120 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6121 if !this.selections.line_mode {
6122 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6123 for selection in &mut selections {
6124 if selection.is_empty() {
6125 let old_head = selection.head();
6126 let mut new_head =
6127 movement::left(&display_map, old_head.to_display_point(&display_map))
6128 .to_point(&display_map);
6129 if let Some((buffer, line_buffer_range)) = display_map
6130 .buffer_snapshot
6131 .buffer_line_for_row(MultiBufferRow(old_head.row))
6132 {
6133 let indent_size =
6134 buffer.indent_size_for_line(line_buffer_range.start.row);
6135 let indent_len = match indent_size.kind {
6136 IndentKind::Space => {
6137 buffer.settings_at(line_buffer_range.start, cx).tab_size
6138 }
6139 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6140 };
6141 if old_head.column <= indent_size.len && old_head.column > 0 {
6142 let indent_len = indent_len.get();
6143 new_head = cmp::min(
6144 new_head,
6145 MultiBufferPoint::new(
6146 old_head.row,
6147 ((old_head.column - 1) / indent_len) * indent_len,
6148 ),
6149 );
6150 }
6151 }
6152
6153 selection.set_head(new_head, SelectionGoal::None);
6154 }
6155 }
6156 }
6157
6158 this.signature_help_state.set_backspace_pressed(true);
6159 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6160 s.select(selections)
6161 });
6162 this.insert("", window, cx);
6163 let empty_str: Arc<str> = Arc::from("");
6164 for (buffer, edits) in linked_ranges {
6165 let snapshot = buffer.read(cx).snapshot();
6166 use text::ToPoint as TP;
6167
6168 let edits = edits
6169 .into_iter()
6170 .map(|range| {
6171 let end_point = TP::to_point(&range.end, &snapshot);
6172 let mut start_point = TP::to_point(&range.start, &snapshot);
6173
6174 if end_point == start_point {
6175 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6176 .saturating_sub(1);
6177 start_point =
6178 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6179 };
6180
6181 (start_point..end_point, empty_str.clone())
6182 })
6183 .sorted_by_key(|(range, _)| range.start)
6184 .collect::<Vec<_>>();
6185 buffer.update(cx, |this, cx| {
6186 this.edit(edits, None, cx);
6187 })
6188 }
6189 this.refresh_inline_completion(true, false, window, cx);
6190 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6191 });
6192 }
6193
6194 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6195 self.transact(window, cx, |this, window, cx| {
6196 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6197 let line_mode = s.line_mode;
6198 s.move_with(|map, selection| {
6199 if selection.is_empty() && !line_mode {
6200 let cursor = movement::right(map, selection.head());
6201 selection.end = cursor;
6202 selection.reversed = true;
6203 selection.goal = SelectionGoal::None;
6204 }
6205 })
6206 });
6207 this.insert("", window, cx);
6208 this.refresh_inline_completion(true, false, window, cx);
6209 });
6210 }
6211
6212 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6213 if self.move_to_prev_snippet_tabstop(window, cx) {
6214 return;
6215 }
6216
6217 self.outdent(&Outdent, window, cx);
6218 }
6219
6220 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6221 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6222 return;
6223 }
6224
6225 let mut selections = self.selections.all_adjusted(cx);
6226 let buffer = self.buffer.read(cx);
6227 let snapshot = buffer.snapshot(cx);
6228 let rows_iter = selections.iter().map(|s| s.head().row);
6229 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6230
6231 let mut edits = Vec::new();
6232 let mut prev_edited_row = 0;
6233 let mut row_delta = 0;
6234 for selection in &mut selections {
6235 if selection.start.row != prev_edited_row {
6236 row_delta = 0;
6237 }
6238 prev_edited_row = selection.end.row;
6239
6240 // If the selection is non-empty, then increase the indentation of the selected lines.
6241 if !selection.is_empty() {
6242 row_delta =
6243 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6244 continue;
6245 }
6246
6247 // If the selection is empty and the cursor is in the leading whitespace before the
6248 // suggested indentation, then auto-indent the line.
6249 let cursor = selection.head();
6250 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6251 if let Some(suggested_indent) =
6252 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6253 {
6254 if cursor.column < suggested_indent.len
6255 && cursor.column <= current_indent.len
6256 && current_indent.len <= suggested_indent.len
6257 {
6258 selection.start = Point::new(cursor.row, suggested_indent.len);
6259 selection.end = selection.start;
6260 if row_delta == 0 {
6261 edits.extend(Buffer::edit_for_indent_size_adjustment(
6262 cursor.row,
6263 current_indent,
6264 suggested_indent,
6265 ));
6266 row_delta = suggested_indent.len - current_indent.len;
6267 }
6268 continue;
6269 }
6270 }
6271
6272 // Otherwise, insert a hard or soft tab.
6273 let settings = buffer.settings_at(cursor, cx);
6274 let tab_size = if settings.hard_tabs {
6275 IndentSize::tab()
6276 } else {
6277 let tab_size = settings.tab_size.get();
6278 let char_column = snapshot
6279 .text_for_range(Point::new(cursor.row, 0)..cursor)
6280 .flat_map(str::chars)
6281 .count()
6282 + row_delta as usize;
6283 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6284 IndentSize::spaces(chars_to_next_tab_stop)
6285 };
6286 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6287 selection.end = selection.start;
6288 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6289 row_delta += tab_size.len;
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 this.refresh_inline_completion(true, false, window, cx);
6298 });
6299 }
6300
6301 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6302 if self.read_only(cx) {
6303 return;
6304 }
6305 let mut selections = self.selections.all::<Point>(cx);
6306 let mut prev_edited_row = 0;
6307 let mut row_delta = 0;
6308 let mut edits = Vec::new();
6309 let buffer = self.buffer.read(cx);
6310 let snapshot = buffer.snapshot(cx);
6311 for selection in &mut selections {
6312 if selection.start.row != prev_edited_row {
6313 row_delta = 0;
6314 }
6315 prev_edited_row = selection.end.row;
6316
6317 row_delta =
6318 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6319 }
6320
6321 self.transact(window, cx, |this, window, cx| {
6322 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6323 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6324 s.select(selections)
6325 });
6326 });
6327 }
6328
6329 fn indent_selection(
6330 buffer: &MultiBuffer,
6331 snapshot: &MultiBufferSnapshot,
6332 selection: &mut Selection<Point>,
6333 edits: &mut Vec<(Range<Point>, String)>,
6334 delta_for_start_row: u32,
6335 cx: &App,
6336 ) -> u32 {
6337 let settings = buffer.settings_at(selection.start, cx);
6338 let tab_size = settings.tab_size.get();
6339 let indent_kind = if settings.hard_tabs {
6340 IndentKind::Tab
6341 } else {
6342 IndentKind::Space
6343 };
6344 let mut start_row = selection.start.row;
6345 let mut end_row = selection.end.row + 1;
6346
6347 // If a selection ends at the beginning of a line, don't indent
6348 // that last line.
6349 if selection.end.column == 0 && selection.end.row > selection.start.row {
6350 end_row -= 1;
6351 }
6352
6353 // Avoid re-indenting a row that has already been indented by a
6354 // previous selection, but still update this selection's column
6355 // to reflect that indentation.
6356 if delta_for_start_row > 0 {
6357 start_row += 1;
6358 selection.start.column += delta_for_start_row;
6359 if selection.end.row == selection.start.row {
6360 selection.end.column += delta_for_start_row;
6361 }
6362 }
6363
6364 let mut delta_for_end_row = 0;
6365 let has_multiple_rows = start_row + 1 != end_row;
6366 for row in start_row..end_row {
6367 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6368 let indent_delta = match (current_indent.kind, indent_kind) {
6369 (IndentKind::Space, IndentKind::Space) => {
6370 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6371 IndentSize::spaces(columns_to_next_tab_stop)
6372 }
6373 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6374 (_, IndentKind::Tab) => IndentSize::tab(),
6375 };
6376
6377 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6378 0
6379 } else {
6380 selection.start.column
6381 };
6382 let row_start = Point::new(row, start);
6383 edits.push((
6384 row_start..row_start,
6385 indent_delta.chars().collect::<String>(),
6386 ));
6387
6388 // Update this selection's endpoints to reflect the indentation.
6389 if row == selection.start.row {
6390 selection.start.column += indent_delta.len;
6391 }
6392 if row == selection.end.row {
6393 selection.end.column += indent_delta.len;
6394 delta_for_end_row = indent_delta.len;
6395 }
6396 }
6397
6398 if selection.start.row == selection.end.row {
6399 delta_for_start_row + delta_for_end_row
6400 } else {
6401 delta_for_end_row
6402 }
6403 }
6404
6405 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6406 if self.read_only(cx) {
6407 return;
6408 }
6409 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6410 let selections = self.selections.all::<Point>(cx);
6411 let mut deletion_ranges = Vec::new();
6412 let mut last_outdent = None;
6413 {
6414 let buffer = self.buffer.read(cx);
6415 let snapshot = buffer.snapshot(cx);
6416 for selection in &selections {
6417 let settings = buffer.settings_at(selection.start, cx);
6418 let tab_size = settings.tab_size.get();
6419 let mut rows = selection.spanned_rows(false, &display_map);
6420
6421 // Avoid re-outdenting a row that has already been outdented by a
6422 // previous selection.
6423 if let Some(last_row) = last_outdent {
6424 if last_row == rows.start {
6425 rows.start = rows.start.next_row();
6426 }
6427 }
6428 let has_multiple_rows = rows.len() > 1;
6429 for row in rows.iter_rows() {
6430 let indent_size = snapshot.indent_size_for_line(row);
6431 if indent_size.len > 0 {
6432 let deletion_len = match indent_size.kind {
6433 IndentKind::Space => {
6434 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6435 if columns_to_prev_tab_stop == 0 {
6436 tab_size
6437 } else {
6438 columns_to_prev_tab_stop
6439 }
6440 }
6441 IndentKind::Tab => 1,
6442 };
6443 let start = if has_multiple_rows
6444 || deletion_len > selection.start.column
6445 || indent_size.len < selection.start.column
6446 {
6447 0
6448 } else {
6449 selection.start.column - deletion_len
6450 };
6451 deletion_ranges.push(
6452 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6453 );
6454 last_outdent = Some(row);
6455 }
6456 }
6457 }
6458 }
6459
6460 self.transact(window, cx, |this, window, cx| {
6461 this.buffer.update(cx, |buffer, cx| {
6462 let empty_str: Arc<str> = Arc::default();
6463 buffer.edit(
6464 deletion_ranges
6465 .into_iter()
6466 .map(|range| (range, empty_str.clone())),
6467 None,
6468 cx,
6469 );
6470 });
6471 let selections = this.selections.all::<usize>(cx);
6472 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6473 s.select(selections)
6474 });
6475 });
6476 }
6477
6478 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6479 if self.read_only(cx) {
6480 return;
6481 }
6482 let selections = self
6483 .selections
6484 .all::<usize>(cx)
6485 .into_iter()
6486 .map(|s| s.range());
6487
6488 self.transact(window, cx, |this, window, cx| {
6489 this.buffer.update(cx, |buffer, cx| {
6490 buffer.autoindent_ranges(selections, cx);
6491 });
6492 let selections = this.selections.all::<usize>(cx);
6493 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6494 s.select(selections)
6495 });
6496 });
6497 }
6498
6499 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6500 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6501 let selections = self.selections.all::<Point>(cx);
6502
6503 let mut new_cursors = Vec::new();
6504 let mut edit_ranges = Vec::new();
6505 let mut selections = selections.iter().peekable();
6506 while let Some(selection) = selections.next() {
6507 let mut rows = selection.spanned_rows(false, &display_map);
6508 let goal_display_column = selection.head().to_display_point(&display_map).column();
6509
6510 // Accumulate contiguous regions of rows that we want to delete.
6511 while let Some(next_selection) = selections.peek() {
6512 let next_rows = next_selection.spanned_rows(false, &display_map);
6513 if next_rows.start <= rows.end {
6514 rows.end = next_rows.end;
6515 selections.next().unwrap();
6516 } else {
6517 break;
6518 }
6519 }
6520
6521 let buffer = &display_map.buffer_snapshot;
6522 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6523 let edit_end;
6524 let cursor_buffer_row;
6525 if buffer.max_point().row >= rows.end.0 {
6526 // If there's a line after the range, delete the \n from the end of the row range
6527 // and position the cursor on the next line.
6528 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6529 cursor_buffer_row = rows.end;
6530 } else {
6531 // If there isn't a line after the range, delete the \n from the line before the
6532 // start of the row range and position the cursor there.
6533 edit_start = edit_start.saturating_sub(1);
6534 edit_end = buffer.len();
6535 cursor_buffer_row = rows.start.previous_row();
6536 }
6537
6538 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6539 *cursor.column_mut() =
6540 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6541
6542 new_cursors.push((
6543 selection.id,
6544 buffer.anchor_after(cursor.to_point(&display_map)),
6545 ));
6546 edit_ranges.push(edit_start..edit_end);
6547 }
6548
6549 self.transact(window, cx, |this, window, cx| {
6550 let buffer = this.buffer.update(cx, |buffer, cx| {
6551 let empty_str: Arc<str> = Arc::default();
6552 buffer.edit(
6553 edit_ranges
6554 .into_iter()
6555 .map(|range| (range, empty_str.clone())),
6556 None,
6557 cx,
6558 );
6559 buffer.snapshot(cx)
6560 });
6561 let new_selections = new_cursors
6562 .into_iter()
6563 .map(|(id, cursor)| {
6564 let cursor = cursor.to_point(&buffer);
6565 Selection {
6566 id,
6567 start: cursor,
6568 end: cursor,
6569 reversed: false,
6570 goal: SelectionGoal::None,
6571 }
6572 })
6573 .collect();
6574
6575 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6576 s.select(new_selections);
6577 });
6578 });
6579 }
6580
6581 pub fn join_lines_impl(
6582 &mut self,
6583 insert_whitespace: bool,
6584 window: &mut Window,
6585 cx: &mut Context<Self>,
6586 ) {
6587 if self.read_only(cx) {
6588 return;
6589 }
6590 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6591 for selection in self.selections.all::<Point>(cx) {
6592 let start = MultiBufferRow(selection.start.row);
6593 // Treat single line selections as if they include the next line. Otherwise this action
6594 // would do nothing for single line selections individual cursors.
6595 let end = if selection.start.row == selection.end.row {
6596 MultiBufferRow(selection.start.row + 1)
6597 } else {
6598 MultiBufferRow(selection.end.row)
6599 };
6600
6601 if let Some(last_row_range) = row_ranges.last_mut() {
6602 if start <= last_row_range.end {
6603 last_row_range.end = end;
6604 continue;
6605 }
6606 }
6607 row_ranges.push(start..end);
6608 }
6609
6610 let snapshot = self.buffer.read(cx).snapshot(cx);
6611 let mut cursor_positions = Vec::new();
6612 for row_range in &row_ranges {
6613 let anchor = snapshot.anchor_before(Point::new(
6614 row_range.end.previous_row().0,
6615 snapshot.line_len(row_range.end.previous_row()),
6616 ));
6617 cursor_positions.push(anchor..anchor);
6618 }
6619
6620 self.transact(window, cx, |this, window, cx| {
6621 for row_range in row_ranges.into_iter().rev() {
6622 for row in row_range.iter_rows().rev() {
6623 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6624 let next_line_row = row.next_row();
6625 let indent = snapshot.indent_size_for_line(next_line_row);
6626 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6627
6628 let replace =
6629 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6630 " "
6631 } else {
6632 ""
6633 };
6634
6635 this.buffer.update(cx, |buffer, cx| {
6636 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6637 });
6638 }
6639 }
6640
6641 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6642 s.select_anchor_ranges(cursor_positions)
6643 });
6644 });
6645 }
6646
6647 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6648 self.join_lines_impl(true, window, cx);
6649 }
6650
6651 pub fn sort_lines_case_sensitive(
6652 &mut self,
6653 _: &SortLinesCaseSensitive,
6654 window: &mut Window,
6655 cx: &mut Context<Self>,
6656 ) {
6657 self.manipulate_lines(window, cx, |lines| lines.sort())
6658 }
6659
6660 pub fn sort_lines_case_insensitive(
6661 &mut self,
6662 _: &SortLinesCaseInsensitive,
6663 window: &mut Window,
6664 cx: &mut Context<Self>,
6665 ) {
6666 self.manipulate_lines(window, cx, |lines| {
6667 lines.sort_by_key(|line| line.to_lowercase())
6668 })
6669 }
6670
6671 pub fn unique_lines_case_insensitive(
6672 &mut self,
6673 _: &UniqueLinesCaseInsensitive,
6674 window: &mut Window,
6675 cx: &mut Context<Self>,
6676 ) {
6677 self.manipulate_lines(window, cx, |lines| {
6678 let mut seen = HashSet::default();
6679 lines.retain(|line| seen.insert(line.to_lowercase()));
6680 })
6681 }
6682
6683 pub fn unique_lines_case_sensitive(
6684 &mut self,
6685 _: &UniqueLinesCaseSensitive,
6686 window: &mut Window,
6687 cx: &mut Context<Self>,
6688 ) {
6689 self.manipulate_lines(window, cx, |lines| {
6690 let mut seen = HashSet::default();
6691 lines.retain(|line| seen.insert(*line));
6692 })
6693 }
6694
6695 pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
6696 let mut revert_changes = HashMap::default();
6697 let snapshot = self.snapshot(window, cx);
6698 for hunk in snapshot
6699 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
6700 {
6701 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6702 }
6703 if !revert_changes.is_empty() {
6704 self.transact(window, cx, |editor, window, cx| {
6705 editor.revert(revert_changes, window, cx);
6706 });
6707 }
6708 }
6709
6710 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
6711 let Some(project) = self.project.clone() else {
6712 return;
6713 };
6714 self.reload(project, window, cx)
6715 .detach_and_notify_err(window, cx);
6716 }
6717
6718 pub fn revert_selected_hunks(
6719 &mut self,
6720 _: &RevertSelectedHunks,
6721 window: &mut Window,
6722 cx: &mut Context<Self>,
6723 ) {
6724 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
6725 self.revert_hunks_in_ranges(selections, window, cx);
6726 }
6727
6728 fn revert_hunks_in_ranges(
6729 &mut self,
6730 ranges: impl Iterator<Item = Range<Point>>,
6731 window: &mut Window,
6732 cx: &mut Context<Editor>,
6733 ) {
6734 let mut revert_changes = HashMap::default();
6735 let snapshot = self.snapshot(window, cx);
6736 for hunk in &snapshot.hunks_for_ranges(ranges) {
6737 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6738 }
6739 if !revert_changes.is_empty() {
6740 self.transact(window, cx, |editor, window, cx| {
6741 editor.revert(revert_changes, window, cx);
6742 });
6743 }
6744 }
6745
6746 pub fn open_active_item_in_terminal(
6747 &mut self,
6748 _: &OpenInTerminal,
6749 window: &mut Window,
6750 cx: &mut Context<Self>,
6751 ) {
6752 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6753 let project_path = buffer.read(cx).project_path(cx)?;
6754 let project = self.project.as_ref()?.read(cx);
6755 let entry = project.entry_for_path(&project_path, cx)?;
6756 let parent = match &entry.canonical_path {
6757 Some(canonical_path) => canonical_path.to_path_buf(),
6758 None => project.absolute_path(&project_path, cx)?,
6759 }
6760 .parent()?
6761 .to_path_buf();
6762 Some(parent)
6763 }) {
6764 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
6765 }
6766 }
6767
6768 pub fn prepare_revert_change(
6769 &self,
6770 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6771 hunk: &MultiBufferDiffHunk,
6772 cx: &mut App,
6773 ) -> Option<()> {
6774 let buffer = self.buffer.read(cx);
6775 let change_set = buffer.change_set_for(hunk.buffer_id)?;
6776 let buffer = buffer.buffer(hunk.buffer_id)?;
6777 let buffer = buffer.read(cx);
6778 let original_text = change_set
6779 .read(cx)
6780 .base_text
6781 .as_ref()?
6782 .as_rope()
6783 .slice(hunk.diff_base_byte_range.clone());
6784 let buffer_snapshot = buffer.snapshot();
6785 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6786 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6787 probe
6788 .0
6789 .start
6790 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6791 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6792 }) {
6793 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6794 Some(())
6795 } else {
6796 None
6797 }
6798 }
6799
6800 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
6801 self.manipulate_lines(window, cx, |lines| lines.reverse())
6802 }
6803
6804 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
6805 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
6806 }
6807
6808 fn manipulate_lines<Fn>(
6809 &mut self,
6810 window: &mut Window,
6811 cx: &mut Context<Self>,
6812 mut callback: Fn,
6813 ) where
6814 Fn: FnMut(&mut Vec<&str>),
6815 {
6816 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6817 let buffer = self.buffer.read(cx).snapshot(cx);
6818
6819 let mut edits = Vec::new();
6820
6821 let selections = self.selections.all::<Point>(cx);
6822 let mut selections = selections.iter().peekable();
6823 let mut contiguous_row_selections = Vec::new();
6824 let mut new_selections = Vec::new();
6825 let mut added_lines = 0;
6826 let mut removed_lines = 0;
6827
6828 while let Some(selection) = selections.next() {
6829 let (start_row, end_row) = consume_contiguous_rows(
6830 &mut contiguous_row_selections,
6831 selection,
6832 &display_map,
6833 &mut selections,
6834 );
6835
6836 let start_point = Point::new(start_row.0, 0);
6837 let end_point = Point::new(
6838 end_row.previous_row().0,
6839 buffer.line_len(end_row.previous_row()),
6840 );
6841 let text = buffer
6842 .text_for_range(start_point..end_point)
6843 .collect::<String>();
6844
6845 let mut lines = text.split('\n').collect_vec();
6846
6847 let lines_before = lines.len();
6848 callback(&mut lines);
6849 let lines_after = lines.len();
6850
6851 edits.push((start_point..end_point, lines.join("\n")));
6852
6853 // Selections must change based on added and removed line count
6854 let start_row =
6855 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6856 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6857 new_selections.push(Selection {
6858 id: selection.id,
6859 start: start_row,
6860 end: end_row,
6861 goal: SelectionGoal::None,
6862 reversed: selection.reversed,
6863 });
6864
6865 if lines_after > lines_before {
6866 added_lines += lines_after - lines_before;
6867 } else if lines_before > lines_after {
6868 removed_lines += lines_before - lines_after;
6869 }
6870 }
6871
6872 self.transact(window, cx, |this, window, cx| {
6873 let buffer = this.buffer.update(cx, |buffer, cx| {
6874 buffer.edit(edits, None, cx);
6875 buffer.snapshot(cx)
6876 });
6877
6878 // Recalculate offsets on newly edited buffer
6879 let new_selections = new_selections
6880 .iter()
6881 .map(|s| {
6882 let start_point = Point::new(s.start.0, 0);
6883 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6884 Selection {
6885 id: s.id,
6886 start: buffer.point_to_offset(start_point),
6887 end: buffer.point_to_offset(end_point),
6888 goal: s.goal,
6889 reversed: s.reversed,
6890 }
6891 })
6892 .collect();
6893
6894 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6895 s.select(new_selections);
6896 });
6897
6898 this.request_autoscroll(Autoscroll::fit(), cx);
6899 });
6900 }
6901
6902 pub fn convert_to_upper_case(
6903 &mut self,
6904 _: &ConvertToUpperCase,
6905 window: &mut Window,
6906 cx: &mut Context<Self>,
6907 ) {
6908 self.manipulate_text(window, cx, |text| text.to_uppercase())
6909 }
6910
6911 pub fn convert_to_lower_case(
6912 &mut self,
6913 _: &ConvertToLowerCase,
6914 window: &mut Window,
6915 cx: &mut Context<Self>,
6916 ) {
6917 self.manipulate_text(window, cx, |text| text.to_lowercase())
6918 }
6919
6920 pub fn convert_to_title_case(
6921 &mut self,
6922 _: &ConvertToTitleCase,
6923 window: &mut Window,
6924 cx: &mut Context<Self>,
6925 ) {
6926 self.manipulate_text(window, cx, |text| {
6927 text.split('\n')
6928 .map(|line| line.to_case(Case::Title))
6929 .join("\n")
6930 })
6931 }
6932
6933 pub fn convert_to_snake_case(
6934 &mut self,
6935 _: &ConvertToSnakeCase,
6936 window: &mut Window,
6937 cx: &mut Context<Self>,
6938 ) {
6939 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
6940 }
6941
6942 pub fn convert_to_kebab_case(
6943 &mut self,
6944 _: &ConvertToKebabCase,
6945 window: &mut Window,
6946 cx: &mut Context<Self>,
6947 ) {
6948 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
6949 }
6950
6951 pub fn convert_to_upper_camel_case(
6952 &mut self,
6953 _: &ConvertToUpperCamelCase,
6954 window: &mut Window,
6955 cx: &mut Context<Self>,
6956 ) {
6957 self.manipulate_text(window, cx, |text| {
6958 text.split('\n')
6959 .map(|line| line.to_case(Case::UpperCamel))
6960 .join("\n")
6961 })
6962 }
6963
6964 pub fn convert_to_lower_camel_case(
6965 &mut self,
6966 _: &ConvertToLowerCamelCase,
6967 window: &mut Window,
6968 cx: &mut Context<Self>,
6969 ) {
6970 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
6971 }
6972
6973 pub fn convert_to_opposite_case(
6974 &mut self,
6975 _: &ConvertToOppositeCase,
6976 window: &mut Window,
6977 cx: &mut Context<Self>,
6978 ) {
6979 self.manipulate_text(window, cx, |text| {
6980 text.chars()
6981 .fold(String::with_capacity(text.len()), |mut t, c| {
6982 if c.is_uppercase() {
6983 t.extend(c.to_lowercase());
6984 } else {
6985 t.extend(c.to_uppercase());
6986 }
6987 t
6988 })
6989 })
6990 }
6991
6992 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
6993 where
6994 Fn: FnMut(&str) -> String,
6995 {
6996 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6997 let buffer = self.buffer.read(cx).snapshot(cx);
6998
6999 let mut new_selections = Vec::new();
7000 let mut edits = Vec::new();
7001 let mut selection_adjustment = 0i32;
7002
7003 for selection in self.selections.all::<usize>(cx) {
7004 let selection_is_empty = selection.is_empty();
7005
7006 let (start, end) = if selection_is_empty {
7007 let word_range = movement::surrounding_word(
7008 &display_map,
7009 selection.start.to_display_point(&display_map),
7010 );
7011 let start = word_range.start.to_offset(&display_map, Bias::Left);
7012 let end = word_range.end.to_offset(&display_map, Bias::Left);
7013 (start, end)
7014 } else {
7015 (selection.start, selection.end)
7016 };
7017
7018 let text = buffer.text_for_range(start..end).collect::<String>();
7019 let old_length = text.len() as i32;
7020 let text = callback(&text);
7021
7022 new_selections.push(Selection {
7023 start: (start as i32 - selection_adjustment) as usize,
7024 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
7025 goal: SelectionGoal::None,
7026 ..selection
7027 });
7028
7029 selection_adjustment += old_length - text.len() as i32;
7030
7031 edits.push((start..end, text));
7032 }
7033
7034 self.transact(window, cx, |this, window, cx| {
7035 this.buffer.update(cx, |buffer, cx| {
7036 buffer.edit(edits, None, cx);
7037 });
7038
7039 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7040 s.select(new_selections);
7041 });
7042
7043 this.request_autoscroll(Autoscroll::fit(), cx);
7044 });
7045 }
7046
7047 pub fn duplicate(
7048 &mut self,
7049 upwards: bool,
7050 whole_lines: bool,
7051 window: &mut Window,
7052 cx: &mut Context<Self>,
7053 ) {
7054 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7055 let buffer = &display_map.buffer_snapshot;
7056 let selections = self.selections.all::<Point>(cx);
7057
7058 let mut edits = Vec::new();
7059 let mut selections_iter = selections.iter().peekable();
7060 while let Some(selection) = selections_iter.next() {
7061 let mut rows = selection.spanned_rows(false, &display_map);
7062 // duplicate line-wise
7063 if whole_lines || selection.start == selection.end {
7064 // Avoid duplicating the same lines twice.
7065 while let Some(next_selection) = selections_iter.peek() {
7066 let next_rows = next_selection.spanned_rows(false, &display_map);
7067 if next_rows.start < rows.end {
7068 rows.end = next_rows.end;
7069 selections_iter.next().unwrap();
7070 } else {
7071 break;
7072 }
7073 }
7074
7075 // Copy the text from the selected row region and splice it either at the start
7076 // or end of the region.
7077 let start = Point::new(rows.start.0, 0);
7078 let end = Point::new(
7079 rows.end.previous_row().0,
7080 buffer.line_len(rows.end.previous_row()),
7081 );
7082 let text = buffer
7083 .text_for_range(start..end)
7084 .chain(Some("\n"))
7085 .collect::<String>();
7086 let insert_location = if upwards {
7087 Point::new(rows.end.0, 0)
7088 } else {
7089 start
7090 };
7091 edits.push((insert_location..insert_location, text));
7092 } else {
7093 // duplicate character-wise
7094 let start = selection.start;
7095 let end = selection.end;
7096 let text = buffer.text_for_range(start..end).collect::<String>();
7097 edits.push((selection.end..selection.end, text));
7098 }
7099 }
7100
7101 self.transact(window, cx, |this, _, cx| {
7102 this.buffer.update(cx, |buffer, cx| {
7103 buffer.edit(edits, None, cx);
7104 });
7105
7106 this.request_autoscroll(Autoscroll::fit(), cx);
7107 });
7108 }
7109
7110 pub fn duplicate_line_up(
7111 &mut self,
7112 _: &DuplicateLineUp,
7113 window: &mut Window,
7114 cx: &mut Context<Self>,
7115 ) {
7116 self.duplicate(true, true, window, cx);
7117 }
7118
7119 pub fn duplicate_line_down(
7120 &mut self,
7121 _: &DuplicateLineDown,
7122 window: &mut Window,
7123 cx: &mut Context<Self>,
7124 ) {
7125 self.duplicate(false, true, window, cx);
7126 }
7127
7128 pub fn duplicate_selection(
7129 &mut self,
7130 _: &DuplicateSelection,
7131 window: &mut Window,
7132 cx: &mut Context<Self>,
7133 ) {
7134 self.duplicate(false, false, window, cx);
7135 }
7136
7137 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7138 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7139 let buffer = self.buffer.read(cx).snapshot(cx);
7140
7141 let mut edits = Vec::new();
7142 let mut unfold_ranges = Vec::new();
7143 let mut refold_creases = Vec::new();
7144
7145 let selections = self.selections.all::<Point>(cx);
7146 let mut selections = selections.iter().peekable();
7147 let mut contiguous_row_selections = Vec::new();
7148 let mut new_selections = Vec::new();
7149
7150 while let Some(selection) = selections.next() {
7151 // Find all the selections that span a contiguous row range
7152 let (start_row, end_row) = consume_contiguous_rows(
7153 &mut contiguous_row_selections,
7154 selection,
7155 &display_map,
7156 &mut selections,
7157 );
7158
7159 // Move the text spanned by the row range to be before the line preceding the row range
7160 if start_row.0 > 0 {
7161 let range_to_move = Point::new(
7162 start_row.previous_row().0,
7163 buffer.line_len(start_row.previous_row()),
7164 )
7165 ..Point::new(
7166 end_row.previous_row().0,
7167 buffer.line_len(end_row.previous_row()),
7168 );
7169 let insertion_point = display_map
7170 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7171 .0;
7172
7173 // Don't move lines across excerpts
7174 if buffer
7175 .excerpt_containing(insertion_point..range_to_move.end)
7176 .is_some()
7177 {
7178 let text = buffer
7179 .text_for_range(range_to_move.clone())
7180 .flat_map(|s| s.chars())
7181 .skip(1)
7182 .chain(['\n'])
7183 .collect::<String>();
7184
7185 edits.push((
7186 buffer.anchor_after(range_to_move.start)
7187 ..buffer.anchor_before(range_to_move.end),
7188 String::new(),
7189 ));
7190 let insertion_anchor = buffer.anchor_after(insertion_point);
7191 edits.push((insertion_anchor..insertion_anchor, text));
7192
7193 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7194
7195 // Move selections up
7196 new_selections.extend(contiguous_row_selections.drain(..).map(
7197 |mut selection| {
7198 selection.start.row -= row_delta;
7199 selection.end.row -= row_delta;
7200 selection
7201 },
7202 ));
7203
7204 // Move folds up
7205 unfold_ranges.push(range_to_move.clone());
7206 for fold in display_map.folds_in_range(
7207 buffer.anchor_before(range_to_move.start)
7208 ..buffer.anchor_after(range_to_move.end),
7209 ) {
7210 let mut start = fold.range.start.to_point(&buffer);
7211 let mut end = fold.range.end.to_point(&buffer);
7212 start.row -= row_delta;
7213 end.row -= row_delta;
7214 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7215 }
7216 }
7217 }
7218
7219 // If we didn't move line(s), preserve the existing selections
7220 new_selections.append(&mut contiguous_row_selections);
7221 }
7222
7223 self.transact(window, cx, |this, window, cx| {
7224 this.unfold_ranges(&unfold_ranges, true, true, cx);
7225 this.buffer.update(cx, |buffer, cx| {
7226 for (range, text) in edits {
7227 buffer.edit([(range, text)], None, cx);
7228 }
7229 });
7230 this.fold_creases(refold_creases, true, window, cx);
7231 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7232 s.select(new_selections);
7233 })
7234 });
7235 }
7236
7237 pub fn move_line_down(
7238 &mut self,
7239 _: &MoveLineDown,
7240 window: &mut Window,
7241 cx: &mut Context<Self>,
7242 ) {
7243 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7244 let buffer = self.buffer.read(cx).snapshot(cx);
7245
7246 let mut edits = Vec::new();
7247 let mut unfold_ranges = Vec::new();
7248 let mut refold_creases = Vec::new();
7249
7250 let selections = self.selections.all::<Point>(cx);
7251 let mut selections = selections.iter().peekable();
7252 let mut contiguous_row_selections = Vec::new();
7253 let mut new_selections = Vec::new();
7254
7255 while let Some(selection) = selections.next() {
7256 // Find all the selections that span a contiguous row range
7257 let (start_row, end_row) = consume_contiguous_rows(
7258 &mut contiguous_row_selections,
7259 selection,
7260 &display_map,
7261 &mut selections,
7262 );
7263
7264 // Move the text spanned by the row range to be after the last line of the row range
7265 if end_row.0 <= buffer.max_point().row {
7266 let range_to_move =
7267 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7268 let insertion_point = display_map
7269 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7270 .0;
7271
7272 // Don't move lines across excerpt boundaries
7273 if buffer
7274 .excerpt_containing(range_to_move.start..insertion_point)
7275 .is_some()
7276 {
7277 let mut text = String::from("\n");
7278 text.extend(buffer.text_for_range(range_to_move.clone()));
7279 text.pop(); // Drop trailing newline
7280 edits.push((
7281 buffer.anchor_after(range_to_move.start)
7282 ..buffer.anchor_before(range_to_move.end),
7283 String::new(),
7284 ));
7285 let insertion_anchor = buffer.anchor_after(insertion_point);
7286 edits.push((insertion_anchor..insertion_anchor, text));
7287
7288 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7289
7290 // Move selections down
7291 new_selections.extend(contiguous_row_selections.drain(..).map(
7292 |mut selection| {
7293 selection.start.row += row_delta;
7294 selection.end.row += row_delta;
7295 selection
7296 },
7297 ));
7298
7299 // Move folds down
7300 unfold_ranges.push(range_to_move.clone());
7301 for fold in display_map.folds_in_range(
7302 buffer.anchor_before(range_to_move.start)
7303 ..buffer.anchor_after(range_to_move.end),
7304 ) {
7305 let mut start = fold.range.start.to_point(&buffer);
7306 let mut end = fold.range.end.to_point(&buffer);
7307 start.row += row_delta;
7308 end.row += row_delta;
7309 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7310 }
7311 }
7312 }
7313
7314 // If we didn't move line(s), preserve the existing selections
7315 new_selections.append(&mut contiguous_row_selections);
7316 }
7317
7318 self.transact(window, cx, |this, window, cx| {
7319 this.unfold_ranges(&unfold_ranges, true, true, cx);
7320 this.buffer.update(cx, |buffer, cx| {
7321 for (range, text) in edits {
7322 buffer.edit([(range, text)], None, cx);
7323 }
7324 });
7325 this.fold_creases(refold_creases, true, window, cx);
7326 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7327 s.select(new_selections)
7328 });
7329 });
7330 }
7331
7332 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7333 let text_layout_details = &self.text_layout_details(window);
7334 self.transact(window, cx, |this, window, cx| {
7335 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7336 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7337 let line_mode = s.line_mode;
7338 s.move_with(|display_map, selection| {
7339 if !selection.is_empty() || line_mode {
7340 return;
7341 }
7342
7343 let mut head = selection.head();
7344 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7345 if head.column() == display_map.line_len(head.row()) {
7346 transpose_offset = display_map
7347 .buffer_snapshot
7348 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7349 }
7350
7351 if transpose_offset == 0 {
7352 return;
7353 }
7354
7355 *head.column_mut() += 1;
7356 head = display_map.clip_point(head, Bias::Right);
7357 let goal = SelectionGoal::HorizontalPosition(
7358 display_map
7359 .x_for_display_point(head, text_layout_details)
7360 .into(),
7361 );
7362 selection.collapse_to(head, goal);
7363
7364 let transpose_start = display_map
7365 .buffer_snapshot
7366 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7367 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7368 let transpose_end = display_map
7369 .buffer_snapshot
7370 .clip_offset(transpose_offset + 1, Bias::Right);
7371 if let Some(ch) =
7372 display_map.buffer_snapshot.chars_at(transpose_start).next()
7373 {
7374 edits.push((transpose_start..transpose_offset, String::new()));
7375 edits.push((transpose_end..transpose_end, ch.to_string()));
7376 }
7377 }
7378 });
7379 edits
7380 });
7381 this.buffer
7382 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7383 let selections = this.selections.all::<usize>(cx);
7384 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7385 s.select(selections);
7386 });
7387 });
7388 }
7389
7390 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7391 self.rewrap_impl(IsVimMode::No, cx)
7392 }
7393
7394 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7395 let buffer = self.buffer.read(cx).snapshot(cx);
7396 let selections = self.selections.all::<Point>(cx);
7397 let mut selections = selections.iter().peekable();
7398
7399 let mut edits = Vec::new();
7400 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7401
7402 while let Some(selection) = selections.next() {
7403 let mut start_row = selection.start.row;
7404 let mut end_row = selection.end.row;
7405
7406 // Skip selections that overlap with a range that has already been rewrapped.
7407 let selection_range = start_row..end_row;
7408 if rewrapped_row_ranges
7409 .iter()
7410 .any(|range| range.overlaps(&selection_range))
7411 {
7412 continue;
7413 }
7414
7415 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7416
7417 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7418 match language_scope.language_name().as_ref() {
7419 "Markdown" | "Plain Text" => {
7420 should_rewrap = true;
7421 }
7422 _ => {}
7423 }
7424 }
7425
7426 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7427
7428 // Since not all lines in the selection may be at the same indent
7429 // level, choose the indent size that is the most common between all
7430 // of the lines.
7431 //
7432 // If there is a tie, we use the deepest indent.
7433 let (indent_size, indent_end) = {
7434 let mut indent_size_occurrences = HashMap::default();
7435 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7436
7437 for row in start_row..=end_row {
7438 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7439 rows_by_indent_size.entry(indent).or_default().push(row);
7440 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7441 }
7442
7443 let indent_size = indent_size_occurrences
7444 .into_iter()
7445 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7446 .map(|(indent, _)| indent)
7447 .unwrap_or_default();
7448 let row = rows_by_indent_size[&indent_size][0];
7449 let indent_end = Point::new(row, indent_size.len);
7450
7451 (indent_size, indent_end)
7452 };
7453
7454 let mut line_prefix = indent_size.chars().collect::<String>();
7455
7456 if let Some(comment_prefix) =
7457 buffer
7458 .language_scope_at(selection.head())
7459 .and_then(|language| {
7460 language
7461 .line_comment_prefixes()
7462 .iter()
7463 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7464 .cloned()
7465 })
7466 {
7467 line_prefix.push_str(&comment_prefix);
7468 should_rewrap = true;
7469 }
7470
7471 if !should_rewrap {
7472 continue;
7473 }
7474
7475 if selection.is_empty() {
7476 'expand_upwards: while start_row > 0 {
7477 let prev_row = start_row - 1;
7478 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7479 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7480 {
7481 start_row = prev_row;
7482 } else {
7483 break 'expand_upwards;
7484 }
7485 }
7486
7487 'expand_downwards: while end_row < buffer.max_point().row {
7488 let next_row = end_row + 1;
7489 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7490 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7491 {
7492 end_row = next_row;
7493 } else {
7494 break 'expand_downwards;
7495 }
7496 }
7497 }
7498
7499 let start = Point::new(start_row, 0);
7500 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7501 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7502 let Some(lines_without_prefixes) = selection_text
7503 .lines()
7504 .map(|line| {
7505 line.strip_prefix(&line_prefix)
7506 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7507 .ok_or_else(|| {
7508 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7509 })
7510 })
7511 .collect::<Result<Vec<_>, _>>()
7512 .log_err()
7513 else {
7514 continue;
7515 };
7516
7517 let wrap_column = buffer
7518 .settings_at(Point::new(start_row, 0), cx)
7519 .preferred_line_length as usize;
7520 let wrapped_text = wrap_with_prefix(
7521 line_prefix,
7522 lines_without_prefixes.join(" "),
7523 wrap_column,
7524 tab_size,
7525 );
7526
7527 // TODO: should always use char-based diff while still supporting cursor behavior that
7528 // matches vim.
7529 let diff = match is_vim_mode {
7530 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7531 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7532 };
7533 let mut offset = start.to_offset(&buffer);
7534 let mut moved_since_edit = true;
7535
7536 for change in diff.iter_all_changes() {
7537 let value = change.value();
7538 match change.tag() {
7539 ChangeTag::Equal => {
7540 offset += value.len();
7541 moved_since_edit = true;
7542 }
7543 ChangeTag::Delete => {
7544 let start = buffer.anchor_after(offset);
7545 let end = buffer.anchor_before(offset + value.len());
7546
7547 if moved_since_edit {
7548 edits.push((start..end, String::new()));
7549 } else {
7550 edits.last_mut().unwrap().0.end = end;
7551 }
7552
7553 offset += value.len();
7554 moved_since_edit = false;
7555 }
7556 ChangeTag::Insert => {
7557 if moved_since_edit {
7558 let anchor = buffer.anchor_after(offset);
7559 edits.push((anchor..anchor, value.to_string()));
7560 } else {
7561 edits.last_mut().unwrap().1.push_str(value);
7562 }
7563
7564 moved_since_edit = false;
7565 }
7566 }
7567 }
7568
7569 rewrapped_row_ranges.push(start_row..=end_row);
7570 }
7571
7572 self.buffer
7573 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7574 }
7575
7576 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7577 let mut text = String::new();
7578 let buffer = self.buffer.read(cx).snapshot(cx);
7579 let mut selections = self.selections.all::<Point>(cx);
7580 let mut clipboard_selections = Vec::with_capacity(selections.len());
7581 {
7582 let max_point = buffer.max_point();
7583 let mut is_first = true;
7584 for selection in &mut selections {
7585 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7586 if is_entire_line {
7587 selection.start = Point::new(selection.start.row, 0);
7588 if !selection.is_empty() && selection.end.column == 0 {
7589 selection.end = cmp::min(max_point, selection.end);
7590 } else {
7591 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7592 }
7593 selection.goal = SelectionGoal::None;
7594 }
7595 if is_first {
7596 is_first = false;
7597 } else {
7598 text += "\n";
7599 }
7600 let mut len = 0;
7601 for chunk in buffer.text_for_range(selection.start..selection.end) {
7602 text.push_str(chunk);
7603 len += chunk.len();
7604 }
7605 clipboard_selections.push(ClipboardSelection {
7606 len,
7607 is_entire_line,
7608 first_line_indent: buffer
7609 .indent_size_for_line(MultiBufferRow(selection.start.row))
7610 .len,
7611 });
7612 }
7613 }
7614
7615 self.transact(window, cx, |this, window, cx| {
7616 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7617 s.select(selections);
7618 });
7619 this.insert("", window, cx);
7620 });
7621 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7622 }
7623
7624 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
7625 let item = self.cut_common(window, cx);
7626 cx.write_to_clipboard(item);
7627 }
7628
7629 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
7630 self.change_selections(None, window, cx, |s| {
7631 s.move_with(|snapshot, sel| {
7632 if sel.is_empty() {
7633 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7634 }
7635 });
7636 });
7637 let item = self.cut_common(window, cx);
7638 cx.set_global(KillRing(item))
7639 }
7640
7641 pub fn kill_ring_yank(
7642 &mut self,
7643 _: &KillRingYank,
7644 window: &mut Window,
7645 cx: &mut Context<Self>,
7646 ) {
7647 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7648 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7649 (kill_ring.text().to_string(), kill_ring.metadata_json())
7650 } else {
7651 return;
7652 }
7653 } else {
7654 return;
7655 };
7656 self.do_paste(&text, metadata, false, window, cx);
7657 }
7658
7659 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
7660 let selections = self.selections.all::<Point>(cx);
7661 let buffer = self.buffer.read(cx).read(cx);
7662 let mut text = String::new();
7663
7664 let mut clipboard_selections = Vec::with_capacity(selections.len());
7665 {
7666 let max_point = buffer.max_point();
7667 let mut is_first = true;
7668 for selection in selections.iter() {
7669 let mut start = selection.start;
7670 let mut end = selection.end;
7671 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7672 if is_entire_line {
7673 start = Point::new(start.row, 0);
7674 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7675 }
7676 if is_first {
7677 is_first = false;
7678 } else {
7679 text += "\n";
7680 }
7681 let mut len = 0;
7682 for chunk in buffer.text_for_range(start..end) {
7683 text.push_str(chunk);
7684 len += chunk.len();
7685 }
7686 clipboard_selections.push(ClipboardSelection {
7687 len,
7688 is_entire_line,
7689 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7690 });
7691 }
7692 }
7693
7694 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7695 text,
7696 clipboard_selections,
7697 ));
7698 }
7699
7700 pub fn do_paste(
7701 &mut self,
7702 text: &String,
7703 clipboard_selections: Option<Vec<ClipboardSelection>>,
7704 handle_entire_lines: bool,
7705 window: &mut Window,
7706 cx: &mut Context<Self>,
7707 ) {
7708 if self.read_only(cx) {
7709 return;
7710 }
7711
7712 let clipboard_text = Cow::Borrowed(text);
7713
7714 self.transact(window, cx, |this, window, cx| {
7715 if let Some(mut clipboard_selections) = clipboard_selections {
7716 let old_selections = this.selections.all::<usize>(cx);
7717 let all_selections_were_entire_line =
7718 clipboard_selections.iter().all(|s| s.is_entire_line);
7719 let first_selection_indent_column =
7720 clipboard_selections.first().map(|s| s.first_line_indent);
7721 if clipboard_selections.len() != old_selections.len() {
7722 clipboard_selections.drain(..);
7723 }
7724 let cursor_offset = this.selections.last::<usize>(cx).head();
7725 let mut auto_indent_on_paste = true;
7726
7727 this.buffer.update(cx, |buffer, cx| {
7728 let snapshot = buffer.read(cx);
7729 auto_indent_on_paste =
7730 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7731
7732 let mut start_offset = 0;
7733 let mut edits = Vec::new();
7734 let mut original_indent_columns = Vec::new();
7735 for (ix, selection) in old_selections.iter().enumerate() {
7736 let to_insert;
7737 let entire_line;
7738 let original_indent_column;
7739 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7740 let end_offset = start_offset + clipboard_selection.len;
7741 to_insert = &clipboard_text[start_offset..end_offset];
7742 entire_line = clipboard_selection.is_entire_line;
7743 start_offset = end_offset + 1;
7744 original_indent_column = Some(clipboard_selection.first_line_indent);
7745 } else {
7746 to_insert = clipboard_text.as_str();
7747 entire_line = all_selections_were_entire_line;
7748 original_indent_column = first_selection_indent_column
7749 }
7750
7751 // If the corresponding selection was empty when this slice of the
7752 // clipboard text was written, then the entire line containing the
7753 // selection was copied. If this selection is also currently empty,
7754 // then paste the line before the current line of the buffer.
7755 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7756 let column = selection.start.to_point(&snapshot).column as usize;
7757 let line_start = selection.start - column;
7758 line_start..line_start
7759 } else {
7760 selection.range()
7761 };
7762
7763 edits.push((range, to_insert));
7764 original_indent_columns.extend(original_indent_column);
7765 }
7766 drop(snapshot);
7767
7768 buffer.edit(
7769 edits,
7770 if auto_indent_on_paste {
7771 Some(AutoindentMode::Block {
7772 original_indent_columns,
7773 })
7774 } else {
7775 None
7776 },
7777 cx,
7778 );
7779 });
7780
7781 let selections = this.selections.all::<usize>(cx);
7782 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7783 s.select(selections)
7784 });
7785 } else {
7786 this.insert(&clipboard_text, window, cx);
7787 }
7788 });
7789 }
7790
7791 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
7792 if let Some(item) = cx.read_from_clipboard() {
7793 let entries = item.entries();
7794
7795 match entries.first() {
7796 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7797 // of all the pasted entries.
7798 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7799 .do_paste(
7800 clipboard_string.text(),
7801 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7802 true,
7803 window,
7804 cx,
7805 ),
7806 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
7807 }
7808 }
7809 }
7810
7811 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
7812 if self.read_only(cx) {
7813 return;
7814 }
7815
7816 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7817 if let Some((selections, _)) =
7818 self.selection_history.transaction(transaction_id).cloned()
7819 {
7820 self.change_selections(None, window, cx, |s| {
7821 s.select_anchors(selections.to_vec());
7822 });
7823 }
7824 self.request_autoscroll(Autoscroll::fit(), cx);
7825 self.unmark_text(window, cx);
7826 self.refresh_inline_completion(true, false, window, cx);
7827 cx.emit(EditorEvent::Edited { transaction_id });
7828 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7829 }
7830 }
7831
7832 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
7833 if self.read_only(cx) {
7834 return;
7835 }
7836
7837 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7838 if let Some((_, Some(selections))) =
7839 self.selection_history.transaction(transaction_id).cloned()
7840 {
7841 self.change_selections(None, window, cx, |s| {
7842 s.select_anchors(selections.to_vec());
7843 });
7844 }
7845 self.request_autoscroll(Autoscroll::fit(), cx);
7846 self.unmark_text(window, cx);
7847 self.refresh_inline_completion(true, false, window, cx);
7848 cx.emit(EditorEvent::Edited { transaction_id });
7849 }
7850 }
7851
7852 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
7853 self.buffer
7854 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7855 }
7856
7857 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
7858 self.buffer
7859 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7860 }
7861
7862 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
7863 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7864 let line_mode = s.line_mode;
7865 s.move_with(|map, selection| {
7866 let cursor = if selection.is_empty() && !line_mode {
7867 movement::left(map, selection.start)
7868 } else {
7869 selection.start
7870 };
7871 selection.collapse_to(cursor, SelectionGoal::None);
7872 });
7873 })
7874 }
7875
7876 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
7877 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7878 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7879 })
7880 }
7881
7882 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
7883 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7884 let line_mode = s.line_mode;
7885 s.move_with(|map, selection| {
7886 let cursor = if selection.is_empty() && !line_mode {
7887 movement::right(map, selection.end)
7888 } else {
7889 selection.end
7890 };
7891 selection.collapse_to(cursor, SelectionGoal::None)
7892 });
7893 })
7894 }
7895
7896 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
7897 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7898 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7899 })
7900 }
7901
7902 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
7903 if self.take_rename(true, window, cx).is_some() {
7904 return;
7905 }
7906
7907 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7908 cx.propagate();
7909 return;
7910 }
7911
7912 let text_layout_details = &self.text_layout_details(window);
7913 let selection_count = self.selections.count();
7914 let first_selection = self.selections.first_anchor();
7915
7916 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7917 let line_mode = s.line_mode;
7918 s.move_with(|map, selection| {
7919 if !selection.is_empty() && !line_mode {
7920 selection.goal = SelectionGoal::None;
7921 }
7922 let (cursor, goal) = movement::up(
7923 map,
7924 selection.start,
7925 selection.goal,
7926 false,
7927 text_layout_details,
7928 );
7929 selection.collapse_to(cursor, goal);
7930 });
7931 });
7932
7933 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7934 {
7935 cx.propagate();
7936 }
7937 }
7938
7939 pub fn move_up_by_lines(
7940 &mut self,
7941 action: &MoveUpByLines,
7942 window: &mut Window,
7943 cx: &mut Context<Self>,
7944 ) {
7945 if self.take_rename(true, window, cx).is_some() {
7946 return;
7947 }
7948
7949 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7950 cx.propagate();
7951 return;
7952 }
7953
7954 let text_layout_details = &self.text_layout_details(window);
7955
7956 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7957 let line_mode = s.line_mode;
7958 s.move_with(|map, selection| {
7959 if !selection.is_empty() && !line_mode {
7960 selection.goal = SelectionGoal::None;
7961 }
7962 let (cursor, goal) = movement::up_by_rows(
7963 map,
7964 selection.start,
7965 action.lines,
7966 selection.goal,
7967 false,
7968 text_layout_details,
7969 );
7970 selection.collapse_to(cursor, goal);
7971 });
7972 })
7973 }
7974
7975 pub fn move_down_by_lines(
7976 &mut self,
7977 action: &MoveDownByLines,
7978 window: &mut Window,
7979 cx: &mut Context<Self>,
7980 ) {
7981 if self.take_rename(true, window, cx).is_some() {
7982 return;
7983 }
7984
7985 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7986 cx.propagate();
7987 return;
7988 }
7989
7990 let text_layout_details = &self.text_layout_details(window);
7991
7992 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7993 let line_mode = s.line_mode;
7994 s.move_with(|map, selection| {
7995 if !selection.is_empty() && !line_mode {
7996 selection.goal = SelectionGoal::None;
7997 }
7998 let (cursor, goal) = movement::down_by_rows(
7999 map,
8000 selection.start,
8001 action.lines,
8002 selection.goal,
8003 false,
8004 text_layout_details,
8005 );
8006 selection.collapse_to(cursor, goal);
8007 });
8008 })
8009 }
8010
8011 pub fn select_down_by_lines(
8012 &mut self,
8013 action: &SelectDownByLines,
8014 window: &mut Window,
8015 cx: &mut Context<Self>,
8016 ) {
8017 let text_layout_details = &self.text_layout_details(window);
8018 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8019 s.move_heads_with(|map, head, goal| {
8020 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
8021 })
8022 })
8023 }
8024
8025 pub fn select_up_by_lines(
8026 &mut self,
8027 action: &SelectUpByLines,
8028 window: &mut Window,
8029 cx: &mut Context<Self>,
8030 ) {
8031 let text_layout_details = &self.text_layout_details(window);
8032 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8033 s.move_heads_with(|map, head, goal| {
8034 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8035 })
8036 })
8037 }
8038
8039 pub fn select_page_up(
8040 &mut self,
8041 _: &SelectPageUp,
8042 window: &mut Window,
8043 cx: &mut Context<Self>,
8044 ) {
8045 let Some(row_count) = self.visible_row_count() else {
8046 return;
8047 };
8048
8049 let text_layout_details = &self.text_layout_details(window);
8050
8051 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8052 s.move_heads_with(|map, head, goal| {
8053 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8054 })
8055 })
8056 }
8057
8058 pub fn move_page_up(
8059 &mut self,
8060 action: &MovePageUp,
8061 window: &mut Window,
8062 cx: &mut Context<Self>,
8063 ) {
8064 if self.take_rename(true, window, cx).is_some() {
8065 return;
8066 }
8067
8068 if self
8069 .context_menu
8070 .borrow_mut()
8071 .as_mut()
8072 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8073 .unwrap_or(false)
8074 {
8075 return;
8076 }
8077
8078 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8079 cx.propagate();
8080 return;
8081 }
8082
8083 let Some(row_count) = self.visible_row_count() else {
8084 return;
8085 };
8086
8087 let autoscroll = if action.center_cursor {
8088 Autoscroll::center()
8089 } else {
8090 Autoscroll::fit()
8091 };
8092
8093 let text_layout_details = &self.text_layout_details(window);
8094
8095 self.change_selections(Some(autoscroll), window, cx, |s| {
8096 let line_mode = s.line_mode;
8097 s.move_with(|map, selection| {
8098 if !selection.is_empty() && !line_mode {
8099 selection.goal = SelectionGoal::None;
8100 }
8101 let (cursor, goal) = movement::up_by_rows(
8102 map,
8103 selection.end,
8104 row_count,
8105 selection.goal,
8106 false,
8107 text_layout_details,
8108 );
8109 selection.collapse_to(cursor, goal);
8110 });
8111 });
8112 }
8113
8114 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8115 let text_layout_details = &self.text_layout_details(window);
8116 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8117 s.move_heads_with(|map, head, goal| {
8118 movement::up(map, head, goal, false, text_layout_details)
8119 })
8120 })
8121 }
8122
8123 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8124 self.take_rename(true, window, cx);
8125
8126 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8127 cx.propagate();
8128 return;
8129 }
8130
8131 let text_layout_details = &self.text_layout_details(window);
8132 let selection_count = self.selections.count();
8133 let first_selection = self.selections.first_anchor();
8134
8135 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8136 let line_mode = s.line_mode;
8137 s.move_with(|map, selection| {
8138 if !selection.is_empty() && !line_mode {
8139 selection.goal = SelectionGoal::None;
8140 }
8141 let (cursor, goal) = movement::down(
8142 map,
8143 selection.end,
8144 selection.goal,
8145 false,
8146 text_layout_details,
8147 );
8148 selection.collapse_to(cursor, goal);
8149 });
8150 });
8151
8152 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8153 {
8154 cx.propagate();
8155 }
8156 }
8157
8158 pub fn select_page_down(
8159 &mut self,
8160 _: &SelectPageDown,
8161 window: &mut Window,
8162 cx: &mut Context<Self>,
8163 ) {
8164 let Some(row_count) = self.visible_row_count() else {
8165 return;
8166 };
8167
8168 let text_layout_details = &self.text_layout_details(window);
8169
8170 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8171 s.move_heads_with(|map, head, goal| {
8172 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8173 })
8174 })
8175 }
8176
8177 pub fn move_page_down(
8178 &mut self,
8179 action: &MovePageDown,
8180 window: &mut Window,
8181 cx: &mut Context<Self>,
8182 ) {
8183 if self.take_rename(true, window, cx).is_some() {
8184 return;
8185 }
8186
8187 if self
8188 .context_menu
8189 .borrow_mut()
8190 .as_mut()
8191 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8192 .unwrap_or(false)
8193 {
8194 return;
8195 }
8196
8197 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8198 cx.propagate();
8199 return;
8200 }
8201
8202 let Some(row_count) = self.visible_row_count() else {
8203 return;
8204 };
8205
8206 let autoscroll = if action.center_cursor {
8207 Autoscroll::center()
8208 } else {
8209 Autoscroll::fit()
8210 };
8211
8212 let text_layout_details = &self.text_layout_details(window);
8213 self.change_selections(Some(autoscroll), window, cx, |s| {
8214 let line_mode = s.line_mode;
8215 s.move_with(|map, selection| {
8216 if !selection.is_empty() && !line_mode {
8217 selection.goal = SelectionGoal::None;
8218 }
8219 let (cursor, goal) = movement::down_by_rows(
8220 map,
8221 selection.end,
8222 row_count,
8223 selection.goal,
8224 false,
8225 text_layout_details,
8226 );
8227 selection.collapse_to(cursor, goal);
8228 });
8229 });
8230 }
8231
8232 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8233 let text_layout_details = &self.text_layout_details(window);
8234 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8235 s.move_heads_with(|map, head, goal| {
8236 movement::down(map, head, goal, false, text_layout_details)
8237 })
8238 });
8239 }
8240
8241 pub fn context_menu_first(
8242 &mut self,
8243 _: &ContextMenuFirst,
8244 _window: &mut Window,
8245 cx: &mut Context<Self>,
8246 ) {
8247 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8248 context_menu.select_first(self.completion_provider.as_deref(), cx);
8249 }
8250 }
8251
8252 pub fn context_menu_prev(
8253 &mut self,
8254 _: &ContextMenuPrev,
8255 _window: &mut Window,
8256 cx: &mut Context<Self>,
8257 ) {
8258 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8259 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8260 }
8261 }
8262
8263 pub fn context_menu_next(
8264 &mut self,
8265 _: &ContextMenuNext,
8266 _window: &mut Window,
8267 cx: &mut Context<Self>,
8268 ) {
8269 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8270 context_menu.select_next(self.completion_provider.as_deref(), cx);
8271 }
8272 }
8273
8274 pub fn context_menu_last(
8275 &mut self,
8276 _: &ContextMenuLast,
8277 _window: &mut Window,
8278 cx: &mut Context<Self>,
8279 ) {
8280 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8281 context_menu.select_last(self.completion_provider.as_deref(), cx);
8282 }
8283 }
8284
8285 pub fn move_to_previous_word_start(
8286 &mut self,
8287 _: &MoveToPreviousWordStart,
8288 window: &mut Window,
8289 cx: &mut Context<Self>,
8290 ) {
8291 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8292 s.move_cursors_with(|map, head, _| {
8293 (
8294 movement::previous_word_start(map, head),
8295 SelectionGoal::None,
8296 )
8297 });
8298 })
8299 }
8300
8301 pub fn move_to_previous_subword_start(
8302 &mut self,
8303 _: &MoveToPreviousSubwordStart,
8304 window: &mut Window,
8305 cx: &mut Context<Self>,
8306 ) {
8307 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8308 s.move_cursors_with(|map, head, _| {
8309 (
8310 movement::previous_subword_start(map, head),
8311 SelectionGoal::None,
8312 )
8313 });
8314 })
8315 }
8316
8317 pub fn select_to_previous_word_start(
8318 &mut self,
8319 _: &SelectToPreviousWordStart,
8320 window: &mut Window,
8321 cx: &mut Context<Self>,
8322 ) {
8323 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8324 s.move_heads_with(|map, head, _| {
8325 (
8326 movement::previous_word_start(map, head),
8327 SelectionGoal::None,
8328 )
8329 });
8330 })
8331 }
8332
8333 pub fn select_to_previous_subword_start(
8334 &mut self,
8335 _: &SelectToPreviousSubwordStart,
8336 window: &mut Window,
8337 cx: &mut Context<Self>,
8338 ) {
8339 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8340 s.move_heads_with(|map, head, _| {
8341 (
8342 movement::previous_subword_start(map, head),
8343 SelectionGoal::None,
8344 )
8345 });
8346 })
8347 }
8348
8349 pub fn delete_to_previous_word_start(
8350 &mut self,
8351 action: &DeleteToPreviousWordStart,
8352 window: &mut Window,
8353 cx: &mut Context<Self>,
8354 ) {
8355 self.transact(window, cx, |this, window, cx| {
8356 this.select_autoclose_pair(window, cx);
8357 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8358 let line_mode = s.line_mode;
8359 s.move_with(|map, selection| {
8360 if selection.is_empty() && !line_mode {
8361 let cursor = if action.ignore_newlines {
8362 movement::previous_word_start(map, selection.head())
8363 } else {
8364 movement::previous_word_start_or_newline(map, selection.head())
8365 };
8366 selection.set_head(cursor, SelectionGoal::None);
8367 }
8368 });
8369 });
8370 this.insert("", window, cx);
8371 });
8372 }
8373
8374 pub fn delete_to_previous_subword_start(
8375 &mut self,
8376 _: &DeleteToPreviousSubwordStart,
8377 window: &mut Window,
8378 cx: &mut Context<Self>,
8379 ) {
8380 self.transact(window, cx, |this, window, cx| {
8381 this.select_autoclose_pair(window, cx);
8382 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8383 let line_mode = s.line_mode;
8384 s.move_with(|map, selection| {
8385 if selection.is_empty() && !line_mode {
8386 let cursor = movement::previous_subword_start(map, selection.head());
8387 selection.set_head(cursor, SelectionGoal::None);
8388 }
8389 });
8390 });
8391 this.insert("", window, cx);
8392 });
8393 }
8394
8395 pub fn move_to_next_word_end(
8396 &mut self,
8397 _: &MoveToNextWordEnd,
8398 window: &mut Window,
8399 cx: &mut Context<Self>,
8400 ) {
8401 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8402 s.move_cursors_with(|map, head, _| {
8403 (movement::next_word_end(map, head), SelectionGoal::None)
8404 });
8405 })
8406 }
8407
8408 pub fn move_to_next_subword_end(
8409 &mut self,
8410 _: &MoveToNextSubwordEnd,
8411 window: &mut Window,
8412 cx: &mut Context<Self>,
8413 ) {
8414 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8415 s.move_cursors_with(|map, head, _| {
8416 (movement::next_subword_end(map, head), SelectionGoal::None)
8417 });
8418 })
8419 }
8420
8421 pub fn select_to_next_word_end(
8422 &mut self,
8423 _: &SelectToNextWordEnd,
8424 window: &mut Window,
8425 cx: &mut Context<Self>,
8426 ) {
8427 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8428 s.move_heads_with(|map, head, _| {
8429 (movement::next_word_end(map, head), SelectionGoal::None)
8430 });
8431 })
8432 }
8433
8434 pub fn select_to_next_subword_end(
8435 &mut self,
8436 _: &SelectToNextSubwordEnd,
8437 window: &mut Window,
8438 cx: &mut Context<Self>,
8439 ) {
8440 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8441 s.move_heads_with(|map, head, _| {
8442 (movement::next_subword_end(map, head), SelectionGoal::None)
8443 });
8444 })
8445 }
8446
8447 pub fn delete_to_next_word_end(
8448 &mut self,
8449 action: &DeleteToNextWordEnd,
8450 window: &mut Window,
8451 cx: &mut Context<Self>,
8452 ) {
8453 self.transact(window, cx, |this, window, cx| {
8454 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8455 let line_mode = s.line_mode;
8456 s.move_with(|map, selection| {
8457 if selection.is_empty() && !line_mode {
8458 let cursor = if action.ignore_newlines {
8459 movement::next_word_end(map, selection.head())
8460 } else {
8461 movement::next_word_end_or_newline(map, selection.head())
8462 };
8463 selection.set_head(cursor, SelectionGoal::None);
8464 }
8465 });
8466 });
8467 this.insert("", window, cx);
8468 });
8469 }
8470
8471 pub fn delete_to_next_subword_end(
8472 &mut self,
8473 _: &DeleteToNextSubwordEnd,
8474 window: &mut Window,
8475 cx: &mut Context<Self>,
8476 ) {
8477 self.transact(window, cx, |this, window, cx| {
8478 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8479 s.move_with(|map, selection| {
8480 if selection.is_empty() {
8481 let cursor = movement::next_subword_end(map, selection.head());
8482 selection.set_head(cursor, SelectionGoal::None);
8483 }
8484 });
8485 });
8486 this.insert("", window, cx);
8487 });
8488 }
8489
8490 pub fn move_to_beginning_of_line(
8491 &mut self,
8492 action: &MoveToBeginningOfLine,
8493 window: &mut Window,
8494 cx: &mut Context<Self>,
8495 ) {
8496 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8497 s.move_cursors_with(|map, head, _| {
8498 (
8499 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8500 SelectionGoal::None,
8501 )
8502 });
8503 })
8504 }
8505
8506 pub fn select_to_beginning_of_line(
8507 &mut self,
8508 action: &SelectToBeginningOfLine,
8509 window: &mut Window,
8510 cx: &mut Context<Self>,
8511 ) {
8512 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8513 s.move_heads_with(|map, head, _| {
8514 (
8515 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8516 SelectionGoal::None,
8517 )
8518 });
8519 });
8520 }
8521
8522 pub fn delete_to_beginning_of_line(
8523 &mut self,
8524 _: &DeleteToBeginningOfLine,
8525 window: &mut Window,
8526 cx: &mut Context<Self>,
8527 ) {
8528 self.transact(window, cx, |this, window, cx| {
8529 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8530 s.move_with(|_, selection| {
8531 selection.reversed = true;
8532 });
8533 });
8534
8535 this.select_to_beginning_of_line(
8536 &SelectToBeginningOfLine {
8537 stop_at_soft_wraps: false,
8538 },
8539 window,
8540 cx,
8541 );
8542 this.backspace(&Backspace, window, cx);
8543 });
8544 }
8545
8546 pub fn move_to_end_of_line(
8547 &mut self,
8548 action: &MoveToEndOfLine,
8549 window: &mut Window,
8550 cx: &mut Context<Self>,
8551 ) {
8552 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8553 s.move_cursors_with(|map, head, _| {
8554 (
8555 movement::line_end(map, head, action.stop_at_soft_wraps),
8556 SelectionGoal::None,
8557 )
8558 });
8559 })
8560 }
8561
8562 pub fn select_to_end_of_line(
8563 &mut self,
8564 action: &SelectToEndOfLine,
8565 window: &mut Window,
8566 cx: &mut Context<Self>,
8567 ) {
8568 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8569 s.move_heads_with(|map, head, _| {
8570 (
8571 movement::line_end(map, head, action.stop_at_soft_wraps),
8572 SelectionGoal::None,
8573 )
8574 });
8575 })
8576 }
8577
8578 pub fn delete_to_end_of_line(
8579 &mut self,
8580 _: &DeleteToEndOfLine,
8581 window: &mut Window,
8582 cx: &mut Context<Self>,
8583 ) {
8584 self.transact(window, cx, |this, window, cx| {
8585 this.select_to_end_of_line(
8586 &SelectToEndOfLine {
8587 stop_at_soft_wraps: false,
8588 },
8589 window,
8590 cx,
8591 );
8592 this.delete(&Delete, window, cx);
8593 });
8594 }
8595
8596 pub fn cut_to_end_of_line(
8597 &mut self,
8598 _: &CutToEndOfLine,
8599 window: &mut Window,
8600 cx: &mut Context<Self>,
8601 ) {
8602 self.transact(window, cx, |this, window, cx| {
8603 this.select_to_end_of_line(
8604 &SelectToEndOfLine {
8605 stop_at_soft_wraps: false,
8606 },
8607 window,
8608 cx,
8609 );
8610 this.cut(&Cut, window, cx);
8611 });
8612 }
8613
8614 pub fn move_to_start_of_paragraph(
8615 &mut self,
8616 _: &MoveToStartOfParagraph,
8617 window: &mut Window,
8618 cx: &mut Context<Self>,
8619 ) {
8620 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8621 cx.propagate();
8622 return;
8623 }
8624
8625 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8626 s.move_with(|map, selection| {
8627 selection.collapse_to(
8628 movement::start_of_paragraph(map, selection.head(), 1),
8629 SelectionGoal::None,
8630 )
8631 });
8632 })
8633 }
8634
8635 pub fn move_to_end_of_paragraph(
8636 &mut self,
8637 _: &MoveToEndOfParagraph,
8638 window: &mut Window,
8639 cx: &mut Context<Self>,
8640 ) {
8641 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8642 cx.propagate();
8643 return;
8644 }
8645
8646 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8647 s.move_with(|map, selection| {
8648 selection.collapse_to(
8649 movement::end_of_paragraph(map, selection.head(), 1),
8650 SelectionGoal::None,
8651 )
8652 });
8653 })
8654 }
8655
8656 pub fn select_to_start_of_paragraph(
8657 &mut self,
8658 _: &SelectToStartOfParagraph,
8659 window: &mut Window,
8660 cx: &mut Context<Self>,
8661 ) {
8662 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8663 cx.propagate();
8664 return;
8665 }
8666
8667 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8668 s.move_heads_with(|map, head, _| {
8669 (
8670 movement::start_of_paragraph(map, head, 1),
8671 SelectionGoal::None,
8672 )
8673 });
8674 })
8675 }
8676
8677 pub fn select_to_end_of_paragraph(
8678 &mut self,
8679 _: &SelectToEndOfParagraph,
8680 window: &mut Window,
8681 cx: &mut Context<Self>,
8682 ) {
8683 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8684 cx.propagate();
8685 return;
8686 }
8687
8688 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8689 s.move_heads_with(|map, head, _| {
8690 (
8691 movement::end_of_paragraph(map, head, 1),
8692 SelectionGoal::None,
8693 )
8694 });
8695 })
8696 }
8697
8698 pub fn move_to_beginning(
8699 &mut self,
8700 _: &MoveToBeginning,
8701 window: &mut Window,
8702 cx: &mut Context<Self>,
8703 ) {
8704 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8705 cx.propagate();
8706 return;
8707 }
8708
8709 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8710 s.select_ranges(vec![0..0]);
8711 });
8712 }
8713
8714 pub fn select_to_beginning(
8715 &mut self,
8716 _: &SelectToBeginning,
8717 window: &mut Window,
8718 cx: &mut Context<Self>,
8719 ) {
8720 let mut selection = self.selections.last::<Point>(cx);
8721 selection.set_head(Point::zero(), SelectionGoal::None);
8722
8723 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8724 s.select(vec![selection]);
8725 });
8726 }
8727
8728 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
8729 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8730 cx.propagate();
8731 return;
8732 }
8733
8734 let cursor = self.buffer.read(cx).read(cx).len();
8735 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8736 s.select_ranges(vec![cursor..cursor])
8737 });
8738 }
8739
8740 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8741 self.nav_history = nav_history;
8742 }
8743
8744 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8745 self.nav_history.as_ref()
8746 }
8747
8748 fn push_to_nav_history(
8749 &mut self,
8750 cursor_anchor: Anchor,
8751 new_position: Option<Point>,
8752 cx: &mut Context<Self>,
8753 ) {
8754 if let Some(nav_history) = self.nav_history.as_mut() {
8755 let buffer = self.buffer.read(cx).read(cx);
8756 let cursor_position = cursor_anchor.to_point(&buffer);
8757 let scroll_state = self.scroll_manager.anchor();
8758 let scroll_top_row = scroll_state.top_row(&buffer);
8759 drop(buffer);
8760
8761 if let Some(new_position) = new_position {
8762 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8763 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8764 return;
8765 }
8766 }
8767
8768 nav_history.push(
8769 Some(NavigationData {
8770 cursor_anchor,
8771 cursor_position,
8772 scroll_anchor: scroll_state,
8773 scroll_top_row,
8774 }),
8775 cx,
8776 );
8777 }
8778 }
8779
8780 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
8781 let buffer = self.buffer.read(cx).snapshot(cx);
8782 let mut selection = self.selections.first::<usize>(cx);
8783 selection.set_head(buffer.len(), SelectionGoal::None);
8784 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8785 s.select(vec![selection]);
8786 });
8787 }
8788
8789 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
8790 let end = self.buffer.read(cx).read(cx).len();
8791 self.change_selections(None, window, cx, |s| {
8792 s.select_ranges(vec![0..end]);
8793 });
8794 }
8795
8796 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
8797 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8798 let mut selections = self.selections.all::<Point>(cx);
8799 let max_point = display_map.buffer_snapshot.max_point();
8800 for selection in &mut selections {
8801 let rows = selection.spanned_rows(true, &display_map);
8802 selection.start = Point::new(rows.start.0, 0);
8803 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8804 selection.reversed = false;
8805 }
8806 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8807 s.select(selections);
8808 });
8809 }
8810
8811 pub fn split_selection_into_lines(
8812 &mut self,
8813 _: &SplitSelectionIntoLines,
8814 window: &mut Window,
8815 cx: &mut Context<Self>,
8816 ) {
8817 let mut to_unfold = Vec::new();
8818 let mut new_selection_ranges = Vec::new();
8819 {
8820 let selections = self.selections.all::<Point>(cx);
8821 let buffer = self.buffer.read(cx).read(cx);
8822 for selection in selections {
8823 for row in selection.start.row..selection.end.row {
8824 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8825 new_selection_ranges.push(cursor..cursor);
8826 }
8827 new_selection_ranges.push(selection.end..selection.end);
8828 to_unfold.push(selection.start..selection.end);
8829 }
8830 }
8831 self.unfold_ranges(&to_unfold, true, true, cx);
8832 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8833 s.select_ranges(new_selection_ranges);
8834 });
8835 }
8836
8837 pub fn add_selection_above(
8838 &mut self,
8839 _: &AddSelectionAbove,
8840 window: &mut Window,
8841 cx: &mut Context<Self>,
8842 ) {
8843 self.add_selection(true, window, cx);
8844 }
8845
8846 pub fn add_selection_below(
8847 &mut self,
8848 _: &AddSelectionBelow,
8849 window: &mut Window,
8850 cx: &mut Context<Self>,
8851 ) {
8852 self.add_selection(false, window, cx);
8853 }
8854
8855 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
8856 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8857 let mut selections = self.selections.all::<Point>(cx);
8858 let text_layout_details = self.text_layout_details(window);
8859 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8860 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8861 let range = oldest_selection.display_range(&display_map).sorted();
8862
8863 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8864 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8865 let positions = start_x.min(end_x)..start_x.max(end_x);
8866
8867 selections.clear();
8868 let mut stack = Vec::new();
8869 for row in range.start.row().0..=range.end.row().0 {
8870 if let Some(selection) = self.selections.build_columnar_selection(
8871 &display_map,
8872 DisplayRow(row),
8873 &positions,
8874 oldest_selection.reversed,
8875 &text_layout_details,
8876 ) {
8877 stack.push(selection.id);
8878 selections.push(selection);
8879 }
8880 }
8881
8882 if above {
8883 stack.reverse();
8884 }
8885
8886 AddSelectionsState { above, stack }
8887 });
8888
8889 let last_added_selection = *state.stack.last().unwrap();
8890 let mut new_selections = Vec::new();
8891 if above == state.above {
8892 let end_row = if above {
8893 DisplayRow(0)
8894 } else {
8895 display_map.max_point().row()
8896 };
8897
8898 'outer: for selection in selections {
8899 if selection.id == last_added_selection {
8900 let range = selection.display_range(&display_map).sorted();
8901 debug_assert_eq!(range.start.row(), range.end.row());
8902 let mut row = range.start.row();
8903 let positions =
8904 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8905 px(start)..px(end)
8906 } else {
8907 let start_x =
8908 display_map.x_for_display_point(range.start, &text_layout_details);
8909 let end_x =
8910 display_map.x_for_display_point(range.end, &text_layout_details);
8911 start_x.min(end_x)..start_x.max(end_x)
8912 };
8913
8914 while row != end_row {
8915 if above {
8916 row.0 -= 1;
8917 } else {
8918 row.0 += 1;
8919 }
8920
8921 if let Some(new_selection) = self.selections.build_columnar_selection(
8922 &display_map,
8923 row,
8924 &positions,
8925 selection.reversed,
8926 &text_layout_details,
8927 ) {
8928 state.stack.push(new_selection.id);
8929 if above {
8930 new_selections.push(new_selection);
8931 new_selections.push(selection);
8932 } else {
8933 new_selections.push(selection);
8934 new_selections.push(new_selection);
8935 }
8936
8937 continue 'outer;
8938 }
8939 }
8940 }
8941
8942 new_selections.push(selection);
8943 }
8944 } else {
8945 new_selections = selections;
8946 new_selections.retain(|s| s.id != last_added_selection);
8947 state.stack.pop();
8948 }
8949
8950 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8951 s.select(new_selections);
8952 });
8953 if state.stack.len() > 1 {
8954 self.add_selections_state = Some(state);
8955 }
8956 }
8957
8958 pub fn select_next_match_internal(
8959 &mut self,
8960 display_map: &DisplaySnapshot,
8961 replace_newest: bool,
8962 autoscroll: Option<Autoscroll>,
8963 window: &mut Window,
8964 cx: &mut Context<Self>,
8965 ) -> Result<()> {
8966 fn select_next_match_ranges(
8967 this: &mut Editor,
8968 range: Range<usize>,
8969 replace_newest: bool,
8970 auto_scroll: Option<Autoscroll>,
8971 window: &mut Window,
8972 cx: &mut Context<Editor>,
8973 ) {
8974 this.unfold_ranges(&[range.clone()], false, true, cx);
8975 this.change_selections(auto_scroll, window, cx, |s| {
8976 if replace_newest {
8977 s.delete(s.newest_anchor().id);
8978 }
8979 s.insert_range(range.clone());
8980 });
8981 }
8982
8983 let buffer = &display_map.buffer_snapshot;
8984 let mut selections = self.selections.all::<usize>(cx);
8985 if let Some(mut select_next_state) = self.select_next_state.take() {
8986 let query = &select_next_state.query;
8987 if !select_next_state.done {
8988 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8989 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8990 let mut next_selected_range = None;
8991
8992 let bytes_after_last_selection =
8993 buffer.bytes_in_range(last_selection.end..buffer.len());
8994 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8995 let query_matches = query
8996 .stream_find_iter(bytes_after_last_selection)
8997 .map(|result| (last_selection.end, result))
8998 .chain(
8999 query
9000 .stream_find_iter(bytes_before_first_selection)
9001 .map(|result| (0, result)),
9002 );
9003
9004 for (start_offset, query_match) in query_matches {
9005 let query_match = query_match.unwrap(); // can only fail due to I/O
9006 let offset_range =
9007 start_offset + query_match.start()..start_offset + query_match.end();
9008 let display_range = offset_range.start.to_display_point(display_map)
9009 ..offset_range.end.to_display_point(display_map);
9010
9011 if !select_next_state.wordwise
9012 || (!movement::is_inside_word(display_map, display_range.start)
9013 && !movement::is_inside_word(display_map, display_range.end))
9014 {
9015 // TODO: This is n^2, because we might check all the selections
9016 if !selections
9017 .iter()
9018 .any(|selection| selection.range().overlaps(&offset_range))
9019 {
9020 next_selected_range = Some(offset_range);
9021 break;
9022 }
9023 }
9024 }
9025
9026 if let Some(next_selected_range) = next_selected_range {
9027 select_next_match_ranges(
9028 self,
9029 next_selected_range,
9030 replace_newest,
9031 autoscroll,
9032 window,
9033 cx,
9034 );
9035 } else {
9036 select_next_state.done = true;
9037 }
9038 }
9039
9040 self.select_next_state = Some(select_next_state);
9041 } else {
9042 let mut only_carets = true;
9043 let mut same_text_selected = true;
9044 let mut selected_text = None;
9045
9046 let mut selections_iter = selections.iter().peekable();
9047 while let Some(selection) = selections_iter.next() {
9048 if selection.start != selection.end {
9049 only_carets = false;
9050 }
9051
9052 if same_text_selected {
9053 if selected_text.is_none() {
9054 selected_text =
9055 Some(buffer.text_for_range(selection.range()).collect::<String>());
9056 }
9057
9058 if let Some(next_selection) = selections_iter.peek() {
9059 if next_selection.range().len() == selection.range().len() {
9060 let next_selected_text = buffer
9061 .text_for_range(next_selection.range())
9062 .collect::<String>();
9063 if Some(next_selected_text) != selected_text {
9064 same_text_selected = false;
9065 selected_text = None;
9066 }
9067 } else {
9068 same_text_selected = false;
9069 selected_text = None;
9070 }
9071 }
9072 }
9073 }
9074
9075 if only_carets {
9076 for selection in &mut selections {
9077 let word_range = movement::surrounding_word(
9078 display_map,
9079 selection.start.to_display_point(display_map),
9080 );
9081 selection.start = word_range.start.to_offset(display_map, Bias::Left);
9082 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9083 selection.goal = SelectionGoal::None;
9084 selection.reversed = false;
9085 select_next_match_ranges(
9086 self,
9087 selection.start..selection.end,
9088 replace_newest,
9089 autoscroll,
9090 window,
9091 cx,
9092 );
9093 }
9094
9095 if selections.len() == 1 {
9096 let selection = selections
9097 .last()
9098 .expect("ensured that there's only one selection");
9099 let query = buffer
9100 .text_for_range(selection.start..selection.end)
9101 .collect::<String>();
9102 let is_empty = query.is_empty();
9103 let select_state = SelectNextState {
9104 query: AhoCorasick::new(&[query])?,
9105 wordwise: true,
9106 done: is_empty,
9107 };
9108 self.select_next_state = Some(select_state);
9109 } else {
9110 self.select_next_state = None;
9111 }
9112 } else if let Some(selected_text) = selected_text {
9113 self.select_next_state = Some(SelectNextState {
9114 query: AhoCorasick::new(&[selected_text])?,
9115 wordwise: false,
9116 done: false,
9117 });
9118 self.select_next_match_internal(
9119 display_map,
9120 replace_newest,
9121 autoscroll,
9122 window,
9123 cx,
9124 )?;
9125 }
9126 }
9127 Ok(())
9128 }
9129
9130 pub fn select_all_matches(
9131 &mut self,
9132 _action: &SelectAllMatches,
9133 window: &mut Window,
9134 cx: &mut Context<Self>,
9135 ) -> Result<()> {
9136 self.push_to_selection_history();
9137 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9138
9139 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9140 let Some(select_next_state) = self.select_next_state.as_mut() else {
9141 return Ok(());
9142 };
9143 if select_next_state.done {
9144 return Ok(());
9145 }
9146
9147 let mut new_selections = self.selections.all::<usize>(cx);
9148
9149 let buffer = &display_map.buffer_snapshot;
9150 let query_matches = select_next_state
9151 .query
9152 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9153
9154 for query_match in query_matches {
9155 let query_match = query_match.unwrap(); // can only fail due to I/O
9156 let offset_range = query_match.start()..query_match.end();
9157 let display_range = offset_range.start.to_display_point(&display_map)
9158 ..offset_range.end.to_display_point(&display_map);
9159
9160 if !select_next_state.wordwise
9161 || (!movement::is_inside_word(&display_map, display_range.start)
9162 && !movement::is_inside_word(&display_map, display_range.end))
9163 {
9164 self.selections.change_with(cx, |selections| {
9165 new_selections.push(Selection {
9166 id: selections.new_selection_id(),
9167 start: offset_range.start,
9168 end: offset_range.end,
9169 reversed: false,
9170 goal: SelectionGoal::None,
9171 });
9172 });
9173 }
9174 }
9175
9176 new_selections.sort_by_key(|selection| selection.start);
9177 let mut ix = 0;
9178 while ix + 1 < new_selections.len() {
9179 let current_selection = &new_selections[ix];
9180 let next_selection = &new_selections[ix + 1];
9181 if current_selection.range().overlaps(&next_selection.range()) {
9182 if current_selection.id < next_selection.id {
9183 new_selections.remove(ix + 1);
9184 } else {
9185 new_selections.remove(ix);
9186 }
9187 } else {
9188 ix += 1;
9189 }
9190 }
9191
9192 let reversed = self.selections.oldest::<usize>(cx).reversed;
9193
9194 for selection in new_selections.iter_mut() {
9195 selection.reversed = reversed;
9196 }
9197
9198 select_next_state.done = true;
9199 self.unfold_ranges(
9200 &new_selections
9201 .iter()
9202 .map(|selection| selection.range())
9203 .collect::<Vec<_>>(),
9204 false,
9205 false,
9206 cx,
9207 );
9208 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9209 selections.select(new_selections)
9210 });
9211
9212 Ok(())
9213 }
9214
9215 pub fn select_next(
9216 &mut self,
9217 action: &SelectNext,
9218 window: &mut Window,
9219 cx: &mut Context<Self>,
9220 ) -> Result<()> {
9221 self.push_to_selection_history();
9222 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9223 self.select_next_match_internal(
9224 &display_map,
9225 action.replace_newest,
9226 Some(Autoscroll::newest()),
9227 window,
9228 cx,
9229 )?;
9230 Ok(())
9231 }
9232
9233 pub fn select_previous(
9234 &mut self,
9235 action: &SelectPrevious,
9236 window: &mut Window,
9237 cx: &mut Context<Self>,
9238 ) -> Result<()> {
9239 self.push_to_selection_history();
9240 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9241 let buffer = &display_map.buffer_snapshot;
9242 let mut selections = self.selections.all::<usize>(cx);
9243 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9244 let query = &select_prev_state.query;
9245 if !select_prev_state.done {
9246 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9247 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9248 let mut next_selected_range = None;
9249 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9250 let bytes_before_last_selection =
9251 buffer.reversed_bytes_in_range(0..last_selection.start);
9252 let bytes_after_first_selection =
9253 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9254 let query_matches = query
9255 .stream_find_iter(bytes_before_last_selection)
9256 .map(|result| (last_selection.start, result))
9257 .chain(
9258 query
9259 .stream_find_iter(bytes_after_first_selection)
9260 .map(|result| (buffer.len(), result)),
9261 );
9262 for (end_offset, query_match) in query_matches {
9263 let query_match = query_match.unwrap(); // can only fail due to I/O
9264 let offset_range =
9265 end_offset - query_match.end()..end_offset - query_match.start();
9266 let display_range = offset_range.start.to_display_point(&display_map)
9267 ..offset_range.end.to_display_point(&display_map);
9268
9269 if !select_prev_state.wordwise
9270 || (!movement::is_inside_word(&display_map, display_range.start)
9271 && !movement::is_inside_word(&display_map, display_range.end))
9272 {
9273 next_selected_range = Some(offset_range);
9274 break;
9275 }
9276 }
9277
9278 if let Some(next_selected_range) = next_selected_range {
9279 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9280 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9281 if action.replace_newest {
9282 s.delete(s.newest_anchor().id);
9283 }
9284 s.insert_range(next_selected_range);
9285 });
9286 } else {
9287 select_prev_state.done = true;
9288 }
9289 }
9290
9291 self.select_prev_state = Some(select_prev_state);
9292 } else {
9293 let mut only_carets = true;
9294 let mut same_text_selected = true;
9295 let mut selected_text = None;
9296
9297 let mut selections_iter = selections.iter().peekable();
9298 while let Some(selection) = selections_iter.next() {
9299 if selection.start != selection.end {
9300 only_carets = false;
9301 }
9302
9303 if same_text_selected {
9304 if selected_text.is_none() {
9305 selected_text =
9306 Some(buffer.text_for_range(selection.range()).collect::<String>());
9307 }
9308
9309 if let Some(next_selection) = selections_iter.peek() {
9310 if next_selection.range().len() == selection.range().len() {
9311 let next_selected_text = buffer
9312 .text_for_range(next_selection.range())
9313 .collect::<String>();
9314 if Some(next_selected_text) != selected_text {
9315 same_text_selected = false;
9316 selected_text = None;
9317 }
9318 } else {
9319 same_text_selected = false;
9320 selected_text = None;
9321 }
9322 }
9323 }
9324 }
9325
9326 if only_carets {
9327 for selection in &mut selections {
9328 let word_range = movement::surrounding_word(
9329 &display_map,
9330 selection.start.to_display_point(&display_map),
9331 );
9332 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9333 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9334 selection.goal = SelectionGoal::None;
9335 selection.reversed = false;
9336 }
9337 if selections.len() == 1 {
9338 let selection = selections
9339 .last()
9340 .expect("ensured that there's only one selection");
9341 let query = buffer
9342 .text_for_range(selection.start..selection.end)
9343 .collect::<String>();
9344 let is_empty = query.is_empty();
9345 let select_state = SelectNextState {
9346 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9347 wordwise: true,
9348 done: is_empty,
9349 };
9350 self.select_prev_state = Some(select_state);
9351 } else {
9352 self.select_prev_state = None;
9353 }
9354
9355 self.unfold_ranges(
9356 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9357 false,
9358 true,
9359 cx,
9360 );
9361 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9362 s.select(selections);
9363 });
9364 } else if let Some(selected_text) = selected_text {
9365 self.select_prev_state = Some(SelectNextState {
9366 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9367 wordwise: false,
9368 done: false,
9369 });
9370 self.select_previous(action, window, cx)?;
9371 }
9372 }
9373 Ok(())
9374 }
9375
9376 pub fn toggle_comments(
9377 &mut self,
9378 action: &ToggleComments,
9379 window: &mut Window,
9380 cx: &mut Context<Self>,
9381 ) {
9382 if self.read_only(cx) {
9383 return;
9384 }
9385 let text_layout_details = &self.text_layout_details(window);
9386 self.transact(window, cx, |this, window, cx| {
9387 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9388 let mut edits = Vec::new();
9389 let mut selection_edit_ranges = Vec::new();
9390 let mut last_toggled_row = None;
9391 let snapshot = this.buffer.read(cx).read(cx);
9392 let empty_str: Arc<str> = Arc::default();
9393 let mut suffixes_inserted = Vec::new();
9394 let ignore_indent = action.ignore_indent;
9395
9396 fn comment_prefix_range(
9397 snapshot: &MultiBufferSnapshot,
9398 row: MultiBufferRow,
9399 comment_prefix: &str,
9400 comment_prefix_whitespace: &str,
9401 ignore_indent: bool,
9402 ) -> Range<Point> {
9403 let indent_size = if ignore_indent {
9404 0
9405 } else {
9406 snapshot.indent_size_for_line(row).len
9407 };
9408
9409 let start = Point::new(row.0, indent_size);
9410
9411 let mut line_bytes = snapshot
9412 .bytes_in_range(start..snapshot.max_point())
9413 .flatten()
9414 .copied();
9415
9416 // If this line currently begins with the line comment prefix, then record
9417 // the range containing the prefix.
9418 if line_bytes
9419 .by_ref()
9420 .take(comment_prefix.len())
9421 .eq(comment_prefix.bytes())
9422 {
9423 // Include any whitespace that matches the comment prefix.
9424 let matching_whitespace_len = line_bytes
9425 .zip(comment_prefix_whitespace.bytes())
9426 .take_while(|(a, b)| a == b)
9427 .count() as u32;
9428 let end = Point::new(
9429 start.row,
9430 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9431 );
9432 start..end
9433 } else {
9434 start..start
9435 }
9436 }
9437
9438 fn comment_suffix_range(
9439 snapshot: &MultiBufferSnapshot,
9440 row: MultiBufferRow,
9441 comment_suffix: &str,
9442 comment_suffix_has_leading_space: bool,
9443 ) -> Range<Point> {
9444 let end = Point::new(row.0, snapshot.line_len(row));
9445 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9446
9447 let mut line_end_bytes = snapshot
9448 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9449 .flatten()
9450 .copied();
9451
9452 let leading_space_len = if suffix_start_column > 0
9453 && line_end_bytes.next() == Some(b' ')
9454 && comment_suffix_has_leading_space
9455 {
9456 1
9457 } else {
9458 0
9459 };
9460
9461 // If this line currently begins with the line comment prefix, then record
9462 // the range containing the prefix.
9463 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9464 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9465 start..end
9466 } else {
9467 end..end
9468 }
9469 }
9470
9471 // TODO: Handle selections that cross excerpts
9472 for selection in &mut selections {
9473 let start_column = snapshot
9474 .indent_size_for_line(MultiBufferRow(selection.start.row))
9475 .len;
9476 let language = if let Some(language) =
9477 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9478 {
9479 language
9480 } else {
9481 continue;
9482 };
9483
9484 selection_edit_ranges.clear();
9485
9486 // If multiple selections contain a given row, avoid processing that
9487 // row more than once.
9488 let mut start_row = MultiBufferRow(selection.start.row);
9489 if last_toggled_row == Some(start_row) {
9490 start_row = start_row.next_row();
9491 }
9492 let end_row =
9493 if selection.end.row > selection.start.row && selection.end.column == 0 {
9494 MultiBufferRow(selection.end.row - 1)
9495 } else {
9496 MultiBufferRow(selection.end.row)
9497 };
9498 last_toggled_row = Some(end_row);
9499
9500 if start_row > end_row {
9501 continue;
9502 }
9503
9504 // If the language has line comments, toggle those.
9505 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9506
9507 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9508 if ignore_indent {
9509 full_comment_prefixes = full_comment_prefixes
9510 .into_iter()
9511 .map(|s| Arc::from(s.trim_end()))
9512 .collect();
9513 }
9514
9515 if !full_comment_prefixes.is_empty() {
9516 let first_prefix = full_comment_prefixes
9517 .first()
9518 .expect("prefixes is non-empty");
9519 let prefix_trimmed_lengths = full_comment_prefixes
9520 .iter()
9521 .map(|p| p.trim_end_matches(' ').len())
9522 .collect::<SmallVec<[usize; 4]>>();
9523
9524 let mut all_selection_lines_are_comments = true;
9525
9526 for row in start_row.0..=end_row.0 {
9527 let row = MultiBufferRow(row);
9528 if start_row < end_row && snapshot.is_line_blank(row) {
9529 continue;
9530 }
9531
9532 let prefix_range = full_comment_prefixes
9533 .iter()
9534 .zip(prefix_trimmed_lengths.iter().copied())
9535 .map(|(prefix, trimmed_prefix_len)| {
9536 comment_prefix_range(
9537 snapshot.deref(),
9538 row,
9539 &prefix[..trimmed_prefix_len],
9540 &prefix[trimmed_prefix_len..],
9541 ignore_indent,
9542 )
9543 })
9544 .max_by_key(|range| range.end.column - range.start.column)
9545 .expect("prefixes is non-empty");
9546
9547 if prefix_range.is_empty() {
9548 all_selection_lines_are_comments = false;
9549 }
9550
9551 selection_edit_ranges.push(prefix_range);
9552 }
9553
9554 if all_selection_lines_are_comments {
9555 edits.extend(
9556 selection_edit_ranges
9557 .iter()
9558 .cloned()
9559 .map(|range| (range, empty_str.clone())),
9560 );
9561 } else {
9562 let min_column = selection_edit_ranges
9563 .iter()
9564 .map(|range| range.start.column)
9565 .min()
9566 .unwrap_or(0);
9567 edits.extend(selection_edit_ranges.iter().map(|range| {
9568 let position = Point::new(range.start.row, min_column);
9569 (position..position, first_prefix.clone())
9570 }));
9571 }
9572 } else if let Some((full_comment_prefix, comment_suffix)) =
9573 language.block_comment_delimiters()
9574 {
9575 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9576 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9577 let prefix_range = comment_prefix_range(
9578 snapshot.deref(),
9579 start_row,
9580 comment_prefix,
9581 comment_prefix_whitespace,
9582 ignore_indent,
9583 );
9584 let suffix_range = comment_suffix_range(
9585 snapshot.deref(),
9586 end_row,
9587 comment_suffix.trim_start_matches(' '),
9588 comment_suffix.starts_with(' '),
9589 );
9590
9591 if prefix_range.is_empty() || suffix_range.is_empty() {
9592 edits.push((
9593 prefix_range.start..prefix_range.start,
9594 full_comment_prefix.clone(),
9595 ));
9596 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9597 suffixes_inserted.push((end_row, comment_suffix.len()));
9598 } else {
9599 edits.push((prefix_range, empty_str.clone()));
9600 edits.push((suffix_range, empty_str.clone()));
9601 }
9602 } else {
9603 continue;
9604 }
9605 }
9606
9607 drop(snapshot);
9608 this.buffer.update(cx, |buffer, cx| {
9609 buffer.edit(edits, None, cx);
9610 });
9611
9612 // Adjust selections so that they end before any comment suffixes that
9613 // were inserted.
9614 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9615 let mut selections = this.selections.all::<Point>(cx);
9616 let snapshot = this.buffer.read(cx).read(cx);
9617 for selection in &mut selections {
9618 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9619 match row.cmp(&MultiBufferRow(selection.end.row)) {
9620 Ordering::Less => {
9621 suffixes_inserted.next();
9622 continue;
9623 }
9624 Ordering::Greater => break,
9625 Ordering::Equal => {
9626 if selection.end.column == snapshot.line_len(row) {
9627 if selection.is_empty() {
9628 selection.start.column -= suffix_len as u32;
9629 }
9630 selection.end.column -= suffix_len as u32;
9631 }
9632 break;
9633 }
9634 }
9635 }
9636 }
9637
9638 drop(snapshot);
9639 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9640 s.select(selections)
9641 });
9642
9643 let selections = this.selections.all::<Point>(cx);
9644 let selections_on_single_row = selections.windows(2).all(|selections| {
9645 selections[0].start.row == selections[1].start.row
9646 && selections[0].end.row == selections[1].end.row
9647 && selections[0].start.row == selections[0].end.row
9648 });
9649 let selections_selecting = selections
9650 .iter()
9651 .any(|selection| selection.start != selection.end);
9652 let advance_downwards = action.advance_downwards
9653 && selections_on_single_row
9654 && !selections_selecting
9655 && !matches!(this.mode, EditorMode::SingleLine { .. });
9656
9657 if advance_downwards {
9658 let snapshot = this.buffer.read(cx).snapshot(cx);
9659
9660 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9661 s.move_cursors_with(|display_snapshot, display_point, _| {
9662 let mut point = display_point.to_point(display_snapshot);
9663 point.row += 1;
9664 point = snapshot.clip_point(point, Bias::Left);
9665 let display_point = point.to_display_point(display_snapshot);
9666 let goal = SelectionGoal::HorizontalPosition(
9667 display_snapshot
9668 .x_for_display_point(display_point, text_layout_details)
9669 .into(),
9670 );
9671 (display_point, goal)
9672 })
9673 });
9674 }
9675 });
9676 }
9677
9678 pub fn select_enclosing_symbol(
9679 &mut self,
9680 _: &SelectEnclosingSymbol,
9681 window: &mut Window,
9682 cx: &mut Context<Self>,
9683 ) {
9684 let buffer = self.buffer.read(cx).snapshot(cx);
9685 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9686
9687 fn update_selection(
9688 selection: &Selection<usize>,
9689 buffer_snap: &MultiBufferSnapshot,
9690 ) -> Option<Selection<usize>> {
9691 let cursor = selection.head();
9692 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9693 for symbol in symbols.iter().rev() {
9694 let start = symbol.range.start.to_offset(buffer_snap);
9695 let end = symbol.range.end.to_offset(buffer_snap);
9696 let new_range = start..end;
9697 if start < selection.start || end > selection.end {
9698 return Some(Selection {
9699 id: selection.id,
9700 start: new_range.start,
9701 end: new_range.end,
9702 goal: SelectionGoal::None,
9703 reversed: selection.reversed,
9704 });
9705 }
9706 }
9707 None
9708 }
9709
9710 let mut selected_larger_symbol = false;
9711 let new_selections = old_selections
9712 .iter()
9713 .map(|selection| match update_selection(selection, &buffer) {
9714 Some(new_selection) => {
9715 if new_selection.range() != selection.range() {
9716 selected_larger_symbol = true;
9717 }
9718 new_selection
9719 }
9720 None => selection.clone(),
9721 })
9722 .collect::<Vec<_>>();
9723
9724 if selected_larger_symbol {
9725 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9726 s.select(new_selections);
9727 });
9728 }
9729 }
9730
9731 pub fn select_larger_syntax_node(
9732 &mut self,
9733 _: &SelectLargerSyntaxNode,
9734 window: &mut Window,
9735 cx: &mut Context<Self>,
9736 ) {
9737 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9738 let buffer = self.buffer.read(cx).snapshot(cx);
9739 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9740
9741 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9742 let mut selected_larger_node = false;
9743 let new_selections = old_selections
9744 .iter()
9745 .map(|selection| {
9746 let old_range = selection.start..selection.end;
9747 let mut new_range = old_range.clone();
9748 let mut new_node = None;
9749 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
9750 {
9751 new_node = Some(node);
9752 new_range = containing_range;
9753 if !display_map.intersects_fold(new_range.start)
9754 && !display_map.intersects_fold(new_range.end)
9755 {
9756 break;
9757 }
9758 }
9759
9760 if let Some(node) = new_node {
9761 // Log the ancestor, to support using this action as a way to explore TreeSitter
9762 // nodes. Parent and grandparent are also logged because this operation will not
9763 // visit nodes that have the same range as their parent.
9764 log::info!("Node: {node:?}");
9765 let parent = node.parent();
9766 log::info!("Parent: {parent:?}");
9767 let grandparent = parent.and_then(|x| x.parent());
9768 log::info!("Grandparent: {grandparent:?}");
9769 }
9770
9771 selected_larger_node |= new_range != old_range;
9772 Selection {
9773 id: selection.id,
9774 start: new_range.start,
9775 end: new_range.end,
9776 goal: SelectionGoal::None,
9777 reversed: selection.reversed,
9778 }
9779 })
9780 .collect::<Vec<_>>();
9781
9782 if selected_larger_node {
9783 stack.push(old_selections);
9784 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9785 s.select(new_selections);
9786 });
9787 }
9788 self.select_larger_syntax_node_stack = stack;
9789 }
9790
9791 pub fn select_smaller_syntax_node(
9792 &mut self,
9793 _: &SelectSmallerSyntaxNode,
9794 window: &mut Window,
9795 cx: &mut Context<Self>,
9796 ) {
9797 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9798 if let Some(selections) = stack.pop() {
9799 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9800 s.select(selections.to_vec());
9801 });
9802 }
9803 self.select_larger_syntax_node_stack = stack;
9804 }
9805
9806 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
9807 if !EditorSettings::get_global(cx).gutter.runnables {
9808 self.clear_tasks();
9809 return Task::ready(());
9810 }
9811 let project = self.project.as_ref().map(Entity::downgrade);
9812 cx.spawn_in(window, |this, mut cx| async move {
9813 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
9814 let Some(project) = project.and_then(|p| p.upgrade()) else {
9815 return;
9816 };
9817 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9818 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9819 }) else {
9820 return;
9821 };
9822
9823 let hide_runnables = project
9824 .update(&mut cx, |project, cx| {
9825 // Do not display any test indicators in non-dev server remote projects.
9826 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9827 })
9828 .unwrap_or(true);
9829 if hide_runnables {
9830 return;
9831 }
9832 let new_rows =
9833 cx.background_executor()
9834 .spawn({
9835 let snapshot = display_snapshot.clone();
9836 async move {
9837 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9838 }
9839 })
9840 .await;
9841
9842 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9843 this.update(&mut cx, |this, _| {
9844 this.clear_tasks();
9845 for (key, value) in rows {
9846 this.insert_tasks(key, value);
9847 }
9848 })
9849 .ok();
9850 })
9851 }
9852 fn fetch_runnable_ranges(
9853 snapshot: &DisplaySnapshot,
9854 range: Range<Anchor>,
9855 ) -> Vec<language::RunnableRange> {
9856 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9857 }
9858
9859 fn runnable_rows(
9860 project: Entity<Project>,
9861 snapshot: DisplaySnapshot,
9862 runnable_ranges: Vec<RunnableRange>,
9863 mut cx: AsyncWindowContext,
9864 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9865 runnable_ranges
9866 .into_iter()
9867 .filter_map(|mut runnable| {
9868 let tasks = cx
9869 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9870 .ok()?;
9871 if tasks.is_empty() {
9872 return None;
9873 }
9874
9875 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9876
9877 let row = snapshot
9878 .buffer_snapshot
9879 .buffer_line_for_row(MultiBufferRow(point.row))?
9880 .1
9881 .start
9882 .row;
9883
9884 let context_range =
9885 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9886 Some((
9887 (runnable.buffer_id, row),
9888 RunnableTasks {
9889 templates: tasks,
9890 offset: MultiBufferOffset(runnable.run_range.start),
9891 context_range,
9892 column: point.column,
9893 extra_variables: runnable.extra_captures,
9894 },
9895 ))
9896 })
9897 .collect()
9898 }
9899
9900 fn templates_with_tags(
9901 project: &Entity<Project>,
9902 runnable: &mut Runnable,
9903 cx: &mut App,
9904 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9905 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9906 let (worktree_id, file) = project
9907 .buffer_for_id(runnable.buffer, cx)
9908 .and_then(|buffer| buffer.read(cx).file())
9909 .map(|file| (file.worktree_id(cx), file.clone()))
9910 .unzip();
9911
9912 (
9913 project.task_store().read(cx).task_inventory().cloned(),
9914 worktree_id,
9915 file,
9916 )
9917 });
9918
9919 let tags = mem::take(&mut runnable.tags);
9920 let mut tags: Vec<_> = tags
9921 .into_iter()
9922 .flat_map(|tag| {
9923 let tag = tag.0.clone();
9924 inventory
9925 .as_ref()
9926 .into_iter()
9927 .flat_map(|inventory| {
9928 inventory.read(cx).list_tasks(
9929 file.clone(),
9930 Some(runnable.language.clone()),
9931 worktree_id,
9932 cx,
9933 )
9934 })
9935 .filter(move |(_, template)| {
9936 template.tags.iter().any(|source_tag| source_tag == &tag)
9937 })
9938 })
9939 .sorted_by_key(|(kind, _)| kind.to_owned())
9940 .collect();
9941 if let Some((leading_tag_source, _)) = tags.first() {
9942 // Strongest source wins; if we have worktree tag binding, prefer that to
9943 // global and language bindings;
9944 // if we have a global binding, prefer that to language binding.
9945 let first_mismatch = tags
9946 .iter()
9947 .position(|(tag_source, _)| tag_source != leading_tag_source);
9948 if let Some(index) = first_mismatch {
9949 tags.truncate(index);
9950 }
9951 }
9952
9953 tags
9954 }
9955
9956 pub fn move_to_enclosing_bracket(
9957 &mut self,
9958 _: &MoveToEnclosingBracket,
9959 window: &mut Window,
9960 cx: &mut Context<Self>,
9961 ) {
9962 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9963 s.move_offsets_with(|snapshot, selection| {
9964 let Some(enclosing_bracket_ranges) =
9965 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9966 else {
9967 return;
9968 };
9969
9970 let mut best_length = usize::MAX;
9971 let mut best_inside = false;
9972 let mut best_in_bracket_range = false;
9973 let mut best_destination = None;
9974 for (open, close) in enclosing_bracket_ranges {
9975 let close = close.to_inclusive();
9976 let length = close.end() - open.start;
9977 let inside = selection.start >= open.end && selection.end <= *close.start();
9978 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9979 || close.contains(&selection.head());
9980
9981 // If best is next to a bracket and current isn't, skip
9982 if !in_bracket_range && best_in_bracket_range {
9983 continue;
9984 }
9985
9986 // Prefer smaller lengths unless best is inside and current isn't
9987 if length > best_length && (best_inside || !inside) {
9988 continue;
9989 }
9990
9991 best_length = length;
9992 best_inside = inside;
9993 best_in_bracket_range = in_bracket_range;
9994 best_destination = Some(
9995 if close.contains(&selection.start) && close.contains(&selection.end) {
9996 if inside {
9997 open.end
9998 } else {
9999 open.start
10000 }
10001 } else if inside {
10002 *close.start()
10003 } else {
10004 *close.end()
10005 },
10006 );
10007 }
10008
10009 if let Some(destination) = best_destination {
10010 selection.collapse_to(destination, SelectionGoal::None);
10011 }
10012 })
10013 });
10014 }
10015
10016 pub fn undo_selection(
10017 &mut self,
10018 _: &UndoSelection,
10019 window: &mut Window,
10020 cx: &mut Context<Self>,
10021 ) {
10022 self.end_selection(window, cx);
10023 self.selection_history.mode = SelectionHistoryMode::Undoing;
10024 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10025 self.change_selections(None, window, cx, |s| {
10026 s.select_anchors(entry.selections.to_vec())
10027 });
10028 self.select_next_state = entry.select_next_state;
10029 self.select_prev_state = entry.select_prev_state;
10030 self.add_selections_state = entry.add_selections_state;
10031 self.request_autoscroll(Autoscroll::newest(), cx);
10032 }
10033 self.selection_history.mode = SelectionHistoryMode::Normal;
10034 }
10035
10036 pub fn redo_selection(
10037 &mut self,
10038 _: &RedoSelection,
10039 window: &mut Window,
10040 cx: &mut Context<Self>,
10041 ) {
10042 self.end_selection(window, cx);
10043 self.selection_history.mode = SelectionHistoryMode::Redoing;
10044 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10045 self.change_selections(None, window, cx, |s| {
10046 s.select_anchors(entry.selections.to_vec())
10047 });
10048 self.select_next_state = entry.select_next_state;
10049 self.select_prev_state = entry.select_prev_state;
10050 self.add_selections_state = entry.add_selections_state;
10051 self.request_autoscroll(Autoscroll::newest(), cx);
10052 }
10053 self.selection_history.mode = SelectionHistoryMode::Normal;
10054 }
10055
10056 pub fn expand_excerpts(
10057 &mut self,
10058 action: &ExpandExcerpts,
10059 _: &mut Window,
10060 cx: &mut Context<Self>,
10061 ) {
10062 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10063 }
10064
10065 pub fn expand_excerpts_down(
10066 &mut self,
10067 action: &ExpandExcerptsDown,
10068 _: &mut Window,
10069 cx: &mut Context<Self>,
10070 ) {
10071 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10072 }
10073
10074 pub fn expand_excerpts_up(
10075 &mut self,
10076 action: &ExpandExcerptsUp,
10077 _: &mut Window,
10078 cx: &mut Context<Self>,
10079 ) {
10080 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10081 }
10082
10083 pub fn expand_excerpts_for_direction(
10084 &mut self,
10085 lines: u32,
10086 direction: ExpandExcerptDirection,
10087
10088 cx: &mut Context<Self>,
10089 ) {
10090 let selections = self.selections.disjoint_anchors();
10091
10092 let lines = if lines == 0 {
10093 EditorSettings::get_global(cx).expand_excerpt_lines
10094 } else {
10095 lines
10096 };
10097
10098 self.buffer.update(cx, |buffer, cx| {
10099 let snapshot = buffer.snapshot(cx);
10100 let mut excerpt_ids = selections
10101 .iter()
10102 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10103 .collect::<Vec<_>>();
10104 excerpt_ids.sort();
10105 excerpt_ids.dedup();
10106 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10107 })
10108 }
10109
10110 pub fn expand_excerpt(
10111 &mut self,
10112 excerpt: ExcerptId,
10113 direction: ExpandExcerptDirection,
10114 cx: &mut Context<Self>,
10115 ) {
10116 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10117 self.buffer.update(cx, |buffer, cx| {
10118 buffer.expand_excerpts([excerpt], lines, direction, cx)
10119 })
10120 }
10121
10122 pub fn go_to_singleton_buffer_point(
10123 &mut self,
10124 point: Point,
10125 window: &mut Window,
10126 cx: &mut Context<Self>,
10127 ) {
10128 self.go_to_singleton_buffer_range(point..point, window, cx);
10129 }
10130
10131 pub fn go_to_singleton_buffer_range(
10132 &mut self,
10133 range: Range<Point>,
10134 window: &mut Window,
10135 cx: &mut Context<Self>,
10136 ) {
10137 let multibuffer = self.buffer().read(cx);
10138 let Some(buffer) = multibuffer.as_singleton() else {
10139 return;
10140 };
10141 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10142 return;
10143 };
10144 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10145 return;
10146 };
10147 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10148 s.select_anchor_ranges([start..end])
10149 });
10150 }
10151
10152 fn go_to_diagnostic(
10153 &mut self,
10154 _: &GoToDiagnostic,
10155 window: &mut Window,
10156 cx: &mut Context<Self>,
10157 ) {
10158 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10159 }
10160
10161 fn go_to_prev_diagnostic(
10162 &mut self,
10163 _: &GoToPrevDiagnostic,
10164 window: &mut Window,
10165 cx: &mut Context<Self>,
10166 ) {
10167 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10168 }
10169
10170 pub fn go_to_diagnostic_impl(
10171 &mut self,
10172 direction: Direction,
10173 window: &mut Window,
10174 cx: &mut Context<Self>,
10175 ) {
10176 let buffer = self.buffer.read(cx).snapshot(cx);
10177 let selection = self.selections.newest::<usize>(cx);
10178
10179 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10180 if direction == Direction::Next {
10181 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10182 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10183 return;
10184 };
10185 self.activate_diagnostics(
10186 buffer_id,
10187 popover.local_diagnostic.diagnostic.group_id,
10188 window,
10189 cx,
10190 );
10191 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10192 let primary_range_start = active_diagnostics.primary_range.start;
10193 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10194 let mut new_selection = s.newest_anchor().clone();
10195 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10196 s.select_anchors(vec![new_selection.clone()]);
10197 });
10198 self.refresh_inline_completion(false, true, window, cx);
10199 }
10200 return;
10201 }
10202 }
10203
10204 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10205 active_diagnostics
10206 .primary_range
10207 .to_offset(&buffer)
10208 .to_inclusive()
10209 });
10210 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10211 if active_primary_range.contains(&selection.head()) {
10212 *active_primary_range.start()
10213 } else {
10214 selection.head()
10215 }
10216 } else {
10217 selection.head()
10218 };
10219 let snapshot = self.snapshot(window, cx);
10220 loop {
10221 let mut diagnostics;
10222 if direction == Direction::Prev {
10223 diagnostics = buffer
10224 .diagnostics_in_range::<usize>(0..search_start)
10225 .collect::<Vec<_>>();
10226 diagnostics.reverse();
10227 } else {
10228 diagnostics = buffer
10229 .diagnostics_in_range::<usize>(search_start..buffer.len())
10230 .collect::<Vec<_>>();
10231 };
10232 let group = diagnostics
10233 .into_iter()
10234 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10235 // relies on diagnostics_in_range to return diagnostics with the same starting range to
10236 // be sorted in a stable way
10237 // skip until we are at current active diagnostic, if it exists
10238 .skip_while(|entry| {
10239 let is_in_range = match direction {
10240 Direction::Prev => entry.range.end > search_start,
10241 Direction::Next => entry.range.start < search_start,
10242 };
10243 is_in_range
10244 && self
10245 .active_diagnostics
10246 .as_ref()
10247 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
10248 })
10249 .find_map(|entry| {
10250 if entry.diagnostic.is_primary
10251 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
10252 && entry.range.start != entry.range.end
10253 // if we match with the active diagnostic, skip it
10254 && Some(entry.diagnostic.group_id)
10255 != self.active_diagnostics.as_ref().map(|d| d.group_id)
10256 {
10257 Some((entry.range, entry.diagnostic.group_id))
10258 } else {
10259 None
10260 }
10261 });
10262
10263 if let Some((primary_range, group_id)) = group {
10264 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10265 return;
10266 };
10267 self.activate_diagnostics(buffer_id, group_id, window, cx);
10268 if self.active_diagnostics.is_some() {
10269 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10270 s.select(vec![Selection {
10271 id: selection.id,
10272 start: primary_range.start,
10273 end: primary_range.start,
10274 reversed: false,
10275 goal: SelectionGoal::None,
10276 }]);
10277 });
10278 self.refresh_inline_completion(false, true, window, cx);
10279 }
10280 break;
10281 } else {
10282 // Cycle around to the start of the buffer, potentially moving back to the start of
10283 // the currently active diagnostic.
10284 active_primary_range.take();
10285 if direction == Direction::Prev {
10286 if search_start == buffer.len() {
10287 break;
10288 } else {
10289 search_start = buffer.len();
10290 }
10291 } else if search_start == 0 {
10292 break;
10293 } else {
10294 search_start = 0;
10295 }
10296 }
10297 }
10298 }
10299
10300 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10301 let snapshot = self.snapshot(window, cx);
10302 let selection = self.selections.newest::<Point>(cx);
10303 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10304 }
10305
10306 fn go_to_hunk_after_position(
10307 &mut self,
10308 snapshot: &EditorSnapshot,
10309 position: Point,
10310 window: &mut Window,
10311 cx: &mut Context<Editor>,
10312 ) -> Option<MultiBufferDiffHunk> {
10313 let mut hunk = snapshot
10314 .buffer_snapshot
10315 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10316 .find(|hunk| hunk.row_range.start.0 > position.row);
10317 if hunk.is_none() {
10318 hunk = snapshot
10319 .buffer_snapshot
10320 .diff_hunks_in_range(Point::zero()..position)
10321 .find(|hunk| hunk.row_range.end.0 < position.row)
10322 }
10323 if let Some(hunk) = &hunk {
10324 let destination = Point::new(hunk.row_range.start.0, 0);
10325 self.unfold_ranges(&[destination..destination], false, false, cx);
10326 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10327 s.select_ranges(vec![destination..destination]);
10328 });
10329 }
10330
10331 hunk
10332 }
10333
10334 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10335 let snapshot = self.snapshot(window, cx);
10336 let selection = self.selections.newest::<Point>(cx);
10337 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10338 }
10339
10340 fn go_to_hunk_before_position(
10341 &mut self,
10342 snapshot: &EditorSnapshot,
10343 position: Point,
10344 window: &mut Window,
10345 cx: &mut Context<Editor>,
10346 ) -> Option<MultiBufferDiffHunk> {
10347 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10348 if hunk.is_none() {
10349 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10350 }
10351 if let Some(hunk) = &hunk {
10352 let destination = Point::new(hunk.row_range.start.0, 0);
10353 self.unfold_ranges(&[destination..destination], false, false, cx);
10354 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10355 s.select_ranges(vec![destination..destination]);
10356 });
10357 }
10358
10359 hunk
10360 }
10361
10362 pub fn go_to_definition(
10363 &mut self,
10364 _: &GoToDefinition,
10365 window: &mut Window,
10366 cx: &mut Context<Self>,
10367 ) -> Task<Result<Navigated>> {
10368 let definition =
10369 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10370 cx.spawn_in(window, |editor, mut cx| async move {
10371 if definition.await? == Navigated::Yes {
10372 return Ok(Navigated::Yes);
10373 }
10374 match editor.update_in(&mut cx, |editor, window, cx| {
10375 editor.find_all_references(&FindAllReferences, window, cx)
10376 })? {
10377 Some(references) => references.await,
10378 None => Ok(Navigated::No),
10379 }
10380 })
10381 }
10382
10383 pub fn go_to_declaration(
10384 &mut self,
10385 _: &GoToDeclaration,
10386 window: &mut Window,
10387 cx: &mut Context<Self>,
10388 ) -> Task<Result<Navigated>> {
10389 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10390 }
10391
10392 pub fn go_to_declaration_split(
10393 &mut self,
10394 _: &GoToDeclaration,
10395 window: &mut Window,
10396 cx: &mut Context<Self>,
10397 ) -> Task<Result<Navigated>> {
10398 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10399 }
10400
10401 pub fn go_to_implementation(
10402 &mut self,
10403 _: &GoToImplementation,
10404 window: &mut Window,
10405 cx: &mut Context<Self>,
10406 ) -> Task<Result<Navigated>> {
10407 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10408 }
10409
10410 pub fn go_to_implementation_split(
10411 &mut self,
10412 _: &GoToImplementationSplit,
10413 window: &mut Window,
10414 cx: &mut Context<Self>,
10415 ) -> Task<Result<Navigated>> {
10416 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10417 }
10418
10419 pub fn go_to_type_definition(
10420 &mut self,
10421 _: &GoToTypeDefinition,
10422 window: &mut Window,
10423 cx: &mut Context<Self>,
10424 ) -> Task<Result<Navigated>> {
10425 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10426 }
10427
10428 pub fn go_to_definition_split(
10429 &mut self,
10430 _: &GoToDefinitionSplit,
10431 window: &mut Window,
10432 cx: &mut Context<Self>,
10433 ) -> Task<Result<Navigated>> {
10434 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10435 }
10436
10437 pub fn go_to_type_definition_split(
10438 &mut self,
10439 _: &GoToTypeDefinitionSplit,
10440 window: &mut Window,
10441 cx: &mut Context<Self>,
10442 ) -> Task<Result<Navigated>> {
10443 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10444 }
10445
10446 fn go_to_definition_of_kind(
10447 &mut self,
10448 kind: GotoDefinitionKind,
10449 split: bool,
10450 window: &mut Window,
10451 cx: &mut Context<Self>,
10452 ) -> Task<Result<Navigated>> {
10453 let Some(provider) = self.semantics_provider.clone() else {
10454 return Task::ready(Ok(Navigated::No));
10455 };
10456 let head = self.selections.newest::<usize>(cx).head();
10457 let buffer = self.buffer.read(cx);
10458 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10459 text_anchor
10460 } else {
10461 return Task::ready(Ok(Navigated::No));
10462 };
10463
10464 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10465 return Task::ready(Ok(Navigated::No));
10466 };
10467
10468 cx.spawn_in(window, |editor, mut cx| async move {
10469 let definitions = definitions.await?;
10470 let navigated = editor
10471 .update_in(&mut cx, |editor, window, cx| {
10472 editor.navigate_to_hover_links(
10473 Some(kind),
10474 definitions
10475 .into_iter()
10476 .filter(|location| {
10477 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10478 })
10479 .map(HoverLink::Text)
10480 .collect::<Vec<_>>(),
10481 split,
10482 window,
10483 cx,
10484 )
10485 })?
10486 .await?;
10487 anyhow::Ok(navigated)
10488 })
10489 }
10490
10491 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10492 let selection = self.selections.newest_anchor();
10493 let head = selection.head();
10494 let tail = selection.tail();
10495
10496 let Some((buffer, start_position)) =
10497 self.buffer.read(cx).text_anchor_for_position(head, cx)
10498 else {
10499 return;
10500 };
10501
10502 let end_position = if head != tail {
10503 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10504 return;
10505 };
10506 Some(pos)
10507 } else {
10508 None
10509 };
10510
10511 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10512 let url = if let Some(end_pos) = end_position {
10513 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10514 } else {
10515 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10516 };
10517
10518 if let Some(url) = url {
10519 editor.update(&mut cx, |_, cx| {
10520 cx.open_url(&url);
10521 })
10522 } else {
10523 Ok(())
10524 }
10525 });
10526
10527 url_finder.detach();
10528 }
10529
10530 pub fn open_selected_filename(
10531 &mut self,
10532 _: &OpenSelectedFilename,
10533 window: &mut Window,
10534 cx: &mut Context<Self>,
10535 ) {
10536 let Some(workspace) = self.workspace() else {
10537 return;
10538 };
10539
10540 let position = self.selections.newest_anchor().head();
10541
10542 let Some((buffer, buffer_position)) =
10543 self.buffer.read(cx).text_anchor_for_position(position, cx)
10544 else {
10545 return;
10546 };
10547
10548 let project = self.project.clone();
10549
10550 cx.spawn_in(window, |_, mut cx| async move {
10551 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10552
10553 if let Some((_, path)) = result {
10554 workspace
10555 .update_in(&mut cx, |workspace, window, cx| {
10556 workspace.open_resolved_path(path, window, cx)
10557 })?
10558 .await?;
10559 }
10560 anyhow::Ok(())
10561 })
10562 .detach();
10563 }
10564
10565 pub(crate) fn navigate_to_hover_links(
10566 &mut self,
10567 kind: Option<GotoDefinitionKind>,
10568 mut definitions: Vec<HoverLink>,
10569 split: bool,
10570 window: &mut Window,
10571 cx: &mut Context<Editor>,
10572 ) -> Task<Result<Navigated>> {
10573 // If there is one definition, just open it directly
10574 if definitions.len() == 1 {
10575 let definition = definitions.pop().unwrap();
10576
10577 enum TargetTaskResult {
10578 Location(Option<Location>),
10579 AlreadyNavigated,
10580 }
10581
10582 let target_task = match definition {
10583 HoverLink::Text(link) => {
10584 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10585 }
10586 HoverLink::InlayHint(lsp_location, server_id) => {
10587 let computation =
10588 self.compute_target_location(lsp_location, server_id, window, cx);
10589 cx.background_executor().spawn(async move {
10590 let location = computation.await?;
10591 Ok(TargetTaskResult::Location(location))
10592 })
10593 }
10594 HoverLink::Url(url) => {
10595 cx.open_url(&url);
10596 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10597 }
10598 HoverLink::File(path) => {
10599 if let Some(workspace) = self.workspace() {
10600 cx.spawn_in(window, |_, mut cx| async move {
10601 workspace
10602 .update_in(&mut cx, |workspace, window, cx| {
10603 workspace.open_resolved_path(path, window, cx)
10604 })?
10605 .await
10606 .map(|_| TargetTaskResult::AlreadyNavigated)
10607 })
10608 } else {
10609 Task::ready(Ok(TargetTaskResult::Location(None)))
10610 }
10611 }
10612 };
10613 cx.spawn_in(window, |editor, mut cx| async move {
10614 let target = match target_task.await.context("target resolution task")? {
10615 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10616 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10617 TargetTaskResult::Location(Some(target)) => target,
10618 };
10619
10620 editor.update_in(&mut cx, |editor, window, cx| {
10621 let Some(workspace) = editor.workspace() else {
10622 return Navigated::No;
10623 };
10624 let pane = workspace.read(cx).active_pane().clone();
10625
10626 let range = target.range.to_point(target.buffer.read(cx));
10627 let range = editor.range_for_match(&range);
10628 let range = collapse_multiline_range(range);
10629
10630 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10631 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10632 } else {
10633 window.defer(cx, move |window, cx| {
10634 let target_editor: Entity<Self> =
10635 workspace.update(cx, |workspace, cx| {
10636 let pane = if split {
10637 workspace.adjacent_pane(window, cx)
10638 } else {
10639 workspace.active_pane().clone()
10640 };
10641
10642 workspace.open_project_item(
10643 pane,
10644 target.buffer.clone(),
10645 true,
10646 true,
10647 window,
10648 cx,
10649 )
10650 });
10651 target_editor.update(cx, |target_editor, cx| {
10652 // When selecting a definition in a different buffer, disable the nav history
10653 // to avoid creating a history entry at the previous cursor location.
10654 pane.update(cx, |pane, _| pane.disable_history());
10655 target_editor.go_to_singleton_buffer_range(range, window, cx);
10656 pane.update(cx, |pane, _| pane.enable_history());
10657 });
10658 });
10659 }
10660 Navigated::Yes
10661 })
10662 })
10663 } else if !definitions.is_empty() {
10664 cx.spawn_in(window, |editor, mut cx| async move {
10665 let (title, location_tasks, workspace) = editor
10666 .update_in(&mut cx, |editor, window, cx| {
10667 let tab_kind = match kind {
10668 Some(GotoDefinitionKind::Implementation) => "Implementations",
10669 _ => "Definitions",
10670 };
10671 let title = definitions
10672 .iter()
10673 .find_map(|definition| match definition {
10674 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10675 let buffer = origin.buffer.read(cx);
10676 format!(
10677 "{} for {}",
10678 tab_kind,
10679 buffer
10680 .text_for_range(origin.range.clone())
10681 .collect::<String>()
10682 )
10683 }),
10684 HoverLink::InlayHint(_, _) => None,
10685 HoverLink::Url(_) => None,
10686 HoverLink::File(_) => None,
10687 })
10688 .unwrap_or(tab_kind.to_string());
10689 let location_tasks = definitions
10690 .into_iter()
10691 .map(|definition| match definition {
10692 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10693 HoverLink::InlayHint(lsp_location, server_id) => editor
10694 .compute_target_location(lsp_location, server_id, window, cx),
10695 HoverLink::Url(_) => Task::ready(Ok(None)),
10696 HoverLink::File(_) => Task::ready(Ok(None)),
10697 })
10698 .collect::<Vec<_>>();
10699 (title, location_tasks, editor.workspace().clone())
10700 })
10701 .context("location tasks preparation")?;
10702
10703 let locations = future::join_all(location_tasks)
10704 .await
10705 .into_iter()
10706 .filter_map(|location| location.transpose())
10707 .collect::<Result<_>>()
10708 .context("location tasks")?;
10709
10710 let Some(workspace) = workspace else {
10711 return Ok(Navigated::No);
10712 };
10713 let opened = workspace
10714 .update_in(&mut cx, |workspace, window, cx| {
10715 Self::open_locations_in_multibuffer(
10716 workspace,
10717 locations,
10718 title,
10719 split,
10720 MultibufferSelectionMode::First,
10721 window,
10722 cx,
10723 )
10724 })
10725 .ok();
10726
10727 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10728 })
10729 } else {
10730 Task::ready(Ok(Navigated::No))
10731 }
10732 }
10733
10734 fn compute_target_location(
10735 &self,
10736 lsp_location: lsp::Location,
10737 server_id: LanguageServerId,
10738 window: &mut Window,
10739 cx: &mut Context<Self>,
10740 ) -> Task<anyhow::Result<Option<Location>>> {
10741 let Some(project) = self.project.clone() else {
10742 return Task::ready(Ok(None));
10743 };
10744
10745 cx.spawn_in(window, move |editor, mut cx| async move {
10746 let location_task = editor.update(&mut cx, |_, cx| {
10747 project.update(cx, |project, cx| {
10748 let language_server_name = project
10749 .language_server_statuses(cx)
10750 .find(|(id, _)| server_id == *id)
10751 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10752 language_server_name.map(|language_server_name| {
10753 project.open_local_buffer_via_lsp(
10754 lsp_location.uri.clone(),
10755 server_id,
10756 language_server_name,
10757 cx,
10758 )
10759 })
10760 })
10761 })?;
10762 let location = match location_task {
10763 Some(task) => Some({
10764 let target_buffer_handle = task.await.context("open local buffer")?;
10765 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10766 let target_start = target_buffer
10767 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10768 let target_end = target_buffer
10769 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10770 target_buffer.anchor_after(target_start)
10771 ..target_buffer.anchor_before(target_end)
10772 })?;
10773 Location {
10774 buffer: target_buffer_handle,
10775 range,
10776 }
10777 }),
10778 None => None,
10779 };
10780 Ok(location)
10781 })
10782 }
10783
10784 pub fn find_all_references(
10785 &mut self,
10786 _: &FindAllReferences,
10787 window: &mut Window,
10788 cx: &mut Context<Self>,
10789 ) -> Option<Task<Result<Navigated>>> {
10790 let selection = self.selections.newest::<usize>(cx);
10791 let multi_buffer = self.buffer.read(cx);
10792 let head = selection.head();
10793
10794 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10795 let head_anchor = multi_buffer_snapshot.anchor_at(
10796 head,
10797 if head < selection.tail() {
10798 Bias::Right
10799 } else {
10800 Bias::Left
10801 },
10802 );
10803
10804 match self
10805 .find_all_references_task_sources
10806 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10807 {
10808 Ok(_) => {
10809 log::info!(
10810 "Ignoring repeated FindAllReferences invocation with the position of already running task"
10811 );
10812 return None;
10813 }
10814 Err(i) => {
10815 self.find_all_references_task_sources.insert(i, head_anchor);
10816 }
10817 }
10818
10819 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10820 let workspace = self.workspace()?;
10821 let project = workspace.read(cx).project().clone();
10822 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10823 Some(cx.spawn_in(window, |editor, mut cx| async move {
10824 let _cleanup = defer({
10825 let mut cx = cx.clone();
10826 move || {
10827 let _ = editor.update(&mut cx, |editor, _| {
10828 if let Ok(i) =
10829 editor
10830 .find_all_references_task_sources
10831 .binary_search_by(|anchor| {
10832 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10833 })
10834 {
10835 editor.find_all_references_task_sources.remove(i);
10836 }
10837 });
10838 }
10839 });
10840
10841 let locations = references.await?;
10842 if locations.is_empty() {
10843 return anyhow::Ok(Navigated::No);
10844 }
10845
10846 workspace.update_in(&mut cx, |workspace, window, cx| {
10847 let title = locations
10848 .first()
10849 .as_ref()
10850 .map(|location| {
10851 let buffer = location.buffer.read(cx);
10852 format!(
10853 "References to `{}`",
10854 buffer
10855 .text_for_range(location.range.clone())
10856 .collect::<String>()
10857 )
10858 })
10859 .unwrap();
10860 Self::open_locations_in_multibuffer(
10861 workspace,
10862 locations,
10863 title,
10864 false,
10865 MultibufferSelectionMode::First,
10866 window,
10867 cx,
10868 );
10869 Navigated::Yes
10870 })
10871 }))
10872 }
10873
10874 /// Opens a multibuffer with the given project locations in it
10875 pub fn open_locations_in_multibuffer(
10876 workspace: &mut Workspace,
10877 mut locations: Vec<Location>,
10878 title: String,
10879 split: bool,
10880 multibuffer_selection_mode: MultibufferSelectionMode,
10881 window: &mut Window,
10882 cx: &mut Context<Workspace>,
10883 ) {
10884 // If there are multiple definitions, open them in a multibuffer
10885 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10886 let mut locations = locations.into_iter().peekable();
10887 let mut ranges = Vec::new();
10888 let capability = workspace.project().read(cx).capability();
10889
10890 let excerpt_buffer = cx.new(|cx| {
10891 let mut multibuffer = MultiBuffer::new(capability);
10892 while let Some(location) = locations.next() {
10893 let buffer = location.buffer.read(cx);
10894 let mut ranges_for_buffer = Vec::new();
10895 let range = location.range.to_offset(buffer);
10896 ranges_for_buffer.push(range.clone());
10897
10898 while let Some(next_location) = locations.peek() {
10899 if next_location.buffer == location.buffer {
10900 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10901 locations.next();
10902 } else {
10903 break;
10904 }
10905 }
10906
10907 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10908 ranges.extend(multibuffer.push_excerpts_with_context_lines(
10909 location.buffer.clone(),
10910 ranges_for_buffer,
10911 DEFAULT_MULTIBUFFER_CONTEXT,
10912 cx,
10913 ))
10914 }
10915
10916 multibuffer.with_title(title)
10917 });
10918
10919 let editor = cx.new(|cx| {
10920 Editor::for_multibuffer(
10921 excerpt_buffer,
10922 Some(workspace.project().clone()),
10923 true,
10924 window,
10925 cx,
10926 )
10927 });
10928 editor.update(cx, |editor, cx| {
10929 match multibuffer_selection_mode {
10930 MultibufferSelectionMode::First => {
10931 if let Some(first_range) = ranges.first() {
10932 editor.change_selections(None, window, cx, |selections| {
10933 selections.clear_disjoint();
10934 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10935 });
10936 }
10937 editor.highlight_background::<Self>(
10938 &ranges,
10939 |theme| theme.editor_highlighted_line_background,
10940 cx,
10941 );
10942 }
10943 MultibufferSelectionMode::All => {
10944 editor.change_selections(None, window, cx, |selections| {
10945 selections.clear_disjoint();
10946 selections.select_anchor_ranges(ranges);
10947 });
10948 }
10949 }
10950 editor.register_buffers_with_language_servers(cx);
10951 });
10952
10953 let item = Box::new(editor);
10954 let item_id = item.item_id();
10955
10956 if split {
10957 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
10958 } else {
10959 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10960 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10961 pane.close_current_preview_item(window, cx)
10962 } else {
10963 None
10964 }
10965 });
10966 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
10967 }
10968 workspace.active_pane().update(cx, |pane, cx| {
10969 pane.set_preview_item_id(Some(item_id), cx);
10970 });
10971 }
10972
10973 pub fn rename(
10974 &mut self,
10975 _: &Rename,
10976 window: &mut Window,
10977 cx: &mut Context<Self>,
10978 ) -> Option<Task<Result<()>>> {
10979 use language::ToOffset as _;
10980
10981 let provider = self.semantics_provider.clone()?;
10982 let selection = self.selections.newest_anchor().clone();
10983 let (cursor_buffer, cursor_buffer_position) = self
10984 .buffer
10985 .read(cx)
10986 .text_anchor_for_position(selection.head(), cx)?;
10987 let (tail_buffer, cursor_buffer_position_end) = self
10988 .buffer
10989 .read(cx)
10990 .text_anchor_for_position(selection.tail(), cx)?;
10991 if tail_buffer != cursor_buffer {
10992 return None;
10993 }
10994
10995 let snapshot = cursor_buffer.read(cx).snapshot();
10996 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10997 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10998 let prepare_rename = provider
10999 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11000 .unwrap_or_else(|| Task::ready(Ok(None)));
11001 drop(snapshot);
11002
11003 Some(cx.spawn_in(window, |this, mut cx| async move {
11004 let rename_range = if let Some(range) = prepare_rename.await? {
11005 Some(range)
11006 } else {
11007 this.update(&mut cx, |this, cx| {
11008 let buffer = this.buffer.read(cx).snapshot(cx);
11009 let mut buffer_highlights = this
11010 .document_highlights_for_position(selection.head(), &buffer)
11011 .filter(|highlight| {
11012 highlight.start.excerpt_id == selection.head().excerpt_id
11013 && highlight.end.excerpt_id == selection.head().excerpt_id
11014 });
11015 buffer_highlights
11016 .next()
11017 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11018 })?
11019 };
11020 if let Some(rename_range) = rename_range {
11021 this.update_in(&mut cx, |this, window, cx| {
11022 let snapshot = cursor_buffer.read(cx).snapshot();
11023 let rename_buffer_range = rename_range.to_offset(&snapshot);
11024 let cursor_offset_in_rename_range =
11025 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11026 let cursor_offset_in_rename_range_end =
11027 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11028
11029 this.take_rename(false, window, cx);
11030 let buffer = this.buffer.read(cx).read(cx);
11031 let cursor_offset = selection.head().to_offset(&buffer);
11032 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11033 let rename_end = rename_start + rename_buffer_range.len();
11034 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11035 let mut old_highlight_id = None;
11036 let old_name: Arc<str> = buffer
11037 .chunks(rename_start..rename_end, true)
11038 .map(|chunk| {
11039 if old_highlight_id.is_none() {
11040 old_highlight_id = chunk.syntax_highlight_id;
11041 }
11042 chunk.text
11043 })
11044 .collect::<String>()
11045 .into();
11046
11047 drop(buffer);
11048
11049 // Position the selection in the rename editor so that it matches the current selection.
11050 this.show_local_selections = false;
11051 let rename_editor = cx.new(|cx| {
11052 let mut editor = Editor::single_line(window, cx);
11053 editor.buffer.update(cx, |buffer, cx| {
11054 buffer.edit([(0..0, old_name.clone())], None, cx)
11055 });
11056 let rename_selection_range = match cursor_offset_in_rename_range
11057 .cmp(&cursor_offset_in_rename_range_end)
11058 {
11059 Ordering::Equal => {
11060 editor.select_all(&SelectAll, window, cx);
11061 return editor;
11062 }
11063 Ordering::Less => {
11064 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11065 }
11066 Ordering::Greater => {
11067 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11068 }
11069 };
11070 if rename_selection_range.end > old_name.len() {
11071 editor.select_all(&SelectAll, window, cx);
11072 } else {
11073 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11074 s.select_ranges([rename_selection_range]);
11075 });
11076 }
11077 editor
11078 });
11079 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11080 if e == &EditorEvent::Focused {
11081 cx.emit(EditorEvent::FocusedIn)
11082 }
11083 })
11084 .detach();
11085
11086 let write_highlights =
11087 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11088 let read_highlights =
11089 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11090 let ranges = write_highlights
11091 .iter()
11092 .flat_map(|(_, ranges)| ranges.iter())
11093 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11094 .cloned()
11095 .collect();
11096
11097 this.highlight_text::<Rename>(
11098 ranges,
11099 HighlightStyle {
11100 fade_out: Some(0.6),
11101 ..Default::default()
11102 },
11103 cx,
11104 );
11105 let rename_focus_handle = rename_editor.focus_handle(cx);
11106 window.focus(&rename_focus_handle);
11107 let block_id = this.insert_blocks(
11108 [BlockProperties {
11109 style: BlockStyle::Flex,
11110 placement: BlockPlacement::Below(range.start),
11111 height: 1,
11112 render: Arc::new({
11113 let rename_editor = rename_editor.clone();
11114 move |cx: &mut BlockContext| {
11115 let mut text_style = cx.editor_style.text.clone();
11116 if let Some(highlight_style) = old_highlight_id
11117 .and_then(|h| h.style(&cx.editor_style.syntax))
11118 {
11119 text_style = text_style.highlight(highlight_style);
11120 }
11121 div()
11122 .block_mouse_down()
11123 .pl(cx.anchor_x)
11124 .child(EditorElement::new(
11125 &rename_editor,
11126 EditorStyle {
11127 background: cx.theme().system().transparent,
11128 local_player: cx.editor_style.local_player,
11129 text: text_style,
11130 scrollbar_width: cx.editor_style.scrollbar_width,
11131 syntax: cx.editor_style.syntax.clone(),
11132 status: cx.editor_style.status.clone(),
11133 inlay_hints_style: HighlightStyle {
11134 font_weight: Some(FontWeight::BOLD),
11135 ..make_inlay_hints_style(cx.app)
11136 },
11137 inline_completion_styles: make_suggestion_styles(
11138 cx.app,
11139 ),
11140 ..EditorStyle::default()
11141 },
11142 ))
11143 .into_any_element()
11144 }
11145 }),
11146 priority: 0,
11147 }],
11148 Some(Autoscroll::fit()),
11149 cx,
11150 )[0];
11151 this.pending_rename = Some(RenameState {
11152 range,
11153 old_name,
11154 editor: rename_editor,
11155 block_id,
11156 });
11157 })?;
11158 }
11159
11160 Ok(())
11161 }))
11162 }
11163
11164 pub fn confirm_rename(
11165 &mut self,
11166 _: &ConfirmRename,
11167 window: &mut Window,
11168 cx: &mut Context<Self>,
11169 ) -> Option<Task<Result<()>>> {
11170 let rename = self.take_rename(false, window, cx)?;
11171 let workspace = self.workspace()?.downgrade();
11172 let (buffer, start) = self
11173 .buffer
11174 .read(cx)
11175 .text_anchor_for_position(rename.range.start, cx)?;
11176 let (end_buffer, _) = self
11177 .buffer
11178 .read(cx)
11179 .text_anchor_for_position(rename.range.end, cx)?;
11180 if buffer != end_buffer {
11181 return None;
11182 }
11183
11184 let old_name = rename.old_name;
11185 let new_name = rename.editor.read(cx).text(cx);
11186
11187 let rename = self.semantics_provider.as_ref()?.perform_rename(
11188 &buffer,
11189 start,
11190 new_name.clone(),
11191 cx,
11192 )?;
11193
11194 Some(cx.spawn_in(window, |editor, mut cx| async move {
11195 let project_transaction = rename.await?;
11196 Self::open_project_transaction(
11197 &editor,
11198 workspace,
11199 project_transaction,
11200 format!("Rename: {} → {}", old_name, new_name),
11201 cx.clone(),
11202 )
11203 .await?;
11204
11205 editor.update(&mut cx, |editor, cx| {
11206 editor.refresh_document_highlights(cx);
11207 })?;
11208 Ok(())
11209 }))
11210 }
11211
11212 fn take_rename(
11213 &mut self,
11214 moving_cursor: bool,
11215 window: &mut Window,
11216 cx: &mut Context<Self>,
11217 ) -> Option<RenameState> {
11218 let rename = self.pending_rename.take()?;
11219 if rename.editor.focus_handle(cx).is_focused(window) {
11220 window.focus(&self.focus_handle);
11221 }
11222
11223 self.remove_blocks(
11224 [rename.block_id].into_iter().collect(),
11225 Some(Autoscroll::fit()),
11226 cx,
11227 );
11228 self.clear_highlights::<Rename>(cx);
11229 self.show_local_selections = true;
11230
11231 if moving_cursor {
11232 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11233 editor.selections.newest::<usize>(cx).head()
11234 });
11235
11236 // Update the selection to match the position of the selection inside
11237 // the rename editor.
11238 let snapshot = self.buffer.read(cx).read(cx);
11239 let rename_range = rename.range.to_offset(&snapshot);
11240 let cursor_in_editor = snapshot
11241 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11242 .min(rename_range.end);
11243 drop(snapshot);
11244
11245 self.change_selections(None, window, cx, |s| {
11246 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11247 });
11248 } else {
11249 self.refresh_document_highlights(cx);
11250 }
11251
11252 Some(rename)
11253 }
11254
11255 pub fn pending_rename(&self) -> Option<&RenameState> {
11256 self.pending_rename.as_ref()
11257 }
11258
11259 fn format(
11260 &mut self,
11261 _: &Format,
11262 window: &mut Window,
11263 cx: &mut Context<Self>,
11264 ) -> Option<Task<Result<()>>> {
11265 let project = match &self.project {
11266 Some(project) => project.clone(),
11267 None => return None,
11268 };
11269
11270 Some(self.perform_format(
11271 project,
11272 FormatTrigger::Manual,
11273 FormatTarget::Buffers,
11274 window,
11275 cx,
11276 ))
11277 }
11278
11279 fn format_selections(
11280 &mut self,
11281 _: &FormatSelections,
11282 window: &mut Window,
11283 cx: &mut Context<Self>,
11284 ) -> Option<Task<Result<()>>> {
11285 let project = match &self.project {
11286 Some(project) => project.clone(),
11287 None => return None,
11288 };
11289
11290 let ranges = self
11291 .selections
11292 .all_adjusted(cx)
11293 .into_iter()
11294 .map(|selection| selection.range())
11295 .collect_vec();
11296
11297 Some(self.perform_format(
11298 project,
11299 FormatTrigger::Manual,
11300 FormatTarget::Ranges(ranges),
11301 window,
11302 cx,
11303 ))
11304 }
11305
11306 fn perform_format(
11307 &mut self,
11308 project: Entity<Project>,
11309 trigger: FormatTrigger,
11310 target: FormatTarget,
11311 window: &mut Window,
11312 cx: &mut Context<Self>,
11313 ) -> Task<Result<()>> {
11314 let buffer = self.buffer.clone();
11315 let (buffers, target) = match target {
11316 FormatTarget::Buffers => {
11317 let mut buffers = buffer.read(cx).all_buffers();
11318 if trigger == FormatTrigger::Save {
11319 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11320 }
11321 (buffers, LspFormatTarget::Buffers)
11322 }
11323 FormatTarget::Ranges(selection_ranges) => {
11324 let multi_buffer = buffer.read(cx);
11325 let snapshot = multi_buffer.read(cx);
11326 let mut buffers = HashSet::default();
11327 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11328 BTreeMap::new();
11329 for selection_range in selection_ranges {
11330 for (buffer, buffer_range, _) in
11331 snapshot.range_to_buffer_ranges(selection_range)
11332 {
11333 let buffer_id = buffer.remote_id();
11334 let start = buffer.anchor_before(buffer_range.start);
11335 let end = buffer.anchor_after(buffer_range.end);
11336 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11337 buffer_id_to_ranges
11338 .entry(buffer_id)
11339 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11340 .or_insert_with(|| vec![start..end]);
11341 }
11342 }
11343 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11344 }
11345 };
11346
11347 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11348 let format = project.update(cx, |project, cx| {
11349 project.format(buffers, target, true, trigger, cx)
11350 });
11351
11352 cx.spawn_in(window, |_, mut cx| async move {
11353 let transaction = futures::select_biased! {
11354 () = timeout => {
11355 log::warn!("timed out waiting for formatting");
11356 None
11357 }
11358 transaction = format.log_err().fuse() => transaction,
11359 };
11360
11361 buffer
11362 .update(&mut cx, |buffer, cx| {
11363 if let Some(transaction) = transaction {
11364 if !buffer.is_singleton() {
11365 buffer.push_transaction(&transaction.0, cx);
11366 }
11367 }
11368
11369 cx.notify();
11370 })
11371 .ok();
11372
11373 Ok(())
11374 })
11375 }
11376
11377 fn restart_language_server(
11378 &mut self,
11379 _: &RestartLanguageServer,
11380 _: &mut Window,
11381 cx: &mut Context<Self>,
11382 ) {
11383 if let Some(project) = self.project.clone() {
11384 self.buffer.update(cx, |multi_buffer, cx| {
11385 project.update(cx, |project, cx| {
11386 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11387 });
11388 })
11389 }
11390 }
11391
11392 fn cancel_language_server_work(
11393 workspace: &mut Workspace,
11394 _: &actions::CancelLanguageServerWork,
11395 _: &mut Window,
11396 cx: &mut Context<Workspace>,
11397 ) {
11398 let project = workspace.project();
11399 let buffers = workspace
11400 .active_item(cx)
11401 .and_then(|item| item.act_as::<Editor>(cx))
11402 .map_or(HashSet::default(), |editor| {
11403 editor.read(cx).buffer.read(cx).all_buffers()
11404 });
11405 project.update(cx, |project, cx| {
11406 project.cancel_language_server_work_for_buffers(buffers, cx);
11407 });
11408 }
11409
11410 fn show_character_palette(
11411 &mut self,
11412 _: &ShowCharacterPalette,
11413 window: &mut Window,
11414 _: &mut Context<Self>,
11415 ) {
11416 window.show_character_palette();
11417 }
11418
11419 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11420 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11421 let buffer = self.buffer.read(cx).snapshot(cx);
11422 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11423 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11424 let is_valid = buffer
11425 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11426 .any(|entry| {
11427 entry.diagnostic.is_primary
11428 && !entry.range.is_empty()
11429 && entry.range.start == primary_range_start
11430 && entry.diagnostic.message == active_diagnostics.primary_message
11431 });
11432
11433 if is_valid != active_diagnostics.is_valid {
11434 active_diagnostics.is_valid = is_valid;
11435 let mut new_styles = HashMap::default();
11436 for (block_id, diagnostic) in &active_diagnostics.blocks {
11437 new_styles.insert(
11438 *block_id,
11439 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11440 );
11441 }
11442 self.display_map.update(cx, |display_map, _cx| {
11443 display_map.replace_blocks(new_styles)
11444 });
11445 }
11446 }
11447 }
11448
11449 fn activate_diagnostics(
11450 &mut self,
11451 buffer_id: BufferId,
11452 group_id: usize,
11453 window: &mut Window,
11454 cx: &mut Context<Self>,
11455 ) {
11456 self.dismiss_diagnostics(cx);
11457 let snapshot = self.snapshot(window, cx);
11458 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11459 let buffer = self.buffer.read(cx).snapshot(cx);
11460
11461 let mut primary_range = None;
11462 let mut primary_message = None;
11463 let diagnostic_group = buffer
11464 .diagnostic_group(buffer_id, group_id)
11465 .filter_map(|entry| {
11466 let start = entry.range.start;
11467 let end = entry.range.end;
11468 if snapshot.is_line_folded(MultiBufferRow(start.row))
11469 && (start.row == end.row
11470 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11471 {
11472 return None;
11473 }
11474 if entry.diagnostic.is_primary {
11475 primary_range = Some(entry.range.clone());
11476 primary_message = Some(entry.diagnostic.message.clone());
11477 }
11478 Some(entry)
11479 })
11480 .collect::<Vec<_>>();
11481 let primary_range = primary_range?;
11482 let primary_message = primary_message?;
11483
11484 let blocks = display_map
11485 .insert_blocks(
11486 diagnostic_group.iter().map(|entry| {
11487 let diagnostic = entry.diagnostic.clone();
11488 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11489 BlockProperties {
11490 style: BlockStyle::Fixed,
11491 placement: BlockPlacement::Below(
11492 buffer.anchor_after(entry.range.start),
11493 ),
11494 height: message_height,
11495 render: diagnostic_block_renderer(diagnostic, None, true, true),
11496 priority: 0,
11497 }
11498 }),
11499 cx,
11500 )
11501 .into_iter()
11502 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11503 .collect();
11504
11505 Some(ActiveDiagnosticGroup {
11506 primary_range: buffer.anchor_before(primary_range.start)
11507 ..buffer.anchor_after(primary_range.end),
11508 primary_message,
11509 group_id,
11510 blocks,
11511 is_valid: true,
11512 })
11513 });
11514 }
11515
11516 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11517 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11518 self.display_map.update(cx, |display_map, cx| {
11519 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11520 });
11521 cx.notify();
11522 }
11523 }
11524
11525 pub fn set_selections_from_remote(
11526 &mut self,
11527 selections: Vec<Selection<Anchor>>,
11528 pending_selection: Option<Selection<Anchor>>,
11529 window: &mut Window,
11530 cx: &mut Context<Self>,
11531 ) {
11532 let old_cursor_position = self.selections.newest_anchor().head();
11533 self.selections.change_with(cx, |s| {
11534 s.select_anchors(selections);
11535 if let Some(pending_selection) = pending_selection {
11536 s.set_pending(pending_selection, SelectMode::Character);
11537 } else {
11538 s.clear_pending();
11539 }
11540 });
11541 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11542 }
11543
11544 fn push_to_selection_history(&mut self) {
11545 self.selection_history.push(SelectionHistoryEntry {
11546 selections: self.selections.disjoint_anchors(),
11547 select_next_state: self.select_next_state.clone(),
11548 select_prev_state: self.select_prev_state.clone(),
11549 add_selections_state: self.add_selections_state.clone(),
11550 });
11551 }
11552
11553 pub fn transact(
11554 &mut self,
11555 window: &mut Window,
11556 cx: &mut Context<Self>,
11557 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11558 ) -> Option<TransactionId> {
11559 self.start_transaction_at(Instant::now(), window, cx);
11560 update(self, window, cx);
11561 self.end_transaction_at(Instant::now(), cx)
11562 }
11563
11564 pub fn start_transaction_at(
11565 &mut self,
11566 now: Instant,
11567 window: &mut Window,
11568 cx: &mut Context<Self>,
11569 ) {
11570 self.end_selection(window, cx);
11571 if let Some(tx_id) = self
11572 .buffer
11573 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11574 {
11575 self.selection_history
11576 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11577 cx.emit(EditorEvent::TransactionBegun {
11578 transaction_id: tx_id,
11579 })
11580 }
11581 }
11582
11583 pub fn end_transaction_at(
11584 &mut self,
11585 now: Instant,
11586 cx: &mut Context<Self>,
11587 ) -> Option<TransactionId> {
11588 if let Some(transaction_id) = self
11589 .buffer
11590 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11591 {
11592 if let Some((_, end_selections)) =
11593 self.selection_history.transaction_mut(transaction_id)
11594 {
11595 *end_selections = Some(self.selections.disjoint_anchors());
11596 } else {
11597 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11598 }
11599
11600 cx.emit(EditorEvent::Edited { transaction_id });
11601 Some(transaction_id)
11602 } else {
11603 None
11604 }
11605 }
11606
11607 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11608 if self.selection_mark_mode {
11609 self.change_selections(None, window, cx, |s| {
11610 s.move_with(|_, sel| {
11611 sel.collapse_to(sel.head(), SelectionGoal::None);
11612 });
11613 })
11614 }
11615 self.selection_mark_mode = true;
11616 cx.notify();
11617 }
11618
11619 pub fn swap_selection_ends(
11620 &mut self,
11621 _: &actions::SwapSelectionEnds,
11622 window: &mut Window,
11623 cx: &mut Context<Self>,
11624 ) {
11625 self.change_selections(None, window, cx, |s| {
11626 s.move_with(|_, sel| {
11627 if sel.start != sel.end {
11628 sel.reversed = !sel.reversed
11629 }
11630 });
11631 });
11632 self.request_autoscroll(Autoscroll::newest(), cx);
11633 cx.notify();
11634 }
11635
11636 pub fn toggle_fold(
11637 &mut self,
11638 _: &actions::ToggleFold,
11639 window: &mut Window,
11640 cx: &mut Context<Self>,
11641 ) {
11642 if self.is_singleton(cx) {
11643 let selection = self.selections.newest::<Point>(cx);
11644
11645 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11646 let range = if selection.is_empty() {
11647 let point = selection.head().to_display_point(&display_map);
11648 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11649 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11650 .to_point(&display_map);
11651 start..end
11652 } else {
11653 selection.range()
11654 };
11655 if display_map.folds_in_range(range).next().is_some() {
11656 self.unfold_lines(&Default::default(), window, cx)
11657 } else {
11658 self.fold(&Default::default(), window, cx)
11659 }
11660 } else {
11661 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11662 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11663 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11664 .map(|(snapshot, _, _)| snapshot.remote_id())
11665 .collect();
11666
11667 for buffer_id in buffer_ids {
11668 if self.is_buffer_folded(buffer_id, cx) {
11669 self.unfold_buffer(buffer_id, cx);
11670 } else {
11671 self.fold_buffer(buffer_id, cx);
11672 }
11673 }
11674 }
11675 }
11676
11677 pub fn toggle_fold_recursive(
11678 &mut self,
11679 _: &actions::ToggleFoldRecursive,
11680 window: &mut Window,
11681 cx: &mut Context<Self>,
11682 ) {
11683 let selection = self.selections.newest::<Point>(cx);
11684
11685 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11686 let range = if selection.is_empty() {
11687 let point = selection.head().to_display_point(&display_map);
11688 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11689 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11690 .to_point(&display_map);
11691 start..end
11692 } else {
11693 selection.range()
11694 };
11695 if display_map.folds_in_range(range).next().is_some() {
11696 self.unfold_recursive(&Default::default(), window, cx)
11697 } else {
11698 self.fold_recursive(&Default::default(), window, cx)
11699 }
11700 }
11701
11702 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11703 if self.is_singleton(cx) {
11704 let mut to_fold = Vec::new();
11705 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11706 let selections = self.selections.all_adjusted(cx);
11707
11708 for selection in selections {
11709 let range = selection.range().sorted();
11710 let buffer_start_row = range.start.row;
11711
11712 if range.start.row != range.end.row {
11713 let mut found = false;
11714 let mut row = range.start.row;
11715 while row <= range.end.row {
11716 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11717 {
11718 found = true;
11719 row = crease.range().end.row + 1;
11720 to_fold.push(crease);
11721 } else {
11722 row += 1
11723 }
11724 }
11725 if found {
11726 continue;
11727 }
11728 }
11729
11730 for row in (0..=range.start.row).rev() {
11731 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11732 if crease.range().end.row >= buffer_start_row {
11733 to_fold.push(crease);
11734 if row <= range.start.row {
11735 break;
11736 }
11737 }
11738 }
11739 }
11740 }
11741
11742 self.fold_creases(to_fold, true, window, cx);
11743 } else {
11744 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11745
11746 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11747 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11748 .map(|(snapshot, _, _)| snapshot.remote_id())
11749 .collect();
11750 for buffer_id in buffer_ids {
11751 self.fold_buffer(buffer_id, cx);
11752 }
11753 }
11754 }
11755
11756 fn fold_at_level(
11757 &mut self,
11758 fold_at: &FoldAtLevel,
11759 window: &mut Window,
11760 cx: &mut Context<Self>,
11761 ) {
11762 if !self.buffer.read(cx).is_singleton() {
11763 return;
11764 }
11765
11766 let fold_at_level = fold_at.level;
11767 let snapshot = self.buffer.read(cx).snapshot(cx);
11768 let mut to_fold = Vec::new();
11769 let mut stack = vec![(0, snapshot.max_row().0, 1)];
11770
11771 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11772 while start_row < end_row {
11773 match self
11774 .snapshot(window, cx)
11775 .crease_for_buffer_row(MultiBufferRow(start_row))
11776 {
11777 Some(crease) => {
11778 let nested_start_row = crease.range().start.row + 1;
11779 let nested_end_row = crease.range().end.row;
11780
11781 if current_level < fold_at_level {
11782 stack.push((nested_start_row, nested_end_row, current_level + 1));
11783 } else if current_level == fold_at_level {
11784 to_fold.push(crease);
11785 }
11786
11787 start_row = nested_end_row + 1;
11788 }
11789 None => start_row += 1,
11790 }
11791 }
11792 }
11793
11794 self.fold_creases(to_fold, true, window, cx);
11795 }
11796
11797 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11798 if self.buffer.read(cx).is_singleton() {
11799 let mut fold_ranges = Vec::new();
11800 let snapshot = self.buffer.read(cx).snapshot(cx);
11801
11802 for row in 0..snapshot.max_row().0 {
11803 if let Some(foldable_range) = self
11804 .snapshot(window, cx)
11805 .crease_for_buffer_row(MultiBufferRow(row))
11806 {
11807 fold_ranges.push(foldable_range);
11808 }
11809 }
11810
11811 self.fold_creases(fold_ranges, true, window, cx);
11812 } else {
11813 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11814 editor
11815 .update_in(&mut cx, |editor, _, cx| {
11816 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11817 editor.fold_buffer(buffer_id, cx);
11818 }
11819 })
11820 .ok();
11821 });
11822 }
11823 }
11824
11825 pub fn fold_function_bodies(
11826 &mut self,
11827 _: &actions::FoldFunctionBodies,
11828 window: &mut Window,
11829 cx: &mut Context<Self>,
11830 ) {
11831 let snapshot = self.buffer.read(cx).snapshot(cx);
11832
11833 let ranges = snapshot
11834 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11835 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11836 .collect::<Vec<_>>();
11837
11838 let creases = ranges
11839 .into_iter()
11840 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11841 .collect();
11842
11843 self.fold_creases(creases, true, window, cx);
11844 }
11845
11846 pub fn fold_recursive(
11847 &mut self,
11848 _: &actions::FoldRecursive,
11849 window: &mut Window,
11850 cx: &mut Context<Self>,
11851 ) {
11852 let mut to_fold = Vec::new();
11853 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11854 let selections = self.selections.all_adjusted(cx);
11855
11856 for selection in selections {
11857 let range = selection.range().sorted();
11858 let buffer_start_row = range.start.row;
11859
11860 if range.start.row != range.end.row {
11861 let mut found = false;
11862 for row in range.start.row..=range.end.row {
11863 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11864 found = true;
11865 to_fold.push(crease);
11866 }
11867 }
11868 if found {
11869 continue;
11870 }
11871 }
11872
11873 for row in (0..=range.start.row).rev() {
11874 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11875 if crease.range().end.row >= buffer_start_row {
11876 to_fold.push(crease);
11877 } else {
11878 break;
11879 }
11880 }
11881 }
11882 }
11883
11884 self.fold_creases(to_fold, true, window, cx);
11885 }
11886
11887 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11888 let buffer_row = fold_at.buffer_row;
11889 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11890
11891 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11892 let autoscroll = self
11893 .selections
11894 .all::<Point>(cx)
11895 .iter()
11896 .any(|selection| crease.range().overlaps(&selection.range()));
11897
11898 self.fold_creases(vec![crease], autoscroll, window, cx);
11899 }
11900 }
11901
11902 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
11903 if self.is_singleton(cx) {
11904 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11905 let buffer = &display_map.buffer_snapshot;
11906 let selections = self.selections.all::<Point>(cx);
11907 let ranges = selections
11908 .iter()
11909 .map(|s| {
11910 let range = s.display_range(&display_map).sorted();
11911 let mut start = range.start.to_point(&display_map);
11912 let mut end = range.end.to_point(&display_map);
11913 start.column = 0;
11914 end.column = buffer.line_len(MultiBufferRow(end.row));
11915 start..end
11916 })
11917 .collect::<Vec<_>>();
11918
11919 self.unfold_ranges(&ranges, true, true, cx);
11920 } else {
11921 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11922 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11923 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11924 .map(|(snapshot, _, _)| snapshot.remote_id())
11925 .collect();
11926 for buffer_id in buffer_ids {
11927 self.unfold_buffer(buffer_id, cx);
11928 }
11929 }
11930 }
11931
11932 pub fn unfold_recursive(
11933 &mut self,
11934 _: &UnfoldRecursive,
11935 _window: &mut Window,
11936 cx: &mut Context<Self>,
11937 ) {
11938 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11939 let selections = self.selections.all::<Point>(cx);
11940 let ranges = selections
11941 .iter()
11942 .map(|s| {
11943 let mut range = s.display_range(&display_map).sorted();
11944 *range.start.column_mut() = 0;
11945 *range.end.column_mut() = display_map.line_len(range.end.row());
11946 let start = range.start.to_point(&display_map);
11947 let end = range.end.to_point(&display_map);
11948 start..end
11949 })
11950 .collect::<Vec<_>>();
11951
11952 self.unfold_ranges(&ranges, true, true, cx);
11953 }
11954
11955 pub fn unfold_at(
11956 &mut self,
11957 unfold_at: &UnfoldAt,
11958 _window: &mut Window,
11959 cx: &mut Context<Self>,
11960 ) {
11961 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11962
11963 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11964 ..Point::new(
11965 unfold_at.buffer_row.0,
11966 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11967 );
11968
11969 let autoscroll = self
11970 .selections
11971 .all::<Point>(cx)
11972 .iter()
11973 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11974
11975 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
11976 }
11977
11978 pub fn unfold_all(
11979 &mut self,
11980 _: &actions::UnfoldAll,
11981 _window: &mut Window,
11982 cx: &mut Context<Self>,
11983 ) {
11984 if self.buffer.read(cx).is_singleton() {
11985 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11986 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11987 } else {
11988 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
11989 editor
11990 .update(&mut cx, |editor, cx| {
11991 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11992 editor.unfold_buffer(buffer_id, cx);
11993 }
11994 })
11995 .ok();
11996 });
11997 }
11998 }
11999
12000 pub fn fold_selected_ranges(
12001 &mut self,
12002 _: &FoldSelectedRanges,
12003 window: &mut Window,
12004 cx: &mut Context<Self>,
12005 ) {
12006 let selections = self.selections.all::<Point>(cx);
12007 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12008 let line_mode = self.selections.line_mode;
12009 let ranges = selections
12010 .into_iter()
12011 .map(|s| {
12012 if line_mode {
12013 let start = Point::new(s.start.row, 0);
12014 let end = Point::new(
12015 s.end.row,
12016 display_map
12017 .buffer_snapshot
12018 .line_len(MultiBufferRow(s.end.row)),
12019 );
12020 Crease::simple(start..end, display_map.fold_placeholder.clone())
12021 } else {
12022 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12023 }
12024 })
12025 .collect::<Vec<_>>();
12026 self.fold_creases(ranges, true, window, cx);
12027 }
12028
12029 pub fn fold_ranges<T: ToOffset + Clone>(
12030 &mut self,
12031 ranges: Vec<Range<T>>,
12032 auto_scroll: bool,
12033 window: &mut Window,
12034 cx: &mut Context<Self>,
12035 ) {
12036 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12037 let ranges = ranges
12038 .into_iter()
12039 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12040 .collect::<Vec<_>>();
12041 self.fold_creases(ranges, auto_scroll, window, cx);
12042 }
12043
12044 pub fn fold_creases<T: ToOffset + Clone>(
12045 &mut self,
12046 creases: Vec<Crease<T>>,
12047 auto_scroll: bool,
12048 window: &mut Window,
12049 cx: &mut Context<Self>,
12050 ) {
12051 if creases.is_empty() {
12052 return;
12053 }
12054
12055 let mut buffers_affected = HashSet::default();
12056 let multi_buffer = self.buffer().read(cx);
12057 for crease in &creases {
12058 if let Some((_, buffer, _)) =
12059 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12060 {
12061 buffers_affected.insert(buffer.read(cx).remote_id());
12062 };
12063 }
12064
12065 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12066
12067 if auto_scroll {
12068 self.request_autoscroll(Autoscroll::fit(), cx);
12069 }
12070
12071 cx.notify();
12072
12073 if let Some(active_diagnostics) = self.active_diagnostics.take() {
12074 // Clear diagnostics block when folding a range that contains it.
12075 let snapshot = self.snapshot(window, cx);
12076 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12077 drop(snapshot);
12078 self.active_diagnostics = Some(active_diagnostics);
12079 self.dismiss_diagnostics(cx);
12080 } else {
12081 self.active_diagnostics = Some(active_diagnostics);
12082 }
12083 }
12084
12085 self.scrollbar_marker_state.dirty = true;
12086 }
12087
12088 /// Removes any folds whose ranges intersect any of the given ranges.
12089 pub fn unfold_ranges<T: ToOffset + Clone>(
12090 &mut self,
12091 ranges: &[Range<T>],
12092 inclusive: bool,
12093 auto_scroll: bool,
12094 cx: &mut Context<Self>,
12095 ) {
12096 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12097 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12098 });
12099 }
12100
12101 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12102 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12103 return;
12104 }
12105 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12106 self.display_map
12107 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12108 cx.emit(EditorEvent::BufferFoldToggled {
12109 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12110 folded: true,
12111 });
12112 cx.notify();
12113 }
12114
12115 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12116 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12117 return;
12118 }
12119 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12120 self.display_map.update(cx, |display_map, cx| {
12121 display_map.unfold_buffer(buffer_id, cx);
12122 });
12123 cx.emit(EditorEvent::BufferFoldToggled {
12124 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12125 folded: false,
12126 });
12127 cx.notify();
12128 }
12129
12130 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12131 self.display_map.read(cx).is_buffer_folded(buffer)
12132 }
12133
12134 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12135 self.display_map.read(cx).folded_buffers()
12136 }
12137
12138 /// Removes any folds with the given ranges.
12139 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12140 &mut self,
12141 ranges: &[Range<T>],
12142 type_id: TypeId,
12143 auto_scroll: bool,
12144 cx: &mut Context<Self>,
12145 ) {
12146 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12147 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12148 });
12149 }
12150
12151 fn remove_folds_with<T: ToOffset + Clone>(
12152 &mut self,
12153 ranges: &[Range<T>],
12154 auto_scroll: bool,
12155 cx: &mut Context<Self>,
12156 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12157 ) {
12158 if ranges.is_empty() {
12159 return;
12160 }
12161
12162 let mut buffers_affected = HashSet::default();
12163 let multi_buffer = self.buffer().read(cx);
12164 for range in ranges {
12165 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12166 buffers_affected.insert(buffer.read(cx).remote_id());
12167 };
12168 }
12169
12170 self.display_map.update(cx, update);
12171
12172 if auto_scroll {
12173 self.request_autoscroll(Autoscroll::fit(), cx);
12174 }
12175
12176 cx.notify();
12177 self.scrollbar_marker_state.dirty = true;
12178 self.active_indent_guides_state.dirty = true;
12179 }
12180
12181 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12182 self.display_map.read(cx).fold_placeholder.clone()
12183 }
12184
12185 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12186 self.buffer.update(cx, |buffer, cx| {
12187 buffer.set_all_diff_hunks_expanded(cx);
12188 });
12189 }
12190
12191 pub fn expand_all_diff_hunks(
12192 &mut self,
12193 _: &ExpandAllHunkDiffs,
12194 _window: &mut Window,
12195 cx: &mut Context<Self>,
12196 ) {
12197 self.buffer.update(cx, |buffer, cx| {
12198 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12199 });
12200 }
12201
12202 pub fn toggle_selected_diff_hunks(
12203 &mut self,
12204 _: &ToggleSelectedDiffHunks,
12205 _window: &mut Window,
12206 cx: &mut Context<Self>,
12207 ) {
12208 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12209 self.toggle_diff_hunks_in_ranges(ranges, cx);
12210 }
12211
12212 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12213 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12214 self.buffer
12215 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12216 }
12217
12218 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12219 self.buffer.update(cx, |buffer, cx| {
12220 let ranges = vec![Anchor::min()..Anchor::max()];
12221 if !buffer.all_diff_hunks_expanded()
12222 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12223 {
12224 buffer.collapse_diff_hunks(ranges, cx);
12225 true
12226 } else {
12227 false
12228 }
12229 })
12230 }
12231
12232 fn toggle_diff_hunks_in_ranges(
12233 &mut self,
12234 ranges: Vec<Range<Anchor>>,
12235 cx: &mut Context<'_, Editor>,
12236 ) {
12237 self.buffer.update(cx, |buffer, cx| {
12238 if buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx) {
12239 buffer.collapse_diff_hunks(ranges, cx)
12240 } else {
12241 buffer.expand_diff_hunks(ranges, cx)
12242 }
12243 })
12244 }
12245
12246 pub(crate) fn apply_all_diff_hunks(
12247 &mut self,
12248 _: &ApplyAllDiffHunks,
12249 window: &mut Window,
12250 cx: &mut Context<Self>,
12251 ) {
12252 let buffers = self.buffer.read(cx).all_buffers();
12253 for branch_buffer in buffers {
12254 branch_buffer.update(cx, |branch_buffer, cx| {
12255 branch_buffer.merge_into_base(Vec::new(), cx);
12256 });
12257 }
12258
12259 if let Some(project) = self.project.clone() {
12260 self.save(true, project, window, cx).detach_and_log_err(cx);
12261 }
12262 }
12263
12264 pub(crate) fn apply_selected_diff_hunks(
12265 &mut self,
12266 _: &ApplyDiffHunk,
12267 window: &mut Window,
12268 cx: &mut Context<Self>,
12269 ) {
12270 let snapshot = self.snapshot(window, cx);
12271 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12272 let mut ranges_by_buffer = HashMap::default();
12273 self.transact(window, cx, |editor, _window, cx| {
12274 for hunk in hunks {
12275 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12276 ranges_by_buffer
12277 .entry(buffer.clone())
12278 .or_insert_with(Vec::new)
12279 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12280 }
12281 }
12282
12283 for (buffer, ranges) in ranges_by_buffer {
12284 buffer.update(cx, |buffer, cx| {
12285 buffer.merge_into_base(ranges, cx);
12286 });
12287 }
12288 });
12289
12290 if let Some(project) = self.project.clone() {
12291 self.save(true, project, window, cx).detach_and_log_err(cx);
12292 }
12293 }
12294
12295 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12296 if hovered != self.gutter_hovered {
12297 self.gutter_hovered = hovered;
12298 cx.notify();
12299 }
12300 }
12301
12302 pub fn insert_blocks(
12303 &mut self,
12304 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12305 autoscroll: Option<Autoscroll>,
12306 cx: &mut Context<Self>,
12307 ) -> Vec<CustomBlockId> {
12308 let blocks = self
12309 .display_map
12310 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12311 if let Some(autoscroll) = autoscroll {
12312 self.request_autoscroll(autoscroll, cx);
12313 }
12314 cx.notify();
12315 blocks
12316 }
12317
12318 pub fn resize_blocks(
12319 &mut self,
12320 heights: HashMap<CustomBlockId, u32>,
12321 autoscroll: Option<Autoscroll>,
12322 cx: &mut Context<Self>,
12323 ) {
12324 self.display_map
12325 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12326 if let Some(autoscroll) = autoscroll {
12327 self.request_autoscroll(autoscroll, cx);
12328 }
12329 cx.notify();
12330 }
12331
12332 pub fn replace_blocks(
12333 &mut self,
12334 renderers: HashMap<CustomBlockId, RenderBlock>,
12335 autoscroll: Option<Autoscroll>,
12336 cx: &mut Context<Self>,
12337 ) {
12338 self.display_map
12339 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12340 if let Some(autoscroll) = autoscroll {
12341 self.request_autoscroll(autoscroll, cx);
12342 }
12343 cx.notify();
12344 }
12345
12346 pub fn remove_blocks(
12347 &mut self,
12348 block_ids: HashSet<CustomBlockId>,
12349 autoscroll: Option<Autoscroll>,
12350 cx: &mut Context<Self>,
12351 ) {
12352 self.display_map.update(cx, |display_map, cx| {
12353 display_map.remove_blocks(block_ids, cx)
12354 });
12355 if let Some(autoscroll) = autoscroll {
12356 self.request_autoscroll(autoscroll, cx);
12357 }
12358 cx.notify();
12359 }
12360
12361 pub fn row_for_block(
12362 &self,
12363 block_id: CustomBlockId,
12364 cx: &mut Context<Self>,
12365 ) -> Option<DisplayRow> {
12366 self.display_map
12367 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12368 }
12369
12370 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12371 self.focused_block = Some(focused_block);
12372 }
12373
12374 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12375 self.focused_block.take()
12376 }
12377
12378 pub fn insert_creases(
12379 &mut self,
12380 creases: impl IntoIterator<Item = Crease<Anchor>>,
12381 cx: &mut Context<Self>,
12382 ) -> Vec<CreaseId> {
12383 self.display_map
12384 .update(cx, |map, cx| map.insert_creases(creases, cx))
12385 }
12386
12387 pub fn remove_creases(
12388 &mut self,
12389 ids: impl IntoIterator<Item = CreaseId>,
12390 cx: &mut Context<Self>,
12391 ) {
12392 self.display_map
12393 .update(cx, |map, cx| map.remove_creases(ids, cx));
12394 }
12395
12396 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12397 self.display_map
12398 .update(cx, |map, cx| map.snapshot(cx))
12399 .longest_row()
12400 }
12401
12402 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12403 self.display_map
12404 .update(cx, |map, cx| map.snapshot(cx))
12405 .max_point()
12406 }
12407
12408 pub fn text(&self, cx: &App) -> String {
12409 self.buffer.read(cx).read(cx).text()
12410 }
12411
12412 pub fn is_empty(&self, cx: &App) -> bool {
12413 self.buffer.read(cx).read(cx).is_empty()
12414 }
12415
12416 pub fn text_option(&self, cx: &App) -> Option<String> {
12417 let text = self.text(cx);
12418 let text = text.trim();
12419
12420 if text.is_empty() {
12421 return None;
12422 }
12423
12424 Some(text.to_string())
12425 }
12426
12427 pub fn set_text(
12428 &mut self,
12429 text: impl Into<Arc<str>>,
12430 window: &mut Window,
12431 cx: &mut Context<Self>,
12432 ) {
12433 self.transact(window, cx, |this, _, cx| {
12434 this.buffer
12435 .read(cx)
12436 .as_singleton()
12437 .expect("you can only call set_text on editors for singleton buffers")
12438 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12439 });
12440 }
12441
12442 pub fn display_text(&self, cx: &mut App) -> String {
12443 self.display_map
12444 .update(cx, |map, cx| map.snapshot(cx))
12445 .text()
12446 }
12447
12448 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12449 let mut wrap_guides = smallvec::smallvec![];
12450
12451 if self.show_wrap_guides == Some(false) {
12452 return wrap_guides;
12453 }
12454
12455 let settings = self.buffer.read(cx).settings_at(0, cx);
12456 if settings.show_wrap_guides {
12457 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12458 wrap_guides.push((soft_wrap as usize, true));
12459 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12460 wrap_guides.push((soft_wrap as usize, true));
12461 }
12462 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12463 }
12464
12465 wrap_guides
12466 }
12467
12468 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12469 let settings = self.buffer.read(cx).settings_at(0, cx);
12470 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12471 match mode {
12472 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12473 SoftWrap::None
12474 }
12475 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12476 language_settings::SoftWrap::PreferredLineLength => {
12477 SoftWrap::Column(settings.preferred_line_length)
12478 }
12479 language_settings::SoftWrap::Bounded => {
12480 SoftWrap::Bounded(settings.preferred_line_length)
12481 }
12482 }
12483 }
12484
12485 pub fn set_soft_wrap_mode(
12486 &mut self,
12487 mode: language_settings::SoftWrap,
12488
12489 cx: &mut Context<Self>,
12490 ) {
12491 self.soft_wrap_mode_override = Some(mode);
12492 cx.notify();
12493 }
12494
12495 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12496 self.text_style_refinement = Some(style);
12497 }
12498
12499 /// called by the Element so we know what style we were most recently rendered with.
12500 pub(crate) fn set_style(
12501 &mut self,
12502 style: EditorStyle,
12503 window: &mut Window,
12504 cx: &mut Context<Self>,
12505 ) {
12506 let rem_size = window.rem_size();
12507 self.display_map.update(cx, |map, cx| {
12508 map.set_font(
12509 style.text.font(),
12510 style.text.font_size.to_pixels(rem_size),
12511 cx,
12512 )
12513 });
12514 self.style = Some(style);
12515 }
12516
12517 pub fn style(&self) -> Option<&EditorStyle> {
12518 self.style.as_ref()
12519 }
12520
12521 // Called by the element. This method is not designed to be called outside of the editor
12522 // element's layout code because it does not notify when rewrapping is computed synchronously.
12523 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12524 self.display_map
12525 .update(cx, |map, cx| map.set_wrap_width(width, cx))
12526 }
12527
12528 pub fn set_soft_wrap(&mut self) {
12529 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12530 }
12531
12532 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12533 if self.soft_wrap_mode_override.is_some() {
12534 self.soft_wrap_mode_override.take();
12535 } else {
12536 let soft_wrap = match self.soft_wrap_mode(cx) {
12537 SoftWrap::GitDiff => return,
12538 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12539 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12540 language_settings::SoftWrap::None
12541 }
12542 };
12543 self.soft_wrap_mode_override = Some(soft_wrap);
12544 }
12545 cx.notify();
12546 }
12547
12548 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12549 let Some(workspace) = self.workspace() else {
12550 return;
12551 };
12552 let fs = workspace.read(cx).app_state().fs.clone();
12553 let current_show = TabBarSettings::get_global(cx).show;
12554 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12555 setting.show = Some(!current_show);
12556 });
12557 }
12558
12559 pub fn toggle_indent_guides(
12560 &mut self,
12561 _: &ToggleIndentGuides,
12562 _: &mut Window,
12563 cx: &mut Context<Self>,
12564 ) {
12565 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12566 self.buffer
12567 .read(cx)
12568 .settings_at(0, cx)
12569 .indent_guides
12570 .enabled
12571 });
12572 self.show_indent_guides = Some(!currently_enabled);
12573 cx.notify();
12574 }
12575
12576 fn should_show_indent_guides(&self) -> Option<bool> {
12577 self.show_indent_guides
12578 }
12579
12580 pub fn toggle_line_numbers(
12581 &mut self,
12582 _: &ToggleLineNumbers,
12583 _: &mut Window,
12584 cx: &mut Context<Self>,
12585 ) {
12586 let mut editor_settings = EditorSettings::get_global(cx).clone();
12587 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12588 EditorSettings::override_global(editor_settings, cx);
12589 }
12590
12591 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12592 self.use_relative_line_numbers
12593 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12594 }
12595
12596 pub fn toggle_relative_line_numbers(
12597 &mut self,
12598 _: &ToggleRelativeLineNumbers,
12599 _: &mut Window,
12600 cx: &mut Context<Self>,
12601 ) {
12602 let is_relative = self.should_use_relative_line_numbers(cx);
12603 self.set_relative_line_number(Some(!is_relative), cx)
12604 }
12605
12606 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12607 self.use_relative_line_numbers = is_relative;
12608 cx.notify();
12609 }
12610
12611 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12612 self.show_gutter = show_gutter;
12613 cx.notify();
12614 }
12615
12616 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12617 self.show_scrollbars = show_scrollbars;
12618 cx.notify();
12619 }
12620
12621 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12622 self.show_line_numbers = Some(show_line_numbers);
12623 cx.notify();
12624 }
12625
12626 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12627 self.show_git_diff_gutter = Some(show_git_diff_gutter);
12628 cx.notify();
12629 }
12630
12631 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12632 self.show_code_actions = Some(show_code_actions);
12633 cx.notify();
12634 }
12635
12636 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12637 self.show_runnables = Some(show_runnables);
12638 cx.notify();
12639 }
12640
12641 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12642 if self.display_map.read(cx).masked != masked {
12643 self.display_map.update(cx, |map, _| map.masked = masked);
12644 }
12645 cx.notify()
12646 }
12647
12648 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12649 self.show_wrap_guides = Some(show_wrap_guides);
12650 cx.notify();
12651 }
12652
12653 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12654 self.show_indent_guides = Some(show_indent_guides);
12655 cx.notify();
12656 }
12657
12658 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12659 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12660 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12661 if let Some(dir) = file.abs_path(cx).parent() {
12662 return Some(dir.to_owned());
12663 }
12664 }
12665
12666 if let Some(project_path) = buffer.read(cx).project_path(cx) {
12667 return Some(project_path.path.to_path_buf());
12668 }
12669 }
12670
12671 None
12672 }
12673
12674 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12675 self.active_excerpt(cx)?
12676 .1
12677 .read(cx)
12678 .file()
12679 .and_then(|f| f.as_local())
12680 }
12681
12682 fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12683 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12684 let project_path = buffer.read(cx).project_path(cx)?;
12685 let project = self.project.as_ref()?.read(cx);
12686 project.absolute_path(&project_path, cx)
12687 })
12688 }
12689
12690 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12691 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12692 let project_path = buffer.read(cx).project_path(cx)?;
12693 let project = self.project.as_ref()?.read(cx);
12694 let entry = project.entry_for_path(&project_path, cx)?;
12695 let path = entry.path.to_path_buf();
12696 Some(path)
12697 })
12698 }
12699
12700 pub fn reveal_in_finder(
12701 &mut self,
12702 _: &RevealInFileManager,
12703 _window: &mut Window,
12704 cx: &mut Context<Self>,
12705 ) {
12706 if let Some(target) = self.target_file(cx) {
12707 cx.reveal_path(&target.abs_path(cx));
12708 }
12709 }
12710
12711 pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12712 if let Some(path) = self.target_file_abs_path(cx) {
12713 if let Some(path) = path.to_str() {
12714 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12715 }
12716 }
12717 }
12718
12719 pub fn copy_relative_path(
12720 &mut self,
12721 _: &CopyRelativePath,
12722 _window: &mut Window,
12723 cx: &mut Context<Self>,
12724 ) {
12725 if let Some(path) = self.target_file_path(cx) {
12726 if let Some(path) = path.to_str() {
12727 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12728 }
12729 }
12730 }
12731
12732 pub fn toggle_git_blame(
12733 &mut self,
12734 _: &ToggleGitBlame,
12735 window: &mut Window,
12736 cx: &mut Context<Self>,
12737 ) {
12738 self.show_git_blame_gutter = !self.show_git_blame_gutter;
12739
12740 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12741 self.start_git_blame(true, window, cx);
12742 }
12743
12744 cx.notify();
12745 }
12746
12747 pub fn toggle_git_blame_inline(
12748 &mut self,
12749 _: &ToggleGitBlameInline,
12750 window: &mut Window,
12751 cx: &mut Context<Self>,
12752 ) {
12753 self.toggle_git_blame_inline_internal(true, window, cx);
12754 cx.notify();
12755 }
12756
12757 pub fn git_blame_inline_enabled(&self) -> bool {
12758 self.git_blame_inline_enabled
12759 }
12760
12761 pub fn toggle_selection_menu(
12762 &mut self,
12763 _: &ToggleSelectionMenu,
12764 _: &mut Window,
12765 cx: &mut Context<Self>,
12766 ) {
12767 self.show_selection_menu = self
12768 .show_selection_menu
12769 .map(|show_selections_menu| !show_selections_menu)
12770 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12771
12772 cx.notify();
12773 }
12774
12775 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12776 self.show_selection_menu
12777 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12778 }
12779
12780 fn start_git_blame(
12781 &mut self,
12782 user_triggered: bool,
12783 window: &mut Window,
12784 cx: &mut Context<Self>,
12785 ) {
12786 if let Some(project) = self.project.as_ref() {
12787 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12788 return;
12789 };
12790
12791 if buffer.read(cx).file().is_none() {
12792 return;
12793 }
12794
12795 let focused = self.focus_handle(cx).contains_focused(window, cx);
12796
12797 let project = project.clone();
12798 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12799 self.blame_subscription =
12800 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12801 self.blame = Some(blame);
12802 }
12803 }
12804
12805 fn toggle_git_blame_inline_internal(
12806 &mut self,
12807 user_triggered: bool,
12808 window: &mut Window,
12809 cx: &mut Context<Self>,
12810 ) {
12811 if self.git_blame_inline_enabled {
12812 self.git_blame_inline_enabled = false;
12813 self.show_git_blame_inline = false;
12814 self.show_git_blame_inline_delay_task.take();
12815 } else {
12816 self.git_blame_inline_enabled = true;
12817 self.start_git_blame_inline(user_triggered, window, cx);
12818 }
12819
12820 cx.notify();
12821 }
12822
12823 fn start_git_blame_inline(
12824 &mut self,
12825 user_triggered: bool,
12826 window: &mut Window,
12827 cx: &mut Context<Self>,
12828 ) {
12829 self.start_git_blame(user_triggered, window, cx);
12830
12831 if ProjectSettings::get_global(cx)
12832 .git
12833 .inline_blame_delay()
12834 .is_some()
12835 {
12836 self.start_inline_blame_timer(window, cx);
12837 } else {
12838 self.show_git_blame_inline = true
12839 }
12840 }
12841
12842 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12843 self.blame.as_ref()
12844 }
12845
12846 pub fn show_git_blame_gutter(&self) -> bool {
12847 self.show_git_blame_gutter
12848 }
12849
12850 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12851 self.show_git_blame_gutter && self.has_blame_entries(cx)
12852 }
12853
12854 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12855 self.show_git_blame_inline
12856 && self.focus_handle.is_focused(window)
12857 && !self.newest_selection_head_on_empty_line(cx)
12858 && self.has_blame_entries(cx)
12859 }
12860
12861 fn has_blame_entries(&self, cx: &App) -> bool {
12862 self.blame()
12863 .map_or(false, |blame| blame.read(cx).has_generated_entries())
12864 }
12865
12866 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12867 let cursor_anchor = self.selections.newest_anchor().head();
12868
12869 let snapshot = self.buffer.read(cx).snapshot(cx);
12870 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12871
12872 snapshot.line_len(buffer_row) == 0
12873 }
12874
12875 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12876 let buffer_and_selection = maybe!({
12877 let selection = self.selections.newest::<Point>(cx);
12878 let selection_range = selection.range();
12879
12880 let multi_buffer = self.buffer().read(cx);
12881 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12882 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12883
12884 let (buffer, range, _) = if selection.reversed {
12885 buffer_ranges.first()
12886 } else {
12887 buffer_ranges.last()
12888 }?;
12889
12890 let selection = text::ToPoint::to_point(&range.start, &buffer).row
12891 ..text::ToPoint::to_point(&range.end, &buffer).row;
12892 Some((
12893 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
12894 selection,
12895 ))
12896 });
12897
12898 let Some((buffer, selection)) = buffer_and_selection else {
12899 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12900 };
12901
12902 let Some(project) = self.project.as_ref() else {
12903 return Task::ready(Err(anyhow!("editor does not have project")));
12904 };
12905
12906 project.update(cx, |project, cx| {
12907 project.get_permalink_to_line(&buffer, selection, cx)
12908 })
12909 }
12910
12911 pub fn copy_permalink_to_line(
12912 &mut self,
12913 _: &CopyPermalinkToLine,
12914 window: &mut Window,
12915 cx: &mut Context<Self>,
12916 ) {
12917 let permalink_task = self.get_permalink_to_line(cx);
12918 let workspace = self.workspace();
12919
12920 cx.spawn_in(window, |_, mut cx| async move {
12921 match permalink_task.await {
12922 Ok(permalink) => {
12923 cx.update(|_, cx| {
12924 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12925 })
12926 .ok();
12927 }
12928 Err(err) => {
12929 let message = format!("Failed to copy permalink: {err}");
12930
12931 Err::<(), anyhow::Error>(err).log_err();
12932
12933 if let Some(workspace) = workspace {
12934 workspace
12935 .update_in(&mut cx, |workspace, _, cx| {
12936 struct CopyPermalinkToLine;
12937
12938 workspace.show_toast(
12939 Toast::new(
12940 NotificationId::unique::<CopyPermalinkToLine>(),
12941 message,
12942 ),
12943 cx,
12944 )
12945 })
12946 .ok();
12947 }
12948 }
12949 }
12950 })
12951 .detach();
12952 }
12953
12954 pub fn copy_file_location(
12955 &mut self,
12956 _: &CopyFileLocation,
12957 _: &mut Window,
12958 cx: &mut Context<Self>,
12959 ) {
12960 let selection = self.selections.newest::<Point>(cx).start.row + 1;
12961 if let Some(file) = self.target_file(cx) {
12962 if let Some(path) = file.path().to_str() {
12963 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
12964 }
12965 }
12966 }
12967
12968 pub fn open_permalink_to_line(
12969 &mut self,
12970 _: &OpenPermalinkToLine,
12971 window: &mut Window,
12972 cx: &mut Context<Self>,
12973 ) {
12974 let permalink_task = self.get_permalink_to_line(cx);
12975 let workspace = self.workspace();
12976
12977 cx.spawn_in(window, |_, mut cx| async move {
12978 match permalink_task.await {
12979 Ok(permalink) => {
12980 cx.update(|_, cx| {
12981 cx.open_url(permalink.as_ref());
12982 })
12983 .ok();
12984 }
12985 Err(err) => {
12986 let message = format!("Failed to open permalink: {err}");
12987
12988 Err::<(), anyhow::Error>(err).log_err();
12989
12990 if let Some(workspace) = workspace {
12991 workspace
12992 .update(&mut cx, |workspace, cx| {
12993 struct OpenPermalinkToLine;
12994
12995 workspace.show_toast(
12996 Toast::new(
12997 NotificationId::unique::<OpenPermalinkToLine>(),
12998 message,
12999 ),
13000 cx,
13001 )
13002 })
13003 .ok();
13004 }
13005 }
13006 }
13007 })
13008 .detach();
13009 }
13010
13011 pub fn insert_uuid_v4(
13012 &mut self,
13013 _: &InsertUuidV4,
13014 window: &mut Window,
13015 cx: &mut Context<Self>,
13016 ) {
13017 self.insert_uuid(UuidVersion::V4, window, cx);
13018 }
13019
13020 pub fn insert_uuid_v7(
13021 &mut self,
13022 _: &InsertUuidV7,
13023 window: &mut Window,
13024 cx: &mut Context<Self>,
13025 ) {
13026 self.insert_uuid(UuidVersion::V7, window, cx);
13027 }
13028
13029 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13030 self.transact(window, cx, |this, window, cx| {
13031 let edits = this
13032 .selections
13033 .all::<Point>(cx)
13034 .into_iter()
13035 .map(|selection| {
13036 let uuid = match version {
13037 UuidVersion::V4 => uuid::Uuid::new_v4(),
13038 UuidVersion::V7 => uuid::Uuid::now_v7(),
13039 };
13040
13041 (selection.range(), uuid.to_string())
13042 });
13043 this.edit(edits, cx);
13044 this.refresh_inline_completion(true, false, window, cx);
13045 });
13046 }
13047
13048 pub fn open_selections_in_multibuffer(
13049 &mut self,
13050 _: &OpenSelectionsInMultibuffer,
13051 window: &mut Window,
13052 cx: &mut Context<Self>,
13053 ) {
13054 let multibuffer = self.buffer.read(cx);
13055
13056 let Some(buffer) = multibuffer.as_singleton() else {
13057 return;
13058 };
13059
13060 let Some(workspace) = self.workspace() else {
13061 return;
13062 };
13063
13064 let locations = self
13065 .selections
13066 .disjoint_anchors()
13067 .iter()
13068 .map(|range| Location {
13069 buffer: buffer.clone(),
13070 range: range.start.text_anchor..range.end.text_anchor,
13071 })
13072 .collect::<Vec<_>>();
13073
13074 let title = multibuffer.title(cx).to_string();
13075
13076 cx.spawn_in(window, |_, mut cx| async move {
13077 workspace.update_in(&mut cx, |workspace, window, cx| {
13078 Self::open_locations_in_multibuffer(
13079 workspace,
13080 locations,
13081 format!("Selections for '{title}'"),
13082 false,
13083 MultibufferSelectionMode::All,
13084 window,
13085 cx,
13086 );
13087 })
13088 })
13089 .detach();
13090 }
13091
13092 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13093 /// last highlight added will be used.
13094 ///
13095 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13096 pub fn highlight_rows<T: 'static>(
13097 &mut self,
13098 range: Range<Anchor>,
13099 color: Hsla,
13100 should_autoscroll: bool,
13101 cx: &mut Context<Self>,
13102 ) {
13103 let snapshot = self.buffer().read(cx).snapshot(cx);
13104 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13105 let ix = row_highlights.binary_search_by(|highlight| {
13106 Ordering::Equal
13107 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13108 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13109 });
13110
13111 if let Err(mut ix) = ix {
13112 let index = post_inc(&mut self.highlight_order);
13113
13114 // If this range intersects with the preceding highlight, then merge it with
13115 // the preceding highlight. Otherwise insert a new highlight.
13116 let mut merged = false;
13117 if ix > 0 {
13118 let prev_highlight = &mut row_highlights[ix - 1];
13119 if prev_highlight
13120 .range
13121 .end
13122 .cmp(&range.start, &snapshot)
13123 .is_ge()
13124 {
13125 ix -= 1;
13126 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13127 prev_highlight.range.end = range.end;
13128 }
13129 merged = true;
13130 prev_highlight.index = index;
13131 prev_highlight.color = color;
13132 prev_highlight.should_autoscroll = should_autoscroll;
13133 }
13134 }
13135
13136 if !merged {
13137 row_highlights.insert(
13138 ix,
13139 RowHighlight {
13140 range: range.clone(),
13141 index,
13142 color,
13143 should_autoscroll,
13144 },
13145 );
13146 }
13147
13148 // If any of the following highlights intersect with this one, merge them.
13149 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13150 let highlight = &row_highlights[ix];
13151 if next_highlight
13152 .range
13153 .start
13154 .cmp(&highlight.range.end, &snapshot)
13155 .is_le()
13156 {
13157 if next_highlight
13158 .range
13159 .end
13160 .cmp(&highlight.range.end, &snapshot)
13161 .is_gt()
13162 {
13163 row_highlights[ix].range.end = next_highlight.range.end;
13164 }
13165 row_highlights.remove(ix + 1);
13166 } else {
13167 break;
13168 }
13169 }
13170 }
13171 }
13172
13173 /// Remove any highlighted row ranges of the given type that intersect the
13174 /// given ranges.
13175 pub fn remove_highlighted_rows<T: 'static>(
13176 &mut self,
13177 ranges_to_remove: Vec<Range<Anchor>>,
13178 cx: &mut Context<Self>,
13179 ) {
13180 let snapshot = self.buffer().read(cx).snapshot(cx);
13181 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13182 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13183 row_highlights.retain(|highlight| {
13184 while let Some(range_to_remove) = ranges_to_remove.peek() {
13185 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13186 Ordering::Less | Ordering::Equal => {
13187 ranges_to_remove.next();
13188 }
13189 Ordering::Greater => {
13190 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13191 Ordering::Less | Ordering::Equal => {
13192 return false;
13193 }
13194 Ordering::Greater => break,
13195 }
13196 }
13197 }
13198 }
13199
13200 true
13201 })
13202 }
13203
13204 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13205 pub fn clear_row_highlights<T: 'static>(&mut self) {
13206 self.highlighted_rows.remove(&TypeId::of::<T>());
13207 }
13208
13209 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13210 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13211 self.highlighted_rows
13212 .get(&TypeId::of::<T>())
13213 .map_or(&[] as &[_], |vec| vec.as_slice())
13214 .iter()
13215 .map(|highlight| (highlight.range.clone(), highlight.color))
13216 }
13217
13218 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13219 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13220 /// Allows to ignore certain kinds of highlights.
13221 pub fn highlighted_display_rows(
13222 &self,
13223 window: &mut Window,
13224 cx: &mut App,
13225 ) -> BTreeMap<DisplayRow, Hsla> {
13226 let snapshot = self.snapshot(window, cx);
13227 let mut used_highlight_orders = HashMap::default();
13228 self.highlighted_rows
13229 .iter()
13230 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13231 .fold(
13232 BTreeMap::<DisplayRow, Hsla>::new(),
13233 |mut unique_rows, highlight| {
13234 let start = highlight.range.start.to_display_point(&snapshot);
13235 let end = highlight.range.end.to_display_point(&snapshot);
13236 let start_row = start.row().0;
13237 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13238 && end.column() == 0
13239 {
13240 end.row().0.saturating_sub(1)
13241 } else {
13242 end.row().0
13243 };
13244 for row in start_row..=end_row {
13245 let used_index =
13246 used_highlight_orders.entry(row).or_insert(highlight.index);
13247 if highlight.index >= *used_index {
13248 *used_index = highlight.index;
13249 unique_rows.insert(DisplayRow(row), highlight.color);
13250 }
13251 }
13252 unique_rows
13253 },
13254 )
13255 }
13256
13257 pub fn highlighted_display_row_for_autoscroll(
13258 &self,
13259 snapshot: &DisplaySnapshot,
13260 ) -> Option<DisplayRow> {
13261 self.highlighted_rows
13262 .values()
13263 .flat_map(|highlighted_rows| highlighted_rows.iter())
13264 .filter_map(|highlight| {
13265 if highlight.should_autoscroll {
13266 Some(highlight.range.start.to_display_point(snapshot).row())
13267 } else {
13268 None
13269 }
13270 })
13271 .min()
13272 }
13273
13274 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13275 self.highlight_background::<SearchWithinRange>(
13276 ranges,
13277 |colors| colors.editor_document_highlight_read_background,
13278 cx,
13279 )
13280 }
13281
13282 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13283 self.breadcrumb_header = Some(new_header);
13284 }
13285
13286 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13287 self.clear_background_highlights::<SearchWithinRange>(cx);
13288 }
13289
13290 pub fn highlight_background<T: 'static>(
13291 &mut self,
13292 ranges: &[Range<Anchor>],
13293 color_fetcher: fn(&ThemeColors) -> Hsla,
13294 cx: &mut Context<Self>,
13295 ) {
13296 self.background_highlights
13297 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13298 self.scrollbar_marker_state.dirty = true;
13299 cx.notify();
13300 }
13301
13302 pub fn clear_background_highlights<T: 'static>(
13303 &mut self,
13304 cx: &mut Context<Self>,
13305 ) -> Option<BackgroundHighlight> {
13306 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13307 if !text_highlights.1.is_empty() {
13308 self.scrollbar_marker_state.dirty = true;
13309 cx.notify();
13310 }
13311 Some(text_highlights)
13312 }
13313
13314 pub fn highlight_gutter<T: 'static>(
13315 &mut self,
13316 ranges: &[Range<Anchor>],
13317 color_fetcher: fn(&App) -> Hsla,
13318 cx: &mut Context<Self>,
13319 ) {
13320 self.gutter_highlights
13321 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13322 cx.notify();
13323 }
13324
13325 pub fn clear_gutter_highlights<T: 'static>(
13326 &mut self,
13327 cx: &mut Context<Self>,
13328 ) -> Option<GutterHighlight> {
13329 cx.notify();
13330 self.gutter_highlights.remove(&TypeId::of::<T>())
13331 }
13332
13333 #[cfg(feature = "test-support")]
13334 pub fn all_text_background_highlights(
13335 &self,
13336 window: &mut Window,
13337 cx: &mut Context<Self>,
13338 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13339 let snapshot = self.snapshot(window, cx);
13340 let buffer = &snapshot.buffer_snapshot;
13341 let start = buffer.anchor_before(0);
13342 let end = buffer.anchor_after(buffer.len());
13343 let theme = cx.theme().colors();
13344 self.background_highlights_in_range(start..end, &snapshot, theme)
13345 }
13346
13347 #[cfg(feature = "test-support")]
13348 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13349 let snapshot = self.buffer().read(cx).snapshot(cx);
13350
13351 let highlights = self
13352 .background_highlights
13353 .get(&TypeId::of::<items::BufferSearchHighlights>());
13354
13355 if let Some((_color, ranges)) = highlights {
13356 ranges
13357 .iter()
13358 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13359 .collect_vec()
13360 } else {
13361 vec![]
13362 }
13363 }
13364
13365 fn document_highlights_for_position<'a>(
13366 &'a self,
13367 position: Anchor,
13368 buffer: &'a MultiBufferSnapshot,
13369 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13370 let read_highlights = self
13371 .background_highlights
13372 .get(&TypeId::of::<DocumentHighlightRead>())
13373 .map(|h| &h.1);
13374 let write_highlights = self
13375 .background_highlights
13376 .get(&TypeId::of::<DocumentHighlightWrite>())
13377 .map(|h| &h.1);
13378 let left_position = position.bias_left(buffer);
13379 let right_position = position.bias_right(buffer);
13380 read_highlights
13381 .into_iter()
13382 .chain(write_highlights)
13383 .flat_map(move |ranges| {
13384 let start_ix = match ranges.binary_search_by(|probe| {
13385 let cmp = probe.end.cmp(&left_position, buffer);
13386 if cmp.is_ge() {
13387 Ordering::Greater
13388 } else {
13389 Ordering::Less
13390 }
13391 }) {
13392 Ok(i) | Err(i) => i,
13393 };
13394
13395 ranges[start_ix..]
13396 .iter()
13397 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13398 })
13399 }
13400
13401 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13402 self.background_highlights
13403 .get(&TypeId::of::<T>())
13404 .map_or(false, |(_, highlights)| !highlights.is_empty())
13405 }
13406
13407 pub fn background_highlights_in_range(
13408 &self,
13409 search_range: Range<Anchor>,
13410 display_snapshot: &DisplaySnapshot,
13411 theme: &ThemeColors,
13412 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13413 let mut results = Vec::new();
13414 for (color_fetcher, ranges) in self.background_highlights.values() {
13415 let color = color_fetcher(theme);
13416 let start_ix = match ranges.binary_search_by(|probe| {
13417 let cmp = probe
13418 .end
13419 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13420 if cmp.is_gt() {
13421 Ordering::Greater
13422 } else {
13423 Ordering::Less
13424 }
13425 }) {
13426 Ok(i) | Err(i) => i,
13427 };
13428 for range in &ranges[start_ix..] {
13429 if range
13430 .start
13431 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13432 .is_ge()
13433 {
13434 break;
13435 }
13436
13437 let start = range.start.to_display_point(display_snapshot);
13438 let end = range.end.to_display_point(display_snapshot);
13439 results.push((start..end, color))
13440 }
13441 }
13442 results
13443 }
13444
13445 pub fn background_highlight_row_ranges<T: 'static>(
13446 &self,
13447 search_range: Range<Anchor>,
13448 display_snapshot: &DisplaySnapshot,
13449 count: usize,
13450 ) -> Vec<RangeInclusive<DisplayPoint>> {
13451 let mut results = Vec::new();
13452 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13453 return vec![];
13454 };
13455
13456 let start_ix = match ranges.binary_search_by(|probe| {
13457 let cmp = probe
13458 .end
13459 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13460 if cmp.is_gt() {
13461 Ordering::Greater
13462 } else {
13463 Ordering::Less
13464 }
13465 }) {
13466 Ok(i) | Err(i) => i,
13467 };
13468 let mut push_region = |start: Option<Point>, end: Option<Point>| {
13469 if let (Some(start_display), Some(end_display)) = (start, end) {
13470 results.push(
13471 start_display.to_display_point(display_snapshot)
13472 ..=end_display.to_display_point(display_snapshot),
13473 );
13474 }
13475 };
13476 let mut start_row: Option<Point> = None;
13477 let mut end_row: Option<Point> = None;
13478 if ranges.len() > count {
13479 return Vec::new();
13480 }
13481 for range in &ranges[start_ix..] {
13482 if range
13483 .start
13484 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13485 .is_ge()
13486 {
13487 break;
13488 }
13489 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13490 if let Some(current_row) = &end_row {
13491 if end.row == current_row.row {
13492 continue;
13493 }
13494 }
13495 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13496 if start_row.is_none() {
13497 assert_eq!(end_row, None);
13498 start_row = Some(start);
13499 end_row = Some(end);
13500 continue;
13501 }
13502 if let Some(current_end) = end_row.as_mut() {
13503 if start.row > current_end.row + 1 {
13504 push_region(start_row, end_row);
13505 start_row = Some(start);
13506 end_row = Some(end);
13507 } else {
13508 // Merge two hunks.
13509 *current_end = end;
13510 }
13511 } else {
13512 unreachable!();
13513 }
13514 }
13515 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13516 push_region(start_row, end_row);
13517 results
13518 }
13519
13520 pub fn gutter_highlights_in_range(
13521 &self,
13522 search_range: Range<Anchor>,
13523 display_snapshot: &DisplaySnapshot,
13524 cx: &App,
13525 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13526 let mut results = Vec::new();
13527 for (color_fetcher, ranges) in self.gutter_highlights.values() {
13528 let color = color_fetcher(cx);
13529 let start_ix = match ranges.binary_search_by(|probe| {
13530 let cmp = probe
13531 .end
13532 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13533 if cmp.is_gt() {
13534 Ordering::Greater
13535 } else {
13536 Ordering::Less
13537 }
13538 }) {
13539 Ok(i) | Err(i) => i,
13540 };
13541 for range in &ranges[start_ix..] {
13542 if range
13543 .start
13544 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13545 .is_ge()
13546 {
13547 break;
13548 }
13549
13550 let start = range.start.to_display_point(display_snapshot);
13551 let end = range.end.to_display_point(display_snapshot);
13552 results.push((start..end, color))
13553 }
13554 }
13555 results
13556 }
13557
13558 /// Get the text ranges corresponding to the redaction query
13559 pub fn redacted_ranges(
13560 &self,
13561 search_range: Range<Anchor>,
13562 display_snapshot: &DisplaySnapshot,
13563 cx: &App,
13564 ) -> Vec<Range<DisplayPoint>> {
13565 display_snapshot
13566 .buffer_snapshot
13567 .redacted_ranges(search_range, |file| {
13568 if let Some(file) = file {
13569 file.is_private()
13570 && EditorSettings::get(
13571 Some(SettingsLocation {
13572 worktree_id: file.worktree_id(cx),
13573 path: file.path().as_ref(),
13574 }),
13575 cx,
13576 )
13577 .redact_private_values
13578 } else {
13579 false
13580 }
13581 })
13582 .map(|range| {
13583 range.start.to_display_point(display_snapshot)
13584 ..range.end.to_display_point(display_snapshot)
13585 })
13586 .collect()
13587 }
13588
13589 pub fn highlight_text<T: 'static>(
13590 &mut self,
13591 ranges: Vec<Range<Anchor>>,
13592 style: HighlightStyle,
13593 cx: &mut Context<Self>,
13594 ) {
13595 self.display_map.update(cx, |map, _| {
13596 map.highlight_text(TypeId::of::<T>(), ranges, style)
13597 });
13598 cx.notify();
13599 }
13600
13601 pub(crate) fn highlight_inlays<T: 'static>(
13602 &mut self,
13603 highlights: Vec<InlayHighlight>,
13604 style: HighlightStyle,
13605 cx: &mut Context<Self>,
13606 ) {
13607 self.display_map.update(cx, |map, _| {
13608 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13609 });
13610 cx.notify();
13611 }
13612
13613 pub fn text_highlights<'a, T: 'static>(
13614 &'a self,
13615 cx: &'a App,
13616 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13617 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13618 }
13619
13620 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13621 let cleared = self
13622 .display_map
13623 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13624 if cleared {
13625 cx.notify();
13626 }
13627 }
13628
13629 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13630 (self.read_only(cx) || self.blink_manager.read(cx).visible())
13631 && self.focus_handle.is_focused(window)
13632 }
13633
13634 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13635 self.show_cursor_when_unfocused = is_enabled;
13636 cx.notify();
13637 }
13638
13639 pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13640 self.project
13641 .as_ref()
13642 .map(|project| project.read(cx).lsp_store())
13643 }
13644
13645 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13646 cx.notify();
13647 }
13648
13649 fn on_buffer_event(
13650 &mut self,
13651 multibuffer: &Entity<MultiBuffer>,
13652 event: &multi_buffer::Event,
13653 window: &mut Window,
13654 cx: &mut Context<Self>,
13655 ) {
13656 match event {
13657 multi_buffer::Event::Edited {
13658 singleton_buffer_edited,
13659 edited_buffer: buffer_edited,
13660 } => {
13661 self.scrollbar_marker_state.dirty = true;
13662 self.active_indent_guides_state.dirty = true;
13663 self.refresh_active_diagnostics(cx);
13664 self.refresh_code_actions(window, cx);
13665 if self.has_active_inline_completion() {
13666 self.update_visible_inline_completion(window, cx);
13667 }
13668 if let Some(buffer) = buffer_edited {
13669 let buffer_id = buffer.read(cx).remote_id();
13670 if !self.registered_buffers.contains_key(&buffer_id) {
13671 if let Some(lsp_store) = self.lsp_store(cx) {
13672 lsp_store.update(cx, |lsp_store, cx| {
13673 self.registered_buffers.insert(
13674 buffer_id,
13675 lsp_store.register_buffer_with_language_servers(&buffer, cx),
13676 );
13677 })
13678 }
13679 }
13680 }
13681 cx.emit(EditorEvent::BufferEdited);
13682 cx.emit(SearchEvent::MatchesInvalidated);
13683 if *singleton_buffer_edited {
13684 if let Some(project) = &self.project {
13685 let project = project.read(cx);
13686 #[allow(clippy::mutable_key_type)]
13687 let languages_affected = multibuffer
13688 .read(cx)
13689 .all_buffers()
13690 .into_iter()
13691 .filter_map(|buffer| {
13692 let buffer = buffer.read(cx);
13693 let language = buffer.language()?;
13694 if project.is_local()
13695 && project
13696 .language_servers_for_local_buffer(buffer, cx)
13697 .count()
13698 == 0
13699 {
13700 None
13701 } else {
13702 Some(language)
13703 }
13704 })
13705 .cloned()
13706 .collect::<HashSet<_>>();
13707 if !languages_affected.is_empty() {
13708 self.refresh_inlay_hints(
13709 InlayHintRefreshReason::BufferEdited(languages_affected),
13710 cx,
13711 );
13712 }
13713 }
13714 }
13715
13716 let Some(project) = &self.project else { return };
13717 let (telemetry, is_via_ssh) = {
13718 let project = project.read(cx);
13719 let telemetry = project.client().telemetry().clone();
13720 let is_via_ssh = project.is_via_ssh();
13721 (telemetry, is_via_ssh)
13722 };
13723 refresh_linked_ranges(self, window, cx);
13724 telemetry.log_edit_event("editor", is_via_ssh);
13725 }
13726 multi_buffer::Event::ExcerptsAdded {
13727 buffer,
13728 predecessor,
13729 excerpts,
13730 } => {
13731 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13732 let buffer_id = buffer.read(cx).remote_id();
13733 if self.buffer.read(cx).change_set_for(buffer_id).is_none() {
13734 if let Some(project) = &self.project {
13735 get_uncommitted_changes_for_buffer(
13736 project,
13737 [buffer.clone()],
13738 self.buffer.clone(),
13739 cx,
13740 );
13741 }
13742 }
13743 cx.emit(EditorEvent::ExcerptsAdded {
13744 buffer: buffer.clone(),
13745 predecessor: *predecessor,
13746 excerpts: excerpts.clone(),
13747 });
13748 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13749 }
13750 multi_buffer::Event::ExcerptsRemoved { ids } => {
13751 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13752 let buffer = self.buffer.read(cx);
13753 self.registered_buffers
13754 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13755 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13756 }
13757 multi_buffer::Event::ExcerptsEdited { ids } => {
13758 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13759 }
13760 multi_buffer::Event::ExcerptsExpanded { ids } => {
13761 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13762 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13763 }
13764 multi_buffer::Event::Reparsed(buffer_id) => {
13765 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13766
13767 cx.emit(EditorEvent::Reparsed(*buffer_id));
13768 }
13769 multi_buffer::Event::DiffHunksToggled => {
13770 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13771 }
13772 multi_buffer::Event::LanguageChanged(buffer_id) => {
13773 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13774 cx.emit(EditorEvent::Reparsed(*buffer_id));
13775 cx.notify();
13776 }
13777 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13778 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13779 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13780 cx.emit(EditorEvent::TitleChanged)
13781 }
13782 // multi_buffer::Event::DiffBaseChanged => {
13783 // self.scrollbar_marker_state.dirty = true;
13784 // cx.emit(EditorEvent::DiffBaseChanged);
13785 // cx.notify();
13786 // }
13787 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13788 multi_buffer::Event::DiagnosticsUpdated => {
13789 self.refresh_active_diagnostics(cx);
13790 self.scrollbar_marker_state.dirty = true;
13791 cx.notify();
13792 }
13793 _ => {}
13794 };
13795 }
13796
13797 fn on_display_map_changed(
13798 &mut self,
13799 _: Entity<DisplayMap>,
13800 _: &mut Window,
13801 cx: &mut Context<Self>,
13802 ) {
13803 cx.notify();
13804 }
13805
13806 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13807 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13808 self.refresh_inline_completion(true, false, window, cx);
13809 self.refresh_inlay_hints(
13810 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13811 self.selections.newest_anchor().head(),
13812 &self.buffer.read(cx).snapshot(cx),
13813 cx,
13814 )),
13815 cx,
13816 );
13817
13818 let old_cursor_shape = self.cursor_shape;
13819
13820 {
13821 let editor_settings = EditorSettings::get_global(cx);
13822 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13823 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13824 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13825 }
13826
13827 if old_cursor_shape != self.cursor_shape {
13828 cx.emit(EditorEvent::CursorShapeChanged);
13829 }
13830
13831 let project_settings = ProjectSettings::get_global(cx);
13832 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13833
13834 if self.mode == EditorMode::Full {
13835 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13836 if self.git_blame_inline_enabled != inline_blame_enabled {
13837 self.toggle_git_blame_inline_internal(false, window, cx);
13838 }
13839 }
13840
13841 cx.notify();
13842 }
13843
13844 pub fn set_searchable(&mut self, searchable: bool) {
13845 self.searchable = searchable;
13846 }
13847
13848 pub fn searchable(&self) -> bool {
13849 self.searchable
13850 }
13851
13852 fn open_proposed_changes_editor(
13853 &mut self,
13854 _: &OpenProposedChangesEditor,
13855 window: &mut Window,
13856 cx: &mut Context<Self>,
13857 ) {
13858 let Some(workspace) = self.workspace() else {
13859 cx.propagate();
13860 return;
13861 };
13862
13863 let selections = self.selections.all::<usize>(cx);
13864 let multi_buffer = self.buffer.read(cx);
13865 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13866 let mut new_selections_by_buffer = HashMap::default();
13867 for selection in selections {
13868 for (buffer, range, _) in
13869 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13870 {
13871 let mut range = range.to_point(buffer);
13872 range.start.column = 0;
13873 range.end.column = buffer.line_len(range.end.row);
13874 new_selections_by_buffer
13875 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13876 .or_insert(Vec::new())
13877 .push(range)
13878 }
13879 }
13880
13881 let proposed_changes_buffers = new_selections_by_buffer
13882 .into_iter()
13883 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13884 .collect::<Vec<_>>();
13885 let proposed_changes_editor = cx.new(|cx| {
13886 ProposedChangesEditor::new(
13887 "Proposed changes",
13888 proposed_changes_buffers,
13889 self.project.clone(),
13890 window,
13891 cx,
13892 )
13893 });
13894
13895 window.defer(cx, move |window, cx| {
13896 workspace.update(cx, |workspace, cx| {
13897 workspace.active_pane().update(cx, |pane, cx| {
13898 pane.add_item(
13899 Box::new(proposed_changes_editor),
13900 true,
13901 true,
13902 None,
13903 window,
13904 cx,
13905 );
13906 });
13907 });
13908 });
13909 }
13910
13911 pub fn open_excerpts_in_split(
13912 &mut self,
13913 _: &OpenExcerptsSplit,
13914 window: &mut Window,
13915 cx: &mut Context<Self>,
13916 ) {
13917 self.open_excerpts_common(None, true, window, cx)
13918 }
13919
13920 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
13921 self.open_excerpts_common(None, false, window, cx)
13922 }
13923
13924 fn open_excerpts_common(
13925 &mut self,
13926 jump_data: Option<JumpData>,
13927 split: bool,
13928 window: &mut Window,
13929 cx: &mut Context<Self>,
13930 ) {
13931 let Some(workspace) = self.workspace() else {
13932 cx.propagate();
13933 return;
13934 };
13935
13936 if self.buffer.read(cx).is_singleton() {
13937 cx.propagate();
13938 return;
13939 }
13940
13941 let mut new_selections_by_buffer = HashMap::default();
13942 match &jump_data {
13943 Some(JumpData::MultiBufferPoint {
13944 excerpt_id,
13945 position,
13946 anchor,
13947 line_offset_from_top,
13948 }) => {
13949 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13950 if let Some(buffer) = multi_buffer_snapshot
13951 .buffer_id_for_excerpt(*excerpt_id)
13952 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
13953 {
13954 let buffer_snapshot = buffer.read(cx).snapshot();
13955 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
13956 language::ToPoint::to_point(anchor, &buffer_snapshot)
13957 } else {
13958 buffer_snapshot.clip_point(*position, Bias::Left)
13959 };
13960 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
13961 new_selections_by_buffer.insert(
13962 buffer,
13963 (
13964 vec![jump_to_offset..jump_to_offset],
13965 Some(*line_offset_from_top),
13966 ),
13967 );
13968 }
13969 }
13970 Some(JumpData::MultiBufferRow {
13971 row,
13972 line_offset_from_top,
13973 }) => {
13974 let point = MultiBufferPoint::new(row.0, 0);
13975 if let Some((buffer, buffer_point, _)) =
13976 self.buffer.read(cx).point_to_buffer_point(point, cx)
13977 {
13978 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
13979 new_selections_by_buffer
13980 .entry(buffer)
13981 .or_insert((Vec::new(), Some(*line_offset_from_top)))
13982 .0
13983 .push(buffer_offset..buffer_offset)
13984 }
13985 }
13986 None => {
13987 let selections = self.selections.all::<usize>(cx);
13988 let multi_buffer = self.buffer.read(cx);
13989 for selection in selections {
13990 for (buffer, mut range, _) in multi_buffer
13991 .snapshot(cx)
13992 .range_to_buffer_ranges(selection.range())
13993 {
13994 // When editing branch buffers, jump to the corresponding location
13995 // in their base buffer.
13996 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
13997 let buffer = buffer_handle.read(cx);
13998 if let Some(base_buffer) = buffer.base_buffer() {
13999 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14000 buffer_handle = base_buffer;
14001 }
14002
14003 if selection.reversed {
14004 mem::swap(&mut range.start, &mut range.end);
14005 }
14006 new_selections_by_buffer
14007 .entry(buffer_handle)
14008 .or_insert((Vec::new(), None))
14009 .0
14010 .push(range)
14011 }
14012 }
14013 }
14014 }
14015
14016 if new_selections_by_buffer.is_empty() {
14017 return;
14018 }
14019
14020 // We defer the pane interaction because we ourselves are a workspace item
14021 // and activating a new item causes the pane to call a method on us reentrantly,
14022 // which panics if we're on the stack.
14023 window.defer(cx, move |window, cx| {
14024 workspace.update(cx, |workspace, cx| {
14025 let pane = if split {
14026 workspace.adjacent_pane(window, cx)
14027 } else {
14028 workspace.active_pane().clone()
14029 };
14030
14031 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14032 let editor = buffer
14033 .read(cx)
14034 .file()
14035 .is_none()
14036 .then(|| {
14037 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14038 // so `workspace.open_project_item` will never find them, always opening a new editor.
14039 // Instead, we try to activate the existing editor in the pane first.
14040 let (editor, pane_item_index) =
14041 pane.read(cx).items().enumerate().find_map(|(i, item)| {
14042 let editor = item.downcast::<Editor>()?;
14043 let singleton_buffer =
14044 editor.read(cx).buffer().read(cx).as_singleton()?;
14045 if singleton_buffer == buffer {
14046 Some((editor, i))
14047 } else {
14048 None
14049 }
14050 })?;
14051 pane.update(cx, |pane, cx| {
14052 pane.activate_item(pane_item_index, true, true, window, cx)
14053 });
14054 Some(editor)
14055 })
14056 .flatten()
14057 .unwrap_or_else(|| {
14058 workspace.open_project_item::<Self>(
14059 pane.clone(),
14060 buffer,
14061 true,
14062 true,
14063 window,
14064 cx,
14065 )
14066 });
14067
14068 editor.update(cx, |editor, cx| {
14069 let autoscroll = match scroll_offset {
14070 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14071 None => Autoscroll::newest(),
14072 };
14073 let nav_history = editor.nav_history.take();
14074 editor.change_selections(Some(autoscroll), window, cx, |s| {
14075 s.select_ranges(ranges);
14076 });
14077 editor.nav_history = nav_history;
14078 });
14079 }
14080 })
14081 });
14082 }
14083
14084 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14085 let snapshot = self.buffer.read(cx).read(cx);
14086 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14087 Some(
14088 ranges
14089 .iter()
14090 .map(move |range| {
14091 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14092 })
14093 .collect(),
14094 )
14095 }
14096
14097 fn selection_replacement_ranges(
14098 &self,
14099 range: Range<OffsetUtf16>,
14100 cx: &mut App,
14101 ) -> Vec<Range<OffsetUtf16>> {
14102 let selections = self.selections.all::<OffsetUtf16>(cx);
14103 let newest_selection = selections
14104 .iter()
14105 .max_by_key(|selection| selection.id)
14106 .unwrap();
14107 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14108 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14109 let snapshot = self.buffer.read(cx).read(cx);
14110 selections
14111 .into_iter()
14112 .map(|mut selection| {
14113 selection.start.0 =
14114 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14115 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14116 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14117 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14118 })
14119 .collect()
14120 }
14121
14122 fn report_editor_event(
14123 &self,
14124 event_type: &'static str,
14125 file_extension: Option<String>,
14126 cx: &App,
14127 ) {
14128 if cfg!(any(test, feature = "test-support")) {
14129 return;
14130 }
14131
14132 let Some(project) = &self.project else { return };
14133
14134 // If None, we are in a file without an extension
14135 let file = self
14136 .buffer
14137 .read(cx)
14138 .as_singleton()
14139 .and_then(|b| b.read(cx).file());
14140 let file_extension = file_extension.or(file
14141 .as_ref()
14142 .and_then(|file| Path::new(file.file_name(cx)).extension())
14143 .and_then(|e| e.to_str())
14144 .map(|a| a.to_string()));
14145
14146 let vim_mode = cx
14147 .global::<SettingsStore>()
14148 .raw_user_settings()
14149 .get("vim_mode")
14150 == Some(&serde_json::Value::Bool(true));
14151
14152 let edit_predictions_provider = all_language_settings(file, cx).inline_completions.provider;
14153 let copilot_enabled = edit_predictions_provider
14154 == language::language_settings::InlineCompletionProvider::Copilot;
14155 let copilot_enabled_for_language = self
14156 .buffer
14157 .read(cx)
14158 .settings_at(0, cx)
14159 .show_inline_completions;
14160
14161 let project = project.read(cx);
14162 telemetry::event!(
14163 event_type,
14164 file_extension,
14165 vim_mode,
14166 copilot_enabled,
14167 copilot_enabled_for_language,
14168 edit_predictions_provider,
14169 is_via_ssh = project.is_via_ssh(),
14170 );
14171 }
14172
14173 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14174 /// with each line being an array of {text, highlight} objects.
14175 fn copy_highlight_json(
14176 &mut self,
14177 _: &CopyHighlightJson,
14178 window: &mut Window,
14179 cx: &mut Context<Self>,
14180 ) {
14181 #[derive(Serialize)]
14182 struct Chunk<'a> {
14183 text: String,
14184 highlight: Option<&'a str>,
14185 }
14186
14187 let snapshot = self.buffer.read(cx).snapshot(cx);
14188 let range = self
14189 .selected_text_range(false, window, cx)
14190 .and_then(|selection| {
14191 if selection.range.is_empty() {
14192 None
14193 } else {
14194 Some(selection.range)
14195 }
14196 })
14197 .unwrap_or_else(|| 0..snapshot.len());
14198
14199 let chunks = snapshot.chunks(range, true);
14200 let mut lines = Vec::new();
14201 let mut line: VecDeque<Chunk> = VecDeque::new();
14202
14203 let Some(style) = self.style.as_ref() else {
14204 return;
14205 };
14206
14207 for chunk in chunks {
14208 let highlight = chunk
14209 .syntax_highlight_id
14210 .and_then(|id| id.name(&style.syntax));
14211 let mut chunk_lines = chunk.text.split('\n').peekable();
14212 while let Some(text) = chunk_lines.next() {
14213 let mut merged_with_last_token = false;
14214 if let Some(last_token) = line.back_mut() {
14215 if last_token.highlight == highlight {
14216 last_token.text.push_str(text);
14217 merged_with_last_token = true;
14218 }
14219 }
14220
14221 if !merged_with_last_token {
14222 line.push_back(Chunk {
14223 text: text.into(),
14224 highlight,
14225 });
14226 }
14227
14228 if chunk_lines.peek().is_some() {
14229 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14230 line.pop_front();
14231 }
14232 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14233 line.pop_back();
14234 }
14235
14236 lines.push(mem::take(&mut line));
14237 }
14238 }
14239 }
14240
14241 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14242 return;
14243 };
14244 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14245 }
14246
14247 pub fn open_context_menu(
14248 &mut self,
14249 _: &OpenContextMenu,
14250 window: &mut Window,
14251 cx: &mut Context<Self>,
14252 ) {
14253 self.request_autoscroll(Autoscroll::newest(), cx);
14254 let position = self.selections.newest_display(cx).start;
14255 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14256 }
14257
14258 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14259 &self.inlay_hint_cache
14260 }
14261
14262 pub fn replay_insert_event(
14263 &mut self,
14264 text: &str,
14265 relative_utf16_range: Option<Range<isize>>,
14266 window: &mut Window,
14267 cx: &mut Context<Self>,
14268 ) {
14269 if !self.input_enabled {
14270 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14271 return;
14272 }
14273 if let Some(relative_utf16_range) = relative_utf16_range {
14274 let selections = self.selections.all::<OffsetUtf16>(cx);
14275 self.change_selections(None, window, cx, |s| {
14276 let new_ranges = selections.into_iter().map(|range| {
14277 let start = OffsetUtf16(
14278 range
14279 .head()
14280 .0
14281 .saturating_add_signed(relative_utf16_range.start),
14282 );
14283 let end = OffsetUtf16(
14284 range
14285 .head()
14286 .0
14287 .saturating_add_signed(relative_utf16_range.end),
14288 );
14289 start..end
14290 });
14291 s.select_ranges(new_ranges);
14292 });
14293 }
14294
14295 self.handle_input(text, window, cx);
14296 }
14297
14298 pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14299 let Some(provider) = self.semantics_provider.as_ref() else {
14300 return false;
14301 };
14302
14303 let mut supports = false;
14304 self.buffer().read(cx).for_each_buffer(|buffer| {
14305 supports |= provider.supports_inlay_hints(buffer, cx);
14306 });
14307 supports
14308 }
14309 pub fn is_focused(&self, window: &mut Window) -> bool {
14310 self.focus_handle.is_focused(window)
14311 }
14312
14313 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14314 cx.emit(EditorEvent::Focused);
14315
14316 if let Some(descendant) = self
14317 .last_focused_descendant
14318 .take()
14319 .and_then(|descendant| descendant.upgrade())
14320 {
14321 window.focus(&descendant);
14322 } else {
14323 if let Some(blame) = self.blame.as_ref() {
14324 blame.update(cx, GitBlame::focus)
14325 }
14326
14327 self.blink_manager.update(cx, BlinkManager::enable);
14328 self.show_cursor_names(window, cx);
14329 self.buffer.update(cx, |buffer, cx| {
14330 buffer.finalize_last_transaction(cx);
14331 if self.leader_peer_id.is_none() {
14332 buffer.set_active_selections(
14333 &self.selections.disjoint_anchors(),
14334 self.selections.line_mode,
14335 self.cursor_shape,
14336 cx,
14337 );
14338 }
14339 });
14340 }
14341 }
14342
14343 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14344 cx.emit(EditorEvent::FocusedIn)
14345 }
14346
14347 fn handle_focus_out(
14348 &mut self,
14349 event: FocusOutEvent,
14350 _window: &mut Window,
14351 _cx: &mut Context<Self>,
14352 ) {
14353 if event.blurred != self.focus_handle {
14354 self.last_focused_descendant = Some(event.blurred);
14355 }
14356 }
14357
14358 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14359 self.blink_manager.update(cx, BlinkManager::disable);
14360 self.buffer
14361 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14362
14363 if let Some(blame) = self.blame.as_ref() {
14364 blame.update(cx, GitBlame::blur)
14365 }
14366 if !self.hover_state.focused(window, cx) {
14367 hide_hover(self, cx);
14368 }
14369
14370 self.hide_context_menu(window, cx);
14371 cx.emit(EditorEvent::Blurred);
14372 cx.notify();
14373 }
14374
14375 pub fn register_action<A: Action>(
14376 &mut self,
14377 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14378 ) -> Subscription {
14379 let id = self.next_editor_action_id.post_inc();
14380 let listener = Arc::new(listener);
14381 self.editor_actions.borrow_mut().insert(
14382 id,
14383 Box::new(move |window, _| {
14384 let listener = listener.clone();
14385 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14386 let action = action.downcast_ref().unwrap();
14387 if phase == DispatchPhase::Bubble {
14388 listener(action, window, cx)
14389 }
14390 })
14391 }),
14392 );
14393
14394 let editor_actions = self.editor_actions.clone();
14395 Subscription::new(move || {
14396 editor_actions.borrow_mut().remove(&id);
14397 })
14398 }
14399
14400 pub fn file_header_size(&self) -> u32 {
14401 FILE_HEADER_HEIGHT
14402 }
14403
14404 pub fn revert(
14405 &mut self,
14406 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14407 window: &mut Window,
14408 cx: &mut Context<Self>,
14409 ) {
14410 self.buffer().update(cx, |multi_buffer, cx| {
14411 for (buffer_id, changes) in revert_changes {
14412 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14413 buffer.update(cx, |buffer, cx| {
14414 buffer.edit(
14415 changes.into_iter().map(|(range, text)| {
14416 (range, text.to_string().map(Arc::<str>::from))
14417 }),
14418 None,
14419 cx,
14420 );
14421 });
14422 }
14423 }
14424 });
14425 self.change_selections(None, window, cx, |selections| selections.refresh());
14426 }
14427
14428 pub fn to_pixel_point(
14429 &self,
14430 source: multi_buffer::Anchor,
14431 editor_snapshot: &EditorSnapshot,
14432 window: &mut Window,
14433 ) -> Option<gpui::Point<Pixels>> {
14434 let source_point = source.to_display_point(editor_snapshot);
14435 self.display_to_pixel_point(source_point, editor_snapshot, window)
14436 }
14437
14438 pub fn display_to_pixel_point(
14439 &self,
14440 source: DisplayPoint,
14441 editor_snapshot: &EditorSnapshot,
14442 window: &mut Window,
14443 ) -> Option<gpui::Point<Pixels>> {
14444 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14445 let text_layout_details = self.text_layout_details(window);
14446 let scroll_top = text_layout_details
14447 .scroll_anchor
14448 .scroll_position(editor_snapshot)
14449 .y;
14450
14451 if source.row().as_f32() < scroll_top.floor() {
14452 return None;
14453 }
14454 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14455 let source_y = line_height * (source.row().as_f32() - scroll_top);
14456 Some(gpui::Point::new(source_x, source_y))
14457 }
14458
14459 pub fn has_visible_completions_menu(&self) -> bool {
14460 !self.previewing_inline_completion
14461 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14462 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14463 })
14464 }
14465
14466 pub fn register_addon<T: Addon>(&mut self, instance: T) {
14467 self.addons
14468 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14469 }
14470
14471 pub fn unregister_addon<T: Addon>(&mut self) {
14472 self.addons.remove(&std::any::TypeId::of::<T>());
14473 }
14474
14475 pub fn addon<T: Addon>(&self) -> Option<&T> {
14476 let type_id = std::any::TypeId::of::<T>();
14477 self.addons
14478 .get(&type_id)
14479 .and_then(|item| item.to_any().downcast_ref::<T>())
14480 }
14481
14482 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14483 let text_layout_details = self.text_layout_details(window);
14484 let style = &text_layout_details.editor_style;
14485 let font_id = window.text_system().resolve_font(&style.text.font());
14486 let font_size = style.text.font_size.to_pixels(window.rem_size());
14487 let line_height = style.text.line_height_in_pixels(window.rem_size());
14488 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14489
14490 gpui::Size::new(em_width, line_height)
14491 }
14492}
14493
14494fn get_uncommitted_changes_for_buffer(
14495 project: &Entity<Project>,
14496 buffers: impl IntoIterator<Item = Entity<Buffer>>,
14497 buffer: Entity<MultiBuffer>,
14498 cx: &mut App,
14499) {
14500 let mut tasks = Vec::new();
14501 project.update(cx, |project, cx| {
14502 for buffer in buffers {
14503 tasks.push(project.open_uncommitted_changes(buffer.clone(), cx))
14504 }
14505 });
14506 cx.spawn(|mut cx| async move {
14507 let change_sets = futures::future::join_all(tasks).await;
14508 buffer
14509 .update(&mut cx, |buffer, cx| {
14510 for change_set in change_sets.into_iter().flatten() {
14511 buffer.add_change_set(change_set, cx);
14512 }
14513 })
14514 .ok();
14515 })
14516 .detach();
14517}
14518
14519fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14520 let tab_size = tab_size.get() as usize;
14521 let mut width = offset;
14522
14523 for ch in text.chars() {
14524 width += if ch == '\t' {
14525 tab_size - (width % tab_size)
14526 } else {
14527 1
14528 };
14529 }
14530
14531 width - offset
14532}
14533
14534#[cfg(test)]
14535mod tests {
14536 use super::*;
14537
14538 #[test]
14539 fn test_string_size_with_expanded_tabs() {
14540 let nz = |val| NonZeroU32::new(val).unwrap();
14541 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14542 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14543 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14544 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14545 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14546 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14547 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14548 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14549 }
14550}
14551
14552/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14553struct WordBreakingTokenizer<'a> {
14554 input: &'a str,
14555}
14556
14557impl<'a> WordBreakingTokenizer<'a> {
14558 fn new(input: &'a str) -> Self {
14559 Self { input }
14560 }
14561}
14562
14563fn is_char_ideographic(ch: char) -> bool {
14564 use unicode_script::Script::*;
14565 use unicode_script::UnicodeScript;
14566 matches!(ch.script(), Han | Tangut | Yi)
14567}
14568
14569fn is_grapheme_ideographic(text: &str) -> bool {
14570 text.chars().any(is_char_ideographic)
14571}
14572
14573fn is_grapheme_whitespace(text: &str) -> bool {
14574 text.chars().any(|x| x.is_whitespace())
14575}
14576
14577fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14578 text.chars().next().map_or(false, |ch| {
14579 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14580 })
14581}
14582
14583#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14584struct WordBreakToken<'a> {
14585 token: &'a str,
14586 grapheme_len: usize,
14587 is_whitespace: bool,
14588}
14589
14590impl<'a> Iterator for WordBreakingTokenizer<'a> {
14591 /// Yields a span, the count of graphemes in the token, and whether it was
14592 /// whitespace. Note that it also breaks at word boundaries.
14593 type Item = WordBreakToken<'a>;
14594
14595 fn next(&mut self) -> Option<Self::Item> {
14596 use unicode_segmentation::UnicodeSegmentation;
14597 if self.input.is_empty() {
14598 return None;
14599 }
14600
14601 let mut iter = self.input.graphemes(true).peekable();
14602 let mut offset = 0;
14603 let mut graphemes = 0;
14604 if let Some(first_grapheme) = iter.next() {
14605 let is_whitespace = is_grapheme_whitespace(first_grapheme);
14606 offset += first_grapheme.len();
14607 graphemes += 1;
14608 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14609 if let Some(grapheme) = iter.peek().copied() {
14610 if should_stay_with_preceding_ideograph(grapheme) {
14611 offset += grapheme.len();
14612 graphemes += 1;
14613 }
14614 }
14615 } else {
14616 let mut words = self.input[offset..].split_word_bound_indices().peekable();
14617 let mut next_word_bound = words.peek().copied();
14618 if next_word_bound.map_or(false, |(i, _)| i == 0) {
14619 next_word_bound = words.next();
14620 }
14621 while let Some(grapheme) = iter.peek().copied() {
14622 if next_word_bound.map_or(false, |(i, _)| i == offset) {
14623 break;
14624 };
14625 if is_grapheme_whitespace(grapheme) != is_whitespace {
14626 break;
14627 };
14628 offset += grapheme.len();
14629 graphemes += 1;
14630 iter.next();
14631 }
14632 }
14633 let token = &self.input[..offset];
14634 self.input = &self.input[offset..];
14635 if is_whitespace {
14636 Some(WordBreakToken {
14637 token: " ",
14638 grapheme_len: 1,
14639 is_whitespace: true,
14640 })
14641 } else {
14642 Some(WordBreakToken {
14643 token,
14644 grapheme_len: graphemes,
14645 is_whitespace: false,
14646 })
14647 }
14648 } else {
14649 None
14650 }
14651 }
14652}
14653
14654#[test]
14655fn test_word_breaking_tokenizer() {
14656 let tests: &[(&str, &[(&str, usize, bool)])] = &[
14657 ("", &[]),
14658 (" ", &[(" ", 1, true)]),
14659 ("Ʒ", &[("Ʒ", 1, false)]),
14660 ("Ǽ", &[("Ǽ", 1, false)]),
14661 ("⋑", &[("⋑", 1, false)]),
14662 ("⋑⋑", &[("⋑⋑", 2, false)]),
14663 (
14664 "原理,进而",
14665 &[
14666 ("原", 1, false),
14667 ("理,", 2, false),
14668 ("进", 1, false),
14669 ("而", 1, false),
14670 ],
14671 ),
14672 (
14673 "hello world",
14674 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14675 ),
14676 (
14677 "hello, world",
14678 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14679 ),
14680 (
14681 " hello world",
14682 &[
14683 (" ", 1, true),
14684 ("hello", 5, false),
14685 (" ", 1, true),
14686 ("world", 5, false),
14687 ],
14688 ),
14689 (
14690 "这是什么 \n 钢笔",
14691 &[
14692 ("这", 1, false),
14693 ("是", 1, false),
14694 ("什", 1, false),
14695 ("么", 1, false),
14696 (" ", 1, true),
14697 ("钢", 1, false),
14698 ("笔", 1, false),
14699 ],
14700 ),
14701 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14702 ];
14703
14704 for (input, result) in tests {
14705 assert_eq!(
14706 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14707 result
14708 .iter()
14709 .copied()
14710 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14711 token,
14712 grapheme_len,
14713 is_whitespace,
14714 })
14715 .collect::<Vec<_>>()
14716 );
14717 }
14718}
14719
14720fn wrap_with_prefix(
14721 line_prefix: String,
14722 unwrapped_text: String,
14723 wrap_column: usize,
14724 tab_size: NonZeroU32,
14725) -> String {
14726 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14727 let mut wrapped_text = String::new();
14728 let mut current_line = line_prefix.clone();
14729
14730 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14731 let mut current_line_len = line_prefix_len;
14732 for WordBreakToken {
14733 token,
14734 grapheme_len,
14735 is_whitespace,
14736 } in tokenizer
14737 {
14738 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14739 wrapped_text.push_str(current_line.trim_end());
14740 wrapped_text.push('\n');
14741 current_line.truncate(line_prefix.len());
14742 current_line_len = line_prefix_len;
14743 if !is_whitespace {
14744 current_line.push_str(token);
14745 current_line_len += grapheme_len;
14746 }
14747 } else if !is_whitespace {
14748 current_line.push_str(token);
14749 current_line_len += grapheme_len;
14750 } else if current_line_len != line_prefix_len {
14751 current_line.push(' ');
14752 current_line_len += 1;
14753 }
14754 }
14755
14756 if !current_line.is_empty() {
14757 wrapped_text.push_str(¤t_line);
14758 }
14759 wrapped_text
14760}
14761
14762#[test]
14763fn test_wrap_with_prefix() {
14764 assert_eq!(
14765 wrap_with_prefix(
14766 "# ".to_string(),
14767 "abcdefg".to_string(),
14768 4,
14769 NonZeroU32::new(4).unwrap()
14770 ),
14771 "# abcdefg"
14772 );
14773 assert_eq!(
14774 wrap_with_prefix(
14775 "".to_string(),
14776 "\thello world".to_string(),
14777 8,
14778 NonZeroU32::new(4).unwrap()
14779 ),
14780 "hello\nworld"
14781 );
14782 assert_eq!(
14783 wrap_with_prefix(
14784 "// ".to_string(),
14785 "xx \nyy zz aa bb cc".to_string(),
14786 12,
14787 NonZeroU32::new(4).unwrap()
14788 ),
14789 "// xx yy zz\n// aa bb cc"
14790 );
14791 assert_eq!(
14792 wrap_with_prefix(
14793 String::new(),
14794 "这是什么 \n 钢笔".to_string(),
14795 3,
14796 NonZeroU32::new(4).unwrap()
14797 ),
14798 "这是什\n么 钢\n笔"
14799 );
14800}
14801
14802pub trait CollaborationHub {
14803 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14804 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14805 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14806}
14807
14808impl CollaborationHub for Entity<Project> {
14809 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14810 self.read(cx).collaborators()
14811 }
14812
14813 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14814 self.read(cx).user_store().read(cx).participant_indices()
14815 }
14816
14817 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14818 let this = self.read(cx);
14819 let user_ids = this.collaborators().values().map(|c| c.user_id);
14820 this.user_store().read_with(cx, |user_store, cx| {
14821 user_store.participant_names(user_ids, cx)
14822 })
14823 }
14824}
14825
14826pub trait SemanticsProvider {
14827 fn hover(
14828 &self,
14829 buffer: &Entity<Buffer>,
14830 position: text::Anchor,
14831 cx: &mut App,
14832 ) -> Option<Task<Vec<project::Hover>>>;
14833
14834 fn inlay_hints(
14835 &self,
14836 buffer_handle: Entity<Buffer>,
14837 range: Range<text::Anchor>,
14838 cx: &mut App,
14839 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14840
14841 fn resolve_inlay_hint(
14842 &self,
14843 hint: InlayHint,
14844 buffer_handle: Entity<Buffer>,
14845 server_id: LanguageServerId,
14846 cx: &mut App,
14847 ) -> Option<Task<anyhow::Result<InlayHint>>>;
14848
14849 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
14850
14851 fn document_highlights(
14852 &self,
14853 buffer: &Entity<Buffer>,
14854 position: text::Anchor,
14855 cx: &mut App,
14856 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14857
14858 fn definitions(
14859 &self,
14860 buffer: &Entity<Buffer>,
14861 position: text::Anchor,
14862 kind: GotoDefinitionKind,
14863 cx: &mut App,
14864 ) -> Option<Task<Result<Vec<LocationLink>>>>;
14865
14866 fn range_for_rename(
14867 &self,
14868 buffer: &Entity<Buffer>,
14869 position: text::Anchor,
14870 cx: &mut App,
14871 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14872
14873 fn perform_rename(
14874 &self,
14875 buffer: &Entity<Buffer>,
14876 position: text::Anchor,
14877 new_name: String,
14878 cx: &mut App,
14879 ) -> Option<Task<Result<ProjectTransaction>>>;
14880}
14881
14882pub trait CompletionProvider {
14883 fn completions(
14884 &self,
14885 buffer: &Entity<Buffer>,
14886 buffer_position: text::Anchor,
14887 trigger: CompletionContext,
14888 window: &mut Window,
14889 cx: &mut Context<Editor>,
14890 ) -> Task<Result<Vec<Completion>>>;
14891
14892 fn resolve_completions(
14893 &self,
14894 buffer: Entity<Buffer>,
14895 completion_indices: Vec<usize>,
14896 completions: Rc<RefCell<Box<[Completion]>>>,
14897 cx: &mut Context<Editor>,
14898 ) -> Task<Result<bool>>;
14899
14900 fn apply_additional_edits_for_completion(
14901 &self,
14902 _buffer: Entity<Buffer>,
14903 _completions: Rc<RefCell<Box<[Completion]>>>,
14904 _completion_index: usize,
14905 _push_to_history: bool,
14906 _cx: &mut Context<Editor>,
14907 ) -> Task<Result<Option<language::Transaction>>> {
14908 Task::ready(Ok(None))
14909 }
14910
14911 fn is_completion_trigger(
14912 &self,
14913 buffer: &Entity<Buffer>,
14914 position: language::Anchor,
14915 text: &str,
14916 trigger_in_words: bool,
14917 cx: &mut Context<Editor>,
14918 ) -> bool;
14919
14920 fn sort_completions(&self) -> bool {
14921 true
14922 }
14923}
14924
14925pub trait CodeActionProvider {
14926 fn id(&self) -> Arc<str>;
14927
14928 fn code_actions(
14929 &self,
14930 buffer: &Entity<Buffer>,
14931 range: Range<text::Anchor>,
14932 window: &mut Window,
14933 cx: &mut App,
14934 ) -> Task<Result<Vec<CodeAction>>>;
14935
14936 fn apply_code_action(
14937 &self,
14938 buffer_handle: Entity<Buffer>,
14939 action: CodeAction,
14940 excerpt_id: ExcerptId,
14941 push_to_history: bool,
14942 window: &mut Window,
14943 cx: &mut App,
14944 ) -> Task<Result<ProjectTransaction>>;
14945}
14946
14947impl CodeActionProvider for Entity<Project> {
14948 fn id(&self) -> Arc<str> {
14949 "project".into()
14950 }
14951
14952 fn code_actions(
14953 &self,
14954 buffer: &Entity<Buffer>,
14955 range: Range<text::Anchor>,
14956 _window: &mut Window,
14957 cx: &mut App,
14958 ) -> Task<Result<Vec<CodeAction>>> {
14959 self.update(cx, |project, cx| {
14960 project.code_actions(buffer, range, None, cx)
14961 })
14962 }
14963
14964 fn apply_code_action(
14965 &self,
14966 buffer_handle: Entity<Buffer>,
14967 action: CodeAction,
14968 _excerpt_id: ExcerptId,
14969 push_to_history: bool,
14970 _window: &mut Window,
14971 cx: &mut App,
14972 ) -> Task<Result<ProjectTransaction>> {
14973 self.update(cx, |project, cx| {
14974 project.apply_code_action(buffer_handle, action, push_to_history, cx)
14975 })
14976 }
14977}
14978
14979fn snippet_completions(
14980 project: &Project,
14981 buffer: &Entity<Buffer>,
14982 buffer_position: text::Anchor,
14983 cx: &mut App,
14984) -> Task<Result<Vec<Completion>>> {
14985 let language = buffer.read(cx).language_at(buffer_position);
14986 let language_name = language.as_ref().map(|language| language.lsp_id());
14987 let snippet_store = project.snippets().read(cx);
14988 let snippets = snippet_store.snippets_for(language_name, cx);
14989
14990 if snippets.is_empty() {
14991 return Task::ready(Ok(vec![]));
14992 }
14993 let snapshot = buffer.read(cx).text_snapshot();
14994 let chars: String = snapshot
14995 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
14996 .collect();
14997
14998 let scope = language.map(|language| language.default_scope());
14999 let executor = cx.background_executor().clone();
15000
15001 cx.background_executor().spawn(async move {
15002 let classifier = CharClassifier::new(scope).for_completion(true);
15003 let mut last_word = chars
15004 .chars()
15005 .take_while(|c| classifier.is_word(*c))
15006 .collect::<String>();
15007 last_word = last_word.chars().rev().collect();
15008
15009 if last_word.is_empty() {
15010 return Ok(vec![]);
15011 }
15012
15013 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15014 let to_lsp = |point: &text::Anchor| {
15015 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15016 point_to_lsp(end)
15017 };
15018 let lsp_end = to_lsp(&buffer_position);
15019
15020 let candidates = snippets
15021 .iter()
15022 .enumerate()
15023 .flat_map(|(ix, snippet)| {
15024 snippet
15025 .prefix
15026 .iter()
15027 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15028 })
15029 .collect::<Vec<StringMatchCandidate>>();
15030
15031 let mut matches = fuzzy::match_strings(
15032 &candidates,
15033 &last_word,
15034 last_word.chars().any(|c| c.is_uppercase()),
15035 100,
15036 &Default::default(),
15037 executor,
15038 )
15039 .await;
15040
15041 // Remove all candidates where the query's start does not match the start of any word in the candidate
15042 if let Some(query_start) = last_word.chars().next() {
15043 matches.retain(|string_match| {
15044 split_words(&string_match.string).any(|word| {
15045 // Check that the first codepoint of the word as lowercase matches the first
15046 // codepoint of the query as lowercase
15047 word.chars()
15048 .flat_map(|codepoint| codepoint.to_lowercase())
15049 .zip(query_start.to_lowercase())
15050 .all(|(word_cp, query_cp)| word_cp == query_cp)
15051 })
15052 });
15053 }
15054
15055 let matched_strings = matches
15056 .into_iter()
15057 .map(|m| m.string)
15058 .collect::<HashSet<_>>();
15059
15060 let result: Vec<Completion> = snippets
15061 .into_iter()
15062 .filter_map(|snippet| {
15063 let matching_prefix = snippet
15064 .prefix
15065 .iter()
15066 .find(|prefix| matched_strings.contains(*prefix))?;
15067 let start = as_offset - last_word.len();
15068 let start = snapshot.anchor_before(start);
15069 let range = start..buffer_position;
15070 let lsp_start = to_lsp(&start);
15071 let lsp_range = lsp::Range {
15072 start: lsp_start,
15073 end: lsp_end,
15074 };
15075 Some(Completion {
15076 old_range: range,
15077 new_text: snippet.body.clone(),
15078 resolved: false,
15079 label: CodeLabel {
15080 text: matching_prefix.clone(),
15081 runs: vec![],
15082 filter_range: 0..matching_prefix.len(),
15083 },
15084 server_id: LanguageServerId(usize::MAX),
15085 documentation: snippet
15086 .description
15087 .clone()
15088 .map(CompletionDocumentation::SingleLine),
15089 lsp_completion: lsp::CompletionItem {
15090 label: snippet.prefix.first().unwrap().clone(),
15091 kind: Some(CompletionItemKind::SNIPPET),
15092 label_details: snippet.description.as_ref().map(|description| {
15093 lsp::CompletionItemLabelDetails {
15094 detail: Some(description.clone()),
15095 description: None,
15096 }
15097 }),
15098 insert_text_format: Some(InsertTextFormat::SNIPPET),
15099 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15100 lsp::InsertReplaceEdit {
15101 new_text: snippet.body.clone(),
15102 insert: lsp_range,
15103 replace: lsp_range,
15104 },
15105 )),
15106 filter_text: Some(snippet.body.clone()),
15107 sort_text: Some(char::MAX.to_string()),
15108 ..Default::default()
15109 },
15110 confirm: None,
15111 })
15112 })
15113 .collect();
15114
15115 Ok(result)
15116 })
15117}
15118
15119impl CompletionProvider for Entity<Project> {
15120 fn completions(
15121 &self,
15122 buffer: &Entity<Buffer>,
15123 buffer_position: text::Anchor,
15124 options: CompletionContext,
15125 _window: &mut Window,
15126 cx: &mut Context<Editor>,
15127 ) -> Task<Result<Vec<Completion>>> {
15128 self.update(cx, |project, cx| {
15129 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15130 let project_completions = project.completions(buffer, buffer_position, options, cx);
15131 cx.background_executor().spawn(async move {
15132 let mut completions = project_completions.await?;
15133 let snippets_completions = snippets.await?;
15134 completions.extend(snippets_completions);
15135 Ok(completions)
15136 })
15137 })
15138 }
15139
15140 fn resolve_completions(
15141 &self,
15142 buffer: Entity<Buffer>,
15143 completion_indices: Vec<usize>,
15144 completions: Rc<RefCell<Box<[Completion]>>>,
15145 cx: &mut Context<Editor>,
15146 ) -> Task<Result<bool>> {
15147 self.update(cx, |project, cx| {
15148 project.lsp_store().update(cx, |lsp_store, cx| {
15149 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15150 })
15151 })
15152 }
15153
15154 fn apply_additional_edits_for_completion(
15155 &self,
15156 buffer: Entity<Buffer>,
15157 completions: Rc<RefCell<Box<[Completion]>>>,
15158 completion_index: usize,
15159 push_to_history: bool,
15160 cx: &mut Context<Editor>,
15161 ) -> Task<Result<Option<language::Transaction>>> {
15162 self.update(cx, |project, cx| {
15163 project.lsp_store().update(cx, |lsp_store, cx| {
15164 lsp_store.apply_additional_edits_for_completion(
15165 buffer,
15166 completions,
15167 completion_index,
15168 push_to_history,
15169 cx,
15170 )
15171 })
15172 })
15173 }
15174
15175 fn is_completion_trigger(
15176 &self,
15177 buffer: &Entity<Buffer>,
15178 position: language::Anchor,
15179 text: &str,
15180 trigger_in_words: bool,
15181 cx: &mut Context<Editor>,
15182 ) -> bool {
15183 let mut chars = text.chars();
15184 let char = if let Some(char) = chars.next() {
15185 char
15186 } else {
15187 return false;
15188 };
15189 if chars.next().is_some() {
15190 return false;
15191 }
15192
15193 let buffer = buffer.read(cx);
15194 let snapshot = buffer.snapshot();
15195 if !snapshot.settings_at(position, cx).show_completions_on_input {
15196 return false;
15197 }
15198 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15199 if trigger_in_words && classifier.is_word(char) {
15200 return true;
15201 }
15202
15203 buffer.completion_triggers().contains(text)
15204 }
15205}
15206
15207impl SemanticsProvider for Entity<Project> {
15208 fn hover(
15209 &self,
15210 buffer: &Entity<Buffer>,
15211 position: text::Anchor,
15212 cx: &mut App,
15213 ) -> Option<Task<Vec<project::Hover>>> {
15214 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15215 }
15216
15217 fn document_highlights(
15218 &self,
15219 buffer: &Entity<Buffer>,
15220 position: text::Anchor,
15221 cx: &mut App,
15222 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15223 Some(self.update(cx, |project, cx| {
15224 project.document_highlights(buffer, position, cx)
15225 }))
15226 }
15227
15228 fn definitions(
15229 &self,
15230 buffer: &Entity<Buffer>,
15231 position: text::Anchor,
15232 kind: GotoDefinitionKind,
15233 cx: &mut App,
15234 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15235 Some(self.update(cx, |project, cx| match kind {
15236 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15237 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15238 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15239 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15240 }))
15241 }
15242
15243 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15244 // TODO: make this work for remote projects
15245 self.read(cx)
15246 .language_servers_for_local_buffer(buffer.read(cx), cx)
15247 .any(
15248 |(_, server)| match server.capabilities().inlay_hint_provider {
15249 Some(lsp::OneOf::Left(enabled)) => enabled,
15250 Some(lsp::OneOf::Right(_)) => true,
15251 None => false,
15252 },
15253 )
15254 }
15255
15256 fn inlay_hints(
15257 &self,
15258 buffer_handle: Entity<Buffer>,
15259 range: Range<text::Anchor>,
15260 cx: &mut App,
15261 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15262 Some(self.update(cx, |project, cx| {
15263 project.inlay_hints(buffer_handle, range, cx)
15264 }))
15265 }
15266
15267 fn resolve_inlay_hint(
15268 &self,
15269 hint: InlayHint,
15270 buffer_handle: Entity<Buffer>,
15271 server_id: LanguageServerId,
15272 cx: &mut App,
15273 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15274 Some(self.update(cx, |project, cx| {
15275 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15276 }))
15277 }
15278
15279 fn range_for_rename(
15280 &self,
15281 buffer: &Entity<Buffer>,
15282 position: text::Anchor,
15283 cx: &mut App,
15284 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15285 Some(self.update(cx, |project, cx| {
15286 let buffer = buffer.clone();
15287 let task = project.prepare_rename(buffer.clone(), position, cx);
15288 cx.spawn(|_, mut cx| async move {
15289 Ok(match task.await? {
15290 PrepareRenameResponse::Success(range) => Some(range),
15291 PrepareRenameResponse::InvalidPosition => None,
15292 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15293 // Fallback on using TreeSitter info to determine identifier range
15294 buffer.update(&mut cx, |buffer, _| {
15295 let snapshot = buffer.snapshot();
15296 let (range, kind) = snapshot.surrounding_word(position);
15297 if kind != Some(CharKind::Word) {
15298 return None;
15299 }
15300 Some(
15301 snapshot.anchor_before(range.start)
15302 ..snapshot.anchor_after(range.end),
15303 )
15304 })?
15305 }
15306 })
15307 })
15308 }))
15309 }
15310
15311 fn perform_rename(
15312 &self,
15313 buffer: &Entity<Buffer>,
15314 position: text::Anchor,
15315 new_name: String,
15316 cx: &mut App,
15317 ) -> Option<Task<Result<ProjectTransaction>>> {
15318 Some(self.update(cx, |project, cx| {
15319 project.perform_rename(buffer.clone(), position, new_name, cx)
15320 }))
15321 }
15322}
15323
15324fn inlay_hint_settings(
15325 location: Anchor,
15326 snapshot: &MultiBufferSnapshot,
15327 cx: &mut Context<Editor>,
15328) -> InlayHintSettings {
15329 let file = snapshot.file_at(location);
15330 let language = snapshot.language_at(location).map(|l| l.name());
15331 language_settings(language, file, cx).inlay_hints
15332}
15333
15334fn consume_contiguous_rows(
15335 contiguous_row_selections: &mut Vec<Selection<Point>>,
15336 selection: &Selection<Point>,
15337 display_map: &DisplaySnapshot,
15338 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15339) -> (MultiBufferRow, MultiBufferRow) {
15340 contiguous_row_selections.push(selection.clone());
15341 let start_row = MultiBufferRow(selection.start.row);
15342 let mut end_row = ending_row(selection, display_map);
15343
15344 while let Some(next_selection) = selections.peek() {
15345 if next_selection.start.row <= end_row.0 {
15346 end_row = ending_row(next_selection, display_map);
15347 contiguous_row_selections.push(selections.next().unwrap().clone());
15348 } else {
15349 break;
15350 }
15351 }
15352 (start_row, end_row)
15353}
15354
15355fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15356 if next_selection.end.column > 0 || next_selection.is_empty() {
15357 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15358 } else {
15359 MultiBufferRow(next_selection.end.row)
15360 }
15361}
15362
15363impl EditorSnapshot {
15364 pub fn remote_selections_in_range<'a>(
15365 &'a self,
15366 range: &'a Range<Anchor>,
15367 collaboration_hub: &dyn CollaborationHub,
15368 cx: &'a App,
15369 ) -> impl 'a + Iterator<Item = RemoteSelection> {
15370 let participant_names = collaboration_hub.user_names(cx);
15371 let participant_indices = collaboration_hub.user_participant_indices(cx);
15372 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15373 let collaborators_by_replica_id = collaborators_by_peer_id
15374 .iter()
15375 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15376 .collect::<HashMap<_, _>>();
15377 self.buffer_snapshot
15378 .selections_in_range(range, false)
15379 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15380 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15381 let participant_index = participant_indices.get(&collaborator.user_id).copied();
15382 let user_name = participant_names.get(&collaborator.user_id).cloned();
15383 Some(RemoteSelection {
15384 replica_id,
15385 selection,
15386 cursor_shape,
15387 line_mode,
15388 participant_index,
15389 peer_id: collaborator.peer_id,
15390 user_name,
15391 })
15392 })
15393 }
15394
15395 pub fn hunks_for_ranges(
15396 &self,
15397 ranges: impl Iterator<Item = Range<Point>>,
15398 ) -> Vec<MultiBufferDiffHunk> {
15399 let mut hunks = Vec::new();
15400 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15401 HashMap::default();
15402 for query_range in ranges {
15403 let query_rows =
15404 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15405 for hunk in self.buffer_snapshot.diff_hunks_in_range(
15406 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15407 ) {
15408 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15409 // when the caret is just above or just below the deleted hunk.
15410 let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15411 let related_to_selection = if allow_adjacent {
15412 hunk.row_range.overlaps(&query_rows)
15413 || hunk.row_range.start == query_rows.end
15414 || hunk.row_range.end == query_rows.start
15415 } else {
15416 hunk.row_range.overlaps(&query_rows)
15417 };
15418 if related_to_selection {
15419 if !processed_buffer_rows
15420 .entry(hunk.buffer_id)
15421 .or_default()
15422 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15423 {
15424 continue;
15425 }
15426 hunks.push(hunk);
15427 }
15428 }
15429 }
15430
15431 hunks
15432 }
15433
15434 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15435 self.display_snapshot.buffer_snapshot.language_at(position)
15436 }
15437
15438 pub fn is_focused(&self) -> bool {
15439 self.is_focused
15440 }
15441
15442 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15443 self.placeholder_text.as_ref()
15444 }
15445
15446 pub fn scroll_position(&self) -> gpui::Point<f32> {
15447 self.scroll_anchor.scroll_position(&self.display_snapshot)
15448 }
15449
15450 fn gutter_dimensions(
15451 &self,
15452 font_id: FontId,
15453 font_size: Pixels,
15454 max_line_number_width: Pixels,
15455 cx: &App,
15456 ) -> Option<GutterDimensions> {
15457 if !self.show_gutter {
15458 return None;
15459 }
15460
15461 let descent = cx.text_system().descent(font_id, font_size);
15462 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15463 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15464
15465 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15466 matches!(
15467 ProjectSettings::get_global(cx).git.git_gutter,
15468 Some(GitGutterSetting::TrackedFiles)
15469 )
15470 });
15471 let gutter_settings = EditorSettings::get_global(cx).gutter;
15472 let show_line_numbers = self
15473 .show_line_numbers
15474 .unwrap_or(gutter_settings.line_numbers);
15475 let line_gutter_width = if show_line_numbers {
15476 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15477 let min_width_for_number_on_gutter = em_advance * 4.0;
15478 max_line_number_width.max(min_width_for_number_on_gutter)
15479 } else {
15480 0.0.into()
15481 };
15482
15483 let show_code_actions = self
15484 .show_code_actions
15485 .unwrap_or(gutter_settings.code_actions);
15486
15487 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15488
15489 let git_blame_entries_width =
15490 self.git_blame_gutter_max_author_length
15491 .map(|max_author_length| {
15492 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15493
15494 /// The number of characters to dedicate to gaps and margins.
15495 const SPACING_WIDTH: usize = 4;
15496
15497 let max_char_count = max_author_length
15498 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15499 + ::git::SHORT_SHA_LENGTH
15500 + MAX_RELATIVE_TIMESTAMP.len()
15501 + SPACING_WIDTH;
15502
15503 em_advance * max_char_count
15504 });
15505
15506 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15507 left_padding += if show_code_actions || show_runnables {
15508 em_width * 3.0
15509 } else if show_git_gutter && show_line_numbers {
15510 em_width * 2.0
15511 } else if show_git_gutter || show_line_numbers {
15512 em_width
15513 } else {
15514 px(0.)
15515 };
15516
15517 let right_padding = if gutter_settings.folds && show_line_numbers {
15518 em_width * 4.0
15519 } else if gutter_settings.folds {
15520 em_width * 3.0
15521 } else if show_line_numbers {
15522 em_width
15523 } else {
15524 px(0.)
15525 };
15526
15527 Some(GutterDimensions {
15528 left_padding,
15529 right_padding,
15530 width: line_gutter_width + left_padding + right_padding,
15531 margin: -descent,
15532 git_blame_entries_width,
15533 })
15534 }
15535
15536 pub fn render_crease_toggle(
15537 &self,
15538 buffer_row: MultiBufferRow,
15539 row_contains_cursor: bool,
15540 editor: Entity<Editor>,
15541 window: &mut Window,
15542 cx: &mut App,
15543 ) -> Option<AnyElement> {
15544 let folded = self.is_line_folded(buffer_row);
15545 let mut is_foldable = false;
15546
15547 if let Some(crease) = self
15548 .crease_snapshot
15549 .query_row(buffer_row, &self.buffer_snapshot)
15550 {
15551 is_foldable = true;
15552 match crease {
15553 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15554 if let Some(render_toggle) = render_toggle {
15555 let toggle_callback =
15556 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15557 if folded {
15558 editor.update(cx, |editor, cx| {
15559 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15560 });
15561 } else {
15562 editor.update(cx, |editor, cx| {
15563 editor.unfold_at(
15564 &crate::UnfoldAt { buffer_row },
15565 window,
15566 cx,
15567 )
15568 });
15569 }
15570 });
15571 return Some((render_toggle)(
15572 buffer_row,
15573 folded,
15574 toggle_callback,
15575 window,
15576 cx,
15577 ));
15578 }
15579 }
15580 }
15581 }
15582
15583 is_foldable |= self.starts_indent(buffer_row);
15584
15585 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15586 Some(
15587 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15588 .toggle_state(folded)
15589 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15590 if folded {
15591 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15592 } else {
15593 this.fold_at(&FoldAt { buffer_row }, window, cx);
15594 }
15595 }))
15596 .into_any_element(),
15597 )
15598 } else {
15599 None
15600 }
15601 }
15602
15603 pub fn render_crease_trailer(
15604 &self,
15605 buffer_row: MultiBufferRow,
15606 window: &mut Window,
15607 cx: &mut App,
15608 ) -> Option<AnyElement> {
15609 let folded = self.is_line_folded(buffer_row);
15610 if let Crease::Inline { render_trailer, .. } = self
15611 .crease_snapshot
15612 .query_row(buffer_row, &self.buffer_snapshot)?
15613 {
15614 let render_trailer = render_trailer.as_ref()?;
15615 Some(render_trailer(buffer_row, folded, window, cx))
15616 } else {
15617 None
15618 }
15619 }
15620}
15621
15622impl Deref for EditorSnapshot {
15623 type Target = DisplaySnapshot;
15624
15625 fn deref(&self) -> &Self::Target {
15626 &self.display_snapshot
15627 }
15628}
15629
15630#[derive(Clone, Debug, PartialEq, Eq)]
15631pub enum EditorEvent {
15632 InputIgnored {
15633 text: Arc<str>,
15634 },
15635 InputHandled {
15636 utf16_range_to_replace: Option<Range<isize>>,
15637 text: Arc<str>,
15638 },
15639 ExcerptsAdded {
15640 buffer: Entity<Buffer>,
15641 predecessor: ExcerptId,
15642 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15643 },
15644 ExcerptsRemoved {
15645 ids: Vec<ExcerptId>,
15646 },
15647 BufferFoldToggled {
15648 ids: Vec<ExcerptId>,
15649 folded: bool,
15650 },
15651 ExcerptsEdited {
15652 ids: Vec<ExcerptId>,
15653 },
15654 ExcerptsExpanded {
15655 ids: Vec<ExcerptId>,
15656 },
15657 BufferEdited,
15658 Edited {
15659 transaction_id: clock::Lamport,
15660 },
15661 Reparsed(BufferId),
15662 Focused,
15663 FocusedIn,
15664 Blurred,
15665 DirtyChanged,
15666 Saved,
15667 TitleChanged,
15668 DiffBaseChanged,
15669 SelectionsChanged {
15670 local: bool,
15671 },
15672 ScrollPositionChanged {
15673 local: bool,
15674 autoscroll: bool,
15675 },
15676 Closed,
15677 TransactionUndone {
15678 transaction_id: clock::Lamport,
15679 },
15680 TransactionBegun {
15681 transaction_id: clock::Lamport,
15682 },
15683 Reloaded,
15684 CursorShapeChanged,
15685}
15686
15687impl EventEmitter<EditorEvent> for Editor {}
15688
15689impl Focusable for Editor {
15690 fn focus_handle(&self, _cx: &App) -> FocusHandle {
15691 self.focus_handle.clone()
15692 }
15693}
15694
15695impl Render for Editor {
15696 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15697 let settings = ThemeSettings::get_global(cx);
15698
15699 let mut text_style = match self.mode {
15700 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15701 color: cx.theme().colors().editor_foreground,
15702 font_family: settings.ui_font.family.clone(),
15703 font_features: settings.ui_font.features.clone(),
15704 font_fallbacks: settings.ui_font.fallbacks.clone(),
15705 font_size: rems(0.875).into(),
15706 font_weight: settings.ui_font.weight,
15707 line_height: relative(settings.buffer_line_height.value()),
15708 ..Default::default()
15709 },
15710 EditorMode::Full => TextStyle {
15711 color: cx.theme().colors().editor_foreground,
15712 font_family: settings.buffer_font.family.clone(),
15713 font_features: settings.buffer_font.features.clone(),
15714 font_fallbacks: settings.buffer_font.fallbacks.clone(),
15715 font_size: settings.buffer_font_size().into(),
15716 font_weight: settings.buffer_font.weight,
15717 line_height: relative(settings.buffer_line_height.value()),
15718 ..Default::default()
15719 },
15720 };
15721 if let Some(text_style_refinement) = &self.text_style_refinement {
15722 text_style.refine(text_style_refinement)
15723 }
15724
15725 let background = match self.mode {
15726 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15727 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15728 EditorMode::Full => cx.theme().colors().editor_background,
15729 };
15730
15731 EditorElement::new(
15732 &cx.entity(),
15733 EditorStyle {
15734 background,
15735 local_player: cx.theme().players().local(),
15736 text: text_style,
15737 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15738 syntax: cx.theme().syntax().clone(),
15739 status: cx.theme().status().clone(),
15740 inlay_hints_style: make_inlay_hints_style(cx),
15741 inline_completion_styles: make_suggestion_styles(cx),
15742 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15743 },
15744 )
15745 }
15746}
15747
15748impl EntityInputHandler for Editor {
15749 fn text_for_range(
15750 &mut self,
15751 range_utf16: Range<usize>,
15752 adjusted_range: &mut Option<Range<usize>>,
15753 _: &mut Window,
15754 cx: &mut Context<Self>,
15755 ) -> Option<String> {
15756 let snapshot = self.buffer.read(cx).read(cx);
15757 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15758 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15759 if (start.0..end.0) != range_utf16 {
15760 adjusted_range.replace(start.0..end.0);
15761 }
15762 Some(snapshot.text_for_range(start..end).collect())
15763 }
15764
15765 fn selected_text_range(
15766 &mut self,
15767 ignore_disabled_input: bool,
15768 _: &mut Window,
15769 cx: &mut Context<Self>,
15770 ) -> Option<UTF16Selection> {
15771 // Prevent the IME menu from appearing when holding down an alphabetic key
15772 // while input is disabled.
15773 if !ignore_disabled_input && !self.input_enabled {
15774 return None;
15775 }
15776
15777 let selection = self.selections.newest::<OffsetUtf16>(cx);
15778 let range = selection.range();
15779
15780 Some(UTF16Selection {
15781 range: range.start.0..range.end.0,
15782 reversed: selection.reversed,
15783 })
15784 }
15785
15786 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15787 let snapshot = self.buffer.read(cx).read(cx);
15788 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15789 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15790 }
15791
15792 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15793 self.clear_highlights::<InputComposition>(cx);
15794 self.ime_transaction.take();
15795 }
15796
15797 fn replace_text_in_range(
15798 &mut self,
15799 range_utf16: Option<Range<usize>>,
15800 text: &str,
15801 window: &mut Window,
15802 cx: &mut Context<Self>,
15803 ) {
15804 if !self.input_enabled {
15805 cx.emit(EditorEvent::InputIgnored { text: text.into() });
15806 return;
15807 }
15808
15809 self.transact(window, cx, |this, window, cx| {
15810 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15811 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15812 Some(this.selection_replacement_ranges(range_utf16, cx))
15813 } else {
15814 this.marked_text_ranges(cx)
15815 };
15816
15817 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15818 let newest_selection_id = this.selections.newest_anchor().id;
15819 this.selections
15820 .all::<OffsetUtf16>(cx)
15821 .iter()
15822 .zip(ranges_to_replace.iter())
15823 .find_map(|(selection, range)| {
15824 if selection.id == newest_selection_id {
15825 Some(
15826 (range.start.0 as isize - selection.head().0 as isize)
15827 ..(range.end.0 as isize - selection.head().0 as isize),
15828 )
15829 } else {
15830 None
15831 }
15832 })
15833 });
15834
15835 cx.emit(EditorEvent::InputHandled {
15836 utf16_range_to_replace: range_to_replace,
15837 text: text.into(),
15838 });
15839
15840 if let Some(new_selected_ranges) = new_selected_ranges {
15841 this.change_selections(None, window, cx, |selections| {
15842 selections.select_ranges(new_selected_ranges)
15843 });
15844 this.backspace(&Default::default(), window, cx);
15845 }
15846
15847 this.handle_input(text, window, cx);
15848 });
15849
15850 if let Some(transaction) = self.ime_transaction {
15851 self.buffer.update(cx, |buffer, cx| {
15852 buffer.group_until_transaction(transaction, cx);
15853 });
15854 }
15855
15856 self.unmark_text(window, cx);
15857 }
15858
15859 fn replace_and_mark_text_in_range(
15860 &mut self,
15861 range_utf16: Option<Range<usize>>,
15862 text: &str,
15863 new_selected_range_utf16: Option<Range<usize>>,
15864 window: &mut Window,
15865 cx: &mut Context<Self>,
15866 ) {
15867 if !self.input_enabled {
15868 return;
15869 }
15870
15871 let transaction = self.transact(window, cx, |this, window, cx| {
15872 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15873 let snapshot = this.buffer.read(cx).read(cx);
15874 if let Some(relative_range_utf16) = range_utf16.as_ref() {
15875 for marked_range in &mut marked_ranges {
15876 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15877 marked_range.start.0 += relative_range_utf16.start;
15878 marked_range.start =
15879 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15880 marked_range.end =
15881 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15882 }
15883 }
15884 Some(marked_ranges)
15885 } else if let Some(range_utf16) = range_utf16 {
15886 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15887 Some(this.selection_replacement_ranges(range_utf16, cx))
15888 } else {
15889 None
15890 };
15891
15892 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
15893 let newest_selection_id = this.selections.newest_anchor().id;
15894 this.selections
15895 .all::<OffsetUtf16>(cx)
15896 .iter()
15897 .zip(ranges_to_replace.iter())
15898 .find_map(|(selection, range)| {
15899 if selection.id == newest_selection_id {
15900 Some(
15901 (range.start.0 as isize - selection.head().0 as isize)
15902 ..(range.end.0 as isize - selection.head().0 as isize),
15903 )
15904 } else {
15905 None
15906 }
15907 })
15908 });
15909
15910 cx.emit(EditorEvent::InputHandled {
15911 utf16_range_to_replace: range_to_replace,
15912 text: text.into(),
15913 });
15914
15915 if let Some(ranges) = ranges_to_replace {
15916 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
15917 }
15918
15919 let marked_ranges = {
15920 let snapshot = this.buffer.read(cx).read(cx);
15921 this.selections
15922 .disjoint_anchors()
15923 .iter()
15924 .map(|selection| {
15925 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
15926 })
15927 .collect::<Vec<_>>()
15928 };
15929
15930 if text.is_empty() {
15931 this.unmark_text(window, cx);
15932 } else {
15933 this.highlight_text::<InputComposition>(
15934 marked_ranges.clone(),
15935 HighlightStyle {
15936 underline: Some(UnderlineStyle {
15937 thickness: px(1.),
15938 color: None,
15939 wavy: false,
15940 }),
15941 ..Default::default()
15942 },
15943 cx,
15944 );
15945 }
15946
15947 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
15948 let use_autoclose = this.use_autoclose;
15949 let use_auto_surround = this.use_auto_surround;
15950 this.set_use_autoclose(false);
15951 this.set_use_auto_surround(false);
15952 this.handle_input(text, window, cx);
15953 this.set_use_autoclose(use_autoclose);
15954 this.set_use_auto_surround(use_auto_surround);
15955
15956 if let Some(new_selected_range) = new_selected_range_utf16 {
15957 let snapshot = this.buffer.read(cx).read(cx);
15958 let new_selected_ranges = marked_ranges
15959 .into_iter()
15960 .map(|marked_range| {
15961 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
15962 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
15963 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
15964 snapshot.clip_offset_utf16(new_start, Bias::Left)
15965 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
15966 })
15967 .collect::<Vec<_>>();
15968
15969 drop(snapshot);
15970 this.change_selections(None, window, cx, |selections| {
15971 selections.select_ranges(new_selected_ranges)
15972 });
15973 }
15974 });
15975
15976 self.ime_transaction = self.ime_transaction.or(transaction);
15977 if let Some(transaction) = self.ime_transaction {
15978 self.buffer.update(cx, |buffer, cx| {
15979 buffer.group_until_transaction(transaction, cx);
15980 });
15981 }
15982
15983 if self.text_highlights::<InputComposition>(cx).is_none() {
15984 self.ime_transaction.take();
15985 }
15986 }
15987
15988 fn bounds_for_range(
15989 &mut self,
15990 range_utf16: Range<usize>,
15991 element_bounds: gpui::Bounds<Pixels>,
15992 window: &mut Window,
15993 cx: &mut Context<Self>,
15994 ) -> Option<gpui::Bounds<Pixels>> {
15995 let text_layout_details = self.text_layout_details(window);
15996 let gpui::Size {
15997 width: em_width,
15998 height: line_height,
15999 } = self.character_size(window);
16000
16001 let snapshot = self.snapshot(window, cx);
16002 let scroll_position = snapshot.scroll_position();
16003 let scroll_left = scroll_position.x * em_width;
16004
16005 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16006 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16007 + self.gutter_dimensions.width
16008 + self.gutter_dimensions.margin;
16009 let y = line_height * (start.row().as_f32() - scroll_position.y);
16010
16011 Some(Bounds {
16012 origin: element_bounds.origin + point(x, y),
16013 size: size(em_width, line_height),
16014 })
16015 }
16016
16017 fn character_index_for_point(
16018 &mut self,
16019 point: gpui::Point<Pixels>,
16020 _window: &mut Window,
16021 _cx: &mut Context<Self>,
16022 ) -> Option<usize> {
16023 let position_map = self.last_position_map.as_ref()?;
16024 if !position_map.text_hitbox.contains(&point) {
16025 return None;
16026 }
16027 let display_point = position_map.point_for_position(point).previous_valid;
16028 let anchor = position_map
16029 .snapshot
16030 .display_point_to_anchor(display_point, Bias::Left);
16031 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16032 Some(utf16_offset.0)
16033 }
16034}
16035
16036trait SelectionExt {
16037 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16038 fn spanned_rows(
16039 &self,
16040 include_end_if_at_line_start: bool,
16041 map: &DisplaySnapshot,
16042 ) -> Range<MultiBufferRow>;
16043}
16044
16045impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16046 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16047 let start = self
16048 .start
16049 .to_point(&map.buffer_snapshot)
16050 .to_display_point(map);
16051 let end = self
16052 .end
16053 .to_point(&map.buffer_snapshot)
16054 .to_display_point(map);
16055 if self.reversed {
16056 end..start
16057 } else {
16058 start..end
16059 }
16060 }
16061
16062 fn spanned_rows(
16063 &self,
16064 include_end_if_at_line_start: bool,
16065 map: &DisplaySnapshot,
16066 ) -> Range<MultiBufferRow> {
16067 let start = self.start.to_point(&map.buffer_snapshot);
16068 let mut end = self.end.to_point(&map.buffer_snapshot);
16069 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16070 end.row -= 1;
16071 }
16072
16073 let buffer_start = map.prev_line_boundary(start).0;
16074 let buffer_end = map.next_line_boundary(end).0;
16075 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16076 }
16077}
16078
16079impl<T: InvalidationRegion> InvalidationStack<T> {
16080 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16081 where
16082 S: Clone + ToOffset,
16083 {
16084 while let Some(region) = self.last() {
16085 let all_selections_inside_invalidation_ranges =
16086 if selections.len() == region.ranges().len() {
16087 selections
16088 .iter()
16089 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16090 .all(|(selection, invalidation_range)| {
16091 let head = selection.head().to_offset(buffer);
16092 invalidation_range.start <= head && invalidation_range.end >= head
16093 })
16094 } else {
16095 false
16096 };
16097
16098 if all_selections_inside_invalidation_ranges {
16099 break;
16100 } else {
16101 self.pop();
16102 }
16103 }
16104 }
16105}
16106
16107impl<T> Default for InvalidationStack<T> {
16108 fn default() -> Self {
16109 Self(Default::default())
16110 }
16111}
16112
16113impl<T> Deref for InvalidationStack<T> {
16114 type Target = Vec<T>;
16115
16116 fn deref(&self) -> &Self::Target {
16117 &self.0
16118 }
16119}
16120
16121impl<T> DerefMut for InvalidationStack<T> {
16122 fn deref_mut(&mut self) -> &mut Self::Target {
16123 &mut self.0
16124 }
16125}
16126
16127impl InvalidationRegion for SnippetState {
16128 fn ranges(&self) -> &[Range<Anchor>] {
16129 &self.ranges[self.active_index]
16130 }
16131}
16132
16133pub fn diagnostic_block_renderer(
16134 diagnostic: Diagnostic,
16135 max_message_rows: Option<u8>,
16136 allow_closing: bool,
16137 _is_valid: bool,
16138) -> RenderBlock {
16139 let (text_without_backticks, code_ranges) =
16140 highlight_diagnostic_message(&diagnostic, max_message_rows);
16141
16142 Arc::new(move |cx: &mut BlockContext| {
16143 let group_id: SharedString = cx.block_id.to_string().into();
16144
16145 let mut text_style = cx.window.text_style().clone();
16146 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16147 let theme_settings = ThemeSettings::get_global(cx);
16148 text_style.font_family = theme_settings.buffer_font.family.clone();
16149 text_style.font_style = theme_settings.buffer_font.style;
16150 text_style.font_features = theme_settings.buffer_font.features.clone();
16151 text_style.font_weight = theme_settings.buffer_font.weight;
16152
16153 let multi_line_diagnostic = diagnostic.message.contains('\n');
16154
16155 let buttons = |diagnostic: &Diagnostic| {
16156 if multi_line_diagnostic {
16157 v_flex()
16158 } else {
16159 h_flex()
16160 }
16161 .when(allow_closing, |div| {
16162 div.children(diagnostic.is_primary.then(|| {
16163 IconButton::new("close-block", IconName::XCircle)
16164 .icon_color(Color::Muted)
16165 .size(ButtonSize::Compact)
16166 .style(ButtonStyle::Transparent)
16167 .visible_on_hover(group_id.clone())
16168 .on_click(move |_click, window, cx| {
16169 window.dispatch_action(Box::new(Cancel), cx)
16170 })
16171 .tooltip(|window, cx| {
16172 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16173 })
16174 }))
16175 })
16176 .child(
16177 IconButton::new("copy-block", IconName::Copy)
16178 .icon_color(Color::Muted)
16179 .size(ButtonSize::Compact)
16180 .style(ButtonStyle::Transparent)
16181 .visible_on_hover(group_id.clone())
16182 .on_click({
16183 let message = diagnostic.message.clone();
16184 move |_click, _, cx| {
16185 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16186 }
16187 })
16188 .tooltip(Tooltip::text("Copy diagnostic message")),
16189 )
16190 };
16191
16192 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16193 AvailableSpace::min_size(),
16194 cx.window,
16195 cx.app,
16196 );
16197
16198 h_flex()
16199 .id(cx.block_id)
16200 .group(group_id.clone())
16201 .relative()
16202 .size_full()
16203 .block_mouse_down()
16204 .pl(cx.gutter_dimensions.width)
16205 .w(cx.max_width - cx.gutter_dimensions.full_width())
16206 .child(
16207 div()
16208 .flex()
16209 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16210 .flex_shrink(),
16211 )
16212 .child(buttons(&diagnostic))
16213 .child(div().flex().flex_shrink_0().child(
16214 StyledText::new(text_without_backticks.clone()).with_highlights(
16215 &text_style,
16216 code_ranges.iter().map(|range| {
16217 (
16218 range.clone(),
16219 HighlightStyle {
16220 font_weight: Some(FontWeight::BOLD),
16221 ..Default::default()
16222 },
16223 )
16224 }),
16225 ),
16226 ))
16227 .into_any_element()
16228 })
16229}
16230
16231fn inline_completion_edit_text(
16232 current_snapshot: &BufferSnapshot,
16233 edits: &[(Range<Anchor>, String)],
16234 edit_preview: &EditPreview,
16235 include_deletions: bool,
16236 cx: &App,
16237) -> HighlightedText {
16238 let edits = edits
16239 .iter()
16240 .map(|(anchor, text)| {
16241 (
16242 anchor.start.text_anchor..anchor.end.text_anchor,
16243 text.clone(),
16244 )
16245 })
16246 .collect::<Vec<_>>();
16247
16248 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16249}
16250
16251pub fn highlight_diagnostic_message(
16252 diagnostic: &Diagnostic,
16253 mut max_message_rows: Option<u8>,
16254) -> (SharedString, Vec<Range<usize>>) {
16255 let mut text_without_backticks = String::new();
16256 let mut code_ranges = Vec::new();
16257
16258 if let Some(source) = &diagnostic.source {
16259 text_without_backticks.push_str(source);
16260 code_ranges.push(0..source.len());
16261 text_without_backticks.push_str(": ");
16262 }
16263
16264 let mut prev_offset = 0;
16265 let mut in_code_block = false;
16266 let has_row_limit = max_message_rows.is_some();
16267 let mut newline_indices = diagnostic
16268 .message
16269 .match_indices('\n')
16270 .filter(|_| has_row_limit)
16271 .map(|(ix, _)| ix)
16272 .fuse()
16273 .peekable();
16274
16275 for (quote_ix, _) in diagnostic
16276 .message
16277 .match_indices('`')
16278 .chain([(diagnostic.message.len(), "")])
16279 {
16280 let mut first_newline_ix = None;
16281 let mut last_newline_ix = None;
16282 while let Some(newline_ix) = newline_indices.peek() {
16283 if *newline_ix < quote_ix {
16284 if first_newline_ix.is_none() {
16285 first_newline_ix = Some(*newline_ix);
16286 }
16287 last_newline_ix = Some(*newline_ix);
16288
16289 if let Some(rows_left) = &mut max_message_rows {
16290 if *rows_left == 0 {
16291 break;
16292 } else {
16293 *rows_left -= 1;
16294 }
16295 }
16296 let _ = newline_indices.next();
16297 } else {
16298 break;
16299 }
16300 }
16301 let prev_len = text_without_backticks.len();
16302 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16303 text_without_backticks.push_str(new_text);
16304 if in_code_block {
16305 code_ranges.push(prev_len..text_without_backticks.len());
16306 }
16307 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16308 in_code_block = !in_code_block;
16309 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16310 text_without_backticks.push_str("...");
16311 break;
16312 }
16313 }
16314
16315 (text_without_backticks.into(), code_ranges)
16316}
16317
16318fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16319 match severity {
16320 DiagnosticSeverity::ERROR => colors.error,
16321 DiagnosticSeverity::WARNING => colors.warning,
16322 DiagnosticSeverity::INFORMATION => colors.info,
16323 DiagnosticSeverity::HINT => colors.info,
16324 _ => colors.ignored,
16325 }
16326}
16327
16328pub fn styled_runs_for_code_label<'a>(
16329 label: &'a CodeLabel,
16330 syntax_theme: &'a theme::SyntaxTheme,
16331) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16332 let fade_out = HighlightStyle {
16333 fade_out: Some(0.35),
16334 ..Default::default()
16335 };
16336
16337 let mut prev_end = label.filter_range.end;
16338 label
16339 .runs
16340 .iter()
16341 .enumerate()
16342 .flat_map(move |(ix, (range, highlight_id))| {
16343 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16344 style
16345 } else {
16346 return Default::default();
16347 };
16348 let mut muted_style = style;
16349 muted_style.highlight(fade_out);
16350
16351 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16352 if range.start >= label.filter_range.end {
16353 if range.start > prev_end {
16354 runs.push((prev_end..range.start, fade_out));
16355 }
16356 runs.push((range.clone(), muted_style));
16357 } else if range.end <= label.filter_range.end {
16358 runs.push((range.clone(), style));
16359 } else {
16360 runs.push((range.start..label.filter_range.end, style));
16361 runs.push((label.filter_range.end..range.end, muted_style));
16362 }
16363 prev_end = cmp::max(prev_end, range.end);
16364
16365 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16366 runs.push((prev_end..label.text.len(), fade_out));
16367 }
16368
16369 runs
16370 })
16371}
16372
16373pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16374 let mut prev_index = 0;
16375 let mut prev_codepoint: Option<char> = None;
16376 text.char_indices()
16377 .chain([(text.len(), '\0')])
16378 .filter_map(move |(index, codepoint)| {
16379 let prev_codepoint = prev_codepoint.replace(codepoint)?;
16380 let is_boundary = index == text.len()
16381 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16382 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16383 if is_boundary {
16384 let chunk = &text[prev_index..index];
16385 prev_index = index;
16386 Some(chunk)
16387 } else {
16388 None
16389 }
16390 })
16391}
16392
16393pub trait RangeToAnchorExt: Sized {
16394 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16395
16396 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16397 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16398 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16399 }
16400}
16401
16402impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16403 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16404 let start_offset = self.start.to_offset(snapshot);
16405 let end_offset = self.end.to_offset(snapshot);
16406 if start_offset == end_offset {
16407 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16408 } else {
16409 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16410 }
16411 }
16412}
16413
16414pub trait RowExt {
16415 fn as_f32(&self) -> f32;
16416
16417 fn next_row(&self) -> Self;
16418
16419 fn previous_row(&self) -> Self;
16420
16421 fn minus(&self, other: Self) -> u32;
16422}
16423
16424impl RowExt for DisplayRow {
16425 fn as_f32(&self) -> f32 {
16426 self.0 as f32
16427 }
16428
16429 fn next_row(&self) -> Self {
16430 Self(self.0 + 1)
16431 }
16432
16433 fn previous_row(&self) -> Self {
16434 Self(self.0.saturating_sub(1))
16435 }
16436
16437 fn minus(&self, other: Self) -> u32 {
16438 self.0 - other.0
16439 }
16440}
16441
16442impl RowExt for MultiBufferRow {
16443 fn as_f32(&self) -> f32 {
16444 self.0 as f32
16445 }
16446
16447 fn next_row(&self) -> Self {
16448 Self(self.0 + 1)
16449 }
16450
16451 fn previous_row(&self) -> Self {
16452 Self(self.0.saturating_sub(1))
16453 }
16454
16455 fn minus(&self, other: Self) -> u32 {
16456 self.0 - other.0
16457 }
16458}
16459
16460trait RowRangeExt {
16461 type Row;
16462
16463 fn len(&self) -> usize;
16464
16465 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16466}
16467
16468impl RowRangeExt for Range<MultiBufferRow> {
16469 type Row = MultiBufferRow;
16470
16471 fn len(&self) -> usize {
16472 (self.end.0 - self.start.0) as usize
16473 }
16474
16475 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16476 (self.start.0..self.end.0).map(MultiBufferRow)
16477 }
16478}
16479
16480impl RowRangeExt for Range<DisplayRow> {
16481 type Row = DisplayRow;
16482
16483 fn len(&self) -> usize {
16484 (self.end.0 - self.start.0) as usize
16485 }
16486
16487 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16488 (self.start.0..self.end.0).map(DisplayRow)
16489 }
16490}
16491
16492/// If select range has more than one line, we
16493/// just point the cursor to range.start.
16494fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16495 if range.start.row == range.end.row {
16496 range
16497 } else {
16498 range.start..range.start
16499 }
16500}
16501pub struct KillRing(ClipboardItem);
16502impl Global for KillRing {}
16503
16504const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16505
16506fn all_edits_insertions_or_deletions(
16507 edits: &Vec<(Range<Anchor>, String)>,
16508 snapshot: &MultiBufferSnapshot,
16509) -> bool {
16510 let mut all_insertions = true;
16511 let mut all_deletions = true;
16512
16513 for (range, new_text) in edits.iter() {
16514 let range_is_empty = range.to_offset(&snapshot).is_empty();
16515 let text_is_empty = new_text.is_empty();
16516
16517 if range_is_empty != text_is_empty {
16518 if range_is_empty {
16519 all_deletions = false;
16520 } else {
16521 all_insertions = false;
16522 }
16523 } else {
16524 return false;
16525 }
16526
16527 if !all_insertions && !all_deletions {
16528 return false;
16529 }
16530 }
16531 all_insertions || all_deletions
16532}