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