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 None,
5617 true,
5618 ),
5619 ))
5620 .child(Label::new("Preview").into_any_element())
5621 .opacity(if has_completion { 1.0 } else { 0.4 }),
5622 )
5623 .into_any(),
5624 )
5625 }
5626
5627 fn render_edit_prediction_cursor_popover_preview(
5628 &self,
5629 completion: &InlineCompletionState,
5630 cursor_point: Point,
5631 style: &EditorStyle,
5632 window: &Window,
5633 cx: &mut Context<Editor>,
5634 ) -> Option<Div> {
5635 use text::ToPoint as _;
5636
5637 fn render_relative_row_jump(
5638 prefix: impl Into<String>,
5639 current_row: u32,
5640 target_row: u32,
5641 ) -> Div {
5642 let (row_diff, arrow) = if target_row < current_row {
5643 (current_row - target_row, IconName::ArrowUp)
5644 } else {
5645 (target_row - current_row, IconName::ArrowDown)
5646 };
5647
5648 h_flex()
5649 .child(
5650 Label::new(format!("{}{}", prefix.into(), row_diff))
5651 .color(Color::Muted)
5652 .size(LabelSize::Small),
5653 )
5654 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
5655 }
5656
5657 match &completion.completion {
5658 InlineCompletion::Edit {
5659 edits,
5660 edit_preview,
5661 snapshot,
5662 display_mode: _,
5663 } => {
5664 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
5665
5666 let highlighted_edits = crate::inline_completion_edit_text(
5667 &snapshot,
5668 &edits,
5669 edit_preview.as_ref()?,
5670 true,
5671 cx,
5672 );
5673
5674 let len_total = highlighted_edits.text.len();
5675 let first_line = &highlighted_edits.text
5676 [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
5677 let first_line_len = first_line.len();
5678
5679 let first_highlight_start = highlighted_edits
5680 .highlights
5681 .first()
5682 .map_or(0, |(range, _)| range.start);
5683 let drop_prefix_len = first_line
5684 .char_indices()
5685 .find(|(_, c)| !c.is_whitespace())
5686 .map_or(first_highlight_start, |(ix, _)| {
5687 ix.min(first_highlight_start)
5688 });
5689
5690 let preview_text = &first_line[drop_prefix_len..];
5691 let preview_len = preview_text.len();
5692 let highlights = highlighted_edits
5693 .highlights
5694 .into_iter()
5695 .take_until(|(range, _)| range.start > first_line_len)
5696 .map(|(range, style)| {
5697 (
5698 range.start - drop_prefix_len
5699 ..(range.end - drop_prefix_len).min(preview_len),
5700 style,
5701 )
5702 });
5703
5704 let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
5705 .with_highlights(&style.text, highlights);
5706
5707 let preview = h_flex()
5708 .gap_1()
5709 .min_w_16()
5710 .child(styled_text)
5711 .when(len_total > first_line_len, |parent| parent.child("…"));
5712
5713 let left = if first_edit_row != cursor_point.row {
5714 render_relative_row_jump("", cursor_point.row, first_edit_row)
5715 .into_any_element()
5716 } else {
5717 Icon::new(IconName::ZedPredict).into_any_element()
5718 };
5719
5720 Some(
5721 h_flex()
5722 .h_full()
5723 .flex_1()
5724 .gap_2()
5725 .pr_1()
5726 .overflow_x_hidden()
5727 .child(left)
5728 .child(preview),
5729 )
5730 }
5731
5732 InlineCompletion::Move {
5733 target,
5734 range_around_target,
5735 snapshot,
5736 } => {
5737 let highlighted_text = snapshot.highlighted_text_for_range(
5738 range_around_target.clone(),
5739 None,
5740 &style.syntax,
5741 );
5742 let base = h_flex().gap_3().flex_1().child(render_relative_row_jump(
5743 "Jump ",
5744 cursor_point.row,
5745 target.text_anchor.to_point(&snapshot).row,
5746 ));
5747
5748 if highlighted_text.text.is_empty() {
5749 return Some(base);
5750 }
5751
5752 let cursor_color = self.current_user_player_color(cx).cursor;
5753
5754 let start_point = range_around_target.start.to_point(&snapshot);
5755 let end_point = range_around_target.end.to_point(&snapshot);
5756 let target_point = target.text_anchor.to_point(&snapshot);
5757
5758 let styled_text = highlighted_text.to_styled_text(&style.text);
5759 let text_len = highlighted_text.text.len();
5760
5761 let cursor_relative_position = window
5762 .text_system()
5763 .layout_line(
5764 highlighted_text.text,
5765 style.text.font_size.to_pixels(window.rem_size()),
5766 // We don't need to include highlights
5767 // because we are only using this for the cursor position
5768 &[TextRun {
5769 len: text_len,
5770 font: style.text.font(),
5771 color: style.text.color,
5772 background_color: None,
5773 underline: None,
5774 strikethrough: None,
5775 }],
5776 )
5777 .log_err()
5778 .map(|line| {
5779 line.x_for_index(
5780 target_point.column.saturating_sub(start_point.column) as usize
5781 )
5782 });
5783
5784 let fade_before = start_point.column > 0;
5785 let fade_after = end_point.column < snapshot.line_len(end_point.row);
5786
5787 let background = cx.theme().colors().elevated_surface_background;
5788
5789 let preview = h_flex()
5790 .relative()
5791 .child(styled_text)
5792 .when(fade_before, |parent| {
5793 parent.child(div().absolute().top_0().left_0().w_4().h_full().bg(
5794 linear_gradient(
5795 90.,
5796 linear_color_stop(background, 0.),
5797 linear_color_stop(background.opacity(0.), 1.),
5798 ),
5799 ))
5800 })
5801 .when(fade_after, |parent| {
5802 parent.child(div().absolute().top_0().right_0().w_4().h_full().bg(
5803 linear_gradient(
5804 -90.,
5805 linear_color_stop(background, 0.),
5806 linear_color_stop(background.opacity(0.), 1.),
5807 ),
5808 ))
5809 })
5810 .when_some(cursor_relative_position, |parent, position| {
5811 parent.child(
5812 div()
5813 .w(px(2.))
5814 .h_full()
5815 .bg(cursor_color)
5816 .absolute()
5817 .top_0()
5818 .left(position),
5819 )
5820 });
5821
5822 Some(base.child(preview))
5823 }
5824 }
5825 }
5826
5827 fn render_context_menu(
5828 &self,
5829 style: &EditorStyle,
5830 max_height_in_lines: u32,
5831 y_flipped: bool,
5832 window: &mut Window,
5833 cx: &mut Context<Editor>,
5834 ) -> Option<AnyElement> {
5835 let menu = self.context_menu.borrow();
5836 let menu = menu.as_ref()?;
5837 if !menu.visible() {
5838 return None;
5839 };
5840 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
5841 }
5842
5843 fn render_context_menu_aside(
5844 &self,
5845 style: &EditorStyle,
5846 max_size: Size<Pixels>,
5847 cx: &mut Context<Editor>,
5848 ) -> Option<AnyElement> {
5849 self.context_menu.borrow().as_ref().and_then(|menu| {
5850 if menu.visible() {
5851 menu.render_aside(
5852 style,
5853 max_size,
5854 self.workspace.as_ref().map(|(w, _)| w.clone()),
5855 cx,
5856 )
5857 } else {
5858 None
5859 }
5860 })
5861 }
5862
5863 fn hide_context_menu(
5864 &mut self,
5865 window: &mut Window,
5866 cx: &mut Context<Self>,
5867 ) -> Option<CodeContextMenu> {
5868 cx.notify();
5869 self.completion_tasks.clear();
5870 let context_menu = self.context_menu.borrow_mut().take();
5871 self.stale_inline_completion_in_menu.take();
5872 self.update_visible_inline_completion(window, cx);
5873 context_menu
5874 }
5875
5876 fn show_snippet_choices(
5877 &mut self,
5878 choices: &Vec<String>,
5879 selection: Range<Anchor>,
5880 cx: &mut Context<Self>,
5881 ) {
5882 if selection.start.buffer_id.is_none() {
5883 return;
5884 }
5885 let buffer_id = selection.start.buffer_id.unwrap();
5886 let buffer = self.buffer().read(cx).buffer(buffer_id);
5887 let id = post_inc(&mut self.next_completion_id);
5888
5889 if let Some(buffer) = buffer {
5890 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5891 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5892 ));
5893 }
5894 }
5895
5896 pub fn insert_snippet(
5897 &mut self,
5898 insertion_ranges: &[Range<usize>],
5899 snippet: Snippet,
5900 window: &mut Window,
5901 cx: &mut Context<Self>,
5902 ) -> Result<()> {
5903 struct Tabstop<T> {
5904 is_end_tabstop: bool,
5905 ranges: Vec<Range<T>>,
5906 choices: Option<Vec<String>>,
5907 }
5908
5909 let tabstops = self.buffer.update(cx, |buffer, cx| {
5910 let snippet_text: Arc<str> = snippet.text.clone().into();
5911 buffer.edit(
5912 insertion_ranges
5913 .iter()
5914 .cloned()
5915 .map(|range| (range, snippet_text.clone())),
5916 Some(AutoindentMode::EachLine),
5917 cx,
5918 );
5919
5920 let snapshot = &*buffer.read(cx);
5921 let snippet = &snippet;
5922 snippet
5923 .tabstops
5924 .iter()
5925 .map(|tabstop| {
5926 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5927 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5928 });
5929 let mut tabstop_ranges = tabstop
5930 .ranges
5931 .iter()
5932 .flat_map(|tabstop_range| {
5933 let mut delta = 0_isize;
5934 insertion_ranges.iter().map(move |insertion_range| {
5935 let insertion_start = insertion_range.start as isize + delta;
5936 delta +=
5937 snippet.text.len() as isize - insertion_range.len() as isize;
5938
5939 let start = ((insertion_start + tabstop_range.start) as usize)
5940 .min(snapshot.len());
5941 let end = ((insertion_start + tabstop_range.end) as usize)
5942 .min(snapshot.len());
5943 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5944 })
5945 })
5946 .collect::<Vec<_>>();
5947 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5948
5949 Tabstop {
5950 is_end_tabstop,
5951 ranges: tabstop_ranges,
5952 choices: tabstop.choices.clone(),
5953 }
5954 })
5955 .collect::<Vec<_>>()
5956 });
5957 if let Some(tabstop) = tabstops.first() {
5958 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
5959 s.select_ranges(tabstop.ranges.iter().cloned());
5960 });
5961
5962 if let Some(choices) = &tabstop.choices {
5963 if let Some(selection) = tabstop.ranges.first() {
5964 self.show_snippet_choices(choices, selection.clone(), cx)
5965 }
5966 }
5967
5968 // If we're already at the last tabstop and it's at the end of the snippet,
5969 // we're done, we don't need to keep the state around.
5970 if !tabstop.is_end_tabstop {
5971 let choices = tabstops
5972 .iter()
5973 .map(|tabstop| tabstop.choices.clone())
5974 .collect();
5975
5976 let ranges = tabstops
5977 .into_iter()
5978 .map(|tabstop| tabstop.ranges)
5979 .collect::<Vec<_>>();
5980
5981 self.snippet_stack.push(SnippetState {
5982 active_index: 0,
5983 ranges,
5984 choices,
5985 });
5986 }
5987
5988 // Check whether the just-entered snippet ends with an auto-closable bracket.
5989 if self.autoclose_regions.is_empty() {
5990 let snapshot = self.buffer.read(cx).snapshot(cx);
5991 for selection in &mut self.selections.all::<Point>(cx) {
5992 let selection_head = selection.head();
5993 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5994 continue;
5995 };
5996
5997 let mut bracket_pair = None;
5998 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5999 let prev_chars = snapshot
6000 .reversed_chars_at(selection_head)
6001 .collect::<String>();
6002 for (pair, enabled) in scope.brackets() {
6003 if enabled
6004 && pair.close
6005 && prev_chars.starts_with(pair.start.as_str())
6006 && next_chars.starts_with(pair.end.as_str())
6007 {
6008 bracket_pair = Some(pair.clone());
6009 break;
6010 }
6011 }
6012 if let Some(pair) = bracket_pair {
6013 let start = snapshot.anchor_after(selection_head);
6014 let end = snapshot.anchor_after(selection_head);
6015 self.autoclose_regions.push(AutocloseRegion {
6016 selection_id: selection.id,
6017 range: start..end,
6018 pair,
6019 });
6020 }
6021 }
6022 }
6023 }
6024 Ok(())
6025 }
6026
6027 pub fn move_to_next_snippet_tabstop(
6028 &mut self,
6029 window: &mut Window,
6030 cx: &mut Context<Self>,
6031 ) -> bool {
6032 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6033 }
6034
6035 pub fn move_to_prev_snippet_tabstop(
6036 &mut self,
6037 window: &mut Window,
6038 cx: &mut Context<Self>,
6039 ) -> bool {
6040 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6041 }
6042
6043 pub fn move_to_snippet_tabstop(
6044 &mut self,
6045 bias: Bias,
6046 window: &mut Window,
6047 cx: &mut Context<Self>,
6048 ) -> bool {
6049 if let Some(mut snippet) = self.snippet_stack.pop() {
6050 match bias {
6051 Bias::Left => {
6052 if snippet.active_index > 0 {
6053 snippet.active_index -= 1;
6054 } else {
6055 self.snippet_stack.push(snippet);
6056 return false;
6057 }
6058 }
6059 Bias::Right => {
6060 if snippet.active_index + 1 < snippet.ranges.len() {
6061 snippet.active_index += 1;
6062 } else {
6063 self.snippet_stack.push(snippet);
6064 return false;
6065 }
6066 }
6067 }
6068 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6069 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6070 s.select_anchor_ranges(current_ranges.iter().cloned())
6071 });
6072
6073 if let Some(choices) = &snippet.choices[snippet.active_index] {
6074 if let Some(selection) = current_ranges.first() {
6075 self.show_snippet_choices(&choices, selection.clone(), cx);
6076 }
6077 }
6078
6079 // If snippet state is not at the last tabstop, push it back on the stack
6080 if snippet.active_index + 1 < snippet.ranges.len() {
6081 self.snippet_stack.push(snippet);
6082 }
6083 return true;
6084 }
6085 }
6086
6087 false
6088 }
6089
6090 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6091 self.transact(window, cx, |this, window, cx| {
6092 this.select_all(&SelectAll, window, cx);
6093 this.insert("", window, cx);
6094 });
6095 }
6096
6097 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6098 self.transact(window, cx, |this, window, cx| {
6099 this.select_autoclose_pair(window, cx);
6100 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6101 if !this.linked_edit_ranges.is_empty() {
6102 let selections = this.selections.all::<MultiBufferPoint>(cx);
6103 let snapshot = this.buffer.read(cx).snapshot(cx);
6104
6105 for selection in selections.iter() {
6106 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6107 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6108 if selection_start.buffer_id != selection_end.buffer_id {
6109 continue;
6110 }
6111 if let Some(ranges) =
6112 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6113 {
6114 for (buffer, entries) in ranges {
6115 linked_ranges.entry(buffer).or_default().extend(entries);
6116 }
6117 }
6118 }
6119 }
6120
6121 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6122 if !this.selections.line_mode {
6123 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6124 for selection in &mut selections {
6125 if selection.is_empty() {
6126 let old_head = selection.head();
6127 let mut new_head =
6128 movement::left(&display_map, old_head.to_display_point(&display_map))
6129 .to_point(&display_map);
6130 if let Some((buffer, line_buffer_range)) = display_map
6131 .buffer_snapshot
6132 .buffer_line_for_row(MultiBufferRow(old_head.row))
6133 {
6134 let indent_size =
6135 buffer.indent_size_for_line(line_buffer_range.start.row);
6136 let indent_len = match indent_size.kind {
6137 IndentKind::Space => {
6138 buffer.settings_at(line_buffer_range.start, cx).tab_size
6139 }
6140 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6141 };
6142 if old_head.column <= indent_size.len && old_head.column > 0 {
6143 let indent_len = indent_len.get();
6144 new_head = cmp::min(
6145 new_head,
6146 MultiBufferPoint::new(
6147 old_head.row,
6148 ((old_head.column - 1) / indent_len) * indent_len,
6149 ),
6150 );
6151 }
6152 }
6153
6154 selection.set_head(new_head, SelectionGoal::None);
6155 }
6156 }
6157 }
6158
6159 this.signature_help_state.set_backspace_pressed(true);
6160 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6161 s.select(selections)
6162 });
6163 this.insert("", window, cx);
6164 let empty_str: Arc<str> = Arc::from("");
6165 for (buffer, edits) in linked_ranges {
6166 let snapshot = buffer.read(cx).snapshot();
6167 use text::ToPoint as TP;
6168
6169 let edits = edits
6170 .into_iter()
6171 .map(|range| {
6172 let end_point = TP::to_point(&range.end, &snapshot);
6173 let mut start_point = TP::to_point(&range.start, &snapshot);
6174
6175 if end_point == start_point {
6176 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6177 .saturating_sub(1);
6178 start_point =
6179 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6180 };
6181
6182 (start_point..end_point, empty_str.clone())
6183 })
6184 .sorted_by_key(|(range, _)| range.start)
6185 .collect::<Vec<_>>();
6186 buffer.update(cx, |this, cx| {
6187 this.edit(edits, None, cx);
6188 })
6189 }
6190 this.refresh_inline_completion(true, false, window, cx);
6191 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6192 });
6193 }
6194
6195 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6196 self.transact(window, cx, |this, window, cx| {
6197 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6198 let line_mode = s.line_mode;
6199 s.move_with(|map, selection| {
6200 if selection.is_empty() && !line_mode {
6201 let cursor = movement::right(map, selection.head());
6202 selection.end = cursor;
6203 selection.reversed = true;
6204 selection.goal = SelectionGoal::None;
6205 }
6206 })
6207 });
6208 this.insert("", window, cx);
6209 this.refresh_inline_completion(true, false, window, cx);
6210 });
6211 }
6212
6213 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6214 if self.move_to_prev_snippet_tabstop(window, cx) {
6215 return;
6216 }
6217
6218 self.outdent(&Outdent, window, cx);
6219 }
6220
6221 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6222 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6223 return;
6224 }
6225
6226 let mut selections = self.selections.all_adjusted(cx);
6227 let buffer = self.buffer.read(cx);
6228 let snapshot = buffer.snapshot(cx);
6229 let rows_iter = selections.iter().map(|s| s.head().row);
6230 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6231
6232 let mut edits = Vec::new();
6233 let mut prev_edited_row = 0;
6234 let mut row_delta = 0;
6235 for selection in &mut selections {
6236 if selection.start.row != prev_edited_row {
6237 row_delta = 0;
6238 }
6239 prev_edited_row = selection.end.row;
6240
6241 // If the selection is non-empty, then increase the indentation of the selected lines.
6242 if !selection.is_empty() {
6243 row_delta =
6244 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6245 continue;
6246 }
6247
6248 // If the selection is empty and the cursor is in the leading whitespace before the
6249 // suggested indentation, then auto-indent the line.
6250 let cursor = selection.head();
6251 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6252 if let Some(suggested_indent) =
6253 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6254 {
6255 if cursor.column < suggested_indent.len
6256 && cursor.column <= current_indent.len
6257 && current_indent.len <= suggested_indent.len
6258 {
6259 selection.start = Point::new(cursor.row, suggested_indent.len);
6260 selection.end = selection.start;
6261 if row_delta == 0 {
6262 edits.extend(Buffer::edit_for_indent_size_adjustment(
6263 cursor.row,
6264 current_indent,
6265 suggested_indent,
6266 ));
6267 row_delta = suggested_indent.len - current_indent.len;
6268 }
6269 continue;
6270 }
6271 }
6272
6273 // Otherwise, insert a hard or soft tab.
6274 let settings = buffer.settings_at(cursor, cx);
6275 let tab_size = if settings.hard_tabs {
6276 IndentSize::tab()
6277 } else {
6278 let tab_size = settings.tab_size.get();
6279 let char_column = snapshot
6280 .text_for_range(Point::new(cursor.row, 0)..cursor)
6281 .flat_map(str::chars)
6282 .count()
6283 + row_delta as usize;
6284 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6285 IndentSize::spaces(chars_to_next_tab_stop)
6286 };
6287 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6288 selection.end = selection.start;
6289 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6290 row_delta += tab_size.len;
6291 }
6292
6293 self.transact(window, cx, |this, window, cx| {
6294 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6295 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6296 s.select(selections)
6297 });
6298 this.refresh_inline_completion(true, false, window, cx);
6299 });
6300 }
6301
6302 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6303 if self.read_only(cx) {
6304 return;
6305 }
6306 let mut selections = self.selections.all::<Point>(cx);
6307 let mut prev_edited_row = 0;
6308 let mut row_delta = 0;
6309 let mut edits = Vec::new();
6310 let buffer = self.buffer.read(cx);
6311 let snapshot = buffer.snapshot(cx);
6312 for selection in &mut selections {
6313 if selection.start.row != prev_edited_row {
6314 row_delta = 0;
6315 }
6316 prev_edited_row = selection.end.row;
6317
6318 row_delta =
6319 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6320 }
6321
6322 self.transact(window, cx, |this, window, cx| {
6323 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6324 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6325 s.select(selections)
6326 });
6327 });
6328 }
6329
6330 fn indent_selection(
6331 buffer: &MultiBuffer,
6332 snapshot: &MultiBufferSnapshot,
6333 selection: &mut Selection<Point>,
6334 edits: &mut Vec<(Range<Point>, String)>,
6335 delta_for_start_row: u32,
6336 cx: &App,
6337 ) -> u32 {
6338 let settings = buffer.settings_at(selection.start, cx);
6339 let tab_size = settings.tab_size.get();
6340 let indent_kind = if settings.hard_tabs {
6341 IndentKind::Tab
6342 } else {
6343 IndentKind::Space
6344 };
6345 let mut start_row = selection.start.row;
6346 let mut end_row = selection.end.row + 1;
6347
6348 // If a selection ends at the beginning of a line, don't indent
6349 // that last line.
6350 if selection.end.column == 0 && selection.end.row > selection.start.row {
6351 end_row -= 1;
6352 }
6353
6354 // Avoid re-indenting a row that has already been indented by a
6355 // previous selection, but still update this selection's column
6356 // to reflect that indentation.
6357 if delta_for_start_row > 0 {
6358 start_row += 1;
6359 selection.start.column += delta_for_start_row;
6360 if selection.end.row == selection.start.row {
6361 selection.end.column += delta_for_start_row;
6362 }
6363 }
6364
6365 let mut delta_for_end_row = 0;
6366 let has_multiple_rows = start_row + 1 != end_row;
6367 for row in start_row..end_row {
6368 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6369 let indent_delta = match (current_indent.kind, indent_kind) {
6370 (IndentKind::Space, IndentKind::Space) => {
6371 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6372 IndentSize::spaces(columns_to_next_tab_stop)
6373 }
6374 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6375 (_, IndentKind::Tab) => IndentSize::tab(),
6376 };
6377
6378 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6379 0
6380 } else {
6381 selection.start.column
6382 };
6383 let row_start = Point::new(row, start);
6384 edits.push((
6385 row_start..row_start,
6386 indent_delta.chars().collect::<String>(),
6387 ));
6388
6389 // Update this selection's endpoints to reflect the indentation.
6390 if row == selection.start.row {
6391 selection.start.column += indent_delta.len;
6392 }
6393 if row == selection.end.row {
6394 selection.end.column += indent_delta.len;
6395 delta_for_end_row = indent_delta.len;
6396 }
6397 }
6398
6399 if selection.start.row == selection.end.row {
6400 delta_for_start_row + delta_for_end_row
6401 } else {
6402 delta_for_end_row
6403 }
6404 }
6405
6406 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6407 if self.read_only(cx) {
6408 return;
6409 }
6410 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6411 let selections = self.selections.all::<Point>(cx);
6412 let mut deletion_ranges = Vec::new();
6413 let mut last_outdent = None;
6414 {
6415 let buffer = self.buffer.read(cx);
6416 let snapshot = buffer.snapshot(cx);
6417 for selection in &selections {
6418 let settings = buffer.settings_at(selection.start, cx);
6419 let tab_size = settings.tab_size.get();
6420 let mut rows = selection.spanned_rows(false, &display_map);
6421
6422 // Avoid re-outdenting a row that has already been outdented by a
6423 // previous selection.
6424 if let Some(last_row) = last_outdent {
6425 if last_row == rows.start {
6426 rows.start = rows.start.next_row();
6427 }
6428 }
6429 let has_multiple_rows = rows.len() > 1;
6430 for row in rows.iter_rows() {
6431 let indent_size = snapshot.indent_size_for_line(row);
6432 if indent_size.len > 0 {
6433 let deletion_len = match indent_size.kind {
6434 IndentKind::Space => {
6435 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6436 if columns_to_prev_tab_stop == 0 {
6437 tab_size
6438 } else {
6439 columns_to_prev_tab_stop
6440 }
6441 }
6442 IndentKind::Tab => 1,
6443 };
6444 let start = if has_multiple_rows
6445 || deletion_len > selection.start.column
6446 || indent_size.len < selection.start.column
6447 {
6448 0
6449 } else {
6450 selection.start.column - deletion_len
6451 };
6452 deletion_ranges.push(
6453 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6454 );
6455 last_outdent = Some(row);
6456 }
6457 }
6458 }
6459 }
6460
6461 self.transact(window, cx, |this, window, cx| {
6462 this.buffer.update(cx, |buffer, cx| {
6463 let empty_str: Arc<str> = Arc::default();
6464 buffer.edit(
6465 deletion_ranges
6466 .into_iter()
6467 .map(|range| (range, empty_str.clone())),
6468 None,
6469 cx,
6470 );
6471 });
6472 let selections = this.selections.all::<usize>(cx);
6473 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6474 s.select(selections)
6475 });
6476 });
6477 }
6478
6479 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6480 if self.read_only(cx) {
6481 return;
6482 }
6483 let selections = self
6484 .selections
6485 .all::<usize>(cx)
6486 .into_iter()
6487 .map(|s| s.range());
6488
6489 self.transact(window, cx, |this, window, cx| {
6490 this.buffer.update(cx, |buffer, cx| {
6491 buffer.autoindent_ranges(selections, cx);
6492 });
6493 let selections = this.selections.all::<usize>(cx);
6494 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6495 s.select(selections)
6496 });
6497 });
6498 }
6499
6500 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6501 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6502 let selections = self.selections.all::<Point>(cx);
6503
6504 let mut new_cursors = Vec::new();
6505 let mut edit_ranges = Vec::new();
6506 let mut selections = selections.iter().peekable();
6507 while let Some(selection) = selections.next() {
6508 let mut rows = selection.spanned_rows(false, &display_map);
6509 let goal_display_column = selection.head().to_display_point(&display_map).column();
6510
6511 // Accumulate contiguous regions of rows that we want to delete.
6512 while let Some(next_selection) = selections.peek() {
6513 let next_rows = next_selection.spanned_rows(false, &display_map);
6514 if next_rows.start <= rows.end {
6515 rows.end = next_rows.end;
6516 selections.next().unwrap();
6517 } else {
6518 break;
6519 }
6520 }
6521
6522 let buffer = &display_map.buffer_snapshot;
6523 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6524 let edit_end;
6525 let cursor_buffer_row;
6526 if buffer.max_point().row >= rows.end.0 {
6527 // If there's a line after the range, delete the \n from the end of the row range
6528 // and position the cursor on the next line.
6529 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6530 cursor_buffer_row = rows.end;
6531 } else {
6532 // If there isn't a line after the range, delete the \n from the line before the
6533 // start of the row range and position the cursor there.
6534 edit_start = edit_start.saturating_sub(1);
6535 edit_end = buffer.len();
6536 cursor_buffer_row = rows.start.previous_row();
6537 }
6538
6539 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6540 *cursor.column_mut() =
6541 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6542
6543 new_cursors.push((
6544 selection.id,
6545 buffer.anchor_after(cursor.to_point(&display_map)),
6546 ));
6547 edit_ranges.push(edit_start..edit_end);
6548 }
6549
6550 self.transact(window, cx, |this, window, cx| {
6551 let buffer = this.buffer.update(cx, |buffer, cx| {
6552 let empty_str: Arc<str> = Arc::default();
6553 buffer.edit(
6554 edit_ranges
6555 .into_iter()
6556 .map(|range| (range, empty_str.clone())),
6557 None,
6558 cx,
6559 );
6560 buffer.snapshot(cx)
6561 });
6562 let new_selections = new_cursors
6563 .into_iter()
6564 .map(|(id, cursor)| {
6565 let cursor = cursor.to_point(&buffer);
6566 Selection {
6567 id,
6568 start: cursor,
6569 end: cursor,
6570 reversed: false,
6571 goal: SelectionGoal::None,
6572 }
6573 })
6574 .collect();
6575
6576 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6577 s.select(new_selections);
6578 });
6579 });
6580 }
6581
6582 pub fn join_lines_impl(
6583 &mut self,
6584 insert_whitespace: bool,
6585 window: &mut Window,
6586 cx: &mut Context<Self>,
6587 ) {
6588 if self.read_only(cx) {
6589 return;
6590 }
6591 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6592 for selection in self.selections.all::<Point>(cx) {
6593 let start = MultiBufferRow(selection.start.row);
6594 // Treat single line selections as if they include the next line. Otherwise this action
6595 // would do nothing for single line selections individual cursors.
6596 let end = if selection.start.row == selection.end.row {
6597 MultiBufferRow(selection.start.row + 1)
6598 } else {
6599 MultiBufferRow(selection.end.row)
6600 };
6601
6602 if let Some(last_row_range) = row_ranges.last_mut() {
6603 if start <= last_row_range.end {
6604 last_row_range.end = end;
6605 continue;
6606 }
6607 }
6608 row_ranges.push(start..end);
6609 }
6610
6611 let snapshot = self.buffer.read(cx).snapshot(cx);
6612 let mut cursor_positions = Vec::new();
6613 for row_range in &row_ranges {
6614 let anchor = snapshot.anchor_before(Point::new(
6615 row_range.end.previous_row().0,
6616 snapshot.line_len(row_range.end.previous_row()),
6617 ));
6618 cursor_positions.push(anchor..anchor);
6619 }
6620
6621 self.transact(window, cx, |this, window, cx| {
6622 for row_range in row_ranges.into_iter().rev() {
6623 for row in row_range.iter_rows().rev() {
6624 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6625 let next_line_row = row.next_row();
6626 let indent = snapshot.indent_size_for_line(next_line_row);
6627 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6628
6629 let replace =
6630 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6631 " "
6632 } else {
6633 ""
6634 };
6635
6636 this.buffer.update(cx, |buffer, cx| {
6637 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6638 });
6639 }
6640 }
6641
6642 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6643 s.select_anchor_ranges(cursor_positions)
6644 });
6645 });
6646 }
6647
6648 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6649 self.join_lines_impl(true, window, cx);
6650 }
6651
6652 pub fn sort_lines_case_sensitive(
6653 &mut self,
6654 _: &SortLinesCaseSensitive,
6655 window: &mut Window,
6656 cx: &mut Context<Self>,
6657 ) {
6658 self.manipulate_lines(window, cx, |lines| lines.sort())
6659 }
6660
6661 pub fn sort_lines_case_insensitive(
6662 &mut self,
6663 _: &SortLinesCaseInsensitive,
6664 window: &mut Window,
6665 cx: &mut Context<Self>,
6666 ) {
6667 self.manipulate_lines(window, cx, |lines| {
6668 lines.sort_by_key(|line| line.to_lowercase())
6669 })
6670 }
6671
6672 pub fn unique_lines_case_insensitive(
6673 &mut self,
6674 _: &UniqueLinesCaseInsensitive,
6675 window: &mut Window,
6676 cx: &mut Context<Self>,
6677 ) {
6678 self.manipulate_lines(window, cx, |lines| {
6679 let mut seen = HashSet::default();
6680 lines.retain(|line| seen.insert(line.to_lowercase()));
6681 })
6682 }
6683
6684 pub fn unique_lines_case_sensitive(
6685 &mut self,
6686 _: &UniqueLinesCaseSensitive,
6687 window: &mut Window,
6688 cx: &mut Context<Self>,
6689 ) {
6690 self.manipulate_lines(window, cx, |lines| {
6691 let mut seen = HashSet::default();
6692 lines.retain(|line| seen.insert(*line));
6693 })
6694 }
6695
6696 pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
6697 let mut revert_changes = HashMap::default();
6698 let snapshot = self.snapshot(window, cx);
6699 for hunk in snapshot
6700 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
6701 {
6702 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6703 }
6704 if !revert_changes.is_empty() {
6705 self.transact(window, cx, |editor, window, cx| {
6706 editor.revert(revert_changes, window, cx);
6707 });
6708 }
6709 }
6710
6711 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
6712 let Some(project) = self.project.clone() else {
6713 return;
6714 };
6715 self.reload(project, window, cx)
6716 .detach_and_notify_err(window, cx);
6717 }
6718
6719 pub fn revert_selected_hunks(
6720 &mut self,
6721 _: &RevertSelectedHunks,
6722 window: &mut Window,
6723 cx: &mut Context<Self>,
6724 ) {
6725 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
6726 self.revert_hunks_in_ranges(selections, window, cx);
6727 }
6728
6729 fn revert_hunks_in_ranges(
6730 &mut self,
6731 ranges: impl Iterator<Item = Range<Point>>,
6732 window: &mut Window,
6733 cx: &mut Context<Editor>,
6734 ) {
6735 let mut revert_changes = HashMap::default();
6736 let snapshot = self.snapshot(window, cx);
6737 for hunk in &snapshot.hunks_for_ranges(ranges) {
6738 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6739 }
6740 if !revert_changes.is_empty() {
6741 self.transact(window, cx, |editor, window, cx| {
6742 editor.revert(revert_changes, window, cx);
6743 });
6744 }
6745 }
6746
6747 pub fn open_active_item_in_terminal(
6748 &mut self,
6749 _: &OpenInTerminal,
6750 window: &mut Window,
6751 cx: &mut Context<Self>,
6752 ) {
6753 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6754 let project_path = buffer.read(cx).project_path(cx)?;
6755 let project = self.project.as_ref()?.read(cx);
6756 let entry = project.entry_for_path(&project_path, cx)?;
6757 let parent = match &entry.canonical_path {
6758 Some(canonical_path) => canonical_path.to_path_buf(),
6759 None => project.absolute_path(&project_path, cx)?,
6760 }
6761 .parent()?
6762 .to_path_buf();
6763 Some(parent)
6764 }) {
6765 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
6766 }
6767 }
6768
6769 pub fn prepare_revert_change(
6770 &self,
6771 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6772 hunk: &MultiBufferDiffHunk,
6773 cx: &mut App,
6774 ) -> Option<()> {
6775 let buffer = self.buffer.read(cx);
6776 let change_set = buffer.change_set_for(hunk.buffer_id)?;
6777 let buffer = buffer.buffer(hunk.buffer_id)?;
6778 let buffer = buffer.read(cx);
6779 let original_text = change_set
6780 .read(cx)
6781 .base_text
6782 .as_ref()?
6783 .as_rope()
6784 .slice(hunk.diff_base_byte_range.clone());
6785 let buffer_snapshot = buffer.snapshot();
6786 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6787 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6788 probe
6789 .0
6790 .start
6791 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6792 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6793 }) {
6794 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6795 Some(())
6796 } else {
6797 None
6798 }
6799 }
6800
6801 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
6802 self.manipulate_lines(window, cx, |lines| lines.reverse())
6803 }
6804
6805 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
6806 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
6807 }
6808
6809 fn manipulate_lines<Fn>(
6810 &mut self,
6811 window: &mut Window,
6812 cx: &mut Context<Self>,
6813 mut callback: Fn,
6814 ) where
6815 Fn: FnMut(&mut Vec<&str>),
6816 {
6817 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6818 let buffer = self.buffer.read(cx).snapshot(cx);
6819
6820 let mut edits = Vec::new();
6821
6822 let selections = self.selections.all::<Point>(cx);
6823 let mut selections = selections.iter().peekable();
6824 let mut contiguous_row_selections = Vec::new();
6825 let mut new_selections = Vec::new();
6826 let mut added_lines = 0;
6827 let mut removed_lines = 0;
6828
6829 while let Some(selection) = selections.next() {
6830 let (start_row, end_row) = consume_contiguous_rows(
6831 &mut contiguous_row_selections,
6832 selection,
6833 &display_map,
6834 &mut selections,
6835 );
6836
6837 let start_point = Point::new(start_row.0, 0);
6838 let end_point = Point::new(
6839 end_row.previous_row().0,
6840 buffer.line_len(end_row.previous_row()),
6841 );
6842 let text = buffer
6843 .text_for_range(start_point..end_point)
6844 .collect::<String>();
6845
6846 let mut lines = text.split('\n').collect_vec();
6847
6848 let lines_before = lines.len();
6849 callback(&mut lines);
6850 let lines_after = lines.len();
6851
6852 edits.push((start_point..end_point, lines.join("\n")));
6853
6854 // Selections must change based on added and removed line count
6855 let start_row =
6856 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6857 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6858 new_selections.push(Selection {
6859 id: selection.id,
6860 start: start_row,
6861 end: end_row,
6862 goal: SelectionGoal::None,
6863 reversed: selection.reversed,
6864 });
6865
6866 if lines_after > lines_before {
6867 added_lines += lines_after - lines_before;
6868 } else if lines_before > lines_after {
6869 removed_lines += lines_before - lines_after;
6870 }
6871 }
6872
6873 self.transact(window, cx, |this, window, cx| {
6874 let buffer = this.buffer.update(cx, |buffer, cx| {
6875 buffer.edit(edits, None, cx);
6876 buffer.snapshot(cx)
6877 });
6878
6879 // Recalculate offsets on newly edited buffer
6880 let new_selections = new_selections
6881 .iter()
6882 .map(|s| {
6883 let start_point = Point::new(s.start.0, 0);
6884 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6885 Selection {
6886 id: s.id,
6887 start: buffer.point_to_offset(start_point),
6888 end: buffer.point_to_offset(end_point),
6889 goal: s.goal,
6890 reversed: s.reversed,
6891 }
6892 })
6893 .collect();
6894
6895 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6896 s.select(new_selections);
6897 });
6898
6899 this.request_autoscroll(Autoscroll::fit(), cx);
6900 });
6901 }
6902
6903 pub fn convert_to_upper_case(
6904 &mut self,
6905 _: &ConvertToUpperCase,
6906 window: &mut Window,
6907 cx: &mut Context<Self>,
6908 ) {
6909 self.manipulate_text(window, cx, |text| text.to_uppercase())
6910 }
6911
6912 pub fn convert_to_lower_case(
6913 &mut self,
6914 _: &ConvertToLowerCase,
6915 window: &mut Window,
6916 cx: &mut Context<Self>,
6917 ) {
6918 self.manipulate_text(window, cx, |text| text.to_lowercase())
6919 }
6920
6921 pub fn convert_to_title_case(
6922 &mut self,
6923 _: &ConvertToTitleCase,
6924 window: &mut Window,
6925 cx: &mut Context<Self>,
6926 ) {
6927 self.manipulate_text(window, cx, |text| {
6928 text.split('\n')
6929 .map(|line| line.to_case(Case::Title))
6930 .join("\n")
6931 })
6932 }
6933
6934 pub fn convert_to_snake_case(
6935 &mut self,
6936 _: &ConvertToSnakeCase,
6937 window: &mut Window,
6938 cx: &mut Context<Self>,
6939 ) {
6940 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
6941 }
6942
6943 pub fn convert_to_kebab_case(
6944 &mut self,
6945 _: &ConvertToKebabCase,
6946 window: &mut Window,
6947 cx: &mut Context<Self>,
6948 ) {
6949 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
6950 }
6951
6952 pub fn convert_to_upper_camel_case(
6953 &mut self,
6954 _: &ConvertToUpperCamelCase,
6955 window: &mut Window,
6956 cx: &mut Context<Self>,
6957 ) {
6958 self.manipulate_text(window, cx, |text| {
6959 text.split('\n')
6960 .map(|line| line.to_case(Case::UpperCamel))
6961 .join("\n")
6962 })
6963 }
6964
6965 pub fn convert_to_lower_camel_case(
6966 &mut self,
6967 _: &ConvertToLowerCamelCase,
6968 window: &mut Window,
6969 cx: &mut Context<Self>,
6970 ) {
6971 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
6972 }
6973
6974 pub fn convert_to_opposite_case(
6975 &mut self,
6976 _: &ConvertToOppositeCase,
6977 window: &mut Window,
6978 cx: &mut Context<Self>,
6979 ) {
6980 self.manipulate_text(window, cx, |text| {
6981 text.chars()
6982 .fold(String::with_capacity(text.len()), |mut t, c| {
6983 if c.is_uppercase() {
6984 t.extend(c.to_lowercase());
6985 } else {
6986 t.extend(c.to_uppercase());
6987 }
6988 t
6989 })
6990 })
6991 }
6992
6993 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
6994 where
6995 Fn: FnMut(&str) -> String,
6996 {
6997 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6998 let buffer = self.buffer.read(cx).snapshot(cx);
6999
7000 let mut new_selections = Vec::new();
7001 let mut edits = Vec::new();
7002 let mut selection_adjustment = 0i32;
7003
7004 for selection in self.selections.all::<usize>(cx) {
7005 let selection_is_empty = selection.is_empty();
7006
7007 let (start, end) = if selection_is_empty {
7008 let word_range = movement::surrounding_word(
7009 &display_map,
7010 selection.start.to_display_point(&display_map),
7011 );
7012 let start = word_range.start.to_offset(&display_map, Bias::Left);
7013 let end = word_range.end.to_offset(&display_map, Bias::Left);
7014 (start, end)
7015 } else {
7016 (selection.start, selection.end)
7017 };
7018
7019 let text = buffer.text_for_range(start..end).collect::<String>();
7020 let old_length = text.len() as i32;
7021 let text = callback(&text);
7022
7023 new_selections.push(Selection {
7024 start: (start as i32 - selection_adjustment) as usize,
7025 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
7026 goal: SelectionGoal::None,
7027 ..selection
7028 });
7029
7030 selection_adjustment += old_length - text.len() as i32;
7031
7032 edits.push((start..end, text));
7033 }
7034
7035 self.transact(window, cx, |this, window, cx| {
7036 this.buffer.update(cx, |buffer, cx| {
7037 buffer.edit(edits, None, cx);
7038 });
7039
7040 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7041 s.select(new_selections);
7042 });
7043
7044 this.request_autoscroll(Autoscroll::fit(), cx);
7045 });
7046 }
7047
7048 pub fn duplicate(
7049 &mut self,
7050 upwards: bool,
7051 whole_lines: bool,
7052 window: &mut Window,
7053 cx: &mut Context<Self>,
7054 ) {
7055 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7056 let buffer = &display_map.buffer_snapshot;
7057 let selections = self.selections.all::<Point>(cx);
7058
7059 let mut edits = Vec::new();
7060 let mut selections_iter = selections.iter().peekable();
7061 while let Some(selection) = selections_iter.next() {
7062 let mut rows = selection.spanned_rows(false, &display_map);
7063 // duplicate line-wise
7064 if whole_lines || selection.start == selection.end {
7065 // Avoid duplicating the same lines twice.
7066 while let Some(next_selection) = selections_iter.peek() {
7067 let next_rows = next_selection.spanned_rows(false, &display_map);
7068 if next_rows.start < rows.end {
7069 rows.end = next_rows.end;
7070 selections_iter.next().unwrap();
7071 } else {
7072 break;
7073 }
7074 }
7075
7076 // Copy the text from the selected row region and splice it either at the start
7077 // or end of the region.
7078 let start = Point::new(rows.start.0, 0);
7079 let end = Point::new(
7080 rows.end.previous_row().0,
7081 buffer.line_len(rows.end.previous_row()),
7082 );
7083 let text = buffer
7084 .text_for_range(start..end)
7085 .chain(Some("\n"))
7086 .collect::<String>();
7087 let insert_location = if upwards {
7088 Point::new(rows.end.0, 0)
7089 } else {
7090 start
7091 };
7092 edits.push((insert_location..insert_location, text));
7093 } else {
7094 // duplicate character-wise
7095 let start = selection.start;
7096 let end = selection.end;
7097 let text = buffer.text_for_range(start..end).collect::<String>();
7098 edits.push((selection.end..selection.end, text));
7099 }
7100 }
7101
7102 self.transact(window, cx, |this, _, cx| {
7103 this.buffer.update(cx, |buffer, cx| {
7104 buffer.edit(edits, None, cx);
7105 });
7106
7107 this.request_autoscroll(Autoscroll::fit(), cx);
7108 });
7109 }
7110
7111 pub fn duplicate_line_up(
7112 &mut self,
7113 _: &DuplicateLineUp,
7114 window: &mut Window,
7115 cx: &mut Context<Self>,
7116 ) {
7117 self.duplicate(true, true, window, cx);
7118 }
7119
7120 pub fn duplicate_line_down(
7121 &mut self,
7122 _: &DuplicateLineDown,
7123 window: &mut Window,
7124 cx: &mut Context<Self>,
7125 ) {
7126 self.duplicate(false, true, window, cx);
7127 }
7128
7129 pub fn duplicate_selection(
7130 &mut self,
7131 _: &DuplicateSelection,
7132 window: &mut Window,
7133 cx: &mut Context<Self>,
7134 ) {
7135 self.duplicate(false, false, window, cx);
7136 }
7137
7138 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7139 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7140 let buffer = self.buffer.read(cx).snapshot(cx);
7141
7142 let mut edits = Vec::new();
7143 let mut unfold_ranges = Vec::new();
7144 let mut refold_creases = Vec::new();
7145
7146 let selections = self.selections.all::<Point>(cx);
7147 let mut selections = selections.iter().peekable();
7148 let mut contiguous_row_selections = Vec::new();
7149 let mut new_selections = Vec::new();
7150
7151 while let Some(selection) = selections.next() {
7152 // Find all the selections that span a contiguous row range
7153 let (start_row, end_row) = consume_contiguous_rows(
7154 &mut contiguous_row_selections,
7155 selection,
7156 &display_map,
7157 &mut selections,
7158 );
7159
7160 // Move the text spanned by the row range to be before the line preceding the row range
7161 if start_row.0 > 0 {
7162 let range_to_move = Point::new(
7163 start_row.previous_row().0,
7164 buffer.line_len(start_row.previous_row()),
7165 )
7166 ..Point::new(
7167 end_row.previous_row().0,
7168 buffer.line_len(end_row.previous_row()),
7169 );
7170 let insertion_point = display_map
7171 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7172 .0;
7173
7174 // Don't move lines across excerpts
7175 if buffer
7176 .excerpt_containing(insertion_point..range_to_move.end)
7177 .is_some()
7178 {
7179 let text = buffer
7180 .text_for_range(range_to_move.clone())
7181 .flat_map(|s| s.chars())
7182 .skip(1)
7183 .chain(['\n'])
7184 .collect::<String>();
7185
7186 edits.push((
7187 buffer.anchor_after(range_to_move.start)
7188 ..buffer.anchor_before(range_to_move.end),
7189 String::new(),
7190 ));
7191 let insertion_anchor = buffer.anchor_after(insertion_point);
7192 edits.push((insertion_anchor..insertion_anchor, text));
7193
7194 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7195
7196 // Move selections up
7197 new_selections.extend(contiguous_row_selections.drain(..).map(
7198 |mut selection| {
7199 selection.start.row -= row_delta;
7200 selection.end.row -= row_delta;
7201 selection
7202 },
7203 ));
7204
7205 // Move folds up
7206 unfold_ranges.push(range_to_move.clone());
7207 for fold in display_map.folds_in_range(
7208 buffer.anchor_before(range_to_move.start)
7209 ..buffer.anchor_after(range_to_move.end),
7210 ) {
7211 let mut start = fold.range.start.to_point(&buffer);
7212 let mut end = fold.range.end.to_point(&buffer);
7213 start.row -= row_delta;
7214 end.row -= row_delta;
7215 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7216 }
7217 }
7218 }
7219
7220 // If we didn't move line(s), preserve the existing selections
7221 new_selections.append(&mut contiguous_row_selections);
7222 }
7223
7224 self.transact(window, cx, |this, window, cx| {
7225 this.unfold_ranges(&unfold_ranges, true, true, cx);
7226 this.buffer.update(cx, |buffer, cx| {
7227 for (range, text) in edits {
7228 buffer.edit([(range, text)], None, cx);
7229 }
7230 });
7231 this.fold_creases(refold_creases, true, window, cx);
7232 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7233 s.select(new_selections);
7234 })
7235 });
7236 }
7237
7238 pub fn move_line_down(
7239 &mut self,
7240 _: &MoveLineDown,
7241 window: &mut Window,
7242 cx: &mut Context<Self>,
7243 ) {
7244 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7245 let buffer = self.buffer.read(cx).snapshot(cx);
7246
7247 let mut edits = Vec::new();
7248 let mut unfold_ranges = Vec::new();
7249 let mut refold_creases = Vec::new();
7250
7251 let selections = self.selections.all::<Point>(cx);
7252 let mut selections = selections.iter().peekable();
7253 let mut contiguous_row_selections = Vec::new();
7254 let mut new_selections = Vec::new();
7255
7256 while let Some(selection) = selections.next() {
7257 // Find all the selections that span a contiguous row range
7258 let (start_row, end_row) = consume_contiguous_rows(
7259 &mut contiguous_row_selections,
7260 selection,
7261 &display_map,
7262 &mut selections,
7263 );
7264
7265 // Move the text spanned by the row range to be after the last line of the row range
7266 if end_row.0 <= buffer.max_point().row {
7267 let range_to_move =
7268 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7269 let insertion_point = display_map
7270 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7271 .0;
7272
7273 // Don't move lines across excerpt boundaries
7274 if buffer
7275 .excerpt_containing(range_to_move.start..insertion_point)
7276 .is_some()
7277 {
7278 let mut text = String::from("\n");
7279 text.extend(buffer.text_for_range(range_to_move.clone()));
7280 text.pop(); // Drop trailing newline
7281 edits.push((
7282 buffer.anchor_after(range_to_move.start)
7283 ..buffer.anchor_before(range_to_move.end),
7284 String::new(),
7285 ));
7286 let insertion_anchor = buffer.anchor_after(insertion_point);
7287 edits.push((insertion_anchor..insertion_anchor, text));
7288
7289 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7290
7291 // Move selections down
7292 new_selections.extend(contiguous_row_selections.drain(..).map(
7293 |mut selection| {
7294 selection.start.row += row_delta;
7295 selection.end.row += row_delta;
7296 selection
7297 },
7298 ));
7299
7300 // Move folds down
7301 unfold_ranges.push(range_to_move.clone());
7302 for fold in display_map.folds_in_range(
7303 buffer.anchor_before(range_to_move.start)
7304 ..buffer.anchor_after(range_to_move.end),
7305 ) {
7306 let mut start = fold.range.start.to_point(&buffer);
7307 let mut end = fold.range.end.to_point(&buffer);
7308 start.row += row_delta;
7309 end.row += row_delta;
7310 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7311 }
7312 }
7313 }
7314
7315 // If we didn't move line(s), preserve the existing selections
7316 new_selections.append(&mut contiguous_row_selections);
7317 }
7318
7319 self.transact(window, cx, |this, window, cx| {
7320 this.unfold_ranges(&unfold_ranges, true, true, cx);
7321 this.buffer.update(cx, |buffer, cx| {
7322 for (range, text) in edits {
7323 buffer.edit([(range, text)], None, cx);
7324 }
7325 });
7326 this.fold_creases(refold_creases, true, window, cx);
7327 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7328 s.select(new_selections)
7329 });
7330 });
7331 }
7332
7333 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7334 let text_layout_details = &self.text_layout_details(window);
7335 self.transact(window, cx, |this, window, cx| {
7336 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7337 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7338 let line_mode = s.line_mode;
7339 s.move_with(|display_map, selection| {
7340 if !selection.is_empty() || line_mode {
7341 return;
7342 }
7343
7344 let mut head = selection.head();
7345 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7346 if head.column() == display_map.line_len(head.row()) {
7347 transpose_offset = display_map
7348 .buffer_snapshot
7349 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7350 }
7351
7352 if transpose_offset == 0 {
7353 return;
7354 }
7355
7356 *head.column_mut() += 1;
7357 head = display_map.clip_point(head, Bias::Right);
7358 let goal = SelectionGoal::HorizontalPosition(
7359 display_map
7360 .x_for_display_point(head, text_layout_details)
7361 .into(),
7362 );
7363 selection.collapse_to(head, goal);
7364
7365 let transpose_start = display_map
7366 .buffer_snapshot
7367 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7368 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7369 let transpose_end = display_map
7370 .buffer_snapshot
7371 .clip_offset(transpose_offset + 1, Bias::Right);
7372 if let Some(ch) =
7373 display_map.buffer_snapshot.chars_at(transpose_start).next()
7374 {
7375 edits.push((transpose_start..transpose_offset, String::new()));
7376 edits.push((transpose_end..transpose_end, ch.to_string()));
7377 }
7378 }
7379 });
7380 edits
7381 });
7382 this.buffer
7383 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7384 let selections = this.selections.all::<usize>(cx);
7385 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7386 s.select(selections);
7387 });
7388 });
7389 }
7390
7391 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7392 self.rewrap_impl(IsVimMode::No, cx)
7393 }
7394
7395 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7396 let buffer = self.buffer.read(cx).snapshot(cx);
7397 let selections = self.selections.all::<Point>(cx);
7398 let mut selections = selections.iter().peekable();
7399
7400 let mut edits = Vec::new();
7401 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7402
7403 while let Some(selection) = selections.next() {
7404 let mut start_row = selection.start.row;
7405 let mut end_row = selection.end.row;
7406
7407 // Skip selections that overlap with a range that has already been rewrapped.
7408 let selection_range = start_row..end_row;
7409 if rewrapped_row_ranges
7410 .iter()
7411 .any(|range| range.overlaps(&selection_range))
7412 {
7413 continue;
7414 }
7415
7416 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7417
7418 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7419 match language_scope.language_name().as_ref() {
7420 "Markdown" | "Plain Text" => {
7421 should_rewrap = true;
7422 }
7423 _ => {}
7424 }
7425 }
7426
7427 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7428
7429 // Since not all lines in the selection may be at the same indent
7430 // level, choose the indent size that is the most common between all
7431 // of the lines.
7432 //
7433 // If there is a tie, we use the deepest indent.
7434 let (indent_size, indent_end) = {
7435 let mut indent_size_occurrences = HashMap::default();
7436 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7437
7438 for row in start_row..=end_row {
7439 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7440 rows_by_indent_size.entry(indent).or_default().push(row);
7441 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7442 }
7443
7444 let indent_size = indent_size_occurrences
7445 .into_iter()
7446 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7447 .map(|(indent, _)| indent)
7448 .unwrap_or_default();
7449 let row = rows_by_indent_size[&indent_size][0];
7450 let indent_end = Point::new(row, indent_size.len);
7451
7452 (indent_size, indent_end)
7453 };
7454
7455 let mut line_prefix = indent_size.chars().collect::<String>();
7456
7457 if let Some(comment_prefix) =
7458 buffer
7459 .language_scope_at(selection.head())
7460 .and_then(|language| {
7461 language
7462 .line_comment_prefixes()
7463 .iter()
7464 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7465 .cloned()
7466 })
7467 {
7468 line_prefix.push_str(&comment_prefix);
7469 should_rewrap = true;
7470 }
7471
7472 if !should_rewrap {
7473 continue;
7474 }
7475
7476 if selection.is_empty() {
7477 'expand_upwards: while start_row > 0 {
7478 let prev_row = start_row - 1;
7479 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7480 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7481 {
7482 start_row = prev_row;
7483 } else {
7484 break 'expand_upwards;
7485 }
7486 }
7487
7488 'expand_downwards: while end_row < buffer.max_point().row {
7489 let next_row = end_row + 1;
7490 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7491 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7492 {
7493 end_row = next_row;
7494 } else {
7495 break 'expand_downwards;
7496 }
7497 }
7498 }
7499
7500 let start = Point::new(start_row, 0);
7501 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7502 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7503 let Some(lines_without_prefixes) = selection_text
7504 .lines()
7505 .map(|line| {
7506 line.strip_prefix(&line_prefix)
7507 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7508 .ok_or_else(|| {
7509 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7510 })
7511 })
7512 .collect::<Result<Vec<_>, _>>()
7513 .log_err()
7514 else {
7515 continue;
7516 };
7517
7518 let wrap_column = buffer
7519 .settings_at(Point::new(start_row, 0), cx)
7520 .preferred_line_length as usize;
7521 let wrapped_text = wrap_with_prefix(
7522 line_prefix,
7523 lines_without_prefixes.join(" "),
7524 wrap_column,
7525 tab_size,
7526 );
7527
7528 // TODO: should always use char-based diff while still supporting cursor behavior that
7529 // matches vim.
7530 let diff = match is_vim_mode {
7531 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7532 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7533 };
7534 let mut offset = start.to_offset(&buffer);
7535 let mut moved_since_edit = true;
7536
7537 for change in diff.iter_all_changes() {
7538 let value = change.value();
7539 match change.tag() {
7540 ChangeTag::Equal => {
7541 offset += value.len();
7542 moved_since_edit = true;
7543 }
7544 ChangeTag::Delete => {
7545 let start = buffer.anchor_after(offset);
7546 let end = buffer.anchor_before(offset + value.len());
7547
7548 if moved_since_edit {
7549 edits.push((start..end, String::new()));
7550 } else {
7551 edits.last_mut().unwrap().0.end = end;
7552 }
7553
7554 offset += value.len();
7555 moved_since_edit = false;
7556 }
7557 ChangeTag::Insert => {
7558 if moved_since_edit {
7559 let anchor = buffer.anchor_after(offset);
7560 edits.push((anchor..anchor, value.to_string()));
7561 } else {
7562 edits.last_mut().unwrap().1.push_str(value);
7563 }
7564
7565 moved_since_edit = false;
7566 }
7567 }
7568 }
7569
7570 rewrapped_row_ranges.push(start_row..=end_row);
7571 }
7572
7573 self.buffer
7574 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7575 }
7576
7577 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7578 let mut text = String::new();
7579 let buffer = self.buffer.read(cx).snapshot(cx);
7580 let mut selections = self.selections.all::<Point>(cx);
7581 let mut clipboard_selections = Vec::with_capacity(selections.len());
7582 {
7583 let max_point = buffer.max_point();
7584 let mut is_first = true;
7585 for selection in &mut selections {
7586 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7587 if is_entire_line {
7588 selection.start = Point::new(selection.start.row, 0);
7589 if !selection.is_empty() && selection.end.column == 0 {
7590 selection.end = cmp::min(max_point, selection.end);
7591 } else {
7592 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7593 }
7594 selection.goal = SelectionGoal::None;
7595 }
7596 if is_first {
7597 is_first = false;
7598 } else {
7599 text += "\n";
7600 }
7601 let mut len = 0;
7602 for chunk in buffer.text_for_range(selection.start..selection.end) {
7603 text.push_str(chunk);
7604 len += chunk.len();
7605 }
7606 clipboard_selections.push(ClipboardSelection {
7607 len,
7608 is_entire_line,
7609 first_line_indent: buffer
7610 .indent_size_for_line(MultiBufferRow(selection.start.row))
7611 .len,
7612 });
7613 }
7614 }
7615
7616 self.transact(window, cx, |this, window, cx| {
7617 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7618 s.select(selections);
7619 });
7620 this.insert("", window, cx);
7621 });
7622 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7623 }
7624
7625 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
7626 let item = self.cut_common(window, cx);
7627 cx.write_to_clipboard(item);
7628 }
7629
7630 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
7631 self.change_selections(None, window, cx, |s| {
7632 s.move_with(|snapshot, sel| {
7633 if sel.is_empty() {
7634 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7635 }
7636 });
7637 });
7638 let item = self.cut_common(window, cx);
7639 cx.set_global(KillRing(item))
7640 }
7641
7642 pub fn kill_ring_yank(
7643 &mut self,
7644 _: &KillRingYank,
7645 window: &mut Window,
7646 cx: &mut Context<Self>,
7647 ) {
7648 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7649 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7650 (kill_ring.text().to_string(), kill_ring.metadata_json())
7651 } else {
7652 return;
7653 }
7654 } else {
7655 return;
7656 };
7657 self.do_paste(&text, metadata, false, window, cx);
7658 }
7659
7660 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
7661 let selections = self.selections.all::<Point>(cx);
7662 let buffer = self.buffer.read(cx).read(cx);
7663 let mut text = String::new();
7664
7665 let mut clipboard_selections = Vec::with_capacity(selections.len());
7666 {
7667 let max_point = buffer.max_point();
7668 let mut is_first = true;
7669 for selection in selections.iter() {
7670 let mut start = selection.start;
7671 let mut end = selection.end;
7672 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7673 if is_entire_line {
7674 start = Point::new(start.row, 0);
7675 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7676 }
7677 if is_first {
7678 is_first = false;
7679 } else {
7680 text += "\n";
7681 }
7682 let mut len = 0;
7683 for chunk in buffer.text_for_range(start..end) {
7684 text.push_str(chunk);
7685 len += chunk.len();
7686 }
7687 clipboard_selections.push(ClipboardSelection {
7688 len,
7689 is_entire_line,
7690 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7691 });
7692 }
7693 }
7694
7695 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7696 text,
7697 clipboard_selections,
7698 ));
7699 }
7700
7701 pub fn do_paste(
7702 &mut self,
7703 text: &String,
7704 clipboard_selections: Option<Vec<ClipboardSelection>>,
7705 handle_entire_lines: bool,
7706 window: &mut Window,
7707 cx: &mut Context<Self>,
7708 ) {
7709 if self.read_only(cx) {
7710 return;
7711 }
7712
7713 let clipboard_text = Cow::Borrowed(text);
7714
7715 self.transact(window, cx, |this, window, cx| {
7716 if let Some(mut clipboard_selections) = clipboard_selections {
7717 let old_selections = this.selections.all::<usize>(cx);
7718 let all_selections_were_entire_line =
7719 clipboard_selections.iter().all(|s| s.is_entire_line);
7720 let first_selection_indent_column =
7721 clipboard_selections.first().map(|s| s.first_line_indent);
7722 if clipboard_selections.len() != old_selections.len() {
7723 clipboard_selections.drain(..);
7724 }
7725 let cursor_offset = this.selections.last::<usize>(cx).head();
7726 let mut auto_indent_on_paste = true;
7727
7728 this.buffer.update(cx, |buffer, cx| {
7729 let snapshot = buffer.read(cx);
7730 auto_indent_on_paste =
7731 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7732
7733 let mut start_offset = 0;
7734 let mut edits = Vec::new();
7735 let mut original_indent_columns = Vec::new();
7736 for (ix, selection) in old_selections.iter().enumerate() {
7737 let to_insert;
7738 let entire_line;
7739 let original_indent_column;
7740 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7741 let end_offset = start_offset + clipboard_selection.len;
7742 to_insert = &clipboard_text[start_offset..end_offset];
7743 entire_line = clipboard_selection.is_entire_line;
7744 start_offset = end_offset + 1;
7745 original_indent_column = Some(clipboard_selection.first_line_indent);
7746 } else {
7747 to_insert = clipboard_text.as_str();
7748 entire_line = all_selections_were_entire_line;
7749 original_indent_column = first_selection_indent_column
7750 }
7751
7752 // If the corresponding selection was empty when this slice of the
7753 // clipboard text was written, then the entire line containing the
7754 // selection was copied. If this selection is also currently empty,
7755 // then paste the line before the current line of the buffer.
7756 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7757 let column = selection.start.to_point(&snapshot).column as usize;
7758 let line_start = selection.start - column;
7759 line_start..line_start
7760 } else {
7761 selection.range()
7762 };
7763
7764 edits.push((range, to_insert));
7765 original_indent_columns.extend(original_indent_column);
7766 }
7767 drop(snapshot);
7768
7769 buffer.edit(
7770 edits,
7771 if auto_indent_on_paste {
7772 Some(AutoindentMode::Block {
7773 original_indent_columns,
7774 })
7775 } else {
7776 None
7777 },
7778 cx,
7779 );
7780 });
7781
7782 let selections = this.selections.all::<usize>(cx);
7783 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7784 s.select(selections)
7785 });
7786 } else {
7787 this.insert(&clipboard_text, window, cx);
7788 }
7789 });
7790 }
7791
7792 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
7793 if let Some(item) = cx.read_from_clipboard() {
7794 let entries = item.entries();
7795
7796 match entries.first() {
7797 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7798 // of all the pasted entries.
7799 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7800 .do_paste(
7801 clipboard_string.text(),
7802 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7803 true,
7804 window,
7805 cx,
7806 ),
7807 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
7808 }
7809 }
7810 }
7811
7812 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
7813 if self.read_only(cx) {
7814 return;
7815 }
7816
7817 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7818 if let Some((selections, _)) =
7819 self.selection_history.transaction(transaction_id).cloned()
7820 {
7821 self.change_selections(None, window, cx, |s| {
7822 s.select_anchors(selections.to_vec());
7823 });
7824 }
7825 self.request_autoscroll(Autoscroll::fit(), cx);
7826 self.unmark_text(window, cx);
7827 self.refresh_inline_completion(true, false, window, cx);
7828 cx.emit(EditorEvent::Edited { transaction_id });
7829 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7830 }
7831 }
7832
7833 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
7834 if self.read_only(cx) {
7835 return;
7836 }
7837
7838 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7839 if let Some((_, Some(selections))) =
7840 self.selection_history.transaction(transaction_id).cloned()
7841 {
7842 self.change_selections(None, window, cx, |s| {
7843 s.select_anchors(selections.to_vec());
7844 });
7845 }
7846 self.request_autoscroll(Autoscroll::fit(), cx);
7847 self.unmark_text(window, cx);
7848 self.refresh_inline_completion(true, false, window, cx);
7849 cx.emit(EditorEvent::Edited { transaction_id });
7850 }
7851 }
7852
7853 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
7854 self.buffer
7855 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7856 }
7857
7858 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
7859 self.buffer
7860 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7861 }
7862
7863 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
7864 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7865 let line_mode = s.line_mode;
7866 s.move_with(|map, selection| {
7867 let cursor = if selection.is_empty() && !line_mode {
7868 movement::left(map, selection.start)
7869 } else {
7870 selection.start
7871 };
7872 selection.collapse_to(cursor, SelectionGoal::None);
7873 });
7874 })
7875 }
7876
7877 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
7878 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7879 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7880 })
7881 }
7882
7883 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
7884 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7885 let line_mode = s.line_mode;
7886 s.move_with(|map, selection| {
7887 let cursor = if selection.is_empty() && !line_mode {
7888 movement::right(map, selection.end)
7889 } else {
7890 selection.end
7891 };
7892 selection.collapse_to(cursor, SelectionGoal::None)
7893 });
7894 })
7895 }
7896
7897 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
7898 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7899 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7900 })
7901 }
7902
7903 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
7904 if self.take_rename(true, window, cx).is_some() {
7905 return;
7906 }
7907
7908 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7909 cx.propagate();
7910 return;
7911 }
7912
7913 let text_layout_details = &self.text_layout_details(window);
7914 let selection_count = self.selections.count();
7915 let first_selection = self.selections.first_anchor();
7916
7917 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7918 let line_mode = s.line_mode;
7919 s.move_with(|map, selection| {
7920 if !selection.is_empty() && !line_mode {
7921 selection.goal = SelectionGoal::None;
7922 }
7923 let (cursor, goal) = movement::up(
7924 map,
7925 selection.start,
7926 selection.goal,
7927 false,
7928 text_layout_details,
7929 );
7930 selection.collapse_to(cursor, goal);
7931 });
7932 });
7933
7934 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7935 {
7936 cx.propagate();
7937 }
7938 }
7939
7940 pub fn move_up_by_lines(
7941 &mut self,
7942 action: &MoveUpByLines,
7943 window: &mut Window,
7944 cx: &mut Context<Self>,
7945 ) {
7946 if self.take_rename(true, window, cx).is_some() {
7947 return;
7948 }
7949
7950 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7951 cx.propagate();
7952 return;
7953 }
7954
7955 let text_layout_details = &self.text_layout_details(window);
7956
7957 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7958 let line_mode = s.line_mode;
7959 s.move_with(|map, selection| {
7960 if !selection.is_empty() && !line_mode {
7961 selection.goal = SelectionGoal::None;
7962 }
7963 let (cursor, goal) = movement::up_by_rows(
7964 map,
7965 selection.start,
7966 action.lines,
7967 selection.goal,
7968 false,
7969 text_layout_details,
7970 );
7971 selection.collapse_to(cursor, goal);
7972 });
7973 })
7974 }
7975
7976 pub fn move_down_by_lines(
7977 &mut self,
7978 action: &MoveDownByLines,
7979 window: &mut Window,
7980 cx: &mut Context<Self>,
7981 ) {
7982 if self.take_rename(true, window, cx).is_some() {
7983 return;
7984 }
7985
7986 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7987 cx.propagate();
7988 return;
7989 }
7990
7991 let text_layout_details = &self.text_layout_details(window);
7992
7993 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7994 let line_mode = s.line_mode;
7995 s.move_with(|map, selection| {
7996 if !selection.is_empty() && !line_mode {
7997 selection.goal = SelectionGoal::None;
7998 }
7999 let (cursor, goal) = movement::down_by_rows(
8000 map,
8001 selection.start,
8002 action.lines,
8003 selection.goal,
8004 false,
8005 text_layout_details,
8006 );
8007 selection.collapse_to(cursor, goal);
8008 });
8009 })
8010 }
8011
8012 pub fn select_down_by_lines(
8013 &mut self,
8014 action: &SelectDownByLines,
8015 window: &mut Window,
8016 cx: &mut Context<Self>,
8017 ) {
8018 let text_layout_details = &self.text_layout_details(window);
8019 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8020 s.move_heads_with(|map, head, goal| {
8021 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
8022 })
8023 })
8024 }
8025
8026 pub fn select_up_by_lines(
8027 &mut self,
8028 action: &SelectUpByLines,
8029 window: &mut Window,
8030 cx: &mut Context<Self>,
8031 ) {
8032 let text_layout_details = &self.text_layout_details(window);
8033 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8034 s.move_heads_with(|map, head, goal| {
8035 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8036 })
8037 })
8038 }
8039
8040 pub fn select_page_up(
8041 &mut self,
8042 _: &SelectPageUp,
8043 window: &mut Window,
8044 cx: &mut Context<Self>,
8045 ) {
8046 let Some(row_count) = self.visible_row_count() else {
8047 return;
8048 };
8049
8050 let text_layout_details = &self.text_layout_details(window);
8051
8052 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8053 s.move_heads_with(|map, head, goal| {
8054 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8055 })
8056 })
8057 }
8058
8059 pub fn move_page_up(
8060 &mut self,
8061 action: &MovePageUp,
8062 window: &mut Window,
8063 cx: &mut Context<Self>,
8064 ) {
8065 if self.take_rename(true, window, cx).is_some() {
8066 return;
8067 }
8068
8069 if self
8070 .context_menu
8071 .borrow_mut()
8072 .as_mut()
8073 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8074 .unwrap_or(false)
8075 {
8076 return;
8077 }
8078
8079 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8080 cx.propagate();
8081 return;
8082 }
8083
8084 let Some(row_count) = self.visible_row_count() else {
8085 return;
8086 };
8087
8088 let autoscroll = if action.center_cursor {
8089 Autoscroll::center()
8090 } else {
8091 Autoscroll::fit()
8092 };
8093
8094 let text_layout_details = &self.text_layout_details(window);
8095
8096 self.change_selections(Some(autoscroll), window, cx, |s| {
8097 let line_mode = s.line_mode;
8098 s.move_with(|map, selection| {
8099 if !selection.is_empty() && !line_mode {
8100 selection.goal = SelectionGoal::None;
8101 }
8102 let (cursor, goal) = movement::up_by_rows(
8103 map,
8104 selection.end,
8105 row_count,
8106 selection.goal,
8107 false,
8108 text_layout_details,
8109 );
8110 selection.collapse_to(cursor, goal);
8111 });
8112 });
8113 }
8114
8115 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8116 let text_layout_details = &self.text_layout_details(window);
8117 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8118 s.move_heads_with(|map, head, goal| {
8119 movement::up(map, head, goal, false, text_layout_details)
8120 })
8121 })
8122 }
8123
8124 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8125 self.take_rename(true, window, cx);
8126
8127 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8128 cx.propagate();
8129 return;
8130 }
8131
8132 let text_layout_details = &self.text_layout_details(window);
8133 let selection_count = self.selections.count();
8134 let first_selection = self.selections.first_anchor();
8135
8136 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8137 let line_mode = s.line_mode;
8138 s.move_with(|map, selection| {
8139 if !selection.is_empty() && !line_mode {
8140 selection.goal = SelectionGoal::None;
8141 }
8142 let (cursor, goal) = movement::down(
8143 map,
8144 selection.end,
8145 selection.goal,
8146 false,
8147 text_layout_details,
8148 );
8149 selection.collapse_to(cursor, goal);
8150 });
8151 });
8152
8153 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8154 {
8155 cx.propagate();
8156 }
8157 }
8158
8159 pub fn select_page_down(
8160 &mut self,
8161 _: &SelectPageDown,
8162 window: &mut Window,
8163 cx: &mut Context<Self>,
8164 ) {
8165 let Some(row_count) = self.visible_row_count() else {
8166 return;
8167 };
8168
8169 let text_layout_details = &self.text_layout_details(window);
8170
8171 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8172 s.move_heads_with(|map, head, goal| {
8173 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8174 })
8175 })
8176 }
8177
8178 pub fn move_page_down(
8179 &mut self,
8180 action: &MovePageDown,
8181 window: &mut Window,
8182 cx: &mut Context<Self>,
8183 ) {
8184 if self.take_rename(true, window, cx).is_some() {
8185 return;
8186 }
8187
8188 if self
8189 .context_menu
8190 .borrow_mut()
8191 .as_mut()
8192 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8193 .unwrap_or(false)
8194 {
8195 return;
8196 }
8197
8198 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8199 cx.propagate();
8200 return;
8201 }
8202
8203 let Some(row_count) = self.visible_row_count() else {
8204 return;
8205 };
8206
8207 let autoscroll = if action.center_cursor {
8208 Autoscroll::center()
8209 } else {
8210 Autoscroll::fit()
8211 };
8212
8213 let text_layout_details = &self.text_layout_details(window);
8214 self.change_selections(Some(autoscroll), window, cx, |s| {
8215 let line_mode = s.line_mode;
8216 s.move_with(|map, selection| {
8217 if !selection.is_empty() && !line_mode {
8218 selection.goal = SelectionGoal::None;
8219 }
8220 let (cursor, goal) = movement::down_by_rows(
8221 map,
8222 selection.end,
8223 row_count,
8224 selection.goal,
8225 false,
8226 text_layout_details,
8227 );
8228 selection.collapse_to(cursor, goal);
8229 });
8230 });
8231 }
8232
8233 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8234 let text_layout_details = &self.text_layout_details(window);
8235 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8236 s.move_heads_with(|map, head, goal| {
8237 movement::down(map, head, goal, false, text_layout_details)
8238 })
8239 });
8240 }
8241
8242 pub fn context_menu_first(
8243 &mut self,
8244 _: &ContextMenuFirst,
8245 _window: &mut Window,
8246 cx: &mut Context<Self>,
8247 ) {
8248 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8249 context_menu.select_first(self.completion_provider.as_deref(), cx);
8250 }
8251 }
8252
8253 pub fn context_menu_prev(
8254 &mut self,
8255 _: &ContextMenuPrev,
8256 _window: &mut Window,
8257 cx: &mut Context<Self>,
8258 ) {
8259 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8260 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8261 }
8262 }
8263
8264 pub fn context_menu_next(
8265 &mut self,
8266 _: &ContextMenuNext,
8267 _window: &mut Window,
8268 cx: &mut Context<Self>,
8269 ) {
8270 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8271 context_menu.select_next(self.completion_provider.as_deref(), cx);
8272 }
8273 }
8274
8275 pub fn context_menu_last(
8276 &mut self,
8277 _: &ContextMenuLast,
8278 _window: &mut Window,
8279 cx: &mut Context<Self>,
8280 ) {
8281 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8282 context_menu.select_last(self.completion_provider.as_deref(), cx);
8283 }
8284 }
8285
8286 pub fn move_to_previous_word_start(
8287 &mut self,
8288 _: &MoveToPreviousWordStart,
8289 window: &mut Window,
8290 cx: &mut Context<Self>,
8291 ) {
8292 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8293 s.move_cursors_with(|map, head, _| {
8294 (
8295 movement::previous_word_start(map, head),
8296 SelectionGoal::None,
8297 )
8298 });
8299 })
8300 }
8301
8302 pub fn move_to_previous_subword_start(
8303 &mut self,
8304 _: &MoveToPreviousSubwordStart,
8305 window: &mut Window,
8306 cx: &mut Context<Self>,
8307 ) {
8308 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8309 s.move_cursors_with(|map, head, _| {
8310 (
8311 movement::previous_subword_start(map, head),
8312 SelectionGoal::None,
8313 )
8314 });
8315 })
8316 }
8317
8318 pub fn select_to_previous_word_start(
8319 &mut self,
8320 _: &SelectToPreviousWordStart,
8321 window: &mut Window,
8322 cx: &mut Context<Self>,
8323 ) {
8324 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8325 s.move_heads_with(|map, head, _| {
8326 (
8327 movement::previous_word_start(map, head),
8328 SelectionGoal::None,
8329 )
8330 });
8331 })
8332 }
8333
8334 pub fn select_to_previous_subword_start(
8335 &mut self,
8336 _: &SelectToPreviousSubwordStart,
8337 window: &mut Window,
8338 cx: &mut Context<Self>,
8339 ) {
8340 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8341 s.move_heads_with(|map, head, _| {
8342 (
8343 movement::previous_subword_start(map, head),
8344 SelectionGoal::None,
8345 )
8346 });
8347 })
8348 }
8349
8350 pub fn delete_to_previous_word_start(
8351 &mut self,
8352 action: &DeleteToPreviousWordStart,
8353 window: &mut Window,
8354 cx: &mut Context<Self>,
8355 ) {
8356 self.transact(window, cx, |this, window, cx| {
8357 this.select_autoclose_pair(window, cx);
8358 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8359 let line_mode = s.line_mode;
8360 s.move_with(|map, selection| {
8361 if selection.is_empty() && !line_mode {
8362 let cursor = if action.ignore_newlines {
8363 movement::previous_word_start(map, selection.head())
8364 } else {
8365 movement::previous_word_start_or_newline(map, selection.head())
8366 };
8367 selection.set_head(cursor, SelectionGoal::None);
8368 }
8369 });
8370 });
8371 this.insert("", window, cx);
8372 });
8373 }
8374
8375 pub fn delete_to_previous_subword_start(
8376 &mut self,
8377 _: &DeleteToPreviousSubwordStart,
8378 window: &mut Window,
8379 cx: &mut Context<Self>,
8380 ) {
8381 self.transact(window, cx, |this, window, cx| {
8382 this.select_autoclose_pair(window, cx);
8383 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8384 let line_mode = s.line_mode;
8385 s.move_with(|map, selection| {
8386 if selection.is_empty() && !line_mode {
8387 let cursor = movement::previous_subword_start(map, selection.head());
8388 selection.set_head(cursor, SelectionGoal::None);
8389 }
8390 });
8391 });
8392 this.insert("", window, cx);
8393 });
8394 }
8395
8396 pub fn move_to_next_word_end(
8397 &mut self,
8398 _: &MoveToNextWordEnd,
8399 window: &mut Window,
8400 cx: &mut Context<Self>,
8401 ) {
8402 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8403 s.move_cursors_with(|map, head, _| {
8404 (movement::next_word_end(map, head), SelectionGoal::None)
8405 });
8406 })
8407 }
8408
8409 pub fn move_to_next_subword_end(
8410 &mut self,
8411 _: &MoveToNextSubwordEnd,
8412 window: &mut Window,
8413 cx: &mut Context<Self>,
8414 ) {
8415 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8416 s.move_cursors_with(|map, head, _| {
8417 (movement::next_subword_end(map, head), SelectionGoal::None)
8418 });
8419 })
8420 }
8421
8422 pub fn select_to_next_word_end(
8423 &mut self,
8424 _: &SelectToNextWordEnd,
8425 window: &mut Window,
8426 cx: &mut Context<Self>,
8427 ) {
8428 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8429 s.move_heads_with(|map, head, _| {
8430 (movement::next_word_end(map, head), SelectionGoal::None)
8431 });
8432 })
8433 }
8434
8435 pub fn select_to_next_subword_end(
8436 &mut self,
8437 _: &SelectToNextSubwordEnd,
8438 window: &mut Window,
8439 cx: &mut Context<Self>,
8440 ) {
8441 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8442 s.move_heads_with(|map, head, _| {
8443 (movement::next_subword_end(map, head), SelectionGoal::None)
8444 });
8445 })
8446 }
8447
8448 pub fn delete_to_next_word_end(
8449 &mut self,
8450 action: &DeleteToNextWordEnd,
8451 window: &mut Window,
8452 cx: &mut Context<Self>,
8453 ) {
8454 self.transact(window, cx, |this, window, cx| {
8455 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8456 let line_mode = s.line_mode;
8457 s.move_with(|map, selection| {
8458 if selection.is_empty() && !line_mode {
8459 let cursor = if action.ignore_newlines {
8460 movement::next_word_end(map, selection.head())
8461 } else {
8462 movement::next_word_end_or_newline(map, selection.head())
8463 };
8464 selection.set_head(cursor, SelectionGoal::None);
8465 }
8466 });
8467 });
8468 this.insert("", window, cx);
8469 });
8470 }
8471
8472 pub fn delete_to_next_subword_end(
8473 &mut self,
8474 _: &DeleteToNextSubwordEnd,
8475 window: &mut Window,
8476 cx: &mut Context<Self>,
8477 ) {
8478 self.transact(window, cx, |this, window, cx| {
8479 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8480 s.move_with(|map, selection| {
8481 if selection.is_empty() {
8482 let cursor = movement::next_subword_end(map, selection.head());
8483 selection.set_head(cursor, SelectionGoal::None);
8484 }
8485 });
8486 });
8487 this.insert("", window, cx);
8488 });
8489 }
8490
8491 pub fn move_to_beginning_of_line(
8492 &mut self,
8493 action: &MoveToBeginningOfLine,
8494 window: &mut Window,
8495 cx: &mut Context<Self>,
8496 ) {
8497 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8498 s.move_cursors_with(|map, head, _| {
8499 (
8500 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8501 SelectionGoal::None,
8502 )
8503 });
8504 })
8505 }
8506
8507 pub fn select_to_beginning_of_line(
8508 &mut self,
8509 action: &SelectToBeginningOfLine,
8510 window: &mut Window,
8511 cx: &mut Context<Self>,
8512 ) {
8513 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8514 s.move_heads_with(|map, head, _| {
8515 (
8516 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8517 SelectionGoal::None,
8518 )
8519 });
8520 });
8521 }
8522
8523 pub fn delete_to_beginning_of_line(
8524 &mut self,
8525 _: &DeleteToBeginningOfLine,
8526 window: &mut Window,
8527 cx: &mut Context<Self>,
8528 ) {
8529 self.transact(window, cx, |this, window, cx| {
8530 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8531 s.move_with(|_, selection| {
8532 selection.reversed = true;
8533 });
8534 });
8535
8536 this.select_to_beginning_of_line(
8537 &SelectToBeginningOfLine {
8538 stop_at_soft_wraps: false,
8539 },
8540 window,
8541 cx,
8542 );
8543 this.backspace(&Backspace, window, cx);
8544 });
8545 }
8546
8547 pub fn move_to_end_of_line(
8548 &mut self,
8549 action: &MoveToEndOfLine,
8550 window: &mut Window,
8551 cx: &mut Context<Self>,
8552 ) {
8553 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8554 s.move_cursors_with(|map, head, _| {
8555 (
8556 movement::line_end(map, head, action.stop_at_soft_wraps),
8557 SelectionGoal::None,
8558 )
8559 });
8560 })
8561 }
8562
8563 pub fn select_to_end_of_line(
8564 &mut self,
8565 action: &SelectToEndOfLine,
8566 window: &mut Window,
8567 cx: &mut Context<Self>,
8568 ) {
8569 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8570 s.move_heads_with(|map, head, _| {
8571 (
8572 movement::line_end(map, head, action.stop_at_soft_wraps),
8573 SelectionGoal::None,
8574 )
8575 });
8576 })
8577 }
8578
8579 pub fn delete_to_end_of_line(
8580 &mut self,
8581 _: &DeleteToEndOfLine,
8582 window: &mut Window,
8583 cx: &mut Context<Self>,
8584 ) {
8585 self.transact(window, cx, |this, window, cx| {
8586 this.select_to_end_of_line(
8587 &SelectToEndOfLine {
8588 stop_at_soft_wraps: false,
8589 },
8590 window,
8591 cx,
8592 );
8593 this.delete(&Delete, window, cx);
8594 });
8595 }
8596
8597 pub fn cut_to_end_of_line(
8598 &mut self,
8599 _: &CutToEndOfLine,
8600 window: &mut Window,
8601 cx: &mut Context<Self>,
8602 ) {
8603 self.transact(window, cx, |this, window, cx| {
8604 this.select_to_end_of_line(
8605 &SelectToEndOfLine {
8606 stop_at_soft_wraps: false,
8607 },
8608 window,
8609 cx,
8610 );
8611 this.cut(&Cut, window, cx);
8612 });
8613 }
8614
8615 pub fn move_to_start_of_paragraph(
8616 &mut self,
8617 _: &MoveToStartOfParagraph,
8618 window: &mut Window,
8619 cx: &mut Context<Self>,
8620 ) {
8621 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8622 cx.propagate();
8623 return;
8624 }
8625
8626 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8627 s.move_with(|map, selection| {
8628 selection.collapse_to(
8629 movement::start_of_paragraph(map, selection.head(), 1),
8630 SelectionGoal::None,
8631 )
8632 });
8633 })
8634 }
8635
8636 pub fn move_to_end_of_paragraph(
8637 &mut self,
8638 _: &MoveToEndOfParagraph,
8639 window: &mut Window,
8640 cx: &mut Context<Self>,
8641 ) {
8642 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8643 cx.propagate();
8644 return;
8645 }
8646
8647 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8648 s.move_with(|map, selection| {
8649 selection.collapse_to(
8650 movement::end_of_paragraph(map, selection.head(), 1),
8651 SelectionGoal::None,
8652 )
8653 });
8654 })
8655 }
8656
8657 pub fn select_to_start_of_paragraph(
8658 &mut self,
8659 _: &SelectToStartOfParagraph,
8660 window: &mut Window,
8661 cx: &mut Context<Self>,
8662 ) {
8663 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8664 cx.propagate();
8665 return;
8666 }
8667
8668 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8669 s.move_heads_with(|map, head, _| {
8670 (
8671 movement::start_of_paragraph(map, head, 1),
8672 SelectionGoal::None,
8673 )
8674 });
8675 })
8676 }
8677
8678 pub fn select_to_end_of_paragraph(
8679 &mut self,
8680 _: &SelectToEndOfParagraph,
8681 window: &mut Window,
8682 cx: &mut Context<Self>,
8683 ) {
8684 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8685 cx.propagate();
8686 return;
8687 }
8688
8689 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8690 s.move_heads_with(|map, head, _| {
8691 (
8692 movement::end_of_paragraph(map, head, 1),
8693 SelectionGoal::None,
8694 )
8695 });
8696 })
8697 }
8698
8699 pub fn move_to_beginning(
8700 &mut self,
8701 _: &MoveToBeginning,
8702 window: &mut Window,
8703 cx: &mut Context<Self>,
8704 ) {
8705 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8706 cx.propagate();
8707 return;
8708 }
8709
8710 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8711 s.select_ranges(vec![0..0]);
8712 });
8713 }
8714
8715 pub fn select_to_beginning(
8716 &mut self,
8717 _: &SelectToBeginning,
8718 window: &mut Window,
8719 cx: &mut Context<Self>,
8720 ) {
8721 let mut selection = self.selections.last::<Point>(cx);
8722 selection.set_head(Point::zero(), SelectionGoal::None);
8723
8724 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8725 s.select(vec![selection]);
8726 });
8727 }
8728
8729 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
8730 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8731 cx.propagate();
8732 return;
8733 }
8734
8735 let cursor = self.buffer.read(cx).read(cx).len();
8736 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8737 s.select_ranges(vec![cursor..cursor])
8738 });
8739 }
8740
8741 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8742 self.nav_history = nav_history;
8743 }
8744
8745 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8746 self.nav_history.as_ref()
8747 }
8748
8749 fn push_to_nav_history(
8750 &mut self,
8751 cursor_anchor: Anchor,
8752 new_position: Option<Point>,
8753 cx: &mut Context<Self>,
8754 ) {
8755 if let Some(nav_history) = self.nav_history.as_mut() {
8756 let buffer = self.buffer.read(cx).read(cx);
8757 let cursor_position = cursor_anchor.to_point(&buffer);
8758 let scroll_state = self.scroll_manager.anchor();
8759 let scroll_top_row = scroll_state.top_row(&buffer);
8760 drop(buffer);
8761
8762 if let Some(new_position) = new_position {
8763 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8764 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8765 return;
8766 }
8767 }
8768
8769 nav_history.push(
8770 Some(NavigationData {
8771 cursor_anchor,
8772 cursor_position,
8773 scroll_anchor: scroll_state,
8774 scroll_top_row,
8775 }),
8776 cx,
8777 );
8778 }
8779 }
8780
8781 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
8782 let buffer = self.buffer.read(cx).snapshot(cx);
8783 let mut selection = self.selections.first::<usize>(cx);
8784 selection.set_head(buffer.len(), SelectionGoal::None);
8785 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8786 s.select(vec![selection]);
8787 });
8788 }
8789
8790 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
8791 let end = self.buffer.read(cx).read(cx).len();
8792 self.change_selections(None, window, cx, |s| {
8793 s.select_ranges(vec![0..end]);
8794 });
8795 }
8796
8797 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
8798 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8799 let mut selections = self.selections.all::<Point>(cx);
8800 let max_point = display_map.buffer_snapshot.max_point();
8801 for selection in &mut selections {
8802 let rows = selection.spanned_rows(true, &display_map);
8803 selection.start = Point::new(rows.start.0, 0);
8804 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8805 selection.reversed = false;
8806 }
8807 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8808 s.select(selections);
8809 });
8810 }
8811
8812 pub fn split_selection_into_lines(
8813 &mut self,
8814 _: &SplitSelectionIntoLines,
8815 window: &mut Window,
8816 cx: &mut Context<Self>,
8817 ) {
8818 let mut to_unfold = Vec::new();
8819 let mut new_selection_ranges = Vec::new();
8820 {
8821 let selections = self.selections.all::<Point>(cx);
8822 let buffer = self.buffer.read(cx).read(cx);
8823 for selection in selections {
8824 for row in selection.start.row..selection.end.row {
8825 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8826 new_selection_ranges.push(cursor..cursor);
8827 }
8828 new_selection_ranges.push(selection.end..selection.end);
8829 to_unfold.push(selection.start..selection.end);
8830 }
8831 }
8832 self.unfold_ranges(&to_unfold, true, true, cx);
8833 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8834 s.select_ranges(new_selection_ranges);
8835 });
8836 }
8837
8838 pub fn add_selection_above(
8839 &mut self,
8840 _: &AddSelectionAbove,
8841 window: &mut Window,
8842 cx: &mut Context<Self>,
8843 ) {
8844 self.add_selection(true, window, cx);
8845 }
8846
8847 pub fn add_selection_below(
8848 &mut self,
8849 _: &AddSelectionBelow,
8850 window: &mut Window,
8851 cx: &mut Context<Self>,
8852 ) {
8853 self.add_selection(false, window, cx);
8854 }
8855
8856 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
8857 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8858 let mut selections = self.selections.all::<Point>(cx);
8859 let text_layout_details = self.text_layout_details(window);
8860 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8861 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8862 let range = oldest_selection.display_range(&display_map).sorted();
8863
8864 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8865 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8866 let positions = start_x.min(end_x)..start_x.max(end_x);
8867
8868 selections.clear();
8869 let mut stack = Vec::new();
8870 for row in range.start.row().0..=range.end.row().0 {
8871 if let Some(selection) = self.selections.build_columnar_selection(
8872 &display_map,
8873 DisplayRow(row),
8874 &positions,
8875 oldest_selection.reversed,
8876 &text_layout_details,
8877 ) {
8878 stack.push(selection.id);
8879 selections.push(selection);
8880 }
8881 }
8882
8883 if above {
8884 stack.reverse();
8885 }
8886
8887 AddSelectionsState { above, stack }
8888 });
8889
8890 let last_added_selection = *state.stack.last().unwrap();
8891 let mut new_selections = Vec::new();
8892 if above == state.above {
8893 let end_row = if above {
8894 DisplayRow(0)
8895 } else {
8896 display_map.max_point().row()
8897 };
8898
8899 'outer: for selection in selections {
8900 if selection.id == last_added_selection {
8901 let range = selection.display_range(&display_map).sorted();
8902 debug_assert_eq!(range.start.row(), range.end.row());
8903 let mut row = range.start.row();
8904 let positions =
8905 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8906 px(start)..px(end)
8907 } else {
8908 let start_x =
8909 display_map.x_for_display_point(range.start, &text_layout_details);
8910 let end_x =
8911 display_map.x_for_display_point(range.end, &text_layout_details);
8912 start_x.min(end_x)..start_x.max(end_x)
8913 };
8914
8915 while row != end_row {
8916 if above {
8917 row.0 -= 1;
8918 } else {
8919 row.0 += 1;
8920 }
8921
8922 if let Some(new_selection) = self.selections.build_columnar_selection(
8923 &display_map,
8924 row,
8925 &positions,
8926 selection.reversed,
8927 &text_layout_details,
8928 ) {
8929 state.stack.push(new_selection.id);
8930 if above {
8931 new_selections.push(new_selection);
8932 new_selections.push(selection);
8933 } else {
8934 new_selections.push(selection);
8935 new_selections.push(new_selection);
8936 }
8937
8938 continue 'outer;
8939 }
8940 }
8941 }
8942
8943 new_selections.push(selection);
8944 }
8945 } else {
8946 new_selections = selections;
8947 new_selections.retain(|s| s.id != last_added_selection);
8948 state.stack.pop();
8949 }
8950
8951 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8952 s.select(new_selections);
8953 });
8954 if state.stack.len() > 1 {
8955 self.add_selections_state = Some(state);
8956 }
8957 }
8958
8959 pub fn select_next_match_internal(
8960 &mut self,
8961 display_map: &DisplaySnapshot,
8962 replace_newest: bool,
8963 autoscroll: Option<Autoscroll>,
8964 window: &mut Window,
8965 cx: &mut Context<Self>,
8966 ) -> Result<()> {
8967 fn select_next_match_ranges(
8968 this: &mut Editor,
8969 range: Range<usize>,
8970 replace_newest: bool,
8971 auto_scroll: Option<Autoscroll>,
8972 window: &mut Window,
8973 cx: &mut Context<Editor>,
8974 ) {
8975 this.unfold_ranges(&[range.clone()], false, true, cx);
8976 this.change_selections(auto_scroll, window, cx, |s| {
8977 if replace_newest {
8978 s.delete(s.newest_anchor().id);
8979 }
8980 s.insert_range(range.clone());
8981 });
8982 }
8983
8984 let buffer = &display_map.buffer_snapshot;
8985 let mut selections = self.selections.all::<usize>(cx);
8986 if let Some(mut select_next_state) = self.select_next_state.take() {
8987 let query = &select_next_state.query;
8988 if !select_next_state.done {
8989 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8990 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8991 let mut next_selected_range = None;
8992
8993 let bytes_after_last_selection =
8994 buffer.bytes_in_range(last_selection.end..buffer.len());
8995 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8996 let query_matches = query
8997 .stream_find_iter(bytes_after_last_selection)
8998 .map(|result| (last_selection.end, result))
8999 .chain(
9000 query
9001 .stream_find_iter(bytes_before_first_selection)
9002 .map(|result| (0, result)),
9003 );
9004
9005 for (start_offset, query_match) in query_matches {
9006 let query_match = query_match.unwrap(); // can only fail due to I/O
9007 let offset_range =
9008 start_offset + query_match.start()..start_offset + query_match.end();
9009 let display_range = offset_range.start.to_display_point(display_map)
9010 ..offset_range.end.to_display_point(display_map);
9011
9012 if !select_next_state.wordwise
9013 || (!movement::is_inside_word(display_map, display_range.start)
9014 && !movement::is_inside_word(display_map, display_range.end))
9015 {
9016 // TODO: This is n^2, because we might check all the selections
9017 if !selections
9018 .iter()
9019 .any(|selection| selection.range().overlaps(&offset_range))
9020 {
9021 next_selected_range = Some(offset_range);
9022 break;
9023 }
9024 }
9025 }
9026
9027 if let Some(next_selected_range) = next_selected_range {
9028 select_next_match_ranges(
9029 self,
9030 next_selected_range,
9031 replace_newest,
9032 autoscroll,
9033 window,
9034 cx,
9035 );
9036 } else {
9037 select_next_state.done = true;
9038 }
9039 }
9040
9041 self.select_next_state = Some(select_next_state);
9042 } else {
9043 let mut only_carets = true;
9044 let mut same_text_selected = true;
9045 let mut selected_text = None;
9046
9047 let mut selections_iter = selections.iter().peekable();
9048 while let Some(selection) = selections_iter.next() {
9049 if selection.start != selection.end {
9050 only_carets = false;
9051 }
9052
9053 if same_text_selected {
9054 if selected_text.is_none() {
9055 selected_text =
9056 Some(buffer.text_for_range(selection.range()).collect::<String>());
9057 }
9058
9059 if let Some(next_selection) = selections_iter.peek() {
9060 if next_selection.range().len() == selection.range().len() {
9061 let next_selected_text = buffer
9062 .text_for_range(next_selection.range())
9063 .collect::<String>();
9064 if Some(next_selected_text) != selected_text {
9065 same_text_selected = false;
9066 selected_text = None;
9067 }
9068 } else {
9069 same_text_selected = false;
9070 selected_text = None;
9071 }
9072 }
9073 }
9074 }
9075
9076 if only_carets {
9077 for selection in &mut selections {
9078 let word_range = movement::surrounding_word(
9079 display_map,
9080 selection.start.to_display_point(display_map),
9081 );
9082 selection.start = word_range.start.to_offset(display_map, Bias::Left);
9083 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9084 selection.goal = SelectionGoal::None;
9085 selection.reversed = false;
9086 select_next_match_ranges(
9087 self,
9088 selection.start..selection.end,
9089 replace_newest,
9090 autoscroll,
9091 window,
9092 cx,
9093 );
9094 }
9095
9096 if selections.len() == 1 {
9097 let selection = selections
9098 .last()
9099 .expect("ensured that there's only one selection");
9100 let query = buffer
9101 .text_for_range(selection.start..selection.end)
9102 .collect::<String>();
9103 let is_empty = query.is_empty();
9104 let select_state = SelectNextState {
9105 query: AhoCorasick::new(&[query])?,
9106 wordwise: true,
9107 done: is_empty,
9108 };
9109 self.select_next_state = Some(select_state);
9110 } else {
9111 self.select_next_state = None;
9112 }
9113 } else if let Some(selected_text) = selected_text {
9114 self.select_next_state = Some(SelectNextState {
9115 query: AhoCorasick::new(&[selected_text])?,
9116 wordwise: false,
9117 done: false,
9118 });
9119 self.select_next_match_internal(
9120 display_map,
9121 replace_newest,
9122 autoscroll,
9123 window,
9124 cx,
9125 )?;
9126 }
9127 }
9128 Ok(())
9129 }
9130
9131 pub fn select_all_matches(
9132 &mut self,
9133 _action: &SelectAllMatches,
9134 window: &mut Window,
9135 cx: &mut Context<Self>,
9136 ) -> Result<()> {
9137 self.push_to_selection_history();
9138 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9139
9140 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9141 let Some(select_next_state) = self.select_next_state.as_mut() else {
9142 return Ok(());
9143 };
9144 if select_next_state.done {
9145 return Ok(());
9146 }
9147
9148 let mut new_selections = self.selections.all::<usize>(cx);
9149
9150 let buffer = &display_map.buffer_snapshot;
9151 let query_matches = select_next_state
9152 .query
9153 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9154
9155 for query_match in query_matches {
9156 let query_match = query_match.unwrap(); // can only fail due to I/O
9157 let offset_range = query_match.start()..query_match.end();
9158 let display_range = offset_range.start.to_display_point(&display_map)
9159 ..offset_range.end.to_display_point(&display_map);
9160
9161 if !select_next_state.wordwise
9162 || (!movement::is_inside_word(&display_map, display_range.start)
9163 && !movement::is_inside_word(&display_map, display_range.end))
9164 {
9165 self.selections.change_with(cx, |selections| {
9166 new_selections.push(Selection {
9167 id: selections.new_selection_id(),
9168 start: offset_range.start,
9169 end: offset_range.end,
9170 reversed: false,
9171 goal: SelectionGoal::None,
9172 });
9173 });
9174 }
9175 }
9176
9177 new_selections.sort_by_key(|selection| selection.start);
9178 let mut ix = 0;
9179 while ix + 1 < new_selections.len() {
9180 let current_selection = &new_selections[ix];
9181 let next_selection = &new_selections[ix + 1];
9182 if current_selection.range().overlaps(&next_selection.range()) {
9183 if current_selection.id < next_selection.id {
9184 new_selections.remove(ix + 1);
9185 } else {
9186 new_selections.remove(ix);
9187 }
9188 } else {
9189 ix += 1;
9190 }
9191 }
9192
9193 let reversed = self.selections.oldest::<usize>(cx).reversed;
9194
9195 for selection in new_selections.iter_mut() {
9196 selection.reversed = reversed;
9197 }
9198
9199 select_next_state.done = true;
9200 self.unfold_ranges(
9201 &new_selections
9202 .iter()
9203 .map(|selection| selection.range())
9204 .collect::<Vec<_>>(),
9205 false,
9206 false,
9207 cx,
9208 );
9209 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9210 selections.select(new_selections)
9211 });
9212
9213 Ok(())
9214 }
9215
9216 pub fn select_next(
9217 &mut self,
9218 action: &SelectNext,
9219 window: &mut Window,
9220 cx: &mut Context<Self>,
9221 ) -> Result<()> {
9222 self.push_to_selection_history();
9223 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9224 self.select_next_match_internal(
9225 &display_map,
9226 action.replace_newest,
9227 Some(Autoscroll::newest()),
9228 window,
9229 cx,
9230 )?;
9231 Ok(())
9232 }
9233
9234 pub fn select_previous(
9235 &mut self,
9236 action: &SelectPrevious,
9237 window: &mut Window,
9238 cx: &mut Context<Self>,
9239 ) -> Result<()> {
9240 self.push_to_selection_history();
9241 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9242 let buffer = &display_map.buffer_snapshot;
9243 let mut selections = self.selections.all::<usize>(cx);
9244 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9245 let query = &select_prev_state.query;
9246 if !select_prev_state.done {
9247 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9248 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9249 let mut next_selected_range = None;
9250 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9251 let bytes_before_last_selection =
9252 buffer.reversed_bytes_in_range(0..last_selection.start);
9253 let bytes_after_first_selection =
9254 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9255 let query_matches = query
9256 .stream_find_iter(bytes_before_last_selection)
9257 .map(|result| (last_selection.start, result))
9258 .chain(
9259 query
9260 .stream_find_iter(bytes_after_first_selection)
9261 .map(|result| (buffer.len(), result)),
9262 );
9263 for (end_offset, query_match) in query_matches {
9264 let query_match = query_match.unwrap(); // can only fail due to I/O
9265 let offset_range =
9266 end_offset - query_match.end()..end_offset - query_match.start();
9267 let display_range = offset_range.start.to_display_point(&display_map)
9268 ..offset_range.end.to_display_point(&display_map);
9269
9270 if !select_prev_state.wordwise
9271 || (!movement::is_inside_word(&display_map, display_range.start)
9272 && !movement::is_inside_word(&display_map, display_range.end))
9273 {
9274 next_selected_range = Some(offset_range);
9275 break;
9276 }
9277 }
9278
9279 if let Some(next_selected_range) = next_selected_range {
9280 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9281 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9282 if action.replace_newest {
9283 s.delete(s.newest_anchor().id);
9284 }
9285 s.insert_range(next_selected_range);
9286 });
9287 } else {
9288 select_prev_state.done = true;
9289 }
9290 }
9291
9292 self.select_prev_state = Some(select_prev_state);
9293 } else {
9294 let mut only_carets = true;
9295 let mut same_text_selected = true;
9296 let mut selected_text = None;
9297
9298 let mut selections_iter = selections.iter().peekable();
9299 while let Some(selection) = selections_iter.next() {
9300 if selection.start != selection.end {
9301 only_carets = false;
9302 }
9303
9304 if same_text_selected {
9305 if selected_text.is_none() {
9306 selected_text =
9307 Some(buffer.text_for_range(selection.range()).collect::<String>());
9308 }
9309
9310 if let Some(next_selection) = selections_iter.peek() {
9311 if next_selection.range().len() == selection.range().len() {
9312 let next_selected_text = buffer
9313 .text_for_range(next_selection.range())
9314 .collect::<String>();
9315 if Some(next_selected_text) != selected_text {
9316 same_text_selected = false;
9317 selected_text = None;
9318 }
9319 } else {
9320 same_text_selected = false;
9321 selected_text = None;
9322 }
9323 }
9324 }
9325 }
9326
9327 if only_carets {
9328 for selection in &mut selections {
9329 let word_range = movement::surrounding_word(
9330 &display_map,
9331 selection.start.to_display_point(&display_map),
9332 );
9333 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9334 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9335 selection.goal = SelectionGoal::None;
9336 selection.reversed = false;
9337 }
9338 if selections.len() == 1 {
9339 let selection = selections
9340 .last()
9341 .expect("ensured that there's only one selection");
9342 let query = buffer
9343 .text_for_range(selection.start..selection.end)
9344 .collect::<String>();
9345 let is_empty = query.is_empty();
9346 let select_state = SelectNextState {
9347 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9348 wordwise: true,
9349 done: is_empty,
9350 };
9351 self.select_prev_state = Some(select_state);
9352 } else {
9353 self.select_prev_state = None;
9354 }
9355
9356 self.unfold_ranges(
9357 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9358 false,
9359 true,
9360 cx,
9361 );
9362 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9363 s.select(selections);
9364 });
9365 } else if let Some(selected_text) = selected_text {
9366 self.select_prev_state = Some(SelectNextState {
9367 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9368 wordwise: false,
9369 done: false,
9370 });
9371 self.select_previous(action, window, cx)?;
9372 }
9373 }
9374 Ok(())
9375 }
9376
9377 pub fn toggle_comments(
9378 &mut self,
9379 action: &ToggleComments,
9380 window: &mut Window,
9381 cx: &mut Context<Self>,
9382 ) {
9383 if self.read_only(cx) {
9384 return;
9385 }
9386 let text_layout_details = &self.text_layout_details(window);
9387 self.transact(window, cx, |this, window, cx| {
9388 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9389 let mut edits = Vec::new();
9390 let mut selection_edit_ranges = Vec::new();
9391 let mut last_toggled_row = None;
9392 let snapshot = this.buffer.read(cx).read(cx);
9393 let empty_str: Arc<str> = Arc::default();
9394 let mut suffixes_inserted = Vec::new();
9395 let ignore_indent = action.ignore_indent;
9396
9397 fn comment_prefix_range(
9398 snapshot: &MultiBufferSnapshot,
9399 row: MultiBufferRow,
9400 comment_prefix: &str,
9401 comment_prefix_whitespace: &str,
9402 ignore_indent: bool,
9403 ) -> Range<Point> {
9404 let indent_size = if ignore_indent {
9405 0
9406 } else {
9407 snapshot.indent_size_for_line(row).len
9408 };
9409
9410 let start = Point::new(row.0, indent_size);
9411
9412 let mut line_bytes = snapshot
9413 .bytes_in_range(start..snapshot.max_point())
9414 .flatten()
9415 .copied();
9416
9417 // If this line currently begins with the line comment prefix, then record
9418 // the range containing the prefix.
9419 if line_bytes
9420 .by_ref()
9421 .take(comment_prefix.len())
9422 .eq(comment_prefix.bytes())
9423 {
9424 // Include any whitespace that matches the comment prefix.
9425 let matching_whitespace_len = line_bytes
9426 .zip(comment_prefix_whitespace.bytes())
9427 .take_while(|(a, b)| a == b)
9428 .count() as u32;
9429 let end = Point::new(
9430 start.row,
9431 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9432 );
9433 start..end
9434 } else {
9435 start..start
9436 }
9437 }
9438
9439 fn comment_suffix_range(
9440 snapshot: &MultiBufferSnapshot,
9441 row: MultiBufferRow,
9442 comment_suffix: &str,
9443 comment_suffix_has_leading_space: bool,
9444 ) -> Range<Point> {
9445 let end = Point::new(row.0, snapshot.line_len(row));
9446 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9447
9448 let mut line_end_bytes = snapshot
9449 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9450 .flatten()
9451 .copied();
9452
9453 let leading_space_len = if suffix_start_column > 0
9454 && line_end_bytes.next() == Some(b' ')
9455 && comment_suffix_has_leading_space
9456 {
9457 1
9458 } else {
9459 0
9460 };
9461
9462 // If this line currently begins with the line comment prefix, then record
9463 // the range containing the prefix.
9464 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9465 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9466 start..end
9467 } else {
9468 end..end
9469 }
9470 }
9471
9472 // TODO: Handle selections that cross excerpts
9473 for selection in &mut selections {
9474 let start_column = snapshot
9475 .indent_size_for_line(MultiBufferRow(selection.start.row))
9476 .len;
9477 let language = if let Some(language) =
9478 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9479 {
9480 language
9481 } else {
9482 continue;
9483 };
9484
9485 selection_edit_ranges.clear();
9486
9487 // If multiple selections contain a given row, avoid processing that
9488 // row more than once.
9489 let mut start_row = MultiBufferRow(selection.start.row);
9490 if last_toggled_row == Some(start_row) {
9491 start_row = start_row.next_row();
9492 }
9493 let end_row =
9494 if selection.end.row > selection.start.row && selection.end.column == 0 {
9495 MultiBufferRow(selection.end.row - 1)
9496 } else {
9497 MultiBufferRow(selection.end.row)
9498 };
9499 last_toggled_row = Some(end_row);
9500
9501 if start_row > end_row {
9502 continue;
9503 }
9504
9505 // If the language has line comments, toggle those.
9506 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9507
9508 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9509 if ignore_indent {
9510 full_comment_prefixes = full_comment_prefixes
9511 .into_iter()
9512 .map(|s| Arc::from(s.trim_end()))
9513 .collect();
9514 }
9515
9516 if !full_comment_prefixes.is_empty() {
9517 let first_prefix = full_comment_prefixes
9518 .first()
9519 .expect("prefixes is non-empty");
9520 let prefix_trimmed_lengths = full_comment_prefixes
9521 .iter()
9522 .map(|p| p.trim_end_matches(' ').len())
9523 .collect::<SmallVec<[usize; 4]>>();
9524
9525 let mut all_selection_lines_are_comments = true;
9526
9527 for row in start_row.0..=end_row.0 {
9528 let row = MultiBufferRow(row);
9529 if start_row < end_row && snapshot.is_line_blank(row) {
9530 continue;
9531 }
9532
9533 let prefix_range = full_comment_prefixes
9534 .iter()
9535 .zip(prefix_trimmed_lengths.iter().copied())
9536 .map(|(prefix, trimmed_prefix_len)| {
9537 comment_prefix_range(
9538 snapshot.deref(),
9539 row,
9540 &prefix[..trimmed_prefix_len],
9541 &prefix[trimmed_prefix_len..],
9542 ignore_indent,
9543 )
9544 })
9545 .max_by_key(|range| range.end.column - range.start.column)
9546 .expect("prefixes is non-empty");
9547
9548 if prefix_range.is_empty() {
9549 all_selection_lines_are_comments = false;
9550 }
9551
9552 selection_edit_ranges.push(prefix_range);
9553 }
9554
9555 if all_selection_lines_are_comments {
9556 edits.extend(
9557 selection_edit_ranges
9558 .iter()
9559 .cloned()
9560 .map(|range| (range, empty_str.clone())),
9561 );
9562 } else {
9563 let min_column = selection_edit_ranges
9564 .iter()
9565 .map(|range| range.start.column)
9566 .min()
9567 .unwrap_or(0);
9568 edits.extend(selection_edit_ranges.iter().map(|range| {
9569 let position = Point::new(range.start.row, min_column);
9570 (position..position, first_prefix.clone())
9571 }));
9572 }
9573 } else if let Some((full_comment_prefix, comment_suffix)) =
9574 language.block_comment_delimiters()
9575 {
9576 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9577 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9578 let prefix_range = comment_prefix_range(
9579 snapshot.deref(),
9580 start_row,
9581 comment_prefix,
9582 comment_prefix_whitespace,
9583 ignore_indent,
9584 );
9585 let suffix_range = comment_suffix_range(
9586 snapshot.deref(),
9587 end_row,
9588 comment_suffix.trim_start_matches(' '),
9589 comment_suffix.starts_with(' '),
9590 );
9591
9592 if prefix_range.is_empty() || suffix_range.is_empty() {
9593 edits.push((
9594 prefix_range.start..prefix_range.start,
9595 full_comment_prefix.clone(),
9596 ));
9597 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9598 suffixes_inserted.push((end_row, comment_suffix.len()));
9599 } else {
9600 edits.push((prefix_range, empty_str.clone()));
9601 edits.push((suffix_range, empty_str.clone()));
9602 }
9603 } else {
9604 continue;
9605 }
9606 }
9607
9608 drop(snapshot);
9609 this.buffer.update(cx, |buffer, cx| {
9610 buffer.edit(edits, None, cx);
9611 });
9612
9613 // Adjust selections so that they end before any comment suffixes that
9614 // were inserted.
9615 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9616 let mut selections = this.selections.all::<Point>(cx);
9617 let snapshot = this.buffer.read(cx).read(cx);
9618 for selection in &mut selections {
9619 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9620 match row.cmp(&MultiBufferRow(selection.end.row)) {
9621 Ordering::Less => {
9622 suffixes_inserted.next();
9623 continue;
9624 }
9625 Ordering::Greater => break,
9626 Ordering::Equal => {
9627 if selection.end.column == snapshot.line_len(row) {
9628 if selection.is_empty() {
9629 selection.start.column -= suffix_len as u32;
9630 }
9631 selection.end.column -= suffix_len as u32;
9632 }
9633 break;
9634 }
9635 }
9636 }
9637 }
9638
9639 drop(snapshot);
9640 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9641 s.select(selections)
9642 });
9643
9644 let selections = this.selections.all::<Point>(cx);
9645 let selections_on_single_row = selections.windows(2).all(|selections| {
9646 selections[0].start.row == selections[1].start.row
9647 && selections[0].end.row == selections[1].end.row
9648 && selections[0].start.row == selections[0].end.row
9649 });
9650 let selections_selecting = selections
9651 .iter()
9652 .any(|selection| selection.start != selection.end);
9653 let advance_downwards = action.advance_downwards
9654 && selections_on_single_row
9655 && !selections_selecting
9656 && !matches!(this.mode, EditorMode::SingleLine { .. });
9657
9658 if advance_downwards {
9659 let snapshot = this.buffer.read(cx).snapshot(cx);
9660
9661 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9662 s.move_cursors_with(|display_snapshot, display_point, _| {
9663 let mut point = display_point.to_point(display_snapshot);
9664 point.row += 1;
9665 point = snapshot.clip_point(point, Bias::Left);
9666 let display_point = point.to_display_point(display_snapshot);
9667 let goal = SelectionGoal::HorizontalPosition(
9668 display_snapshot
9669 .x_for_display_point(display_point, text_layout_details)
9670 .into(),
9671 );
9672 (display_point, goal)
9673 })
9674 });
9675 }
9676 });
9677 }
9678
9679 pub fn select_enclosing_symbol(
9680 &mut self,
9681 _: &SelectEnclosingSymbol,
9682 window: &mut Window,
9683 cx: &mut Context<Self>,
9684 ) {
9685 let buffer = self.buffer.read(cx).snapshot(cx);
9686 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9687
9688 fn update_selection(
9689 selection: &Selection<usize>,
9690 buffer_snap: &MultiBufferSnapshot,
9691 ) -> Option<Selection<usize>> {
9692 let cursor = selection.head();
9693 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9694 for symbol in symbols.iter().rev() {
9695 let start = symbol.range.start.to_offset(buffer_snap);
9696 let end = symbol.range.end.to_offset(buffer_snap);
9697 let new_range = start..end;
9698 if start < selection.start || end > selection.end {
9699 return Some(Selection {
9700 id: selection.id,
9701 start: new_range.start,
9702 end: new_range.end,
9703 goal: SelectionGoal::None,
9704 reversed: selection.reversed,
9705 });
9706 }
9707 }
9708 None
9709 }
9710
9711 let mut selected_larger_symbol = false;
9712 let new_selections = old_selections
9713 .iter()
9714 .map(|selection| match update_selection(selection, &buffer) {
9715 Some(new_selection) => {
9716 if new_selection.range() != selection.range() {
9717 selected_larger_symbol = true;
9718 }
9719 new_selection
9720 }
9721 None => selection.clone(),
9722 })
9723 .collect::<Vec<_>>();
9724
9725 if selected_larger_symbol {
9726 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9727 s.select(new_selections);
9728 });
9729 }
9730 }
9731
9732 pub fn select_larger_syntax_node(
9733 &mut self,
9734 _: &SelectLargerSyntaxNode,
9735 window: &mut Window,
9736 cx: &mut Context<Self>,
9737 ) {
9738 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9739 let buffer = self.buffer.read(cx).snapshot(cx);
9740 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9741
9742 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9743 let mut selected_larger_node = false;
9744 let new_selections = old_selections
9745 .iter()
9746 .map(|selection| {
9747 let old_range = selection.start..selection.end;
9748 let mut new_range = old_range.clone();
9749 let mut new_node = None;
9750 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
9751 {
9752 new_node = Some(node);
9753 new_range = containing_range;
9754 if !display_map.intersects_fold(new_range.start)
9755 && !display_map.intersects_fold(new_range.end)
9756 {
9757 break;
9758 }
9759 }
9760
9761 if let Some(node) = new_node {
9762 // Log the ancestor, to support using this action as a way to explore TreeSitter
9763 // nodes. Parent and grandparent are also logged because this operation will not
9764 // visit nodes that have the same range as their parent.
9765 log::info!("Node: {node:?}");
9766 let parent = node.parent();
9767 log::info!("Parent: {parent:?}");
9768 let grandparent = parent.and_then(|x| x.parent());
9769 log::info!("Grandparent: {grandparent:?}");
9770 }
9771
9772 selected_larger_node |= new_range != old_range;
9773 Selection {
9774 id: selection.id,
9775 start: new_range.start,
9776 end: new_range.end,
9777 goal: SelectionGoal::None,
9778 reversed: selection.reversed,
9779 }
9780 })
9781 .collect::<Vec<_>>();
9782
9783 if selected_larger_node {
9784 stack.push(old_selections);
9785 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9786 s.select(new_selections);
9787 });
9788 }
9789 self.select_larger_syntax_node_stack = stack;
9790 }
9791
9792 pub fn select_smaller_syntax_node(
9793 &mut self,
9794 _: &SelectSmallerSyntaxNode,
9795 window: &mut Window,
9796 cx: &mut Context<Self>,
9797 ) {
9798 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9799 if let Some(selections) = stack.pop() {
9800 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9801 s.select(selections.to_vec());
9802 });
9803 }
9804 self.select_larger_syntax_node_stack = stack;
9805 }
9806
9807 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
9808 if !EditorSettings::get_global(cx).gutter.runnables {
9809 self.clear_tasks();
9810 return Task::ready(());
9811 }
9812 let project = self.project.as_ref().map(Entity::downgrade);
9813 cx.spawn_in(window, |this, mut cx| async move {
9814 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
9815 let Some(project) = project.and_then(|p| p.upgrade()) else {
9816 return;
9817 };
9818 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9819 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9820 }) else {
9821 return;
9822 };
9823
9824 let hide_runnables = project
9825 .update(&mut cx, |project, cx| {
9826 // Do not display any test indicators in non-dev server remote projects.
9827 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9828 })
9829 .unwrap_or(true);
9830 if hide_runnables {
9831 return;
9832 }
9833 let new_rows =
9834 cx.background_executor()
9835 .spawn({
9836 let snapshot = display_snapshot.clone();
9837 async move {
9838 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9839 }
9840 })
9841 .await;
9842
9843 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9844 this.update(&mut cx, |this, _| {
9845 this.clear_tasks();
9846 for (key, value) in rows {
9847 this.insert_tasks(key, value);
9848 }
9849 })
9850 .ok();
9851 })
9852 }
9853 fn fetch_runnable_ranges(
9854 snapshot: &DisplaySnapshot,
9855 range: Range<Anchor>,
9856 ) -> Vec<language::RunnableRange> {
9857 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9858 }
9859
9860 fn runnable_rows(
9861 project: Entity<Project>,
9862 snapshot: DisplaySnapshot,
9863 runnable_ranges: Vec<RunnableRange>,
9864 mut cx: AsyncWindowContext,
9865 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9866 runnable_ranges
9867 .into_iter()
9868 .filter_map(|mut runnable| {
9869 let tasks = cx
9870 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9871 .ok()?;
9872 if tasks.is_empty() {
9873 return None;
9874 }
9875
9876 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9877
9878 let row = snapshot
9879 .buffer_snapshot
9880 .buffer_line_for_row(MultiBufferRow(point.row))?
9881 .1
9882 .start
9883 .row;
9884
9885 let context_range =
9886 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9887 Some((
9888 (runnable.buffer_id, row),
9889 RunnableTasks {
9890 templates: tasks,
9891 offset: MultiBufferOffset(runnable.run_range.start),
9892 context_range,
9893 column: point.column,
9894 extra_variables: runnable.extra_captures,
9895 },
9896 ))
9897 })
9898 .collect()
9899 }
9900
9901 fn templates_with_tags(
9902 project: &Entity<Project>,
9903 runnable: &mut Runnable,
9904 cx: &mut App,
9905 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9906 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9907 let (worktree_id, file) = project
9908 .buffer_for_id(runnable.buffer, cx)
9909 .and_then(|buffer| buffer.read(cx).file())
9910 .map(|file| (file.worktree_id(cx), file.clone()))
9911 .unzip();
9912
9913 (
9914 project.task_store().read(cx).task_inventory().cloned(),
9915 worktree_id,
9916 file,
9917 )
9918 });
9919
9920 let tags = mem::take(&mut runnable.tags);
9921 let mut tags: Vec<_> = tags
9922 .into_iter()
9923 .flat_map(|tag| {
9924 let tag = tag.0.clone();
9925 inventory
9926 .as_ref()
9927 .into_iter()
9928 .flat_map(|inventory| {
9929 inventory.read(cx).list_tasks(
9930 file.clone(),
9931 Some(runnable.language.clone()),
9932 worktree_id,
9933 cx,
9934 )
9935 })
9936 .filter(move |(_, template)| {
9937 template.tags.iter().any(|source_tag| source_tag == &tag)
9938 })
9939 })
9940 .sorted_by_key(|(kind, _)| kind.to_owned())
9941 .collect();
9942 if let Some((leading_tag_source, _)) = tags.first() {
9943 // Strongest source wins; if we have worktree tag binding, prefer that to
9944 // global and language bindings;
9945 // if we have a global binding, prefer that to language binding.
9946 let first_mismatch = tags
9947 .iter()
9948 .position(|(tag_source, _)| tag_source != leading_tag_source);
9949 if let Some(index) = first_mismatch {
9950 tags.truncate(index);
9951 }
9952 }
9953
9954 tags
9955 }
9956
9957 pub fn move_to_enclosing_bracket(
9958 &mut self,
9959 _: &MoveToEnclosingBracket,
9960 window: &mut Window,
9961 cx: &mut Context<Self>,
9962 ) {
9963 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9964 s.move_offsets_with(|snapshot, selection| {
9965 let Some(enclosing_bracket_ranges) =
9966 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9967 else {
9968 return;
9969 };
9970
9971 let mut best_length = usize::MAX;
9972 let mut best_inside = false;
9973 let mut best_in_bracket_range = false;
9974 let mut best_destination = None;
9975 for (open, close) in enclosing_bracket_ranges {
9976 let close = close.to_inclusive();
9977 let length = close.end() - open.start;
9978 let inside = selection.start >= open.end && selection.end <= *close.start();
9979 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9980 || close.contains(&selection.head());
9981
9982 // If best is next to a bracket and current isn't, skip
9983 if !in_bracket_range && best_in_bracket_range {
9984 continue;
9985 }
9986
9987 // Prefer smaller lengths unless best is inside and current isn't
9988 if length > best_length && (best_inside || !inside) {
9989 continue;
9990 }
9991
9992 best_length = length;
9993 best_inside = inside;
9994 best_in_bracket_range = in_bracket_range;
9995 best_destination = Some(
9996 if close.contains(&selection.start) && close.contains(&selection.end) {
9997 if inside {
9998 open.end
9999 } else {
10000 open.start
10001 }
10002 } else if inside {
10003 *close.start()
10004 } else {
10005 *close.end()
10006 },
10007 );
10008 }
10009
10010 if let Some(destination) = best_destination {
10011 selection.collapse_to(destination, SelectionGoal::None);
10012 }
10013 })
10014 });
10015 }
10016
10017 pub fn undo_selection(
10018 &mut self,
10019 _: &UndoSelection,
10020 window: &mut Window,
10021 cx: &mut Context<Self>,
10022 ) {
10023 self.end_selection(window, cx);
10024 self.selection_history.mode = SelectionHistoryMode::Undoing;
10025 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10026 self.change_selections(None, window, cx, |s| {
10027 s.select_anchors(entry.selections.to_vec())
10028 });
10029 self.select_next_state = entry.select_next_state;
10030 self.select_prev_state = entry.select_prev_state;
10031 self.add_selections_state = entry.add_selections_state;
10032 self.request_autoscroll(Autoscroll::newest(), cx);
10033 }
10034 self.selection_history.mode = SelectionHistoryMode::Normal;
10035 }
10036
10037 pub fn redo_selection(
10038 &mut self,
10039 _: &RedoSelection,
10040 window: &mut Window,
10041 cx: &mut Context<Self>,
10042 ) {
10043 self.end_selection(window, cx);
10044 self.selection_history.mode = SelectionHistoryMode::Redoing;
10045 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10046 self.change_selections(None, window, cx, |s| {
10047 s.select_anchors(entry.selections.to_vec())
10048 });
10049 self.select_next_state = entry.select_next_state;
10050 self.select_prev_state = entry.select_prev_state;
10051 self.add_selections_state = entry.add_selections_state;
10052 self.request_autoscroll(Autoscroll::newest(), cx);
10053 }
10054 self.selection_history.mode = SelectionHistoryMode::Normal;
10055 }
10056
10057 pub fn expand_excerpts(
10058 &mut self,
10059 action: &ExpandExcerpts,
10060 _: &mut Window,
10061 cx: &mut Context<Self>,
10062 ) {
10063 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10064 }
10065
10066 pub fn expand_excerpts_down(
10067 &mut self,
10068 action: &ExpandExcerptsDown,
10069 _: &mut Window,
10070 cx: &mut Context<Self>,
10071 ) {
10072 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10073 }
10074
10075 pub fn expand_excerpts_up(
10076 &mut self,
10077 action: &ExpandExcerptsUp,
10078 _: &mut Window,
10079 cx: &mut Context<Self>,
10080 ) {
10081 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10082 }
10083
10084 pub fn expand_excerpts_for_direction(
10085 &mut self,
10086 lines: u32,
10087 direction: ExpandExcerptDirection,
10088
10089 cx: &mut Context<Self>,
10090 ) {
10091 let selections = self.selections.disjoint_anchors();
10092
10093 let lines = if lines == 0 {
10094 EditorSettings::get_global(cx).expand_excerpt_lines
10095 } else {
10096 lines
10097 };
10098
10099 self.buffer.update(cx, |buffer, cx| {
10100 let snapshot = buffer.snapshot(cx);
10101 let mut excerpt_ids = selections
10102 .iter()
10103 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10104 .collect::<Vec<_>>();
10105 excerpt_ids.sort();
10106 excerpt_ids.dedup();
10107 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10108 })
10109 }
10110
10111 pub fn expand_excerpt(
10112 &mut self,
10113 excerpt: ExcerptId,
10114 direction: ExpandExcerptDirection,
10115 cx: &mut Context<Self>,
10116 ) {
10117 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10118 self.buffer.update(cx, |buffer, cx| {
10119 buffer.expand_excerpts([excerpt], lines, direction, cx)
10120 })
10121 }
10122
10123 pub fn go_to_singleton_buffer_point(
10124 &mut self,
10125 point: Point,
10126 window: &mut Window,
10127 cx: &mut Context<Self>,
10128 ) {
10129 self.go_to_singleton_buffer_range(point..point, window, cx);
10130 }
10131
10132 pub fn go_to_singleton_buffer_range(
10133 &mut self,
10134 range: Range<Point>,
10135 window: &mut Window,
10136 cx: &mut Context<Self>,
10137 ) {
10138 let multibuffer = self.buffer().read(cx);
10139 let Some(buffer) = multibuffer.as_singleton() else {
10140 return;
10141 };
10142 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10143 return;
10144 };
10145 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10146 return;
10147 };
10148 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10149 s.select_anchor_ranges([start..end])
10150 });
10151 }
10152
10153 fn go_to_diagnostic(
10154 &mut self,
10155 _: &GoToDiagnostic,
10156 window: &mut Window,
10157 cx: &mut Context<Self>,
10158 ) {
10159 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10160 }
10161
10162 fn go_to_prev_diagnostic(
10163 &mut self,
10164 _: &GoToPrevDiagnostic,
10165 window: &mut Window,
10166 cx: &mut Context<Self>,
10167 ) {
10168 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10169 }
10170
10171 pub fn go_to_diagnostic_impl(
10172 &mut self,
10173 direction: Direction,
10174 window: &mut Window,
10175 cx: &mut Context<Self>,
10176 ) {
10177 let buffer = self.buffer.read(cx).snapshot(cx);
10178 let selection = self.selections.newest::<usize>(cx);
10179
10180 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10181 if direction == Direction::Next {
10182 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10183 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10184 return;
10185 };
10186 self.activate_diagnostics(
10187 buffer_id,
10188 popover.local_diagnostic.diagnostic.group_id,
10189 window,
10190 cx,
10191 );
10192 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10193 let primary_range_start = active_diagnostics.primary_range.start;
10194 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10195 let mut new_selection = s.newest_anchor().clone();
10196 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10197 s.select_anchors(vec![new_selection.clone()]);
10198 });
10199 self.refresh_inline_completion(false, true, window, cx);
10200 }
10201 return;
10202 }
10203 }
10204
10205 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10206 active_diagnostics
10207 .primary_range
10208 .to_offset(&buffer)
10209 .to_inclusive()
10210 });
10211 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10212 if active_primary_range.contains(&selection.head()) {
10213 *active_primary_range.start()
10214 } else {
10215 selection.head()
10216 }
10217 } else {
10218 selection.head()
10219 };
10220 let snapshot = self.snapshot(window, cx);
10221 loop {
10222 let mut diagnostics;
10223 if direction == Direction::Prev {
10224 diagnostics = buffer
10225 .diagnostics_in_range::<usize>(0..search_start)
10226 .collect::<Vec<_>>();
10227 diagnostics.reverse();
10228 } else {
10229 diagnostics = buffer
10230 .diagnostics_in_range::<usize>(search_start..buffer.len())
10231 .collect::<Vec<_>>();
10232 };
10233 let group = diagnostics
10234 .into_iter()
10235 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10236 // relies on diagnostics_in_range to return diagnostics with the same starting range to
10237 // be sorted in a stable way
10238 // skip until we are at current active diagnostic, if it exists
10239 .skip_while(|entry| {
10240 let is_in_range = match direction {
10241 Direction::Prev => entry.range.end > search_start,
10242 Direction::Next => entry.range.start < search_start,
10243 };
10244 is_in_range
10245 && self
10246 .active_diagnostics
10247 .as_ref()
10248 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
10249 })
10250 .find_map(|entry| {
10251 if entry.diagnostic.is_primary
10252 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
10253 && entry.range.start != entry.range.end
10254 // if we match with the active diagnostic, skip it
10255 && Some(entry.diagnostic.group_id)
10256 != self.active_diagnostics.as_ref().map(|d| d.group_id)
10257 {
10258 Some((entry.range, entry.diagnostic.group_id))
10259 } else {
10260 None
10261 }
10262 });
10263
10264 if let Some((primary_range, group_id)) = group {
10265 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10266 return;
10267 };
10268 self.activate_diagnostics(buffer_id, group_id, window, cx);
10269 if self.active_diagnostics.is_some() {
10270 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10271 s.select(vec![Selection {
10272 id: selection.id,
10273 start: primary_range.start,
10274 end: primary_range.start,
10275 reversed: false,
10276 goal: SelectionGoal::None,
10277 }]);
10278 });
10279 self.refresh_inline_completion(false, true, window, cx);
10280 }
10281 break;
10282 } else {
10283 // Cycle around to the start of the buffer, potentially moving back to the start of
10284 // the currently active diagnostic.
10285 active_primary_range.take();
10286 if direction == Direction::Prev {
10287 if search_start == buffer.len() {
10288 break;
10289 } else {
10290 search_start = buffer.len();
10291 }
10292 } else if search_start == 0 {
10293 break;
10294 } else {
10295 search_start = 0;
10296 }
10297 }
10298 }
10299 }
10300
10301 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10302 let snapshot = self.snapshot(window, cx);
10303 let selection = self.selections.newest::<Point>(cx);
10304 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10305 }
10306
10307 fn go_to_hunk_after_position(
10308 &mut self,
10309 snapshot: &EditorSnapshot,
10310 position: Point,
10311 window: &mut Window,
10312 cx: &mut Context<Editor>,
10313 ) -> Option<MultiBufferDiffHunk> {
10314 let mut hunk = snapshot
10315 .buffer_snapshot
10316 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10317 .find(|hunk| hunk.row_range.start.0 > position.row);
10318 if hunk.is_none() {
10319 hunk = snapshot
10320 .buffer_snapshot
10321 .diff_hunks_in_range(Point::zero()..position)
10322 .find(|hunk| hunk.row_range.end.0 < position.row)
10323 }
10324 if let Some(hunk) = &hunk {
10325 let destination = Point::new(hunk.row_range.start.0, 0);
10326 self.unfold_ranges(&[destination..destination], false, false, cx);
10327 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10328 s.select_ranges(vec![destination..destination]);
10329 });
10330 }
10331
10332 hunk
10333 }
10334
10335 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10336 let snapshot = self.snapshot(window, cx);
10337 let selection = self.selections.newest::<Point>(cx);
10338 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10339 }
10340
10341 fn go_to_hunk_before_position(
10342 &mut self,
10343 snapshot: &EditorSnapshot,
10344 position: Point,
10345 window: &mut Window,
10346 cx: &mut Context<Editor>,
10347 ) -> Option<MultiBufferDiffHunk> {
10348 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10349 if hunk.is_none() {
10350 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10351 }
10352 if let Some(hunk) = &hunk {
10353 let destination = Point::new(hunk.row_range.start.0, 0);
10354 self.unfold_ranges(&[destination..destination], false, false, cx);
10355 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10356 s.select_ranges(vec![destination..destination]);
10357 });
10358 }
10359
10360 hunk
10361 }
10362
10363 pub fn go_to_definition(
10364 &mut self,
10365 _: &GoToDefinition,
10366 window: &mut Window,
10367 cx: &mut Context<Self>,
10368 ) -> Task<Result<Navigated>> {
10369 let definition =
10370 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10371 cx.spawn_in(window, |editor, mut cx| async move {
10372 if definition.await? == Navigated::Yes {
10373 return Ok(Navigated::Yes);
10374 }
10375 match editor.update_in(&mut cx, |editor, window, cx| {
10376 editor.find_all_references(&FindAllReferences, window, cx)
10377 })? {
10378 Some(references) => references.await,
10379 None => Ok(Navigated::No),
10380 }
10381 })
10382 }
10383
10384 pub fn go_to_declaration(
10385 &mut self,
10386 _: &GoToDeclaration,
10387 window: &mut Window,
10388 cx: &mut Context<Self>,
10389 ) -> Task<Result<Navigated>> {
10390 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10391 }
10392
10393 pub fn go_to_declaration_split(
10394 &mut self,
10395 _: &GoToDeclaration,
10396 window: &mut Window,
10397 cx: &mut Context<Self>,
10398 ) -> Task<Result<Navigated>> {
10399 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10400 }
10401
10402 pub fn go_to_implementation(
10403 &mut self,
10404 _: &GoToImplementation,
10405 window: &mut Window,
10406 cx: &mut Context<Self>,
10407 ) -> Task<Result<Navigated>> {
10408 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10409 }
10410
10411 pub fn go_to_implementation_split(
10412 &mut self,
10413 _: &GoToImplementationSplit,
10414 window: &mut Window,
10415 cx: &mut Context<Self>,
10416 ) -> Task<Result<Navigated>> {
10417 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10418 }
10419
10420 pub fn go_to_type_definition(
10421 &mut self,
10422 _: &GoToTypeDefinition,
10423 window: &mut Window,
10424 cx: &mut Context<Self>,
10425 ) -> Task<Result<Navigated>> {
10426 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10427 }
10428
10429 pub fn go_to_definition_split(
10430 &mut self,
10431 _: &GoToDefinitionSplit,
10432 window: &mut Window,
10433 cx: &mut Context<Self>,
10434 ) -> Task<Result<Navigated>> {
10435 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10436 }
10437
10438 pub fn go_to_type_definition_split(
10439 &mut self,
10440 _: &GoToTypeDefinitionSplit,
10441 window: &mut Window,
10442 cx: &mut Context<Self>,
10443 ) -> Task<Result<Navigated>> {
10444 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10445 }
10446
10447 fn go_to_definition_of_kind(
10448 &mut self,
10449 kind: GotoDefinitionKind,
10450 split: bool,
10451 window: &mut Window,
10452 cx: &mut Context<Self>,
10453 ) -> Task<Result<Navigated>> {
10454 let Some(provider) = self.semantics_provider.clone() else {
10455 return Task::ready(Ok(Navigated::No));
10456 };
10457 let head = self.selections.newest::<usize>(cx).head();
10458 let buffer = self.buffer.read(cx);
10459 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10460 text_anchor
10461 } else {
10462 return Task::ready(Ok(Navigated::No));
10463 };
10464
10465 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10466 return Task::ready(Ok(Navigated::No));
10467 };
10468
10469 cx.spawn_in(window, |editor, mut cx| async move {
10470 let definitions = definitions.await?;
10471 let navigated = editor
10472 .update_in(&mut cx, |editor, window, cx| {
10473 editor.navigate_to_hover_links(
10474 Some(kind),
10475 definitions
10476 .into_iter()
10477 .filter(|location| {
10478 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10479 })
10480 .map(HoverLink::Text)
10481 .collect::<Vec<_>>(),
10482 split,
10483 window,
10484 cx,
10485 )
10486 })?
10487 .await?;
10488 anyhow::Ok(navigated)
10489 })
10490 }
10491
10492 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10493 let selection = self.selections.newest_anchor();
10494 let head = selection.head();
10495 let tail = selection.tail();
10496
10497 let Some((buffer, start_position)) =
10498 self.buffer.read(cx).text_anchor_for_position(head, cx)
10499 else {
10500 return;
10501 };
10502
10503 let end_position = if head != tail {
10504 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10505 return;
10506 };
10507 Some(pos)
10508 } else {
10509 None
10510 };
10511
10512 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10513 let url = if let Some(end_pos) = end_position {
10514 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10515 } else {
10516 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10517 };
10518
10519 if let Some(url) = url {
10520 editor.update(&mut cx, |_, cx| {
10521 cx.open_url(&url);
10522 })
10523 } else {
10524 Ok(())
10525 }
10526 });
10527
10528 url_finder.detach();
10529 }
10530
10531 pub fn open_selected_filename(
10532 &mut self,
10533 _: &OpenSelectedFilename,
10534 window: &mut Window,
10535 cx: &mut Context<Self>,
10536 ) {
10537 let Some(workspace) = self.workspace() else {
10538 return;
10539 };
10540
10541 let position = self.selections.newest_anchor().head();
10542
10543 let Some((buffer, buffer_position)) =
10544 self.buffer.read(cx).text_anchor_for_position(position, cx)
10545 else {
10546 return;
10547 };
10548
10549 let project = self.project.clone();
10550
10551 cx.spawn_in(window, |_, mut cx| async move {
10552 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10553
10554 if let Some((_, path)) = result {
10555 workspace
10556 .update_in(&mut cx, |workspace, window, cx| {
10557 workspace.open_resolved_path(path, window, cx)
10558 })?
10559 .await?;
10560 }
10561 anyhow::Ok(())
10562 })
10563 .detach();
10564 }
10565
10566 pub(crate) fn navigate_to_hover_links(
10567 &mut self,
10568 kind: Option<GotoDefinitionKind>,
10569 mut definitions: Vec<HoverLink>,
10570 split: bool,
10571 window: &mut Window,
10572 cx: &mut Context<Editor>,
10573 ) -> Task<Result<Navigated>> {
10574 // If there is one definition, just open it directly
10575 if definitions.len() == 1 {
10576 let definition = definitions.pop().unwrap();
10577
10578 enum TargetTaskResult {
10579 Location(Option<Location>),
10580 AlreadyNavigated,
10581 }
10582
10583 let target_task = match definition {
10584 HoverLink::Text(link) => {
10585 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10586 }
10587 HoverLink::InlayHint(lsp_location, server_id) => {
10588 let computation =
10589 self.compute_target_location(lsp_location, server_id, window, cx);
10590 cx.background_executor().spawn(async move {
10591 let location = computation.await?;
10592 Ok(TargetTaskResult::Location(location))
10593 })
10594 }
10595 HoverLink::Url(url) => {
10596 cx.open_url(&url);
10597 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10598 }
10599 HoverLink::File(path) => {
10600 if let Some(workspace) = self.workspace() {
10601 cx.spawn_in(window, |_, mut cx| async move {
10602 workspace
10603 .update_in(&mut cx, |workspace, window, cx| {
10604 workspace.open_resolved_path(path, window, cx)
10605 })?
10606 .await
10607 .map(|_| TargetTaskResult::AlreadyNavigated)
10608 })
10609 } else {
10610 Task::ready(Ok(TargetTaskResult::Location(None)))
10611 }
10612 }
10613 };
10614 cx.spawn_in(window, |editor, mut cx| async move {
10615 let target = match target_task.await.context("target resolution task")? {
10616 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10617 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10618 TargetTaskResult::Location(Some(target)) => target,
10619 };
10620
10621 editor.update_in(&mut cx, |editor, window, cx| {
10622 let Some(workspace) = editor.workspace() else {
10623 return Navigated::No;
10624 };
10625 let pane = workspace.read(cx).active_pane().clone();
10626
10627 let range = target.range.to_point(target.buffer.read(cx));
10628 let range = editor.range_for_match(&range);
10629 let range = collapse_multiline_range(range);
10630
10631 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10632 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10633 } else {
10634 window.defer(cx, move |window, cx| {
10635 let target_editor: Entity<Self> =
10636 workspace.update(cx, |workspace, cx| {
10637 let pane = if split {
10638 workspace.adjacent_pane(window, cx)
10639 } else {
10640 workspace.active_pane().clone()
10641 };
10642
10643 workspace.open_project_item(
10644 pane,
10645 target.buffer.clone(),
10646 true,
10647 true,
10648 window,
10649 cx,
10650 )
10651 });
10652 target_editor.update(cx, |target_editor, cx| {
10653 // When selecting a definition in a different buffer, disable the nav history
10654 // to avoid creating a history entry at the previous cursor location.
10655 pane.update(cx, |pane, _| pane.disable_history());
10656 target_editor.go_to_singleton_buffer_range(range, window, cx);
10657 pane.update(cx, |pane, _| pane.enable_history());
10658 });
10659 });
10660 }
10661 Navigated::Yes
10662 })
10663 })
10664 } else if !definitions.is_empty() {
10665 cx.spawn_in(window, |editor, mut cx| async move {
10666 let (title, location_tasks, workspace) = editor
10667 .update_in(&mut cx, |editor, window, cx| {
10668 let tab_kind = match kind {
10669 Some(GotoDefinitionKind::Implementation) => "Implementations",
10670 _ => "Definitions",
10671 };
10672 let title = definitions
10673 .iter()
10674 .find_map(|definition| match definition {
10675 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10676 let buffer = origin.buffer.read(cx);
10677 format!(
10678 "{} for {}",
10679 tab_kind,
10680 buffer
10681 .text_for_range(origin.range.clone())
10682 .collect::<String>()
10683 )
10684 }),
10685 HoverLink::InlayHint(_, _) => None,
10686 HoverLink::Url(_) => None,
10687 HoverLink::File(_) => None,
10688 })
10689 .unwrap_or(tab_kind.to_string());
10690 let location_tasks = definitions
10691 .into_iter()
10692 .map(|definition| match definition {
10693 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10694 HoverLink::InlayHint(lsp_location, server_id) => editor
10695 .compute_target_location(lsp_location, server_id, window, cx),
10696 HoverLink::Url(_) => Task::ready(Ok(None)),
10697 HoverLink::File(_) => Task::ready(Ok(None)),
10698 })
10699 .collect::<Vec<_>>();
10700 (title, location_tasks, editor.workspace().clone())
10701 })
10702 .context("location tasks preparation")?;
10703
10704 let locations = future::join_all(location_tasks)
10705 .await
10706 .into_iter()
10707 .filter_map(|location| location.transpose())
10708 .collect::<Result<_>>()
10709 .context("location tasks")?;
10710
10711 let Some(workspace) = workspace else {
10712 return Ok(Navigated::No);
10713 };
10714 let opened = workspace
10715 .update_in(&mut cx, |workspace, window, cx| {
10716 Self::open_locations_in_multibuffer(
10717 workspace,
10718 locations,
10719 title,
10720 split,
10721 MultibufferSelectionMode::First,
10722 window,
10723 cx,
10724 )
10725 })
10726 .ok();
10727
10728 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10729 })
10730 } else {
10731 Task::ready(Ok(Navigated::No))
10732 }
10733 }
10734
10735 fn compute_target_location(
10736 &self,
10737 lsp_location: lsp::Location,
10738 server_id: LanguageServerId,
10739 window: &mut Window,
10740 cx: &mut Context<Self>,
10741 ) -> Task<anyhow::Result<Option<Location>>> {
10742 let Some(project) = self.project.clone() else {
10743 return Task::ready(Ok(None));
10744 };
10745
10746 cx.spawn_in(window, move |editor, mut cx| async move {
10747 let location_task = editor.update(&mut cx, |_, cx| {
10748 project.update(cx, |project, cx| {
10749 let language_server_name = project
10750 .language_server_statuses(cx)
10751 .find(|(id, _)| server_id == *id)
10752 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10753 language_server_name.map(|language_server_name| {
10754 project.open_local_buffer_via_lsp(
10755 lsp_location.uri.clone(),
10756 server_id,
10757 language_server_name,
10758 cx,
10759 )
10760 })
10761 })
10762 })?;
10763 let location = match location_task {
10764 Some(task) => Some({
10765 let target_buffer_handle = task.await.context("open local buffer")?;
10766 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10767 let target_start = target_buffer
10768 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10769 let target_end = target_buffer
10770 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10771 target_buffer.anchor_after(target_start)
10772 ..target_buffer.anchor_before(target_end)
10773 })?;
10774 Location {
10775 buffer: target_buffer_handle,
10776 range,
10777 }
10778 }),
10779 None => None,
10780 };
10781 Ok(location)
10782 })
10783 }
10784
10785 pub fn find_all_references(
10786 &mut self,
10787 _: &FindAllReferences,
10788 window: &mut Window,
10789 cx: &mut Context<Self>,
10790 ) -> Option<Task<Result<Navigated>>> {
10791 let selection = self.selections.newest::<usize>(cx);
10792 let multi_buffer = self.buffer.read(cx);
10793 let head = selection.head();
10794
10795 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10796 let head_anchor = multi_buffer_snapshot.anchor_at(
10797 head,
10798 if head < selection.tail() {
10799 Bias::Right
10800 } else {
10801 Bias::Left
10802 },
10803 );
10804
10805 match self
10806 .find_all_references_task_sources
10807 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10808 {
10809 Ok(_) => {
10810 log::info!(
10811 "Ignoring repeated FindAllReferences invocation with the position of already running task"
10812 );
10813 return None;
10814 }
10815 Err(i) => {
10816 self.find_all_references_task_sources.insert(i, head_anchor);
10817 }
10818 }
10819
10820 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10821 let workspace = self.workspace()?;
10822 let project = workspace.read(cx).project().clone();
10823 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10824 Some(cx.spawn_in(window, |editor, mut cx| async move {
10825 let _cleanup = defer({
10826 let mut cx = cx.clone();
10827 move || {
10828 let _ = editor.update(&mut cx, |editor, _| {
10829 if let Ok(i) =
10830 editor
10831 .find_all_references_task_sources
10832 .binary_search_by(|anchor| {
10833 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10834 })
10835 {
10836 editor.find_all_references_task_sources.remove(i);
10837 }
10838 });
10839 }
10840 });
10841
10842 let locations = references.await?;
10843 if locations.is_empty() {
10844 return anyhow::Ok(Navigated::No);
10845 }
10846
10847 workspace.update_in(&mut cx, |workspace, window, cx| {
10848 let title = locations
10849 .first()
10850 .as_ref()
10851 .map(|location| {
10852 let buffer = location.buffer.read(cx);
10853 format!(
10854 "References to `{}`",
10855 buffer
10856 .text_for_range(location.range.clone())
10857 .collect::<String>()
10858 )
10859 })
10860 .unwrap();
10861 Self::open_locations_in_multibuffer(
10862 workspace,
10863 locations,
10864 title,
10865 false,
10866 MultibufferSelectionMode::First,
10867 window,
10868 cx,
10869 );
10870 Navigated::Yes
10871 })
10872 }))
10873 }
10874
10875 /// Opens a multibuffer with the given project locations in it
10876 pub fn open_locations_in_multibuffer(
10877 workspace: &mut Workspace,
10878 mut locations: Vec<Location>,
10879 title: String,
10880 split: bool,
10881 multibuffer_selection_mode: MultibufferSelectionMode,
10882 window: &mut Window,
10883 cx: &mut Context<Workspace>,
10884 ) {
10885 // If there are multiple definitions, open them in a multibuffer
10886 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10887 let mut locations = locations.into_iter().peekable();
10888 let mut ranges = Vec::new();
10889 let capability = workspace.project().read(cx).capability();
10890
10891 let excerpt_buffer = cx.new(|cx| {
10892 let mut multibuffer = MultiBuffer::new(capability);
10893 while let Some(location) = locations.next() {
10894 let buffer = location.buffer.read(cx);
10895 let mut ranges_for_buffer = Vec::new();
10896 let range = location.range.to_offset(buffer);
10897 ranges_for_buffer.push(range.clone());
10898
10899 while let Some(next_location) = locations.peek() {
10900 if next_location.buffer == location.buffer {
10901 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10902 locations.next();
10903 } else {
10904 break;
10905 }
10906 }
10907
10908 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10909 ranges.extend(multibuffer.push_excerpts_with_context_lines(
10910 location.buffer.clone(),
10911 ranges_for_buffer,
10912 DEFAULT_MULTIBUFFER_CONTEXT,
10913 cx,
10914 ))
10915 }
10916
10917 multibuffer.with_title(title)
10918 });
10919
10920 let editor = cx.new(|cx| {
10921 Editor::for_multibuffer(
10922 excerpt_buffer,
10923 Some(workspace.project().clone()),
10924 true,
10925 window,
10926 cx,
10927 )
10928 });
10929 editor.update(cx, |editor, cx| {
10930 match multibuffer_selection_mode {
10931 MultibufferSelectionMode::First => {
10932 if let Some(first_range) = ranges.first() {
10933 editor.change_selections(None, window, cx, |selections| {
10934 selections.clear_disjoint();
10935 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10936 });
10937 }
10938 editor.highlight_background::<Self>(
10939 &ranges,
10940 |theme| theme.editor_highlighted_line_background,
10941 cx,
10942 );
10943 }
10944 MultibufferSelectionMode::All => {
10945 editor.change_selections(None, window, cx, |selections| {
10946 selections.clear_disjoint();
10947 selections.select_anchor_ranges(ranges);
10948 });
10949 }
10950 }
10951 editor.register_buffers_with_language_servers(cx);
10952 });
10953
10954 let item = Box::new(editor);
10955 let item_id = item.item_id();
10956
10957 if split {
10958 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
10959 } else {
10960 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10961 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10962 pane.close_current_preview_item(window, cx)
10963 } else {
10964 None
10965 }
10966 });
10967 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
10968 }
10969 workspace.active_pane().update(cx, |pane, cx| {
10970 pane.set_preview_item_id(Some(item_id), cx);
10971 });
10972 }
10973
10974 pub fn rename(
10975 &mut self,
10976 _: &Rename,
10977 window: &mut Window,
10978 cx: &mut Context<Self>,
10979 ) -> Option<Task<Result<()>>> {
10980 use language::ToOffset as _;
10981
10982 let provider = self.semantics_provider.clone()?;
10983 let selection = self.selections.newest_anchor().clone();
10984 let (cursor_buffer, cursor_buffer_position) = self
10985 .buffer
10986 .read(cx)
10987 .text_anchor_for_position(selection.head(), cx)?;
10988 let (tail_buffer, cursor_buffer_position_end) = self
10989 .buffer
10990 .read(cx)
10991 .text_anchor_for_position(selection.tail(), cx)?;
10992 if tail_buffer != cursor_buffer {
10993 return None;
10994 }
10995
10996 let snapshot = cursor_buffer.read(cx).snapshot();
10997 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10998 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10999 let prepare_rename = provider
11000 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11001 .unwrap_or_else(|| Task::ready(Ok(None)));
11002 drop(snapshot);
11003
11004 Some(cx.spawn_in(window, |this, mut cx| async move {
11005 let rename_range = if let Some(range) = prepare_rename.await? {
11006 Some(range)
11007 } else {
11008 this.update(&mut cx, |this, cx| {
11009 let buffer = this.buffer.read(cx).snapshot(cx);
11010 let mut buffer_highlights = this
11011 .document_highlights_for_position(selection.head(), &buffer)
11012 .filter(|highlight| {
11013 highlight.start.excerpt_id == selection.head().excerpt_id
11014 && highlight.end.excerpt_id == selection.head().excerpt_id
11015 });
11016 buffer_highlights
11017 .next()
11018 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11019 })?
11020 };
11021 if let Some(rename_range) = rename_range {
11022 this.update_in(&mut cx, |this, window, cx| {
11023 let snapshot = cursor_buffer.read(cx).snapshot();
11024 let rename_buffer_range = rename_range.to_offset(&snapshot);
11025 let cursor_offset_in_rename_range =
11026 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11027 let cursor_offset_in_rename_range_end =
11028 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11029
11030 this.take_rename(false, window, cx);
11031 let buffer = this.buffer.read(cx).read(cx);
11032 let cursor_offset = selection.head().to_offset(&buffer);
11033 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11034 let rename_end = rename_start + rename_buffer_range.len();
11035 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11036 let mut old_highlight_id = None;
11037 let old_name: Arc<str> = buffer
11038 .chunks(rename_start..rename_end, true)
11039 .map(|chunk| {
11040 if old_highlight_id.is_none() {
11041 old_highlight_id = chunk.syntax_highlight_id;
11042 }
11043 chunk.text
11044 })
11045 .collect::<String>()
11046 .into();
11047
11048 drop(buffer);
11049
11050 // Position the selection in the rename editor so that it matches the current selection.
11051 this.show_local_selections = false;
11052 let rename_editor = cx.new(|cx| {
11053 let mut editor = Editor::single_line(window, cx);
11054 editor.buffer.update(cx, |buffer, cx| {
11055 buffer.edit([(0..0, old_name.clone())], None, cx)
11056 });
11057 let rename_selection_range = match cursor_offset_in_rename_range
11058 .cmp(&cursor_offset_in_rename_range_end)
11059 {
11060 Ordering::Equal => {
11061 editor.select_all(&SelectAll, window, cx);
11062 return editor;
11063 }
11064 Ordering::Less => {
11065 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11066 }
11067 Ordering::Greater => {
11068 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11069 }
11070 };
11071 if rename_selection_range.end > old_name.len() {
11072 editor.select_all(&SelectAll, window, cx);
11073 } else {
11074 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11075 s.select_ranges([rename_selection_range]);
11076 });
11077 }
11078 editor
11079 });
11080 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11081 if e == &EditorEvent::Focused {
11082 cx.emit(EditorEvent::FocusedIn)
11083 }
11084 })
11085 .detach();
11086
11087 let write_highlights =
11088 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11089 let read_highlights =
11090 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11091 let ranges = write_highlights
11092 .iter()
11093 .flat_map(|(_, ranges)| ranges.iter())
11094 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11095 .cloned()
11096 .collect();
11097
11098 this.highlight_text::<Rename>(
11099 ranges,
11100 HighlightStyle {
11101 fade_out: Some(0.6),
11102 ..Default::default()
11103 },
11104 cx,
11105 );
11106 let rename_focus_handle = rename_editor.focus_handle(cx);
11107 window.focus(&rename_focus_handle);
11108 let block_id = this.insert_blocks(
11109 [BlockProperties {
11110 style: BlockStyle::Flex,
11111 placement: BlockPlacement::Below(range.start),
11112 height: 1,
11113 render: Arc::new({
11114 let rename_editor = rename_editor.clone();
11115 move |cx: &mut BlockContext| {
11116 let mut text_style = cx.editor_style.text.clone();
11117 if let Some(highlight_style) = old_highlight_id
11118 .and_then(|h| h.style(&cx.editor_style.syntax))
11119 {
11120 text_style = text_style.highlight(highlight_style);
11121 }
11122 div()
11123 .block_mouse_down()
11124 .pl(cx.anchor_x)
11125 .child(EditorElement::new(
11126 &rename_editor,
11127 EditorStyle {
11128 background: cx.theme().system().transparent,
11129 local_player: cx.editor_style.local_player,
11130 text: text_style,
11131 scrollbar_width: cx.editor_style.scrollbar_width,
11132 syntax: cx.editor_style.syntax.clone(),
11133 status: cx.editor_style.status.clone(),
11134 inlay_hints_style: HighlightStyle {
11135 font_weight: Some(FontWeight::BOLD),
11136 ..make_inlay_hints_style(cx.app)
11137 },
11138 inline_completion_styles: make_suggestion_styles(
11139 cx.app,
11140 ),
11141 ..EditorStyle::default()
11142 },
11143 ))
11144 .into_any_element()
11145 }
11146 }),
11147 priority: 0,
11148 }],
11149 Some(Autoscroll::fit()),
11150 cx,
11151 )[0];
11152 this.pending_rename = Some(RenameState {
11153 range,
11154 old_name,
11155 editor: rename_editor,
11156 block_id,
11157 });
11158 })?;
11159 }
11160
11161 Ok(())
11162 }))
11163 }
11164
11165 pub fn confirm_rename(
11166 &mut self,
11167 _: &ConfirmRename,
11168 window: &mut Window,
11169 cx: &mut Context<Self>,
11170 ) -> Option<Task<Result<()>>> {
11171 let rename = self.take_rename(false, window, cx)?;
11172 let workspace = self.workspace()?.downgrade();
11173 let (buffer, start) = self
11174 .buffer
11175 .read(cx)
11176 .text_anchor_for_position(rename.range.start, cx)?;
11177 let (end_buffer, _) = self
11178 .buffer
11179 .read(cx)
11180 .text_anchor_for_position(rename.range.end, cx)?;
11181 if buffer != end_buffer {
11182 return None;
11183 }
11184
11185 let old_name = rename.old_name;
11186 let new_name = rename.editor.read(cx).text(cx);
11187
11188 let rename = self.semantics_provider.as_ref()?.perform_rename(
11189 &buffer,
11190 start,
11191 new_name.clone(),
11192 cx,
11193 )?;
11194
11195 Some(cx.spawn_in(window, |editor, mut cx| async move {
11196 let project_transaction = rename.await?;
11197 Self::open_project_transaction(
11198 &editor,
11199 workspace,
11200 project_transaction,
11201 format!("Rename: {} → {}", old_name, new_name),
11202 cx.clone(),
11203 )
11204 .await?;
11205
11206 editor.update(&mut cx, |editor, cx| {
11207 editor.refresh_document_highlights(cx);
11208 })?;
11209 Ok(())
11210 }))
11211 }
11212
11213 fn take_rename(
11214 &mut self,
11215 moving_cursor: bool,
11216 window: &mut Window,
11217 cx: &mut Context<Self>,
11218 ) -> Option<RenameState> {
11219 let rename = self.pending_rename.take()?;
11220 if rename.editor.focus_handle(cx).is_focused(window) {
11221 window.focus(&self.focus_handle);
11222 }
11223
11224 self.remove_blocks(
11225 [rename.block_id].into_iter().collect(),
11226 Some(Autoscroll::fit()),
11227 cx,
11228 );
11229 self.clear_highlights::<Rename>(cx);
11230 self.show_local_selections = true;
11231
11232 if moving_cursor {
11233 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11234 editor.selections.newest::<usize>(cx).head()
11235 });
11236
11237 // Update the selection to match the position of the selection inside
11238 // the rename editor.
11239 let snapshot = self.buffer.read(cx).read(cx);
11240 let rename_range = rename.range.to_offset(&snapshot);
11241 let cursor_in_editor = snapshot
11242 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11243 .min(rename_range.end);
11244 drop(snapshot);
11245
11246 self.change_selections(None, window, cx, |s| {
11247 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11248 });
11249 } else {
11250 self.refresh_document_highlights(cx);
11251 }
11252
11253 Some(rename)
11254 }
11255
11256 pub fn pending_rename(&self) -> Option<&RenameState> {
11257 self.pending_rename.as_ref()
11258 }
11259
11260 fn format(
11261 &mut self,
11262 _: &Format,
11263 window: &mut Window,
11264 cx: &mut Context<Self>,
11265 ) -> Option<Task<Result<()>>> {
11266 let project = match &self.project {
11267 Some(project) => project.clone(),
11268 None => return None,
11269 };
11270
11271 Some(self.perform_format(
11272 project,
11273 FormatTrigger::Manual,
11274 FormatTarget::Buffers,
11275 window,
11276 cx,
11277 ))
11278 }
11279
11280 fn format_selections(
11281 &mut self,
11282 _: &FormatSelections,
11283 window: &mut Window,
11284 cx: &mut Context<Self>,
11285 ) -> Option<Task<Result<()>>> {
11286 let project = match &self.project {
11287 Some(project) => project.clone(),
11288 None => return None,
11289 };
11290
11291 let ranges = self
11292 .selections
11293 .all_adjusted(cx)
11294 .into_iter()
11295 .map(|selection| selection.range())
11296 .collect_vec();
11297
11298 Some(self.perform_format(
11299 project,
11300 FormatTrigger::Manual,
11301 FormatTarget::Ranges(ranges),
11302 window,
11303 cx,
11304 ))
11305 }
11306
11307 fn perform_format(
11308 &mut self,
11309 project: Entity<Project>,
11310 trigger: FormatTrigger,
11311 target: FormatTarget,
11312 window: &mut Window,
11313 cx: &mut Context<Self>,
11314 ) -> Task<Result<()>> {
11315 let buffer = self.buffer.clone();
11316 let (buffers, target) = match target {
11317 FormatTarget::Buffers => {
11318 let mut buffers = buffer.read(cx).all_buffers();
11319 if trigger == FormatTrigger::Save {
11320 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11321 }
11322 (buffers, LspFormatTarget::Buffers)
11323 }
11324 FormatTarget::Ranges(selection_ranges) => {
11325 let multi_buffer = buffer.read(cx);
11326 let snapshot = multi_buffer.read(cx);
11327 let mut buffers = HashSet::default();
11328 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11329 BTreeMap::new();
11330 for selection_range in selection_ranges {
11331 for (buffer, buffer_range, _) in
11332 snapshot.range_to_buffer_ranges(selection_range)
11333 {
11334 let buffer_id = buffer.remote_id();
11335 let start = buffer.anchor_before(buffer_range.start);
11336 let end = buffer.anchor_after(buffer_range.end);
11337 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11338 buffer_id_to_ranges
11339 .entry(buffer_id)
11340 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11341 .or_insert_with(|| vec![start..end]);
11342 }
11343 }
11344 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11345 }
11346 };
11347
11348 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11349 let format = project.update(cx, |project, cx| {
11350 project.format(buffers, target, true, trigger, cx)
11351 });
11352
11353 cx.spawn_in(window, |_, mut cx| async move {
11354 let transaction = futures::select_biased! {
11355 () = timeout => {
11356 log::warn!("timed out waiting for formatting");
11357 None
11358 }
11359 transaction = format.log_err().fuse() => transaction,
11360 };
11361
11362 buffer
11363 .update(&mut cx, |buffer, cx| {
11364 if let Some(transaction) = transaction {
11365 if !buffer.is_singleton() {
11366 buffer.push_transaction(&transaction.0, cx);
11367 }
11368 }
11369
11370 cx.notify();
11371 })
11372 .ok();
11373
11374 Ok(())
11375 })
11376 }
11377
11378 fn restart_language_server(
11379 &mut self,
11380 _: &RestartLanguageServer,
11381 _: &mut Window,
11382 cx: &mut Context<Self>,
11383 ) {
11384 if let Some(project) = self.project.clone() {
11385 self.buffer.update(cx, |multi_buffer, cx| {
11386 project.update(cx, |project, cx| {
11387 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11388 });
11389 })
11390 }
11391 }
11392
11393 fn cancel_language_server_work(
11394 workspace: &mut Workspace,
11395 _: &actions::CancelLanguageServerWork,
11396 _: &mut Window,
11397 cx: &mut Context<Workspace>,
11398 ) {
11399 let project = workspace.project();
11400 let buffers = workspace
11401 .active_item(cx)
11402 .and_then(|item| item.act_as::<Editor>(cx))
11403 .map_or(HashSet::default(), |editor| {
11404 editor.read(cx).buffer.read(cx).all_buffers()
11405 });
11406 project.update(cx, |project, cx| {
11407 project.cancel_language_server_work_for_buffers(buffers, cx);
11408 });
11409 }
11410
11411 fn show_character_palette(
11412 &mut self,
11413 _: &ShowCharacterPalette,
11414 window: &mut Window,
11415 _: &mut Context<Self>,
11416 ) {
11417 window.show_character_palette();
11418 }
11419
11420 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11421 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11422 let buffer = self.buffer.read(cx).snapshot(cx);
11423 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11424 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11425 let is_valid = buffer
11426 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11427 .any(|entry| {
11428 entry.diagnostic.is_primary
11429 && !entry.range.is_empty()
11430 && entry.range.start == primary_range_start
11431 && entry.diagnostic.message == active_diagnostics.primary_message
11432 });
11433
11434 if is_valid != active_diagnostics.is_valid {
11435 active_diagnostics.is_valid = is_valid;
11436 let mut new_styles = HashMap::default();
11437 for (block_id, diagnostic) in &active_diagnostics.blocks {
11438 new_styles.insert(
11439 *block_id,
11440 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11441 );
11442 }
11443 self.display_map.update(cx, |display_map, _cx| {
11444 display_map.replace_blocks(new_styles)
11445 });
11446 }
11447 }
11448 }
11449
11450 fn activate_diagnostics(
11451 &mut self,
11452 buffer_id: BufferId,
11453 group_id: usize,
11454 window: &mut Window,
11455 cx: &mut Context<Self>,
11456 ) {
11457 self.dismiss_diagnostics(cx);
11458 let snapshot = self.snapshot(window, cx);
11459 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11460 let buffer = self.buffer.read(cx).snapshot(cx);
11461
11462 let mut primary_range = None;
11463 let mut primary_message = None;
11464 let diagnostic_group = buffer
11465 .diagnostic_group(buffer_id, group_id)
11466 .filter_map(|entry| {
11467 let start = entry.range.start;
11468 let end = entry.range.end;
11469 if snapshot.is_line_folded(MultiBufferRow(start.row))
11470 && (start.row == end.row
11471 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11472 {
11473 return None;
11474 }
11475 if entry.diagnostic.is_primary {
11476 primary_range = Some(entry.range.clone());
11477 primary_message = Some(entry.diagnostic.message.clone());
11478 }
11479 Some(entry)
11480 })
11481 .collect::<Vec<_>>();
11482 let primary_range = primary_range?;
11483 let primary_message = primary_message?;
11484
11485 let blocks = display_map
11486 .insert_blocks(
11487 diagnostic_group.iter().map(|entry| {
11488 let diagnostic = entry.diagnostic.clone();
11489 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11490 BlockProperties {
11491 style: BlockStyle::Fixed,
11492 placement: BlockPlacement::Below(
11493 buffer.anchor_after(entry.range.start),
11494 ),
11495 height: message_height,
11496 render: diagnostic_block_renderer(diagnostic, None, true, true),
11497 priority: 0,
11498 }
11499 }),
11500 cx,
11501 )
11502 .into_iter()
11503 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11504 .collect();
11505
11506 Some(ActiveDiagnosticGroup {
11507 primary_range: buffer.anchor_before(primary_range.start)
11508 ..buffer.anchor_after(primary_range.end),
11509 primary_message,
11510 group_id,
11511 blocks,
11512 is_valid: true,
11513 })
11514 });
11515 }
11516
11517 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11518 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11519 self.display_map.update(cx, |display_map, cx| {
11520 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11521 });
11522 cx.notify();
11523 }
11524 }
11525
11526 pub fn set_selections_from_remote(
11527 &mut self,
11528 selections: Vec<Selection<Anchor>>,
11529 pending_selection: Option<Selection<Anchor>>,
11530 window: &mut Window,
11531 cx: &mut Context<Self>,
11532 ) {
11533 let old_cursor_position = self.selections.newest_anchor().head();
11534 self.selections.change_with(cx, |s| {
11535 s.select_anchors(selections);
11536 if let Some(pending_selection) = pending_selection {
11537 s.set_pending(pending_selection, SelectMode::Character);
11538 } else {
11539 s.clear_pending();
11540 }
11541 });
11542 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11543 }
11544
11545 fn push_to_selection_history(&mut self) {
11546 self.selection_history.push(SelectionHistoryEntry {
11547 selections: self.selections.disjoint_anchors(),
11548 select_next_state: self.select_next_state.clone(),
11549 select_prev_state: self.select_prev_state.clone(),
11550 add_selections_state: self.add_selections_state.clone(),
11551 });
11552 }
11553
11554 pub fn transact(
11555 &mut self,
11556 window: &mut Window,
11557 cx: &mut Context<Self>,
11558 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11559 ) -> Option<TransactionId> {
11560 self.start_transaction_at(Instant::now(), window, cx);
11561 update(self, window, cx);
11562 self.end_transaction_at(Instant::now(), cx)
11563 }
11564
11565 pub fn start_transaction_at(
11566 &mut self,
11567 now: Instant,
11568 window: &mut Window,
11569 cx: &mut Context<Self>,
11570 ) {
11571 self.end_selection(window, cx);
11572 if let Some(tx_id) = self
11573 .buffer
11574 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11575 {
11576 self.selection_history
11577 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11578 cx.emit(EditorEvent::TransactionBegun {
11579 transaction_id: tx_id,
11580 })
11581 }
11582 }
11583
11584 pub fn end_transaction_at(
11585 &mut self,
11586 now: Instant,
11587 cx: &mut Context<Self>,
11588 ) -> Option<TransactionId> {
11589 if let Some(transaction_id) = self
11590 .buffer
11591 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11592 {
11593 if let Some((_, end_selections)) =
11594 self.selection_history.transaction_mut(transaction_id)
11595 {
11596 *end_selections = Some(self.selections.disjoint_anchors());
11597 } else {
11598 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11599 }
11600
11601 cx.emit(EditorEvent::Edited { transaction_id });
11602 Some(transaction_id)
11603 } else {
11604 None
11605 }
11606 }
11607
11608 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11609 if self.selection_mark_mode {
11610 self.change_selections(None, window, cx, |s| {
11611 s.move_with(|_, sel| {
11612 sel.collapse_to(sel.head(), SelectionGoal::None);
11613 });
11614 })
11615 }
11616 self.selection_mark_mode = true;
11617 cx.notify();
11618 }
11619
11620 pub fn swap_selection_ends(
11621 &mut self,
11622 _: &actions::SwapSelectionEnds,
11623 window: &mut Window,
11624 cx: &mut Context<Self>,
11625 ) {
11626 self.change_selections(None, window, cx, |s| {
11627 s.move_with(|_, sel| {
11628 if sel.start != sel.end {
11629 sel.reversed = !sel.reversed
11630 }
11631 });
11632 });
11633 self.request_autoscroll(Autoscroll::newest(), cx);
11634 cx.notify();
11635 }
11636
11637 pub fn toggle_fold(
11638 &mut self,
11639 _: &actions::ToggleFold,
11640 window: &mut Window,
11641 cx: &mut Context<Self>,
11642 ) {
11643 if self.is_singleton(cx) {
11644 let selection = self.selections.newest::<Point>(cx);
11645
11646 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11647 let range = if selection.is_empty() {
11648 let point = selection.head().to_display_point(&display_map);
11649 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11650 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11651 .to_point(&display_map);
11652 start..end
11653 } else {
11654 selection.range()
11655 };
11656 if display_map.folds_in_range(range).next().is_some() {
11657 self.unfold_lines(&Default::default(), window, cx)
11658 } else {
11659 self.fold(&Default::default(), window, cx)
11660 }
11661 } else {
11662 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11663 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11664 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11665 .map(|(snapshot, _, _)| snapshot.remote_id())
11666 .collect();
11667
11668 for buffer_id in buffer_ids {
11669 if self.is_buffer_folded(buffer_id, cx) {
11670 self.unfold_buffer(buffer_id, cx);
11671 } else {
11672 self.fold_buffer(buffer_id, cx);
11673 }
11674 }
11675 }
11676 }
11677
11678 pub fn toggle_fold_recursive(
11679 &mut self,
11680 _: &actions::ToggleFoldRecursive,
11681 window: &mut Window,
11682 cx: &mut Context<Self>,
11683 ) {
11684 let selection = self.selections.newest::<Point>(cx);
11685
11686 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11687 let range = if selection.is_empty() {
11688 let point = selection.head().to_display_point(&display_map);
11689 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11690 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11691 .to_point(&display_map);
11692 start..end
11693 } else {
11694 selection.range()
11695 };
11696 if display_map.folds_in_range(range).next().is_some() {
11697 self.unfold_recursive(&Default::default(), window, cx)
11698 } else {
11699 self.fold_recursive(&Default::default(), window, cx)
11700 }
11701 }
11702
11703 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11704 if self.is_singleton(cx) {
11705 let mut to_fold = Vec::new();
11706 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11707 let selections = self.selections.all_adjusted(cx);
11708
11709 for selection in selections {
11710 let range = selection.range().sorted();
11711 let buffer_start_row = range.start.row;
11712
11713 if range.start.row != range.end.row {
11714 let mut found = false;
11715 let mut row = range.start.row;
11716 while row <= range.end.row {
11717 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11718 {
11719 found = true;
11720 row = crease.range().end.row + 1;
11721 to_fold.push(crease);
11722 } else {
11723 row += 1
11724 }
11725 }
11726 if found {
11727 continue;
11728 }
11729 }
11730
11731 for row in (0..=range.start.row).rev() {
11732 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11733 if crease.range().end.row >= buffer_start_row {
11734 to_fold.push(crease);
11735 if row <= range.start.row {
11736 break;
11737 }
11738 }
11739 }
11740 }
11741 }
11742
11743 self.fold_creases(to_fold, true, window, cx);
11744 } else {
11745 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11746
11747 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11748 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11749 .map(|(snapshot, _, _)| snapshot.remote_id())
11750 .collect();
11751 for buffer_id in buffer_ids {
11752 self.fold_buffer(buffer_id, cx);
11753 }
11754 }
11755 }
11756
11757 fn fold_at_level(
11758 &mut self,
11759 fold_at: &FoldAtLevel,
11760 window: &mut Window,
11761 cx: &mut Context<Self>,
11762 ) {
11763 if !self.buffer.read(cx).is_singleton() {
11764 return;
11765 }
11766
11767 let fold_at_level = fold_at.level;
11768 let snapshot = self.buffer.read(cx).snapshot(cx);
11769 let mut to_fold = Vec::new();
11770 let mut stack = vec![(0, snapshot.max_row().0, 1)];
11771
11772 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11773 while start_row < end_row {
11774 match self
11775 .snapshot(window, cx)
11776 .crease_for_buffer_row(MultiBufferRow(start_row))
11777 {
11778 Some(crease) => {
11779 let nested_start_row = crease.range().start.row + 1;
11780 let nested_end_row = crease.range().end.row;
11781
11782 if current_level < fold_at_level {
11783 stack.push((nested_start_row, nested_end_row, current_level + 1));
11784 } else if current_level == fold_at_level {
11785 to_fold.push(crease);
11786 }
11787
11788 start_row = nested_end_row + 1;
11789 }
11790 None => start_row += 1,
11791 }
11792 }
11793 }
11794
11795 self.fold_creases(to_fold, true, window, cx);
11796 }
11797
11798 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11799 if self.buffer.read(cx).is_singleton() {
11800 let mut fold_ranges = Vec::new();
11801 let snapshot = self.buffer.read(cx).snapshot(cx);
11802
11803 for row in 0..snapshot.max_row().0 {
11804 if let Some(foldable_range) = self
11805 .snapshot(window, cx)
11806 .crease_for_buffer_row(MultiBufferRow(row))
11807 {
11808 fold_ranges.push(foldable_range);
11809 }
11810 }
11811
11812 self.fold_creases(fold_ranges, true, window, cx);
11813 } else {
11814 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11815 editor
11816 .update_in(&mut cx, |editor, _, cx| {
11817 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11818 editor.fold_buffer(buffer_id, cx);
11819 }
11820 })
11821 .ok();
11822 });
11823 }
11824 }
11825
11826 pub fn fold_function_bodies(
11827 &mut self,
11828 _: &actions::FoldFunctionBodies,
11829 window: &mut Window,
11830 cx: &mut Context<Self>,
11831 ) {
11832 let snapshot = self.buffer.read(cx).snapshot(cx);
11833
11834 let ranges = snapshot
11835 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11836 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11837 .collect::<Vec<_>>();
11838
11839 let creases = ranges
11840 .into_iter()
11841 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11842 .collect();
11843
11844 self.fold_creases(creases, true, window, cx);
11845 }
11846
11847 pub fn fold_recursive(
11848 &mut self,
11849 _: &actions::FoldRecursive,
11850 window: &mut Window,
11851 cx: &mut Context<Self>,
11852 ) {
11853 let mut to_fold = Vec::new();
11854 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11855 let selections = self.selections.all_adjusted(cx);
11856
11857 for selection in selections {
11858 let range = selection.range().sorted();
11859 let buffer_start_row = range.start.row;
11860
11861 if range.start.row != range.end.row {
11862 let mut found = false;
11863 for row in range.start.row..=range.end.row {
11864 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11865 found = true;
11866 to_fold.push(crease);
11867 }
11868 }
11869 if found {
11870 continue;
11871 }
11872 }
11873
11874 for row in (0..=range.start.row).rev() {
11875 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11876 if crease.range().end.row >= buffer_start_row {
11877 to_fold.push(crease);
11878 } else {
11879 break;
11880 }
11881 }
11882 }
11883 }
11884
11885 self.fold_creases(to_fold, true, window, cx);
11886 }
11887
11888 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11889 let buffer_row = fold_at.buffer_row;
11890 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11891
11892 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11893 let autoscroll = self
11894 .selections
11895 .all::<Point>(cx)
11896 .iter()
11897 .any(|selection| crease.range().overlaps(&selection.range()));
11898
11899 self.fold_creases(vec![crease], autoscroll, window, cx);
11900 }
11901 }
11902
11903 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
11904 if self.is_singleton(cx) {
11905 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11906 let buffer = &display_map.buffer_snapshot;
11907 let selections = self.selections.all::<Point>(cx);
11908 let ranges = selections
11909 .iter()
11910 .map(|s| {
11911 let range = s.display_range(&display_map).sorted();
11912 let mut start = range.start.to_point(&display_map);
11913 let mut end = range.end.to_point(&display_map);
11914 start.column = 0;
11915 end.column = buffer.line_len(MultiBufferRow(end.row));
11916 start..end
11917 })
11918 .collect::<Vec<_>>();
11919
11920 self.unfold_ranges(&ranges, true, true, cx);
11921 } else {
11922 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11923 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11924 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11925 .map(|(snapshot, _, _)| snapshot.remote_id())
11926 .collect();
11927 for buffer_id in buffer_ids {
11928 self.unfold_buffer(buffer_id, cx);
11929 }
11930 }
11931 }
11932
11933 pub fn unfold_recursive(
11934 &mut self,
11935 _: &UnfoldRecursive,
11936 _window: &mut Window,
11937 cx: &mut Context<Self>,
11938 ) {
11939 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11940 let selections = self.selections.all::<Point>(cx);
11941 let ranges = selections
11942 .iter()
11943 .map(|s| {
11944 let mut range = s.display_range(&display_map).sorted();
11945 *range.start.column_mut() = 0;
11946 *range.end.column_mut() = display_map.line_len(range.end.row());
11947 let start = range.start.to_point(&display_map);
11948 let end = range.end.to_point(&display_map);
11949 start..end
11950 })
11951 .collect::<Vec<_>>();
11952
11953 self.unfold_ranges(&ranges, true, true, cx);
11954 }
11955
11956 pub fn unfold_at(
11957 &mut self,
11958 unfold_at: &UnfoldAt,
11959 _window: &mut Window,
11960 cx: &mut Context<Self>,
11961 ) {
11962 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11963
11964 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11965 ..Point::new(
11966 unfold_at.buffer_row.0,
11967 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11968 );
11969
11970 let autoscroll = self
11971 .selections
11972 .all::<Point>(cx)
11973 .iter()
11974 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11975
11976 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
11977 }
11978
11979 pub fn unfold_all(
11980 &mut self,
11981 _: &actions::UnfoldAll,
11982 _window: &mut Window,
11983 cx: &mut Context<Self>,
11984 ) {
11985 if self.buffer.read(cx).is_singleton() {
11986 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11987 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11988 } else {
11989 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
11990 editor
11991 .update(&mut cx, |editor, cx| {
11992 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11993 editor.unfold_buffer(buffer_id, cx);
11994 }
11995 })
11996 .ok();
11997 });
11998 }
11999 }
12000
12001 pub fn fold_selected_ranges(
12002 &mut self,
12003 _: &FoldSelectedRanges,
12004 window: &mut Window,
12005 cx: &mut Context<Self>,
12006 ) {
12007 let selections = self.selections.all::<Point>(cx);
12008 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12009 let line_mode = self.selections.line_mode;
12010 let ranges = selections
12011 .into_iter()
12012 .map(|s| {
12013 if line_mode {
12014 let start = Point::new(s.start.row, 0);
12015 let end = Point::new(
12016 s.end.row,
12017 display_map
12018 .buffer_snapshot
12019 .line_len(MultiBufferRow(s.end.row)),
12020 );
12021 Crease::simple(start..end, display_map.fold_placeholder.clone())
12022 } else {
12023 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12024 }
12025 })
12026 .collect::<Vec<_>>();
12027 self.fold_creases(ranges, true, window, cx);
12028 }
12029
12030 pub fn fold_ranges<T: ToOffset + Clone>(
12031 &mut self,
12032 ranges: Vec<Range<T>>,
12033 auto_scroll: bool,
12034 window: &mut Window,
12035 cx: &mut Context<Self>,
12036 ) {
12037 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12038 let ranges = ranges
12039 .into_iter()
12040 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12041 .collect::<Vec<_>>();
12042 self.fold_creases(ranges, auto_scroll, window, cx);
12043 }
12044
12045 pub fn fold_creases<T: ToOffset + Clone>(
12046 &mut self,
12047 creases: Vec<Crease<T>>,
12048 auto_scroll: bool,
12049 window: &mut Window,
12050 cx: &mut Context<Self>,
12051 ) {
12052 if creases.is_empty() {
12053 return;
12054 }
12055
12056 let mut buffers_affected = HashSet::default();
12057 let multi_buffer = self.buffer().read(cx);
12058 for crease in &creases {
12059 if let Some((_, buffer, _)) =
12060 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12061 {
12062 buffers_affected.insert(buffer.read(cx).remote_id());
12063 };
12064 }
12065
12066 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12067
12068 if auto_scroll {
12069 self.request_autoscroll(Autoscroll::fit(), cx);
12070 }
12071
12072 cx.notify();
12073
12074 if let Some(active_diagnostics) = self.active_diagnostics.take() {
12075 // Clear diagnostics block when folding a range that contains it.
12076 let snapshot = self.snapshot(window, cx);
12077 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12078 drop(snapshot);
12079 self.active_diagnostics = Some(active_diagnostics);
12080 self.dismiss_diagnostics(cx);
12081 } else {
12082 self.active_diagnostics = Some(active_diagnostics);
12083 }
12084 }
12085
12086 self.scrollbar_marker_state.dirty = true;
12087 }
12088
12089 /// Removes any folds whose ranges intersect any of the given ranges.
12090 pub fn unfold_ranges<T: ToOffset + Clone>(
12091 &mut self,
12092 ranges: &[Range<T>],
12093 inclusive: bool,
12094 auto_scroll: bool,
12095 cx: &mut Context<Self>,
12096 ) {
12097 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12098 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12099 });
12100 }
12101
12102 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12103 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12104 return;
12105 }
12106 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12107 self.display_map
12108 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12109 cx.emit(EditorEvent::BufferFoldToggled {
12110 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12111 folded: true,
12112 });
12113 cx.notify();
12114 }
12115
12116 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12117 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12118 return;
12119 }
12120 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12121 self.display_map.update(cx, |display_map, cx| {
12122 display_map.unfold_buffer(buffer_id, cx);
12123 });
12124 cx.emit(EditorEvent::BufferFoldToggled {
12125 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12126 folded: false,
12127 });
12128 cx.notify();
12129 }
12130
12131 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12132 self.display_map.read(cx).is_buffer_folded(buffer)
12133 }
12134
12135 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12136 self.display_map.read(cx).folded_buffers()
12137 }
12138
12139 /// Removes any folds with the given ranges.
12140 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12141 &mut self,
12142 ranges: &[Range<T>],
12143 type_id: TypeId,
12144 auto_scroll: bool,
12145 cx: &mut Context<Self>,
12146 ) {
12147 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12148 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12149 });
12150 }
12151
12152 fn remove_folds_with<T: ToOffset + Clone>(
12153 &mut self,
12154 ranges: &[Range<T>],
12155 auto_scroll: bool,
12156 cx: &mut Context<Self>,
12157 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12158 ) {
12159 if ranges.is_empty() {
12160 return;
12161 }
12162
12163 let mut buffers_affected = HashSet::default();
12164 let multi_buffer = self.buffer().read(cx);
12165 for range in ranges {
12166 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12167 buffers_affected.insert(buffer.read(cx).remote_id());
12168 };
12169 }
12170
12171 self.display_map.update(cx, update);
12172
12173 if auto_scroll {
12174 self.request_autoscroll(Autoscroll::fit(), cx);
12175 }
12176
12177 cx.notify();
12178 self.scrollbar_marker_state.dirty = true;
12179 self.active_indent_guides_state.dirty = true;
12180 }
12181
12182 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12183 self.display_map.read(cx).fold_placeholder.clone()
12184 }
12185
12186 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12187 self.buffer.update(cx, |buffer, cx| {
12188 buffer.set_all_diff_hunks_expanded(cx);
12189 });
12190 }
12191
12192 pub fn expand_all_diff_hunks(
12193 &mut self,
12194 _: &ExpandAllHunkDiffs,
12195 _window: &mut Window,
12196 cx: &mut Context<Self>,
12197 ) {
12198 self.buffer.update(cx, |buffer, cx| {
12199 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12200 });
12201 }
12202
12203 pub fn toggle_selected_diff_hunks(
12204 &mut self,
12205 _: &ToggleSelectedDiffHunks,
12206 _window: &mut Window,
12207 cx: &mut Context<Self>,
12208 ) {
12209 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12210 self.toggle_diff_hunks_in_ranges(ranges, cx);
12211 }
12212
12213 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12214 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12215 self.buffer
12216 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12217 }
12218
12219 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12220 self.buffer.update(cx, |buffer, cx| {
12221 let ranges = vec![Anchor::min()..Anchor::max()];
12222 if !buffer.all_diff_hunks_expanded()
12223 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12224 {
12225 buffer.collapse_diff_hunks(ranges, cx);
12226 true
12227 } else {
12228 false
12229 }
12230 })
12231 }
12232
12233 fn toggle_diff_hunks_in_ranges(
12234 &mut self,
12235 ranges: Vec<Range<Anchor>>,
12236 cx: &mut Context<'_, Editor>,
12237 ) {
12238 self.buffer.update(cx, |buffer, cx| {
12239 if buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx) {
12240 buffer.collapse_diff_hunks(ranges, cx)
12241 } else {
12242 buffer.expand_diff_hunks(ranges, cx)
12243 }
12244 })
12245 }
12246
12247 pub(crate) fn apply_all_diff_hunks(
12248 &mut self,
12249 _: &ApplyAllDiffHunks,
12250 window: &mut Window,
12251 cx: &mut Context<Self>,
12252 ) {
12253 let buffers = self.buffer.read(cx).all_buffers();
12254 for branch_buffer in buffers {
12255 branch_buffer.update(cx, |branch_buffer, cx| {
12256 branch_buffer.merge_into_base(Vec::new(), cx);
12257 });
12258 }
12259
12260 if let Some(project) = self.project.clone() {
12261 self.save(true, project, window, cx).detach_and_log_err(cx);
12262 }
12263 }
12264
12265 pub(crate) fn apply_selected_diff_hunks(
12266 &mut self,
12267 _: &ApplyDiffHunk,
12268 window: &mut Window,
12269 cx: &mut Context<Self>,
12270 ) {
12271 let snapshot = self.snapshot(window, cx);
12272 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12273 let mut ranges_by_buffer = HashMap::default();
12274 self.transact(window, cx, |editor, _window, cx| {
12275 for hunk in hunks {
12276 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12277 ranges_by_buffer
12278 .entry(buffer.clone())
12279 .or_insert_with(Vec::new)
12280 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12281 }
12282 }
12283
12284 for (buffer, ranges) in ranges_by_buffer {
12285 buffer.update(cx, |buffer, cx| {
12286 buffer.merge_into_base(ranges, cx);
12287 });
12288 }
12289 });
12290
12291 if let Some(project) = self.project.clone() {
12292 self.save(true, project, window, cx).detach_and_log_err(cx);
12293 }
12294 }
12295
12296 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12297 if hovered != self.gutter_hovered {
12298 self.gutter_hovered = hovered;
12299 cx.notify();
12300 }
12301 }
12302
12303 pub fn insert_blocks(
12304 &mut self,
12305 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12306 autoscroll: Option<Autoscroll>,
12307 cx: &mut Context<Self>,
12308 ) -> Vec<CustomBlockId> {
12309 let blocks = self
12310 .display_map
12311 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12312 if let Some(autoscroll) = autoscroll {
12313 self.request_autoscroll(autoscroll, cx);
12314 }
12315 cx.notify();
12316 blocks
12317 }
12318
12319 pub fn resize_blocks(
12320 &mut self,
12321 heights: HashMap<CustomBlockId, u32>,
12322 autoscroll: Option<Autoscroll>,
12323 cx: &mut Context<Self>,
12324 ) {
12325 self.display_map
12326 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12327 if let Some(autoscroll) = autoscroll {
12328 self.request_autoscroll(autoscroll, cx);
12329 }
12330 cx.notify();
12331 }
12332
12333 pub fn replace_blocks(
12334 &mut self,
12335 renderers: HashMap<CustomBlockId, RenderBlock>,
12336 autoscroll: Option<Autoscroll>,
12337 cx: &mut Context<Self>,
12338 ) {
12339 self.display_map
12340 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12341 if let Some(autoscroll) = autoscroll {
12342 self.request_autoscroll(autoscroll, cx);
12343 }
12344 cx.notify();
12345 }
12346
12347 pub fn remove_blocks(
12348 &mut self,
12349 block_ids: HashSet<CustomBlockId>,
12350 autoscroll: Option<Autoscroll>,
12351 cx: &mut Context<Self>,
12352 ) {
12353 self.display_map.update(cx, |display_map, cx| {
12354 display_map.remove_blocks(block_ids, cx)
12355 });
12356 if let Some(autoscroll) = autoscroll {
12357 self.request_autoscroll(autoscroll, cx);
12358 }
12359 cx.notify();
12360 }
12361
12362 pub fn row_for_block(
12363 &self,
12364 block_id: CustomBlockId,
12365 cx: &mut Context<Self>,
12366 ) -> Option<DisplayRow> {
12367 self.display_map
12368 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12369 }
12370
12371 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12372 self.focused_block = Some(focused_block);
12373 }
12374
12375 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12376 self.focused_block.take()
12377 }
12378
12379 pub fn insert_creases(
12380 &mut self,
12381 creases: impl IntoIterator<Item = Crease<Anchor>>,
12382 cx: &mut Context<Self>,
12383 ) -> Vec<CreaseId> {
12384 self.display_map
12385 .update(cx, |map, cx| map.insert_creases(creases, cx))
12386 }
12387
12388 pub fn remove_creases(
12389 &mut self,
12390 ids: impl IntoIterator<Item = CreaseId>,
12391 cx: &mut Context<Self>,
12392 ) {
12393 self.display_map
12394 .update(cx, |map, cx| map.remove_creases(ids, cx));
12395 }
12396
12397 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12398 self.display_map
12399 .update(cx, |map, cx| map.snapshot(cx))
12400 .longest_row()
12401 }
12402
12403 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12404 self.display_map
12405 .update(cx, |map, cx| map.snapshot(cx))
12406 .max_point()
12407 }
12408
12409 pub fn text(&self, cx: &App) -> String {
12410 self.buffer.read(cx).read(cx).text()
12411 }
12412
12413 pub fn is_empty(&self, cx: &App) -> bool {
12414 self.buffer.read(cx).read(cx).is_empty()
12415 }
12416
12417 pub fn text_option(&self, cx: &App) -> Option<String> {
12418 let text = self.text(cx);
12419 let text = text.trim();
12420
12421 if text.is_empty() {
12422 return None;
12423 }
12424
12425 Some(text.to_string())
12426 }
12427
12428 pub fn set_text(
12429 &mut self,
12430 text: impl Into<Arc<str>>,
12431 window: &mut Window,
12432 cx: &mut Context<Self>,
12433 ) {
12434 self.transact(window, cx, |this, _, cx| {
12435 this.buffer
12436 .read(cx)
12437 .as_singleton()
12438 .expect("you can only call set_text on editors for singleton buffers")
12439 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12440 });
12441 }
12442
12443 pub fn display_text(&self, cx: &mut App) -> String {
12444 self.display_map
12445 .update(cx, |map, cx| map.snapshot(cx))
12446 .text()
12447 }
12448
12449 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12450 let mut wrap_guides = smallvec::smallvec![];
12451
12452 if self.show_wrap_guides == Some(false) {
12453 return wrap_guides;
12454 }
12455
12456 let settings = self.buffer.read(cx).settings_at(0, cx);
12457 if settings.show_wrap_guides {
12458 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12459 wrap_guides.push((soft_wrap as usize, true));
12460 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12461 wrap_guides.push((soft_wrap as usize, true));
12462 }
12463 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12464 }
12465
12466 wrap_guides
12467 }
12468
12469 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12470 let settings = self.buffer.read(cx).settings_at(0, cx);
12471 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12472 match mode {
12473 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12474 SoftWrap::None
12475 }
12476 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12477 language_settings::SoftWrap::PreferredLineLength => {
12478 SoftWrap::Column(settings.preferred_line_length)
12479 }
12480 language_settings::SoftWrap::Bounded => {
12481 SoftWrap::Bounded(settings.preferred_line_length)
12482 }
12483 }
12484 }
12485
12486 pub fn set_soft_wrap_mode(
12487 &mut self,
12488 mode: language_settings::SoftWrap,
12489
12490 cx: &mut Context<Self>,
12491 ) {
12492 self.soft_wrap_mode_override = Some(mode);
12493 cx.notify();
12494 }
12495
12496 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12497 self.text_style_refinement = Some(style);
12498 }
12499
12500 /// called by the Element so we know what style we were most recently rendered with.
12501 pub(crate) fn set_style(
12502 &mut self,
12503 style: EditorStyle,
12504 window: &mut Window,
12505 cx: &mut Context<Self>,
12506 ) {
12507 let rem_size = window.rem_size();
12508 self.display_map.update(cx, |map, cx| {
12509 map.set_font(
12510 style.text.font(),
12511 style.text.font_size.to_pixels(rem_size),
12512 cx,
12513 )
12514 });
12515 self.style = Some(style);
12516 }
12517
12518 pub fn style(&self) -> Option<&EditorStyle> {
12519 self.style.as_ref()
12520 }
12521
12522 // Called by the element. This method is not designed to be called outside of the editor
12523 // element's layout code because it does not notify when rewrapping is computed synchronously.
12524 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12525 self.display_map
12526 .update(cx, |map, cx| map.set_wrap_width(width, cx))
12527 }
12528
12529 pub fn set_soft_wrap(&mut self) {
12530 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12531 }
12532
12533 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12534 if self.soft_wrap_mode_override.is_some() {
12535 self.soft_wrap_mode_override.take();
12536 } else {
12537 let soft_wrap = match self.soft_wrap_mode(cx) {
12538 SoftWrap::GitDiff => return,
12539 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12540 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12541 language_settings::SoftWrap::None
12542 }
12543 };
12544 self.soft_wrap_mode_override = Some(soft_wrap);
12545 }
12546 cx.notify();
12547 }
12548
12549 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12550 let Some(workspace) = self.workspace() else {
12551 return;
12552 };
12553 let fs = workspace.read(cx).app_state().fs.clone();
12554 let current_show = TabBarSettings::get_global(cx).show;
12555 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12556 setting.show = Some(!current_show);
12557 });
12558 }
12559
12560 pub fn toggle_indent_guides(
12561 &mut self,
12562 _: &ToggleIndentGuides,
12563 _: &mut Window,
12564 cx: &mut Context<Self>,
12565 ) {
12566 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12567 self.buffer
12568 .read(cx)
12569 .settings_at(0, cx)
12570 .indent_guides
12571 .enabled
12572 });
12573 self.show_indent_guides = Some(!currently_enabled);
12574 cx.notify();
12575 }
12576
12577 fn should_show_indent_guides(&self) -> Option<bool> {
12578 self.show_indent_guides
12579 }
12580
12581 pub fn toggle_line_numbers(
12582 &mut self,
12583 _: &ToggleLineNumbers,
12584 _: &mut Window,
12585 cx: &mut Context<Self>,
12586 ) {
12587 let mut editor_settings = EditorSettings::get_global(cx).clone();
12588 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12589 EditorSettings::override_global(editor_settings, cx);
12590 }
12591
12592 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12593 self.use_relative_line_numbers
12594 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12595 }
12596
12597 pub fn toggle_relative_line_numbers(
12598 &mut self,
12599 _: &ToggleRelativeLineNumbers,
12600 _: &mut Window,
12601 cx: &mut Context<Self>,
12602 ) {
12603 let is_relative = self.should_use_relative_line_numbers(cx);
12604 self.set_relative_line_number(Some(!is_relative), cx)
12605 }
12606
12607 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12608 self.use_relative_line_numbers = is_relative;
12609 cx.notify();
12610 }
12611
12612 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12613 self.show_gutter = show_gutter;
12614 cx.notify();
12615 }
12616
12617 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12618 self.show_scrollbars = show_scrollbars;
12619 cx.notify();
12620 }
12621
12622 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12623 self.show_line_numbers = Some(show_line_numbers);
12624 cx.notify();
12625 }
12626
12627 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12628 self.show_git_diff_gutter = Some(show_git_diff_gutter);
12629 cx.notify();
12630 }
12631
12632 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12633 self.show_code_actions = Some(show_code_actions);
12634 cx.notify();
12635 }
12636
12637 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12638 self.show_runnables = Some(show_runnables);
12639 cx.notify();
12640 }
12641
12642 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12643 if self.display_map.read(cx).masked != masked {
12644 self.display_map.update(cx, |map, _| map.masked = masked);
12645 }
12646 cx.notify()
12647 }
12648
12649 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12650 self.show_wrap_guides = Some(show_wrap_guides);
12651 cx.notify();
12652 }
12653
12654 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12655 self.show_indent_guides = Some(show_indent_guides);
12656 cx.notify();
12657 }
12658
12659 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12660 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12661 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12662 if let Some(dir) = file.abs_path(cx).parent() {
12663 return Some(dir.to_owned());
12664 }
12665 }
12666
12667 if let Some(project_path) = buffer.read(cx).project_path(cx) {
12668 return Some(project_path.path.to_path_buf());
12669 }
12670 }
12671
12672 None
12673 }
12674
12675 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12676 self.active_excerpt(cx)?
12677 .1
12678 .read(cx)
12679 .file()
12680 .and_then(|f| f.as_local())
12681 }
12682
12683 fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12684 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12685 let project_path = buffer.read(cx).project_path(cx)?;
12686 let project = self.project.as_ref()?.read(cx);
12687 project.absolute_path(&project_path, cx)
12688 })
12689 }
12690
12691 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12692 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12693 let project_path = buffer.read(cx).project_path(cx)?;
12694 let project = self.project.as_ref()?.read(cx);
12695 let entry = project.entry_for_path(&project_path, cx)?;
12696 let path = entry.path.to_path_buf();
12697 Some(path)
12698 })
12699 }
12700
12701 pub fn reveal_in_finder(
12702 &mut self,
12703 _: &RevealInFileManager,
12704 _window: &mut Window,
12705 cx: &mut Context<Self>,
12706 ) {
12707 if let Some(target) = self.target_file(cx) {
12708 cx.reveal_path(&target.abs_path(cx));
12709 }
12710 }
12711
12712 pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12713 if let Some(path) = self.target_file_abs_path(cx) {
12714 if let Some(path) = path.to_str() {
12715 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12716 }
12717 }
12718 }
12719
12720 pub fn copy_relative_path(
12721 &mut self,
12722 _: &CopyRelativePath,
12723 _window: &mut Window,
12724 cx: &mut Context<Self>,
12725 ) {
12726 if let Some(path) = self.target_file_path(cx) {
12727 if let Some(path) = path.to_str() {
12728 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12729 }
12730 }
12731 }
12732
12733 pub fn toggle_git_blame(
12734 &mut self,
12735 _: &ToggleGitBlame,
12736 window: &mut Window,
12737 cx: &mut Context<Self>,
12738 ) {
12739 self.show_git_blame_gutter = !self.show_git_blame_gutter;
12740
12741 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12742 self.start_git_blame(true, window, cx);
12743 }
12744
12745 cx.notify();
12746 }
12747
12748 pub fn toggle_git_blame_inline(
12749 &mut self,
12750 _: &ToggleGitBlameInline,
12751 window: &mut Window,
12752 cx: &mut Context<Self>,
12753 ) {
12754 self.toggle_git_blame_inline_internal(true, window, cx);
12755 cx.notify();
12756 }
12757
12758 pub fn git_blame_inline_enabled(&self) -> bool {
12759 self.git_blame_inline_enabled
12760 }
12761
12762 pub fn toggle_selection_menu(
12763 &mut self,
12764 _: &ToggleSelectionMenu,
12765 _: &mut Window,
12766 cx: &mut Context<Self>,
12767 ) {
12768 self.show_selection_menu = self
12769 .show_selection_menu
12770 .map(|show_selections_menu| !show_selections_menu)
12771 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12772
12773 cx.notify();
12774 }
12775
12776 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12777 self.show_selection_menu
12778 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12779 }
12780
12781 fn start_git_blame(
12782 &mut self,
12783 user_triggered: bool,
12784 window: &mut Window,
12785 cx: &mut Context<Self>,
12786 ) {
12787 if let Some(project) = self.project.as_ref() {
12788 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12789 return;
12790 };
12791
12792 if buffer.read(cx).file().is_none() {
12793 return;
12794 }
12795
12796 let focused = self.focus_handle(cx).contains_focused(window, cx);
12797
12798 let project = project.clone();
12799 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12800 self.blame_subscription =
12801 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12802 self.blame = Some(blame);
12803 }
12804 }
12805
12806 fn toggle_git_blame_inline_internal(
12807 &mut self,
12808 user_triggered: bool,
12809 window: &mut Window,
12810 cx: &mut Context<Self>,
12811 ) {
12812 if self.git_blame_inline_enabled {
12813 self.git_blame_inline_enabled = false;
12814 self.show_git_blame_inline = false;
12815 self.show_git_blame_inline_delay_task.take();
12816 } else {
12817 self.git_blame_inline_enabled = true;
12818 self.start_git_blame_inline(user_triggered, window, cx);
12819 }
12820
12821 cx.notify();
12822 }
12823
12824 fn start_git_blame_inline(
12825 &mut self,
12826 user_triggered: bool,
12827 window: &mut Window,
12828 cx: &mut Context<Self>,
12829 ) {
12830 self.start_git_blame(user_triggered, window, cx);
12831
12832 if ProjectSettings::get_global(cx)
12833 .git
12834 .inline_blame_delay()
12835 .is_some()
12836 {
12837 self.start_inline_blame_timer(window, cx);
12838 } else {
12839 self.show_git_blame_inline = true
12840 }
12841 }
12842
12843 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12844 self.blame.as_ref()
12845 }
12846
12847 pub fn show_git_blame_gutter(&self) -> bool {
12848 self.show_git_blame_gutter
12849 }
12850
12851 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12852 self.show_git_blame_gutter && self.has_blame_entries(cx)
12853 }
12854
12855 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12856 self.show_git_blame_inline
12857 && self.focus_handle.is_focused(window)
12858 && !self.newest_selection_head_on_empty_line(cx)
12859 && self.has_blame_entries(cx)
12860 }
12861
12862 fn has_blame_entries(&self, cx: &App) -> bool {
12863 self.blame()
12864 .map_or(false, |blame| blame.read(cx).has_generated_entries())
12865 }
12866
12867 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12868 let cursor_anchor = self.selections.newest_anchor().head();
12869
12870 let snapshot = self.buffer.read(cx).snapshot(cx);
12871 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12872
12873 snapshot.line_len(buffer_row) == 0
12874 }
12875
12876 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12877 let buffer_and_selection = maybe!({
12878 let selection = self.selections.newest::<Point>(cx);
12879 let selection_range = selection.range();
12880
12881 let multi_buffer = self.buffer().read(cx);
12882 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12883 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12884
12885 let (buffer, range, _) = if selection.reversed {
12886 buffer_ranges.first()
12887 } else {
12888 buffer_ranges.last()
12889 }?;
12890
12891 let selection = text::ToPoint::to_point(&range.start, &buffer).row
12892 ..text::ToPoint::to_point(&range.end, &buffer).row;
12893 Some((
12894 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
12895 selection,
12896 ))
12897 });
12898
12899 let Some((buffer, selection)) = buffer_and_selection else {
12900 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12901 };
12902
12903 let Some(project) = self.project.as_ref() else {
12904 return Task::ready(Err(anyhow!("editor does not have project")));
12905 };
12906
12907 project.update(cx, |project, cx| {
12908 project.get_permalink_to_line(&buffer, selection, cx)
12909 })
12910 }
12911
12912 pub fn copy_permalink_to_line(
12913 &mut self,
12914 _: &CopyPermalinkToLine,
12915 window: &mut Window,
12916 cx: &mut Context<Self>,
12917 ) {
12918 let permalink_task = self.get_permalink_to_line(cx);
12919 let workspace = self.workspace();
12920
12921 cx.spawn_in(window, |_, mut cx| async move {
12922 match permalink_task.await {
12923 Ok(permalink) => {
12924 cx.update(|_, cx| {
12925 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12926 })
12927 .ok();
12928 }
12929 Err(err) => {
12930 let message = format!("Failed to copy permalink: {err}");
12931
12932 Err::<(), anyhow::Error>(err).log_err();
12933
12934 if let Some(workspace) = workspace {
12935 workspace
12936 .update_in(&mut cx, |workspace, _, cx| {
12937 struct CopyPermalinkToLine;
12938
12939 workspace.show_toast(
12940 Toast::new(
12941 NotificationId::unique::<CopyPermalinkToLine>(),
12942 message,
12943 ),
12944 cx,
12945 )
12946 })
12947 .ok();
12948 }
12949 }
12950 }
12951 })
12952 .detach();
12953 }
12954
12955 pub fn copy_file_location(
12956 &mut self,
12957 _: &CopyFileLocation,
12958 _: &mut Window,
12959 cx: &mut Context<Self>,
12960 ) {
12961 let selection = self.selections.newest::<Point>(cx).start.row + 1;
12962 if let Some(file) = self.target_file(cx) {
12963 if let Some(path) = file.path().to_str() {
12964 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
12965 }
12966 }
12967 }
12968
12969 pub fn open_permalink_to_line(
12970 &mut self,
12971 _: &OpenPermalinkToLine,
12972 window: &mut Window,
12973 cx: &mut Context<Self>,
12974 ) {
12975 let permalink_task = self.get_permalink_to_line(cx);
12976 let workspace = self.workspace();
12977
12978 cx.spawn_in(window, |_, mut cx| async move {
12979 match permalink_task.await {
12980 Ok(permalink) => {
12981 cx.update(|_, cx| {
12982 cx.open_url(permalink.as_ref());
12983 })
12984 .ok();
12985 }
12986 Err(err) => {
12987 let message = format!("Failed to open permalink: {err}");
12988
12989 Err::<(), anyhow::Error>(err).log_err();
12990
12991 if let Some(workspace) = workspace {
12992 workspace
12993 .update(&mut cx, |workspace, cx| {
12994 struct OpenPermalinkToLine;
12995
12996 workspace.show_toast(
12997 Toast::new(
12998 NotificationId::unique::<OpenPermalinkToLine>(),
12999 message,
13000 ),
13001 cx,
13002 )
13003 })
13004 .ok();
13005 }
13006 }
13007 }
13008 })
13009 .detach();
13010 }
13011
13012 pub fn insert_uuid_v4(
13013 &mut self,
13014 _: &InsertUuidV4,
13015 window: &mut Window,
13016 cx: &mut Context<Self>,
13017 ) {
13018 self.insert_uuid(UuidVersion::V4, window, cx);
13019 }
13020
13021 pub fn insert_uuid_v7(
13022 &mut self,
13023 _: &InsertUuidV7,
13024 window: &mut Window,
13025 cx: &mut Context<Self>,
13026 ) {
13027 self.insert_uuid(UuidVersion::V7, window, cx);
13028 }
13029
13030 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13031 self.transact(window, cx, |this, window, cx| {
13032 let edits = this
13033 .selections
13034 .all::<Point>(cx)
13035 .into_iter()
13036 .map(|selection| {
13037 let uuid = match version {
13038 UuidVersion::V4 => uuid::Uuid::new_v4(),
13039 UuidVersion::V7 => uuid::Uuid::now_v7(),
13040 };
13041
13042 (selection.range(), uuid.to_string())
13043 });
13044 this.edit(edits, cx);
13045 this.refresh_inline_completion(true, false, window, cx);
13046 });
13047 }
13048
13049 pub fn open_selections_in_multibuffer(
13050 &mut self,
13051 _: &OpenSelectionsInMultibuffer,
13052 window: &mut Window,
13053 cx: &mut Context<Self>,
13054 ) {
13055 let multibuffer = self.buffer.read(cx);
13056
13057 let Some(buffer) = multibuffer.as_singleton() else {
13058 return;
13059 };
13060
13061 let Some(workspace) = self.workspace() else {
13062 return;
13063 };
13064
13065 let locations = self
13066 .selections
13067 .disjoint_anchors()
13068 .iter()
13069 .map(|range| Location {
13070 buffer: buffer.clone(),
13071 range: range.start.text_anchor..range.end.text_anchor,
13072 })
13073 .collect::<Vec<_>>();
13074
13075 let title = multibuffer.title(cx).to_string();
13076
13077 cx.spawn_in(window, |_, mut cx| async move {
13078 workspace.update_in(&mut cx, |workspace, window, cx| {
13079 Self::open_locations_in_multibuffer(
13080 workspace,
13081 locations,
13082 format!("Selections for '{title}'"),
13083 false,
13084 MultibufferSelectionMode::All,
13085 window,
13086 cx,
13087 );
13088 })
13089 })
13090 .detach();
13091 }
13092
13093 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13094 /// last highlight added will be used.
13095 ///
13096 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13097 pub fn highlight_rows<T: 'static>(
13098 &mut self,
13099 range: Range<Anchor>,
13100 color: Hsla,
13101 should_autoscroll: bool,
13102 cx: &mut Context<Self>,
13103 ) {
13104 let snapshot = self.buffer().read(cx).snapshot(cx);
13105 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13106 let ix = row_highlights.binary_search_by(|highlight| {
13107 Ordering::Equal
13108 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13109 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13110 });
13111
13112 if let Err(mut ix) = ix {
13113 let index = post_inc(&mut self.highlight_order);
13114
13115 // If this range intersects with the preceding highlight, then merge it with
13116 // the preceding highlight. Otherwise insert a new highlight.
13117 let mut merged = false;
13118 if ix > 0 {
13119 let prev_highlight = &mut row_highlights[ix - 1];
13120 if prev_highlight
13121 .range
13122 .end
13123 .cmp(&range.start, &snapshot)
13124 .is_ge()
13125 {
13126 ix -= 1;
13127 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13128 prev_highlight.range.end = range.end;
13129 }
13130 merged = true;
13131 prev_highlight.index = index;
13132 prev_highlight.color = color;
13133 prev_highlight.should_autoscroll = should_autoscroll;
13134 }
13135 }
13136
13137 if !merged {
13138 row_highlights.insert(
13139 ix,
13140 RowHighlight {
13141 range: range.clone(),
13142 index,
13143 color,
13144 should_autoscroll,
13145 },
13146 );
13147 }
13148
13149 // If any of the following highlights intersect with this one, merge them.
13150 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13151 let highlight = &row_highlights[ix];
13152 if next_highlight
13153 .range
13154 .start
13155 .cmp(&highlight.range.end, &snapshot)
13156 .is_le()
13157 {
13158 if next_highlight
13159 .range
13160 .end
13161 .cmp(&highlight.range.end, &snapshot)
13162 .is_gt()
13163 {
13164 row_highlights[ix].range.end = next_highlight.range.end;
13165 }
13166 row_highlights.remove(ix + 1);
13167 } else {
13168 break;
13169 }
13170 }
13171 }
13172 }
13173
13174 /// Remove any highlighted row ranges of the given type that intersect the
13175 /// given ranges.
13176 pub fn remove_highlighted_rows<T: 'static>(
13177 &mut self,
13178 ranges_to_remove: Vec<Range<Anchor>>,
13179 cx: &mut Context<Self>,
13180 ) {
13181 let snapshot = self.buffer().read(cx).snapshot(cx);
13182 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13183 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13184 row_highlights.retain(|highlight| {
13185 while let Some(range_to_remove) = ranges_to_remove.peek() {
13186 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13187 Ordering::Less | Ordering::Equal => {
13188 ranges_to_remove.next();
13189 }
13190 Ordering::Greater => {
13191 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13192 Ordering::Less | Ordering::Equal => {
13193 return false;
13194 }
13195 Ordering::Greater => break,
13196 }
13197 }
13198 }
13199 }
13200
13201 true
13202 })
13203 }
13204
13205 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13206 pub fn clear_row_highlights<T: 'static>(&mut self) {
13207 self.highlighted_rows.remove(&TypeId::of::<T>());
13208 }
13209
13210 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13211 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13212 self.highlighted_rows
13213 .get(&TypeId::of::<T>())
13214 .map_or(&[] as &[_], |vec| vec.as_slice())
13215 .iter()
13216 .map(|highlight| (highlight.range.clone(), highlight.color))
13217 }
13218
13219 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13220 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13221 /// Allows to ignore certain kinds of highlights.
13222 pub fn highlighted_display_rows(
13223 &self,
13224 window: &mut Window,
13225 cx: &mut App,
13226 ) -> BTreeMap<DisplayRow, Hsla> {
13227 let snapshot = self.snapshot(window, cx);
13228 let mut used_highlight_orders = HashMap::default();
13229 self.highlighted_rows
13230 .iter()
13231 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13232 .fold(
13233 BTreeMap::<DisplayRow, Hsla>::new(),
13234 |mut unique_rows, highlight| {
13235 let start = highlight.range.start.to_display_point(&snapshot);
13236 let end = highlight.range.end.to_display_point(&snapshot);
13237 let start_row = start.row().0;
13238 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13239 && end.column() == 0
13240 {
13241 end.row().0.saturating_sub(1)
13242 } else {
13243 end.row().0
13244 };
13245 for row in start_row..=end_row {
13246 let used_index =
13247 used_highlight_orders.entry(row).or_insert(highlight.index);
13248 if highlight.index >= *used_index {
13249 *used_index = highlight.index;
13250 unique_rows.insert(DisplayRow(row), highlight.color);
13251 }
13252 }
13253 unique_rows
13254 },
13255 )
13256 }
13257
13258 pub fn highlighted_display_row_for_autoscroll(
13259 &self,
13260 snapshot: &DisplaySnapshot,
13261 ) -> Option<DisplayRow> {
13262 self.highlighted_rows
13263 .values()
13264 .flat_map(|highlighted_rows| highlighted_rows.iter())
13265 .filter_map(|highlight| {
13266 if highlight.should_autoscroll {
13267 Some(highlight.range.start.to_display_point(snapshot).row())
13268 } else {
13269 None
13270 }
13271 })
13272 .min()
13273 }
13274
13275 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13276 self.highlight_background::<SearchWithinRange>(
13277 ranges,
13278 |colors| colors.editor_document_highlight_read_background,
13279 cx,
13280 )
13281 }
13282
13283 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13284 self.breadcrumb_header = Some(new_header);
13285 }
13286
13287 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13288 self.clear_background_highlights::<SearchWithinRange>(cx);
13289 }
13290
13291 pub fn highlight_background<T: 'static>(
13292 &mut self,
13293 ranges: &[Range<Anchor>],
13294 color_fetcher: fn(&ThemeColors) -> Hsla,
13295 cx: &mut Context<Self>,
13296 ) {
13297 self.background_highlights
13298 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13299 self.scrollbar_marker_state.dirty = true;
13300 cx.notify();
13301 }
13302
13303 pub fn clear_background_highlights<T: 'static>(
13304 &mut self,
13305 cx: &mut Context<Self>,
13306 ) -> Option<BackgroundHighlight> {
13307 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13308 if !text_highlights.1.is_empty() {
13309 self.scrollbar_marker_state.dirty = true;
13310 cx.notify();
13311 }
13312 Some(text_highlights)
13313 }
13314
13315 pub fn highlight_gutter<T: 'static>(
13316 &mut self,
13317 ranges: &[Range<Anchor>],
13318 color_fetcher: fn(&App) -> Hsla,
13319 cx: &mut Context<Self>,
13320 ) {
13321 self.gutter_highlights
13322 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13323 cx.notify();
13324 }
13325
13326 pub fn clear_gutter_highlights<T: 'static>(
13327 &mut self,
13328 cx: &mut Context<Self>,
13329 ) -> Option<GutterHighlight> {
13330 cx.notify();
13331 self.gutter_highlights.remove(&TypeId::of::<T>())
13332 }
13333
13334 #[cfg(feature = "test-support")]
13335 pub fn all_text_background_highlights(
13336 &self,
13337 window: &mut Window,
13338 cx: &mut Context<Self>,
13339 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13340 let snapshot = self.snapshot(window, cx);
13341 let buffer = &snapshot.buffer_snapshot;
13342 let start = buffer.anchor_before(0);
13343 let end = buffer.anchor_after(buffer.len());
13344 let theme = cx.theme().colors();
13345 self.background_highlights_in_range(start..end, &snapshot, theme)
13346 }
13347
13348 #[cfg(feature = "test-support")]
13349 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13350 let snapshot = self.buffer().read(cx).snapshot(cx);
13351
13352 let highlights = self
13353 .background_highlights
13354 .get(&TypeId::of::<items::BufferSearchHighlights>());
13355
13356 if let Some((_color, ranges)) = highlights {
13357 ranges
13358 .iter()
13359 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13360 .collect_vec()
13361 } else {
13362 vec![]
13363 }
13364 }
13365
13366 fn document_highlights_for_position<'a>(
13367 &'a self,
13368 position: Anchor,
13369 buffer: &'a MultiBufferSnapshot,
13370 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13371 let read_highlights = self
13372 .background_highlights
13373 .get(&TypeId::of::<DocumentHighlightRead>())
13374 .map(|h| &h.1);
13375 let write_highlights = self
13376 .background_highlights
13377 .get(&TypeId::of::<DocumentHighlightWrite>())
13378 .map(|h| &h.1);
13379 let left_position = position.bias_left(buffer);
13380 let right_position = position.bias_right(buffer);
13381 read_highlights
13382 .into_iter()
13383 .chain(write_highlights)
13384 .flat_map(move |ranges| {
13385 let start_ix = match ranges.binary_search_by(|probe| {
13386 let cmp = probe.end.cmp(&left_position, buffer);
13387 if cmp.is_ge() {
13388 Ordering::Greater
13389 } else {
13390 Ordering::Less
13391 }
13392 }) {
13393 Ok(i) | Err(i) => i,
13394 };
13395
13396 ranges[start_ix..]
13397 .iter()
13398 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13399 })
13400 }
13401
13402 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13403 self.background_highlights
13404 .get(&TypeId::of::<T>())
13405 .map_or(false, |(_, highlights)| !highlights.is_empty())
13406 }
13407
13408 pub fn background_highlights_in_range(
13409 &self,
13410 search_range: Range<Anchor>,
13411 display_snapshot: &DisplaySnapshot,
13412 theme: &ThemeColors,
13413 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13414 let mut results = Vec::new();
13415 for (color_fetcher, ranges) in self.background_highlights.values() {
13416 let color = color_fetcher(theme);
13417 let start_ix = match ranges.binary_search_by(|probe| {
13418 let cmp = probe
13419 .end
13420 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13421 if cmp.is_gt() {
13422 Ordering::Greater
13423 } else {
13424 Ordering::Less
13425 }
13426 }) {
13427 Ok(i) | Err(i) => i,
13428 };
13429 for range in &ranges[start_ix..] {
13430 if range
13431 .start
13432 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13433 .is_ge()
13434 {
13435 break;
13436 }
13437
13438 let start = range.start.to_display_point(display_snapshot);
13439 let end = range.end.to_display_point(display_snapshot);
13440 results.push((start..end, color))
13441 }
13442 }
13443 results
13444 }
13445
13446 pub fn background_highlight_row_ranges<T: 'static>(
13447 &self,
13448 search_range: Range<Anchor>,
13449 display_snapshot: &DisplaySnapshot,
13450 count: usize,
13451 ) -> Vec<RangeInclusive<DisplayPoint>> {
13452 let mut results = Vec::new();
13453 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13454 return vec![];
13455 };
13456
13457 let start_ix = match ranges.binary_search_by(|probe| {
13458 let cmp = probe
13459 .end
13460 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13461 if cmp.is_gt() {
13462 Ordering::Greater
13463 } else {
13464 Ordering::Less
13465 }
13466 }) {
13467 Ok(i) | Err(i) => i,
13468 };
13469 let mut push_region = |start: Option<Point>, end: Option<Point>| {
13470 if let (Some(start_display), Some(end_display)) = (start, end) {
13471 results.push(
13472 start_display.to_display_point(display_snapshot)
13473 ..=end_display.to_display_point(display_snapshot),
13474 );
13475 }
13476 };
13477 let mut start_row: Option<Point> = None;
13478 let mut end_row: Option<Point> = None;
13479 if ranges.len() > count {
13480 return Vec::new();
13481 }
13482 for range in &ranges[start_ix..] {
13483 if range
13484 .start
13485 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13486 .is_ge()
13487 {
13488 break;
13489 }
13490 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13491 if let Some(current_row) = &end_row {
13492 if end.row == current_row.row {
13493 continue;
13494 }
13495 }
13496 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13497 if start_row.is_none() {
13498 assert_eq!(end_row, None);
13499 start_row = Some(start);
13500 end_row = Some(end);
13501 continue;
13502 }
13503 if let Some(current_end) = end_row.as_mut() {
13504 if start.row > current_end.row + 1 {
13505 push_region(start_row, end_row);
13506 start_row = Some(start);
13507 end_row = Some(end);
13508 } else {
13509 // Merge two hunks.
13510 *current_end = end;
13511 }
13512 } else {
13513 unreachable!();
13514 }
13515 }
13516 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13517 push_region(start_row, end_row);
13518 results
13519 }
13520
13521 pub fn gutter_highlights_in_range(
13522 &self,
13523 search_range: Range<Anchor>,
13524 display_snapshot: &DisplaySnapshot,
13525 cx: &App,
13526 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13527 let mut results = Vec::new();
13528 for (color_fetcher, ranges) in self.gutter_highlights.values() {
13529 let color = color_fetcher(cx);
13530 let start_ix = match ranges.binary_search_by(|probe| {
13531 let cmp = probe
13532 .end
13533 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13534 if cmp.is_gt() {
13535 Ordering::Greater
13536 } else {
13537 Ordering::Less
13538 }
13539 }) {
13540 Ok(i) | Err(i) => i,
13541 };
13542 for range in &ranges[start_ix..] {
13543 if range
13544 .start
13545 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13546 .is_ge()
13547 {
13548 break;
13549 }
13550
13551 let start = range.start.to_display_point(display_snapshot);
13552 let end = range.end.to_display_point(display_snapshot);
13553 results.push((start..end, color))
13554 }
13555 }
13556 results
13557 }
13558
13559 /// Get the text ranges corresponding to the redaction query
13560 pub fn redacted_ranges(
13561 &self,
13562 search_range: Range<Anchor>,
13563 display_snapshot: &DisplaySnapshot,
13564 cx: &App,
13565 ) -> Vec<Range<DisplayPoint>> {
13566 display_snapshot
13567 .buffer_snapshot
13568 .redacted_ranges(search_range, |file| {
13569 if let Some(file) = file {
13570 file.is_private()
13571 && EditorSettings::get(
13572 Some(SettingsLocation {
13573 worktree_id: file.worktree_id(cx),
13574 path: file.path().as_ref(),
13575 }),
13576 cx,
13577 )
13578 .redact_private_values
13579 } else {
13580 false
13581 }
13582 })
13583 .map(|range| {
13584 range.start.to_display_point(display_snapshot)
13585 ..range.end.to_display_point(display_snapshot)
13586 })
13587 .collect()
13588 }
13589
13590 pub fn highlight_text<T: 'static>(
13591 &mut self,
13592 ranges: Vec<Range<Anchor>>,
13593 style: HighlightStyle,
13594 cx: &mut Context<Self>,
13595 ) {
13596 self.display_map.update(cx, |map, _| {
13597 map.highlight_text(TypeId::of::<T>(), ranges, style)
13598 });
13599 cx.notify();
13600 }
13601
13602 pub(crate) fn highlight_inlays<T: 'static>(
13603 &mut self,
13604 highlights: Vec<InlayHighlight>,
13605 style: HighlightStyle,
13606 cx: &mut Context<Self>,
13607 ) {
13608 self.display_map.update(cx, |map, _| {
13609 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13610 });
13611 cx.notify();
13612 }
13613
13614 pub fn text_highlights<'a, T: 'static>(
13615 &'a self,
13616 cx: &'a App,
13617 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13618 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13619 }
13620
13621 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13622 let cleared = self
13623 .display_map
13624 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13625 if cleared {
13626 cx.notify();
13627 }
13628 }
13629
13630 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13631 (self.read_only(cx) || self.blink_manager.read(cx).visible())
13632 && self.focus_handle.is_focused(window)
13633 }
13634
13635 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13636 self.show_cursor_when_unfocused = is_enabled;
13637 cx.notify();
13638 }
13639
13640 pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13641 self.project
13642 .as_ref()
13643 .map(|project| project.read(cx).lsp_store())
13644 }
13645
13646 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13647 cx.notify();
13648 }
13649
13650 fn on_buffer_event(
13651 &mut self,
13652 multibuffer: &Entity<MultiBuffer>,
13653 event: &multi_buffer::Event,
13654 window: &mut Window,
13655 cx: &mut Context<Self>,
13656 ) {
13657 match event {
13658 multi_buffer::Event::Edited {
13659 singleton_buffer_edited,
13660 edited_buffer: buffer_edited,
13661 } => {
13662 self.scrollbar_marker_state.dirty = true;
13663 self.active_indent_guides_state.dirty = true;
13664 self.refresh_active_diagnostics(cx);
13665 self.refresh_code_actions(window, cx);
13666 if self.has_active_inline_completion() {
13667 self.update_visible_inline_completion(window, cx);
13668 }
13669 if let Some(buffer) = buffer_edited {
13670 let buffer_id = buffer.read(cx).remote_id();
13671 if !self.registered_buffers.contains_key(&buffer_id) {
13672 if let Some(lsp_store) = self.lsp_store(cx) {
13673 lsp_store.update(cx, |lsp_store, cx| {
13674 self.registered_buffers.insert(
13675 buffer_id,
13676 lsp_store.register_buffer_with_language_servers(&buffer, cx),
13677 );
13678 })
13679 }
13680 }
13681 }
13682 cx.emit(EditorEvent::BufferEdited);
13683 cx.emit(SearchEvent::MatchesInvalidated);
13684 if *singleton_buffer_edited {
13685 if let Some(project) = &self.project {
13686 let project = project.read(cx);
13687 #[allow(clippy::mutable_key_type)]
13688 let languages_affected = multibuffer
13689 .read(cx)
13690 .all_buffers()
13691 .into_iter()
13692 .filter_map(|buffer| {
13693 let buffer = buffer.read(cx);
13694 let language = buffer.language()?;
13695 if project.is_local()
13696 && project
13697 .language_servers_for_local_buffer(buffer, cx)
13698 .count()
13699 == 0
13700 {
13701 None
13702 } else {
13703 Some(language)
13704 }
13705 })
13706 .cloned()
13707 .collect::<HashSet<_>>();
13708 if !languages_affected.is_empty() {
13709 self.refresh_inlay_hints(
13710 InlayHintRefreshReason::BufferEdited(languages_affected),
13711 cx,
13712 );
13713 }
13714 }
13715 }
13716
13717 let Some(project) = &self.project else { return };
13718 let (telemetry, is_via_ssh) = {
13719 let project = project.read(cx);
13720 let telemetry = project.client().telemetry().clone();
13721 let is_via_ssh = project.is_via_ssh();
13722 (telemetry, is_via_ssh)
13723 };
13724 refresh_linked_ranges(self, window, cx);
13725 telemetry.log_edit_event("editor", is_via_ssh);
13726 }
13727 multi_buffer::Event::ExcerptsAdded {
13728 buffer,
13729 predecessor,
13730 excerpts,
13731 } => {
13732 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13733 let buffer_id = buffer.read(cx).remote_id();
13734 if self.buffer.read(cx).change_set_for(buffer_id).is_none() {
13735 if let Some(project) = &self.project {
13736 get_uncommitted_changes_for_buffer(
13737 project,
13738 [buffer.clone()],
13739 self.buffer.clone(),
13740 cx,
13741 );
13742 }
13743 }
13744 cx.emit(EditorEvent::ExcerptsAdded {
13745 buffer: buffer.clone(),
13746 predecessor: *predecessor,
13747 excerpts: excerpts.clone(),
13748 });
13749 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13750 }
13751 multi_buffer::Event::ExcerptsRemoved { ids } => {
13752 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13753 let buffer = self.buffer.read(cx);
13754 self.registered_buffers
13755 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13756 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13757 }
13758 multi_buffer::Event::ExcerptsEdited { ids } => {
13759 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13760 }
13761 multi_buffer::Event::ExcerptsExpanded { ids } => {
13762 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13763 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13764 }
13765 multi_buffer::Event::Reparsed(buffer_id) => {
13766 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13767
13768 cx.emit(EditorEvent::Reparsed(*buffer_id));
13769 }
13770 multi_buffer::Event::DiffHunksToggled => {
13771 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13772 }
13773 multi_buffer::Event::LanguageChanged(buffer_id) => {
13774 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13775 cx.emit(EditorEvent::Reparsed(*buffer_id));
13776 cx.notify();
13777 }
13778 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13779 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13780 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13781 cx.emit(EditorEvent::TitleChanged)
13782 }
13783 // multi_buffer::Event::DiffBaseChanged => {
13784 // self.scrollbar_marker_state.dirty = true;
13785 // cx.emit(EditorEvent::DiffBaseChanged);
13786 // cx.notify();
13787 // }
13788 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13789 multi_buffer::Event::DiagnosticsUpdated => {
13790 self.refresh_active_diagnostics(cx);
13791 self.scrollbar_marker_state.dirty = true;
13792 cx.notify();
13793 }
13794 _ => {}
13795 };
13796 }
13797
13798 fn on_display_map_changed(
13799 &mut self,
13800 _: Entity<DisplayMap>,
13801 _: &mut Window,
13802 cx: &mut Context<Self>,
13803 ) {
13804 cx.notify();
13805 }
13806
13807 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13808 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13809 self.refresh_inline_completion(true, false, window, cx);
13810 self.refresh_inlay_hints(
13811 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13812 self.selections.newest_anchor().head(),
13813 &self.buffer.read(cx).snapshot(cx),
13814 cx,
13815 )),
13816 cx,
13817 );
13818
13819 let old_cursor_shape = self.cursor_shape;
13820
13821 {
13822 let editor_settings = EditorSettings::get_global(cx);
13823 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13824 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13825 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13826 }
13827
13828 if old_cursor_shape != self.cursor_shape {
13829 cx.emit(EditorEvent::CursorShapeChanged);
13830 }
13831
13832 let project_settings = ProjectSettings::get_global(cx);
13833 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13834
13835 if self.mode == EditorMode::Full {
13836 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13837 if self.git_blame_inline_enabled != inline_blame_enabled {
13838 self.toggle_git_blame_inline_internal(false, window, cx);
13839 }
13840 }
13841
13842 cx.notify();
13843 }
13844
13845 pub fn set_searchable(&mut self, searchable: bool) {
13846 self.searchable = searchable;
13847 }
13848
13849 pub fn searchable(&self) -> bool {
13850 self.searchable
13851 }
13852
13853 fn open_proposed_changes_editor(
13854 &mut self,
13855 _: &OpenProposedChangesEditor,
13856 window: &mut Window,
13857 cx: &mut Context<Self>,
13858 ) {
13859 let Some(workspace) = self.workspace() else {
13860 cx.propagate();
13861 return;
13862 };
13863
13864 let selections = self.selections.all::<usize>(cx);
13865 let multi_buffer = self.buffer.read(cx);
13866 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13867 let mut new_selections_by_buffer = HashMap::default();
13868 for selection in selections {
13869 for (buffer, range, _) in
13870 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13871 {
13872 let mut range = range.to_point(buffer);
13873 range.start.column = 0;
13874 range.end.column = buffer.line_len(range.end.row);
13875 new_selections_by_buffer
13876 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13877 .or_insert(Vec::new())
13878 .push(range)
13879 }
13880 }
13881
13882 let proposed_changes_buffers = new_selections_by_buffer
13883 .into_iter()
13884 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13885 .collect::<Vec<_>>();
13886 let proposed_changes_editor = cx.new(|cx| {
13887 ProposedChangesEditor::new(
13888 "Proposed changes",
13889 proposed_changes_buffers,
13890 self.project.clone(),
13891 window,
13892 cx,
13893 )
13894 });
13895
13896 window.defer(cx, move |window, cx| {
13897 workspace.update(cx, |workspace, cx| {
13898 workspace.active_pane().update(cx, |pane, cx| {
13899 pane.add_item(
13900 Box::new(proposed_changes_editor),
13901 true,
13902 true,
13903 None,
13904 window,
13905 cx,
13906 );
13907 });
13908 });
13909 });
13910 }
13911
13912 pub fn open_excerpts_in_split(
13913 &mut self,
13914 _: &OpenExcerptsSplit,
13915 window: &mut Window,
13916 cx: &mut Context<Self>,
13917 ) {
13918 self.open_excerpts_common(None, true, window, cx)
13919 }
13920
13921 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
13922 self.open_excerpts_common(None, false, window, cx)
13923 }
13924
13925 fn open_excerpts_common(
13926 &mut self,
13927 jump_data: Option<JumpData>,
13928 split: bool,
13929 window: &mut Window,
13930 cx: &mut Context<Self>,
13931 ) {
13932 let Some(workspace) = self.workspace() else {
13933 cx.propagate();
13934 return;
13935 };
13936
13937 if self.buffer.read(cx).is_singleton() {
13938 cx.propagate();
13939 return;
13940 }
13941
13942 let mut new_selections_by_buffer = HashMap::default();
13943 match &jump_data {
13944 Some(JumpData::MultiBufferPoint {
13945 excerpt_id,
13946 position,
13947 anchor,
13948 line_offset_from_top,
13949 }) => {
13950 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13951 if let Some(buffer) = multi_buffer_snapshot
13952 .buffer_id_for_excerpt(*excerpt_id)
13953 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
13954 {
13955 let buffer_snapshot = buffer.read(cx).snapshot();
13956 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
13957 language::ToPoint::to_point(anchor, &buffer_snapshot)
13958 } else {
13959 buffer_snapshot.clip_point(*position, Bias::Left)
13960 };
13961 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
13962 new_selections_by_buffer.insert(
13963 buffer,
13964 (
13965 vec![jump_to_offset..jump_to_offset],
13966 Some(*line_offset_from_top),
13967 ),
13968 );
13969 }
13970 }
13971 Some(JumpData::MultiBufferRow {
13972 row,
13973 line_offset_from_top,
13974 }) => {
13975 let point = MultiBufferPoint::new(row.0, 0);
13976 if let Some((buffer, buffer_point, _)) =
13977 self.buffer.read(cx).point_to_buffer_point(point, cx)
13978 {
13979 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
13980 new_selections_by_buffer
13981 .entry(buffer)
13982 .or_insert((Vec::new(), Some(*line_offset_from_top)))
13983 .0
13984 .push(buffer_offset..buffer_offset)
13985 }
13986 }
13987 None => {
13988 let selections = self.selections.all::<usize>(cx);
13989 let multi_buffer = self.buffer.read(cx);
13990 for selection in selections {
13991 for (buffer, mut range, _) in multi_buffer
13992 .snapshot(cx)
13993 .range_to_buffer_ranges(selection.range())
13994 {
13995 // When editing branch buffers, jump to the corresponding location
13996 // in their base buffer.
13997 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
13998 let buffer = buffer_handle.read(cx);
13999 if let Some(base_buffer) = buffer.base_buffer() {
14000 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14001 buffer_handle = base_buffer;
14002 }
14003
14004 if selection.reversed {
14005 mem::swap(&mut range.start, &mut range.end);
14006 }
14007 new_selections_by_buffer
14008 .entry(buffer_handle)
14009 .or_insert((Vec::new(), None))
14010 .0
14011 .push(range)
14012 }
14013 }
14014 }
14015 }
14016
14017 if new_selections_by_buffer.is_empty() {
14018 return;
14019 }
14020
14021 // We defer the pane interaction because we ourselves are a workspace item
14022 // and activating a new item causes the pane to call a method on us reentrantly,
14023 // which panics if we're on the stack.
14024 window.defer(cx, move |window, cx| {
14025 workspace.update(cx, |workspace, cx| {
14026 let pane = if split {
14027 workspace.adjacent_pane(window, cx)
14028 } else {
14029 workspace.active_pane().clone()
14030 };
14031
14032 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14033 let editor = buffer
14034 .read(cx)
14035 .file()
14036 .is_none()
14037 .then(|| {
14038 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14039 // so `workspace.open_project_item` will never find them, always opening a new editor.
14040 // Instead, we try to activate the existing editor in the pane first.
14041 let (editor, pane_item_index) =
14042 pane.read(cx).items().enumerate().find_map(|(i, item)| {
14043 let editor = item.downcast::<Editor>()?;
14044 let singleton_buffer =
14045 editor.read(cx).buffer().read(cx).as_singleton()?;
14046 if singleton_buffer == buffer {
14047 Some((editor, i))
14048 } else {
14049 None
14050 }
14051 })?;
14052 pane.update(cx, |pane, cx| {
14053 pane.activate_item(pane_item_index, true, true, window, cx)
14054 });
14055 Some(editor)
14056 })
14057 .flatten()
14058 .unwrap_or_else(|| {
14059 workspace.open_project_item::<Self>(
14060 pane.clone(),
14061 buffer,
14062 true,
14063 true,
14064 window,
14065 cx,
14066 )
14067 });
14068
14069 editor.update(cx, |editor, cx| {
14070 let autoscroll = match scroll_offset {
14071 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14072 None => Autoscroll::newest(),
14073 };
14074 let nav_history = editor.nav_history.take();
14075 editor.change_selections(Some(autoscroll), window, cx, |s| {
14076 s.select_ranges(ranges);
14077 });
14078 editor.nav_history = nav_history;
14079 });
14080 }
14081 })
14082 });
14083 }
14084
14085 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14086 let snapshot = self.buffer.read(cx).read(cx);
14087 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14088 Some(
14089 ranges
14090 .iter()
14091 .map(move |range| {
14092 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14093 })
14094 .collect(),
14095 )
14096 }
14097
14098 fn selection_replacement_ranges(
14099 &self,
14100 range: Range<OffsetUtf16>,
14101 cx: &mut App,
14102 ) -> Vec<Range<OffsetUtf16>> {
14103 let selections = self.selections.all::<OffsetUtf16>(cx);
14104 let newest_selection = selections
14105 .iter()
14106 .max_by_key(|selection| selection.id)
14107 .unwrap();
14108 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14109 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14110 let snapshot = self.buffer.read(cx).read(cx);
14111 selections
14112 .into_iter()
14113 .map(|mut selection| {
14114 selection.start.0 =
14115 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14116 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14117 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14118 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14119 })
14120 .collect()
14121 }
14122
14123 fn report_editor_event(
14124 &self,
14125 event_type: &'static str,
14126 file_extension: Option<String>,
14127 cx: &App,
14128 ) {
14129 if cfg!(any(test, feature = "test-support")) {
14130 return;
14131 }
14132
14133 let Some(project) = &self.project else { return };
14134
14135 // If None, we are in a file without an extension
14136 let file = self
14137 .buffer
14138 .read(cx)
14139 .as_singleton()
14140 .and_then(|b| b.read(cx).file());
14141 let file_extension = file_extension.or(file
14142 .as_ref()
14143 .and_then(|file| Path::new(file.file_name(cx)).extension())
14144 .and_then(|e| e.to_str())
14145 .map(|a| a.to_string()));
14146
14147 let vim_mode = cx
14148 .global::<SettingsStore>()
14149 .raw_user_settings()
14150 .get("vim_mode")
14151 == Some(&serde_json::Value::Bool(true));
14152
14153 let edit_predictions_provider = all_language_settings(file, cx).inline_completions.provider;
14154 let copilot_enabled = edit_predictions_provider
14155 == language::language_settings::InlineCompletionProvider::Copilot;
14156 let copilot_enabled_for_language = self
14157 .buffer
14158 .read(cx)
14159 .settings_at(0, cx)
14160 .show_inline_completions;
14161
14162 let project = project.read(cx);
14163 telemetry::event!(
14164 event_type,
14165 file_extension,
14166 vim_mode,
14167 copilot_enabled,
14168 copilot_enabled_for_language,
14169 edit_predictions_provider,
14170 is_via_ssh = project.is_via_ssh(),
14171 );
14172 }
14173
14174 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14175 /// with each line being an array of {text, highlight} objects.
14176 fn copy_highlight_json(
14177 &mut self,
14178 _: &CopyHighlightJson,
14179 window: &mut Window,
14180 cx: &mut Context<Self>,
14181 ) {
14182 #[derive(Serialize)]
14183 struct Chunk<'a> {
14184 text: String,
14185 highlight: Option<&'a str>,
14186 }
14187
14188 let snapshot = self.buffer.read(cx).snapshot(cx);
14189 let range = self
14190 .selected_text_range(false, window, cx)
14191 .and_then(|selection| {
14192 if selection.range.is_empty() {
14193 None
14194 } else {
14195 Some(selection.range)
14196 }
14197 })
14198 .unwrap_or_else(|| 0..snapshot.len());
14199
14200 let chunks = snapshot.chunks(range, true);
14201 let mut lines = Vec::new();
14202 let mut line: VecDeque<Chunk> = VecDeque::new();
14203
14204 let Some(style) = self.style.as_ref() else {
14205 return;
14206 };
14207
14208 for chunk in chunks {
14209 let highlight = chunk
14210 .syntax_highlight_id
14211 .and_then(|id| id.name(&style.syntax));
14212 let mut chunk_lines = chunk.text.split('\n').peekable();
14213 while let Some(text) = chunk_lines.next() {
14214 let mut merged_with_last_token = false;
14215 if let Some(last_token) = line.back_mut() {
14216 if last_token.highlight == highlight {
14217 last_token.text.push_str(text);
14218 merged_with_last_token = true;
14219 }
14220 }
14221
14222 if !merged_with_last_token {
14223 line.push_back(Chunk {
14224 text: text.into(),
14225 highlight,
14226 });
14227 }
14228
14229 if chunk_lines.peek().is_some() {
14230 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14231 line.pop_front();
14232 }
14233 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14234 line.pop_back();
14235 }
14236
14237 lines.push(mem::take(&mut line));
14238 }
14239 }
14240 }
14241
14242 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14243 return;
14244 };
14245 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14246 }
14247
14248 pub fn open_context_menu(
14249 &mut self,
14250 _: &OpenContextMenu,
14251 window: &mut Window,
14252 cx: &mut Context<Self>,
14253 ) {
14254 self.request_autoscroll(Autoscroll::newest(), cx);
14255 let position = self.selections.newest_display(cx).start;
14256 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14257 }
14258
14259 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14260 &self.inlay_hint_cache
14261 }
14262
14263 pub fn replay_insert_event(
14264 &mut self,
14265 text: &str,
14266 relative_utf16_range: Option<Range<isize>>,
14267 window: &mut Window,
14268 cx: &mut Context<Self>,
14269 ) {
14270 if !self.input_enabled {
14271 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14272 return;
14273 }
14274 if let Some(relative_utf16_range) = relative_utf16_range {
14275 let selections = self.selections.all::<OffsetUtf16>(cx);
14276 self.change_selections(None, window, cx, |s| {
14277 let new_ranges = selections.into_iter().map(|range| {
14278 let start = OffsetUtf16(
14279 range
14280 .head()
14281 .0
14282 .saturating_add_signed(relative_utf16_range.start),
14283 );
14284 let end = OffsetUtf16(
14285 range
14286 .head()
14287 .0
14288 .saturating_add_signed(relative_utf16_range.end),
14289 );
14290 start..end
14291 });
14292 s.select_ranges(new_ranges);
14293 });
14294 }
14295
14296 self.handle_input(text, window, cx);
14297 }
14298
14299 pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14300 let Some(provider) = self.semantics_provider.as_ref() else {
14301 return false;
14302 };
14303
14304 let mut supports = false;
14305 self.buffer().read(cx).for_each_buffer(|buffer| {
14306 supports |= provider.supports_inlay_hints(buffer, cx);
14307 });
14308 supports
14309 }
14310 pub fn is_focused(&self, window: &mut Window) -> bool {
14311 self.focus_handle.is_focused(window)
14312 }
14313
14314 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14315 cx.emit(EditorEvent::Focused);
14316
14317 if let Some(descendant) = self
14318 .last_focused_descendant
14319 .take()
14320 .and_then(|descendant| descendant.upgrade())
14321 {
14322 window.focus(&descendant);
14323 } else {
14324 if let Some(blame) = self.blame.as_ref() {
14325 blame.update(cx, GitBlame::focus)
14326 }
14327
14328 self.blink_manager.update(cx, BlinkManager::enable);
14329 self.show_cursor_names(window, cx);
14330 self.buffer.update(cx, |buffer, cx| {
14331 buffer.finalize_last_transaction(cx);
14332 if self.leader_peer_id.is_none() {
14333 buffer.set_active_selections(
14334 &self.selections.disjoint_anchors(),
14335 self.selections.line_mode,
14336 self.cursor_shape,
14337 cx,
14338 );
14339 }
14340 });
14341 }
14342 }
14343
14344 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14345 cx.emit(EditorEvent::FocusedIn)
14346 }
14347
14348 fn handle_focus_out(
14349 &mut self,
14350 event: FocusOutEvent,
14351 _window: &mut Window,
14352 _cx: &mut Context<Self>,
14353 ) {
14354 if event.blurred != self.focus_handle {
14355 self.last_focused_descendant = Some(event.blurred);
14356 }
14357 }
14358
14359 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14360 self.blink_manager.update(cx, BlinkManager::disable);
14361 self.buffer
14362 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14363
14364 if let Some(blame) = self.blame.as_ref() {
14365 blame.update(cx, GitBlame::blur)
14366 }
14367 if !self.hover_state.focused(window, cx) {
14368 hide_hover(self, cx);
14369 }
14370
14371 self.hide_context_menu(window, cx);
14372 cx.emit(EditorEvent::Blurred);
14373 cx.notify();
14374 }
14375
14376 pub fn register_action<A: Action>(
14377 &mut self,
14378 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14379 ) -> Subscription {
14380 let id = self.next_editor_action_id.post_inc();
14381 let listener = Arc::new(listener);
14382 self.editor_actions.borrow_mut().insert(
14383 id,
14384 Box::new(move |window, _| {
14385 let listener = listener.clone();
14386 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14387 let action = action.downcast_ref().unwrap();
14388 if phase == DispatchPhase::Bubble {
14389 listener(action, window, cx)
14390 }
14391 })
14392 }),
14393 );
14394
14395 let editor_actions = self.editor_actions.clone();
14396 Subscription::new(move || {
14397 editor_actions.borrow_mut().remove(&id);
14398 })
14399 }
14400
14401 pub fn file_header_size(&self) -> u32 {
14402 FILE_HEADER_HEIGHT
14403 }
14404
14405 pub fn revert(
14406 &mut self,
14407 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14408 window: &mut Window,
14409 cx: &mut Context<Self>,
14410 ) {
14411 self.buffer().update(cx, |multi_buffer, cx| {
14412 for (buffer_id, changes) in revert_changes {
14413 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14414 buffer.update(cx, |buffer, cx| {
14415 buffer.edit(
14416 changes.into_iter().map(|(range, text)| {
14417 (range, text.to_string().map(Arc::<str>::from))
14418 }),
14419 None,
14420 cx,
14421 );
14422 });
14423 }
14424 }
14425 });
14426 self.change_selections(None, window, cx, |selections| selections.refresh());
14427 }
14428
14429 pub fn to_pixel_point(
14430 &self,
14431 source: multi_buffer::Anchor,
14432 editor_snapshot: &EditorSnapshot,
14433 window: &mut Window,
14434 ) -> Option<gpui::Point<Pixels>> {
14435 let source_point = source.to_display_point(editor_snapshot);
14436 self.display_to_pixel_point(source_point, editor_snapshot, window)
14437 }
14438
14439 pub fn display_to_pixel_point(
14440 &self,
14441 source: DisplayPoint,
14442 editor_snapshot: &EditorSnapshot,
14443 window: &mut Window,
14444 ) -> Option<gpui::Point<Pixels>> {
14445 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14446 let text_layout_details = self.text_layout_details(window);
14447 let scroll_top = text_layout_details
14448 .scroll_anchor
14449 .scroll_position(editor_snapshot)
14450 .y;
14451
14452 if source.row().as_f32() < scroll_top.floor() {
14453 return None;
14454 }
14455 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14456 let source_y = line_height * (source.row().as_f32() - scroll_top);
14457 Some(gpui::Point::new(source_x, source_y))
14458 }
14459
14460 pub fn has_visible_completions_menu(&self) -> bool {
14461 !self.previewing_inline_completion
14462 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14463 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14464 })
14465 }
14466
14467 pub fn register_addon<T: Addon>(&mut self, instance: T) {
14468 self.addons
14469 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14470 }
14471
14472 pub fn unregister_addon<T: Addon>(&mut self) {
14473 self.addons.remove(&std::any::TypeId::of::<T>());
14474 }
14475
14476 pub fn addon<T: Addon>(&self) -> Option<&T> {
14477 let type_id = std::any::TypeId::of::<T>();
14478 self.addons
14479 .get(&type_id)
14480 .and_then(|item| item.to_any().downcast_ref::<T>())
14481 }
14482
14483 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14484 let text_layout_details = self.text_layout_details(window);
14485 let style = &text_layout_details.editor_style;
14486 let font_id = window.text_system().resolve_font(&style.text.font());
14487 let font_size = style.text.font_size.to_pixels(window.rem_size());
14488 let line_height = style.text.line_height_in_pixels(window.rem_size());
14489 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14490
14491 gpui::Size::new(em_width, line_height)
14492 }
14493}
14494
14495fn get_uncommitted_changes_for_buffer(
14496 project: &Entity<Project>,
14497 buffers: impl IntoIterator<Item = Entity<Buffer>>,
14498 buffer: Entity<MultiBuffer>,
14499 cx: &mut App,
14500) {
14501 let mut tasks = Vec::new();
14502 project.update(cx, |project, cx| {
14503 for buffer in buffers {
14504 tasks.push(project.open_uncommitted_changes(buffer.clone(), cx))
14505 }
14506 });
14507 cx.spawn(|mut cx| async move {
14508 let change_sets = futures::future::join_all(tasks).await;
14509 buffer
14510 .update(&mut cx, |buffer, cx| {
14511 for change_set in change_sets.into_iter().flatten() {
14512 buffer.add_change_set(change_set, cx);
14513 }
14514 })
14515 .ok();
14516 })
14517 .detach();
14518}
14519
14520fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14521 let tab_size = tab_size.get() as usize;
14522 let mut width = offset;
14523
14524 for ch in text.chars() {
14525 width += if ch == '\t' {
14526 tab_size - (width % tab_size)
14527 } else {
14528 1
14529 };
14530 }
14531
14532 width - offset
14533}
14534
14535#[cfg(test)]
14536mod tests {
14537 use super::*;
14538
14539 #[test]
14540 fn test_string_size_with_expanded_tabs() {
14541 let nz = |val| NonZeroU32::new(val).unwrap();
14542 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14543 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14544 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14545 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14546 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14547 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14548 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14549 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14550 }
14551}
14552
14553/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14554struct WordBreakingTokenizer<'a> {
14555 input: &'a str,
14556}
14557
14558impl<'a> WordBreakingTokenizer<'a> {
14559 fn new(input: &'a str) -> Self {
14560 Self { input }
14561 }
14562}
14563
14564fn is_char_ideographic(ch: char) -> bool {
14565 use unicode_script::Script::*;
14566 use unicode_script::UnicodeScript;
14567 matches!(ch.script(), Han | Tangut | Yi)
14568}
14569
14570fn is_grapheme_ideographic(text: &str) -> bool {
14571 text.chars().any(is_char_ideographic)
14572}
14573
14574fn is_grapheme_whitespace(text: &str) -> bool {
14575 text.chars().any(|x| x.is_whitespace())
14576}
14577
14578fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14579 text.chars().next().map_or(false, |ch| {
14580 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14581 })
14582}
14583
14584#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14585struct WordBreakToken<'a> {
14586 token: &'a str,
14587 grapheme_len: usize,
14588 is_whitespace: bool,
14589}
14590
14591impl<'a> Iterator for WordBreakingTokenizer<'a> {
14592 /// Yields a span, the count of graphemes in the token, and whether it was
14593 /// whitespace. Note that it also breaks at word boundaries.
14594 type Item = WordBreakToken<'a>;
14595
14596 fn next(&mut self) -> Option<Self::Item> {
14597 use unicode_segmentation::UnicodeSegmentation;
14598 if self.input.is_empty() {
14599 return None;
14600 }
14601
14602 let mut iter = self.input.graphemes(true).peekable();
14603 let mut offset = 0;
14604 let mut graphemes = 0;
14605 if let Some(first_grapheme) = iter.next() {
14606 let is_whitespace = is_grapheme_whitespace(first_grapheme);
14607 offset += first_grapheme.len();
14608 graphemes += 1;
14609 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14610 if let Some(grapheme) = iter.peek().copied() {
14611 if should_stay_with_preceding_ideograph(grapheme) {
14612 offset += grapheme.len();
14613 graphemes += 1;
14614 }
14615 }
14616 } else {
14617 let mut words = self.input[offset..].split_word_bound_indices().peekable();
14618 let mut next_word_bound = words.peek().copied();
14619 if next_word_bound.map_or(false, |(i, _)| i == 0) {
14620 next_word_bound = words.next();
14621 }
14622 while let Some(grapheme) = iter.peek().copied() {
14623 if next_word_bound.map_or(false, |(i, _)| i == offset) {
14624 break;
14625 };
14626 if is_grapheme_whitespace(grapheme) != is_whitespace {
14627 break;
14628 };
14629 offset += grapheme.len();
14630 graphemes += 1;
14631 iter.next();
14632 }
14633 }
14634 let token = &self.input[..offset];
14635 self.input = &self.input[offset..];
14636 if is_whitespace {
14637 Some(WordBreakToken {
14638 token: " ",
14639 grapheme_len: 1,
14640 is_whitespace: true,
14641 })
14642 } else {
14643 Some(WordBreakToken {
14644 token,
14645 grapheme_len: graphemes,
14646 is_whitespace: false,
14647 })
14648 }
14649 } else {
14650 None
14651 }
14652 }
14653}
14654
14655#[test]
14656fn test_word_breaking_tokenizer() {
14657 let tests: &[(&str, &[(&str, usize, bool)])] = &[
14658 ("", &[]),
14659 (" ", &[(" ", 1, true)]),
14660 ("Ʒ", &[("Ʒ", 1, false)]),
14661 ("Ǽ", &[("Ǽ", 1, false)]),
14662 ("⋑", &[("⋑", 1, false)]),
14663 ("⋑⋑", &[("⋑⋑", 2, false)]),
14664 (
14665 "原理,进而",
14666 &[
14667 ("原", 1, false),
14668 ("理,", 2, false),
14669 ("进", 1, false),
14670 ("而", 1, false),
14671 ],
14672 ),
14673 (
14674 "hello world",
14675 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14676 ),
14677 (
14678 "hello, world",
14679 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14680 ),
14681 (
14682 " hello world",
14683 &[
14684 (" ", 1, true),
14685 ("hello", 5, false),
14686 (" ", 1, true),
14687 ("world", 5, false),
14688 ],
14689 ),
14690 (
14691 "这是什么 \n 钢笔",
14692 &[
14693 ("这", 1, false),
14694 ("是", 1, false),
14695 ("什", 1, false),
14696 ("么", 1, false),
14697 (" ", 1, true),
14698 ("钢", 1, false),
14699 ("笔", 1, false),
14700 ],
14701 ),
14702 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14703 ];
14704
14705 for (input, result) in tests {
14706 assert_eq!(
14707 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14708 result
14709 .iter()
14710 .copied()
14711 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14712 token,
14713 grapheme_len,
14714 is_whitespace,
14715 })
14716 .collect::<Vec<_>>()
14717 );
14718 }
14719}
14720
14721fn wrap_with_prefix(
14722 line_prefix: String,
14723 unwrapped_text: String,
14724 wrap_column: usize,
14725 tab_size: NonZeroU32,
14726) -> String {
14727 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14728 let mut wrapped_text = String::new();
14729 let mut current_line = line_prefix.clone();
14730
14731 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14732 let mut current_line_len = line_prefix_len;
14733 for WordBreakToken {
14734 token,
14735 grapheme_len,
14736 is_whitespace,
14737 } in tokenizer
14738 {
14739 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14740 wrapped_text.push_str(current_line.trim_end());
14741 wrapped_text.push('\n');
14742 current_line.truncate(line_prefix.len());
14743 current_line_len = line_prefix_len;
14744 if !is_whitespace {
14745 current_line.push_str(token);
14746 current_line_len += grapheme_len;
14747 }
14748 } else if !is_whitespace {
14749 current_line.push_str(token);
14750 current_line_len += grapheme_len;
14751 } else if current_line_len != line_prefix_len {
14752 current_line.push(' ');
14753 current_line_len += 1;
14754 }
14755 }
14756
14757 if !current_line.is_empty() {
14758 wrapped_text.push_str(¤t_line);
14759 }
14760 wrapped_text
14761}
14762
14763#[test]
14764fn test_wrap_with_prefix() {
14765 assert_eq!(
14766 wrap_with_prefix(
14767 "# ".to_string(),
14768 "abcdefg".to_string(),
14769 4,
14770 NonZeroU32::new(4).unwrap()
14771 ),
14772 "# abcdefg"
14773 );
14774 assert_eq!(
14775 wrap_with_prefix(
14776 "".to_string(),
14777 "\thello world".to_string(),
14778 8,
14779 NonZeroU32::new(4).unwrap()
14780 ),
14781 "hello\nworld"
14782 );
14783 assert_eq!(
14784 wrap_with_prefix(
14785 "// ".to_string(),
14786 "xx \nyy zz aa bb cc".to_string(),
14787 12,
14788 NonZeroU32::new(4).unwrap()
14789 ),
14790 "// xx yy zz\n// aa bb cc"
14791 );
14792 assert_eq!(
14793 wrap_with_prefix(
14794 String::new(),
14795 "这是什么 \n 钢笔".to_string(),
14796 3,
14797 NonZeroU32::new(4).unwrap()
14798 ),
14799 "这是什\n么 钢\n笔"
14800 );
14801}
14802
14803pub trait CollaborationHub {
14804 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14805 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14806 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14807}
14808
14809impl CollaborationHub for Entity<Project> {
14810 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14811 self.read(cx).collaborators()
14812 }
14813
14814 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14815 self.read(cx).user_store().read(cx).participant_indices()
14816 }
14817
14818 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14819 let this = self.read(cx);
14820 let user_ids = this.collaborators().values().map(|c| c.user_id);
14821 this.user_store().read_with(cx, |user_store, cx| {
14822 user_store.participant_names(user_ids, cx)
14823 })
14824 }
14825}
14826
14827pub trait SemanticsProvider {
14828 fn hover(
14829 &self,
14830 buffer: &Entity<Buffer>,
14831 position: text::Anchor,
14832 cx: &mut App,
14833 ) -> Option<Task<Vec<project::Hover>>>;
14834
14835 fn inlay_hints(
14836 &self,
14837 buffer_handle: Entity<Buffer>,
14838 range: Range<text::Anchor>,
14839 cx: &mut App,
14840 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14841
14842 fn resolve_inlay_hint(
14843 &self,
14844 hint: InlayHint,
14845 buffer_handle: Entity<Buffer>,
14846 server_id: LanguageServerId,
14847 cx: &mut App,
14848 ) -> Option<Task<anyhow::Result<InlayHint>>>;
14849
14850 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
14851
14852 fn document_highlights(
14853 &self,
14854 buffer: &Entity<Buffer>,
14855 position: text::Anchor,
14856 cx: &mut App,
14857 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14858
14859 fn definitions(
14860 &self,
14861 buffer: &Entity<Buffer>,
14862 position: text::Anchor,
14863 kind: GotoDefinitionKind,
14864 cx: &mut App,
14865 ) -> Option<Task<Result<Vec<LocationLink>>>>;
14866
14867 fn range_for_rename(
14868 &self,
14869 buffer: &Entity<Buffer>,
14870 position: text::Anchor,
14871 cx: &mut App,
14872 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14873
14874 fn perform_rename(
14875 &self,
14876 buffer: &Entity<Buffer>,
14877 position: text::Anchor,
14878 new_name: String,
14879 cx: &mut App,
14880 ) -> Option<Task<Result<ProjectTransaction>>>;
14881}
14882
14883pub trait CompletionProvider {
14884 fn completions(
14885 &self,
14886 buffer: &Entity<Buffer>,
14887 buffer_position: text::Anchor,
14888 trigger: CompletionContext,
14889 window: &mut Window,
14890 cx: &mut Context<Editor>,
14891 ) -> Task<Result<Vec<Completion>>>;
14892
14893 fn resolve_completions(
14894 &self,
14895 buffer: Entity<Buffer>,
14896 completion_indices: Vec<usize>,
14897 completions: Rc<RefCell<Box<[Completion]>>>,
14898 cx: &mut Context<Editor>,
14899 ) -> Task<Result<bool>>;
14900
14901 fn apply_additional_edits_for_completion(
14902 &self,
14903 _buffer: Entity<Buffer>,
14904 _completions: Rc<RefCell<Box<[Completion]>>>,
14905 _completion_index: usize,
14906 _push_to_history: bool,
14907 _cx: &mut Context<Editor>,
14908 ) -> Task<Result<Option<language::Transaction>>> {
14909 Task::ready(Ok(None))
14910 }
14911
14912 fn is_completion_trigger(
14913 &self,
14914 buffer: &Entity<Buffer>,
14915 position: language::Anchor,
14916 text: &str,
14917 trigger_in_words: bool,
14918 cx: &mut Context<Editor>,
14919 ) -> bool;
14920
14921 fn sort_completions(&self) -> bool {
14922 true
14923 }
14924}
14925
14926pub trait CodeActionProvider {
14927 fn id(&self) -> Arc<str>;
14928
14929 fn code_actions(
14930 &self,
14931 buffer: &Entity<Buffer>,
14932 range: Range<text::Anchor>,
14933 window: &mut Window,
14934 cx: &mut App,
14935 ) -> Task<Result<Vec<CodeAction>>>;
14936
14937 fn apply_code_action(
14938 &self,
14939 buffer_handle: Entity<Buffer>,
14940 action: CodeAction,
14941 excerpt_id: ExcerptId,
14942 push_to_history: bool,
14943 window: &mut Window,
14944 cx: &mut App,
14945 ) -> Task<Result<ProjectTransaction>>;
14946}
14947
14948impl CodeActionProvider for Entity<Project> {
14949 fn id(&self) -> Arc<str> {
14950 "project".into()
14951 }
14952
14953 fn code_actions(
14954 &self,
14955 buffer: &Entity<Buffer>,
14956 range: Range<text::Anchor>,
14957 _window: &mut Window,
14958 cx: &mut App,
14959 ) -> Task<Result<Vec<CodeAction>>> {
14960 self.update(cx, |project, cx| {
14961 project.code_actions(buffer, range, None, cx)
14962 })
14963 }
14964
14965 fn apply_code_action(
14966 &self,
14967 buffer_handle: Entity<Buffer>,
14968 action: CodeAction,
14969 _excerpt_id: ExcerptId,
14970 push_to_history: bool,
14971 _window: &mut Window,
14972 cx: &mut App,
14973 ) -> Task<Result<ProjectTransaction>> {
14974 self.update(cx, |project, cx| {
14975 project.apply_code_action(buffer_handle, action, push_to_history, cx)
14976 })
14977 }
14978}
14979
14980fn snippet_completions(
14981 project: &Project,
14982 buffer: &Entity<Buffer>,
14983 buffer_position: text::Anchor,
14984 cx: &mut App,
14985) -> Task<Result<Vec<Completion>>> {
14986 let language = buffer.read(cx).language_at(buffer_position);
14987 let language_name = language.as_ref().map(|language| language.lsp_id());
14988 let snippet_store = project.snippets().read(cx);
14989 let snippets = snippet_store.snippets_for(language_name, cx);
14990
14991 if snippets.is_empty() {
14992 return Task::ready(Ok(vec![]));
14993 }
14994 let snapshot = buffer.read(cx).text_snapshot();
14995 let chars: String = snapshot
14996 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
14997 .collect();
14998
14999 let scope = language.map(|language| language.default_scope());
15000 let executor = cx.background_executor().clone();
15001
15002 cx.background_executor().spawn(async move {
15003 let classifier = CharClassifier::new(scope).for_completion(true);
15004 let mut last_word = chars
15005 .chars()
15006 .take_while(|c| classifier.is_word(*c))
15007 .collect::<String>();
15008 last_word = last_word.chars().rev().collect();
15009
15010 if last_word.is_empty() {
15011 return Ok(vec![]);
15012 }
15013
15014 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15015 let to_lsp = |point: &text::Anchor| {
15016 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15017 point_to_lsp(end)
15018 };
15019 let lsp_end = to_lsp(&buffer_position);
15020
15021 let candidates = snippets
15022 .iter()
15023 .enumerate()
15024 .flat_map(|(ix, snippet)| {
15025 snippet
15026 .prefix
15027 .iter()
15028 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15029 })
15030 .collect::<Vec<StringMatchCandidate>>();
15031
15032 let mut matches = fuzzy::match_strings(
15033 &candidates,
15034 &last_word,
15035 last_word.chars().any(|c| c.is_uppercase()),
15036 100,
15037 &Default::default(),
15038 executor,
15039 )
15040 .await;
15041
15042 // Remove all candidates where the query's start does not match the start of any word in the candidate
15043 if let Some(query_start) = last_word.chars().next() {
15044 matches.retain(|string_match| {
15045 split_words(&string_match.string).any(|word| {
15046 // Check that the first codepoint of the word as lowercase matches the first
15047 // codepoint of the query as lowercase
15048 word.chars()
15049 .flat_map(|codepoint| codepoint.to_lowercase())
15050 .zip(query_start.to_lowercase())
15051 .all(|(word_cp, query_cp)| word_cp == query_cp)
15052 })
15053 });
15054 }
15055
15056 let matched_strings = matches
15057 .into_iter()
15058 .map(|m| m.string)
15059 .collect::<HashSet<_>>();
15060
15061 let result: Vec<Completion> = snippets
15062 .into_iter()
15063 .filter_map(|snippet| {
15064 let matching_prefix = snippet
15065 .prefix
15066 .iter()
15067 .find(|prefix| matched_strings.contains(*prefix))?;
15068 let start = as_offset - last_word.len();
15069 let start = snapshot.anchor_before(start);
15070 let range = start..buffer_position;
15071 let lsp_start = to_lsp(&start);
15072 let lsp_range = lsp::Range {
15073 start: lsp_start,
15074 end: lsp_end,
15075 };
15076 Some(Completion {
15077 old_range: range,
15078 new_text: snippet.body.clone(),
15079 resolved: false,
15080 label: CodeLabel {
15081 text: matching_prefix.clone(),
15082 runs: vec![],
15083 filter_range: 0..matching_prefix.len(),
15084 },
15085 server_id: LanguageServerId(usize::MAX),
15086 documentation: snippet
15087 .description
15088 .clone()
15089 .map(CompletionDocumentation::SingleLine),
15090 lsp_completion: lsp::CompletionItem {
15091 label: snippet.prefix.first().unwrap().clone(),
15092 kind: Some(CompletionItemKind::SNIPPET),
15093 label_details: snippet.description.as_ref().map(|description| {
15094 lsp::CompletionItemLabelDetails {
15095 detail: Some(description.clone()),
15096 description: None,
15097 }
15098 }),
15099 insert_text_format: Some(InsertTextFormat::SNIPPET),
15100 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15101 lsp::InsertReplaceEdit {
15102 new_text: snippet.body.clone(),
15103 insert: lsp_range,
15104 replace: lsp_range,
15105 },
15106 )),
15107 filter_text: Some(snippet.body.clone()),
15108 sort_text: Some(char::MAX.to_string()),
15109 ..Default::default()
15110 },
15111 confirm: None,
15112 })
15113 })
15114 .collect();
15115
15116 Ok(result)
15117 })
15118}
15119
15120impl CompletionProvider for Entity<Project> {
15121 fn completions(
15122 &self,
15123 buffer: &Entity<Buffer>,
15124 buffer_position: text::Anchor,
15125 options: CompletionContext,
15126 _window: &mut Window,
15127 cx: &mut Context<Editor>,
15128 ) -> Task<Result<Vec<Completion>>> {
15129 self.update(cx, |project, cx| {
15130 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15131 let project_completions = project.completions(buffer, buffer_position, options, cx);
15132 cx.background_executor().spawn(async move {
15133 let mut completions = project_completions.await?;
15134 let snippets_completions = snippets.await?;
15135 completions.extend(snippets_completions);
15136 Ok(completions)
15137 })
15138 })
15139 }
15140
15141 fn resolve_completions(
15142 &self,
15143 buffer: Entity<Buffer>,
15144 completion_indices: Vec<usize>,
15145 completions: Rc<RefCell<Box<[Completion]>>>,
15146 cx: &mut Context<Editor>,
15147 ) -> Task<Result<bool>> {
15148 self.update(cx, |project, cx| {
15149 project.lsp_store().update(cx, |lsp_store, cx| {
15150 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15151 })
15152 })
15153 }
15154
15155 fn apply_additional_edits_for_completion(
15156 &self,
15157 buffer: Entity<Buffer>,
15158 completions: Rc<RefCell<Box<[Completion]>>>,
15159 completion_index: usize,
15160 push_to_history: bool,
15161 cx: &mut Context<Editor>,
15162 ) -> Task<Result<Option<language::Transaction>>> {
15163 self.update(cx, |project, cx| {
15164 project.lsp_store().update(cx, |lsp_store, cx| {
15165 lsp_store.apply_additional_edits_for_completion(
15166 buffer,
15167 completions,
15168 completion_index,
15169 push_to_history,
15170 cx,
15171 )
15172 })
15173 })
15174 }
15175
15176 fn is_completion_trigger(
15177 &self,
15178 buffer: &Entity<Buffer>,
15179 position: language::Anchor,
15180 text: &str,
15181 trigger_in_words: bool,
15182 cx: &mut Context<Editor>,
15183 ) -> bool {
15184 let mut chars = text.chars();
15185 let char = if let Some(char) = chars.next() {
15186 char
15187 } else {
15188 return false;
15189 };
15190 if chars.next().is_some() {
15191 return false;
15192 }
15193
15194 let buffer = buffer.read(cx);
15195 let snapshot = buffer.snapshot();
15196 if !snapshot.settings_at(position, cx).show_completions_on_input {
15197 return false;
15198 }
15199 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15200 if trigger_in_words && classifier.is_word(char) {
15201 return true;
15202 }
15203
15204 buffer.completion_triggers().contains(text)
15205 }
15206}
15207
15208impl SemanticsProvider for Entity<Project> {
15209 fn hover(
15210 &self,
15211 buffer: &Entity<Buffer>,
15212 position: text::Anchor,
15213 cx: &mut App,
15214 ) -> Option<Task<Vec<project::Hover>>> {
15215 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15216 }
15217
15218 fn document_highlights(
15219 &self,
15220 buffer: &Entity<Buffer>,
15221 position: text::Anchor,
15222 cx: &mut App,
15223 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15224 Some(self.update(cx, |project, cx| {
15225 project.document_highlights(buffer, position, cx)
15226 }))
15227 }
15228
15229 fn definitions(
15230 &self,
15231 buffer: &Entity<Buffer>,
15232 position: text::Anchor,
15233 kind: GotoDefinitionKind,
15234 cx: &mut App,
15235 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15236 Some(self.update(cx, |project, cx| match kind {
15237 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15238 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15239 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15240 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15241 }))
15242 }
15243
15244 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15245 // TODO: make this work for remote projects
15246 self.read(cx)
15247 .language_servers_for_local_buffer(buffer.read(cx), cx)
15248 .any(
15249 |(_, server)| match server.capabilities().inlay_hint_provider {
15250 Some(lsp::OneOf::Left(enabled)) => enabled,
15251 Some(lsp::OneOf::Right(_)) => true,
15252 None => false,
15253 },
15254 )
15255 }
15256
15257 fn inlay_hints(
15258 &self,
15259 buffer_handle: Entity<Buffer>,
15260 range: Range<text::Anchor>,
15261 cx: &mut App,
15262 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15263 Some(self.update(cx, |project, cx| {
15264 project.inlay_hints(buffer_handle, range, cx)
15265 }))
15266 }
15267
15268 fn resolve_inlay_hint(
15269 &self,
15270 hint: InlayHint,
15271 buffer_handle: Entity<Buffer>,
15272 server_id: LanguageServerId,
15273 cx: &mut App,
15274 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15275 Some(self.update(cx, |project, cx| {
15276 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15277 }))
15278 }
15279
15280 fn range_for_rename(
15281 &self,
15282 buffer: &Entity<Buffer>,
15283 position: text::Anchor,
15284 cx: &mut App,
15285 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15286 Some(self.update(cx, |project, cx| {
15287 let buffer = buffer.clone();
15288 let task = project.prepare_rename(buffer.clone(), position, cx);
15289 cx.spawn(|_, mut cx| async move {
15290 Ok(match task.await? {
15291 PrepareRenameResponse::Success(range) => Some(range),
15292 PrepareRenameResponse::InvalidPosition => None,
15293 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15294 // Fallback on using TreeSitter info to determine identifier range
15295 buffer.update(&mut cx, |buffer, _| {
15296 let snapshot = buffer.snapshot();
15297 let (range, kind) = snapshot.surrounding_word(position);
15298 if kind != Some(CharKind::Word) {
15299 return None;
15300 }
15301 Some(
15302 snapshot.anchor_before(range.start)
15303 ..snapshot.anchor_after(range.end),
15304 )
15305 })?
15306 }
15307 })
15308 })
15309 }))
15310 }
15311
15312 fn perform_rename(
15313 &self,
15314 buffer: &Entity<Buffer>,
15315 position: text::Anchor,
15316 new_name: String,
15317 cx: &mut App,
15318 ) -> Option<Task<Result<ProjectTransaction>>> {
15319 Some(self.update(cx, |project, cx| {
15320 project.perform_rename(buffer.clone(), position, new_name, cx)
15321 }))
15322 }
15323}
15324
15325fn inlay_hint_settings(
15326 location: Anchor,
15327 snapshot: &MultiBufferSnapshot,
15328 cx: &mut Context<Editor>,
15329) -> InlayHintSettings {
15330 let file = snapshot.file_at(location);
15331 let language = snapshot.language_at(location).map(|l| l.name());
15332 language_settings(language, file, cx).inlay_hints
15333}
15334
15335fn consume_contiguous_rows(
15336 contiguous_row_selections: &mut Vec<Selection<Point>>,
15337 selection: &Selection<Point>,
15338 display_map: &DisplaySnapshot,
15339 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15340) -> (MultiBufferRow, MultiBufferRow) {
15341 contiguous_row_selections.push(selection.clone());
15342 let start_row = MultiBufferRow(selection.start.row);
15343 let mut end_row = ending_row(selection, display_map);
15344
15345 while let Some(next_selection) = selections.peek() {
15346 if next_selection.start.row <= end_row.0 {
15347 end_row = ending_row(next_selection, display_map);
15348 contiguous_row_selections.push(selections.next().unwrap().clone());
15349 } else {
15350 break;
15351 }
15352 }
15353 (start_row, end_row)
15354}
15355
15356fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15357 if next_selection.end.column > 0 || next_selection.is_empty() {
15358 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15359 } else {
15360 MultiBufferRow(next_selection.end.row)
15361 }
15362}
15363
15364impl EditorSnapshot {
15365 pub fn remote_selections_in_range<'a>(
15366 &'a self,
15367 range: &'a Range<Anchor>,
15368 collaboration_hub: &dyn CollaborationHub,
15369 cx: &'a App,
15370 ) -> impl 'a + Iterator<Item = RemoteSelection> {
15371 let participant_names = collaboration_hub.user_names(cx);
15372 let participant_indices = collaboration_hub.user_participant_indices(cx);
15373 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15374 let collaborators_by_replica_id = collaborators_by_peer_id
15375 .iter()
15376 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15377 .collect::<HashMap<_, _>>();
15378 self.buffer_snapshot
15379 .selections_in_range(range, false)
15380 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15381 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15382 let participant_index = participant_indices.get(&collaborator.user_id).copied();
15383 let user_name = participant_names.get(&collaborator.user_id).cloned();
15384 Some(RemoteSelection {
15385 replica_id,
15386 selection,
15387 cursor_shape,
15388 line_mode,
15389 participant_index,
15390 peer_id: collaborator.peer_id,
15391 user_name,
15392 })
15393 })
15394 }
15395
15396 pub fn hunks_for_ranges(
15397 &self,
15398 ranges: impl Iterator<Item = Range<Point>>,
15399 ) -> Vec<MultiBufferDiffHunk> {
15400 let mut hunks = Vec::new();
15401 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15402 HashMap::default();
15403 for query_range in ranges {
15404 let query_rows =
15405 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15406 for hunk in self.buffer_snapshot.diff_hunks_in_range(
15407 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15408 ) {
15409 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15410 // when the caret is just above or just below the deleted hunk.
15411 let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15412 let related_to_selection = if allow_adjacent {
15413 hunk.row_range.overlaps(&query_rows)
15414 || hunk.row_range.start == query_rows.end
15415 || hunk.row_range.end == query_rows.start
15416 } else {
15417 hunk.row_range.overlaps(&query_rows)
15418 };
15419 if related_to_selection {
15420 if !processed_buffer_rows
15421 .entry(hunk.buffer_id)
15422 .or_default()
15423 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15424 {
15425 continue;
15426 }
15427 hunks.push(hunk);
15428 }
15429 }
15430 }
15431
15432 hunks
15433 }
15434
15435 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15436 self.display_snapshot.buffer_snapshot.language_at(position)
15437 }
15438
15439 pub fn is_focused(&self) -> bool {
15440 self.is_focused
15441 }
15442
15443 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15444 self.placeholder_text.as_ref()
15445 }
15446
15447 pub fn scroll_position(&self) -> gpui::Point<f32> {
15448 self.scroll_anchor.scroll_position(&self.display_snapshot)
15449 }
15450
15451 fn gutter_dimensions(
15452 &self,
15453 font_id: FontId,
15454 font_size: Pixels,
15455 max_line_number_width: Pixels,
15456 cx: &App,
15457 ) -> Option<GutterDimensions> {
15458 if !self.show_gutter {
15459 return None;
15460 }
15461
15462 let descent = cx.text_system().descent(font_id, font_size);
15463 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15464 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15465
15466 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15467 matches!(
15468 ProjectSettings::get_global(cx).git.git_gutter,
15469 Some(GitGutterSetting::TrackedFiles)
15470 )
15471 });
15472 let gutter_settings = EditorSettings::get_global(cx).gutter;
15473 let show_line_numbers = self
15474 .show_line_numbers
15475 .unwrap_or(gutter_settings.line_numbers);
15476 let line_gutter_width = if show_line_numbers {
15477 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15478 let min_width_for_number_on_gutter = em_advance * 4.0;
15479 max_line_number_width.max(min_width_for_number_on_gutter)
15480 } else {
15481 0.0.into()
15482 };
15483
15484 let show_code_actions = self
15485 .show_code_actions
15486 .unwrap_or(gutter_settings.code_actions);
15487
15488 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15489
15490 let git_blame_entries_width =
15491 self.git_blame_gutter_max_author_length
15492 .map(|max_author_length| {
15493 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15494
15495 /// The number of characters to dedicate to gaps and margins.
15496 const SPACING_WIDTH: usize = 4;
15497
15498 let max_char_count = max_author_length
15499 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15500 + ::git::SHORT_SHA_LENGTH
15501 + MAX_RELATIVE_TIMESTAMP.len()
15502 + SPACING_WIDTH;
15503
15504 em_advance * max_char_count
15505 });
15506
15507 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15508 left_padding += if show_code_actions || show_runnables {
15509 em_width * 3.0
15510 } else if show_git_gutter && show_line_numbers {
15511 em_width * 2.0
15512 } else if show_git_gutter || show_line_numbers {
15513 em_width
15514 } else {
15515 px(0.)
15516 };
15517
15518 let right_padding = if gutter_settings.folds && show_line_numbers {
15519 em_width * 4.0
15520 } else if gutter_settings.folds {
15521 em_width * 3.0
15522 } else if show_line_numbers {
15523 em_width
15524 } else {
15525 px(0.)
15526 };
15527
15528 Some(GutterDimensions {
15529 left_padding,
15530 right_padding,
15531 width: line_gutter_width + left_padding + right_padding,
15532 margin: -descent,
15533 git_blame_entries_width,
15534 })
15535 }
15536
15537 pub fn render_crease_toggle(
15538 &self,
15539 buffer_row: MultiBufferRow,
15540 row_contains_cursor: bool,
15541 editor: Entity<Editor>,
15542 window: &mut Window,
15543 cx: &mut App,
15544 ) -> Option<AnyElement> {
15545 let folded = self.is_line_folded(buffer_row);
15546 let mut is_foldable = false;
15547
15548 if let Some(crease) = self
15549 .crease_snapshot
15550 .query_row(buffer_row, &self.buffer_snapshot)
15551 {
15552 is_foldable = true;
15553 match crease {
15554 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15555 if let Some(render_toggle) = render_toggle {
15556 let toggle_callback =
15557 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15558 if folded {
15559 editor.update(cx, |editor, cx| {
15560 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15561 });
15562 } else {
15563 editor.update(cx, |editor, cx| {
15564 editor.unfold_at(
15565 &crate::UnfoldAt { buffer_row },
15566 window,
15567 cx,
15568 )
15569 });
15570 }
15571 });
15572 return Some((render_toggle)(
15573 buffer_row,
15574 folded,
15575 toggle_callback,
15576 window,
15577 cx,
15578 ));
15579 }
15580 }
15581 }
15582 }
15583
15584 is_foldable |= self.starts_indent(buffer_row);
15585
15586 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15587 Some(
15588 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15589 .toggle_state(folded)
15590 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15591 if folded {
15592 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15593 } else {
15594 this.fold_at(&FoldAt { buffer_row }, window, cx);
15595 }
15596 }))
15597 .into_any_element(),
15598 )
15599 } else {
15600 None
15601 }
15602 }
15603
15604 pub fn render_crease_trailer(
15605 &self,
15606 buffer_row: MultiBufferRow,
15607 window: &mut Window,
15608 cx: &mut App,
15609 ) -> Option<AnyElement> {
15610 let folded = self.is_line_folded(buffer_row);
15611 if let Crease::Inline { render_trailer, .. } = self
15612 .crease_snapshot
15613 .query_row(buffer_row, &self.buffer_snapshot)?
15614 {
15615 let render_trailer = render_trailer.as_ref()?;
15616 Some(render_trailer(buffer_row, folded, window, cx))
15617 } else {
15618 None
15619 }
15620 }
15621}
15622
15623impl Deref for EditorSnapshot {
15624 type Target = DisplaySnapshot;
15625
15626 fn deref(&self) -> &Self::Target {
15627 &self.display_snapshot
15628 }
15629}
15630
15631#[derive(Clone, Debug, PartialEq, Eq)]
15632pub enum EditorEvent {
15633 InputIgnored {
15634 text: Arc<str>,
15635 },
15636 InputHandled {
15637 utf16_range_to_replace: Option<Range<isize>>,
15638 text: Arc<str>,
15639 },
15640 ExcerptsAdded {
15641 buffer: Entity<Buffer>,
15642 predecessor: ExcerptId,
15643 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15644 },
15645 ExcerptsRemoved {
15646 ids: Vec<ExcerptId>,
15647 },
15648 BufferFoldToggled {
15649 ids: Vec<ExcerptId>,
15650 folded: bool,
15651 },
15652 ExcerptsEdited {
15653 ids: Vec<ExcerptId>,
15654 },
15655 ExcerptsExpanded {
15656 ids: Vec<ExcerptId>,
15657 },
15658 BufferEdited,
15659 Edited {
15660 transaction_id: clock::Lamport,
15661 },
15662 Reparsed(BufferId),
15663 Focused,
15664 FocusedIn,
15665 Blurred,
15666 DirtyChanged,
15667 Saved,
15668 TitleChanged,
15669 DiffBaseChanged,
15670 SelectionsChanged {
15671 local: bool,
15672 },
15673 ScrollPositionChanged {
15674 local: bool,
15675 autoscroll: bool,
15676 },
15677 Closed,
15678 TransactionUndone {
15679 transaction_id: clock::Lamport,
15680 },
15681 TransactionBegun {
15682 transaction_id: clock::Lamport,
15683 },
15684 Reloaded,
15685 CursorShapeChanged,
15686}
15687
15688impl EventEmitter<EditorEvent> for Editor {}
15689
15690impl Focusable for Editor {
15691 fn focus_handle(&self, _cx: &App) -> FocusHandle {
15692 self.focus_handle.clone()
15693 }
15694}
15695
15696impl Render for Editor {
15697 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15698 let settings = ThemeSettings::get_global(cx);
15699
15700 let mut text_style = match self.mode {
15701 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15702 color: cx.theme().colors().editor_foreground,
15703 font_family: settings.ui_font.family.clone(),
15704 font_features: settings.ui_font.features.clone(),
15705 font_fallbacks: settings.ui_font.fallbacks.clone(),
15706 font_size: rems(0.875).into(),
15707 font_weight: settings.ui_font.weight,
15708 line_height: relative(settings.buffer_line_height.value()),
15709 ..Default::default()
15710 },
15711 EditorMode::Full => TextStyle {
15712 color: cx.theme().colors().editor_foreground,
15713 font_family: settings.buffer_font.family.clone(),
15714 font_features: settings.buffer_font.features.clone(),
15715 font_fallbacks: settings.buffer_font.fallbacks.clone(),
15716 font_size: settings.buffer_font_size().into(),
15717 font_weight: settings.buffer_font.weight,
15718 line_height: relative(settings.buffer_line_height.value()),
15719 ..Default::default()
15720 },
15721 };
15722 if let Some(text_style_refinement) = &self.text_style_refinement {
15723 text_style.refine(text_style_refinement)
15724 }
15725
15726 let background = match self.mode {
15727 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15728 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15729 EditorMode::Full => cx.theme().colors().editor_background,
15730 };
15731
15732 EditorElement::new(
15733 &cx.entity(),
15734 EditorStyle {
15735 background,
15736 local_player: cx.theme().players().local(),
15737 text: text_style,
15738 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15739 syntax: cx.theme().syntax().clone(),
15740 status: cx.theme().status().clone(),
15741 inlay_hints_style: make_inlay_hints_style(cx),
15742 inline_completion_styles: make_suggestion_styles(cx),
15743 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15744 },
15745 )
15746 }
15747}
15748
15749impl EntityInputHandler for Editor {
15750 fn text_for_range(
15751 &mut self,
15752 range_utf16: Range<usize>,
15753 adjusted_range: &mut Option<Range<usize>>,
15754 _: &mut Window,
15755 cx: &mut Context<Self>,
15756 ) -> Option<String> {
15757 let snapshot = self.buffer.read(cx).read(cx);
15758 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15759 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15760 if (start.0..end.0) != range_utf16 {
15761 adjusted_range.replace(start.0..end.0);
15762 }
15763 Some(snapshot.text_for_range(start..end).collect())
15764 }
15765
15766 fn selected_text_range(
15767 &mut self,
15768 ignore_disabled_input: bool,
15769 _: &mut Window,
15770 cx: &mut Context<Self>,
15771 ) -> Option<UTF16Selection> {
15772 // Prevent the IME menu from appearing when holding down an alphabetic key
15773 // while input is disabled.
15774 if !ignore_disabled_input && !self.input_enabled {
15775 return None;
15776 }
15777
15778 let selection = self.selections.newest::<OffsetUtf16>(cx);
15779 let range = selection.range();
15780
15781 Some(UTF16Selection {
15782 range: range.start.0..range.end.0,
15783 reversed: selection.reversed,
15784 })
15785 }
15786
15787 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15788 let snapshot = self.buffer.read(cx).read(cx);
15789 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15790 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15791 }
15792
15793 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15794 self.clear_highlights::<InputComposition>(cx);
15795 self.ime_transaction.take();
15796 }
15797
15798 fn replace_text_in_range(
15799 &mut self,
15800 range_utf16: Option<Range<usize>>,
15801 text: &str,
15802 window: &mut Window,
15803 cx: &mut Context<Self>,
15804 ) {
15805 if !self.input_enabled {
15806 cx.emit(EditorEvent::InputIgnored { text: text.into() });
15807 return;
15808 }
15809
15810 self.transact(window, cx, |this, window, cx| {
15811 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15812 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15813 Some(this.selection_replacement_ranges(range_utf16, cx))
15814 } else {
15815 this.marked_text_ranges(cx)
15816 };
15817
15818 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15819 let newest_selection_id = this.selections.newest_anchor().id;
15820 this.selections
15821 .all::<OffsetUtf16>(cx)
15822 .iter()
15823 .zip(ranges_to_replace.iter())
15824 .find_map(|(selection, range)| {
15825 if selection.id == newest_selection_id {
15826 Some(
15827 (range.start.0 as isize - selection.head().0 as isize)
15828 ..(range.end.0 as isize - selection.head().0 as isize),
15829 )
15830 } else {
15831 None
15832 }
15833 })
15834 });
15835
15836 cx.emit(EditorEvent::InputHandled {
15837 utf16_range_to_replace: range_to_replace,
15838 text: text.into(),
15839 });
15840
15841 if let Some(new_selected_ranges) = new_selected_ranges {
15842 this.change_selections(None, window, cx, |selections| {
15843 selections.select_ranges(new_selected_ranges)
15844 });
15845 this.backspace(&Default::default(), window, cx);
15846 }
15847
15848 this.handle_input(text, window, cx);
15849 });
15850
15851 if let Some(transaction) = self.ime_transaction {
15852 self.buffer.update(cx, |buffer, cx| {
15853 buffer.group_until_transaction(transaction, cx);
15854 });
15855 }
15856
15857 self.unmark_text(window, cx);
15858 }
15859
15860 fn replace_and_mark_text_in_range(
15861 &mut self,
15862 range_utf16: Option<Range<usize>>,
15863 text: &str,
15864 new_selected_range_utf16: Option<Range<usize>>,
15865 window: &mut Window,
15866 cx: &mut Context<Self>,
15867 ) {
15868 if !self.input_enabled {
15869 return;
15870 }
15871
15872 let transaction = self.transact(window, cx, |this, window, cx| {
15873 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15874 let snapshot = this.buffer.read(cx).read(cx);
15875 if let Some(relative_range_utf16) = range_utf16.as_ref() {
15876 for marked_range in &mut marked_ranges {
15877 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15878 marked_range.start.0 += relative_range_utf16.start;
15879 marked_range.start =
15880 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15881 marked_range.end =
15882 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15883 }
15884 }
15885 Some(marked_ranges)
15886 } else if let Some(range_utf16) = range_utf16 {
15887 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15888 Some(this.selection_replacement_ranges(range_utf16, cx))
15889 } else {
15890 None
15891 };
15892
15893 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
15894 let newest_selection_id = this.selections.newest_anchor().id;
15895 this.selections
15896 .all::<OffsetUtf16>(cx)
15897 .iter()
15898 .zip(ranges_to_replace.iter())
15899 .find_map(|(selection, range)| {
15900 if selection.id == newest_selection_id {
15901 Some(
15902 (range.start.0 as isize - selection.head().0 as isize)
15903 ..(range.end.0 as isize - selection.head().0 as isize),
15904 )
15905 } else {
15906 None
15907 }
15908 })
15909 });
15910
15911 cx.emit(EditorEvent::InputHandled {
15912 utf16_range_to_replace: range_to_replace,
15913 text: text.into(),
15914 });
15915
15916 if let Some(ranges) = ranges_to_replace {
15917 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
15918 }
15919
15920 let marked_ranges = {
15921 let snapshot = this.buffer.read(cx).read(cx);
15922 this.selections
15923 .disjoint_anchors()
15924 .iter()
15925 .map(|selection| {
15926 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
15927 })
15928 .collect::<Vec<_>>()
15929 };
15930
15931 if text.is_empty() {
15932 this.unmark_text(window, cx);
15933 } else {
15934 this.highlight_text::<InputComposition>(
15935 marked_ranges.clone(),
15936 HighlightStyle {
15937 underline: Some(UnderlineStyle {
15938 thickness: px(1.),
15939 color: None,
15940 wavy: false,
15941 }),
15942 ..Default::default()
15943 },
15944 cx,
15945 );
15946 }
15947
15948 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
15949 let use_autoclose = this.use_autoclose;
15950 let use_auto_surround = this.use_auto_surround;
15951 this.set_use_autoclose(false);
15952 this.set_use_auto_surround(false);
15953 this.handle_input(text, window, cx);
15954 this.set_use_autoclose(use_autoclose);
15955 this.set_use_auto_surround(use_auto_surround);
15956
15957 if let Some(new_selected_range) = new_selected_range_utf16 {
15958 let snapshot = this.buffer.read(cx).read(cx);
15959 let new_selected_ranges = marked_ranges
15960 .into_iter()
15961 .map(|marked_range| {
15962 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
15963 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
15964 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
15965 snapshot.clip_offset_utf16(new_start, Bias::Left)
15966 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
15967 })
15968 .collect::<Vec<_>>();
15969
15970 drop(snapshot);
15971 this.change_selections(None, window, cx, |selections| {
15972 selections.select_ranges(new_selected_ranges)
15973 });
15974 }
15975 });
15976
15977 self.ime_transaction = self.ime_transaction.or(transaction);
15978 if let Some(transaction) = self.ime_transaction {
15979 self.buffer.update(cx, |buffer, cx| {
15980 buffer.group_until_transaction(transaction, cx);
15981 });
15982 }
15983
15984 if self.text_highlights::<InputComposition>(cx).is_none() {
15985 self.ime_transaction.take();
15986 }
15987 }
15988
15989 fn bounds_for_range(
15990 &mut self,
15991 range_utf16: Range<usize>,
15992 element_bounds: gpui::Bounds<Pixels>,
15993 window: &mut Window,
15994 cx: &mut Context<Self>,
15995 ) -> Option<gpui::Bounds<Pixels>> {
15996 let text_layout_details = self.text_layout_details(window);
15997 let gpui::Size {
15998 width: em_width,
15999 height: line_height,
16000 } = self.character_size(window);
16001
16002 let snapshot = self.snapshot(window, cx);
16003 let scroll_position = snapshot.scroll_position();
16004 let scroll_left = scroll_position.x * em_width;
16005
16006 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16007 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16008 + self.gutter_dimensions.width
16009 + self.gutter_dimensions.margin;
16010 let y = line_height * (start.row().as_f32() - scroll_position.y);
16011
16012 Some(Bounds {
16013 origin: element_bounds.origin + point(x, y),
16014 size: size(em_width, line_height),
16015 })
16016 }
16017
16018 fn character_index_for_point(
16019 &mut self,
16020 point: gpui::Point<Pixels>,
16021 _window: &mut Window,
16022 _cx: &mut Context<Self>,
16023 ) -> Option<usize> {
16024 let position_map = self.last_position_map.as_ref()?;
16025 if !position_map.text_hitbox.contains(&point) {
16026 return None;
16027 }
16028 let display_point = position_map.point_for_position(point).previous_valid;
16029 let anchor = position_map
16030 .snapshot
16031 .display_point_to_anchor(display_point, Bias::Left);
16032 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16033 Some(utf16_offset.0)
16034 }
16035}
16036
16037trait SelectionExt {
16038 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16039 fn spanned_rows(
16040 &self,
16041 include_end_if_at_line_start: bool,
16042 map: &DisplaySnapshot,
16043 ) -> Range<MultiBufferRow>;
16044}
16045
16046impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16047 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16048 let start = self
16049 .start
16050 .to_point(&map.buffer_snapshot)
16051 .to_display_point(map);
16052 let end = self
16053 .end
16054 .to_point(&map.buffer_snapshot)
16055 .to_display_point(map);
16056 if self.reversed {
16057 end..start
16058 } else {
16059 start..end
16060 }
16061 }
16062
16063 fn spanned_rows(
16064 &self,
16065 include_end_if_at_line_start: bool,
16066 map: &DisplaySnapshot,
16067 ) -> Range<MultiBufferRow> {
16068 let start = self.start.to_point(&map.buffer_snapshot);
16069 let mut end = self.end.to_point(&map.buffer_snapshot);
16070 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16071 end.row -= 1;
16072 }
16073
16074 let buffer_start = map.prev_line_boundary(start).0;
16075 let buffer_end = map.next_line_boundary(end).0;
16076 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16077 }
16078}
16079
16080impl<T: InvalidationRegion> InvalidationStack<T> {
16081 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16082 where
16083 S: Clone + ToOffset,
16084 {
16085 while let Some(region) = self.last() {
16086 let all_selections_inside_invalidation_ranges =
16087 if selections.len() == region.ranges().len() {
16088 selections
16089 .iter()
16090 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16091 .all(|(selection, invalidation_range)| {
16092 let head = selection.head().to_offset(buffer);
16093 invalidation_range.start <= head && invalidation_range.end >= head
16094 })
16095 } else {
16096 false
16097 };
16098
16099 if all_selections_inside_invalidation_ranges {
16100 break;
16101 } else {
16102 self.pop();
16103 }
16104 }
16105 }
16106}
16107
16108impl<T> Default for InvalidationStack<T> {
16109 fn default() -> Self {
16110 Self(Default::default())
16111 }
16112}
16113
16114impl<T> Deref for InvalidationStack<T> {
16115 type Target = Vec<T>;
16116
16117 fn deref(&self) -> &Self::Target {
16118 &self.0
16119 }
16120}
16121
16122impl<T> DerefMut for InvalidationStack<T> {
16123 fn deref_mut(&mut self) -> &mut Self::Target {
16124 &mut self.0
16125 }
16126}
16127
16128impl InvalidationRegion for SnippetState {
16129 fn ranges(&self) -> &[Range<Anchor>] {
16130 &self.ranges[self.active_index]
16131 }
16132}
16133
16134pub fn diagnostic_block_renderer(
16135 diagnostic: Diagnostic,
16136 max_message_rows: Option<u8>,
16137 allow_closing: bool,
16138 _is_valid: bool,
16139) -> RenderBlock {
16140 let (text_without_backticks, code_ranges) =
16141 highlight_diagnostic_message(&diagnostic, max_message_rows);
16142
16143 Arc::new(move |cx: &mut BlockContext| {
16144 let group_id: SharedString = cx.block_id.to_string().into();
16145
16146 let mut text_style = cx.window.text_style().clone();
16147 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16148 let theme_settings = ThemeSettings::get_global(cx);
16149 text_style.font_family = theme_settings.buffer_font.family.clone();
16150 text_style.font_style = theme_settings.buffer_font.style;
16151 text_style.font_features = theme_settings.buffer_font.features.clone();
16152 text_style.font_weight = theme_settings.buffer_font.weight;
16153
16154 let multi_line_diagnostic = diagnostic.message.contains('\n');
16155
16156 let buttons = |diagnostic: &Diagnostic| {
16157 if multi_line_diagnostic {
16158 v_flex()
16159 } else {
16160 h_flex()
16161 }
16162 .when(allow_closing, |div| {
16163 div.children(diagnostic.is_primary.then(|| {
16164 IconButton::new("close-block", IconName::XCircle)
16165 .icon_color(Color::Muted)
16166 .size(ButtonSize::Compact)
16167 .style(ButtonStyle::Transparent)
16168 .visible_on_hover(group_id.clone())
16169 .on_click(move |_click, window, cx| {
16170 window.dispatch_action(Box::new(Cancel), cx)
16171 })
16172 .tooltip(|window, cx| {
16173 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16174 })
16175 }))
16176 })
16177 .child(
16178 IconButton::new("copy-block", IconName::Copy)
16179 .icon_color(Color::Muted)
16180 .size(ButtonSize::Compact)
16181 .style(ButtonStyle::Transparent)
16182 .visible_on_hover(group_id.clone())
16183 .on_click({
16184 let message = diagnostic.message.clone();
16185 move |_click, _, cx| {
16186 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16187 }
16188 })
16189 .tooltip(Tooltip::text("Copy diagnostic message")),
16190 )
16191 };
16192
16193 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16194 AvailableSpace::min_size(),
16195 cx.window,
16196 cx.app,
16197 );
16198
16199 h_flex()
16200 .id(cx.block_id)
16201 .group(group_id.clone())
16202 .relative()
16203 .size_full()
16204 .block_mouse_down()
16205 .pl(cx.gutter_dimensions.width)
16206 .w(cx.max_width - cx.gutter_dimensions.full_width())
16207 .child(
16208 div()
16209 .flex()
16210 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16211 .flex_shrink(),
16212 )
16213 .child(buttons(&diagnostic))
16214 .child(div().flex().flex_shrink_0().child(
16215 StyledText::new(text_without_backticks.clone()).with_highlights(
16216 &text_style,
16217 code_ranges.iter().map(|range| {
16218 (
16219 range.clone(),
16220 HighlightStyle {
16221 font_weight: Some(FontWeight::BOLD),
16222 ..Default::default()
16223 },
16224 )
16225 }),
16226 ),
16227 ))
16228 .into_any_element()
16229 })
16230}
16231
16232fn inline_completion_edit_text(
16233 current_snapshot: &BufferSnapshot,
16234 edits: &[(Range<Anchor>, String)],
16235 edit_preview: &EditPreview,
16236 include_deletions: bool,
16237 cx: &App,
16238) -> HighlightedText {
16239 let edits = edits
16240 .iter()
16241 .map(|(anchor, text)| {
16242 (
16243 anchor.start.text_anchor..anchor.end.text_anchor,
16244 text.clone(),
16245 )
16246 })
16247 .collect::<Vec<_>>();
16248
16249 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16250}
16251
16252pub fn highlight_diagnostic_message(
16253 diagnostic: &Diagnostic,
16254 mut max_message_rows: Option<u8>,
16255) -> (SharedString, Vec<Range<usize>>) {
16256 let mut text_without_backticks = String::new();
16257 let mut code_ranges = Vec::new();
16258
16259 if let Some(source) = &diagnostic.source {
16260 text_without_backticks.push_str(source);
16261 code_ranges.push(0..source.len());
16262 text_without_backticks.push_str(": ");
16263 }
16264
16265 let mut prev_offset = 0;
16266 let mut in_code_block = false;
16267 let has_row_limit = max_message_rows.is_some();
16268 let mut newline_indices = diagnostic
16269 .message
16270 .match_indices('\n')
16271 .filter(|_| has_row_limit)
16272 .map(|(ix, _)| ix)
16273 .fuse()
16274 .peekable();
16275
16276 for (quote_ix, _) in diagnostic
16277 .message
16278 .match_indices('`')
16279 .chain([(diagnostic.message.len(), "")])
16280 {
16281 let mut first_newline_ix = None;
16282 let mut last_newline_ix = None;
16283 while let Some(newline_ix) = newline_indices.peek() {
16284 if *newline_ix < quote_ix {
16285 if first_newline_ix.is_none() {
16286 first_newline_ix = Some(*newline_ix);
16287 }
16288 last_newline_ix = Some(*newline_ix);
16289
16290 if let Some(rows_left) = &mut max_message_rows {
16291 if *rows_left == 0 {
16292 break;
16293 } else {
16294 *rows_left -= 1;
16295 }
16296 }
16297 let _ = newline_indices.next();
16298 } else {
16299 break;
16300 }
16301 }
16302 let prev_len = text_without_backticks.len();
16303 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16304 text_without_backticks.push_str(new_text);
16305 if in_code_block {
16306 code_ranges.push(prev_len..text_without_backticks.len());
16307 }
16308 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16309 in_code_block = !in_code_block;
16310 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16311 text_without_backticks.push_str("...");
16312 break;
16313 }
16314 }
16315
16316 (text_without_backticks.into(), code_ranges)
16317}
16318
16319fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16320 match severity {
16321 DiagnosticSeverity::ERROR => colors.error,
16322 DiagnosticSeverity::WARNING => colors.warning,
16323 DiagnosticSeverity::INFORMATION => colors.info,
16324 DiagnosticSeverity::HINT => colors.info,
16325 _ => colors.ignored,
16326 }
16327}
16328
16329pub fn styled_runs_for_code_label<'a>(
16330 label: &'a CodeLabel,
16331 syntax_theme: &'a theme::SyntaxTheme,
16332) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16333 let fade_out = HighlightStyle {
16334 fade_out: Some(0.35),
16335 ..Default::default()
16336 };
16337
16338 let mut prev_end = label.filter_range.end;
16339 label
16340 .runs
16341 .iter()
16342 .enumerate()
16343 .flat_map(move |(ix, (range, highlight_id))| {
16344 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16345 style
16346 } else {
16347 return Default::default();
16348 };
16349 let mut muted_style = style;
16350 muted_style.highlight(fade_out);
16351
16352 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16353 if range.start >= label.filter_range.end {
16354 if range.start > prev_end {
16355 runs.push((prev_end..range.start, fade_out));
16356 }
16357 runs.push((range.clone(), muted_style));
16358 } else if range.end <= label.filter_range.end {
16359 runs.push((range.clone(), style));
16360 } else {
16361 runs.push((range.start..label.filter_range.end, style));
16362 runs.push((label.filter_range.end..range.end, muted_style));
16363 }
16364 prev_end = cmp::max(prev_end, range.end);
16365
16366 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16367 runs.push((prev_end..label.text.len(), fade_out));
16368 }
16369
16370 runs
16371 })
16372}
16373
16374pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16375 let mut prev_index = 0;
16376 let mut prev_codepoint: Option<char> = None;
16377 text.char_indices()
16378 .chain([(text.len(), '\0')])
16379 .filter_map(move |(index, codepoint)| {
16380 let prev_codepoint = prev_codepoint.replace(codepoint)?;
16381 let is_boundary = index == text.len()
16382 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16383 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16384 if is_boundary {
16385 let chunk = &text[prev_index..index];
16386 prev_index = index;
16387 Some(chunk)
16388 } else {
16389 None
16390 }
16391 })
16392}
16393
16394pub trait RangeToAnchorExt: Sized {
16395 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16396
16397 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16398 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16399 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16400 }
16401}
16402
16403impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16404 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16405 let start_offset = self.start.to_offset(snapshot);
16406 let end_offset = self.end.to_offset(snapshot);
16407 if start_offset == end_offset {
16408 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16409 } else {
16410 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16411 }
16412 }
16413}
16414
16415pub trait RowExt {
16416 fn as_f32(&self) -> f32;
16417
16418 fn next_row(&self) -> Self;
16419
16420 fn previous_row(&self) -> Self;
16421
16422 fn minus(&self, other: Self) -> u32;
16423}
16424
16425impl RowExt for DisplayRow {
16426 fn as_f32(&self) -> f32 {
16427 self.0 as f32
16428 }
16429
16430 fn next_row(&self) -> Self {
16431 Self(self.0 + 1)
16432 }
16433
16434 fn previous_row(&self) -> Self {
16435 Self(self.0.saturating_sub(1))
16436 }
16437
16438 fn minus(&self, other: Self) -> u32 {
16439 self.0 - other.0
16440 }
16441}
16442
16443impl RowExt for MultiBufferRow {
16444 fn as_f32(&self) -> f32 {
16445 self.0 as f32
16446 }
16447
16448 fn next_row(&self) -> Self {
16449 Self(self.0 + 1)
16450 }
16451
16452 fn previous_row(&self) -> Self {
16453 Self(self.0.saturating_sub(1))
16454 }
16455
16456 fn minus(&self, other: Self) -> u32 {
16457 self.0 - other.0
16458 }
16459}
16460
16461trait RowRangeExt {
16462 type Row;
16463
16464 fn len(&self) -> usize;
16465
16466 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16467}
16468
16469impl RowRangeExt for Range<MultiBufferRow> {
16470 type Row = MultiBufferRow;
16471
16472 fn len(&self) -> usize {
16473 (self.end.0 - self.start.0) as usize
16474 }
16475
16476 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16477 (self.start.0..self.end.0).map(MultiBufferRow)
16478 }
16479}
16480
16481impl RowRangeExt for Range<DisplayRow> {
16482 type Row = DisplayRow;
16483
16484 fn len(&self) -> usize {
16485 (self.end.0 - self.start.0) as usize
16486 }
16487
16488 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16489 (self.start.0..self.end.0).map(DisplayRow)
16490 }
16491}
16492
16493/// If select range has more than one line, we
16494/// just point the cursor to range.start.
16495fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16496 if range.start.row == range.end.row {
16497 range
16498 } else {
16499 range.start..range.start
16500 }
16501}
16502pub struct KillRing(ClipboardItem);
16503impl Global for KillRing {}
16504
16505const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16506
16507fn all_edits_insertions_or_deletions(
16508 edits: &Vec<(Range<Anchor>, String)>,
16509 snapshot: &MultiBufferSnapshot,
16510) -> bool {
16511 let mut all_insertions = true;
16512 let mut all_deletions = true;
16513
16514 for (range, new_text) in edits.iter() {
16515 let range_is_empty = range.to_offset(&snapshot).is_empty();
16516 let text_is_empty = new_text.is_empty();
16517
16518 if range_is_empty != text_is_empty {
16519 if range_is_empty {
16520 all_deletions = false;
16521 } else {
16522 all_insertions = false;
16523 }
16524 } else {
16525 return false;
16526 }
16527
16528 if !all_insertions && !all_deletions {
16529 return false;
16530 }
16531 }
16532 all_insertions || all_deletions
16533}