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
50pub(crate) use actions::*;
51pub use actions::{OpenExcerpts, OpenExcerptsSplit};
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use client::{Collaborator, ParticipantIndex};
56use clock::ReplicaId;
57use collections::{BTreeMap, HashMap, HashSet, VecDeque};
58use convert_case::{Case, Casing};
59use display_map::*;
60pub use display_map::{DisplayPoint, FoldPlaceholder};
61pub use editor_settings::{
62 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
63};
64pub use editor_settings_controls::*;
65use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
66pub use element::{
67 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
68};
69use futures::{future, FutureExt};
70use fuzzy::StringMatchCandidate;
71
72use code_context_menus::{
73 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
74 CompletionsMenu, ContextMenuOrigin,
75};
76use diff::DiffHunkStatus;
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::{EditPredictionProvider, 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(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
194pub(crate) const EDIT_PREDICTION_REQUIRES_MODIFIER_KEY_CONTEXT: &str =
195 "edit_prediction_requires_modifier";
196
197pub fn render_parsed_markdown(
198 element_id: impl Into<ElementId>,
199 parsed: &language::ParsedMarkdown,
200 editor_style: &EditorStyle,
201 workspace: Option<WeakEntity<Workspace>>,
202 cx: &mut App,
203) -> InteractiveText {
204 let code_span_background_color = cx
205 .theme()
206 .colors()
207 .editor_document_highlight_read_background;
208
209 let highlights = gpui::combine_highlights(
210 parsed.highlights.iter().filter_map(|(range, highlight)| {
211 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
212 Some((range.clone(), highlight))
213 }),
214 parsed
215 .regions
216 .iter()
217 .zip(&parsed.region_ranges)
218 .filter_map(|(region, range)| {
219 if region.code {
220 Some((
221 range.clone(),
222 HighlightStyle {
223 background_color: Some(code_span_background_color),
224 ..Default::default()
225 },
226 ))
227 } else {
228 None
229 }
230 }),
231 );
232
233 let mut links = Vec::new();
234 let mut link_ranges = Vec::new();
235 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
236 if let Some(link) = region.link.clone() {
237 links.push(link);
238 link_ranges.push(range.clone());
239 }
240 }
241
242 InteractiveText::new(
243 element_id,
244 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
245 )
246 .on_click(
247 link_ranges,
248 move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
249 markdown::Link::Web { url } => cx.open_url(url),
250 markdown::Link::Path { path } => {
251 if let Some(workspace) = &workspace {
252 _ = workspace.update(cx, |workspace, cx| {
253 workspace
254 .open_abs_path(path.clone(), false, window, cx)
255 .detach();
256 });
257 }
258 }
259 },
260 )
261}
262
263#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
264pub enum InlayId {
265 InlineCompletion(usize),
266 Hint(usize),
267}
268
269impl InlayId {
270 fn id(&self) -> usize {
271 match self {
272 Self::InlineCompletion(id) => *id,
273 Self::Hint(id) => *id,
274 }
275 }
276}
277
278enum DocumentHighlightRead {}
279enum DocumentHighlightWrite {}
280enum InputComposition {}
281
282#[derive(Debug, Copy, Clone, PartialEq, Eq)]
283pub enum Navigated {
284 Yes,
285 No,
286}
287
288impl Navigated {
289 pub fn from_bool(yes: bool) -> Navigated {
290 if yes {
291 Navigated::Yes
292 } else {
293 Navigated::No
294 }
295 }
296}
297
298pub fn init_settings(cx: &mut App) {
299 EditorSettings::register(cx);
300}
301
302pub fn init(cx: &mut App) {
303 init_settings(cx);
304
305 workspace::register_project_item::<Editor>(cx);
306 workspace::FollowableViewRegistry::register::<Editor>(cx);
307 workspace::register_serializable_item::<Editor>(cx);
308
309 cx.observe_new(
310 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
311 workspace.register_action(Editor::new_file);
312 workspace.register_action(Editor::new_file_vertical);
313 workspace.register_action(Editor::new_file_horizontal);
314 workspace.register_action(Editor::cancel_language_server_work);
315 },
316 )
317 .detach();
318
319 cx.on_action(move |_: &workspace::NewFile, cx| {
320 let app_state = workspace::AppState::global(cx);
321 if let Some(app_state) = app_state.upgrade() {
322 workspace::open_new(
323 Default::default(),
324 app_state,
325 cx,
326 |workspace, window, cx| {
327 Editor::new_file(workspace, &Default::default(), window, cx)
328 },
329 )
330 .detach();
331 }
332 });
333 cx.on_action(move |_: &workspace::NewWindow, cx| {
334 let app_state = workspace::AppState::global(cx);
335 if let Some(app_state) = app_state.upgrade() {
336 workspace::open_new(
337 Default::default(),
338 app_state,
339 cx,
340 |workspace, window, cx| {
341 cx.activate(true);
342 Editor::new_file(workspace, &Default::default(), window, cx)
343 },
344 )
345 .detach();
346 }
347 });
348}
349
350pub struct SearchWithinRange;
351
352trait InvalidationRegion {
353 fn ranges(&self) -> &[Range<Anchor>];
354}
355
356#[derive(Clone, Debug, PartialEq)]
357pub enum SelectPhase {
358 Begin {
359 position: DisplayPoint,
360 add: bool,
361 click_count: usize,
362 },
363 BeginColumnar {
364 position: DisplayPoint,
365 reset: bool,
366 goal_column: u32,
367 },
368 Extend {
369 position: DisplayPoint,
370 click_count: usize,
371 },
372 Update {
373 position: DisplayPoint,
374 goal_column: u32,
375 scroll_delta: gpui::Point<f32>,
376 },
377 End,
378}
379
380#[derive(Clone, Debug)]
381pub enum SelectMode {
382 Character,
383 Word(Range<Anchor>),
384 Line(Range<Anchor>),
385 All,
386}
387
388#[derive(Copy, Clone, PartialEq, Eq, Debug)]
389pub enum EditorMode {
390 SingleLine { auto_width: bool },
391 AutoHeight { max_lines: usize },
392 Full,
393}
394
395#[derive(Copy, Clone, Debug)]
396pub enum SoftWrap {
397 /// Prefer not to wrap at all.
398 ///
399 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
400 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
401 GitDiff,
402 /// Prefer a single line generally, unless an overly long line is encountered.
403 None,
404 /// Soft wrap lines that exceed the editor width.
405 EditorWidth,
406 /// Soft wrap lines at the preferred line length.
407 Column(u32),
408 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
409 Bounded(u32),
410}
411
412#[derive(Clone)]
413pub struct EditorStyle {
414 pub background: Hsla,
415 pub local_player: PlayerColor,
416 pub text: TextStyle,
417 pub scrollbar_width: Pixels,
418 pub syntax: Arc<SyntaxTheme>,
419 pub status: StatusColors,
420 pub inlay_hints_style: HighlightStyle,
421 pub inline_completion_styles: InlineCompletionStyles,
422 pub unnecessary_code_fade: f32,
423}
424
425impl Default for EditorStyle {
426 fn default() -> Self {
427 Self {
428 background: Hsla::default(),
429 local_player: PlayerColor::default(),
430 text: TextStyle::default(),
431 scrollbar_width: Pixels::default(),
432 syntax: Default::default(),
433 // HACK: Status colors don't have a real default.
434 // We should look into removing the status colors from the editor
435 // style and retrieve them directly from the theme.
436 status: StatusColors::dark(),
437 inlay_hints_style: HighlightStyle::default(),
438 inline_completion_styles: InlineCompletionStyles {
439 insertion: HighlightStyle::default(),
440 whitespace: HighlightStyle::default(),
441 },
442 unnecessary_code_fade: Default::default(),
443 }
444 }
445}
446
447pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
448 let show_background = language_settings::language_settings(None, None, cx)
449 .inlay_hints
450 .show_background;
451
452 HighlightStyle {
453 color: Some(cx.theme().status().hint),
454 background_color: show_background.then(|| cx.theme().status().hint_background),
455 ..HighlightStyle::default()
456 }
457}
458
459pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
460 InlineCompletionStyles {
461 insertion: HighlightStyle {
462 color: Some(cx.theme().status().predictive),
463 ..HighlightStyle::default()
464 },
465 whitespace: HighlightStyle {
466 background_color: Some(cx.theme().status().created_background),
467 ..HighlightStyle::default()
468 },
469 }
470}
471
472type CompletionId = usize;
473
474pub(crate) enum EditDisplayMode {
475 TabAccept,
476 DiffPopover,
477 Inline,
478}
479
480enum InlineCompletion {
481 Edit {
482 edits: Vec<(Range<Anchor>, String)>,
483 edit_preview: Option<EditPreview>,
484 display_mode: EditDisplayMode,
485 snapshot: BufferSnapshot,
486 },
487 Move {
488 target: Anchor,
489 range_around_target: Range<text::Anchor>,
490 snapshot: BufferSnapshot,
491 },
492}
493
494struct InlineCompletionState {
495 inlay_ids: Vec<InlayId>,
496 completion: InlineCompletion,
497 completion_id: Option<SharedString>,
498 invalidation_range: Range<Anchor>,
499}
500
501enum EditPredictionSettings {
502 Disabled,
503 Enabled {
504 show_in_menu: bool,
505 preview_requires_modifier: bool,
506 },
507}
508
509impl EditPredictionSettings {
510 pub fn is_enabled(&self) -> bool {
511 match self {
512 EditPredictionSettings::Disabled => false,
513 EditPredictionSettings::Enabled { .. } => true,
514 }
515 }
516}
517
518enum InlineCompletionHighlight {}
519
520pub enum MenuInlineCompletionsPolicy {
521 Never,
522 ByProvider,
523}
524
525#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
526struct EditorActionId(usize);
527
528impl EditorActionId {
529 pub fn post_inc(&mut self) -> Self {
530 let answer = self.0;
531
532 *self = Self(answer + 1);
533
534 Self(answer)
535 }
536}
537
538// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
539// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
540
541type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
542type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
543
544#[derive(Default)]
545struct ScrollbarMarkerState {
546 scrollbar_size: Size<Pixels>,
547 dirty: bool,
548 markers: Arc<[PaintQuad]>,
549 pending_refresh: Option<Task<Result<()>>>,
550}
551
552impl ScrollbarMarkerState {
553 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
554 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
555 }
556}
557
558#[derive(Clone, Debug)]
559struct RunnableTasks {
560 templates: Vec<(TaskSourceKind, TaskTemplate)>,
561 offset: MultiBufferOffset,
562 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
563 column: u32,
564 // Values of all named captures, including those starting with '_'
565 extra_variables: HashMap<String, String>,
566 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
567 context_range: Range<BufferOffset>,
568}
569
570impl RunnableTasks {
571 fn resolve<'a>(
572 &'a self,
573 cx: &'a task::TaskContext,
574 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
575 self.templates.iter().filter_map(|(kind, template)| {
576 template
577 .resolve_task(&kind.to_id_base(), cx)
578 .map(|task| (kind.clone(), task))
579 })
580 }
581}
582
583#[derive(Clone)]
584struct ResolvedTasks {
585 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
586 position: Anchor,
587}
588#[derive(Copy, Clone, Debug)]
589struct MultiBufferOffset(usize);
590#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
591struct BufferOffset(usize);
592
593// Addons allow storing per-editor state in other crates (e.g. Vim)
594pub trait Addon: 'static {
595 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
596
597 fn render_buffer_header_controls(
598 &self,
599 _: &ExcerptInfo,
600 _: &Window,
601 _: &App,
602 ) -> Option<AnyElement> {
603 None
604 }
605
606 fn to_any(&self) -> &dyn std::any::Any;
607}
608
609#[derive(Debug, Copy, Clone, PartialEq, Eq)]
610pub enum IsVimMode {
611 Yes,
612 No,
613}
614
615/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
616///
617/// See the [module level documentation](self) for more information.
618pub struct Editor {
619 focus_handle: FocusHandle,
620 last_focused_descendant: Option<WeakFocusHandle>,
621 /// The text buffer being edited
622 buffer: Entity<MultiBuffer>,
623 /// Map of how text in the buffer should be displayed.
624 /// Handles soft wraps, folds, fake inlay text insertions, etc.
625 pub display_map: Entity<DisplayMap>,
626 pub selections: SelectionsCollection,
627 pub scroll_manager: ScrollManager,
628 /// When inline assist editors are linked, they all render cursors because
629 /// typing enters text into each of them, even the ones that aren't focused.
630 pub(crate) show_cursor_when_unfocused: bool,
631 columnar_selection_tail: Option<Anchor>,
632 add_selections_state: Option<AddSelectionsState>,
633 select_next_state: Option<SelectNextState>,
634 select_prev_state: Option<SelectNextState>,
635 selection_history: SelectionHistory,
636 autoclose_regions: Vec<AutocloseRegion>,
637 snippet_stack: InvalidationStack<SnippetState>,
638 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
639 ime_transaction: Option<TransactionId>,
640 active_diagnostics: Option<ActiveDiagnosticGroup>,
641 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
642
643 // TODO: make this a access method
644 pub project: Option<Entity<Project>>,
645 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
646 completion_provider: Option<Box<dyn CompletionProvider>>,
647 collaboration_hub: Option<Box<dyn CollaborationHub>>,
648 blink_manager: Entity<BlinkManager>,
649 show_cursor_names: bool,
650 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
651 pub show_local_selections: bool,
652 mode: EditorMode,
653 show_breadcrumbs: bool,
654 show_gutter: bool,
655 show_scrollbars: bool,
656 show_line_numbers: Option<bool>,
657 use_relative_line_numbers: Option<bool>,
658 show_git_diff_gutter: Option<bool>,
659 show_code_actions: Option<bool>,
660 show_runnables: Option<bool>,
661 show_wrap_guides: Option<bool>,
662 show_indent_guides: Option<bool>,
663 placeholder_text: Option<Arc<str>>,
664 highlight_order: usize,
665 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
666 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
667 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
668 scrollbar_marker_state: ScrollbarMarkerState,
669 active_indent_guides_state: ActiveIndentGuidesState,
670 nav_history: Option<ItemNavHistory>,
671 context_menu: RefCell<Option<CodeContextMenu>>,
672 mouse_context_menu: Option<MouseContextMenu>,
673 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
674 signature_help_state: SignatureHelpState,
675 auto_signature_help: Option<bool>,
676 find_all_references_task_sources: Vec<Anchor>,
677 next_completion_id: CompletionId,
678 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
679 code_actions_task: Option<Task<Result<()>>>,
680 document_highlights_task: Option<Task<()>>,
681 linked_editing_range_task: Option<Task<Option<()>>>,
682 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
683 pending_rename: Option<RenameState>,
684 searchable: bool,
685 cursor_shape: CursorShape,
686 current_line_highlight: Option<CurrentLineHighlight>,
687 collapse_matches: bool,
688 autoindent_mode: Option<AutoindentMode>,
689 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
690 input_enabled: bool,
691 use_modal_editing: bool,
692 read_only: bool,
693 leader_peer_id: Option<PeerId>,
694 remote_id: Option<ViewId>,
695 hover_state: HoverState,
696 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
697 gutter_hovered: bool,
698 hovered_link_state: Option<HoveredLinkState>,
699 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
700 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
701 active_inline_completion: Option<InlineCompletionState>,
702 /// Used to prevent flickering as the user types while the menu is open
703 stale_inline_completion_in_menu: Option<InlineCompletionState>,
704 edit_prediction_settings: EditPredictionSettings,
705 inline_completions_hidden_for_vim_mode: bool,
706 show_inline_completions_override: Option<bool>,
707 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
708 previewing_inline_completion: bool,
709 inlay_hint_cache: InlayHintCache,
710 next_inlay_id: usize,
711 _subscriptions: Vec<Subscription>,
712 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
713 gutter_dimensions: GutterDimensions,
714 style: Option<EditorStyle>,
715 text_style_refinement: Option<TextStyleRefinement>,
716 next_editor_action_id: EditorActionId,
717 editor_actions:
718 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
719 use_autoclose: bool,
720 use_auto_surround: bool,
721 auto_replace_emoji_shortcode: bool,
722 show_git_blame_gutter: bool,
723 show_git_blame_inline: bool,
724 show_git_blame_inline_delay_task: Option<Task<()>>,
725 git_blame_inline_enabled: bool,
726 serialize_dirty_buffers: bool,
727 show_selection_menu: Option<bool>,
728 blame: Option<Entity<GitBlame>>,
729 blame_subscription: Option<Subscription>,
730 custom_context_menu: Option<
731 Box<
732 dyn 'static
733 + Fn(
734 &mut Self,
735 DisplayPoint,
736 &mut Window,
737 &mut Context<Self>,
738 ) -> Option<Entity<ui::ContextMenu>>,
739 >,
740 >,
741 last_bounds: Option<Bounds<Pixels>>,
742 last_position_map: Option<Rc<PositionMap>>,
743 expect_bounds_change: Option<Bounds<Pixels>>,
744 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
745 tasks_update_task: Option<Task<()>>,
746 in_project_search: bool,
747 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
748 breadcrumb_header: Option<String>,
749 focused_block: Option<FocusedBlock>,
750 next_scroll_position: NextScrollCursorCenterTopBottom,
751 addons: HashMap<TypeId, Box<dyn Addon>>,
752 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
753 selection_mark_mode: bool,
754 toggle_fold_multiple_buffers: Task<()>,
755 _scroll_cursor_center_top_bottom_task: Task<()>,
756}
757
758#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
759enum NextScrollCursorCenterTopBottom {
760 #[default]
761 Center,
762 Top,
763 Bottom,
764}
765
766impl NextScrollCursorCenterTopBottom {
767 fn next(&self) -> Self {
768 match self {
769 Self::Center => Self::Top,
770 Self::Top => Self::Bottom,
771 Self::Bottom => Self::Center,
772 }
773 }
774}
775
776#[derive(Clone)]
777pub struct EditorSnapshot {
778 pub mode: EditorMode,
779 show_gutter: bool,
780 show_line_numbers: Option<bool>,
781 show_git_diff_gutter: Option<bool>,
782 show_code_actions: Option<bool>,
783 show_runnables: Option<bool>,
784 git_blame_gutter_max_author_length: Option<usize>,
785 pub display_snapshot: DisplaySnapshot,
786 pub placeholder_text: Option<Arc<str>>,
787 is_focused: bool,
788 scroll_anchor: ScrollAnchor,
789 ongoing_scroll: OngoingScroll,
790 current_line_highlight: CurrentLineHighlight,
791 gutter_hovered: bool,
792}
793
794const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
795
796#[derive(Default, Debug, Clone, Copy)]
797pub struct GutterDimensions {
798 pub left_padding: Pixels,
799 pub right_padding: Pixels,
800 pub width: Pixels,
801 pub margin: Pixels,
802 pub git_blame_entries_width: Option<Pixels>,
803}
804
805impl GutterDimensions {
806 /// The full width of the space taken up by the gutter.
807 pub fn full_width(&self) -> Pixels {
808 self.margin + self.width
809 }
810
811 /// The width of the space reserved for the fold indicators,
812 /// use alongside 'justify_end' and `gutter_width` to
813 /// right align content with the line numbers
814 pub fn fold_area_width(&self) -> Pixels {
815 self.margin + self.right_padding
816 }
817}
818
819#[derive(Debug)]
820pub struct RemoteSelection {
821 pub replica_id: ReplicaId,
822 pub selection: Selection<Anchor>,
823 pub cursor_shape: CursorShape,
824 pub peer_id: PeerId,
825 pub line_mode: bool,
826 pub participant_index: Option<ParticipantIndex>,
827 pub user_name: Option<SharedString>,
828}
829
830#[derive(Clone, Debug)]
831struct SelectionHistoryEntry {
832 selections: Arc<[Selection<Anchor>]>,
833 select_next_state: Option<SelectNextState>,
834 select_prev_state: Option<SelectNextState>,
835 add_selections_state: Option<AddSelectionsState>,
836}
837
838enum SelectionHistoryMode {
839 Normal,
840 Undoing,
841 Redoing,
842}
843
844#[derive(Clone, PartialEq, Eq, Hash)]
845struct HoveredCursor {
846 replica_id: u16,
847 selection_id: usize,
848}
849
850impl Default for SelectionHistoryMode {
851 fn default() -> Self {
852 Self::Normal
853 }
854}
855
856#[derive(Default)]
857struct SelectionHistory {
858 #[allow(clippy::type_complexity)]
859 selections_by_transaction:
860 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
861 mode: SelectionHistoryMode,
862 undo_stack: VecDeque<SelectionHistoryEntry>,
863 redo_stack: VecDeque<SelectionHistoryEntry>,
864}
865
866impl SelectionHistory {
867 fn insert_transaction(
868 &mut self,
869 transaction_id: TransactionId,
870 selections: Arc<[Selection<Anchor>]>,
871 ) {
872 self.selections_by_transaction
873 .insert(transaction_id, (selections, None));
874 }
875
876 #[allow(clippy::type_complexity)]
877 fn transaction(
878 &self,
879 transaction_id: TransactionId,
880 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
881 self.selections_by_transaction.get(&transaction_id)
882 }
883
884 #[allow(clippy::type_complexity)]
885 fn transaction_mut(
886 &mut self,
887 transaction_id: TransactionId,
888 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
889 self.selections_by_transaction.get_mut(&transaction_id)
890 }
891
892 fn push(&mut self, entry: SelectionHistoryEntry) {
893 if !entry.selections.is_empty() {
894 match self.mode {
895 SelectionHistoryMode::Normal => {
896 self.push_undo(entry);
897 self.redo_stack.clear();
898 }
899 SelectionHistoryMode::Undoing => self.push_redo(entry),
900 SelectionHistoryMode::Redoing => self.push_undo(entry),
901 }
902 }
903 }
904
905 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
906 if self
907 .undo_stack
908 .back()
909 .map_or(true, |e| e.selections != entry.selections)
910 {
911 self.undo_stack.push_back(entry);
912 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
913 self.undo_stack.pop_front();
914 }
915 }
916 }
917
918 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
919 if self
920 .redo_stack
921 .back()
922 .map_or(true, |e| e.selections != entry.selections)
923 {
924 self.redo_stack.push_back(entry);
925 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
926 self.redo_stack.pop_front();
927 }
928 }
929 }
930}
931
932struct RowHighlight {
933 index: usize,
934 range: Range<Anchor>,
935 color: Hsla,
936 should_autoscroll: bool,
937}
938
939#[derive(Clone, Debug)]
940struct AddSelectionsState {
941 above: bool,
942 stack: Vec<usize>,
943}
944
945#[derive(Clone)]
946struct SelectNextState {
947 query: AhoCorasick,
948 wordwise: bool,
949 done: bool,
950}
951
952impl std::fmt::Debug for SelectNextState {
953 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
954 f.debug_struct(std::any::type_name::<Self>())
955 .field("wordwise", &self.wordwise)
956 .field("done", &self.done)
957 .finish()
958 }
959}
960
961#[derive(Debug)]
962struct AutocloseRegion {
963 selection_id: usize,
964 range: Range<Anchor>,
965 pair: BracketPair,
966}
967
968#[derive(Debug)]
969struct SnippetState {
970 ranges: Vec<Vec<Range<Anchor>>>,
971 active_index: usize,
972 choices: Vec<Option<Vec<String>>>,
973}
974
975#[doc(hidden)]
976pub struct RenameState {
977 pub range: Range<Anchor>,
978 pub old_name: Arc<str>,
979 pub editor: Entity<Editor>,
980 block_id: CustomBlockId,
981}
982
983struct InvalidationStack<T>(Vec<T>);
984
985struct RegisteredInlineCompletionProvider {
986 provider: Arc<dyn InlineCompletionProviderHandle>,
987 _subscription: Subscription,
988}
989
990#[derive(Debug)]
991struct ActiveDiagnosticGroup {
992 primary_range: Range<Anchor>,
993 primary_message: String,
994 group_id: usize,
995 blocks: HashMap<CustomBlockId, Diagnostic>,
996 is_valid: bool,
997}
998
999#[derive(Serialize, Deserialize, Clone, Debug)]
1000pub struct ClipboardSelection {
1001 pub len: usize,
1002 pub is_entire_line: bool,
1003 pub first_line_indent: u32,
1004}
1005
1006#[derive(Debug)]
1007pub(crate) struct NavigationData {
1008 cursor_anchor: Anchor,
1009 cursor_position: Point,
1010 scroll_anchor: ScrollAnchor,
1011 scroll_top_row: u32,
1012}
1013
1014#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1015pub enum GotoDefinitionKind {
1016 Symbol,
1017 Declaration,
1018 Type,
1019 Implementation,
1020}
1021
1022#[derive(Debug, Clone)]
1023enum InlayHintRefreshReason {
1024 Toggle(bool),
1025 SettingsChange(InlayHintSettings),
1026 NewLinesShown,
1027 BufferEdited(HashSet<Arc<Language>>),
1028 RefreshRequested,
1029 ExcerptsRemoved(Vec<ExcerptId>),
1030}
1031
1032impl InlayHintRefreshReason {
1033 fn description(&self) -> &'static str {
1034 match self {
1035 Self::Toggle(_) => "toggle",
1036 Self::SettingsChange(_) => "settings change",
1037 Self::NewLinesShown => "new lines shown",
1038 Self::BufferEdited(_) => "buffer edited",
1039 Self::RefreshRequested => "refresh requested",
1040 Self::ExcerptsRemoved(_) => "excerpts removed",
1041 }
1042 }
1043}
1044
1045pub enum FormatTarget {
1046 Buffers,
1047 Ranges(Vec<Range<MultiBufferPoint>>),
1048}
1049
1050pub(crate) struct FocusedBlock {
1051 id: BlockId,
1052 focus_handle: WeakFocusHandle,
1053}
1054
1055#[derive(Clone)]
1056enum JumpData {
1057 MultiBufferRow {
1058 row: MultiBufferRow,
1059 line_offset_from_top: u32,
1060 },
1061 MultiBufferPoint {
1062 excerpt_id: ExcerptId,
1063 position: Point,
1064 anchor: text::Anchor,
1065 line_offset_from_top: u32,
1066 },
1067}
1068
1069pub enum MultibufferSelectionMode {
1070 First,
1071 All,
1072}
1073
1074impl Editor {
1075 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1076 let buffer = cx.new(|cx| Buffer::local("", cx));
1077 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1078 Self::new(
1079 EditorMode::SingleLine { auto_width: false },
1080 buffer,
1081 None,
1082 false,
1083 window,
1084 cx,
1085 )
1086 }
1087
1088 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1089 let buffer = cx.new(|cx| Buffer::local("", cx));
1090 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1091 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1092 }
1093
1094 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1095 let buffer = cx.new(|cx| Buffer::local("", cx));
1096 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1097 Self::new(
1098 EditorMode::SingleLine { auto_width: true },
1099 buffer,
1100 None,
1101 false,
1102 window,
1103 cx,
1104 )
1105 }
1106
1107 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1108 let buffer = cx.new(|cx| Buffer::local("", cx));
1109 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1110 Self::new(
1111 EditorMode::AutoHeight { max_lines },
1112 buffer,
1113 None,
1114 false,
1115 window,
1116 cx,
1117 )
1118 }
1119
1120 pub fn for_buffer(
1121 buffer: Entity<Buffer>,
1122 project: Option<Entity<Project>>,
1123 window: &mut Window,
1124 cx: &mut Context<Self>,
1125 ) -> Self {
1126 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1127 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1128 }
1129
1130 pub fn for_multibuffer(
1131 buffer: Entity<MultiBuffer>,
1132 project: Option<Entity<Project>>,
1133 show_excerpt_controls: bool,
1134 window: &mut Window,
1135 cx: &mut Context<Self>,
1136 ) -> Self {
1137 Self::new(
1138 EditorMode::Full,
1139 buffer,
1140 project,
1141 show_excerpt_controls,
1142 window,
1143 cx,
1144 )
1145 }
1146
1147 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1148 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1149 let mut clone = Self::new(
1150 self.mode,
1151 self.buffer.clone(),
1152 self.project.clone(),
1153 show_excerpt_controls,
1154 window,
1155 cx,
1156 );
1157 self.display_map.update(cx, |display_map, cx| {
1158 let snapshot = display_map.snapshot(cx);
1159 clone.display_map.update(cx, |display_map, cx| {
1160 display_map.set_state(&snapshot, cx);
1161 });
1162 });
1163 clone.selections.clone_state(&self.selections);
1164 clone.scroll_manager.clone_state(&self.scroll_manager);
1165 clone.searchable = self.searchable;
1166 clone
1167 }
1168
1169 pub fn new(
1170 mode: EditorMode,
1171 buffer: Entity<MultiBuffer>,
1172 project: Option<Entity<Project>>,
1173 show_excerpt_controls: bool,
1174 window: &mut Window,
1175 cx: &mut Context<Self>,
1176 ) -> Self {
1177 let style = window.text_style();
1178 let font_size = style.font_size.to_pixels(window.rem_size());
1179 let editor = cx.entity().downgrade();
1180 let fold_placeholder = FoldPlaceholder {
1181 constrain_width: true,
1182 render: Arc::new(move |fold_id, fold_range, _, cx| {
1183 let editor = editor.clone();
1184 div()
1185 .id(fold_id)
1186 .bg(cx.theme().colors().ghost_element_background)
1187 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1188 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1189 .rounded_sm()
1190 .size_full()
1191 .cursor_pointer()
1192 .child("⋯")
1193 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1194 .on_click(move |_, _window, cx| {
1195 editor
1196 .update(cx, |editor, cx| {
1197 editor.unfold_ranges(
1198 &[fold_range.start..fold_range.end],
1199 true,
1200 false,
1201 cx,
1202 );
1203 cx.stop_propagation();
1204 })
1205 .ok();
1206 })
1207 .into_any()
1208 }),
1209 merge_adjacent: true,
1210 ..Default::default()
1211 };
1212 let display_map = cx.new(|cx| {
1213 DisplayMap::new(
1214 buffer.clone(),
1215 style.font(),
1216 font_size,
1217 None,
1218 show_excerpt_controls,
1219 FILE_HEADER_HEIGHT,
1220 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1221 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1222 fold_placeholder,
1223 cx,
1224 )
1225 });
1226
1227 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1228
1229 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1230
1231 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1232 .then(|| language_settings::SoftWrap::None);
1233
1234 let mut project_subscriptions = Vec::new();
1235 if mode == EditorMode::Full {
1236 if let Some(project) = project.as_ref() {
1237 if buffer.read(cx).is_singleton() {
1238 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1239 cx.emit(EditorEvent::TitleChanged);
1240 }));
1241 }
1242 project_subscriptions.push(cx.subscribe_in(
1243 project,
1244 window,
1245 |editor, _, event, window, cx| {
1246 if let project::Event::RefreshInlayHints = event {
1247 editor
1248 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1249 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1250 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1251 let focus_handle = editor.focus_handle(cx);
1252 if focus_handle.is_focused(window) {
1253 let snapshot = buffer.read(cx).snapshot();
1254 for (range, snippet) in snippet_edits {
1255 let editor_range =
1256 language::range_from_lsp(*range).to_offset(&snapshot);
1257 editor
1258 .insert_snippet(
1259 &[editor_range],
1260 snippet.clone(),
1261 window,
1262 cx,
1263 )
1264 .ok();
1265 }
1266 }
1267 }
1268 }
1269 },
1270 ));
1271 if let Some(task_inventory) = project
1272 .read(cx)
1273 .task_store()
1274 .read(cx)
1275 .task_inventory()
1276 .cloned()
1277 {
1278 project_subscriptions.push(cx.observe_in(
1279 &task_inventory,
1280 window,
1281 |editor, _, window, cx| {
1282 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1283 },
1284 ));
1285 }
1286 }
1287 }
1288
1289 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1290
1291 let inlay_hint_settings =
1292 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1293 let focus_handle = cx.focus_handle();
1294 cx.on_focus(&focus_handle, window, Self::handle_focus)
1295 .detach();
1296 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1297 .detach();
1298 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1299 .detach();
1300 cx.on_blur(&focus_handle, window, Self::handle_blur)
1301 .detach();
1302
1303 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1304 Some(false)
1305 } else {
1306 None
1307 };
1308
1309 let mut code_action_providers = Vec::new();
1310 if let Some(project) = project.clone() {
1311 get_uncommitted_diff_for_buffer(
1312 &project,
1313 buffer.read(cx).all_buffers(),
1314 buffer.clone(),
1315 cx,
1316 );
1317 code_action_providers.push(Rc::new(project) as Rc<_>);
1318 }
1319
1320 let mut this = Self {
1321 focus_handle,
1322 show_cursor_when_unfocused: false,
1323 last_focused_descendant: None,
1324 buffer: buffer.clone(),
1325 display_map: display_map.clone(),
1326 selections,
1327 scroll_manager: ScrollManager::new(cx),
1328 columnar_selection_tail: None,
1329 add_selections_state: None,
1330 select_next_state: None,
1331 select_prev_state: None,
1332 selection_history: Default::default(),
1333 autoclose_regions: Default::default(),
1334 snippet_stack: Default::default(),
1335 select_larger_syntax_node_stack: Vec::new(),
1336 ime_transaction: Default::default(),
1337 active_diagnostics: None,
1338 soft_wrap_mode_override,
1339 completion_provider: project.clone().map(|project| Box::new(project) as _),
1340 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1341 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1342 project,
1343 blink_manager: blink_manager.clone(),
1344 show_local_selections: true,
1345 show_scrollbars: true,
1346 mode,
1347 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1348 show_gutter: mode == EditorMode::Full,
1349 show_line_numbers: None,
1350 use_relative_line_numbers: None,
1351 show_git_diff_gutter: None,
1352 show_code_actions: None,
1353 show_runnables: None,
1354 show_wrap_guides: None,
1355 show_indent_guides,
1356 placeholder_text: None,
1357 highlight_order: 0,
1358 highlighted_rows: HashMap::default(),
1359 background_highlights: Default::default(),
1360 gutter_highlights: TreeMap::default(),
1361 scrollbar_marker_state: ScrollbarMarkerState::default(),
1362 active_indent_guides_state: ActiveIndentGuidesState::default(),
1363 nav_history: None,
1364 context_menu: RefCell::new(None),
1365 mouse_context_menu: None,
1366 completion_tasks: Default::default(),
1367 signature_help_state: SignatureHelpState::default(),
1368 auto_signature_help: None,
1369 find_all_references_task_sources: Vec::new(),
1370 next_completion_id: 0,
1371 next_inlay_id: 0,
1372 code_action_providers,
1373 available_code_actions: Default::default(),
1374 code_actions_task: Default::default(),
1375 document_highlights_task: Default::default(),
1376 linked_editing_range_task: Default::default(),
1377 pending_rename: Default::default(),
1378 searchable: true,
1379 cursor_shape: EditorSettings::get_global(cx)
1380 .cursor_shape
1381 .unwrap_or_default(),
1382 current_line_highlight: None,
1383 autoindent_mode: Some(AutoindentMode::EachLine),
1384 collapse_matches: false,
1385 workspace: None,
1386 input_enabled: true,
1387 use_modal_editing: mode == EditorMode::Full,
1388 read_only: false,
1389 use_autoclose: true,
1390 use_auto_surround: true,
1391 auto_replace_emoji_shortcode: false,
1392 leader_peer_id: None,
1393 remote_id: None,
1394 hover_state: Default::default(),
1395 pending_mouse_down: None,
1396 hovered_link_state: Default::default(),
1397 edit_prediction_provider: None,
1398 active_inline_completion: None,
1399 stale_inline_completion_in_menu: None,
1400 previewing_inline_completion: false,
1401 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1402
1403 gutter_hovered: false,
1404 pixel_position_of_newest_cursor: None,
1405 last_bounds: None,
1406 last_position_map: None,
1407 expect_bounds_change: None,
1408 gutter_dimensions: GutterDimensions::default(),
1409 style: None,
1410 show_cursor_names: false,
1411 hovered_cursors: Default::default(),
1412 next_editor_action_id: EditorActionId::default(),
1413 editor_actions: Rc::default(),
1414 inline_completions_hidden_for_vim_mode: false,
1415 show_inline_completions_override: None,
1416 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1417 edit_prediction_settings: EditPredictionSettings::Disabled,
1418 custom_context_menu: None,
1419 show_git_blame_gutter: false,
1420 show_git_blame_inline: false,
1421 show_selection_menu: None,
1422 show_git_blame_inline_delay_task: None,
1423 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1424 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1425 .session
1426 .restore_unsaved_buffers,
1427 blame: None,
1428 blame_subscription: None,
1429 tasks: Default::default(),
1430 _subscriptions: vec![
1431 cx.observe(&buffer, Self::on_buffer_changed),
1432 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1433 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1434 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1435 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1436 cx.observe_window_activation(window, |editor, window, cx| {
1437 let active = window.is_window_active();
1438 editor.blink_manager.update(cx, |blink_manager, cx| {
1439 if active {
1440 blink_manager.enable(cx);
1441 } else {
1442 blink_manager.disable(cx);
1443 }
1444 });
1445 }),
1446 ],
1447 tasks_update_task: None,
1448 linked_edit_ranges: Default::default(),
1449 in_project_search: false,
1450 previous_search_ranges: None,
1451 breadcrumb_header: None,
1452 focused_block: None,
1453 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1454 addons: HashMap::default(),
1455 registered_buffers: HashMap::default(),
1456 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1457 selection_mark_mode: false,
1458 toggle_fold_multiple_buffers: Task::ready(()),
1459 text_style_refinement: None,
1460 };
1461 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1462 this._subscriptions.extend(project_subscriptions);
1463
1464 this.end_selection(window, cx);
1465 this.scroll_manager.show_scrollbar(window, cx);
1466
1467 if mode == EditorMode::Full {
1468 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1469 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1470
1471 if this.git_blame_inline_enabled {
1472 this.git_blame_inline_enabled = true;
1473 this.start_git_blame_inline(false, window, cx);
1474 }
1475
1476 if let Some(buffer) = buffer.read(cx).as_singleton() {
1477 if let Some(project) = this.project.as_ref() {
1478 let lsp_store = project.read(cx).lsp_store();
1479 let handle = lsp_store.update(cx, |lsp_store, cx| {
1480 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1481 });
1482 this.registered_buffers
1483 .insert(buffer.read(cx).remote_id(), handle);
1484 }
1485 }
1486 }
1487
1488 this.report_editor_event("Editor Opened", None, cx);
1489 this
1490 }
1491
1492 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1493 self.mouse_context_menu
1494 .as_ref()
1495 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1496 }
1497
1498 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1499 let mut key_context = KeyContext::new_with_defaults();
1500 key_context.add("Editor");
1501 let mode = match self.mode {
1502 EditorMode::SingleLine { .. } => "single_line",
1503 EditorMode::AutoHeight { .. } => "auto_height",
1504 EditorMode::Full => "full",
1505 };
1506
1507 if EditorSettings::jupyter_enabled(cx) {
1508 key_context.add("jupyter");
1509 }
1510
1511 key_context.set("mode", mode);
1512 if self.pending_rename.is_some() {
1513 key_context.add("renaming");
1514 }
1515
1516 let mut showing_completions = false;
1517
1518 match self.context_menu.borrow().as_ref() {
1519 Some(CodeContextMenu::Completions(_)) => {
1520 key_context.add("menu");
1521 key_context.add("showing_completions");
1522 showing_completions = true;
1523 }
1524 Some(CodeContextMenu::CodeActions(_)) => {
1525 key_context.add("menu");
1526 key_context.add("showing_code_actions")
1527 }
1528 None => {}
1529 }
1530
1531 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1532 if !self.focus_handle(cx).contains_focused(window, cx)
1533 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1534 {
1535 for addon in self.addons.values() {
1536 addon.extend_key_context(&mut key_context, cx)
1537 }
1538 }
1539
1540 if let Some(extension) = self
1541 .buffer
1542 .read(cx)
1543 .as_singleton()
1544 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1545 {
1546 key_context.set("extension", extension.to_string());
1547 }
1548
1549 if self.has_active_inline_completion() {
1550 key_context.add("copilot_suggestion");
1551 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1552
1553 if showing_completions || self.edit_prediction_requires_modifier() {
1554 key_context.add(EDIT_PREDICTION_REQUIRES_MODIFIER_KEY_CONTEXT);
1555 }
1556 }
1557
1558 if self.selection_mark_mode {
1559 key_context.add("selection_mode");
1560 }
1561
1562 key_context
1563 }
1564
1565 pub fn accept_edit_prediction_keybind(
1566 &self,
1567 window: &Window,
1568 cx: &App,
1569 ) -> AcceptEditPredictionBinding {
1570 let mut context = self.key_context(window, cx);
1571 context.add(EDIT_PREDICTION_KEY_CONTEXT);
1572
1573 AcceptEditPredictionBinding(
1574 window
1575 .bindings_for_action_in_context(&AcceptEditPrediction, context)
1576 .into_iter()
1577 .rev()
1578 .next(),
1579 )
1580 }
1581
1582 pub fn new_file(
1583 workspace: &mut Workspace,
1584 _: &workspace::NewFile,
1585 window: &mut Window,
1586 cx: &mut Context<Workspace>,
1587 ) {
1588 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1589 "Failed to create buffer",
1590 window,
1591 cx,
1592 |e, _, _| match e.error_code() {
1593 ErrorCode::RemoteUpgradeRequired => Some(format!(
1594 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1595 e.error_tag("required").unwrap_or("the latest version")
1596 )),
1597 _ => None,
1598 },
1599 );
1600 }
1601
1602 pub fn new_in_workspace(
1603 workspace: &mut Workspace,
1604 window: &mut Window,
1605 cx: &mut Context<Workspace>,
1606 ) -> Task<Result<Entity<Editor>>> {
1607 let project = workspace.project().clone();
1608 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1609
1610 cx.spawn_in(window, |workspace, mut cx| async move {
1611 let buffer = create.await?;
1612 workspace.update_in(&mut cx, |workspace, window, cx| {
1613 let editor =
1614 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1615 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1616 editor
1617 })
1618 })
1619 }
1620
1621 fn new_file_vertical(
1622 workspace: &mut Workspace,
1623 _: &workspace::NewFileSplitVertical,
1624 window: &mut Window,
1625 cx: &mut Context<Workspace>,
1626 ) {
1627 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1628 }
1629
1630 fn new_file_horizontal(
1631 workspace: &mut Workspace,
1632 _: &workspace::NewFileSplitHorizontal,
1633 window: &mut Window,
1634 cx: &mut Context<Workspace>,
1635 ) {
1636 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1637 }
1638
1639 fn new_file_in_direction(
1640 workspace: &mut Workspace,
1641 direction: SplitDirection,
1642 window: &mut Window,
1643 cx: &mut Context<Workspace>,
1644 ) {
1645 let project = workspace.project().clone();
1646 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1647
1648 cx.spawn_in(window, |workspace, mut cx| async move {
1649 let buffer = create.await?;
1650 workspace.update_in(&mut cx, move |workspace, window, cx| {
1651 workspace.split_item(
1652 direction,
1653 Box::new(
1654 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1655 ),
1656 window,
1657 cx,
1658 )
1659 })?;
1660 anyhow::Ok(())
1661 })
1662 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1663 match e.error_code() {
1664 ErrorCode::RemoteUpgradeRequired => Some(format!(
1665 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1666 e.error_tag("required").unwrap_or("the latest version")
1667 )),
1668 _ => None,
1669 }
1670 });
1671 }
1672
1673 pub fn leader_peer_id(&self) -> Option<PeerId> {
1674 self.leader_peer_id
1675 }
1676
1677 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1678 &self.buffer
1679 }
1680
1681 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1682 self.workspace.as_ref()?.0.upgrade()
1683 }
1684
1685 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1686 self.buffer().read(cx).title(cx)
1687 }
1688
1689 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1690 let git_blame_gutter_max_author_length = self
1691 .render_git_blame_gutter(cx)
1692 .then(|| {
1693 if let Some(blame) = self.blame.as_ref() {
1694 let max_author_length =
1695 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1696 Some(max_author_length)
1697 } else {
1698 None
1699 }
1700 })
1701 .flatten();
1702
1703 EditorSnapshot {
1704 mode: self.mode,
1705 show_gutter: self.show_gutter,
1706 show_line_numbers: self.show_line_numbers,
1707 show_git_diff_gutter: self.show_git_diff_gutter,
1708 show_code_actions: self.show_code_actions,
1709 show_runnables: self.show_runnables,
1710 git_blame_gutter_max_author_length,
1711 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1712 scroll_anchor: self.scroll_manager.anchor(),
1713 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1714 placeholder_text: self.placeholder_text.clone(),
1715 is_focused: self.focus_handle.is_focused(window),
1716 current_line_highlight: self
1717 .current_line_highlight
1718 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1719 gutter_hovered: self.gutter_hovered,
1720 }
1721 }
1722
1723 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1724 self.buffer.read(cx).language_at(point, cx)
1725 }
1726
1727 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1728 self.buffer.read(cx).read(cx).file_at(point).cloned()
1729 }
1730
1731 pub fn active_excerpt(
1732 &self,
1733 cx: &App,
1734 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1735 self.buffer
1736 .read(cx)
1737 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1738 }
1739
1740 pub fn mode(&self) -> EditorMode {
1741 self.mode
1742 }
1743
1744 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1745 self.collaboration_hub.as_deref()
1746 }
1747
1748 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1749 self.collaboration_hub = Some(hub);
1750 }
1751
1752 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1753 self.in_project_search = in_project_search;
1754 }
1755
1756 pub fn set_custom_context_menu(
1757 &mut self,
1758 f: impl 'static
1759 + Fn(
1760 &mut Self,
1761 DisplayPoint,
1762 &mut Window,
1763 &mut Context<Self>,
1764 ) -> Option<Entity<ui::ContextMenu>>,
1765 ) {
1766 self.custom_context_menu = Some(Box::new(f))
1767 }
1768
1769 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1770 self.completion_provider = provider;
1771 }
1772
1773 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1774 self.semantics_provider.clone()
1775 }
1776
1777 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1778 self.semantics_provider = provider;
1779 }
1780
1781 pub fn set_edit_prediction_provider<T>(
1782 &mut self,
1783 provider: Option<Entity<T>>,
1784 window: &mut Window,
1785 cx: &mut Context<Self>,
1786 ) where
1787 T: EditPredictionProvider,
1788 {
1789 self.edit_prediction_provider =
1790 provider.map(|provider| RegisteredInlineCompletionProvider {
1791 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1792 if this.focus_handle.is_focused(window) {
1793 this.update_visible_inline_completion(window, cx);
1794 }
1795 }),
1796 provider: Arc::new(provider),
1797 });
1798 self.refresh_inline_completion(false, false, window, cx);
1799 }
1800
1801 pub fn placeholder_text(&self) -> Option<&str> {
1802 self.placeholder_text.as_deref()
1803 }
1804
1805 pub fn set_placeholder_text(
1806 &mut self,
1807 placeholder_text: impl Into<Arc<str>>,
1808 cx: &mut Context<Self>,
1809 ) {
1810 let placeholder_text = Some(placeholder_text.into());
1811 if self.placeholder_text != placeholder_text {
1812 self.placeholder_text = placeholder_text;
1813 cx.notify();
1814 }
1815 }
1816
1817 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1818 self.cursor_shape = cursor_shape;
1819
1820 // Disrupt blink for immediate user feedback that the cursor shape has changed
1821 self.blink_manager.update(cx, BlinkManager::show_cursor);
1822
1823 cx.notify();
1824 }
1825
1826 pub fn set_current_line_highlight(
1827 &mut self,
1828 current_line_highlight: Option<CurrentLineHighlight>,
1829 ) {
1830 self.current_line_highlight = current_line_highlight;
1831 }
1832
1833 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1834 self.collapse_matches = collapse_matches;
1835 }
1836
1837 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1838 let buffers = self.buffer.read(cx).all_buffers();
1839 let Some(lsp_store) = self.lsp_store(cx) else {
1840 return;
1841 };
1842 lsp_store.update(cx, |lsp_store, cx| {
1843 for buffer in buffers {
1844 self.registered_buffers
1845 .entry(buffer.read(cx).remote_id())
1846 .or_insert_with(|| {
1847 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1848 });
1849 }
1850 })
1851 }
1852
1853 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1854 if self.collapse_matches {
1855 return range.start..range.start;
1856 }
1857 range.clone()
1858 }
1859
1860 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1861 if self.display_map.read(cx).clip_at_line_ends != clip {
1862 self.display_map
1863 .update(cx, |map, _| map.clip_at_line_ends = clip);
1864 }
1865 }
1866
1867 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1868 self.input_enabled = input_enabled;
1869 }
1870
1871 pub fn set_inline_completions_hidden_for_vim_mode(
1872 &mut self,
1873 hidden: bool,
1874 window: &mut Window,
1875 cx: &mut Context<Self>,
1876 ) {
1877 if hidden != self.inline_completions_hidden_for_vim_mode {
1878 self.inline_completions_hidden_for_vim_mode = hidden;
1879 if hidden {
1880 self.update_visible_inline_completion(window, cx);
1881 } else {
1882 self.refresh_inline_completion(true, false, window, cx);
1883 }
1884 }
1885 }
1886
1887 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1888 self.menu_inline_completions_policy = value;
1889 }
1890
1891 pub fn set_autoindent(&mut self, autoindent: bool) {
1892 if autoindent {
1893 self.autoindent_mode = Some(AutoindentMode::EachLine);
1894 } else {
1895 self.autoindent_mode = None;
1896 }
1897 }
1898
1899 pub fn read_only(&self, cx: &App) -> bool {
1900 self.read_only || self.buffer.read(cx).read_only()
1901 }
1902
1903 pub fn set_read_only(&mut self, read_only: bool) {
1904 self.read_only = read_only;
1905 }
1906
1907 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1908 self.use_autoclose = autoclose;
1909 }
1910
1911 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1912 self.use_auto_surround = auto_surround;
1913 }
1914
1915 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1916 self.auto_replace_emoji_shortcode = auto_replace;
1917 }
1918
1919 pub fn toggle_inline_completions(
1920 &mut self,
1921 _: &ToggleEditPrediction,
1922 window: &mut Window,
1923 cx: &mut Context<Self>,
1924 ) {
1925 if self.show_inline_completions_override.is_some() {
1926 self.set_show_edit_predictions(None, window, cx);
1927 } else {
1928 let show_edit_predictions = !self.edit_predictions_enabled();
1929 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
1930 }
1931 }
1932
1933 pub fn set_show_edit_predictions(
1934 &mut self,
1935 show_edit_predictions: Option<bool>,
1936 window: &mut Window,
1937 cx: &mut Context<Self>,
1938 ) {
1939 self.show_inline_completions_override = show_edit_predictions;
1940 self.refresh_inline_completion(false, true, window, cx);
1941 }
1942
1943 pub fn inline_completion_start_anchor(&self) -> Option<Anchor> {
1944 let active_completion = self.active_inline_completion.as_ref()?;
1945 let result = match &active_completion.completion {
1946 InlineCompletion::Edit { edits, .. } => edits.first()?.0.start,
1947 InlineCompletion::Move { target, .. } => *target,
1948 };
1949 Some(result)
1950 }
1951
1952 fn inline_completions_disabled_in_scope(
1953 &self,
1954 buffer: &Entity<Buffer>,
1955 buffer_position: language::Anchor,
1956 cx: &App,
1957 ) -> bool {
1958 let snapshot = buffer.read(cx).snapshot();
1959 let settings = snapshot.settings_at(buffer_position, cx);
1960
1961 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1962 return false;
1963 };
1964
1965 scope.override_name().map_or(false, |scope_name| {
1966 settings
1967 .edit_predictions_disabled_in
1968 .iter()
1969 .any(|s| s == scope_name)
1970 })
1971 }
1972
1973 pub fn set_use_modal_editing(&mut self, to: bool) {
1974 self.use_modal_editing = to;
1975 }
1976
1977 pub fn use_modal_editing(&self) -> bool {
1978 self.use_modal_editing
1979 }
1980
1981 fn selections_did_change(
1982 &mut self,
1983 local: bool,
1984 old_cursor_position: &Anchor,
1985 show_completions: bool,
1986 window: &mut Window,
1987 cx: &mut Context<Self>,
1988 ) {
1989 window.invalidate_character_coordinates();
1990
1991 // Copy selections to primary selection buffer
1992 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1993 if local {
1994 let selections = self.selections.all::<usize>(cx);
1995 let buffer_handle = self.buffer.read(cx).read(cx);
1996
1997 let mut text = String::new();
1998 for (index, selection) in selections.iter().enumerate() {
1999 let text_for_selection = buffer_handle
2000 .text_for_range(selection.start..selection.end)
2001 .collect::<String>();
2002
2003 text.push_str(&text_for_selection);
2004 if index != selections.len() - 1 {
2005 text.push('\n');
2006 }
2007 }
2008
2009 if !text.is_empty() {
2010 cx.write_to_primary(ClipboardItem::new_string(text));
2011 }
2012 }
2013
2014 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2015 self.buffer.update(cx, |buffer, cx| {
2016 buffer.set_active_selections(
2017 &self.selections.disjoint_anchors(),
2018 self.selections.line_mode,
2019 self.cursor_shape,
2020 cx,
2021 )
2022 });
2023 }
2024 let display_map = self
2025 .display_map
2026 .update(cx, |display_map, cx| display_map.snapshot(cx));
2027 let buffer = &display_map.buffer_snapshot;
2028 self.add_selections_state = None;
2029 self.select_next_state = None;
2030 self.select_prev_state = None;
2031 self.select_larger_syntax_node_stack.clear();
2032 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2033 self.snippet_stack
2034 .invalidate(&self.selections.disjoint_anchors(), buffer);
2035 self.take_rename(false, window, cx);
2036
2037 let new_cursor_position = self.selections.newest_anchor().head();
2038
2039 self.push_to_nav_history(
2040 *old_cursor_position,
2041 Some(new_cursor_position.to_point(buffer)),
2042 cx,
2043 );
2044
2045 if local {
2046 let new_cursor_position = self.selections.newest_anchor().head();
2047 let mut context_menu = self.context_menu.borrow_mut();
2048 let completion_menu = match context_menu.as_ref() {
2049 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2050 _ => {
2051 *context_menu = None;
2052 None
2053 }
2054 };
2055 if let Some(buffer_id) = new_cursor_position.buffer_id {
2056 if !self.registered_buffers.contains_key(&buffer_id) {
2057 if let Some(lsp_store) = self.lsp_store(cx) {
2058 lsp_store.update(cx, |lsp_store, cx| {
2059 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2060 return;
2061 };
2062 self.registered_buffers.insert(
2063 buffer_id,
2064 lsp_store.register_buffer_with_language_servers(&buffer, cx),
2065 );
2066 })
2067 }
2068 }
2069 }
2070
2071 if let Some(completion_menu) = completion_menu {
2072 let cursor_position = new_cursor_position.to_offset(buffer);
2073 let (word_range, kind) =
2074 buffer.surrounding_word(completion_menu.initial_position, true);
2075 if kind == Some(CharKind::Word)
2076 && word_range.to_inclusive().contains(&cursor_position)
2077 {
2078 let mut completion_menu = completion_menu.clone();
2079 drop(context_menu);
2080
2081 let query = Self::completion_query(buffer, cursor_position);
2082 cx.spawn(move |this, mut cx| async move {
2083 completion_menu
2084 .filter(query.as_deref(), cx.background_executor().clone())
2085 .await;
2086
2087 this.update(&mut cx, |this, cx| {
2088 let mut context_menu = this.context_menu.borrow_mut();
2089 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2090 else {
2091 return;
2092 };
2093
2094 if menu.id > completion_menu.id {
2095 return;
2096 }
2097
2098 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2099 drop(context_menu);
2100 cx.notify();
2101 })
2102 })
2103 .detach();
2104
2105 if show_completions {
2106 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2107 }
2108 } else {
2109 drop(context_menu);
2110 self.hide_context_menu(window, cx);
2111 }
2112 } else {
2113 drop(context_menu);
2114 }
2115
2116 hide_hover(self, cx);
2117
2118 if old_cursor_position.to_display_point(&display_map).row()
2119 != new_cursor_position.to_display_point(&display_map).row()
2120 {
2121 self.available_code_actions.take();
2122 }
2123 self.refresh_code_actions(window, cx);
2124 self.refresh_document_highlights(cx);
2125 refresh_matching_bracket_highlights(self, window, cx);
2126 self.update_visible_inline_completion(window, cx);
2127 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2128 if self.git_blame_inline_enabled {
2129 self.start_inline_blame_timer(window, cx);
2130 }
2131 }
2132
2133 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2134 cx.emit(EditorEvent::SelectionsChanged { local });
2135
2136 if self.selections.disjoint_anchors().len() == 1 {
2137 cx.emit(SearchEvent::ActiveMatchChanged)
2138 }
2139 cx.notify();
2140 }
2141
2142 pub fn change_selections<R>(
2143 &mut self,
2144 autoscroll: Option<Autoscroll>,
2145 window: &mut Window,
2146 cx: &mut Context<Self>,
2147 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2148 ) -> R {
2149 self.change_selections_inner(autoscroll, true, window, cx, change)
2150 }
2151
2152 pub fn change_selections_inner<R>(
2153 &mut self,
2154 autoscroll: Option<Autoscroll>,
2155 request_completions: bool,
2156 window: &mut Window,
2157 cx: &mut Context<Self>,
2158 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2159 ) -> R {
2160 let old_cursor_position = self.selections.newest_anchor().head();
2161 self.push_to_selection_history();
2162
2163 let (changed, result) = self.selections.change_with(cx, change);
2164
2165 if changed {
2166 if let Some(autoscroll) = autoscroll {
2167 self.request_autoscroll(autoscroll, cx);
2168 }
2169 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2170
2171 if self.should_open_signature_help_automatically(
2172 &old_cursor_position,
2173 self.signature_help_state.backspace_pressed(),
2174 cx,
2175 ) {
2176 self.show_signature_help(&ShowSignatureHelp, window, cx);
2177 }
2178 self.signature_help_state.set_backspace_pressed(false);
2179 }
2180
2181 result
2182 }
2183
2184 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2185 where
2186 I: IntoIterator<Item = (Range<S>, T)>,
2187 S: ToOffset,
2188 T: Into<Arc<str>>,
2189 {
2190 if self.read_only(cx) {
2191 return;
2192 }
2193
2194 self.buffer
2195 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2196 }
2197
2198 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2199 where
2200 I: IntoIterator<Item = (Range<S>, T)>,
2201 S: ToOffset,
2202 T: Into<Arc<str>>,
2203 {
2204 if self.read_only(cx) {
2205 return;
2206 }
2207
2208 self.buffer.update(cx, |buffer, cx| {
2209 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2210 });
2211 }
2212
2213 pub fn edit_with_block_indent<I, S, T>(
2214 &mut self,
2215 edits: I,
2216 original_indent_columns: Vec<u32>,
2217 cx: &mut Context<Self>,
2218 ) where
2219 I: IntoIterator<Item = (Range<S>, T)>,
2220 S: ToOffset,
2221 T: Into<Arc<str>>,
2222 {
2223 if self.read_only(cx) {
2224 return;
2225 }
2226
2227 self.buffer.update(cx, |buffer, cx| {
2228 buffer.edit(
2229 edits,
2230 Some(AutoindentMode::Block {
2231 original_indent_columns,
2232 }),
2233 cx,
2234 )
2235 });
2236 }
2237
2238 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2239 self.hide_context_menu(window, cx);
2240
2241 match phase {
2242 SelectPhase::Begin {
2243 position,
2244 add,
2245 click_count,
2246 } => self.begin_selection(position, add, click_count, window, cx),
2247 SelectPhase::BeginColumnar {
2248 position,
2249 goal_column,
2250 reset,
2251 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2252 SelectPhase::Extend {
2253 position,
2254 click_count,
2255 } => self.extend_selection(position, click_count, window, cx),
2256 SelectPhase::Update {
2257 position,
2258 goal_column,
2259 scroll_delta,
2260 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2261 SelectPhase::End => self.end_selection(window, cx),
2262 }
2263 }
2264
2265 fn extend_selection(
2266 &mut self,
2267 position: DisplayPoint,
2268 click_count: usize,
2269 window: &mut Window,
2270 cx: &mut Context<Self>,
2271 ) {
2272 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2273 let tail = self.selections.newest::<usize>(cx).tail();
2274 self.begin_selection(position, false, click_count, window, cx);
2275
2276 let position = position.to_offset(&display_map, Bias::Left);
2277 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2278
2279 let mut pending_selection = self
2280 .selections
2281 .pending_anchor()
2282 .expect("extend_selection not called with pending selection");
2283 if position >= tail {
2284 pending_selection.start = tail_anchor;
2285 } else {
2286 pending_selection.end = tail_anchor;
2287 pending_selection.reversed = true;
2288 }
2289
2290 let mut pending_mode = self.selections.pending_mode().unwrap();
2291 match &mut pending_mode {
2292 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2293 _ => {}
2294 }
2295
2296 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2297 s.set_pending(pending_selection, pending_mode)
2298 });
2299 }
2300
2301 fn begin_selection(
2302 &mut self,
2303 position: DisplayPoint,
2304 add: bool,
2305 click_count: usize,
2306 window: &mut Window,
2307 cx: &mut Context<Self>,
2308 ) {
2309 if !self.focus_handle.is_focused(window) {
2310 self.last_focused_descendant = None;
2311 window.focus(&self.focus_handle);
2312 }
2313
2314 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2315 let buffer = &display_map.buffer_snapshot;
2316 let newest_selection = self.selections.newest_anchor().clone();
2317 let position = display_map.clip_point(position, Bias::Left);
2318
2319 let start;
2320 let end;
2321 let mode;
2322 let mut auto_scroll;
2323 match click_count {
2324 1 => {
2325 start = buffer.anchor_before(position.to_point(&display_map));
2326 end = start;
2327 mode = SelectMode::Character;
2328 auto_scroll = true;
2329 }
2330 2 => {
2331 let range = movement::surrounding_word(&display_map, position);
2332 start = buffer.anchor_before(range.start.to_point(&display_map));
2333 end = buffer.anchor_before(range.end.to_point(&display_map));
2334 mode = SelectMode::Word(start..end);
2335 auto_scroll = true;
2336 }
2337 3 => {
2338 let position = display_map
2339 .clip_point(position, Bias::Left)
2340 .to_point(&display_map);
2341 let line_start = display_map.prev_line_boundary(position).0;
2342 let next_line_start = buffer.clip_point(
2343 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2344 Bias::Left,
2345 );
2346 start = buffer.anchor_before(line_start);
2347 end = buffer.anchor_before(next_line_start);
2348 mode = SelectMode::Line(start..end);
2349 auto_scroll = true;
2350 }
2351 _ => {
2352 start = buffer.anchor_before(0);
2353 end = buffer.anchor_before(buffer.len());
2354 mode = SelectMode::All;
2355 auto_scroll = false;
2356 }
2357 }
2358 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2359
2360 let point_to_delete: Option<usize> = {
2361 let selected_points: Vec<Selection<Point>> =
2362 self.selections.disjoint_in_range(start..end, cx);
2363
2364 if !add || click_count > 1 {
2365 None
2366 } else if !selected_points.is_empty() {
2367 Some(selected_points[0].id)
2368 } else {
2369 let clicked_point_already_selected =
2370 self.selections.disjoint.iter().find(|selection| {
2371 selection.start.to_point(buffer) == start.to_point(buffer)
2372 || selection.end.to_point(buffer) == end.to_point(buffer)
2373 });
2374
2375 clicked_point_already_selected.map(|selection| selection.id)
2376 }
2377 };
2378
2379 let selections_count = self.selections.count();
2380
2381 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2382 if let Some(point_to_delete) = point_to_delete {
2383 s.delete(point_to_delete);
2384
2385 if selections_count == 1 {
2386 s.set_pending_anchor_range(start..end, mode);
2387 }
2388 } else {
2389 if !add {
2390 s.clear_disjoint();
2391 } else if click_count > 1 {
2392 s.delete(newest_selection.id)
2393 }
2394
2395 s.set_pending_anchor_range(start..end, mode);
2396 }
2397 });
2398 }
2399
2400 fn begin_columnar_selection(
2401 &mut self,
2402 position: DisplayPoint,
2403 goal_column: u32,
2404 reset: bool,
2405 window: &mut Window,
2406 cx: &mut Context<Self>,
2407 ) {
2408 if !self.focus_handle.is_focused(window) {
2409 self.last_focused_descendant = None;
2410 window.focus(&self.focus_handle);
2411 }
2412
2413 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2414
2415 if reset {
2416 let pointer_position = display_map
2417 .buffer_snapshot
2418 .anchor_before(position.to_point(&display_map));
2419
2420 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2421 s.clear_disjoint();
2422 s.set_pending_anchor_range(
2423 pointer_position..pointer_position,
2424 SelectMode::Character,
2425 );
2426 });
2427 }
2428
2429 let tail = self.selections.newest::<Point>(cx).tail();
2430 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2431
2432 if !reset {
2433 self.select_columns(
2434 tail.to_display_point(&display_map),
2435 position,
2436 goal_column,
2437 &display_map,
2438 window,
2439 cx,
2440 );
2441 }
2442 }
2443
2444 fn update_selection(
2445 &mut self,
2446 position: DisplayPoint,
2447 goal_column: u32,
2448 scroll_delta: gpui::Point<f32>,
2449 window: &mut Window,
2450 cx: &mut Context<Self>,
2451 ) {
2452 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2453
2454 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2455 let tail = tail.to_display_point(&display_map);
2456 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2457 } else if let Some(mut pending) = self.selections.pending_anchor() {
2458 let buffer = self.buffer.read(cx).snapshot(cx);
2459 let head;
2460 let tail;
2461 let mode = self.selections.pending_mode().unwrap();
2462 match &mode {
2463 SelectMode::Character => {
2464 head = position.to_point(&display_map);
2465 tail = pending.tail().to_point(&buffer);
2466 }
2467 SelectMode::Word(original_range) => {
2468 let original_display_range = original_range.start.to_display_point(&display_map)
2469 ..original_range.end.to_display_point(&display_map);
2470 let original_buffer_range = original_display_range.start.to_point(&display_map)
2471 ..original_display_range.end.to_point(&display_map);
2472 if movement::is_inside_word(&display_map, position)
2473 || original_display_range.contains(&position)
2474 {
2475 let word_range = movement::surrounding_word(&display_map, position);
2476 if word_range.start < original_display_range.start {
2477 head = word_range.start.to_point(&display_map);
2478 } else {
2479 head = word_range.end.to_point(&display_map);
2480 }
2481 } else {
2482 head = position.to_point(&display_map);
2483 }
2484
2485 if head <= original_buffer_range.start {
2486 tail = original_buffer_range.end;
2487 } else {
2488 tail = original_buffer_range.start;
2489 }
2490 }
2491 SelectMode::Line(original_range) => {
2492 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2493
2494 let position = display_map
2495 .clip_point(position, Bias::Left)
2496 .to_point(&display_map);
2497 let line_start = display_map.prev_line_boundary(position).0;
2498 let next_line_start = buffer.clip_point(
2499 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2500 Bias::Left,
2501 );
2502
2503 if line_start < original_range.start {
2504 head = line_start
2505 } else {
2506 head = next_line_start
2507 }
2508
2509 if head <= original_range.start {
2510 tail = original_range.end;
2511 } else {
2512 tail = original_range.start;
2513 }
2514 }
2515 SelectMode::All => {
2516 return;
2517 }
2518 };
2519
2520 if head < tail {
2521 pending.start = buffer.anchor_before(head);
2522 pending.end = buffer.anchor_before(tail);
2523 pending.reversed = true;
2524 } else {
2525 pending.start = buffer.anchor_before(tail);
2526 pending.end = buffer.anchor_before(head);
2527 pending.reversed = false;
2528 }
2529
2530 self.change_selections(None, window, cx, |s| {
2531 s.set_pending(pending, mode);
2532 });
2533 } else {
2534 log::error!("update_selection dispatched with no pending selection");
2535 return;
2536 }
2537
2538 self.apply_scroll_delta(scroll_delta, window, cx);
2539 cx.notify();
2540 }
2541
2542 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2543 self.columnar_selection_tail.take();
2544 if self.selections.pending_anchor().is_some() {
2545 let selections = self.selections.all::<usize>(cx);
2546 self.change_selections(None, window, cx, |s| {
2547 s.select(selections);
2548 s.clear_pending();
2549 });
2550 }
2551 }
2552
2553 fn select_columns(
2554 &mut self,
2555 tail: DisplayPoint,
2556 head: DisplayPoint,
2557 goal_column: u32,
2558 display_map: &DisplaySnapshot,
2559 window: &mut Window,
2560 cx: &mut Context<Self>,
2561 ) {
2562 let start_row = cmp::min(tail.row(), head.row());
2563 let end_row = cmp::max(tail.row(), head.row());
2564 let start_column = cmp::min(tail.column(), goal_column);
2565 let end_column = cmp::max(tail.column(), goal_column);
2566 let reversed = start_column < tail.column();
2567
2568 let selection_ranges = (start_row.0..=end_row.0)
2569 .map(DisplayRow)
2570 .filter_map(|row| {
2571 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2572 let start = display_map
2573 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2574 .to_point(display_map);
2575 let end = display_map
2576 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2577 .to_point(display_map);
2578 if reversed {
2579 Some(end..start)
2580 } else {
2581 Some(start..end)
2582 }
2583 } else {
2584 None
2585 }
2586 })
2587 .collect::<Vec<_>>();
2588
2589 self.change_selections(None, window, cx, |s| {
2590 s.select_ranges(selection_ranges);
2591 });
2592 cx.notify();
2593 }
2594
2595 pub fn has_pending_nonempty_selection(&self) -> bool {
2596 let pending_nonempty_selection = match self.selections.pending_anchor() {
2597 Some(Selection { start, end, .. }) => start != end,
2598 None => false,
2599 };
2600
2601 pending_nonempty_selection
2602 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2603 }
2604
2605 pub fn has_pending_selection(&self) -> bool {
2606 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2607 }
2608
2609 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2610 self.selection_mark_mode = false;
2611
2612 if self.clear_expanded_diff_hunks(cx) {
2613 cx.notify();
2614 return;
2615 }
2616 if self.dismiss_menus_and_popups(true, window, cx) {
2617 return;
2618 }
2619
2620 if self.mode == EditorMode::Full
2621 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2622 {
2623 return;
2624 }
2625
2626 cx.propagate();
2627 }
2628
2629 pub fn dismiss_menus_and_popups(
2630 &mut self,
2631 is_user_requested: bool,
2632 window: &mut Window,
2633 cx: &mut Context<Self>,
2634 ) -> bool {
2635 if self.take_rename(false, window, cx).is_some() {
2636 return true;
2637 }
2638
2639 if hide_hover(self, cx) {
2640 return true;
2641 }
2642
2643 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2644 return true;
2645 }
2646
2647 if self.hide_context_menu(window, cx).is_some() {
2648 return true;
2649 }
2650
2651 if self.mouse_context_menu.take().is_some() {
2652 return true;
2653 }
2654
2655 if is_user_requested && self.discard_inline_completion(true, cx) {
2656 return true;
2657 }
2658
2659 if self.snippet_stack.pop().is_some() {
2660 return true;
2661 }
2662
2663 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2664 self.dismiss_diagnostics(cx);
2665 return true;
2666 }
2667
2668 false
2669 }
2670
2671 fn linked_editing_ranges_for(
2672 &self,
2673 selection: Range<text::Anchor>,
2674 cx: &App,
2675 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2676 if self.linked_edit_ranges.is_empty() {
2677 return None;
2678 }
2679 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2680 selection.end.buffer_id.and_then(|end_buffer_id| {
2681 if selection.start.buffer_id != Some(end_buffer_id) {
2682 return None;
2683 }
2684 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2685 let snapshot = buffer.read(cx).snapshot();
2686 self.linked_edit_ranges
2687 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2688 .map(|ranges| (ranges, snapshot, buffer))
2689 })?;
2690 use text::ToOffset as TO;
2691 // find offset from the start of current range to current cursor position
2692 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2693
2694 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2695 let start_difference = start_offset - start_byte_offset;
2696 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2697 let end_difference = end_offset - start_byte_offset;
2698 // Current range has associated linked ranges.
2699 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2700 for range in linked_ranges.iter() {
2701 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2702 let end_offset = start_offset + end_difference;
2703 let start_offset = start_offset + start_difference;
2704 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2705 continue;
2706 }
2707 if self.selections.disjoint_anchor_ranges().any(|s| {
2708 if s.start.buffer_id != selection.start.buffer_id
2709 || s.end.buffer_id != selection.end.buffer_id
2710 {
2711 return false;
2712 }
2713 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2714 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2715 }) {
2716 continue;
2717 }
2718 let start = buffer_snapshot.anchor_after(start_offset);
2719 let end = buffer_snapshot.anchor_after(end_offset);
2720 linked_edits
2721 .entry(buffer.clone())
2722 .or_default()
2723 .push(start..end);
2724 }
2725 Some(linked_edits)
2726 }
2727
2728 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2729 let text: Arc<str> = text.into();
2730
2731 if self.read_only(cx) {
2732 return;
2733 }
2734
2735 let selections = self.selections.all_adjusted(cx);
2736 let mut bracket_inserted = false;
2737 let mut edits = Vec::new();
2738 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2739 let mut new_selections = Vec::with_capacity(selections.len());
2740 let mut new_autoclose_regions = Vec::new();
2741 let snapshot = self.buffer.read(cx).read(cx);
2742
2743 for (selection, autoclose_region) in
2744 self.selections_with_autoclose_regions(selections, &snapshot)
2745 {
2746 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2747 // Determine if the inserted text matches the opening or closing
2748 // bracket of any of this language's bracket pairs.
2749 let mut bracket_pair = None;
2750 let mut is_bracket_pair_start = false;
2751 let mut is_bracket_pair_end = false;
2752 if !text.is_empty() {
2753 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2754 // and they are removing the character that triggered IME popup.
2755 for (pair, enabled) in scope.brackets() {
2756 if !pair.close && !pair.surround {
2757 continue;
2758 }
2759
2760 if enabled && pair.start.ends_with(text.as_ref()) {
2761 let prefix_len = pair.start.len() - text.len();
2762 let preceding_text_matches_prefix = prefix_len == 0
2763 || (selection.start.column >= (prefix_len as u32)
2764 && snapshot.contains_str_at(
2765 Point::new(
2766 selection.start.row,
2767 selection.start.column - (prefix_len as u32),
2768 ),
2769 &pair.start[..prefix_len],
2770 ));
2771 if preceding_text_matches_prefix {
2772 bracket_pair = Some(pair.clone());
2773 is_bracket_pair_start = true;
2774 break;
2775 }
2776 }
2777 if pair.end.as_str() == text.as_ref() {
2778 bracket_pair = Some(pair.clone());
2779 is_bracket_pair_end = true;
2780 break;
2781 }
2782 }
2783 }
2784
2785 if let Some(bracket_pair) = bracket_pair {
2786 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2787 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2788 let auto_surround =
2789 self.use_auto_surround && snapshot_settings.use_auto_surround;
2790 if selection.is_empty() {
2791 if is_bracket_pair_start {
2792 // If the inserted text is a suffix of an opening bracket and the
2793 // selection is preceded by the rest of the opening bracket, then
2794 // insert the closing bracket.
2795 let following_text_allows_autoclose = snapshot
2796 .chars_at(selection.start)
2797 .next()
2798 .map_or(true, |c| scope.should_autoclose_before(c));
2799
2800 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2801 && bracket_pair.start.len() == 1
2802 {
2803 let target = bracket_pair.start.chars().next().unwrap();
2804 let current_line_count = snapshot
2805 .reversed_chars_at(selection.start)
2806 .take_while(|&c| c != '\n')
2807 .filter(|&c| c == target)
2808 .count();
2809 current_line_count % 2 == 1
2810 } else {
2811 false
2812 };
2813
2814 if autoclose
2815 && bracket_pair.close
2816 && following_text_allows_autoclose
2817 && !is_closing_quote
2818 {
2819 let anchor = snapshot.anchor_before(selection.end);
2820 new_selections.push((selection.map(|_| anchor), text.len()));
2821 new_autoclose_regions.push((
2822 anchor,
2823 text.len(),
2824 selection.id,
2825 bracket_pair.clone(),
2826 ));
2827 edits.push((
2828 selection.range(),
2829 format!("{}{}", text, bracket_pair.end).into(),
2830 ));
2831 bracket_inserted = true;
2832 continue;
2833 }
2834 }
2835
2836 if let Some(region) = autoclose_region {
2837 // If the selection is followed by an auto-inserted closing bracket,
2838 // then don't insert that closing bracket again; just move the selection
2839 // past the closing bracket.
2840 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2841 && text.as_ref() == region.pair.end.as_str();
2842 if should_skip {
2843 let anchor = snapshot.anchor_after(selection.end);
2844 new_selections
2845 .push((selection.map(|_| anchor), region.pair.end.len()));
2846 continue;
2847 }
2848 }
2849
2850 let always_treat_brackets_as_autoclosed = snapshot
2851 .settings_at(selection.start, cx)
2852 .always_treat_brackets_as_autoclosed;
2853 if always_treat_brackets_as_autoclosed
2854 && is_bracket_pair_end
2855 && snapshot.contains_str_at(selection.end, text.as_ref())
2856 {
2857 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2858 // and the inserted text is a closing bracket and the selection is followed
2859 // by the closing bracket then move the selection past the closing bracket.
2860 let anchor = snapshot.anchor_after(selection.end);
2861 new_selections.push((selection.map(|_| anchor), text.len()));
2862 continue;
2863 }
2864 }
2865 // If an opening bracket is 1 character long and is typed while
2866 // text is selected, then surround that text with the bracket pair.
2867 else if auto_surround
2868 && bracket_pair.surround
2869 && is_bracket_pair_start
2870 && bracket_pair.start.chars().count() == 1
2871 {
2872 edits.push((selection.start..selection.start, text.clone()));
2873 edits.push((
2874 selection.end..selection.end,
2875 bracket_pair.end.as_str().into(),
2876 ));
2877 bracket_inserted = true;
2878 new_selections.push((
2879 Selection {
2880 id: selection.id,
2881 start: snapshot.anchor_after(selection.start),
2882 end: snapshot.anchor_before(selection.end),
2883 reversed: selection.reversed,
2884 goal: selection.goal,
2885 },
2886 0,
2887 ));
2888 continue;
2889 }
2890 }
2891 }
2892
2893 if self.auto_replace_emoji_shortcode
2894 && selection.is_empty()
2895 && text.as_ref().ends_with(':')
2896 {
2897 if let Some(possible_emoji_short_code) =
2898 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2899 {
2900 if !possible_emoji_short_code.is_empty() {
2901 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2902 let emoji_shortcode_start = Point::new(
2903 selection.start.row,
2904 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2905 );
2906
2907 // Remove shortcode from buffer
2908 edits.push((
2909 emoji_shortcode_start..selection.start,
2910 "".to_string().into(),
2911 ));
2912 new_selections.push((
2913 Selection {
2914 id: selection.id,
2915 start: snapshot.anchor_after(emoji_shortcode_start),
2916 end: snapshot.anchor_before(selection.start),
2917 reversed: selection.reversed,
2918 goal: selection.goal,
2919 },
2920 0,
2921 ));
2922
2923 // Insert emoji
2924 let selection_start_anchor = snapshot.anchor_after(selection.start);
2925 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2926 edits.push((selection.start..selection.end, emoji.to_string().into()));
2927
2928 continue;
2929 }
2930 }
2931 }
2932 }
2933
2934 // If not handling any auto-close operation, then just replace the selected
2935 // text with the given input and move the selection to the end of the
2936 // newly inserted text.
2937 let anchor = snapshot.anchor_after(selection.end);
2938 if !self.linked_edit_ranges.is_empty() {
2939 let start_anchor = snapshot.anchor_before(selection.start);
2940
2941 let is_word_char = text.chars().next().map_or(true, |char| {
2942 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2943 classifier.is_word(char)
2944 });
2945
2946 if is_word_char {
2947 if let Some(ranges) = self
2948 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2949 {
2950 for (buffer, edits) in ranges {
2951 linked_edits
2952 .entry(buffer.clone())
2953 .or_default()
2954 .extend(edits.into_iter().map(|range| (range, text.clone())));
2955 }
2956 }
2957 }
2958 }
2959
2960 new_selections.push((selection.map(|_| anchor), 0));
2961 edits.push((selection.start..selection.end, text.clone()));
2962 }
2963
2964 drop(snapshot);
2965
2966 self.transact(window, cx, |this, window, cx| {
2967 this.buffer.update(cx, |buffer, cx| {
2968 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2969 });
2970 for (buffer, edits) in linked_edits {
2971 buffer.update(cx, |buffer, cx| {
2972 let snapshot = buffer.snapshot();
2973 let edits = edits
2974 .into_iter()
2975 .map(|(range, text)| {
2976 use text::ToPoint as TP;
2977 let end_point = TP::to_point(&range.end, &snapshot);
2978 let start_point = TP::to_point(&range.start, &snapshot);
2979 (start_point..end_point, text)
2980 })
2981 .sorted_by_key(|(range, _)| range.start)
2982 .collect::<Vec<_>>();
2983 buffer.edit(edits, None, cx);
2984 })
2985 }
2986 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2987 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2988 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2989 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2990 .zip(new_selection_deltas)
2991 .map(|(selection, delta)| Selection {
2992 id: selection.id,
2993 start: selection.start + delta,
2994 end: selection.end + delta,
2995 reversed: selection.reversed,
2996 goal: SelectionGoal::None,
2997 })
2998 .collect::<Vec<_>>();
2999
3000 let mut i = 0;
3001 for (position, delta, selection_id, pair) in new_autoclose_regions {
3002 let position = position.to_offset(&map.buffer_snapshot) + delta;
3003 let start = map.buffer_snapshot.anchor_before(position);
3004 let end = map.buffer_snapshot.anchor_after(position);
3005 while let Some(existing_state) = this.autoclose_regions.get(i) {
3006 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3007 Ordering::Less => i += 1,
3008 Ordering::Greater => break,
3009 Ordering::Equal => {
3010 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3011 Ordering::Less => i += 1,
3012 Ordering::Equal => break,
3013 Ordering::Greater => break,
3014 }
3015 }
3016 }
3017 }
3018 this.autoclose_regions.insert(
3019 i,
3020 AutocloseRegion {
3021 selection_id,
3022 range: start..end,
3023 pair,
3024 },
3025 );
3026 }
3027
3028 let had_active_inline_completion = this.has_active_inline_completion();
3029 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3030 s.select(new_selections)
3031 });
3032
3033 if !bracket_inserted {
3034 if let Some(on_type_format_task) =
3035 this.trigger_on_type_formatting(text.to_string(), window, cx)
3036 {
3037 on_type_format_task.detach_and_log_err(cx);
3038 }
3039 }
3040
3041 let editor_settings = EditorSettings::get_global(cx);
3042 if bracket_inserted
3043 && (editor_settings.auto_signature_help
3044 || editor_settings.show_signature_help_after_edits)
3045 {
3046 this.show_signature_help(&ShowSignatureHelp, window, cx);
3047 }
3048
3049 let trigger_in_words =
3050 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3051 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3052 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3053 this.refresh_inline_completion(true, false, window, cx);
3054 });
3055 }
3056
3057 fn find_possible_emoji_shortcode_at_position(
3058 snapshot: &MultiBufferSnapshot,
3059 position: Point,
3060 ) -> Option<String> {
3061 let mut chars = Vec::new();
3062 let mut found_colon = false;
3063 for char in snapshot.reversed_chars_at(position).take(100) {
3064 // Found a possible emoji shortcode in the middle of the buffer
3065 if found_colon {
3066 if char.is_whitespace() {
3067 chars.reverse();
3068 return Some(chars.iter().collect());
3069 }
3070 // If the previous character is not a whitespace, we are in the middle of a word
3071 // and we only want to complete the shortcode if the word is made up of other emojis
3072 let mut containing_word = String::new();
3073 for ch in snapshot
3074 .reversed_chars_at(position)
3075 .skip(chars.len() + 1)
3076 .take(100)
3077 {
3078 if ch.is_whitespace() {
3079 break;
3080 }
3081 containing_word.push(ch);
3082 }
3083 let containing_word = containing_word.chars().rev().collect::<String>();
3084 if util::word_consists_of_emojis(containing_word.as_str()) {
3085 chars.reverse();
3086 return Some(chars.iter().collect());
3087 }
3088 }
3089
3090 if char.is_whitespace() || !char.is_ascii() {
3091 return None;
3092 }
3093 if char == ':' {
3094 found_colon = true;
3095 } else {
3096 chars.push(char);
3097 }
3098 }
3099 // Found a possible emoji shortcode at the beginning of the buffer
3100 chars.reverse();
3101 Some(chars.iter().collect())
3102 }
3103
3104 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3105 self.transact(window, cx, |this, window, cx| {
3106 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3107 let selections = this.selections.all::<usize>(cx);
3108 let multi_buffer = this.buffer.read(cx);
3109 let buffer = multi_buffer.snapshot(cx);
3110 selections
3111 .iter()
3112 .map(|selection| {
3113 let start_point = selection.start.to_point(&buffer);
3114 let mut indent =
3115 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3116 indent.len = cmp::min(indent.len, start_point.column);
3117 let start = selection.start;
3118 let end = selection.end;
3119 let selection_is_empty = start == end;
3120 let language_scope = buffer.language_scope_at(start);
3121 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3122 &language_scope
3123 {
3124 let leading_whitespace_len = buffer
3125 .reversed_chars_at(start)
3126 .take_while(|c| c.is_whitespace() && *c != '\n')
3127 .map(|c| c.len_utf8())
3128 .sum::<usize>();
3129
3130 let trailing_whitespace_len = buffer
3131 .chars_at(end)
3132 .take_while(|c| c.is_whitespace() && *c != '\n')
3133 .map(|c| c.len_utf8())
3134 .sum::<usize>();
3135
3136 let insert_extra_newline =
3137 language.brackets().any(|(pair, enabled)| {
3138 let pair_start = pair.start.trim_end();
3139 let pair_end = pair.end.trim_start();
3140
3141 enabled
3142 && pair.newline
3143 && buffer.contains_str_at(
3144 end + trailing_whitespace_len,
3145 pair_end,
3146 )
3147 && buffer.contains_str_at(
3148 (start - leading_whitespace_len)
3149 .saturating_sub(pair_start.len()),
3150 pair_start,
3151 )
3152 });
3153
3154 // Comment extension on newline is allowed only for cursor selections
3155 let comment_delimiter = maybe!({
3156 if !selection_is_empty {
3157 return None;
3158 }
3159
3160 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3161 return None;
3162 }
3163
3164 let delimiters = language.line_comment_prefixes();
3165 let max_len_of_delimiter =
3166 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3167 let (snapshot, range) =
3168 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3169
3170 let mut index_of_first_non_whitespace = 0;
3171 let comment_candidate = snapshot
3172 .chars_for_range(range)
3173 .skip_while(|c| {
3174 let should_skip = c.is_whitespace();
3175 if should_skip {
3176 index_of_first_non_whitespace += 1;
3177 }
3178 should_skip
3179 })
3180 .take(max_len_of_delimiter)
3181 .collect::<String>();
3182 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3183 comment_candidate.starts_with(comment_prefix.as_ref())
3184 })?;
3185 let cursor_is_placed_after_comment_marker =
3186 index_of_first_non_whitespace + comment_prefix.len()
3187 <= start_point.column as usize;
3188 if cursor_is_placed_after_comment_marker {
3189 Some(comment_prefix.clone())
3190 } else {
3191 None
3192 }
3193 });
3194 (comment_delimiter, insert_extra_newline)
3195 } else {
3196 (None, false)
3197 };
3198
3199 let capacity_for_delimiter = comment_delimiter
3200 .as_deref()
3201 .map(str::len)
3202 .unwrap_or_default();
3203 let mut new_text =
3204 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3205 new_text.push('\n');
3206 new_text.extend(indent.chars());
3207 if let Some(delimiter) = &comment_delimiter {
3208 new_text.push_str(delimiter);
3209 }
3210 if insert_extra_newline {
3211 new_text = new_text.repeat(2);
3212 }
3213
3214 let anchor = buffer.anchor_after(end);
3215 let new_selection = selection.map(|_| anchor);
3216 (
3217 (start..end, new_text),
3218 (insert_extra_newline, new_selection),
3219 )
3220 })
3221 .unzip()
3222 };
3223
3224 this.edit_with_autoindent(edits, cx);
3225 let buffer = this.buffer.read(cx).snapshot(cx);
3226 let new_selections = selection_fixup_info
3227 .into_iter()
3228 .map(|(extra_newline_inserted, new_selection)| {
3229 let mut cursor = new_selection.end.to_point(&buffer);
3230 if extra_newline_inserted {
3231 cursor.row -= 1;
3232 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3233 }
3234 new_selection.map(|_| cursor)
3235 })
3236 .collect();
3237
3238 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3239 s.select(new_selections)
3240 });
3241 this.refresh_inline_completion(true, false, window, cx);
3242 });
3243 }
3244
3245 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3246 let buffer = self.buffer.read(cx);
3247 let snapshot = buffer.snapshot(cx);
3248
3249 let mut edits = Vec::new();
3250 let mut rows = Vec::new();
3251
3252 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3253 let cursor = selection.head();
3254 let row = cursor.row;
3255
3256 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3257
3258 let newline = "\n".to_string();
3259 edits.push((start_of_line..start_of_line, newline));
3260
3261 rows.push(row + rows_inserted as u32);
3262 }
3263
3264 self.transact(window, cx, |editor, window, cx| {
3265 editor.edit(edits, cx);
3266
3267 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3268 let mut index = 0;
3269 s.move_cursors_with(|map, _, _| {
3270 let row = rows[index];
3271 index += 1;
3272
3273 let point = Point::new(row, 0);
3274 let boundary = map.next_line_boundary(point).1;
3275 let clipped = map.clip_point(boundary, Bias::Left);
3276
3277 (clipped, SelectionGoal::None)
3278 });
3279 });
3280
3281 let mut indent_edits = Vec::new();
3282 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3283 for row in rows {
3284 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3285 for (row, indent) in indents {
3286 if indent.len == 0 {
3287 continue;
3288 }
3289
3290 let text = match indent.kind {
3291 IndentKind::Space => " ".repeat(indent.len as usize),
3292 IndentKind::Tab => "\t".repeat(indent.len as usize),
3293 };
3294 let point = Point::new(row.0, 0);
3295 indent_edits.push((point..point, text));
3296 }
3297 }
3298 editor.edit(indent_edits, cx);
3299 });
3300 }
3301
3302 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3303 let buffer = self.buffer.read(cx);
3304 let snapshot = buffer.snapshot(cx);
3305
3306 let mut edits = Vec::new();
3307 let mut rows = Vec::new();
3308 let mut rows_inserted = 0;
3309
3310 for selection in self.selections.all_adjusted(cx) {
3311 let cursor = selection.head();
3312 let row = cursor.row;
3313
3314 let point = Point::new(row + 1, 0);
3315 let start_of_line = snapshot.clip_point(point, Bias::Left);
3316
3317 let newline = "\n".to_string();
3318 edits.push((start_of_line..start_of_line, newline));
3319
3320 rows_inserted += 1;
3321 rows.push(row + rows_inserted);
3322 }
3323
3324 self.transact(window, cx, |editor, window, cx| {
3325 editor.edit(edits, cx);
3326
3327 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3328 let mut index = 0;
3329 s.move_cursors_with(|map, _, _| {
3330 let row = rows[index];
3331 index += 1;
3332
3333 let point = Point::new(row, 0);
3334 let boundary = map.next_line_boundary(point).1;
3335 let clipped = map.clip_point(boundary, Bias::Left);
3336
3337 (clipped, SelectionGoal::None)
3338 });
3339 });
3340
3341 let mut indent_edits = Vec::new();
3342 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3343 for row in rows {
3344 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3345 for (row, indent) in indents {
3346 if indent.len == 0 {
3347 continue;
3348 }
3349
3350 let text = match indent.kind {
3351 IndentKind::Space => " ".repeat(indent.len as usize),
3352 IndentKind::Tab => "\t".repeat(indent.len as usize),
3353 };
3354 let point = Point::new(row.0, 0);
3355 indent_edits.push((point..point, text));
3356 }
3357 }
3358 editor.edit(indent_edits, cx);
3359 });
3360 }
3361
3362 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3363 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3364 original_indent_columns: Vec::new(),
3365 });
3366 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3367 }
3368
3369 fn insert_with_autoindent_mode(
3370 &mut self,
3371 text: &str,
3372 autoindent_mode: Option<AutoindentMode>,
3373 window: &mut Window,
3374 cx: &mut Context<Self>,
3375 ) {
3376 if self.read_only(cx) {
3377 return;
3378 }
3379
3380 let text: Arc<str> = text.into();
3381 self.transact(window, cx, |this, window, cx| {
3382 let old_selections = this.selections.all_adjusted(cx);
3383 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3384 let anchors = {
3385 let snapshot = buffer.read(cx);
3386 old_selections
3387 .iter()
3388 .map(|s| {
3389 let anchor = snapshot.anchor_after(s.head());
3390 s.map(|_| anchor)
3391 })
3392 .collect::<Vec<_>>()
3393 };
3394 buffer.edit(
3395 old_selections
3396 .iter()
3397 .map(|s| (s.start..s.end, text.clone())),
3398 autoindent_mode,
3399 cx,
3400 );
3401 anchors
3402 });
3403
3404 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3405 s.select_anchors(selection_anchors);
3406 });
3407
3408 cx.notify();
3409 });
3410 }
3411
3412 fn trigger_completion_on_input(
3413 &mut self,
3414 text: &str,
3415 trigger_in_words: bool,
3416 window: &mut Window,
3417 cx: &mut Context<Self>,
3418 ) {
3419 if self.is_completion_trigger(text, trigger_in_words, cx) {
3420 self.show_completions(
3421 &ShowCompletions {
3422 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3423 },
3424 window,
3425 cx,
3426 );
3427 } else {
3428 self.hide_context_menu(window, cx);
3429 }
3430 }
3431
3432 fn is_completion_trigger(
3433 &self,
3434 text: &str,
3435 trigger_in_words: bool,
3436 cx: &mut Context<Self>,
3437 ) -> bool {
3438 let position = self.selections.newest_anchor().head();
3439 let multibuffer = self.buffer.read(cx);
3440 let Some(buffer) = position
3441 .buffer_id
3442 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3443 else {
3444 return false;
3445 };
3446
3447 if let Some(completion_provider) = &self.completion_provider {
3448 completion_provider.is_completion_trigger(
3449 &buffer,
3450 position.text_anchor,
3451 text,
3452 trigger_in_words,
3453 cx,
3454 )
3455 } else {
3456 false
3457 }
3458 }
3459
3460 /// If any empty selections is touching the start of its innermost containing autoclose
3461 /// region, expand it to select the brackets.
3462 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3463 let selections = self.selections.all::<usize>(cx);
3464 let buffer = self.buffer.read(cx).read(cx);
3465 let new_selections = self
3466 .selections_with_autoclose_regions(selections, &buffer)
3467 .map(|(mut selection, region)| {
3468 if !selection.is_empty() {
3469 return selection;
3470 }
3471
3472 if let Some(region) = region {
3473 let mut range = region.range.to_offset(&buffer);
3474 if selection.start == range.start && range.start >= region.pair.start.len() {
3475 range.start -= region.pair.start.len();
3476 if buffer.contains_str_at(range.start, ®ion.pair.start)
3477 && buffer.contains_str_at(range.end, ®ion.pair.end)
3478 {
3479 range.end += region.pair.end.len();
3480 selection.start = range.start;
3481 selection.end = range.end;
3482
3483 return selection;
3484 }
3485 }
3486 }
3487
3488 let always_treat_brackets_as_autoclosed = buffer
3489 .settings_at(selection.start, cx)
3490 .always_treat_brackets_as_autoclosed;
3491
3492 if !always_treat_brackets_as_autoclosed {
3493 return selection;
3494 }
3495
3496 if let Some(scope) = buffer.language_scope_at(selection.start) {
3497 for (pair, enabled) in scope.brackets() {
3498 if !enabled || !pair.close {
3499 continue;
3500 }
3501
3502 if buffer.contains_str_at(selection.start, &pair.end) {
3503 let pair_start_len = pair.start.len();
3504 if buffer.contains_str_at(
3505 selection.start.saturating_sub(pair_start_len),
3506 &pair.start,
3507 ) {
3508 selection.start -= pair_start_len;
3509 selection.end += pair.end.len();
3510
3511 return selection;
3512 }
3513 }
3514 }
3515 }
3516
3517 selection
3518 })
3519 .collect();
3520
3521 drop(buffer);
3522 self.change_selections(None, window, cx, |selections| {
3523 selections.select(new_selections)
3524 });
3525 }
3526
3527 /// Iterate the given selections, and for each one, find the smallest surrounding
3528 /// autoclose region. This uses the ordering of the selections and the autoclose
3529 /// regions to avoid repeated comparisons.
3530 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3531 &'a self,
3532 selections: impl IntoIterator<Item = Selection<D>>,
3533 buffer: &'a MultiBufferSnapshot,
3534 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3535 let mut i = 0;
3536 let mut regions = self.autoclose_regions.as_slice();
3537 selections.into_iter().map(move |selection| {
3538 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3539
3540 let mut enclosing = None;
3541 while let Some(pair_state) = regions.get(i) {
3542 if pair_state.range.end.to_offset(buffer) < range.start {
3543 regions = ®ions[i + 1..];
3544 i = 0;
3545 } else if pair_state.range.start.to_offset(buffer) > range.end {
3546 break;
3547 } else {
3548 if pair_state.selection_id == selection.id {
3549 enclosing = Some(pair_state);
3550 }
3551 i += 1;
3552 }
3553 }
3554
3555 (selection, enclosing)
3556 })
3557 }
3558
3559 /// Remove any autoclose regions that no longer contain their selection.
3560 fn invalidate_autoclose_regions(
3561 &mut self,
3562 mut selections: &[Selection<Anchor>],
3563 buffer: &MultiBufferSnapshot,
3564 ) {
3565 self.autoclose_regions.retain(|state| {
3566 let mut i = 0;
3567 while let Some(selection) = selections.get(i) {
3568 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3569 selections = &selections[1..];
3570 continue;
3571 }
3572 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3573 break;
3574 }
3575 if selection.id == state.selection_id {
3576 return true;
3577 } else {
3578 i += 1;
3579 }
3580 }
3581 false
3582 });
3583 }
3584
3585 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3586 let offset = position.to_offset(buffer);
3587 let (word_range, kind) = buffer.surrounding_word(offset, true);
3588 if offset > word_range.start && kind == Some(CharKind::Word) {
3589 Some(
3590 buffer
3591 .text_for_range(word_range.start..offset)
3592 .collect::<String>(),
3593 )
3594 } else {
3595 None
3596 }
3597 }
3598
3599 pub fn toggle_inlay_hints(
3600 &mut self,
3601 _: &ToggleInlayHints,
3602 _: &mut Window,
3603 cx: &mut Context<Self>,
3604 ) {
3605 self.refresh_inlay_hints(
3606 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3607 cx,
3608 );
3609 }
3610
3611 pub fn inlay_hints_enabled(&self) -> bool {
3612 self.inlay_hint_cache.enabled
3613 }
3614
3615 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3616 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3617 return;
3618 }
3619
3620 let reason_description = reason.description();
3621 let ignore_debounce = matches!(
3622 reason,
3623 InlayHintRefreshReason::SettingsChange(_)
3624 | InlayHintRefreshReason::Toggle(_)
3625 | InlayHintRefreshReason::ExcerptsRemoved(_)
3626 );
3627 let (invalidate_cache, required_languages) = match reason {
3628 InlayHintRefreshReason::Toggle(enabled) => {
3629 self.inlay_hint_cache.enabled = enabled;
3630 if enabled {
3631 (InvalidationStrategy::RefreshRequested, None)
3632 } else {
3633 self.inlay_hint_cache.clear();
3634 self.splice_inlays(
3635 &self
3636 .visible_inlay_hints(cx)
3637 .iter()
3638 .map(|inlay| inlay.id)
3639 .collect::<Vec<InlayId>>(),
3640 Vec::new(),
3641 cx,
3642 );
3643 return;
3644 }
3645 }
3646 InlayHintRefreshReason::SettingsChange(new_settings) => {
3647 match self.inlay_hint_cache.update_settings(
3648 &self.buffer,
3649 new_settings,
3650 self.visible_inlay_hints(cx),
3651 cx,
3652 ) {
3653 ControlFlow::Break(Some(InlaySplice {
3654 to_remove,
3655 to_insert,
3656 })) => {
3657 self.splice_inlays(&to_remove, to_insert, cx);
3658 return;
3659 }
3660 ControlFlow::Break(None) => return,
3661 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3662 }
3663 }
3664 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3665 if let Some(InlaySplice {
3666 to_remove,
3667 to_insert,
3668 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3669 {
3670 self.splice_inlays(&to_remove, to_insert, cx);
3671 }
3672 return;
3673 }
3674 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3675 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3676 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3677 }
3678 InlayHintRefreshReason::RefreshRequested => {
3679 (InvalidationStrategy::RefreshRequested, None)
3680 }
3681 };
3682
3683 if let Some(InlaySplice {
3684 to_remove,
3685 to_insert,
3686 }) = self.inlay_hint_cache.spawn_hint_refresh(
3687 reason_description,
3688 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3689 invalidate_cache,
3690 ignore_debounce,
3691 cx,
3692 ) {
3693 self.splice_inlays(&to_remove, to_insert, cx);
3694 }
3695 }
3696
3697 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3698 self.display_map
3699 .read(cx)
3700 .current_inlays()
3701 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3702 .cloned()
3703 .collect()
3704 }
3705
3706 pub fn excerpts_for_inlay_hints_query(
3707 &self,
3708 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3709 cx: &mut Context<Editor>,
3710 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3711 let Some(project) = self.project.as_ref() else {
3712 return HashMap::default();
3713 };
3714 let project = project.read(cx);
3715 let multi_buffer = self.buffer().read(cx);
3716 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3717 let multi_buffer_visible_start = self
3718 .scroll_manager
3719 .anchor()
3720 .anchor
3721 .to_point(&multi_buffer_snapshot);
3722 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3723 multi_buffer_visible_start
3724 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3725 Bias::Left,
3726 );
3727 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3728 multi_buffer_snapshot
3729 .range_to_buffer_ranges(multi_buffer_visible_range)
3730 .into_iter()
3731 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3732 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3733 let buffer_file = project::File::from_dyn(buffer.file())?;
3734 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3735 let worktree_entry = buffer_worktree
3736 .read(cx)
3737 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3738 if worktree_entry.is_ignored {
3739 return None;
3740 }
3741
3742 let language = buffer.language()?;
3743 if let Some(restrict_to_languages) = restrict_to_languages {
3744 if !restrict_to_languages.contains(language) {
3745 return None;
3746 }
3747 }
3748 Some((
3749 excerpt_id,
3750 (
3751 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3752 buffer.version().clone(),
3753 excerpt_visible_range,
3754 ),
3755 ))
3756 })
3757 .collect()
3758 }
3759
3760 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3761 TextLayoutDetails {
3762 text_system: window.text_system().clone(),
3763 editor_style: self.style.clone().unwrap(),
3764 rem_size: window.rem_size(),
3765 scroll_anchor: self.scroll_manager.anchor(),
3766 visible_rows: self.visible_line_count(),
3767 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3768 }
3769 }
3770
3771 pub fn splice_inlays(
3772 &self,
3773 to_remove: &[InlayId],
3774 to_insert: Vec<Inlay>,
3775 cx: &mut Context<Self>,
3776 ) {
3777 self.display_map.update(cx, |display_map, cx| {
3778 display_map.splice_inlays(to_remove, to_insert, cx)
3779 });
3780 cx.notify();
3781 }
3782
3783 fn trigger_on_type_formatting(
3784 &self,
3785 input: String,
3786 window: &mut Window,
3787 cx: &mut Context<Self>,
3788 ) -> Option<Task<Result<()>>> {
3789 if input.len() != 1 {
3790 return None;
3791 }
3792
3793 let project = self.project.as_ref()?;
3794 let position = self.selections.newest_anchor().head();
3795 let (buffer, buffer_position) = self
3796 .buffer
3797 .read(cx)
3798 .text_anchor_for_position(position, cx)?;
3799
3800 let settings = language_settings::language_settings(
3801 buffer
3802 .read(cx)
3803 .language_at(buffer_position)
3804 .map(|l| l.name()),
3805 buffer.read(cx).file(),
3806 cx,
3807 );
3808 if !settings.use_on_type_format {
3809 return None;
3810 }
3811
3812 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3813 // hence we do LSP request & edit on host side only — add formats to host's history.
3814 let push_to_lsp_host_history = true;
3815 // If this is not the host, append its history with new edits.
3816 let push_to_client_history = project.read(cx).is_via_collab();
3817
3818 let on_type_formatting = project.update(cx, |project, cx| {
3819 project.on_type_format(
3820 buffer.clone(),
3821 buffer_position,
3822 input,
3823 push_to_lsp_host_history,
3824 cx,
3825 )
3826 });
3827 Some(cx.spawn_in(window, |editor, mut cx| async move {
3828 if let Some(transaction) = on_type_formatting.await? {
3829 if push_to_client_history {
3830 buffer
3831 .update(&mut cx, |buffer, _| {
3832 buffer.push_transaction(transaction, Instant::now());
3833 })
3834 .ok();
3835 }
3836 editor.update(&mut cx, |editor, cx| {
3837 editor.refresh_document_highlights(cx);
3838 })?;
3839 }
3840 Ok(())
3841 }))
3842 }
3843
3844 pub fn show_completions(
3845 &mut self,
3846 options: &ShowCompletions,
3847 window: &mut Window,
3848 cx: &mut Context<Self>,
3849 ) {
3850 if self.pending_rename.is_some() {
3851 return;
3852 }
3853
3854 let Some(provider) = self.completion_provider.as_ref() else {
3855 return;
3856 };
3857
3858 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3859 return;
3860 }
3861
3862 let position = self.selections.newest_anchor().head();
3863 if position.diff_base_anchor.is_some() {
3864 return;
3865 }
3866 let (buffer, buffer_position) =
3867 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3868 output
3869 } else {
3870 return;
3871 };
3872 let show_completion_documentation = buffer
3873 .read(cx)
3874 .snapshot()
3875 .settings_at(buffer_position, cx)
3876 .show_completion_documentation;
3877
3878 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3879
3880 let trigger_kind = match &options.trigger {
3881 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3882 CompletionTriggerKind::TRIGGER_CHARACTER
3883 }
3884 _ => CompletionTriggerKind::INVOKED,
3885 };
3886 let completion_context = CompletionContext {
3887 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3888 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3889 Some(String::from(trigger))
3890 } else {
3891 None
3892 }
3893 }),
3894 trigger_kind,
3895 };
3896 let completions =
3897 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3898 let sort_completions = provider.sort_completions();
3899
3900 let id = post_inc(&mut self.next_completion_id);
3901 let task = cx.spawn_in(window, |editor, mut cx| {
3902 async move {
3903 editor.update(&mut cx, |this, _| {
3904 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3905 })?;
3906 let completions = completions.await.log_err();
3907 let menu = if let Some(completions) = completions {
3908 let mut menu = CompletionsMenu::new(
3909 id,
3910 sort_completions,
3911 show_completion_documentation,
3912 position,
3913 buffer.clone(),
3914 completions.into(),
3915 );
3916
3917 menu.filter(query.as_deref(), cx.background_executor().clone())
3918 .await;
3919
3920 menu.visible().then_some(menu)
3921 } else {
3922 None
3923 };
3924
3925 editor.update_in(&mut cx, |editor, window, cx| {
3926 match editor.context_menu.borrow().as_ref() {
3927 None => {}
3928 Some(CodeContextMenu::Completions(prev_menu)) => {
3929 if prev_menu.id > id {
3930 return;
3931 }
3932 }
3933 _ => return,
3934 }
3935
3936 if editor.focus_handle.is_focused(window) && menu.is_some() {
3937 let mut menu = menu.unwrap();
3938 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3939
3940 *editor.context_menu.borrow_mut() =
3941 Some(CodeContextMenu::Completions(menu));
3942
3943 if editor.show_edit_predictions_in_menu() {
3944 editor.update_visible_inline_completion(window, cx);
3945 } else {
3946 editor.discard_inline_completion(false, cx);
3947 }
3948
3949 cx.notify();
3950 } else if editor.completion_tasks.len() <= 1 {
3951 // If there are no more completion tasks and the last menu was
3952 // empty, we should hide it.
3953 let was_hidden = editor.hide_context_menu(window, cx).is_none();
3954 // If it was already hidden and we don't show inline
3955 // completions in the menu, we should also show the
3956 // inline-completion when available.
3957 if was_hidden && editor.show_edit_predictions_in_menu() {
3958 editor.update_visible_inline_completion(window, cx);
3959 }
3960 }
3961 })?;
3962
3963 Ok::<_, anyhow::Error>(())
3964 }
3965 .log_err()
3966 });
3967
3968 self.completion_tasks.push((id, task));
3969 }
3970
3971 pub fn confirm_completion(
3972 &mut self,
3973 action: &ConfirmCompletion,
3974 window: &mut Window,
3975 cx: &mut Context<Self>,
3976 ) -> Option<Task<Result<()>>> {
3977 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
3978 }
3979
3980 pub fn compose_completion(
3981 &mut self,
3982 action: &ComposeCompletion,
3983 window: &mut Window,
3984 cx: &mut Context<Self>,
3985 ) -> Option<Task<Result<()>>> {
3986 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
3987 }
3988
3989 fn do_completion(
3990 &mut self,
3991 item_ix: Option<usize>,
3992 intent: CompletionIntent,
3993 window: &mut Window,
3994 cx: &mut Context<Editor>,
3995 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3996 use language::ToOffset as _;
3997
3998 let completions_menu =
3999 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4000 menu
4001 } else {
4002 return None;
4003 };
4004
4005 let entries = completions_menu.entries.borrow();
4006 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4007 if self.show_edit_predictions_in_menu() {
4008 self.discard_inline_completion(true, cx);
4009 }
4010 let candidate_id = mat.candidate_id;
4011 drop(entries);
4012
4013 let buffer_handle = completions_menu.buffer;
4014 let completion = completions_menu
4015 .completions
4016 .borrow()
4017 .get(candidate_id)?
4018 .clone();
4019 cx.stop_propagation();
4020
4021 let snippet;
4022 let text;
4023
4024 if completion.is_snippet() {
4025 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4026 text = snippet.as_ref().unwrap().text.clone();
4027 } else {
4028 snippet = None;
4029 text = completion.new_text.clone();
4030 };
4031 let selections = self.selections.all::<usize>(cx);
4032 let buffer = buffer_handle.read(cx);
4033 let old_range = completion.old_range.to_offset(buffer);
4034 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4035
4036 let newest_selection = self.selections.newest_anchor();
4037 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4038 return None;
4039 }
4040
4041 let lookbehind = newest_selection
4042 .start
4043 .text_anchor
4044 .to_offset(buffer)
4045 .saturating_sub(old_range.start);
4046 let lookahead = old_range
4047 .end
4048 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4049 let mut common_prefix_len = old_text
4050 .bytes()
4051 .zip(text.bytes())
4052 .take_while(|(a, b)| a == b)
4053 .count();
4054
4055 let snapshot = self.buffer.read(cx).snapshot(cx);
4056 let mut range_to_replace: Option<Range<isize>> = None;
4057 let mut ranges = Vec::new();
4058 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4059 for selection in &selections {
4060 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4061 let start = selection.start.saturating_sub(lookbehind);
4062 let end = selection.end + lookahead;
4063 if selection.id == newest_selection.id {
4064 range_to_replace = Some(
4065 ((start + common_prefix_len) as isize - selection.start as isize)
4066 ..(end as isize - selection.start as isize),
4067 );
4068 }
4069 ranges.push(start + common_prefix_len..end);
4070 } else {
4071 common_prefix_len = 0;
4072 ranges.clear();
4073 ranges.extend(selections.iter().map(|s| {
4074 if s.id == newest_selection.id {
4075 range_to_replace = Some(
4076 old_range.start.to_offset_utf16(&snapshot).0 as isize
4077 - selection.start as isize
4078 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4079 - selection.start as isize,
4080 );
4081 old_range.clone()
4082 } else {
4083 s.start..s.end
4084 }
4085 }));
4086 break;
4087 }
4088 if !self.linked_edit_ranges.is_empty() {
4089 let start_anchor = snapshot.anchor_before(selection.head());
4090 let end_anchor = snapshot.anchor_after(selection.tail());
4091 if let Some(ranges) = self
4092 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4093 {
4094 for (buffer, edits) in ranges {
4095 linked_edits.entry(buffer.clone()).or_default().extend(
4096 edits
4097 .into_iter()
4098 .map(|range| (range, text[common_prefix_len..].to_owned())),
4099 );
4100 }
4101 }
4102 }
4103 }
4104 let text = &text[common_prefix_len..];
4105
4106 cx.emit(EditorEvent::InputHandled {
4107 utf16_range_to_replace: range_to_replace,
4108 text: text.into(),
4109 });
4110
4111 self.transact(window, cx, |this, window, cx| {
4112 if let Some(mut snippet) = snippet {
4113 snippet.text = text.to_string();
4114 for tabstop in snippet
4115 .tabstops
4116 .iter_mut()
4117 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4118 {
4119 tabstop.start -= common_prefix_len as isize;
4120 tabstop.end -= common_prefix_len as isize;
4121 }
4122
4123 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4124 } else {
4125 this.buffer.update(cx, |buffer, cx| {
4126 buffer.edit(
4127 ranges.iter().map(|range| (range.clone(), text)),
4128 this.autoindent_mode.clone(),
4129 cx,
4130 );
4131 });
4132 }
4133 for (buffer, edits) in linked_edits {
4134 buffer.update(cx, |buffer, cx| {
4135 let snapshot = buffer.snapshot();
4136 let edits = edits
4137 .into_iter()
4138 .map(|(range, text)| {
4139 use text::ToPoint as TP;
4140 let end_point = TP::to_point(&range.end, &snapshot);
4141 let start_point = TP::to_point(&range.start, &snapshot);
4142 (start_point..end_point, text)
4143 })
4144 .sorted_by_key(|(range, _)| range.start)
4145 .collect::<Vec<_>>();
4146 buffer.edit(edits, None, cx);
4147 })
4148 }
4149
4150 this.refresh_inline_completion(true, false, window, cx);
4151 });
4152
4153 let show_new_completions_on_confirm = completion
4154 .confirm
4155 .as_ref()
4156 .map_or(false, |confirm| confirm(intent, window, cx));
4157 if show_new_completions_on_confirm {
4158 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4159 }
4160
4161 let provider = self.completion_provider.as_ref()?;
4162 drop(completion);
4163 let apply_edits = provider.apply_additional_edits_for_completion(
4164 buffer_handle,
4165 completions_menu.completions.clone(),
4166 candidate_id,
4167 true,
4168 cx,
4169 );
4170
4171 let editor_settings = EditorSettings::get_global(cx);
4172 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4173 // After the code completion is finished, users often want to know what signatures are needed.
4174 // so we should automatically call signature_help
4175 self.show_signature_help(&ShowSignatureHelp, window, cx);
4176 }
4177
4178 Some(cx.foreground_executor().spawn(async move {
4179 apply_edits.await?;
4180 Ok(())
4181 }))
4182 }
4183
4184 pub fn toggle_code_actions(
4185 &mut self,
4186 action: &ToggleCodeActions,
4187 window: &mut Window,
4188 cx: &mut Context<Self>,
4189 ) {
4190 let mut context_menu = self.context_menu.borrow_mut();
4191 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4192 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4193 // Toggle if we're selecting the same one
4194 *context_menu = None;
4195 cx.notify();
4196 return;
4197 } else {
4198 // Otherwise, clear it and start a new one
4199 *context_menu = None;
4200 cx.notify();
4201 }
4202 }
4203 drop(context_menu);
4204 let snapshot = self.snapshot(window, cx);
4205 let deployed_from_indicator = action.deployed_from_indicator;
4206 let mut task = self.code_actions_task.take();
4207 let action = action.clone();
4208 cx.spawn_in(window, |editor, mut cx| async move {
4209 while let Some(prev_task) = task {
4210 prev_task.await.log_err();
4211 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4212 }
4213
4214 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4215 if editor.focus_handle.is_focused(window) {
4216 let multibuffer_point = action
4217 .deployed_from_indicator
4218 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4219 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4220 let (buffer, buffer_row) = snapshot
4221 .buffer_snapshot
4222 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4223 .and_then(|(buffer_snapshot, range)| {
4224 editor
4225 .buffer
4226 .read(cx)
4227 .buffer(buffer_snapshot.remote_id())
4228 .map(|buffer| (buffer, range.start.row))
4229 })?;
4230 let (_, code_actions) = editor
4231 .available_code_actions
4232 .clone()
4233 .and_then(|(location, code_actions)| {
4234 let snapshot = location.buffer.read(cx).snapshot();
4235 let point_range = location.range.to_point(&snapshot);
4236 let point_range = point_range.start.row..=point_range.end.row;
4237 if point_range.contains(&buffer_row) {
4238 Some((location, code_actions))
4239 } else {
4240 None
4241 }
4242 })
4243 .unzip();
4244 let buffer_id = buffer.read(cx).remote_id();
4245 let tasks = editor
4246 .tasks
4247 .get(&(buffer_id, buffer_row))
4248 .map(|t| Arc::new(t.to_owned()));
4249 if tasks.is_none() && code_actions.is_none() {
4250 return None;
4251 }
4252
4253 editor.completion_tasks.clear();
4254 editor.discard_inline_completion(false, cx);
4255 let task_context =
4256 tasks
4257 .as_ref()
4258 .zip(editor.project.clone())
4259 .map(|(tasks, project)| {
4260 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4261 });
4262
4263 Some(cx.spawn_in(window, |editor, mut cx| async move {
4264 let task_context = match task_context {
4265 Some(task_context) => task_context.await,
4266 None => None,
4267 };
4268 let resolved_tasks =
4269 tasks.zip(task_context).map(|(tasks, task_context)| {
4270 Rc::new(ResolvedTasks {
4271 templates: tasks.resolve(&task_context).collect(),
4272 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4273 multibuffer_point.row,
4274 tasks.column,
4275 )),
4276 })
4277 });
4278 let spawn_straight_away = resolved_tasks
4279 .as_ref()
4280 .map_or(false, |tasks| tasks.templates.len() == 1)
4281 && code_actions
4282 .as_ref()
4283 .map_or(true, |actions| actions.is_empty());
4284 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4285 *editor.context_menu.borrow_mut() =
4286 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4287 buffer,
4288 actions: CodeActionContents {
4289 tasks: resolved_tasks,
4290 actions: code_actions,
4291 },
4292 selected_item: Default::default(),
4293 scroll_handle: UniformListScrollHandle::default(),
4294 deployed_from_indicator,
4295 }));
4296 if spawn_straight_away {
4297 if let Some(task) = editor.confirm_code_action(
4298 &ConfirmCodeAction { item_ix: Some(0) },
4299 window,
4300 cx,
4301 ) {
4302 cx.notify();
4303 return task;
4304 }
4305 }
4306 cx.notify();
4307 Task::ready(Ok(()))
4308 }) {
4309 task.await
4310 } else {
4311 Ok(())
4312 }
4313 }))
4314 } else {
4315 Some(Task::ready(Ok(())))
4316 }
4317 })?;
4318 if let Some(task) = spawned_test_task {
4319 task.await?;
4320 }
4321
4322 Ok::<_, anyhow::Error>(())
4323 })
4324 .detach_and_log_err(cx);
4325 }
4326
4327 pub fn confirm_code_action(
4328 &mut self,
4329 action: &ConfirmCodeAction,
4330 window: &mut Window,
4331 cx: &mut Context<Self>,
4332 ) -> Option<Task<Result<()>>> {
4333 let actions_menu =
4334 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4335 menu
4336 } else {
4337 return None;
4338 };
4339 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4340 let action = actions_menu.actions.get(action_ix)?;
4341 let title = action.label();
4342 let buffer = actions_menu.buffer;
4343 let workspace = self.workspace()?;
4344
4345 match action {
4346 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4347 workspace.update(cx, |workspace, cx| {
4348 workspace::tasks::schedule_resolved_task(
4349 workspace,
4350 task_source_kind,
4351 resolved_task,
4352 false,
4353 cx,
4354 );
4355
4356 Some(Task::ready(Ok(())))
4357 })
4358 }
4359 CodeActionsItem::CodeAction {
4360 excerpt_id,
4361 action,
4362 provider,
4363 } => {
4364 let apply_code_action =
4365 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4366 let workspace = workspace.downgrade();
4367 Some(cx.spawn_in(window, |editor, cx| async move {
4368 let project_transaction = apply_code_action.await?;
4369 Self::open_project_transaction(
4370 &editor,
4371 workspace,
4372 project_transaction,
4373 title,
4374 cx,
4375 )
4376 .await
4377 }))
4378 }
4379 }
4380 }
4381
4382 pub async fn open_project_transaction(
4383 this: &WeakEntity<Editor>,
4384 workspace: WeakEntity<Workspace>,
4385 transaction: ProjectTransaction,
4386 title: String,
4387 mut cx: AsyncWindowContext,
4388 ) -> Result<()> {
4389 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4390 cx.update(|_, cx| {
4391 entries.sort_unstable_by_key(|(buffer, _)| {
4392 buffer.read(cx).file().map(|f| f.path().clone())
4393 });
4394 })?;
4395
4396 // If the project transaction's edits are all contained within this editor, then
4397 // avoid opening a new editor to display them.
4398
4399 if let Some((buffer, transaction)) = entries.first() {
4400 if entries.len() == 1 {
4401 let excerpt = this.update(&mut cx, |editor, cx| {
4402 editor
4403 .buffer()
4404 .read(cx)
4405 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4406 })?;
4407 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4408 if excerpted_buffer == *buffer {
4409 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4410 let excerpt_range = excerpt_range.to_offset(buffer);
4411 buffer
4412 .edited_ranges_for_transaction::<usize>(transaction)
4413 .all(|range| {
4414 excerpt_range.start <= range.start
4415 && excerpt_range.end >= range.end
4416 })
4417 })?;
4418
4419 if all_edits_within_excerpt {
4420 return Ok(());
4421 }
4422 }
4423 }
4424 }
4425 } else {
4426 return Ok(());
4427 }
4428
4429 let mut ranges_to_highlight = Vec::new();
4430 let excerpt_buffer = cx.new(|cx| {
4431 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4432 for (buffer_handle, transaction) in &entries {
4433 let buffer = buffer_handle.read(cx);
4434 ranges_to_highlight.extend(
4435 multibuffer.push_excerpts_with_context_lines(
4436 buffer_handle.clone(),
4437 buffer
4438 .edited_ranges_for_transaction::<usize>(transaction)
4439 .collect(),
4440 DEFAULT_MULTIBUFFER_CONTEXT,
4441 cx,
4442 ),
4443 );
4444 }
4445 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4446 multibuffer
4447 })?;
4448
4449 workspace.update_in(&mut cx, |workspace, window, cx| {
4450 let project = workspace.project().clone();
4451 let editor = cx
4452 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4453 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4454 editor.update(cx, |editor, cx| {
4455 editor.highlight_background::<Self>(
4456 &ranges_to_highlight,
4457 |theme| theme.editor_highlighted_line_background,
4458 cx,
4459 );
4460 });
4461 })?;
4462
4463 Ok(())
4464 }
4465
4466 pub fn clear_code_action_providers(&mut self) {
4467 self.code_action_providers.clear();
4468 self.available_code_actions.take();
4469 }
4470
4471 pub fn add_code_action_provider(
4472 &mut self,
4473 provider: Rc<dyn CodeActionProvider>,
4474 window: &mut Window,
4475 cx: &mut Context<Self>,
4476 ) {
4477 if self
4478 .code_action_providers
4479 .iter()
4480 .any(|existing_provider| existing_provider.id() == provider.id())
4481 {
4482 return;
4483 }
4484
4485 self.code_action_providers.push(provider);
4486 self.refresh_code_actions(window, cx);
4487 }
4488
4489 pub fn remove_code_action_provider(
4490 &mut self,
4491 id: Arc<str>,
4492 window: &mut Window,
4493 cx: &mut Context<Self>,
4494 ) {
4495 self.code_action_providers
4496 .retain(|provider| provider.id() != id);
4497 self.refresh_code_actions(window, cx);
4498 }
4499
4500 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4501 let buffer = self.buffer.read(cx);
4502 let newest_selection = self.selections.newest_anchor().clone();
4503 if newest_selection.head().diff_base_anchor.is_some() {
4504 return None;
4505 }
4506 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4507 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4508 if start_buffer != end_buffer {
4509 return None;
4510 }
4511
4512 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4513 cx.background_executor()
4514 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4515 .await;
4516
4517 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4518 let providers = this.code_action_providers.clone();
4519 let tasks = this
4520 .code_action_providers
4521 .iter()
4522 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4523 .collect::<Vec<_>>();
4524 (providers, tasks)
4525 })?;
4526
4527 let mut actions = Vec::new();
4528 for (provider, provider_actions) in
4529 providers.into_iter().zip(future::join_all(tasks).await)
4530 {
4531 if let Some(provider_actions) = provider_actions.log_err() {
4532 actions.extend(provider_actions.into_iter().map(|action| {
4533 AvailableCodeAction {
4534 excerpt_id: newest_selection.start.excerpt_id,
4535 action,
4536 provider: provider.clone(),
4537 }
4538 }));
4539 }
4540 }
4541
4542 this.update(&mut cx, |this, cx| {
4543 this.available_code_actions = if actions.is_empty() {
4544 None
4545 } else {
4546 Some((
4547 Location {
4548 buffer: start_buffer,
4549 range: start..end,
4550 },
4551 actions.into(),
4552 ))
4553 };
4554 cx.notify();
4555 })
4556 }));
4557 None
4558 }
4559
4560 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4561 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4562 self.show_git_blame_inline = false;
4563
4564 self.show_git_blame_inline_delay_task =
4565 Some(cx.spawn_in(window, |this, mut cx| async move {
4566 cx.background_executor().timer(delay).await;
4567
4568 this.update(&mut cx, |this, cx| {
4569 this.show_git_blame_inline = true;
4570 cx.notify();
4571 })
4572 .log_err();
4573 }));
4574 }
4575 }
4576
4577 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4578 if self.pending_rename.is_some() {
4579 return None;
4580 }
4581
4582 let provider = self.semantics_provider.clone()?;
4583 let buffer = self.buffer.read(cx);
4584 let newest_selection = self.selections.newest_anchor().clone();
4585 let cursor_position = newest_selection.head();
4586 let (cursor_buffer, cursor_buffer_position) =
4587 buffer.text_anchor_for_position(cursor_position, cx)?;
4588 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4589 if cursor_buffer != tail_buffer {
4590 return None;
4591 }
4592 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4593 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4594 cx.background_executor()
4595 .timer(Duration::from_millis(debounce))
4596 .await;
4597
4598 let highlights = if let Some(highlights) = cx
4599 .update(|cx| {
4600 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4601 })
4602 .ok()
4603 .flatten()
4604 {
4605 highlights.await.log_err()
4606 } else {
4607 None
4608 };
4609
4610 if let Some(highlights) = highlights {
4611 this.update(&mut cx, |this, cx| {
4612 if this.pending_rename.is_some() {
4613 return;
4614 }
4615
4616 let buffer_id = cursor_position.buffer_id;
4617 let buffer = this.buffer.read(cx);
4618 if !buffer
4619 .text_anchor_for_position(cursor_position, cx)
4620 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4621 {
4622 return;
4623 }
4624
4625 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4626 let mut write_ranges = Vec::new();
4627 let mut read_ranges = Vec::new();
4628 for highlight in highlights {
4629 for (excerpt_id, excerpt_range) in
4630 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4631 {
4632 let start = highlight
4633 .range
4634 .start
4635 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4636 let end = highlight
4637 .range
4638 .end
4639 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4640 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4641 continue;
4642 }
4643
4644 let range = Anchor {
4645 buffer_id,
4646 excerpt_id,
4647 text_anchor: start,
4648 diff_base_anchor: None,
4649 }..Anchor {
4650 buffer_id,
4651 excerpt_id,
4652 text_anchor: end,
4653 diff_base_anchor: None,
4654 };
4655 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4656 write_ranges.push(range);
4657 } else {
4658 read_ranges.push(range);
4659 }
4660 }
4661 }
4662
4663 this.highlight_background::<DocumentHighlightRead>(
4664 &read_ranges,
4665 |theme| theme.editor_document_highlight_read_background,
4666 cx,
4667 );
4668 this.highlight_background::<DocumentHighlightWrite>(
4669 &write_ranges,
4670 |theme| theme.editor_document_highlight_write_background,
4671 cx,
4672 );
4673 cx.notify();
4674 })
4675 .log_err();
4676 }
4677 }));
4678 None
4679 }
4680
4681 pub fn refresh_inline_completion(
4682 &mut self,
4683 debounce: bool,
4684 user_requested: bool,
4685 window: &mut Window,
4686 cx: &mut Context<Self>,
4687 ) -> Option<()> {
4688 let provider = self.edit_prediction_provider()?;
4689 let cursor = self.selections.newest_anchor().head();
4690 let (buffer, cursor_buffer_position) =
4691 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4692
4693 if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4694 self.discard_inline_completion(false, cx);
4695 return None;
4696 }
4697
4698 if !user_requested
4699 && (!self.should_show_edit_predictions()
4700 || !self.is_focused(window)
4701 || buffer.read(cx).is_empty())
4702 {
4703 self.discard_inline_completion(false, cx);
4704 return None;
4705 }
4706
4707 self.update_visible_inline_completion(window, cx);
4708 provider.refresh(
4709 self.project.clone(),
4710 buffer,
4711 cursor_buffer_position,
4712 debounce,
4713 cx,
4714 );
4715 Some(())
4716 }
4717
4718 fn show_edit_predictions_in_menu(&self) -> bool {
4719 match self.edit_prediction_settings {
4720 EditPredictionSettings::Disabled => false,
4721 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4722 }
4723 }
4724
4725 pub fn edit_predictions_enabled(&self) -> bool {
4726 match self.edit_prediction_settings {
4727 EditPredictionSettings::Disabled => false,
4728 EditPredictionSettings::Enabled { .. } => true,
4729 }
4730 }
4731
4732 fn edit_prediction_requires_modifier(&self) -> bool {
4733 match self.edit_prediction_settings {
4734 EditPredictionSettings::Disabled => false,
4735 EditPredictionSettings::Enabled {
4736 preview_requires_modifier,
4737 ..
4738 } => preview_requires_modifier,
4739 }
4740 }
4741
4742 fn edit_prediction_settings_at_position(
4743 &self,
4744 buffer: &Entity<Buffer>,
4745 buffer_position: language::Anchor,
4746 cx: &App,
4747 ) -> EditPredictionSettings {
4748 if self.mode != EditorMode::Full
4749 || !self.show_inline_completions_override.unwrap_or(true)
4750 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
4751 {
4752 return EditPredictionSettings::Disabled;
4753 }
4754
4755 let buffer = buffer.read(cx);
4756
4757 let file = buffer.file();
4758
4759 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
4760 return EditPredictionSettings::Disabled;
4761 };
4762
4763 let by_provider = matches!(
4764 self.menu_inline_completions_policy,
4765 MenuInlineCompletionsPolicy::ByProvider
4766 );
4767
4768 let show_in_menu = by_provider
4769 && EditorSettings::get_global(cx).show_edit_predictions_in_menu
4770 && self
4771 .edit_prediction_provider
4772 .as_ref()
4773 .map_or(false, |provider| {
4774 provider.provider.show_completions_in_menu()
4775 });
4776
4777 let preview_requires_modifier = all_language_settings(file, cx)
4778 .inline_completions_preview_mode()
4779 == InlineCompletionPreviewMode::WhenHoldingModifier;
4780
4781 EditPredictionSettings::Enabled {
4782 show_in_menu,
4783 preview_requires_modifier,
4784 }
4785 }
4786
4787 fn should_show_edit_predictions(&self) -> bool {
4788 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
4789 }
4790
4791 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
4792 let cursor = self.selections.newest_anchor().head();
4793 if let Some((buffer, cursor_position)) =
4794 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4795 {
4796 self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
4797 } else {
4798 false
4799 }
4800 }
4801
4802 fn inline_completions_enabled_in_buffer(
4803 &self,
4804 buffer: &Entity<Buffer>,
4805 buffer_position: language::Anchor,
4806 cx: &App,
4807 ) -> bool {
4808 maybe!({
4809 let provider = self.edit_prediction_provider()?;
4810 if !provider.is_enabled(&buffer, buffer_position, cx) {
4811 return Some(false);
4812 }
4813 let buffer = buffer.read(cx);
4814 let Some(file) = buffer.file() else {
4815 return Some(true);
4816 };
4817 let settings = all_language_settings(Some(file), cx);
4818 Some(settings.inline_completions_enabled_for_path(file.path()))
4819 })
4820 .unwrap_or(false)
4821 }
4822
4823 fn cycle_inline_completion(
4824 &mut self,
4825 direction: Direction,
4826 window: &mut Window,
4827 cx: &mut Context<Self>,
4828 ) -> Option<()> {
4829 let provider = self.edit_prediction_provider()?;
4830 let cursor = self.selections.newest_anchor().head();
4831 let (buffer, cursor_buffer_position) =
4832 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4833 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
4834 return None;
4835 }
4836
4837 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4838 self.update_visible_inline_completion(window, cx);
4839
4840 Some(())
4841 }
4842
4843 pub fn show_inline_completion(
4844 &mut self,
4845 _: &ShowEditPrediction,
4846 window: &mut Window,
4847 cx: &mut Context<Self>,
4848 ) {
4849 if !self.has_active_inline_completion() {
4850 self.refresh_inline_completion(false, true, window, cx);
4851 return;
4852 }
4853
4854 self.update_visible_inline_completion(window, cx);
4855 }
4856
4857 pub fn display_cursor_names(
4858 &mut self,
4859 _: &DisplayCursorNames,
4860 window: &mut Window,
4861 cx: &mut Context<Self>,
4862 ) {
4863 self.show_cursor_names(window, cx);
4864 }
4865
4866 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4867 self.show_cursor_names = true;
4868 cx.notify();
4869 cx.spawn_in(window, |this, mut cx| async move {
4870 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4871 this.update(&mut cx, |this, cx| {
4872 this.show_cursor_names = false;
4873 cx.notify()
4874 })
4875 .ok()
4876 })
4877 .detach();
4878 }
4879
4880 pub fn next_edit_prediction(
4881 &mut self,
4882 _: &NextEditPrediction,
4883 window: &mut Window,
4884 cx: &mut Context<Self>,
4885 ) {
4886 if self.has_active_inline_completion() {
4887 self.cycle_inline_completion(Direction::Next, window, cx);
4888 } else {
4889 let is_copilot_disabled = self
4890 .refresh_inline_completion(false, true, window, cx)
4891 .is_none();
4892 if is_copilot_disabled {
4893 cx.propagate();
4894 }
4895 }
4896 }
4897
4898 pub fn previous_edit_prediction(
4899 &mut self,
4900 _: &PreviousEditPrediction,
4901 window: &mut Window,
4902 cx: &mut Context<Self>,
4903 ) {
4904 if self.has_active_inline_completion() {
4905 self.cycle_inline_completion(Direction::Prev, window, cx);
4906 } else {
4907 let is_copilot_disabled = self
4908 .refresh_inline_completion(false, true, window, cx)
4909 .is_none();
4910 if is_copilot_disabled {
4911 cx.propagate();
4912 }
4913 }
4914 }
4915
4916 pub fn accept_edit_prediction(
4917 &mut self,
4918 _: &AcceptEditPrediction,
4919 window: &mut Window,
4920 cx: &mut Context<Self>,
4921 ) {
4922 let buffer = self.buffer.read(cx);
4923 let snapshot = buffer.snapshot(cx);
4924 let selection = self.selections.newest_adjusted(cx);
4925 let cursor = selection.head();
4926 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
4927 let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
4928 if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
4929 {
4930 if cursor.column < suggested_indent.len
4931 && cursor.column <= current_indent.len
4932 && current_indent.len <= suggested_indent.len
4933 {
4934 self.tab(&Default::default(), window, cx);
4935 return;
4936 }
4937 }
4938
4939 if self.show_edit_predictions_in_menu() {
4940 self.hide_context_menu(window, cx);
4941 }
4942
4943 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4944 return;
4945 };
4946
4947 self.report_inline_completion_event(
4948 active_inline_completion.completion_id.clone(),
4949 true,
4950 cx,
4951 );
4952
4953 match &active_inline_completion.completion {
4954 InlineCompletion::Move { target, .. } => {
4955 let target = *target;
4956 // Note that this is also done in vim's handler of the Tab action.
4957 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
4958 selections.select_anchor_ranges([target..target]);
4959 });
4960 }
4961 InlineCompletion::Edit { edits, .. } => {
4962 if let Some(provider) = self.edit_prediction_provider() {
4963 provider.accept(cx);
4964 }
4965
4966 let snapshot = self.buffer.read(cx).snapshot(cx);
4967 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4968
4969 self.buffer.update(cx, |buffer, cx| {
4970 buffer.edit(edits.iter().cloned(), None, cx)
4971 });
4972
4973 self.change_selections(None, window, cx, |s| {
4974 s.select_anchor_ranges([last_edit_end..last_edit_end])
4975 });
4976
4977 self.update_visible_inline_completion(window, cx);
4978 if self.active_inline_completion.is_none() {
4979 self.refresh_inline_completion(true, true, window, cx);
4980 }
4981
4982 cx.notify();
4983 }
4984 }
4985 }
4986
4987 pub fn accept_partial_inline_completion(
4988 &mut self,
4989 _: &AcceptPartialEditPrediction,
4990 window: &mut Window,
4991 cx: &mut Context<Self>,
4992 ) {
4993 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4994 return;
4995 };
4996 if self.selections.count() != 1 {
4997 return;
4998 }
4999
5000 self.report_inline_completion_event(
5001 active_inline_completion.completion_id.clone(),
5002 true,
5003 cx,
5004 );
5005
5006 match &active_inline_completion.completion {
5007 InlineCompletion::Move { target, .. } => {
5008 let target = *target;
5009 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5010 selections.select_anchor_ranges([target..target]);
5011 });
5012 }
5013 InlineCompletion::Edit { edits, .. } => {
5014 // Find an insertion that starts at the cursor position.
5015 let snapshot = self.buffer.read(cx).snapshot(cx);
5016 let cursor_offset = self.selections.newest::<usize>(cx).head();
5017 let insertion = edits.iter().find_map(|(range, text)| {
5018 let range = range.to_offset(&snapshot);
5019 if range.is_empty() && range.start == cursor_offset {
5020 Some(text)
5021 } else {
5022 None
5023 }
5024 });
5025
5026 if let Some(text) = insertion {
5027 let mut partial_completion = text
5028 .chars()
5029 .by_ref()
5030 .take_while(|c| c.is_alphabetic())
5031 .collect::<String>();
5032 if partial_completion.is_empty() {
5033 partial_completion = text
5034 .chars()
5035 .by_ref()
5036 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5037 .collect::<String>();
5038 }
5039
5040 cx.emit(EditorEvent::InputHandled {
5041 utf16_range_to_replace: None,
5042 text: partial_completion.clone().into(),
5043 });
5044
5045 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5046
5047 self.refresh_inline_completion(true, true, window, cx);
5048 cx.notify();
5049 } else {
5050 self.accept_edit_prediction(&Default::default(), window, cx);
5051 }
5052 }
5053 }
5054 }
5055
5056 fn discard_inline_completion(
5057 &mut self,
5058 should_report_inline_completion_event: bool,
5059 cx: &mut Context<Self>,
5060 ) -> bool {
5061 if should_report_inline_completion_event {
5062 let completion_id = self
5063 .active_inline_completion
5064 .as_ref()
5065 .and_then(|active_completion| active_completion.completion_id.clone());
5066
5067 self.report_inline_completion_event(completion_id, false, cx);
5068 }
5069
5070 if let Some(provider) = self.edit_prediction_provider() {
5071 provider.discard(cx);
5072 }
5073
5074 self.take_active_inline_completion(cx)
5075 }
5076
5077 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5078 let Some(provider) = self.edit_prediction_provider() else {
5079 return;
5080 };
5081
5082 let Some((_, buffer, _)) = self
5083 .buffer
5084 .read(cx)
5085 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5086 else {
5087 return;
5088 };
5089
5090 let extension = buffer
5091 .read(cx)
5092 .file()
5093 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5094
5095 let event_type = match accepted {
5096 true => "Edit Prediction Accepted",
5097 false => "Edit Prediction Discarded",
5098 };
5099 telemetry::event!(
5100 event_type,
5101 provider = provider.name(),
5102 prediction_id = id,
5103 suggestion_accepted = accepted,
5104 file_extension = extension,
5105 );
5106 }
5107
5108 pub fn has_active_inline_completion(&self) -> bool {
5109 self.active_inline_completion.is_some()
5110 }
5111
5112 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5113 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5114 return false;
5115 };
5116
5117 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5118 self.clear_highlights::<InlineCompletionHighlight>(cx);
5119 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5120 true
5121 }
5122
5123 /// Returns true when we're displaying the inline completion popover below the cursor
5124 /// like we are not previewing and the LSP autocomplete menu is visible
5125 /// or we are in `when_holding_modifier` mode.
5126 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5127 if self.previewing_inline_completion
5128 || !self.show_edit_predictions_in_menu()
5129 || !self.edit_predictions_enabled()
5130 {
5131 return false;
5132 }
5133
5134 if self.has_visible_completions_menu() {
5135 return true;
5136 }
5137
5138 has_completion && self.edit_prediction_requires_modifier()
5139 }
5140
5141 fn handle_modifiers_changed(
5142 &mut self,
5143 modifiers: Modifiers,
5144 position_map: &PositionMap,
5145 window: &mut Window,
5146 cx: &mut Context<Self>,
5147 ) {
5148 if self.show_edit_predictions_in_menu() {
5149 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
5150 if let Some(accept_keystroke) = accept_binding.keystroke() {
5151 let was_previewing_inline_completion = self.previewing_inline_completion;
5152 self.previewing_inline_completion = modifiers == accept_keystroke.modifiers
5153 && accept_keystroke.modifiers.modified();
5154 if self.previewing_inline_completion != was_previewing_inline_completion {
5155 self.update_visible_inline_completion(window, cx);
5156 }
5157 }
5158 }
5159
5160 let mouse_position = window.mouse_position();
5161 if !position_map.text_hitbox.is_hovered(window) {
5162 return;
5163 }
5164
5165 self.update_hovered_link(
5166 position_map.point_for_position(mouse_position),
5167 &position_map.snapshot,
5168 modifiers,
5169 window,
5170 cx,
5171 )
5172 }
5173
5174 fn update_visible_inline_completion(
5175 &mut self,
5176 _window: &mut Window,
5177 cx: &mut Context<Self>,
5178 ) -> Option<()> {
5179 let selection = self.selections.newest_anchor();
5180 let cursor = selection.head();
5181 let multibuffer = self.buffer.read(cx).snapshot(cx);
5182 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5183 let excerpt_id = cursor.excerpt_id;
5184
5185 let show_in_menu = self.show_edit_predictions_in_menu();
5186 let completions_menu_has_precedence = !show_in_menu
5187 && (self.context_menu.borrow().is_some()
5188 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5189
5190 if completions_menu_has_precedence
5191 || !offset_selection.is_empty()
5192 || self
5193 .active_inline_completion
5194 .as_ref()
5195 .map_or(false, |completion| {
5196 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5197 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5198 !invalidation_range.contains(&offset_selection.head())
5199 })
5200 {
5201 self.discard_inline_completion(false, cx);
5202 return None;
5203 }
5204
5205 self.take_active_inline_completion(cx);
5206 let Some(provider) = self.edit_prediction_provider() else {
5207 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5208 return None;
5209 };
5210
5211 let (buffer, cursor_buffer_position) =
5212 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5213
5214 self.edit_prediction_settings =
5215 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5216
5217 if !self.edit_prediction_settings.is_enabled() {
5218 self.discard_inline_completion(false, cx);
5219 return None;
5220 }
5221
5222 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5223 let edits = inline_completion
5224 .edits
5225 .into_iter()
5226 .flat_map(|(range, new_text)| {
5227 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5228 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5229 Some((start..end, new_text))
5230 })
5231 .collect::<Vec<_>>();
5232 if edits.is_empty() {
5233 return None;
5234 }
5235
5236 let first_edit_start = edits.first().unwrap().0.start;
5237 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5238 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5239
5240 let last_edit_end = edits.last().unwrap().0.end;
5241 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5242 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5243
5244 let cursor_row = cursor.to_point(&multibuffer).row;
5245
5246 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5247
5248 let mut inlay_ids = Vec::new();
5249 let invalidation_row_range;
5250 let move_invalidation_row_range = if cursor_row < edit_start_row {
5251 Some(cursor_row..edit_end_row)
5252 } else if cursor_row > edit_end_row {
5253 Some(edit_start_row..cursor_row)
5254 } else {
5255 None
5256 };
5257 let is_move =
5258 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5259 let completion = if is_move {
5260 invalidation_row_range =
5261 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5262 let target = first_edit_start;
5263 let target_point = text::ToPoint::to_point(&target.text_anchor, &snapshot);
5264 // TODO: Base this off of TreeSitter or word boundaries?
5265 let target_excerpt_begin = snapshot.anchor_before(snapshot.clip_point(
5266 Point::new(target_point.row, target_point.column.saturating_sub(20)),
5267 Bias::Left,
5268 ));
5269 let target_excerpt_end = snapshot.anchor_after(snapshot.clip_point(
5270 Point::new(target_point.row, target_point.column + 20),
5271 Bias::Right,
5272 ));
5273 let range_around_target = target_excerpt_begin..target_excerpt_end;
5274 InlineCompletion::Move {
5275 target,
5276 range_around_target,
5277 snapshot,
5278 }
5279 } else {
5280 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5281 && !self.inline_completions_hidden_for_vim_mode;
5282 if show_completions_in_buffer {
5283 if edits
5284 .iter()
5285 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5286 {
5287 let mut inlays = Vec::new();
5288 for (range, new_text) in &edits {
5289 let inlay = Inlay::inline_completion(
5290 post_inc(&mut self.next_inlay_id),
5291 range.start,
5292 new_text.as_str(),
5293 );
5294 inlay_ids.push(inlay.id);
5295 inlays.push(inlay);
5296 }
5297
5298 self.splice_inlays(&[], inlays, cx);
5299 } else {
5300 let background_color = cx.theme().status().deleted_background;
5301 self.highlight_text::<InlineCompletionHighlight>(
5302 edits.iter().map(|(range, _)| range.clone()).collect(),
5303 HighlightStyle {
5304 background_color: Some(background_color),
5305 ..Default::default()
5306 },
5307 cx,
5308 );
5309 }
5310 }
5311
5312 invalidation_row_range = edit_start_row..edit_end_row;
5313
5314 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5315 if provider.show_tab_accept_marker() {
5316 EditDisplayMode::TabAccept
5317 } else {
5318 EditDisplayMode::Inline
5319 }
5320 } else {
5321 EditDisplayMode::DiffPopover
5322 };
5323
5324 InlineCompletion::Edit {
5325 edits,
5326 edit_preview: inline_completion.edit_preview,
5327 display_mode,
5328 snapshot,
5329 }
5330 };
5331
5332 let invalidation_range = multibuffer
5333 .anchor_before(Point::new(invalidation_row_range.start, 0))
5334 ..multibuffer.anchor_after(Point::new(
5335 invalidation_row_range.end,
5336 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5337 ));
5338
5339 self.stale_inline_completion_in_menu = None;
5340 self.active_inline_completion = Some(InlineCompletionState {
5341 inlay_ids,
5342 completion,
5343 completion_id: inline_completion.id,
5344 invalidation_range,
5345 });
5346
5347 cx.notify();
5348
5349 Some(())
5350 }
5351
5352 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5353 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5354 }
5355
5356 fn render_code_actions_indicator(
5357 &self,
5358 _style: &EditorStyle,
5359 row: DisplayRow,
5360 is_active: bool,
5361 cx: &mut Context<Self>,
5362 ) -> Option<IconButton> {
5363 if self.available_code_actions.is_some() {
5364 Some(
5365 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5366 .shape(ui::IconButtonShape::Square)
5367 .icon_size(IconSize::XSmall)
5368 .icon_color(Color::Muted)
5369 .toggle_state(is_active)
5370 .tooltip({
5371 let focus_handle = self.focus_handle.clone();
5372 move |window, cx| {
5373 Tooltip::for_action_in(
5374 "Toggle Code Actions",
5375 &ToggleCodeActions {
5376 deployed_from_indicator: None,
5377 },
5378 &focus_handle,
5379 window,
5380 cx,
5381 )
5382 }
5383 })
5384 .on_click(cx.listener(move |editor, _e, window, cx| {
5385 window.focus(&editor.focus_handle(cx));
5386 editor.toggle_code_actions(
5387 &ToggleCodeActions {
5388 deployed_from_indicator: Some(row),
5389 },
5390 window,
5391 cx,
5392 );
5393 })),
5394 )
5395 } else {
5396 None
5397 }
5398 }
5399
5400 fn clear_tasks(&mut self) {
5401 self.tasks.clear()
5402 }
5403
5404 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5405 if self.tasks.insert(key, value).is_some() {
5406 // This case should hopefully be rare, but just in case...
5407 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5408 }
5409 }
5410
5411 fn build_tasks_context(
5412 project: &Entity<Project>,
5413 buffer: &Entity<Buffer>,
5414 buffer_row: u32,
5415 tasks: &Arc<RunnableTasks>,
5416 cx: &mut Context<Self>,
5417 ) -> Task<Option<task::TaskContext>> {
5418 let position = Point::new(buffer_row, tasks.column);
5419 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5420 let location = Location {
5421 buffer: buffer.clone(),
5422 range: range_start..range_start,
5423 };
5424 // Fill in the environmental variables from the tree-sitter captures
5425 let mut captured_task_variables = TaskVariables::default();
5426 for (capture_name, value) in tasks.extra_variables.clone() {
5427 captured_task_variables.insert(
5428 task::VariableName::Custom(capture_name.into()),
5429 value.clone(),
5430 );
5431 }
5432 project.update(cx, |project, cx| {
5433 project.task_store().update(cx, |task_store, cx| {
5434 task_store.task_context_for_location(captured_task_variables, location, cx)
5435 })
5436 })
5437 }
5438
5439 pub fn spawn_nearest_task(
5440 &mut self,
5441 action: &SpawnNearestTask,
5442 window: &mut Window,
5443 cx: &mut Context<Self>,
5444 ) {
5445 let Some((workspace, _)) = self.workspace.clone() else {
5446 return;
5447 };
5448 let Some(project) = self.project.clone() else {
5449 return;
5450 };
5451
5452 // Try to find a closest, enclosing node using tree-sitter that has a
5453 // task
5454 let Some((buffer, buffer_row, tasks)) = self
5455 .find_enclosing_node_task(cx)
5456 // Or find the task that's closest in row-distance.
5457 .or_else(|| self.find_closest_task(cx))
5458 else {
5459 return;
5460 };
5461
5462 let reveal_strategy = action.reveal;
5463 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5464 cx.spawn_in(window, |_, mut cx| async move {
5465 let context = task_context.await?;
5466 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5467
5468 let resolved = resolved_task.resolved.as_mut()?;
5469 resolved.reveal = reveal_strategy;
5470
5471 workspace
5472 .update(&mut cx, |workspace, cx| {
5473 workspace::tasks::schedule_resolved_task(
5474 workspace,
5475 task_source_kind,
5476 resolved_task,
5477 false,
5478 cx,
5479 );
5480 })
5481 .ok()
5482 })
5483 .detach();
5484 }
5485
5486 fn find_closest_task(
5487 &mut self,
5488 cx: &mut Context<Self>,
5489 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5490 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5491
5492 let ((buffer_id, row), tasks) = self
5493 .tasks
5494 .iter()
5495 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5496
5497 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5498 let tasks = Arc::new(tasks.to_owned());
5499 Some((buffer, *row, tasks))
5500 }
5501
5502 fn find_enclosing_node_task(
5503 &mut self,
5504 cx: &mut Context<Self>,
5505 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5506 let snapshot = self.buffer.read(cx).snapshot(cx);
5507 let offset = self.selections.newest::<usize>(cx).head();
5508 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5509 let buffer_id = excerpt.buffer().remote_id();
5510
5511 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5512 let mut cursor = layer.node().walk();
5513
5514 while cursor.goto_first_child_for_byte(offset).is_some() {
5515 if cursor.node().end_byte() == offset {
5516 cursor.goto_next_sibling();
5517 }
5518 }
5519
5520 // Ascend to the smallest ancestor that contains the range and has a task.
5521 loop {
5522 let node = cursor.node();
5523 let node_range = node.byte_range();
5524 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5525
5526 // Check if this node contains our offset
5527 if node_range.start <= offset && node_range.end >= offset {
5528 // If it contains offset, check for task
5529 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5530 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5531 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5532 }
5533 }
5534
5535 if !cursor.goto_parent() {
5536 break;
5537 }
5538 }
5539 None
5540 }
5541
5542 fn render_run_indicator(
5543 &self,
5544 _style: &EditorStyle,
5545 is_active: bool,
5546 row: DisplayRow,
5547 cx: &mut Context<Self>,
5548 ) -> IconButton {
5549 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5550 .shape(ui::IconButtonShape::Square)
5551 .icon_size(IconSize::XSmall)
5552 .icon_color(Color::Muted)
5553 .toggle_state(is_active)
5554 .on_click(cx.listener(move |editor, _e, window, cx| {
5555 window.focus(&editor.focus_handle(cx));
5556 editor.toggle_code_actions(
5557 &ToggleCodeActions {
5558 deployed_from_indicator: Some(row),
5559 },
5560 window,
5561 cx,
5562 );
5563 }))
5564 }
5565
5566 pub fn context_menu_visible(&self) -> bool {
5567 !self.previewing_inline_completion
5568 && self
5569 .context_menu
5570 .borrow()
5571 .as_ref()
5572 .map_or(false, |menu| menu.visible())
5573 }
5574
5575 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5576 self.context_menu
5577 .borrow()
5578 .as_ref()
5579 .map(|menu| menu.origin())
5580 }
5581
5582 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5583 px(30.)
5584 }
5585
5586 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5587 if self.read_only(cx) {
5588 cx.theme().players().read_only()
5589 } else {
5590 self.style.as_ref().unwrap().local_player
5591 }
5592 }
5593
5594 #[allow(clippy::too_many_arguments)]
5595 fn render_edit_prediction_cursor_popover(
5596 &self,
5597 min_width: Pixels,
5598 max_width: Pixels,
5599 cursor_point: Point,
5600 style: &EditorStyle,
5601 accept_keystroke: &gpui::Keystroke,
5602 window: &Window,
5603 cx: &mut Context<Editor>,
5604 ) -> Option<AnyElement> {
5605 let provider = self.edit_prediction_provider.as_ref()?;
5606
5607 if provider.provider.needs_terms_acceptance(cx) {
5608 return Some(
5609 h_flex()
5610 .min_w(min_width)
5611 .flex_1()
5612 .px_2()
5613 .py_1()
5614 .gap_3()
5615 .elevation_2(cx)
5616 .hover(|style| style.bg(cx.theme().colors().element_hover))
5617 .id("accept-terms")
5618 .cursor_pointer()
5619 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5620 .on_click(cx.listener(|this, _event, window, cx| {
5621 cx.stop_propagation();
5622 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
5623 window.dispatch_action(
5624 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
5625 cx,
5626 );
5627 }))
5628 .child(
5629 h_flex()
5630 .flex_1()
5631 .gap_2()
5632 .child(Icon::new(IconName::ZedPredict))
5633 .child(Label::new("Accept Terms of Service"))
5634 .child(div().w_full())
5635 .child(
5636 Icon::new(IconName::ArrowUpRight)
5637 .color(Color::Muted)
5638 .size(IconSize::Small),
5639 )
5640 .into_any_element(),
5641 )
5642 .into_any(),
5643 );
5644 }
5645
5646 let is_refreshing = provider.provider.is_refreshing(cx);
5647
5648 fn pending_completion_container() -> Div {
5649 h_flex()
5650 .h_full()
5651 .flex_1()
5652 .gap_2()
5653 .child(Icon::new(IconName::ZedPredict))
5654 }
5655
5656 let completion = match &self.active_inline_completion {
5657 Some(completion) => self.render_edit_prediction_cursor_popover_preview(
5658 completion,
5659 cursor_point,
5660 style,
5661 window,
5662 cx,
5663 )?,
5664
5665 None if is_refreshing => match &self.stale_inline_completion_in_menu {
5666 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
5667 stale_completion,
5668 cursor_point,
5669 style,
5670 window,
5671 cx,
5672 )?,
5673
5674 None => {
5675 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
5676 }
5677 },
5678
5679 None => pending_completion_container().child(Label::new("No Prediction")),
5680 };
5681
5682 let buffer_font = theme::ThemeSettings::get_global(cx).buffer_font.clone();
5683 let completion = completion.font(buffer_font.clone());
5684
5685 let completion = if is_refreshing {
5686 completion
5687 .with_animation(
5688 "loading-completion",
5689 Animation::new(Duration::from_secs(2))
5690 .repeat()
5691 .with_easing(pulsating_between(0.4, 0.8)),
5692 |label, delta| label.opacity(delta),
5693 )
5694 .into_any_element()
5695 } else {
5696 completion.into_any_element()
5697 };
5698
5699 let has_completion = self.active_inline_completion.is_some();
5700
5701 Some(
5702 h_flex()
5703 .min_w(min_width)
5704 .max_w(max_width)
5705 .flex_1()
5706 .px_2()
5707 .py_1()
5708 .elevation_2(cx)
5709 .child(completion)
5710 .child(ui::Divider::vertical())
5711 .child(
5712 h_flex()
5713 .h_full()
5714 .gap_1()
5715 .pl_2()
5716 .child(h_flex().font(buffer_font.clone()).gap_1().children(
5717 ui::render_modifiers(
5718 &accept_keystroke.modifiers,
5719 PlatformStyle::platform(),
5720 Some(if !has_completion {
5721 Color::Muted
5722 } else {
5723 Color::Default
5724 }),
5725 None,
5726 true,
5727 ),
5728 ))
5729 .child(Label::new("Preview").into_any_element())
5730 .opacity(if has_completion { 1.0 } else { 0.4 }),
5731 )
5732 .into_any(),
5733 )
5734 }
5735
5736 fn render_edit_prediction_cursor_popover_preview(
5737 &self,
5738 completion: &InlineCompletionState,
5739 cursor_point: Point,
5740 style: &EditorStyle,
5741 window: &Window,
5742 cx: &mut Context<Editor>,
5743 ) -> Option<Div> {
5744 use text::ToPoint as _;
5745
5746 fn render_relative_row_jump(
5747 prefix: impl Into<String>,
5748 current_row: u32,
5749 target_row: u32,
5750 ) -> Div {
5751 let (row_diff, arrow) = if target_row < current_row {
5752 (current_row - target_row, IconName::ArrowUp)
5753 } else {
5754 (target_row - current_row, IconName::ArrowDown)
5755 };
5756
5757 h_flex()
5758 .child(
5759 Label::new(format!("{}{}", prefix.into(), row_diff))
5760 .color(Color::Muted)
5761 .size(LabelSize::Small),
5762 )
5763 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
5764 }
5765
5766 match &completion.completion {
5767 InlineCompletion::Edit {
5768 edits,
5769 edit_preview,
5770 snapshot,
5771 display_mode: _,
5772 } => {
5773 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
5774
5775 let highlighted_edits = crate::inline_completion_edit_text(
5776 &snapshot,
5777 &edits,
5778 edit_preview.as_ref()?,
5779 true,
5780 cx,
5781 );
5782
5783 let len_total = highlighted_edits.text.len();
5784 let first_line = &highlighted_edits.text
5785 [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
5786 let first_line_len = first_line.len();
5787
5788 let first_highlight_start = highlighted_edits
5789 .highlights
5790 .first()
5791 .map_or(0, |(range, _)| range.start);
5792 let drop_prefix_len = first_line
5793 .char_indices()
5794 .find(|(_, c)| !c.is_whitespace())
5795 .map_or(first_highlight_start, |(ix, _)| {
5796 ix.min(first_highlight_start)
5797 });
5798
5799 let preview_text = &first_line[drop_prefix_len..];
5800 let preview_len = preview_text.len();
5801 let highlights = highlighted_edits
5802 .highlights
5803 .into_iter()
5804 .take_until(|(range, _)| range.start > first_line_len)
5805 .map(|(range, style)| {
5806 (
5807 range.start - drop_prefix_len
5808 ..(range.end - drop_prefix_len).min(preview_len),
5809 style,
5810 )
5811 });
5812
5813 let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
5814 .with_highlights(&style.text, highlights);
5815
5816 let preview = h_flex()
5817 .gap_1()
5818 .min_w_16()
5819 .child(styled_text)
5820 .when(len_total > first_line_len, |parent| parent.child("…"));
5821
5822 let left = if first_edit_row != cursor_point.row {
5823 render_relative_row_jump("", cursor_point.row, first_edit_row)
5824 .into_any_element()
5825 } else {
5826 Icon::new(IconName::ZedPredict).into_any_element()
5827 };
5828
5829 Some(
5830 h_flex()
5831 .h_full()
5832 .flex_1()
5833 .gap_2()
5834 .pr_1()
5835 .overflow_x_hidden()
5836 .child(left)
5837 .child(preview),
5838 )
5839 }
5840
5841 InlineCompletion::Move {
5842 target,
5843 range_around_target,
5844 snapshot,
5845 } => {
5846 let highlighted_text = snapshot.highlighted_text_for_range(
5847 range_around_target.clone(),
5848 None,
5849 &style.syntax,
5850 );
5851 let base = h_flex().gap_3().flex_1().child(render_relative_row_jump(
5852 "Jump ",
5853 cursor_point.row,
5854 target.text_anchor.to_point(&snapshot).row,
5855 ));
5856
5857 if highlighted_text.text.is_empty() {
5858 return Some(base);
5859 }
5860
5861 let cursor_color = self.current_user_player_color(cx).cursor;
5862
5863 let start_point = range_around_target.start.to_point(&snapshot);
5864 let end_point = range_around_target.end.to_point(&snapshot);
5865 let target_point = target.text_anchor.to_point(&snapshot);
5866
5867 let styled_text = highlighted_text.to_styled_text(&style.text);
5868 let text_len = highlighted_text.text.len();
5869
5870 let cursor_relative_position = window
5871 .text_system()
5872 .layout_line(
5873 highlighted_text.text,
5874 style.text.font_size.to_pixels(window.rem_size()),
5875 // We don't need to include highlights
5876 // because we are only using this for the cursor position
5877 &[TextRun {
5878 len: text_len,
5879 font: style.text.font(),
5880 color: style.text.color,
5881 background_color: None,
5882 underline: None,
5883 strikethrough: None,
5884 }],
5885 )
5886 .log_err()
5887 .map(|line| {
5888 line.x_for_index(
5889 target_point.column.saturating_sub(start_point.column) as usize
5890 )
5891 });
5892
5893 let fade_before = start_point.column > 0;
5894 let fade_after = end_point.column < snapshot.line_len(end_point.row);
5895
5896 let background = cx.theme().colors().elevated_surface_background;
5897
5898 let preview = h_flex()
5899 .relative()
5900 .child(styled_text)
5901 .when(fade_before, |parent| {
5902 parent.child(div().absolute().top_0().left_0().w_4().h_full().bg(
5903 linear_gradient(
5904 90.,
5905 linear_color_stop(background, 0.),
5906 linear_color_stop(background.opacity(0.), 1.),
5907 ),
5908 ))
5909 })
5910 .when(fade_after, |parent| {
5911 parent.child(div().absolute().top_0().right_0().w_4().h_full().bg(
5912 linear_gradient(
5913 -90.,
5914 linear_color_stop(background, 0.),
5915 linear_color_stop(background.opacity(0.), 1.),
5916 ),
5917 ))
5918 })
5919 .when_some(cursor_relative_position, |parent, position| {
5920 parent.child(
5921 div()
5922 .w(px(2.))
5923 .h_full()
5924 .bg(cursor_color)
5925 .absolute()
5926 .top_0()
5927 .left(position),
5928 )
5929 });
5930
5931 Some(base.child(preview))
5932 }
5933 }
5934 }
5935
5936 fn render_context_menu(
5937 &self,
5938 style: &EditorStyle,
5939 max_height_in_lines: u32,
5940 y_flipped: bool,
5941 window: &mut Window,
5942 cx: &mut Context<Editor>,
5943 ) -> Option<AnyElement> {
5944 let menu = self.context_menu.borrow();
5945 let menu = menu.as_ref()?;
5946 if !menu.visible() {
5947 return None;
5948 };
5949 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
5950 }
5951
5952 fn render_context_menu_aside(
5953 &self,
5954 style: &EditorStyle,
5955 max_size: Size<Pixels>,
5956 cx: &mut Context<Editor>,
5957 ) -> Option<AnyElement> {
5958 self.context_menu.borrow().as_ref().and_then(|menu| {
5959 if menu.visible() {
5960 menu.render_aside(
5961 style,
5962 max_size,
5963 self.workspace.as_ref().map(|(w, _)| w.clone()),
5964 cx,
5965 )
5966 } else {
5967 None
5968 }
5969 })
5970 }
5971
5972 fn hide_context_menu(
5973 &mut self,
5974 window: &mut Window,
5975 cx: &mut Context<Self>,
5976 ) -> Option<CodeContextMenu> {
5977 cx.notify();
5978 self.completion_tasks.clear();
5979 let context_menu = self.context_menu.borrow_mut().take();
5980 self.stale_inline_completion_in_menu.take();
5981 self.update_visible_inline_completion(window, cx);
5982 context_menu
5983 }
5984
5985 fn show_snippet_choices(
5986 &mut self,
5987 choices: &Vec<String>,
5988 selection: Range<Anchor>,
5989 cx: &mut Context<Self>,
5990 ) {
5991 if selection.start.buffer_id.is_none() {
5992 return;
5993 }
5994 let buffer_id = selection.start.buffer_id.unwrap();
5995 let buffer = self.buffer().read(cx).buffer(buffer_id);
5996 let id = post_inc(&mut self.next_completion_id);
5997
5998 if let Some(buffer) = buffer {
5999 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6000 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6001 ));
6002 }
6003 }
6004
6005 pub fn insert_snippet(
6006 &mut self,
6007 insertion_ranges: &[Range<usize>],
6008 snippet: Snippet,
6009 window: &mut Window,
6010 cx: &mut Context<Self>,
6011 ) -> Result<()> {
6012 struct Tabstop<T> {
6013 is_end_tabstop: bool,
6014 ranges: Vec<Range<T>>,
6015 choices: Option<Vec<String>>,
6016 }
6017
6018 let tabstops = self.buffer.update(cx, |buffer, cx| {
6019 let snippet_text: Arc<str> = snippet.text.clone().into();
6020 buffer.edit(
6021 insertion_ranges
6022 .iter()
6023 .cloned()
6024 .map(|range| (range, snippet_text.clone())),
6025 Some(AutoindentMode::EachLine),
6026 cx,
6027 );
6028
6029 let snapshot = &*buffer.read(cx);
6030 let snippet = &snippet;
6031 snippet
6032 .tabstops
6033 .iter()
6034 .map(|tabstop| {
6035 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6036 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6037 });
6038 let mut tabstop_ranges = tabstop
6039 .ranges
6040 .iter()
6041 .flat_map(|tabstop_range| {
6042 let mut delta = 0_isize;
6043 insertion_ranges.iter().map(move |insertion_range| {
6044 let insertion_start = insertion_range.start as isize + delta;
6045 delta +=
6046 snippet.text.len() as isize - insertion_range.len() as isize;
6047
6048 let start = ((insertion_start + tabstop_range.start) as usize)
6049 .min(snapshot.len());
6050 let end = ((insertion_start + tabstop_range.end) as usize)
6051 .min(snapshot.len());
6052 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6053 })
6054 })
6055 .collect::<Vec<_>>();
6056 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6057
6058 Tabstop {
6059 is_end_tabstop,
6060 ranges: tabstop_ranges,
6061 choices: tabstop.choices.clone(),
6062 }
6063 })
6064 .collect::<Vec<_>>()
6065 });
6066 if let Some(tabstop) = tabstops.first() {
6067 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6068 s.select_ranges(tabstop.ranges.iter().cloned());
6069 });
6070
6071 if let Some(choices) = &tabstop.choices {
6072 if let Some(selection) = tabstop.ranges.first() {
6073 self.show_snippet_choices(choices, selection.clone(), cx)
6074 }
6075 }
6076
6077 // If we're already at the last tabstop and it's at the end of the snippet,
6078 // we're done, we don't need to keep the state around.
6079 if !tabstop.is_end_tabstop {
6080 let choices = tabstops
6081 .iter()
6082 .map(|tabstop| tabstop.choices.clone())
6083 .collect();
6084
6085 let ranges = tabstops
6086 .into_iter()
6087 .map(|tabstop| tabstop.ranges)
6088 .collect::<Vec<_>>();
6089
6090 self.snippet_stack.push(SnippetState {
6091 active_index: 0,
6092 ranges,
6093 choices,
6094 });
6095 }
6096
6097 // Check whether the just-entered snippet ends with an auto-closable bracket.
6098 if self.autoclose_regions.is_empty() {
6099 let snapshot = self.buffer.read(cx).snapshot(cx);
6100 for selection in &mut self.selections.all::<Point>(cx) {
6101 let selection_head = selection.head();
6102 let Some(scope) = snapshot.language_scope_at(selection_head) else {
6103 continue;
6104 };
6105
6106 let mut bracket_pair = None;
6107 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
6108 let prev_chars = snapshot
6109 .reversed_chars_at(selection_head)
6110 .collect::<String>();
6111 for (pair, enabled) in scope.brackets() {
6112 if enabled
6113 && pair.close
6114 && prev_chars.starts_with(pair.start.as_str())
6115 && next_chars.starts_with(pair.end.as_str())
6116 {
6117 bracket_pair = Some(pair.clone());
6118 break;
6119 }
6120 }
6121 if let Some(pair) = bracket_pair {
6122 let start = snapshot.anchor_after(selection_head);
6123 let end = snapshot.anchor_after(selection_head);
6124 self.autoclose_regions.push(AutocloseRegion {
6125 selection_id: selection.id,
6126 range: start..end,
6127 pair,
6128 });
6129 }
6130 }
6131 }
6132 }
6133 Ok(())
6134 }
6135
6136 pub fn move_to_next_snippet_tabstop(
6137 &mut self,
6138 window: &mut Window,
6139 cx: &mut Context<Self>,
6140 ) -> bool {
6141 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6142 }
6143
6144 pub fn move_to_prev_snippet_tabstop(
6145 &mut self,
6146 window: &mut Window,
6147 cx: &mut Context<Self>,
6148 ) -> bool {
6149 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6150 }
6151
6152 pub fn move_to_snippet_tabstop(
6153 &mut self,
6154 bias: Bias,
6155 window: &mut Window,
6156 cx: &mut Context<Self>,
6157 ) -> bool {
6158 if let Some(mut snippet) = self.snippet_stack.pop() {
6159 match bias {
6160 Bias::Left => {
6161 if snippet.active_index > 0 {
6162 snippet.active_index -= 1;
6163 } else {
6164 self.snippet_stack.push(snippet);
6165 return false;
6166 }
6167 }
6168 Bias::Right => {
6169 if snippet.active_index + 1 < snippet.ranges.len() {
6170 snippet.active_index += 1;
6171 } else {
6172 self.snippet_stack.push(snippet);
6173 return false;
6174 }
6175 }
6176 }
6177 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6178 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6179 s.select_anchor_ranges(current_ranges.iter().cloned())
6180 });
6181
6182 if let Some(choices) = &snippet.choices[snippet.active_index] {
6183 if let Some(selection) = current_ranges.first() {
6184 self.show_snippet_choices(&choices, selection.clone(), cx);
6185 }
6186 }
6187
6188 // If snippet state is not at the last tabstop, push it back on the stack
6189 if snippet.active_index + 1 < snippet.ranges.len() {
6190 self.snippet_stack.push(snippet);
6191 }
6192 return true;
6193 }
6194 }
6195
6196 false
6197 }
6198
6199 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6200 self.transact(window, cx, |this, window, cx| {
6201 this.select_all(&SelectAll, window, cx);
6202 this.insert("", window, cx);
6203 });
6204 }
6205
6206 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6207 self.transact(window, cx, |this, window, cx| {
6208 this.select_autoclose_pair(window, cx);
6209 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6210 if !this.linked_edit_ranges.is_empty() {
6211 let selections = this.selections.all::<MultiBufferPoint>(cx);
6212 let snapshot = this.buffer.read(cx).snapshot(cx);
6213
6214 for selection in selections.iter() {
6215 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6216 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6217 if selection_start.buffer_id != selection_end.buffer_id {
6218 continue;
6219 }
6220 if let Some(ranges) =
6221 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6222 {
6223 for (buffer, entries) in ranges {
6224 linked_ranges.entry(buffer).or_default().extend(entries);
6225 }
6226 }
6227 }
6228 }
6229
6230 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6231 if !this.selections.line_mode {
6232 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6233 for selection in &mut selections {
6234 if selection.is_empty() {
6235 let old_head = selection.head();
6236 let mut new_head =
6237 movement::left(&display_map, old_head.to_display_point(&display_map))
6238 .to_point(&display_map);
6239 if let Some((buffer, line_buffer_range)) = display_map
6240 .buffer_snapshot
6241 .buffer_line_for_row(MultiBufferRow(old_head.row))
6242 {
6243 let indent_size =
6244 buffer.indent_size_for_line(line_buffer_range.start.row);
6245 let indent_len = match indent_size.kind {
6246 IndentKind::Space => {
6247 buffer.settings_at(line_buffer_range.start, cx).tab_size
6248 }
6249 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6250 };
6251 if old_head.column <= indent_size.len && old_head.column > 0 {
6252 let indent_len = indent_len.get();
6253 new_head = cmp::min(
6254 new_head,
6255 MultiBufferPoint::new(
6256 old_head.row,
6257 ((old_head.column - 1) / indent_len) * indent_len,
6258 ),
6259 );
6260 }
6261 }
6262
6263 selection.set_head(new_head, SelectionGoal::None);
6264 }
6265 }
6266 }
6267
6268 this.signature_help_state.set_backspace_pressed(true);
6269 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6270 s.select(selections)
6271 });
6272 this.insert("", window, cx);
6273 let empty_str: Arc<str> = Arc::from("");
6274 for (buffer, edits) in linked_ranges {
6275 let snapshot = buffer.read(cx).snapshot();
6276 use text::ToPoint as TP;
6277
6278 let edits = edits
6279 .into_iter()
6280 .map(|range| {
6281 let end_point = TP::to_point(&range.end, &snapshot);
6282 let mut start_point = TP::to_point(&range.start, &snapshot);
6283
6284 if end_point == start_point {
6285 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6286 .saturating_sub(1);
6287 start_point =
6288 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6289 };
6290
6291 (start_point..end_point, empty_str.clone())
6292 })
6293 .sorted_by_key(|(range, _)| range.start)
6294 .collect::<Vec<_>>();
6295 buffer.update(cx, |this, cx| {
6296 this.edit(edits, None, cx);
6297 })
6298 }
6299 this.refresh_inline_completion(true, false, window, cx);
6300 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6301 });
6302 }
6303
6304 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6305 self.transact(window, cx, |this, window, cx| {
6306 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6307 let line_mode = s.line_mode;
6308 s.move_with(|map, selection| {
6309 if selection.is_empty() && !line_mode {
6310 let cursor = movement::right(map, selection.head());
6311 selection.end = cursor;
6312 selection.reversed = true;
6313 selection.goal = SelectionGoal::None;
6314 }
6315 })
6316 });
6317 this.insert("", window, cx);
6318 this.refresh_inline_completion(true, false, window, cx);
6319 });
6320 }
6321
6322 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6323 if self.move_to_prev_snippet_tabstop(window, cx) {
6324 return;
6325 }
6326
6327 self.outdent(&Outdent, window, cx);
6328 }
6329
6330 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6331 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6332 return;
6333 }
6334
6335 let mut selections = self.selections.all_adjusted(cx);
6336 let buffer = self.buffer.read(cx);
6337 let snapshot = buffer.snapshot(cx);
6338 let rows_iter = selections.iter().map(|s| s.head().row);
6339 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6340
6341 let mut edits = Vec::new();
6342 let mut prev_edited_row = 0;
6343 let mut row_delta = 0;
6344 for selection in &mut selections {
6345 if selection.start.row != prev_edited_row {
6346 row_delta = 0;
6347 }
6348 prev_edited_row = selection.end.row;
6349
6350 // If the selection is non-empty, then increase the indentation of the selected lines.
6351 if !selection.is_empty() {
6352 row_delta =
6353 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6354 continue;
6355 }
6356
6357 // If the selection is empty and the cursor is in the leading whitespace before the
6358 // suggested indentation, then auto-indent the line.
6359 let cursor = selection.head();
6360 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6361 if let Some(suggested_indent) =
6362 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6363 {
6364 if cursor.column < suggested_indent.len
6365 && cursor.column <= current_indent.len
6366 && current_indent.len <= suggested_indent.len
6367 {
6368 selection.start = Point::new(cursor.row, suggested_indent.len);
6369 selection.end = selection.start;
6370 if row_delta == 0 {
6371 edits.extend(Buffer::edit_for_indent_size_adjustment(
6372 cursor.row,
6373 current_indent,
6374 suggested_indent,
6375 ));
6376 row_delta = suggested_indent.len - current_indent.len;
6377 }
6378 continue;
6379 }
6380 }
6381
6382 // Otherwise, insert a hard or soft tab.
6383 let settings = buffer.settings_at(cursor, cx);
6384 let tab_size = if settings.hard_tabs {
6385 IndentSize::tab()
6386 } else {
6387 let tab_size = settings.tab_size.get();
6388 let char_column = snapshot
6389 .text_for_range(Point::new(cursor.row, 0)..cursor)
6390 .flat_map(str::chars)
6391 .count()
6392 + row_delta as usize;
6393 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6394 IndentSize::spaces(chars_to_next_tab_stop)
6395 };
6396 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6397 selection.end = selection.start;
6398 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6399 row_delta += tab_size.len;
6400 }
6401
6402 self.transact(window, cx, |this, window, cx| {
6403 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6404 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6405 s.select(selections)
6406 });
6407 this.refresh_inline_completion(true, false, window, cx);
6408 });
6409 }
6410
6411 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6412 if self.read_only(cx) {
6413 return;
6414 }
6415 let mut selections = self.selections.all::<Point>(cx);
6416 let mut prev_edited_row = 0;
6417 let mut row_delta = 0;
6418 let mut edits = Vec::new();
6419 let buffer = self.buffer.read(cx);
6420 let snapshot = buffer.snapshot(cx);
6421 for selection in &mut selections {
6422 if selection.start.row != prev_edited_row {
6423 row_delta = 0;
6424 }
6425 prev_edited_row = selection.end.row;
6426
6427 row_delta =
6428 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6429 }
6430
6431 self.transact(window, cx, |this, window, cx| {
6432 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6433 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6434 s.select(selections)
6435 });
6436 });
6437 }
6438
6439 fn indent_selection(
6440 buffer: &MultiBuffer,
6441 snapshot: &MultiBufferSnapshot,
6442 selection: &mut Selection<Point>,
6443 edits: &mut Vec<(Range<Point>, String)>,
6444 delta_for_start_row: u32,
6445 cx: &App,
6446 ) -> u32 {
6447 let settings = buffer.settings_at(selection.start, cx);
6448 let tab_size = settings.tab_size.get();
6449 let indent_kind = if settings.hard_tabs {
6450 IndentKind::Tab
6451 } else {
6452 IndentKind::Space
6453 };
6454 let mut start_row = selection.start.row;
6455 let mut end_row = selection.end.row + 1;
6456
6457 // If a selection ends at the beginning of a line, don't indent
6458 // that last line.
6459 if selection.end.column == 0 && selection.end.row > selection.start.row {
6460 end_row -= 1;
6461 }
6462
6463 // Avoid re-indenting a row that has already been indented by a
6464 // previous selection, but still update this selection's column
6465 // to reflect that indentation.
6466 if delta_for_start_row > 0 {
6467 start_row += 1;
6468 selection.start.column += delta_for_start_row;
6469 if selection.end.row == selection.start.row {
6470 selection.end.column += delta_for_start_row;
6471 }
6472 }
6473
6474 let mut delta_for_end_row = 0;
6475 let has_multiple_rows = start_row + 1 != end_row;
6476 for row in start_row..end_row {
6477 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6478 let indent_delta = match (current_indent.kind, indent_kind) {
6479 (IndentKind::Space, IndentKind::Space) => {
6480 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6481 IndentSize::spaces(columns_to_next_tab_stop)
6482 }
6483 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6484 (_, IndentKind::Tab) => IndentSize::tab(),
6485 };
6486
6487 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6488 0
6489 } else {
6490 selection.start.column
6491 };
6492 let row_start = Point::new(row, start);
6493 edits.push((
6494 row_start..row_start,
6495 indent_delta.chars().collect::<String>(),
6496 ));
6497
6498 // Update this selection's endpoints to reflect the indentation.
6499 if row == selection.start.row {
6500 selection.start.column += indent_delta.len;
6501 }
6502 if row == selection.end.row {
6503 selection.end.column += indent_delta.len;
6504 delta_for_end_row = indent_delta.len;
6505 }
6506 }
6507
6508 if selection.start.row == selection.end.row {
6509 delta_for_start_row + delta_for_end_row
6510 } else {
6511 delta_for_end_row
6512 }
6513 }
6514
6515 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6516 if self.read_only(cx) {
6517 return;
6518 }
6519 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6520 let selections = self.selections.all::<Point>(cx);
6521 let mut deletion_ranges = Vec::new();
6522 let mut last_outdent = None;
6523 {
6524 let buffer = self.buffer.read(cx);
6525 let snapshot = buffer.snapshot(cx);
6526 for selection in &selections {
6527 let settings = buffer.settings_at(selection.start, cx);
6528 let tab_size = settings.tab_size.get();
6529 let mut rows = selection.spanned_rows(false, &display_map);
6530
6531 // Avoid re-outdenting a row that has already been outdented by a
6532 // previous selection.
6533 if let Some(last_row) = last_outdent {
6534 if last_row == rows.start {
6535 rows.start = rows.start.next_row();
6536 }
6537 }
6538 let has_multiple_rows = rows.len() > 1;
6539 for row in rows.iter_rows() {
6540 let indent_size = snapshot.indent_size_for_line(row);
6541 if indent_size.len > 0 {
6542 let deletion_len = match indent_size.kind {
6543 IndentKind::Space => {
6544 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6545 if columns_to_prev_tab_stop == 0 {
6546 tab_size
6547 } else {
6548 columns_to_prev_tab_stop
6549 }
6550 }
6551 IndentKind::Tab => 1,
6552 };
6553 let start = if has_multiple_rows
6554 || deletion_len > selection.start.column
6555 || indent_size.len < selection.start.column
6556 {
6557 0
6558 } else {
6559 selection.start.column - deletion_len
6560 };
6561 deletion_ranges.push(
6562 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6563 );
6564 last_outdent = Some(row);
6565 }
6566 }
6567 }
6568 }
6569
6570 self.transact(window, cx, |this, window, cx| {
6571 this.buffer.update(cx, |buffer, cx| {
6572 let empty_str: Arc<str> = Arc::default();
6573 buffer.edit(
6574 deletion_ranges
6575 .into_iter()
6576 .map(|range| (range, empty_str.clone())),
6577 None,
6578 cx,
6579 );
6580 });
6581 let selections = this.selections.all::<usize>(cx);
6582 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6583 s.select(selections)
6584 });
6585 });
6586 }
6587
6588 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6589 if self.read_only(cx) {
6590 return;
6591 }
6592 let selections = self
6593 .selections
6594 .all::<usize>(cx)
6595 .into_iter()
6596 .map(|s| s.range());
6597
6598 self.transact(window, cx, |this, window, cx| {
6599 this.buffer.update(cx, |buffer, cx| {
6600 buffer.autoindent_ranges(selections, cx);
6601 });
6602 let selections = this.selections.all::<usize>(cx);
6603 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6604 s.select(selections)
6605 });
6606 });
6607 }
6608
6609 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6610 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6611 let selections = self.selections.all::<Point>(cx);
6612
6613 let mut new_cursors = Vec::new();
6614 let mut edit_ranges = Vec::new();
6615 let mut selections = selections.iter().peekable();
6616 while let Some(selection) = selections.next() {
6617 let mut rows = selection.spanned_rows(false, &display_map);
6618 let goal_display_column = selection.head().to_display_point(&display_map).column();
6619
6620 // Accumulate contiguous regions of rows that we want to delete.
6621 while let Some(next_selection) = selections.peek() {
6622 let next_rows = next_selection.spanned_rows(false, &display_map);
6623 if next_rows.start <= rows.end {
6624 rows.end = next_rows.end;
6625 selections.next().unwrap();
6626 } else {
6627 break;
6628 }
6629 }
6630
6631 let buffer = &display_map.buffer_snapshot;
6632 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6633 let edit_end;
6634 let cursor_buffer_row;
6635 if buffer.max_point().row >= rows.end.0 {
6636 // If there's a line after the range, delete the \n from the end of the row range
6637 // and position the cursor on the next line.
6638 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6639 cursor_buffer_row = rows.end;
6640 } else {
6641 // If there isn't a line after the range, delete the \n from the line before the
6642 // start of the row range and position the cursor there.
6643 edit_start = edit_start.saturating_sub(1);
6644 edit_end = buffer.len();
6645 cursor_buffer_row = rows.start.previous_row();
6646 }
6647
6648 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6649 *cursor.column_mut() =
6650 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6651
6652 new_cursors.push((
6653 selection.id,
6654 buffer.anchor_after(cursor.to_point(&display_map)),
6655 ));
6656 edit_ranges.push(edit_start..edit_end);
6657 }
6658
6659 self.transact(window, cx, |this, window, cx| {
6660 let buffer = this.buffer.update(cx, |buffer, cx| {
6661 let empty_str: Arc<str> = Arc::default();
6662 buffer.edit(
6663 edit_ranges
6664 .into_iter()
6665 .map(|range| (range, empty_str.clone())),
6666 None,
6667 cx,
6668 );
6669 buffer.snapshot(cx)
6670 });
6671 let new_selections = new_cursors
6672 .into_iter()
6673 .map(|(id, cursor)| {
6674 let cursor = cursor.to_point(&buffer);
6675 Selection {
6676 id,
6677 start: cursor,
6678 end: cursor,
6679 reversed: false,
6680 goal: SelectionGoal::None,
6681 }
6682 })
6683 .collect();
6684
6685 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6686 s.select(new_selections);
6687 });
6688 });
6689 }
6690
6691 pub fn join_lines_impl(
6692 &mut self,
6693 insert_whitespace: bool,
6694 window: &mut Window,
6695 cx: &mut Context<Self>,
6696 ) {
6697 if self.read_only(cx) {
6698 return;
6699 }
6700 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6701 for selection in self.selections.all::<Point>(cx) {
6702 let start = MultiBufferRow(selection.start.row);
6703 // Treat single line selections as if they include the next line. Otherwise this action
6704 // would do nothing for single line selections individual cursors.
6705 let end = if selection.start.row == selection.end.row {
6706 MultiBufferRow(selection.start.row + 1)
6707 } else {
6708 MultiBufferRow(selection.end.row)
6709 };
6710
6711 if let Some(last_row_range) = row_ranges.last_mut() {
6712 if start <= last_row_range.end {
6713 last_row_range.end = end;
6714 continue;
6715 }
6716 }
6717 row_ranges.push(start..end);
6718 }
6719
6720 let snapshot = self.buffer.read(cx).snapshot(cx);
6721 let mut cursor_positions = Vec::new();
6722 for row_range in &row_ranges {
6723 let anchor = snapshot.anchor_before(Point::new(
6724 row_range.end.previous_row().0,
6725 snapshot.line_len(row_range.end.previous_row()),
6726 ));
6727 cursor_positions.push(anchor..anchor);
6728 }
6729
6730 self.transact(window, cx, |this, window, cx| {
6731 for row_range in row_ranges.into_iter().rev() {
6732 for row in row_range.iter_rows().rev() {
6733 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6734 let next_line_row = row.next_row();
6735 let indent = snapshot.indent_size_for_line(next_line_row);
6736 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6737
6738 let replace =
6739 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6740 " "
6741 } else {
6742 ""
6743 };
6744
6745 this.buffer.update(cx, |buffer, cx| {
6746 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6747 });
6748 }
6749 }
6750
6751 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6752 s.select_anchor_ranges(cursor_positions)
6753 });
6754 });
6755 }
6756
6757 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6758 self.join_lines_impl(true, window, cx);
6759 }
6760
6761 pub fn sort_lines_case_sensitive(
6762 &mut self,
6763 _: &SortLinesCaseSensitive,
6764 window: &mut Window,
6765 cx: &mut Context<Self>,
6766 ) {
6767 self.manipulate_lines(window, cx, |lines| lines.sort())
6768 }
6769
6770 pub fn sort_lines_case_insensitive(
6771 &mut self,
6772 _: &SortLinesCaseInsensitive,
6773 window: &mut Window,
6774 cx: &mut Context<Self>,
6775 ) {
6776 self.manipulate_lines(window, cx, |lines| {
6777 lines.sort_by_key(|line| line.to_lowercase())
6778 })
6779 }
6780
6781 pub fn unique_lines_case_insensitive(
6782 &mut self,
6783 _: &UniqueLinesCaseInsensitive,
6784 window: &mut Window,
6785 cx: &mut Context<Self>,
6786 ) {
6787 self.manipulate_lines(window, cx, |lines| {
6788 let mut seen = HashSet::default();
6789 lines.retain(|line| seen.insert(line.to_lowercase()));
6790 })
6791 }
6792
6793 pub fn unique_lines_case_sensitive(
6794 &mut self,
6795 _: &UniqueLinesCaseSensitive,
6796 window: &mut Window,
6797 cx: &mut Context<Self>,
6798 ) {
6799 self.manipulate_lines(window, cx, |lines| {
6800 let mut seen = HashSet::default();
6801 lines.retain(|line| seen.insert(*line));
6802 })
6803 }
6804
6805 pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
6806 let mut revert_changes = HashMap::default();
6807 let snapshot = self.snapshot(window, cx);
6808 for hunk in snapshot
6809 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
6810 {
6811 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6812 }
6813 if !revert_changes.is_empty() {
6814 self.transact(window, cx, |editor, window, cx| {
6815 editor.revert(revert_changes, window, cx);
6816 });
6817 }
6818 }
6819
6820 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
6821 let Some(project) = self.project.clone() else {
6822 return;
6823 };
6824 self.reload(project, window, cx)
6825 .detach_and_notify_err(window, cx);
6826 }
6827
6828 pub fn revert_selected_hunks(
6829 &mut self,
6830 _: &RevertSelectedHunks,
6831 window: &mut Window,
6832 cx: &mut Context<Self>,
6833 ) {
6834 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
6835 self.revert_hunks_in_ranges(selections, window, cx);
6836 }
6837
6838 fn revert_hunks_in_ranges(
6839 &mut self,
6840 ranges: impl Iterator<Item = Range<Point>>,
6841 window: &mut Window,
6842 cx: &mut Context<Editor>,
6843 ) {
6844 let mut revert_changes = HashMap::default();
6845 let snapshot = self.snapshot(window, cx);
6846 for hunk in &snapshot.hunks_for_ranges(ranges) {
6847 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6848 }
6849 if !revert_changes.is_empty() {
6850 self.transact(window, cx, |editor, window, cx| {
6851 editor.revert(revert_changes, window, cx);
6852 });
6853 }
6854 }
6855
6856 pub fn open_active_item_in_terminal(
6857 &mut self,
6858 _: &OpenInTerminal,
6859 window: &mut Window,
6860 cx: &mut Context<Self>,
6861 ) {
6862 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6863 let project_path = buffer.read(cx).project_path(cx)?;
6864 let project = self.project.as_ref()?.read(cx);
6865 let entry = project.entry_for_path(&project_path, cx)?;
6866 let parent = match &entry.canonical_path {
6867 Some(canonical_path) => canonical_path.to_path_buf(),
6868 None => project.absolute_path(&project_path, cx)?,
6869 }
6870 .parent()?
6871 .to_path_buf();
6872 Some(parent)
6873 }) {
6874 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
6875 }
6876 }
6877
6878 pub fn prepare_revert_change(
6879 &self,
6880 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6881 hunk: &MultiBufferDiffHunk,
6882 cx: &mut App,
6883 ) -> Option<()> {
6884 let buffer = self.buffer.read(cx);
6885 let diff = buffer.diff_for(hunk.buffer_id)?;
6886 let buffer = buffer.buffer(hunk.buffer_id)?;
6887 let buffer = buffer.read(cx);
6888 let original_text = diff
6889 .read(cx)
6890 .snapshot
6891 .base_text
6892 .as_ref()?
6893 .as_rope()
6894 .slice(hunk.diff_base_byte_range.clone());
6895 let buffer_snapshot = buffer.snapshot();
6896 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6897 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6898 probe
6899 .0
6900 .start
6901 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6902 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6903 }) {
6904 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6905 Some(())
6906 } else {
6907 None
6908 }
6909 }
6910
6911 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
6912 self.manipulate_lines(window, cx, |lines| lines.reverse())
6913 }
6914
6915 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
6916 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
6917 }
6918
6919 fn manipulate_lines<Fn>(
6920 &mut self,
6921 window: &mut Window,
6922 cx: &mut Context<Self>,
6923 mut callback: Fn,
6924 ) where
6925 Fn: FnMut(&mut Vec<&str>),
6926 {
6927 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6928 let buffer = self.buffer.read(cx).snapshot(cx);
6929
6930 let mut edits = Vec::new();
6931
6932 let selections = self.selections.all::<Point>(cx);
6933 let mut selections = selections.iter().peekable();
6934 let mut contiguous_row_selections = Vec::new();
6935 let mut new_selections = Vec::new();
6936 let mut added_lines = 0;
6937 let mut removed_lines = 0;
6938
6939 while let Some(selection) = selections.next() {
6940 let (start_row, end_row) = consume_contiguous_rows(
6941 &mut contiguous_row_selections,
6942 selection,
6943 &display_map,
6944 &mut selections,
6945 );
6946
6947 let start_point = Point::new(start_row.0, 0);
6948 let end_point = Point::new(
6949 end_row.previous_row().0,
6950 buffer.line_len(end_row.previous_row()),
6951 );
6952 let text = buffer
6953 .text_for_range(start_point..end_point)
6954 .collect::<String>();
6955
6956 let mut lines = text.split('\n').collect_vec();
6957
6958 let lines_before = lines.len();
6959 callback(&mut lines);
6960 let lines_after = lines.len();
6961
6962 edits.push((start_point..end_point, lines.join("\n")));
6963
6964 // Selections must change based on added and removed line count
6965 let start_row =
6966 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6967 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6968 new_selections.push(Selection {
6969 id: selection.id,
6970 start: start_row,
6971 end: end_row,
6972 goal: SelectionGoal::None,
6973 reversed: selection.reversed,
6974 });
6975
6976 if lines_after > lines_before {
6977 added_lines += lines_after - lines_before;
6978 } else if lines_before > lines_after {
6979 removed_lines += lines_before - lines_after;
6980 }
6981 }
6982
6983 self.transact(window, cx, |this, window, cx| {
6984 let buffer = this.buffer.update(cx, |buffer, cx| {
6985 buffer.edit(edits, None, cx);
6986 buffer.snapshot(cx)
6987 });
6988
6989 // Recalculate offsets on newly edited buffer
6990 let new_selections = new_selections
6991 .iter()
6992 .map(|s| {
6993 let start_point = Point::new(s.start.0, 0);
6994 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6995 Selection {
6996 id: s.id,
6997 start: buffer.point_to_offset(start_point),
6998 end: buffer.point_to_offset(end_point),
6999 goal: s.goal,
7000 reversed: s.reversed,
7001 }
7002 })
7003 .collect();
7004
7005 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7006 s.select(new_selections);
7007 });
7008
7009 this.request_autoscroll(Autoscroll::fit(), cx);
7010 });
7011 }
7012
7013 pub fn convert_to_upper_case(
7014 &mut self,
7015 _: &ConvertToUpperCase,
7016 window: &mut Window,
7017 cx: &mut Context<Self>,
7018 ) {
7019 self.manipulate_text(window, cx, |text| text.to_uppercase())
7020 }
7021
7022 pub fn convert_to_lower_case(
7023 &mut self,
7024 _: &ConvertToLowerCase,
7025 window: &mut Window,
7026 cx: &mut Context<Self>,
7027 ) {
7028 self.manipulate_text(window, cx, |text| text.to_lowercase())
7029 }
7030
7031 pub fn convert_to_title_case(
7032 &mut self,
7033 _: &ConvertToTitleCase,
7034 window: &mut Window,
7035 cx: &mut Context<Self>,
7036 ) {
7037 self.manipulate_text(window, cx, |text| {
7038 text.split('\n')
7039 .map(|line| line.to_case(Case::Title))
7040 .join("\n")
7041 })
7042 }
7043
7044 pub fn convert_to_snake_case(
7045 &mut self,
7046 _: &ConvertToSnakeCase,
7047 window: &mut Window,
7048 cx: &mut Context<Self>,
7049 ) {
7050 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7051 }
7052
7053 pub fn convert_to_kebab_case(
7054 &mut self,
7055 _: &ConvertToKebabCase,
7056 window: &mut Window,
7057 cx: &mut Context<Self>,
7058 ) {
7059 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7060 }
7061
7062 pub fn convert_to_upper_camel_case(
7063 &mut self,
7064 _: &ConvertToUpperCamelCase,
7065 window: &mut Window,
7066 cx: &mut Context<Self>,
7067 ) {
7068 self.manipulate_text(window, cx, |text| {
7069 text.split('\n')
7070 .map(|line| line.to_case(Case::UpperCamel))
7071 .join("\n")
7072 })
7073 }
7074
7075 pub fn convert_to_lower_camel_case(
7076 &mut self,
7077 _: &ConvertToLowerCamelCase,
7078 window: &mut Window,
7079 cx: &mut Context<Self>,
7080 ) {
7081 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
7082 }
7083
7084 pub fn convert_to_opposite_case(
7085 &mut self,
7086 _: &ConvertToOppositeCase,
7087 window: &mut Window,
7088 cx: &mut Context<Self>,
7089 ) {
7090 self.manipulate_text(window, cx, |text| {
7091 text.chars()
7092 .fold(String::with_capacity(text.len()), |mut t, c| {
7093 if c.is_uppercase() {
7094 t.extend(c.to_lowercase());
7095 } else {
7096 t.extend(c.to_uppercase());
7097 }
7098 t
7099 })
7100 })
7101 }
7102
7103 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
7104 where
7105 Fn: FnMut(&str) -> String,
7106 {
7107 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7108 let buffer = self.buffer.read(cx).snapshot(cx);
7109
7110 let mut new_selections = Vec::new();
7111 let mut edits = Vec::new();
7112 let mut selection_adjustment = 0i32;
7113
7114 for selection in self.selections.all::<usize>(cx) {
7115 let selection_is_empty = selection.is_empty();
7116
7117 let (start, end) = if selection_is_empty {
7118 let word_range = movement::surrounding_word(
7119 &display_map,
7120 selection.start.to_display_point(&display_map),
7121 );
7122 let start = word_range.start.to_offset(&display_map, Bias::Left);
7123 let end = word_range.end.to_offset(&display_map, Bias::Left);
7124 (start, end)
7125 } else {
7126 (selection.start, selection.end)
7127 };
7128
7129 let text = buffer.text_for_range(start..end).collect::<String>();
7130 let old_length = text.len() as i32;
7131 let text = callback(&text);
7132
7133 new_selections.push(Selection {
7134 start: (start as i32 - selection_adjustment) as usize,
7135 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
7136 goal: SelectionGoal::None,
7137 ..selection
7138 });
7139
7140 selection_adjustment += old_length - text.len() as i32;
7141
7142 edits.push((start..end, text));
7143 }
7144
7145 self.transact(window, cx, |this, window, cx| {
7146 this.buffer.update(cx, |buffer, cx| {
7147 buffer.edit(edits, None, cx);
7148 });
7149
7150 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7151 s.select(new_selections);
7152 });
7153
7154 this.request_autoscroll(Autoscroll::fit(), cx);
7155 });
7156 }
7157
7158 pub fn duplicate(
7159 &mut self,
7160 upwards: bool,
7161 whole_lines: bool,
7162 window: &mut Window,
7163 cx: &mut Context<Self>,
7164 ) {
7165 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7166 let buffer = &display_map.buffer_snapshot;
7167 let selections = self.selections.all::<Point>(cx);
7168
7169 let mut edits = Vec::new();
7170 let mut selections_iter = selections.iter().peekable();
7171 while let Some(selection) = selections_iter.next() {
7172 let mut rows = selection.spanned_rows(false, &display_map);
7173 // duplicate line-wise
7174 if whole_lines || selection.start == selection.end {
7175 // Avoid duplicating the same lines twice.
7176 while let Some(next_selection) = selections_iter.peek() {
7177 let next_rows = next_selection.spanned_rows(false, &display_map);
7178 if next_rows.start < rows.end {
7179 rows.end = next_rows.end;
7180 selections_iter.next().unwrap();
7181 } else {
7182 break;
7183 }
7184 }
7185
7186 // Copy the text from the selected row region and splice it either at the start
7187 // or end of the region.
7188 let start = Point::new(rows.start.0, 0);
7189 let end = Point::new(
7190 rows.end.previous_row().0,
7191 buffer.line_len(rows.end.previous_row()),
7192 );
7193 let text = buffer
7194 .text_for_range(start..end)
7195 .chain(Some("\n"))
7196 .collect::<String>();
7197 let insert_location = if upwards {
7198 Point::new(rows.end.0, 0)
7199 } else {
7200 start
7201 };
7202 edits.push((insert_location..insert_location, text));
7203 } else {
7204 // duplicate character-wise
7205 let start = selection.start;
7206 let end = selection.end;
7207 let text = buffer.text_for_range(start..end).collect::<String>();
7208 edits.push((selection.end..selection.end, text));
7209 }
7210 }
7211
7212 self.transact(window, cx, |this, _, cx| {
7213 this.buffer.update(cx, |buffer, cx| {
7214 buffer.edit(edits, None, cx);
7215 });
7216
7217 this.request_autoscroll(Autoscroll::fit(), cx);
7218 });
7219 }
7220
7221 pub fn duplicate_line_up(
7222 &mut self,
7223 _: &DuplicateLineUp,
7224 window: &mut Window,
7225 cx: &mut Context<Self>,
7226 ) {
7227 self.duplicate(true, true, window, cx);
7228 }
7229
7230 pub fn duplicate_line_down(
7231 &mut self,
7232 _: &DuplicateLineDown,
7233 window: &mut Window,
7234 cx: &mut Context<Self>,
7235 ) {
7236 self.duplicate(false, true, window, cx);
7237 }
7238
7239 pub fn duplicate_selection(
7240 &mut self,
7241 _: &DuplicateSelection,
7242 window: &mut Window,
7243 cx: &mut Context<Self>,
7244 ) {
7245 self.duplicate(false, false, window, cx);
7246 }
7247
7248 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7249 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7250 let buffer = self.buffer.read(cx).snapshot(cx);
7251
7252 let mut edits = Vec::new();
7253 let mut unfold_ranges = Vec::new();
7254 let mut refold_creases = Vec::new();
7255
7256 let selections = self.selections.all::<Point>(cx);
7257 let mut selections = selections.iter().peekable();
7258 let mut contiguous_row_selections = Vec::new();
7259 let mut new_selections = Vec::new();
7260
7261 while let Some(selection) = selections.next() {
7262 // Find all the selections that span a contiguous row range
7263 let (start_row, end_row) = consume_contiguous_rows(
7264 &mut contiguous_row_selections,
7265 selection,
7266 &display_map,
7267 &mut selections,
7268 );
7269
7270 // Move the text spanned by the row range to be before the line preceding the row range
7271 if start_row.0 > 0 {
7272 let range_to_move = Point::new(
7273 start_row.previous_row().0,
7274 buffer.line_len(start_row.previous_row()),
7275 )
7276 ..Point::new(
7277 end_row.previous_row().0,
7278 buffer.line_len(end_row.previous_row()),
7279 );
7280 let insertion_point = display_map
7281 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7282 .0;
7283
7284 // Don't move lines across excerpts
7285 if buffer
7286 .excerpt_containing(insertion_point..range_to_move.end)
7287 .is_some()
7288 {
7289 let text = buffer
7290 .text_for_range(range_to_move.clone())
7291 .flat_map(|s| s.chars())
7292 .skip(1)
7293 .chain(['\n'])
7294 .collect::<String>();
7295
7296 edits.push((
7297 buffer.anchor_after(range_to_move.start)
7298 ..buffer.anchor_before(range_to_move.end),
7299 String::new(),
7300 ));
7301 let insertion_anchor = buffer.anchor_after(insertion_point);
7302 edits.push((insertion_anchor..insertion_anchor, text));
7303
7304 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7305
7306 // Move selections up
7307 new_selections.extend(contiguous_row_selections.drain(..).map(
7308 |mut selection| {
7309 selection.start.row -= row_delta;
7310 selection.end.row -= row_delta;
7311 selection
7312 },
7313 ));
7314
7315 // Move folds up
7316 unfold_ranges.push(range_to_move.clone());
7317 for fold in display_map.folds_in_range(
7318 buffer.anchor_before(range_to_move.start)
7319 ..buffer.anchor_after(range_to_move.end),
7320 ) {
7321 let mut start = fold.range.start.to_point(&buffer);
7322 let mut end = fold.range.end.to_point(&buffer);
7323 start.row -= row_delta;
7324 end.row -= row_delta;
7325 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7326 }
7327 }
7328 }
7329
7330 // If we didn't move line(s), preserve the existing selections
7331 new_selections.append(&mut contiguous_row_selections);
7332 }
7333
7334 self.transact(window, cx, |this, window, cx| {
7335 this.unfold_ranges(&unfold_ranges, true, true, cx);
7336 this.buffer.update(cx, |buffer, cx| {
7337 for (range, text) in edits {
7338 buffer.edit([(range, text)], None, cx);
7339 }
7340 });
7341 this.fold_creases(refold_creases, true, window, cx);
7342 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7343 s.select(new_selections);
7344 })
7345 });
7346 }
7347
7348 pub fn move_line_down(
7349 &mut self,
7350 _: &MoveLineDown,
7351 window: &mut Window,
7352 cx: &mut Context<Self>,
7353 ) {
7354 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7355 let buffer = self.buffer.read(cx).snapshot(cx);
7356
7357 let mut edits = Vec::new();
7358 let mut unfold_ranges = Vec::new();
7359 let mut refold_creases = Vec::new();
7360
7361 let selections = self.selections.all::<Point>(cx);
7362 let mut selections = selections.iter().peekable();
7363 let mut contiguous_row_selections = Vec::new();
7364 let mut new_selections = Vec::new();
7365
7366 while let Some(selection) = selections.next() {
7367 // Find all the selections that span a contiguous row range
7368 let (start_row, end_row) = consume_contiguous_rows(
7369 &mut contiguous_row_selections,
7370 selection,
7371 &display_map,
7372 &mut selections,
7373 );
7374
7375 // Move the text spanned by the row range to be after the last line of the row range
7376 if end_row.0 <= buffer.max_point().row {
7377 let range_to_move =
7378 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7379 let insertion_point = display_map
7380 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7381 .0;
7382
7383 // Don't move lines across excerpt boundaries
7384 if buffer
7385 .excerpt_containing(range_to_move.start..insertion_point)
7386 .is_some()
7387 {
7388 let mut text = String::from("\n");
7389 text.extend(buffer.text_for_range(range_to_move.clone()));
7390 text.pop(); // Drop trailing newline
7391 edits.push((
7392 buffer.anchor_after(range_to_move.start)
7393 ..buffer.anchor_before(range_to_move.end),
7394 String::new(),
7395 ));
7396 let insertion_anchor = buffer.anchor_after(insertion_point);
7397 edits.push((insertion_anchor..insertion_anchor, text));
7398
7399 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7400
7401 // Move selections down
7402 new_selections.extend(contiguous_row_selections.drain(..).map(
7403 |mut selection| {
7404 selection.start.row += row_delta;
7405 selection.end.row += row_delta;
7406 selection
7407 },
7408 ));
7409
7410 // Move folds down
7411 unfold_ranges.push(range_to_move.clone());
7412 for fold in display_map.folds_in_range(
7413 buffer.anchor_before(range_to_move.start)
7414 ..buffer.anchor_after(range_to_move.end),
7415 ) {
7416 let mut start = fold.range.start.to_point(&buffer);
7417 let mut end = fold.range.end.to_point(&buffer);
7418 start.row += row_delta;
7419 end.row += row_delta;
7420 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7421 }
7422 }
7423 }
7424
7425 // If we didn't move line(s), preserve the existing selections
7426 new_selections.append(&mut contiguous_row_selections);
7427 }
7428
7429 self.transact(window, cx, |this, window, cx| {
7430 this.unfold_ranges(&unfold_ranges, true, true, cx);
7431 this.buffer.update(cx, |buffer, cx| {
7432 for (range, text) in edits {
7433 buffer.edit([(range, text)], None, cx);
7434 }
7435 });
7436 this.fold_creases(refold_creases, true, window, cx);
7437 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7438 s.select(new_selections)
7439 });
7440 });
7441 }
7442
7443 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7444 let text_layout_details = &self.text_layout_details(window);
7445 self.transact(window, cx, |this, window, cx| {
7446 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7447 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7448 let line_mode = s.line_mode;
7449 s.move_with(|display_map, selection| {
7450 if !selection.is_empty() || line_mode {
7451 return;
7452 }
7453
7454 let mut head = selection.head();
7455 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7456 if head.column() == display_map.line_len(head.row()) {
7457 transpose_offset = display_map
7458 .buffer_snapshot
7459 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7460 }
7461
7462 if transpose_offset == 0 {
7463 return;
7464 }
7465
7466 *head.column_mut() += 1;
7467 head = display_map.clip_point(head, Bias::Right);
7468 let goal = SelectionGoal::HorizontalPosition(
7469 display_map
7470 .x_for_display_point(head, text_layout_details)
7471 .into(),
7472 );
7473 selection.collapse_to(head, goal);
7474
7475 let transpose_start = display_map
7476 .buffer_snapshot
7477 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7478 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7479 let transpose_end = display_map
7480 .buffer_snapshot
7481 .clip_offset(transpose_offset + 1, Bias::Right);
7482 if let Some(ch) =
7483 display_map.buffer_snapshot.chars_at(transpose_start).next()
7484 {
7485 edits.push((transpose_start..transpose_offset, String::new()));
7486 edits.push((transpose_end..transpose_end, ch.to_string()));
7487 }
7488 }
7489 });
7490 edits
7491 });
7492 this.buffer
7493 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7494 let selections = this.selections.all::<usize>(cx);
7495 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7496 s.select(selections);
7497 });
7498 });
7499 }
7500
7501 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7502 self.rewrap_impl(IsVimMode::No, cx)
7503 }
7504
7505 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7506 let buffer = self.buffer.read(cx).snapshot(cx);
7507 let selections = self.selections.all::<Point>(cx);
7508 let mut selections = selections.iter().peekable();
7509
7510 let mut edits = Vec::new();
7511 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7512
7513 while let Some(selection) = selections.next() {
7514 let mut start_row = selection.start.row;
7515 let mut end_row = selection.end.row;
7516
7517 // Skip selections that overlap with a range that has already been rewrapped.
7518 let selection_range = start_row..end_row;
7519 if rewrapped_row_ranges
7520 .iter()
7521 .any(|range| range.overlaps(&selection_range))
7522 {
7523 continue;
7524 }
7525
7526 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7527
7528 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7529 match language_scope.language_name().as_ref() {
7530 "Markdown" | "Plain Text" => {
7531 should_rewrap = true;
7532 }
7533 _ => {}
7534 }
7535 }
7536
7537 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7538
7539 // Since not all lines in the selection may be at the same indent
7540 // level, choose the indent size that is the most common between all
7541 // of the lines.
7542 //
7543 // If there is a tie, we use the deepest indent.
7544 let (indent_size, indent_end) = {
7545 let mut indent_size_occurrences = HashMap::default();
7546 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7547
7548 for row in start_row..=end_row {
7549 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7550 rows_by_indent_size.entry(indent).or_default().push(row);
7551 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7552 }
7553
7554 let indent_size = indent_size_occurrences
7555 .into_iter()
7556 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7557 .map(|(indent, _)| indent)
7558 .unwrap_or_default();
7559 let row = rows_by_indent_size[&indent_size][0];
7560 let indent_end = Point::new(row, indent_size.len);
7561
7562 (indent_size, indent_end)
7563 };
7564
7565 let mut line_prefix = indent_size.chars().collect::<String>();
7566
7567 if let Some(comment_prefix) =
7568 buffer
7569 .language_scope_at(selection.head())
7570 .and_then(|language| {
7571 language
7572 .line_comment_prefixes()
7573 .iter()
7574 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7575 .cloned()
7576 })
7577 {
7578 line_prefix.push_str(&comment_prefix);
7579 should_rewrap = true;
7580 }
7581
7582 if !should_rewrap {
7583 continue;
7584 }
7585
7586 if selection.is_empty() {
7587 'expand_upwards: while start_row > 0 {
7588 let prev_row = start_row - 1;
7589 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7590 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7591 {
7592 start_row = prev_row;
7593 } else {
7594 break 'expand_upwards;
7595 }
7596 }
7597
7598 'expand_downwards: while end_row < buffer.max_point().row {
7599 let next_row = end_row + 1;
7600 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7601 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7602 {
7603 end_row = next_row;
7604 } else {
7605 break 'expand_downwards;
7606 }
7607 }
7608 }
7609
7610 let start = Point::new(start_row, 0);
7611 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7612 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7613 let Some(lines_without_prefixes) = selection_text
7614 .lines()
7615 .map(|line| {
7616 line.strip_prefix(&line_prefix)
7617 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7618 .ok_or_else(|| {
7619 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7620 })
7621 })
7622 .collect::<Result<Vec<_>, _>>()
7623 .log_err()
7624 else {
7625 continue;
7626 };
7627
7628 let wrap_column = buffer
7629 .settings_at(Point::new(start_row, 0), cx)
7630 .preferred_line_length as usize;
7631 let wrapped_text = wrap_with_prefix(
7632 line_prefix,
7633 lines_without_prefixes.join(" "),
7634 wrap_column,
7635 tab_size,
7636 );
7637
7638 // TODO: should always use char-based diff while still supporting cursor behavior that
7639 // matches vim.
7640 let diff = match is_vim_mode {
7641 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7642 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7643 };
7644 let mut offset = start.to_offset(&buffer);
7645 let mut moved_since_edit = true;
7646
7647 for change in diff.iter_all_changes() {
7648 let value = change.value();
7649 match change.tag() {
7650 ChangeTag::Equal => {
7651 offset += value.len();
7652 moved_since_edit = true;
7653 }
7654 ChangeTag::Delete => {
7655 let start = buffer.anchor_after(offset);
7656 let end = buffer.anchor_before(offset + value.len());
7657
7658 if moved_since_edit {
7659 edits.push((start..end, String::new()));
7660 } else {
7661 edits.last_mut().unwrap().0.end = end;
7662 }
7663
7664 offset += value.len();
7665 moved_since_edit = false;
7666 }
7667 ChangeTag::Insert => {
7668 if moved_since_edit {
7669 let anchor = buffer.anchor_after(offset);
7670 edits.push((anchor..anchor, value.to_string()));
7671 } else {
7672 edits.last_mut().unwrap().1.push_str(value);
7673 }
7674
7675 moved_since_edit = false;
7676 }
7677 }
7678 }
7679
7680 rewrapped_row_ranges.push(start_row..=end_row);
7681 }
7682
7683 self.buffer
7684 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7685 }
7686
7687 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7688 let mut text = String::new();
7689 let buffer = self.buffer.read(cx).snapshot(cx);
7690 let mut selections = self.selections.all::<Point>(cx);
7691 let mut clipboard_selections = Vec::with_capacity(selections.len());
7692 {
7693 let max_point = buffer.max_point();
7694 let mut is_first = true;
7695 for selection in &mut selections {
7696 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7697 if is_entire_line {
7698 selection.start = Point::new(selection.start.row, 0);
7699 if !selection.is_empty() && selection.end.column == 0 {
7700 selection.end = cmp::min(max_point, selection.end);
7701 } else {
7702 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7703 }
7704 selection.goal = SelectionGoal::None;
7705 }
7706 if is_first {
7707 is_first = false;
7708 } else {
7709 text += "\n";
7710 }
7711 let mut len = 0;
7712 for chunk in buffer.text_for_range(selection.start..selection.end) {
7713 text.push_str(chunk);
7714 len += chunk.len();
7715 }
7716 clipboard_selections.push(ClipboardSelection {
7717 len,
7718 is_entire_line,
7719 first_line_indent: buffer
7720 .indent_size_for_line(MultiBufferRow(selection.start.row))
7721 .len,
7722 });
7723 }
7724 }
7725
7726 self.transact(window, cx, |this, window, cx| {
7727 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7728 s.select(selections);
7729 });
7730 this.insert("", window, cx);
7731 });
7732 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7733 }
7734
7735 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
7736 let item = self.cut_common(window, cx);
7737 cx.write_to_clipboard(item);
7738 }
7739
7740 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
7741 self.change_selections(None, window, cx, |s| {
7742 s.move_with(|snapshot, sel| {
7743 if sel.is_empty() {
7744 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7745 }
7746 });
7747 });
7748 let item = self.cut_common(window, cx);
7749 cx.set_global(KillRing(item))
7750 }
7751
7752 pub fn kill_ring_yank(
7753 &mut self,
7754 _: &KillRingYank,
7755 window: &mut Window,
7756 cx: &mut Context<Self>,
7757 ) {
7758 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7759 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7760 (kill_ring.text().to_string(), kill_ring.metadata_json())
7761 } else {
7762 return;
7763 }
7764 } else {
7765 return;
7766 };
7767 self.do_paste(&text, metadata, false, window, cx);
7768 }
7769
7770 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
7771 let selections = self.selections.all::<Point>(cx);
7772 let buffer = self.buffer.read(cx).read(cx);
7773 let mut text = String::new();
7774
7775 let mut clipboard_selections = Vec::with_capacity(selections.len());
7776 {
7777 let max_point = buffer.max_point();
7778 let mut is_first = true;
7779 for selection in selections.iter() {
7780 let mut start = selection.start;
7781 let mut end = selection.end;
7782 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7783 if is_entire_line {
7784 start = Point::new(start.row, 0);
7785 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7786 }
7787 if is_first {
7788 is_first = false;
7789 } else {
7790 text += "\n";
7791 }
7792 let mut len = 0;
7793 for chunk in buffer.text_for_range(start..end) {
7794 text.push_str(chunk);
7795 len += chunk.len();
7796 }
7797 clipboard_selections.push(ClipboardSelection {
7798 len,
7799 is_entire_line,
7800 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7801 });
7802 }
7803 }
7804
7805 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7806 text,
7807 clipboard_selections,
7808 ));
7809 }
7810
7811 pub fn do_paste(
7812 &mut self,
7813 text: &String,
7814 clipboard_selections: Option<Vec<ClipboardSelection>>,
7815 handle_entire_lines: bool,
7816 window: &mut Window,
7817 cx: &mut Context<Self>,
7818 ) {
7819 if self.read_only(cx) {
7820 return;
7821 }
7822
7823 let clipboard_text = Cow::Borrowed(text);
7824
7825 self.transact(window, cx, |this, window, cx| {
7826 if let Some(mut clipboard_selections) = clipboard_selections {
7827 let old_selections = this.selections.all::<usize>(cx);
7828 let all_selections_were_entire_line =
7829 clipboard_selections.iter().all(|s| s.is_entire_line);
7830 let first_selection_indent_column =
7831 clipboard_selections.first().map(|s| s.first_line_indent);
7832 if clipboard_selections.len() != old_selections.len() {
7833 clipboard_selections.drain(..);
7834 }
7835 let cursor_offset = this.selections.last::<usize>(cx).head();
7836 let mut auto_indent_on_paste = true;
7837
7838 this.buffer.update(cx, |buffer, cx| {
7839 let snapshot = buffer.read(cx);
7840 auto_indent_on_paste =
7841 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7842
7843 let mut start_offset = 0;
7844 let mut edits = Vec::new();
7845 let mut original_indent_columns = Vec::new();
7846 for (ix, selection) in old_selections.iter().enumerate() {
7847 let to_insert;
7848 let entire_line;
7849 let original_indent_column;
7850 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7851 let end_offset = start_offset + clipboard_selection.len;
7852 to_insert = &clipboard_text[start_offset..end_offset];
7853 entire_line = clipboard_selection.is_entire_line;
7854 start_offset = end_offset + 1;
7855 original_indent_column = Some(clipboard_selection.first_line_indent);
7856 } else {
7857 to_insert = clipboard_text.as_str();
7858 entire_line = all_selections_were_entire_line;
7859 original_indent_column = first_selection_indent_column
7860 }
7861
7862 // If the corresponding selection was empty when this slice of the
7863 // clipboard text was written, then the entire line containing the
7864 // selection was copied. If this selection is also currently empty,
7865 // then paste the line before the current line of the buffer.
7866 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7867 let column = selection.start.to_point(&snapshot).column as usize;
7868 let line_start = selection.start - column;
7869 line_start..line_start
7870 } else {
7871 selection.range()
7872 };
7873
7874 edits.push((range, to_insert));
7875 original_indent_columns.extend(original_indent_column);
7876 }
7877 drop(snapshot);
7878
7879 buffer.edit(
7880 edits,
7881 if auto_indent_on_paste {
7882 Some(AutoindentMode::Block {
7883 original_indent_columns,
7884 })
7885 } else {
7886 None
7887 },
7888 cx,
7889 );
7890 });
7891
7892 let selections = this.selections.all::<usize>(cx);
7893 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7894 s.select(selections)
7895 });
7896 } else {
7897 this.insert(&clipboard_text, window, cx);
7898 }
7899 });
7900 }
7901
7902 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
7903 if let Some(item) = cx.read_from_clipboard() {
7904 let entries = item.entries();
7905
7906 match entries.first() {
7907 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7908 // of all the pasted entries.
7909 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7910 .do_paste(
7911 clipboard_string.text(),
7912 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7913 true,
7914 window,
7915 cx,
7916 ),
7917 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
7918 }
7919 }
7920 }
7921
7922 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
7923 if self.read_only(cx) {
7924 return;
7925 }
7926
7927 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7928 if let Some((selections, _)) =
7929 self.selection_history.transaction(transaction_id).cloned()
7930 {
7931 self.change_selections(None, window, cx, |s| {
7932 s.select_anchors(selections.to_vec());
7933 });
7934 }
7935 self.request_autoscroll(Autoscroll::fit(), cx);
7936 self.unmark_text(window, cx);
7937 self.refresh_inline_completion(true, false, window, cx);
7938 cx.emit(EditorEvent::Edited { transaction_id });
7939 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7940 }
7941 }
7942
7943 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
7944 if self.read_only(cx) {
7945 return;
7946 }
7947
7948 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7949 if let Some((_, Some(selections))) =
7950 self.selection_history.transaction(transaction_id).cloned()
7951 {
7952 self.change_selections(None, window, cx, |s| {
7953 s.select_anchors(selections.to_vec());
7954 });
7955 }
7956 self.request_autoscroll(Autoscroll::fit(), cx);
7957 self.unmark_text(window, cx);
7958 self.refresh_inline_completion(true, false, window, cx);
7959 cx.emit(EditorEvent::Edited { transaction_id });
7960 }
7961 }
7962
7963 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
7964 self.buffer
7965 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7966 }
7967
7968 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
7969 self.buffer
7970 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7971 }
7972
7973 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
7974 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7975 let line_mode = s.line_mode;
7976 s.move_with(|map, selection| {
7977 let cursor = if selection.is_empty() && !line_mode {
7978 movement::left(map, selection.start)
7979 } else {
7980 selection.start
7981 };
7982 selection.collapse_to(cursor, SelectionGoal::None);
7983 });
7984 })
7985 }
7986
7987 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
7988 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7989 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7990 })
7991 }
7992
7993 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
7994 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7995 let line_mode = s.line_mode;
7996 s.move_with(|map, selection| {
7997 let cursor = if selection.is_empty() && !line_mode {
7998 movement::right(map, selection.end)
7999 } else {
8000 selection.end
8001 };
8002 selection.collapse_to(cursor, SelectionGoal::None)
8003 });
8004 })
8005 }
8006
8007 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
8008 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8009 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
8010 })
8011 }
8012
8013 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
8014 if self.take_rename(true, window, cx).is_some() {
8015 return;
8016 }
8017
8018 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8019 cx.propagate();
8020 return;
8021 }
8022
8023 let text_layout_details = &self.text_layout_details(window);
8024 let selection_count = self.selections.count();
8025 let first_selection = self.selections.first_anchor();
8026
8027 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8028 let line_mode = s.line_mode;
8029 s.move_with(|map, selection| {
8030 if !selection.is_empty() && !line_mode {
8031 selection.goal = SelectionGoal::None;
8032 }
8033 let (cursor, goal) = movement::up(
8034 map,
8035 selection.start,
8036 selection.goal,
8037 false,
8038 text_layout_details,
8039 );
8040 selection.collapse_to(cursor, goal);
8041 });
8042 });
8043
8044 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8045 {
8046 cx.propagate();
8047 }
8048 }
8049
8050 pub fn move_up_by_lines(
8051 &mut self,
8052 action: &MoveUpByLines,
8053 window: &mut Window,
8054 cx: &mut Context<Self>,
8055 ) {
8056 if self.take_rename(true, window, cx).is_some() {
8057 return;
8058 }
8059
8060 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8061 cx.propagate();
8062 return;
8063 }
8064
8065 let text_layout_details = &self.text_layout_details(window);
8066
8067 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8068 let line_mode = s.line_mode;
8069 s.move_with(|map, selection| {
8070 if !selection.is_empty() && !line_mode {
8071 selection.goal = SelectionGoal::None;
8072 }
8073 let (cursor, goal) = movement::up_by_rows(
8074 map,
8075 selection.start,
8076 action.lines,
8077 selection.goal,
8078 false,
8079 text_layout_details,
8080 );
8081 selection.collapse_to(cursor, goal);
8082 });
8083 })
8084 }
8085
8086 pub fn move_down_by_lines(
8087 &mut self,
8088 action: &MoveDownByLines,
8089 window: &mut Window,
8090 cx: &mut Context<Self>,
8091 ) {
8092 if self.take_rename(true, window, cx).is_some() {
8093 return;
8094 }
8095
8096 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8097 cx.propagate();
8098 return;
8099 }
8100
8101 let text_layout_details = &self.text_layout_details(window);
8102
8103 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8104 let line_mode = s.line_mode;
8105 s.move_with(|map, selection| {
8106 if !selection.is_empty() && !line_mode {
8107 selection.goal = SelectionGoal::None;
8108 }
8109 let (cursor, goal) = movement::down_by_rows(
8110 map,
8111 selection.start,
8112 action.lines,
8113 selection.goal,
8114 false,
8115 text_layout_details,
8116 );
8117 selection.collapse_to(cursor, goal);
8118 });
8119 })
8120 }
8121
8122 pub fn select_down_by_lines(
8123 &mut self,
8124 action: &SelectDownByLines,
8125 window: &mut Window,
8126 cx: &mut Context<Self>,
8127 ) {
8128 let text_layout_details = &self.text_layout_details(window);
8129 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8130 s.move_heads_with(|map, head, goal| {
8131 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
8132 })
8133 })
8134 }
8135
8136 pub fn select_up_by_lines(
8137 &mut self,
8138 action: &SelectUpByLines,
8139 window: &mut Window,
8140 cx: &mut Context<Self>,
8141 ) {
8142 let text_layout_details = &self.text_layout_details(window);
8143 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8144 s.move_heads_with(|map, head, goal| {
8145 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8146 })
8147 })
8148 }
8149
8150 pub fn select_page_up(
8151 &mut self,
8152 _: &SelectPageUp,
8153 window: &mut Window,
8154 cx: &mut Context<Self>,
8155 ) {
8156 let Some(row_count) = self.visible_row_count() else {
8157 return;
8158 };
8159
8160 let text_layout_details = &self.text_layout_details(window);
8161
8162 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8163 s.move_heads_with(|map, head, goal| {
8164 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8165 })
8166 })
8167 }
8168
8169 pub fn move_page_up(
8170 &mut self,
8171 action: &MovePageUp,
8172 window: &mut Window,
8173 cx: &mut Context<Self>,
8174 ) {
8175 if self.take_rename(true, window, cx).is_some() {
8176 return;
8177 }
8178
8179 if self
8180 .context_menu
8181 .borrow_mut()
8182 .as_mut()
8183 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8184 .unwrap_or(false)
8185 {
8186 return;
8187 }
8188
8189 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8190 cx.propagate();
8191 return;
8192 }
8193
8194 let Some(row_count) = self.visible_row_count() else {
8195 return;
8196 };
8197
8198 let autoscroll = if action.center_cursor {
8199 Autoscroll::center()
8200 } else {
8201 Autoscroll::fit()
8202 };
8203
8204 let text_layout_details = &self.text_layout_details(window);
8205
8206 self.change_selections(Some(autoscroll), window, cx, |s| {
8207 let line_mode = s.line_mode;
8208 s.move_with(|map, selection| {
8209 if !selection.is_empty() && !line_mode {
8210 selection.goal = SelectionGoal::None;
8211 }
8212 let (cursor, goal) = movement::up_by_rows(
8213 map,
8214 selection.end,
8215 row_count,
8216 selection.goal,
8217 false,
8218 text_layout_details,
8219 );
8220 selection.collapse_to(cursor, goal);
8221 });
8222 });
8223 }
8224
8225 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8226 let text_layout_details = &self.text_layout_details(window);
8227 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8228 s.move_heads_with(|map, head, goal| {
8229 movement::up(map, head, goal, false, text_layout_details)
8230 })
8231 })
8232 }
8233
8234 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8235 self.take_rename(true, window, cx);
8236
8237 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8238 cx.propagate();
8239 return;
8240 }
8241
8242 let text_layout_details = &self.text_layout_details(window);
8243 let selection_count = self.selections.count();
8244 let first_selection = self.selections.first_anchor();
8245
8246 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8247 let line_mode = s.line_mode;
8248 s.move_with(|map, selection| {
8249 if !selection.is_empty() && !line_mode {
8250 selection.goal = SelectionGoal::None;
8251 }
8252 let (cursor, goal) = movement::down(
8253 map,
8254 selection.end,
8255 selection.goal,
8256 false,
8257 text_layout_details,
8258 );
8259 selection.collapse_to(cursor, goal);
8260 });
8261 });
8262
8263 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8264 {
8265 cx.propagate();
8266 }
8267 }
8268
8269 pub fn select_page_down(
8270 &mut self,
8271 _: &SelectPageDown,
8272 window: &mut Window,
8273 cx: &mut Context<Self>,
8274 ) {
8275 let Some(row_count) = self.visible_row_count() else {
8276 return;
8277 };
8278
8279 let text_layout_details = &self.text_layout_details(window);
8280
8281 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8282 s.move_heads_with(|map, head, goal| {
8283 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8284 })
8285 })
8286 }
8287
8288 pub fn move_page_down(
8289 &mut self,
8290 action: &MovePageDown,
8291 window: &mut Window,
8292 cx: &mut Context<Self>,
8293 ) {
8294 if self.take_rename(true, window, cx).is_some() {
8295 return;
8296 }
8297
8298 if self
8299 .context_menu
8300 .borrow_mut()
8301 .as_mut()
8302 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8303 .unwrap_or(false)
8304 {
8305 return;
8306 }
8307
8308 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8309 cx.propagate();
8310 return;
8311 }
8312
8313 let Some(row_count) = self.visible_row_count() else {
8314 return;
8315 };
8316
8317 let autoscroll = if action.center_cursor {
8318 Autoscroll::center()
8319 } else {
8320 Autoscroll::fit()
8321 };
8322
8323 let text_layout_details = &self.text_layout_details(window);
8324 self.change_selections(Some(autoscroll), window, cx, |s| {
8325 let line_mode = s.line_mode;
8326 s.move_with(|map, selection| {
8327 if !selection.is_empty() && !line_mode {
8328 selection.goal = SelectionGoal::None;
8329 }
8330 let (cursor, goal) = movement::down_by_rows(
8331 map,
8332 selection.end,
8333 row_count,
8334 selection.goal,
8335 false,
8336 text_layout_details,
8337 );
8338 selection.collapse_to(cursor, goal);
8339 });
8340 });
8341 }
8342
8343 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8344 let text_layout_details = &self.text_layout_details(window);
8345 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8346 s.move_heads_with(|map, head, goal| {
8347 movement::down(map, head, goal, false, text_layout_details)
8348 })
8349 });
8350 }
8351
8352 pub fn context_menu_first(
8353 &mut self,
8354 _: &ContextMenuFirst,
8355 _window: &mut Window,
8356 cx: &mut Context<Self>,
8357 ) {
8358 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8359 context_menu.select_first(self.completion_provider.as_deref(), cx);
8360 }
8361 }
8362
8363 pub fn context_menu_prev(
8364 &mut self,
8365 _: &ContextMenuPrev,
8366 _window: &mut Window,
8367 cx: &mut Context<Self>,
8368 ) {
8369 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8370 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8371 }
8372 }
8373
8374 pub fn context_menu_next(
8375 &mut self,
8376 _: &ContextMenuNext,
8377 _window: &mut Window,
8378 cx: &mut Context<Self>,
8379 ) {
8380 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8381 context_menu.select_next(self.completion_provider.as_deref(), cx);
8382 }
8383 }
8384
8385 pub fn context_menu_last(
8386 &mut self,
8387 _: &ContextMenuLast,
8388 _window: &mut Window,
8389 cx: &mut Context<Self>,
8390 ) {
8391 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8392 context_menu.select_last(self.completion_provider.as_deref(), cx);
8393 }
8394 }
8395
8396 pub fn move_to_previous_word_start(
8397 &mut self,
8398 _: &MoveToPreviousWordStart,
8399 window: &mut Window,
8400 cx: &mut Context<Self>,
8401 ) {
8402 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8403 s.move_cursors_with(|map, head, _| {
8404 (
8405 movement::previous_word_start(map, head),
8406 SelectionGoal::None,
8407 )
8408 });
8409 })
8410 }
8411
8412 pub fn move_to_previous_subword_start(
8413 &mut self,
8414 _: &MoveToPreviousSubwordStart,
8415 window: &mut Window,
8416 cx: &mut Context<Self>,
8417 ) {
8418 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8419 s.move_cursors_with(|map, head, _| {
8420 (
8421 movement::previous_subword_start(map, head),
8422 SelectionGoal::None,
8423 )
8424 });
8425 })
8426 }
8427
8428 pub fn select_to_previous_word_start(
8429 &mut self,
8430 _: &SelectToPreviousWordStart,
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 (
8437 movement::previous_word_start(map, head),
8438 SelectionGoal::None,
8439 )
8440 });
8441 })
8442 }
8443
8444 pub fn select_to_previous_subword_start(
8445 &mut self,
8446 _: &SelectToPreviousSubwordStart,
8447 window: &mut Window,
8448 cx: &mut Context<Self>,
8449 ) {
8450 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8451 s.move_heads_with(|map, head, _| {
8452 (
8453 movement::previous_subword_start(map, head),
8454 SelectionGoal::None,
8455 )
8456 });
8457 })
8458 }
8459
8460 pub fn delete_to_previous_word_start(
8461 &mut self,
8462 action: &DeleteToPreviousWordStart,
8463 window: &mut Window,
8464 cx: &mut Context<Self>,
8465 ) {
8466 self.transact(window, cx, |this, window, cx| {
8467 this.select_autoclose_pair(window, cx);
8468 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8469 let line_mode = s.line_mode;
8470 s.move_with(|map, selection| {
8471 if selection.is_empty() && !line_mode {
8472 let cursor = if action.ignore_newlines {
8473 movement::previous_word_start(map, selection.head())
8474 } else {
8475 movement::previous_word_start_or_newline(map, selection.head())
8476 };
8477 selection.set_head(cursor, SelectionGoal::None);
8478 }
8479 });
8480 });
8481 this.insert("", window, cx);
8482 });
8483 }
8484
8485 pub fn delete_to_previous_subword_start(
8486 &mut self,
8487 _: &DeleteToPreviousSubwordStart,
8488 window: &mut Window,
8489 cx: &mut Context<Self>,
8490 ) {
8491 self.transact(window, cx, |this, window, cx| {
8492 this.select_autoclose_pair(window, cx);
8493 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8494 let line_mode = s.line_mode;
8495 s.move_with(|map, selection| {
8496 if selection.is_empty() && !line_mode {
8497 let cursor = movement::previous_subword_start(map, selection.head());
8498 selection.set_head(cursor, SelectionGoal::None);
8499 }
8500 });
8501 });
8502 this.insert("", window, cx);
8503 });
8504 }
8505
8506 pub fn move_to_next_word_end(
8507 &mut self,
8508 _: &MoveToNextWordEnd,
8509 window: &mut Window,
8510 cx: &mut Context<Self>,
8511 ) {
8512 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8513 s.move_cursors_with(|map, head, _| {
8514 (movement::next_word_end(map, head), SelectionGoal::None)
8515 });
8516 })
8517 }
8518
8519 pub fn move_to_next_subword_end(
8520 &mut self,
8521 _: &MoveToNextSubwordEnd,
8522 window: &mut Window,
8523 cx: &mut Context<Self>,
8524 ) {
8525 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8526 s.move_cursors_with(|map, head, _| {
8527 (movement::next_subword_end(map, head), SelectionGoal::None)
8528 });
8529 })
8530 }
8531
8532 pub fn select_to_next_word_end(
8533 &mut self,
8534 _: &SelectToNextWordEnd,
8535 window: &mut Window,
8536 cx: &mut Context<Self>,
8537 ) {
8538 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8539 s.move_heads_with(|map, head, _| {
8540 (movement::next_word_end(map, head), SelectionGoal::None)
8541 });
8542 })
8543 }
8544
8545 pub fn select_to_next_subword_end(
8546 &mut self,
8547 _: &SelectToNextSubwordEnd,
8548 window: &mut Window,
8549 cx: &mut Context<Self>,
8550 ) {
8551 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8552 s.move_heads_with(|map, head, _| {
8553 (movement::next_subword_end(map, head), SelectionGoal::None)
8554 });
8555 })
8556 }
8557
8558 pub fn delete_to_next_word_end(
8559 &mut self,
8560 action: &DeleteToNextWordEnd,
8561 window: &mut Window,
8562 cx: &mut Context<Self>,
8563 ) {
8564 self.transact(window, cx, |this, window, cx| {
8565 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8566 let line_mode = s.line_mode;
8567 s.move_with(|map, selection| {
8568 if selection.is_empty() && !line_mode {
8569 let cursor = if action.ignore_newlines {
8570 movement::next_word_end(map, selection.head())
8571 } else {
8572 movement::next_word_end_or_newline(map, selection.head())
8573 };
8574 selection.set_head(cursor, SelectionGoal::None);
8575 }
8576 });
8577 });
8578 this.insert("", window, cx);
8579 });
8580 }
8581
8582 pub fn delete_to_next_subword_end(
8583 &mut self,
8584 _: &DeleteToNextSubwordEnd,
8585 window: &mut Window,
8586 cx: &mut Context<Self>,
8587 ) {
8588 self.transact(window, cx, |this, window, cx| {
8589 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8590 s.move_with(|map, selection| {
8591 if selection.is_empty() {
8592 let cursor = movement::next_subword_end(map, selection.head());
8593 selection.set_head(cursor, SelectionGoal::None);
8594 }
8595 });
8596 });
8597 this.insert("", window, cx);
8598 });
8599 }
8600
8601 pub fn move_to_beginning_of_line(
8602 &mut self,
8603 action: &MoveToBeginningOfLine,
8604 window: &mut Window,
8605 cx: &mut Context<Self>,
8606 ) {
8607 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8608 s.move_cursors_with(|map, head, _| {
8609 (
8610 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8611 SelectionGoal::None,
8612 )
8613 });
8614 })
8615 }
8616
8617 pub fn select_to_beginning_of_line(
8618 &mut self,
8619 action: &SelectToBeginningOfLine,
8620 window: &mut Window,
8621 cx: &mut Context<Self>,
8622 ) {
8623 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8624 s.move_heads_with(|map, head, _| {
8625 (
8626 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8627 SelectionGoal::None,
8628 )
8629 });
8630 });
8631 }
8632
8633 pub fn delete_to_beginning_of_line(
8634 &mut self,
8635 _: &DeleteToBeginningOfLine,
8636 window: &mut Window,
8637 cx: &mut Context<Self>,
8638 ) {
8639 self.transact(window, cx, |this, window, cx| {
8640 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8641 s.move_with(|_, selection| {
8642 selection.reversed = true;
8643 });
8644 });
8645
8646 this.select_to_beginning_of_line(
8647 &SelectToBeginningOfLine {
8648 stop_at_soft_wraps: false,
8649 },
8650 window,
8651 cx,
8652 );
8653 this.backspace(&Backspace, window, cx);
8654 });
8655 }
8656
8657 pub fn move_to_end_of_line(
8658 &mut self,
8659 action: &MoveToEndOfLine,
8660 window: &mut Window,
8661 cx: &mut Context<Self>,
8662 ) {
8663 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8664 s.move_cursors_with(|map, head, _| {
8665 (
8666 movement::line_end(map, head, action.stop_at_soft_wraps),
8667 SelectionGoal::None,
8668 )
8669 });
8670 })
8671 }
8672
8673 pub fn select_to_end_of_line(
8674 &mut self,
8675 action: &SelectToEndOfLine,
8676 window: &mut Window,
8677 cx: &mut Context<Self>,
8678 ) {
8679 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8680 s.move_heads_with(|map, head, _| {
8681 (
8682 movement::line_end(map, head, action.stop_at_soft_wraps),
8683 SelectionGoal::None,
8684 )
8685 });
8686 })
8687 }
8688
8689 pub fn delete_to_end_of_line(
8690 &mut self,
8691 _: &DeleteToEndOfLine,
8692 window: &mut Window,
8693 cx: &mut Context<Self>,
8694 ) {
8695 self.transact(window, cx, |this, window, cx| {
8696 this.select_to_end_of_line(
8697 &SelectToEndOfLine {
8698 stop_at_soft_wraps: false,
8699 },
8700 window,
8701 cx,
8702 );
8703 this.delete(&Delete, window, cx);
8704 });
8705 }
8706
8707 pub fn cut_to_end_of_line(
8708 &mut self,
8709 _: &CutToEndOfLine,
8710 window: &mut Window,
8711 cx: &mut Context<Self>,
8712 ) {
8713 self.transact(window, cx, |this, window, cx| {
8714 this.select_to_end_of_line(
8715 &SelectToEndOfLine {
8716 stop_at_soft_wraps: false,
8717 },
8718 window,
8719 cx,
8720 );
8721 this.cut(&Cut, window, cx);
8722 });
8723 }
8724
8725 pub fn move_to_start_of_paragraph(
8726 &mut self,
8727 _: &MoveToStartOfParagraph,
8728 window: &mut Window,
8729 cx: &mut Context<Self>,
8730 ) {
8731 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8732 cx.propagate();
8733 return;
8734 }
8735
8736 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8737 s.move_with(|map, selection| {
8738 selection.collapse_to(
8739 movement::start_of_paragraph(map, selection.head(), 1),
8740 SelectionGoal::None,
8741 )
8742 });
8743 })
8744 }
8745
8746 pub fn move_to_end_of_paragraph(
8747 &mut self,
8748 _: &MoveToEndOfParagraph,
8749 window: &mut Window,
8750 cx: &mut Context<Self>,
8751 ) {
8752 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8753 cx.propagate();
8754 return;
8755 }
8756
8757 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8758 s.move_with(|map, selection| {
8759 selection.collapse_to(
8760 movement::end_of_paragraph(map, selection.head(), 1),
8761 SelectionGoal::None,
8762 )
8763 });
8764 })
8765 }
8766
8767 pub fn select_to_start_of_paragraph(
8768 &mut self,
8769 _: &SelectToStartOfParagraph,
8770 window: &mut Window,
8771 cx: &mut Context<Self>,
8772 ) {
8773 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8774 cx.propagate();
8775 return;
8776 }
8777
8778 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8779 s.move_heads_with(|map, head, _| {
8780 (
8781 movement::start_of_paragraph(map, head, 1),
8782 SelectionGoal::None,
8783 )
8784 });
8785 })
8786 }
8787
8788 pub fn select_to_end_of_paragraph(
8789 &mut self,
8790 _: &SelectToEndOfParagraph,
8791 window: &mut Window,
8792 cx: &mut Context<Self>,
8793 ) {
8794 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8795 cx.propagate();
8796 return;
8797 }
8798
8799 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8800 s.move_heads_with(|map, head, _| {
8801 (
8802 movement::end_of_paragraph(map, head, 1),
8803 SelectionGoal::None,
8804 )
8805 });
8806 })
8807 }
8808
8809 pub fn move_to_beginning(
8810 &mut self,
8811 _: &MoveToBeginning,
8812 window: &mut Window,
8813 cx: &mut Context<Self>,
8814 ) {
8815 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8816 cx.propagate();
8817 return;
8818 }
8819
8820 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8821 s.select_ranges(vec![0..0]);
8822 });
8823 }
8824
8825 pub fn select_to_beginning(
8826 &mut self,
8827 _: &SelectToBeginning,
8828 window: &mut Window,
8829 cx: &mut Context<Self>,
8830 ) {
8831 let mut selection = self.selections.last::<Point>(cx);
8832 selection.set_head(Point::zero(), SelectionGoal::None);
8833
8834 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8835 s.select(vec![selection]);
8836 });
8837 }
8838
8839 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
8840 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8841 cx.propagate();
8842 return;
8843 }
8844
8845 let cursor = self.buffer.read(cx).read(cx).len();
8846 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8847 s.select_ranges(vec![cursor..cursor])
8848 });
8849 }
8850
8851 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8852 self.nav_history = nav_history;
8853 }
8854
8855 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8856 self.nav_history.as_ref()
8857 }
8858
8859 fn push_to_nav_history(
8860 &mut self,
8861 cursor_anchor: Anchor,
8862 new_position: Option<Point>,
8863 cx: &mut Context<Self>,
8864 ) {
8865 if let Some(nav_history) = self.nav_history.as_mut() {
8866 let buffer = self.buffer.read(cx).read(cx);
8867 let cursor_position = cursor_anchor.to_point(&buffer);
8868 let scroll_state = self.scroll_manager.anchor();
8869 let scroll_top_row = scroll_state.top_row(&buffer);
8870 drop(buffer);
8871
8872 if let Some(new_position) = new_position {
8873 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8874 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8875 return;
8876 }
8877 }
8878
8879 nav_history.push(
8880 Some(NavigationData {
8881 cursor_anchor,
8882 cursor_position,
8883 scroll_anchor: scroll_state,
8884 scroll_top_row,
8885 }),
8886 cx,
8887 );
8888 }
8889 }
8890
8891 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
8892 let buffer = self.buffer.read(cx).snapshot(cx);
8893 let mut selection = self.selections.first::<usize>(cx);
8894 selection.set_head(buffer.len(), SelectionGoal::None);
8895 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8896 s.select(vec![selection]);
8897 });
8898 }
8899
8900 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
8901 let end = self.buffer.read(cx).read(cx).len();
8902 self.change_selections(None, window, cx, |s| {
8903 s.select_ranges(vec![0..end]);
8904 });
8905 }
8906
8907 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
8908 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8909 let mut selections = self.selections.all::<Point>(cx);
8910 let max_point = display_map.buffer_snapshot.max_point();
8911 for selection in &mut selections {
8912 let rows = selection.spanned_rows(true, &display_map);
8913 selection.start = Point::new(rows.start.0, 0);
8914 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8915 selection.reversed = false;
8916 }
8917 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8918 s.select(selections);
8919 });
8920 }
8921
8922 pub fn split_selection_into_lines(
8923 &mut self,
8924 _: &SplitSelectionIntoLines,
8925 window: &mut Window,
8926 cx: &mut Context<Self>,
8927 ) {
8928 let mut to_unfold = Vec::new();
8929 let mut new_selection_ranges = Vec::new();
8930 {
8931 let selections = self.selections.all::<Point>(cx);
8932 let buffer = self.buffer.read(cx).read(cx);
8933 for selection in selections {
8934 for row in selection.start.row..selection.end.row {
8935 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8936 new_selection_ranges.push(cursor..cursor);
8937 }
8938 new_selection_ranges.push(selection.end..selection.end);
8939 to_unfold.push(selection.start..selection.end);
8940 }
8941 }
8942 self.unfold_ranges(&to_unfold, true, true, cx);
8943 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8944 s.select_ranges(new_selection_ranges);
8945 });
8946 }
8947
8948 pub fn add_selection_above(
8949 &mut self,
8950 _: &AddSelectionAbove,
8951 window: &mut Window,
8952 cx: &mut Context<Self>,
8953 ) {
8954 self.add_selection(true, window, cx);
8955 }
8956
8957 pub fn add_selection_below(
8958 &mut self,
8959 _: &AddSelectionBelow,
8960 window: &mut Window,
8961 cx: &mut Context<Self>,
8962 ) {
8963 self.add_selection(false, window, cx);
8964 }
8965
8966 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
8967 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8968 let mut selections = self.selections.all::<Point>(cx);
8969 let text_layout_details = self.text_layout_details(window);
8970 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8971 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8972 let range = oldest_selection.display_range(&display_map).sorted();
8973
8974 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8975 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8976 let positions = start_x.min(end_x)..start_x.max(end_x);
8977
8978 selections.clear();
8979 let mut stack = Vec::new();
8980 for row in range.start.row().0..=range.end.row().0 {
8981 if let Some(selection) = self.selections.build_columnar_selection(
8982 &display_map,
8983 DisplayRow(row),
8984 &positions,
8985 oldest_selection.reversed,
8986 &text_layout_details,
8987 ) {
8988 stack.push(selection.id);
8989 selections.push(selection);
8990 }
8991 }
8992
8993 if above {
8994 stack.reverse();
8995 }
8996
8997 AddSelectionsState { above, stack }
8998 });
8999
9000 let last_added_selection = *state.stack.last().unwrap();
9001 let mut new_selections = Vec::new();
9002 if above == state.above {
9003 let end_row = if above {
9004 DisplayRow(0)
9005 } else {
9006 display_map.max_point().row()
9007 };
9008
9009 'outer: for selection in selections {
9010 if selection.id == last_added_selection {
9011 let range = selection.display_range(&display_map).sorted();
9012 debug_assert_eq!(range.start.row(), range.end.row());
9013 let mut row = range.start.row();
9014 let positions =
9015 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
9016 px(start)..px(end)
9017 } else {
9018 let start_x =
9019 display_map.x_for_display_point(range.start, &text_layout_details);
9020 let end_x =
9021 display_map.x_for_display_point(range.end, &text_layout_details);
9022 start_x.min(end_x)..start_x.max(end_x)
9023 };
9024
9025 while row != end_row {
9026 if above {
9027 row.0 -= 1;
9028 } else {
9029 row.0 += 1;
9030 }
9031
9032 if let Some(new_selection) = self.selections.build_columnar_selection(
9033 &display_map,
9034 row,
9035 &positions,
9036 selection.reversed,
9037 &text_layout_details,
9038 ) {
9039 state.stack.push(new_selection.id);
9040 if above {
9041 new_selections.push(new_selection);
9042 new_selections.push(selection);
9043 } else {
9044 new_selections.push(selection);
9045 new_selections.push(new_selection);
9046 }
9047
9048 continue 'outer;
9049 }
9050 }
9051 }
9052
9053 new_selections.push(selection);
9054 }
9055 } else {
9056 new_selections = selections;
9057 new_selections.retain(|s| s.id != last_added_selection);
9058 state.stack.pop();
9059 }
9060
9061 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9062 s.select(new_selections);
9063 });
9064 if state.stack.len() > 1 {
9065 self.add_selections_state = Some(state);
9066 }
9067 }
9068
9069 pub fn select_next_match_internal(
9070 &mut self,
9071 display_map: &DisplaySnapshot,
9072 replace_newest: bool,
9073 autoscroll: Option<Autoscroll>,
9074 window: &mut Window,
9075 cx: &mut Context<Self>,
9076 ) -> Result<()> {
9077 fn select_next_match_ranges(
9078 this: &mut Editor,
9079 range: Range<usize>,
9080 replace_newest: bool,
9081 auto_scroll: Option<Autoscroll>,
9082 window: &mut Window,
9083 cx: &mut Context<Editor>,
9084 ) {
9085 this.unfold_ranges(&[range.clone()], false, true, cx);
9086 this.change_selections(auto_scroll, window, cx, |s| {
9087 if replace_newest {
9088 s.delete(s.newest_anchor().id);
9089 }
9090 s.insert_range(range.clone());
9091 });
9092 }
9093
9094 let buffer = &display_map.buffer_snapshot;
9095 let mut selections = self.selections.all::<usize>(cx);
9096 if let Some(mut select_next_state) = self.select_next_state.take() {
9097 let query = &select_next_state.query;
9098 if !select_next_state.done {
9099 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9100 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9101 let mut next_selected_range = None;
9102
9103 let bytes_after_last_selection =
9104 buffer.bytes_in_range(last_selection.end..buffer.len());
9105 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
9106 let query_matches = query
9107 .stream_find_iter(bytes_after_last_selection)
9108 .map(|result| (last_selection.end, result))
9109 .chain(
9110 query
9111 .stream_find_iter(bytes_before_first_selection)
9112 .map(|result| (0, result)),
9113 );
9114
9115 for (start_offset, query_match) in query_matches {
9116 let query_match = query_match.unwrap(); // can only fail due to I/O
9117 let offset_range =
9118 start_offset + query_match.start()..start_offset + query_match.end();
9119 let display_range = offset_range.start.to_display_point(display_map)
9120 ..offset_range.end.to_display_point(display_map);
9121
9122 if !select_next_state.wordwise
9123 || (!movement::is_inside_word(display_map, display_range.start)
9124 && !movement::is_inside_word(display_map, display_range.end))
9125 {
9126 // TODO: This is n^2, because we might check all the selections
9127 if !selections
9128 .iter()
9129 .any(|selection| selection.range().overlaps(&offset_range))
9130 {
9131 next_selected_range = Some(offset_range);
9132 break;
9133 }
9134 }
9135 }
9136
9137 if let Some(next_selected_range) = next_selected_range {
9138 select_next_match_ranges(
9139 self,
9140 next_selected_range,
9141 replace_newest,
9142 autoscroll,
9143 window,
9144 cx,
9145 );
9146 } else {
9147 select_next_state.done = true;
9148 }
9149 }
9150
9151 self.select_next_state = Some(select_next_state);
9152 } else {
9153 let mut only_carets = true;
9154 let mut same_text_selected = true;
9155 let mut selected_text = None;
9156
9157 let mut selections_iter = selections.iter().peekable();
9158 while let Some(selection) = selections_iter.next() {
9159 if selection.start != selection.end {
9160 only_carets = false;
9161 }
9162
9163 if same_text_selected {
9164 if selected_text.is_none() {
9165 selected_text =
9166 Some(buffer.text_for_range(selection.range()).collect::<String>());
9167 }
9168
9169 if let Some(next_selection) = selections_iter.peek() {
9170 if next_selection.range().len() == selection.range().len() {
9171 let next_selected_text = buffer
9172 .text_for_range(next_selection.range())
9173 .collect::<String>();
9174 if Some(next_selected_text) != selected_text {
9175 same_text_selected = false;
9176 selected_text = None;
9177 }
9178 } else {
9179 same_text_selected = false;
9180 selected_text = None;
9181 }
9182 }
9183 }
9184 }
9185
9186 if only_carets {
9187 for selection in &mut selections {
9188 let word_range = movement::surrounding_word(
9189 display_map,
9190 selection.start.to_display_point(display_map),
9191 );
9192 selection.start = word_range.start.to_offset(display_map, Bias::Left);
9193 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9194 selection.goal = SelectionGoal::None;
9195 selection.reversed = false;
9196 select_next_match_ranges(
9197 self,
9198 selection.start..selection.end,
9199 replace_newest,
9200 autoscroll,
9201 window,
9202 cx,
9203 );
9204 }
9205
9206 if selections.len() == 1 {
9207 let selection = selections
9208 .last()
9209 .expect("ensured that there's only one selection");
9210 let query = buffer
9211 .text_for_range(selection.start..selection.end)
9212 .collect::<String>();
9213 let is_empty = query.is_empty();
9214 let select_state = SelectNextState {
9215 query: AhoCorasick::new(&[query])?,
9216 wordwise: true,
9217 done: is_empty,
9218 };
9219 self.select_next_state = Some(select_state);
9220 } else {
9221 self.select_next_state = None;
9222 }
9223 } else if let Some(selected_text) = selected_text {
9224 self.select_next_state = Some(SelectNextState {
9225 query: AhoCorasick::new(&[selected_text])?,
9226 wordwise: false,
9227 done: false,
9228 });
9229 self.select_next_match_internal(
9230 display_map,
9231 replace_newest,
9232 autoscroll,
9233 window,
9234 cx,
9235 )?;
9236 }
9237 }
9238 Ok(())
9239 }
9240
9241 pub fn select_all_matches(
9242 &mut self,
9243 _action: &SelectAllMatches,
9244 window: &mut Window,
9245 cx: &mut Context<Self>,
9246 ) -> Result<()> {
9247 self.push_to_selection_history();
9248 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9249
9250 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9251 let Some(select_next_state) = self.select_next_state.as_mut() else {
9252 return Ok(());
9253 };
9254 if select_next_state.done {
9255 return Ok(());
9256 }
9257
9258 let mut new_selections = self.selections.all::<usize>(cx);
9259
9260 let buffer = &display_map.buffer_snapshot;
9261 let query_matches = select_next_state
9262 .query
9263 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9264
9265 for query_match in query_matches {
9266 let query_match = query_match.unwrap(); // can only fail due to I/O
9267 let offset_range = query_match.start()..query_match.end();
9268 let display_range = offset_range.start.to_display_point(&display_map)
9269 ..offset_range.end.to_display_point(&display_map);
9270
9271 if !select_next_state.wordwise
9272 || (!movement::is_inside_word(&display_map, display_range.start)
9273 && !movement::is_inside_word(&display_map, display_range.end))
9274 {
9275 self.selections.change_with(cx, |selections| {
9276 new_selections.push(Selection {
9277 id: selections.new_selection_id(),
9278 start: offset_range.start,
9279 end: offset_range.end,
9280 reversed: false,
9281 goal: SelectionGoal::None,
9282 });
9283 });
9284 }
9285 }
9286
9287 new_selections.sort_by_key(|selection| selection.start);
9288 let mut ix = 0;
9289 while ix + 1 < new_selections.len() {
9290 let current_selection = &new_selections[ix];
9291 let next_selection = &new_selections[ix + 1];
9292 if current_selection.range().overlaps(&next_selection.range()) {
9293 if current_selection.id < next_selection.id {
9294 new_selections.remove(ix + 1);
9295 } else {
9296 new_selections.remove(ix);
9297 }
9298 } else {
9299 ix += 1;
9300 }
9301 }
9302
9303 let reversed = self.selections.oldest::<usize>(cx).reversed;
9304
9305 for selection in new_selections.iter_mut() {
9306 selection.reversed = reversed;
9307 }
9308
9309 select_next_state.done = true;
9310 self.unfold_ranges(
9311 &new_selections
9312 .iter()
9313 .map(|selection| selection.range())
9314 .collect::<Vec<_>>(),
9315 false,
9316 false,
9317 cx,
9318 );
9319 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9320 selections.select(new_selections)
9321 });
9322
9323 Ok(())
9324 }
9325
9326 pub fn select_next(
9327 &mut self,
9328 action: &SelectNext,
9329 window: &mut Window,
9330 cx: &mut Context<Self>,
9331 ) -> Result<()> {
9332 self.push_to_selection_history();
9333 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9334 self.select_next_match_internal(
9335 &display_map,
9336 action.replace_newest,
9337 Some(Autoscroll::newest()),
9338 window,
9339 cx,
9340 )?;
9341 Ok(())
9342 }
9343
9344 pub fn select_previous(
9345 &mut self,
9346 action: &SelectPrevious,
9347 window: &mut Window,
9348 cx: &mut Context<Self>,
9349 ) -> Result<()> {
9350 self.push_to_selection_history();
9351 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9352 let buffer = &display_map.buffer_snapshot;
9353 let mut selections = self.selections.all::<usize>(cx);
9354 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9355 let query = &select_prev_state.query;
9356 if !select_prev_state.done {
9357 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9358 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9359 let mut next_selected_range = None;
9360 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9361 let bytes_before_last_selection =
9362 buffer.reversed_bytes_in_range(0..last_selection.start);
9363 let bytes_after_first_selection =
9364 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9365 let query_matches = query
9366 .stream_find_iter(bytes_before_last_selection)
9367 .map(|result| (last_selection.start, result))
9368 .chain(
9369 query
9370 .stream_find_iter(bytes_after_first_selection)
9371 .map(|result| (buffer.len(), result)),
9372 );
9373 for (end_offset, query_match) in query_matches {
9374 let query_match = query_match.unwrap(); // can only fail due to I/O
9375 let offset_range =
9376 end_offset - query_match.end()..end_offset - query_match.start();
9377 let display_range = offset_range.start.to_display_point(&display_map)
9378 ..offset_range.end.to_display_point(&display_map);
9379
9380 if !select_prev_state.wordwise
9381 || (!movement::is_inside_word(&display_map, display_range.start)
9382 && !movement::is_inside_word(&display_map, display_range.end))
9383 {
9384 next_selected_range = Some(offset_range);
9385 break;
9386 }
9387 }
9388
9389 if let Some(next_selected_range) = next_selected_range {
9390 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9391 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9392 if action.replace_newest {
9393 s.delete(s.newest_anchor().id);
9394 }
9395 s.insert_range(next_selected_range);
9396 });
9397 } else {
9398 select_prev_state.done = true;
9399 }
9400 }
9401
9402 self.select_prev_state = Some(select_prev_state);
9403 } else {
9404 let mut only_carets = true;
9405 let mut same_text_selected = true;
9406 let mut selected_text = None;
9407
9408 let mut selections_iter = selections.iter().peekable();
9409 while let Some(selection) = selections_iter.next() {
9410 if selection.start != selection.end {
9411 only_carets = false;
9412 }
9413
9414 if same_text_selected {
9415 if selected_text.is_none() {
9416 selected_text =
9417 Some(buffer.text_for_range(selection.range()).collect::<String>());
9418 }
9419
9420 if let Some(next_selection) = selections_iter.peek() {
9421 if next_selection.range().len() == selection.range().len() {
9422 let next_selected_text = buffer
9423 .text_for_range(next_selection.range())
9424 .collect::<String>();
9425 if Some(next_selected_text) != selected_text {
9426 same_text_selected = false;
9427 selected_text = None;
9428 }
9429 } else {
9430 same_text_selected = false;
9431 selected_text = None;
9432 }
9433 }
9434 }
9435 }
9436
9437 if only_carets {
9438 for selection in &mut selections {
9439 let word_range = movement::surrounding_word(
9440 &display_map,
9441 selection.start.to_display_point(&display_map),
9442 );
9443 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9444 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9445 selection.goal = SelectionGoal::None;
9446 selection.reversed = false;
9447 }
9448 if selections.len() == 1 {
9449 let selection = selections
9450 .last()
9451 .expect("ensured that there's only one selection");
9452 let query = buffer
9453 .text_for_range(selection.start..selection.end)
9454 .collect::<String>();
9455 let is_empty = query.is_empty();
9456 let select_state = SelectNextState {
9457 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9458 wordwise: true,
9459 done: is_empty,
9460 };
9461 self.select_prev_state = Some(select_state);
9462 } else {
9463 self.select_prev_state = None;
9464 }
9465
9466 self.unfold_ranges(
9467 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9468 false,
9469 true,
9470 cx,
9471 );
9472 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9473 s.select(selections);
9474 });
9475 } else if let Some(selected_text) = selected_text {
9476 self.select_prev_state = Some(SelectNextState {
9477 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9478 wordwise: false,
9479 done: false,
9480 });
9481 self.select_previous(action, window, cx)?;
9482 }
9483 }
9484 Ok(())
9485 }
9486
9487 pub fn toggle_comments(
9488 &mut self,
9489 action: &ToggleComments,
9490 window: &mut Window,
9491 cx: &mut Context<Self>,
9492 ) {
9493 if self.read_only(cx) {
9494 return;
9495 }
9496 let text_layout_details = &self.text_layout_details(window);
9497 self.transact(window, cx, |this, window, cx| {
9498 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9499 let mut edits = Vec::new();
9500 let mut selection_edit_ranges = Vec::new();
9501 let mut last_toggled_row = None;
9502 let snapshot = this.buffer.read(cx).read(cx);
9503 let empty_str: Arc<str> = Arc::default();
9504 let mut suffixes_inserted = Vec::new();
9505 let ignore_indent = action.ignore_indent;
9506
9507 fn comment_prefix_range(
9508 snapshot: &MultiBufferSnapshot,
9509 row: MultiBufferRow,
9510 comment_prefix: &str,
9511 comment_prefix_whitespace: &str,
9512 ignore_indent: bool,
9513 ) -> Range<Point> {
9514 let indent_size = if ignore_indent {
9515 0
9516 } else {
9517 snapshot.indent_size_for_line(row).len
9518 };
9519
9520 let start = Point::new(row.0, indent_size);
9521
9522 let mut line_bytes = snapshot
9523 .bytes_in_range(start..snapshot.max_point())
9524 .flatten()
9525 .copied();
9526
9527 // If this line currently begins with the line comment prefix, then record
9528 // the range containing the prefix.
9529 if line_bytes
9530 .by_ref()
9531 .take(comment_prefix.len())
9532 .eq(comment_prefix.bytes())
9533 {
9534 // Include any whitespace that matches the comment prefix.
9535 let matching_whitespace_len = line_bytes
9536 .zip(comment_prefix_whitespace.bytes())
9537 .take_while(|(a, b)| a == b)
9538 .count() as u32;
9539 let end = Point::new(
9540 start.row,
9541 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9542 );
9543 start..end
9544 } else {
9545 start..start
9546 }
9547 }
9548
9549 fn comment_suffix_range(
9550 snapshot: &MultiBufferSnapshot,
9551 row: MultiBufferRow,
9552 comment_suffix: &str,
9553 comment_suffix_has_leading_space: bool,
9554 ) -> Range<Point> {
9555 let end = Point::new(row.0, snapshot.line_len(row));
9556 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9557
9558 let mut line_end_bytes = snapshot
9559 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9560 .flatten()
9561 .copied();
9562
9563 let leading_space_len = if suffix_start_column > 0
9564 && line_end_bytes.next() == Some(b' ')
9565 && comment_suffix_has_leading_space
9566 {
9567 1
9568 } else {
9569 0
9570 };
9571
9572 // If this line currently begins with the line comment prefix, then record
9573 // the range containing the prefix.
9574 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9575 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9576 start..end
9577 } else {
9578 end..end
9579 }
9580 }
9581
9582 // TODO: Handle selections that cross excerpts
9583 for selection in &mut selections {
9584 let start_column = snapshot
9585 .indent_size_for_line(MultiBufferRow(selection.start.row))
9586 .len;
9587 let language = if let Some(language) =
9588 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9589 {
9590 language
9591 } else {
9592 continue;
9593 };
9594
9595 selection_edit_ranges.clear();
9596
9597 // If multiple selections contain a given row, avoid processing that
9598 // row more than once.
9599 let mut start_row = MultiBufferRow(selection.start.row);
9600 if last_toggled_row == Some(start_row) {
9601 start_row = start_row.next_row();
9602 }
9603 let end_row =
9604 if selection.end.row > selection.start.row && selection.end.column == 0 {
9605 MultiBufferRow(selection.end.row - 1)
9606 } else {
9607 MultiBufferRow(selection.end.row)
9608 };
9609 last_toggled_row = Some(end_row);
9610
9611 if start_row > end_row {
9612 continue;
9613 }
9614
9615 // If the language has line comments, toggle those.
9616 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9617
9618 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9619 if ignore_indent {
9620 full_comment_prefixes = full_comment_prefixes
9621 .into_iter()
9622 .map(|s| Arc::from(s.trim_end()))
9623 .collect();
9624 }
9625
9626 if !full_comment_prefixes.is_empty() {
9627 let first_prefix = full_comment_prefixes
9628 .first()
9629 .expect("prefixes is non-empty");
9630 let prefix_trimmed_lengths = full_comment_prefixes
9631 .iter()
9632 .map(|p| p.trim_end_matches(' ').len())
9633 .collect::<SmallVec<[usize; 4]>>();
9634
9635 let mut all_selection_lines_are_comments = true;
9636
9637 for row in start_row.0..=end_row.0 {
9638 let row = MultiBufferRow(row);
9639 if start_row < end_row && snapshot.is_line_blank(row) {
9640 continue;
9641 }
9642
9643 let prefix_range = full_comment_prefixes
9644 .iter()
9645 .zip(prefix_trimmed_lengths.iter().copied())
9646 .map(|(prefix, trimmed_prefix_len)| {
9647 comment_prefix_range(
9648 snapshot.deref(),
9649 row,
9650 &prefix[..trimmed_prefix_len],
9651 &prefix[trimmed_prefix_len..],
9652 ignore_indent,
9653 )
9654 })
9655 .max_by_key(|range| range.end.column - range.start.column)
9656 .expect("prefixes is non-empty");
9657
9658 if prefix_range.is_empty() {
9659 all_selection_lines_are_comments = false;
9660 }
9661
9662 selection_edit_ranges.push(prefix_range);
9663 }
9664
9665 if all_selection_lines_are_comments {
9666 edits.extend(
9667 selection_edit_ranges
9668 .iter()
9669 .cloned()
9670 .map(|range| (range, empty_str.clone())),
9671 );
9672 } else {
9673 let min_column = selection_edit_ranges
9674 .iter()
9675 .map(|range| range.start.column)
9676 .min()
9677 .unwrap_or(0);
9678 edits.extend(selection_edit_ranges.iter().map(|range| {
9679 let position = Point::new(range.start.row, min_column);
9680 (position..position, first_prefix.clone())
9681 }));
9682 }
9683 } else if let Some((full_comment_prefix, comment_suffix)) =
9684 language.block_comment_delimiters()
9685 {
9686 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9687 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9688 let prefix_range = comment_prefix_range(
9689 snapshot.deref(),
9690 start_row,
9691 comment_prefix,
9692 comment_prefix_whitespace,
9693 ignore_indent,
9694 );
9695 let suffix_range = comment_suffix_range(
9696 snapshot.deref(),
9697 end_row,
9698 comment_suffix.trim_start_matches(' '),
9699 comment_suffix.starts_with(' '),
9700 );
9701
9702 if prefix_range.is_empty() || suffix_range.is_empty() {
9703 edits.push((
9704 prefix_range.start..prefix_range.start,
9705 full_comment_prefix.clone(),
9706 ));
9707 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9708 suffixes_inserted.push((end_row, comment_suffix.len()));
9709 } else {
9710 edits.push((prefix_range, empty_str.clone()));
9711 edits.push((suffix_range, empty_str.clone()));
9712 }
9713 } else {
9714 continue;
9715 }
9716 }
9717
9718 drop(snapshot);
9719 this.buffer.update(cx, |buffer, cx| {
9720 buffer.edit(edits, None, cx);
9721 });
9722
9723 // Adjust selections so that they end before any comment suffixes that
9724 // were inserted.
9725 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9726 let mut selections = this.selections.all::<Point>(cx);
9727 let snapshot = this.buffer.read(cx).read(cx);
9728 for selection in &mut selections {
9729 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9730 match row.cmp(&MultiBufferRow(selection.end.row)) {
9731 Ordering::Less => {
9732 suffixes_inserted.next();
9733 continue;
9734 }
9735 Ordering::Greater => break,
9736 Ordering::Equal => {
9737 if selection.end.column == snapshot.line_len(row) {
9738 if selection.is_empty() {
9739 selection.start.column -= suffix_len as u32;
9740 }
9741 selection.end.column -= suffix_len as u32;
9742 }
9743 break;
9744 }
9745 }
9746 }
9747 }
9748
9749 drop(snapshot);
9750 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9751 s.select(selections)
9752 });
9753
9754 let selections = this.selections.all::<Point>(cx);
9755 let selections_on_single_row = selections.windows(2).all(|selections| {
9756 selections[0].start.row == selections[1].start.row
9757 && selections[0].end.row == selections[1].end.row
9758 && selections[0].start.row == selections[0].end.row
9759 });
9760 let selections_selecting = selections
9761 .iter()
9762 .any(|selection| selection.start != selection.end);
9763 let advance_downwards = action.advance_downwards
9764 && selections_on_single_row
9765 && !selections_selecting
9766 && !matches!(this.mode, EditorMode::SingleLine { .. });
9767
9768 if advance_downwards {
9769 let snapshot = this.buffer.read(cx).snapshot(cx);
9770
9771 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9772 s.move_cursors_with(|display_snapshot, display_point, _| {
9773 let mut point = display_point.to_point(display_snapshot);
9774 point.row += 1;
9775 point = snapshot.clip_point(point, Bias::Left);
9776 let display_point = point.to_display_point(display_snapshot);
9777 let goal = SelectionGoal::HorizontalPosition(
9778 display_snapshot
9779 .x_for_display_point(display_point, text_layout_details)
9780 .into(),
9781 );
9782 (display_point, goal)
9783 })
9784 });
9785 }
9786 });
9787 }
9788
9789 pub fn select_enclosing_symbol(
9790 &mut self,
9791 _: &SelectEnclosingSymbol,
9792 window: &mut Window,
9793 cx: &mut Context<Self>,
9794 ) {
9795 let buffer = self.buffer.read(cx).snapshot(cx);
9796 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9797
9798 fn update_selection(
9799 selection: &Selection<usize>,
9800 buffer_snap: &MultiBufferSnapshot,
9801 ) -> Option<Selection<usize>> {
9802 let cursor = selection.head();
9803 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9804 for symbol in symbols.iter().rev() {
9805 let start = symbol.range.start.to_offset(buffer_snap);
9806 let end = symbol.range.end.to_offset(buffer_snap);
9807 let new_range = start..end;
9808 if start < selection.start || end > selection.end {
9809 return Some(Selection {
9810 id: selection.id,
9811 start: new_range.start,
9812 end: new_range.end,
9813 goal: SelectionGoal::None,
9814 reversed: selection.reversed,
9815 });
9816 }
9817 }
9818 None
9819 }
9820
9821 let mut selected_larger_symbol = false;
9822 let new_selections = old_selections
9823 .iter()
9824 .map(|selection| match update_selection(selection, &buffer) {
9825 Some(new_selection) => {
9826 if new_selection.range() != selection.range() {
9827 selected_larger_symbol = true;
9828 }
9829 new_selection
9830 }
9831 None => selection.clone(),
9832 })
9833 .collect::<Vec<_>>();
9834
9835 if selected_larger_symbol {
9836 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9837 s.select(new_selections);
9838 });
9839 }
9840 }
9841
9842 pub fn select_larger_syntax_node(
9843 &mut self,
9844 _: &SelectLargerSyntaxNode,
9845 window: &mut Window,
9846 cx: &mut Context<Self>,
9847 ) {
9848 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9849 let buffer = self.buffer.read(cx).snapshot(cx);
9850 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9851
9852 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9853 let mut selected_larger_node = false;
9854 let new_selections = old_selections
9855 .iter()
9856 .map(|selection| {
9857 let old_range = selection.start..selection.end;
9858 let mut new_range = old_range.clone();
9859 let mut new_node = None;
9860 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
9861 {
9862 new_node = Some(node);
9863 new_range = containing_range;
9864 if !display_map.intersects_fold(new_range.start)
9865 && !display_map.intersects_fold(new_range.end)
9866 {
9867 break;
9868 }
9869 }
9870
9871 if let Some(node) = new_node {
9872 // Log the ancestor, to support using this action as a way to explore TreeSitter
9873 // nodes. Parent and grandparent are also logged because this operation will not
9874 // visit nodes that have the same range as their parent.
9875 log::info!("Node: {node:?}");
9876 let parent = node.parent();
9877 log::info!("Parent: {parent:?}");
9878 let grandparent = parent.and_then(|x| x.parent());
9879 log::info!("Grandparent: {grandparent:?}");
9880 }
9881
9882 selected_larger_node |= new_range != old_range;
9883 Selection {
9884 id: selection.id,
9885 start: new_range.start,
9886 end: new_range.end,
9887 goal: SelectionGoal::None,
9888 reversed: selection.reversed,
9889 }
9890 })
9891 .collect::<Vec<_>>();
9892
9893 if selected_larger_node {
9894 stack.push(old_selections);
9895 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9896 s.select(new_selections);
9897 });
9898 }
9899 self.select_larger_syntax_node_stack = stack;
9900 }
9901
9902 pub fn select_smaller_syntax_node(
9903 &mut self,
9904 _: &SelectSmallerSyntaxNode,
9905 window: &mut Window,
9906 cx: &mut Context<Self>,
9907 ) {
9908 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9909 if let Some(selections) = stack.pop() {
9910 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9911 s.select(selections.to_vec());
9912 });
9913 }
9914 self.select_larger_syntax_node_stack = stack;
9915 }
9916
9917 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
9918 if !EditorSettings::get_global(cx).gutter.runnables {
9919 self.clear_tasks();
9920 return Task::ready(());
9921 }
9922 let project = self.project.as_ref().map(Entity::downgrade);
9923 cx.spawn_in(window, |this, mut cx| async move {
9924 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
9925 let Some(project) = project.and_then(|p| p.upgrade()) else {
9926 return;
9927 };
9928 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9929 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9930 }) else {
9931 return;
9932 };
9933
9934 let hide_runnables = project
9935 .update(&mut cx, |project, cx| {
9936 // Do not display any test indicators in non-dev server remote projects.
9937 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9938 })
9939 .unwrap_or(true);
9940 if hide_runnables {
9941 return;
9942 }
9943 let new_rows =
9944 cx.background_executor()
9945 .spawn({
9946 let snapshot = display_snapshot.clone();
9947 async move {
9948 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9949 }
9950 })
9951 .await;
9952
9953 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9954 this.update(&mut cx, |this, _| {
9955 this.clear_tasks();
9956 for (key, value) in rows {
9957 this.insert_tasks(key, value);
9958 }
9959 })
9960 .ok();
9961 })
9962 }
9963 fn fetch_runnable_ranges(
9964 snapshot: &DisplaySnapshot,
9965 range: Range<Anchor>,
9966 ) -> Vec<language::RunnableRange> {
9967 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9968 }
9969
9970 fn runnable_rows(
9971 project: Entity<Project>,
9972 snapshot: DisplaySnapshot,
9973 runnable_ranges: Vec<RunnableRange>,
9974 mut cx: AsyncWindowContext,
9975 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9976 runnable_ranges
9977 .into_iter()
9978 .filter_map(|mut runnable| {
9979 let tasks = cx
9980 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9981 .ok()?;
9982 if tasks.is_empty() {
9983 return None;
9984 }
9985
9986 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9987
9988 let row = snapshot
9989 .buffer_snapshot
9990 .buffer_line_for_row(MultiBufferRow(point.row))?
9991 .1
9992 .start
9993 .row;
9994
9995 let context_range =
9996 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9997 Some((
9998 (runnable.buffer_id, row),
9999 RunnableTasks {
10000 templates: tasks,
10001 offset: MultiBufferOffset(runnable.run_range.start),
10002 context_range,
10003 column: point.column,
10004 extra_variables: runnable.extra_captures,
10005 },
10006 ))
10007 })
10008 .collect()
10009 }
10010
10011 fn templates_with_tags(
10012 project: &Entity<Project>,
10013 runnable: &mut Runnable,
10014 cx: &mut App,
10015 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10016 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10017 let (worktree_id, file) = project
10018 .buffer_for_id(runnable.buffer, cx)
10019 .and_then(|buffer| buffer.read(cx).file())
10020 .map(|file| (file.worktree_id(cx), file.clone()))
10021 .unzip();
10022
10023 (
10024 project.task_store().read(cx).task_inventory().cloned(),
10025 worktree_id,
10026 file,
10027 )
10028 });
10029
10030 let tags = mem::take(&mut runnable.tags);
10031 let mut tags: Vec<_> = tags
10032 .into_iter()
10033 .flat_map(|tag| {
10034 let tag = tag.0.clone();
10035 inventory
10036 .as_ref()
10037 .into_iter()
10038 .flat_map(|inventory| {
10039 inventory.read(cx).list_tasks(
10040 file.clone(),
10041 Some(runnable.language.clone()),
10042 worktree_id,
10043 cx,
10044 )
10045 })
10046 .filter(move |(_, template)| {
10047 template.tags.iter().any(|source_tag| source_tag == &tag)
10048 })
10049 })
10050 .sorted_by_key(|(kind, _)| kind.to_owned())
10051 .collect();
10052 if let Some((leading_tag_source, _)) = tags.first() {
10053 // Strongest source wins; if we have worktree tag binding, prefer that to
10054 // global and language bindings;
10055 // if we have a global binding, prefer that to language binding.
10056 let first_mismatch = tags
10057 .iter()
10058 .position(|(tag_source, _)| tag_source != leading_tag_source);
10059 if let Some(index) = first_mismatch {
10060 tags.truncate(index);
10061 }
10062 }
10063
10064 tags
10065 }
10066
10067 pub fn move_to_enclosing_bracket(
10068 &mut self,
10069 _: &MoveToEnclosingBracket,
10070 window: &mut Window,
10071 cx: &mut Context<Self>,
10072 ) {
10073 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10074 s.move_offsets_with(|snapshot, selection| {
10075 let Some(enclosing_bracket_ranges) =
10076 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10077 else {
10078 return;
10079 };
10080
10081 let mut best_length = usize::MAX;
10082 let mut best_inside = false;
10083 let mut best_in_bracket_range = false;
10084 let mut best_destination = None;
10085 for (open, close) in enclosing_bracket_ranges {
10086 let close = close.to_inclusive();
10087 let length = close.end() - open.start;
10088 let inside = selection.start >= open.end && selection.end <= *close.start();
10089 let in_bracket_range = open.to_inclusive().contains(&selection.head())
10090 || close.contains(&selection.head());
10091
10092 // If best is next to a bracket and current isn't, skip
10093 if !in_bracket_range && best_in_bracket_range {
10094 continue;
10095 }
10096
10097 // Prefer smaller lengths unless best is inside and current isn't
10098 if length > best_length && (best_inside || !inside) {
10099 continue;
10100 }
10101
10102 best_length = length;
10103 best_inside = inside;
10104 best_in_bracket_range = in_bracket_range;
10105 best_destination = Some(
10106 if close.contains(&selection.start) && close.contains(&selection.end) {
10107 if inside {
10108 open.end
10109 } else {
10110 open.start
10111 }
10112 } else if inside {
10113 *close.start()
10114 } else {
10115 *close.end()
10116 },
10117 );
10118 }
10119
10120 if let Some(destination) = best_destination {
10121 selection.collapse_to(destination, SelectionGoal::None);
10122 }
10123 })
10124 });
10125 }
10126
10127 pub fn undo_selection(
10128 &mut self,
10129 _: &UndoSelection,
10130 window: &mut Window,
10131 cx: &mut Context<Self>,
10132 ) {
10133 self.end_selection(window, cx);
10134 self.selection_history.mode = SelectionHistoryMode::Undoing;
10135 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10136 self.change_selections(None, window, cx, |s| {
10137 s.select_anchors(entry.selections.to_vec())
10138 });
10139 self.select_next_state = entry.select_next_state;
10140 self.select_prev_state = entry.select_prev_state;
10141 self.add_selections_state = entry.add_selections_state;
10142 self.request_autoscroll(Autoscroll::newest(), cx);
10143 }
10144 self.selection_history.mode = SelectionHistoryMode::Normal;
10145 }
10146
10147 pub fn redo_selection(
10148 &mut self,
10149 _: &RedoSelection,
10150 window: &mut Window,
10151 cx: &mut Context<Self>,
10152 ) {
10153 self.end_selection(window, cx);
10154 self.selection_history.mode = SelectionHistoryMode::Redoing;
10155 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10156 self.change_selections(None, window, cx, |s| {
10157 s.select_anchors(entry.selections.to_vec())
10158 });
10159 self.select_next_state = entry.select_next_state;
10160 self.select_prev_state = entry.select_prev_state;
10161 self.add_selections_state = entry.add_selections_state;
10162 self.request_autoscroll(Autoscroll::newest(), cx);
10163 }
10164 self.selection_history.mode = SelectionHistoryMode::Normal;
10165 }
10166
10167 pub fn expand_excerpts(
10168 &mut self,
10169 action: &ExpandExcerpts,
10170 _: &mut Window,
10171 cx: &mut Context<Self>,
10172 ) {
10173 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10174 }
10175
10176 pub fn expand_excerpts_down(
10177 &mut self,
10178 action: &ExpandExcerptsDown,
10179 _: &mut Window,
10180 cx: &mut Context<Self>,
10181 ) {
10182 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10183 }
10184
10185 pub fn expand_excerpts_up(
10186 &mut self,
10187 action: &ExpandExcerptsUp,
10188 _: &mut Window,
10189 cx: &mut Context<Self>,
10190 ) {
10191 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10192 }
10193
10194 pub fn expand_excerpts_for_direction(
10195 &mut self,
10196 lines: u32,
10197 direction: ExpandExcerptDirection,
10198
10199 cx: &mut Context<Self>,
10200 ) {
10201 let selections = self.selections.disjoint_anchors();
10202
10203 let lines = if lines == 0 {
10204 EditorSettings::get_global(cx).expand_excerpt_lines
10205 } else {
10206 lines
10207 };
10208
10209 self.buffer.update(cx, |buffer, cx| {
10210 let snapshot = buffer.snapshot(cx);
10211 let mut excerpt_ids = selections
10212 .iter()
10213 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10214 .collect::<Vec<_>>();
10215 excerpt_ids.sort();
10216 excerpt_ids.dedup();
10217 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10218 })
10219 }
10220
10221 pub fn expand_excerpt(
10222 &mut self,
10223 excerpt: ExcerptId,
10224 direction: ExpandExcerptDirection,
10225 cx: &mut Context<Self>,
10226 ) {
10227 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10228 self.buffer.update(cx, |buffer, cx| {
10229 buffer.expand_excerpts([excerpt], lines, direction, cx)
10230 })
10231 }
10232
10233 pub fn go_to_singleton_buffer_point(
10234 &mut self,
10235 point: Point,
10236 window: &mut Window,
10237 cx: &mut Context<Self>,
10238 ) {
10239 self.go_to_singleton_buffer_range(point..point, window, cx);
10240 }
10241
10242 pub fn go_to_singleton_buffer_range(
10243 &mut self,
10244 range: Range<Point>,
10245 window: &mut Window,
10246 cx: &mut Context<Self>,
10247 ) {
10248 let multibuffer = self.buffer().read(cx);
10249 let Some(buffer) = multibuffer.as_singleton() else {
10250 return;
10251 };
10252 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10253 return;
10254 };
10255 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10256 return;
10257 };
10258 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10259 s.select_anchor_ranges([start..end])
10260 });
10261 }
10262
10263 fn go_to_diagnostic(
10264 &mut self,
10265 _: &GoToDiagnostic,
10266 window: &mut Window,
10267 cx: &mut Context<Self>,
10268 ) {
10269 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10270 }
10271
10272 fn go_to_prev_diagnostic(
10273 &mut self,
10274 _: &GoToPrevDiagnostic,
10275 window: &mut Window,
10276 cx: &mut Context<Self>,
10277 ) {
10278 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10279 }
10280
10281 pub fn go_to_diagnostic_impl(
10282 &mut self,
10283 direction: Direction,
10284 window: &mut Window,
10285 cx: &mut Context<Self>,
10286 ) {
10287 let buffer = self.buffer.read(cx).snapshot(cx);
10288 let selection = self.selections.newest::<usize>(cx);
10289
10290 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10291 if direction == Direction::Next {
10292 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10293 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10294 return;
10295 };
10296 self.activate_diagnostics(
10297 buffer_id,
10298 popover.local_diagnostic.diagnostic.group_id,
10299 window,
10300 cx,
10301 );
10302 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10303 let primary_range_start = active_diagnostics.primary_range.start;
10304 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10305 let mut new_selection = s.newest_anchor().clone();
10306 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10307 s.select_anchors(vec![new_selection.clone()]);
10308 });
10309 self.refresh_inline_completion(false, true, window, cx);
10310 }
10311 return;
10312 }
10313 }
10314
10315 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10316 active_diagnostics
10317 .primary_range
10318 .to_offset(&buffer)
10319 .to_inclusive()
10320 });
10321 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10322 if active_primary_range.contains(&selection.head()) {
10323 *active_primary_range.start()
10324 } else {
10325 selection.head()
10326 }
10327 } else {
10328 selection.head()
10329 };
10330 let snapshot = self.snapshot(window, cx);
10331 loop {
10332 let mut diagnostics;
10333 if direction == Direction::Prev {
10334 diagnostics = buffer
10335 .diagnostics_in_range::<usize>(0..search_start)
10336 .collect::<Vec<_>>();
10337 diagnostics.reverse();
10338 } else {
10339 diagnostics = buffer
10340 .diagnostics_in_range::<usize>(search_start..buffer.len())
10341 .collect::<Vec<_>>();
10342 };
10343 let group = diagnostics
10344 .into_iter()
10345 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10346 // relies on diagnostics_in_range to return diagnostics with the same starting range to
10347 // be sorted in a stable way
10348 // skip until we are at current active diagnostic, if it exists
10349 .skip_while(|entry| {
10350 let is_in_range = match direction {
10351 Direction::Prev => entry.range.end > search_start,
10352 Direction::Next => entry.range.start < search_start,
10353 };
10354 is_in_range
10355 && self
10356 .active_diagnostics
10357 .as_ref()
10358 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
10359 })
10360 .find_map(|entry| {
10361 if entry.diagnostic.is_primary
10362 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
10363 && entry.range.start != entry.range.end
10364 // if we match with the active diagnostic, skip it
10365 && Some(entry.diagnostic.group_id)
10366 != self.active_diagnostics.as_ref().map(|d| d.group_id)
10367 {
10368 Some((entry.range, entry.diagnostic.group_id))
10369 } else {
10370 None
10371 }
10372 });
10373
10374 if let Some((primary_range, group_id)) = group {
10375 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10376 return;
10377 };
10378 self.activate_diagnostics(buffer_id, group_id, window, cx);
10379 if self.active_diagnostics.is_some() {
10380 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10381 s.select(vec![Selection {
10382 id: selection.id,
10383 start: primary_range.start,
10384 end: primary_range.start,
10385 reversed: false,
10386 goal: SelectionGoal::None,
10387 }]);
10388 });
10389 self.refresh_inline_completion(false, true, window, cx);
10390 }
10391 break;
10392 } else {
10393 // Cycle around to the start of the buffer, potentially moving back to the start of
10394 // the currently active diagnostic.
10395 active_primary_range.take();
10396 if direction == Direction::Prev {
10397 if search_start == buffer.len() {
10398 break;
10399 } else {
10400 search_start = buffer.len();
10401 }
10402 } else if search_start == 0 {
10403 break;
10404 } else {
10405 search_start = 0;
10406 }
10407 }
10408 }
10409 }
10410
10411 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10412 let snapshot = self.snapshot(window, cx);
10413 let selection = self.selections.newest::<Point>(cx);
10414 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10415 }
10416
10417 fn go_to_hunk_after_position(
10418 &mut self,
10419 snapshot: &EditorSnapshot,
10420 position: Point,
10421 window: &mut Window,
10422 cx: &mut Context<Editor>,
10423 ) -> Option<MultiBufferDiffHunk> {
10424 let mut hunk = snapshot
10425 .buffer_snapshot
10426 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10427 .find(|hunk| hunk.row_range.start.0 > position.row);
10428 if hunk.is_none() {
10429 hunk = snapshot
10430 .buffer_snapshot
10431 .diff_hunks_in_range(Point::zero()..position)
10432 .find(|hunk| hunk.row_range.end.0 < position.row)
10433 }
10434 if let Some(hunk) = &hunk {
10435 let destination = Point::new(hunk.row_range.start.0, 0);
10436 self.unfold_ranges(&[destination..destination], false, false, cx);
10437 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10438 s.select_ranges(vec![destination..destination]);
10439 });
10440 }
10441
10442 hunk
10443 }
10444
10445 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10446 let snapshot = self.snapshot(window, cx);
10447 let selection = self.selections.newest::<Point>(cx);
10448 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10449 }
10450
10451 fn go_to_hunk_before_position(
10452 &mut self,
10453 snapshot: &EditorSnapshot,
10454 position: Point,
10455 window: &mut Window,
10456 cx: &mut Context<Editor>,
10457 ) -> Option<MultiBufferDiffHunk> {
10458 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10459 if hunk.is_none() {
10460 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10461 }
10462 if let Some(hunk) = &hunk {
10463 let destination = Point::new(hunk.row_range.start.0, 0);
10464 self.unfold_ranges(&[destination..destination], false, false, cx);
10465 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10466 s.select_ranges(vec![destination..destination]);
10467 });
10468 }
10469
10470 hunk
10471 }
10472
10473 pub fn go_to_definition(
10474 &mut self,
10475 _: &GoToDefinition,
10476 window: &mut Window,
10477 cx: &mut Context<Self>,
10478 ) -> Task<Result<Navigated>> {
10479 let definition =
10480 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10481 cx.spawn_in(window, |editor, mut cx| async move {
10482 if definition.await? == Navigated::Yes {
10483 return Ok(Navigated::Yes);
10484 }
10485 match editor.update_in(&mut cx, |editor, window, cx| {
10486 editor.find_all_references(&FindAllReferences, window, cx)
10487 })? {
10488 Some(references) => references.await,
10489 None => Ok(Navigated::No),
10490 }
10491 })
10492 }
10493
10494 pub fn go_to_declaration(
10495 &mut self,
10496 _: &GoToDeclaration,
10497 window: &mut Window,
10498 cx: &mut Context<Self>,
10499 ) -> Task<Result<Navigated>> {
10500 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10501 }
10502
10503 pub fn go_to_declaration_split(
10504 &mut self,
10505 _: &GoToDeclaration,
10506 window: &mut Window,
10507 cx: &mut Context<Self>,
10508 ) -> Task<Result<Navigated>> {
10509 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10510 }
10511
10512 pub fn go_to_implementation(
10513 &mut self,
10514 _: &GoToImplementation,
10515 window: &mut Window,
10516 cx: &mut Context<Self>,
10517 ) -> Task<Result<Navigated>> {
10518 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10519 }
10520
10521 pub fn go_to_implementation_split(
10522 &mut self,
10523 _: &GoToImplementationSplit,
10524 window: &mut Window,
10525 cx: &mut Context<Self>,
10526 ) -> Task<Result<Navigated>> {
10527 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10528 }
10529
10530 pub fn go_to_type_definition(
10531 &mut self,
10532 _: &GoToTypeDefinition,
10533 window: &mut Window,
10534 cx: &mut Context<Self>,
10535 ) -> Task<Result<Navigated>> {
10536 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10537 }
10538
10539 pub fn go_to_definition_split(
10540 &mut self,
10541 _: &GoToDefinitionSplit,
10542 window: &mut Window,
10543 cx: &mut Context<Self>,
10544 ) -> Task<Result<Navigated>> {
10545 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10546 }
10547
10548 pub fn go_to_type_definition_split(
10549 &mut self,
10550 _: &GoToTypeDefinitionSplit,
10551 window: &mut Window,
10552 cx: &mut Context<Self>,
10553 ) -> Task<Result<Navigated>> {
10554 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10555 }
10556
10557 fn go_to_definition_of_kind(
10558 &mut self,
10559 kind: GotoDefinitionKind,
10560 split: bool,
10561 window: &mut Window,
10562 cx: &mut Context<Self>,
10563 ) -> Task<Result<Navigated>> {
10564 let Some(provider) = self.semantics_provider.clone() else {
10565 return Task::ready(Ok(Navigated::No));
10566 };
10567 let head = self.selections.newest::<usize>(cx).head();
10568 let buffer = self.buffer.read(cx);
10569 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10570 text_anchor
10571 } else {
10572 return Task::ready(Ok(Navigated::No));
10573 };
10574
10575 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10576 return Task::ready(Ok(Navigated::No));
10577 };
10578
10579 cx.spawn_in(window, |editor, mut cx| async move {
10580 let definitions = definitions.await?;
10581 let navigated = editor
10582 .update_in(&mut cx, |editor, window, cx| {
10583 editor.navigate_to_hover_links(
10584 Some(kind),
10585 definitions
10586 .into_iter()
10587 .filter(|location| {
10588 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10589 })
10590 .map(HoverLink::Text)
10591 .collect::<Vec<_>>(),
10592 split,
10593 window,
10594 cx,
10595 )
10596 })?
10597 .await?;
10598 anyhow::Ok(navigated)
10599 })
10600 }
10601
10602 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10603 let selection = self.selections.newest_anchor();
10604 let head = selection.head();
10605 let tail = selection.tail();
10606
10607 let Some((buffer, start_position)) =
10608 self.buffer.read(cx).text_anchor_for_position(head, cx)
10609 else {
10610 return;
10611 };
10612
10613 let end_position = if head != tail {
10614 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10615 return;
10616 };
10617 Some(pos)
10618 } else {
10619 None
10620 };
10621
10622 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10623 let url = if let Some(end_pos) = end_position {
10624 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10625 } else {
10626 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10627 };
10628
10629 if let Some(url) = url {
10630 editor.update(&mut cx, |_, cx| {
10631 cx.open_url(&url);
10632 })
10633 } else {
10634 Ok(())
10635 }
10636 });
10637
10638 url_finder.detach();
10639 }
10640
10641 pub fn open_selected_filename(
10642 &mut self,
10643 _: &OpenSelectedFilename,
10644 window: &mut Window,
10645 cx: &mut Context<Self>,
10646 ) {
10647 let Some(workspace) = self.workspace() else {
10648 return;
10649 };
10650
10651 let position = self.selections.newest_anchor().head();
10652
10653 let Some((buffer, buffer_position)) =
10654 self.buffer.read(cx).text_anchor_for_position(position, cx)
10655 else {
10656 return;
10657 };
10658
10659 let project = self.project.clone();
10660
10661 cx.spawn_in(window, |_, mut cx| async move {
10662 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10663
10664 if let Some((_, path)) = result {
10665 workspace
10666 .update_in(&mut cx, |workspace, window, cx| {
10667 workspace.open_resolved_path(path, window, cx)
10668 })?
10669 .await?;
10670 }
10671 anyhow::Ok(())
10672 })
10673 .detach();
10674 }
10675
10676 pub(crate) fn navigate_to_hover_links(
10677 &mut self,
10678 kind: Option<GotoDefinitionKind>,
10679 mut definitions: Vec<HoverLink>,
10680 split: bool,
10681 window: &mut Window,
10682 cx: &mut Context<Editor>,
10683 ) -> Task<Result<Navigated>> {
10684 // If there is one definition, just open it directly
10685 if definitions.len() == 1 {
10686 let definition = definitions.pop().unwrap();
10687
10688 enum TargetTaskResult {
10689 Location(Option<Location>),
10690 AlreadyNavigated,
10691 }
10692
10693 let target_task = match definition {
10694 HoverLink::Text(link) => {
10695 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10696 }
10697 HoverLink::InlayHint(lsp_location, server_id) => {
10698 let computation =
10699 self.compute_target_location(lsp_location, server_id, window, cx);
10700 cx.background_executor().spawn(async move {
10701 let location = computation.await?;
10702 Ok(TargetTaskResult::Location(location))
10703 })
10704 }
10705 HoverLink::Url(url) => {
10706 cx.open_url(&url);
10707 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10708 }
10709 HoverLink::File(path) => {
10710 if let Some(workspace) = self.workspace() {
10711 cx.spawn_in(window, |_, mut cx| async move {
10712 workspace
10713 .update_in(&mut cx, |workspace, window, cx| {
10714 workspace.open_resolved_path(path, window, cx)
10715 })?
10716 .await
10717 .map(|_| TargetTaskResult::AlreadyNavigated)
10718 })
10719 } else {
10720 Task::ready(Ok(TargetTaskResult::Location(None)))
10721 }
10722 }
10723 };
10724 cx.spawn_in(window, |editor, mut cx| async move {
10725 let target = match target_task.await.context("target resolution task")? {
10726 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10727 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10728 TargetTaskResult::Location(Some(target)) => target,
10729 };
10730
10731 editor.update_in(&mut cx, |editor, window, cx| {
10732 let Some(workspace) = editor.workspace() else {
10733 return Navigated::No;
10734 };
10735 let pane = workspace.read(cx).active_pane().clone();
10736
10737 let range = target.range.to_point(target.buffer.read(cx));
10738 let range = editor.range_for_match(&range);
10739 let range = collapse_multiline_range(range);
10740
10741 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10742 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10743 } else {
10744 window.defer(cx, move |window, cx| {
10745 let target_editor: Entity<Self> =
10746 workspace.update(cx, |workspace, cx| {
10747 let pane = if split {
10748 workspace.adjacent_pane(window, cx)
10749 } else {
10750 workspace.active_pane().clone()
10751 };
10752
10753 workspace.open_project_item(
10754 pane,
10755 target.buffer.clone(),
10756 true,
10757 true,
10758 window,
10759 cx,
10760 )
10761 });
10762 target_editor.update(cx, |target_editor, cx| {
10763 // When selecting a definition in a different buffer, disable the nav history
10764 // to avoid creating a history entry at the previous cursor location.
10765 pane.update(cx, |pane, _| pane.disable_history());
10766 target_editor.go_to_singleton_buffer_range(range, window, cx);
10767 pane.update(cx, |pane, _| pane.enable_history());
10768 });
10769 });
10770 }
10771 Navigated::Yes
10772 })
10773 })
10774 } else if !definitions.is_empty() {
10775 cx.spawn_in(window, |editor, mut cx| async move {
10776 let (title, location_tasks, workspace) = editor
10777 .update_in(&mut cx, |editor, window, cx| {
10778 let tab_kind = match kind {
10779 Some(GotoDefinitionKind::Implementation) => "Implementations",
10780 _ => "Definitions",
10781 };
10782 let title = definitions
10783 .iter()
10784 .find_map(|definition| match definition {
10785 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10786 let buffer = origin.buffer.read(cx);
10787 format!(
10788 "{} for {}",
10789 tab_kind,
10790 buffer
10791 .text_for_range(origin.range.clone())
10792 .collect::<String>()
10793 )
10794 }),
10795 HoverLink::InlayHint(_, _) => None,
10796 HoverLink::Url(_) => None,
10797 HoverLink::File(_) => None,
10798 })
10799 .unwrap_or(tab_kind.to_string());
10800 let location_tasks = definitions
10801 .into_iter()
10802 .map(|definition| match definition {
10803 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10804 HoverLink::InlayHint(lsp_location, server_id) => editor
10805 .compute_target_location(lsp_location, server_id, window, cx),
10806 HoverLink::Url(_) => Task::ready(Ok(None)),
10807 HoverLink::File(_) => Task::ready(Ok(None)),
10808 })
10809 .collect::<Vec<_>>();
10810 (title, location_tasks, editor.workspace().clone())
10811 })
10812 .context("location tasks preparation")?;
10813
10814 let locations = future::join_all(location_tasks)
10815 .await
10816 .into_iter()
10817 .filter_map(|location| location.transpose())
10818 .collect::<Result<_>>()
10819 .context("location tasks")?;
10820
10821 let Some(workspace) = workspace else {
10822 return Ok(Navigated::No);
10823 };
10824 let opened = workspace
10825 .update_in(&mut cx, |workspace, window, cx| {
10826 Self::open_locations_in_multibuffer(
10827 workspace,
10828 locations,
10829 title,
10830 split,
10831 MultibufferSelectionMode::First,
10832 window,
10833 cx,
10834 )
10835 })
10836 .ok();
10837
10838 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10839 })
10840 } else {
10841 Task::ready(Ok(Navigated::No))
10842 }
10843 }
10844
10845 fn compute_target_location(
10846 &self,
10847 lsp_location: lsp::Location,
10848 server_id: LanguageServerId,
10849 window: &mut Window,
10850 cx: &mut Context<Self>,
10851 ) -> Task<anyhow::Result<Option<Location>>> {
10852 let Some(project) = self.project.clone() else {
10853 return Task::ready(Ok(None));
10854 };
10855
10856 cx.spawn_in(window, move |editor, mut cx| async move {
10857 let location_task = editor.update(&mut cx, |_, cx| {
10858 project.update(cx, |project, cx| {
10859 let language_server_name = project
10860 .language_server_statuses(cx)
10861 .find(|(id, _)| server_id == *id)
10862 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10863 language_server_name.map(|language_server_name| {
10864 project.open_local_buffer_via_lsp(
10865 lsp_location.uri.clone(),
10866 server_id,
10867 language_server_name,
10868 cx,
10869 )
10870 })
10871 })
10872 })?;
10873 let location = match location_task {
10874 Some(task) => Some({
10875 let target_buffer_handle = task.await.context("open local buffer")?;
10876 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10877 let target_start = target_buffer
10878 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10879 let target_end = target_buffer
10880 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10881 target_buffer.anchor_after(target_start)
10882 ..target_buffer.anchor_before(target_end)
10883 })?;
10884 Location {
10885 buffer: target_buffer_handle,
10886 range,
10887 }
10888 }),
10889 None => None,
10890 };
10891 Ok(location)
10892 })
10893 }
10894
10895 pub fn find_all_references(
10896 &mut self,
10897 _: &FindAllReferences,
10898 window: &mut Window,
10899 cx: &mut Context<Self>,
10900 ) -> Option<Task<Result<Navigated>>> {
10901 let selection = self.selections.newest::<usize>(cx);
10902 let multi_buffer = self.buffer.read(cx);
10903 let head = selection.head();
10904
10905 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10906 let head_anchor = multi_buffer_snapshot.anchor_at(
10907 head,
10908 if head < selection.tail() {
10909 Bias::Right
10910 } else {
10911 Bias::Left
10912 },
10913 );
10914
10915 match self
10916 .find_all_references_task_sources
10917 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10918 {
10919 Ok(_) => {
10920 log::info!(
10921 "Ignoring repeated FindAllReferences invocation with the position of already running task"
10922 );
10923 return None;
10924 }
10925 Err(i) => {
10926 self.find_all_references_task_sources.insert(i, head_anchor);
10927 }
10928 }
10929
10930 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10931 let workspace = self.workspace()?;
10932 let project = workspace.read(cx).project().clone();
10933 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10934 Some(cx.spawn_in(window, |editor, mut cx| async move {
10935 let _cleanup = defer({
10936 let mut cx = cx.clone();
10937 move || {
10938 let _ = editor.update(&mut cx, |editor, _| {
10939 if let Ok(i) =
10940 editor
10941 .find_all_references_task_sources
10942 .binary_search_by(|anchor| {
10943 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10944 })
10945 {
10946 editor.find_all_references_task_sources.remove(i);
10947 }
10948 });
10949 }
10950 });
10951
10952 let locations = references.await?;
10953 if locations.is_empty() {
10954 return anyhow::Ok(Navigated::No);
10955 }
10956
10957 workspace.update_in(&mut cx, |workspace, window, cx| {
10958 let title = locations
10959 .first()
10960 .as_ref()
10961 .map(|location| {
10962 let buffer = location.buffer.read(cx);
10963 format!(
10964 "References to `{}`",
10965 buffer
10966 .text_for_range(location.range.clone())
10967 .collect::<String>()
10968 )
10969 })
10970 .unwrap();
10971 Self::open_locations_in_multibuffer(
10972 workspace,
10973 locations,
10974 title,
10975 false,
10976 MultibufferSelectionMode::First,
10977 window,
10978 cx,
10979 );
10980 Navigated::Yes
10981 })
10982 }))
10983 }
10984
10985 /// Opens a multibuffer with the given project locations in it
10986 pub fn open_locations_in_multibuffer(
10987 workspace: &mut Workspace,
10988 mut locations: Vec<Location>,
10989 title: String,
10990 split: bool,
10991 multibuffer_selection_mode: MultibufferSelectionMode,
10992 window: &mut Window,
10993 cx: &mut Context<Workspace>,
10994 ) {
10995 // If there are multiple definitions, open them in a multibuffer
10996 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10997 let mut locations = locations.into_iter().peekable();
10998 let mut ranges = Vec::new();
10999 let capability = workspace.project().read(cx).capability();
11000
11001 let excerpt_buffer = cx.new(|cx| {
11002 let mut multibuffer = MultiBuffer::new(capability);
11003 while let Some(location) = locations.next() {
11004 let buffer = location.buffer.read(cx);
11005 let mut ranges_for_buffer = Vec::new();
11006 let range = location.range.to_offset(buffer);
11007 ranges_for_buffer.push(range.clone());
11008
11009 while let Some(next_location) = locations.peek() {
11010 if next_location.buffer == location.buffer {
11011 ranges_for_buffer.push(next_location.range.to_offset(buffer));
11012 locations.next();
11013 } else {
11014 break;
11015 }
11016 }
11017
11018 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11019 ranges.extend(multibuffer.push_excerpts_with_context_lines(
11020 location.buffer.clone(),
11021 ranges_for_buffer,
11022 DEFAULT_MULTIBUFFER_CONTEXT,
11023 cx,
11024 ))
11025 }
11026
11027 multibuffer.with_title(title)
11028 });
11029
11030 let editor = cx.new(|cx| {
11031 Editor::for_multibuffer(
11032 excerpt_buffer,
11033 Some(workspace.project().clone()),
11034 true,
11035 window,
11036 cx,
11037 )
11038 });
11039 editor.update(cx, |editor, cx| {
11040 match multibuffer_selection_mode {
11041 MultibufferSelectionMode::First => {
11042 if let Some(first_range) = ranges.first() {
11043 editor.change_selections(None, window, cx, |selections| {
11044 selections.clear_disjoint();
11045 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11046 });
11047 }
11048 editor.highlight_background::<Self>(
11049 &ranges,
11050 |theme| theme.editor_highlighted_line_background,
11051 cx,
11052 );
11053 }
11054 MultibufferSelectionMode::All => {
11055 editor.change_selections(None, window, cx, |selections| {
11056 selections.clear_disjoint();
11057 selections.select_anchor_ranges(ranges);
11058 });
11059 }
11060 }
11061 editor.register_buffers_with_language_servers(cx);
11062 });
11063
11064 let item = Box::new(editor);
11065 let item_id = item.item_id();
11066
11067 if split {
11068 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11069 } else {
11070 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11071 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11072 pane.close_current_preview_item(window, cx)
11073 } else {
11074 None
11075 }
11076 });
11077 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11078 }
11079 workspace.active_pane().update(cx, |pane, cx| {
11080 pane.set_preview_item_id(Some(item_id), cx);
11081 });
11082 }
11083
11084 pub fn rename(
11085 &mut self,
11086 _: &Rename,
11087 window: &mut Window,
11088 cx: &mut Context<Self>,
11089 ) -> Option<Task<Result<()>>> {
11090 use language::ToOffset as _;
11091
11092 let provider = self.semantics_provider.clone()?;
11093 let selection = self.selections.newest_anchor().clone();
11094 let (cursor_buffer, cursor_buffer_position) = self
11095 .buffer
11096 .read(cx)
11097 .text_anchor_for_position(selection.head(), cx)?;
11098 let (tail_buffer, cursor_buffer_position_end) = self
11099 .buffer
11100 .read(cx)
11101 .text_anchor_for_position(selection.tail(), cx)?;
11102 if tail_buffer != cursor_buffer {
11103 return None;
11104 }
11105
11106 let snapshot = cursor_buffer.read(cx).snapshot();
11107 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11108 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11109 let prepare_rename = provider
11110 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11111 .unwrap_or_else(|| Task::ready(Ok(None)));
11112 drop(snapshot);
11113
11114 Some(cx.spawn_in(window, |this, mut cx| async move {
11115 let rename_range = if let Some(range) = prepare_rename.await? {
11116 Some(range)
11117 } else {
11118 this.update(&mut cx, |this, cx| {
11119 let buffer = this.buffer.read(cx).snapshot(cx);
11120 let mut buffer_highlights = this
11121 .document_highlights_for_position(selection.head(), &buffer)
11122 .filter(|highlight| {
11123 highlight.start.excerpt_id == selection.head().excerpt_id
11124 && highlight.end.excerpt_id == selection.head().excerpt_id
11125 });
11126 buffer_highlights
11127 .next()
11128 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11129 })?
11130 };
11131 if let Some(rename_range) = rename_range {
11132 this.update_in(&mut cx, |this, window, cx| {
11133 let snapshot = cursor_buffer.read(cx).snapshot();
11134 let rename_buffer_range = rename_range.to_offset(&snapshot);
11135 let cursor_offset_in_rename_range =
11136 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11137 let cursor_offset_in_rename_range_end =
11138 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11139
11140 this.take_rename(false, window, cx);
11141 let buffer = this.buffer.read(cx).read(cx);
11142 let cursor_offset = selection.head().to_offset(&buffer);
11143 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11144 let rename_end = rename_start + rename_buffer_range.len();
11145 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11146 let mut old_highlight_id = None;
11147 let old_name: Arc<str> = buffer
11148 .chunks(rename_start..rename_end, true)
11149 .map(|chunk| {
11150 if old_highlight_id.is_none() {
11151 old_highlight_id = chunk.syntax_highlight_id;
11152 }
11153 chunk.text
11154 })
11155 .collect::<String>()
11156 .into();
11157
11158 drop(buffer);
11159
11160 // Position the selection in the rename editor so that it matches the current selection.
11161 this.show_local_selections = false;
11162 let rename_editor = cx.new(|cx| {
11163 let mut editor = Editor::single_line(window, cx);
11164 editor.buffer.update(cx, |buffer, cx| {
11165 buffer.edit([(0..0, old_name.clone())], None, cx)
11166 });
11167 let rename_selection_range = match cursor_offset_in_rename_range
11168 .cmp(&cursor_offset_in_rename_range_end)
11169 {
11170 Ordering::Equal => {
11171 editor.select_all(&SelectAll, window, cx);
11172 return editor;
11173 }
11174 Ordering::Less => {
11175 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11176 }
11177 Ordering::Greater => {
11178 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11179 }
11180 };
11181 if rename_selection_range.end > old_name.len() {
11182 editor.select_all(&SelectAll, window, cx);
11183 } else {
11184 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11185 s.select_ranges([rename_selection_range]);
11186 });
11187 }
11188 editor
11189 });
11190 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11191 if e == &EditorEvent::Focused {
11192 cx.emit(EditorEvent::FocusedIn)
11193 }
11194 })
11195 .detach();
11196
11197 let write_highlights =
11198 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11199 let read_highlights =
11200 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11201 let ranges = write_highlights
11202 .iter()
11203 .flat_map(|(_, ranges)| ranges.iter())
11204 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11205 .cloned()
11206 .collect();
11207
11208 this.highlight_text::<Rename>(
11209 ranges,
11210 HighlightStyle {
11211 fade_out: Some(0.6),
11212 ..Default::default()
11213 },
11214 cx,
11215 );
11216 let rename_focus_handle = rename_editor.focus_handle(cx);
11217 window.focus(&rename_focus_handle);
11218 let block_id = this.insert_blocks(
11219 [BlockProperties {
11220 style: BlockStyle::Flex,
11221 placement: BlockPlacement::Below(range.start),
11222 height: 1,
11223 render: Arc::new({
11224 let rename_editor = rename_editor.clone();
11225 move |cx: &mut BlockContext| {
11226 let mut text_style = cx.editor_style.text.clone();
11227 if let Some(highlight_style) = old_highlight_id
11228 .and_then(|h| h.style(&cx.editor_style.syntax))
11229 {
11230 text_style = text_style.highlight(highlight_style);
11231 }
11232 div()
11233 .block_mouse_down()
11234 .pl(cx.anchor_x)
11235 .child(EditorElement::new(
11236 &rename_editor,
11237 EditorStyle {
11238 background: cx.theme().system().transparent,
11239 local_player: cx.editor_style.local_player,
11240 text: text_style,
11241 scrollbar_width: cx.editor_style.scrollbar_width,
11242 syntax: cx.editor_style.syntax.clone(),
11243 status: cx.editor_style.status.clone(),
11244 inlay_hints_style: HighlightStyle {
11245 font_weight: Some(FontWeight::BOLD),
11246 ..make_inlay_hints_style(cx.app)
11247 },
11248 inline_completion_styles: make_suggestion_styles(
11249 cx.app,
11250 ),
11251 ..EditorStyle::default()
11252 },
11253 ))
11254 .into_any_element()
11255 }
11256 }),
11257 priority: 0,
11258 }],
11259 Some(Autoscroll::fit()),
11260 cx,
11261 )[0];
11262 this.pending_rename = Some(RenameState {
11263 range,
11264 old_name,
11265 editor: rename_editor,
11266 block_id,
11267 });
11268 })?;
11269 }
11270
11271 Ok(())
11272 }))
11273 }
11274
11275 pub fn confirm_rename(
11276 &mut self,
11277 _: &ConfirmRename,
11278 window: &mut Window,
11279 cx: &mut Context<Self>,
11280 ) -> Option<Task<Result<()>>> {
11281 let rename = self.take_rename(false, window, cx)?;
11282 let workspace = self.workspace()?.downgrade();
11283 let (buffer, start) = self
11284 .buffer
11285 .read(cx)
11286 .text_anchor_for_position(rename.range.start, cx)?;
11287 let (end_buffer, _) = self
11288 .buffer
11289 .read(cx)
11290 .text_anchor_for_position(rename.range.end, cx)?;
11291 if buffer != end_buffer {
11292 return None;
11293 }
11294
11295 let old_name = rename.old_name;
11296 let new_name = rename.editor.read(cx).text(cx);
11297
11298 let rename = self.semantics_provider.as_ref()?.perform_rename(
11299 &buffer,
11300 start,
11301 new_name.clone(),
11302 cx,
11303 )?;
11304
11305 Some(cx.spawn_in(window, |editor, mut cx| async move {
11306 let project_transaction = rename.await?;
11307 Self::open_project_transaction(
11308 &editor,
11309 workspace,
11310 project_transaction,
11311 format!("Rename: {} → {}", old_name, new_name),
11312 cx.clone(),
11313 )
11314 .await?;
11315
11316 editor.update(&mut cx, |editor, cx| {
11317 editor.refresh_document_highlights(cx);
11318 })?;
11319 Ok(())
11320 }))
11321 }
11322
11323 fn take_rename(
11324 &mut self,
11325 moving_cursor: bool,
11326 window: &mut Window,
11327 cx: &mut Context<Self>,
11328 ) -> Option<RenameState> {
11329 let rename = self.pending_rename.take()?;
11330 if rename.editor.focus_handle(cx).is_focused(window) {
11331 window.focus(&self.focus_handle);
11332 }
11333
11334 self.remove_blocks(
11335 [rename.block_id].into_iter().collect(),
11336 Some(Autoscroll::fit()),
11337 cx,
11338 );
11339 self.clear_highlights::<Rename>(cx);
11340 self.show_local_selections = true;
11341
11342 if moving_cursor {
11343 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11344 editor.selections.newest::<usize>(cx).head()
11345 });
11346
11347 // Update the selection to match the position of the selection inside
11348 // the rename editor.
11349 let snapshot = self.buffer.read(cx).read(cx);
11350 let rename_range = rename.range.to_offset(&snapshot);
11351 let cursor_in_editor = snapshot
11352 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11353 .min(rename_range.end);
11354 drop(snapshot);
11355
11356 self.change_selections(None, window, cx, |s| {
11357 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11358 });
11359 } else {
11360 self.refresh_document_highlights(cx);
11361 }
11362
11363 Some(rename)
11364 }
11365
11366 pub fn pending_rename(&self) -> Option<&RenameState> {
11367 self.pending_rename.as_ref()
11368 }
11369
11370 fn format(
11371 &mut self,
11372 _: &Format,
11373 window: &mut Window,
11374 cx: &mut Context<Self>,
11375 ) -> Option<Task<Result<()>>> {
11376 let project = match &self.project {
11377 Some(project) => project.clone(),
11378 None => return None,
11379 };
11380
11381 Some(self.perform_format(
11382 project,
11383 FormatTrigger::Manual,
11384 FormatTarget::Buffers,
11385 window,
11386 cx,
11387 ))
11388 }
11389
11390 fn format_selections(
11391 &mut self,
11392 _: &FormatSelections,
11393 window: &mut Window,
11394 cx: &mut Context<Self>,
11395 ) -> Option<Task<Result<()>>> {
11396 let project = match &self.project {
11397 Some(project) => project.clone(),
11398 None => return None,
11399 };
11400
11401 let ranges = self
11402 .selections
11403 .all_adjusted(cx)
11404 .into_iter()
11405 .map(|selection| selection.range())
11406 .collect_vec();
11407
11408 Some(self.perform_format(
11409 project,
11410 FormatTrigger::Manual,
11411 FormatTarget::Ranges(ranges),
11412 window,
11413 cx,
11414 ))
11415 }
11416
11417 fn perform_format(
11418 &mut self,
11419 project: Entity<Project>,
11420 trigger: FormatTrigger,
11421 target: FormatTarget,
11422 window: &mut Window,
11423 cx: &mut Context<Self>,
11424 ) -> Task<Result<()>> {
11425 let buffer = self.buffer.clone();
11426 let (buffers, target) = match target {
11427 FormatTarget::Buffers => {
11428 let mut buffers = buffer.read(cx).all_buffers();
11429 if trigger == FormatTrigger::Save {
11430 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11431 }
11432 (buffers, LspFormatTarget::Buffers)
11433 }
11434 FormatTarget::Ranges(selection_ranges) => {
11435 let multi_buffer = buffer.read(cx);
11436 let snapshot = multi_buffer.read(cx);
11437 let mut buffers = HashSet::default();
11438 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11439 BTreeMap::new();
11440 for selection_range in selection_ranges {
11441 for (buffer, buffer_range, _) in
11442 snapshot.range_to_buffer_ranges(selection_range)
11443 {
11444 let buffer_id = buffer.remote_id();
11445 let start = buffer.anchor_before(buffer_range.start);
11446 let end = buffer.anchor_after(buffer_range.end);
11447 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11448 buffer_id_to_ranges
11449 .entry(buffer_id)
11450 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11451 .or_insert_with(|| vec![start..end]);
11452 }
11453 }
11454 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11455 }
11456 };
11457
11458 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11459 let format = project.update(cx, |project, cx| {
11460 project.format(buffers, target, true, trigger, cx)
11461 });
11462
11463 cx.spawn_in(window, |_, mut cx| async move {
11464 let transaction = futures::select_biased! {
11465 () = timeout => {
11466 log::warn!("timed out waiting for formatting");
11467 None
11468 }
11469 transaction = format.log_err().fuse() => transaction,
11470 };
11471
11472 buffer
11473 .update(&mut cx, |buffer, cx| {
11474 if let Some(transaction) = transaction {
11475 if !buffer.is_singleton() {
11476 buffer.push_transaction(&transaction.0, cx);
11477 }
11478 }
11479
11480 cx.notify();
11481 })
11482 .ok();
11483
11484 Ok(())
11485 })
11486 }
11487
11488 fn restart_language_server(
11489 &mut self,
11490 _: &RestartLanguageServer,
11491 _: &mut Window,
11492 cx: &mut Context<Self>,
11493 ) {
11494 if let Some(project) = self.project.clone() {
11495 self.buffer.update(cx, |multi_buffer, cx| {
11496 project.update(cx, |project, cx| {
11497 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11498 });
11499 })
11500 }
11501 }
11502
11503 fn cancel_language_server_work(
11504 workspace: &mut Workspace,
11505 _: &actions::CancelLanguageServerWork,
11506 _: &mut Window,
11507 cx: &mut Context<Workspace>,
11508 ) {
11509 let project = workspace.project();
11510 let buffers = workspace
11511 .active_item(cx)
11512 .and_then(|item| item.act_as::<Editor>(cx))
11513 .map_or(HashSet::default(), |editor| {
11514 editor.read(cx).buffer.read(cx).all_buffers()
11515 });
11516 project.update(cx, |project, cx| {
11517 project.cancel_language_server_work_for_buffers(buffers, cx);
11518 });
11519 }
11520
11521 fn show_character_palette(
11522 &mut self,
11523 _: &ShowCharacterPalette,
11524 window: &mut Window,
11525 _: &mut Context<Self>,
11526 ) {
11527 window.show_character_palette();
11528 }
11529
11530 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11531 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11532 let buffer = self.buffer.read(cx).snapshot(cx);
11533 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11534 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11535 let is_valid = buffer
11536 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11537 .any(|entry| {
11538 entry.diagnostic.is_primary
11539 && !entry.range.is_empty()
11540 && entry.range.start == primary_range_start
11541 && entry.diagnostic.message == active_diagnostics.primary_message
11542 });
11543
11544 if is_valid != active_diagnostics.is_valid {
11545 active_diagnostics.is_valid = is_valid;
11546 let mut new_styles = HashMap::default();
11547 for (block_id, diagnostic) in &active_diagnostics.blocks {
11548 new_styles.insert(
11549 *block_id,
11550 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11551 );
11552 }
11553 self.display_map.update(cx, |display_map, _cx| {
11554 display_map.replace_blocks(new_styles)
11555 });
11556 }
11557 }
11558 }
11559
11560 fn activate_diagnostics(
11561 &mut self,
11562 buffer_id: BufferId,
11563 group_id: usize,
11564 window: &mut Window,
11565 cx: &mut Context<Self>,
11566 ) {
11567 self.dismiss_diagnostics(cx);
11568 let snapshot = self.snapshot(window, cx);
11569 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11570 let buffer = self.buffer.read(cx).snapshot(cx);
11571
11572 let mut primary_range = None;
11573 let mut primary_message = None;
11574 let diagnostic_group = buffer
11575 .diagnostic_group(buffer_id, group_id)
11576 .filter_map(|entry| {
11577 let start = entry.range.start;
11578 let end = entry.range.end;
11579 if snapshot.is_line_folded(MultiBufferRow(start.row))
11580 && (start.row == end.row
11581 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11582 {
11583 return None;
11584 }
11585 if entry.diagnostic.is_primary {
11586 primary_range = Some(entry.range.clone());
11587 primary_message = Some(entry.diagnostic.message.clone());
11588 }
11589 Some(entry)
11590 })
11591 .collect::<Vec<_>>();
11592 let primary_range = primary_range?;
11593 let primary_message = primary_message?;
11594
11595 let blocks = display_map
11596 .insert_blocks(
11597 diagnostic_group.iter().map(|entry| {
11598 let diagnostic = entry.diagnostic.clone();
11599 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11600 BlockProperties {
11601 style: BlockStyle::Fixed,
11602 placement: BlockPlacement::Below(
11603 buffer.anchor_after(entry.range.start),
11604 ),
11605 height: message_height,
11606 render: diagnostic_block_renderer(diagnostic, None, true, true),
11607 priority: 0,
11608 }
11609 }),
11610 cx,
11611 )
11612 .into_iter()
11613 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11614 .collect();
11615
11616 Some(ActiveDiagnosticGroup {
11617 primary_range: buffer.anchor_before(primary_range.start)
11618 ..buffer.anchor_after(primary_range.end),
11619 primary_message,
11620 group_id,
11621 blocks,
11622 is_valid: true,
11623 })
11624 });
11625 }
11626
11627 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11628 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11629 self.display_map.update(cx, |display_map, cx| {
11630 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11631 });
11632 cx.notify();
11633 }
11634 }
11635
11636 pub fn set_selections_from_remote(
11637 &mut self,
11638 selections: Vec<Selection<Anchor>>,
11639 pending_selection: Option<Selection<Anchor>>,
11640 window: &mut Window,
11641 cx: &mut Context<Self>,
11642 ) {
11643 let old_cursor_position = self.selections.newest_anchor().head();
11644 self.selections.change_with(cx, |s| {
11645 s.select_anchors(selections);
11646 if let Some(pending_selection) = pending_selection {
11647 s.set_pending(pending_selection, SelectMode::Character);
11648 } else {
11649 s.clear_pending();
11650 }
11651 });
11652 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11653 }
11654
11655 fn push_to_selection_history(&mut self) {
11656 self.selection_history.push(SelectionHistoryEntry {
11657 selections: self.selections.disjoint_anchors(),
11658 select_next_state: self.select_next_state.clone(),
11659 select_prev_state: self.select_prev_state.clone(),
11660 add_selections_state: self.add_selections_state.clone(),
11661 });
11662 }
11663
11664 pub fn transact(
11665 &mut self,
11666 window: &mut Window,
11667 cx: &mut Context<Self>,
11668 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11669 ) -> Option<TransactionId> {
11670 self.start_transaction_at(Instant::now(), window, cx);
11671 update(self, window, cx);
11672 self.end_transaction_at(Instant::now(), cx)
11673 }
11674
11675 pub fn start_transaction_at(
11676 &mut self,
11677 now: Instant,
11678 window: &mut Window,
11679 cx: &mut Context<Self>,
11680 ) {
11681 self.end_selection(window, cx);
11682 if let Some(tx_id) = self
11683 .buffer
11684 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11685 {
11686 self.selection_history
11687 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11688 cx.emit(EditorEvent::TransactionBegun {
11689 transaction_id: tx_id,
11690 })
11691 }
11692 }
11693
11694 pub fn end_transaction_at(
11695 &mut self,
11696 now: Instant,
11697 cx: &mut Context<Self>,
11698 ) -> Option<TransactionId> {
11699 if let Some(transaction_id) = self
11700 .buffer
11701 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11702 {
11703 if let Some((_, end_selections)) =
11704 self.selection_history.transaction_mut(transaction_id)
11705 {
11706 *end_selections = Some(self.selections.disjoint_anchors());
11707 } else {
11708 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11709 }
11710
11711 cx.emit(EditorEvent::Edited { transaction_id });
11712 Some(transaction_id)
11713 } else {
11714 None
11715 }
11716 }
11717
11718 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11719 if self.selection_mark_mode {
11720 self.change_selections(None, window, cx, |s| {
11721 s.move_with(|_, sel| {
11722 sel.collapse_to(sel.head(), SelectionGoal::None);
11723 });
11724 })
11725 }
11726 self.selection_mark_mode = true;
11727 cx.notify();
11728 }
11729
11730 pub fn swap_selection_ends(
11731 &mut self,
11732 _: &actions::SwapSelectionEnds,
11733 window: &mut Window,
11734 cx: &mut Context<Self>,
11735 ) {
11736 self.change_selections(None, window, cx, |s| {
11737 s.move_with(|_, sel| {
11738 if sel.start != sel.end {
11739 sel.reversed = !sel.reversed
11740 }
11741 });
11742 });
11743 self.request_autoscroll(Autoscroll::newest(), cx);
11744 cx.notify();
11745 }
11746
11747 pub fn toggle_fold(
11748 &mut self,
11749 _: &actions::ToggleFold,
11750 window: &mut Window,
11751 cx: &mut Context<Self>,
11752 ) {
11753 if self.is_singleton(cx) {
11754 let selection = self.selections.newest::<Point>(cx);
11755
11756 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11757 let range = if selection.is_empty() {
11758 let point = selection.head().to_display_point(&display_map);
11759 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11760 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11761 .to_point(&display_map);
11762 start..end
11763 } else {
11764 selection.range()
11765 };
11766 if display_map.folds_in_range(range).next().is_some() {
11767 self.unfold_lines(&Default::default(), window, cx)
11768 } else {
11769 self.fold(&Default::default(), window, cx)
11770 }
11771 } else {
11772 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11773 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11774 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11775 .map(|(snapshot, _, _)| snapshot.remote_id())
11776 .collect();
11777
11778 for buffer_id in buffer_ids {
11779 if self.is_buffer_folded(buffer_id, cx) {
11780 self.unfold_buffer(buffer_id, cx);
11781 } else {
11782 self.fold_buffer(buffer_id, cx);
11783 }
11784 }
11785 }
11786 }
11787
11788 pub fn toggle_fold_recursive(
11789 &mut self,
11790 _: &actions::ToggleFoldRecursive,
11791 window: &mut Window,
11792 cx: &mut Context<Self>,
11793 ) {
11794 let selection = self.selections.newest::<Point>(cx);
11795
11796 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11797 let range = if selection.is_empty() {
11798 let point = selection.head().to_display_point(&display_map);
11799 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11800 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11801 .to_point(&display_map);
11802 start..end
11803 } else {
11804 selection.range()
11805 };
11806 if display_map.folds_in_range(range).next().is_some() {
11807 self.unfold_recursive(&Default::default(), window, cx)
11808 } else {
11809 self.fold_recursive(&Default::default(), window, cx)
11810 }
11811 }
11812
11813 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11814 if self.is_singleton(cx) {
11815 let mut to_fold = Vec::new();
11816 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11817 let selections = self.selections.all_adjusted(cx);
11818
11819 for selection in selections {
11820 let range = selection.range().sorted();
11821 let buffer_start_row = range.start.row;
11822
11823 if range.start.row != range.end.row {
11824 let mut found = false;
11825 let mut row = range.start.row;
11826 while row <= range.end.row {
11827 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11828 {
11829 found = true;
11830 row = crease.range().end.row + 1;
11831 to_fold.push(crease);
11832 } else {
11833 row += 1
11834 }
11835 }
11836 if found {
11837 continue;
11838 }
11839 }
11840
11841 for row in (0..=range.start.row).rev() {
11842 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11843 if crease.range().end.row >= buffer_start_row {
11844 to_fold.push(crease);
11845 if row <= range.start.row {
11846 break;
11847 }
11848 }
11849 }
11850 }
11851 }
11852
11853 self.fold_creases(to_fold, true, window, cx);
11854 } else {
11855 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11856
11857 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11858 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11859 .map(|(snapshot, _, _)| snapshot.remote_id())
11860 .collect();
11861 for buffer_id in buffer_ids {
11862 self.fold_buffer(buffer_id, cx);
11863 }
11864 }
11865 }
11866
11867 fn fold_at_level(
11868 &mut self,
11869 fold_at: &FoldAtLevel,
11870 window: &mut Window,
11871 cx: &mut Context<Self>,
11872 ) {
11873 if !self.buffer.read(cx).is_singleton() {
11874 return;
11875 }
11876
11877 let fold_at_level = fold_at.0;
11878 let snapshot = self.buffer.read(cx).snapshot(cx);
11879 let mut to_fold = Vec::new();
11880 let mut stack = vec![(0, snapshot.max_row().0, 1)];
11881
11882 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11883 while start_row < end_row {
11884 match self
11885 .snapshot(window, cx)
11886 .crease_for_buffer_row(MultiBufferRow(start_row))
11887 {
11888 Some(crease) => {
11889 let nested_start_row = crease.range().start.row + 1;
11890 let nested_end_row = crease.range().end.row;
11891
11892 if current_level < fold_at_level {
11893 stack.push((nested_start_row, nested_end_row, current_level + 1));
11894 } else if current_level == fold_at_level {
11895 to_fold.push(crease);
11896 }
11897
11898 start_row = nested_end_row + 1;
11899 }
11900 None => start_row += 1,
11901 }
11902 }
11903 }
11904
11905 self.fold_creases(to_fold, true, window, cx);
11906 }
11907
11908 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11909 if self.buffer.read(cx).is_singleton() {
11910 let mut fold_ranges = Vec::new();
11911 let snapshot = self.buffer.read(cx).snapshot(cx);
11912
11913 for row in 0..snapshot.max_row().0 {
11914 if let Some(foldable_range) = self
11915 .snapshot(window, cx)
11916 .crease_for_buffer_row(MultiBufferRow(row))
11917 {
11918 fold_ranges.push(foldable_range);
11919 }
11920 }
11921
11922 self.fold_creases(fold_ranges, true, window, cx);
11923 } else {
11924 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11925 editor
11926 .update_in(&mut cx, |editor, _, cx| {
11927 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11928 editor.fold_buffer(buffer_id, cx);
11929 }
11930 })
11931 .ok();
11932 });
11933 }
11934 }
11935
11936 pub fn fold_function_bodies(
11937 &mut self,
11938 _: &actions::FoldFunctionBodies,
11939 window: &mut Window,
11940 cx: &mut Context<Self>,
11941 ) {
11942 let snapshot = self.buffer.read(cx).snapshot(cx);
11943
11944 let ranges = snapshot
11945 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11946 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11947 .collect::<Vec<_>>();
11948
11949 let creases = ranges
11950 .into_iter()
11951 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11952 .collect();
11953
11954 self.fold_creases(creases, true, window, cx);
11955 }
11956
11957 pub fn fold_recursive(
11958 &mut self,
11959 _: &actions::FoldRecursive,
11960 window: &mut Window,
11961 cx: &mut Context<Self>,
11962 ) {
11963 let mut to_fold = Vec::new();
11964 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11965 let selections = self.selections.all_adjusted(cx);
11966
11967 for selection in selections {
11968 let range = selection.range().sorted();
11969 let buffer_start_row = range.start.row;
11970
11971 if range.start.row != range.end.row {
11972 let mut found = false;
11973 for row in range.start.row..=range.end.row {
11974 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11975 found = true;
11976 to_fold.push(crease);
11977 }
11978 }
11979 if found {
11980 continue;
11981 }
11982 }
11983
11984 for row in (0..=range.start.row).rev() {
11985 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11986 if crease.range().end.row >= buffer_start_row {
11987 to_fold.push(crease);
11988 } else {
11989 break;
11990 }
11991 }
11992 }
11993 }
11994
11995 self.fold_creases(to_fold, true, window, cx);
11996 }
11997
11998 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11999 let buffer_row = fold_at.buffer_row;
12000 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12001
12002 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12003 let autoscroll = self
12004 .selections
12005 .all::<Point>(cx)
12006 .iter()
12007 .any(|selection| crease.range().overlaps(&selection.range()));
12008
12009 self.fold_creases(vec![crease], autoscroll, window, cx);
12010 }
12011 }
12012
12013 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12014 if self.is_singleton(cx) {
12015 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12016 let buffer = &display_map.buffer_snapshot;
12017 let selections = self.selections.all::<Point>(cx);
12018 let ranges = selections
12019 .iter()
12020 .map(|s| {
12021 let range = s.display_range(&display_map).sorted();
12022 let mut start = range.start.to_point(&display_map);
12023 let mut end = range.end.to_point(&display_map);
12024 start.column = 0;
12025 end.column = buffer.line_len(MultiBufferRow(end.row));
12026 start..end
12027 })
12028 .collect::<Vec<_>>();
12029
12030 self.unfold_ranges(&ranges, true, true, cx);
12031 } else {
12032 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12033 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12034 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12035 .map(|(snapshot, _, _)| snapshot.remote_id())
12036 .collect();
12037 for buffer_id in buffer_ids {
12038 self.unfold_buffer(buffer_id, cx);
12039 }
12040 }
12041 }
12042
12043 pub fn unfold_recursive(
12044 &mut self,
12045 _: &UnfoldRecursive,
12046 _window: &mut Window,
12047 cx: &mut Context<Self>,
12048 ) {
12049 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12050 let selections = self.selections.all::<Point>(cx);
12051 let ranges = selections
12052 .iter()
12053 .map(|s| {
12054 let mut range = s.display_range(&display_map).sorted();
12055 *range.start.column_mut() = 0;
12056 *range.end.column_mut() = display_map.line_len(range.end.row());
12057 let start = range.start.to_point(&display_map);
12058 let end = range.end.to_point(&display_map);
12059 start..end
12060 })
12061 .collect::<Vec<_>>();
12062
12063 self.unfold_ranges(&ranges, true, true, cx);
12064 }
12065
12066 pub fn unfold_at(
12067 &mut self,
12068 unfold_at: &UnfoldAt,
12069 _window: &mut Window,
12070 cx: &mut Context<Self>,
12071 ) {
12072 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12073
12074 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12075 ..Point::new(
12076 unfold_at.buffer_row.0,
12077 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12078 );
12079
12080 let autoscroll = self
12081 .selections
12082 .all::<Point>(cx)
12083 .iter()
12084 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12085
12086 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12087 }
12088
12089 pub fn unfold_all(
12090 &mut self,
12091 _: &actions::UnfoldAll,
12092 _window: &mut Window,
12093 cx: &mut Context<Self>,
12094 ) {
12095 if self.buffer.read(cx).is_singleton() {
12096 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12097 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12098 } else {
12099 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12100 editor
12101 .update(&mut cx, |editor, cx| {
12102 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12103 editor.unfold_buffer(buffer_id, cx);
12104 }
12105 })
12106 .ok();
12107 });
12108 }
12109 }
12110
12111 pub fn fold_selected_ranges(
12112 &mut self,
12113 _: &FoldSelectedRanges,
12114 window: &mut Window,
12115 cx: &mut Context<Self>,
12116 ) {
12117 let selections = self.selections.all::<Point>(cx);
12118 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12119 let line_mode = self.selections.line_mode;
12120 let ranges = selections
12121 .into_iter()
12122 .map(|s| {
12123 if line_mode {
12124 let start = Point::new(s.start.row, 0);
12125 let end = Point::new(
12126 s.end.row,
12127 display_map
12128 .buffer_snapshot
12129 .line_len(MultiBufferRow(s.end.row)),
12130 );
12131 Crease::simple(start..end, display_map.fold_placeholder.clone())
12132 } else {
12133 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12134 }
12135 })
12136 .collect::<Vec<_>>();
12137 self.fold_creases(ranges, true, window, cx);
12138 }
12139
12140 pub fn fold_ranges<T: ToOffset + Clone>(
12141 &mut self,
12142 ranges: Vec<Range<T>>,
12143 auto_scroll: bool,
12144 window: &mut Window,
12145 cx: &mut Context<Self>,
12146 ) {
12147 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12148 let ranges = ranges
12149 .into_iter()
12150 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12151 .collect::<Vec<_>>();
12152 self.fold_creases(ranges, auto_scroll, window, cx);
12153 }
12154
12155 pub fn fold_creases<T: ToOffset + Clone>(
12156 &mut self,
12157 creases: Vec<Crease<T>>,
12158 auto_scroll: bool,
12159 window: &mut Window,
12160 cx: &mut Context<Self>,
12161 ) {
12162 if creases.is_empty() {
12163 return;
12164 }
12165
12166 let mut buffers_affected = HashSet::default();
12167 let multi_buffer = self.buffer().read(cx);
12168 for crease in &creases {
12169 if let Some((_, buffer, _)) =
12170 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12171 {
12172 buffers_affected.insert(buffer.read(cx).remote_id());
12173 };
12174 }
12175
12176 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12177
12178 if auto_scroll {
12179 self.request_autoscroll(Autoscroll::fit(), cx);
12180 }
12181
12182 cx.notify();
12183
12184 if let Some(active_diagnostics) = self.active_diagnostics.take() {
12185 // Clear diagnostics block when folding a range that contains it.
12186 let snapshot = self.snapshot(window, cx);
12187 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12188 drop(snapshot);
12189 self.active_diagnostics = Some(active_diagnostics);
12190 self.dismiss_diagnostics(cx);
12191 } else {
12192 self.active_diagnostics = Some(active_diagnostics);
12193 }
12194 }
12195
12196 self.scrollbar_marker_state.dirty = true;
12197 }
12198
12199 /// Removes any folds whose ranges intersect any of the given ranges.
12200 pub fn unfold_ranges<T: ToOffset + Clone>(
12201 &mut self,
12202 ranges: &[Range<T>],
12203 inclusive: bool,
12204 auto_scroll: bool,
12205 cx: &mut Context<Self>,
12206 ) {
12207 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12208 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12209 });
12210 }
12211
12212 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12213 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12214 return;
12215 }
12216 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12217 self.display_map
12218 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12219 cx.emit(EditorEvent::BufferFoldToggled {
12220 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12221 folded: true,
12222 });
12223 cx.notify();
12224 }
12225
12226 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12227 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12228 return;
12229 }
12230 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12231 self.display_map.update(cx, |display_map, cx| {
12232 display_map.unfold_buffer(buffer_id, cx);
12233 });
12234 cx.emit(EditorEvent::BufferFoldToggled {
12235 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12236 folded: false,
12237 });
12238 cx.notify();
12239 }
12240
12241 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12242 self.display_map.read(cx).is_buffer_folded(buffer)
12243 }
12244
12245 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12246 self.display_map.read(cx).folded_buffers()
12247 }
12248
12249 /// Removes any folds with the given ranges.
12250 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12251 &mut self,
12252 ranges: &[Range<T>],
12253 type_id: TypeId,
12254 auto_scroll: bool,
12255 cx: &mut Context<Self>,
12256 ) {
12257 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12258 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12259 });
12260 }
12261
12262 fn remove_folds_with<T: ToOffset + Clone>(
12263 &mut self,
12264 ranges: &[Range<T>],
12265 auto_scroll: bool,
12266 cx: &mut Context<Self>,
12267 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12268 ) {
12269 if ranges.is_empty() {
12270 return;
12271 }
12272
12273 let mut buffers_affected = HashSet::default();
12274 let multi_buffer = self.buffer().read(cx);
12275 for range in ranges {
12276 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12277 buffers_affected.insert(buffer.read(cx).remote_id());
12278 };
12279 }
12280
12281 self.display_map.update(cx, update);
12282
12283 if auto_scroll {
12284 self.request_autoscroll(Autoscroll::fit(), cx);
12285 }
12286
12287 cx.notify();
12288 self.scrollbar_marker_state.dirty = true;
12289 self.active_indent_guides_state.dirty = true;
12290 }
12291
12292 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12293 self.display_map.read(cx).fold_placeholder.clone()
12294 }
12295
12296 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12297 self.buffer.update(cx, |buffer, cx| {
12298 buffer.set_all_diff_hunks_expanded(cx);
12299 });
12300 }
12301
12302 pub fn expand_all_diff_hunks(
12303 &mut self,
12304 _: &ExpandAllHunkDiffs,
12305 _window: &mut Window,
12306 cx: &mut Context<Self>,
12307 ) {
12308 self.buffer.update(cx, |buffer, cx| {
12309 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12310 });
12311 }
12312
12313 pub fn toggle_selected_diff_hunks(
12314 &mut self,
12315 _: &ToggleSelectedDiffHunks,
12316 _window: &mut Window,
12317 cx: &mut Context<Self>,
12318 ) {
12319 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12320 self.toggle_diff_hunks_in_ranges(ranges, cx);
12321 }
12322
12323 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12324 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12325 self.buffer
12326 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12327 }
12328
12329 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12330 self.buffer.update(cx, |buffer, cx| {
12331 let ranges = vec![Anchor::min()..Anchor::max()];
12332 if !buffer.all_diff_hunks_expanded()
12333 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12334 {
12335 buffer.collapse_diff_hunks(ranges, cx);
12336 true
12337 } else {
12338 false
12339 }
12340 })
12341 }
12342
12343 fn toggle_diff_hunks_in_ranges(
12344 &mut self,
12345 ranges: Vec<Range<Anchor>>,
12346 cx: &mut Context<'_, Editor>,
12347 ) {
12348 self.buffer.update(cx, |buffer, cx| {
12349 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12350 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12351 })
12352 }
12353
12354 fn toggle_diff_hunks_in_ranges_narrow(
12355 &mut self,
12356 ranges: Vec<Range<Anchor>>,
12357 cx: &mut Context<'_, Editor>,
12358 ) {
12359 self.buffer.update(cx, |buffer, cx| {
12360 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12361 buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12362 })
12363 }
12364
12365 pub(crate) fn apply_all_diff_hunks(
12366 &mut self,
12367 _: &ApplyAllDiffHunks,
12368 window: &mut Window,
12369 cx: &mut Context<Self>,
12370 ) {
12371 let buffers = self.buffer.read(cx).all_buffers();
12372 for branch_buffer in buffers {
12373 branch_buffer.update(cx, |branch_buffer, cx| {
12374 branch_buffer.merge_into_base(Vec::new(), cx);
12375 });
12376 }
12377
12378 if let Some(project) = self.project.clone() {
12379 self.save(true, project, window, cx).detach_and_log_err(cx);
12380 }
12381 }
12382
12383 pub(crate) fn apply_selected_diff_hunks(
12384 &mut self,
12385 _: &ApplyDiffHunk,
12386 window: &mut Window,
12387 cx: &mut Context<Self>,
12388 ) {
12389 let snapshot = self.snapshot(window, cx);
12390 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12391 let mut ranges_by_buffer = HashMap::default();
12392 self.transact(window, cx, |editor, _window, cx| {
12393 for hunk in hunks {
12394 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12395 ranges_by_buffer
12396 .entry(buffer.clone())
12397 .or_insert_with(Vec::new)
12398 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12399 }
12400 }
12401
12402 for (buffer, ranges) in ranges_by_buffer {
12403 buffer.update(cx, |buffer, cx| {
12404 buffer.merge_into_base(ranges, cx);
12405 });
12406 }
12407 });
12408
12409 if let Some(project) = self.project.clone() {
12410 self.save(true, project, window, cx).detach_and_log_err(cx);
12411 }
12412 }
12413
12414 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12415 if hovered != self.gutter_hovered {
12416 self.gutter_hovered = hovered;
12417 cx.notify();
12418 }
12419 }
12420
12421 pub fn insert_blocks(
12422 &mut self,
12423 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12424 autoscroll: Option<Autoscroll>,
12425 cx: &mut Context<Self>,
12426 ) -> Vec<CustomBlockId> {
12427 let blocks = self
12428 .display_map
12429 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12430 if let Some(autoscroll) = autoscroll {
12431 self.request_autoscroll(autoscroll, cx);
12432 }
12433 cx.notify();
12434 blocks
12435 }
12436
12437 pub fn resize_blocks(
12438 &mut self,
12439 heights: HashMap<CustomBlockId, u32>,
12440 autoscroll: Option<Autoscroll>,
12441 cx: &mut Context<Self>,
12442 ) {
12443 self.display_map
12444 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12445 if let Some(autoscroll) = autoscroll {
12446 self.request_autoscroll(autoscroll, cx);
12447 }
12448 cx.notify();
12449 }
12450
12451 pub fn replace_blocks(
12452 &mut self,
12453 renderers: HashMap<CustomBlockId, RenderBlock>,
12454 autoscroll: Option<Autoscroll>,
12455 cx: &mut Context<Self>,
12456 ) {
12457 self.display_map
12458 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12459 if let Some(autoscroll) = autoscroll {
12460 self.request_autoscroll(autoscroll, cx);
12461 }
12462 cx.notify();
12463 }
12464
12465 pub fn remove_blocks(
12466 &mut self,
12467 block_ids: HashSet<CustomBlockId>,
12468 autoscroll: Option<Autoscroll>,
12469 cx: &mut Context<Self>,
12470 ) {
12471 self.display_map.update(cx, |display_map, cx| {
12472 display_map.remove_blocks(block_ids, cx)
12473 });
12474 if let Some(autoscroll) = autoscroll {
12475 self.request_autoscroll(autoscroll, cx);
12476 }
12477 cx.notify();
12478 }
12479
12480 pub fn row_for_block(
12481 &self,
12482 block_id: CustomBlockId,
12483 cx: &mut Context<Self>,
12484 ) -> Option<DisplayRow> {
12485 self.display_map
12486 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12487 }
12488
12489 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12490 self.focused_block = Some(focused_block);
12491 }
12492
12493 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12494 self.focused_block.take()
12495 }
12496
12497 pub fn insert_creases(
12498 &mut self,
12499 creases: impl IntoIterator<Item = Crease<Anchor>>,
12500 cx: &mut Context<Self>,
12501 ) -> Vec<CreaseId> {
12502 self.display_map
12503 .update(cx, |map, cx| map.insert_creases(creases, cx))
12504 }
12505
12506 pub fn remove_creases(
12507 &mut self,
12508 ids: impl IntoIterator<Item = CreaseId>,
12509 cx: &mut Context<Self>,
12510 ) {
12511 self.display_map
12512 .update(cx, |map, cx| map.remove_creases(ids, cx));
12513 }
12514
12515 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12516 self.display_map
12517 .update(cx, |map, cx| map.snapshot(cx))
12518 .longest_row()
12519 }
12520
12521 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12522 self.display_map
12523 .update(cx, |map, cx| map.snapshot(cx))
12524 .max_point()
12525 }
12526
12527 pub fn text(&self, cx: &App) -> String {
12528 self.buffer.read(cx).read(cx).text()
12529 }
12530
12531 pub fn is_empty(&self, cx: &App) -> bool {
12532 self.buffer.read(cx).read(cx).is_empty()
12533 }
12534
12535 pub fn text_option(&self, cx: &App) -> Option<String> {
12536 let text = self.text(cx);
12537 let text = text.trim();
12538
12539 if text.is_empty() {
12540 return None;
12541 }
12542
12543 Some(text.to_string())
12544 }
12545
12546 pub fn set_text(
12547 &mut self,
12548 text: impl Into<Arc<str>>,
12549 window: &mut Window,
12550 cx: &mut Context<Self>,
12551 ) {
12552 self.transact(window, cx, |this, _, cx| {
12553 this.buffer
12554 .read(cx)
12555 .as_singleton()
12556 .expect("you can only call set_text on editors for singleton buffers")
12557 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12558 });
12559 }
12560
12561 pub fn display_text(&self, cx: &mut App) -> String {
12562 self.display_map
12563 .update(cx, |map, cx| map.snapshot(cx))
12564 .text()
12565 }
12566
12567 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12568 let mut wrap_guides = smallvec::smallvec![];
12569
12570 if self.show_wrap_guides == Some(false) {
12571 return wrap_guides;
12572 }
12573
12574 let settings = self.buffer.read(cx).settings_at(0, cx);
12575 if settings.show_wrap_guides {
12576 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12577 wrap_guides.push((soft_wrap as usize, true));
12578 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12579 wrap_guides.push((soft_wrap as usize, true));
12580 }
12581 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12582 }
12583
12584 wrap_guides
12585 }
12586
12587 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12588 let settings = self.buffer.read(cx).settings_at(0, cx);
12589 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12590 match mode {
12591 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12592 SoftWrap::None
12593 }
12594 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12595 language_settings::SoftWrap::PreferredLineLength => {
12596 SoftWrap::Column(settings.preferred_line_length)
12597 }
12598 language_settings::SoftWrap::Bounded => {
12599 SoftWrap::Bounded(settings.preferred_line_length)
12600 }
12601 }
12602 }
12603
12604 pub fn set_soft_wrap_mode(
12605 &mut self,
12606 mode: language_settings::SoftWrap,
12607
12608 cx: &mut Context<Self>,
12609 ) {
12610 self.soft_wrap_mode_override = Some(mode);
12611 cx.notify();
12612 }
12613
12614 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12615 self.text_style_refinement = Some(style);
12616 }
12617
12618 /// called by the Element so we know what style we were most recently rendered with.
12619 pub(crate) fn set_style(
12620 &mut self,
12621 style: EditorStyle,
12622 window: &mut Window,
12623 cx: &mut Context<Self>,
12624 ) {
12625 let rem_size = window.rem_size();
12626 self.display_map.update(cx, |map, cx| {
12627 map.set_font(
12628 style.text.font(),
12629 style.text.font_size.to_pixels(rem_size),
12630 cx,
12631 )
12632 });
12633 self.style = Some(style);
12634 }
12635
12636 pub fn style(&self) -> Option<&EditorStyle> {
12637 self.style.as_ref()
12638 }
12639
12640 // Called by the element. This method is not designed to be called outside of the editor
12641 // element's layout code because it does not notify when rewrapping is computed synchronously.
12642 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12643 self.display_map
12644 .update(cx, |map, cx| map.set_wrap_width(width, cx))
12645 }
12646
12647 pub fn set_soft_wrap(&mut self) {
12648 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12649 }
12650
12651 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12652 if self.soft_wrap_mode_override.is_some() {
12653 self.soft_wrap_mode_override.take();
12654 } else {
12655 let soft_wrap = match self.soft_wrap_mode(cx) {
12656 SoftWrap::GitDiff => return,
12657 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12658 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12659 language_settings::SoftWrap::None
12660 }
12661 };
12662 self.soft_wrap_mode_override = Some(soft_wrap);
12663 }
12664 cx.notify();
12665 }
12666
12667 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12668 let Some(workspace) = self.workspace() else {
12669 return;
12670 };
12671 let fs = workspace.read(cx).app_state().fs.clone();
12672 let current_show = TabBarSettings::get_global(cx).show;
12673 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12674 setting.show = Some(!current_show);
12675 });
12676 }
12677
12678 pub fn toggle_indent_guides(
12679 &mut self,
12680 _: &ToggleIndentGuides,
12681 _: &mut Window,
12682 cx: &mut Context<Self>,
12683 ) {
12684 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12685 self.buffer
12686 .read(cx)
12687 .settings_at(0, cx)
12688 .indent_guides
12689 .enabled
12690 });
12691 self.show_indent_guides = Some(!currently_enabled);
12692 cx.notify();
12693 }
12694
12695 fn should_show_indent_guides(&self) -> Option<bool> {
12696 self.show_indent_guides
12697 }
12698
12699 pub fn toggle_line_numbers(
12700 &mut self,
12701 _: &ToggleLineNumbers,
12702 _: &mut Window,
12703 cx: &mut Context<Self>,
12704 ) {
12705 let mut editor_settings = EditorSettings::get_global(cx).clone();
12706 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12707 EditorSettings::override_global(editor_settings, cx);
12708 }
12709
12710 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12711 self.use_relative_line_numbers
12712 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12713 }
12714
12715 pub fn toggle_relative_line_numbers(
12716 &mut self,
12717 _: &ToggleRelativeLineNumbers,
12718 _: &mut Window,
12719 cx: &mut Context<Self>,
12720 ) {
12721 let is_relative = self.should_use_relative_line_numbers(cx);
12722 self.set_relative_line_number(Some(!is_relative), cx)
12723 }
12724
12725 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12726 self.use_relative_line_numbers = is_relative;
12727 cx.notify();
12728 }
12729
12730 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12731 self.show_gutter = show_gutter;
12732 cx.notify();
12733 }
12734
12735 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12736 self.show_scrollbars = show_scrollbars;
12737 cx.notify();
12738 }
12739
12740 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12741 self.show_line_numbers = Some(show_line_numbers);
12742 cx.notify();
12743 }
12744
12745 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12746 self.show_git_diff_gutter = Some(show_git_diff_gutter);
12747 cx.notify();
12748 }
12749
12750 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12751 self.show_code_actions = Some(show_code_actions);
12752 cx.notify();
12753 }
12754
12755 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12756 self.show_runnables = Some(show_runnables);
12757 cx.notify();
12758 }
12759
12760 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12761 if self.display_map.read(cx).masked != masked {
12762 self.display_map.update(cx, |map, _| map.masked = masked);
12763 }
12764 cx.notify()
12765 }
12766
12767 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12768 self.show_wrap_guides = Some(show_wrap_guides);
12769 cx.notify();
12770 }
12771
12772 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12773 self.show_indent_guides = Some(show_indent_guides);
12774 cx.notify();
12775 }
12776
12777 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12778 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12779 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12780 if let Some(dir) = file.abs_path(cx).parent() {
12781 return Some(dir.to_owned());
12782 }
12783 }
12784
12785 if let Some(project_path) = buffer.read(cx).project_path(cx) {
12786 return Some(project_path.path.to_path_buf());
12787 }
12788 }
12789
12790 None
12791 }
12792
12793 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12794 self.active_excerpt(cx)?
12795 .1
12796 .read(cx)
12797 .file()
12798 .and_then(|f| f.as_local())
12799 }
12800
12801 fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12802 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12803 let project_path = buffer.read(cx).project_path(cx)?;
12804 let project = self.project.as_ref()?.read(cx);
12805 project.absolute_path(&project_path, cx)
12806 })
12807 }
12808
12809 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12810 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12811 let project_path = buffer.read(cx).project_path(cx)?;
12812 let project = self.project.as_ref()?.read(cx);
12813 let entry = project.entry_for_path(&project_path, cx)?;
12814 let path = entry.path.to_path_buf();
12815 Some(path)
12816 })
12817 }
12818
12819 pub fn reveal_in_finder(
12820 &mut self,
12821 _: &RevealInFileManager,
12822 _window: &mut Window,
12823 cx: &mut Context<Self>,
12824 ) {
12825 if let Some(target) = self.target_file(cx) {
12826 cx.reveal_path(&target.abs_path(cx));
12827 }
12828 }
12829
12830 pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12831 if let Some(path) = self.target_file_abs_path(cx) {
12832 if let Some(path) = path.to_str() {
12833 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12834 }
12835 }
12836 }
12837
12838 pub fn copy_relative_path(
12839 &mut self,
12840 _: &CopyRelativePath,
12841 _window: &mut Window,
12842 cx: &mut Context<Self>,
12843 ) {
12844 if let Some(path) = self.target_file_path(cx) {
12845 if let Some(path) = path.to_str() {
12846 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12847 }
12848 }
12849 }
12850
12851 pub fn toggle_git_blame(
12852 &mut self,
12853 _: &ToggleGitBlame,
12854 window: &mut Window,
12855 cx: &mut Context<Self>,
12856 ) {
12857 self.show_git_blame_gutter = !self.show_git_blame_gutter;
12858
12859 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12860 self.start_git_blame(true, window, cx);
12861 }
12862
12863 cx.notify();
12864 }
12865
12866 pub fn toggle_git_blame_inline(
12867 &mut self,
12868 _: &ToggleGitBlameInline,
12869 window: &mut Window,
12870 cx: &mut Context<Self>,
12871 ) {
12872 self.toggle_git_blame_inline_internal(true, window, cx);
12873 cx.notify();
12874 }
12875
12876 pub fn git_blame_inline_enabled(&self) -> bool {
12877 self.git_blame_inline_enabled
12878 }
12879
12880 pub fn toggle_selection_menu(
12881 &mut self,
12882 _: &ToggleSelectionMenu,
12883 _: &mut Window,
12884 cx: &mut Context<Self>,
12885 ) {
12886 self.show_selection_menu = self
12887 .show_selection_menu
12888 .map(|show_selections_menu| !show_selections_menu)
12889 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12890
12891 cx.notify();
12892 }
12893
12894 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12895 self.show_selection_menu
12896 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12897 }
12898
12899 fn start_git_blame(
12900 &mut self,
12901 user_triggered: bool,
12902 window: &mut Window,
12903 cx: &mut Context<Self>,
12904 ) {
12905 if let Some(project) = self.project.as_ref() {
12906 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12907 return;
12908 };
12909
12910 if buffer.read(cx).file().is_none() {
12911 return;
12912 }
12913
12914 let focused = self.focus_handle(cx).contains_focused(window, cx);
12915
12916 let project = project.clone();
12917 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12918 self.blame_subscription =
12919 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12920 self.blame = Some(blame);
12921 }
12922 }
12923
12924 fn toggle_git_blame_inline_internal(
12925 &mut self,
12926 user_triggered: bool,
12927 window: &mut Window,
12928 cx: &mut Context<Self>,
12929 ) {
12930 if self.git_blame_inline_enabled {
12931 self.git_blame_inline_enabled = false;
12932 self.show_git_blame_inline = false;
12933 self.show_git_blame_inline_delay_task.take();
12934 } else {
12935 self.git_blame_inline_enabled = true;
12936 self.start_git_blame_inline(user_triggered, window, cx);
12937 }
12938
12939 cx.notify();
12940 }
12941
12942 fn start_git_blame_inline(
12943 &mut self,
12944 user_triggered: bool,
12945 window: &mut Window,
12946 cx: &mut Context<Self>,
12947 ) {
12948 self.start_git_blame(user_triggered, window, cx);
12949
12950 if ProjectSettings::get_global(cx)
12951 .git
12952 .inline_blame_delay()
12953 .is_some()
12954 {
12955 self.start_inline_blame_timer(window, cx);
12956 } else {
12957 self.show_git_blame_inline = true
12958 }
12959 }
12960
12961 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12962 self.blame.as_ref()
12963 }
12964
12965 pub fn show_git_blame_gutter(&self) -> bool {
12966 self.show_git_blame_gutter
12967 }
12968
12969 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12970 self.show_git_blame_gutter && self.has_blame_entries(cx)
12971 }
12972
12973 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12974 self.show_git_blame_inline
12975 && self.focus_handle.is_focused(window)
12976 && !self.newest_selection_head_on_empty_line(cx)
12977 && self.has_blame_entries(cx)
12978 }
12979
12980 fn has_blame_entries(&self, cx: &App) -> bool {
12981 self.blame()
12982 .map_or(false, |blame| blame.read(cx).has_generated_entries())
12983 }
12984
12985 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12986 let cursor_anchor = self.selections.newest_anchor().head();
12987
12988 let snapshot = self.buffer.read(cx).snapshot(cx);
12989 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12990
12991 snapshot.line_len(buffer_row) == 0
12992 }
12993
12994 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12995 let buffer_and_selection = maybe!({
12996 let selection = self.selections.newest::<Point>(cx);
12997 let selection_range = selection.range();
12998
12999 let multi_buffer = self.buffer().read(cx);
13000 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13001 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13002
13003 let (buffer, range, _) = if selection.reversed {
13004 buffer_ranges.first()
13005 } else {
13006 buffer_ranges.last()
13007 }?;
13008
13009 let selection = text::ToPoint::to_point(&range.start, &buffer).row
13010 ..text::ToPoint::to_point(&range.end, &buffer).row;
13011 Some((
13012 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13013 selection,
13014 ))
13015 });
13016
13017 let Some((buffer, selection)) = buffer_and_selection else {
13018 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13019 };
13020
13021 let Some(project) = self.project.as_ref() else {
13022 return Task::ready(Err(anyhow!("editor does not have project")));
13023 };
13024
13025 project.update(cx, |project, cx| {
13026 project.get_permalink_to_line(&buffer, selection, cx)
13027 })
13028 }
13029
13030 pub fn copy_permalink_to_line(
13031 &mut self,
13032 _: &CopyPermalinkToLine,
13033 window: &mut Window,
13034 cx: &mut Context<Self>,
13035 ) {
13036 let permalink_task = self.get_permalink_to_line(cx);
13037 let workspace = self.workspace();
13038
13039 cx.spawn_in(window, |_, mut cx| async move {
13040 match permalink_task.await {
13041 Ok(permalink) => {
13042 cx.update(|_, cx| {
13043 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13044 })
13045 .ok();
13046 }
13047 Err(err) => {
13048 let message = format!("Failed to copy permalink: {err}");
13049
13050 Err::<(), anyhow::Error>(err).log_err();
13051
13052 if let Some(workspace) = workspace {
13053 workspace
13054 .update_in(&mut cx, |workspace, _, cx| {
13055 struct CopyPermalinkToLine;
13056
13057 workspace.show_toast(
13058 Toast::new(
13059 NotificationId::unique::<CopyPermalinkToLine>(),
13060 message,
13061 ),
13062 cx,
13063 )
13064 })
13065 .ok();
13066 }
13067 }
13068 }
13069 })
13070 .detach();
13071 }
13072
13073 pub fn copy_file_location(
13074 &mut self,
13075 _: &CopyFileLocation,
13076 _: &mut Window,
13077 cx: &mut Context<Self>,
13078 ) {
13079 let selection = self.selections.newest::<Point>(cx).start.row + 1;
13080 if let Some(file) = self.target_file(cx) {
13081 if let Some(path) = file.path().to_str() {
13082 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13083 }
13084 }
13085 }
13086
13087 pub fn open_permalink_to_line(
13088 &mut self,
13089 _: &OpenPermalinkToLine,
13090 window: &mut Window,
13091 cx: &mut Context<Self>,
13092 ) {
13093 let permalink_task = self.get_permalink_to_line(cx);
13094 let workspace = self.workspace();
13095
13096 cx.spawn_in(window, |_, mut cx| async move {
13097 match permalink_task.await {
13098 Ok(permalink) => {
13099 cx.update(|_, cx| {
13100 cx.open_url(permalink.as_ref());
13101 })
13102 .ok();
13103 }
13104 Err(err) => {
13105 let message = format!("Failed to open permalink: {err}");
13106
13107 Err::<(), anyhow::Error>(err).log_err();
13108
13109 if let Some(workspace) = workspace {
13110 workspace
13111 .update(&mut cx, |workspace, cx| {
13112 struct OpenPermalinkToLine;
13113
13114 workspace.show_toast(
13115 Toast::new(
13116 NotificationId::unique::<OpenPermalinkToLine>(),
13117 message,
13118 ),
13119 cx,
13120 )
13121 })
13122 .ok();
13123 }
13124 }
13125 }
13126 })
13127 .detach();
13128 }
13129
13130 pub fn insert_uuid_v4(
13131 &mut self,
13132 _: &InsertUuidV4,
13133 window: &mut Window,
13134 cx: &mut Context<Self>,
13135 ) {
13136 self.insert_uuid(UuidVersion::V4, window, cx);
13137 }
13138
13139 pub fn insert_uuid_v7(
13140 &mut self,
13141 _: &InsertUuidV7,
13142 window: &mut Window,
13143 cx: &mut Context<Self>,
13144 ) {
13145 self.insert_uuid(UuidVersion::V7, window, cx);
13146 }
13147
13148 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13149 self.transact(window, cx, |this, window, cx| {
13150 let edits = this
13151 .selections
13152 .all::<Point>(cx)
13153 .into_iter()
13154 .map(|selection| {
13155 let uuid = match version {
13156 UuidVersion::V4 => uuid::Uuid::new_v4(),
13157 UuidVersion::V7 => uuid::Uuid::now_v7(),
13158 };
13159
13160 (selection.range(), uuid.to_string())
13161 });
13162 this.edit(edits, cx);
13163 this.refresh_inline_completion(true, false, window, cx);
13164 });
13165 }
13166
13167 pub fn open_selections_in_multibuffer(
13168 &mut self,
13169 _: &OpenSelectionsInMultibuffer,
13170 window: &mut Window,
13171 cx: &mut Context<Self>,
13172 ) {
13173 let multibuffer = self.buffer.read(cx);
13174
13175 let Some(buffer) = multibuffer.as_singleton() else {
13176 return;
13177 };
13178
13179 let Some(workspace) = self.workspace() else {
13180 return;
13181 };
13182
13183 let locations = self
13184 .selections
13185 .disjoint_anchors()
13186 .iter()
13187 .map(|range| Location {
13188 buffer: buffer.clone(),
13189 range: range.start.text_anchor..range.end.text_anchor,
13190 })
13191 .collect::<Vec<_>>();
13192
13193 let title = multibuffer.title(cx).to_string();
13194
13195 cx.spawn_in(window, |_, mut cx| async move {
13196 workspace.update_in(&mut cx, |workspace, window, cx| {
13197 Self::open_locations_in_multibuffer(
13198 workspace,
13199 locations,
13200 format!("Selections for '{title}'"),
13201 false,
13202 MultibufferSelectionMode::All,
13203 window,
13204 cx,
13205 );
13206 })
13207 })
13208 .detach();
13209 }
13210
13211 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13212 /// last highlight added will be used.
13213 ///
13214 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13215 pub fn highlight_rows<T: 'static>(
13216 &mut self,
13217 range: Range<Anchor>,
13218 color: Hsla,
13219 should_autoscroll: bool,
13220 cx: &mut Context<Self>,
13221 ) {
13222 let snapshot = self.buffer().read(cx).snapshot(cx);
13223 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13224 let ix = row_highlights.binary_search_by(|highlight| {
13225 Ordering::Equal
13226 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13227 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13228 });
13229
13230 if let Err(mut ix) = ix {
13231 let index = post_inc(&mut self.highlight_order);
13232
13233 // If this range intersects with the preceding highlight, then merge it with
13234 // the preceding highlight. Otherwise insert a new highlight.
13235 let mut merged = false;
13236 if ix > 0 {
13237 let prev_highlight = &mut row_highlights[ix - 1];
13238 if prev_highlight
13239 .range
13240 .end
13241 .cmp(&range.start, &snapshot)
13242 .is_ge()
13243 {
13244 ix -= 1;
13245 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13246 prev_highlight.range.end = range.end;
13247 }
13248 merged = true;
13249 prev_highlight.index = index;
13250 prev_highlight.color = color;
13251 prev_highlight.should_autoscroll = should_autoscroll;
13252 }
13253 }
13254
13255 if !merged {
13256 row_highlights.insert(
13257 ix,
13258 RowHighlight {
13259 range: range.clone(),
13260 index,
13261 color,
13262 should_autoscroll,
13263 },
13264 );
13265 }
13266
13267 // If any of the following highlights intersect with this one, merge them.
13268 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13269 let highlight = &row_highlights[ix];
13270 if next_highlight
13271 .range
13272 .start
13273 .cmp(&highlight.range.end, &snapshot)
13274 .is_le()
13275 {
13276 if next_highlight
13277 .range
13278 .end
13279 .cmp(&highlight.range.end, &snapshot)
13280 .is_gt()
13281 {
13282 row_highlights[ix].range.end = next_highlight.range.end;
13283 }
13284 row_highlights.remove(ix + 1);
13285 } else {
13286 break;
13287 }
13288 }
13289 }
13290 }
13291
13292 /// Remove any highlighted row ranges of the given type that intersect the
13293 /// given ranges.
13294 pub fn remove_highlighted_rows<T: 'static>(
13295 &mut self,
13296 ranges_to_remove: Vec<Range<Anchor>>,
13297 cx: &mut Context<Self>,
13298 ) {
13299 let snapshot = self.buffer().read(cx).snapshot(cx);
13300 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13301 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13302 row_highlights.retain(|highlight| {
13303 while let Some(range_to_remove) = ranges_to_remove.peek() {
13304 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13305 Ordering::Less | Ordering::Equal => {
13306 ranges_to_remove.next();
13307 }
13308 Ordering::Greater => {
13309 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13310 Ordering::Less | Ordering::Equal => {
13311 return false;
13312 }
13313 Ordering::Greater => break,
13314 }
13315 }
13316 }
13317 }
13318
13319 true
13320 })
13321 }
13322
13323 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13324 pub fn clear_row_highlights<T: 'static>(&mut self) {
13325 self.highlighted_rows.remove(&TypeId::of::<T>());
13326 }
13327
13328 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13329 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13330 self.highlighted_rows
13331 .get(&TypeId::of::<T>())
13332 .map_or(&[] as &[_], |vec| vec.as_slice())
13333 .iter()
13334 .map(|highlight| (highlight.range.clone(), highlight.color))
13335 }
13336
13337 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13338 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13339 /// Allows to ignore certain kinds of highlights.
13340 pub fn highlighted_display_rows(
13341 &self,
13342 window: &mut Window,
13343 cx: &mut App,
13344 ) -> BTreeMap<DisplayRow, Hsla> {
13345 let snapshot = self.snapshot(window, cx);
13346 let mut used_highlight_orders = HashMap::default();
13347 self.highlighted_rows
13348 .iter()
13349 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13350 .fold(
13351 BTreeMap::<DisplayRow, Hsla>::new(),
13352 |mut unique_rows, highlight| {
13353 let start = highlight.range.start.to_display_point(&snapshot);
13354 let end = highlight.range.end.to_display_point(&snapshot);
13355 let start_row = start.row().0;
13356 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13357 && end.column() == 0
13358 {
13359 end.row().0.saturating_sub(1)
13360 } else {
13361 end.row().0
13362 };
13363 for row in start_row..=end_row {
13364 let used_index =
13365 used_highlight_orders.entry(row).or_insert(highlight.index);
13366 if highlight.index >= *used_index {
13367 *used_index = highlight.index;
13368 unique_rows.insert(DisplayRow(row), highlight.color);
13369 }
13370 }
13371 unique_rows
13372 },
13373 )
13374 }
13375
13376 pub fn highlighted_display_row_for_autoscroll(
13377 &self,
13378 snapshot: &DisplaySnapshot,
13379 ) -> Option<DisplayRow> {
13380 self.highlighted_rows
13381 .values()
13382 .flat_map(|highlighted_rows| highlighted_rows.iter())
13383 .filter_map(|highlight| {
13384 if highlight.should_autoscroll {
13385 Some(highlight.range.start.to_display_point(snapshot).row())
13386 } else {
13387 None
13388 }
13389 })
13390 .min()
13391 }
13392
13393 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13394 self.highlight_background::<SearchWithinRange>(
13395 ranges,
13396 |colors| colors.editor_document_highlight_read_background,
13397 cx,
13398 )
13399 }
13400
13401 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13402 self.breadcrumb_header = Some(new_header);
13403 }
13404
13405 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13406 self.clear_background_highlights::<SearchWithinRange>(cx);
13407 }
13408
13409 pub fn highlight_background<T: 'static>(
13410 &mut self,
13411 ranges: &[Range<Anchor>],
13412 color_fetcher: fn(&ThemeColors) -> Hsla,
13413 cx: &mut Context<Self>,
13414 ) {
13415 self.background_highlights
13416 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13417 self.scrollbar_marker_state.dirty = true;
13418 cx.notify();
13419 }
13420
13421 pub fn clear_background_highlights<T: 'static>(
13422 &mut self,
13423 cx: &mut Context<Self>,
13424 ) -> Option<BackgroundHighlight> {
13425 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13426 if !text_highlights.1.is_empty() {
13427 self.scrollbar_marker_state.dirty = true;
13428 cx.notify();
13429 }
13430 Some(text_highlights)
13431 }
13432
13433 pub fn highlight_gutter<T: 'static>(
13434 &mut self,
13435 ranges: &[Range<Anchor>],
13436 color_fetcher: fn(&App) -> Hsla,
13437 cx: &mut Context<Self>,
13438 ) {
13439 self.gutter_highlights
13440 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13441 cx.notify();
13442 }
13443
13444 pub fn clear_gutter_highlights<T: 'static>(
13445 &mut self,
13446 cx: &mut Context<Self>,
13447 ) -> Option<GutterHighlight> {
13448 cx.notify();
13449 self.gutter_highlights.remove(&TypeId::of::<T>())
13450 }
13451
13452 #[cfg(feature = "test-support")]
13453 pub fn all_text_background_highlights(
13454 &self,
13455 window: &mut Window,
13456 cx: &mut Context<Self>,
13457 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13458 let snapshot = self.snapshot(window, cx);
13459 let buffer = &snapshot.buffer_snapshot;
13460 let start = buffer.anchor_before(0);
13461 let end = buffer.anchor_after(buffer.len());
13462 let theme = cx.theme().colors();
13463 self.background_highlights_in_range(start..end, &snapshot, theme)
13464 }
13465
13466 #[cfg(feature = "test-support")]
13467 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13468 let snapshot = self.buffer().read(cx).snapshot(cx);
13469
13470 let highlights = self
13471 .background_highlights
13472 .get(&TypeId::of::<items::BufferSearchHighlights>());
13473
13474 if let Some((_color, ranges)) = highlights {
13475 ranges
13476 .iter()
13477 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13478 .collect_vec()
13479 } else {
13480 vec![]
13481 }
13482 }
13483
13484 fn document_highlights_for_position<'a>(
13485 &'a self,
13486 position: Anchor,
13487 buffer: &'a MultiBufferSnapshot,
13488 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13489 let read_highlights = self
13490 .background_highlights
13491 .get(&TypeId::of::<DocumentHighlightRead>())
13492 .map(|h| &h.1);
13493 let write_highlights = self
13494 .background_highlights
13495 .get(&TypeId::of::<DocumentHighlightWrite>())
13496 .map(|h| &h.1);
13497 let left_position = position.bias_left(buffer);
13498 let right_position = position.bias_right(buffer);
13499 read_highlights
13500 .into_iter()
13501 .chain(write_highlights)
13502 .flat_map(move |ranges| {
13503 let start_ix = match ranges.binary_search_by(|probe| {
13504 let cmp = probe.end.cmp(&left_position, buffer);
13505 if cmp.is_ge() {
13506 Ordering::Greater
13507 } else {
13508 Ordering::Less
13509 }
13510 }) {
13511 Ok(i) | Err(i) => i,
13512 };
13513
13514 ranges[start_ix..]
13515 .iter()
13516 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13517 })
13518 }
13519
13520 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13521 self.background_highlights
13522 .get(&TypeId::of::<T>())
13523 .map_or(false, |(_, highlights)| !highlights.is_empty())
13524 }
13525
13526 pub fn background_highlights_in_range(
13527 &self,
13528 search_range: Range<Anchor>,
13529 display_snapshot: &DisplaySnapshot,
13530 theme: &ThemeColors,
13531 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13532 let mut results = Vec::new();
13533 for (color_fetcher, ranges) in self.background_highlights.values() {
13534 let color = color_fetcher(theme);
13535 let start_ix = match ranges.binary_search_by(|probe| {
13536 let cmp = probe
13537 .end
13538 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13539 if cmp.is_gt() {
13540 Ordering::Greater
13541 } else {
13542 Ordering::Less
13543 }
13544 }) {
13545 Ok(i) | Err(i) => i,
13546 };
13547 for range in &ranges[start_ix..] {
13548 if range
13549 .start
13550 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13551 .is_ge()
13552 {
13553 break;
13554 }
13555
13556 let start = range.start.to_display_point(display_snapshot);
13557 let end = range.end.to_display_point(display_snapshot);
13558 results.push((start..end, color))
13559 }
13560 }
13561 results
13562 }
13563
13564 pub fn background_highlight_row_ranges<T: 'static>(
13565 &self,
13566 search_range: Range<Anchor>,
13567 display_snapshot: &DisplaySnapshot,
13568 count: usize,
13569 ) -> Vec<RangeInclusive<DisplayPoint>> {
13570 let mut results = Vec::new();
13571 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13572 return vec![];
13573 };
13574
13575 let start_ix = match ranges.binary_search_by(|probe| {
13576 let cmp = probe
13577 .end
13578 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13579 if cmp.is_gt() {
13580 Ordering::Greater
13581 } else {
13582 Ordering::Less
13583 }
13584 }) {
13585 Ok(i) | Err(i) => i,
13586 };
13587 let mut push_region = |start: Option<Point>, end: Option<Point>| {
13588 if let (Some(start_display), Some(end_display)) = (start, end) {
13589 results.push(
13590 start_display.to_display_point(display_snapshot)
13591 ..=end_display.to_display_point(display_snapshot),
13592 );
13593 }
13594 };
13595 let mut start_row: Option<Point> = None;
13596 let mut end_row: Option<Point> = None;
13597 if ranges.len() > count {
13598 return Vec::new();
13599 }
13600 for range in &ranges[start_ix..] {
13601 if range
13602 .start
13603 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13604 .is_ge()
13605 {
13606 break;
13607 }
13608 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13609 if let Some(current_row) = &end_row {
13610 if end.row == current_row.row {
13611 continue;
13612 }
13613 }
13614 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13615 if start_row.is_none() {
13616 assert_eq!(end_row, None);
13617 start_row = Some(start);
13618 end_row = Some(end);
13619 continue;
13620 }
13621 if let Some(current_end) = end_row.as_mut() {
13622 if start.row > current_end.row + 1 {
13623 push_region(start_row, end_row);
13624 start_row = Some(start);
13625 end_row = Some(end);
13626 } else {
13627 // Merge two hunks.
13628 *current_end = end;
13629 }
13630 } else {
13631 unreachable!();
13632 }
13633 }
13634 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13635 push_region(start_row, end_row);
13636 results
13637 }
13638
13639 pub fn gutter_highlights_in_range(
13640 &self,
13641 search_range: Range<Anchor>,
13642 display_snapshot: &DisplaySnapshot,
13643 cx: &App,
13644 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13645 let mut results = Vec::new();
13646 for (color_fetcher, ranges) in self.gutter_highlights.values() {
13647 let color = color_fetcher(cx);
13648 let start_ix = match ranges.binary_search_by(|probe| {
13649 let cmp = probe
13650 .end
13651 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13652 if cmp.is_gt() {
13653 Ordering::Greater
13654 } else {
13655 Ordering::Less
13656 }
13657 }) {
13658 Ok(i) | Err(i) => i,
13659 };
13660 for range in &ranges[start_ix..] {
13661 if range
13662 .start
13663 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13664 .is_ge()
13665 {
13666 break;
13667 }
13668
13669 let start = range.start.to_display_point(display_snapshot);
13670 let end = range.end.to_display_point(display_snapshot);
13671 results.push((start..end, color))
13672 }
13673 }
13674 results
13675 }
13676
13677 /// Get the text ranges corresponding to the redaction query
13678 pub fn redacted_ranges(
13679 &self,
13680 search_range: Range<Anchor>,
13681 display_snapshot: &DisplaySnapshot,
13682 cx: &App,
13683 ) -> Vec<Range<DisplayPoint>> {
13684 display_snapshot
13685 .buffer_snapshot
13686 .redacted_ranges(search_range, |file| {
13687 if let Some(file) = file {
13688 file.is_private()
13689 && EditorSettings::get(
13690 Some(SettingsLocation {
13691 worktree_id: file.worktree_id(cx),
13692 path: file.path().as_ref(),
13693 }),
13694 cx,
13695 )
13696 .redact_private_values
13697 } else {
13698 false
13699 }
13700 })
13701 .map(|range| {
13702 range.start.to_display_point(display_snapshot)
13703 ..range.end.to_display_point(display_snapshot)
13704 })
13705 .collect()
13706 }
13707
13708 pub fn highlight_text<T: 'static>(
13709 &mut self,
13710 ranges: Vec<Range<Anchor>>,
13711 style: HighlightStyle,
13712 cx: &mut Context<Self>,
13713 ) {
13714 self.display_map.update(cx, |map, _| {
13715 map.highlight_text(TypeId::of::<T>(), ranges, style)
13716 });
13717 cx.notify();
13718 }
13719
13720 pub(crate) fn highlight_inlays<T: 'static>(
13721 &mut self,
13722 highlights: Vec<InlayHighlight>,
13723 style: HighlightStyle,
13724 cx: &mut Context<Self>,
13725 ) {
13726 self.display_map.update(cx, |map, _| {
13727 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13728 });
13729 cx.notify();
13730 }
13731
13732 pub fn text_highlights<'a, T: 'static>(
13733 &'a self,
13734 cx: &'a App,
13735 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13736 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13737 }
13738
13739 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13740 let cleared = self
13741 .display_map
13742 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13743 if cleared {
13744 cx.notify();
13745 }
13746 }
13747
13748 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13749 (self.read_only(cx) || self.blink_manager.read(cx).visible())
13750 && self.focus_handle.is_focused(window)
13751 }
13752
13753 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13754 self.show_cursor_when_unfocused = is_enabled;
13755 cx.notify();
13756 }
13757
13758 pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13759 self.project
13760 .as_ref()
13761 .map(|project| project.read(cx).lsp_store())
13762 }
13763
13764 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13765 cx.notify();
13766 }
13767
13768 fn on_buffer_event(
13769 &mut self,
13770 multibuffer: &Entity<MultiBuffer>,
13771 event: &multi_buffer::Event,
13772 window: &mut Window,
13773 cx: &mut Context<Self>,
13774 ) {
13775 match event {
13776 multi_buffer::Event::Edited {
13777 singleton_buffer_edited,
13778 edited_buffer: buffer_edited,
13779 } => {
13780 self.scrollbar_marker_state.dirty = true;
13781 self.active_indent_guides_state.dirty = true;
13782 self.refresh_active_diagnostics(cx);
13783 self.refresh_code_actions(window, cx);
13784 if self.has_active_inline_completion() {
13785 self.update_visible_inline_completion(window, cx);
13786 }
13787 if let Some(buffer) = buffer_edited {
13788 let buffer_id = buffer.read(cx).remote_id();
13789 if !self.registered_buffers.contains_key(&buffer_id) {
13790 if let Some(lsp_store) = self.lsp_store(cx) {
13791 lsp_store.update(cx, |lsp_store, cx| {
13792 self.registered_buffers.insert(
13793 buffer_id,
13794 lsp_store.register_buffer_with_language_servers(&buffer, cx),
13795 );
13796 })
13797 }
13798 }
13799 }
13800 cx.emit(EditorEvent::BufferEdited);
13801 cx.emit(SearchEvent::MatchesInvalidated);
13802 if *singleton_buffer_edited {
13803 if let Some(project) = &self.project {
13804 let project = project.read(cx);
13805 #[allow(clippy::mutable_key_type)]
13806 let languages_affected = multibuffer
13807 .read(cx)
13808 .all_buffers()
13809 .into_iter()
13810 .filter_map(|buffer| {
13811 let buffer = buffer.read(cx);
13812 let language = buffer.language()?;
13813 if project.is_local()
13814 && project
13815 .language_servers_for_local_buffer(buffer, cx)
13816 .count()
13817 == 0
13818 {
13819 None
13820 } else {
13821 Some(language)
13822 }
13823 })
13824 .cloned()
13825 .collect::<HashSet<_>>();
13826 if !languages_affected.is_empty() {
13827 self.refresh_inlay_hints(
13828 InlayHintRefreshReason::BufferEdited(languages_affected),
13829 cx,
13830 );
13831 }
13832 }
13833 }
13834
13835 let Some(project) = &self.project else { return };
13836 let (telemetry, is_via_ssh) = {
13837 let project = project.read(cx);
13838 let telemetry = project.client().telemetry().clone();
13839 let is_via_ssh = project.is_via_ssh();
13840 (telemetry, is_via_ssh)
13841 };
13842 refresh_linked_ranges(self, window, cx);
13843 telemetry.log_edit_event("editor", is_via_ssh);
13844 }
13845 multi_buffer::Event::ExcerptsAdded {
13846 buffer,
13847 predecessor,
13848 excerpts,
13849 } => {
13850 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13851 let buffer_id = buffer.read(cx).remote_id();
13852 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
13853 if let Some(project) = &self.project {
13854 get_uncommitted_diff_for_buffer(
13855 project,
13856 [buffer.clone()],
13857 self.buffer.clone(),
13858 cx,
13859 );
13860 }
13861 }
13862 cx.emit(EditorEvent::ExcerptsAdded {
13863 buffer: buffer.clone(),
13864 predecessor: *predecessor,
13865 excerpts: excerpts.clone(),
13866 });
13867 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13868 }
13869 multi_buffer::Event::ExcerptsRemoved { ids } => {
13870 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13871 let buffer = self.buffer.read(cx);
13872 self.registered_buffers
13873 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13874 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13875 }
13876 multi_buffer::Event::ExcerptsEdited { ids } => {
13877 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13878 }
13879 multi_buffer::Event::ExcerptsExpanded { ids } => {
13880 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13881 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13882 }
13883 multi_buffer::Event::Reparsed(buffer_id) => {
13884 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13885
13886 cx.emit(EditorEvent::Reparsed(*buffer_id));
13887 }
13888 multi_buffer::Event::DiffHunksToggled => {
13889 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13890 }
13891 multi_buffer::Event::LanguageChanged(buffer_id) => {
13892 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13893 cx.emit(EditorEvent::Reparsed(*buffer_id));
13894 cx.notify();
13895 }
13896 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13897 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13898 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13899 cx.emit(EditorEvent::TitleChanged)
13900 }
13901 // multi_buffer::Event::DiffBaseChanged => {
13902 // self.scrollbar_marker_state.dirty = true;
13903 // cx.emit(EditorEvent::DiffBaseChanged);
13904 // cx.notify();
13905 // }
13906 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13907 multi_buffer::Event::DiagnosticsUpdated => {
13908 self.refresh_active_diagnostics(cx);
13909 self.scrollbar_marker_state.dirty = true;
13910 cx.notify();
13911 }
13912 _ => {}
13913 };
13914 }
13915
13916 fn on_display_map_changed(
13917 &mut self,
13918 _: Entity<DisplayMap>,
13919 _: &mut Window,
13920 cx: &mut Context<Self>,
13921 ) {
13922 cx.notify();
13923 }
13924
13925 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13926 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13927 self.refresh_inline_completion(true, false, window, cx);
13928 self.refresh_inlay_hints(
13929 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13930 self.selections.newest_anchor().head(),
13931 &self.buffer.read(cx).snapshot(cx),
13932 cx,
13933 )),
13934 cx,
13935 );
13936
13937 let old_cursor_shape = self.cursor_shape;
13938
13939 {
13940 let editor_settings = EditorSettings::get_global(cx);
13941 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13942 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13943 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13944 }
13945
13946 if old_cursor_shape != self.cursor_shape {
13947 cx.emit(EditorEvent::CursorShapeChanged);
13948 }
13949
13950 let project_settings = ProjectSettings::get_global(cx);
13951 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13952
13953 if self.mode == EditorMode::Full {
13954 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13955 if self.git_blame_inline_enabled != inline_blame_enabled {
13956 self.toggle_git_blame_inline_internal(false, window, cx);
13957 }
13958 }
13959
13960 cx.notify();
13961 }
13962
13963 pub fn set_searchable(&mut self, searchable: bool) {
13964 self.searchable = searchable;
13965 }
13966
13967 pub fn searchable(&self) -> bool {
13968 self.searchable
13969 }
13970
13971 fn open_proposed_changes_editor(
13972 &mut self,
13973 _: &OpenProposedChangesEditor,
13974 window: &mut Window,
13975 cx: &mut Context<Self>,
13976 ) {
13977 let Some(workspace) = self.workspace() else {
13978 cx.propagate();
13979 return;
13980 };
13981
13982 let selections = self.selections.all::<usize>(cx);
13983 let multi_buffer = self.buffer.read(cx);
13984 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13985 let mut new_selections_by_buffer = HashMap::default();
13986 for selection in selections {
13987 for (buffer, range, _) in
13988 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13989 {
13990 let mut range = range.to_point(buffer);
13991 range.start.column = 0;
13992 range.end.column = buffer.line_len(range.end.row);
13993 new_selections_by_buffer
13994 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13995 .or_insert(Vec::new())
13996 .push(range)
13997 }
13998 }
13999
14000 let proposed_changes_buffers = new_selections_by_buffer
14001 .into_iter()
14002 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14003 .collect::<Vec<_>>();
14004 let proposed_changes_editor = cx.new(|cx| {
14005 ProposedChangesEditor::new(
14006 "Proposed changes",
14007 proposed_changes_buffers,
14008 self.project.clone(),
14009 window,
14010 cx,
14011 )
14012 });
14013
14014 window.defer(cx, move |window, cx| {
14015 workspace.update(cx, |workspace, cx| {
14016 workspace.active_pane().update(cx, |pane, cx| {
14017 pane.add_item(
14018 Box::new(proposed_changes_editor),
14019 true,
14020 true,
14021 None,
14022 window,
14023 cx,
14024 );
14025 });
14026 });
14027 });
14028 }
14029
14030 pub fn open_excerpts_in_split(
14031 &mut self,
14032 _: &OpenExcerptsSplit,
14033 window: &mut Window,
14034 cx: &mut Context<Self>,
14035 ) {
14036 self.open_excerpts_common(None, true, window, cx)
14037 }
14038
14039 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14040 self.open_excerpts_common(None, false, window, cx)
14041 }
14042
14043 fn open_excerpts_common(
14044 &mut self,
14045 jump_data: Option<JumpData>,
14046 split: bool,
14047 window: &mut Window,
14048 cx: &mut Context<Self>,
14049 ) {
14050 let Some(workspace) = self.workspace() else {
14051 cx.propagate();
14052 return;
14053 };
14054
14055 if self.buffer.read(cx).is_singleton() {
14056 cx.propagate();
14057 return;
14058 }
14059
14060 let mut new_selections_by_buffer = HashMap::default();
14061 match &jump_data {
14062 Some(JumpData::MultiBufferPoint {
14063 excerpt_id,
14064 position,
14065 anchor,
14066 line_offset_from_top,
14067 }) => {
14068 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14069 if let Some(buffer) = multi_buffer_snapshot
14070 .buffer_id_for_excerpt(*excerpt_id)
14071 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14072 {
14073 let buffer_snapshot = buffer.read(cx).snapshot();
14074 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14075 language::ToPoint::to_point(anchor, &buffer_snapshot)
14076 } else {
14077 buffer_snapshot.clip_point(*position, Bias::Left)
14078 };
14079 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14080 new_selections_by_buffer.insert(
14081 buffer,
14082 (
14083 vec![jump_to_offset..jump_to_offset],
14084 Some(*line_offset_from_top),
14085 ),
14086 );
14087 }
14088 }
14089 Some(JumpData::MultiBufferRow {
14090 row,
14091 line_offset_from_top,
14092 }) => {
14093 let point = MultiBufferPoint::new(row.0, 0);
14094 if let Some((buffer, buffer_point, _)) =
14095 self.buffer.read(cx).point_to_buffer_point(point, cx)
14096 {
14097 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14098 new_selections_by_buffer
14099 .entry(buffer)
14100 .or_insert((Vec::new(), Some(*line_offset_from_top)))
14101 .0
14102 .push(buffer_offset..buffer_offset)
14103 }
14104 }
14105 None => {
14106 let selections = self.selections.all::<usize>(cx);
14107 let multi_buffer = self.buffer.read(cx);
14108 for selection in selections {
14109 for (buffer, mut range, _) in multi_buffer
14110 .snapshot(cx)
14111 .range_to_buffer_ranges(selection.range())
14112 {
14113 // When editing branch buffers, jump to the corresponding location
14114 // in their base buffer.
14115 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14116 let buffer = buffer_handle.read(cx);
14117 if let Some(base_buffer) = buffer.base_buffer() {
14118 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14119 buffer_handle = base_buffer;
14120 }
14121
14122 if selection.reversed {
14123 mem::swap(&mut range.start, &mut range.end);
14124 }
14125 new_selections_by_buffer
14126 .entry(buffer_handle)
14127 .or_insert((Vec::new(), None))
14128 .0
14129 .push(range)
14130 }
14131 }
14132 }
14133 }
14134
14135 if new_selections_by_buffer.is_empty() {
14136 return;
14137 }
14138
14139 // We defer the pane interaction because we ourselves are a workspace item
14140 // and activating a new item causes the pane to call a method on us reentrantly,
14141 // which panics if we're on the stack.
14142 window.defer(cx, move |window, cx| {
14143 workspace.update(cx, |workspace, cx| {
14144 let pane = if split {
14145 workspace.adjacent_pane(window, cx)
14146 } else {
14147 workspace.active_pane().clone()
14148 };
14149
14150 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14151 let editor = buffer
14152 .read(cx)
14153 .file()
14154 .is_none()
14155 .then(|| {
14156 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14157 // so `workspace.open_project_item` will never find them, always opening a new editor.
14158 // Instead, we try to activate the existing editor in the pane first.
14159 let (editor, pane_item_index) =
14160 pane.read(cx).items().enumerate().find_map(|(i, item)| {
14161 let editor = item.downcast::<Editor>()?;
14162 let singleton_buffer =
14163 editor.read(cx).buffer().read(cx).as_singleton()?;
14164 if singleton_buffer == buffer {
14165 Some((editor, i))
14166 } else {
14167 None
14168 }
14169 })?;
14170 pane.update(cx, |pane, cx| {
14171 pane.activate_item(pane_item_index, true, true, window, cx)
14172 });
14173 Some(editor)
14174 })
14175 .flatten()
14176 .unwrap_or_else(|| {
14177 workspace.open_project_item::<Self>(
14178 pane.clone(),
14179 buffer,
14180 true,
14181 true,
14182 window,
14183 cx,
14184 )
14185 });
14186
14187 editor.update(cx, |editor, cx| {
14188 let autoscroll = match scroll_offset {
14189 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14190 None => Autoscroll::newest(),
14191 };
14192 let nav_history = editor.nav_history.take();
14193 editor.change_selections(Some(autoscroll), window, cx, |s| {
14194 s.select_ranges(ranges);
14195 });
14196 editor.nav_history = nav_history;
14197 });
14198 }
14199 })
14200 });
14201 }
14202
14203 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14204 let snapshot = self.buffer.read(cx).read(cx);
14205 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14206 Some(
14207 ranges
14208 .iter()
14209 .map(move |range| {
14210 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14211 })
14212 .collect(),
14213 )
14214 }
14215
14216 fn selection_replacement_ranges(
14217 &self,
14218 range: Range<OffsetUtf16>,
14219 cx: &mut App,
14220 ) -> Vec<Range<OffsetUtf16>> {
14221 let selections = self.selections.all::<OffsetUtf16>(cx);
14222 let newest_selection = selections
14223 .iter()
14224 .max_by_key(|selection| selection.id)
14225 .unwrap();
14226 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14227 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14228 let snapshot = self.buffer.read(cx).read(cx);
14229 selections
14230 .into_iter()
14231 .map(|mut selection| {
14232 selection.start.0 =
14233 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14234 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14235 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14236 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14237 })
14238 .collect()
14239 }
14240
14241 fn report_editor_event(
14242 &self,
14243 event_type: &'static str,
14244 file_extension: Option<String>,
14245 cx: &App,
14246 ) {
14247 if cfg!(any(test, feature = "test-support")) {
14248 return;
14249 }
14250
14251 let Some(project) = &self.project else { return };
14252
14253 // If None, we are in a file without an extension
14254 let file = self
14255 .buffer
14256 .read(cx)
14257 .as_singleton()
14258 .and_then(|b| b.read(cx).file());
14259 let file_extension = file_extension.or(file
14260 .as_ref()
14261 .and_then(|file| Path::new(file.file_name(cx)).extension())
14262 .and_then(|e| e.to_str())
14263 .map(|a| a.to_string()));
14264
14265 let vim_mode = cx
14266 .global::<SettingsStore>()
14267 .raw_user_settings()
14268 .get("vim_mode")
14269 == Some(&serde_json::Value::Bool(true));
14270
14271 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14272 let copilot_enabled = edit_predictions_provider
14273 == language::language_settings::EditPredictionProvider::Copilot;
14274 let copilot_enabled_for_language = self
14275 .buffer
14276 .read(cx)
14277 .settings_at(0, cx)
14278 .show_edit_predictions;
14279
14280 let project = project.read(cx);
14281 telemetry::event!(
14282 event_type,
14283 file_extension,
14284 vim_mode,
14285 copilot_enabled,
14286 copilot_enabled_for_language,
14287 edit_predictions_provider,
14288 is_via_ssh = project.is_via_ssh(),
14289 );
14290 }
14291
14292 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14293 /// with each line being an array of {text, highlight} objects.
14294 fn copy_highlight_json(
14295 &mut self,
14296 _: &CopyHighlightJson,
14297 window: &mut Window,
14298 cx: &mut Context<Self>,
14299 ) {
14300 #[derive(Serialize)]
14301 struct Chunk<'a> {
14302 text: String,
14303 highlight: Option<&'a str>,
14304 }
14305
14306 let snapshot = self.buffer.read(cx).snapshot(cx);
14307 let range = self
14308 .selected_text_range(false, window, cx)
14309 .and_then(|selection| {
14310 if selection.range.is_empty() {
14311 None
14312 } else {
14313 Some(selection.range)
14314 }
14315 })
14316 .unwrap_or_else(|| 0..snapshot.len());
14317
14318 let chunks = snapshot.chunks(range, true);
14319 let mut lines = Vec::new();
14320 let mut line: VecDeque<Chunk> = VecDeque::new();
14321
14322 let Some(style) = self.style.as_ref() else {
14323 return;
14324 };
14325
14326 for chunk in chunks {
14327 let highlight = chunk
14328 .syntax_highlight_id
14329 .and_then(|id| id.name(&style.syntax));
14330 let mut chunk_lines = chunk.text.split('\n').peekable();
14331 while let Some(text) = chunk_lines.next() {
14332 let mut merged_with_last_token = false;
14333 if let Some(last_token) = line.back_mut() {
14334 if last_token.highlight == highlight {
14335 last_token.text.push_str(text);
14336 merged_with_last_token = true;
14337 }
14338 }
14339
14340 if !merged_with_last_token {
14341 line.push_back(Chunk {
14342 text: text.into(),
14343 highlight,
14344 });
14345 }
14346
14347 if chunk_lines.peek().is_some() {
14348 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14349 line.pop_front();
14350 }
14351 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14352 line.pop_back();
14353 }
14354
14355 lines.push(mem::take(&mut line));
14356 }
14357 }
14358 }
14359
14360 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14361 return;
14362 };
14363 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14364 }
14365
14366 pub fn open_context_menu(
14367 &mut self,
14368 _: &OpenContextMenu,
14369 window: &mut Window,
14370 cx: &mut Context<Self>,
14371 ) {
14372 self.request_autoscroll(Autoscroll::newest(), cx);
14373 let position = self.selections.newest_display(cx).start;
14374 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14375 }
14376
14377 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14378 &self.inlay_hint_cache
14379 }
14380
14381 pub fn replay_insert_event(
14382 &mut self,
14383 text: &str,
14384 relative_utf16_range: Option<Range<isize>>,
14385 window: &mut Window,
14386 cx: &mut Context<Self>,
14387 ) {
14388 if !self.input_enabled {
14389 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14390 return;
14391 }
14392 if let Some(relative_utf16_range) = relative_utf16_range {
14393 let selections = self.selections.all::<OffsetUtf16>(cx);
14394 self.change_selections(None, window, cx, |s| {
14395 let new_ranges = selections.into_iter().map(|range| {
14396 let start = OffsetUtf16(
14397 range
14398 .head()
14399 .0
14400 .saturating_add_signed(relative_utf16_range.start),
14401 );
14402 let end = OffsetUtf16(
14403 range
14404 .head()
14405 .0
14406 .saturating_add_signed(relative_utf16_range.end),
14407 );
14408 start..end
14409 });
14410 s.select_ranges(new_ranges);
14411 });
14412 }
14413
14414 self.handle_input(text, window, cx);
14415 }
14416
14417 pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14418 let Some(provider) = self.semantics_provider.as_ref() else {
14419 return false;
14420 };
14421
14422 let mut supports = false;
14423 self.buffer().read(cx).for_each_buffer(|buffer| {
14424 supports |= provider.supports_inlay_hints(buffer, cx);
14425 });
14426 supports
14427 }
14428
14429 pub fn is_focused(&self, window: &Window) -> bool {
14430 self.focus_handle.is_focused(window)
14431 }
14432
14433 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14434 cx.emit(EditorEvent::Focused);
14435
14436 if let Some(descendant) = self
14437 .last_focused_descendant
14438 .take()
14439 .and_then(|descendant| descendant.upgrade())
14440 {
14441 window.focus(&descendant);
14442 } else {
14443 if let Some(blame) = self.blame.as_ref() {
14444 blame.update(cx, GitBlame::focus)
14445 }
14446
14447 self.blink_manager.update(cx, BlinkManager::enable);
14448 self.show_cursor_names(window, cx);
14449 self.buffer.update(cx, |buffer, cx| {
14450 buffer.finalize_last_transaction(cx);
14451 if self.leader_peer_id.is_none() {
14452 buffer.set_active_selections(
14453 &self.selections.disjoint_anchors(),
14454 self.selections.line_mode,
14455 self.cursor_shape,
14456 cx,
14457 );
14458 }
14459 });
14460 }
14461 }
14462
14463 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14464 cx.emit(EditorEvent::FocusedIn)
14465 }
14466
14467 fn handle_focus_out(
14468 &mut self,
14469 event: FocusOutEvent,
14470 _window: &mut Window,
14471 _cx: &mut Context<Self>,
14472 ) {
14473 if event.blurred != self.focus_handle {
14474 self.last_focused_descendant = Some(event.blurred);
14475 }
14476 }
14477
14478 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14479 self.blink_manager.update(cx, BlinkManager::disable);
14480 self.buffer
14481 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14482
14483 if let Some(blame) = self.blame.as_ref() {
14484 blame.update(cx, GitBlame::blur)
14485 }
14486 if !self.hover_state.focused(window, cx) {
14487 hide_hover(self, cx);
14488 }
14489
14490 self.hide_context_menu(window, cx);
14491 cx.emit(EditorEvent::Blurred);
14492 cx.notify();
14493 }
14494
14495 pub fn register_action<A: Action>(
14496 &mut self,
14497 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14498 ) -> Subscription {
14499 let id = self.next_editor_action_id.post_inc();
14500 let listener = Arc::new(listener);
14501 self.editor_actions.borrow_mut().insert(
14502 id,
14503 Box::new(move |window, _| {
14504 let listener = listener.clone();
14505 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14506 let action = action.downcast_ref().unwrap();
14507 if phase == DispatchPhase::Bubble {
14508 listener(action, window, cx)
14509 }
14510 })
14511 }),
14512 );
14513
14514 let editor_actions = self.editor_actions.clone();
14515 Subscription::new(move || {
14516 editor_actions.borrow_mut().remove(&id);
14517 })
14518 }
14519
14520 pub fn file_header_size(&self) -> u32 {
14521 FILE_HEADER_HEIGHT
14522 }
14523
14524 pub fn revert(
14525 &mut self,
14526 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14527 window: &mut Window,
14528 cx: &mut Context<Self>,
14529 ) {
14530 self.buffer().update(cx, |multi_buffer, cx| {
14531 for (buffer_id, changes) in revert_changes {
14532 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14533 buffer.update(cx, |buffer, cx| {
14534 buffer.edit(
14535 changes.into_iter().map(|(range, text)| {
14536 (range, text.to_string().map(Arc::<str>::from))
14537 }),
14538 None,
14539 cx,
14540 );
14541 });
14542 }
14543 }
14544 });
14545 self.change_selections(None, window, cx, |selections| selections.refresh());
14546 }
14547
14548 pub fn to_pixel_point(
14549 &self,
14550 source: multi_buffer::Anchor,
14551 editor_snapshot: &EditorSnapshot,
14552 window: &mut Window,
14553 ) -> Option<gpui::Point<Pixels>> {
14554 let source_point = source.to_display_point(editor_snapshot);
14555 self.display_to_pixel_point(source_point, editor_snapshot, window)
14556 }
14557
14558 pub fn display_to_pixel_point(
14559 &self,
14560 source: DisplayPoint,
14561 editor_snapshot: &EditorSnapshot,
14562 window: &mut Window,
14563 ) -> Option<gpui::Point<Pixels>> {
14564 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14565 let text_layout_details = self.text_layout_details(window);
14566 let scroll_top = text_layout_details
14567 .scroll_anchor
14568 .scroll_position(editor_snapshot)
14569 .y;
14570
14571 if source.row().as_f32() < scroll_top.floor() {
14572 return None;
14573 }
14574 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14575 let source_y = line_height * (source.row().as_f32() - scroll_top);
14576 Some(gpui::Point::new(source_x, source_y))
14577 }
14578
14579 pub fn has_visible_completions_menu(&self) -> bool {
14580 !self.previewing_inline_completion
14581 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14582 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14583 })
14584 }
14585
14586 pub fn register_addon<T: Addon>(&mut self, instance: T) {
14587 self.addons
14588 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14589 }
14590
14591 pub fn unregister_addon<T: Addon>(&mut self) {
14592 self.addons.remove(&std::any::TypeId::of::<T>());
14593 }
14594
14595 pub fn addon<T: Addon>(&self) -> Option<&T> {
14596 let type_id = std::any::TypeId::of::<T>();
14597 self.addons
14598 .get(&type_id)
14599 .and_then(|item| item.to_any().downcast_ref::<T>())
14600 }
14601
14602 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14603 let text_layout_details = self.text_layout_details(window);
14604 let style = &text_layout_details.editor_style;
14605 let font_id = window.text_system().resolve_font(&style.text.font());
14606 let font_size = style.text.font_size.to_pixels(window.rem_size());
14607 let line_height = style.text.line_height_in_pixels(window.rem_size());
14608 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14609
14610 gpui::Size::new(em_width, line_height)
14611 }
14612}
14613
14614fn get_uncommitted_diff_for_buffer(
14615 project: &Entity<Project>,
14616 buffers: impl IntoIterator<Item = Entity<Buffer>>,
14617 buffer: Entity<MultiBuffer>,
14618 cx: &mut App,
14619) {
14620 let mut tasks = Vec::new();
14621 project.update(cx, |project, cx| {
14622 for buffer in buffers {
14623 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14624 }
14625 });
14626 cx.spawn(|mut cx| async move {
14627 let diffs = futures::future::join_all(tasks).await;
14628 buffer
14629 .update(&mut cx, |buffer, cx| {
14630 for diff in diffs.into_iter().flatten() {
14631 buffer.add_diff(diff, cx);
14632 }
14633 })
14634 .ok();
14635 })
14636 .detach();
14637}
14638
14639fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14640 let tab_size = tab_size.get() as usize;
14641 let mut width = offset;
14642
14643 for ch in text.chars() {
14644 width += if ch == '\t' {
14645 tab_size - (width % tab_size)
14646 } else {
14647 1
14648 };
14649 }
14650
14651 width - offset
14652}
14653
14654#[cfg(test)]
14655mod tests {
14656 use super::*;
14657
14658 #[test]
14659 fn test_string_size_with_expanded_tabs() {
14660 let nz = |val| NonZeroU32::new(val).unwrap();
14661 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14662 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14663 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14664 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14665 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14666 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14667 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14668 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14669 }
14670}
14671
14672/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14673struct WordBreakingTokenizer<'a> {
14674 input: &'a str,
14675}
14676
14677impl<'a> WordBreakingTokenizer<'a> {
14678 fn new(input: &'a str) -> Self {
14679 Self { input }
14680 }
14681}
14682
14683fn is_char_ideographic(ch: char) -> bool {
14684 use unicode_script::Script::*;
14685 use unicode_script::UnicodeScript;
14686 matches!(ch.script(), Han | Tangut | Yi)
14687}
14688
14689fn is_grapheme_ideographic(text: &str) -> bool {
14690 text.chars().any(is_char_ideographic)
14691}
14692
14693fn is_grapheme_whitespace(text: &str) -> bool {
14694 text.chars().any(|x| x.is_whitespace())
14695}
14696
14697fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14698 text.chars().next().map_or(false, |ch| {
14699 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14700 })
14701}
14702
14703#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14704struct WordBreakToken<'a> {
14705 token: &'a str,
14706 grapheme_len: usize,
14707 is_whitespace: bool,
14708}
14709
14710impl<'a> Iterator for WordBreakingTokenizer<'a> {
14711 /// Yields a span, the count of graphemes in the token, and whether it was
14712 /// whitespace. Note that it also breaks at word boundaries.
14713 type Item = WordBreakToken<'a>;
14714
14715 fn next(&mut self) -> Option<Self::Item> {
14716 use unicode_segmentation::UnicodeSegmentation;
14717 if self.input.is_empty() {
14718 return None;
14719 }
14720
14721 let mut iter = self.input.graphemes(true).peekable();
14722 let mut offset = 0;
14723 let mut graphemes = 0;
14724 if let Some(first_grapheme) = iter.next() {
14725 let is_whitespace = is_grapheme_whitespace(first_grapheme);
14726 offset += first_grapheme.len();
14727 graphemes += 1;
14728 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14729 if let Some(grapheme) = iter.peek().copied() {
14730 if should_stay_with_preceding_ideograph(grapheme) {
14731 offset += grapheme.len();
14732 graphemes += 1;
14733 }
14734 }
14735 } else {
14736 let mut words = self.input[offset..].split_word_bound_indices().peekable();
14737 let mut next_word_bound = words.peek().copied();
14738 if next_word_bound.map_or(false, |(i, _)| i == 0) {
14739 next_word_bound = words.next();
14740 }
14741 while let Some(grapheme) = iter.peek().copied() {
14742 if next_word_bound.map_or(false, |(i, _)| i == offset) {
14743 break;
14744 };
14745 if is_grapheme_whitespace(grapheme) != is_whitespace {
14746 break;
14747 };
14748 offset += grapheme.len();
14749 graphemes += 1;
14750 iter.next();
14751 }
14752 }
14753 let token = &self.input[..offset];
14754 self.input = &self.input[offset..];
14755 if is_whitespace {
14756 Some(WordBreakToken {
14757 token: " ",
14758 grapheme_len: 1,
14759 is_whitespace: true,
14760 })
14761 } else {
14762 Some(WordBreakToken {
14763 token,
14764 grapheme_len: graphemes,
14765 is_whitespace: false,
14766 })
14767 }
14768 } else {
14769 None
14770 }
14771 }
14772}
14773
14774#[test]
14775fn test_word_breaking_tokenizer() {
14776 let tests: &[(&str, &[(&str, usize, bool)])] = &[
14777 ("", &[]),
14778 (" ", &[(" ", 1, true)]),
14779 ("Ʒ", &[("Ʒ", 1, false)]),
14780 ("Ǽ", &[("Ǽ", 1, false)]),
14781 ("⋑", &[("⋑", 1, false)]),
14782 ("⋑⋑", &[("⋑⋑", 2, false)]),
14783 (
14784 "原理,进而",
14785 &[
14786 ("原", 1, false),
14787 ("理,", 2, false),
14788 ("进", 1, false),
14789 ("而", 1, false),
14790 ],
14791 ),
14792 (
14793 "hello world",
14794 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14795 ),
14796 (
14797 "hello, world",
14798 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14799 ),
14800 (
14801 " hello world",
14802 &[
14803 (" ", 1, true),
14804 ("hello", 5, false),
14805 (" ", 1, true),
14806 ("world", 5, false),
14807 ],
14808 ),
14809 (
14810 "这是什么 \n 钢笔",
14811 &[
14812 ("这", 1, false),
14813 ("是", 1, false),
14814 ("什", 1, false),
14815 ("么", 1, false),
14816 (" ", 1, true),
14817 ("钢", 1, false),
14818 ("笔", 1, false),
14819 ],
14820 ),
14821 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14822 ];
14823
14824 for (input, result) in tests {
14825 assert_eq!(
14826 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14827 result
14828 .iter()
14829 .copied()
14830 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14831 token,
14832 grapheme_len,
14833 is_whitespace,
14834 })
14835 .collect::<Vec<_>>()
14836 );
14837 }
14838}
14839
14840fn wrap_with_prefix(
14841 line_prefix: String,
14842 unwrapped_text: String,
14843 wrap_column: usize,
14844 tab_size: NonZeroU32,
14845) -> String {
14846 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14847 let mut wrapped_text = String::new();
14848 let mut current_line = line_prefix.clone();
14849
14850 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14851 let mut current_line_len = line_prefix_len;
14852 for WordBreakToken {
14853 token,
14854 grapheme_len,
14855 is_whitespace,
14856 } in tokenizer
14857 {
14858 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14859 wrapped_text.push_str(current_line.trim_end());
14860 wrapped_text.push('\n');
14861 current_line.truncate(line_prefix.len());
14862 current_line_len = line_prefix_len;
14863 if !is_whitespace {
14864 current_line.push_str(token);
14865 current_line_len += grapheme_len;
14866 }
14867 } else if !is_whitespace {
14868 current_line.push_str(token);
14869 current_line_len += grapheme_len;
14870 } else if current_line_len != line_prefix_len {
14871 current_line.push(' ');
14872 current_line_len += 1;
14873 }
14874 }
14875
14876 if !current_line.is_empty() {
14877 wrapped_text.push_str(¤t_line);
14878 }
14879 wrapped_text
14880}
14881
14882#[test]
14883fn test_wrap_with_prefix() {
14884 assert_eq!(
14885 wrap_with_prefix(
14886 "# ".to_string(),
14887 "abcdefg".to_string(),
14888 4,
14889 NonZeroU32::new(4).unwrap()
14890 ),
14891 "# abcdefg"
14892 );
14893 assert_eq!(
14894 wrap_with_prefix(
14895 "".to_string(),
14896 "\thello world".to_string(),
14897 8,
14898 NonZeroU32::new(4).unwrap()
14899 ),
14900 "hello\nworld"
14901 );
14902 assert_eq!(
14903 wrap_with_prefix(
14904 "// ".to_string(),
14905 "xx \nyy zz aa bb cc".to_string(),
14906 12,
14907 NonZeroU32::new(4).unwrap()
14908 ),
14909 "// xx yy zz\n// aa bb cc"
14910 );
14911 assert_eq!(
14912 wrap_with_prefix(
14913 String::new(),
14914 "这是什么 \n 钢笔".to_string(),
14915 3,
14916 NonZeroU32::new(4).unwrap()
14917 ),
14918 "这是什\n么 钢\n笔"
14919 );
14920}
14921
14922pub trait CollaborationHub {
14923 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14924 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14925 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14926}
14927
14928impl CollaborationHub for Entity<Project> {
14929 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14930 self.read(cx).collaborators()
14931 }
14932
14933 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14934 self.read(cx).user_store().read(cx).participant_indices()
14935 }
14936
14937 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14938 let this = self.read(cx);
14939 let user_ids = this.collaborators().values().map(|c| c.user_id);
14940 this.user_store().read_with(cx, |user_store, cx| {
14941 user_store.participant_names(user_ids, cx)
14942 })
14943 }
14944}
14945
14946pub trait SemanticsProvider {
14947 fn hover(
14948 &self,
14949 buffer: &Entity<Buffer>,
14950 position: text::Anchor,
14951 cx: &mut App,
14952 ) -> Option<Task<Vec<project::Hover>>>;
14953
14954 fn inlay_hints(
14955 &self,
14956 buffer_handle: Entity<Buffer>,
14957 range: Range<text::Anchor>,
14958 cx: &mut App,
14959 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14960
14961 fn resolve_inlay_hint(
14962 &self,
14963 hint: InlayHint,
14964 buffer_handle: Entity<Buffer>,
14965 server_id: LanguageServerId,
14966 cx: &mut App,
14967 ) -> Option<Task<anyhow::Result<InlayHint>>>;
14968
14969 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
14970
14971 fn document_highlights(
14972 &self,
14973 buffer: &Entity<Buffer>,
14974 position: text::Anchor,
14975 cx: &mut App,
14976 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14977
14978 fn definitions(
14979 &self,
14980 buffer: &Entity<Buffer>,
14981 position: text::Anchor,
14982 kind: GotoDefinitionKind,
14983 cx: &mut App,
14984 ) -> Option<Task<Result<Vec<LocationLink>>>>;
14985
14986 fn range_for_rename(
14987 &self,
14988 buffer: &Entity<Buffer>,
14989 position: text::Anchor,
14990 cx: &mut App,
14991 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14992
14993 fn perform_rename(
14994 &self,
14995 buffer: &Entity<Buffer>,
14996 position: text::Anchor,
14997 new_name: String,
14998 cx: &mut App,
14999 ) -> Option<Task<Result<ProjectTransaction>>>;
15000}
15001
15002pub trait CompletionProvider {
15003 fn completions(
15004 &self,
15005 buffer: &Entity<Buffer>,
15006 buffer_position: text::Anchor,
15007 trigger: CompletionContext,
15008 window: &mut Window,
15009 cx: &mut Context<Editor>,
15010 ) -> Task<Result<Vec<Completion>>>;
15011
15012 fn resolve_completions(
15013 &self,
15014 buffer: Entity<Buffer>,
15015 completion_indices: Vec<usize>,
15016 completions: Rc<RefCell<Box<[Completion]>>>,
15017 cx: &mut Context<Editor>,
15018 ) -> Task<Result<bool>>;
15019
15020 fn apply_additional_edits_for_completion(
15021 &self,
15022 _buffer: Entity<Buffer>,
15023 _completions: Rc<RefCell<Box<[Completion]>>>,
15024 _completion_index: usize,
15025 _push_to_history: bool,
15026 _cx: &mut Context<Editor>,
15027 ) -> Task<Result<Option<language::Transaction>>> {
15028 Task::ready(Ok(None))
15029 }
15030
15031 fn is_completion_trigger(
15032 &self,
15033 buffer: &Entity<Buffer>,
15034 position: language::Anchor,
15035 text: &str,
15036 trigger_in_words: bool,
15037 cx: &mut Context<Editor>,
15038 ) -> bool;
15039
15040 fn sort_completions(&self) -> bool {
15041 true
15042 }
15043}
15044
15045pub trait CodeActionProvider {
15046 fn id(&self) -> Arc<str>;
15047
15048 fn code_actions(
15049 &self,
15050 buffer: &Entity<Buffer>,
15051 range: Range<text::Anchor>,
15052 window: &mut Window,
15053 cx: &mut App,
15054 ) -> Task<Result<Vec<CodeAction>>>;
15055
15056 fn apply_code_action(
15057 &self,
15058 buffer_handle: Entity<Buffer>,
15059 action: CodeAction,
15060 excerpt_id: ExcerptId,
15061 push_to_history: bool,
15062 window: &mut Window,
15063 cx: &mut App,
15064 ) -> Task<Result<ProjectTransaction>>;
15065}
15066
15067impl CodeActionProvider for Entity<Project> {
15068 fn id(&self) -> Arc<str> {
15069 "project".into()
15070 }
15071
15072 fn code_actions(
15073 &self,
15074 buffer: &Entity<Buffer>,
15075 range: Range<text::Anchor>,
15076 _window: &mut Window,
15077 cx: &mut App,
15078 ) -> Task<Result<Vec<CodeAction>>> {
15079 self.update(cx, |project, cx| {
15080 project.code_actions(buffer, range, None, cx)
15081 })
15082 }
15083
15084 fn apply_code_action(
15085 &self,
15086 buffer_handle: Entity<Buffer>,
15087 action: CodeAction,
15088 _excerpt_id: ExcerptId,
15089 push_to_history: bool,
15090 _window: &mut Window,
15091 cx: &mut App,
15092 ) -> Task<Result<ProjectTransaction>> {
15093 self.update(cx, |project, cx| {
15094 project.apply_code_action(buffer_handle, action, push_to_history, cx)
15095 })
15096 }
15097}
15098
15099fn snippet_completions(
15100 project: &Project,
15101 buffer: &Entity<Buffer>,
15102 buffer_position: text::Anchor,
15103 cx: &mut App,
15104) -> Task<Result<Vec<Completion>>> {
15105 let language = buffer.read(cx).language_at(buffer_position);
15106 let language_name = language.as_ref().map(|language| language.lsp_id());
15107 let snippet_store = project.snippets().read(cx);
15108 let snippets = snippet_store.snippets_for(language_name, cx);
15109
15110 if snippets.is_empty() {
15111 return Task::ready(Ok(vec![]));
15112 }
15113 let snapshot = buffer.read(cx).text_snapshot();
15114 let chars: String = snapshot
15115 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15116 .collect();
15117
15118 let scope = language.map(|language| language.default_scope());
15119 let executor = cx.background_executor().clone();
15120
15121 cx.background_executor().spawn(async move {
15122 let classifier = CharClassifier::new(scope).for_completion(true);
15123 let mut last_word = chars
15124 .chars()
15125 .take_while(|c| classifier.is_word(*c))
15126 .collect::<String>();
15127 last_word = last_word.chars().rev().collect();
15128
15129 if last_word.is_empty() {
15130 return Ok(vec![]);
15131 }
15132
15133 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15134 let to_lsp = |point: &text::Anchor| {
15135 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15136 point_to_lsp(end)
15137 };
15138 let lsp_end = to_lsp(&buffer_position);
15139
15140 let candidates = snippets
15141 .iter()
15142 .enumerate()
15143 .flat_map(|(ix, snippet)| {
15144 snippet
15145 .prefix
15146 .iter()
15147 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15148 })
15149 .collect::<Vec<StringMatchCandidate>>();
15150
15151 let mut matches = fuzzy::match_strings(
15152 &candidates,
15153 &last_word,
15154 last_word.chars().any(|c| c.is_uppercase()),
15155 100,
15156 &Default::default(),
15157 executor,
15158 )
15159 .await;
15160
15161 // Remove all candidates where the query's start does not match the start of any word in the candidate
15162 if let Some(query_start) = last_word.chars().next() {
15163 matches.retain(|string_match| {
15164 split_words(&string_match.string).any(|word| {
15165 // Check that the first codepoint of the word as lowercase matches the first
15166 // codepoint of the query as lowercase
15167 word.chars()
15168 .flat_map(|codepoint| codepoint.to_lowercase())
15169 .zip(query_start.to_lowercase())
15170 .all(|(word_cp, query_cp)| word_cp == query_cp)
15171 })
15172 });
15173 }
15174
15175 let matched_strings = matches
15176 .into_iter()
15177 .map(|m| m.string)
15178 .collect::<HashSet<_>>();
15179
15180 let result: Vec<Completion> = snippets
15181 .into_iter()
15182 .filter_map(|snippet| {
15183 let matching_prefix = snippet
15184 .prefix
15185 .iter()
15186 .find(|prefix| matched_strings.contains(*prefix))?;
15187 let start = as_offset - last_word.len();
15188 let start = snapshot.anchor_before(start);
15189 let range = start..buffer_position;
15190 let lsp_start = to_lsp(&start);
15191 let lsp_range = lsp::Range {
15192 start: lsp_start,
15193 end: lsp_end,
15194 };
15195 Some(Completion {
15196 old_range: range,
15197 new_text: snippet.body.clone(),
15198 resolved: false,
15199 label: CodeLabel {
15200 text: matching_prefix.clone(),
15201 runs: vec![],
15202 filter_range: 0..matching_prefix.len(),
15203 },
15204 server_id: LanguageServerId(usize::MAX),
15205 documentation: snippet
15206 .description
15207 .clone()
15208 .map(CompletionDocumentation::SingleLine),
15209 lsp_completion: lsp::CompletionItem {
15210 label: snippet.prefix.first().unwrap().clone(),
15211 kind: Some(CompletionItemKind::SNIPPET),
15212 label_details: snippet.description.as_ref().map(|description| {
15213 lsp::CompletionItemLabelDetails {
15214 detail: Some(description.clone()),
15215 description: None,
15216 }
15217 }),
15218 insert_text_format: Some(InsertTextFormat::SNIPPET),
15219 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15220 lsp::InsertReplaceEdit {
15221 new_text: snippet.body.clone(),
15222 insert: lsp_range,
15223 replace: lsp_range,
15224 },
15225 )),
15226 filter_text: Some(snippet.body.clone()),
15227 sort_text: Some(char::MAX.to_string()),
15228 ..Default::default()
15229 },
15230 confirm: None,
15231 })
15232 })
15233 .collect();
15234
15235 Ok(result)
15236 })
15237}
15238
15239impl CompletionProvider for Entity<Project> {
15240 fn completions(
15241 &self,
15242 buffer: &Entity<Buffer>,
15243 buffer_position: text::Anchor,
15244 options: CompletionContext,
15245 _window: &mut Window,
15246 cx: &mut Context<Editor>,
15247 ) -> Task<Result<Vec<Completion>>> {
15248 self.update(cx, |project, cx| {
15249 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15250 let project_completions = project.completions(buffer, buffer_position, options, cx);
15251 cx.background_executor().spawn(async move {
15252 let mut completions = project_completions.await?;
15253 let snippets_completions = snippets.await?;
15254 completions.extend(snippets_completions);
15255 Ok(completions)
15256 })
15257 })
15258 }
15259
15260 fn resolve_completions(
15261 &self,
15262 buffer: Entity<Buffer>,
15263 completion_indices: Vec<usize>,
15264 completions: Rc<RefCell<Box<[Completion]>>>,
15265 cx: &mut Context<Editor>,
15266 ) -> Task<Result<bool>> {
15267 self.update(cx, |project, cx| {
15268 project.lsp_store().update(cx, |lsp_store, cx| {
15269 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15270 })
15271 })
15272 }
15273
15274 fn apply_additional_edits_for_completion(
15275 &self,
15276 buffer: Entity<Buffer>,
15277 completions: Rc<RefCell<Box<[Completion]>>>,
15278 completion_index: usize,
15279 push_to_history: bool,
15280 cx: &mut Context<Editor>,
15281 ) -> Task<Result<Option<language::Transaction>>> {
15282 self.update(cx, |project, cx| {
15283 project.lsp_store().update(cx, |lsp_store, cx| {
15284 lsp_store.apply_additional_edits_for_completion(
15285 buffer,
15286 completions,
15287 completion_index,
15288 push_to_history,
15289 cx,
15290 )
15291 })
15292 })
15293 }
15294
15295 fn is_completion_trigger(
15296 &self,
15297 buffer: &Entity<Buffer>,
15298 position: language::Anchor,
15299 text: &str,
15300 trigger_in_words: bool,
15301 cx: &mut Context<Editor>,
15302 ) -> bool {
15303 let mut chars = text.chars();
15304 let char = if let Some(char) = chars.next() {
15305 char
15306 } else {
15307 return false;
15308 };
15309 if chars.next().is_some() {
15310 return false;
15311 }
15312
15313 let buffer = buffer.read(cx);
15314 let snapshot = buffer.snapshot();
15315 if !snapshot.settings_at(position, cx).show_completions_on_input {
15316 return false;
15317 }
15318 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15319 if trigger_in_words && classifier.is_word(char) {
15320 return true;
15321 }
15322
15323 buffer.completion_triggers().contains(text)
15324 }
15325}
15326
15327impl SemanticsProvider for Entity<Project> {
15328 fn hover(
15329 &self,
15330 buffer: &Entity<Buffer>,
15331 position: text::Anchor,
15332 cx: &mut App,
15333 ) -> Option<Task<Vec<project::Hover>>> {
15334 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15335 }
15336
15337 fn document_highlights(
15338 &self,
15339 buffer: &Entity<Buffer>,
15340 position: text::Anchor,
15341 cx: &mut App,
15342 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15343 Some(self.update(cx, |project, cx| {
15344 project.document_highlights(buffer, position, cx)
15345 }))
15346 }
15347
15348 fn definitions(
15349 &self,
15350 buffer: &Entity<Buffer>,
15351 position: text::Anchor,
15352 kind: GotoDefinitionKind,
15353 cx: &mut App,
15354 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15355 Some(self.update(cx, |project, cx| match kind {
15356 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15357 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15358 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15359 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15360 }))
15361 }
15362
15363 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15364 // TODO: make this work for remote projects
15365 self.read(cx)
15366 .language_servers_for_local_buffer(buffer.read(cx), cx)
15367 .any(
15368 |(_, server)| match server.capabilities().inlay_hint_provider {
15369 Some(lsp::OneOf::Left(enabled)) => enabled,
15370 Some(lsp::OneOf::Right(_)) => true,
15371 None => false,
15372 },
15373 )
15374 }
15375
15376 fn inlay_hints(
15377 &self,
15378 buffer_handle: Entity<Buffer>,
15379 range: Range<text::Anchor>,
15380 cx: &mut App,
15381 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15382 Some(self.update(cx, |project, cx| {
15383 project.inlay_hints(buffer_handle, range, cx)
15384 }))
15385 }
15386
15387 fn resolve_inlay_hint(
15388 &self,
15389 hint: InlayHint,
15390 buffer_handle: Entity<Buffer>,
15391 server_id: LanguageServerId,
15392 cx: &mut App,
15393 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15394 Some(self.update(cx, |project, cx| {
15395 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15396 }))
15397 }
15398
15399 fn range_for_rename(
15400 &self,
15401 buffer: &Entity<Buffer>,
15402 position: text::Anchor,
15403 cx: &mut App,
15404 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15405 Some(self.update(cx, |project, cx| {
15406 let buffer = buffer.clone();
15407 let task = project.prepare_rename(buffer.clone(), position, cx);
15408 cx.spawn(|_, mut cx| async move {
15409 Ok(match task.await? {
15410 PrepareRenameResponse::Success(range) => Some(range),
15411 PrepareRenameResponse::InvalidPosition => None,
15412 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15413 // Fallback on using TreeSitter info to determine identifier range
15414 buffer.update(&mut cx, |buffer, _| {
15415 let snapshot = buffer.snapshot();
15416 let (range, kind) = snapshot.surrounding_word(position);
15417 if kind != Some(CharKind::Word) {
15418 return None;
15419 }
15420 Some(
15421 snapshot.anchor_before(range.start)
15422 ..snapshot.anchor_after(range.end),
15423 )
15424 })?
15425 }
15426 })
15427 })
15428 }))
15429 }
15430
15431 fn perform_rename(
15432 &self,
15433 buffer: &Entity<Buffer>,
15434 position: text::Anchor,
15435 new_name: String,
15436 cx: &mut App,
15437 ) -> Option<Task<Result<ProjectTransaction>>> {
15438 Some(self.update(cx, |project, cx| {
15439 project.perform_rename(buffer.clone(), position, new_name, cx)
15440 }))
15441 }
15442}
15443
15444fn inlay_hint_settings(
15445 location: Anchor,
15446 snapshot: &MultiBufferSnapshot,
15447 cx: &mut Context<Editor>,
15448) -> InlayHintSettings {
15449 let file = snapshot.file_at(location);
15450 let language = snapshot.language_at(location).map(|l| l.name());
15451 language_settings(language, file, cx).inlay_hints
15452}
15453
15454fn consume_contiguous_rows(
15455 contiguous_row_selections: &mut Vec<Selection<Point>>,
15456 selection: &Selection<Point>,
15457 display_map: &DisplaySnapshot,
15458 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15459) -> (MultiBufferRow, MultiBufferRow) {
15460 contiguous_row_selections.push(selection.clone());
15461 let start_row = MultiBufferRow(selection.start.row);
15462 let mut end_row = ending_row(selection, display_map);
15463
15464 while let Some(next_selection) = selections.peek() {
15465 if next_selection.start.row <= end_row.0 {
15466 end_row = ending_row(next_selection, display_map);
15467 contiguous_row_selections.push(selections.next().unwrap().clone());
15468 } else {
15469 break;
15470 }
15471 }
15472 (start_row, end_row)
15473}
15474
15475fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15476 if next_selection.end.column > 0 || next_selection.is_empty() {
15477 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15478 } else {
15479 MultiBufferRow(next_selection.end.row)
15480 }
15481}
15482
15483impl EditorSnapshot {
15484 pub fn remote_selections_in_range<'a>(
15485 &'a self,
15486 range: &'a Range<Anchor>,
15487 collaboration_hub: &dyn CollaborationHub,
15488 cx: &'a App,
15489 ) -> impl 'a + Iterator<Item = RemoteSelection> {
15490 let participant_names = collaboration_hub.user_names(cx);
15491 let participant_indices = collaboration_hub.user_participant_indices(cx);
15492 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15493 let collaborators_by_replica_id = collaborators_by_peer_id
15494 .iter()
15495 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15496 .collect::<HashMap<_, _>>();
15497 self.buffer_snapshot
15498 .selections_in_range(range, false)
15499 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15500 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15501 let participant_index = participant_indices.get(&collaborator.user_id).copied();
15502 let user_name = participant_names.get(&collaborator.user_id).cloned();
15503 Some(RemoteSelection {
15504 replica_id,
15505 selection,
15506 cursor_shape,
15507 line_mode,
15508 participant_index,
15509 peer_id: collaborator.peer_id,
15510 user_name,
15511 })
15512 })
15513 }
15514
15515 pub fn hunks_for_ranges(
15516 &self,
15517 ranges: impl Iterator<Item = Range<Point>>,
15518 ) -> Vec<MultiBufferDiffHunk> {
15519 let mut hunks = Vec::new();
15520 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15521 HashMap::default();
15522 for query_range in ranges {
15523 let query_rows =
15524 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15525 for hunk in self.buffer_snapshot.diff_hunks_in_range(
15526 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15527 ) {
15528 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15529 // when the caret is just above or just below the deleted hunk.
15530 let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15531 let related_to_selection = if allow_adjacent {
15532 hunk.row_range.overlaps(&query_rows)
15533 || hunk.row_range.start == query_rows.end
15534 || hunk.row_range.end == query_rows.start
15535 } else {
15536 hunk.row_range.overlaps(&query_rows)
15537 };
15538 if related_to_selection {
15539 if !processed_buffer_rows
15540 .entry(hunk.buffer_id)
15541 .or_default()
15542 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15543 {
15544 continue;
15545 }
15546 hunks.push(hunk);
15547 }
15548 }
15549 }
15550
15551 hunks
15552 }
15553
15554 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15555 self.display_snapshot.buffer_snapshot.language_at(position)
15556 }
15557
15558 pub fn is_focused(&self) -> bool {
15559 self.is_focused
15560 }
15561
15562 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15563 self.placeholder_text.as_ref()
15564 }
15565
15566 pub fn scroll_position(&self) -> gpui::Point<f32> {
15567 self.scroll_anchor.scroll_position(&self.display_snapshot)
15568 }
15569
15570 fn gutter_dimensions(
15571 &self,
15572 font_id: FontId,
15573 font_size: Pixels,
15574 max_line_number_width: Pixels,
15575 cx: &App,
15576 ) -> Option<GutterDimensions> {
15577 if !self.show_gutter {
15578 return None;
15579 }
15580
15581 let descent = cx.text_system().descent(font_id, font_size);
15582 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15583 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15584
15585 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15586 matches!(
15587 ProjectSettings::get_global(cx).git.git_gutter,
15588 Some(GitGutterSetting::TrackedFiles)
15589 )
15590 });
15591 let gutter_settings = EditorSettings::get_global(cx).gutter;
15592 let show_line_numbers = self
15593 .show_line_numbers
15594 .unwrap_or(gutter_settings.line_numbers);
15595 let line_gutter_width = if show_line_numbers {
15596 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15597 let min_width_for_number_on_gutter = em_advance * 4.0;
15598 max_line_number_width.max(min_width_for_number_on_gutter)
15599 } else {
15600 0.0.into()
15601 };
15602
15603 let show_code_actions = self
15604 .show_code_actions
15605 .unwrap_or(gutter_settings.code_actions);
15606
15607 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15608
15609 let git_blame_entries_width =
15610 self.git_blame_gutter_max_author_length
15611 .map(|max_author_length| {
15612 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15613
15614 /// The number of characters to dedicate to gaps and margins.
15615 const SPACING_WIDTH: usize = 4;
15616
15617 let max_char_count = max_author_length
15618 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15619 + ::git::SHORT_SHA_LENGTH
15620 + MAX_RELATIVE_TIMESTAMP.len()
15621 + SPACING_WIDTH;
15622
15623 em_advance * max_char_count
15624 });
15625
15626 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15627 left_padding += if show_code_actions || show_runnables {
15628 em_width * 3.0
15629 } else if show_git_gutter && show_line_numbers {
15630 em_width * 2.0
15631 } else if show_git_gutter || show_line_numbers {
15632 em_width
15633 } else {
15634 px(0.)
15635 };
15636
15637 let right_padding = if gutter_settings.folds && show_line_numbers {
15638 em_width * 4.0
15639 } else if gutter_settings.folds {
15640 em_width * 3.0
15641 } else if show_line_numbers {
15642 em_width
15643 } else {
15644 px(0.)
15645 };
15646
15647 Some(GutterDimensions {
15648 left_padding,
15649 right_padding,
15650 width: line_gutter_width + left_padding + right_padding,
15651 margin: -descent,
15652 git_blame_entries_width,
15653 })
15654 }
15655
15656 pub fn render_crease_toggle(
15657 &self,
15658 buffer_row: MultiBufferRow,
15659 row_contains_cursor: bool,
15660 editor: Entity<Editor>,
15661 window: &mut Window,
15662 cx: &mut App,
15663 ) -> Option<AnyElement> {
15664 let folded = self.is_line_folded(buffer_row);
15665 let mut is_foldable = false;
15666
15667 if let Some(crease) = self
15668 .crease_snapshot
15669 .query_row(buffer_row, &self.buffer_snapshot)
15670 {
15671 is_foldable = true;
15672 match crease {
15673 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15674 if let Some(render_toggle) = render_toggle {
15675 let toggle_callback =
15676 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15677 if folded {
15678 editor.update(cx, |editor, cx| {
15679 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15680 });
15681 } else {
15682 editor.update(cx, |editor, cx| {
15683 editor.unfold_at(
15684 &crate::UnfoldAt { buffer_row },
15685 window,
15686 cx,
15687 )
15688 });
15689 }
15690 });
15691 return Some((render_toggle)(
15692 buffer_row,
15693 folded,
15694 toggle_callback,
15695 window,
15696 cx,
15697 ));
15698 }
15699 }
15700 }
15701 }
15702
15703 is_foldable |= self.starts_indent(buffer_row);
15704
15705 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15706 Some(
15707 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15708 .toggle_state(folded)
15709 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15710 if folded {
15711 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15712 } else {
15713 this.fold_at(&FoldAt { buffer_row }, window, cx);
15714 }
15715 }))
15716 .into_any_element(),
15717 )
15718 } else {
15719 None
15720 }
15721 }
15722
15723 pub fn render_crease_trailer(
15724 &self,
15725 buffer_row: MultiBufferRow,
15726 window: &mut Window,
15727 cx: &mut App,
15728 ) -> Option<AnyElement> {
15729 let folded = self.is_line_folded(buffer_row);
15730 if let Crease::Inline { render_trailer, .. } = self
15731 .crease_snapshot
15732 .query_row(buffer_row, &self.buffer_snapshot)?
15733 {
15734 let render_trailer = render_trailer.as_ref()?;
15735 Some(render_trailer(buffer_row, folded, window, cx))
15736 } else {
15737 None
15738 }
15739 }
15740}
15741
15742impl Deref for EditorSnapshot {
15743 type Target = DisplaySnapshot;
15744
15745 fn deref(&self) -> &Self::Target {
15746 &self.display_snapshot
15747 }
15748}
15749
15750#[derive(Clone, Debug, PartialEq, Eq)]
15751pub enum EditorEvent {
15752 InputIgnored {
15753 text: Arc<str>,
15754 },
15755 InputHandled {
15756 utf16_range_to_replace: Option<Range<isize>>,
15757 text: Arc<str>,
15758 },
15759 ExcerptsAdded {
15760 buffer: Entity<Buffer>,
15761 predecessor: ExcerptId,
15762 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15763 },
15764 ExcerptsRemoved {
15765 ids: Vec<ExcerptId>,
15766 },
15767 BufferFoldToggled {
15768 ids: Vec<ExcerptId>,
15769 folded: bool,
15770 },
15771 ExcerptsEdited {
15772 ids: Vec<ExcerptId>,
15773 },
15774 ExcerptsExpanded {
15775 ids: Vec<ExcerptId>,
15776 },
15777 BufferEdited,
15778 Edited {
15779 transaction_id: clock::Lamport,
15780 },
15781 Reparsed(BufferId),
15782 Focused,
15783 FocusedIn,
15784 Blurred,
15785 DirtyChanged,
15786 Saved,
15787 TitleChanged,
15788 DiffBaseChanged,
15789 SelectionsChanged {
15790 local: bool,
15791 },
15792 ScrollPositionChanged {
15793 local: bool,
15794 autoscroll: bool,
15795 },
15796 Closed,
15797 TransactionUndone {
15798 transaction_id: clock::Lamport,
15799 },
15800 TransactionBegun {
15801 transaction_id: clock::Lamport,
15802 },
15803 Reloaded,
15804 CursorShapeChanged,
15805}
15806
15807impl EventEmitter<EditorEvent> for Editor {}
15808
15809impl Focusable for Editor {
15810 fn focus_handle(&self, _cx: &App) -> FocusHandle {
15811 self.focus_handle.clone()
15812 }
15813}
15814
15815impl Render for Editor {
15816 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15817 let settings = ThemeSettings::get_global(cx);
15818
15819 let mut text_style = match self.mode {
15820 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15821 color: cx.theme().colors().editor_foreground,
15822 font_family: settings.ui_font.family.clone(),
15823 font_features: settings.ui_font.features.clone(),
15824 font_fallbacks: settings.ui_font.fallbacks.clone(),
15825 font_size: rems(0.875).into(),
15826 font_weight: settings.ui_font.weight,
15827 line_height: relative(settings.buffer_line_height.value()),
15828 ..Default::default()
15829 },
15830 EditorMode::Full => TextStyle {
15831 color: cx.theme().colors().editor_foreground,
15832 font_family: settings.buffer_font.family.clone(),
15833 font_features: settings.buffer_font.features.clone(),
15834 font_fallbacks: settings.buffer_font.fallbacks.clone(),
15835 font_size: settings.buffer_font_size().into(),
15836 font_weight: settings.buffer_font.weight,
15837 line_height: relative(settings.buffer_line_height.value()),
15838 ..Default::default()
15839 },
15840 };
15841 if let Some(text_style_refinement) = &self.text_style_refinement {
15842 text_style.refine(text_style_refinement)
15843 }
15844
15845 let background = match self.mode {
15846 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15847 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15848 EditorMode::Full => cx.theme().colors().editor_background,
15849 };
15850
15851 EditorElement::new(
15852 &cx.entity(),
15853 EditorStyle {
15854 background,
15855 local_player: cx.theme().players().local(),
15856 text: text_style,
15857 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15858 syntax: cx.theme().syntax().clone(),
15859 status: cx.theme().status().clone(),
15860 inlay_hints_style: make_inlay_hints_style(cx),
15861 inline_completion_styles: make_suggestion_styles(cx),
15862 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15863 },
15864 )
15865 }
15866}
15867
15868impl EntityInputHandler for Editor {
15869 fn text_for_range(
15870 &mut self,
15871 range_utf16: Range<usize>,
15872 adjusted_range: &mut Option<Range<usize>>,
15873 _: &mut Window,
15874 cx: &mut Context<Self>,
15875 ) -> Option<String> {
15876 let snapshot = self.buffer.read(cx).read(cx);
15877 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15878 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15879 if (start.0..end.0) != range_utf16 {
15880 adjusted_range.replace(start.0..end.0);
15881 }
15882 Some(snapshot.text_for_range(start..end).collect())
15883 }
15884
15885 fn selected_text_range(
15886 &mut self,
15887 ignore_disabled_input: bool,
15888 _: &mut Window,
15889 cx: &mut Context<Self>,
15890 ) -> Option<UTF16Selection> {
15891 // Prevent the IME menu from appearing when holding down an alphabetic key
15892 // while input is disabled.
15893 if !ignore_disabled_input && !self.input_enabled {
15894 return None;
15895 }
15896
15897 let selection = self.selections.newest::<OffsetUtf16>(cx);
15898 let range = selection.range();
15899
15900 Some(UTF16Selection {
15901 range: range.start.0..range.end.0,
15902 reversed: selection.reversed,
15903 })
15904 }
15905
15906 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15907 let snapshot = self.buffer.read(cx).read(cx);
15908 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15909 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15910 }
15911
15912 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15913 self.clear_highlights::<InputComposition>(cx);
15914 self.ime_transaction.take();
15915 }
15916
15917 fn replace_text_in_range(
15918 &mut self,
15919 range_utf16: Option<Range<usize>>,
15920 text: &str,
15921 window: &mut Window,
15922 cx: &mut Context<Self>,
15923 ) {
15924 if !self.input_enabled {
15925 cx.emit(EditorEvent::InputIgnored { text: text.into() });
15926 return;
15927 }
15928
15929 self.transact(window, cx, |this, window, cx| {
15930 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15931 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15932 Some(this.selection_replacement_ranges(range_utf16, cx))
15933 } else {
15934 this.marked_text_ranges(cx)
15935 };
15936
15937 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15938 let newest_selection_id = this.selections.newest_anchor().id;
15939 this.selections
15940 .all::<OffsetUtf16>(cx)
15941 .iter()
15942 .zip(ranges_to_replace.iter())
15943 .find_map(|(selection, range)| {
15944 if selection.id == newest_selection_id {
15945 Some(
15946 (range.start.0 as isize - selection.head().0 as isize)
15947 ..(range.end.0 as isize - selection.head().0 as isize),
15948 )
15949 } else {
15950 None
15951 }
15952 })
15953 });
15954
15955 cx.emit(EditorEvent::InputHandled {
15956 utf16_range_to_replace: range_to_replace,
15957 text: text.into(),
15958 });
15959
15960 if let Some(new_selected_ranges) = new_selected_ranges {
15961 this.change_selections(None, window, cx, |selections| {
15962 selections.select_ranges(new_selected_ranges)
15963 });
15964 this.backspace(&Default::default(), window, cx);
15965 }
15966
15967 this.handle_input(text, window, cx);
15968 });
15969
15970 if let Some(transaction) = self.ime_transaction {
15971 self.buffer.update(cx, |buffer, cx| {
15972 buffer.group_until_transaction(transaction, cx);
15973 });
15974 }
15975
15976 self.unmark_text(window, cx);
15977 }
15978
15979 fn replace_and_mark_text_in_range(
15980 &mut self,
15981 range_utf16: Option<Range<usize>>,
15982 text: &str,
15983 new_selected_range_utf16: Option<Range<usize>>,
15984 window: &mut Window,
15985 cx: &mut Context<Self>,
15986 ) {
15987 if !self.input_enabled {
15988 return;
15989 }
15990
15991 let transaction = self.transact(window, cx, |this, window, cx| {
15992 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15993 let snapshot = this.buffer.read(cx).read(cx);
15994 if let Some(relative_range_utf16) = range_utf16.as_ref() {
15995 for marked_range in &mut marked_ranges {
15996 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15997 marked_range.start.0 += relative_range_utf16.start;
15998 marked_range.start =
15999 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16000 marked_range.end =
16001 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16002 }
16003 }
16004 Some(marked_ranges)
16005 } else if let Some(range_utf16) = range_utf16 {
16006 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16007 Some(this.selection_replacement_ranges(range_utf16, cx))
16008 } else {
16009 None
16010 };
16011
16012 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16013 let newest_selection_id = this.selections.newest_anchor().id;
16014 this.selections
16015 .all::<OffsetUtf16>(cx)
16016 .iter()
16017 .zip(ranges_to_replace.iter())
16018 .find_map(|(selection, range)| {
16019 if selection.id == newest_selection_id {
16020 Some(
16021 (range.start.0 as isize - selection.head().0 as isize)
16022 ..(range.end.0 as isize - selection.head().0 as isize),
16023 )
16024 } else {
16025 None
16026 }
16027 })
16028 });
16029
16030 cx.emit(EditorEvent::InputHandled {
16031 utf16_range_to_replace: range_to_replace,
16032 text: text.into(),
16033 });
16034
16035 if let Some(ranges) = ranges_to_replace {
16036 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16037 }
16038
16039 let marked_ranges = {
16040 let snapshot = this.buffer.read(cx).read(cx);
16041 this.selections
16042 .disjoint_anchors()
16043 .iter()
16044 .map(|selection| {
16045 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16046 })
16047 .collect::<Vec<_>>()
16048 };
16049
16050 if text.is_empty() {
16051 this.unmark_text(window, cx);
16052 } else {
16053 this.highlight_text::<InputComposition>(
16054 marked_ranges.clone(),
16055 HighlightStyle {
16056 underline: Some(UnderlineStyle {
16057 thickness: px(1.),
16058 color: None,
16059 wavy: false,
16060 }),
16061 ..Default::default()
16062 },
16063 cx,
16064 );
16065 }
16066
16067 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16068 let use_autoclose = this.use_autoclose;
16069 let use_auto_surround = this.use_auto_surround;
16070 this.set_use_autoclose(false);
16071 this.set_use_auto_surround(false);
16072 this.handle_input(text, window, cx);
16073 this.set_use_autoclose(use_autoclose);
16074 this.set_use_auto_surround(use_auto_surround);
16075
16076 if let Some(new_selected_range) = new_selected_range_utf16 {
16077 let snapshot = this.buffer.read(cx).read(cx);
16078 let new_selected_ranges = marked_ranges
16079 .into_iter()
16080 .map(|marked_range| {
16081 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16082 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16083 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16084 snapshot.clip_offset_utf16(new_start, Bias::Left)
16085 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16086 })
16087 .collect::<Vec<_>>();
16088
16089 drop(snapshot);
16090 this.change_selections(None, window, cx, |selections| {
16091 selections.select_ranges(new_selected_ranges)
16092 });
16093 }
16094 });
16095
16096 self.ime_transaction = self.ime_transaction.or(transaction);
16097 if let Some(transaction) = self.ime_transaction {
16098 self.buffer.update(cx, |buffer, cx| {
16099 buffer.group_until_transaction(transaction, cx);
16100 });
16101 }
16102
16103 if self.text_highlights::<InputComposition>(cx).is_none() {
16104 self.ime_transaction.take();
16105 }
16106 }
16107
16108 fn bounds_for_range(
16109 &mut self,
16110 range_utf16: Range<usize>,
16111 element_bounds: gpui::Bounds<Pixels>,
16112 window: &mut Window,
16113 cx: &mut Context<Self>,
16114 ) -> Option<gpui::Bounds<Pixels>> {
16115 let text_layout_details = self.text_layout_details(window);
16116 let gpui::Size {
16117 width: em_width,
16118 height: line_height,
16119 } = self.character_size(window);
16120
16121 let snapshot = self.snapshot(window, cx);
16122 let scroll_position = snapshot.scroll_position();
16123 let scroll_left = scroll_position.x * em_width;
16124
16125 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16126 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16127 + self.gutter_dimensions.width
16128 + self.gutter_dimensions.margin;
16129 let y = line_height * (start.row().as_f32() - scroll_position.y);
16130
16131 Some(Bounds {
16132 origin: element_bounds.origin + point(x, y),
16133 size: size(em_width, line_height),
16134 })
16135 }
16136
16137 fn character_index_for_point(
16138 &mut self,
16139 point: gpui::Point<Pixels>,
16140 _window: &mut Window,
16141 _cx: &mut Context<Self>,
16142 ) -> Option<usize> {
16143 let position_map = self.last_position_map.as_ref()?;
16144 if !position_map.text_hitbox.contains(&point) {
16145 return None;
16146 }
16147 let display_point = position_map.point_for_position(point).previous_valid;
16148 let anchor = position_map
16149 .snapshot
16150 .display_point_to_anchor(display_point, Bias::Left);
16151 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16152 Some(utf16_offset.0)
16153 }
16154}
16155
16156trait SelectionExt {
16157 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16158 fn spanned_rows(
16159 &self,
16160 include_end_if_at_line_start: bool,
16161 map: &DisplaySnapshot,
16162 ) -> Range<MultiBufferRow>;
16163}
16164
16165impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16166 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16167 let start = self
16168 .start
16169 .to_point(&map.buffer_snapshot)
16170 .to_display_point(map);
16171 let end = self
16172 .end
16173 .to_point(&map.buffer_snapshot)
16174 .to_display_point(map);
16175 if self.reversed {
16176 end..start
16177 } else {
16178 start..end
16179 }
16180 }
16181
16182 fn spanned_rows(
16183 &self,
16184 include_end_if_at_line_start: bool,
16185 map: &DisplaySnapshot,
16186 ) -> Range<MultiBufferRow> {
16187 let start = self.start.to_point(&map.buffer_snapshot);
16188 let mut end = self.end.to_point(&map.buffer_snapshot);
16189 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16190 end.row -= 1;
16191 }
16192
16193 let buffer_start = map.prev_line_boundary(start).0;
16194 let buffer_end = map.next_line_boundary(end).0;
16195 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16196 }
16197}
16198
16199impl<T: InvalidationRegion> InvalidationStack<T> {
16200 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16201 where
16202 S: Clone + ToOffset,
16203 {
16204 while let Some(region) = self.last() {
16205 let all_selections_inside_invalidation_ranges =
16206 if selections.len() == region.ranges().len() {
16207 selections
16208 .iter()
16209 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16210 .all(|(selection, invalidation_range)| {
16211 let head = selection.head().to_offset(buffer);
16212 invalidation_range.start <= head && invalidation_range.end >= head
16213 })
16214 } else {
16215 false
16216 };
16217
16218 if all_selections_inside_invalidation_ranges {
16219 break;
16220 } else {
16221 self.pop();
16222 }
16223 }
16224 }
16225}
16226
16227impl<T> Default for InvalidationStack<T> {
16228 fn default() -> Self {
16229 Self(Default::default())
16230 }
16231}
16232
16233impl<T> Deref for InvalidationStack<T> {
16234 type Target = Vec<T>;
16235
16236 fn deref(&self) -> &Self::Target {
16237 &self.0
16238 }
16239}
16240
16241impl<T> DerefMut for InvalidationStack<T> {
16242 fn deref_mut(&mut self) -> &mut Self::Target {
16243 &mut self.0
16244 }
16245}
16246
16247impl InvalidationRegion for SnippetState {
16248 fn ranges(&self) -> &[Range<Anchor>] {
16249 &self.ranges[self.active_index]
16250 }
16251}
16252
16253pub fn diagnostic_block_renderer(
16254 diagnostic: Diagnostic,
16255 max_message_rows: Option<u8>,
16256 allow_closing: bool,
16257 _is_valid: bool,
16258) -> RenderBlock {
16259 let (text_without_backticks, code_ranges) =
16260 highlight_diagnostic_message(&diagnostic, max_message_rows);
16261
16262 Arc::new(move |cx: &mut BlockContext| {
16263 let group_id: SharedString = cx.block_id.to_string().into();
16264
16265 let mut text_style = cx.window.text_style().clone();
16266 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16267 let theme_settings = ThemeSettings::get_global(cx);
16268 text_style.font_family = theme_settings.buffer_font.family.clone();
16269 text_style.font_style = theme_settings.buffer_font.style;
16270 text_style.font_features = theme_settings.buffer_font.features.clone();
16271 text_style.font_weight = theme_settings.buffer_font.weight;
16272
16273 let multi_line_diagnostic = diagnostic.message.contains('\n');
16274
16275 let buttons = |diagnostic: &Diagnostic| {
16276 if multi_line_diagnostic {
16277 v_flex()
16278 } else {
16279 h_flex()
16280 }
16281 .when(allow_closing, |div| {
16282 div.children(diagnostic.is_primary.then(|| {
16283 IconButton::new("close-block", IconName::XCircle)
16284 .icon_color(Color::Muted)
16285 .size(ButtonSize::Compact)
16286 .style(ButtonStyle::Transparent)
16287 .visible_on_hover(group_id.clone())
16288 .on_click(move |_click, window, cx| {
16289 window.dispatch_action(Box::new(Cancel), cx)
16290 })
16291 .tooltip(|window, cx| {
16292 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16293 })
16294 }))
16295 })
16296 .child(
16297 IconButton::new("copy-block", IconName::Copy)
16298 .icon_color(Color::Muted)
16299 .size(ButtonSize::Compact)
16300 .style(ButtonStyle::Transparent)
16301 .visible_on_hover(group_id.clone())
16302 .on_click({
16303 let message = diagnostic.message.clone();
16304 move |_click, _, cx| {
16305 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16306 }
16307 })
16308 .tooltip(Tooltip::text("Copy diagnostic message")),
16309 )
16310 };
16311
16312 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16313 AvailableSpace::min_size(),
16314 cx.window,
16315 cx.app,
16316 );
16317
16318 h_flex()
16319 .id(cx.block_id)
16320 .group(group_id.clone())
16321 .relative()
16322 .size_full()
16323 .block_mouse_down()
16324 .pl(cx.gutter_dimensions.width)
16325 .w(cx.max_width - cx.gutter_dimensions.full_width())
16326 .child(
16327 div()
16328 .flex()
16329 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16330 .flex_shrink(),
16331 )
16332 .child(buttons(&diagnostic))
16333 .child(div().flex().flex_shrink_0().child(
16334 StyledText::new(text_without_backticks.clone()).with_highlights(
16335 &text_style,
16336 code_ranges.iter().map(|range| {
16337 (
16338 range.clone(),
16339 HighlightStyle {
16340 font_weight: Some(FontWeight::BOLD),
16341 ..Default::default()
16342 },
16343 )
16344 }),
16345 ),
16346 ))
16347 .into_any_element()
16348 })
16349}
16350
16351fn inline_completion_edit_text(
16352 current_snapshot: &BufferSnapshot,
16353 edits: &[(Range<Anchor>, String)],
16354 edit_preview: &EditPreview,
16355 include_deletions: bool,
16356 cx: &App,
16357) -> HighlightedText {
16358 let edits = edits
16359 .iter()
16360 .map(|(anchor, text)| {
16361 (
16362 anchor.start.text_anchor..anchor.end.text_anchor,
16363 text.clone(),
16364 )
16365 })
16366 .collect::<Vec<_>>();
16367
16368 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16369}
16370
16371pub fn highlight_diagnostic_message(
16372 diagnostic: &Diagnostic,
16373 mut max_message_rows: Option<u8>,
16374) -> (SharedString, Vec<Range<usize>>) {
16375 let mut text_without_backticks = String::new();
16376 let mut code_ranges = Vec::new();
16377
16378 if let Some(source) = &diagnostic.source {
16379 text_without_backticks.push_str(source);
16380 code_ranges.push(0..source.len());
16381 text_without_backticks.push_str(": ");
16382 }
16383
16384 let mut prev_offset = 0;
16385 let mut in_code_block = false;
16386 let has_row_limit = max_message_rows.is_some();
16387 let mut newline_indices = diagnostic
16388 .message
16389 .match_indices('\n')
16390 .filter(|_| has_row_limit)
16391 .map(|(ix, _)| ix)
16392 .fuse()
16393 .peekable();
16394
16395 for (quote_ix, _) in diagnostic
16396 .message
16397 .match_indices('`')
16398 .chain([(diagnostic.message.len(), "")])
16399 {
16400 let mut first_newline_ix = None;
16401 let mut last_newline_ix = None;
16402 while let Some(newline_ix) = newline_indices.peek() {
16403 if *newline_ix < quote_ix {
16404 if first_newline_ix.is_none() {
16405 first_newline_ix = Some(*newline_ix);
16406 }
16407 last_newline_ix = Some(*newline_ix);
16408
16409 if let Some(rows_left) = &mut max_message_rows {
16410 if *rows_left == 0 {
16411 break;
16412 } else {
16413 *rows_left -= 1;
16414 }
16415 }
16416 let _ = newline_indices.next();
16417 } else {
16418 break;
16419 }
16420 }
16421 let prev_len = text_without_backticks.len();
16422 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16423 text_without_backticks.push_str(new_text);
16424 if in_code_block {
16425 code_ranges.push(prev_len..text_without_backticks.len());
16426 }
16427 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16428 in_code_block = !in_code_block;
16429 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16430 text_without_backticks.push_str("...");
16431 break;
16432 }
16433 }
16434
16435 (text_without_backticks.into(), code_ranges)
16436}
16437
16438fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16439 match severity {
16440 DiagnosticSeverity::ERROR => colors.error,
16441 DiagnosticSeverity::WARNING => colors.warning,
16442 DiagnosticSeverity::INFORMATION => colors.info,
16443 DiagnosticSeverity::HINT => colors.info,
16444 _ => colors.ignored,
16445 }
16446}
16447
16448pub fn styled_runs_for_code_label<'a>(
16449 label: &'a CodeLabel,
16450 syntax_theme: &'a theme::SyntaxTheme,
16451) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16452 let fade_out = HighlightStyle {
16453 fade_out: Some(0.35),
16454 ..Default::default()
16455 };
16456
16457 let mut prev_end = label.filter_range.end;
16458 label
16459 .runs
16460 .iter()
16461 .enumerate()
16462 .flat_map(move |(ix, (range, highlight_id))| {
16463 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16464 style
16465 } else {
16466 return Default::default();
16467 };
16468 let mut muted_style = style;
16469 muted_style.highlight(fade_out);
16470
16471 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16472 if range.start >= label.filter_range.end {
16473 if range.start > prev_end {
16474 runs.push((prev_end..range.start, fade_out));
16475 }
16476 runs.push((range.clone(), muted_style));
16477 } else if range.end <= label.filter_range.end {
16478 runs.push((range.clone(), style));
16479 } else {
16480 runs.push((range.start..label.filter_range.end, style));
16481 runs.push((label.filter_range.end..range.end, muted_style));
16482 }
16483 prev_end = cmp::max(prev_end, range.end);
16484
16485 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16486 runs.push((prev_end..label.text.len(), fade_out));
16487 }
16488
16489 runs
16490 })
16491}
16492
16493pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16494 let mut prev_index = 0;
16495 let mut prev_codepoint: Option<char> = None;
16496 text.char_indices()
16497 .chain([(text.len(), '\0')])
16498 .filter_map(move |(index, codepoint)| {
16499 let prev_codepoint = prev_codepoint.replace(codepoint)?;
16500 let is_boundary = index == text.len()
16501 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16502 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16503 if is_boundary {
16504 let chunk = &text[prev_index..index];
16505 prev_index = index;
16506 Some(chunk)
16507 } else {
16508 None
16509 }
16510 })
16511}
16512
16513pub trait RangeToAnchorExt: Sized {
16514 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16515
16516 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16517 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16518 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16519 }
16520}
16521
16522impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16523 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16524 let start_offset = self.start.to_offset(snapshot);
16525 let end_offset = self.end.to_offset(snapshot);
16526 if start_offset == end_offset {
16527 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16528 } else {
16529 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16530 }
16531 }
16532}
16533
16534pub trait RowExt {
16535 fn as_f32(&self) -> f32;
16536
16537 fn next_row(&self) -> Self;
16538
16539 fn previous_row(&self) -> Self;
16540
16541 fn minus(&self, other: Self) -> u32;
16542}
16543
16544impl RowExt for DisplayRow {
16545 fn as_f32(&self) -> f32 {
16546 self.0 as f32
16547 }
16548
16549 fn next_row(&self) -> Self {
16550 Self(self.0 + 1)
16551 }
16552
16553 fn previous_row(&self) -> Self {
16554 Self(self.0.saturating_sub(1))
16555 }
16556
16557 fn minus(&self, other: Self) -> u32 {
16558 self.0 - other.0
16559 }
16560}
16561
16562impl RowExt for MultiBufferRow {
16563 fn as_f32(&self) -> f32 {
16564 self.0 as f32
16565 }
16566
16567 fn next_row(&self) -> Self {
16568 Self(self.0 + 1)
16569 }
16570
16571 fn previous_row(&self) -> Self {
16572 Self(self.0.saturating_sub(1))
16573 }
16574
16575 fn minus(&self, other: Self) -> u32 {
16576 self.0 - other.0
16577 }
16578}
16579
16580trait RowRangeExt {
16581 type Row;
16582
16583 fn len(&self) -> usize;
16584
16585 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16586}
16587
16588impl RowRangeExt for Range<MultiBufferRow> {
16589 type Row = MultiBufferRow;
16590
16591 fn len(&self) -> usize {
16592 (self.end.0 - self.start.0) as usize
16593 }
16594
16595 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16596 (self.start.0..self.end.0).map(MultiBufferRow)
16597 }
16598}
16599
16600impl RowRangeExt for Range<DisplayRow> {
16601 type Row = DisplayRow;
16602
16603 fn len(&self) -> usize {
16604 (self.end.0 - self.start.0) as usize
16605 }
16606
16607 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16608 (self.start.0..self.end.0).map(DisplayRow)
16609 }
16610}
16611
16612/// If select range has more than one line, we
16613/// just point the cursor to range.start.
16614fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16615 if range.start.row == range.end.row {
16616 range
16617 } else {
16618 range.start..range.start
16619 }
16620}
16621pub struct KillRing(ClipboardItem);
16622impl Global for KillRing {}
16623
16624const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16625
16626fn all_edits_insertions_or_deletions(
16627 edits: &Vec<(Range<Anchor>, String)>,
16628 snapshot: &MultiBufferSnapshot,
16629) -> bool {
16630 let mut all_insertions = true;
16631 let mut all_deletions = true;
16632
16633 for (range, new_text) in edits.iter() {
16634 let range_is_empty = range.to_offset(&snapshot).is_empty();
16635 let text_is_empty = new_text.is_empty();
16636
16637 if range_is_empty != text_is_empty {
16638 if range_is_empty {
16639 all_deletions = false;
16640 } else {
16641 all_insertions = false;
16642 }
16643 } else {
16644 return false;
16645 }
16646
16647 if !all_insertions && !all_deletions {
16648 return false;
16649 }
16650 }
16651 all_insertions || all_deletions
16652}