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::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use buffer_diff::DiffHunkSecondaryStatus;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{
63 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
64};
65pub use editor_settings_controls::*;
66use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
67pub use element::{
68 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
69};
70use futures::{future, FutureExt};
71use fuzzy::StringMatchCandidate;
72
73use code_context_menus::{
74 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
75 CompletionsMenu, ContextMenuOrigin,
76};
77use git::blame::GitBlame;
78use gpui::{
79 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
80 AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
81 ClipboardEntry, ClipboardItem, Context, DispatchPhase, ElementId, Entity, EntityInputHandler,
82 EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
83 HighlightStyle, Hsla, InteractiveText, KeyContext, Modifiers, MouseButton, MouseDownEvent,
84 PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription,
85 Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
86 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, DiskState, EditPredictionsMode, EditPreview,
100 HighlightedText, IndentKind, IndentSize, 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 snapshot: BufferSnapshot,
490 },
491}
492
493struct InlineCompletionState {
494 inlay_ids: Vec<InlayId>,
495 completion: InlineCompletion,
496 completion_id: Option<SharedString>,
497 invalidation_range: Range<Anchor>,
498}
499
500enum EditPredictionSettings {
501 Disabled,
502 Enabled {
503 show_in_menu: bool,
504 preview_requires_modifier: bool,
505 },
506}
507
508impl EditPredictionSettings {
509 pub fn is_enabled(&self) -> bool {
510 match self {
511 EditPredictionSettings::Disabled => false,
512 EditPredictionSettings::Enabled { .. } => true,
513 }
514 }
515}
516
517enum InlineCompletionHighlight {}
518
519pub enum MenuInlineCompletionsPolicy {
520 Never,
521 ByProvider,
522}
523
524pub enum EditPredictionPreview {
525 /// Modifier is not pressed
526 Inactive,
527 /// Modifier pressed
528 Active {
529 previous_scroll_position: Option<ScrollAnchor>,
530 },
531}
532
533#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
534struct EditorActionId(usize);
535
536impl EditorActionId {
537 pub fn post_inc(&mut self) -> Self {
538 let answer = self.0;
539
540 *self = Self(answer + 1);
541
542 Self(answer)
543 }
544}
545
546// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
547// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
548
549type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
550type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
551
552#[derive(Default)]
553struct ScrollbarMarkerState {
554 scrollbar_size: Size<Pixels>,
555 dirty: bool,
556 markers: Arc<[PaintQuad]>,
557 pending_refresh: Option<Task<Result<()>>>,
558}
559
560impl ScrollbarMarkerState {
561 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
562 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
563 }
564}
565
566#[derive(Clone, Debug)]
567struct RunnableTasks {
568 templates: Vec<(TaskSourceKind, TaskTemplate)>,
569 offset: MultiBufferOffset,
570 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
571 column: u32,
572 // Values of all named captures, including those starting with '_'
573 extra_variables: HashMap<String, String>,
574 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
575 context_range: Range<BufferOffset>,
576}
577
578impl RunnableTasks {
579 fn resolve<'a>(
580 &'a self,
581 cx: &'a task::TaskContext,
582 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
583 self.templates.iter().filter_map(|(kind, template)| {
584 template
585 .resolve_task(&kind.to_id_base(), cx)
586 .map(|task| (kind.clone(), task))
587 })
588 }
589}
590
591#[derive(Clone)]
592struct ResolvedTasks {
593 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
594 position: Anchor,
595}
596#[derive(Copy, Clone, Debug)]
597struct MultiBufferOffset(usize);
598#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
599struct BufferOffset(usize);
600
601// Addons allow storing per-editor state in other crates (e.g. Vim)
602pub trait Addon: 'static {
603 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
604
605 fn render_buffer_header_controls(
606 &self,
607 _: &ExcerptInfo,
608 _: &Window,
609 _: &App,
610 ) -> Option<AnyElement> {
611 None
612 }
613
614 fn to_any(&self) -> &dyn std::any::Any;
615}
616
617#[derive(Debug, Copy, Clone, PartialEq, Eq)]
618pub enum IsVimMode {
619 Yes,
620 No,
621}
622
623/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
624///
625/// See the [module level documentation](self) for more information.
626pub struct Editor {
627 focus_handle: FocusHandle,
628 last_focused_descendant: Option<WeakFocusHandle>,
629 /// The text buffer being edited
630 buffer: Entity<MultiBuffer>,
631 /// Map of how text in the buffer should be displayed.
632 /// Handles soft wraps, folds, fake inlay text insertions, etc.
633 pub display_map: Entity<DisplayMap>,
634 pub selections: SelectionsCollection,
635 pub scroll_manager: ScrollManager,
636 /// When inline assist editors are linked, they all render cursors because
637 /// typing enters text into each of them, even the ones that aren't focused.
638 pub(crate) show_cursor_when_unfocused: bool,
639 columnar_selection_tail: Option<Anchor>,
640 add_selections_state: Option<AddSelectionsState>,
641 select_next_state: Option<SelectNextState>,
642 select_prev_state: Option<SelectNextState>,
643 selection_history: SelectionHistory,
644 autoclose_regions: Vec<AutocloseRegion>,
645 snippet_stack: InvalidationStack<SnippetState>,
646 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
647 ime_transaction: Option<TransactionId>,
648 active_diagnostics: Option<ActiveDiagnosticGroup>,
649 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
650
651 // TODO: make this a access method
652 pub project: Option<Entity<Project>>,
653 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
654 completion_provider: Option<Box<dyn CompletionProvider>>,
655 collaboration_hub: Option<Box<dyn CollaborationHub>>,
656 blink_manager: Entity<BlinkManager>,
657 show_cursor_names: bool,
658 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
659 pub show_local_selections: bool,
660 mode: EditorMode,
661 show_breadcrumbs: bool,
662 show_gutter: bool,
663 show_scrollbars: bool,
664 show_line_numbers: Option<bool>,
665 use_relative_line_numbers: Option<bool>,
666 show_git_diff_gutter: Option<bool>,
667 show_code_actions: Option<bool>,
668 show_runnables: Option<bool>,
669 show_wrap_guides: Option<bool>,
670 show_indent_guides: Option<bool>,
671 placeholder_text: Option<Arc<str>>,
672 highlight_order: usize,
673 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
674 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
675 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
676 scrollbar_marker_state: ScrollbarMarkerState,
677 active_indent_guides_state: ActiveIndentGuidesState,
678 nav_history: Option<ItemNavHistory>,
679 context_menu: RefCell<Option<CodeContextMenu>>,
680 mouse_context_menu: Option<MouseContextMenu>,
681 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
682 signature_help_state: SignatureHelpState,
683 auto_signature_help: Option<bool>,
684 find_all_references_task_sources: Vec<Anchor>,
685 next_completion_id: CompletionId,
686 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
687 code_actions_task: Option<Task<Result<()>>>,
688 document_highlights_task: Option<Task<()>>,
689 linked_editing_range_task: Option<Task<Option<()>>>,
690 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
691 pending_rename: Option<RenameState>,
692 searchable: bool,
693 cursor_shape: CursorShape,
694 current_line_highlight: Option<CurrentLineHighlight>,
695 collapse_matches: bool,
696 autoindent_mode: Option<AutoindentMode>,
697 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
698 input_enabled: bool,
699 use_modal_editing: bool,
700 read_only: bool,
701 leader_peer_id: Option<PeerId>,
702 remote_id: Option<ViewId>,
703 hover_state: HoverState,
704 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
705 gutter_hovered: bool,
706 hovered_link_state: Option<HoveredLinkState>,
707 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
708 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
709 active_inline_completion: Option<InlineCompletionState>,
710 /// Used to prevent flickering as the user types while the menu is open
711 stale_inline_completion_in_menu: Option<InlineCompletionState>,
712 edit_prediction_settings: EditPredictionSettings,
713 inline_completions_hidden_for_vim_mode: bool,
714 show_inline_completions_override: Option<bool>,
715 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
716 edit_prediction_preview: EditPredictionPreview,
717 edit_prediction_cursor_on_leading_whitespace: bool,
718 edit_prediction_requires_modifier_in_leading_space: bool,
719 inlay_hint_cache: InlayHintCache,
720 next_inlay_id: usize,
721 _subscriptions: Vec<Subscription>,
722 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
723 gutter_dimensions: GutterDimensions,
724 style: Option<EditorStyle>,
725 text_style_refinement: Option<TextStyleRefinement>,
726 next_editor_action_id: EditorActionId,
727 editor_actions:
728 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
729 use_autoclose: bool,
730 use_auto_surround: bool,
731 auto_replace_emoji_shortcode: bool,
732 show_git_blame_gutter: bool,
733 show_git_blame_inline: bool,
734 show_git_blame_inline_delay_task: Option<Task<()>>,
735 distinguish_unstaged_diff_hunks: bool,
736 git_blame_inline_enabled: bool,
737 serialize_dirty_buffers: bool,
738 show_selection_menu: Option<bool>,
739 blame: Option<Entity<GitBlame>>,
740 blame_subscription: Option<Subscription>,
741 custom_context_menu: Option<
742 Box<
743 dyn 'static
744 + Fn(
745 &mut Self,
746 DisplayPoint,
747 &mut Window,
748 &mut Context<Self>,
749 ) -> Option<Entity<ui::ContextMenu>>,
750 >,
751 >,
752 last_bounds: Option<Bounds<Pixels>>,
753 last_position_map: Option<Rc<PositionMap>>,
754 expect_bounds_change: Option<Bounds<Pixels>>,
755 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
756 tasks_update_task: Option<Task<()>>,
757 in_project_search: bool,
758 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
759 breadcrumb_header: Option<String>,
760 focused_block: Option<FocusedBlock>,
761 next_scroll_position: NextScrollCursorCenterTopBottom,
762 addons: HashMap<TypeId, Box<dyn Addon>>,
763 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
764 selection_mark_mode: bool,
765 toggle_fold_multiple_buffers: Task<()>,
766 _scroll_cursor_center_top_bottom_task: Task<()>,
767}
768
769#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
770enum NextScrollCursorCenterTopBottom {
771 #[default]
772 Center,
773 Top,
774 Bottom,
775}
776
777impl NextScrollCursorCenterTopBottom {
778 fn next(&self) -> Self {
779 match self {
780 Self::Center => Self::Top,
781 Self::Top => Self::Bottom,
782 Self::Bottom => Self::Center,
783 }
784 }
785}
786
787#[derive(Clone)]
788pub struct EditorSnapshot {
789 pub mode: EditorMode,
790 show_gutter: bool,
791 show_line_numbers: Option<bool>,
792 show_git_diff_gutter: Option<bool>,
793 show_code_actions: Option<bool>,
794 show_runnables: Option<bool>,
795 git_blame_gutter_max_author_length: Option<usize>,
796 pub display_snapshot: DisplaySnapshot,
797 pub placeholder_text: Option<Arc<str>>,
798 is_focused: bool,
799 scroll_anchor: ScrollAnchor,
800 ongoing_scroll: OngoingScroll,
801 current_line_highlight: CurrentLineHighlight,
802 gutter_hovered: bool,
803}
804
805const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
806
807#[derive(Default, Debug, Clone, Copy)]
808pub struct GutterDimensions {
809 pub left_padding: Pixels,
810 pub right_padding: Pixels,
811 pub width: Pixels,
812 pub margin: Pixels,
813 pub git_blame_entries_width: Option<Pixels>,
814}
815
816impl GutterDimensions {
817 /// The full width of the space taken up by the gutter.
818 pub fn full_width(&self) -> Pixels {
819 self.margin + self.width
820 }
821
822 /// The width of the space reserved for the fold indicators,
823 /// use alongside 'justify_end' and `gutter_width` to
824 /// right align content with the line numbers
825 pub fn fold_area_width(&self) -> Pixels {
826 self.margin + self.right_padding
827 }
828}
829
830#[derive(Debug)]
831pub struct RemoteSelection {
832 pub replica_id: ReplicaId,
833 pub selection: Selection<Anchor>,
834 pub cursor_shape: CursorShape,
835 pub peer_id: PeerId,
836 pub line_mode: bool,
837 pub participant_index: Option<ParticipantIndex>,
838 pub user_name: Option<SharedString>,
839}
840
841#[derive(Clone, Debug)]
842struct SelectionHistoryEntry {
843 selections: Arc<[Selection<Anchor>]>,
844 select_next_state: Option<SelectNextState>,
845 select_prev_state: Option<SelectNextState>,
846 add_selections_state: Option<AddSelectionsState>,
847}
848
849enum SelectionHistoryMode {
850 Normal,
851 Undoing,
852 Redoing,
853}
854
855#[derive(Clone, PartialEq, Eq, Hash)]
856struct HoveredCursor {
857 replica_id: u16,
858 selection_id: usize,
859}
860
861impl Default for SelectionHistoryMode {
862 fn default() -> Self {
863 Self::Normal
864 }
865}
866
867#[derive(Default)]
868struct SelectionHistory {
869 #[allow(clippy::type_complexity)]
870 selections_by_transaction:
871 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
872 mode: SelectionHistoryMode,
873 undo_stack: VecDeque<SelectionHistoryEntry>,
874 redo_stack: VecDeque<SelectionHistoryEntry>,
875}
876
877impl SelectionHistory {
878 fn insert_transaction(
879 &mut self,
880 transaction_id: TransactionId,
881 selections: Arc<[Selection<Anchor>]>,
882 ) {
883 self.selections_by_transaction
884 .insert(transaction_id, (selections, None));
885 }
886
887 #[allow(clippy::type_complexity)]
888 fn transaction(
889 &self,
890 transaction_id: TransactionId,
891 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
892 self.selections_by_transaction.get(&transaction_id)
893 }
894
895 #[allow(clippy::type_complexity)]
896 fn transaction_mut(
897 &mut self,
898 transaction_id: TransactionId,
899 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
900 self.selections_by_transaction.get_mut(&transaction_id)
901 }
902
903 fn push(&mut self, entry: SelectionHistoryEntry) {
904 if !entry.selections.is_empty() {
905 match self.mode {
906 SelectionHistoryMode::Normal => {
907 self.push_undo(entry);
908 self.redo_stack.clear();
909 }
910 SelectionHistoryMode::Undoing => self.push_redo(entry),
911 SelectionHistoryMode::Redoing => self.push_undo(entry),
912 }
913 }
914 }
915
916 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
917 if self
918 .undo_stack
919 .back()
920 .map_or(true, |e| e.selections != entry.selections)
921 {
922 self.undo_stack.push_back(entry);
923 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
924 self.undo_stack.pop_front();
925 }
926 }
927 }
928
929 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
930 if self
931 .redo_stack
932 .back()
933 .map_or(true, |e| e.selections != entry.selections)
934 {
935 self.redo_stack.push_back(entry);
936 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
937 self.redo_stack.pop_front();
938 }
939 }
940 }
941}
942
943struct RowHighlight {
944 index: usize,
945 range: Range<Anchor>,
946 color: Hsla,
947 should_autoscroll: bool,
948}
949
950#[derive(Clone, Debug)]
951struct AddSelectionsState {
952 above: bool,
953 stack: Vec<usize>,
954}
955
956#[derive(Clone)]
957struct SelectNextState {
958 query: AhoCorasick,
959 wordwise: bool,
960 done: bool,
961}
962
963impl std::fmt::Debug for SelectNextState {
964 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
965 f.debug_struct(std::any::type_name::<Self>())
966 .field("wordwise", &self.wordwise)
967 .field("done", &self.done)
968 .finish()
969 }
970}
971
972#[derive(Debug)]
973struct AutocloseRegion {
974 selection_id: usize,
975 range: Range<Anchor>,
976 pair: BracketPair,
977}
978
979#[derive(Debug)]
980struct SnippetState {
981 ranges: Vec<Vec<Range<Anchor>>>,
982 active_index: usize,
983 choices: Vec<Option<Vec<String>>>,
984}
985
986#[doc(hidden)]
987pub struct RenameState {
988 pub range: Range<Anchor>,
989 pub old_name: Arc<str>,
990 pub editor: Entity<Editor>,
991 block_id: CustomBlockId,
992}
993
994struct InvalidationStack<T>(Vec<T>);
995
996struct RegisteredInlineCompletionProvider {
997 provider: Arc<dyn InlineCompletionProviderHandle>,
998 _subscription: Subscription,
999}
1000
1001#[derive(Debug)]
1002struct ActiveDiagnosticGroup {
1003 primary_range: Range<Anchor>,
1004 primary_message: String,
1005 group_id: usize,
1006 blocks: HashMap<CustomBlockId, Diagnostic>,
1007 is_valid: bool,
1008}
1009
1010#[derive(Serialize, Deserialize, Clone, Debug)]
1011pub struct ClipboardSelection {
1012 pub len: usize,
1013 pub is_entire_line: bool,
1014 pub first_line_indent: u32,
1015}
1016
1017#[derive(Debug)]
1018pub(crate) struct NavigationData {
1019 cursor_anchor: Anchor,
1020 cursor_position: Point,
1021 scroll_anchor: ScrollAnchor,
1022 scroll_top_row: u32,
1023}
1024
1025#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1026pub enum GotoDefinitionKind {
1027 Symbol,
1028 Declaration,
1029 Type,
1030 Implementation,
1031}
1032
1033#[derive(Debug, Clone)]
1034enum InlayHintRefreshReason {
1035 Toggle(bool),
1036 SettingsChange(InlayHintSettings),
1037 NewLinesShown,
1038 BufferEdited(HashSet<Arc<Language>>),
1039 RefreshRequested,
1040 ExcerptsRemoved(Vec<ExcerptId>),
1041}
1042
1043impl InlayHintRefreshReason {
1044 fn description(&self) -> &'static str {
1045 match self {
1046 Self::Toggle(_) => "toggle",
1047 Self::SettingsChange(_) => "settings change",
1048 Self::NewLinesShown => "new lines shown",
1049 Self::BufferEdited(_) => "buffer edited",
1050 Self::RefreshRequested => "refresh requested",
1051 Self::ExcerptsRemoved(_) => "excerpts removed",
1052 }
1053 }
1054}
1055
1056pub enum FormatTarget {
1057 Buffers,
1058 Ranges(Vec<Range<MultiBufferPoint>>),
1059}
1060
1061pub(crate) struct FocusedBlock {
1062 id: BlockId,
1063 focus_handle: WeakFocusHandle,
1064}
1065
1066#[derive(Clone)]
1067enum JumpData {
1068 MultiBufferRow {
1069 row: MultiBufferRow,
1070 line_offset_from_top: u32,
1071 },
1072 MultiBufferPoint {
1073 excerpt_id: ExcerptId,
1074 position: Point,
1075 anchor: text::Anchor,
1076 line_offset_from_top: u32,
1077 },
1078}
1079
1080pub enum MultibufferSelectionMode {
1081 First,
1082 All,
1083}
1084
1085impl Editor {
1086 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1087 let buffer = cx.new(|cx| Buffer::local("", cx));
1088 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1089 Self::new(
1090 EditorMode::SingleLine { auto_width: false },
1091 buffer,
1092 None,
1093 false,
1094 window,
1095 cx,
1096 )
1097 }
1098
1099 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1100 let buffer = cx.new(|cx| Buffer::local("", cx));
1101 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1102 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1103 }
1104
1105 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1106 let buffer = cx.new(|cx| Buffer::local("", cx));
1107 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1108 Self::new(
1109 EditorMode::SingleLine { auto_width: true },
1110 buffer,
1111 None,
1112 false,
1113 window,
1114 cx,
1115 )
1116 }
1117
1118 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1119 let buffer = cx.new(|cx| Buffer::local("", cx));
1120 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1121 Self::new(
1122 EditorMode::AutoHeight { max_lines },
1123 buffer,
1124 None,
1125 false,
1126 window,
1127 cx,
1128 )
1129 }
1130
1131 pub fn for_buffer(
1132 buffer: Entity<Buffer>,
1133 project: Option<Entity<Project>>,
1134 window: &mut Window,
1135 cx: &mut Context<Self>,
1136 ) -> Self {
1137 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1138 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1139 }
1140
1141 pub fn for_multibuffer(
1142 buffer: Entity<MultiBuffer>,
1143 project: Option<Entity<Project>>,
1144 show_excerpt_controls: bool,
1145 window: &mut Window,
1146 cx: &mut Context<Self>,
1147 ) -> Self {
1148 Self::new(
1149 EditorMode::Full,
1150 buffer,
1151 project,
1152 show_excerpt_controls,
1153 window,
1154 cx,
1155 )
1156 }
1157
1158 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1159 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1160 let mut clone = Self::new(
1161 self.mode,
1162 self.buffer.clone(),
1163 self.project.clone(),
1164 show_excerpt_controls,
1165 window,
1166 cx,
1167 );
1168 self.display_map.update(cx, |display_map, cx| {
1169 let snapshot = display_map.snapshot(cx);
1170 clone.display_map.update(cx, |display_map, cx| {
1171 display_map.set_state(&snapshot, cx);
1172 });
1173 });
1174 clone.selections.clone_state(&self.selections);
1175 clone.scroll_manager.clone_state(&self.scroll_manager);
1176 clone.searchable = self.searchable;
1177 clone
1178 }
1179
1180 pub fn new(
1181 mode: EditorMode,
1182 buffer: Entity<MultiBuffer>,
1183 project: Option<Entity<Project>>,
1184 show_excerpt_controls: bool,
1185 window: &mut Window,
1186 cx: &mut Context<Self>,
1187 ) -> Self {
1188 let style = window.text_style();
1189 let font_size = style.font_size.to_pixels(window.rem_size());
1190 let editor = cx.entity().downgrade();
1191 let fold_placeholder = FoldPlaceholder {
1192 constrain_width: true,
1193 render: Arc::new(move |fold_id, fold_range, _, cx| {
1194 let editor = editor.clone();
1195 div()
1196 .id(fold_id)
1197 .bg(cx.theme().colors().ghost_element_background)
1198 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1199 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1200 .rounded_sm()
1201 .size_full()
1202 .cursor_pointer()
1203 .child("⋯")
1204 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1205 .on_click(move |_, _window, cx| {
1206 editor
1207 .update(cx, |editor, cx| {
1208 editor.unfold_ranges(
1209 &[fold_range.start..fold_range.end],
1210 true,
1211 false,
1212 cx,
1213 );
1214 cx.stop_propagation();
1215 })
1216 .ok();
1217 })
1218 .into_any()
1219 }),
1220 merge_adjacent: true,
1221 ..Default::default()
1222 };
1223 let display_map = cx.new(|cx| {
1224 DisplayMap::new(
1225 buffer.clone(),
1226 style.font(),
1227 font_size,
1228 None,
1229 show_excerpt_controls,
1230 FILE_HEADER_HEIGHT,
1231 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1232 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1233 fold_placeholder,
1234 cx,
1235 )
1236 });
1237
1238 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1239
1240 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1241
1242 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1243 .then(|| language_settings::SoftWrap::None);
1244
1245 let mut project_subscriptions = Vec::new();
1246 if mode == EditorMode::Full {
1247 if let Some(project) = project.as_ref() {
1248 if buffer.read(cx).is_singleton() {
1249 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1250 cx.emit(EditorEvent::TitleChanged);
1251 }));
1252 }
1253 project_subscriptions.push(cx.subscribe_in(
1254 project,
1255 window,
1256 |editor, _, event, window, cx| {
1257 if let project::Event::RefreshInlayHints = event {
1258 editor
1259 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1260 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1261 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1262 let focus_handle = editor.focus_handle(cx);
1263 if focus_handle.is_focused(window) {
1264 let snapshot = buffer.read(cx).snapshot();
1265 for (range, snippet) in snippet_edits {
1266 let editor_range =
1267 language::range_from_lsp(*range).to_offset(&snapshot);
1268 editor
1269 .insert_snippet(
1270 &[editor_range],
1271 snippet.clone(),
1272 window,
1273 cx,
1274 )
1275 .ok();
1276 }
1277 }
1278 }
1279 }
1280 },
1281 ));
1282 if let Some(task_inventory) = project
1283 .read(cx)
1284 .task_store()
1285 .read(cx)
1286 .task_inventory()
1287 .cloned()
1288 {
1289 project_subscriptions.push(cx.observe_in(
1290 &task_inventory,
1291 window,
1292 |editor, _, window, cx| {
1293 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1294 },
1295 ));
1296 }
1297 }
1298 }
1299
1300 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1301
1302 let inlay_hint_settings =
1303 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1304 let focus_handle = cx.focus_handle();
1305 cx.on_focus(&focus_handle, window, Self::handle_focus)
1306 .detach();
1307 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1308 .detach();
1309 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1310 .detach();
1311 cx.on_blur(&focus_handle, window, Self::handle_blur)
1312 .detach();
1313
1314 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1315 Some(false)
1316 } else {
1317 None
1318 };
1319
1320 let mut code_action_providers = Vec::new();
1321 if let Some(project) = project.clone() {
1322 get_uncommitted_diff_for_buffer(
1323 &project,
1324 buffer.read(cx).all_buffers(),
1325 buffer.clone(),
1326 cx,
1327 );
1328 code_action_providers.push(Rc::new(project) as Rc<_>);
1329 }
1330
1331 let mut this = Self {
1332 focus_handle,
1333 show_cursor_when_unfocused: false,
1334 last_focused_descendant: None,
1335 buffer: buffer.clone(),
1336 display_map: display_map.clone(),
1337 selections,
1338 scroll_manager: ScrollManager::new(cx),
1339 columnar_selection_tail: None,
1340 add_selections_state: None,
1341 select_next_state: None,
1342 select_prev_state: None,
1343 selection_history: Default::default(),
1344 autoclose_regions: Default::default(),
1345 snippet_stack: Default::default(),
1346 select_larger_syntax_node_stack: Vec::new(),
1347 ime_transaction: Default::default(),
1348 active_diagnostics: None,
1349 soft_wrap_mode_override,
1350 completion_provider: project.clone().map(|project| Box::new(project) as _),
1351 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1352 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1353 project,
1354 blink_manager: blink_manager.clone(),
1355 show_local_selections: true,
1356 show_scrollbars: true,
1357 mode,
1358 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1359 show_gutter: mode == EditorMode::Full,
1360 show_line_numbers: None,
1361 use_relative_line_numbers: None,
1362 show_git_diff_gutter: None,
1363 show_code_actions: None,
1364 show_runnables: None,
1365 show_wrap_guides: None,
1366 show_indent_guides,
1367 placeholder_text: None,
1368 highlight_order: 0,
1369 highlighted_rows: HashMap::default(),
1370 background_highlights: Default::default(),
1371 gutter_highlights: TreeMap::default(),
1372 scrollbar_marker_state: ScrollbarMarkerState::default(),
1373 active_indent_guides_state: ActiveIndentGuidesState::default(),
1374 nav_history: None,
1375 context_menu: RefCell::new(None),
1376 mouse_context_menu: None,
1377 completion_tasks: Default::default(),
1378 signature_help_state: SignatureHelpState::default(),
1379 auto_signature_help: None,
1380 find_all_references_task_sources: Vec::new(),
1381 next_completion_id: 0,
1382 next_inlay_id: 0,
1383 code_action_providers,
1384 available_code_actions: Default::default(),
1385 code_actions_task: Default::default(),
1386 document_highlights_task: Default::default(),
1387 linked_editing_range_task: Default::default(),
1388 pending_rename: Default::default(),
1389 searchable: true,
1390 cursor_shape: EditorSettings::get_global(cx)
1391 .cursor_shape
1392 .unwrap_or_default(),
1393 current_line_highlight: None,
1394 autoindent_mode: Some(AutoindentMode::EachLine),
1395 collapse_matches: false,
1396 workspace: None,
1397 input_enabled: true,
1398 use_modal_editing: mode == EditorMode::Full,
1399 read_only: false,
1400 use_autoclose: true,
1401 use_auto_surround: true,
1402 auto_replace_emoji_shortcode: false,
1403 leader_peer_id: None,
1404 remote_id: None,
1405 hover_state: Default::default(),
1406 pending_mouse_down: None,
1407 hovered_link_state: Default::default(),
1408 edit_prediction_provider: None,
1409 active_inline_completion: None,
1410 stale_inline_completion_in_menu: None,
1411 edit_prediction_preview: EditPredictionPreview::Inactive,
1412 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1413
1414 gutter_hovered: false,
1415 pixel_position_of_newest_cursor: None,
1416 last_bounds: None,
1417 last_position_map: None,
1418 expect_bounds_change: None,
1419 gutter_dimensions: GutterDimensions::default(),
1420 style: None,
1421 show_cursor_names: false,
1422 hovered_cursors: Default::default(),
1423 next_editor_action_id: EditorActionId::default(),
1424 editor_actions: Rc::default(),
1425 inline_completions_hidden_for_vim_mode: false,
1426 show_inline_completions_override: None,
1427 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1428 edit_prediction_settings: EditPredictionSettings::Disabled,
1429 edit_prediction_cursor_on_leading_whitespace: false,
1430 edit_prediction_requires_modifier_in_leading_space: true,
1431 custom_context_menu: None,
1432 show_git_blame_gutter: false,
1433 show_git_blame_inline: false,
1434 distinguish_unstaged_diff_hunks: false,
1435 show_selection_menu: None,
1436 show_git_blame_inline_delay_task: None,
1437 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1438 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1439 .session
1440 .restore_unsaved_buffers,
1441 blame: None,
1442 blame_subscription: None,
1443 tasks: Default::default(),
1444 _subscriptions: vec![
1445 cx.observe(&buffer, Self::on_buffer_changed),
1446 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1447 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1448 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1449 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1450 cx.observe_window_activation(window, |editor, window, cx| {
1451 let active = window.is_window_active();
1452 editor.blink_manager.update(cx, |blink_manager, cx| {
1453 if active {
1454 blink_manager.enable(cx);
1455 } else {
1456 blink_manager.disable(cx);
1457 }
1458 });
1459 }),
1460 ],
1461 tasks_update_task: None,
1462 linked_edit_ranges: Default::default(),
1463 in_project_search: false,
1464 previous_search_ranges: None,
1465 breadcrumb_header: None,
1466 focused_block: None,
1467 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1468 addons: HashMap::default(),
1469 registered_buffers: HashMap::default(),
1470 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1471 selection_mark_mode: false,
1472 toggle_fold_multiple_buffers: Task::ready(()),
1473 text_style_refinement: None,
1474 };
1475 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1476 this._subscriptions.extend(project_subscriptions);
1477
1478 this.end_selection(window, cx);
1479 this.scroll_manager.show_scrollbar(window, cx);
1480
1481 if mode == EditorMode::Full {
1482 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1483 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1484
1485 if this.git_blame_inline_enabled {
1486 this.git_blame_inline_enabled = true;
1487 this.start_git_blame_inline(false, window, cx);
1488 }
1489
1490 if let Some(buffer) = buffer.read(cx).as_singleton() {
1491 if let Some(project) = this.project.as_ref() {
1492 let lsp_store = project.read(cx).lsp_store();
1493 let handle = lsp_store.update(cx, |lsp_store, cx| {
1494 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1495 });
1496 this.registered_buffers
1497 .insert(buffer.read(cx).remote_id(), handle);
1498 }
1499 }
1500 }
1501
1502 this.report_editor_event("Editor Opened", None, cx);
1503 this
1504 }
1505
1506 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1507 self.mouse_context_menu
1508 .as_ref()
1509 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1510 }
1511
1512 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1513 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1514 }
1515
1516 fn key_context_internal(
1517 &self,
1518 has_active_edit_prediction: bool,
1519 window: &Window,
1520 cx: &App,
1521 ) -> KeyContext {
1522 let mut key_context = KeyContext::new_with_defaults();
1523 key_context.add("Editor");
1524 let mode = match self.mode {
1525 EditorMode::SingleLine { .. } => "single_line",
1526 EditorMode::AutoHeight { .. } => "auto_height",
1527 EditorMode::Full => "full",
1528 };
1529
1530 if EditorSettings::jupyter_enabled(cx) {
1531 key_context.add("jupyter");
1532 }
1533
1534 key_context.set("mode", mode);
1535 if self.pending_rename.is_some() {
1536 key_context.add("renaming");
1537 }
1538
1539 let mut showing_completions = false;
1540
1541 match self.context_menu.borrow().as_ref() {
1542 Some(CodeContextMenu::Completions(_)) => {
1543 key_context.add("menu");
1544 key_context.add("showing_completions");
1545 showing_completions = true;
1546 }
1547 Some(CodeContextMenu::CodeActions(_)) => {
1548 key_context.add("menu");
1549 key_context.add("showing_code_actions")
1550 }
1551 None => {}
1552 }
1553
1554 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1555 if !self.focus_handle(cx).contains_focused(window, cx)
1556 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1557 {
1558 for addon in self.addons.values() {
1559 addon.extend_key_context(&mut key_context, cx)
1560 }
1561 }
1562
1563 if let Some(extension) = self
1564 .buffer
1565 .read(cx)
1566 .as_singleton()
1567 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1568 {
1569 key_context.set("extension", extension.to_string());
1570 }
1571
1572 if has_active_edit_prediction {
1573 key_context.add("copilot_suggestion");
1574 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1575 if showing_completions
1576 || self.edit_prediction_requires_modifier()
1577 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1578 // bindings to insert tab characters.
1579 || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
1580 {
1581 key_context.add(EDIT_PREDICTION_REQUIRES_MODIFIER_KEY_CONTEXT);
1582 }
1583 }
1584
1585 if self.selection_mark_mode {
1586 key_context.add("selection_mode");
1587 }
1588
1589 key_context
1590 }
1591
1592 pub fn accept_edit_prediction_keybind(
1593 &self,
1594 window: &Window,
1595 cx: &App,
1596 ) -> AcceptEditPredictionBinding {
1597 let key_context = self.key_context_internal(true, window, cx);
1598 AcceptEditPredictionBinding(
1599 window
1600 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1601 .into_iter()
1602 .rev()
1603 .next(),
1604 )
1605 }
1606
1607 pub fn new_file(
1608 workspace: &mut Workspace,
1609 _: &workspace::NewFile,
1610 window: &mut Window,
1611 cx: &mut Context<Workspace>,
1612 ) {
1613 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1614 "Failed to create buffer",
1615 window,
1616 cx,
1617 |e, _, _| match e.error_code() {
1618 ErrorCode::RemoteUpgradeRequired => Some(format!(
1619 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1620 e.error_tag("required").unwrap_or("the latest version")
1621 )),
1622 _ => None,
1623 },
1624 );
1625 }
1626
1627 pub fn new_in_workspace(
1628 workspace: &mut Workspace,
1629 window: &mut Window,
1630 cx: &mut Context<Workspace>,
1631 ) -> Task<Result<Entity<Editor>>> {
1632 let project = workspace.project().clone();
1633 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1634
1635 cx.spawn_in(window, |workspace, mut cx| async move {
1636 let buffer = create.await?;
1637 workspace.update_in(&mut cx, |workspace, window, cx| {
1638 let editor =
1639 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1640 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1641 editor
1642 })
1643 })
1644 }
1645
1646 fn new_file_vertical(
1647 workspace: &mut Workspace,
1648 _: &workspace::NewFileSplitVertical,
1649 window: &mut Window,
1650 cx: &mut Context<Workspace>,
1651 ) {
1652 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1653 }
1654
1655 fn new_file_horizontal(
1656 workspace: &mut Workspace,
1657 _: &workspace::NewFileSplitHorizontal,
1658 window: &mut Window,
1659 cx: &mut Context<Workspace>,
1660 ) {
1661 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1662 }
1663
1664 fn new_file_in_direction(
1665 workspace: &mut Workspace,
1666 direction: SplitDirection,
1667 window: &mut Window,
1668 cx: &mut Context<Workspace>,
1669 ) {
1670 let project = workspace.project().clone();
1671 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1672
1673 cx.spawn_in(window, |workspace, mut cx| async move {
1674 let buffer = create.await?;
1675 workspace.update_in(&mut cx, move |workspace, window, cx| {
1676 workspace.split_item(
1677 direction,
1678 Box::new(
1679 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1680 ),
1681 window,
1682 cx,
1683 )
1684 })?;
1685 anyhow::Ok(())
1686 })
1687 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1688 match e.error_code() {
1689 ErrorCode::RemoteUpgradeRequired => Some(format!(
1690 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1691 e.error_tag("required").unwrap_or("the latest version")
1692 )),
1693 _ => None,
1694 }
1695 });
1696 }
1697
1698 pub fn leader_peer_id(&self) -> Option<PeerId> {
1699 self.leader_peer_id
1700 }
1701
1702 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1703 &self.buffer
1704 }
1705
1706 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1707 self.workspace.as_ref()?.0.upgrade()
1708 }
1709
1710 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1711 self.buffer().read(cx).title(cx)
1712 }
1713
1714 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1715 let git_blame_gutter_max_author_length = self
1716 .render_git_blame_gutter(cx)
1717 .then(|| {
1718 if let Some(blame) = self.blame.as_ref() {
1719 let max_author_length =
1720 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1721 Some(max_author_length)
1722 } else {
1723 None
1724 }
1725 })
1726 .flatten();
1727
1728 EditorSnapshot {
1729 mode: self.mode,
1730 show_gutter: self.show_gutter,
1731 show_line_numbers: self.show_line_numbers,
1732 show_git_diff_gutter: self.show_git_diff_gutter,
1733 show_code_actions: self.show_code_actions,
1734 show_runnables: self.show_runnables,
1735 git_blame_gutter_max_author_length,
1736 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1737 scroll_anchor: self.scroll_manager.anchor(),
1738 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1739 placeholder_text: self.placeholder_text.clone(),
1740 is_focused: self.focus_handle.is_focused(window),
1741 current_line_highlight: self
1742 .current_line_highlight
1743 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1744 gutter_hovered: self.gutter_hovered,
1745 }
1746 }
1747
1748 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1749 self.buffer.read(cx).language_at(point, cx)
1750 }
1751
1752 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1753 self.buffer.read(cx).read(cx).file_at(point).cloned()
1754 }
1755
1756 pub fn active_excerpt(
1757 &self,
1758 cx: &App,
1759 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1760 self.buffer
1761 .read(cx)
1762 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1763 }
1764
1765 pub fn mode(&self) -> EditorMode {
1766 self.mode
1767 }
1768
1769 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1770 self.collaboration_hub.as_deref()
1771 }
1772
1773 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1774 self.collaboration_hub = Some(hub);
1775 }
1776
1777 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1778 self.in_project_search = in_project_search;
1779 }
1780
1781 pub fn set_custom_context_menu(
1782 &mut self,
1783 f: impl 'static
1784 + Fn(
1785 &mut Self,
1786 DisplayPoint,
1787 &mut Window,
1788 &mut Context<Self>,
1789 ) -> Option<Entity<ui::ContextMenu>>,
1790 ) {
1791 self.custom_context_menu = Some(Box::new(f))
1792 }
1793
1794 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1795 self.completion_provider = provider;
1796 }
1797
1798 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1799 self.semantics_provider.clone()
1800 }
1801
1802 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1803 self.semantics_provider = provider;
1804 }
1805
1806 pub fn set_edit_prediction_provider<T>(
1807 &mut self,
1808 provider: Option<Entity<T>>,
1809 window: &mut Window,
1810 cx: &mut Context<Self>,
1811 ) where
1812 T: EditPredictionProvider,
1813 {
1814 self.edit_prediction_provider =
1815 provider.map(|provider| RegisteredInlineCompletionProvider {
1816 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1817 if this.focus_handle.is_focused(window) {
1818 this.update_visible_inline_completion(window, cx);
1819 }
1820 }),
1821 provider: Arc::new(provider),
1822 });
1823 self.refresh_inline_completion(false, false, window, cx);
1824 }
1825
1826 pub fn placeholder_text(&self) -> Option<&str> {
1827 self.placeholder_text.as_deref()
1828 }
1829
1830 pub fn set_placeholder_text(
1831 &mut self,
1832 placeholder_text: impl Into<Arc<str>>,
1833 cx: &mut Context<Self>,
1834 ) {
1835 let placeholder_text = Some(placeholder_text.into());
1836 if self.placeholder_text != placeholder_text {
1837 self.placeholder_text = placeholder_text;
1838 cx.notify();
1839 }
1840 }
1841
1842 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1843 self.cursor_shape = cursor_shape;
1844
1845 // Disrupt blink for immediate user feedback that the cursor shape has changed
1846 self.blink_manager.update(cx, BlinkManager::show_cursor);
1847
1848 cx.notify();
1849 }
1850
1851 pub fn set_current_line_highlight(
1852 &mut self,
1853 current_line_highlight: Option<CurrentLineHighlight>,
1854 ) {
1855 self.current_line_highlight = current_line_highlight;
1856 }
1857
1858 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1859 self.collapse_matches = collapse_matches;
1860 }
1861
1862 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1863 let buffers = self.buffer.read(cx).all_buffers();
1864 let Some(lsp_store) = self.lsp_store(cx) else {
1865 return;
1866 };
1867 lsp_store.update(cx, |lsp_store, cx| {
1868 for buffer in buffers {
1869 self.registered_buffers
1870 .entry(buffer.read(cx).remote_id())
1871 .or_insert_with(|| {
1872 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1873 });
1874 }
1875 })
1876 }
1877
1878 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1879 if self.collapse_matches {
1880 return range.start..range.start;
1881 }
1882 range.clone()
1883 }
1884
1885 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1886 if self.display_map.read(cx).clip_at_line_ends != clip {
1887 self.display_map
1888 .update(cx, |map, _| map.clip_at_line_ends = clip);
1889 }
1890 }
1891
1892 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1893 self.input_enabled = input_enabled;
1894 }
1895
1896 pub fn set_inline_completions_hidden_for_vim_mode(
1897 &mut self,
1898 hidden: bool,
1899 window: &mut Window,
1900 cx: &mut Context<Self>,
1901 ) {
1902 if hidden != self.inline_completions_hidden_for_vim_mode {
1903 self.inline_completions_hidden_for_vim_mode = hidden;
1904 if hidden {
1905 self.update_visible_inline_completion(window, cx);
1906 } else {
1907 self.refresh_inline_completion(true, false, window, cx);
1908 }
1909 }
1910 }
1911
1912 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1913 self.menu_inline_completions_policy = value;
1914 }
1915
1916 pub fn set_autoindent(&mut self, autoindent: bool) {
1917 if autoindent {
1918 self.autoindent_mode = Some(AutoindentMode::EachLine);
1919 } else {
1920 self.autoindent_mode = None;
1921 }
1922 }
1923
1924 pub fn read_only(&self, cx: &App) -> bool {
1925 self.read_only || self.buffer.read(cx).read_only()
1926 }
1927
1928 pub fn set_read_only(&mut self, read_only: bool) {
1929 self.read_only = read_only;
1930 }
1931
1932 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1933 self.use_autoclose = autoclose;
1934 }
1935
1936 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1937 self.use_auto_surround = auto_surround;
1938 }
1939
1940 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1941 self.auto_replace_emoji_shortcode = auto_replace;
1942 }
1943
1944 pub fn toggle_inline_completions(
1945 &mut self,
1946 _: &ToggleEditPrediction,
1947 window: &mut Window,
1948 cx: &mut Context<Self>,
1949 ) {
1950 if self.show_inline_completions_override.is_some() {
1951 self.set_show_edit_predictions(None, window, cx);
1952 } else {
1953 let show_edit_predictions = !self.edit_predictions_enabled();
1954 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
1955 }
1956 }
1957
1958 pub fn set_show_edit_predictions(
1959 &mut self,
1960 show_edit_predictions: Option<bool>,
1961 window: &mut Window,
1962 cx: &mut Context<Self>,
1963 ) {
1964 self.show_inline_completions_override = show_edit_predictions;
1965 self.refresh_inline_completion(false, true, window, cx);
1966 }
1967
1968 fn inline_completions_disabled_in_scope(
1969 &self,
1970 buffer: &Entity<Buffer>,
1971 buffer_position: language::Anchor,
1972 cx: &App,
1973 ) -> bool {
1974 let snapshot = buffer.read(cx).snapshot();
1975 let settings = snapshot.settings_at(buffer_position, cx);
1976
1977 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1978 return false;
1979 };
1980
1981 scope.override_name().map_or(false, |scope_name| {
1982 settings
1983 .edit_predictions_disabled_in
1984 .iter()
1985 .any(|s| s == scope_name)
1986 })
1987 }
1988
1989 pub fn set_use_modal_editing(&mut self, to: bool) {
1990 self.use_modal_editing = to;
1991 }
1992
1993 pub fn use_modal_editing(&self) -> bool {
1994 self.use_modal_editing
1995 }
1996
1997 fn selections_did_change(
1998 &mut self,
1999 local: bool,
2000 old_cursor_position: &Anchor,
2001 show_completions: bool,
2002 window: &mut Window,
2003 cx: &mut Context<Self>,
2004 ) {
2005 window.invalidate_character_coordinates();
2006
2007 // Copy selections to primary selection buffer
2008 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2009 if local {
2010 let selections = self.selections.all::<usize>(cx);
2011 let buffer_handle = self.buffer.read(cx).read(cx);
2012
2013 let mut text = String::new();
2014 for (index, selection) in selections.iter().enumerate() {
2015 let text_for_selection = buffer_handle
2016 .text_for_range(selection.start..selection.end)
2017 .collect::<String>();
2018
2019 text.push_str(&text_for_selection);
2020 if index != selections.len() - 1 {
2021 text.push('\n');
2022 }
2023 }
2024
2025 if !text.is_empty() {
2026 cx.write_to_primary(ClipboardItem::new_string(text));
2027 }
2028 }
2029
2030 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2031 self.buffer.update(cx, |buffer, cx| {
2032 buffer.set_active_selections(
2033 &self.selections.disjoint_anchors(),
2034 self.selections.line_mode,
2035 self.cursor_shape,
2036 cx,
2037 )
2038 });
2039 }
2040 let display_map = self
2041 .display_map
2042 .update(cx, |display_map, cx| display_map.snapshot(cx));
2043 let buffer = &display_map.buffer_snapshot;
2044 self.add_selections_state = None;
2045 self.select_next_state = None;
2046 self.select_prev_state = None;
2047 self.select_larger_syntax_node_stack.clear();
2048 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2049 self.snippet_stack
2050 .invalidate(&self.selections.disjoint_anchors(), buffer);
2051 self.take_rename(false, window, cx);
2052
2053 let new_cursor_position = self.selections.newest_anchor().head();
2054
2055 self.push_to_nav_history(
2056 *old_cursor_position,
2057 Some(new_cursor_position.to_point(buffer)),
2058 cx,
2059 );
2060
2061 if local {
2062 let new_cursor_position = self.selections.newest_anchor().head();
2063 let mut context_menu = self.context_menu.borrow_mut();
2064 let completion_menu = match context_menu.as_ref() {
2065 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2066 _ => {
2067 *context_menu = None;
2068 None
2069 }
2070 };
2071 if let Some(buffer_id) = new_cursor_position.buffer_id {
2072 if !self.registered_buffers.contains_key(&buffer_id) {
2073 if let Some(lsp_store) = self.lsp_store(cx) {
2074 lsp_store.update(cx, |lsp_store, cx| {
2075 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2076 return;
2077 };
2078 self.registered_buffers.insert(
2079 buffer_id,
2080 lsp_store.register_buffer_with_language_servers(&buffer, cx),
2081 );
2082 })
2083 }
2084 }
2085 }
2086
2087 if let Some(completion_menu) = completion_menu {
2088 let cursor_position = new_cursor_position.to_offset(buffer);
2089 let (word_range, kind) =
2090 buffer.surrounding_word(completion_menu.initial_position, true);
2091 if kind == Some(CharKind::Word)
2092 && word_range.to_inclusive().contains(&cursor_position)
2093 {
2094 let mut completion_menu = completion_menu.clone();
2095 drop(context_menu);
2096
2097 let query = Self::completion_query(buffer, cursor_position);
2098 cx.spawn(move |this, mut cx| async move {
2099 completion_menu
2100 .filter(query.as_deref(), cx.background_executor().clone())
2101 .await;
2102
2103 this.update(&mut cx, |this, cx| {
2104 let mut context_menu = this.context_menu.borrow_mut();
2105 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2106 else {
2107 return;
2108 };
2109
2110 if menu.id > completion_menu.id {
2111 return;
2112 }
2113
2114 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2115 drop(context_menu);
2116 cx.notify();
2117 })
2118 })
2119 .detach();
2120
2121 if show_completions {
2122 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2123 }
2124 } else {
2125 drop(context_menu);
2126 self.hide_context_menu(window, cx);
2127 }
2128 } else {
2129 drop(context_menu);
2130 }
2131
2132 hide_hover(self, cx);
2133
2134 if old_cursor_position.to_display_point(&display_map).row()
2135 != new_cursor_position.to_display_point(&display_map).row()
2136 {
2137 self.available_code_actions.take();
2138 }
2139 self.refresh_code_actions(window, cx);
2140 self.refresh_document_highlights(cx);
2141 refresh_matching_bracket_highlights(self, window, cx);
2142 self.update_visible_inline_completion(window, cx);
2143 self.edit_prediction_requires_modifier_in_leading_space = true;
2144 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2145 if self.git_blame_inline_enabled {
2146 self.start_inline_blame_timer(window, cx);
2147 }
2148 }
2149
2150 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2151 cx.emit(EditorEvent::SelectionsChanged { local });
2152
2153 if self.selections.disjoint_anchors().len() == 1 {
2154 cx.emit(SearchEvent::ActiveMatchChanged)
2155 }
2156 cx.notify();
2157 }
2158
2159 pub fn change_selections<R>(
2160 &mut self,
2161 autoscroll: Option<Autoscroll>,
2162 window: &mut Window,
2163 cx: &mut Context<Self>,
2164 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2165 ) -> R {
2166 self.change_selections_inner(autoscroll, true, window, cx, change)
2167 }
2168
2169 pub fn change_selections_inner<R>(
2170 &mut self,
2171 autoscroll: Option<Autoscroll>,
2172 request_completions: bool,
2173 window: &mut Window,
2174 cx: &mut Context<Self>,
2175 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2176 ) -> R {
2177 let old_cursor_position = self.selections.newest_anchor().head();
2178 self.push_to_selection_history();
2179
2180 let (changed, result) = self.selections.change_with(cx, change);
2181
2182 if changed {
2183 if let Some(autoscroll) = autoscroll {
2184 self.request_autoscroll(autoscroll, cx);
2185 }
2186 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2187
2188 if self.should_open_signature_help_automatically(
2189 &old_cursor_position,
2190 self.signature_help_state.backspace_pressed(),
2191 cx,
2192 ) {
2193 self.show_signature_help(&ShowSignatureHelp, window, cx);
2194 }
2195 self.signature_help_state.set_backspace_pressed(false);
2196 }
2197
2198 result
2199 }
2200
2201 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2202 where
2203 I: IntoIterator<Item = (Range<S>, T)>,
2204 S: ToOffset,
2205 T: Into<Arc<str>>,
2206 {
2207 if self.read_only(cx) {
2208 return;
2209 }
2210
2211 self.buffer
2212 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2213 }
2214
2215 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2216 where
2217 I: IntoIterator<Item = (Range<S>, T)>,
2218 S: ToOffset,
2219 T: Into<Arc<str>>,
2220 {
2221 if self.read_only(cx) {
2222 return;
2223 }
2224
2225 self.buffer.update(cx, |buffer, cx| {
2226 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2227 });
2228 }
2229
2230 pub fn edit_with_block_indent<I, S, T>(
2231 &mut self,
2232 edits: I,
2233 original_indent_columns: Vec<u32>,
2234 cx: &mut Context<Self>,
2235 ) where
2236 I: IntoIterator<Item = (Range<S>, T)>,
2237 S: ToOffset,
2238 T: Into<Arc<str>>,
2239 {
2240 if self.read_only(cx) {
2241 return;
2242 }
2243
2244 self.buffer.update(cx, |buffer, cx| {
2245 buffer.edit(
2246 edits,
2247 Some(AutoindentMode::Block {
2248 original_indent_columns,
2249 }),
2250 cx,
2251 )
2252 });
2253 }
2254
2255 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2256 self.hide_context_menu(window, cx);
2257
2258 match phase {
2259 SelectPhase::Begin {
2260 position,
2261 add,
2262 click_count,
2263 } => self.begin_selection(position, add, click_count, window, cx),
2264 SelectPhase::BeginColumnar {
2265 position,
2266 goal_column,
2267 reset,
2268 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2269 SelectPhase::Extend {
2270 position,
2271 click_count,
2272 } => self.extend_selection(position, click_count, window, cx),
2273 SelectPhase::Update {
2274 position,
2275 goal_column,
2276 scroll_delta,
2277 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2278 SelectPhase::End => self.end_selection(window, cx),
2279 }
2280 }
2281
2282 fn extend_selection(
2283 &mut self,
2284 position: DisplayPoint,
2285 click_count: usize,
2286 window: &mut Window,
2287 cx: &mut Context<Self>,
2288 ) {
2289 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2290 let tail = self.selections.newest::<usize>(cx).tail();
2291 self.begin_selection(position, false, click_count, window, cx);
2292
2293 let position = position.to_offset(&display_map, Bias::Left);
2294 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2295
2296 let mut pending_selection = self
2297 .selections
2298 .pending_anchor()
2299 .expect("extend_selection not called with pending selection");
2300 if position >= tail {
2301 pending_selection.start = tail_anchor;
2302 } else {
2303 pending_selection.end = tail_anchor;
2304 pending_selection.reversed = true;
2305 }
2306
2307 let mut pending_mode = self.selections.pending_mode().unwrap();
2308 match &mut pending_mode {
2309 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2310 _ => {}
2311 }
2312
2313 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2314 s.set_pending(pending_selection, pending_mode)
2315 });
2316 }
2317
2318 fn begin_selection(
2319 &mut self,
2320 position: DisplayPoint,
2321 add: bool,
2322 click_count: usize,
2323 window: &mut Window,
2324 cx: &mut Context<Self>,
2325 ) {
2326 if !self.focus_handle.is_focused(window) {
2327 self.last_focused_descendant = None;
2328 window.focus(&self.focus_handle);
2329 }
2330
2331 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2332 let buffer = &display_map.buffer_snapshot;
2333 let newest_selection = self.selections.newest_anchor().clone();
2334 let position = display_map.clip_point(position, Bias::Left);
2335
2336 let start;
2337 let end;
2338 let mode;
2339 let mut auto_scroll;
2340 match click_count {
2341 1 => {
2342 start = buffer.anchor_before(position.to_point(&display_map));
2343 end = start;
2344 mode = SelectMode::Character;
2345 auto_scroll = true;
2346 }
2347 2 => {
2348 let range = movement::surrounding_word(&display_map, position);
2349 start = buffer.anchor_before(range.start.to_point(&display_map));
2350 end = buffer.anchor_before(range.end.to_point(&display_map));
2351 mode = SelectMode::Word(start..end);
2352 auto_scroll = true;
2353 }
2354 3 => {
2355 let position = display_map
2356 .clip_point(position, Bias::Left)
2357 .to_point(&display_map);
2358 let line_start = display_map.prev_line_boundary(position).0;
2359 let next_line_start = buffer.clip_point(
2360 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2361 Bias::Left,
2362 );
2363 start = buffer.anchor_before(line_start);
2364 end = buffer.anchor_before(next_line_start);
2365 mode = SelectMode::Line(start..end);
2366 auto_scroll = true;
2367 }
2368 _ => {
2369 start = buffer.anchor_before(0);
2370 end = buffer.anchor_before(buffer.len());
2371 mode = SelectMode::All;
2372 auto_scroll = false;
2373 }
2374 }
2375 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2376
2377 let point_to_delete: Option<usize> = {
2378 let selected_points: Vec<Selection<Point>> =
2379 self.selections.disjoint_in_range(start..end, cx);
2380
2381 if !add || click_count > 1 {
2382 None
2383 } else if !selected_points.is_empty() {
2384 Some(selected_points[0].id)
2385 } else {
2386 let clicked_point_already_selected =
2387 self.selections.disjoint.iter().find(|selection| {
2388 selection.start.to_point(buffer) == start.to_point(buffer)
2389 || selection.end.to_point(buffer) == end.to_point(buffer)
2390 });
2391
2392 clicked_point_already_selected.map(|selection| selection.id)
2393 }
2394 };
2395
2396 let selections_count = self.selections.count();
2397
2398 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2399 if let Some(point_to_delete) = point_to_delete {
2400 s.delete(point_to_delete);
2401
2402 if selections_count == 1 {
2403 s.set_pending_anchor_range(start..end, mode);
2404 }
2405 } else {
2406 if !add {
2407 s.clear_disjoint();
2408 } else if click_count > 1 {
2409 s.delete(newest_selection.id)
2410 }
2411
2412 s.set_pending_anchor_range(start..end, mode);
2413 }
2414 });
2415 }
2416
2417 fn begin_columnar_selection(
2418 &mut self,
2419 position: DisplayPoint,
2420 goal_column: u32,
2421 reset: bool,
2422 window: &mut Window,
2423 cx: &mut Context<Self>,
2424 ) {
2425 if !self.focus_handle.is_focused(window) {
2426 self.last_focused_descendant = None;
2427 window.focus(&self.focus_handle);
2428 }
2429
2430 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2431
2432 if reset {
2433 let pointer_position = display_map
2434 .buffer_snapshot
2435 .anchor_before(position.to_point(&display_map));
2436
2437 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2438 s.clear_disjoint();
2439 s.set_pending_anchor_range(
2440 pointer_position..pointer_position,
2441 SelectMode::Character,
2442 );
2443 });
2444 }
2445
2446 let tail = self.selections.newest::<Point>(cx).tail();
2447 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2448
2449 if !reset {
2450 self.select_columns(
2451 tail.to_display_point(&display_map),
2452 position,
2453 goal_column,
2454 &display_map,
2455 window,
2456 cx,
2457 );
2458 }
2459 }
2460
2461 fn update_selection(
2462 &mut self,
2463 position: DisplayPoint,
2464 goal_column: u32,
2465 scroll_delta: gpui::Point<f32>,
2466 window: &mut Window,
2467 cx: &mut Context<Self>,
2468 ) {
2469 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2470
2471 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2472 let tail = tail.to_display_point(&display_map);
2473 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2474 } else if let Some(mut pending) = self.selections.pending_anchor() {
2475 let buffer = self.buffer.read(cx).snapshot(cx);
2476 let head;
2477 let tail;
2478 let mode = self.selections.pending_mode().unwrap();
2479 match &mode {
2480 SelectMode::Character => {
2481 head = position.to_point(&display_map);
2482 tail = pending.tail().to_point(&buffer);
2483 }
2484 SelectMode::Word(original_range) => {
2485 let original_display_range = original_range.start.to_display_point(&display_map)
2486 ..original_range.end.to_display_point(&display_map);
2487 let original_buffer_range = original_display_range.start.to_point(&display_map)
2488 ..original_display_range.end.to_point(&display_map);
2489 if movement::is_inside_word(&display_map, position)
2490 || original_display_range.contains(&position)
2491 {
2492 let word_range = movement::surrounding_word(&display_map, position);
2493 if word_range.start < original_display_range.start {
2494 head = word_range.start.to_point(&display_map);
2495 } else {
2496 head = word_range.end.to_point(&display_map);
2497 }
2498 } else {
2499 head = position.to_point(&display_map);
2500 }
2501
2502 if head <= original_buffer_range.start {
2503 tail = original_buffer_range.end;
2504 } else {
2505 tail = original_buffer_range.start;
2506 }
2507 }
2508 SelectMode::Line(original_range) => {
2509 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2510
2511 let position = display_map
2512 .clip_point(position, Bias::Left)
2513 .to_point(&display_map);
2514 let line_start = display_map.prev_line_boundary(position).0;
2515 let next_line_start = buffer.clip_point(
2516 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2517 Bias::Left,
2518 );
2519
2520 if line_start < original_range.start {
2521 head = line_start
2522 } else {
2523 head = next_line_start
2524 }
2525
2526 if head <= original_range.start {
2527 tail = original_range.end;
2528 } else {
2529 tail = original_range.start;
2530 }
2531 }
2532 SelectMode::All => {
2533 return;
2534 }
2535 };
2536
2537 if head < tail {
2538 pending.start = buffer.anchor_before(head);
2539 pending.end = buffer.anchor_before(tail);
2540 pending.reversed = true;
2541 } else {
2542 pending.start = buffer.anchor_before(tail);
2543 pending.end = buffer.anchor_before(head);
2544 pending.reversed = false;
2545 }
2546
2547 self.change_selections(None, window, cx, |s| {
2548 s.set_pending(pending, mode);
2549 });
2550 } else {
2551 log::error!("update_selection dispatched with no pending selection");
2552 return;
2553 }
2554
2555 self.apply_scroll_delta(scroll_delta, window, cx);
2556 cx.notify();
2557 }
2558
2559 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2560 self.columnar_selection_tail.take();
2561 if self.selections.pending_anchor().is_some() {
2562 let selections = self.selections.all::<usize>(cx);
2563 self.change_selections(None, window, cx, |s| {
2564 s.select(selections);
2565 s.clear_pending();
2566 });
2567 }
2568 }
2569
2570 fn select_columns(
2571 &mut self,
2572 tail: DisplayPoint,
2573 head: DisplayPoint,
2574 goal_column: u32,
2575 display_map: &DisplaySnapshot,
2576 window: &mut Window,
2577 cx: &mut Context<Self>,
2578 ) {
2579 let start_row = cmp::min(tail.row(), head.row());
2580 let end_row = cmp::max(tail.row(), head.row());
2581 let start_column = cmp::min(tail.column(), goal_column);
2582 let end_column = cmp::max(tail.column(), goal_column);
2583 let reversed = start_column < tail.column();
2584
2585 let selection_ranges = (start_row.0..=end_row.0)
2586 .map(DisplayRow)
2587 .filter_map(|row| {
2588 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2589 let start = display_map
2590 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2591 .to_point(display_map);
2592 let end = display_map
2593 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2594 .to_point(display_map);
2595 if reversed {
2596 Some(end..start)
2597 } else {
2598 Some(start..end)
2599 }
2600 } else {
2601 None
2602 }
2603 })
2604 .collect::<Vec<_>>();
2605
2606 self.change_selections(None, window, cx, |s| {
2607 s.select_ranges(selection_ranges);
2608 });
2609 cx.notify();
2610 }
2611
2612 pub fn has_pending_nonempty_selection(&self) -> bool {
2613 let pending_nonempty_selection = match self.selections.pending_anchor() {
2614 Some(Selection { start, end, .. }) => start != end,
2615 None => false,
2616 };
2617
2618 pending_nonempty_selection
2619 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2620 }
2621
2622 pub fn has_pending_selection(&self) -> bool {
2623 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2624 }
2625
2626 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2627 self.selection_mark_mode = false;
2628
2629 if self.clear_expanded_diff_hunks(cx) {
2630 cx.notify();
2631 return;
2632 }
2633 if self.dismiss_menus_and_popups(true, window, cx) {
2634 return;
2635 }
2636
2637 if self.mode == EditorMode::Full
2638 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2639 {
2640 return;
2641 }
2642
2643 cx.propagate();
2644 }
2645
2646 pub fn dismiss_menus_and_popups(
2647 &mut self,
2648 is_user_requested: bool,
2649 window: &mut Window,
2650 cx: &mut Context<Self>,
2651 ) -> bool {
2652 if self.take_rename(false, window, cx).is_some() {
2653 return true;
2654 }
2655
2656 if hide_hover(self, cx) {
2657 return true;
2658 }
2659
2660 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2661 return true;
2662 }
2663
2664 if self.hide_context_menu(window, cx).is_some() {
2665 return true;
2666 }
2667
2668 if self.mouse_context_menu.take().is_some() {
2669 return true;
2670 }
2671
2672 if is_user_requested && self.discard_inline_completion(true, cx) {
2673 return true;
2674 }
2675
2676 if self.snippet_stack.pop().is_some() {
2677 return true;
2678 }
2679
2680 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2681 self.dismiss_diagnostics(cx);
2682 return true;
2683 }
2684
2685 false
2686 }
2687
2688 fn linked_editing_ranges_for(
2689 &self,
2690 selection: Range<text::Anchor>,
2691 cx: &App,
2692 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2693 if self.linked_edit_ranges.is_empty() {
2694 return None;
2695 }
2696 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2697 selection.end.buffer_id.and_then(|end_buffer_id| {
2698 if selection.start.buffer_id != Some(end_buffer_id) {
2699 return None;
2700 }
2701 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2702 let snapshot = buffer.read(cx).snapshot();
2703 self.linked_edit_ranges
2704 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2705 .map(|ranges| (ranges, snapshot, buffer))
2706 })?;
2707 use text::ToOffset as TO;
2708 // find offset from the start of current range to current cursor position
2709 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2710
2711 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2712 let start_difference = start_offset - start_byte_offset;
2713 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2714 let end_difference = end_offset - start_byte_offset;
2715 // Current range has associated linked ranges.
2716 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2717 for range in linked_ranges.iter() {
2718 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2719 let end_offset = start_offset + end_difference;
2720 let start_offset = start_offset + start_difference;
2721 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2722 continue;
2723 }
2724 if self.selections.disjoint_anchor_ranges().any(|s| {
2725 if s.start.buffer_id != selection.start.buffer_id
2726 || s.end.buffer_id != selection.end.buffer_id
2727 {
2728 return false;
2729 }
2730 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2731 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2732 }) {
2733 continue;
2734 }
2735 let start = buffer_snapshot.anchor_after(start_offset);
2736 let end = buffer_snapshot.anchor_after(end_offset);
2737 linked_edits
2738 .entry(buffer.clone())
2739 .or_default()
2740 .push(start..end);
2741 }
2742 Some(linked_edits)
2743 }
2744
2745 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2746 let text: Arc<str> = text.into();
2747
2748 if self.read_only(cx) {
2749 return;
2750 }
2751
2752 let selections = self.selections.all_adjusted(cx);
2753 let mut bracket_inserted = false;
2754 let mut edits = Vec::new();
2755 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2756 let mut new_selections = Vec::with_capacity(selections.len());
2757 let mut new_autoclose_regions = Vec::new();
2758 let snapshot = self.buffer.read(cx).read(cx);
2759
2760 for (selection, autoclose_region) in
2761 self.selections_with_autoclose_regions(selections, &snapshot)
2762 {
2763 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2764 // Determine if the inserted text matches the opening or closing
2765 // bracket of any of this language's bracket pairs.
2766 let mut bracket_pair = None;
2767 let mut is_bracket_pair_start = false;
2768 let mut is_bracket_pair_end = false;
2769 if !text.is_empty() {
2770 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2771 // and they are removing the character that triggered IME popup.
2772 for (pair, enabled) in scope.brackets() {
2773 if !pair.close && !pair.surround {
2774 continue;
2775 }
2776
2777 if enabled && pair.start.ends_with(text.as_ref()) {
2778 let prefix_len = pair.start.len() - text.len();
2779 let preceding_text_matches_prefix = prefix_len == 0
2780 || (selection.start.column >= (prefix_len as u32)
2781 && snapshot.contains_str_at(
2782 Point::new(
2783 selection.start.row,
2784 selection.start.column - (prefix_len as u32),
2785 ),
2786 &pair.start[..prefix_len],
2787 ));
2788 if preceding_text_matches_prefix {
2789 bracket_pair = Some(pair.clone());
2790 is_bracket_pair_start = true;
2791 break;
2792 }
2793 }
2794 if pair.end.as_str() == text.as_ref() {
2795 bracket_pair = Some(pair.clone());
2796 is_bracket_pair_end = true;
2797 break;
2798 }
2799 }
2800 }
2801
2802 if let Some(bracket_pair) = bracket_pair {
2803 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2804 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2805 let auto_surround =
2806 self.use_auto_surround && snapshot_settings.use_auto_surround;
2807 if selection.is_empty() {
2808 if is_bracket_pair_start {
2809 // If the inserted text is a suffix of an opening bracket and the
2810 // selection is preceded by the rest of the opening bracket, then
2811 // insert the closing bracket.
2812 let following_text_allows_autoclose = snapshot
2813 .chars_at(selection.start)
2814 .next()
2815 .map_or(true, |c| scope.should_autoclose_before(c));
2816
2817 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2818 && bracket_pair.start.len() == 1
2819 {
2820 let target = bracket_pair.start.chars().next().unwrap();
2821 let current_line_count = snapshot
2822 .reversed_chars_at(selection.start)
2823 .take_while(|&c| c != '\n')
2824 .filter(|&c| c == target)
2825 .count();
2826 current_line_count % 2 == 1
2827 } else {
2828 false
2829 };
2830
2831 if autoclose
2832 && bracket_pair.close
2833 && following_text_allows_autoclose
2834 && !is_closing_quote
2835 {
2836 let anchor = snapshot.anchor_before(selection.end);
2837 new_selections.push((selection.map(|_| anchor), text.len()));
2838 new_autoclose_regions.push((
2839 anchor,
2840 text.len(),
2841 selection.id,
2842 bracket_pair.clone(),
2843 ));
2844 edits.push((
2845 selection.range(),
2846 format!("{}{}", text, bracket_pair.end).into(),
2847 ));
2848 bracket_inserted = true;
2849 continue;
2850 }
2851 }
2852
2853 if let Some(region) = autoclose_region {
2854 // If the selection is followed by an auto-inserted closing bracket,
2855 // then don't insert that closing bracket again; just move the selection
2856 // past the closing bracket.
2857 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2858 && text.as_ref() == region.pair.end.as_str();
2859 if should_skip {
2860 let anchor = snapshot.anchor_after(selection.end);
2861 new_selections
2862 .push((selection.map(|_| anchor), region.pair.end.len()));
2863 continue;
2864 }
2865 }
2866
2867 let always_treat_brackets_as_autoclosed = snapshot
2868 .settings_at(selection.start, cx)
2869 .always_treat_brackets_as_autoclosed;
2870 if always_treat_brackets_as_autoclosed
2871 && is_bracket_pair_end
2872 && snapshot.contains_str_at(selection.end, text.as_ref())
2873 {
2874 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2875 // and the inserted text is a closing bracket and the selection is followed
2876 // by the closing bracket then move the selection past the closing bracket.
2877 let anchor = snapshot.anchor_after(selection.end);
2878 new_selections.push((selection.map(|_| anchor), text.len()));
2879 continue;
2880 }
2881 }
2882 // If an opening bracket is 1 character long and is typed while
2883 // text is selected, then surround that text with the bracket pair.
2884 else if auto_surround
2885 && bracket_pair.surround
2886 && is_bracket_pair_start
2887 && bracket_pair.start.chars().count() == 1
2888 {
2889 edits.push((selection.start..selection.start, text.clone()));
2890 edits.push((
2891 selection.end..selection.end,
2892 bracket_pair.end.as_str().into(),
2893 ));
2894 bracket_inserted = true;
2895 new_selections.push((
2896 Selection {
2897 id: selection.id,
2898 start: snapshot.anchor_after(selection.start),
2899 end: snapshot.anchor_before(selection.end),
2900 reversed: selection.reversed,
2901 goal: selection.goal,
2902 },
2903 0,
2904 ));
2905 continue;
2906 }
2907 }
2908 }
2909
2910 if self.auto_replace_emoji_shortcode
2911 && selection.is_empty()
2912 && text.as_ref().ends_with(':')
2913 {
2914 if let Some(possible_emoji_short_code) =
2915 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2916 {
2917 if !possible_emoji_short_code.is_empty() {
2918 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2919 let emoji_shortcode_start = Point::new(
2920 selection.start.row,
2921 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2922 );
2923
2924 // Remove shortcode from buffer
2925 edits.push((
2926 emoji_shortcode_start..selection.start,
2927 "".to_string().into(),
2928 ));
2929 new_selections.push((
2930 Selection {
2931 id: selection.id,
2932 start: snapshot.anchor_after(emoji_shortcode_start),
2933 end: snapshot.anchor_before(selection.start),
2934 reversed: selection.reversed,
2935 goal: selection.goal,
2936 },
2937 0,
2938 ));
2939
2940 // Insert emoji
2941 let selection_start_anchor = snapshot.anchor_after(selection.start);
2942 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2943 edits.push((selection.start..selection.end, emoji.to_string().into()));
2944
2945 continue;
2946 }
2947 }
2948 }
2949 }
2950
2951 // If not handling any auto-close operation, then just replace the selected
2952 // text with the given input and move the selection to the end of the
2953 // newly inserted text.
2954 let anchor = snapshot.anchor_after(selection.end);
2955 if !self.linked_edit_ranges.is_empty() {
2956 let start_anchor = snapshot.anchor_before(selection.start);
2957
2958 let is_word_char = text.chars().next().map_or(true, |char| {
2959 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2960 classifier.is_word(char)
2961 });
2962
2963 if is_word_char {
2964 if let Some(ranges) = self
2965 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2966 {
2967 for (buffer, edits) in ranges {
2968 linked_edits
2969 .entry(buffer.clone())
2970 .or_default()
2971 .extend(edits.into_iter().map(|range| (range, text.clone())));
2972 }
2973 }
2974 }
2975 }
2976
2977 new_selections.push((selection.map(|_| anchor), 0));
2978 edits.push((selection.start..selection.end, text.clone()));
2979 }
2980
2981 drop(snapshot);
2982
2983 self.transact(window, cx, |this, window, cx| {
2984 this.buffer.update(cx, |buffer, cx| {
2985 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2986 });
2987 for (buffer, edits) in linked_edits {
2988 buffer.update(cx, |buffer, cx| {
2989 let snapshot = buffer.snapshot();
2990 let edits = edits
2991 .into_iter()
2992 .map(|(range, text)| {
2993 use text::ToPoint as TP;
2994 let end_point = TP::to_point(&range.end, &snapshot);
2995 let start_point = TP::to_point(&range.start, &snapshot);
2996 (start_point..end_point, text)
2997 })
2998 .sorted_by_key(|(range, _)| range.start)
2999 .collect::<Vec<_>>();
3000 buffer.edit(edits, None, cx);
3001 })
3002 }
3003 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3004 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3005 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3006 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3007 .zip(new_selection_deltas)
3008 .map(|(selection, delta)| Selection {
3009 id: selection.id,
3010 start: selection.start + delta,
3011 end: selection.end + delta,
3012 reversed: selection.reversed,
3013 goal: SelectionGoal::None,
3014 })
3015 .collect::<Vec<_>>();
3016
3017 let mut i = 0;
3018 for (position, delta, selection_id, pair) in new_autoclose_regions {
3019 let position = position.to_offset(&map.buffer_snapshot) + delta;
3020 let start = map.buffer_snapshot.anchor_before(position);
3021 let end = map.buffer_snapshot.anchor_after(position);
3022 while let Some(existing_state) = this.autoclose_regions.get(i) {
3023 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3024 Ordering::Less => i += 1,
3025 Ordering::Greater => break,
3026 Ordering::Equal => {
3027 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3028 Ordering::Less => i += 1,
3029 Ordering::Equal => break,
3030 Ordering::Greater => break,
3031 }
3032 }
3033 }
3034 }
3035 this.autoclose_regions.insert(
3036 i,
3037 AutocloseRegion {
3038 selection_id,
3039 range: start..end,
3040 pair,
3041 },
3042 );
3043 }
3044
3045 let had_active_inline_completion = this.has_active_inline_completion();
3046 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3047 s.select(new_selections)
3048 });
3049
3050 if !bracket_inserted {
3051 if let Some(on_type_format_task) =
3052 this.trigger_on_type_formatting(text.to_string(), window, cx)
3053 {
3054 on_type_format_task.detach_and_log_err(cx);
3055 }
3056 }
3057
3058 let editor_settings = EditorSettings::get_global(cx);
3059 if bracket_inserted
3060 && (editor_settings.auto_signature_help
3061 || editor_settings.show_signature_help_after_edits)
3062 {
3063 this.show_signature_help(&ShowSignatureHelp, window, cx);
3064 }
3065
3066 let trigger_in_words =
3067 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3068 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3069 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3070 this.refresh_inline_completion(true, false, window, cx);
3071 });
3072 }
3073
3074 fn find_possible_emoji_shortcode_at_position(
3075 snapshot: &MultiBufferSnapshot,
3076 position: Point,
3077 ) -> Option<String> {
3078 let mut chars = Vec::new();
3079 let mut found_colon = false;
3080 for char in snapshot.reversed_chars_at(position).take(100) {
3081 // Found a possible emoji shortcode in the middle of the buffer
3082 if found_colon {
3083 if char.is_whitespace() {
3084 chars.reverse();
3085 return Some(chars.iter().collect());
3086 }
3087 // If the previous character is not a whitespace, we are in the middle of a word
3088 // and we only want to complete the shortcode if the word is made up of other emojis
3089 let mut containing_word = String::new();
3090 for ch in snapshot
3091 .reversed_chars_at(position)
3092 .skip(chars.len() + 1)
3093 .take(100)
3094 {
3095 if ch.is_whitespace() {
3096 break;
3097 }
3098 containing_word.push(ch);
3099 }
3100 let containing_word = containing_word.chars().rev().collect::<String>();
3101 if util::word_consists_of_emojis(containing_word.as_str()) {
3102 chars.reverse();
3103 return Some(chars.iter().collect());
3104 }
3105 }
3106
3107 if char.is_whitespace() || !char.is_ascii() {
3108 return None;
3109 }
3110 if char == ':' {
3111 found_colon = true;
3112 } else {
3113 chars.push(char);
3114 }
3115 }
3116 // Found a possible emoji shortcode at the beginning of the buffer
3117 chars.reverse();
3118 Some(chars.iter().collect())
3119 }
3120
3121 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3122 self.transact(window, cx, |this, window, cx| {
3123 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3124 let selections = this.selections.all::<usize>(cx);
3125 let multi_buffer = this.buffer.read(cx);
3126 let buffer = multi_buffer.snapshot(cx);
3127 selections
3128 .iter()
3129 .map(|selection| {
3130 let start_point = selection.start.to_point(&buffer);
3131 let mut indent =
3132 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3133 indent.len = cmp::min(indent.len, start_point.column);
3134 let start = selection.start;
3135 let end = selection.end;
3136 let selection_is_empty = start == end;
3137 let language_scope = buffer.language_scope_at(start);
3138 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3139 &language_scope
3140 {
3141 let leading_whitespace_len = buffer
3142 .reversed_chars_at(start)
3143 .take_while(|c| c.is_whitespace() && *c != '\n')
3144 .map(|c| c.len_utf8())
3145 .sum::<usize>();
3146
3147 let trailing_whitespace_len = buffer
3148 .chars_at(end)
3149 .take_while(|c| c.is_whitespace() && *c != '\n')
3150 .map(|c| c.len_utf8())
3151 .sum::<usize>();
3152
3153 let insert_extra_newline =
3154 language.brackets().any(|(pair, enabled)| {
3155 let pair_start = pair.start.trim_end();
3156 let pair_end = pair.end.trim_start();
3157
3158 enabled
3159 && pair.newline
3160 && buffer.contains_str_at(
3161 end + trailing_whitespace_len,
3162 pair_end,
3163 )
3164 && buffer.contains_str_at(
3165 (start - leading_whitespace_len)
3166 .saturating_sub(pair_start.len()),
3167 pair_start,
3168 )
3169 });
3170
3171 // Comment extension on newline is allowed only for cursor selections
3172 let comment_delimiter = maybe!({
3173 if !selection_is_empty {
3174 return None;
3175 }
3176
3177 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3178 return None;
3179 }
3180
3181 let delimiters = language.line_comment_prefixes();
3182 let max_len_of_delimiter =
3183 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3184 let (snapshot, range) =
3185 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3186
3187 let mut index_of_first_non_whitespace = 0;
3188 let comment_candidate = snapshot
3189 .chars_for_range(range)
3190 .skip_while(|c| {
3191 let should_skip = c.is_whitespace();
3192 if should_skip {
3193 index_of_first_non_whitespace += 1;
3194 }
3195 should_skip
3196 })
3197 .take(max_len_of_delimiter)
3198 .collect::<String>();
3199 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3200 comment_candidate.starts_with(comment_prefix.as_ref())
3201 })?;
3202 let cursor_is_placed_after_comment_marker =
3203 index_of_first_non_whitespace + comment_prefix.len()
3204 <= start_point.column as usize;
3205 if cursor_is_placed_after_comment_marker {
3206 Some(comment_prefix.clone())
3207 } else {
3208 None
3209 }
3210 });
3211 (comment_delimiter, insert_extra_newline)
3212 } else {
3213 (None, false)
3214 };
3215
3216 let capacity_for_delimiter = comment_delimiter
3217 .as_deref()
3218 .map(str::len)
3219 .unwrap_or_default();
3220 let mut new_text =
3221 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3222 new_text.push('\n');
3223 new_text.extend(indent.chars());
3224 if let Some(delimiter) = &comment_delimiter {
3225 new_text.push_str(delimiter);
3226 }
3227 if insert_extra_newline {
3228 new_text = new_text.repeat(2);
3229 }
3230
3231 let anchor = buffer.anchor_after(end);
3232 let new_selection = selection.map(|_| anchor);
3233 (
3234 (start..end, new_text),
3235 (insert_extra_newline, new_selection),
3236 )
3237 })
3238 .unzip()
3239 };
3240
3241 this.edit_with_autoindent(edits, cx);
3242 let buffer = this.buffer.read(cx).snapshot(cx);
3243 let new_selections = selection_fixup_info
3244 .into_iter()
3245 .map(|(extra_newline_inserted, new_selection)| {
3246 let mut cursor = new_selection.end.to_point(&buffer);
3247 if extra_newline_inserted {
3248 cursor.row -= 1;
3249 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3250 }
3251 new_selection.map(|_| cursor)
3252 })
3253 .collect();
3254
3255 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3256 s.select(new_selections)
3257 });
3258 this.refresh_inline_completion(true, false, window, cx);
3259 });
3260 }
3261
3262 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3263 let buffer = self.buffer.read(cx);
3264 let snapshot = buffer.snapshot(cx);
3265
3266 let mut edits = Vec::new();
3267 let mut rows = Vec::new();
3268
3269 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3270 let cursor = selection.head();
3271 let row = cursor.row;
3272
3273 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3274
3275 let newline = "\n".to_string();
3276 edits.push((start_of_line..start_of_line, newline));
3277
3278 rows.push(row + rows_inserted as u32);
3279 }
3280
3281 self.transact(window, cx, |editor, window, cx| {
3282 editor.edit(edits, cx);
3283
3284 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3285 let mut index = 0;
3286 s.move_cursors_with(|map, _, _| {
3287 let row = rows[index];
3288 index += 1;
3289
3290 let point = Point::new(row, 0);
3291 let boundary = map.next_line_boundary(point).1;
3292 let clipped = map.clip_point(boundary, Bias::Left);
3293
3294 (clipped, SelectionGoal::None)
3295 });
3296 });
3297
3298 let mut indent_edits = Vec::new();
3299 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3300 for row in rows {
3301 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3302 for (row, indent) in indents {
3303 if indent.len == 0 {
3304 continue;
3305 }
3306
3307 let text = match indent.kind {
3308 IndentKind::Space => " ".repeat(indent.len as usize),
3309 IndentKind::Tab => "\t".repeat(indent.len as usize),
3310 };
3311 let point = Point::new(row.0, 0);
3312 indent_edits.push((point..point, text));
3313 }
3314 }
3315 editor.edit(indent_edits, cx);
3316 });
3317 }
3318
3319 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3320 let buffer = self.buffer.read(cx);
3321 let snapshot = buffer.snapshot(cx);
3322
3323 let mut edits = Vec::new();
3324 let mut rows = Vec::new();
3325 let mut rows_inserted = 0;
3326
3327 for selection in self.selections.all_adjusted(cx) {
3328 let cursor = selection.head();
3329 let row = cursor.row;
3330
3331 let point = Point::new(row + 1, 0);
3332 let start_of_line = snapshot.clip_point(point, Bias::Left);
3333
3334 let newline = "\n".to_string();
3335 edits.push((start_of_line..start_of_line, newline));
3336
3337 rows_inserted += 1;
3338 rows.push(row + rows_inserted);
3339 }
3340
3341 self.transact(window, cx, |editor, window, cx| {
3342 editor.edit(edits, cx);
3343
3344 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3345 let mut index = 0;
3346 s.move_cursors_with(|map, _, _| {
3347 let row = rows[index];
3348 index += 1;
3349
3350 let point = Point::new(row, 0);
3351 let boundary = map.next_line_boundary(point).1;
3352 let clipped = map.clip_point(boundary, Bias::Left);
3353
3354 (clipped, SelectionGoal::None)
3355 });
3356 });
3357
3358 let mut indent_edits = Vec::new();
3359 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3360 for row in rows {
3361 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3362 for (row, indent) in indents {
3363 if indent.len == 0 {
3364 continue;
3365 }
3366
3367 let text = match indent.kind {
3368 IndentKind::Space => " ".repeat(indent.len as usize),
3369 IndentKind::Tab => "\t".repeat(indent.len as usize),
3370 };
3371 let point = Point::new(row.0, 0);
3372 indent_edits.push((point..point, text));
3373 }
3374 }
3375 editor.edit(indent_edits, cx);
3376 });
3377 }
3378
3379 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3380 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3381 original_indent_columns: Vec::new(),
3382 });
3383 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3384 }
3385
3386 fn insert_with_autoindent_mode(
3387 &mut self,
3388 text: &str,
3389 autoindent_mode: Option<AutoindentMode>,
3390 window: &mut Window,
3391 cx: &mut Context<Self>,
3392 ) {
3393 if self.read_only(cx) {
3394 return;
3395 }
3396
3397 let text: Arc<str> = text.into();
3398 self.transact(window, cx, |this, window, cx| {
3399 let old_selections = this.selections.all_adjusted(cx);
3400 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3401 let anchors = {
3402 let snapshot = buffer.read(cx);
3403 old_selections
3404 .iter()
3405 .map(|s| {
3406 let anchor = snapshot.anchor_after(s.head());
3407 s.map(|_| anchor)
3408 })
3409 .collect::<Vec<_>>()
3410 };
3411 buffer.edit(
3412 old_selections
3413 .iter()
3414 .map(|s| (s.start..s.end, text.clone())),
3415 autoindent_mode,
3416 cx,
3417 );
3418 anchors
3419 });
3420
3421 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3422 s.select_anchors(selection_anchors);
3423 });
3424
3425 cx.notify();
3426 });
3427 }
3428
3429 fn trigger_completion_on_input(
3430 &mut self,
3431 text: &str,
3432 trigger_in_words: bool,
3433 window: &mut Window,
3434 cx: &mut Context<Self>,
3435 ) {
3436 if self.is_completion_trigger(text, trigger_in_words, cx) {
3437 self.show_completions(
3438 &ShowCompletions {
3439 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3440 },
3441 window,
3442 cx,
3443 );
3444 } else {
3445 self.hide_context_menu(window, cx);
3446 }
3447 }
3448
3449 fn is_completion_trigger(
3450 &self,
3451 text: &str,
3452 trigger_in_words: bool,
3453 cx: &mut Context<Self>,
3454 ) -> bool {
3455 let position = self.selections.newest_anchor().head();
3456 let multibuffer = self.buffer.read(cx);
3457 let Some(buffer) = position
3458 .buffer_id
3459 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3460 else {
3461 return false;
3462 };
3463
3464 if let Some(completion_provider) = &self.completion_provider {
3465 completion_provider.is_completion_trigger(
3466 &buffer,
3467 position.text_anchor,
3468 text,
3469 trigger_in_words,
3470 cx,
3471 )
3472 } else {
3473 false
3474 }
3475 }
3476
3477 /// If any empty selections is touching the start of its innermost containing autoclose
3478 /// region, expand it to select the brackets.
3479 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3480 let selections = self.selections.all::<usize>(cx);
3481 let buffer = self.buffer.read(cx).read(cx);
3482 let new_selections = self
3483 .selections_with_autoclose_regions(selections, &buffer)
3484 .map(|(mut selection, region)| {
3485 if !selection.is_empty() {
3486 return selection;
3487 }
3488
3489 if let Some(region) = region {
3490 let mut range = region.range.to_offset(&buffer);
3491 if selection.start == range.start && range.start >= region.pair.start.len() {
3492 range.start -= region.pair.start.len();
3493 if buffer.contains_str_at(range.start, ®ion.pair.start)
3494 && buffer.contains_str_at(range.end, ®ion.pair.end)
3495 {
3496 range.end += region.pair.end.len();
3497 selection.start = range.start;
3498 selection.end = range.end;
3499
3500 return selection;
3501 }
3502 }
3503 }
3504
3505 let always_treat_brackets_as_autoclosed = buffer
3506 .settings_at(selection.start, cx)
3507 .always_treat_brackets_as_autoclosed;
3508
3509 if !always_treat_brackets_as_autoclosed {
3510 return selection;
3511 }
3512
3513 if let Some(scope) = buffer.language_scope_at(selection.start) {
3514 for (pair, enabled) in scope.brackets() {
3515 if !enabled || !pair.close {
3516 continue;
3517 }
3518
3519 if buffer.contains_str_at(selection.start, &pair.end) {
3520 let pair_start_len = pair.start.len();
3521 if buffer.contains_str_at(
3522 selection.start.saturating_sub(pair_start_len),
3523 &pair.start,
3524 ) {
3525 selection.start -= pair_start_len;
3526 selection.end += pair.end.len();
3527
3528 return selection;
3529 }
3530 }
3531 }
3532 }
3533
3534 selection
3535 })
3536 .collect();
3537
3538 drop(buffer);
3539 self.change_selections(None, window, cx, |selections| {
3540 selections.select(new_selections)
3541 });
3542 }
3543
3544 /// Iterate the given selections, and for each one, find the smallest surrounding
3545 /// autoclose region. This uses the ordering of the selections and the autoclose
3546 /// regions to avoid repeated comparisons.
3547 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3548 &'a self,
3549 selections: impl IntoIterator<Item = Selection<D>>,
3550 buffer: &'a MultiBufferSnapshot,
3551 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3552 let mut i = 0;
3553 let mut regions = self.autoclose_regions.as_slice();
3554 selections.into_iter().map(move |selection| {
3555 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3556
3557 let mut enclosing = None;
3558 while let Some(pair_state) = regions.get(i) {
3559 if pair_state.range.end.to_offset(buffer) < range.start {
3560 regions = ®ions[i + 1..];
3561 i = 0;
3562 } else if pair_state.range.start.to_offset(buffer) > range.end {
3563 break;
3564 } else {
3565 if pair_state.selection_id == selection.id {
3566 enclosing = Some(pair_state);
3567 }
3568 i += 1;
3569 }
3570 }
3571
3572 (selection, enclosing)
3573 })
3574 }
3575
3576 /// Remove any autoclose regions that no longer contain their selection.
3577 fn invalidate_autoclose_regions(
3578 &mut self,
3579 mut selections: &[Selection<Anchor>],
3580 buffer: &MultiBufferSnapshot,
3581 ) {
3582 self.autoclose_regions.retain(|state| {
3583 let mut i = 0;
3584 while let Some(selection) = selections.get(i) {
3585 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3586 selections = &selections[1..];
3587 continue;
3588 }
3589 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3590 break;
3591 }
3592 if selection.id == state.selection_id {
3593 return true;
3594 } else {
3595 i += 1;
3596 }
3597 }
3598 false
3599 });
3600 }
3601
3602 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3603 let offset = position.to_offset(buffer);
3604 let (word_range, kind) = buffer.surrounding_word(offset, true);
3605 if offset > word_range.start && kind == Some(CharKind::Word) {
3606 Some(
3607 buffer
3608 .text_for_range(word_range.start..offset)
3609 .collect::<String>(),
3610 )
3611 } else {
3612 None
3613 }
3614 }
3615
3616 pub fn toggle_inlay_hints(
3617 &mut self,
3618 _: &ToggleInlayHints,
3619 _: &mut Window,
3620 cx: &mut Context<Self>,
3621 ) {
3622 self.refresh_inlay_hints(
3623 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3624 cx,
3625 );
3626 }
3627
3628 pub fn inlay_hints_enabled(&self) -> bool {
3629 self.inlay_hint_cache.enabled
3630 }
3631
3632 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3633 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3634 return;
3635 }
3636
3637 let reason_description = reason.description();
3638 let ignore_debounce = matches!(
3639 reason,
3640 InlayHintRefreshReason::SettingsChange(_)
3641 | InlayHintRefreshReason::Toggle(_)
3642 | InlayHintRefreshReason::ExcerptsRemoved(_)
3643 );
3644 let (invalidate_cache, required_languages) = match reason {
3645 InlayHintRefreshReason::Toggle(enabled) => {
3646 self.inlay_hint_cache.enabled = enabled;
3647 if enabled {
3648 (InvalidationStrategy::RefreshRequested, None)
3649 } else {
3650 self.inlay_hint_cache.clear();
3651 self.splice_inlays(
3652 &self
3653 .visible_inlay_hints(cx)
3654 .iter()
3655 .map(|inlay| inlay.id)
3656 .collect::<Vec<InlayId>>(),
3657 Vec::new(),
3658 cx,
3659 );
3660 return;
3661 }
3662 }
3663 InlayHintRefreshReason::SettingsChange(new_settings) => {
3664 match self.inlay_hint_cache.update_settings(
3665 &self.buffer,
3666 new_settings,
3667 self.visible_inlay_hints(cx),
3668 cx,
3669 ) {
3670 ControlFlow::Break(Some(InlaySplice {
3671 to_remove,
3672 to_insert,
3673 })) => {
3674 self.splice_inlays(&to_remove, to_insert, cx);
3675 return;
3676 }
3677 ControlFlow::Break(None) => return,
3678 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3679 }
3680 }
3681 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3682 if let Some(InlaySplice {
3683 to_remove,
3684 to_insert,
3685 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3686 {
3687 self.splice_inlays(&to_remove, to_insert, cx);
3688 }
3689 return;
3690 }
3691 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3692 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3693 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3694 }
3695 InlayHintRefreshReason::RefreshRequested => {
3696 (InvalidationStrategy::RefreshRequested, None)
3697 }
3698 };
3699
3700 if let Some(InlaySplice {
3701 to_remove,
3702 to_insert,
3703 }) = self.inlay_hint_cache.spawn_hint_refresh(
3704 reason_description,
3705 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3706 invalidate_cache,
3707 ignore_debounce,
3708 cx,
3709 ) {
3710 self.splice_inlays(&to_remove, to_insert, cx);
3711 }
3712 }
3713
3714 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3715 self.display_map
3716 .read(cx)
3717 .current_inlays()
3718 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3719 .cloned()
3720 .collect()
3721 }
3722
3723 pub fn excerpts_for_inlay_hints_query(
3724 &self,
3725 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3726 cx: &mut Context<Editor>,
3727 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3728 let Some(project) = self.project.as_ref() else {
3729 return HashMap::default();
3730 };
3731 let project = project.read(cx);
3732 let multi_buffer = self.buffer().read(cx);
3733 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3734 let multi_buffer_visible_start = self
3735 .scroll_manager
3736 .anchor()
3737 .anchor
3738 .to_point(&multi_buffer_snapshot);
3739 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3740 multi_buffer_visible_start
3741 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3742 Bias::Left,
3743 );
3744 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3745 multi_buffer_snapshot
3746 .range_to_buffer_ranges(multi_buffer_visible_range)
3747 .into_iter()
3748 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3749 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3750 let buffer_file = project::File::from_dyn(buffer.file())?;
3751 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3752 let worktree_entry = buffer_worktree
3753 .read(cx)
3754 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3755 if worktree_entry.is_ignored {
3756 return None;
3757 }
3758
3759 let language = buffer.language()?;
3760 if let Some(restrict_to_languages) = restrict_to_languages {
3761 if !restrict_to_languages.contains(language) {
3762 return None;
3763 }
3764 }
3765 Some((
3766 excerpt_id,
3767 (
3768 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3769 buffer.version().clone(),
3770 excerpt_visible_range,
3771 ),
3772 ))
3773 })
3774 .collect()
3775 }
3776
3777 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3778 TextLayoutDetails {
3779 text_system: window.text_system().clone(),
3780 editor_style: self.style.clone().unwrap(),
3781 rem_size: window.rem_size(),
3782 scroll_anchor: self.scroll_manager.anchor(),
3783 visible_rows: self.visible_line_count(),
3784 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3785 }
3786 }
3787
3788 pub fn splice_inlays(
3789 &self,
3790 to_remove: &[InlayId],
3791 to_insert: Vec<Inlay>,
3792 cx: &mut Context<Self>,
3793 ) {
3794 self.display_map.update(cx, |display_map, cx| {
3795 display_map.splice_inlays(to_remove, to_insert, cx)
3796 });
3797 cx.notify();
3798 }
3799
3800 fn trigger_on_type_formatting(
3801 &self,
3802 input: String,
3803 window: &mut Window,
3804 cx: &mut Context<Self>,
3805 ) -> Option<Task<Result<()>>> {
3806 if input.len() != 1 {
3807 return None;
3808 }
3809
3810 let project = self.project.as_ref()?;
3811 let position = self.selections.newest_anchor().head();
3812 let (buffer, buffer_position) = self
3813 .buffer
3814 .read(cx)
3815 .text_anchor_for_position(position, cx)?;
3816
3817 let settings = language_settings::language_settings(
3818 buffer
3819 .read(cx)
3820 .language_at(buffer_position)
3821 .map(|l| l.name()),
3822 buffer.read(cx).file(),
3823 cx,
3824 );
3825 if !settings.use_on_type_format {
3826 return None;
3827 }
3828
3829 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3830 // hence we do LSP request & edit on host side only — add formats to host's history.
3831 let push_to_lsp_host_history = true;
3832 // If this is not the host, append its history with new edits.
3833 let push_to_client_history = project.read(cx).is_via_collab();
3834
3835 let on_type_formatting = project.update(cx, |project, cx| {
3836 project.on_type_format(
3837 buffer.clone(),
3838 buffer_position,
3839 input,
3840 push_to_lsp_host_history,
3841 cx,
3842 )
3843 });
3844 Some(cx.spawn_in(window, |editor, mut cx| async move {
3845 if let Some(transaction) = on_type_formatting.await? {
3846 if push_to_client_history {
3847 buffer
3848 .update(&mut cx, |buffer, _| {
3849 buffer.push_transaction(transaction, Instant::now());
3850 })
3851 .ok();
3852 }
3853 editor.update(&mut cx, |editor, cx| {
3854 editor.refresh_document_highlights(cx);
3855 })?;
3856 }
3857 Ok(())
3858 }))
3859 }
3860
3861 pub fn show_completions(
3862 &mut self,
3863 options: &ShowCompletions,
3864 window: &mut Window,
3865 cx: &mut Context<Self>,
3866 ) {
3867 if self.pending_rename.is_some() {
3868 return;
3869 }
3870
3871 let Some(provider) = self.completion_provider.as_ref() else {
3872 return;
3873 };
3874
3875 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3876 return;
3877 }
3878
3879 let position = self.selections.newest_anchor().head();
3880 if position.diff_base_anchor.is_some() {
3881 return;
3882 }
3883 let (buffer, buffer_position) =
3884 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3885 output
3886 } else {
3887 return;
3888 };
3889 let show_completion_documentation = buffer
3890 .read(cx)
3891 .snapshot()
3892 .settings_at(buffer_position, cx)
3893 .show_completion_documentation;
3894
3895 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3896
3897 let trigger_kind = match &options.trigger {
3898 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3899 CompletionTriggerKind::TRIGGER_CHARACTER
3900 }
3901 _ => CompletionTriggerKind::INVOKED,
3902 };
3903 let completion_context = CompletionContext {
3904 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3905 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3906 Some(String::from(trigger))
3907 } else {
3908 None
3909 }
3910 }),
3911 trigger_kind,
3912 };
3913 let completions =
3914 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3915 let sort_completions = provider.sort_completions();
3916
3917 let id = post_inc(&mut self.next_completion_id);
3918 let task = cx.spawn_in(window, |editor, mut cx| {
3919 async move {
3920 editor.update(&mut cx, |this, _| {
3921 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3922 })?;
3923 let completions = completions.await.log_err();
3924 let menu = if let Some(completions) = completions {
3925 let mut menu = CompletionsMenu::new(
3926 id,
3927 sort_completions,
3928 show_completion_documentation,
3929 position,
3930 buffer.clone(),
3931 completions.into(),
3932 );
3933
3934 menu.filter(query.as_deref(), cx.background_executor().clone())
3935 .await;
3936
3937 menu.visible().then_some(menu)
3938 } else {
3939 None
3940 };
3941
3942 editor.update_in(&mut cx, |editor, window, cx| {
3943 match editor.context_menu.borrow().as_ref() {
3944 None => {}
3945 Some(CodeContextMenu::Completions(prev_menu)) => {
3946 if prev_menu.id > id {
3947 return;
3948 }
3949 }
3950 _ => return,
3951 }
3952
3953 if editor.focus_handle.is_focused(window) && menu.is_some() {
3954 let mut menu = menu.unwrap();
3955 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3956
3957 *editor.context_menu.borrow_mut() =
3958 Some(CodeContextMenu::Completions(menu));
3959
3960 if editor.show_edit_predictions_in_menu() {
3961 editor.update_visible_inline_completion(window, cx);
3962 } else {
3963 editor.discard_inline_completion(false, cx);
3964 }
3965
3966 cx.notify();
3967 } else if editor.completion_tasks.len() <= 1 {
3968 // If there are no more completion tasks and the last menu was
3969 // empty, we should hide it.
3970 let was_hidden = editor.hide_context_menu(window, cx).is_none();
3971 // If it was already hidden and we don't show inline
3972 // completions in the menu, we should also show the
3973 // inline-completion when available.
3974 if was_hidden && editor.show_edit_predictions_in_menu() {
3975 editor.update_visible_inline_completion(window, cx);
3976 }
3977 }
3978 })?;
3979
3980 Ok::<_, anyhow::Error>(())
3981 }
3982 .log_err()
3983 });
3984
3985 self.completion_tasks.push((id, task));
3986 }
3987
3988 pub fn confirm_completion(
3989 &mut self,
3990 action: &ConfirmCompletion,
3991 window: &mut Window,
3992 cx: &mut Context<Self>,
3993 ) -> Option<Task<Result<()>>> {
3994 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
3995 }
3996
3997 pub fn compose_completion(
3998 &mut self,
3999 action: &ComposeCompletion,
4000 window: &mut Window,
4001 cx: &mut Context<Self>,
4002 ) -> Option<Task<Result<()>>> {
4003 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4004 }
4005
4006 fn do_completion(
4007 &mut self,
4008 item_ix: Option<usize>,
4009 intent: CompletionIntent,
4010 window: &mut Window,
4011 cx: &mut Context<Editor>,
4012 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4013 use language::ToOffset as _;
4014
4015 let completions_menu =
4016 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4017 menu
4018 } else {
4019 return None;
4020 };
4021
4022 let entries = completions_menu.entries.borrow();
4023 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4024 if self.show_edit_predictions_in_menu() {
4025 self.discard_inline_completion(true, cx);
4026 }
4027 let candidate_id = mat.candidate_id;
4028 drop(entries);
4029
4030 let buffer_handle = completions_menu.buffer;
4031 let completion = completions_menu
4032 .completions
4033 .borrow()
4034 .get(candidate_id)?
4035 .clone();
4036 cx.stop_propagation();
4037
4038 let snippet;
4039 let text;
4040
4041 if completion.is_snippet() {
4042 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4043 text = snippet.as_ref().unwrap().text.clone();
4044 } else {
4045 snippet = None;
4046 text = completion.new_text.clone();
4047 };
4048 let selections = self.selections.all::<usize>(cx);
4049 let buffer = buffer_handle.read(cx);
4050 let old_range = completion.old_range.to_offset(buffer);
4051 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4052
4053 let newest_selection = self.selections.newest_anchor();
4054 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4055 return None;
4056 }
4057
4058 let lookbehind = newest_selection
4059 .start
4060 .text_anchor
4061 .to_offset(buffer)
4062 .saturating_sub(old_range.start);
4063 let lookahead = old_range
4064 .end
4065 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4066 let mut common_prefix_len = old_text
4067 .bytes()
4068 .zip(text.bytes())
4069 .take_while(|(a, b)| a == b)
4070 .count();
4071
4072 let snapshot = self.buffer.read(cx).snapshot(cx);
4073 let mut range_to_replace: Option<Range<isize>> = None;
4074 let mut ranges = Vec::new();
4075 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4076 for selection in &selections {
4077 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4078 let start = selection.start.saturating_sub(lookbehind);
4079 let end = selection.end + lookahead;
4080 if selection.id == newest_selection.id {
4081 range_to_replace = Some(
4082 ((start + common_prefix_len) as isize - selection.start as isize)
4083 ..(end as isize - selection.start as isize),
4084 );
4085 }
4086 ranges.push(start + common_prefix_len..end);
4087 } else {
4088 common_prefix_len = 0;
4089 ranges.clear();
4090 ranges.extend(selections.iter().map(|s| {
4091 if s.id == newest_selection.id {
4092 range_to_replace = Some(
4093 old_range.start.to_offset_utf16(&snapshot).0 as isize
4094 - selection.start as isize
4095 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4096 - selection.start as isize,
4097 );
4098 old_range.clone()
4099 } else {
4100 s.start..s.end
4101 }
4102 }));
4103 break;
4104 }
4105 if !self.linked_edit_ranges.is_empty() {
4106 let start_anchor = snapshot.anchor_before(selection.head());
4107 let end_anchor = snapshot.anchor_after(selection.tail());
4108 if let Some(ranges) = self
4109 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4110 {
4111 for (buffer, edits) in ranges {
4112 linked_edits.entry(buffer.clone()).or_default().extend(
4113 edits
4114 .into_iter()
4115 .map(|range| (range, text[common_prefix_len..].to_owned())),
4116 );
4117 }
4118 }
4119 }
4120 }
4121 let text = &text[common_prefix_len..];
4122
4123 cx.emit(EditorEvent::InputHandled {
4124 utf16_range_to_replace: range_to_replace,
4125 text: text.into(),
4126 });
4127
4128 self.transact(window, cx, |this, window, cx| {
4129 if let Some(mut snippet) = snippet {
4130 snippet.text = text.to_string();
4131 for tabstop in snippet
4132 .tabstops
4133 .iter_mut()
4134 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4135 {
4136 tabstop.start -= common_prefix_len as isize;
4137 tabstop.end -= common_prefix_len as isize;
4138 }
4139
4140 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4141 } else {
4142 this.buffer.update(cx, |buffer, cx| {
4143 buffer.edit(
4144 ranges.iter().map(|range| (range.clone(), text)),
4145 this.autoindent_mode.clone(),
4146 cx,
4147 );
4148 });
4149 }
4150 for (buffer, edits) in linked_edits {
4151 buffer.update(cx, |buffer, cx| {
4152 let snapshot = buffer.snapshot();
4153 let edits = edits
4154 .into_iter()
4155 .map(|(range, text)| {
4156 use text::ToPoint as TP;
4157 let end_point = TP::to_point(&range.end, &snapshot);
4158 let start_point = TP::to_point(&range.start, &snapshot);
4159 (start_point..end_point, text)
4160 })
4161 .sorted_by_key(|(range, _)| range.start)
4162 .collect::<Vec<_>>();
4163 buffer.edit(edits, None, cx);
4164 })
4165 }
4166
4167 this.refresh_inline_completion(true, false, window, cx);
4168 });
4169
4170 let show_new_completions_on_confirm = completion
4171 .confirm
4172 .as_ref()
4173 .map_or(false, |confirm| confirm(intent, window, cx));
4174 if show_new_completions_on_confirm {
4175 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4176 }
4177
4178 let provider = self.completion_provider.as_ref()?;
4179 drop(completion);
4180 let apply_edits = provider.apply_additional_edits_for_completion(
4181 buffer_handle,
4182 completions_menu.completions.clone(),
4183 candidate_id,
4184 true,
4185 cx,
4186 );
4187
4188 let editor_settings = EditorSettings::get_global(cx);
4189 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4190 // After the code completion is finished, users often want to know what signatures are needed.
4191 // so we should automatically call signature_help
4192 self.show_signature_help(&ShowSignatureHelp, window, cx);
4193 }
4194
4195 Some(cx.foreground_executor().spawn(async move {
4196 apply_edits.await?;
4197 Ok(())
4198 }))
4199 }
4200
4201 pub fn toggle_code_actions(
4202 &mut self,
4203 action: &ToggleCodeActions,
4204 window: &mut Window,
4205 cx: &mut Context<Self>,
4206 ) {
4207 let mut context_menu = self.context_menu.borrow_mut();
4208 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4209 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4210 // Toggle if we're selecting the same one
4211 *context_menu = None;
4212 cx.notify();
4213 return;
4214 } else {
4215 // Otherwise, clear it and start a new one
4216 *context_menu = None;
4217 cx.notify();
4218 }
4219 }
4220 drop(context_menu);
4221 let snapshot = self.snapshot(window, cx);
4222 let deployed_from_indicator = action.deployed_from_indicator;
4223 let mut task = self.code_actions_task.take();
4224 let action = action.clone();
4225 cx.spawn_in(window, |editor, mut cx| async move {
4226 while let Some(prev_task) = task {
4227 prev_task.await.log_err();
4228 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4229 }
4230
4231 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4232 if editor.focus_handle.is_focused(window) {
4233 let multibuffer_point = action
4234 .deployed_from_indicator
4235 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4236 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4237 let (buffer, buffer_row) = snapshot
4238 .buffer_snapshot
4239 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4240 .and_then(|(buffer_snapshot, range)| {
4241 editor
4242 .buffer
4243 .read(cx)
4244 .buffer(buffer_snapshot.remote_id())
4245 .map(|buffer| (buffer, range.start.row))
4246 })?;
4247 let (_, code_actions) = editor
4248 .available_code_actions
4249 .clone()
4250 .and_then(|(location, code_actions)| {
4251 let snapshot = location.buffer.read(cx).snapshot();
4252 let point_range = location.range.to_point(&snapshot);
4253 let point_range = point_range.start.row..=point_range.end.row;
4254 if point_range.contains(&buffer_row) {
4255 Some((location, code_actions))
4256 } else {
4257 None
4258 }
4259 })
4260 .unzip();
4261 let buffer_id = buffer.read(cx).remote_id();
4262 let tasks = editor
4263 .tasks
4264 .get(&(buffer_id, buffer_row))
4265 .map(|t| Arc::new(t.to_owned()));
4266 if tasks.is_none() && code_actions.is_none() {
4267 return None;
4268 }
4269
4270 editor.completion_tasks.clear();
4271 editor.discard_inline_completion(false, cx);
4272 let task_context =
4273 tasks
4274 .as_ref()
4275 .zip(editor.project.clone())
4276 .map(|(tasks, project)| {
4277 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4278 });
4279
4280 Some(cx.spawn_in(window, |editor, mut cx| async move {
4281 let task_context = match task_context {
4282 Some(task_context) => task_context.await,
4283 None => None,
4284 };
4285 let resolved_tasks =
4286 tasks.zip(task_context).map(|(tasks, task_context)| {
4287 Rc::new(ResolvedTasks {
4288 templates: tasks.resolve(&task_context).collect(),
4289 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4290 multibuffer_point.row,
4291 tasks.column,
4292 )),
4293 })
4294 });
4295 let spawn_straight_away = resolved_tasks
4296 .as_ref()
4297 .map_or(false, |tasks| tasks.templates.len() == 1)
4298 && code_actions
4299 .as_ref()
4300 .map_or(true, |actions| actions.is_empty());
4301 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4302 *editor.context_menu.borrow_mut() =
4303 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4304 buffer,
4305 actions: CodeActionContents {
4306 tasks: resolved_tasks,
4307 actions: code_actions,
4308 },
4309 selected_item: Default::default(),
4310 scroll_handle: UniformListScrollHandle::default(),
4311 deployed_from_indicator,
4312 }));
4313 if spawn_straight_away {
4314 if let Some(task) = editor.confirm_code_action(
4315 &ConfirmCodeAction { item_ix: Some(0) },
4316 window,
4317 cx,
4318 ) {
4319 cx.notify();
4320 return task;
4321 }
4322 }
4323 cx.notify();
4324 Task::ready(Ok(()))
4325 }) {
4326 task.await
4327 } else {
4328 Ok(())
4329 }
4330 }))
4331 } else {
4332 Some(Task::ready(Ok(())))
4333 }
4334 })?;
4335 if let Some(task) = spawned_test_task {
4336 task.await?;
4337 }
4338
4339 Ok::<_, anyhow::Error>(())
4340 })
4341 .detach_and_log_err(cx);
4342 }
4343
4344 pub fn confirm_code_action(
4345 &mut self,
4346 action: &ConfirmCodeAction,
4347 window: &mut Window,
4348 cx: &mut Context<Self>,
4349 ) -> Option<Task<Result<()>>> {
4350 let actions_menu =
4351 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4352 menu
4353 } else {
4354 return None;
4355 };
4356 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4357 let action = actions_menu.actions.get(action_ix)?;
4358 let title = action.label();
4359 let buffer = actions_menu.buffer;
4360 let workspace = self.workspace()?;
4361
4362 match action {
4363 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4364 workspace.update(cx, |workspace, cx| {
4365 workspace::tasks::schedule_resolved_task(
4366 workspace,
4367 task_source_kind,
4368 resolved_task,
4369 false,
4370 cx,
4371 );
4372
4373 Some(Task::ready(Ok(())))
4374 })
4375 }
4376 CodeActionsItem::CodeAction {
4377 excerpt_id,
4378 action,
4379 provider,
4380 } => {
4381 let apply_code_action =
4382 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4383 let workspace = workspace.downgrade();
4384 Some(cx.spawn_in(window, |editor, cx| async move {
4385 let project_transaction = apply_code_action.await?;
4386 Self::open_project_transaction(
4387 &editor,
4388 workspace,
4389 project_transaction,
4390 title,
4391 cx,
4392 )
4393 .await
4394 }))
4395 }
4396 }
4397 }
4398
4399 pub async fn open_project_transaction(
4400 this: &WeakEntity<Editor>,
4401 workspace: WeakEntity<Workspace>,
4402 transaction: ProjectTransaction,
4403 title: String,
4404 mut cx: AsyncWindowContext,
4405 ) -> Result<()> {
4406 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4407 cx.update(|_, cx| {
4408 entries.sort_unstable_by_key(|(buffer, _)| {
4409 buffer.read(cx).file().map(|f| f.path().clone())
4410 });
4411 })?;
4412
4413 // If the project transaction's edits are all contained within this editor, then
4414 // avoid opening a new editor to display them.
4415
4416 if let Some((buffer, transaction)) = entries.first() {
4417 if entries.len() == 1 {
4418 let excerpt = this.update(&mut cx, |editor, cx| {
4419 editor
4420 .buffer()
4421 .read(cx)
4422 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4423 })?;
4424 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4425 if excerpted_buffer == *buffer {
4426 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4427 let excerpt_range = excerpt_range.to_offset(buffer);
4428 buffer
4429 .edited_ranges_for_transaction::<usize>(transaction)
4430 .all(|range| {
4431 excerpt_range.start <= range.start
4432 && excerpt_range.end >= range.end
4433 })
4434 })?;
4435
4436 if all_edits_within_excerpt {
4437 return Ok(());
4438 }
4439 }
4440 }
4441 }
4442 } else {
4443 return Ok(());
4444 }
4445
4446 let mut ranges_to_highlight = Vec::new();
4447 let excerpt_buffer = cx.new(|cx| {
4448 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4449 for (buffer_handle, transaction) in &entries {
4450 let buffer = buffer_handle.read(cx);
4451 ranges_to_highlight.extend(
4452 multibuffer.push_excerpts_with_context_lines(
4453 buffer_handle.clone(),
4454 buffer
4455 .edited_ranges_for_transaction::<usize>(transaction)
4456 .collect(),
4457 DEFAULT_MULTIBUFFER_CONTEXT,
4458 cx,
4459 ),
4460 );
4461 }
4462 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4463 multibuffer
4464 })?;
4465
4466 workspace.update_in(&mut cx, |workspace, window, cx| {
4467 let project = workspace.project().clone();
4468 let editor = cx
4469 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4470 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4471 editor.update(cx, |editor, cx| {
4472 editor.highlight_background::<Self>(
4473 &ranges_to_highlight,
4474 |theme| theme.editor_highlighted_line_background,
4475 cx,
4476 );
4477 });
4478 })?;
4479
4480 Ok(())
4481 }
4482
4483 pub fn clear_code_action_providers(&mut self) {
4484 self.code_action_providers.clear();
4485 self.available_code_actions.take();
4486 }
4487
4488 pub fn add_code_action_provider(
4489 &mut self,
4490 provider: Rc<dyn CodeActionProvider>,
4491 window: &mut Window,
4492 cx: &mut Context<Self>,
4493 ) {
4494 if self
4495 .code_action_providers
4496 .iter()
4497 .any(|existing_provider| existing_provider.id() == provider.id())
4498 {
4499 return;
4500 }
4501
4502 self.code_action_providers.push(provider);
4503 self.refresh_code_actions(window, cx);
4504 }
4505
4506 pub fn remove_code_action_provider(
4507 &mut self,
4508 id: Arc<str>,
4509 window: &mut Window,
4510 cx: &mut Context<Self>,
4511 ) {
4512 self.code_action_providers
4513 .retain(|provider| provider.id() != id);
4514 self.refresh_code_actions(window, cx);
4515 }
4516
4517 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4518 let buffer = self.buffer.read(cx);
4519 let newest_selection = self.selections.newest_anchor().clone();
4520 if newest_selection.head().diff_base_anchor.is_some() {
4521 return None;
4522 }
4523 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4524 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4525 if start_buffer != end_buffer {
4526 return None;
4527 }
4528
4529 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4530 cx.background_executor()
4531 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4532 .await;
4533
4534 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4535 let providers = this.code_action_providers.clone();
4536 let tasks = this
4537 .code_action_providers
4538 .iter()
4539 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4540 .collect::<Vec<_>>();
4541 (providers, tasks)
4542 })?;
4543
4544 let mut actions = Vec::new();
4545 for (provider, provider_actions) in
4546 providers.into_iter().zip(future::join_all(tasks).await)
4547 {
4548 if let Some(provider_actions) = provider_actions.log_err() {
4549 actions.extend(provider_actions.into_iter().map(|action| {
4550 AvailableCodeAction {
4551 excerpt_id: newest_selection.start.excerpt_id,
4552 action,
4553 provider: provider.clone(),
4554 }
4555 }));
4556 }
4557 }
4558
4559 this.update(&mut cx, |this, cx| {
4560 this.available_code_actions = if actions.is_empty() {
4561 None
4562 } else {
4563 Some((
4564 Location {
4565 buffer: start_buffer,
4566 range: start..end,
4567 },
4568 actions.into(),
4569 ))
4570 };
4571 cx.notify();
4572 })
4573 }));
4574 None
4575 }
4576
4577 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4578 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4579 self.show_git_blame_inline = false;
4580
4581 self.show_git_blame_inline_delay_task =
4582 Some(cx.spawn_in(window, |this, mut cx| async move {
4583 cx.background_executor().timer(delay).await;
4584
4585 this.update(&mut cx, |this, cx| {
4586 this.show_git_blame_inline = true;
4587 cx.notify();
4588 })
4589 .log_err();
4590 }));
4591 }
4592 }
4593
4594 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4595 if self.pending_rename.is_some() {
4596 return None;
4597 }
4598
4599 let provider = self.semantics_provider.clone()?;
4600 let buffer = self.buffer.read(cx);
4601 let newest_selection = self.selections.newest_anchor().clone();
4602 let cursor_position = newest_selection.head();
4603 let (cursor_buffer, cursor_buffer_position) =
4604 buffer.text_anchor_for_position(cursor_position, cx)?;
4605 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4606 if cursor_buffer != tail_buffer {
4607 return None;
4608 }
4609 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4610 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4611 cx.background_executor()
4612 .timer(Duration::from_millis(debounce))
4613 .await;
4614
4615 let highlights = if let Some(highlights) = cx
4616 .update(|cx| {
4617 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4618 })
4619 .ok()
4620 .flatten()
4621 {
4622 highlights.await.log_err()
4623 } else {
4624 None
4625 };
4626
4627 if let Some(highlights) = highlights {
4628 this.update(&mut cx, |this, cx| {
4629 if this.pending_rename.is_some() {
4630 return;
4631 }
4632
4633 let buffer_id = cursor_position.buffer_id;
4634 let buffer = this.buffer.read(cx);
4635 if !buffer
4636 .text_anchor_for_position(cursor_position, cx)
4637 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4638 {
4639 return;
4640 }
4641
4642 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4643 let mut write_ranges = Vec::new();
4644 let mut read_ranges = Vec::new();
4645 for highlight in highlights {
4646 for (excerpt_id, excerpt_range) in
4647 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4648 {
4649 let start = highlight
4650 .range
4651 .start
4652 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4653 let end = highlight
4654 .range
4655 .end
4656 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4657 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4658 continue;
4659 }
4660
4661 let range = Anchor {
4662 buffer_id,
4663 excerpt_id,
4664 text_anchor: start,
4665 diff_base_anchor: None,
4666 }..Anchor {
4667 buffer_id,
4668 excerpt_id,
4669 text_anchor: end,
4670 diff_base_anchor: None,
4671 };
4672 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4673 write_ranges.push(range);
4674 } else {
4675 read_ranges.push(range);
4676 }
4677 }
4678 }
4679
4680 this.highlight_background::<DocumentHighlightRead>(
4681 &read_ranges,
4682 |theme| theme.editor_document_highlight_read_background,
4683 cx,
4684 );
4685 this.highlight_background::<DocumentHighlightWrite>(
4686 &write_ranges,
4687 |theme| theme.editor_document_highlight_write_background,
4688 cx,
4689 );
4690 cx.notify();
4691 })
4692 .log_err();
4693 }
4694 }));
4695 None
4696 }
4697
4698 pub fn refresh_inline_completion(
4699 &mut self,
4700 debounce: bool,
4701 user_requested: bool,
4702 window: &mut Window,
4703 cx: &mut Context<Self>,
4704 ) -> Option<()> {
4705 let provider = self.edit_prediction_provider()?;
4706 let cursor = self.selections.newest_anchor().head();
4707 let (buffer, cursor_buffer_position) =
4708 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4709
4710 if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4711 self.discard_inline_completion(false, cx);
4712 return None;
4713 }
4714
4715 if !user_requested
4716 && (!self.should_show_edit_predictions()
4717 || !self.is_focused(window)
4718 || buffer.read(cx).is_empty())
4719 {
4720 self.discard_inline_completion(false, cx);
4721 return None;
4722 }
4723
4724 self.update_visible_inline_completion(window, cx);
4725 provider.refresh(
4726 self.project.clone(),
4727 buffer,
4728 cursor_buffer_position,
4729 debounce,
4730 cx,
4731 );
4732 Some(())
4733 }
4734
4735 fn show_edit_predictions_in_menu(&self) -> bool {
4736 match self.edit_prediction_settings {
4737 EditPredictionSettings::Disabled => false,
4738 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4739 }
4740 }
4741
4742 pub fn edit_predictions_enabled(&self) -> bool {
4743 match self.edit_prediction_settings {
4744 EditPredictionSettings::Disabled => false,
4745 EditPredictionSettings::Enabled { .. } => true,
4746 }
4747 }
4748
4749 fn edit_prediction_requires_modifier(&self) -> bool {
4750 match self.edit_prediction_settings {
4751 EditPredictionSettings::Disabled => false,
4752 EditPredictionSettings::Enabled {
4753 preview_requires_modifier,
4754 ..
4755 } => preview_requires_modifier,
4756 }
4757 }
4758
4759 fn edit_prediction_settings_at_position(
4760 &self,
4761 buffer: &Entity<Buffer>,
4762 buffer_position: language::Anchor,
4763 cx: &App,
4764 ) -> EditPredictionSettings {
4765 if self.mode != EditorMode::Full
4766 || !self.show_inline_completions_override.unwrap_or(true)
4767 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
4768 {
4769 return EditPredictionSettings::Disabled;
4770 }
4771
4772 let buffer = buffer.read(cx);
4773
4774 let file = buffer.file();
4775
4776 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
4777 return EditPredictionSettings::Disabled;
4778 };
4779
4780 let by_provider = matches!(
4781 self.menu_inline_completions_policy,
4782 MenuInlineCompletionsPolicy::ByProvider
4783 );
4784
4785 let show_in_menu = by_provider
4786 && self
4787 .edit_prediction_provider
4788 .as_ref()
4789 .map_or(false, |provider| {
4790 provider.provider.show_completions_in_menu()
4791 });
4792
4793 let preview_requires_modifier =
4794 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
4795
4796 EditPredictionSettings::Enabled {
4797 show_in_menu,
4798 preview_requires_modifier,
4799 }
4800 }
4801
4802 fn should_show_edit_predictions(&self) -> bool {
4803 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
4804 }
4805
4806 pub fn edit_prediction_preview_is_active(&self) -> bool {
4807 matches!(
4808 self.edit_prediction_preview,
4809 EditPredictionPreview::Active { .. }
4810 )
4811 }
4812
4813 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
4814 let cursor = self.selections.newest_anchor().head();
4815 if let Some((buffer, cursor_position)) =
4816 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4817 {
4818 self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
4819 } else {
4820 false
4821 }
4822 }
4823
4824 fn inline_completions_enabled_in_buffer(
4825 &self,
4826 buffer: &Entity<Buffer>,
4827 buffer_position: language::Anchor,
4828 cx: &App,
4829 ) -> bool {
4830 maybe!({
4831 let provider = self.edit_prediction_provider()?;
4832 if !provider.is_enabled(&buffer, buffer_position, cx) {
4833 return Some(false);
4834 }
4835 let buffer = buffer.read(cx);
4836 let Some(file) = buffer.file() else {
4837 return Some(true);
4838 };
4839 let settings = all_language_settings(Some(file), cx);
4840 Some(settings.inline_completions_enabled_for_path(file.path()))
4841 })
4842 .unwrap_or(false)
4843 }
4844
4845 fn cycle_inline_completion(
4846 &mut self,
4847 direction: Direction,
4848 window: &mut Window,
4849 cx: &mut Context<Self>,
4850 ) -> Option<()> {
4851 let provider = self.edit_prediction_provider()?;
4852 let cursor = self.selections.newest_anchor().head();
4853 let (buffer, cursor_buffer_position) =
4854 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4855 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
4856 return None;
4857 }
4858
4859 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4860 self.update_visible_inline_completion(window, cx);
4861
4862 Some(())
4863 }
4864
4865 pub fn show_inline_completion(
4866 &mut self,
4867 _: &ShowEditPrediction,
4868 window: &mut Window,
4869 cx: &mut Context<Self>,
4870 ) {
4871 if !self.has_active_inline_completion() {
4872 self.refresh_inline_completion(false, true, window, cx);
4873 return;
4874 }
4875
4876 self.update_visible_inline_completion(window, cx);
4877 }
4878
4879 pub fn display_cursor_names(
4880 &mut self,
4881 _: &DisplayCursorNames,
4882 window: &mut Window,
4883 cx: &mut Context<Self>,
4884 ) {
4885 self.show_cursor_names(window, cx);
4886 }
4887
4888 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4889 self.show_cursor_names = true;
4890 cx.notify();
4891 cx.spawn_in(window, |this, mut cx| async move {
4892 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4893 this.update(&mut cx, |this, cx| {
4894 this.show_cursor_names = false;
4895 cx.notify()
4896 })
4897 .ok()
4898 })
4899 .detach();
4900 }
4901
4902 pub fn next_edit_prediction(
4903 &mut self,
4904 _: &NextEditPrediction,
4905 window: &mut Window,
4906 cx: &mut Context<Self>,
4907 ) {
4908 if self.has_active_inline_completion() {
4909 self.cycle_inline_completion(Direction::Next, window, cx);
4910 } else {
4911 let is_copilot_disabled = self
4912 .refresh_inline_completion(false, true, window, cx)
4913 .is_none();
4914 if is_copilot_disabled {
4915 cx.propagate();
4916 }
4917 }
4918 }
4919
4920 pub fn previous_edit_prediction(
4921 &mut self,
4922 _: &PreviousEditPrediction,
4923 window: &mut Window,
4924 cx: &mut Context<Self>,
4925 ) {
4926 if self.has_active_inline_completion() {
4927 self.cycle_inline_completion(Direction::Prev, window, cx);
4928 } else {
4929 let is_copilot_disabled = self
4930 .refresh_inline_completion(false, true, window, cx)
4931 .is_none();
4932 if is_copilot_disabled {
4933 cx.propagate();
4934 }
4935 }
4936 }
4937
4938 pub fn accept_edit_prediction(
4939 &mut self,
4940 _: &AcceptEditPrediction,
4941 window: &mut Window,
4942 cx: &mut Context<Self>,
4943 ) {
4944 if self.show_edit_predictions_in_menu() {
4945 self.hide_context_menu(window, cx);
4946 }
4947
4948 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4949 return;
4950 };
4951
4952 self.report_inline_completion_event(
4953 active_inline_completion.completion_id.clone(),
4954 true,
4955 cx,
4956 );
4957
4958 match &active_inline_completion.completion {
4959 InlineCompletion::Move { target, .. } => {
4960 let target = *target;
4961
4962 if let Some(position_map) = &self.last_position_map {
4963 if position_map
4964 .visible_row_range
4965 .contains(&target.to_display_point(&position_map.snapshot).row())
4966 || !self.edit_prediction_requires_modifier()
4967 {
4968 // Note that this is also done in vim's handler of the Tab action.
4969 self.change_selections(
4970 Some(Autoscroll::newest()),
4971 window,
4972 cx,
4973 |selections| {
4974 selections.select_anchor_ranges([target..target]);
4975 },
4976 );
4977 self.clear_row_highlights::<EditPredictionPreview>();
4978
4979 self.edit_prediction_preview = EditPredictionPreview::Active {
4980 previous_scroll_position: None,
4981 };
4982 } else {
4983 self.edit_prediction_preview = EditPredictionPreview::Active {
4984 previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
4985 };
4986 self.highlight_rows::<EditPredictionPreview>(
4987 target..target,
4988 cx.theme().colors().editor_highlighted_line_background,
4989 true,
4990 cx,
4991 );
4992 self.request_autoscroll(Autoscroll::fit(), cx);
4993 }
4994 }
4995 }
4996 InlineCompletion::Edit { edits, .. } => {
4997 if let Some(provider) = self.edit_prediction_provider() {
4998 provider.accept(cx);
4999 }
5000
5001 let snapshot = self.buffer.read(cx).snapshot(cx);
5002 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5003
5004 self.buffer.update(cx, |buffer, cx| {
5005 buffer.edit(edits.iter().cloned(), None, cx)
5006 });
5007
5008 self.change_selections(None, window, cx, |s| {
5009 s.select_anchor_ranges([last_edit_end..last_edit_end])
5010 });
5011
5012 self.update_visible_inline_completion(window, cx);
5013 if self.active_inline_completion.is_none() {
5014 self.refresh_inline_completion(true, true, window, cx);
5015 }
5016
5017 cx.notify();
5018 }
5019 }
5020
5021 self.edit_prediction_requires_modifier_in_leading_space = false;
5022 }
5023
5024 pub fn accept_partial_inline_completion(
5025 &mut self,
5026 _: &AcceptPartialEditPrediction,
5027 window: &mut Window,
5028 cx: &mut Context<Self>,
5029 ) {
5030 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5031 return;
5032 };
5033 if self.selections.count() != 1 {
5034 return;
5035 }
5036
5037 self.report_inline_completion_event(
5038 active_inline_completion.completion_id.clone(),
5039 true,
5040 cx,
5041 );
5042
5043 match &active_inline_completion.completion {
5044 InlineCompletion::Move { target, .. } => {
5045 let target = *target;
5046 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5047 selections.select_anchor_ranges([target..target]);
5048 });
5049 }
5050 InlineCompletion::Edit { edits, .. } => {
5051 // Find an insertion that starts at the cursor position.
5052 let snapshot = self.buffer.read(cx).snapshot(cx);
5053 let cursor_offset = self.selections.newest::<usize>(cx).head();
5054 let insertion = edits.iter().find_map(|(range, text)| {
5055 let range = range.to_offset(&snapshot);
5056 if range.is_empty() && range.start == cursor_offset {
5057 Some(text)
5058 } else {
5059 None
5060 }
5061 });
5062
5063 if let Some(text) = insertion {
5064 let mut partial_completion = text
5065 .chars()
5066 .by_ref()
5067 .take_while(|c| c.is_alphabetic())
5068 .collect::<String>();
5069 if partial_completion.is_empty() {
5070 partial_completion = text
5071 .chars()
5072 .by_ref()
5073 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5074 .collect::<String>();
5075 }
5076
5077 cx.emit(EditorEvent::InputHandled {
5078 utf16_range_to_replace: None,
5079 text: partial_completion.clone().into(),
5080 });
5081
5082 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5083
5084 self.refresh_inline_completion(true, true, window, cx);
5085 cx.notify();
5086 } else {
5087 self.accept_edit_prediction(&Default::default(), window, cx);
5088 }
5089 }
5090 }
5091 }
5092
5093 fn discard_inline_completion(
5094 &mut self,
5095 should_report_inline_completion_event: bool,
5096 cx: &mut Context<Self>,
5097 ) -> bool {
5098 if should_report_inline_completion_event {
5099 let completion_id = self
5100 .active_inline_completion
5101 .as_ref()
5102 .and_then(|active_completion| active_completion.completion_id.clone());
5103
5104 self.report_inline_completion_event(completion_id, false, cx);
5105 }
5106
5107 if let Some(provider) = self.edit_prediction_provider() {
5108 provider.discard(cx);
5109 }
5110
5111 self.take_active_inline_completion(cx)
5112 }
5113
5114 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5115 let Some(provider) = self.edit_prediction_provider() else {
5116 return;
5117 };
5118
5119 let Some((_, buffer, _)) = self
5120 .buffer
5121 .read(cx)
5122 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5123 else {
5124 return;
5125 };
5126
5127 let extension = buffer
5128 .read(cx)
5129 .file()
5130 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5131
5132 let event_type = match accepted {
5133 true => "Edit Prediction Accepted",
5134 false => "Edit Prediction Discarded",
5135 };
5136 telemetry::event!(
5137 event_type,
5138 provider = provider.name(),
5139 prediction_id = id,
5140 suggestion_accepted = accepted,
5141 file_extension = extension,
5142 );
5143 }
5144
5145 pub fn has_active_inline_completion(&self) -> bool {
5146 self.active_inline_completion.is_some()
5147 }
5148
5149 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5150 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5151 return false;
5152 };
5153
5154 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5155 self.clear_highlights::<InlineCompletionHighlight>(cx);
5156 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5157 true
5158 }
5159
5160 /// Returns true when we're displaying the edit prediction popover below the cursor
5161 /// like we are not previewing and the LSP autocomplete menu is visible
5162 /// or we are in `when_holding_modifier` mode.
5163 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5164 if self.edit_prediction_preview_is_active()
5165 || !self.show_edit_predictions_in_menu()
5166 || !self.edit_predictions_enabled()
5167 {
5168 return false;
5169 }
5170
5171 if self.has_visible_completions_menu() {
5172 return true;
5173 }
5174
5175 has_completion && self.edit_prediction_requires_modifier()
5176 }
5177
5178 fn handle_modifiers_changed(
5179 &mut self,
5180 modifiers: Modifiers,
5181 position_map: &PositionMap,
5182 window: &mut Window,
5183 cx: &mut Context<Self>,
5184 ) {
5185 if self.show_edit_predictions_in_menu() {
5186 self.update_edit_prediction_preview(&modifiers, window, cx);
5187 }
5188
5189 let mouse_position = window.mouse_position();
5190 if !position_map.text_hitbox.is_hovered(window) {
5191 return;
5192 }
5193
5194 self.update_hovered_link(
5195 position_map.point_for_position(mouse_position),
5196 &position_map.snapshot,
5197 modifiers,
5198 window,
5199 cx,
5200 )
5201 }
5202
5203 fn update_edit_prediction_preview(
5204 &mut self,
5205 modifiers: &Modifiers,
5206 window: &mut Window,
5207 cx: &mut Context<Self>,
5208 ) {
5209 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5210 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5211 return;
5212 };
5213
5214 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5215 if matches!(
5216 self.edit_prediction_preview,
5217 EditPredictionPreview::Inactive
5218 ) {
5219 self.edit_prediction_preview = EditPredictionPreview::Active {
5220 previous_scroll_position: None,
5221 };
5222
5223 self.update_visible_inline_completion(window, cx);
5224 cx.notify();
5225 }
5226 } else if let EditPredictionPreview::Active {
5227 previous_scroll_position,
5228 } = self.edit_prediction_preview
5229 {
5230 if let (Some(previous_scroll_position), Some(position_map)) =
5231 (previous_scroll_position, self.last_position_map.as_ref())
5232 {
5233 self.set_scroll_position(
5234 previous_scroll_position
5235 .scroll_position(&position_map.snapshot.display_snapshot),
5236 window,
5237 cx,
5238 );
5239 }
5240
5241 self.edit_prediction_preview = EditPredictionPreview::Inactive;
5242 self.clear_row_highlights::<EditPredictionPreview>();
5243 self.update_visible_inline_completion(window, cx);
5244 cx.notify();
5245 }
5246 }
5247
5248 fn update_visible_inline_completion(
5249 &mut self,
5250 _window: &mut Window,
5251 cx: &mut Context<Self>,
5252 ) -> Option<()> {
5253 let selection = self.selections.newest_anchor();
5254 let cursor = selection.head();
5255 let multibuffer = self.buffer.read(cx).snapshot(cx);
5256 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5257 let excerpt_id = cursor.excerpt_id;
5258
5259 let show_in_menu = self.show_edit_predictions_in_menu();
5260 let completions_menu_has_precedence = !show_in_menu
5261 && (self.context_menu.borrow().is_some()
5262 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5263
5264 if completions_menu_has_precedence
5265 || !offset_selection.is_empty()
5266 || self
5267 .active_inline_completion
5268 .as_ref()
5269 .map_or(false, |completion| {
5270 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5271 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5272 !invalidation_range.contains(&offset_selection.head())
5273 })
5274 {
5275 self.discard_inline_completion(false, cx);
5276 return None;
5277 }
5278
5279 self.take_active_inline_completion(cx);
5280 let Some(provider) = self.edit_prediction_provider() else {
5281 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5282 return None;
5283 };
5284
5285 let (buffer, cursor_buffer_position) =
5286 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5287
5288 self.edit_prediction_settings =
5289 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5290
5291 if !self.edit_prediction_settings.is_enabled() {
5292 self.discard_inline_completion(false, cx);
5293 return None;
5294 }
5295
5296 self.edit_prediction_cursor_on_leading_whitespace =
5297 multibuffer.is_line_whitespace_upto(cursor);
5298
5299 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5300 let edits = inline_completion
5301 .edits
5302 .into_iter()
5303 .flat_map(|(range, new_text)| {
5304 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5305 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5306 Some((start..end, new_text))
5307 })
5308 .collect::<Vec<_>>();
5309 if edits.is_empty() {
5310 return None;
5311 }
5312
5313 let first_edit_start = edits.first().unwrap().0.start;
5314 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5315 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5316
5317 let last_edit_end = edits.last().unwrap().0.end;
5318 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5319 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5320
5321 let cursor_row = cursor.to_point(&multibuffer).row;
5322
5323 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5324
5325 let mut inlay_ids = Vec::new();
5326 let invalidation_row_range;
5327 let move_invalidation_row_range = if cursor_row < edit_start_row {
5328 Some(cursor_row..edit_end_row)
5329 } else if cursor_row > edit_end_row {
5330 Some(edit_start_row..cursor_row)
5331 } else {
5332 None
5333 };
5334 let is_move =
5335 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5336 let completion = if is_move {
5337 invalidation_row_range =
5338 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5339 let target = first_edit_start;
5340 InlineCompletion::Move { target, snapshot }
5341 } else {
5342 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5343 && !self.inline_completions_hidden_for_vim_mode;
5344
5345 if show_completions_in_buffer {
5346 if edits
5347 .iter()
5348 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5349 {
5350 let mut inlays = Vec::new();
5351 for (range, new_text) in &edits {
5352 let inlay = Inlay::inline_completion(
5353 post_inc(&mut self.next_inlay_id),
5354 range.start,
5355 new_text.as_str(),
5356 );
5357 inlay_ids.push(inlay.id);
5358 inlays.push(inlay);
5359 }
5360
5361 self.splice_inlays(&[], inlays, cx);
5362 } else {
5363 let background_color = cx.theme().status().deleted_background;
5364 self.highlight_text::<InlineCompletionHighlight>(
5365 edits.iter().map(|(range, _)| range.clone()).collect(),
5366 HighlightStyle {
5367 background_color: Some(background_color),
5368 ..Default::default()
5369 },
5370 cx,
5371 );
5372 }
5373 }
5374
5375 invalidation_row_range = edit_start_row..edit_end_row;
5376
5377 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5378 if provider.show_tab_accept_marker() {
5379 EditDisplayMode::TabAccept
5380 } else {
5381 EditDisplayMode::Inline
5382 }
5383 } else {
5384 EditDisplayMode::DiffPopover
5385 };
5386
5387 InlineCompletion::Edit {
5388 edits,
5389 edit_preview: inline_completion.edit_preview,
5390 display_mode,
5391 snapshot,
5392 }
5393 };
5394
5395 let invalidation_range = multibuffer
5396 .anchor_before(Point::new(invalidation_row_range.start, 0))
5397 ..multibuffer.anchor_after(Point::new(
5398 invalidation_row_range.end,
5399 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5400 ));
5401
5402 self.stale_inline_completion_in_menu = None;
5403 self.active_inline_completion = Some(InlineCompletionState {
5404 inlay_ids,
5405 completion,
5406 completion_id: inline_completion.id,
5407 invalidation_range,
5408 });
5409
5410 cx.notify();
5411
5412 Some(())
5413 }
5414
5415 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5416 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5417 }
5418
5419 fn render_code_actions_indicator(
5420 &self,
5421 _style: &EditorStyle,
5422 row: DisplayRow,
5423 is_active: bool,
5424 cx: &mut Context<Self>,
5425 ) -> Option<IconButton> {
5426 if self.available_code_actions.is_some() {
5427 Some(
5428 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5429 .shape(ui::IconButtonShape::Square)
5430 .icon_size(IconSize::XSmall)
5431 .icon_color(Color::Muted)
5432 .toggle_state(is_active)
5433 .tooltip({
5434 let focus_handle = self.focus_handle.clone();
5435 move |window, cx| {
5436 Tooltip::for_action_in(
5437 "Toggle Code Actions",
5438 &ToggleCodeActions {
5439 deployed_from_indicator: None,
5440 },
5441 &focus_handle,
5442 window,
5443 cx,
5444 )
5445 }
5446 })
5447 .on_click(cx.listener(move |editor, _e, window, cx| {
5448 window.focus(&editor.focus_handle(cx));
5449 editor.toggle_code_actions(
5450 &ToggleCodeActions {
5451 deployed_from_indicator: Some(row),
5452 },
5453 window,
5454 cx,
5455 );
5456 })),
5457 )
5458 } else {
5459 None
5460 }
5461 }
5462
5463 fn clear_tasks(&mut self) {
5464 self.tasks.clear()
5465 }
5466
5467 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5468 if self.tasks.insert(key, value).is_some() {
5469 // This case should hopefully be rare, but just in case...
5470 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5471 }
5472 }
5473
5474 fn build_tasks_context(
5475 project: &Entity<Project>,
5476 buffer: &Entity<Buffer>,
5477 buffer_row: u32,
5478 tasks: &Arc<RunnableTasks>,
5479 cx: &mut Context<Self>,
5480 ) -> Task<Option<task::TaskContext>> {
5481 let position = Point::new(buffer_row, tasks.column);
5482 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5483 let location = Location {
5484 buffer: buffer.clone(),
5485 range: range_start..range_start,
5486 };
5487 // Fill in the environmental variables from the tree-sitter captures
5488 let mut captured_task_variables = TaskVariables::default();
5489 for (capture_name, value) in tasks.extra_variables.clone() {
5490 captured_task_variables.insert(
5491 task::VariableName::Custom(capture_name.into()),
5492 value.clone(),
5493 );
5494 }
5495 project.update(cx, |project, cx| {
5496 project.task_store().update(cx, |task_store, cx| {
5497 task_store.task_context_for_location(captured_task_variables, location, cx)
5498 })
5499 })
5500 }
5501
5502 pub fn spawn_nearest_task(
5503 &mut self,
5504 action: &SpawnNearestTask,
5505 window: &mut Window,
5506 cx: &mut Context<Self>,
5507 ) {
5508 let Some((workspace, _)) = self.workspace.clone() else {
5509 return;
5510 };
5511 let Some(project) = self.project.clone() else {
5512 return;
5513 };
5514
5515 // Try to find a closest, enclosing node using tree-sitter that has a
5516 // task
5517 let Some((buffer, buffer_row, tasks)) = self
5518 .find_enclosing_node_task(cx)
5519 // Or find the task that's closest in row-distance.
5520 .or_else(|| self.find_closest_task(cx))
5521 else {
5522 return;
5523 };
5524
5525 let reveal_strategy = action.reveal;
5526 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5527 cx.spawn_in(window, |_, mut cx| async move {
5528 let context = task_context.await?;
5529 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5530
5531 let resolved = resolved_task.resolved.as_mut()?;
5532 resolved.reveal = reveal_strategy;
5533
5534 workspace
5535 .update(&mut cx, |workspace, cx| {
5536 workspace::tasks::schedule_resolved_task(
5537 workspace,
5538 task_source_kind,
5539 resolved_task,
5540 false,
5541 cx,
5542 );
5543 })
5544 .ok()
5545 })
5546 .detach();
5547 }
5548
5549 fn find_closest_task(
5550 &mut self,
5551 cx: &mut Context<Self>,
5552 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5553 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5554
5555 let ((buffer_id, row), tasks) = self
5556 .tasks
5557 .iter()
5558 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5559
5560 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5561 let tasks = Arc::new(tasks.to_owned());
5562 Some((buffer, *row, tasks))
5563 }
5564
5565 fn find_enclosing_node_task(
5566 &mut self,
5567 cx: &mut Context<Self>,
5568 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5569 let snapshot = self.buffer.read(cx).snapshot(cx);
5570 let offset = self.selections.newest::<usize>(cx).head();
5571 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5572 let buffer_id = excerpt.buffer().remote_id();
5573
5574 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5575 let mut cursor = layer.node().walk();
5576
5577 while cursor.goto_first_child_for_byte(offset).is_some() {
5578 if cursor.node().end_byte() == offset {
5579 cursor.goto_next_sibling();
5580 }
5581 }
5582
5583 // Ascend to the smallest ancestor that contains the range and has a task.
5584 loop {
5585 let node = cursor.node();
5586 let node_range = node.byte_range();
5587 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5588
5589 // Check if this node contains our offset
5590 if node_range.start <= offset && node_range.end >= offset {
5591 // If it contains offset, check for task
5592 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5593 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5594 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5595 }
5596 }
5597
5598 if !cursor.goto_parent() {
5599 break;
5600 }
5601 }
5602 None
5603 }
5604
5605 fn render_run_indicator(
5606 &self,
5607 _style: &EditorStyle,
5608 is_active: bool,
5609 row: DisplayRow,
5610 cx: &mut Context<Self>,
5611 ) -> IconButton {
5612 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5613 .shape(ui::IconButtonShape::Square)
5614 .icon_size(IconSize::XSmall)
5615 .icon_color(Color::Muted)
5616 .toggle_state(is_active)
5617 .on_click(cx.listener(move |editor, _e, window, cx| {
5618 window.focus(&editor.focus_handle(cx));
5619 editor.toggle_code_actions(
5620 &ToggleCodeActions {
5621 deployed_from_indicator: Some(row),
5622 },
5623 window,
5624 cx,
5625 );
5626 }))
5627 }
5628
5629 pub fn context_menu_visible(&self) -> bool {
5630 !self.edit_prediction_preview_is_active()
5631 && self
5632 .context_menu
5633 .borrow()
5634 .as_ref()
5635 .map_or(false, |menu| menu.visible())
5636 }
5637
5638 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5639 self.context_menu
5640 .borrow()
5641 .as_ref()
5642 .map(|menu| menu.origin())
5643 }
5644
5645 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5646 px(30.)
5647 }
5648
5649 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5650 if self.read_only(cx) {
5651 cx.theme().players().read_only()
5652 } else {
5653 self.style.as_ref().unwrap().local_player
5654 }
5655 }
5656
5657 fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
5658 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
5659 let accept_keystroke = accept_binding.keystroke()?;
5660 let colors = cx.theme().colors();
5661 let accent_color = colors.text_accent;
5662 let editor_bg_color = colors.editor_background;
5663 let bg_color = editor_bg_color.blend(accent_color.opacity(0.1));
5664
5665 h_flex()
5666 .px_0p5()
5667 .gap_1()
5668 .bg(bg_color)
5669 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
5670 .text_size(TextSize::XSmall.rems(cx))
5671 .children(ui::render_modifiers(
5672 &accept_keystroke.modifiers,
5673 PlatformStyle::platform(),
5674 Some(if accept_keystroke.modifiers == window.modifiers() {
5675 Color::Accent
5676 } else {
5677 Color::Muted
5678 }),
5679 Some(IconSize::XSmall.rems().into()),
5680 false,
5681 ))
5682 .child(accept_keystroke.key.clone())
5683 .into()
5684 }
5685
5686 fn render_edit_prediction_line_popover(
5687 &self,
5688 label: impl Into<SharedString>,
5689 icon: Option<IconName>,
5690 window: &mut Window,
5691 cx: &App,
5692 ) -> Option<Div> {
5693 let bg_color = Self::edit_prediction_line_popover_bg_color(cx);
5694
5695 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
5696
5697 let result = h_flex()
5698 .gap_1()
5699 .border_1()
5700 .rounded_lg()
5701 .shadow_sm()
5702 .bg(bg_color)
5703 .border_color(cx.theme().colors().text_accent.opacity(0.4))
5704 .py_0p5()
5705 .pl_1()
5706 .pr(padding_right)
5707 .children(self.render_edit_prediction_accept_keybind(window, cx))
5708 .child(Label::new(label).size(LabelSize::Small))
5709 .when_some(icon, |element, icon| {
5710 element.child(
5711 div()
5712 .mt(px(1.5))
5713 .child(Icon::new(icon).size(IconSize::Small)),
5714 )
5715 });
5716
5717 Some(result)
5718 }
5719
5720 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
5721 let accent_color = cx.theme().colors().text_accent;
5722 let editor_bg_color = cx.theme().colors().editor_background;
5723 editor_bg_color.blend(accent_color.opacity(0.1))
5724 }
5725
5726 #[allow(clippy::too_many_arguments)]
5727 fn render_edit_prediction_cursor_popover(
5728 &self,
5729 min_width: Pixels,
5730 max_width: Pixels,
5731 cursor_point: Point,
5732 style: &EditorStyle,
5733 accept_keystroke: &gpui::Keystroke,
5734 _window: &Window,
5735 cx: &mut Context<Editor>,
5736 ) -> Option<AnyElement> {
5737 let provider = self.edit_prediction_provider.as_ref()?;
5738
5739 if provider.provider.needs_terms_acceptance(cx) {
5740 return Some(
5741 h_flex()
5742 .min_w(min_width)
5743 .flex_1()
5744 .px_2()
5745 .py_1()
5746 .gap_3()
5747 .elevation_2(cx)
5748 .hover(|style| style.bg(cx.theme().colors().element_hover))
5749 .id("accept-terms")
5750 .cursor_pointer()
5751 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5752 .on_click(cx.listener(|this, _event, window, cx| {
5753 cx.stop_propagation();
5754 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
5755 window.dispatch_action(
5756 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
5757 cx,
5758 );
5759 }))
5760 .child(
5761 h_flex()
5762 .flex_1()
5763 .gap_2()
5764 .child(Icon::new(IconName::ZedPredict))
5765 .child(Label::new("Accept Terms of Service"))
5766 .child(div().w_full())
5767 .child(
5768 Icon::new(IconName::ArrowUpRight)
5769 .color(Color::Muted)
5770 .size(IconSize::Small),
5771 )
5772 .into_any_element(),
5773 )
5774 .into_any(),
5775 );
5776 }
5777
5778 let is_refreshing = provider.provider.is_refreshing(cx);
5779
5780 fn pending_completion_container() -> Div {
5781 h_flex()
5782 .h_full()
5783 .flex_1()
5784 .gap_2()
5785 .child(Icon::new(IconName::ZedPredict))
5786 }
5787
5788 let completion = match &self.active_inline_completion {
5789 Some(completion) => match &completion.completion {
5790 InlineCompletion::Move {
5791 target, snapshot, ..
5792 } if !self.has_visible_completions_menu() => {
5793 use text::ToPoint as _;
5794
5795 return Some(
5796 h_flex()
5797 .px_2()
5798 .py_1()
5799 .elevation_2(cx)
5800 .border_color(cx.theme().colors().border)
5801 .rounded_tl(px(0.))
5802 .gap_2()
5803 .child(
5804 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
5805 Icon::new(IconName::ZedPredictDown)
5806 } else {
5807 Icon::new(IconName::ZedPredictUp)
5808 },
5809 )
5810 .child(Label::new("Hold").size(LabelSize::Small))
5811 .children(ui::render_modifiers(
5812 &accept_keystroke.modifiers,
5813 PlatformStyle::platform(),
5814 Some(Color::Default),
5815 Some(IconSize::Small.rems().into()),
5816 true,
5817 ))
5818 .into_any(),
5819 );
5820 }
5821 _ => self.render_edit_prediction_cursor_popover_preview(
5822 completion,
5823 cursor_point,
5824 style,
5825 cx,
5826 )?,
5827 },
5828
5829 None if is_refreshing => match &self.stale_inline_completion_in_menu {
5830 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
5831 stale_completion,
5832 cursor_point,
5833 style,
5834 cx,
5835 )?,
5836
5837 None => {
5838 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
5839 }
5840 },
5841
5842 None => pending_completion_container().child(Label::new("No Prediction")),
5843 };
5844
5845 let completion = if is_refreshing {
5846 completion
5847 .with_animation(
5848 "loading-completion",
5849 Animation::new(Duration::from_secs(2))
5850 .repeat()
5851 .with_easing(pulsating_between(0.4, 0.8)),
5852 |label, delta| label.opacity(delta),
5853 )
5854 .into_any_element()
5855 } else {
5856 completion.into_any_element()
5857 };
5858
5859 let has_completion = self.active_inline_completion.is_some();
5860
5861 Some(
5862 h_flex()
5863 .min_w(min_width)
5864 .max_w(max_width)
5865 .flex_1()
5866 .elevation_2(cx)
5867 .border_color(cx.theme().colors().border)
5868 .child(
5869 div()
5870 .flex_1()
5871 .py_1()
5872 .px_2()
5873 .overflow_hidden()
5874 .child(completion),
5875 )
5876 .child(
5877 h_flex()
5878 .h_full()
5879 .border_l_1()
5880 .rounded_r_lg()
5881 .border_color(cx.theme().colors().border)
5882 .bg(Self::edit_prediction_line_popover_bg_color(cx))
5883 .gap_1()
5884 .py_1()
5885 .px_2()
5886 .child(
5887 h_flex()
5888 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
5889 .gap_1()
5890 .children(ui::render_modifiers(
5891 &accept_keystroke.modifiers,
5892 PlatformStyle::platform(),
5893 Some(if !has_completion {
5894 Color::Muted
5895 } else {
5896 Color::Default
5897 }),
5898 None,
5899 true,
5900 )),
5901 )
5902 .child(Label::new("Preview").into_any_element())
5903 .opacity(if has_completion { 1.0 } else { 0.4 }),
5904 )
5905 .into_any(),
5906 )
5907 }
5908
5909 fn render_edit_prediction_cursor_popover_preview(
5910 &self,
5911 completion: &InlineCompletionState,
5912 cursor_point: Point,
5913 style: &EditorStyle,
5914 cx: &mut Context<Editor>,
5915 ) -> Option<Div> {
5916 use text::ToPoint as _;
5917
5918 fn render_relative_row_jump(
5919 prefix: impl Into<String>,
5920 current_row: u32,
5921 target_row: u32,
5922 ) -> Div {
5923 let (row_diff, arrow) = if target_row < current_row {
5924 (current_row - target_row, IconName::ArrowUp)
5925 } else {
5926 (target_row - current_row, IconName::ArrowDown)
5927 };
5928
5929 h_flex()
5930 .child(
5931 Label::new(format!("{}{}", prefix.into(), row_diff))
5932 .color(Color::Muted)
5933 .size(LabelSize::Small),
5934 )
5935 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
5936 }
5937
5938 match &completion.completion {
5939 InlineCompletion::Move {
5940 target, snapshot, ..
5941 } => Some(
5942 h_flex()
5943 .px_2()
5944 .gap_2()
5945 .flex_1()
5946 .child(
5947 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
5948 Icon::new(IconName::ZedPredictDown)
5949 } else {
5950 Icon::new(IconName::ZedPredictUp)
5951 },
5952 )
5953 .child(Label::new("Jump to Edit")),
5954 ),
5955
5956 InlineCompletion::Edit {
5957 edits,
5958 edit_preview,
5959 snapshot,
5960 display_mode: _,
5961 } => {
5962 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
5963
5964 let highlighted_edits = crate::inline_completion_edit_text(
5965 &snapshot,
5966 &edits,
5967 edit_preview.as_ref()?,
5968 true,
5969 cx,
5970 );
5971
5972 let len_total = highlighted_edits.text.len();
5973 let first_line = &highlighted_edits.text
5974 [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
5975 let first_line_len = first_line.len();
5976
5977 let first_highlight_start = highlighted_edits
5978 .highlights
5979 .first()
5980 .map_or(0, |(range, _)| range.start);
5981 let drop_prefix_len = first_line
5982 .char_indices()
5983 .find(|(_, c)| !c.is_whitespace())
5984 .map_or(first_highlight_start, |(ix, _)| {
5985 ix.min(first_highlight_start)
5986 });
5987
5988 let preview_text = &first_line[drop_prefix_len..];
5989 let preview_len = preview_text.len();
5990 let highlights = highlighted_edits
5991 .highlights
5992 .into_iter()
5993 .take_until(|(range, _)| range.start > first_line_len)
5994 .map(|(range, style)| {
5995 (
5996 range.start - drop_prefix_len
5997 ..(range.end - drop_prefix_len).min(preview_len),
5998 style,
5999 )
6000 });
6001
6002 let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
6003 .with_highlights(&style.text, highlights);
6004
6005 let preview = h_flex()
6006 .gap_1()
6007 .min_w_16()
6008 .child(styled_text)
6009 .when(len_total > first_line_len, |parent| parent.child("…"));
6010
6011 let left = if first_edit_row != cursor_point.row {
6012 render_relative_row_jump("", cursor_point.row, first_edit_row)
6013 .into_any_element()
6014 } else {
6015 Icon::new(IconName::ZedPredict).into_any_element()
6016 };
6017
6018 Some(
6019 h_flex()
6020 .h_full()
6021 .flex_1()
6022 .gap_2()
6023 .pr_1()
6024 .overflow_x_hidden()
6025 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6026 .child(left)
6027 .child(preview),
6028 )
6029 }
6030 }
6031 }
6032
6033 fn render_context_menu(
6034 &self,
6035 style: &EditorStyle,
6036 max_height_in_lines: u32,
6037 y_flipped: bool,
6038 window: &mut Window,
6039 cx: &mut Context<Editor>,
6040 ) -> Option<AnyElement> {
6041 let menu = self.context_menu.borrow();
6042 let menu = menu.as_ref()?;
6043 if !menu.visible() {
6044 return None;
6045 };
6046 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6047 }
6048
6049 fn render_context_menu_aside(
6050 &self,
6051 style: &EditorStyle,
6052 max_size: Size<Pixels>,
6053 cx: &mut Context<Editor>,
6054 ) -> Option<AnyElement> {
6055 self.context_menu.borrow().as_ref().and_then(|menu| {
6056 if menu.visible() {
6057 menu.render_aside(
6058 style,
6059 max_size,
6060 self.workspace.as_ref().map(|(w, _)| w.clone()),
6061 cx,
6062 )
6063 } else {
6064 None
6065 }
6066 })
6067 }
6068
6069 fn hide_context_menu(
6070 &mut self,
6071 window: &mut Window,
6072 cx: &mut Context<Self>,
6073 ) -> Option<CodeContextMenu> {
6074 cx.notify();
6075 self.completion_tasks.clear();
6076 let context_menu = self.context_menu.borrow_mut().take();
6077 self.stale_inline_completion_in_menu.take();
6078 self.update_visible_inline_completion(window, cx);
6079 context_menu
6080 }
6081
6082 fn show_snippet_choices(
6083 &mut self,
6084 choices: &Vec<String>,
6085 selection: Range<Anchor>,
6086 cx: &mut Context<Self>,
6087 ) {
6088 if selection.start.buffer_id.is_none() {
6089 return;
6090 }
6091 let buffer_id = selection.start.buffer_id.unwrap();
6092 let buffer = self.buffer().read(cx).buffer(buffer_id);
6093 let id = post_inc(&mut self.next_completion_id);
6094
6095 if let Some(buffer) = buffer {
6096 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6097 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6098 ));
6099 }
6100 }
6101
6102 pub fn insert_snippet(
6103 &mut self,
6104 insertion_ranges: &[Range<usize>],
6105 snippet: Snippet,
6106 window: &mut Window,
6107 cx: &mut Context<Self>,
6108 ) -> Result<()> {
6109 struct Tabstop<T> {
6110 is_end_tabstop: bool,
6111 ranges: Vec<Range<T>>,
6112 choices: Option<Vec<String>>,
6113 }
6114
6115 let tabstops = self.buffer.update(cx, |buffer, cx| {
6116 let snippet_text: Arc<str> = snippet.text.clone().into();
6117 buffer.edit(
6118 insertion_ranges
6119 .iter()
6120 .cloned()
6121 .map(|range| (range, snippet_text.clone())),
6122 Some(AutoindentMode::EachLine),
6123 cx,
6124 );
6125
6126 let snapshot = &*buffer.read(cx);
6127 let snippet = &snippet;
6128 snippet
6129 .tabstops
6130 .iter()
6131 .map(|tabstop| {
6132 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6133 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6134 });
6135 let mut tabstop_ranges = tabstop
6136 .ranges
6137 .iter()
6138 .flat_map(|tabstop_range| {
6139 let mut delta = 0_isize;
6140 insertion_ranges.iter().map(move |insertion_range| {
6141 let insertion_start = insertion_range.start as isize + delta;
6142 delta +=
6143 snippet.text.len() as isize - insertion_range.len() as isize;
6144
6145 let start = ((insertion_start + tabstop_range.start) as usize)
6146 .min(snapshot.len());
6147 let end = ((insertion_start + tabstop_range.end) as usize)
6148 .min(snapshot.len());
6149 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6150 })
6151 })
6152 .collect::<Vec<_>>();
6153 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6154
6155 Tabstop {
6156 is_end_tabstop,
6157 ranges: tabstop_ranges,
6158 choices: tabstop.choices.clone(),
6159 }
6160 })
6161 .collect::<Vec<_>>()
6162 });
6163 if let Some(tabstop) = tabstops.first() {
6164 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6165 s.select_ranges(tabstop.ranges.iter().cloned());
6166 });
6167
6168 if let Some(choices) = &tabstop.choices {
6169 if let Some(selection) = tabstop.ranges.first() {
6170 self.show_snippet_choices(choices, selection.clone(), cx)
6171 }
6172 }
6173
6174 // If we're already at the last tabstop and it's at the end of the snippet,
6175 // we're done, we don't need to keep the state around.
6176 if !tabstop.is_end_tabstop {
6177 let choices = tabstops
6178 .iter()
6179 .map(|tabstop| tabstop.choices.clone())
6180 .collect();
6181
6182 let ranges = tabstops
6183 .into_iter()
6184 .map(|tabstop| tabstop.ranges)
6185 .collect::<Vec<_>>();
6186
6187 self.snippet_stack.push(SnippetState {
6188 active_index: 0,
6189 ranges,
6190 choices,
6191 });
6192 }
6193
6194 // Check whether the just-entered snippet ends with an auto-closable bracket.
6195 if self.autoclose_regions.is_empty() {
6196 let snapshot = self.buffer.read(cx).snapshot(cx);
6197 for selection in &mut self.selections.all::<Point>(cx) {
6198 let selection_head = selection.head();
6199 let Some(scope) = snapshot.language_scope_at(selection_head) else {
6200 continue;
6201 };
6202
6203 let mut bracket_pair = None;
6204 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
6205 let prev_chars = snapshot
6206 .reversed_chars_at(selection_head)
6207 .collect::<String>();
6208 for (pair, enabled) in scope.brackets() {
6209 if enabled
6210 && pair.close
6211 && prev_chars.starts_with(pair.start.as_str())
6212 && next_chars.starts_with(pair.end.as_str())
6213 {
6214 bracket_pair = Some(pair.clone());
6215 break;
6216 }
6217 }
6218 if let Some(pair) = bracket_pair {
6219 let start = snapshot.anchor_after(selection_head);
6220 let end = snapshot.anchor_after(selection_head);
6221 self.autoclose_regions.push(AutocloseRegion {
6222 selection_id: selection.id,
6223 range: start..end,
6224 pair,
6225 });
6226 }
6227 }
6228 }
6229 }
6230 Ok(())
6231 }
6232
6233 pub fn move_to_next_snippet_tabstop(
6234 &mut self,
6235 window: &mut Window,
6236 cx: &mut Context<Self>,
6237 ) -> bool {
6238 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6239 }
6240
6241 pub fn move_to_prev_snippet_tabstop(
6242 &mut self,
6243 window: &mut Window,
6244 cx: &mut Context<Self>,
6245 ) -> bool {
6246 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6247 }
6248
6249 pub fn move_to_snippet_tabstop(
6250 &mut self,
6251 bias: Bias,
6252 window: &mut Window,
6253 cx: &mut Context<Self>,
6254 ) -> bool {
6255 if let Some(mut snippet) = self.snippet_stack.pop() {
6256 match bias {
6257 Bias::Left => {
6258 if snippet.active_index > 0 {
6259 snippet.active_index -= 1;
6260 } else {
6261 self.snippet_stack.push(snippet);
6262 return false;
6263 }
6264 }
6265 Bias::Right => {
6266 if snippet.active_index + 1 < snippet.ranges.len() {
6267 snippet.active_index += 1;
6268 } else {
6269 self.snippet_stack.push(snippet);
6270 return false;
6271 }
6272 }
6273 }
6274 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6275 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6276 s.select_anchor_ranges(current_ranges.iter().cloned())
6277 });
6278
6279 if let Some(choices) = &snippet.choices[snippet.active_index] {
6280 if let Some(selection) = current_ranges.first() {
6281 self.show_snippet_choices(&choices, selection.clone(), cx);
6282 }
6283 }
6284
6285 // If snippet state is not at the last tabstop, push it back on the stack
6286 if snippet.active_index + 1 < snippet.ranges.len() {
6287 self.snippet_stack.push(snippet);
6288 }
6289 return true;
6290 }
6291 }
6292
6293 false
6294 }
6295
6296 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6297 self.transact(window, cx, |this, window, cx| {
6298 this.select_all(&SelectAll, window, cx);
6299 this.insert("", window, cx);
6300 });
6301 }
6302
6303 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6304 self.transact(window, cx, |this, window, cx| {
6305 this.select_autoclose_pair(window, cx);
6306 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6307 if !this.linked_edit_ranges.is_empty() {
6308 let selections = this.selections.all::<MultiBufferPoint>(cx);
6309 let snapshot = this.buffer.read(cx).snapshot(cx);
6310
6311 for selection in selections.iter() {
6312 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6313 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6314 if selection_start.buffer_id != selection_end.buffer_id {
6315 continue;
6316 }
6317 if let Some(ranges) =
6318 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6319 {
6320 for (buffer, entries) in ranges {
6321 linked_ranges.entry(buffer).or_default().extend(entries);
6322 }
6323 }
6324 }
6325 }
6326
6327 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6328 if !this.selections.line_mode {
6329 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6330 for selection in &mut selections {
6331 if selection.is_empty() {
6332 let old_head = selection.head();
6333 let mut new_head =
6334 movement::left(&display_map, old_head.to_display_point(&display_map))
6335 .to_point(&display_map);
6336 if let Some((buffer, line_buffer_range)) = display_map
6337 .buffer_snapshot
6338 .buffer_line_for_row(MultiBufferRow(old_head.row))
6339 {
6340 let indent_size =
6341 buffer.indent_size_for_line(line_buffer_range.start.row);
6342 let indent_len = match indent_size.kind {
6343 IndentKind::Space => {
6344 buffer.settings_at(line_buffer_range.start, cx).tab_size
6345 }
6346 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6347 };
6348 if old_head.column <= indent_size.len && old_head.column > 0 {
6349 let indent_len = indent_len.get();
6350 new_head = cmp::min(
6351 new_head,
6352 MultiBufferPoint::new(
6353 old_head.row,
6354 ((old_head.column - 1) / indent_len) * indent_len,
6355 ),
6356 );
6357 }
6358 }
6359
6360 selection.set_head(new_head, SelectionGoal::None);
6361 }
6362 }
6363 }
6364
6365 this.signature_help_state.set_backspace_pressed(true);
6366 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6367 s.select(selections)
6368 });
6369 this.insert("", window, cx);
6370 let empty_str: Arc<str> = Arc::from("");
6371 for (buffer, edits) in linked_ranges {
6372 let snapshot = buffer.read(cx).snapshot();
6373 use text::ToPoint as TP;
6374
6375 let edits = edits
6376 .into_iter()
6377 .map(|range| {
6378 let end_point = TP::to_point(&range.end, &snapshot);
6379 let mut start_point = TP::to_point(&range.start, &snapshot);
6380
6381 if end_point == start_point {
6382 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6383 .saturating_sub(1);
6384 start_point =
6385 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6386 };
6387
6388 (start_point..end_point, empty_str.clone())
6389 })
6390 .sorted_by_key(|(range, _)| range.start)
6391 .collect::<Vec<_>>();
6392 buffer.update(cx, |this, cx| {
6393 this.edit(edits, None, cx);
6394 })
6395 }
6396 this.refresh_inline_completion(true, false, window, cx);
6397 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6398 });
6399 }
6400
6401 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6402 self.transact(window, cx, |this, window, cx| {
6403 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6404 let line_mode = s.line_mode;
6405 s.move_with(|map, selection| {
6406 if selection.is_empty() && !line_mode {
6407 let cursor = movement::right(map, selection.head());
6408 selection.end = cursor;
6409 selection.reversed = true;
6410 selection.goal = SelectionGoal::None;
6411 }
6412 })
6413 });
6414 this.insert("", window, cx);
6415 this.refresh_inline_completion(true, false, window, cx);
6416 });
6417 }
6418
6419 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6420 if self.move_to_prev_snippet_tabstop(window, cx) {
6421 return;
6422 }
6423
6424 self.outdent(&Outdent, window, cx);
6425 }
6426
6427 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6428 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6429 return;
6430 }
6431
6432 let mut selections = self.selections.all_adjusted(cx);
6433 let buffer = self.buffer.read(cx);
6434 let snapshot = buffer.snapshot(cx);
6435 let rows_iter = selections.iter().map(|s| s.head().row);
6436 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6437
6438 let mut edits = Vec::new();
6439 let mut prev_edited_row = 0;
6440 let mut row_delta = 0;
6441 for selection in &mut selections {
6442 if selection.start.row != prev_edited_row {
6443 row_delta = 0;
6444 }
6445 prev_edited_row = selection.end.row;
6446
6447 // If the selection is non-empty, then increase the indentation of the selected lines.
6448 if !selection.is_empty() {
6449 row_delta =
6450 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6451 continue;
6452 }
6453
6454 // If the selection is empty and the cursor is in the leading whitespace before the
6455 // suggested indentation, then auto-indent the line.
6456 let cursor = selection.head();
6457 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6458 if let Some(suggested_indent) =
6459 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6460 {
6461 if cursor.column < suggested_indent.len
6462 && cursor.column <= current_indent.len
6463 && current_indent.len <= suggested_indent.len
6464 {
6465 selection.start = Point::new(cursor.row, suggested_indent.len);
6466 selection.end = selection.start;
6467 if row_delta == 0 {
6468 edits.extend(Buffer::edit_for_indent_size_adjustment(
6469 cursor.row,
6470 current_indent,
6471 suggested_indent,
6472 ));
6473 row_delta = suggested_indent.len - current_indent.len;
6474 }
6475 continue;
6476 }
6477 }
6478
6479 // Otherwise, insert a hard or soft tab.
6480 let settings = buffer.settings_at(cursor, cx);
6481 let tab_size = if settings.hard_tabs {
6482 IndentSize::tab()
6483 } else {
6484 let tab_size = settings.tab_size.get();
6485 let char_column = snapshot
6486 .text_for_range(Point::new(cursor.row, 0)..cursor)
6487 .flat_map(str::chars)
6488 .count()
6489 + row_delta as usize;
6490 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6491 IndentSize::spaces(chars_to_next_tab_stop)
6492 };
6493 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6494 selection.end = selection.start;
6495 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6496 row_delta += tab_size.len;
6497 }
6498
6499 self.transact(window, cx, |this, window, cx| {
6500 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6501 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6502 s.select(selections)
6503 });
6504 this.refresh_inline_completion(true, false, window, cx);
6505 });
6506 }
6507
6508 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6509 if self.read_only(cx) {
6510 return;
6511 }
6512 let mut selections = self.selections.all::<Point>(cx);
6513 let mut prev_edited_row = 0;
6514 let mut row_delta = 0;
6515 let mut edits = Vec::new();
6516 let buffer = self.buffer.read(cx);
6517 let snapshot = buffer.snapshot(cx);
6518 for selection in &mut selections {
6519 if selection.start.row != prev_edited_row {
6520 row_delta = 0;
6521 }
6522 prev_edited_row = selection.end.row;
6523
6524 row_delta =
6525 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6526 }
6527
6528 self.transact(window, cx, |this, window, cx| {
6529 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6530 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6531 s.select(selections)
6532 });
6533 });
6534 }
6535
6536 fn indent_selection(
6537 buffer: &MultiBuffer,
6538 snapshot: &MultiBufferSnapshot,
6539 selection: &mut Selection<Point>,
6540 edits: &mut Vec<(Range<Point>, String)>,
6541 delta_for_start_row: u32,
6542 cx: &App,
6543 ) -> u32 {
6544 let settings = buffer.settings_at(selection.start, cx);
6545 let tab_size = settings.tab_size.get();
6546 let indent_kind = if settings.hard_tabs {
6547 IndentKind::Tab
6548 } else {
6549 IndentKind::Space
6550 };
6551 let mut start_row = selection.start.row;
6552 let mut end_row = selection.end.row + 1;
6553
6554 // If a selection ends at the beginning of a line, don't indent
6555 // that last line.
6556 if selection.end.column == 0 && selection.end.row > selection.start.row {
6557 end_row -= 1;
6558 }
6559
6560 // Avoid re-indenting a row that has already been indented by a
6561 // previous selection, but still update this selection's column
6562 // to reflect that indentation.
6563 if delta_for_start_row > 0 {
6564 start_row += 1;
6565 selection.start.column += delta_for_start_row;
6566 if selection.end.row == selection.start.row {
6567 selection.end.column += delta_for_start_row;
6568 }
6569 }
6570
6571 let mut delta_for_end_row = 0;
6572 let has_multiple_rows = start_row + 1 != end_row;
6573 for row in start_row..end_row {
6574 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6575 let indent_delta = match (current_indent.kind, indent_kind) {
6576 (IndentKind::Space, IndentKind::Space) => {
6577 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6578 IndentSize::spaces(columns_to_next_tab_stop)
6579 }
6580 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6581 (_, IndentKind::Tab) => IndentSize::tab(),
6582 };
6583
6584 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6585 0
6586 } else {
6587 selection.start.column
6588 };
6589 let row_start = Point::new(row, start);
6590 edits.push((
6591 row_start..row_start,
6592 indent_delta.chars().collect::<String>(),
6593 ));
6594
6595 // Update this selection's endpoints to reflect the indentation.
6596 if row == selection.start.row {
6597 selection.start.column += indent_delta.len;
6598 }
6599 if row == selection.end.row {
6600 selection.end.column += indent_delta.len;
6601 delta_for_end_row = indent_delta.len;
6602 }
6603 }
6604
6605 if selection.start.row == selection.end.row {
6606 delta_for_start_row + delta_for_end_row
6607 } else {
6608 delta_for_end_row
6609 }
6610 }
6611
6612 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6613 if self.read_only(cx) {
6614 return;
6615 }
6616 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6617 let selections = self.selections.all::<Point>(cx);
6618 let mut deletion_ranges = Vec::new();
6619 let mut last_outdent = None;
6620 {
6621 let buffer = self.buffer.read(cx);
6622 let snapshot = buffer.snapshot(cx);
6623 for selection in &selections {
6624 let settings = buffer.settings_at(selection.start, cx);
6625 let tab_size = settings.tab_size.get();
6626 let mut rows = selection.spanned_rows(false, &display_map);
6627
6628 // Avoid re-outdenting a row that has already been outdented by a
6629 // previous selection.
6630 if let Some(last_row) = last_outdent {
6631 if last_row == rows.start {
6632 rows.start = rows.start.next_row();
6633 }
6634 }
6635 let has_multiple_rows = rows.len() > 1;
6636 for row in rows.iter_rows() {
6637 let indent_size = snapshot.indent_size_for_line(row);
6638 if indent_size.len > 0 {
6639 let deletion_len = match indent_size.kind {
6640 IndentKind::Space => {
6641 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6642 if columns_to_prev_tab_stop == 0 {
6643 tab_size
6644 } else {
6645 columns_to_prev_tab_stop
6646 }
6647 }
6648 IndentKind::Tab => 1,
6649 };
6650 let start = if has_multiple_rows
6651 || deletion_len > selection.start.column
6652 || indent_size.len < selection.start.column
6653 {
6654 0
6655 } else {
6656 selection.start.column - deletion_len
6657 };
6658 deletion_ranges.push(
6659 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6660 );
6661 last_outdent = Some(row);
6662 }
6663 }
6664 }
6665 }
6666
6667 self.transact(window, cx, |this, window, cx| {
6668 this.buffer.update(cx, |buffer, cx| {
6669 let empty_str: Arc<str> = Arc::default();
6670 buffer.edit(
6671 deletion_ranges
6672 .into_iter()
6673 .map(|range| (range, empty_str.clone())),
6674 None,
6675 cx,
6676 );
6677 });
6678 let selections = this.selections.all::<usize>(cx);
6679 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6680 s.select(selections)
6681 });
6682 });
6683 }
6684
6685 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6686 if self.read_only(cx) {
6687 return;
6688 }
6689 let selections = self
6690 .selections
6691 .all::<usize>(cx)
6692 .into_iter()
6693 .map(|s| s.range());
6694
6695 self.transact(window, cx, |this, window, cx| {
6696 this.buffer.update(cx, |buffer, cx| {
6697 buffer.autoindent_ranges(selections, cx);
6698 });
6699 let selections = this.selections.all::<usize>(cx);
6700 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6701 s.select(selections)
6702 });
6703 });
6704 }
6705
6706 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6707 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6708 let selections = self.selections.all::<Point>(cx);
6709
6710 let mut new_cursors = Vec::new();
6711 let mut edit_ranges = Vec::new();
6712 let mut selections = selections.iter().peekable();
6713 while let Some(selection) = selections.next() {
6714 let mut rows = selection.spanned_rows(false, &display_map);
6715 let goal_display_column = selection.head().to_display_point(&display_map).column();
6716
6717 // Accumulate contiguous regions of rows that we want to delete.
6718 while let Some(next_selection) = selections.peek() {
6719 let next_rows = next_selection.spanned_rows(false, &display_map);
6720 if next_rows.start <= rows.end {
6721 rows.end = next_rows.end;
6722 selections.next().unwrap();
6723 } else {
6724 break;
6725 }
6726 }
6727
6728 let buffer = &display_map.buffer_snapshot;
6729 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6730 let edit_end;
6731 let cursor_buffer_row;
6732 if buffer.max_point().row >= rows.end.0 {
6733 // If there's a line after the range, delete the \n from the end of the row range
6734 // and position the cursor on the next line.
6735 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6736 cursor_buffer_row = rows.end;
6737 } else {
6738 // If there isn't a line after the range, delete the \n from the line before the
6739 // start of the row range and position the cursor there.
6740 edit_start = edit_start.saturating_sub(1);
6741 edit_end = buffer.len();
6742 cursor_buffer_row = rows.start.previous_row();
6743 }
6744
6745 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6746 *cursor.column_mut() =
6747 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6748
6749 new_cursors.push((
6750 selection.id,
6751 buffer.anchor_after(cursor.to_point(&display_map)),
6752 ));
6753 edit_ranges.push(edit_start..edit_end);
6754 }
6755
6756 self.transact(window, cx, |this, window, cx| {
6757 let buffer = this.buffer.update(cx, |buffer, cx| {
6758 let empty_str: Arc<str> = Arc::default();
6759 buffer.edit(
6760 edit_ranges
6761 .into_iter()
6762 .map(|range| (range, empty_str.clone())),
6763 None,
6764 cx,
6765 );
6766 buffer.snapshot(cx)
6767 });
6768 let new_selections = new_cursors
6769 .into_iter()
6770 .map(|(id, cursor)| {
6771 let cursor = cursor.to_point(&buffer);
6772 Selection {
6773 id,
6774 start: cursor,
6775 end: cursor,
6776 reversed: false,
6777 goal: SelectionGoal::None,
6778 }
6779 })
6780 .collect();
6781
6782 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6783 s.select(new_selections);
6784 });
6785 });
6786 }
6787
6788 pub fn join_lines_impl(
6789 &mut self,
6790 insert_whitespace: bool,
6791 window: &mut Window,
6792 cx: &mut Context<Self>,
6793 ) {
6794 if self.read_only(cx) {
6795 return;
6796 }
6797 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6798 for selection in self.selections.all::<Point>(cx) {
6799 let start = MultiBufferRow(selection.start.row);
6800 // Treat single line selections as if they include the next line. Otherwise this action
6801 // would do nothing for single line selections individual cursors.
6802 let end = if selection.start.row == selection.end.row {
6803 MultiBufferRow(selection.start.row + 1)
6804 } else {
6805 MultiBufferRow(selection.end.row)
6806 };
6807
6808 if let Some(last_row_range) = row_ranges.last_mut() {
6809 if start <= last_row_range.end {
6810 last_row_range.end = end;
6811 continue;
6812 }
6813 }
6814 row_ranges.push(start..end);
6815 }
6816
6817 let snapshot = self.buffer.read(cx).snapshot(cx);
6818 let mut cursor_positions = Vec::new();
6819 for row_range in &row_ranges {
6820 let anchor = snapshot.anchor_before(Point::new(
6821 row_range.end.previous_row().0,
6822 snapshot.line_len(row_range.end.previous_row()),
6823 ));
6824 cursor_positions.push(anchor..anchor);
6825 }
6826
6827 self.transact(window, cx, |this, window, cx| {
6828 for row_range in row_ranges.into_iter().rev() {
6829 for row in row_range.iter_rows().rev() {
6830 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6831 let next_line_row = row.next_row();
6832 let indent = snapshot.indent_size_for_line(next_line_row);
6833 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6834
6835 let replace =
6836 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6837 " "
6838 } else {
6839 ""
6840 };
6841
6842 this.buffer.update(cx, |buffer, cx| {
6843 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6844 });
6845 }
6846 }
6847
6848 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6849 s.select_anchor_ranges(cursor_positions)
6850 });
6851 });
6852 }
6853
6854 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6855 self.join_lines_impl(true, window, cx);
6856 }
6857
6858 pub fn sort_lines_case_sensitive(
6859 &mut self,
6860 _: &SortLinesCaseSensitive,
6861 window: &mut Window,
6862 cx: &mut Context<Self>,
6863 ) {
6864 self.manipulate_lines(window, cx, |lines| lines.sort())
6865 }
6866
6867 pub fn sort_lines_case_insensitive(
6868 &mut self,
6869 _: &SortLinesCaseInsensitive,
6870 window: &mut Window,
6871 cx: &mut Context<Self>,
6872 ) {
6873 self.manipulate_lines(window, cx, |lines| {
6874 lines.sort_by_key(|line| line.to_lowercase())
6875 })
6876 }
6877
6878 pub fn unique_lines_case_insensitive(
6879 &mut self,
6880 _: &UniqueLinesCaseInsensitive,
6881 window: &mut Window,
6882 cx: &mut Context<Self>,
6883 ) {
6884 self.manipulate_lines(window, cx, |lines| {
6885 let mut seen = HashSet::default();
6886 lines.retain(|line| seen.insert(line.to_lowercase()));
6887 })
6888 }
6889
6890 pub fn unique_lines_case_sensitive(
6891 &mut self,
6892 _: &UniqueLinesCaseSensitive,
6893 window: &mut Window,
6894 cx: &mut Context<Self>,
6895 ) {
6896 self.manipulate_lines(window, cx, |lines| {
6897 let mut seen = HashSet::default();
6898 lines.retain(|line| seen.insert(*line));
6899 })
6900 }
6901
6902 pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
6903 let mut revert_changes = HashMap::default();
6904 let snapshot = self.snapshot(window, cx);
6905 for hunk in snapshot
6906 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
6907 {
6908 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6909 }
6910 if !revert_changes.is_empty() {
6911 self.transact(window, cx, |editor, window, cx| {
6912 editor.revert(revert_changes, window, cx);
6913 });
6914 }
6915 }
6916
6917 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
6918 let Some(project) = self.project.clone() else {
6919 return;
6920 };
6921 self.reload(project, window, cx)
6922 .detach_and_notify_err(window, cx);
6923 }
6924
6925 pub fn revert_selected_hunks(
6926 &mut self,
6927 _: &RevertSelectedHunks,
6928 window: &mut Window,
6929 cx: &mut Context<Self>,
6930 ) {
6931 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
6932 self.revert_hunks_in_ranges(selections, window, cx);
6933 }
6934
6935 fn revert_hunks_in_ranges(
6936 &mut self,
6937 ranges: impl Iterator<Item = Range<Point>>,
6938 window: &mut Window,
6939 cx: &mut Context<Editor>,
6940 ) {
6941 let mut revert_changes = HashMap::default();
6942 let snapshot = self.snapshot(window, cx);
6943 for hunk in &snapshot.hunks_for_ranges(ranges) {
6944 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6945 }
6946 if !revert_changes.is_empty() {
6947 self.transact(window, cx, |editor, window, cx| {
6948 editor.revert(revert_changes, window, cx);
6949 });
6950 }
6951 }
6952
6953 pub fn open_active_item_in_terminal(
6954 &mut self,
6955 _: &OpenInTerminal,
6956 window: &mut Window,
6957 cx: &mut Context<Self>,
6958 ) {
6959 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6960 let project_path = buffer.read(cx).project_path(cx)?;
6961 let project = self.project.as_ref()?.read(cx);
6962 let entry = project.entry_for_path(&project_path, cx)?;
6963 let parent = match &entry.canonical_path {
6964 Some(canonical_path) => canonical_path.to_path_buf(),
6965 None => project.absolute_path(&project_path, cx)?,
6966 }
6967 .parent()?
6968 .to_path_buf();
6969 Some(parent)
6970 }) {
6971 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
6972 }
6973 }
6974
6975 pub fn prepare_revert_change(
6976 &self,
6977 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6978 hunk: &MultiBufferDiffHunk,
6979 cx: &mut App,
6980 ) -> Option<()> {
6981 let buffer = self.buffer.read(cx);
6982 let diff = buffer.diff_for(hunk.buffer_id)?;
6983 let buffer = buffer.buffer(hunk.buffer_id)?;
6984 let buffer = buffer.read(cx);
6985 let original_text = diff
6986 .read(cx)
6987 .base_text()
6988 .as_ref()?
6989 .as_rope()
6990 .slice(hunk.diff_base_byte_range.clone());
6991 let buffer_snapshot = buffer.snapshot();
6992 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6993 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6994 probe
6995 .0
6996 .start
6997 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6998 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6999 }) {
7000 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7001 Some(())
7002 } else {
7003 None
7004 }
7005 }
7006
7007 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7008 self.manipulate_lines(window, cx, |lines| lines.reverse())
7009 }
7010
7011 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7012 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7013 }
7014
7015 fn manipulate_lines<Fn>(
7016 &mut self,
7017 window: &mut Window,
7018 cx: &mut Context<Self>,
7019 mut callback: Fn,
7020 ) where
7021 Fn: FnMut(&mut Vec<&str>),
7022 {
7023 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7024 let buffer = self.buffer.read(cx).snapshot(cx);
7025
7026 let mut edits = Vec::new();
7027
7028 let selections = self.selections.all::<Point>(cx);
7029 let mut selections = selections.iter().peekable();
7030 let mut contiguous_row_selections = Vec::new();
7031 let mut new_selections = Vec::new();
7032 let mut added_lines = 0;
7033 let mut removed_lines = 0;
7034
7035 while let Some(selection) = selections.next() {
7036 let (start_row, end_row) = consume_contiguous_rows(
7037 &mut contiguous_row_selections,
7038 selection,
7039 &display_map,
7040 &mut selections,
7041 );
7042
7043 let start_point = Point::new(start_row.0, 0);
7044 let end_point = Point::new(
7045 end_row.previous_row().0,
7046 buffer.line_len(end_row.previous_row()),
7047 );
7048 let text = buffer
7049 .text_for_range(start_point..end_point)
7050 .collect::<String>();
7051
7052 let mut lines = text.split('\n').collect_vec();
7053
7054 let lines_before = lines.len();
7055 callback(&mut lines);
7056 let lines_after = lines.len();
7057
7058 edits.push((start_point..end_point, lines.join("\n")));
7059
7060 // Selections must change based on added and removed line count
7061 let start_row =
7062 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7063 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7064 new_selections.push(Selection {
7065 id: selection.id,
7066 start: start_row,
7067 end: end_row,
7068 goal: SelectionGoal::None,
7069 reversed: selection.reversed,
7070 });
7071
7072 if lines_after > lines_before {
7073 added_lines += lines_after - lines_before;
7074 } else if lines_before > lines_after {
7075 removed_lines += lines_before - lines_after;
7076 }
7077 }
7078
7079 self.transact(window, cx, |this, window, cx| {
7080 let buffer = this.buffer.update(cx, |buffer, cx| {
7081 buffer.edit(edits, None, cx);
7082 buffer.snapshot(cx)
7083 });
7084
7085 // Recalculate offsets on newly edited buffer
7086 let new_selections = new_selections
7087 .iter()
7088 .map(|s| {
7089 let start_point = Point::new(s.start.0, 0);
7090 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
7091 Selection {
7092 id: s.id,
7093 start: buffer.point_to_offset(start_point),
7094 end: buffer.point_to_offset(end_point),
7095 goal: s.goal,
7096 reversed: s.reversed,
7097 }
7098 })
7099 .collect();
7100
7101 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7102 s.select(new_selections);
7103 });
7104
7105 this.request_autoscroll(Autoscroll::fit(), cx);
7106 });
7107 }
7108
7109 pub fn convert_to_upper_case(
7110 &mut self,
7111 _: &ConvertToUpperCase,
7112 window: &mut Window,
7113 cx: &mut Context<Self>,
7114 ) {
7115 self.manipulate_text(window, cx, |text| text.to_uppercase())
7116 }
7117
7118 pub fn convert_to_lower_case(
7119 &mut self,
7120 _: &ConvertToLowerCase,
7121 window: &mut Window,
7122 cx: &mut Context<Self>,
7123 ) {
7124 self.manipulate_text(window, cx, |text| text.to_lowercase())
7125 }
7126
7127 pub fn convert_to_title_case(
7128 &mut self,
7129 _: &ConvertToTitleCase,
7130 window: &mut Window,
7131 cx: &mut Context<Self>,
7132 ) {
7133 self.manipulate_text(window, cx, |text| {
7134 text.split('\n')
7135 .map(|line| line.to_case(Case::Title))
7136 .join("\n")
7137 })
7138 }
7139
7140 pub fn convert_to_snake_case(
7141 &mut self,
7142 _: &ConvertToSnakeCase,
7143 window: &mut Window,
7144 cx: &mut Context<Self>,
7145 ) {
7146 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7147 }
7148
7149 pub fn convert_to_kebab_case(
7150 &mut self,
7151 _: &ConvertToKebabCase,
7152 window: &mut Window,
7153 cx: &mut Context<Self>,
7154 ) {
7155 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7156 }
7157
7158 pub fn convert_to_upper_camel_case(
7159 &mut self,
7160 _: &ConvertToUpperCamelCase,
7161 window: &mut Window,
7162 cx: &mut Context<Self>,
7163 ) {
7164 self.manipulate_text(window, cx, |text| {
7165 text.split('\n')
7166 .map(|line| line.to_case(Case::UpperCamel))
7167 .join("\n")
7168 })
7169 }
7170
7171 pub fn convert_to_lower_camel_case(
7172 &mut self,
7173 _: &ConvertToLowerCamelCase,
7174 window: &mut Window,
7175 cx: &mut Context<Self>,
7176 ) {
7177 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
7178 }
7179
7180 pub fn convert_to_opposite_case(
7181 &mut self,
7182 _: &ConvertToOppositeCase,
7183 window: &mut Window,
7184 cx: &mut Context<Self>,
7185 ) {
7186 self.manipulate_text(window, cx, |text| {
7187 text.chars()
7188 .fold(String::with_capacity(text.len()), |mut t, c| {
7189 if c.is_uppercase() {
7190 t.extend(c.to_lowercase());
7191 } else {
7192 t.extend(c.to_uppercase());
7193 }
7194 t
7195 })
7196 })
7197 }
7198
7199 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
7200 where
7201 Fn: FnMut(&str) -> String,
7202 {
7203 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7204 let buffer = self.buffer.read(cx).snapshot(cx);
7205
7206 let mut new_selections = Vec::new();
7207 let mut edits = Vec::new();
7208 let mut selection_adjustment = 0i32;
7209
7210 for selection in self.selections.all::<usize>(cx) {
7211 let selection_is_empty = selection.is_empty();
7212
7213 let (start, end) = if selection_is_empty {
7214 let word_range = movement::surrounding_word(
7215 &display_map,
7216 selection.start.to_display_point(&display_map),
7217 );
7218 let start = word_range.start.to_offset(&display_map, Bias::Left);
7219 let end = word_range.end.to_offset(&display_map, Bias::Left);
7220 (start, end)
7221 } else {
7222 (selection.start, selection.end)
7223 };
7224
7225 let text = buffer.text_for_range(start..end).collect::<String>();
7226 let old_length = text.len() as i32;
7227 let text = callback(&text);
7228
7229 new_selections.push(Selection {
7230 start: (start as i32 - selection_adjustment) as usize,
7231 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
7232 goal: SelectionGoal::None,
7233 ..selection
7234 });
7235
7236 selection_adjustment += old_length - text.len() as i32;
7237
7238 edits.push((start..end, text));
7239 }
7240
7241 self.transact(window, cx, |this, window, cx| {
7242 this.buffer.update(cx, |buffer, cx| {
7243 buffer.edit(edits, None, cx);
7244 });
7245
7246 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7247 s.select(new_selections);
7248 });
7249
7250 this.request_autoscroll(Autoscroll::fit(), cx);
7251 });
7252 }
7253
7254 pub fn duplicate(
7255 &mut self,
7256 upwards: bool,
7257 whole_lines: bool,
7258 window: &mut Window,
7259 cx: &mut Context<Self>,
7260 ) {
7261 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7262 let buffer = &display_map.buffer_snapshot;
7263 let selections = self.selections.all::<Point>(cx);
7264
7265 let mut edits = Vec::new();
7266 let mut selections_iter = selections.iter().peekable();
7267 while let Some(selection) = selections_iter.next() {
7268 let mut rows = selection.spanned_rows(false, &display_map);
7269 // duplicate line-wise
7270 if whole_lines || selection.start == selection.end {
7271 // Avoid duplicating the same lines twice.
7272 while let Some(next_selection) = selections_iter.peek() {
7273 let next_rows = next_selection.spanned_rows(false, &display_map);
7274 if next_rows.start < rows.end {
7275 rows.end = next_rows.end;
7276 selections_iter.next().unwrap();
7277 } else {
7278 break;
7279 }
7280 }
7281
7282 // Copy the text from the selected row region and splice it either at the start
7283 // or end of the region.
7284 let start = Point::new(rows.start.0, 0);
7285 let end = Point::new(
7286 rows.end.previous_row().0,
7287 buffer.line_len(rows.end.previous_row()),
7288 );
7289 let text = buffer
7290 .text_for_range(start..end)
7291 .chain(Some("\n"))
7292 .collect::<String>();
7293 let insert_location = if upwards {
7294 Point::new(rows.end.0, 0)
7295 } else {
7296 start
7297 };
7298 edits.push((insert_location..insert_location, text));
7299 } else {
7300 // duplicate character-wise
7301 let start = selection.start;
7302 let end = selection.end;
7303 let text = buffer.text_for_range(start..end).collect::<String>();
7304 edits.push((selection.end..selection.end, text));
7305 }
7306 }
7307
7308 self.transact(window, cx, |this, _, cx| {
7309 this.buffer.update(cx, |buffer, cx| {
7310 buffer.edit(edits, None, cx);
7311 });
7312
7313 this.request_autoscroll(Autoscroll::fit(), cx);
7314 });
7315 }
7316
7317 pub fn duplicate_line_up(
7318 &mut self,
7319 _: &DuplicateLineUp,
7320 window: &mut Window,
7321 cx: &mut Context<Self>,
7322 ) {
7323 self.duplicate(true, true, window, cx);
7324 }
7325
7326 pub fn duplicate_line_down(
7327 &mut self,
7328 _: &DuplicateLineDown,
7329 window: &mut Window,
7330 cx: &mut Context<Self>,
7331 ) {
7332 self.duplicate(false, true, window, cx);
7333 }
7334
7335 pub fn duplicate_selection(
7336 &mut self,
7337 _: &DuplicateSelection,
7338 window: &mut Window,
7339 cx: &mut Context<Self>,
7340 ) {
7341 self.duplicate(false, false, window, cx);
7342 }
7343
7344 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7345 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7346 let buffer = self.buffer.read(cx).snapshot(cx);
7347
7348 let mut edits = Vec::new();
7349 let mut unfold_ranges = Vec::new();
7350 let mut refold_creases = Vec::new();
7351
7352 let selections = self.selections.all::<Point>(cx);
7353 let mut selections = selections.iter().peekable();
7354 let mut contiguous_row_selections = Vec::new();
7355 let mut new_selections = Vec::new();
7356
7357 while let Some(selection) = selections.next() {
7358 // Find all the selections that span a contiguous row range
7359 let (start_row, end_row) = consume_contiguous_rows(
7360 &mut contiguous_row_selections,
7361 selection,
7362 &display_map,
7363 &mut selections,
7364 );
7365
7366 // Move the text spanned by the row range to be before the line preceding the row range
7367 if start_row.0 > 0 {
7368 let range_to_move = Point::new(
7369 start_row.previous_row().0,
7370 buffer.line_len(start_row.previous_row()),
7371 )
7372 ..Point::new(
7373 end_row.previous_row().0,
7374 buffer.line_len(end_row.previous_row()),
7375 );
7376 let insertion_point = display_map
7377 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7378 .0;
7379
7380 // Don't move lines across excerpts
7381 if buffer
7382 .excerpt_containing(insertion_point..range_to_move.end)
7383 .is_some()
7384 {
7385 let text = buffer
7386 .text_for_range(range_to_move.clone())
7387 .flat_map(|s| s.chars())
7388 .skip(1)
7389 .chain(['\n'])
7390 .collect::<String>();
7391
7392 edits.push((
7393 buffer.anchor_after(range_to_move.start)
7394 ..buffer.anchor_before(range_to_move.end),
7395 String::new(),
7396 ));
7397 let insertion_anchor = buffer.anchor_after(insertion_point);
7398 edits.push((insertion_anchor..insertion_anchor, text));
7399
7400 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7401
7402 // Move selections up
7403 new_selections.extend(contiguous_row_selections.drain(..).map(
7404 |mut selection| {
7405 selection.start.row -= row_delta;
7406 selection.end.row -= row_delta;
7407 selection
7408 },
7409 ));
7410
7411 // Move folds up
7412 unfold_ranges.push(range_to_move.clone());
7413 for fold in display_map.folds_in_range(
7414 buffer.anchor_before(range_to_move.start)
7415 ..buffer.anchor_after(range_to_move.end),
7416 ) {
7417 let mut start = fold.range.start.to_point(&buffer);
7418 let mut end = fold.range.end.to_point(&buffer);
7419 start.row -= row_delta;
7420 end.row -= row_delta;
7421 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7422 }
7423 }
7424 }
7425
7426 // If we didn't move line(s), preserve the existing selections
7427 new_selections.append(&mut contiguous_row_selections);
7428 }
7429
7430 self.transact(window, cx, |this, window, cx| {
7431 this.unfold_ranges(&unfold_ranges, true, true, cx);
7432 this.buffer.update(cx, |buffer, cx| {
7433 for (range, text) in edits {
7434 buffer.edit([(range, text)], None, cx);
7435 }
7436 });
7437 this.fold_creases(refold_creases, true, window, cx);
7438 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7439 s.select(new_selections);
7440 })
7441 });
7442 }
7443
7444 pub fn move_line_down(
7445 &mut self,
7446 _: &MoveLineDown,
7447 window: &mut Window,
7448 cx: &mut Context<Self>,
7449 ) {
7450 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7451 let buffer = self.buffer.read(cx).snapshot(cx);
7452
7453 let mut edits = Vec::new();
7454 let mut unfold_ranges = Vec::new();
7455 let mut refold_creases = Vec::new();
7456
7457 let selections = self.selections.all::<Point>(cx);
7458 let mut selections = selections.iter().peekable();
7459 let mut contiguous_row_selections = Vec::new();
7460 let mut new_selections = Vec::new();
7461
7462 while let Some(selection) = selections.next() {
7463 // Find all the selections that span a contiguous row range
7464 let (start_row, end_row) = consume_contiguous_rows(
7465 &mut contiguous_row_selections,
7466 selection,
7467 &display_map,
7468 &mut selections,
7469 );
7470
7471 // Move the text spanned by the row range to be after the last line of the row range
7472 if end_row.0 <= buffer.max_point().row {
7473 let range_to_move =
7474 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7475 let insertion_point = display_map
7476 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7477 .0;
7478
7479 // Don't move lines across excerpt boundaries
7480 if buffer
7481 .excerpt_containing(range_to_move.start..insertion_point)
7482 .is_some()
7483 {
7484 let mut text = String::from("\n");
7485 text.extend(buffer.text_for_range(range_to_move.clone()));
7486 text.pop(); // Drop trailing newline
7487 edits.push((
7488 buffer.anchor_after(range_to_move.start)
7489 ..buffer.anchor_before(range_to_move.end),
7490 String::new(),
7491 ));
7492 let insertion_anchor = buffer.anchor_after(insertion_point);
7493 edits.push((insertion_anchor..insertion_anchor, text));
7494
7495 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7496
7497 // Move selections down
7498 new_selections.extend(contiguous_row_selections.drain(..).map(
7499 |mut selection| {
7500 selection.start.row += row_delta;
7501 selection.end.row += row_delta;
7502 selection
7503 },
7504 ));
7505
7506 // Move folds down
7507 unfold_ranges.push(range_to_move.clone());
7508 for fold in display_map.folds_in_range(
7509 buffer.anchor_before(range_to_move.start)
7510 ..buffer.anchor_after(range_to_move.end),
7511 ) {
7512 let mut start = fold.range.start.to_point(&buffer);
7513 let mut end = fold.range.end.to_point(&buffer);
7514 start.row += row_delta;
7515 end.row += row_delta;
7516 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7517 }
7518 }
7519 }
7520
7521 // If we didn't move line(s), preserve the existing selections
7522 new_selections.append(&mut contiguous_row_selections);
7523 }
7524
7525 self.transact(window, cx, |this, window, cx| {
7526 this.unfold_ranges(&unfold_ranges, true, true, cx);
7527 this.buffer.update(cx, |buffer, cx| {
7528 for (range, text) in edits {
7529 buffer.edit([(range, text)], None, cx);
7530 }
7531 });
7532 this.fold_creases(refold_creases, true, window, cx);
7533 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7534 s.select(new_selections)
7535 });
7536 });
7537 }
7538
7539 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7540 let text_layout_details = &self.text_layout_details(window);
7541 self.transact(window, cx, |this, window, cx| {
7542 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7543 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7544 let line_mode = s.line_mode;
7545 s.move_with(|display_map, selection| {
7546 if !selection.is_empty() || line_mode {
7547 return;
7548 }
7549
7550 let mut head = selection.head();
7551 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7552 if head.column() == display_map.line_len(head.row()) {
7553 transpose_offset = display_map
7554 .buffer_snapshot
7555 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7556 }
7557
7558 if transpose_offset == 0 {
7559 return;
7560 }
7561
7562 *head.column_mut() += 1;
7563 head = display_map.clip_point(head, Bias::Right);
7564 let goal = SelectionGoal::HorizontalPosition(
7565 display_map
7566 .x_for_display_point(head, text_layout_details)
7567 .into(),
7568 );
7569 selection.collapse_to(head, goal);
7570
7571 let transpose_start = display_map
7572 .buffer_snapshot
7573 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7574 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7575 let transpose_end = display_map
7576 .buffer_snapshot
7577 .clip_offset(transpose_offset + 1, Bias::Right);
7578 if let Some(ch) =
7579 display_map.buffer_snapshot.chars_at(transpose_start).next()
7580 {
7581 edits.push((transpose_start..transpose_offset, String::new()));
7582 edits.push((transpose_end..transpose_end, ch.to_string()));
7583 }
7584 }
7585 });
7586 edits
7587 });
7588 this.buffer
7589 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7590 let selections = this.selections.all::<usize>(cx);
7591 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7592 s.select(selections);
7593 });
7594 });
7595 }
7596
7597 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7598 self.rewrap_impl(IsVimMode::No, cx)
7599 }
7600
7601 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7602 let buffer = self.buffer.read(cx).snapshot(cx);
7603 let selections = self.selections.all::<Point>(cx);
7604 let mut selections = selections.iter().peekable();
7605
7606 let mut edits = Vec::new();
7607 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7608
7609 while let Some(selection) = selections.next() {
7610 let mut start_row = selection.start.row;
7611 let mut end_row = selection.end.row;
7612
7613 // Skip selections that overlap with a range that has already been rewrapped.
7614 let selection_range = start_row..end_row;
7615 if rewrapped_row_ranges
7616 .iter()
7617 .any(|range| range.overlaps(&selection_range))
7618 {
7619 continue;
7620 }
7621
7622 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7623
7624 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7625 match language_scope.language_name().as_ref() {
7626 "Markdown" | "Plain Text" => {
7627 should_rewrap = true;
7628 }
7629 _ => {}
7630 }
7631 }
7632
7633 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7634
7635 // Since not all lines in the selection may be at the same indent
7636 // level, choose the indent size that is the most common between all
7637 // of the lines.
7638 //
7639 // If there is a tie, we use the deepest indent.
7640 let (indent_size, indent_end) = {
7641 let mut indent_size_occurrences = HashMap::default();
7642 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7643
7644 for row in start_row..=end_row {
7645 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7646 rows_by_indent_size.entry(indent).or_default().push(row);
7647 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7648 }
7649
7650 let indent_size = indent_size_occurrences
7651 .into_iter()
7652 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7653 .map(|(indent, _)| indent)
7654 .unwrap_or_default();
7655 let row = rows_by_indent_size[&indent_size][0];
7656 let indent_end = Point::new(row, indent_size.len);
7657
7658 (indent_size, indent_end)
7659 };
7660
7661 let mut line_prefix = indent_size.chars().collect::<String>();
7662
7663 if let Some(comment_prefix) =
7664 buffer
7665 .language_scope_at(selection.head())
7666 .and_then(|language| {
7667 language
7668 .line_comment_prefixes()
7669 .iter()
7670 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7671 .cloned()
7672 })
7673 {
7674 line_prefix.push_str(&comment_prefix);
7675 should_rewrap = true;
7676 }
7677
7678 if !should_rewrap {
7679 continue;
7680 }
7681
7682 if selection.is_empty() {
7683 'expand_upwards: while start_row > 0 {
7684 let prev_row = start_row - 1;
7685 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7686 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7687 {
7688 start_row = prev_row;
7689 } else {
7690 break 'expand_upwards;
7691 }
7692 }
7693
7694 'expand_downwards: while end_row < buffer.max_point().row {
7695 let next_row = end_row + 1;
7696 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7697 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7698 {
7699 end_row = next_row;
7700 } else {
7701 break 'expand_downwards;
7702 }
7703 }
7704 }
7705
7706 let start = Point::new(start_row, 0);
7707 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7708 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7709 let Some(lines_without_prefixes) = selection_text
7710 .lines()
7711 .map(|line| {
7712 line.strip_prefix(&line_prefix)
7713 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7714 .ok_or_else(|| {
7715 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7716 })
7717 })
7718 .collect::<Result<Vec<_>, _>>()
7719 .log_err()
7720 else {
7721 continue;
7722 };
7723
7724 let wrap_column = buffer
7725 .settings_at(Point::new(start_row, 0), cx)
7726 .preferred_line_length as usize;
7727 let wrapped_text = wrap_with_prefix(
7728 line_prefix,
7729 lines_without_prefixes.join(" "),
7730 wrap_column,
7731 tab_size,
7732 );
7733
7734 // TODO: should always use char-based diff while still supporting cursor behavior that
7735 // matches vim.
7736 let diff = match is_vim_mode {
7737 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7738 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7739 };
7740 let mut offset = start.to_offset(&buffer);
7741 let mut moved_since_edit = true;
7742
7743 for change in diff.iter_all_changes() {
7744 let value = change.value();
7745 match change.tag() {
7746 ChangeTag::Equal => {
7747 offset += value.len();
7748 moved_since_edit = true;
7749 }
7750 ChangeTag::Delete => {
7751 let start = buffer.anchor_after(offset);
7752 let end = buffer.anchor_before(offset + value.len());
7753
7754 if moved_since_edit {
7755 edits.push((start..end, String::new()));
7756 } else {
7757 edits.last_mut().unwrap().0.end = end;
7758 }
7759
7760 offset += value.len();
7761 moved_since_edit = false;
7762 }
7763 ChangeTag::Insert => {
7764 if moved_since_edit {
7765 let anchor = buffer.anchor_after(offset);
7766 edits.push((anchor..anchor, value.to_string()));
7767 } else {
7768 edits.last_mut().unwrap().1.push_str(value);
7769 }
7770
7771 moved_since_edit = false;
7772 }
7773 }
7774 }
7775
7776 rewrapped_row_ranges.push(start_row..=end_row);
7777 }
7778
7779 self.buffer
7780 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7781 }
7782
7783 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7784 let mut text = String::new();
7785 let buffer = self.buffer.read(cx).snapshot(cx);
7786 let mut selections = self.selections.all::<Point>(cx);
7787 let mut clipboard_selections = Vec::with_capacity(selections.len());
7788 {
7789 let max_point = buffer.max_point();
7790 let mut is_first = true;
7791 for selection in &mut selections {
7792 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7793 if is_entire_line {
7794 selection.start = Point::new(selection.start.row, 0);
7795 if !selection.is_empty() && selection.end.column == 0 {
7796 selection.end = cmp::min(max_point, selection.end);
7797 } else {
7798 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7799 }
7800 selection.goal = SelectionGoal::None;
7801 }
7802 if is_first {
7803 is_first = false;
7804 } else {
7805 text += "\n";
7806 }
7807 let mut len = 0;
7808 for chunk in buffer.text_for_range(selection.start..selection.end) {
7809 text.push_str(chunk);
7810 len += chunk.len();
7811 }
7812 clipboard_selections.push(ClipboardSelection {
7813 len,
7814 is_entire_line,
7815 first_line_indent: buffer
7816 .indent_size_for_line(MultiBufferRow(selection.start.row))
7817 .len,
7818 });
7819 }
7820 }
7821
7822 self.transact(window, cx, |this, window, cx| {
7823 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7824 s.select(selections);
7825 });
7826 this.insert("", window, cx);
7827 });
7828 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7829 }
7830
7831 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
7832 let item = self.cut_common(window, cx);
7833 cx.write_to_clipboard(item);
7834 }
7835
7836 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
7837 self.change_selections(None, window, cx, |s| {
7838 s.move_with(|snapshot, sel| {
7839 if sel.is_empty() {
7840 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7841 }
7842 });
7843 });
7844 let item = self.cut_common(window, cx);
7845 cx.set_global(KillRing(item))
7846 }
7847
7848 pub fn kill_ring_yank(
7849 &mut self,
7850 _: &KillRingYank,
7851 window: &mut Window,
7852 cx: &mut Context<Self>,
7853 ) {
7854 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7855 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7856 (kill_ring.text().to_string(), kill_ring.metadata_json())
7857 } else {
7858 return;
7859 }
7860 } else {
7861 return;
7862 };
7863 self.do_paste(&text, metadata, false, window, cx);
7864 }
7865
7866 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
7867 let selections = self.selections.all::<Point>(cx);
7868 let buffer = self.buffer.read(cx).read(cx);
7869 let mut text = String::new();
7870
7871 let mut clipboard_selections = Vec::with_capacity(selections.len());
7872 {
7873 let max_point = buffer.max_point();
7874 let mut is_first = true;
7875 for selection in selections.iter() {
7876 let mut start = selection.start;
7877 let mut end = selection.end;
7878 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7879 if is_entire_line {
7880 start = Point::new(start.row, 0);
7881 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7882 }
7883 if is_first {
7884 is_first = false;
7885 } else {
7886 text += "\n";
7887 }
7888 let mut len = 0;
7889 for chunk in buffer.text_for_range(start..end) {
7890 text.push_str(chunk);
7891 len += chunk.len();
7892 }
7893 clipboard_selections.push(ClipboardSelection {
7894 len,
7895 is_entire_line,
7896 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7897 });
7898 }
7899 }
7900
7901 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7902 text,
7903 clipboard_selections,
7904 ));
7905 }
7906
7907 pub fn do_paste(
7908 &mut self,
7909 text: &String,
7910 clipboard_selections: Option<Vec<ClipboardSelection>>,
7911 handle_entire_lines: bool,
7912 window: &mut Window,
7913 cx: &mut Context<Self>,
7914 ) {
7915 if self.read_only(cx) {
7916 return;
7917 }
7918
7919 let clipboard_text = Cow::Borrowed(text);
7920
7921 self.transact(window, cx, |this, window, cx| {
7922 if let Some(mut clipboard_selections) = clipboard_selections {
7923 let old_selections = this.selections.all::<usize>(cx);
7924 let all_selections_were_entire_line =
7925 clipboard_selections.iter().all(|s| s.is_entire_line);
7926 let first_selection_indent_column =
7927 clipboard_selections.first().map(|s| s.first_line_indent);
7928 if clipboard_selections.len() != old_selections.len() {
7929 clipboard_selections.drain(..);
7930 }
7931 let cursor_offset = this.selections.last::<usize>(cx).head();
7932 let mut auto_indent_on_paste = true;
7933
7934 this.buffer.update(cx, |buffer, cx| {
7935 let snapshot = buffer.read(cx);
7936 auto_indent_on_paste =
7937 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7938
7939 let mut start_offset = 0;
7940 let mut edits = Vec::new();
7941 let mut original_indent_columns = Vec::new();
7942 for (ix, selection) in old_selections.iter().enumerate() {
7943 let to_insert;
7944 let entire_line;
7945 let original_indent_column;
7946 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7947 let end_offset = start_offset + clipboard_selection.len;
7948 to_insert = &clipboard_text[start_offset..end_offset];
7949 entire_line = clipboard_selection.is_entire_line;
7950 start_offset = end_offset + 1;
7951 original_indent_column = Some(clipboard_selection.first_line_indent);
7952 } else {
7953 to_insert = clipboard_text.as_str();
7954 entire_line = all_selections_were_entire_line;
7955 original_indent_column = first_selection_indent_column
7956 }
7957
7958 // If the corresponding selection was empty when this slice of the
7959 // clipboard text was written, then the entire line containing the
7960 // selection was copied. If this selection is also currently empty,
7961 // then paste the line before the current line of the buffer.
7962 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7963 let column = selection.start.to_point(&snapshot).column as usize;
7964 let line_start = selection.start - column;
7965 line_start..line_start
7966 } else {
7967 selection.range()
7968 };
7969
7970 edits.push((range, to_insert));
7971 original_indent_columns.extend(original_indent_column);
7972 }
7973 drop(snapshot);
7974
7975 buffer.edit(
7976 edits,
7977 if auto_indent_on_paste {
7978 Some(AutoindentMode::Block {
7979 original_indent_columns,
7980 })
7981 } else {
7982 None
7983 },
7984 cx,
7985 );
7986 });
7987
7988 let selections = this.selections.all::<usize>(cx);
7989 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7990 s.select(selections)
7991 });
7992 } else {
7993 this.insert(&clipboard_text, window, cx);
7994 }
7995 });
7996 }
7997
7998 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
7999 if let Some(item) = cx.read_from_clipboard() {
8000 let entries = item.entries();
8001
8002 match entries.first() {
8003 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8004 // of all the pasted entries.
8005 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8006 .do_paste(
8007 clipboard_string.text(),
8008 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8009 true,
8010 window,
8011 cx,
8012 ),
8013 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8014 }
8015 }
8016 }
8017
8018 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8019 if self.read_only(cx) {
8020 return;
8021 }
8022
8023 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8024 if let Some((selections, _)) =
8025 self.selection_history.transaction(transaction_id).cloned()
8026 {
8027 self.change_selections(None, window, cx, |s| {
8028 s.select_anchors(selections.to_vec());
8029 });
8030 }
8031 self.request_autoscroll(Autoscroll::fit(), cx);
8032 self.unmark_text(window, cx);
8033 self.refresh_inline_completion(true, false, window, cx);
8034 cx.emit(EditorEvent::Edited { transaction_id });
8035 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8036 }
8037 }
8038
8039 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8040 if self.read_only(cx) {
8041 return;
8042 }
8043
8044 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8045 if let Some((_, Some(selections))) =
8046 self.selection_history.transaction(transaction_id).cloned()
8047 {
8048 self.change_selections(None, window, cx, |s| {
8049 s.select_anchors(selections.to_vec());
8050 });
8051 }
8052 self.request_autoscroll(Autoscroll::fit(), cx);
8053 self.unmark_text(window, cx);
8054 self.refresh_inline_completion(true, false, window, cx);
8055 cx.emit(EditorEvent::Edited { transaction_id });
8056 }
8057 }
8058
8059 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8060 self.buffer
8061 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8062 }
8063
8064 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8065 self.buffer
8066 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8067 }
8068
8069 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8070 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8071 let line_mode = s.line_mode;
8072 s.move_with(|map, selection| {
8073 let cursor = if selection.is_empty() && !line_mode {
8074 movement::left(map, selection.start)
8075 } else {
8076 selection.start
8077 };
8078 selection.collapse_to(cursor, SelectionGoal::None);
8079 });
8080 })
8081 }
8082
8083 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8084 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8085 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8086 })
8087 }
8088
8089 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8090 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8091 let line_mode = s.line_mode;
8092 s.move_with(|map, selection| {
8093 let cursor = if selection.is_empty() && !line_mode {
8094 movement::right(map, selection.end)
8095 } else {
8096 selection.end
8097 };
8098 selection.collapse_to(cursor, SelectionGoal::None)
8099 });
8100 })
8101 }
8102
8103 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
8104 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8105 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
8106 })
8107 }
8108
8109 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
8110 if self.take_rename(true, window, cx).is_some() {
8111 return;
8112 }
8113
8114 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8115 cx.propagate();
8116 return;
8117 }
8118
8119 let text_layout_details = &self.text_layout_details(window);
8120 let selection_count = self.selections.count();
8121 let first_selection = self.selections.first_anchor();
8122
8123 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8124 let line_mode = s.line_mode;
8125 s.move_with(|map, selection| {
8126 if !selection.is_empty() && !line_mode {
8127 selection.goal = SelectionGoal::None;
8128 }
8129 let (cursor, goal) = movement::up(
8130 map,
8131 selection.start,
8132 selection.goal,
8133 false,
8134 text_layout_details,
8135 );
8136 selection.collapse_to(cursor, goal);
8137 });
8138 });
8139
8140 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8141 {
8142 cx.propagate();
8143 }
8144 }
8145
8146 pub fn move_up_by_lines(
8147 &mut self,
8148 action: &MoveUpByLines,
8149 window: &mut Window,
8150 cx: &mut Context<Self>,
8151 ) {
8152 if self.take_rename(true, window, cx).is_some() {
8153 return;
8154 }
8155
8156 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8157 cx.propagate();
8158 return;
8159 }
8160
8161 let text_layout_details = &self.text_layout_details(window);
8162
8163 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8164 let line_mode = s.line_mode;
8165 s.move_with(|map, selection| {
8166 if !selection.is_empty() && !line_mode {
8167 selection.goal = SelectionGoal::None;
8168 }
8169 let (cursor, goal) = movement::up_by_rows(
8170 map,
8171 selection.start,
8172 action.lines,
8173 selection.goal,
8174 false,
8175 text_layout_details,
8176 );
8177 selection.collapse_to(cursor, goal);
8178 });
8179 })
8180 }
8181
8182 pub fn move_down_by_lines(
8183 &mut self,
8184 action: &MoveDownByLines,
8185 window: &mut Window,
8186 cx: &mut Context<Self>,
8187 ) {
8188 if self.take_rename(true, window, cx).is_some() {
8189 return;
8190 }
8191
8192 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8193 cx.propagate();
8194 return;
8195 }
8196
8197 let text_layout_details = &self.text_layout_details(window);
8198
8199 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8200 let line_mode = s.line_mode;
8201 s.move_with(|map, selection| {
8202 if !selection.is_empty() && !line_mode {
8203 selection.goal = SelectionGoal::None;
8204 }
8205 let (cursor, goal) = movement::down_by_rows(
8206 map,
8207 selection.start,
8208 action.lines,
8209 selection.goal,
8210 false,
8211 text_layout_details,
8212 );
8213 selection.collapse_to(cursor, goal);
8214 });
8215 })
8216 }
8217
8218 pub fn select_down_by_lines(
8219 &mut self,
8220 action: &SelectDownByLines,
8221 window: &mut Window,
8222 cx: &mut Context<Self>,
8223 ) {
8224 let text_layout_details = &self.text_layout_details(window);
8225 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8226 s.move_heads_with(|map, head, goal| {
8227 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
8228 })
8229 })
8230 }
8231
8232 pub fn select_up_by_lines(
8233 &mut self,
8234 action: &SelectUpByLines,
8235 window: &mut Window,
8236 cx: &mut Context<Self>,
8237 ) {
8238 let text_layout_details = &self.text_layout_details(window);
8239 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8240 s.move_heads_with(|map, head, goal| {
8241 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8242 })
8243 })
8244 }
8245
8246 pub fn select_page_up(
8247 &mut self,
8248 _: &SelectPageUp,
8249 window: &mut Window,
8250 cx: &mut Context<Self>,
8251 ) {
8252 let Some(row_count) = self.visible_row_count() else {
8253 return;
8254 };
8255
8256 let text_layout_details = &self.text_layout_details(window);
8257
8258 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8259 s.move_heads_with(|map, head, goal| {
8260 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8261 })
8262 })
8263 }
8264
8265 pub fn move_page_up(
8266 &mut self,
8267 action: &MovePageUp,
8268 window: &mut Window,
8269 cx: &mut Context<Self>,
8270 ) {
8271 if self.take_rename(true, window, cx).is_some() {
8272 return;
8273 }
8274
8275 if self
8276 .context_menu
8277 .borrow_mut()
8278 .as_mut()
8279 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8280 .unwrap_or(false)
8281 {
8282 return;
8283 }
8284
8285 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8286 cx.propagate();
8287 return;
8288 }
8289
8290 let Some(row_count) = self.visible_row_count() else {
8291 return;
8292 };
8293
8294 let autoscroll = if action.center_cursor {
8295 Autoscroll::center()
8296 } else {
8297 Autoscroll::fit()
8298 };
8299
8300 let text_layout_details = &self.text_layout_details(window);
8301
8302 self.change_selections(Some(autoscroll), window, cx, |s| {
8303 let line_mode = s.line_mode;
8304 s.move_with(|map, selection| {
8305 if !selection.is_empty() && !line_mode {
8306 selection.goal = SelectionGoal::None;
8307 }
8308 let (cursor, goal) = movement::up_by_rows(
8309 map,
8310 selection.end,
8311 row_count,
8312 selection.goal,
8313 false,
8314 text_layout_details,
8315 );
8316 selection.collapse_to(cursor, goal);
8317 });
8318 });
8319 }
8320
8321 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8322 let text_layout_details = &self.text_layout_details(window);
8323 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8324 s.move_heads_with(|map, head, goal| {
8325 movement::up(map, head, goal, false, text_layout_details)
8326 })
8327 })
8328 }
8329
8330 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8331 self.take_rename(true, window, cx);
8332
8333 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8334 cx.propagate();
8335 return;
8336 }
8337
8338 let text_layout_details = &self.text_layout_details(window);
8339 let selection_count = self.selections.count();
8340 let first_selection = self.selections.first_anchor();
8341
8342 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8343 let line_mode = s.line_mode;
8344 s.move_with(|map, selection| {
8345 if !selection.is_empty() && !line_mode {
8346 selection.goal = SelectionGoal::None;
8347 }
8348 let (cursor, goal) = movement::down(
8349 map,
8350 selection.end,
8351 selection.goal,
8352 false,
8353 text_layout_details,
8354 );
8355 selection.collapse_to(cursor, goal);
8356 });
8357 });
8358
8359 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8360 {
8361 cx.propagate();
8362 }
8363 }
8364
8365 pub fn select_page_down(
8366 &mut self,
8367 _: &SelectPageDown,
8368 window: &mut Window,
8369 cx: &mut Context<Self>,
8370 ) {
8371 let Some(row_count) = self.visible_row_count() else {
8372 return;
8373 };
8374
8375 let text_layout_details = &self.text_layout_details(window);
8376
8377 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8378 s.move_heads_with(|map, head, goal| {
8379 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8380 })
8381 })
8382 }
8383
8384 pub fn move_page_down(
8385 &mut self,
8386 action: &MovePageDown,
8387 window: &mut Window,
8388 cx: &mut Context<Self>,
8389 ) {
8390 if self.take_rename(true, window, cx).is_some() {
8391 return;
8392 }
8393
8394 if self
8395 .context_menu
8396 .borrow_mut()
8397 .as_mut()
8398 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8399 .unwrap_or(false)
8400 {
8401 return;
8402 }
8403
8404 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8405 cx.propagate();
8406 return;
8407 }
8408
8409 let Some(row_count) = self.visible_row_count() else {
8410 return;
8411 };
8412
8413 let autoscroll = if action.center_cursor {
8414 Autoscroll::center()
8415 } else {
8416 Autoscroll::fit()
8417 };
8418
8419 let text_layout_details = &self.text_layout_details(window);
8420 self.change_selections(Some(autoscroll), window, cx, |s| {
8421 let line_mode = s.line_mode;
8422 s.move_with(|map, selection| {
8423 if !selection.is_empty() && !line_mode {
8424 selection.goal = SelectionGoal::None;
8425 }
8426 let (cursor, goal) = movement::down_by_rows(
8427 map,
8428 selection.end,
8429 row_count,
8430 selection.goal,
8431 false,
8432 text_layout_details,
8433 );
8434 selection.collapse_to(cursor, goal);
8435 });
8436 });
8437 }
8438
8439 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8440 let text_layout_details = &self.text_layout_details(window);
8441 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8442 s.move_heads_with(|map, head, goal| {
8443 movement::down(map, head, goal, false, text_layout_details)
8444 })
8445 });
8446 }
8447
8448 pub fn context_menu_first(
8449 &mut self,
8450 _: &ContextMenuFirst,
8451 _window: &mut Window,
8452 cx: &mut Context<Self>,
8453 ) {
8454 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8455 context_menu.select_first(self.completion_provider.as_deref(), cx);
8456 }
8457 }
8458
8459 pub fn context_menu_prev(
8460 &mut self,
8461 _: &ContextMenuPrev,
8462 _window: &mut Window,
8463 cx: &mut Context<Self>,
8464 ) {
8465 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8466 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8467 }
8468 }
8469
8470 pub fn context_menu_next(
8471 &mut self,
8472 _: &ContextMenuNext,
8473 _window: &mut Window,
8474 cx: &mut Context<Self>,
8475 ) {
8476 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8477 context_menu.select_next(self.completion_provider.as_deref(), cx);
8478 }
8479 }
8480
8481 pub fn context_menu_last(
8482 &mut self,
8483 _: &ContextMenuLast,
8484 _window: &mut Window,
8485 cx: &mut Context<Self>,
8486 ) {
8487 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8488 context_menu.select_last(self.completion_provider.as_deref(), cx);
8489 }
8490 }
8491
8492 pub fn move_to_previous_word_start(
8493 &mut self,
8494 _: &MoveToPreviousWordStart,
8495 window: &mut Window,
8496 cx: &mut Context<Self>,
8497 ) {
8498 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8499 s.move_cursors_with(|map, head, _| {
8500 (
8501 movement::previous_word_start(map, head),
8502 SelectionGoal::None,
8503 )
8504 });
8505 })
8506 }
8507
8508 pub fn move_to_previous_subword_start(
8509 &mut self,
8510 _: &MoveToPreviousSubwordStart,
8511 window: &mut Window,
8512 cx: &mut Context<Self>,
8513 ) {
8514 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8515 s.move_cursors_with(|map, head, _| {
8516 (
8517 movement::previous_subword_start(map, head),
8518 SelectionGoal::None,
8519 )
8520 });
8521 })
8522 }
8523
8524 pub fn select_to_previous_word_start(
8525 &mut self,
8526 _: &SelectToPreviousWordStart,
8527 window: &mut Window,
8528 cx: &mut Context<Self>,
8529 ) {
8530 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8531 s.move_heads_with(|map, head, _| {
8532 (
8533 movement::previous_word_start(map, head),
8534 SelectionGoal::None,
8535 )
8536 });
8537 })
8538 }
8539
8540 pub fn select_to_previous_subword_start(
8541 &mut self,
8542 _: &SelectToPreviousSubwordStart,
8543 window: &mut Window,
8544 cx: &mut Context<Self>,
8545 ) {
8546 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8547 s.move_heads_with(|map, head, _| {
8548 (
8549 movement::previous_subword_start(map, head),
8550 SelectionGoal::None,
8551 )
8552 });
8553 })
8554 }
8555
8556 pub fn delete_to_previous_word_start(
8557 &mut self,
8558 action: &DeleteToPreviousWordStart,
8559 window: &mut Window,
8560 cx: &mut Context<Self>,
8561 ) {
8562 self.transact(window, cx, |this, window, cx| {
8563 this.select_autoclose_pair(window, cx);
8564 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8565 let line_mode = s.line_mode;
8566 s.move_with(|map, selection| {
8567 if selection.is_empty() && !line_mode {
8568 let cursor = if action.ignore_newlines {
8569 movement::previous_word_start(map, selection.head())
8570 } else {
8571 movement::previous_word_start_or_newline(map, selection.head())
8572 };
8573 selection.set_head(cursor, SelectionGoal::None);
8574 }
8575 });
8576 });
8577 this.insert("", window, cx);
8578 });
8579 }
8580
8581 pub fn delete_to_previous_subword_start(
8582 &mut self,
8583 _: &DeleteToPreviousSubwordStart,
8584 window: &mut Window,
8585 cx: &mut Context<Self>,
8586 ) {
8587 self.transact(window, cx, |this, window, cx| {
8588 this.select_autoclose_pair(window, cx);
8589 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8590 let line_mode = s.line_mode;
8591 s.move_with(|map, selection| {
8592 if selection.is_empty() && !line_mode {
8593 let cursor = movement::previous_subword_start(map, selection.head());
8594 selection.set_head(cursor, SelectionGoal::None);
8595 }
8596 });
8597 });
8598 this.insert("", window, cx);
8599 });
8600 }
8601
8602 pub fn move_to_next_word_end(
8603 &mut self,
8604 _: &MoveToNextWordEnd,
8605 window: &mut Window,
8606 cx: &mut Context<Self>,
8607 ) {
8608 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8609 s.move_cursors_with(|map, head, _| {
8610 (movement::next_word_end(map, head), SelectionGoal::None)
8611 });
8612 })
8613 }
8614
8615 pub fn move_to_next_subword_end(
8616 &mut self,
8617 _: &MoveToNextSubwordEnd,
8618 window: &mut Window,
8619 cx: &mut Context<Self>,
8620 ) {
8621 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8622 s.move_cursors_with(|map, head, _| {
8623 (movement::next_subword_end(map, head), SelectionGoal::None)
8624 });
8625 })
8626 }
8627
8628 pub fn select_to_next_word_end(
8629 &mut self,
8630 _: &SelectToNextWordEnd,
8631 window: &mut Window,
8632 cx: &mut Context<Self>,
8633 ) {
8634 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8635 s.move_heads_with(|map, head, _| {
8636 (movement::next_word_end(map, head), SelectionGoal::None)
8637 });
8638 })
8639 }
8640
8641 pub fn select_to_next_subword_end(
8642 &mut self,
8643 _: &SelectToNextSubwordEnd,
8644 window: &mut Window,
8645 cx: &mut Context<Self>,
8646 ) {
8647 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8648 s.move_heads_with(|map, head, _| {
8649 (movement::next_subword_end(map, head), SelectionGoal::None)
8650 });
8651 })
8652 }
8653
8654 pub fn delete_to_next_word_end(
8655 &mut self,
8656 action: &DeleteToNextWordEnd,
8657 window: &mut Window,
8658 cx: &mut Context<Self>,
8659 ) {
8660 self.transact(window, cx, |this, window, cx| {
8661 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8662 let line_mode = s.line_mode;
8663 s.move_with(|map, selection| {
8664 if selection.is_empty() && !line_mode {
8665 let cursor = if action.ignore_newlines {
8666 movement::next_word_end(map, selection.head())
8667 } else {
8668 movement::next_word_end_or_newline(map, selection.head())
8669 };
8670 selection.set_head(cursor, SelectionGoal::None);
8671 }
8672 });
8673 });
8674 this.insert("", window, cx);
8675 });
8676 }
8677
8678 pub fn delete_to_next_subword_end(
8679 &mut self,
8680 _: &DeleteToNextSubwordEnd,
8681 window: &mut Window,
8682 cx: &mut Context<Self>,
8683 ) {
8684 self.transact(window, cx, |this, window, cx| {
8685 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8686 s.move_with(|map, selection| {
8687 if selection.is_empty() {
8688 let cursor = movement::next_subword_end(map, selection.head());
8689 selection.set_head(cursor, SelectionGoal::None);
8690 }
8691 });
8692 });
8693 this.insert("", window, cx);
8694 });
8695 }
8696
8697 pub fn move_to_beginning_of_line(
8698 &mut self,
8699 action: &MoveToBeginningOfLine,
8700 window: &mut Window,
8701 cx: &mut Context<Self>,
8702 ) {
8703 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8704 s.move_cursors_with(|map, head, _| {
8705 (
8706 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8707 SelectionGoal::None,
8708 )
8709 });
8710 })
8711 }
8712
8713 pub fn select_to_beginning_of_line(
8714 &mut self,
8715 action: &SelectToBeginningOfLine,
8716 window: &mut Window,
8717 cx: &mut Context<Self>,
8718 ) {
8719 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8720 s.move_heads_with(|map, head, _| {
8721 (
8722 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8723 SelectionGoal::None,
8724 )
8725 });
8726 });
8727 }
8728
8729 pub fn delete_to_beginning_of_line(
8730 &mut self,
8731 _: &DeleteToBeginningOfLine,
8732 window: &mut Window,
8733 cx: &mut Context<Self>,
8734 ) {
8735 self.transact(window, cx, |this, window, cx| {
8736 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8737 s.move_with(|_, selection| {
8738 selection.reversed = true;
8739 });
8740 });
8741
8742 this.select_to_beginning_of_line(
8743 &SelectToBeginningOfLine {
8744 stop_at_soft_wraps: false,
8745 },
8746 window,
8747 cx,
8748 );
8749 this.backspace(&Backspace, window, cx);
8750 });
8751 }
8752
8753 pub fn move_to_end_of_line(
8754 &mut self,
8755 action: &MoveToEndOfLine,
8756 window: &mut Window,
8757 cx: &mut Context<Self>,
8758 ) {
8759 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8760 s.move_cursors_with(|map, head, _| {
8761 (
8762 movement::line_end(map, head, action.stop_at_soft_wraps),
8763 SelectionGoal::None,
8764 )
8765 });
8766 })
8767 }
8768
8769 pub fn select_to_end_of_line(
8770 &mut self,
8771 action: &SelectToEndOfLine,
8772 window: &mut Window,
8773 cx: &mut Context<Self>,
8774 ) {
8775 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8776 s.move_heads_with(|map, head, _| {
8777 (
8778 movement::line_end(map, head, action.stop_at_soft_wraps),
8779 SelectionGoal::None,
8780 )
8781 });
8782 })
8783 }
8784
8785 pub fn delete_to_end_of_line(
8786 &mut self,
8787 _: &DeleteToEndOfLine,
8788 window: &mut Window,
8789 cx: &mut Context<Self>,
8790 ) {
8791 self.transact(window, cx, |this, window, cx| {
8792 this.select_to_end_of_line(
8793 &SelectToEndOfLine {
8794 stop_at_soft_wraps: false,
8795 },
8796 window,
8797 cx,
8798 );
8799 this.delete(&Delete, window, cx);
8800 });
8801 }
8802
8803 pub fn cut_to_end_of_line(
8804 &mut self,
8805 _: &CutToEndOfLine,
8806 window: &mut Window,
8807 cx: &mut Context<Self>,
8808 ) {
8809 self.transact(window, cx, |this, window, cx| {
8810 this.select_to_end_of_line(
8811 &SelectToEndOfLine {
8812 stop_at_soft_wraps: false,
8813 },
8814 window,
8815 cx,
8816 );
8817 this.cut(&Cut, window, cx);
8818 });
8819 }
8820
8821 pub fn move_to_start_of_paragraph(
8822 &mut self,
8823 _: &MoveToStartOfParagraph,
8824 window: &mut Window,
8825 cx: &mut Context<Self>,
8826 ) {
8827 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8828 cx.propagate();
8829 return;
8830 }
8831
8832 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8833 s.move_with(|map, selection| {
8834 selection.collapse_to(
8835 movement::start_of_paragraph(map, selection.head(), 1),
8836 SelectionGoal::None,
8837 )
8838 });
8839 })
8840 }
8841
8842 pub fn move_to_end_of_paragraph(
8843 &mut self,
8844 _: &MoveToEndOfParagraph,
8845 window: &mut Window,
8846 cx: &mut Context<Self>,
8847 ) {
8848 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8849 cx.propagate();
8850 return;
8851 }
8852
8853 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8854 s.move_with(|map, selection| {
8855 selection.collapse_to(
8856 movement::end_of_paragraph(map, selection.head(), 1),
8857 SelectionGoal::None,
8858 )
8859 });
8860 })
8861 }
8862
8863 pub fn select_to_start_of_paragraph(
8864 &mut self,
8865 _: &SelectToStartOfParagraph,
8866 window: &mut Window,
8867 cx: &mut Context<Self>,
8868 ) {
8869 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8870 cx.propagate();
8871 return;
8872 }
8873
8874 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8875 s.move_heads_with(|map, head, _| {
8876 (
8877 movement::start_of_paragraph(map, head, 1),
8878 SelectionGoal::None,
8879 )
8880 });
8881 })
8882 }
8883
8884 pub fn select_to_end_of_paragraph(
8885 &mut self,
8886 _: &SelectToEndOfParagraph,
8887 window: &mut Window,
8888 cx: &mut Context<Self>,
8889 ) {
8890 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8891 cx.propagate();
8892 return;
8893 }
8894
8895 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8896 s.move_heads_with(|map, head, _| {
8897 (
8898 movement::end_of_paragraph(map, head, 1),
8899 SelectionGoal::None,
8900 )
8901 });
8902 })
8903 }
8904
8905 pub fn move_to_beginning(
8906 &mut self,
8907 _: &MoveToBeginning,
8908 window: &mut Window,
8909 cx: &mut Context<Self>,
8910 ) {
8911 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8912 cx.propagate();
8913 return;
8914 }
8915
8916 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8917 s.select_ranges(vec![0..0]);
8918 });
8919 }
8920
8921 pub fn select_to_beginning(
8922 &mut self,
8923 _: &SelectToBeginning,
8924 window: &mut Window,
8925 cx: &mut Context<Self>,
8926 ) {
8927 let mut selection = self.selections.last::<Point>(cx);
8928 selection.set_head(Point::zero(), SelectionGoal::None);
8929
8930 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8931 s.select(vec![selection]);
8932 });
8933 }
8934
8935 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
8936 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8937 cx.propagate();
8938 return;
8939 }
8940
8941 let cursor = self.buffer.read(cx).read(cx).len();
8942 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8943 s.select_ranges(vec![cursor..cursor])
8944 });
8945 }
8946
8947 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8948 self.nav_history = nav_history;
8949 }
8950
8951 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8952 self.nav_history.as_ref()
8953 }
8954
8955 fn push_to_nav_history(
8956 &mut self,
8957 cursor_anchor: Anchor,
8958 new_position: Option<Point>,
8959 cx: &mut Context<Self>,
8960 ) {
8961 if let Some(nav_history) = self.nav_history.as_mut() {
8962 let buffer = self.buffer.read(cx).read(cx);
8963 let cursor_position = cursor_anchor.to_point(&buffer);
8964 let scroll_state = self.scroll_manager.anchor();
8965 let scroll_top_row = scroll_state.top_row(&buffer);
8966 drop(buffer);
8967
8968 if let Some(new_position) = new_position {
8969 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8970 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8971 return;
8972 }
8973 }
8974
8975 nav_history.push(
8976 Some(NavigationData {
8977 cursor_anchor,
8978 cursor_position,
8979 scroll_anchor: scroll_state,
8980 scroll_top_row,
8981 }),
8982 cx,
8983 );
8984 }
8985 }
8986
8987 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
8988 let buffer = self.buffer.read(cx).snapshot(cx);
8989 let mut selection = self.selections.first::<usize>(cx);
8990 selection.set_head(buffer.len(), SelectionGoal::None);
8991 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8992 s.select(vec![selection]);
8993 });
8994 }
8995
8996 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
8997 let end = self.buffer.read(cx).read(cx).len();
8998 self.change_selections(None, window, cx, |s| {
8999 s.select_ranges(vec![0..end]);
9000 });
9001 }
9002
9003 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
9004 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9005 let mut selections = self.selections.all::<Point>(cx);
9006 let max_point = display_map.buffer_snapshot.max_point();
9007 for selection in &mut selections {
9008 let rows = selection.spanned_rows(true, &display_map);
9009 selection.start = Point::new(rows.start.0, 0);
9010 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
9011 selection.reversed = false;
9012 }
9013 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9014 s.select(selections);
9015 });
9016 }
9017
9018 pub fn split_selection_into_lines(
9019 &mut self,
9020 _: &SplitSelectionIntoLines,
9021 window: &mut Window,
9022 cx: &mut Context<Self>,
9023 ) {
9024 let mut to_unfold = Vec::new();
9025 let mut new_selection_ranges = Vec::new();
9026 {
9027 let selections = self.selections.all::<Point>(cx);
9028 let buffer = self.buffer.read(cx).read(cx);
9029 for selection in selections {
9030 for row in selection.start.row..selection.end.row {
9031 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
9032 new_selection_ranges.push(cursor..cursor);
9033 }
9034 new_selection_ranges.push(selection.end..selection.end);
9035 to_unfold.push(selection.start..selection.end);
9036 }
9037 }
9038 self.unfold_ranges(&to_unfold, true, true, cx);
9039 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9040 s.select_ranges(new_selection_ranges);
9041 });
9042 }
9043
9044 pub fn add_selection_above(
9045 &mut self,
9046 _: &AddSelectionAbove,
9047 window: &mut Window,
9048 cx: &mut Context<Self>,
9049 ) {
9050 self.add_selection(true, window, cx);
9051 }
9052
9053 pub fn add_selection_below(
9054 &mut self,
9055 _: &AddSelectionBelow,
9056 window: &mut Window,
9057 cx: &mut Context<Self>,
9058 ) {
9059 self.add_selection(false, window, cx);
9060 }
9061
9062 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
9063 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9064 let mut selections = self.selections.all::<Point>(cx);
9065 let text_layout_details = self.text_layout_details(window);
9066 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
9067 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
9068 let range = oldest_selection.display_range(&display_map).sorted();
9069
9070 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
9071 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
9072 let positions = start_x.min(end_x)..start_x.max(end_x);
9073
9074 selections.clear();
9075 let mut stack = Vec::new();
9076 for row in range.start.row().0..=range.end.row().0 {
9077 if let Some(selection) = self.selections.build_columnar_selection(
9078 &display_map,
9079 DisplayRow(row),
9080 &positions,
9081 oldest_selection.reversed,
9082 &text_layout_details,
9083 ) {
9084 stack.push(selection.id);
9085 selections.push(selection);
9086 }
9087 }
9088
9089 if above {
9090 stack.reverse();
9091 }
9092
9093 AddSelectionsState { above, stack }
9094 });
9095
9096 let last_added_selection = *state.stack.last().unwrap();
9097 let mut new_selections = Vec::new();
9098 if above == state.above {
9099 let end_row = if above {
9100 DisplayRow(0)
9101 } else {
9102 display_map.max_point().row()
9103 };
9104
9105 'outer: for selection in selections {
9106 if selection.id == last_added_selection {
9107 let range = selection.display_range(&display_map).sorted();
9108 debug_assert_eq!(range.start.row(), range.end.row());
9109 let mut row = range.start.row();
9110 let positions =
9111 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
9112 px(start)..px(end)
9113 } else {
9114 let start_x =
9115 display_map.x_for_display_point(range.start, &text_layout_details);
9116 let end_x =
9117 display_map.x_for_display_point(range.end, &text_layout_details);
9118 start_x.min(end_x)..start_x.max(end_x)
9119 };
9120
9121 while row != end_row {
9122 if above {
9123 row.0 -= 1;
9124 } else {
9125 row.0 += 1;
9126 }
9127
9128 if let Some(new_selection) = self.selections.build_columnar_selection(
9129 &display_map,
9130 row,
9131 &positions,
9132 selection.reversed,
9133 &text_layout_details,
9134 ) {
9135 state.stack.push(new_selection.id);
9136 if above {
9137 new_selections.push(new_selection);
9138 new_selections.push(selection);
9139 } else {
9140 new_selections.push(selection);
9141 new_selections.push(new_selection);
9142 }
9143
9144 continue 'outer;
9145 }
9146 }
9147 }
9148
9149 new_selections.push(selection);
9150 }
9151 } else {
9152 new_selections = selections;
9153 new_selections.retain(|s| s.id != last_added_selection);
9154 state.stack.pop();
9155 }
9156
9157 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9158 s.select(new_selections);
9159 });
9160 if state.stack.len() > 1 {
9161 self.add_selections_state = Some(state);
9162 }
9163 }
9164
9165 pub fn select_next_match_internal(
9166 &mut self,
9167 display_map: &DisplaySnapshot,
9168 replace_newest: bool,
9169 autoscroll: Option<Autoscroll>,
9170 window: &mut Window,
9171 cx: &mut Context<Self>,
9172 ) -> Result<()> {
9173 fn select_next_match_ranges(
9174 this: &mut Editor,
9175 range: Range<usize>,
9176 replace_newest: bool,
9177 auto_scroll: Option<Autoscroll>,
9178 window: &mut Window,
9179 cx: &mut Context<Editor>,
9180 ) {
9181 this.unfold_ranges(&[range.clone()], false, true, cx);
9182 this.change_selections(auto_scroll, window, cx, |s| {
9183 if replace_newest {
9184 s.delete(s.newest_anchor().id);
9185 }
9186 s.insert_range(range.clone());
9187 });
9188 }
9189
9190 let buffer = &display_map.buffer_snapshot;
9191 let mut selections = self.selections.all::<usize>(cx);
9192 if let Some(mut select_next_state) = self.select_next_state.take() {
9193 let query = &select_next_state.query;
9194 if !select_next_state.done {
9195 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9196 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9197 let mut next_selected_range = None;
9198
9199 let bytes_after_last_selection =
9200 buffer.bytes_in_range(last_selection.end..buffer.len());
9201 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
9202 let query_matches = query
9203 .stream_find_iter(bytes_after_last_selection)
9204 .map(|result| (last_selection.end, result))
9205 .chain(
9206 query
9207 .stream_find_iter(bytes_before_first_selection)
9208 .map(|result| (0, result)),
9209 );
9210
9211 for (start_offset, query_match) in query_matches {
9212 let query_match = query_match.unwrap(); // can only fail due to I/O
9213 let offset_range =
9214 start_offset + query_match.start()..start_offset + query_match.end();
9215 let display_range = offset_range.start.to_display_point(display_map)
9216 ..offset_range.end.to_display_point(display_map);
9217
9218 if !select_next_state.wordwise
9219 || (!movement::is_inside_word(display_map, display_range.start)
9220 && !movement::is_inside_word(display_map, display_range.end))
9221 {
9222 // TODO: This is n^2, because we might check all the selections
9223 if !selections
9224 .iter()
9225 .any(|selection| selection.range().overlaps(&offset_range))
9226 {
9227 next_selected_range = Some(offset_range);
9228 break;
9229 }
9230 }
9231 }
9232
9233 if let Some(next_selected_range) = next_selected_range {
9234 select_next_match_ranges(
9235 self,
9236 next_selected_range,
9237 replace_newest,
9238 autoscroll,
9239 window,
9240 cx,
9241 );
9242 } else {
9243 select_next_state.done = true;
9244 }
9245 }
9246
9247 self.select_next_state = Some(select_next_state);
9248 } else {
9249 let mut only_carets = true;
9250 let mut same_text_selected = true;
9251 let mut selected_text = None;
9252
9253 let mut selections_iter = selections.iter().peekable();
9254 while let Some(selection) = selections_iter.next() {
9255 if selection.start != selection.end {
9256 only_carets = false;
9257 }
9258
9259 if same_text_selected {
9260 if selected_text.is_none() {
9261 selected_text =
9262 Some(buffer.text_for_range(selection.range()).collect::<String>());
9263 }
9264
9265 if let Some(next_selection) = selections_iter.peek() {
9266 if next_selection.range().len() == selection.range().len() {
9267 let next_selected_text = buffer
9268 .text_for_range(next_selection.range())
9269 .collect::<String>();
9270 if Some(next_selected_text) != selected_text {
9271 same_text_selected = false;
9272 selected_text = None;
9273 }
9274 } else {
9275 same_text_selected = false;
9276 selected_text = None;
9277 }
9278 }
9279 }
9280 }
9281
9282 if only_carets {
9283 for selection in &mut selections {
9284 let word_range = movement::surrounding_word(
9285 display_map,
9286 selection.start.to_display_point(display_map),
9287 );
9288 selection.start = word_range.start.to_offset(display_map, Bias::Left);
9289 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9290 selection.goal = SelectionGoal::None;
9291 selection.reversed = false;
9292 select_next_match_ranges(
9293 self,
9294 selection.start..selection.end,
9295 replace_newest,
9296 autoscroll,
9297 window,
9298 cx,
9299 );
9300 }
9301
9302 if selections.len() == 1 {
9303 let selection = selections
9304 .last()
9305 .expect("ensured that there's only one selection");
9306 let query = buffer
9307 .text_for_range(selection.start..selection.end)
9308 .collect::<String>();
9309 let is_empty = query.is_empty();
9310 let select_state = SelectNextState {
9311 query: AhoCorasick::new(&[query])?,
9312 wordwise: true,
9313 done: is_empty,
9314 };
9315 self.select_next_state = Some(select_state);
9316 } else {
9317 self.select_next_state = None;
9318 }
9319 } else if let Some(selected_text) = selected_text {
9320 self.select_next_state = Some(SelectNextState {
9321 query: AhoCorasick::new(&[selected_text])?,
9322 wordwise: false,
9323 done: false,
9324 });
9325 self.select_next_match_internal(
9326 display_map,
9327 replace_newest,
9328 autoscroll,
9329 window,
9330 cx,
9331 )?;
9332 }
9333 }
9334 Ok(())
9335 }
9336
9337 pub fn select_all_matches(
9338 &mut self,
9339 _action: &SelectAllMatches,
9340 window: &mut Window,
9341 cx: &mut Context<Self>,
9342 ) -> Result<()> {
9343 self.push_to_selection_history();
9344 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9345
9346 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9347 let Some(select_next_state) = self.select_next_state.as_mut() else {
9348 return Ok(());
9349 };
9350 if select_next_state.done {
9351 return Ok(());
9352 }
9353
9354 let mut new_selections = self.selections.all::<usize>(cx);
9355
9356 let buffer = &display_map.buffer_snapshot;
9357 let query_matches = select_next_state
9358 .query
9359 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9360
9361 for query_match in query_matches {
9362 let query_match = query_match.unwrap(); // can only fail due to I/O
9363 let offset_range = query_match.start()..query_match.end();
9364 let display_range = offset_range.start.to_display_point(&display_map)
9365 ..offset_range.end.to_display_point(&display_map);
9366
9367 if !select_next_state.wordwise
9368 || (!movement::is_inside_word(&display_map, display_range.start)
9369 && !movement::is_inside_word(&display_map, display_range.end))
9370 {
9371 self.selections.change_with(cx, |selections| {
9372 new_selections.push(Selection {
9373 id: selections.new_selection_id(),
9374 start: offset_range.start,
9375 end: offset_range.end,
9376 reversed: false,
9377 goal: SelectionGoal::None,
9378 });
9379 });
9380 }
9381 }
9382
9383 new_selections.sort_by_key(|selection| selection.start);
9384 let mut ix = 0;
9385 while ix + 1 < new_selections.len() {
9386 let current_selection = &new_selections[ix];
9387 let next_selection = &new_selections[ix + 1];
9388 if current_selection.range().overlaps(&next_selection.range()) {
9389 if current_selection.id < next_selection.id {
9390 new_selections.remove(ix + 1);
9391 } else {
9392 new_selections.remove(ix);
9393 }
9394 } else {
9395 ix += 1;
9396 }
9397 }
9398
9399 let reversed = self.selections.oldest::<usize>(cx).reversed;
9400
9401 for selection in new_selections.iter_mut() {
9402 selection.reversed = reversed;
9403 }
9404
9405 select_next_state.done = true;
9406 self.unfold_ranges(
9407 &new_selections
9408 .iter()
9409 .map(|selection| selection.range())
9410 .collect::<Vec<_>>(),
9411 false,
9412 false,
9413 cx,
9414 );
9415 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9416 selections.select(new_selections)
9417 });
9418
9419 Ok(())
9420 }
9421
9422 pub fn select_next(
9423 &mut self,
9424 action: &SelectNext,
9425 window: &mut Window,
9426 cx: &mut Context<Self>,
9427 ) -> Result<()> {
9428 self.push_to_selection_history();
9429 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9430 self.select_next_match_internal(
9431 &display_map,
9432 action.replace_newest,
9433 Some(Autoscroll::newest()),
9434 window,
9435 cx,
9436 )?;
9437 Ok(())
9438 }
9439
9440 pub fn select_previous(
9441 &mut self,
9442 action: &SelectPrevious,
9443 window: &mut Window,
9444 cx: &mut Context<Self>,
9445 ) -> Result<()> {
9446 self.push_to_selection_history();
9447 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9448 let buffer = &display_map.buffer_snapshot;
9449 let mut selections = self.selections.all::<usize>(cx);
9450 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9451 let query = &select_prev_state.query;
9452 if !select_prev_state.done {
9453 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9454 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9455 let mut next_selected_range = None;
9456 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9457 let bytes_before_last_selection =
9458 buffer.reversed_bytes_in_range(0..last_selection.start);
9459 let bytes_after_first_selection =
9460 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9461 let query_matches = query
9462 .stream_find_iter(bytes_before_last_selection)
9463 .map(|result| (last_selection.start, result))
9464 .chain(
9465 query
9466 .stream_find_iter(bytes_after_first_selection)
9467 .map(|result| (buffer.len(), result)),
9468 );
9469 for (end_offset, query_match) in query_matches {
9470 let query_match = query_match.unwrap(); // can only fail due to I/O
9471 let offset_range =
9472 end_offset - query_match.end()..end_offset - query_match.start();
9473 let display_range = offset_range.start.to_display_point(&display_map)
9474 ..offset_range.end.to_display_point(&display_map);
9475
9476 if !select_prev_state.wordwise
9477 || (!movement::is_inside_word(&display_map, display_range.start)
9478 && !movement::is_inside_word(&display_map, display_range.end))
9479 {
9480 next_selected_range = Some(offset_range);
9481 break;
9482 }
9483 }
9484
9485 if let Some(next_selected_range) = next_selected_range {
9486 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9487 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9488 if action.replace_newest {
9489 s.delete(s.newest_anchor().id);
9490 }
9491 s.insert_range(next_selected_range);
9492 });
9493 } else {
9494 select_prev_state.done = true;
9495 }
9496 }
9497
9498 self.select_prev_state = Some(select_prev_state);
9499 } else {
9500 let mut only_carets = true;
9501 let mut same_text_selected = true;
9502 let mut selected_text = None;
9503
9504 let mut selections_iter = selections.iter().peekable();
9505 while let Some(selection) = selections_iter.next() {
9506 if selection.start != selection.end {
9507 only_carets = false;
9508 }
9509
9510 if same_text_selected {
9511 if selected_text.is_none() {
9512 selected_text =
9513 Some(buffer.text_for_range(selection.range()).collect::<String>());
9514 }
9515
9516 if let Some(next_selection) = selections_iter.peek() {
9517 if next_selection.range().len() == selection.range().len() {
9518 let next_selected_text = buffer
9519 .text_for_range(next_selection.range())
9520 .collect::<String>();
9521 if Some(next_selected_text) != selected_text {
9522 same_text_selected = false;
9523 selected_text = None;
9524 }
9525 } else {
9526 same_text_selected = false;
9527 selected_text = None;
9528 }
9529 }
9530 }
9531 }
9532
9533 if only_carets {
9534 for selection in &mut selections {
9535 let word_range = movement::surrounding_word(
9536 &display_map,
9537 selection.start.to_display_point(&display_map),
9538 );
9539 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9540 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9541 selection.goal = SelectionGoal::None;
9542 selection.reversed = false;
9543 }
9544 if selections.len() == 1 {
9545 let selection = selections
9546 .last()
9547 .expect("ensured that there's only one selection");
9548 let query = buffer
9549 .text_for_range(selection.start..selection.end)
9550 .collect::<String>();
9551 let is_empty = query.is_empty();
9552 let select_state = SelectNextState {
9553 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9554 wordwise: true,
9555 done: is_empty,
9556 };
9557 self.select_prev_state = Some(select_state);
9558 } else {
9559 self.select_prev_state = None;
9560 }
9561
9562 self.unfold_ranges(
9563 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9564 false,
9565 true,
9566 cx,
9567 );
9568 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9569 s.select(selections);
9570 });
9571 } else if let Some(selected_text) = selected_text {
9572 self.select_prev_state = Some(SelectNextState {
9573 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9574 wordwise: false,
9575 done: false,
9576 });
9577 self.select_previous(action, window, cx)?;
9578 }
9579 }
9580 Ok(())
9581 }
9582
9583 pub fn toggle_comments(
9584 &mut self,
9585 action: &ToggleComments,
9586 window: &mut Window,
9587 cx: &mut Context<Self>,
9588 ) {
9589 if self.read_only(cx) {
9590 return;
9591 }
9592 let text_layout_details = &self.text_layout_details(window);
9593 self.transact(window, cx, |this, window, cx| {
9594 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9595 let mut edits = Vec::new();
9596 let mut selection_edit_ranges = Vec::new();
9597 let mut last_toggled_row = None;
9598 let snapshot = this.buffer.read(cx).read(cx);
9599 let empty_str: Arc<str> = Arc::default();
9600 let mut suffixes_inserted = Vec::new();
9601 let ignore_indent = action.ignore_indent;
9602
9603 fn comment_prefix_range(
9604 snapshot: &MultiBufferSnapshot,
9605 row: MultiBufferRow,
9606 comment_prefix: &str,
9607 comment_prefix_whitespace: &str,
9608 ignore_indent: bool,
9609 ) -> Range<Point> {
9610 let indent_size = if ignore_indent {
9611 0
9612 } else {
9613 snapshot.indent_size_for_line(row).len
9614 };
9615
9616 let start = Point::new(row.0, indent_size);
9617
9618 let mut line_bytes = snapshot
9619 .bytes_in_range(start..snapshot.max_point())
9620 .flatten()
9621 .copied();
9622
9623 // If this line currently begins with the line comment prefix, then record
9624 // the range containing the prefix.
9625 if line_bytes
9626 .by_ref()
9627 .take(comment_prefix.len())
9628 .eq(comment_prefix.bytes())
9629 {
9630 // Include any whitespace that matches the comment prefix.
9631 let matching_whitespace_len = line_bytes
9632 .zip(comment_prefix_whitespace.bytes())
9633 .take_while(|(a, b)| a == b)
9634 .count() as u32;
9635 let end = Point::new(
9636 start.row,
9637 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9638 );
9639 start..end
9640 } else {
9641 start..start
9642 }
9643 }
9644
9645 fn comment_suffix_range(
9646 snapshot: &MultiBufferSnapshot,
9647 row: MultiBufferRow,
9648 comment_suffix: &str,
9649 comment_suffix_has_leading_space: bool,
9650 ) -> Range<Point> {
9651 let end = Point::new(row.0, snapshot.line_len(row));
9652 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9653
9654 let mut line_end_bytes = snapshot
9655 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9656 .flatten()
9657 .copied();
9658
9659 let leading_space_len = if suffix_start_column > 0
9660 && line_end_bytes.next() == Some(b' ')
9661 && comment_suffix_has_leading_space
9662 {
9663 1
9664 } else {
9665 0
9666 };
9667
9668 // If this line currently begins with the line comment prefix, then record
9669 // the range containing the prefix.
9670 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9671 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9672 start..end
9673 } else {
9674 end..end
9675 }
9676 }
9677
9678 // TODO: Handle selections that cross excerpts
9679 for selection in &mut selections {
9680 let start_column = snapshot
9681 .indent_size_for_line(MultiBufferRow(selection.start.row))
9682 .len;
9683 let language = if let Some(language) =
9684 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9685 {
9686 language
9687 } else {
9688 continue;
9689 };
9690
9691 selection_edit_ranges.clear();
9692
9693 // If multiple selections contain a given row, avoid processing that
9694 // row more than once.
9695 let mut start_row = MultiBufferRow(selection.start.row);
9696 if last_toggled_row == Some(start_row) {
9697 start_row = start_row.next_row();
9698 }
9699 let end_row =
9700 if selection.end.row > selection.start.row && selection.end.column == 0 {
9701 MultiBufferRow(selection.end.row - 1)
9702 } else {
9703 MultiBufferRow(selection.end.row)
9704 };
9705 last_toggled_row = Some(end_row);
9706
9707 if start_row > end_row {
9708 continue;
9709 }
9710
9711 // If the language has line comments, toggle those.
9712 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9713
9714 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9715 if ignore_indent {
9716 full_comment_prefixes = full_comment_prefixes
9717 .into_iter()
9718 .map(|s| Arc::from(s.trim_end()))
9719 .collect();
9720 }
9721
9722 if !full_comment_prefixes.is_empty() {
9723 let first_prefix = full_comment_prefixes
9724 .first()
9725 .expect("prefixes is non-empty");
9726 let prefix_trimmed_lengths = full_comment_prefixes
9727 .iter()
9728 .map(|p| p.trim_end_matches(' ').len())
9729 .collect::<SmallVec<[usize; 4]>>();
9730
9731 let mut all_selection_lines_are_comments = true;
9732
9733 for row in start_row.0..=end_row.0 {
9734 let row = MultiBufferRow(row);
9735 if start_row < end_row && snapshot.is_line_blank(row) {
9736 continue;
9737 }
9738
9739 let prefix_range = full_comment_prefixes
9740 .iter()
9741 .zip(prefix_trimmed_lengths.iter().copied())
9742 .map(|(prefix, trimmed_prefix_len)| {
9743 comment_prefix_range(
9744 snapshot.deref(),
9745 row,
9746 &prefix[..trimmed_prefix_len],
9747 &prefix[trimmed_prefix_len..],
9748 ignore_indent,
9749 )
9750 })
9751 .max_by_key(|range| range.end.column - range.start.column)
9752 .expect("prefixes is non-empty");
9753
9754 if prefix_range.is_empty() {
9755 all_selection_lines_are_comments = false;
9756 }
9757
9758 selection_edit_ranges.push(prefix_range);
9759 }
9760
9761 if all_selection_lines_are_comments {
9762 edits.extend(
9763 selection_edit_ranges
9764 .iter()
9765 .cloned()
9766 .map(|range| (range, empty_str.clone())),
9767 );
9768 } else {
9769 let min_column = selection_edit_ranges
9770 .iter()
9771 .map(|range| range.start.column)
9772 .min()
9773 .unwrap_or(0);
9774 edits.extend(selection_edit_ranges.iter().map(|range| {
9775 let position = Point::new(range.start.row, min_column);
9776 (position..position, first_prefix.clone())
9777 }));
9778 }
9779 } else if let Some((full_comment_prefix, comment_suffix)) =
9780 language.block_comment_delimiters()
9781 {
9782 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9783 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9784 let prefix_range = comment_prefix_range(
9785 snapshot.deref(),
9786 start_row,
9787 comment_prefix,
9788 comment_prefix_whitespace,
9789 ignore_indent,
9790 );
9791 let suffix_range = comment_suffix_range(
9792 snapshot.deref(),
9793 end_row,
9794 comment_suffix.trim_start_matches(' '),
9795 comment_suffix.starts_with(' '),
9796 );
9797
9798 if prefix_range.is_empty() || suffix_range.is_empty() {
9799 edits.push((
9800 prefix_range.start..prefix_range.start,
9801 full_comment_prefix.clone(),
9802 ));
9803 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9804 suffixes_inserted.push((end_row, comment_suffix.len()));
9805 } else {
9806 edits.push((prefix_range, empty_str.clone()));
9807 edits.push((suffix_range, empty_str.clone()));
9808 }
9809 } else {
9810 continue;
9811 }
9812 }
9813
9814 drop(snapshot);
9815 this.buffer.update(cx, |buffer, cx| {
9816 buffer.edit(edits, None, cx);
9817 });
9818
9819 // Adjust selections so that they end before any comment suffixes that
9820 // were inserted.
9821 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9822 let mut selections = this.selections.all::<Point>(cx);
9823 let snapshot = this.buffer.read(cx).read(cx);
9824 for selection in &mut selections {
9825 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9826 match row.cmp(&MultiBufferRow(selection.end.row)) {
9827 Ordering::Less => {
9828 suffixes_inserted.next();
9829 continue;
9830 }
9831 Ordering::Greater => break,
9832 Ordering::Equal => {
9833 if selection.end.column == snapshot.line_len(row) {
9834 if selection.is_empty() {
9835 selection.start.column -= suffix_len as u32;
9836 }
9837 selection.end.column -= suffix_len as u32;
9838 }
9839 break;
9840 }
9841 }
9842 }
9843 }
9844
9845 drop(snapshot);
9846 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9847 s.select(selections)
9848 });
9849
9850 let selections = this.selections.all::<Point>(cx);
9851 let selections_on_single_row = selections.windows(2).all(|selections| {
9852 selections[0].start.row == selections[1].start.row
9853 && selections[0].end.row == selections[1].end.row
9854 && selections[0].start.row == selections[0].end.row
9855 });
9856 let selections_selecting = selections
9857 .iter()
9858 .any(|selection| selection.start != selection.end);
9859 let advance_downwards = action.advance_downwards
9860 && selections_on_single_row
9861 && !selections_selecting
9862 && !matches!(this.mode, EditorMode::SingleLine { .. });
9863
9864 if advance_downwards {
9865 let snapshot = this.buffer.read(cx).snapshot(cx);
9866
9867 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9868 s.move_cursors_with(|display_snapshot, display_point, _| {
9869 let mut point = display_point.to_point(display_snapshot);
9870 point.row += 1;
9871 point = snapshot.clip_point(point, Bias::Left);
9872 let display_point = point.to_display_point(display_snapshot);
9873 let goal = SelectionGoal::HorizontalPosition(
9874 display_snapshot
9875 .x_for_display_point(display_point, text_layout_details)
9876 .into(),
9877 );
9878 (display_point, goal)
9879 })
9880 });
9881 }
9882 });
9883 }
9884
9885 pub fn select_enclosing_symbol(
9886 &mut self,
9887 _: &SelectEnclosingSymbol,
9888 window: &mut Window,
9889 cx: &mut Context<Self>,
9890 ) {
9891 let buffer = self.buffer.read(cx).snapshot(cx);
9892 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9893
9894 fn update_selection(
9895 selection: &Selection<usize>,
9896 buffer_snap: &MultiBufferSnapshot,
9897 ) -> Option<Selection<usize>> {
9898 let cursor = selection.head();
9899 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9900 for symbol in symbols.iter().rev() {
9901 let start = symbol.range.start.to_offset(buffer_snap);
9902 let end = symbol.range.end.to_offset(buffer_snap);
9903 let new_range = start..end;
9904 if start < selection.start || end > selection.end {
9905 return Some(Selection {
9906 id: selection.id,
9907 start: new_range.start,
9908 end: new_range.end,
9909 goal: SelectionGoal::None,
9910 reversed: selection.reversed,
9911 });
9912 }
9913 }
9914 None
9915 }
9916
9917 let mut selected_larger_symbol = false;
9918 let new_selections = old_selections
9919 .iter()
9920 .map(|selection| match update_selection(selection, &buffer) {
9921 Some(new_selection) => {
9922 if new_selection.range() != selection.range() {
9923 selected_larger_symbol = true;
9924 }
9925 new_selection
9926 }
9927 None => selection.clone(),
9928 })
9929 .collect::<Vec<_>>();
9930
9931 if selected_larger_symbol {
9932 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9933 s.select(new_selections);
9934 });
9935 }
9936 }
9937
9938 pub fn select_larger_syntax_node(
9939 &mut self,
9940 _: &SelectLargerSyntaxNode,
9941 window: &mut Window,
9942 cx: &mut Context<Self>,
9943 ) {
9944 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9945 let buffer = self.buffer.read(cx).snapshot(cx);
9946 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9947
9948 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9949 let mut selected_larger_node = false;
9950 let new_selections = old_selections
9951 .iter()
9952 .map(|selection| {
9953 let old_range = selection.start..selection.end;
9954 let mut new_range = old_range.clone();
9955 let mut new_node = None;
9956 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
9957 {
9958 new_node = Some(node);
9959 new_range = containing_range;
9960 if !display_map.intersects_fold(new_range.start)
9961 && !display_map.intersects_fold(new_range.end)
9962 {
9963 break;
9964 }
9965 }
9966
9967 if let Some(node) = new_node {
9968 // Log the ancestor, to support using this action as a way to explore TreeSitter
9969 // nodes. Parent and grandparent are also logged because this operation will not
9970 // visit nodes that have the same range as their parent.
9971 log::info!("Node: {node:?}");
9972 let parent = node.parent();
9973 log::info!("Parent: {parent:?}");
9974 let grandparent = parent.and_then(|x| x.parent());
9975 log::info!("Grandparent: {grandparent:?}");
9976 }
9977
9978 selected_larger_node |= new_range != old_range;
9979 Selection {
9980 id: selection.id,
9981 start: new_range.start,
9982 end: new_range.end,
9983 goal: SelectionGoal::None,
9984 reversed: selection.reversed,
9985 }
9986 })
9987 .collect::<Vec<_>>();
9988
9989 if selected_larger_node {
9990 stack.push(old_selections);
9991 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9992 s.select(new_selections);
9993 });
9994 }
9995 self.select_larger_syntax_node_stack = stack;
9996 }
9997
9998 pub fn select_smaller_syntax_node(
9999 &mut self,
10000 _: &SelectSmallerSyntaxNode,
10001 window: &mut Window,
10002 cx: &mut Context<Self>,
10003 ) {
10004 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10005 if let Some(selections) = stack.pop() {
10006 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10007 s.select(selections.to_vec());
10008 });
10009 }
10010 self.select_larger_syntax_node_stack = stack;
10011 }
10012
10013 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10014 if !EditorSettings::get_global(cx).gutter.runnables {
10015 self.clear_tasks();
10016 return Task::ready(());
10017 }
10018 let project = self.project.as_ref().map(Entity::downgrade);
10019 cx.spawn_in(window, |this, mut cx| async move {
10020 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10021 let Some(project) = project.and_then(|p| p.upgrade()) else {
10022 return;
10023 };
10024 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10025 this.display_map.update(cx, |map, cx| map.snapshot(cx))
10026 }) else {
10027 return;
10028 };
10029
10030 let hide_runnables = project
10031 .update(&mut cx, |project, cx| {
10032 // Do not display any test indicators in non-dev server remote projects.
10033 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10034 })
10035 .unwrap_or(true);
10036 if hide_runnables {
10037 return;
10038 }
10039 let new_rows =
10040 cx.background_executor()
10041 .spawn({
10042 let snapshot = display_snapshot.clone();
10043 async move {
10044 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10045 }
10046 })
10047 .await;
10048
10049 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10050 this.update(&mut cx, |this, _| {
10051 this.clear_tasks();
10052 for (key, value) in rows {
10053 this.insert_tasks(key, value);
10054 }
10055 })
10056 .ok();
10057 })
10058 }
10059 fn fetch_runnable_ranges(
10060 snapshot: &DisplaySnapshot,
10061 range: Range<Anchor>,
10062 ) -> Vec<language::RunnableRange> {
10063 snapshot.buffer_snapshot.runnable_ranges(range).collect()
10064 }
10065
10066 fn runnable_rows(
10067 project: Entity<Project>,
10068 snapshot: DisplaySnapshot,
10069 runnable_ranges: Vec<RunnableRange>,
10070 mut cx: AsyncWindowContext,
10071 ) -> Vec<((BufferId, u32), RunnableTasks)> {
10072 runnable_ranges
10073 .into_iter()
10074 .filter_map(|mut runnable| {
10075 let tasks = cx
10076 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10077 .ok()?;
10078 if tasks.is_empty() {
10079 return None;
10080 }
10081
10082 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10083
10084 let row = snapshot
10085 .buffer_snapshot
10086 .buffer_line_for_row(MultiBufferRow(point.row))?
10087 .1
10088 .start
10089 .row;
10090
10091 let context_range =
10092 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10093 Some((
10094 (runnable.buffer_id, row),
10095 RunnableTasks {
10096 templates: tasks,
10097 offset: MultiBufferOffset(runnable.run_range.start),
10098 context_range,
10099 column: point.column,
10100 extra_variables: runnable.extra_captures,
10101 },
10102 ))
10103 })
10104 .collect()
10105 }
10106
10107 fn templates_with_tags(
10108 project: &Entity<Project>,
10109 runnable: &mut Runnable,
10110 cx: &mut App,
10111 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10112 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10113 let (worktree_id, file) = project
10114 .buffer_for_id(runnable.buffer, cx)
10115 .and_then(|buffer| buffer.read(cx).file())
10116 .map(|file| (file.worktree_id(cx), file.clone()))
10117 .unzip();
10118
10119 (
10120 project.task_store().read(cx).task_inventory().cloned(),
10121 worktree_id,
10122 file,
10123 )
10124 });
10125
10126 let tags = mem::take(&mut runnable.tags);
10127 let mut tags: Vec<_> = tags
10128 .into_iter()
10129 .flat_map(|tag| {
10130 let tag = tag.0.clone();
10131 inventory
10132 .as_ref()
10133 .into_iter()
10134 .flat_map(|inventory| {
10135 inventory.read(cx).list_tasks(
10136 file.clone(),
10137 Some(runnable.language.clone()),
10138 worktree_id,
10139 cx,
10140 )
10141 })
10142 .filter(move |(_, template)| {
10143 template.tags.iter().any(|source_tag| source_tag == &tag)
10144 })
10145 })
10146 .sorted_by_key(|(kind, _)| kind.to_owned())
10147 .collect();
10148 if let Some((leading_tag_source, _)) = tags.first() {
10149 // Strongest source wins; if we have worktree tag binding, prefer that to
10150 // global and language bindings;
10151 // if we have a global binding, prefer that to language binding.
10152 let first_mismatch = tags
10153 .iter()
10154 .position(|(tag_source, _)| tag_source != leading_tag_source);
10155 if let Some(index) = first_mismatch {
10156 tags.truncate(index);
10157 }
10158 }
10159
10160 tags
10161 }
10162
10163 pub fn move_to_enclosing_bracket(
10164 &mut self,
10165 _: &MoveToEnclosingBracket,
10166 window: &mut Window,
10167 cx: &mut Context<Self>,
10168 ) {
10169 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10170 s.move_offsets_with(|snapshot, selection| {
10171 let Some(enclosing_bracket_ranges) =
10172 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10173 else {
10174 return;
10175 };
10176
10177 let mut best_length = usize::MAX;
10178 let mut best_inside = false;
10179 let mut best_in_bracket_range = false;
10180 let mut best_destination = None;
10181 for (open, close) in enclosing_bracket_ranges {
10182 let close = close.to_inclusive();
10183 let length = close.end() - open.start;
10184 let inside = selection.start >= open.end && selection.end <= *close.start();
10185 let in_bracket_range = open.to_inclusive().contains(&selection.head())
10186 || close.contains(&selection.head());
10187
10188 // If best is next to a bracket and current isn't, skip
10189 if !in_bracket_range && best_in_bracket_range {
10190 continue;
10191 }
10192
10193 // Prefer smaller lengths unless best is inside and current isn't
10194 if length > best_length && (best_inside || !inside) {
10195 continue;
10196 }
10197
10198 best_length = length;
10199 best_inside = inside;
10200 best_in_bracket_range = in_bracket_range;
10201 best_destination = Some(
10202 if close.contains(&selection.start) && close.contains(&selection.end) {
10203 if inside {
10204 open.end
10205 } else {
10206 open.start
10207 }
10208 } else if inside {
10209 *close.start()
10210 } else {
10211 *close.end()
10212 },
10213 );
10214 }
10215
10216 if let Some(destination) = best_destination {
10217 selection.collapse_to(destination, SelectionGoal::None);
10218 }
10219 })
10220 });
10221 }
10222
10223 pub fn undo_selection(
10224 &mut self,
10225 _: &UndoSelection,
10226 window: &mut Window,
10227 cx: &mut Context<Self>,
10228 ) {
10229 self.end_selection(window, cx);
10230 self.selection_history.mode = SelectionHistoryMode::Undoing;
10231 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10232 self.change_selections(None, window, cx, |s| {
10233 s.select_anchors(entry.selections.to_vec())
10234 });
10235 self.select_next_state = entry.select_next_state;
10236 self.select_prev_state = entry.select_prev_state;
10237 self.add_selections_state = entry.add_selections_state;
10238 self.request_autoscroll(Autoscroll::newest(), cx);
10239 }
10240 self.selection_history.mode = SelectionHistoryMode::Normal;
10241 }
10242
10243 pub fn redo_selection(
10244 &mut self,
10245 _: &RedoSelection,
10246 window: &mut Window,
10247 cx: &mut Context<Self>,
10248 ) {
10249 self.end_selection(window, cx);
10250 self.selection_history.mode = SelectionHistoryMode::Redoing;
10251 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10252 self.change_selections(None, window, cx, |s| {
10253 s.select_anchors(entry.selections.to_vec())
10254 });
10255 self.select_next_state = entry.select_next_state;
10256 self.select_prev_state = entry.select_prev_state;
10257 self.add_selections_state = entry.add_selections_state;
10258 self.request_autoscroll(Autoscroll::newest(), cx);
10259 }
10260 self.selection_history.mode = SelectionHistoryMode::Normal;
10261 }
10262
10263 pub fn expand_excerpts(
10264 &mut self,
10265 action: &ExpandExcerpts,
10266 _: &mut Window,
10267 cx: &mut Context<Self>,
10268 ) {
10269 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10270 }
10271
10272 pub fn expand_excerpts_down(
10273 &mut self,
10274 action: &ExpandExcerptsDown,
10275 _: &mut Window,
10276 cx: &mut Context<Self>,
10277 ) {
10278 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10279 }
10280
10281 pub fn expand_excerpts_up(
10282 &mut self,
10283 action: &ExpandExcerptsUp,
10284 _: &mut Window,
10285 cx: &mut Context<Self>,
10286 ) {
10287 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10288 }
10289
10290 pub fn expand_excerpts_for_direction(
10291 &mut self,
10292 lines: u32,
10293 direction: ExpandExcerptDirection,
10294
10295 cx: &mut Context<Self>,
10296 ) {
10297 let selections = self.selections.disjoint_anchors();
10298
10299 let lines = if lines == 0 {
10300 EditorSettings::get_global(cx).expand_excerpt_lines
10301 } else {
10302 lines
10303 };
10304
10305 self.buffer.update(cx, |buffer, cx| {
10306 let snapshot = buffer.snapshot(cx);
10307 let mut excerpt_ids = selections
10308 .iter()
10309 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10310 .collect::<Vec<_>>();
10311 excerpt_ids.sort();
10312 excerpt_ids.dedup();
10313 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10314 })
10315 }
10316
10317 pub fn expand_excerpt(
10318 &mut self,
10319 excerpt: ExcerptId,
10320 direction: ExpandExcerptDirection,
10321 cx: &mut Context<Self>,
10322 ) {
10323 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10324 self.buffer.update(cx, |buffer, cx| {
10325 buffer.expand_excerpts([excerpt], lines, direction, cx)
10326 })
10327 }
10328
10329 pub fn go_to_singleton_buffer_point(
10330 &mut self,
10331 point: Point,
10332 window: &mut Window,
10333 cx: &mut Context<Self>,
10334 ) {
10335 self.go_to_singleton_buffer_range(point..point, window, cx);
10336 }
10337
10338 pub fn go_to_singleton_buffer_range(
10339 &mut self,
10340 range: Range<Point>,
10341 window: &mut Window,
10342 cx: &mut Context<Self>,
10343 ) {
10344 let multibuffer = self.buffer().read(cx);
10345 let Some(buffer) = multibuffer.as_singleton() else {
10346 return;
10347 };
10348 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10349 return;
10350 };
10351 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10352 return;
10353 };
10354 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10355 s.select_anchor_ranges([start..end])
10356 });
10357 }
10358
10359 fn go_to_diagnostic(
10360 &mut self,
10361 _: &GoToDiagnostic,
10362 window: &mut Window,
10363 cx: &mut Context<Self>,
10364 ) {
10365 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10366 }
10367
10368 fn go_to_prev_diagnostic(
10369 &mut self,
10370 _: &GoToPrevDiagnostic,
10371 window: &mut Window,
10372 cx: &mut Context<Self>,
10373 ) {
10374 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10375 }
10376
10377 pub fn go_to_diagnostic_impl(
10378 &mut self,
10379 direction: Direction,
10380 window: &mut Window,
10381 cx: &mut Context<Self>,
10382 ) {
10383 let buffer = self.buffer.read(cx).snapshot(cx);
10384 let selection = self.selections.newest::<usize>(cx);
10385
10386 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10387 if direction == Direction::Next {
10388 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10389 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10390 return;
10391 };
10392 self.activate_diagnostics(
10393 buffer_id,
10394 popover.local_diagnostic.diagnostic.group_id,
10395 window,
10396 cx,
10397 );
10398 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10399 let primary_range_start = active_diagnostics.primary_range.start;
10400 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10401 let mut new_selection = s.newest_anchor().clone();
10402 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10403 s.select_anchors(vec![new_selection.clone()]);
10404 });
10405 self.refresh_inline_completion(false, true, window, cx);
10406 }
10407 return;
10408 }
10409 }
10410
10411 let active_group_id = self
10412 .active_diagnostics
10413 .as_ref()
10414 .map(|active_group| active_group.group_id);
10415 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10416 active_diagnostics
10417 .primary_range
10418 .to_offset(&buffer)
10419 .to_inclusive()
10420 });
10421 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10422 if active_primary_range.contains(&selection.head()) {
10423 *active_primary_range.start()
10424 } else {
10425 selection.head()
10426 }
10427 } else {
10428 selection.head()
10429 };
10430
10431 let snapshot = self.snapshot(window, cx);
10432 let primary_diagnostics_before = buffer
10433 .diagnostics_in_range::<usize>(0..search_start)
10434 .filter(|entry| entry.diagnostic.is_primary)
10435 .filter(|entry| entry.range.start != entry.range.end)
10436 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10437 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10438 .collect::<Vec<_>>();
10439 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10440 primary_diagnostics_before
10441 .iter()
10442 .position(|entry| entry.diagnostic.group_id == active_group_id)
10443 });
10444
10445 let primary_diagnostics_after = buffer
10446 .diagnostics_in_range::<usize>(search_start..buffer.len())
10447 .filter(|entry| entry.diagnostic.is_primary)
10448 .filter(|entry| entry.range.start != entry.range.end)
10449 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10450 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10451 .collect::<Vec<_>>();
10452 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10453 primary_diagnostics_after
10454 .iter()
10455 .enumerate()
10456 .rev()
10457 .find_map(|(i, entry)| {
10458 if entry.diagnostic.group_id == active_group_id {
10459 Some(i)
10460 } else {
10461 None
10462 }
10463 })
10464 });
10465
10466 let next_primary_diagnostic = match direction {
10467 Direction::Prev => primary_diagnostics_before
10468 .iter()
10469 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10470 .rev()
10471 .next(),
10472 Direction::Next => primary_diagnostics_after
10473 .iter()
10474 .skip(
10475 last_same_group_diagnostic_after
10476 .map(|index| index + 1)
10477 .unwrap_or(0),
10478 )
10479 .next(),
10480 };
10481
10482 // Cycle around to the start of the buffer, potentially moving back to the start of
10483 // the currently active diagnostic.
10484 let cycle_around = || match direction {
10485 Direction::Prev => primary_diagnostics_after
10486 .iter()
10487 .rev()
10488 .chain(primary_diagnostics_before.iter().rev())
10489 .next(),
10490 Direction::Next => primary_diagnostics_before
10491 .iter()
10492 .chain(primary_diagnostics_after.iter())
10493 .next(),
10494 };
10495
10496 if let Some((primary_range, group_id)) = next_primary_diagnostic
10497 .or_else(cycle_around)
10498 .map(|entry| (&entry.range, entry.diagnostic.group_id))
10499 {
10500 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10501 return;
10502 };
10503 self.activate_diagnostics(buffer_id, group_id, window, cx);
10504 if self.active_diagnostics.is_some() {
10505 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10506 s.select(vec![Selection {
10507 id: selection.id,
10508 start: primary_range.start,
10509 end: primary_range.start,
10510 reversed: false,
10511 goal: SelectionGoal::None,
10512 }]);
10513 });
10514 self.refresh_inline_completion(false, true, window, cx);
10515 }
10516 }
10517 }
10518
10519 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10520 let snapshot = self.snapshot(window, cx);
10521 let selection = self.selections.newest::<Point>(cx);
10522 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10523 }
10524
10525 fn go_to_hunk_after_position(
10526 &mut self,
10527 snapshot: &EditorSnapshot,
10528 position: Point,
10529 window: &mut Window,
10530 cx: &mut Context<Editor>,
10531 ) -> Option<MultiBufferDiffHunk> {
10532 let mut hunk = snapshot
10533 .buffer_snapshot
10534 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10535 .find(|hunk| hunk.row_range.start.0 > position.row);
10536 if hunk.is_none() {
10537 hunk = snapshot
10538 .buffer_snapshot
10539 .diff_hunks_in_range(Point::zero()..position)
10540 .find(|hunk| hunk.row_range.end.0 < position.row)
10541 }
10542 if let Some(hunk) = &hunk {
10543 let destination = Point::new(hunk.row_range.start.0, 0);
10544 self.unfold_ranges(&[destination..destination], false, false, cx);
10545 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10546 s.select_ranges(vec![destination..destination]);
10547 });
10548 }
10549
10550 hunk
10551 }
10552
10553 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10554 let snapshot = self.snapshot(window, cx);
10555 let selection = self.selections.newest::<Point>(cx);
10556 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10557 }
10558
10559 fn go_to_hunk_before_position(
10560 &mut self,
10561 snapshot: &EditorSnapshot,
10562 position: Point,
10563 window: &mut Window,
10564 cx: &mut Context<Editor>,
10565 ) -> Option<MultiBufferDiffHunk> {
10566 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10567 if hunk.is_none() {
10568 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10569 }
10570 if let Some(hunk) = &hunk {
10571 let destination = Point::new(hunk.row_range.start.0, 0);
10572 self.unfold_ranges(&[destination..destination], false, false, cx);
10573 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10574 s.select_ranges(vec![destination..destination]);
10575 });
10576 }
10577
10578 hunk
10579 }
10580
10581 pub fn go_to_definition(
10582 &mut self,
10583 _: &GoToDefinition,
10584 window: &mut Window,
10585 cx: &mut Context<Self>,
10586 ) -> Task<Result<Navigated>> {
10587 let definition =
10588 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10589 cx.spawn_in(window, |editor, mut cx| async move {
10590 if definition.await? == Navigated::Yes {
10591 return Ok(Navigated::Yes);
10592 }
10593 match editor.update_in(&mut cx, |editor, window, cx| {
10594 editor.find_all_references(&FindAllReferences, window, cx)
10595 })? {
10596 Some(references) => references.await,
10597 None => Ok(Navigated::No),
10598 }
10599 })
10600 }
10601
10602 pub fn go_to_declaration(
10603 &mut self,
10604 _: &GoToDeclaration,
10605 window: &mut Window,
10606 cx: &mut Context<Self>,
10607 ) -> Task<Result<Navigated>> {
10608 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10609 }
10610
10611 pub fn go_to_declaration_split(
10612 &mut self,
10613 _: &GoToDeclaration,
10614 window: &mut Window,
10615 cx: &mut Context<Self>,
10616 ) -> Task<Result<Navigated>> {
10617 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10618 }
10619
10620 pub fn go_to_implementation(
10621 &mut self,
10622 _: &GoToImplementation,
10623 window: &mut Window,
10624 cx: &mut Context<Self>,
10625 ) -> Task<Result<Navigated>> {
10626 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10627 }
10628
10629 pub fn go_to_implementation_split(
10630 &mut self,
10631 _: &GoToImplementationSplit,
10632 window: &mut Window,
10633 cx: &mut Context<Self>,
10634 ) -> Task<Result<Navigated>> {
10635 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10636 }
10637
10638 pub fn go_to_type_definition(
10639 &mut self,
10640 _: &GoToTypeDefinition,
10641 window: &mut Window,
10642 cx: &mut Context<Self>,
10643 ) -> Task<Result<Navigated>> {
10644 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10645 }
10646
10647 pub fn go_to_definition_split(
10648 &mut self,
10649 _: &GoToDefinitionSplit,
10650 window: &mut Window,
10651 cx: &mut Context<Self>,
10652 ) -> Task<Result<Navigated>> {
10653 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10654 }
10655
10656 pub fn go_to_type_definition_split(
10657 &mut self,
10658 _: &GoToTypeDefinitionSplit,
10659 window: &mut Window,
10660 cx: &mut Context<Self>,
10661 ) -> Task<Result<Navigated>> {
10662 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10663 }
10664
10665 fn go_to_definition_of_kind(
10666 &mut self,
10667 kind: GotoDefinitionKind,
10668 split: bool,
10669 window: &mut Window,
10670 cx: &mut Context<Self>,
10671 ) -> Task<Result<Navigated>> {
10672 let Some(provider) = self.semantics_provider.clone() else {
10673 return Task::ready(Ok(Navigated::No));
10674 };
10675 let head = self.selections.newest::<usize>(cx).head();
10676 let buffer = self.buffer.read(cx);
10677 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10678 text_anchor
10679 } else {
10680 return Task::ready(Ok(Navigated::No));
10681 };
10682
10683 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10684 return Task::ready(Ok(Navigated::No));
10685 };
10686
10687 cx.spawn_in(window, |editor, mut cx| async move {
10688 let definitions = definitions.await?;
10689 let navigated = editor
10690 .update_in(&mut cx, |editor, window, cx| {
10691 editor.navigate_to_hover_links(
10692 Some(kind),
10693 definitions
10694 .into_iter()
10695 .filter(|location| {
10696 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10697 })
10698 .map(HoverLink::Text)
10699 .collect::<Vec<_>>(),
10700 split,
10701 window,
10702 cx,
10703 )
10704 })?
10705 .await?;
10706 anyhow::Ok(navigated)
10707 })
10708 }
10709
10710 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10711 let selection = self.selections.newest_anchor();
10712 let head = selection.head();
10713 let tail = selection.tail();
10714
10715 let Some((buffer, start_position)) =
10716 self.buffer.read(cx).text_anchor_for_position(head, cx)
10717 else {
10718 return;
10719 };
10720
10721 let end_position = if head != tail {
10722 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10723 return;
10724 };
10725 Some(pos)
10726 } else {
10727 None
10728 };
10729
10730 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10731 let url = if let Some(end_pos) = end_position {
10732 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10733 } else {
10734 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10735 };
10736
10737 if let Some(url) = url {
10738 editor.update(&mut cx, |_, cx| {
10739 cx.open_url(&url);
10740 })
10741 } else {
10742 Ok(())
10743 }
10744 });
10745
10746 url_finder.detach();
10747 }
10748
10749 pub fn open_selected_filename(
10750 &mut self,
10751 _: &OpenSelectedFilename,
10752 window: &mut Window,
10753 cx: &mut Context<Self>,
10754 ) {
10755 let Some(workspace) = self.workspace() else {
10756 return;
10757 };
10758
10759 let position = self.selections.newest_anchor().head();
10760
10761 let Some((buffer, buffer_position)) =
10762 self.buffer.read(cx).text_anchor_for_position(position, cx)
10763 else {
10764 return;
10765 };
10766
10767 let project = self.project.clone();
10768
10769 cx.spawn_in(window, |_, mut cx| async move {
10770 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10771
10772 if let Some((_, path)) = result {
10773 workspace
10774 .update_in(&mut cx, |workspace, window, cx| {
10775 workspace.open_resolved_path(path, window, cx)
10776 })?
10777 .await?;
10778 }
10779 anyhow::Ok(())
10780 })
10781 .detach();
10782 }
10783
10784 pub(crate) fn navigate_to_hover_links(
10785 &mut self,
10786 kind: Option<GotoDefinitionKind>,
10787 mut definitions: Vec<HoverLink>,
10788 split: bool,
10789 window: &mut Window,
10790 cx: &mut Context<Editor>,
10791 ) -> Task<Result<Navigated>> {
10792 // If there is one definition, just open it directly
10793 if definitions.len() == 1 {
10794 let definition = definitions.pop().unwrap();
10795
10796 enum TargetTaskResult {
10797 Location(Option<Location>),
10798 AlreadyNavigated,
10799 }
10800
10801 let target_task = match definition {
10802 HoverLink::Text(link) => {
10803 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10804 }
10805 HoverLink::InlayHint(lsp_location, server_id) => {
10806 let computation =
10807 self.compute_target_location(lsp_location, server_id, window, cx);
10808 cx.background_executor().spawn(async move {
10809 let location = computation.await?;
10810 Ok(TargetTaskResult::Location(location))
10811 })
10812 }
10813 HoverLink::Url(url) => {
10814 cx.open_url(&url);
10815 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10816 }
10817 HoverLink::File(path) => {
10818 if let Some(workspace) = self.workspace() {
10819 cx.spawn_in(window, |_, mut cx| async move {
10820 workspace
10821 .update_in(&mut cx, |workspace, window, cx| {
10822 workspace.open_resolved_path(path, window, cx)
10823 })?
10824 .await
10825 .map(|_| TargetTaskResult::AlreadyNavigated)
10826 })
10827 } else {
10828 Task::ready(Ok(TargetTaskResult::Location(None)))
10829 }
10830 }
10831 };
10832 cx.spawn_in(window, |editor, mut cx| async move {
10833 let target = match target_task.await.context("target resolution task")? {
10834 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10835 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10836 TargetTaskResult::Location(Some(target)) => target,
10837 };
10838
10839 editor.update_in(&mut cx, |editor, window, cx| {
10840 let Some(workspace) = editor.workspace() else {
10841 return Navigated::No;
10842 };
10843 let pane = workspace.read(cx).active_pane().clone();
10844
10845 let range = target.range.to_point(target.buffer.read(cx));
10846 let range = editor.range_for_match(&range);
10847 let range = collapse_multiline_range(range);
10848
10849 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10850 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10851 } else {
10852 window.defer(cx, move |window, cx| {
10853 let target_editor: Entity<Self> =
10854 workspace.update(cx, |workspace, cx| {
10855 let pane = if split {
10856 workspace.adjacent_pane(window, cx)
10857 } else {
10858 workspace.active_pane().clone()
10859 };
10860
10861 workspace.open_project_item(
10862 pane,
10863 target.buffer.clone(),
10864 true,
10865 true,
10866 window,
10867 cx,
10868 )
10869 });
10870 target_editor.update(cx, |target_editor, cx| {
10871 // When selecting a definition in a different buffer, disable the nav history
10872 // to avoid creating a history entry at the previous cursor location.
10873 pane.update(cx, |pane, _| pane.disable_history());
10874 target_editor.go_to_singleton_buffer_range(range, window, cx);
10875 pane.update(cx, |pane, _| pane.enable_history());
10876 });
10877 });
10878 }
10879 Navigated::Yes
10880 })
10881 })
10882 } else if !definitions.is_empty() {
10883 cx.spawn_in(window, |editor, mut cx| async move {
10884 let (title, location_tasks, workspace) = editor
10885 .update_in(&mut cx, |editor, window, cx| {
10886 let tab_kind = match kind {
10887 Some(GotoDefinitionKind::Implementation) => "Implementations",
10888 _ => "Definitions",
10889 };
10890 let title = definitions
10891 .iter()
10892 .find_map(|definition| match definition {
10893 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10894 let buffer = origin.buffer.read(cx);
10895 format!(
10896 "{} for {}",
10897 tab_kind,
10898 buffer
10899 .text_for_range(origin.range.clone())
10900 .collect::<String>()
10901 )
10902 }),
10903 HoverLink::InlayHint(_, _) => None,
10904 HoverLink::Url(_) => None,
10905 HoverLink::File(_) => None,
10906 })
10907 .unwrap_or(tab_kind.to_string());
10908 let location_tasks = definitions
10909 .into_iter()
10910 .map(|definition| match definition {
10911 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10912 HoverLink::InlayHint(lsp_location, server_id) => editor
10913 .compute_target_location(lsp_location, server_id, window, cx),
10914 HoverLink::Url(_) => Task::ready(Ok(None)),
10915 HoverLink::File(_) => Task::ready(Ok(None)),
10916 })
10917 .collect::<Vec<_>>();
10918 (title, location_tasks, editor.workspace().clone())
10919 })
10920 .context("location tasks preparation")?;
10921
10922 let locations = future::join_all(location_tasks)
10923 .await
10924 .into_iter()
10925 .filter_map(|location| location.transpose())
10926 .collect::<Result<_>>()
10927 .context("location tasks")?;
10928
10929 let Some(workspace) = workspace else {
10930 return Ok(Navigated::No);
10931 };
10932 let opened = workspace
10933 .update_in(&mut cx, |workspace, window, cx| {
10934 Self::open_locations_in_multibuffer(
10935 workspace,
10936 locations,
10937 title,
10938 split,
10939 MultibufferSelectionMode::First,
10940 window,
10941 cx,
10942 )
10943 })
10944 .ok();
10945
10946 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10947 })
10948 } else {
10949 Task::ready(Ok(Navigated::No))
10950 }
10951 }
10952
10953 fn compute_target_location(
10954 &self,
10955 lsp_location: lsp::Location,
10956 server_id: LanguageServerId,
10957 window: &mut Window,
10958 cx: &mut Context<Self>,
10959 ) -> Task<anyhow::Result<Option<Location>>> {
10960 let Some(project) = self.project.clone() else {
10961 return Task::ready(Ok(None));
10962 };
10963
10964 cx.spawn_in(window, move |editor, mut cx| async move {
10965 let location_task = editor.update(&mut cx, |_, cx| {
10966 project.update(cx, |project, cx| {
10967 let language_server_name = project
10968 .language_server_statuses(cx)
10969 .find(|(id, _)| server_id == *id)
10970 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10971 language_server_name.map(|language_server_name| {
10972 project.open_local_buffer_via_lsp(
10973 lsp_location.uri.clone(),
10974 server_id,
10975 language_server_name,
10976 cx,
10977 )
10978 })
10979 })
10980 })?;
10981 let location = match location_task {
10982 Some(task) => Some({
10983 let target_buffer_handle = task.await.context("open local buffer")?;
10984 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10985 let target_start = target_buffer
10986 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10987 let target_end = target_buffer
10988 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10989 target_buffer.anchor_after(target_start)
10990 ..target_buffer.anchor_before(target_end)
10991 })?;
10992 Location {
10993 buffer: target_buffer_handle,
10994 range,
10995 }
10996 }),
10997 None => None,
10998 };
10999 Ok(location)
11000 })
11001 }
11002
11003 pub fn find_all_references(
11004 &mut self,
11005 _: &FindAllReferences,
11006 window: &mut Window,
11007 cx: &mut Context<Self>,
11008 ) -> Option<Task<Result<Navigated>>> {
11009 let selection = self.selections.newest::<usize>(cx);
11010 let multi_buffer = self.buffer.read(cx);
11011 let head = selection.head();
11012
11013 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11014 let head_anchor = multi_buffer_snapshot.anchor_at(
11015 head,
11016 if head < selection.tail() {
11017 Bias::Right
11018 } else {
11019 Bias::Left
11020 },
11021 );
11022
11023 match self
11024 .find_all_references_task_sources
11025 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11026 {
11027 Ok(_) => {
11028 log::info!(
11029 "Ignoring repeated FindAllReferences invocation with the position of already running task"
11030 );
11031 return None;
11032 }
11033 Err(i) => {
11034 self.find_all_references_task_sources.insert(i, head_anchor);
11035 }
11036 }
11037
11038 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11039 let workspace = self.workspace()?;
11040 let project = workspace.read(cx).project().clone();
11041 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11042 Some(cx.spawn_in(window, |editor, mut cx| async move {
11043 let _cleanup = defer({
11044 let mut cx = cx.clone();
11045 move || {
11046 let _ = editor.update(&mut cx, |editor, _| {
11047 if let Ok(i) =
11048 editor
11049 .find_all_references_task_sources
11050 .binary_search_by(|anchor| {
11051 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11052 })
11053 {
11054 editor.find_all_references_task_sources.remove(i);
11055 }
11056 });
11057 }
11058 });
11059
11060 let locations = references.await?;
11061 if locations.is_empty() {
11062 return anyhow::Ok(Navigated::No);
11063 }
11064
11065 workspace.update_in(&mut cx, |workspace, window, cx| {
11066 let title = locations
11067 .first()
11068 .as_ref()
11069 .map(|location| {
11070 let buffer = location.buffer.read(cx);
11071 format!(
11072 "References to `{}`",
11073 buffer
11074 .text_for_range(location.range.clone())
11075 .collect::<String>()
11076 )
11077 })
11078 .unwrap();
11079 Self::open_locations_in_multibuffer(
11080 workspace,
11081 locations,
11082 title,
11083 false,
11084 MultibufferSelectionMode::First,
11085 window,
11086 cx,
11087 );
11088 Navigated::Yes
11089 })
11090 }))
11091 }
11092
11093 /// Opens a multibuffer with the given project locations in it
11094 pub fn open_locations_in_multibuffer(
11095 workspace: &mut Workspace,
11096 mut locations: Vec<Location>,
11097 title: String,
11098 split: bool,
11099 multibuffer_selection_mode: MultibufferSelectionMode,
11100 window: &mut Window,
11101 cx: &mut Context<Workspace>,
11102 ) {
11103 // If there are multiple definitions, open them in a multibuffer
11104 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11105 let mut locations = locations.into_iter().peekable();
11106 let mut ranges = Vec::new();
11107 let capability = workspace.project().read(cx).capability();
11108
11109 let excerpt_buffer = cx.new(|cx| {
11110 let mut multibuffer = MultiBuffer::new(capability);
11111 while let Some(location) = locations.next() {
11112 let buffer = location.buffer.read(cx);
11113 let mut ranges_for_buffer = Vec::new();
11114 let range = location.range.to_offset(buffer);
11115 ranges_for_buffer.push(range.clone());
11116
11117 while let Some(next_location) = locations.peek() {
11118 if next_location.buffer == location.buffer {
11119 ranges_for_buffer.push(next_location.range.to_offset(buffer));
11120 locations.next();
11121 } else {
11122 break;
11123 }
11124 }
11125
11126 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11127 ranges.extend(multibuffer.push_excerpts_with_context_lines(
11128 location.buffer.clone(),
11129 ranges_for_buffer,
11130 DEFAULT_MULTIBUFFER_CONTEXT,
11131 cx,
11132 ))
11133 }
11134
11135 multibuffer.with_title(title)
11136 });
11137
11138 let editor = cx.new(|cx| {
11139 Editor::for_multibuffer(
11140 excerpt_buffer,
11141 Some(workspace.project().clone()),
11142 true,
11143 window,
11144 cx,
11145 )
11146 });
11147 editor.update(cx, |editor, cx| {
11148 match multibuffer_selection_mode {
11149 MultibufferSelectionMode::First => {
11150 if let Some(first_range) = ranges.first() {
11151 editor.change_selections(None, window, cx, |selections| {
11152 selections.clear_disjoint();
11153 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11154 });
11155 }
11156 editor.highlight_background::<Self>(
11157 &ranges,
11158 |theme| theme.editor_highlighted_line_background,
11159 cx,
11160 );
11161 }
11162 MultibufferSelectionMode::All => {
11163 editor.change_selections(None, window, cx, |selections| {
11164 selections.clear_disjoint();
11165 selections.select_anchor_ranges(ranges);
11166 });
11167 }
11168 }
11169 editor.register_buffers_with_language_servers(cx);
11170 });
11171
11172 let item = Box::new(editor);
11173 let item_id = item.item_id();
11174
11175 if split {
11176 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11177 } else {
11178 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11179 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11180 pane.close_current_preview_item(window, cx)
11181 } else {
11182 None
11183 }
11184 });
11185 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11186 }
11187 workspace.active_pane().update(cx, |pane, cx| {
11188 pane.set_preview_item_id(Some(item_id), cx);
11189 });
11190 }
11191
11192 pub fn rename(
11193 &mut self,
11194 _: &Rename,
11195 window: &mut Window,
11196 cx: &mut Context<Self>,
11197 ) -> Option<Task<Result<()>>> {
11198 use language::ToOffset as _;
11199
11200 let provider = self.semantics_provider.clone()?;
11201 let selection = self.selections.newest_anchor().clone();
11202 let (cursor_buffer, cursor_buffer_position) = self
11203 .buffer
11204 .read(cx)
11205 .text_anchor_for_position(selection.head(), cx)?;
11206 let (tail_buffer, cursor_buffer_position_end) = self
11207 .buffer
11208 .read(cx)
11209 .text_anchor_for_position(selection.tail(), cx)?;
11210 if tail_buffer != cursor_buffer {
11211 return None;
11212 }
11213
11214 let snapshot = cursor_buffer.read(cx).snapshot();
11215 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11216 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11217 let prepare_rename = provider
11218 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11219 .unwrap_or_else(|| Task::ready(Ok(None)));
11220 drop(snapshot);
11221
11222 Some(cx.spawn_in(window, |this, mut cx| async move {
11223 let rename_range = if let Some(range) = prepare_rename.await? {
11224 Some(range)
11225 } else {
11226 this.update(&mut cx, |this, cx| {
11227 let buffer = this.buffer.read(cx).snapshot(cx);
11228 let mut buffer_highlights = this
11229 .document_highlights_for_position(selection.head(), &buffer)
11230 .filter(|highlight| {
11231 highlight.start.excerpt_id == selection.head().excerpt_id
11232 && highlight.end.excerpt_id == selection.head().excerpt_id
11233 });
11234 buffer_highlights
11235 .next()
11236 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11237 })?
11238 };
11239 if let Some(rename_range) = rename_range {
11240 this.update_in(&mut cx, |this, window, cx| {
11241 let snapshot = cursor_buffer.read(cx).snapshot();
11242 let rename_buffer_range = rename_range.to_offset(&snapshot);
11243 let cursor_offset_in_rename_range =
11244 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11245 let cursor_offset_in_rename_range_end =
11246 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11247
11248 this.take_rename(false, window, cx);
11249 let buffer = this.buffer.read(cx).read(cx);
11250 let cursor_offset = selection.head().to_offset(&buffer);
11251 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11252 let rename_end = rename_start + rename_buffer_range.len();
11253 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11254 let mut old_highlight_id = None;
11255 let old_name: Arc<str> = buffer
11256 .chunks(rename_start..rename_end, true)
11257 .map(|chunk| {
11258 if old_highlight_id.is_none() {
11259 old_highlight_id = chunk.syntax_highlight_id;
11260 }
11261 chunk.text
11262 })
11263 .collect::<String>()
11264 .into();
11265
11266 drop(buffer);
11267
11268 // Position the selection in the rename editor so that it matches the current selection.
11269 this.show_local_selections = false;
11270 let rename_editor = cx.new(|cx| {
11271 let mut editor = Editor::single_line(window, cx);
11272 editor.buffer.update(cx, |buffer, cx| {
11273 buffer.edit([(0..0, old_name.clone())], None, cx)
11274 });
11275 let rename_selection_range = match cursor_offset_in_rename_range
11276 .cmp(&cursor_offset_in_rename_range_end)
11277 {
11278 Ordering::Equal => {
11279 editor.select_all(&SelectAll, window, cx);
11280 return editor;
11281 }
11282 Ordering::Less => {
11283 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11284 }
11285 Ordering::Greater => {
11286 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11287 }
11288 };
11289 if rename_selection_range.end > old_name.len() {
11290 editor.select_all(&SelectAll, window, cx);
11291 } else {
11292 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11293 s.select_ranges([rename_selection_range]);
11294 });
11295 }
11296 editor
11297 });
11298 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11299 if e == &EditorEvent::Focused {
11300 cx.emit(EditorEvent::FocusedIn)
11301 }
11302 })
11303 .detach();
11304
11305 let write_highlights =
11306 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11307 let read_highlights =
11308 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11309 let ranges = write_highlights
11310 .iter()
11311 .flat_map(|(_, ranges)| ranges.iter())
11312 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11313 .cloned()
11314 .collect();
11315
11316 this.highlight_text::<Rename>(
11317 ranges,
11318 HighlightStyle {
11319 fade_out: Some(0.6),
11320 ..Default::default()
11321 },
11322 cx,
11323 );
11324 let rename_focus_handle = rename_editor.focus_handle(cx);
11325 window.focus(&rename_focus_handle);
11326 let block_id = this.insert_blocks(
11327 [BlockProperties {
11328 style: BlockStyle::Flex,
11329 placement: BlockPlacement::Below(range.start),
11330 height: 1,
11331 render: Arc::new({
11332 let rename_editor = rename_editor.clone();
11333 move |cx: &mut BlockContext| {
11334 let mut text_style = cx.editor_style.text.clone();
11335 if let Some(highlight_style) = old_highlight_id
11336 .and_then(|h| h.style(&cx.editor_style.syntax))
11337 {
11338 text_style = text_style.highlight(highlight_style);
11339 }
11340 div()
11341 .block_mouse_down()
11342 .pl(cx.anchor_x)
11343 .child(EditorElement::new(
11344 &rename_editor,
11345 EditorStyle {
11346 background: cx.theme().system().transparent,
11347 local_player: cx.editor_style.local_player,
11348 text: text_style,
11349 scrollbar_width: cx.editor_style.scrollbar_width,
11350 syntax: cx.editor_style.syntax.clone(),
11351 status: cx.editor_style.status.clone(),
11352 inlay_hints_style: HighlightStyle {
11353 font_weight: Some(FontWeight::BOLD),
11354 ..make_inlay_hints_style(cx.app)
11355 },
11356 inline_completion_styles: make_suggestion_styles(
11357 cx.app,
11358 ),
11359 ..EditorStyle::default()
11360 },
11361 ))
11362 .into_any_element()
11363 }
11364 }),
11365 priority: 0,
11366 }],
11367 Some(Autoscroll::fit()),
11368 cx,
11369 )[0];
11370 this.pending_rename = Some(RenameState {
11371 range,
11372 old_name,
11373 editor: rename_editor,
11374 block_id,
11375 });
11376 })?;
11377 }
11378
11379 Ok(())
11380 }))
11381 }
11382
11383 pub fn confirm_rename(
11384 &mut self,
11385 _: &ConfirmRename,
11386 window: &mut Window,
11387 cx: &mut Context<Self>,
11388 ) -> Option<Task<Result<()>>> {
11389 let rename = self.take_rename(false, window, cx)?;
11390 let workspace = self.workspace()?.downgrade();
11391 let (buffer, start) = self
11392 .buffer
11393 .read(cx)
11394 .text_anchor_for_position(rename.range.start, cx)?;
11395 let (end_buffer, _) = self
11396 .buffer
11397 .read(cx)
11398 .text_anchor_for_position(rename.range.end, cx)?;
11399 if buffer != end_buffer {
11400 return None;
11401 }
11402
11403 let old_name = rename.old_name;
11404 let new_name = rename.editor.read(cx).text(cx);
11405
11406 let rename = self.semantics_provider.as_ref()?.perform_rename(
11407 &buffer,
11408 start,
11409 new_name.clone(),
11410 cx,
11411 )?;
11412
11413 Some(cx.spawn_in(window, |editor, mut cx| async move {
11414 let project_transaction = rename.await?;
11415 Self::open_project_transaction(
11416 &editor,
11417 workspace,
11418 project_transaction,
11419 format!("Rename: {} → {}", old_name, new_name),
11420 cx.clone(),
11421 )
11422 .await?;
11423
11424 editor.update(&mut cx, |editor, cx| {
11425 editor.refresh_document_highlights(cx);
11426 })?;
11427 Ok(())
11428 }))
11429 }
11430
11431 fn take_rename(
11432 &mut self,
11433 moving_cursor: bool,
11434 window: &mut Window,
11435 cx: &mut Context<Self>,
11436 ) -> Option<RenameState> {
11437 let rename = self.pending_rename.take()?;
11438 if rename.editor.focus_handle(cx).is_focused(window) {
11439 window.focus(&self.focus_handle);
11440 }
11441
11442 self.remove_blocks(
11443 [rename.block_id].into_iter().collect(),
11444 Some(Autoscroll::fit()),
11445 cx,
11446 );
11447 self.clear_highlights::<Rename>(cx);
11448 self.show_local_selections = true;
11449
11450 if moving_cursor {
11451 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11452 editor.selections.newest::<usize>(cx).head()
11453 });
11454
11455 // Update the selection to match the position of the selection inside
11456 // the rename editor.
11457 let snapshot = self.buffer.read(cx).read(cx);
11458 let rename_range = rename.range.to_offset(&snapshot);
11459 let cursor_in_editor = snapshot
11460 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11461 .min(rename_range.end);
11462 drop(snapshot);
11463
11464 self.change_selections(None, window, cx, |s| {
11465 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11466 });
11467 } else {
11468 self.refresh_document_highlights(cx);
11469 }
11470
11471 Some(rename)
11472 }
11473
11474 pub fn pending_rename(&self) -> Option<&RenameState> {
11475 self.pending_rename.as_ref()
11476 }
11477
11478 fn format(
11479 &mut self,
11480 _: &Format,
11481 window: &mut Window,
11482 cx: &mut Context<Self>,
11483 ) -> Option<Task<Result<()>>> {
11484 let project = match &self.project {
11485 Some(project) => project.clone(),
11486 None => return None,
11487 };
11488
11489 Some(self.perform_format(
11490 project,
11491 FormatTrigger::Manual,
11492 FormatTarget::Buffers,
11493 window,
11494 cx,
11495 ))
11496 }
11497
11498 fn format_selections(
11499 &mut self,
11500 _: &FormatSelections,
11501 window: &mut Window,
11502 cx: &mut Context<Self>,
11503 ) -> Option<Task<Result<()>>> {
11504 let project = match &self.project {
11505 Some(project) => project.clone(),
11506 None => return None,
11507 };
11508
11509 let ranges = self
11510 .selections
11511 .all_adjusted(cx)
11512 .into_iter()
11513 .map(|selection| selection.range())
11514 .collect_vec();
11515
11516 Some(self.perform_format(
11517 project,
11518 FormatTrigger::Manual,
11519 FormatTarget::Ranges(ranges),
11520 window,
11521 cx,
11522 ))
11523 }
11524
11525 fn perform_format(
11526 &mut self,
11527 project: Entity<Project>,
11528 trigger: FormatTrigger,
11529 target: FormatTarget,
11530 window: &mut Window,
11531 cx: &mut Context<Self>,
11532 ) -> Task<Result<()>> {
11533 let buffer = self.buffer.clone();
11534 let (buffers, target) = match target {
11535 FormatTarget::Buffers => {
11536 let mut buffers = buffer.read(cx).all_buffers();
11537 if trigger == FormatTrigger::Save {
11538 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11539 }
11540 (buffers, LspFormatTarget::Buffers)
11541 }
11542 FormatTarget::Ranges(selection_ranges) => {
11543 let multi_buffer = buffer.read(cx);
11544 let snapshot = multi_buffer.read(cx);
11545 let mut buffers = HashSet::default();
11546 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11547 BTreeMap::new();
11548 for selection_range in selection_ranges {
11549 for (buffer, buffer_range, _) in
11550 snapshot.range_to_buffer_ranges(selection_range)
11551 {
11552 let buffer_id = buffer.remote_id();
11553 let start = buffer.anchor_before(buffer_range.start);
11554 let end = buffer.anchor_after(buffer_range.end);
11555 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11556 buffer_id_to_ranges
11557 .entry(buffer_id)
11558 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11559 .or_insert_with(|| vec![start..end]);
11560 }
11561 }
11562 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11563 }
11564 };
11565
11566 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11567 let format = project.update(cx, |project, cx| {
11568 project.format(buffers, target, true, trigger, cx)
11569 });
11570
11571 cx.spawn_in(window, |_, mut cx| async move {
11572 let transaction = futures::select_biased! {
11573 () = timeout => {
11574 log::warn!("timed out waiting for formatting");
11575 None
11576 }
11577 transaction = format.log_err().fuse() => transaction,
11578 };
11579
11580 buffer
11581 .update(&mut cx, |buffer, cx| {
11582 if let Some(transaction) = transaction {
11583 if !buffer.is_singleton() {
11584 buffer.push_transaction(&transaction.0, cx);
11585 }
11586 }
11587
11588 cx.notify();
11589 })
11590 .ok();
11591
11592 Ok(())
11593 })
11594 }
11595
11596 fn restart_language_server(
11597 &mut self,
11598 _: &RestartLanguageServer,
11599 _: &mut Window,
11600 cx: &mut Context<Self>,
11601 ) {
11602 if let Some(project) = self.project.clone() {
11603 self.buffer.update(cx, |multi_buffer, cx| {
11604 project.update(cx, |project, cx| {
11605 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11606 });
11607 })
11608 }
11609 }
11610
11611 fn cancel_language_server_work(
11612 workspace: &mut Workspace,
11613 _: &actions::CancelLanguageServerWork,
11614 _: &mut Window,
11615 cx: &mut Context<Workspace>,
11616 ) {
11617 let project = workspace.project();
11618 let buffers = workspace
11619 .active_item(cx)
11620 .and_then(|item| item.act_as::<Editor>(cx))
11621 .map_or(HashSet::default(), |editor| {
11622 editor.read(cx).buffer.read(cx).all_buffers()
11623 });
11624 project.update(cx, |project, cx| {
11625 project.cancel_language_server_work_for_buffers(buffers, cx);
11626 });
11627 }
11628
11629 fn show_character_palette(
11630 &mut self,
11631 _: &ShowCharacterPalette,
11632 window: &mut Window,
11633 _: &mut Context<Self>,
11634 ) {
11635 window.show_character_palette();
11636 }
11637
11638 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11639 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11640 let buffer = self.buffer.read(cx).snapshot(cx);
11641 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11642 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11643 let is_valid = buffer
11644 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11645 .any(|entry| {
11646 entry.diagnostic.is_primary
11647 && !entry.range.is_empty()
11648 && entry.range.start == primary_range_start
11649 && entry.diagnostic.message == active_diagnostics.primary_message
11650 });
11651
11652 if is_valid != active_diagnostics.is_valid {
11653 active_diagnostics.is_valid = is_valid;
11654 let mut new_styles = HashMap::default();
11655 for (block_id, diagnostic) in &active_diagnostics.blocks {
11656 new_styles.insert(
11657 *block_id,
11658 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11659 );
11660 }
11661 self.display_map.update(cx, |display_map, _cx| {
11662 display_map.replace_blocks(new_styles)
11663 });
11664 }
11665 }
11666 }
11667
11668 fn activate_diagnostics(
11669 &mut self,
11670 buffer_id: BufferId,
11671 group_id: usize,
11672 window: &mut Window,
11673 cx: &mut Context<Self>,
11674 ) {
11675 self.dismiss_diagnostics(cx);
11676 let snapshot = self.snapshot(window, cx);
11677 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11678 let buffer = self.buffer.read(cx).snapshot(cx);
11679
11680 let mut primary_range = None;
11681 let mut primary_message = None;
11682 let diagnostic_group = buffer
11683 .diagnostic_group(buffer_id, group_id)
11684 .filter_map(|entry| {
11685 let start = entry.range.start;
11686 let end = entry.range.end;
11687 if snapshot.is_line_folded(MultiBufferRow(start.row))
11688 && (start.row == end.row
11689 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11690 {
11691 return None;
11692 }
11693 if entry.diagnostic.is_primary {
11694 primary_range = Some(entry.range.clone());
11695 primary_message = Some(entry.diagnostic.message.clone());
11696 }
11697 Some(entry)
11698 })
11699 .collect::<Vec<_>>();
11700 let primary_range = primary_range?;
11701 let primary_message = primary_message?;
11702
11703 let blocks = display_map
11704 .insert_blocks(
11705 diagnostic_group.iter().map(|entry| {
11706 let diagnostic = entry.diagnostic.clone();
11707 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11708 BlockProperties {
11709 style: BlockStyle::Fixed,
11710 placement: BlockPlacement::Below(
11711 buffer.anchor_after(entry.range.start),
11712 ),
11713 height: message_height,
11714 render: diagnostic_block_renderer(diagnostic, None, true, true),
11715 priority: 0,
11716 }
11717 }),
11718 cx,
11719 )
11720 .into_iter()
11721 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11722 .collect();
11723
11724 Some(ActiveDiagnosticGroup {
11725 primary_range: buffer.anchor_before(primary_range.start)
11726 ..buffer.anchor_after(primary_range.end),
11727 primary_message,
11728 group_id,
11729 blocks,
11730 is_valid: true,
11731 })
11732 });
11733 }
11734
11735 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11736 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11737 self.display_map.update(cx, |display_map, cx| {
11738 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11739 });
11740 cx.notify();
11741 }
11742 }
11743
11744 pub fn set_selections_from_remote(
11745 &mut self,
11746 selections: Vec<Selection<Anchor>>,
11747 pending_selection: Option<Selection<Anchor>>,
11748 window: &mut Window,
11749 cx: &mut Context<Self>,
11750 ) {
11751 let old_cursor_position = self.selections.newest_anchor().head();
11752 self.selections.change_with(cx, |s| {
11753 s.select_anchors(selections);
11754 if let Some(pending_selection) = pending_selection {
11755 s.set_pending(pending_selection, SelectMode::Character);
11756 } else {
11757 s.clear_pending();
11758 }
11759 });
11760 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11761 }
11762
11763 fn push_to_selection_history(&mut self) {
11764 self.selection_history.push(SelectionHistoryEntry {
11765 selections: self.selections.disjoint_anchors(),
11766 select_next_state: self.select_next_state.clone(),
11767 select_prev_state: self.select_prev_state.clone(),
11768 add_selections_state: self.add_selections_state.clone(),
11769 });
11770 }
11771
11772 pub fn transact(
11773 &mut self,
11774 window: &mut Window,
11775 cx: &mut Context<Self>,
11776 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11777 ) -> Option<TransactionId> {
11778 self.start_transaction_at(Instant::now(), window, cx);
11779 update(self, window, cx);
11780 self.end_transaction_at(Instant::now(), cx)
11781 }
11782
11783 pub fn start_transaction_at(
11784 &mut self,
11785 now: Instant,
11786 window: &mut Window,
11787 cx: &mut Context<Self>,
11788 ) {
11789 self.end_selection(window, cx);
11790 if let Some(tx_id) = self
11791 .buffer
11792 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11793 {
11794 self.selection_history
11795 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11796 cx.emit(EditorEvent::TransactionBegun {
11797 transaction_id: tx_id,
11798 })
11799 }
11800 }
11801
11802 pub fn end_transaction_at(
11803 &mut self,
11804 now: Instant,
11805 cx: &mut Context<Self>,
11806 ) -> Option<TransactionId> {
11807 if let Some(transaction_id) = self
11808 .buffer
11809 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11810 {
11811 if let Some((_, end_selections)) =
11812 self.selection_history.transaction_mut(transaction_id)
11813 {
11814 *end_selections = Some(self.selections.disjoint_anchors());
11815 } else {
11816 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11817 }
11818
11819 cx.emit(EditorEvent::Edited { transaction_id });
11820 Some(transaction_id)
11821 } else {
11822 None
11823 }
11824 }
11825
11826 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11827 if self.selection_mark_mode {
11828 self.change_selections(None, window, cx, |s| {
11829 s.move_with(|_, sel| {
11830 sel.collapse_to(sel.head(), SelectionGoal::None);
11831 });
11832 })
11833 }
11834 self.selection_mark_mode = true;
11835 cx.notify();
11836 }
11837
11838 pub fn swap_selection_ends(
11839 &mut self,
11840 _: &actions::SwapSelectionEnds,
11841 window: &mut Window,
11842 cx: &mut Context<Self>,
11843 ) {
11844 self.change_selections(None, window, cx, |s| {
11845 s.move_with(|_, sel| {
11846 if sel.start != sel.end {
11847 sel.reversed = !sel.reversed
11848 }
11849 });
11850 });
11851 self.request_autoscroll(Autoscroll::newest(), cx);
11852 cx.notify();
11853 }
11854
11855 pub fn toggle_fold(
11856 &mut self,
11857 _: &actions::ToggleFold,
11858 window: &mut Window,
11859 cx: &mut Context<Self>,
11860 ) {
11861 if self.is_singleton(cx) {
11862 let selection = self.selections.newest::<Point>(cx);
11863
11864 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11865 let range = if selection.is_empty() {
11866 let point = selection.head().to_display_point(&display_map);
11867 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11868 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11869 .to_point(&display_map);
11870 start..end
11871 } else {
11872 selection.range()
11873 };
11874 if display_map.folds_in_range(range).next().is_some() {
11875 self.unfold_lines(&Default::default(), window, cx)
11876 } else {
11877 self.fold(&Default::default(), window, cx)
11878 }
11879 } else {
11880 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11881 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11882 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11883 .map(|(snapshot, _, _)| snapshot.remote_id())
11884 .collect();
11885
11886 for buffer_id in buffer_ids {
11887 if self.is_buffer_folded(buffer_id, cx) {
11888 self.unfold_buffer(buffer_id, cx);
11889 } else {
11890 self.fold_buffer(buffer_id, cx);
11891 }
11892 }
11893 }
11894 }
11895
11896 pub fn toggle_fold_recursive(
11897 &mut self,
11898 _: &actions::ToggleFoldRecursive,
11899 window: &mut Window,
11900 cx: &mut Context<Self>,
11901 ) {
11902 let selection = self.selections.newest::<Point>(cx);
11903
11904 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11905 let range = if selection.is_empty() {
11906 let point = selection.head().to_display_point(&display_map);
11907 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11908 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11909 .to_point(&display_map);
11910 start..end
11911 } else {
11912 selection.range()
11913 };
11914 if display_map.folds_in_range(range).next().is_some() {
11915 self.unfold_recursive(&Default::default(), window, cx)
11916 } else {
11917 self.fold_recursive(&Default::default(), window, cx)
11918 }
11919 }
11920
11921 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11922 if self.is_singleton(cx) {
11923 let mut to_fold = Vec::new();
11924 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11925 let selections = self.selections.all_adjusted(cx);
11926
11927 for selection in selections {
11928 let range = selection.range().sorted();
11929 let buffer_start_row = range.start.row;
11930
11931 if range.start.row != range.end.row {
11932 let mut found = false;
11933 let mut row = range.start.row;
11934 while row <= range.end.row {
11935 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11936 {
11937 found = true;
11938 row = crease.range().end.row + 1;
11939 to_fold.push(crease);
11940 } else {
11941 row += 1
11942 }
11943 }
11944 if found {
11945 continue;
11946 }
11947 }
11948
11949 for row in (0..=range.start.row).rev() {
11950 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11951 if crease.range().end.row >= buffer_start_row {
11952 to_fold.push(crease);
11953 if row <= range.start.row {
11954 break;
11955 }
11956 }
11957 }
11958 }
11959 }
11960
11961 self.fold_creases(to_fold, true, window, cx);
11962 } else {
11963 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11964
11965 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11966 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11967 .map(|(snapshot, _, _)| snapshot.remote_id())
11968 .collect();
11969 for buffer_id in buffer_ids {
11970 self.fold_buffer(buffer_id, cx);
11971 }
11972 }
11973 }
11974
11975 fn fold_at_level(
11976 &mut self,
11977 fold_at: &FoldAtLevel,
11978 window: &mut Window,
11979 cx: &mut Context<Self>,
11980 ) {
11981 if !self.buffer.read(cx).is_singleton() {
11982 return;
11983 }
11984
11985 let fold_at_level = fold_at.0;
11986 let snapshot = self.buffer.read(cx).snapshot(cx);
11987 let mut to_fold = Vec::new();
11988 let mut stack = vec![(0, snapshot.max_row().0, 1)];
11989
11990 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11991 while start_row < end_row {
11992 match self
11993 .snapshot(window, cx)
11994 .crease_for_buffer_row(MultiBufferRow(start_row))
11995 {
11996 Some(crease) => {
11997 let nested_start_row = crease.range().start.row + 1;
11998 let nested_end_row = crease.range().end.row;
11999
12000 if current_level < fold_at_level {
12001 stack.push((nested_start_row, nested_end_row, current_level + 1));
12002 } else if current_level == fold_at_level {
12003 to_fold.push(crease);
12004 }
12005
12006 start_row = nested_end_row + 1;
12007 }
12008 None => start_row += 1,
12009 }
12010 }
12011 }
12012
12013 self.fold_creases(to_fold, true, window, cx);
12014 }
12015
12016 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12017 if self.buffer.read(cx).is_singleton() {
12018 let mut fold_ranges = Vec::new();
12019 let snapshot = self.buffer.read(cx).snapshot(cx);
12020
12021 for row in 0..snapshot.max_row().0 {
12022 if let Some(foldable_range) = self
12023 .snapshot(window, cx)
12024 .crease_for_buffer_row(MultiBufferRow(row))
12025 {
12026 fold_ranges.push(foldable_range);
12027 }
12028 }
12029
12030 self.fold_creases(fold_ranges, true, window, cx);
12031 } else {
12032 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12033 editor
12034 .update_in(&mut cx, |editor, _, cx| {
12035 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12036 editor.fold_buffer(buffer_id, cx);
12037 }
12038 })
12039 .ok();
12040 });
12041 }
12042 }
12043
12044 pub fn fold_function_bodies(
12045 &mut self,
12046 _: &actions::FoldFunctionBodies,
12047 window: &mut Window,
12048 cx: &mut Context<Self>,
12049 ) {
12050 let snapshot = self.buffer.read(cx).snapshot(cx);
12051
12052 let ranges = snapshot
12053 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12054 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12055 .collect::<Vec<_>>();
12056
12057 let creases = ranges
12058 .into_iter()
12059 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12060 .collect();
12061
12062 self.fold_creases(creases, true, window, cx);
12063 }
12064
12065 pub fn fold_recursive(
12066 &mut self,
12067 _: &actions::FoldRecursive,
12068 window: &mut Window,
12069 cx: &mut Context<Self>,
12070 ) {
12071 let mut to_fold = Vec::new();
12072 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12073 let selections = self.selections.all_adjusted(cx);
12074
12075 for selection in selections {
12076 let range = selection.range().sorted();
12077 let buffer_start_row = range.start.row;
12078
12079 if range.start.row != range.end.row {
12080 let mut found = false;
12081 for row in range.start.row..=range.end.row {
12082 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12083 found = true;
12084 to_fold.push(crease);
12085 }
12086 }
12087 if found {
12088 continue;
12089 }
12090 }
12091
12092 for row in (0..=range.start.row).rev() {
12093 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12094 if crease.range().end.row >= buffer_start_row {
12095 to_fold.push(crease);
12096 } else {
12097 break;
12098 }
12099 }
12100 }
12101 }
12102
12103 self.fold_creases(to_fold, true, window, cx);
12104 }
12105
12106 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12107 let buffer_row = fold_at.buffer_row;
12108 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12109
12110 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12111 let autoscroll = self
12112 .selections
12113 .all::<Point>(cx)
12114 .iter()
12115 .any(|selection| crease.range().overlaps(&selection.range()));
12116
12117 self.fold_creases(vec![crease], autoscroll, window, cx);
12118 }
12119 }
12120
12121 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12122 if self.is_singleton(cx) {
12123 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12124 let buffer = &display_map.buffer_snapshot;
12125 let selections = self.selections.all::<Point>(cx);
12126 let ranges = selections
12127 .iter()
12128 .map(|s| {
12129 let range = s.display_range(&display_map).sorted();
12130 let mut start = range.start.to_point(&display_map);
12131 let mut end = range.end.to_point(&display_map);
12132 start.column = 0;
12133 end.column = buffer.line_len(MultiBufferRow(end.row));
12134 start..end
12135 })
12136 .collect::<Vec<_>>();
12137
12138 self.unfold_ranges(&ranges, true, true, cx);
12139 } else {
12140 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12141 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12142 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12143 .map(|(snapshot, _, _)| snapshot.remote_id())
12144 .collect();
12145 for buffer_id in buffer_ids {
12146 self.unfold_buffer(buffer_id, cx);
12147 }
12148 }
12149 }
12150
12151 pub fn unfold_recursive(
12152 &mut self,
12153 _: &UnfoldRecursive,
12154 _window: &mut Window,
12155 cx: &mut Context<Self>,
12156 ) {
12157 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12158 let selections = self.selections.all::<Point>(cx);
12159 let ranges = selections
12160 .iter()
12161 .map(|s| {
12162 let mut range = s.display_range(&display_map).sorted();
12163 *range.start.column_mut() = 0;
12164 *range.end.column_mut() = display_map.line_len(range.end.row());
12165 let start = range.start.to_point(&display_map);
12166 let end = range.end.to_point(&display_map);
12167 start..end
12168 })
12169 .collect::<Vec<_>>();
12170
12171 self.unfold_ranges(&ranges, true, true, cx);
12172 }
12173
12174 pub fn unfold_at(
12175 &mut self,
12176 unfold_at: &UnfoldAt,
12177 _window: &mut Window,
12178 cx: &mut Context<Self>,
12179 ) {
12180 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12181
12182 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12183 ..Point::new(
12184 unfold_at.buffer_row.0,
12185 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12186 );
12187
12188 let autoscroll = self
12189 .selections
12190 .all::<Point>(cx)
12191 .iter()
12192 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12193
12194 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12195 }
12196
12197 pub fn unfold_all(
12198 &mut self,
12199 _: &actions::UnfoldAll,
12200 _window: &mut Window,
12201 cx: &mut Context<Self>,
12202 ) {
12203 if self.buffer.read(cx).is_singleton() {
12204 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12205 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12206 } else {
12207 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12208 editor
12209 .update(&mut cx, |editor, cx| {
12210 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12211 editor.unfold_buffer(buffer_id, cx);
12212 }
12213 })
12214 .ok();
12215 });
12216 }
12217 }
12218
12219 pub fn fold_selected_ranges(
12220 &mut self,
12221 _: &FoldSelectedRanges,
12222 window: &mut Window,
12223 cx: &mut Context<Self>,
12224 ) {
12225 let selections = self.selections.all::<Point>(cx);
12226 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12227 let line_mode = self.selections.line_mode;
12228 let ranges = selections
12229 .into_iter()
12230 .map(|s| {
12231 if line_mode {
12232 let start = Point::new(s.start.row, 0);
12233 let end = Point::new(
12234 s.end.row,
12235 display_map
12236 .buffer_snapshot
12237 .line_len(MultiBufferRow(s.end.row)),
12238 );
12239 Crease::simple(start..end, display_map.fold_placeholder.clone())
12240 } else {
12241 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12242 }
12243 })
12244 .collect::<Vec<_>>();
12245 self.fold_creases(ranges, true, window, cx);
12246 }
12247
12248 pub fn fold_ranges<T: ToOffset + Clone>(
12249 &mut self,
12250 ranges: Vec<Range<T>>,
12251 auto_scroll: bool,
12252 window: &mut Window,
12253 cx: &mut Context<Self>,
12254 ) {
12255 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12256 let ranges = ranges
12257 .into_iter()
12258 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12259 .collect::<Vec<_>>();
12260 self.fold_creases(ranges, auto_scroll, window, cx);
12261 }
12262
12263 pub fn fold_creases<T: ToOffset + Clone>(
12264 &mut self,
12265 creases: Vec<Crease<T>>,
12266 auto_scroll: bool,
12267 window: &mut Window,
12268 cx: &mut Context<Self>,
12269 ) {
12270 if creases.is_empty() {
12271 return;
12272 }
12273
12274 let mut buffers_affected = HashSet::default();
12275 let multi_buffer = self.buffer().read(cx);
12276 for crease in &creases {
12277 if let Some((_, buffer, _)) =
12278 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12279 {
12280 buffers_affected.insert(buffer.read(cx).remote_id());
12281 };
12282 }
12283
12284 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12285
12286 if auto_scroll {
12287 self.request_autoscroll(Autoscroll::fit(), cx);
12288 }
12289
12290 cx.notify();
12291
12292 if let Some(active_diagnostics) = self.active_diagnostics.take() {
12293 // Clear diagnostics block when folding a range that contains it.
12294 let snapshot = self.snapshot(window, cx);
12295 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12296 drop(snapshot);
12297 self.active_diagnostics = Some(active_diagnostics);
12298 self.dismiss_diagnostics(cx);
12299 } else {
12300 self.active_diagnostics = Some(active_diagnostics);
12301 }
12302 }
12303
12304 self.scrollbar_marker_state.dirty = true;
12305 }
12306
12307 /// Removes any folds whose ranges intersect any of the given ranges.
12308 pub fn unfold_ranges<T: ToOffset + Clone>(
12309 &mut self,
12310 ranges: &[Range<T>],
12311 inclusive: bool,
12312 auto_scroll: bool,
12313 cx: &mut Context<Self>,
12314 ) {
12315 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12316 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12317 });
12318 }
12319
12320 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12321 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12322 return;
12323 }
12324 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12325 self.display_map
12326 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12327 cx.emit(EditorEvent::BufferFoldToggled {
12328 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12329 folded: true,
12330 });
12331 cx.notify();
12332 }
12333
12334 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12335 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12336 return;
12337 }
12338 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12339 self.display_map.update(cx, |display_map, cx| {
12340 display_map.unfold_buffer(buffer_id, cx);
12341 });
12342 cx.emit(EditorEvent::BufferFoldToggled {
12343 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12344 folded: false,
12345 });
12346 cx.notify();
12347 }
12348
12349 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12350 self.display_map.read(cx).is_buffer_folded(buffer)
12351 }
12352
12353 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12354 self.display_map.read(cx).folded_buffers()
12355 }
12356
12357 /// Removes any folds with the given ranges.
12358 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12359 &mut self,
12360 ranges: &[Range<T>],
12361 type_id: TypeId,
12362 auto_scroll: bool,
12363 cx: &mut Context<Self>,
12364 ) {
12365 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12366 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12367 });
12368 }
12369
12370 fn remove_folds_with<T: ToOffset + Clone>(
12371 &mut self,
12372 ranges: &[Range<T>],
12373 auto_scroll: bool,
12374 cx: &mut Context<Self>,
12375 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12376 ) {
12377 if ranges.is_empty() {
12378 return;
12379 }
12380
12381 let mut buffers_affected = HashSet::default();
12382 let multi_buffer = self.buffer().read(cx);
12383 for range in ranges {
12384 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12385 buffers_affected.insert(buffer.read(cx).remote_id());
12386 };
12387 }
12388
12389 self.display_map.update(cx, update);
12390
12391 if auto_scroll {
12392 self.request_autoscroll(Autoscroll::fit(), cx);
12393 }
12394
12395 cx.notify();
12396 self.scrollbar_marker_state.dirty = true;
12397 self.active_indent_guides_state.dirty = true;
12398 }
12399
12400 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12401 self.display_map.read(cx).fold_placeholder.clone()
12402 }
12403
12404 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12405 self.buffer.update(cx, |buffer, cx| {
12406 buffer.set_all_diff_hunks_expanded(cx);
12407 });
12408 }
12409
12410 pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12411 self.distinguish_unstaged_diff_hunks = true;
12412 }
12413
12414 pub fn expand_all_diff_hunks(
12415 &mut self,
12416 _: &ExpandAllHunkDiffs,
12417 _window: &mut Window,
12418 cx: &mut Context<Self>,
12419 ) {
12420 self.buffer.update(cx, |buffer, cx| {
12421 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12422 });
12423 }
12424
12425 pub fn toggle_selected_diff_hunks(
12426 &mut self,
12427 _: &ToggleSelectedDiffHunks,
12428 _window: &mut Window,
12429 cx: &mut Context<Self>,
12430 ) {
12431 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12432 self.toggle_diff_hunks_in_ranges(ranges, cx);
12433 }
12434
12435 fn diff_hunks_in_ranges<'a>(
12436 &'a self,
12437 ranges: &'a [Range<Anchor>],
12438 buffer: &'a MultiBufferSnapshot,
12439 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12440 ranges.iter().flat_map(move |range| {
12441 let end_excerpt_id = range.end.excerpt_id;
12442 let range = range.to_point(buffer);
12443 let mut peek_end = range.end;
12444 if range.end.row < buffer.max_row().0 {
12445 peek_end = Point::new(range.end.row + 1, 0);
12446 }
12447 buffer
12448 .diff_hunks_in_range(range.start..peek_end)
12449 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12450 })
12451 }
12452
12453 pub fn has_stageable_diff_hunks_in_ranges(
12454 &self,
12455 ranges: &[Range<Anchor>],
12456 snapshot: &MultiBufferSnapshot,
12457 ) -> bool {
12458 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12459 hunks.any(|hunk| {
12460 log::debug!("considering {hunk:?}");
12461 hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
12462 })
12463 }
12464
12465 pub fn toggle_staged_selected_diff_hunks(
12466 &mut self,
12467 _: &ToggleStagedSelectedDiffHunks,
12468 _window: &mut Window,
12469 cx: &mut Context<Self>,
12470 ) {
12471 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12472 self.stage_or_unstage_diff_hunks(&ranges, cx);
12473 }
12474
12475 pub fn stage_or_unstage_diff_hunks(
12476 &mut self,
12477 ranges: &[Range<Anchor>],
12478 cx: &mut Context<Self>,
12479 ) {
12480 let Some(project) = &self.project else {
12481 return;
12482 };
12483 let snapshot = self.buffer.read(cx).snapshot(cx);
12484 let stage = self.has_stageable_diff_hunks_in_ranges(ranges, &snapshot);
12485
12486 let chunk_by = self
12487 .diff_hunks_in_ranges(&ranges, &snapshot)
12488 .chunk_by(|hunk| hunk.buffer_id);
12489 for (buffer_id, hunks) in &chunk_by {
12490 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12491 log::debug!("no buffer for id");
12492 continue;
12493 };
12494 let buffer = buffer.read(cx).snapshot();
12495 let Some((repo, path)) = project
12496 .read(cx)
12497 .repository_and_path_for_buffer_id(buffer_id, cx)
12498 else {
12499 log::debug!("no git repo for buffer id");
12500 continue;
12501 };
12502 let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12503 log::debug!("no diff for buffer id");
12504 continue;
12505 };
12506 let Some(secondary_diff) = diff.secondary_diff() else {
12507 log::debug!("no secondary diff for buffer id");
12508 continue;
12509 };
12510
12511 let edits = diff.secondary_edits_for_stage_or_unstage(
12512 stage,
12513 hunks.map(|hunk| {
12514 (
12515 hunk.diff_base_byte_range.clone(),
12516 hunk.secondary_diff_base_byte_range.clone(),
12517 hunk.buffer_range.clone(),
12518 )
12519 }),
12520 &buffer,
12521 );
12522
12523 let index_base = secondary_diff.base_text().map_or_else(
12524 || Rope::from(""),
12525 |snapshot| snapshot.text.as_rope().clone(),
12526 );
12527 let index_buffer = cx.new(|cx| {
12528 Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12529 });
12530 let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12531 index_buffer.edit(edits, None, cx);
12532 index_buffer.snapshot().as_rope().to_string()
12533 });
12534 let new_index_text = if new_index_text.is_empty()
12535 && (diff.is_single_insertion
12536 || buffer
12537 .file()
12538 .map_or(false, |file| file.disk_state() == DiskState::New))
12539 {
12540 log::debug!("removing from index");
12541 None
12542 } else {
12543 Some(new_index_text)
12544 };
12545
12546 let _ = repo.read(cx).set_index_text(&path, new_index_text);
12547 }
12548 }
12549
12550 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12551 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12552 self.buffer
12553 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12554 }
12555
12556 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12557 self.buffer.update(cx, |buffer, cx| {
12558 let ranges = vec![Anchor::min()..Anchor::max()];
12559 if !buffer.all_diff_hunks_expanded()
12560 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12561 {
12562 buffer.collapse_diff_hunks(ranges, cx);
12563 true
12564 } else {
12565 false
12566 }
12567 })
12568 }
12569
12570 fn toggle_diff_hunks_in_ranges(
12571 &mut self,
12572 ranges: Vec<Range<Anchor>>,
12573 cx: &mut Context<'_, Editor>,
12574 ) {
12575 self.buffer.update(cx, |buffer, cx| {
12576 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12577 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12578 })
12579 }
12580
12581 fn toggle_diff_hunks_in_ranges_narrow(
12582 &mut self,
12583 ranges: Vec<Range<Anchor>>,
12584 cx: &mut Context<'_, Editor>,
12585 ) {
12586 self.buffer.update(cx, |buffer, cx| {
12587 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12588 buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12589 })
12590 }
12591
12592 pub(crate) fn apply_all_diff_hunks(
12593 &mut self,
12594 _: &ApplyAllDiffHunks,
12595 window: &mut Window,
12596 cx: &mut Context<Self>,
12597 ) {
12598 let buffers = self.buffer.read(cx).all_buffers();
12599 for branch_buffer in buffers {
12600 branch_buffer.update(cx, |branch_buffer, cx| {
12601 branch_buffer.merge_into_base(Vec::new(), cx);
12602 });
12603 }
12604
12605 if let Some(project) = self.project.clone() {
12606 self.save(true, project, window, cx).detach_and_log_err(cx);
12607 }
12608 }
12609
12610 pub(crate) fn apply_selected_diff_hunks(
12611 &mut self,
12612 _: &ApplyDiffHunk,
12613 window: &mut Window,
12614 cx: &mut Context<Self>,
12615 ) {
12616 let snapshot = self.snapshot(window, cx);
12617 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12618 let mut ranges_by_buffer = HashMap::default();
12619 self.transact(window, cx, |editor, _window, cx| {
12620 for hunk in hunks {
12621 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12622 ranges_by_buffer
12623 .entry(buffer.clone())
12624 .or_insert_with(Vec::new)
12625 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12626 }
12627 }
12628
12629 for (buffer, ranges) in ranges_by_buffer {
12630 buffer.update(cx, |buffer, cx| {
12631 buffer.merge_into_base(ranges, cx);
12632 });
12633 }
12634 });
12635
12636 if let Some(project) = self.project.clone() {
12637 self.save(true, project, window, cx).detach_and_log_err(cx);
12638 }
12639 }
12640
12641 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12642 if hovered != self.gutter_hovered {
12643 self.gutter_hovered = hovered;
12644 cx.notify();
12645 }
12646 }
12647
12648 pub fn insert_blocks(
12649 &mut self,
12650 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12651 autoscroll: Option<Autoscroll>,
12652 cx: &mut Context<Self>,
12653 ) -> Vec<CustomBlockId> {
12654 let blocks = self
12655 .display_map
12656 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12657 if let Some(autoscroll) = autoscroll {
12658 self.request_autoscroll(autoscroll, cx);
12659 }
12660 cx.notify();
12661 blocks
12662 }
12663
12664 pub fn resize_blocks(
12665 &mut self,
12666 heights: HashMap<CustomBlockId, u32>,
12667 autoscroll: Option<Autoscroll>,
12668 cx: &mut Context<Self>,
12669 ) {
12670 self.display_map
12671 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12672 if let Some(autoscroll) = autoscroll {
12673 self.request_autoscroll(autoscroll, cx);
12674 }
12675 cx.notify();
12676 }
12677
12678 pub fn replace_blocks(
12679 &mut self,
12680 renderers: HashMap<CustomBlockId, RenderBlock>,
12681 autoscroll: Option<Autoscroll>,
12682 cx: &mut Context<Self>,
12683 ) {
12684 self.display_map
12685 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12686 if let Some(autoscroll) = autoscroll {
12687 self.request_autoscroll(autoscroll, cx);
12688 }
12689 cx.notify();
12690 }
12691
12692 pub fn remove_blocks(
12693 &mut self,
12694 block_ids: HashSet<CustomBlockId>,
12695 autoscroll: Option<Autoscroll>,
12696 cx: &mut Context<Self>,
12697 ) {
12698 self.display_map.update(cx, |display_map, cx| {
12699 display_map.remove_blocks(block_ids, cx)
12700 });
12701 if let Some(autoscroll) = autoscroll {
12702 self.request_autoscroll(autoscroll, cx);
12703 }
12704 cx.notify();
12705 }
12706
12707 pub fn row_for_block(
12708 &self,
12709 block_id: CustomBlockId,
12710 cx: &mut Context<Self>,
12711 ) -> Option<DisplayRow> {
12712 self.display_map
12713 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12714 }
12715
12716 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12717 self.focused_block = Some(focused_block);
12718 }
12719
12720 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12721 self.focused_block.take()
12722 }
12723
12724 pub fn insert_creases(
12725 &mut self,
12726 creases: impl IntoIterator<Item = Crease<Anchor>>,
12727 cx: &mut Context<Self>,
12728 ) -> Vec<CreaseId> {
12729 self.display_map
12730 .update(cx, |map, cx| map.insert_creases(creases, cx))
12731 }
12732
12733 pub fn remove_creases(
12734 &mut self,
12735 ids: impl IntoIterator<Item = CreaseId>,
12736 cx: &mut Context<Self>,
12737 ) {
12738 self.display_map
12739 .update(cx, |map, cx| map.remove_creases(ids, cx));
12740 }
12741
12742 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12743 self.display_map
12744 .update(cx, |map, cx| map.snapshot(cx))
12745 .longest_row()
12746 }
12747
12748 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12749 self.display_map
12750 .update(cx, |map, cx| map.snapshot(cx))
12751 .max_point()
12752 }
12753
12754 pub fn text(&self, cx: &App) -> String {
12755 self.buffer.read(cx).read(cx).text()
12756 }
12757
12758 pub fn is_empty(&self, cx: &App) -> bool {
12759 self.buffer.read(cx).read(cx).is_empty()
12760 }
12761
12762 pub fn text_option(&self, cx: &App) -> Option<String> {
12763 let text = self.text(cx);
12764 let text = text.trim();
12765
12766 if text.is_empty() {
12767 return None;
12768 }
12769
12770 Some(text.to_string())
12771 }
12772
12773 pub fn set_text(
12774 &mut self,
12775 text: impl Into<Arc<str>>,
12776 window: &mut Window,
12777 cx: &mut Context<Self>,
12778 ) {
12779 self.transact(window, cx, |this, _, cx| {
12780 this.buffer
12781 .read(cx)
12782 .as_singleton()
12783 .expect("you can only call set_text on editors for singleton buffers")
12784 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12785 });
12786 }
12787
12788 pub fn display_text(&self, cx: &mut App) -> String {
12789 self.display_map
12790 .update(cx, |map, cx| map.snapshot(cx))
12791 .text()
12792 }
12793
12794 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12795 let mut wrap_guides = smallvec::smallvec![];
12796
12797 if self.show_wrap_guides == Some(false) {
12798 return wrap_guides;
12799 }
12800
12801 let settings = self.buffer.read(cx).settings_at(0, cx);
12802 if settings.show_wrap_guides {
12803 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12804 wrap_guides.push((soft_wrap as usize, true));
12805 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12806 wrap_guides.push((soft_wrap as usize, true));
12807 }
12808 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12809 }
12810
12811 wrap_guides
12812 }
12813
12814 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12815 let settings = self.buffer.read(cx).settings_at(0, cx);
12816 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12817 match mode {
12818 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12819 SoftWrap::None
12820 }
12821 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12822 language_settings::SoftWrap::PreferredLineLength => {
12823 SoftWrap::Column(settings.preferred_line_length)
12824 }
12825 language_settings::SoftWrap::Bounded => {
12826 SoftWrap::Bounded(settings.preferred_line_length)
12827 }
12828 }
12829 }
12830
12831 pub fn set_soft_wrap_mode(
12832 &mut self,
12833 mode: language_settings::SoftWrap,
12834
12835 cx: &mut Context<Self>,
12836 ) {
12837 self.soft_wrap_mode_override = Some(mode);
12838 cx.notify();
12839 }
12840
12841 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12842 self.text_style_refinement = Some(style);
12843 }
12844
12845 /// called by the Element so we know what style we were most recently rendered with.
12846 pub(crate) fn set_style(
12847 &mut self,
12848 style: EditorStyle,
12849 window: &mut Window,
12850 cx: &mut Context<Self>,
12851 ) {
12852 let rem_size = window.rem_size();
12853 self.display_map.update(cx, |map, cx| {
12854 map.set_font(
12855 style.text.font(),
12856 style.text.font_size.to_pixels(rem_size),
12857 cx,
12858 )
12859 });
12860 self.style = Some(style);
12861 }
12862
12863 pub fn style(&self) -> Option<&EditorStyle> {
12864 self.style.as_ref()
12865 }
12866
12867 // Called by the element. This method is not designed to be called outside of the editor
12868 // element's layout code because it does not notify when rewrapping is computed synchronously.
12869 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12870 self.display_map
12871 .update(cx, |map, cx| map.set_wrap_width(width, cx))
12872 }
12873
12874 pub fn set_soft_wrap(&mut self) {
12875 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12876 }
12877
12878 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12879 if self.soft_wrap_mode_override.is_some() {
12880 self.soft_wrap_mode_override.take();
12881 } else {
12882 let soft_wrap = match self.soft_wrap_mode(cx) {
12883 SoftWrap::GitDiff => return,
12884 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12885 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12886 language_settings::SoftWrap::None
12887 }
12888 };
12889 self.soft_wrap_mode_override = Some(soft_wrap);
12890 }
12891 cx.notify();
12892 }
12893
12894 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12895 let Some(workspace) = self.workspace() else {
12896 return;
12897 };
12898 let fs = workspace.read(cx).app_state().fs.clone();
12899 let current_show = TabBarSettings::get_global(cx).show;
12900 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12901 setting.show = Some(!current_show);
12902 });
12903 }
12904
12905 pub fn toggle_indent_guides(
12906 &mut self,
12907 _: &ToggleIndentGuides,
12908 _: &mut Window,
12909 cx: &mut Context<Self>,
12910 ) {
12911 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12912 self.buffer
12913 .read(cx)
12914 .settings_at(0, cx)
12915 .indent_guides
12916 .enabled
12917 });
12918 self.show_indent_guides = Some(!currently_enabled);
12919 cx.notify();
12920 }
12921
12922 fn should_show_indent_guides(&self) -> Option<bool> {
12923 self.show_indent_guides
12924 }
12925
12926 pub fn toggle_line_numbers(
12927 &mut self,
12928 _: &ToggleLineNumbers,
12929 _: &mut Window,
12930 cx: &mut Context<Self>,
12931 ) {
12932 let mut editor_settings = EditorSettings::get_global(cx).clone();
12933 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12934 EditorSettings::override_global(editor_settings, cx);
12935 }
12936
12937 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12938 self.use_relative_line_numbers
12939 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12940 }
12941
12942 pub fn toggle_relative_line_numbers(
12943 &mut self,
12944 _: &ToggleRelativeLineNumbers,
12945 _: &mut Window,
12946 cx: &mut Context<Self>,
12947 ) {
12948 let is_relative = self.should_use_relative_line_numbers(cx);
12949 self.set_relative_line_number(Some(!is_relative), cx)
12950 }
12951
12952 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12953 self.use_relative_line_numbers = is_relative;
12954 cx.notify();
12955 }
12956
12957 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12958 self.show_gutter = show_gutter;
12959 cx.notify();
12960 }
12961
12962 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12963 self.show_scrollbars = show_scrollbars;
12964 cx.notify();
12965 }
12966
12967 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12968 self.show_line_numbers = Some(show_line_numbers);
12969 cx.notify();
12970 }
12971
12972 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12973 self.show_git_diff_gutter = Some(show_git_diff_gutter);
12974 cx.notify();
12975 }
12976
12977 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12978 self.show_code_actions = Some(show_code_actions);
12979 cx.notify();
12980 }
12981
12982 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12983 self.show_runnables = Some(show_runnables);
12984 cx.notify();
12985 }
12986
12987 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12988 if self.display_map.read(cx).masked != masked {
12989 self.display_map.update(cx, |map, _| map.masked = masked);
12990 }
12991 cx.notify()
12992 }
12993
12994 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12995 self.show_wrap_guides = Some(show_wrap_guides);
12996 cx.notify();
12997 }
12998
12999 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13000 self.show_indent_guides = Some(show_indent_guides);
13001 cx.notify();
13002 }
13003
13004 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13005 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13006 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13007 if let Some(dir) = file.abs_path(cx).parent() {
13008 return Some(dir.to_owned());
13009 }
13010 }
13011
13012 if let Some(project_path) = buffer.read(cx).project_path(cx) {
13013 return Some(project_path.path.to_path_buf());
13014 }
13015 }
13016
13017 None
13018 }
13019
13020 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13021 self.active_excerpt(cx)?
13022 .1
13023 .read(cx)
13024 .file()
13025 .and_then(|f| f.as_local())
13026 }
13027
13028 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13029 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13030 let buffer = buffer.read(cx);
13031 if let Some(project_path) = buffer.project_path(cx) {
13032 let project = self.project.as_ref()?.read(cx);
13033 project.absolute_path(&project_path, cx)
13034 } else {
13035 buffer
13036 .file()
13037 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13038 }
13039 })
13040 }
13041
13042 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13043 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13044 let project_path = buffer.read(cx).project_path(cx)?;
13045 let project = self.project.as_ref()?.read(cx);
13046 let entry = project.entry_for_path(&project_path, cx)?;
13047 let path = entry.path.to_path_buf();
13048 Some(path)
13049 })
13050 }
13051
13052 pub fn reveal_in_finder(
13053 &mut self,
13054 _: &RevealInFileManager,
13055 _window: &mut Window,
13056 cx: &mut Context<Self>,
13057 ) {
13058 if let Some(target) = self.target_file(cx) {
13059 cx.reveal_path(&target.abs_path(cx));
13060 }
13061 }
13062
13063 pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
13064 if let Some(path) = self.target_file_abs_path(cx) {
13065 if let Some(path) = path.to_str() {
13066 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13067 }
13068 }
13069 }
13070
13071 pub fn copy_relative_path(
13072 &mut self,
13073 _: &CopyRelativePath,
13074 _window: &mut Window,
13075 cx: &mut Context<Self>,
13076 ) {
13077 if let Some(path) = self.target_file_path(cx) {
13078 if let Some(path) = path.to_str() {
13079 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13080 }
13081 }
13082 }
13083
13084 pub fn copy_file_name_without_extension(
13085 &mut self,
13086 _: &CopyFileNameWithoutExtension,
13087 _: &mut Window,
13088 cx: &mut Context<Self>,
13089 ) {
13090 if let Some(file) = self.target_file(cx) {
13091 if let Some(file_stem) = file.path().file_stem() {
13092 if let Some(name) = file_stem.to_str() {
13093 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13094 }
13095 }
13096 }
13097 }
13098
13099 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13100 if let Some(file) = self.target_file(cx) {
13101 if let Some(file_name) = file.path().file_name() {
13102 if let Some(name) = file_name.to_str() {
13103 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13104 }
13105 }
13106 }
13107 }
13108
13109 pub fn toggle_git_blame(
13110 &mut self,
13111 _: &ToggleGitBlame,
13112 window: &mut Window,
13113 cx: &mut Context<Self>,
13114 ) {
13115 self.show_git_blame_gutter = !self.show_git_blame_gutter;
13116
13117 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13118 self.start_git_blame(true, window, cx);
13119 }
13120
13121 cx.notify();
13122 }
13123
13124 pub fn toggle_git_blame_inline(
13125 &mut self,
13126 _: &ToggleGitBlameInline,
13127 window: &mut Window,
13128 cx: &mut Context<Self>,
13129 ) {
13130 self.toggle_git_blame_inline_internal(true, window, cx);
13131 cx.notify();
13132 }
13133
13134 pub fn git_blame_inline_enabled(&self) -> bool {
13135 self.git_blame_inline_enabled
13136 }
13137
13138 pub fn toggle_selection_menu(
13139 &mut self,
13140 _: &ToggleSelectionMenu,
13141 _: &mut Window,
13142 cx: &mut Context<Self>,
13143 ) {
13144 self.show_selection_menu = self
13145 .show_selection_menu
13146 .map(|show_selections_menu| !show_selections_menu)
13147 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13148
13149 cx.notify();
13150 }
13151
13152 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13153 self.show_selection_menu
13154 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13155 }
13156
13157 fn start_git_blame(
13158 &mut self,
13159 user_triggered: bool,
13160 window: &mut Window,
13161 cx: &mut Context<Self>,
13162 ) {
13163 if let Some(project) = self.project.as_ref() {
13164 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13165 return;
13166 };
13167
13168 if buffer.read(cx).file().is_none() {
13169 return;
13170 }
13171
13172 let focused = self.focus_handle(cx).contains_focused(window, cx);
13173
13174 let project = project.clone();
13175 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13176 self.blame_subscription =
13177 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13178 self.blame = Some(blame);
13179 }
13180 }
13181
13182 fn toggle_git_blame_inline_internal(
13183 &mut self,
13184 user_triggered: bool,
13185 window: &mut Window,
13186 cx: &mut Context<Self>,
13187 ) {
13188 if self.git_blame_inline_enabled {
13189 self.git_blame_inline_enabled = false;
13190 self.show_git_blame_inline = false;
13191 self.show_git_blame_inline_delay_task.take();
13192 } else {
13193 self.git_blame_inline_enabled = true;
13194 self.start_git_blame_inline(user_triggered, window, cx);
13195 }
13196
13197 cx.notify();
13198 }
13199
13200 fn start_git_blame_inline(
13201 &mut self,
13202 user_triggered: bool,
13203 window: &mut Window,
13204 cx: &mut Context<Self>,
13205 ) {
13206 self.start_git_blame(user_triggered, window, cx);
13207
13208 if ProjectSettings::get_global(cx)
13209 .git
13210 .inline_blame_delay()
13211 .is_some()
13212 {
13213 self.start_inline_blame_timer(window, cx);
13214 } else {
13215 self.show_git_blame_inline = true
13216 }
13217 }
13218
13219 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13220 self.blame.as_ref()
13221 }
13222
13223 pub fn show_git_blame_gutter(&self) -> bool {
13224 self.show_git_blame_gutter
13225 }
13226
13227 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13228 self.show_git_blame_gutter && self.has_blame_entries(cx)
13229 }
13230
13231 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13232 self.show_git_blame_inline
13233 && self.focus_handle.is_focused(window)
13234 && !self.newest_selection_head_on_empty_line(cx)
13235 && self.has_blame_entries(cx)
13236 }
13237
13238 fn has_blame_entries(&self, cx: &App) -> bool {
13239 self.blame()
13240 .map_or(false, |blame| blame.read(cx).has_generated_entries())
13241 }
13242
13243 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13244 let cursor_anchor = self.selections.newest_anchor().head();
13245
13246 let snapshot = self.buffer.read(cx).snapshot(cx);
13247 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13248
13249 snapshot.line_len(buffer_row) == 0
13250 }
13251
13252 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13253 let buffer_and_selection = maybe!({
13254 let selection = self.selections.newest::<Point>(cx);
13255 let selection_range = selection.range();
13256
13257 let multi_buffer = self.buffer().read(cx);
13258 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13259 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13260
13261 let (buffer, range, _) = if selection.reversed {
13262 buffer_ranges.first()
13263 } else {
13264 buffer_ranges.last()
13265 }?;
13266
13267 let selection = text::ToPoint::to_point(&range.start, &buffer).row
13268 ..text::ToPoint::to_point(&range.end, &buffer).row;
13269 Some((
13270 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13271 selection,
13272 ))
13273 });
13274
13275 let Some((buffer, selection)) = buffer_and_selection else {
13276 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13277 };
13278
13279 let Some(project) = self.project.as_ref() else {
13280 return Task::ready(Err(anyhow!("editor does not have project")));
13281 };
13282
13283 project.update(cx, |project, cx| {
13284 project.get_permalink_to_line(&buffer, selection, cx)
13285 })
13286 }
13287
13288 pub fn copy_permalink_to_line(
13289 &mut self,
13290 _: &CopyPermalinkToLine,
13291 window: &mut Window,
13292 cx: &mut Context<Self>,
13293 ) {
13294 let permalink_task = self.get_permalink_to_line(cx);
13295 let workspace = self.workspace();
13296
13297 cx.spawn_in(window, |_, mut cx| async move {
13298 match permalink_task.await {
13299 Ok(permalink) => {
13300 cx.update(|_, cx| {
13301 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13302 })
13303 .ok();
13304 }
13305 Err(err) => {
13306 let message = format!("Failed to copy permalink: {err}");
13307
13308 Err::<(), anyhow::Error>(err).log_err();
13309
13310 if let Some(workspace) = workspace {
13311 workspace
13312 .update_in(&mut cx, |workspace, _, cx| {
13313 struct CopyPermalinkToLine;
13314
13315 workspace.show_toast(
13316 Toast::new(
13317 NotificationId::unique::<CopyPermalinkToLine>(),
13318 message,
13319 ),
13320 cx,
13321 )
13322 })
13323 .ok();
13324 }
13325 }
13326 }
13327 })
13328 .detach();
13329 }
13330
13331 pub fn copy_file_location(
13332 &mut self,
13333 _: &CopyFileLocation,
13334 _: &mut Window,
13335 cx: &mut Context<Self>,
13336 ) {
13337 let selection = self.selections.newest::<Point>(cx).start.row + 1;
13338 if let Some(file) = self.target_file(cx) {
13339 if let Some(path) = file.path().to_str() {
13340 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13341 }
13342 }
13343 }
13344
13345 pub fn open_permalink_to_line(
13346 &mut self,
13347 _: &OpenPermalinkToLine,
13348 window: &mut Window,
13349 cx: &mut Context<Self>,
13350 ) {
13351 let permalink_task = self.get_permalink_to_line(cx);
13352 let workspace = self.workspace();
13353
13354 cx.spawn_in(window, |_, mut cx| async move {
13355 match permalink_task.await {
13356 Ok(permalink) => {
13357 cx.update(|_, cx| {
13358 cx.open_url(permalink.as_ref());
13359 })
13360 .ok();
13361 }
13362 Err(err) => {
13363 let message = format!("Failed to open permalink: {err}");
13364
13365 Err::<(), anyhow::Error>(err).log_err();
13366
13367 if let Some(workspace) = workspace {
13368 workspace
13369 .update(&mut cx, |workspace, cx| {
13370 struct OpenPermalinkToLine;
13371
13372 workspace.show_toast(
13373 Toast::new(
13374 NotificationId::unique::<OpenPermalinkToLine>(),
13375 message,
13376 ),
13377 cx,
13378 )
13379 })
13380 .ok();
13381 }
13382 }
13383 }
13384 })
13385 .detach();
13386 }
13387
13388 pub fn insert_uuid_v4(
13389 &mut self,
13390 _: &InsertUuidV4,
13391 window: &mut Window,
13392 cx: &mut Context<Self>,
13393 ) {
13394 self.insert_uuid(UuidVersion::V4, window, cx);
13395 }
13396
13397 pub fn insert_uuid_v7(
13398 &mut self,
13399 _: &InsertUuidV7,
13400 window: &mut Window,
13401 cx: &mut Context<Self>,
13402 ) {
13403 self.insert_uuid(UuidVersion::V7, window, cx);
13404 }
13405
13406 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13407 self.transact(window, cx, |this, window, cx| {
13408 let edits = this
13409 .selections
13410 .all::<Point>(cx)
13411 .into_iter()
13412 .map(|selection| {
13413 let uuid = match version {
13414 UuidVersion::V4 => uuid::Uuid::new_v4(),
13415 UuidVersion::V7 => uuid::Uuid::now_v7(),
13416 };
13417
13418 (selection.range(), uuid.to_string())
13419 });
13420 this.edit(edits, cx);
13421 this.refresh_inline_completion(true, false, window, cx);
13422 });
13423 }
13424
13425 pub fn open_selections_in_multibuffer(
13426 &mut self,
13427 _: &OpenSelectionsInMultibuffer,
13428 window: &mut Window,
13429 cx: &mut Context<Self>,
13430 ) {
13431 let multibuffer = self.buffer.read(cx);
13432
13433 let Some(buffer) = multibuffer.as_singleton() else {
13434 return;
13435 };
13436
13437 let Some(workspace) = self.workspace() else {
13438 return;
13439 };
13440
13441 let locations = self
13442 .selections
13443 .disjoint_anchors()
13444 .iter()
13445 .map(|range| Location {
13446 buffer: buffer.clone(),
13447 range: range.start.text_anchor..range.end.text_anchor,
13448 })
13449 .collect::<Vec<_>>();
13450
13451 let title = multibuffer.title(cx).to_string();
13452
13453 cx.spawn_in(window, |_, mut cx| async move {
13454 workspace.update_in(&mut cx, |workspace, window, cx| {
13455 Self::open_locations_in_multibuffer(
13456 workspace,
13457 locations,
13458 format!("Selections for '{title}'"),
13459 false,
13460 MultibufferSelectionMode::All,
13461 window,
13462 cx,
13463 );
13464 })
13465 })
13466 .detach();
13467 }
13468
13469 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13470 /// last highlight added will be used.
13471 ///
13472 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13473 pub fn highlight_rows<T: 'static>(
13474 &mut self,
13475 range: Range<Anchor>,
13476 color: Hsla,
13477 should_autoscroll: bool,
13478 cx: &mut Context<Self>,
13479 ) {
13480 let snapshot = self.buffer().read(cx).snapshot(cx);
13481 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13482 let ix = row_highlights.binary_search_by(|highlight| {
13483 Ordering::Equal
13484 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13485 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13486 });
13487
13488 if let Err(mut ix) = ix {
13489 let index = post_inc(&mut self.highlight_order);
13490
13491 // If this range intersects with the preceding highlight, then merge it with
13492 // the preceding highlight. Otherwise insert a new highlight.
13493 let mut merged = false;
13494 if ix > 0 {
13495 let prev_highlight = &mut row_highlights[ix - 1];
13496 if prev_highlight
13497 .range
13498 .end
13499 .cmp(&range.start, &snapshot)
13500 .is_ge()
13501 {
13502 ix -= 1;
13503 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13504 prev_highlight.range.end = range.end;
13505 }
13506 merged = true;
13507 prev_highlight.index = index;
13508 prev_highlight.color = color;
13509 prev_highlight.should_autoscroll = should_autoscroll;
13510 }
13511 }
13512
13513 if !merged {
13514 row_highlights.insert(
13515 ix,
13516 RowHighlight {
13517 range: range.clone(),
13518 index,
13519 color,
13520 should_autoscroll,
13521 },
13522 );
13523 }
13524
13525 // If any of the following highlights intersect with this one, merge them.
13526 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13527 let highlight = &row_highlights[ix];
13528 if next_highlight
13529 .range
13530 .start
13531 .cmp(&highlight.range.end, &snapshot)
13532 .is_le()
13533 {
13534 if next_highlight
13535 .range
13536 .end
13537 .cmp(&highlight.range.end, &snapshot)
13538 .is_gt()
13539 {
13540 row_highlights[ix].range.end = next_highlight.range.end;
13541 }
13542 row_highlights.remove(ix + 1);
13543 } else {
13544 break;
13545 }
13546 }
13547 }
13548 }
13549
13550 /// Remove any highlighted row ranges of the given type that intersect the
13551 /// given ranges.
13552 pub fn remove_highlighted_rows<T: 'static>(
13553 &mut self,
13554 ranges_to_remove: Vec<Range<Anchor>>,
13555 cx: &mut Context<Self>,
13556 ) {
13557 let snapshot = self.buffer().read(cx).snapshot(cx);
13558 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13559 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13560 row_highlights.retain(|highlight| {
13561 while let Some(range_to_remove) = ranges_to_remove.peek() {
13562 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13563 Ordering::Less | Ordering::Equal => {
13564 ranges_to_remove.next();
13565 }
13566 Ordering::Greater => {
13567 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13568 Ordering::Less | Ordering::Equal => {
13569 return false;
13570 }
13571 Ordering::Greater => break,
13572 }
13573 }
13574 }
13575 }
13576
13577 true
13578 })
13579 }
13580
13581 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13582 pub fn clear_row_highlights<T: 'static>(&mut self) {
13583 self.highlighted_rows.remove(&TypeId::of::<T>());
13584 }
13585
13586 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13587 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13588 self.highlighted_rows
13589 .get(&TypeId::of::<T>())
13590 .map_or(&[] as &[_], |vec| vec.as_slice())
13591 .iter()
13592 .map(|highlight| (highlight.range.clone(), highlight.color))
13593 }
13594
13595 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13596 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13597 /// Allows to ignore certain kinds of highlights.
13598 pub fn highlighted_display_rows(
13599 &self,
13600 window: &mut Window,
13601 cx: &mut App,
13602 ) -> BTreeMap<DisplayRow, Background> {
13603 let snapshot = self.snapshot(window, cx);
13604 let mut used_highlight_orders = HashMap::default();
13605 self.highlighted_rows
13606 .iter()
13607 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13608 .fold(
13609 BTreeMap::<DisplayRow, Background>::new(),
13610 |mut unique_rows, highlight| {
13611 let start = highlight.range.start.to_display_point(&snapshot);
13612 let end = highlight.range.end.to_display_point(&snapshot);
13613 let start_row = start.row().0;
13614 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13615 && end.column() == 0
13616 {
13617 end.row().0.saturating_sub(1)
13618 } else {
13619 end.row().0
13620 };
13621 for row in start_row..=end_row {
13622 let used_index =
13623 used_highlight_orders.entry(row).or_insert(highlight.index);
13624 if highlight.index >= *used_index {
13625 *used_index = highlight.index;
13626 unique_rows.insert(DisplayRow(row), highlight.color.into());
13627 }
13628 }
13629 unique_rows
13630 },
13631 )
13632 }
13633
13634 pub fn highlighted_display_row_for_autoscroll(
13635 &self,
13636 snapshot: &DisplaySnapshot,
13637 ) -> Option<DisplayRow> {
13638 self.highlighted_rows
13639 .values()
13640 .flat_map(|highlighted_rows| highlighted_rows.iter())
13641 .filter_map(|highlight| {
13642 if highlight.should_autoscroll {
13643 Some(highlight.range.start.to_display_point(snapshot).row())
13644 } else {
13645 None
13646 }
13647 })
13648 .min()
13649 }
13650
13651 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13652 self.highlight_background::<SearchWithinRange>(
13653 ranges,
13654 |colors| colors.editor_document_highlight_read_background,
13655 cx,
13656 )
13657 }
13658
13659 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13660 self.breadcrumb_header = Some(new_header);
13661 }
13662
13663 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13664 self.clear_background_highlights::<SearchWithinRange>(cx);
13665 }
13666
13667 pub fn highlight_background<T: 'static>(
13668 &mut self,
13669 ranges: &[Range<Anchor>],
13670 color_fetcher: fn(&ThemeColors) -> Hsla,
13671 cx: &mut Context<Self>,
13672 ) {
13673 self.background_highlights
13674 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13675 self.scrollbar_marker_state.dirty = true;
13676 cx.notify();
13677 }
13678
13679 pub fn clear_background_highlights<T: 'static>(
13680 &mut self,
13681 cx: &mut Context<Self>,
13682 ) -> Option<BackgroundHighlight> {
13683 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13684 if !text_highlights.1.is_empty() {
13685 self.scrollbar_marker_state.dirty = true;
13686 cx.notify();
13687 }
13688 Some(text_highlights)
13689 }
13690
13691 pub fn highlight_gutter<T: 'static>(
13692 &mut self,
13693 ranges: &[Range<Anchor>],
13694 color_fetcher: fn(&App) -> Hsla,
13695 cx: &mut Context<Self>,
13696 ) {
13697 self.gutter_highlights
13698 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13699 cx.notify();
13700 }
13701
13702 pub fn clear_gutter_highlights<T: 'static>(
13703 &mut self,
13704 cx: &mut Context<Self>,
13705 ) -> Option<GutterHighlight> {
13706 cx.notify();
13707 self.gutter_highlights.remove(&TypeId::of::<T>())
13708 }
13709
13710 #[cfg(feature = "test-support")]
13711 pub fn all_text_background_highlights(
13712 &self,
13713 window: &mut Window,
13714 cx: &mut Context<Self>,
13715 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13716 let snapshot = self.snapshot(window, cx);
13717 let buffer = &snapshot.buffer_snapshot;
13718 let start = buffer.anchor_before(0);
13719 let end = buffer.anchor_after(buffer.len());
13720 let theme = cx.theme().colors();
13721 self.background_highlights_in_range(start..end, &snapshot, theme)
13722 }
13723
13724 #[cfg(feature = "test-support")]
13725 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13726 let snapshot = self.buffer().read(cx).snapshot(cx);
13727
13728 let highlights = self
13729 .background_highlights
13730 .get(&TypeId::of::<items::BufferSearchHighlights>());
13731
13732 if let Some((_color, ranges)) = highlights {
13733 ranges
13734 .iter()
13735 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13736 .collect_vec()
13737 } else {
13738 vec![]
13739 }
13740 }
13741
13742 fn document_highlights_for_position<'a>(
13743 &'a self,
13744 position: Anchor,
13745 buffer: &'a MultiBufferSnapshot,
13746 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13747 let read_highlights = self
13748 .background_highlights
13749 .get(&TypeId::of::<DocumentHighlightRead>())
13750 .map(|h| &h.1);
13751 let write_highlights = self
13752 .background_highlights
13753 .get(&TypeId::of::<DocumentHighlightWrite>())
13754 .map(|h| &h.1);
13755 let left_position = position.bias_left(buffer);
13756 let right_position = position.bias_right(buffer);
13757 read_highlights
13758 .into_iter()
13759 .chain(write_highlights)
13760 .flat_map(move |ranges| {
13761 let start_ix = match ranges.binary_search_by(|probe| {
13762 let cmp = probe.end.cmp(&left_position, buffer);
13763 if cmp.is_ge() {
13764 Ordering::Greater
13765 } else {
13766 Ordering::Less
13767 }
13768 }) {
13769 Ok(i) | Err(i) => i,
13770 };
13771
13772 ranges[start_ix..]
13773 .iter()
13774 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13775 })
13776 }
13777
13778 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13779 self.background_highlights
13780 .get(&TypeId::of::<T>())
13781 .map_or(false, |(_, highlights)| !highlights.is_empty())
13782 }
13783
13784 pub fn background_highlights_in_range(
13785 &self,
13786 search_range: Range<Anchor>,
13787 display_snapshot: &DisplaySnapshot,
13788 theme: &ThemeColors,
13789 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13790 let mut results = Vec::new();
13791 for (color_fetcher, ranges) in self.background_highlights.values() {
13792 let color = color_fetcher(theme);
13793 let start_ix = match ranges.binary_search_by(|probe| {
13794 let cmp = probe
13795 .end
13796 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13797 if cmp.is_gt() {
13798 Ordering::Greater
13799 } else {
13800 Ordering::Less
13801 }
13802 }) {
13803 Ok(i) | Err(i) => i,
13804 };
13805 for range in &ranges[start_ix..] {
13806 if range
13807 .start
13808 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13809 .is_ge()
13810 {
13811 break;
13812 }
13813
13814 let start = range.start.to_display_point(display_snapshot);
13815 let end = range.end.to_display_point(display_snapshot);
13816 results.push((start..end, color))
13817 }
13818 }
13819 results
13820 }
13821
13822 pub fn background_highlight_row_ranges<T: 'static>(
13823 &self,
13824 search_range: Range<Anchor>,
13825 display_snapshot: &DisplaySnapshot,
13826 count: usize,
13827 ) -> Vec<RangeInclusive<DisplayPoint>> {
13828 let mut results = Vec::new();
13829 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13830 return vec![];
13831 };
13832
13833 let start_ix = match ranges.binary_search_by(|probe| {
13834 let cmp = probe
13835 .end
13836 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13837 if cmp.is_gt() {
13838 Ordering::Greater
13839 } else {
13840 Ordering::Less
13841 }
13842 }) {
13843 Ok(i) | Err(i) => i,
13844 };
13845 let mut push_region = |start: Option<Point>, end: Option<Point>| {
13846 if let (Some(start_display), Some(end_display)) = (start, end) {
13847 results.push(
13848 start_display.to_display_point(display_snapshot)
13849 ..=end_display.to_display_point(display_snapshot),
13850 );
13851 }
13852 };
13853 let mut start_row: Option<Point> = None;
13854 let mut end_row: Option<Point> = None;
13855 if ranges.len() > count {
13856 return Vec::new();
13857 }
13858 for range in &ranges[start_ix..] {
13859 if range
13860 .start
13861 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13862 .is_ge()
13863 {
13864 break;
13865 }
13866 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13867 if let Some(current_row) = &end_row {
13868 if end.row == current_row.row {
13869 continue;
13870 }
13871 }
13872 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13873 if start_row.is_none() {
13874 assert_eq!(end_row, None);
13875 start_row = Some(start);
13876 end_row = Some(end);
13877 continue;
13878 }
13879 if let Some(current_end) = end_row.as_mut() {
13880 if start.row > current_end.row + 1 {
13881 push_region(start_row, end_row);
13882 start_row = Some(start);
13883 end_row = Some(end);
13884 } else {
13885 // Merge two hunks.
13886 *current_end = end;
13887 }
13888 } else {
13889 unreachable!();
13890 }
13891 }
13892 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13893 push_region(start_row, end_row);
13894 results
13895 }
13896
13897 pub fn gutter_highlights_in_range(
13898 &self,
13899 search_range: Range<Anchor>,
13900 display_snapshot: &DisplaySnapshot,
13901 cx: &App,
13902 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13903 let mut results = Vec::new();
13904 for (color_fetcher, ranges) in self.gutter_highlights.values() {
13905 let color = color_fetcher(cx);
13906 let start_ix = match ranges.binary_search_by(|probe| {
13907 let cmp = probe
13908 .end
13909 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13910 if cmp.is_gt() {
13911 Ordering::Greater
13912 } else {
13913 Ordering::Less
13914 }
13915 }) {
13916 Ok(i) | Err(i) => i,
13917 };
13918 for range in &ranges[start_ix..] {
13919 if range
13920 .start
13921 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13922 .is_ge()
13923 {
13924 break;
13925 }
13926
13927 let start = range.start.to_display_point(display_snapshot);
13928 let end = range.end.to_display_point(display_snapshot);
13929 results.push((start..end, color))
13930 }
13931 }
13932 results
13933 }
13934
13935 /// Get the text ranges corresponding to the redaction query
13936 pub fn redacted_ranges(
13937 &self,
13938 search_range: Range<Anchor>,
13939 display_snapshot: &DisplaySnapshot,
13940 cx: &App,
13941 ) -> Vec<Range<DisplayPoint>> {
13942 display_snapshot
13943 .buffer_snapshot
13944 .redacted_ranges(search_range, |file| {
13945 if let Some(file) = file {
13946 file.is_private()
13947 && EditorSettings::get(
13948 Some(SettingsLocation {
13949 worktree_id: file.worktree_id(cx),
13950 path: file.path().as_ref(),
13951 }),
13952 cx,
13953 )
13954 .redact_private_values
13955 } else {
13956 false
13957 }
13958 })
13959 .map(|range| {
13960 range.start.to_display_point(display_snapshot)
13961 ..range.end.to_display_point(display_snapshot)
13962 })
13963 .collect()
13964 }
13965
13966 pub fn highlight_text<T: 'static>(
13967 &mut self,
13968 ranges: Vec<Range<Anchor>>,
13969 style: HighlightStyle,
13970 cx: &mut Context<Self>,
13971 ) {
13972 self.display_map.update(cx, |map, _| {
13973 map.highlight_text(TypeId::of::<T>(), ranges, style)
13974 });
13975 cx.notify();
13976 }
13977
13978 pub(crate) fn highlight_inlays<T: 'static>(
13979 &mut self,
13980 highlights: Vec<InlayHighlight>,
13981 style: HighlightStyle,
13982 cx: &mut Context<Self>,
13983 ) {
13984 self.display_map.update(cx, |map, _| {
13985 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13986 });
13987 cx.notify();
13988 }
13989
13990 pub fn text_highlights<'a, T: 'static>(
13991 &'a self,
13992 cx: &'a App,
13993 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13994 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13995 }
13996
13997 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13998 let cleared = self
13999 .display_map
14000 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14001 if cleared {
14002 cx.notify();
14003 }
14004 }
14005
14006 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14007 (self.read_only(cx) || self.blink_manager.read(cx).visible())
14008 && self.focus_handle.is_focused(window)
14009 }
14010
14011 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14012 self.show_cursor_when_unfocused = is_enabled;
14013 cx.notify();
14014 }
14015
14016 pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
14017 self.project
14018 .as_ref()
14019 .map(|project| project.read(cx).lsp_store())
14020 }
14021
14022 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14023 cx.notify();
14024 }
14025
14026 fn on_buffer_event(
14027 &mut self,
14028 multibuffer: &Entity<MultiBuffer>,
14029 event: &multi_buffer::Event,
14030 window: &mut Window,
14031 cx: &mut Context<Self>,
14032 ) {
14033 match event {
14034 multi_buffer::Event::Edited {
14035 singleton_buffer_edited,
14036 edited_buffer: buffer_edited,
14037 } => {
14038 self.scrollbar_marker_state.dirty = true;
14039 self.active_indent_guides_state.dirty = true;
14040 self.refresh_active_diagnostics(cx);
14041 self.refresh_code_actions(window, cx);
14042 if self.has_active_inline_completion() {
14043 self.update_visible_inline_completion(window, cx);
14044 }
14045 if let Some(buffer) = buffer_edited {
14046 let buffer_id = buffer.read(cx).remote_id();
14047 if !self.registered_buffers.contains_key(&buffer_id) {
14048 if let Some(lsp_store) = self.lsp_store(cx) {
14049 lsp_store.update(cx, |lsp_store, cx| {
14050 self.registered_buffers.insert(
14051 buffer_id,
14052 lsp_store.register_buffer_with_language_servers(&buffer, cx),
14053 );
14054 })
14055 }
14056 }
14057 }
14058 cx.emit(EditorEvent::BufferEdited);
14059 cx.emit(SearchEvent::MatchesInvalidated);
14060 if *singleton_buffer_edited {
14061 if let Some(project) = &self.project {
14062 let project = project.read(cx);
14063 #[allow(clippy::mutable_key_type)]
14064 let languages_affected = multibuffer
14065 .read(cx)
14066 .all_buffers()
14067 .into_iter()
14068 .filter_map(|buffer| {
14069 let buffer = buffer.read(cx);
14070 let language = buffer.language()?;
14071 if project.is_local()
14072 && project
14073 .language_servers_for_local_buffer(buffer, cx)
14074 .count()
14075 == 0
14076 {
14077 None
14078 } else {
14079 Some(language)
14080 }
14081 })
14082 .cloned()
14083 .collect::<HashSet<_>>();
14084 if !languages_affected.is_empty() {
14085 self.refresh_inlay_hints(
14086 InlayHintRefreshReason::BufferEdited(languages_affected),
14087 cx,
14088 );
14089 }
14090 }
14091 }
14092
14093 let Some(project) = &self.project else { return };
14094 let (telemetry, is_via_ssh) = {
14095 let project = project.read(cx);
14096 let telemetry = project.client().telemetry().clone();
14097 let is_via_ssh = project.is_via_ssh();
14098 (telemetry, is_via_ssh)
14099 };
14100 refresh_linked_ranges(self, window, cx);
14101 telemetry.log_edit_event("editor", is_via_ssh);
14102 }
14103 multi_buffer::Event::ExcerptsAdded {
14104 buffer,
14105 predecessor,
14106 excerpts,
14107 } => {
14108 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14109 let buffer_id = buffer.read(cx).remote_id();
14110 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14111 if let Some(project) = &self.project {
14112 get_uncommitted_diff_for_buffer(
14113 project,
14114 [buffer.clone()],
14115 self.buffer.clone(),
14116 cx,
14117 );
14118 }
14119 }
14120 cx.emit(EditorEvent::ExcerptsAdded {
14121 buffer: buffer.clone(),
14122 predecessor: *predecessor,
14123 excerpts: excerpts.clone(),
14124 });
14125 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14126 }
14127 multi_buffer::Event::ExcerptsRemoved { ids } => {
14128 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14129 let buffer = self.buffer.read(cx);
14130 self.registered_buffers
14131 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14132 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14133 }
14134 multi_buffer::Event::ExcerptsEdited { ids } => {
14135 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14136 }
14137 multi_buffer::Event::ExcerptsExpanded { ids } => {
14138 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14139 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14140 }
14141 multi_buffer::Event::Reparsed(buffer_id) => {
14142 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14143
14144 cx.emit(EditorEvent::Reparsed(*buffer_id));
14145 }
14146 multi_buffer::Event::DiffHunksToggled => {
14147 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14148 }
14149 multi_buffer::Event::LanguageChanged(buffer_id) => {
14150 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14151 cx.emit(EditorEvent::Reparsed(*buffer_id));
14152 cx.notify();
14153 }
14154 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14155 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14156 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14157 cx.emit(EditorEvent::TitleChanged)
14158 }
14159 // multi_buffer::Event::DiffBaseChanged => {
14160 // self.scrollbar_marker_state.dirty = true;
14161 // cx.emit(EditorEvent::DiffBaseChanged);
14162 // cx.notify();
14163 // }
14164 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14165 multi_buffer::Event::DiagnosticsUpdated => {
14166 self.refresh_active_diagnostics(cx);
14167 self.scrollbar_marker_state.dirty = true;
14168 cx.notify();
14169 }
14170 _ => {}
14171 };
14172 }
14173
14174 fn on_display_map_changed(
14175 &mut self,
14176 _: Entity<DisplayMap>,
14177 _: &mut Window,
14178 cx: &mut Context<Self>,
14179 ) {
14180 cx.notify();
14181 }
14182
14183 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14184 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14185 self.refresh_inline_completion(true, false, window, cx);
14186 self.refresh_inlay_hints(
14187 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14188 self.selections.newest_anchor().head(),
14189 &self.buffer.read(cx).snapshot(cx),
14190 cx,
14191 )),
14192 cx,
14193 );
14194
14195 let old_cursor_shape = self.cursor_shape;
14196
14197 {
14198 let editor_settings = EditorSettings::get_global(cx);
14199 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14200 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14201 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14202 }
14203
14204 if old_cursor_shape != self.cursor_shape {
14205 cx.emit(EditorEvent::CursorShapeChanged);
14206 }
14207
14208 let project_settings = ProjectSettings::get_global(cx);
14209 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14210
14211 if self.mode == EditorMode::Full {
14212 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14213 if self.git_blame_inline_enabled != inline_blame_enabled {
14214 self.toggle_git_blame_inline_internal(false, window, cx);
14215 }
14216 }
14217
14218 cx.notify();
14219 }
14220
14221 pub fn set_searchable(&mut self, searchable: bool) {
14222 self.searchable = searchable;
14223 }
14224
14225 pub fn searchable(&self) -> bool {
14226 self.searchable
14227 }
14228
14229 fn open_proposed_changes_editor(
14230 &mut self,
14231 _: &OpenProposedChangesEditor,
14232 window: &mut Window,
14233 cx: &mut Context<Self>,
14234 ) {
14235 let Some(workspace) = self.workspace() else {
14236 cx.propagate();
14237 return;
14238 };
14239
14240 let selections = self.selections.all::<usize>(cx);
14241 let multi_buffer = self.buffer.read(cx);
14242 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14243 let mut new_selections_by_buffer = HashMap::default();
14244 for selection in selections {
14245 for (buffer, range, _) in
14246 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14247 {
14248 let mut range = range.to_point(buffer);
14249 range.start.column = 0;
14250 range.end.column = buffer.line_len(range.end.row);
14251 new_selections_by_buffer
14252 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14253 .or_insert(Vec::new())
14254 .push(range)
14255 }
14256 }
14257
14258 let proposed_changes_buffers = new_selections_by_buffer
14259 .into_iter()
14260 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14261 .collect::<Vec<_>>();
14262 let proposed_changes_editor = cx.new(|cx| {
14263 ProposedChangesEditor::new(
14264 "Proposed changes",
14265 proposed_changes_buffers,
14266 self.project.clone(),
14267 window,
14268 cx,
14269 )
14270 });
14271
14272 window.defer(cx, move |window, cx| {
14273 workspace.update(cx, |workspace, cx| {
14274 workspace.active_pane().update(cx, |pane, cx| {
14275 pane.add_item(
14276 Box::new(proposed_changes_editor),
14277 true,
14278 true,
14279 None,
14280 window,
14281 cx,
14282 );
14283 });
14284 });
14285 });
14286 }
14287
14288 pub fn open_excerpts_in_split(
14289 &mut self,
14290 _: &OpenExcerptsSplit,
14291 window: &mut Window,
14292 cx: &mut Context<Self>,
14293 ) {
14294 self.open_excerpts_common(None, true, window, cx)
14295 }
14296
14297 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14298 self.open_excerpts_common(None, false, window, cx)
14299 }
14300
14301 fn open_excerpts_common(
14302 &mut self,
14303 jump_data: Option<JumpData>,
14304 split: bool,
14305 window: &mut Window,
14306 cx: &mut Context<Self>,
14307 ) {
14308 let Some(workspace) = self.workspace() else {
14309 cx.propagate();
14310 return;
14311 };
14312
14313 if self.buffer.read(cx).is_singleton() {
14314 cx.propagate();
14315 return;
14316 }
14317
14318 let mut new_selections_by_buffer = HashMap::default();
14319 match &jump_data {
14320 Some(JumpData::MultiBufferPoint {
14321 excerpt_id,
14322 position,
14323 anchor,
14324 line_offset_from_top,
14325 }) => {
14326 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14327 if let Some(buffer) = multi_buffer_snapshot
14328 .buffer_id_for_excerpt(*excerpt_id)
14329 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14330 {
14331 let buffer_snapshot = buffer.read(cx).snapshot();
14332 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14333 language::ToPoint::to_point(anchor, &buffer_snapshot)
14334 } else {
14335 buffer_snapshot.clip_point(*position, Bias::Left)
14336 };
14337 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14338 new_selections_by_buffer.insert(
14339 buffer,
14340 (
14341 vec![jump_to_offset..jump_to_offset],
14342 Some(*line_offset_from_top),
14343 ),
14344 );
14345 }
14346 }
14347 Some(JumpData::MultiBufferRow {
14348 row,
14349 line_offset_from_top,
14350 }) => {
14351 let point = MultiBufferPoint::new(row.0, 0);
14352 if let Some((buffer, buffer_point, _)) =
14353 self.buffer.read(cx).point_to_buffer_point(point, cx)
14354 {
14355 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14356 new_selections_by_buffer
14357 .entry(buffer)
14358 .or_insert((Vec::new(), Some(*line_offset_from_top)))
14359 .0
14360 .push(buffer_offset..buffer_offset)
14361 }
14362 }
14363 None => {
14364 let selections = self.selections.all::<usize>(cx);
14365 let multi_buffer = self.buffer.read(cx);
14366 for selection in selections {
14367 for (buffer, mut range, _) in multi_buffer
14368 .snapshot(cx)
14369 .range_to_buffer_ranges(selection.range())
14370 {
14371 // When editing branch buffers, jump to the corresponding location
14372 // in their base buffer.
14373 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14374 let buffer = buffer_handle.read(cx);
14375 if let Some(base_buffer) = buffer.base_buffer() {
14376 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14377 buffer_handle = base_buffer;
14378 }
14379
14380 if selection.reversed {
14381 mem::swap(&mut range.start, &mut range.end);
14382 }
14383 new_selections_by_buffer
14384 .entry(buffer_handle)
14385 .or_insert((Vec::new(), None))
14386 .0
14387 .push(range)
14388 }
14389 }
14390 }
14391 }
14392
14393 if new_selections_by_buffer.is_empty() {
14394 return;
14395 }
14396
14397 // We defer the pane interaction because we ourselves are a workspace item
14398 // and activating a new item causes the pane to call a method on us reentrantly,
14399 // which panics if we're on the stack.
14400 window.defer(cx, move |window, cx| {
14401 workspace.update(cx, |workspace, cx| {
14402 let pane = if split {
14403 workspace.adjacent_pane(window, cx)
14404 } else {
14405 workspace.active_pane().clone()
14406 };
14407
14408 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14409 let editor = buffer
14410 .read(cx)
14411 .file()
14412 .is_none()
14413 .then(|| {
14414 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14415 // so `workspace.open_project_item` will never find them, always opening a new editor.
14416 // Instead, we try to activate the existing editor in the pane first.
14417 let (editor, pane_item_index) =
14418 pane.read(cx).items().enumerate().find_map(|(i, item)| {
14419 let editor = item.downcast::<Editor>()?;
14420 let singleton_buffer =
14421 editor.read(cx).buffer().read(cx).as_singleton()?;
14422 if singleton_buffer == buffer {
14423 Some((editor, i))
14424 } else {
14425 None
14426 }
14427 })?;
14428 pane.update(cx, |pane, cx| {
14429 pane.activate_item(pane_item_index, true, true, window, cx)
14430 });
14431 Some(editor)
14432 })
14433 .flatten()
14434 .unwrap_or_else(|| {
14435 workspace.open_project_item::<Self>(
14436 pane.clone(),
14437 buffer,
14438 true,
14439 true,
14440 window,
14441 cx,
14442 )
14443 });
14444
14445 editor.update(cx, |editor, cx| {
14446 let autoscroll = match scroll_offset {
14447 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14448 None => Autoscroll::newest(),
14449 };
14450 let nav_history = editor.nav_history.take();
14451 editor.change_selections(Some(autoscroll), window, cx, |s| {
14452 s.select_ranges(ranges);
14453 });
14454 editor.nav_history = nav_history;
14455 });
14456 }
14457 })
14458 });
14459 }
14460
14461 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14462 let snapshot = self.buffer.read(cx).read(cx);
14463 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14464 Some(
14465 ranges
14466 .iter()
14467 .map(move |range| {
14468 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14469 })
14470 .collect(),
14471 )
14472 }
14473
14474 fn selection_replacement_ranges(
14475 &self,
14476 range: Range<OffsetUtf16>,
14477 cx: &mut App,
14478 ) -> Vec<Range<OffsetUtf16>> {
14479 let selections = self.selections.all::<OffsetUtf16>(cx);
14480 let newest_selection = selections
14481 .iter()
14482 .max_by_key(|selection| selection.id)
14483 .unwrap();
14484 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14485 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14486 let snapshot = self.buffer.read(cx).read(cx);
14487 selections
14488 .into_iter()
14489 .map(|mut selection| {
14490 selection.start.0 =
14491 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14492 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14493 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14494 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14495 })
14496 .collect()
14497 }
14498
14499 fn report_editor_event(
14500 &self,
14501 event_type: &'static str,
14502 file_extension: Option<String>,
14503 cx: &App,
14504 ) {
14505 if cfg!(any(test, feature = "test-support")) {
14506 return;
14507 }
14508
14509 let Some(project) = &self.project else { return };
14510
14511 // If None, we are in a file without an extension
14512 let file = self
14513 .buffer
14514 .read(cx)
14515 .as_singleton()
14516 .and_then(|b| b.read(cx).file());
14517 let file_extension = file_extension.or(file
14518 .as_ref()
14519 .and_then(|file| Path::new(file.file_name(cx)).extension())
14520 .and_then(|e| e.to_str())
14521 .map(|a| a.to_string()));
14522
14523 let vim_mode = cx
14524 .global::<SettingsStore>()
14525 .raw_user_settings()
14526 .get("vim_mode")
14527 == Some(&serde_json::Value::Bool(true));
14528
14529 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14530 let copilot_enabled = edit_predictions_provider
14531 == language::language_settings::EditPredictionProvider::Copilot;
14532 let copilot_enabled_for_language = self
14533 .buffer
14534 .read(cx)
14535 .settings_at(0, cx)
14536 .show_edit_predictions;
14537
14538 let project = project.read(cx);
14539 telemetry::event!(
14540 event_type,
14541 file_extension,
14542 vim_mode,
14543 copilot_enabled,
14544 copilot_enabled_for_language,
14545 edit_predictions_provider,
14546 is_via_ssh = project.is_via_ssh(),
14547 );
14548 }
14549
14550 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14551 /// with each line being an array of {text, highlight} objects.
14552 fn copy_highlight_json(
14553 &mut self,
14554 _: &CopyHighlightJson,
14555 window: &mut Window,
14556 cx: &mut Context<Self>,
14557 ) {
14558 #[derive(Serialize)]
14559 struct Chunk<'a> {
14560 text: String,
14561 highlight: Option<&'a str>,
14562 }
14563
14564 let snapshot = self.buffer.read(cx).snapshot(cx);
14565 let range = self
14566 .selected_text_range(false, window, cx)
14567 .and_then(|selection| {
14568 if selection.range.is_empty() {
14569 None
14570 } else {
14571 Some(selection.range)
14572 }
14573 })
14574 .unwrap_or_else(|| 0..snapshot.len());
14575
14576 let chunks = snapshot.chunks(range, true);
14577 let mut lines = Vec::new();
14578 let mut line: VecDeque<Chunk> = VecDeque::new();
14579
14580 let Some(style) = self.style.as_ref() else {
14581 return;
14582 };
14583
14584 for chunk in chunks {
14585 let highlight = chunk
14586 .syntax_highlight_id
14587 .and_then(|id| id.name(&style.syntax));
14588 let mut chunk_lines = chunk.text.split('\n').peekable();
14589 while let Some(text) = chunk_lines.next() {
14590 let mut merged_with_last_token = false;
14591 if let Some(last_token) = line.back_mut() {
14592 if last_token.highlight == highlight {
14593 last_token.text.push_str(text);
14594 merged_with_last_token = true;
14595 }
14596 }
14597
14598 if !merged_with_last_token {
14599 line.push_back(Chunk {
14600 text: text.into(),
14601 highlight,
14602 });
14603 }
14604
14605 if chunk_lines.peek().is_some() {
14606 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14607 line.pop_front();
14608 }
14609 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14610 line.pop_back();
14611 }
14612
14613 lines.push(mem::take(&mut line));
14614 }
14615 }
14616 }
14617
14618 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14619 return;
14620 };
14621 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14622 }
14623
14624 pub fn open_context_menu(
14625 &mut self,
14626 _: &OpenContextMenu,
14627 window: &mut Window,
14628 cx: &mut Context<Self>,
14629 ) {
14630 self.request_autoscroll(Autoscroll::newest(), cx);
14631 let position = self.selections.newest_display(cx).start;
14632 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14633 }
14634
14635 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14636 &self.inlay_hint_cache
14637 }
14638
14639 pub fn replay_insert_event(
14640 &mut self,
14641 text: &str,
14642 relative_utf16_range: Option<Range<isize>>,
14643 window: &mut Window,
14644 cx: &mut Context<Self>,
14645 ) {
14646 if !self.input_enabled {
14647 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14648 return;
14649 }
14650 if let Some(relative_utf16_range) = relative_utf16_range {
14651 let selections = self.selections.all::<OffsetUtf16>(cx);
14652 self.change_selections(None, window, cx, |s| {
14653 let new_ranges = selections.into_iter().map(|range| {
14654 let start = OffsetUtf16(
14655 range
14656 .head()
14657 .0
14658 .saturating_add_signed(relative_utf16_range.start),
14659 );
14660 let end = OffsetUtf16(
14661 range
14662 .head()
14663 .0
14664 .saturating_add_signed(relative_utf16_range.end),
14665 );
14666 start..end
14667 });
14668 s.select_ranges(new_ranges);
14669 });
14670 }
14671
14672 self.handle_input(text, window, cx);
14673 }
14674
14675 pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14676 let Some(provider) = self.semantics_provider.as_ref() else {
14677 return false;
14678 };
14679
14680 let mut supports = false;
14681 self.buffer().read(cx).for_each_buffer(|buffer| {
14682 supports |= provider.supports_inlay_hints(buffer, cx);
14683 });
14684 supports
14685 }
14686
14687 pub fn is_focused(&self, window: &Window) -> bool {
14688 self.focus_handle.is_focused(window)
14689 }
14690
14691 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14692 cx.emit(EditorEvent::Focused);
14693
14694 if let Some(descendant) = self
14695 .last_focused_descendant
14696 .take()
14697 .and_then(|descendant| descendant.upgrade())
14698 {
14699 window.focus(&descendant);
14700 } else {
14701 if let Some(blame) = self.blame.as_ref() {
14702 blame.update(cx, GitBlame::focus)
14703 }
14704
14705 self.blink_manager.update(cx, BlinkManager::enable);
14706 self.show_cursor_names(window, cx);
14707 self.buffer.update(cx, |buffer, cx| {
14708 buffer.finalize_last_transaction(cx);
14709 if self.leader_peer_id.is_none() {
14710 buffer.set_active_selections(
14711 &self.selections.disjoint_anchors(),
14712 self.selections.line_mode,
14713 self.cursor_shape,
14714 cx,
14715 );
14716 }
14717 });
14718 }
14719 }
14720
14721 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14722 cx.emit(EditorEvent::FocusedIn)
14723 }
14724
14725 fn handle_focus_out(
14726 &mut self,
14727 event: FocusOutEvent,
14728 _window: &mut Window,
14729 _cx: &mut Context<Self>,
14730 ) {
14731 if event.blurred != self.focus_handle {
14732 self.last_focused_descendant = Some(event.blurred);
14733 }
14734 }
14735
14736 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14737 self.blink_manager.update(cx, BlinkManager::disable);
14738 self.buffer
14739 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14740
14741 if let Some(blame) = self.blame.as_ref() {
14742 blame.update(cx, GitBlame::blur)
14743 }
14744 if !self.hover_state.focused(window, cx) {
14745 hide_hover(self, cx);
14746 }
14747
14748 self.hide_context_menu(window, cx);
14749 self.discard_inline_completion(false, cx);
14750 cx.emit(EditorEvent::Blurred);
14751 cx.notify();
14752 }
14753
14754 pub fn register_action<A: Action>(
14755 &mut self,
14756 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14757 ) -> Subscription {
14758 let id = self.next_editor_action_id.post_inc();
14759 let listener = Arc::new(listener);
14760 self.editor_actions.borrow_mut().insert(
14761 id,
14762 Box::new(move |window, _| {
14763 let listener = listener.clone();
14764 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14765 let action = action.downcast_ref().unwrap();
14766 if phase == DispatchPhase::Bubble {
14767 listener(action, window, cx)
14768 }
14769 })
14770 }),
14771 );
14772
14773 let editor_actions = self.editor_actions.clone();
14774 Subscription::new(move || {
14775 editor_actions.borrow_mut().remove(&id);
14776 })
14777 }
14778
14779 pub fn file_header_size(&self) -> u32 {
14780 FILE_HEADER_HEIGHT
14781 }
14782
14783 pub fn revert(
14784 &mut self,
14785 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14786 window: &mut Window,
14787 cx: &mut Context<Self>,
14788 ) {
14789 self.buffer().update(cx, |multi_buffer, cx| {
14790 for (buffer_id, changes) in revert_changes {
14791 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14792 buffer.update(cx, |buffer, cx| {
14793 buffer.edit(
14794 changes.into_iter().map(|(range, text)| {
14795 (range, text.to_string().map(Arc::<str>::from))
14796 }),
14797 None,
14798 cx,
14799 );
14800 });
14801 }
14802 }
14803 });
14804 self.change_selections(None, window, cx, |selections| selections.refresh());
14805 }
14806
14807 pub fn to_pixel_point(
14808 &self,
14809 source: multi_buffer::Anchor,
14810 editor_snapshot: &EditorSnapshot,
14811 window: &mut Window,
14812 ) -> Option<gpui::Point<Pixels>> {
14813 let source_point = source.to_display_point(editor_snapshot);
14814 self.display_to_pixel_point(source_point, editor_snapshot, window)
14815 }
14816
14817 pub fn display_to_pixel_point(
14818 &self,
14819 source: DisplayPoint,
14820 editor_snapshot: &EditorSnapshot,
14821 window: &mut Window,
14822 ) -> Option<gpui::Point<Pixels>> {
14823 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14824 let text_layout_details = self.text_layout_details(window);
14825 let scroll_top = text_layout_details
14826 .scroll_anchor
14827 .scroll_position(editor_snapshot)
14828 .y;
14829
14830 if source.row().as_f32() < scroll_top.floor() {
14831 return None;
14832 }
14833 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14834 let source_y = line_height * (source.row().as_f32() - scroll_top);
14835 Some(gpui::Point::new(source_x, source_y))
14836 }
14837
14838 pub fn has_visible_completions_menu(&self) -> bool {
14839 !self.edit_prediction_preview_is_active()
14840 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14841 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14842 })
14843 }
14844
14845 pub fn register_addon<T: Addon>(&mut self, instance: T) {
14846 self.addons
14847 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14848 }
14849
14850 pub fn unregister_addon<T: Addon>(&mut self) {
14851 self.addons.remove(&std::any::TypeId::of::<T>());
14852 }
14853
14854 pub fn addon<T: Addon>(&self) -> Option<&T> {
14855 let type_id = std::any::TypeId::of::<T>();
14856 self.addons
14857 .get(&type_id)
14858 .and_then(|item| item.to_any().downcast_ref::<T>())
14859 }
14860
14861 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14862 let text_layout_details = self.text_layout_details(window);
14863 let style = &text_layout_details.editor_style;
14864 let font_id = window.text_system().resolve_font(&style.text.font());
14865 let font_size = style.text.font_size.to_pixels(window.rem_size());
14866 let line_height = style.text.line_height_in_pixels(window.rem_size());
14867 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14868
14869 gpui::Size::new(em_width, line_height)
14870 }
14871}
14872
14873fn get_uncommitted_diff_for_buffer(
14874 project: &Entity<Project>,
14875 buffers: impl IntoIterator<Item = Entity<Buffer>>,
14876 buffer: Entity<MultiBuffer>,
14877 cx: &mut App,
14878) {
14879 let mut tasks = Vec::new();
14880 project.update(cx, |project, cx| {
14881 for buffer in buffers {
14882 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14883 }
14884 });
14885 cx.spawn(|mut cx| async move {
14886 let diffs = futures::future::join_all(tasks).await;
14887 buffer
14888 .update(&mut cx, |buffer, cx| {
14889 for diff in diffs.into_iter().flatten() {
14890 buffer.add_diff(diff, cx);
14891 }
14892 })
14893 .ok();
14894 })
14895 .detach();
14896}
14897
14898fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14899 let tab_size = tab_size.get() as usize;
14900 let mut width = offset;
14901
14902 for ch in text.chars() {
14903 width += if ch == '\t' {
14904 tab_size - (width % tab_size)
14905 } else {
14906 1
14907 };
14908 }
14909
14910 width - offset
14911}
14912
14913#[cfg(test)]
14914mod tests {
14915 use super::*;
14916
14917 #[test]
14918 fn test_string_size_with_expanded_tabs() {
14919 let nz = |val| NonZeroU32::new(val).unwrap();
14920 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14921 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14922 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14923 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14924 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14925 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14926 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14927 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14928 }
14929}
14930
14931/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14932struct WordBreakingTokenizer<'a> {
14933 input: &'a str,
14934}
14935
14936impl<'a> WordBreakingTokenizer<'a> {
14937 fn new(input: &'a str) -> Self {
14938 Self { input }
14939 }
14940}
14941
14942fn is_char_ideographic(ch: char) -> bool {
14943 use unicode_script::Script::*;
14944 use unicode_script::UnicodeScript;
14945 matches!(ch.script(), Han | Tangut | Yi)
14946}
14947
14948fn is_grapheme_ideographic(text: &str) -> bool {
14949 text.chars().any(is_char_ideographic)
14950}
14951
14952fn is_grapheme_whitespace(text: &str) -> bool {
14953 text.chars().any(|x| x.is_whitespace())
14954}
14955
14956fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14957 text.chars().next().map_or(false, |ch| {
14958 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14959 })
14960}
14961
14962#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14963struct WordBreakToken<'a> {
14964 token: &'a str,
14965 grapheme_len: usize,
14966 is_whitespace: bool,
14967}
14968
14969impl<'a> Iterator for WordBreakingTokenizer<'a> {
14970 /// Yields a span, the count of graphemes in the token, and whether it was
14971 /// whitespace. Note that it also breaks at word boundaries.
14972 type Item = WordBreakToken<'a>;
14973
14974 fn next(&mut self) -> Option<Self::Item> {
14975 use unicode_segmentation::UnicodeSegmentation;
14976 if self.input.is_empty() {
14977 return None;
14978 }
14979
14980 let mut iter = self.input.graphemes(true).peekable();
14981 let mut offset = 0;
14982 let mut graphemes = 0;
14983 if let Some(first_grapheme) = iter.next() {
14984 let is_whitespace = is_grapheme_whitespace(first_grapheme);
14985 offset += first_grapheme.len();
14986 graphemes += 1;
14987 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14988 if let Some(grapheme) = iter.peek().copied() {
14989 if should_stay_with_preceding_ideograph(grapheme) {
14990 offset += grapheme.len();
14991 graphemes += 1;
14992 }
14993 }
14994 } else {
14995 let mut words = self.input[offset..].split_word_bound_indices().peekable();
14996 let mut next_word_bound = words.peek().copied();
14997 if next_word_bound.map_or(false, |(i, _)| i == 0) {
14998 next_word_bound = words.next();
14999 }
15000 while let Some(grapheme) = iter.peek().copied() {
15001 if next_word_bound.map_or(false, |(i, _)| i == offset) {
15002 break;
15003 };
15004 if is_grapheme_whitespace(grapheme) != is_whitespace {
15005 break;
15006 };
15007 offset += grapheme.len();
15008 graphemes += 1;
15009 iter.next();
15010 }
15011 }
15012 let token = &self.input[..offset];
15013 self.input = &self.input[offset..];
15014 if is_whitespace {
15015 Some(WordBreakToken {
15016 token: " ",
15017 grapheme_len: 1,
15018 is_whitespace: true,
15019 })
15020 } else {
15021 Some(WordBreakToken {
15022 token,
15023 grapheme_len: graphemes,
15024 is_whitespace: false,
15025 })
15026 }
15027 } else {
15028 None
15029 }
15030 }
15031}
15032
15033#[test]
15034fn test_word_breaking_tokenizer() {
15035 let tests: &[(&str, &[(&str, usize, bool)])] = &[
15036 ("", &[]),
15037 (" ", &[(" ", 1, true)]),
15038 ("Ʒ", &[("Ʒ", 1, false)]),
15039 ("Ǽ", &[("Ǽ", 1, false)]),
15040 ("⋑", &[("⋑", 1, false)]),
15041 ("⋑⋑", &[("⋑⋑", 2, false)]),
15042 (
15043 "原理,进而",
15044 &[
15045 ("原", 1, false),
15046 ("理,", 2, false),
15047 ("进", 1, false),
15048 ("而", 1, false),
15049 ],
15050 ),
15051 (
15052 "hello world",
15053 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15054 ),
15055 (
15056 "hello, world",
15057 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15058 ),
15059 (
15060 " hello world",
15061 &[
15062 (" ", 1, true),
15063 ("hello", 5, false),
15064 (" ", 1, true),
15065 ("world", 5, false),
15066 ],
15067 ),
15068 (
15069 "这是什么 \n 钢笔",
15070 &[
15071 ("这", 1, false),
15072 ("是", 1, false),
15073 ("什", 1, false),
15074 ("么", 1, false),
15075 (" ", 1, true),
15076 ("钢", 1, false),
15077 ("笔", 1, false),
15078 ],
15079 ),
15080 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15081 ];
15082
15083 for (input, result) in tests {
15084 assert_eq!(
15085 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15086 result
15087 .iter()
15088 .copied()
15089 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15090 token,
15091 grapheme_len,
15092 is_whitespace,
15093 })
15094 .collect::<Vec<_>>()
15095 );
15096 }
15097}
15098
15099fn wrap_with_prefix(
15100 line_prefix: String,
15101 unwrapped_text: String,
15102 wrap_column: usize,
15103 tab_size: NonZeroU32,
15104) -> String {
15105 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15106 let mut wrapped_text = String::new();
15107 let mut current_line = line_prefix.clone();
15108
15109 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15110 let mut current_line_len = line_prefix_len;
15111 for WordBreakToken {
15112 token,
15113 grapheme_len,
15114 is_whitespace,
15115 } in tokenizer
15116 {
15117 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15118 wrapped_text.push_str(current_line.trim_end());
15119 wrapped_text.push('\n');
15120 current_line.truncate(line_prefix.len());
15121 current_line_len = line_prefix_len;
15122 if !is_whitespace {
15123 current_line.push_str(token);
15124 current_line_len += grapheme_len;
15125 }
15126 } else if !is_whitespace {
15127 current_line.push_str(token);
15128 current_line_len += grapheme_len;
15129 } else if current_line_len != line_prefix_len {
15130 current_line.push(' ');
15131 current_line_len += 1;
15132 }
15133 }
15134
15135 if !current_line.is_empty() {
15136 wrapped_text.push_str(¤t_line);
15137 }
15138 wrapped_text
15139}
15140
15141#[test]
15142fn test_wrap_with_prefix() {
15143 assert_eq!(
15144 wrap_with_prefix(
15145 "# ".to_string(),
15146 "abcdefg".to_string(),
15147 4,
15148 NonZeroU32::new(4).unwrap()
15149 ),
15150 "# abcdefg"
15151 );
15152 assert_eq!(
15153 wrap_with_prefix(
15154 "".to_string(),
15155 "\thello world".to_string(),
15156 8,
15157 NonZeroU32::new(4).unwrap()
15158 ),
15159 "hello\nworld"
15160 );
15161 assert_eq!(
15162 wrap_with_prefix(
15163 "// ".to_string(),
15164 "xx \nyy zz aa bb cc".to_string(),
15165 12,
15166 NonZeroU32::new(4).unwrap()
15167 ),
15168 "// xx yy zz\n// aa bb cc"
15169 );
15170 assert_eq!(
15171 wrap_with_prefix(
15172 String::new(),
15173 "这是什么 \n 钢笔".to_string(),
15174 3,
15175 NonZeroU32::new(4).unwrap()
15176 ),
15177 "这是什\n么 钢\n笔"
15178 );
15179}
15180
15181pub trait CollaborationHub {
15182 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15183 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15184 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15185}
15186
15187impl CollaborationHub for Entity<Project> {
15188 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15189 self.read(cx).collaborators()
15190 }
15191
15192 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15193 self.read(cx).user_store().read(cx).participant_indices()
15194 }
15195
15196 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15197 let this = self.read(cx);
15198 let user_ids = this.collaborators().values().map(|c| c.user_id);
15199 this.user_store().read_with(cx, |user_store, cx| {
15200 user_store.participant_names(user_ids, cx)
15201 })
15202 }
15203}
15204
15205pub trait SemanticsProvider {
15206 fn hover(
15207 &self,
15208 buffer: &Entity<Buffer>,
15209 position: text::Anchor,
15210 cx: &mut App,
15211 ) -> Option<Task<Vec<project::Hover>>>;
15212
15213 fn inlay_hints(
15214 &self,
15215 buffer_handle: Entity<Buffer>,
15216 range: Range<text::Anchor>,
15217 cx: &mut App,
15218 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15219
15220 fn resolve_inlay_hint(
15221 &self,
15222 hint: InlayHint,
15223 buffer_handle: Entity<Buffer>,
15224 server_id: LanguageServerId,
15225 cx: &mut App,
15226 ) -> Option<Task<anyhow::Result<InlayHint>>>;
15227
15228 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
15229
15230 fn document_highlights(
15231 &self,
15232 buffer: &Entity<Buffer>,
15233 position: text::Anchor,
15234 cx: &mut App,
15235 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15236
15237 fn definitions(
15238 &self,
15239 buffer: &Entity<Buffer>,
15240 position: text::Anchor,
15241 kind: GotoDefinitionKind,
15242 cx: &mut App,
15243 ) -> Option<Task<Result<Vec<LocationLink>>>>;
15244
15245 fn range_for_rename(
15246 &self,
15247 buffer: &Entity<Buffer>,
15248 position: text::Anchor,
15249 cx: &mut App,
15250 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15251
15252 fn perform_rename(
15253 &self,
15254 buffer: &Entity<Buffer>,
15255 position: text::Anchor,
15256 new_name: String,
15257 cx: &mut App,
15258 ) -> Option<Task<Result<ProjectTransaction>>>;
15259}
15260
15261pub trait CompletionProvider {
15262 fn completions(
15263 &self,
15264 buffer: &Entity<Buffer>,
15265 buffer_position: text::Anchor,
15266 trigger: CompletionContext,
15267 window: &mut Window,
15268 cx: &mut Context<Editor>,
15269 ) -> Task<Result<Vec<Completion>>>;
15270
15271 fn resolve_completions(
15272 &self,
15273 buffer: Entity<Buffer>,
15274 completion_indices: Vec<usize>,
15275 completions: Rc<RefCell<Box<[Completion]>>>,
15276 cx: &mut Context<Editor>,
15277 ) -> Task<Result<bool>>;
15278
15279 fn apply_additional_edits_for_completion(
15280 &self,
15281 _buffer: Entity<Buffer>,
15282 _completions: Rc<RefCell<Box<[Completion]>>>,
15283 _completion_index: usize,
15284 _push_to_history: bool,
15285 _cx: &mut Context<Editor>,
15286 ) -> Task<Result<Option<language::Transaction>>> {
15287 Task::ready(Ok(None))
15288 }
15289
15290 fn is_completion_trigger(
15291 &self,
15292 buffer: &Entity<Buffer>,
15293 position: language::Anchor,
15294 text: &str,
15295 trigger_in_words: bool,
15296 cx: &mut Context<Editor>,
15297 ) -> bool;
15298
15299 fn sort_completions(&self) -> bool {
15300 true
15301 }
15302}
15303
15304pub trait CodeActionProvider {
15305 fn id(&self) -> Arc<str>;
15306
15307 fn code_actions(
15308 &self,
15309 buffer: &Entity<Buffer>,
15310 range: Range<text::Anchor>,
15311 window: &mut Window,
15312 cx: &mut App,
15313 ) -> Task<Result<Vec<CodeAction>>>;
15314
15315 fn apply_code_action(
15316 &self,
15317 buffer_handle: Entity<Buffer>,
15318 action: CodeAction,
15319 excerpt_id: ExcerptId,
15320 push_to_history: bool,
15321 window: &mut Window,
15322 cx: &mut App,
15323 ) -> Task<Result<ProjectTransaction>>;
15324}
15325
15326impl CodeActionProvider for Entity<Project> {
15327 fn id(&self) -> Arc<str> {
15328 "project".into()
15329 }
15330
15331 fn code_actions(
15332 &self,
15333 buffer: &Entity<Buffer>,
15334 range: Range<text::Anchor>,
15335 _window: &mut Window,
15336 cx: &mut App,
15337 ) -> Task<Result<Vec<CodeAction>>> {
15338 self.update(cx, |project, cx| {
15339 project.code_actions(buffer, range, None, cx)
15340 })
15341 }
15342
15343 fn apply_code_action(
15344 &self,
15345 buffer_handle: Entity<Buffer>,
15346 action: CodeAction,
15347 _excerpt_id: ExcerptId,
15348 push_to_history: bool,
15349 _window: &mut Window,
15350 cx: &mut App,
15351 ) -> Task<Result<ProjectTransaction>> {
15352 self.update(cx, |project, cx| {
15353 project.apply_code_action(buffer_handle, action, push_to_history, cx)
15354 })
15355 }
15356}
15357
15358fn snippet_completions(
15359 project: &Project,
15360 buffer: &Entity<Buffer>,
15361 buffer_position: text::Anchor,
15362 cx: &mut App,
15363) -> Task<Result<Vec<Completion>>> {
15364 let language = buffer.read(cx).language_at(buffer_position);
15365 let language_name = language.as_ref().map(|language| language.lsp_id());
15366 let snippet_store = project.snippets().read(cx);
15367 let snippets = snippet_store.snippets_for(language_name, cx);
15368
15369 if snippets.is_empty() {
15370 return Task::ready(Ok(vec![]));
15371 }
15372 let snapshot = buffer.read(cx).text_snapshot();
15373 let chars: String = snapshot
15374 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15375 .collect();
15376
15377 let scope = language.map(|language| language.default_scope());
15378 let executor = cx.background_executor().clone();
15379
15380 cx.background_executor().spawn(async move {
15381 let classifier = CharClassifier::new(scope).for_completion(true);
15382 let mut last_word = chars
15383 .chars()
15384 .take_while(|c| classifier.is_word(*c))
15385 .collect::<String>();
15386 last_word = last_word.chars().rev().collect();
15387
15388 if last_word.is_empty() {
15389 return Ok(vec![]);
15390 }
15391
15392 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15393 let to_lsp = |point: &text::Anchor| {
15394 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15395 point_to_lsp(end)
15396 };
15397 let lsp_end = to_lsp(&buffer_position);
15398
15399 let candidates = snippets
15400 .iter()
15401 .enumerate()
15402 .flat_map(|(ix, snippet)| {
15403 snippet
15404 .prefix
15405 .iter()
15406 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15407 })
15408 .collect::<Vec<StringMatchCandidate>>();
15409
15410 let mut matches = fuzzy::match_strings(
15411 &candidates,
15412 &last_word,
15413 last_word.chars().any(|c| c.is_uppercase()),
15414 100,
15415 &Default::default(),
15416 executor,
15417 )
15418 .await;
15419
15420 // Remove all candidates where the query's start does not match the start of any word in the candidate
15421 if let Some(query_start) = last_word.chars().next() {
15422 matches.retain(|string_match| {
15423 split_words(&string_match.string).any(|word| {
15424 // Check that the first codepoint of the word as lowercase matches the first
15425 // codepoint of the query as lowercase
15426 word.chars()
15427 .flat_map(|codepoint| codepoint.to_lowercase())
15428 .zip(query_start.to_lowercase())
15429 .all(|(word_cp, query_cp)| word_cp == query_cp)
15430 })
15431 });
15432 }
15433
15434 let matched_strings = matches
15435 .into_iter()
15436 .map(|m| m.string)
15437 .collect::<HashSet<_>>();
15438
15439 let result: Vec<Completion> = snippets
15440 .into_iter()
15441 .filter_map(|snippet| {
15442 let matching_prefix = snippet
15443 .prefix
15444 .iter()
15445 .find(|prefix| matched_strings.contains(*prefix))?;
15446 let start = as_offset - last_word.len();
15447 let start = snapshot.anchor_before(start);
15448 let range = start..buffer_position;
15449 let lsp_start = to_lsp(&start);
15450 let lsp_range = lsp::Range {
15451 start: lsp_start,
15452 end: lsp_end,
15453 };
15454 Some(Completion {
15455 old_range: range,
15456 new_text: snippet.body.clone(),
15457 resolved: false,
15458 label: CodeLabel {
15459 text: matching_prefix.clone(),
15460 runs: vec![],
15461 filter_range: 0..matching_prefix.len(),
15462 },
15463 server_id: LanguageServerId(usize::MAX),
15464 documentation: snippet
15465 .description
15466 .clone()
15467 .map(CompletionDocumentation::SingleLine),
15468 lsp_completion: lsp::CompletionItem {
15469 label: snippet.prefix.first().unwrap().clone(),
15470 kind: Some(CompletionItemKind::SNIPPET),
15471 label_details: snippet.description.as_ref().map(|description| {
15472 lsp::CompletionItemLabelDetails {
15473 detail: Some(description.clone()),
15474 description: None,
15475 }
15476 }),
15477 insert_text_format: Some(InsertTextFormat::SNIPPET),
15478 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15479 lsp::InsertReplaceEdit {
15480 new_text: snippet.body.clone(),
15481 insert: lsp_range,
15482 replace: lsp_range,
15483 },
15484 )),
15485 filter_text: Some(snippet.body.clone()),
15486 sort_text: Some(char::MAX.to_string()),
15487 ..Default::default()
15488 },
15489 confirm: None,
15490 })
15491 })
15492 .collect();
15493
15494 Ok(result)
15495 })
15496}
15497
15498impl CompletionProvider for Entity<Project> {
15499 fn completions(
15500 &self,
15501 buffer: &Entity<Buffer>,
15502 buffer_position: text::Anchor,
15503 options: CompletionContext,
15504 _window: &mut Window,
15505 cx: &mut Context<Editor>,
15506 ) -> Task<Result<Vec<Completion>>> {
15507 self.update(cx, |project, cx| {
15508 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15509 let project_completions = project.completions(buffer, buffer_position, options, cx);
15510 cx.background_executor().spawn(async move {
15511 let mut completions = project_completions.await?;
15512 let snippets_completions = snippets.await?;
15513 completions.extend(snippets_completions);
15514 Ok(completions)
15515 })
15516 })
15517 }
15518
15519 fn resolve_completions(
15520 &self,
15521 buffer: Entity<Buffer>,
15522 completion_indices: Vec<usize>,
15523 completions: Rc<RefCell<Box<[Completion]>>>,
15524 cx: &mut Context<Editor>,
15525 ) -> Task<Result<bool>> {
15526 self.update(cx, |project, cx| {
15527 project.lsp_store().update(cx, |lsp_store, cx| {
15528 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15529 })
15530 })
15531 }
15532
15533 fn apply_additional_edits_for_completion(
15534 &self,
15535 buffer: Entity<Buffer>,
15536 completions: Rc<RefCell<Box<[Completion]>>>,
15537 completion_index: usize,
15538 push_to_history: bool,
15539 cx: &mut Context<Editor>,
15540 ) -> Task<Result<Option<language::Transaction>>> {
15541 self.update(cx, |project, cx| {
15542 project.lsp_store().update(cx, |lsp_store, cx| {
15543 lsp_store.apply_additional_edits_for_completion(
15544 buffer,
15545 completions,
15546 completion_index,
15547 push_to_history,
15548 cx,
15549 )
15550 })
15551 })
15552 }
15553
15554 fn is_completion_trigger(
15555 &self,
15556 buffer: &Entity<Buffer>,
15557 position: language::Anchor,
15558 text: &str,
15559 trigger_in_words: bool,
15560 cx: &mut Context<Editor>,
15561 ) -> bool {
15562 let mut chars = text.chars();
15563 let char = if let Some(char) = chars.next() {
15564 char
15565 } else {
15566 return false;
15567 };
15568 if chars.next().is_some() {
15569 return false;
15570 }
15571
15572 let buffer = buffer.read(cx);
15573 let snapshot = buffer.snapshot();
15574 if !snapshot.settings_at(position, cx).show_completions_on_input {
15575 return false;
15576 }
15577 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15578 if trigger_in_words && classifier.is_word(char) {
15579 return true;
15580 }
15581
15582 buffer.completion_triggers().contains(text)
15583 }
15584}
15585
15586impl SemanticsProvider for Entity<Project> {
15587 fn hover(
15588 &self,
15589 buffer: &Entity<Buffer>,
15590 position: text::Anchor,
15591 cx: &mut App,
15592 ) -> Option<Task<Vec<project::Hover>>> {
15593 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15594 }
15595
15596 fn document_highlights(
15597 &self,
15598 buffer: &Entity<Buffer>,
15599 position: text::Anchor,
15600 cx: &mut App,
15601 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15602 Some(self.update(cx, |project, cx| {
15603 project.document_highlights(buffer, position, cx)
15604 }))
15605 }
15606
15607 fn definitions(
15608 &self,
15609 buffer: &Entity<Buffer>,
15610 position: text::Anchor,
15611 kind: GotoDefinitionKind,
15612 cx: &mut App,
15613 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15614 Some(self.update(cx, |project, cx| match kind {
15615 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15616 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15617 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15618 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15619 }))
15620 }
15621
15622 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15623 // TODO: make this work for remote projects
15624 self.read(cx)
15625 .language_servers_for_local_buffer(buffer.read(cx), cx)
15626 .any(
15627 |(_, server)| match server.capabilities().inlay_hint_provider {
15628 Some(lsp::OneOf::Left(enabled)) => enabled,
15629 Some(lsp::OneOf::Right(_)) => true,
15630 None => false,
15631 },
15632 )
15633 }
15634
15635 fn inlay_hints(
15636 &self,
15637 buffer_handle: Entity<Buffer>,
15638 range: Range<text::Anchor>,
15639 cx: &mut App,
15640 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15641 Some(self.update(cx, |project, cx| {
15642 project.inlay_hints(buffer_handle, range, cx)
15643 }))
15644 }
15645
15646 fn resolve_inlay_hint(
15647 &self,
15648 hint: InlayHint,
15649 buffer_handle: Entity<Buffer>,
15650 server_id: LanguageServerId,
15651 cx: &mut App,
15652 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15653 Some(self.update(cx, |project, cx| {
15654 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15655 }))
15656 }
15657
15658 fn range_for_rename(
15659 &self,
15660 buffer: &Entity<Buffer>,
15661 position: text::Anchor,
15662 cx: &mut App,
15663 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15664 Some(self.update(cx, |project, cx| {
15665 let buffer = buffer.clone();
15666 let task = project.prepare_rename(buffer.clone(), position, cx);
15667 cx.spawn(|_, mut cx| async move {
15668 Ok(match task.await? {
15669 PrepareRenameResponse::Success(range) => Some(range),
15670 PrepareRenameResponse::InvalidPosition => None,
15671 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15672 // Fallback on using TreeSitter info to determine identifier range
15673 buffer.update(&mut cx, |buffer, _| {
15674 let snapshot = buffer.snapshot();
15675 let (range, kind) = snapshot.surrounding_word(position);
15676 if kind != Some(CharKind::Word) {
15677 return None;
15678 }
15679 Some(
15680 snapshot.anchor_before(range.start)
15681 ..snapshot.anchor_after(range.end),
15682 )
15683 })?
15684 }
15685 })
15686 })
15687 }))
15688 }
15689
15690 fn perform_rename(
15691 &self,
15692 buffer: &Entity<Buffer>,
15693 position: text::Anchor,
15694 new_name: String,
15695 cx: &mut App,
15696 ) -> Option<Task<Result<ProjectTransaction>>> {
15697 Some(self.update(cx, |project, cx| {
15698 project.perform_rename(buffer.clone(), position, new_name, cx)
15699 }))
15700 }
15701}
15702
15703fn inlay_hint_settings(
15704 location: Anchor,
15705 snapshot: &MultiBufferSnapshot,
15706 cx: &mut Context<Editor>,
15707) -> InlayHintSettings {
15708 let file = snapshot.file_at(location);
15709 let language = snapshot.language_at(location).map(|l| l.name());
15710 language_settings(language, file, cx).inlay_hints
15711}
15712
15713fn consume_contiguous_rows(
15714 contiguous_row_selections: &mut Vec<Selection<Point>>,
15715 selection: &Selection<Point>,
15716 display_map: &DisplaySnapshot,
15717 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15718) -> (MultiBufferRow, MultiBufferRow) {
15719 contiguous_row_selections.push(selection.clone());
15720 let start_row = MultiBufferRow(selection.start.row);
15721 let mut end_row = ending_row(selection, display_map);
15722
15723 while let Some(next_selection) = selections.peek() {
15724 if next_selection.start.row <= end_row.0 {
15725 end_row = ending_row(next_selection, display_map);
15726 contiguous_row_selections.push(selections.next().unwrap().clone());
15727 } else {
15728 break;
15729 }
15730 }
15731 (start_row, end_row)
15732}
15733
15734fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15735 if next_selection.end.column > 0 || next_selection.is_empty() {
15736 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15737 } else {
15738 MultiBufferRow(next_selection.end.row)
15739 }
15740}
15741
15742impl EditorSnapshot {
15743 pub fn remote_selections_in_range<'a>(
15744 &'a self,
15745 range: &'a Range<Anchor>,
15746 collaboration_hub: &dyn CollaborationHub,
15747 cx: &'a App,
15748 ) -> impl 'a + Iterator<Item = RemoteSelection> {
15749 let participant_names = collaboration_hub.user_names(cx);
15750 let participant_indices = collaboration_hub.user_participant_indices(cx);
15751 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15752 let collaborators_by_replica_id = collaborators_by_peer_id
15753 .iter()
15754 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15755 .collect::<HashMap<_, _>>();
15756 self.buffer_snapshot
15757 .selections_in_range(range, false)
15758 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15759 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15760 let participant_index = participant_indices.get(&collaborator.user_id).copied();
15761 let user_name = participant_names.get(&collaborator.user_id).cloned();
15762 Some(RemoteSelection {
15763 replica_id,
15764 selection,
15765 cursor_shape,
15766 line_mode,
15767 participant_index,
15768 peer_id: collaborator.peer_id,
15769 user_name,
15770 })
15771 })
15772 }
15773
15774 pub fn hunks_for_ranges(
15775 &self,
15776 ranges: impl Iterator<Item = Range<Point>>,
15777 ) -> Vec<MultiBufferDiffHunk> {
15778 let mut hunks = Vec::new();
15779 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15780 HashMap::default();
15781 for query_range in ranges {
15782 let query_rows =
15783 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15784 for hunk in self.buffer_snapshot.diff_hunks_in_range(
15785 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15786 ) {
15787 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15788 // when the caret is just above or just below the deleted hunk.
15789 let allow_adjacent = hunk.status().is_removed();
15790 let related_to_selection = if allow_adjacent {
15791 hunk.row_range.overlaps(&query_rows)
15792 || hunk.row_range.start == query_rows.end
15793 || hunk.row_range.end == query_rows.start
15794 } else {
15795 hunk.row_range.overlaps(&query_rows)
15796 };
15797 if related_to_selection {
15798 if !processed_buffer_rows
15799 .entry(hunk.buffer_id)
15800 .or_default()
15801 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15802 {
15803 continue;
15804 }
15805 hunks.push(hunk);
15806 }
15807 }
15808 }
15809
15810 hunks
15811 }
15812
15813 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15814 self.display_snapshot.buffer_snapshot.language_at(position)
15815 }
15816
15817 pub fn is_focused(&self) -> bool {
15818 self.is_focused
15819 }
15820
15821 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15822 self.placeholder_text.as_ref()
15823 }
15824
15825 pub fn scroll_position(&self) -> gpui::Point<f32> {
15826 self.scroll_anchor.scroll_position(&self.display_snapshot)
15827 }
15828
15829 fn gutter_dimensions(
15830 &self,
15831 font_id: FontId,
15832 font_size: Pixels,
15833 max_line_number_width: Pixels,
15834 cx: &App,
15835 ) -> Option<GutterDimensions> {
15836 if !self.show_gutter {
15837 return None;
15838 }
15839
15840 let descent = cx.text_system().descent(font_id, font_size);
15841 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15842 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15843
15844 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15845 matches!(
15846 ProjectSettings::get_global(cx).git.git_gutter,
15847 Some(GitGutterSetting::TrackedFiles)
15848 )
15849 });
15850 let gutter_settings = EditorSettings::get_global(cx).gutter;
15851 let show_line_numbers = self
15852 .show_line_numbers
15853 .unwrap_or(gutter_settings.line_numbers);
15854 let line_gutter_width = if show_line_numbers {
15855 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15856 let min_width_for_number_on_gutter = em_advance * 4.0;
15857 max_line_number_width.max(min_width_for_number_on_gutter)
15858 } else {
15859 0.0.into()
15860 };
15861
15862 let show_code_actions = self
15863 .show_code_actions
15864 .unwrap_or(gutter_settings.code_actions);
15865
15866 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15867
15868 let git_blame_entries_width =
15869 self.git_blame_gutter_max_author_length
15870 .map(|max_author_length| {
15871 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15872
15873 /// The number of characters to dedicate to gaps and margins.
15874 const SPACING_WIDTH: usize = 4;
15875
15876 let max_char_count = max_author_length
15877 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15878 + ::git::SHORT_SHA_LENGTH
15879 + MAX_RELATIVE_TIMESTAMP.len()
15880 + SPACING_WIDTH;
15881
15882 em_advance * max_char_count
15883 });
15884
15885 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15886 left_padding += if show_code_actions || show_runnables {
15887 em_width * 3.0
15888 } else if show_git_gutter && show_line_numbers {
15889 em_width * 2.0
15890 } else if show_git_gutter || show_line_numbers {
15891 em_width
15892 } else {
15893 px(0.)
15894 };
15895
15896 let right_padding = if gutter_settings.folds && show_line_numbers {
15897 em_width * 4.0
15898 } else if gutter_settings.folds {
15899 em_width * 3.0
15900 } else if show_line_numbers {
15901 em_width
15902 } else {
15903 px(0.)
15904 };
15905
15906 Some(GutterDimensions {
15907 left_padding,
15908 right_padding,
15909 width: line_gutter_width + left_padding + right_padding,
15910 margin: -descent,
15911 git_blame_entries_width,
15912 })
15913 }
15914
15915 pub fn render_crease_toggle(
15916 &self,
15917 buffer_row: MultiBufferRow,
15918 row_contains_cursor: bool,
15919 editor: Entity<Editor>,
15920 window: &mut Window,
15921 cx: &mut App,
15922 ) -> Option<AnyElement> {
15923 let folded = self.is_line_folded(buffer_row);
15924 let mut is_foldable = false;
15925
15926 if let Some(crease) = self
15927 .crease_snapshot
15928 .query_row(buffer_row, &self.buffer_snapshot)
15929 {
15930 is_foldable = true;
15931 match crease {
15932 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15933 if let Some(render_toggle) = render_toggle {
15934 let toggle_callback =
15935 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15936 if folded {
15937 editor.update(cx, |editor, cx| {
15938 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15939 });
15940 } else {
15941 editor.update(cx, |editor, cx| {
15942 editor.unfold_at(
15943 &crate::UnfoldAt { buffer_row },
15944 window,
15945 cx,
15946 )
15947 });
15948 }
15949 });
15950 return Some((render_toggle)(
15951 buffer_row,
15952 folded,
15953 toggle_callback,
15954 window,
15955 cx,
15956 ));
15957 }
15958 }
15959 }
15960 }
15961
15962 is_foldable |= self.starts_indent(buffer_row);
15963
15964 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15965 Some(
15966 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15967 .toggle_state(folded)
15968 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15969 if folded {
15970 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15971 } else {
15972 this.fold_at(&FoldAt { buffer_row }, window, cx);
15973 }
15974 }))
15975 .into_any_element(),
15976 )
15977 } else {
15978 None
15979 }
15980 }
15981
15982 pub fn render_crease_trailer(
15983 &self,
15984 buffer_row: MultiBufferRow,
15985 window: &mut Window,
15986 cx: &mut App,
15987 ) -> Option<AnyElement> {
15988 let folded = self.is_line_folded(buffer_row);
15989 if let Crease::Inline { render_trailer, .. } = self
15990 .crease_snapshot
15991 .query_row(buffer_row, &self.buffer_snapshot)?
15992 {
15993 let render_trailer = render_trailer.as_ref()?;
15994 Some(render_trailer(buffer_row, folded, window, cx))
15995 } else {
15996 None
15997 }
15998 }
15999}
16000
16001impl Deref for EditorSnapshot {
16002 type Target = DisplaySnapshot;
16003
16004 fn deref(&self) -> &Self::Target {
16005 &self.display_snapshot
16006 }
16007}
16008
16009#[derive(Clone, Debug, PartialEq, Eq)]
16010pub enum EditorEvent {
16011 InputIgnored {
16012 text: Arc<str>,
16013 },
16014 InputHandled {
16015 utf16_range_to_replace: Option<Range<isize>>,
16016 text: Arc<str>,
16017 },
16018 ExcerptsAdded {
16019 buffer: Entity<Buffer>,
16020 predecessor: ExcerptId,
16021 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16022 },
16023 ExcerptsRemoved {
16024 ids: Vec<ExcerptId>,
16025 },
16026 BufferFoldToggled {
16027 ids: Vec<ExcerptId>,
16028 folded: bool,
16029 },
16030 ExcerptsEdited {
16031 ids: Vec<ExcerptId>,
16032 },
16033 ExcerptsExpanded {
16034 ids: Vec<ExcerptId>,
16035 },
16036 BufferEdited,
16037 Edited {
16038 transaction_id: clock::Lamport,
16039 },
16040 Reparsed(BufferId),
16041 Focused,
16042 FocusedIn,
16043 Blurred,
16044 DirtyChanged,
16045 Saved,
16046 TitleChanged,
16047 DiffBaseChanged,
16048 SelectionsChanged {
16049 local: bool,
16050 },
16051 ScrollPositionChanged {
16052 local: bool,
16053 autoscroll: bool,
16054 },
16055 Closed,
16056 TransactionUndone {
16057 transaction_id: clock::Lamport,
16058 },
16059 TransactionBegun {
16060 transaction_id: clock::Lamport,
16061 },
16062 Reloaded,
16063 CursorShapeChanged,
16064}
16065
16066impl EventEmitter<EditorEvent> for Editor {}
16067
16068impl Focusable for Editor {
16069 fn focus_handle(&self, _cx: &App) -> FocusHandle {
16070 self.focus_handle.clone()
16071 }
16072}
16073
16074impl Render for Editor {
16075 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16076 let settings = ThemeSettings::get_global(cx);
16077
16078 let mut text_style = match self.mode {
16079 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16080 color: cx.theme().colors().editor_foreground,
16081 font_family: settings.ui_font.family.clone(),
16082 font_features: settings.ui_font.features.clone(),
16083 font_fallbacks: settings.ui_font.fallbacks.clone(),
16084 font_size: rems(0.875).into(),
16085 font_weight: settings.ui_font.weight,
16086 line_height: relative(settings.buffer_line_height.value()),
16087 ..Default::default()
16088 },
16089 EditorMode::Full => TextStyle {
16090 color: cx.theme().colors().editor_foreground,
16091 font_family: settings.buffer_font.family.clone(),
16092 font_features: settings.buffer_font.features.clone(),
16093 font_fallbacks: settings.buffer_font.fallbacks.clone(),
16094 font_size: settings.buffer_font_size().into(),
16095 font_weight: settings.buffer_font.weight,
16096 line_height: relative(settings.buffer_line_height.value()),
16097 ..Default::default()
16098 },
16099 };
16100 if let Some(text_style_refinement) = &self.text_style_refinement {
16101 text_style.refine(text_style_refinement)
16102 }
16103
16104 let background = match self.mode {
16105 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16106 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16107 EditorMode::Full => cx.theme().colors().editor_background,
16108 };
16109
16110 EditorElement::new(
16111 &cx.entity(),
16112 EditorStyle {
16113 background,
16114 local_player: cx.theme().players().local(),
16115 text: text_style,
16116 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16117 syntax: cx.theme().syntax().clone(),
16118 status: cx.theme().status().clone(),
16119 inlay_hints_style: make_inlay_hints_style(cx),
16120 inline_completion_styles: make_suggestion_styles(cx),
16121 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16122 },
16123 )
16124 }
16125}
16126
16127impl EntityInputHandler for Editor {
16128 fn text_for_range(
16129 &mut self,
16130 range_utf16: Range<usize>,
16131 adjusted_range: &mut Option<Range<usize>>,
16132 _: &mut Window,
16133 cx: &mut Context<Self>,
16134 ) -> Option<String> {
16135 let snapshot = self.buffer.read(cx).read(cx);
16136 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16137 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16138 if (start.0..end.0) != range_utf16 {
16139 adjusted_range.replace(start.0..end.0);
16140 }
16141 Some(snapshot.text_for_range(start..end).collect())
16142 }
16143
16144 fn selected_text_range(
16145 &mut self,
16146 ignore_disabled_input: bool,
16147 _: &mut Window,
16148 cx: &mut Context<Self>,
16149 ) -> Option<UTF16Selection> {
16150 // Prevent the IME menu from appearing when holding down an alphabetic key
16151 // while input is disabled.
16152 if !ignore_disabled_input && !self.input_enabled {
16153 return None;
16154 }
16155
16156 let selection = self.selections.newest::<OffsetUtf16>(cx);
16157 let range = selection.range();
16158
16159 Some(UTF16Selection {
16160 range: range.start.0..range.end.0,
16161 reversed: selection.reversed,
16162 })
16163 }
16164
16165 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16166 let snapshot = self.buffer.read(cx).read(cx);
16167 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16168 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16169 }
16170
16171 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16172 self.clear_highlights::<InputComposition>(cx);
16173 self.ime_transaction.take();
16174 }
16175
16176 fn replace_text_in_range(
16177 &mut self,
16178 range_utf16: Option<Range<usize>>,
16179 text: &str,
16180 window: &mut Window,
16181 cx: &mut Context<Self>,
16182 ) {
16183 if !self.input_enabled {
16184 cx.emit(EditorEvent::InputIgnored { text: text.into() });
16185 return;
16186 }
16187
16188 self.transact(window, cx, |this, window, cx| {
16189 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16190 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16191 Some(this.selection_replacement_ranges(range_utf16, cx))
16192 } else {
16193 this.marked_text_ranges(cx)
16194 };
16195
16196 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16197 let newest_selection_id = this.selections.newest_anchor().id;
16198 this.selections
16199 .all::<OffsetUtf16>(cx)
16200 .iter()
16201 .zip(ranges_to_replace.iter())
16202 .find_map(|(selection, range)| {
16203 if selection.id == newest_selection_id {
16204 Some(
16205 (range.start.0 as isize - selection.head().0 as isize)
16206 ..(range.end.0 as isize - selection.head().0 as isize),
16207 )
16208 } else {
16209 None
16210 }
16211 })
16212 });
16213
16214 cx.emit(EditorEvent::InputHandled {
16215 utf16_range_to_replace: range_to_replace,
16216 text: text.into(),
16217 });
16218
16219 if let Some(new_selected_ranges) = new_selected_ranges {
16220 this.change_selections(None, window, cx, |selections| {
16221 selections.select_ranges(new_selected_ranges)
16222 });
16223 this.backspace(&Default::default(), window, cx);
16224 }
16225
16226 this.handle_input(text, window, cx);
16227 });
16228
16229 if let Some(transaction) = self.ime_transaction {
16230 self.buffer.update(cx, |buffer, cx| {
16231 buffer.group_until_transaction(transaction, cx);
16232 });
16233 }
16234
16235 self.unmark_text(window, cx);
16236 }
16237
16238 fn replace_and_mark_text_in_range(
16239 &mut self,
16240 range_utf16: Option<Range<usize>>,
16241 text: &str,
16242 new_selected_range_utf16: Option<Range<usize>>,
16243 window: &mut Window,
16244 cx: &mut Context<Self>,
16245 ) {
16246 if !self.input_enabled {
16247 return;
16248 }
16249
16250 let transaction = self.transact(window, cx, |this, window, cx| {
16251 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16252 let snapshot = this.buffer.read(cx).read(cx);
16253 if let Some(relative_range_utf16) = range_utf16.as_ref() {
16254 for marked_range in &mut marked_ranges {
16255 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16256 marked_range.start.0 += relative_range_utf16.start;
16257 marked_range.start =
16258 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16259 marked_range.end =
16260 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16261 }
16262 }
16263 Some(marked_ranges)
16264 } else if let Some(range_utf16) = range_utf16 {
16265 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16266 Some(this.selection_replacement_ranges(range_utf16, cx))
16267 } else {
16268 None
16269 };
16270
16271 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16272 let newest_selection_id = this.selections.newest_anchor().id;
16273 this.selections
16274 .all::<OffsetUtf16>(cx)
16275 .iter()
16276 .zip(ranges_to_replace.iter())
16277 .find_map(|(selection, range)| {
16278 if selection.id == newest_selection_id {
16279 Some(
16280 (range.start.0 as isize - selection.head().0 as isize)
16281 ..(range.end.0 as isize - selection.head().0 as isize),
16282 )
16283 } else {
16284 None
16285 }
16286 })
16287 });
16288
16289 cx.emit(EditorEvent::InputHandled {
16290 utf16_range_to_replace: range_to_replace,
16291 text: text.into(),
16292 });
16293
16294 if let Some(ranges) = ranges_to_replace {
16295 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16296 }
16297
16298 let marked_ranges = {
16299 let snapshot = this.buffer.read(cx).read(cx);
16300 this.selections
16301 .disjoint_anchors()
16302 .iter()
16303 .map(|selection| {
16304 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16305 })
16306 .collect::<Vec<_>>()
16307 };
16308
16309 if text.is_empty() {
16310 this.unmark_text(window, cx);
16311 } else {
16312 this.highlight_text::<InputComposition>(
16313 marked_ranges.clone(),
16314 HighlightStyle {
16315 underline: Some(UnderlineStyle {
16316 thickness: px(1.),
16317 color: None,
16318 wavy: false,
16319 }),
16320 ..Default::default()
16321 },
16322 cx,
16323 );
16324 }
16325
16326 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16327 let use_autoclose = this.use_autoclose;
16328 let use_auto_surround = this.use_auto_surround;
16329 this.set_use_autoclose(false);
16330 this.set_use_auto_surround(false);
16331 this.handle_input(text, window, cx);
16332 this.set_use_autoclose(use_autoclose);
16333 this.set_use_auto_surround(use_auto_surround);
16334
16335 if let Some(new_selected_range) = new_selected_range_utf16 {
16336 let snapshot = this.buffer.read(cx).read(cx);
16337 let new_selected_ranges = marked_ranges
16338 .into_iter()
16339 .map(|marked_range| {
16340 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16341 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16342 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16343 snapshot.clip_offset_utf16(new_start, Bias::Left)
16344 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16345 })
16346 .collect::<Vec<_>>();
16347
16348 drop(snapshot);
16349 this.change_selections(None, window, cx, |selections| {
16350 selections.select_ranges(new_selected_ranges)
16351 });
16352 }
16353 });
16354
16355 self.ime_transaction = self.ime_transaction.or(transaction);
16356 if let Some(transaction) = self.ime_transaction {
16357 self.buffer.update(cx, |buffer, cx| {
16358 buffer.group_until_transaction(transaction, cx);
16359 });
16360 }
16361
16362 if self.text_highlights::<InputComposition>(cx).is_none() {
16363 self.ime_transaction.take();
16364 }
16365 }
16366
16367 fn bounds_for_range(
16368 &mut self,
16369 range_utf16: Range<usize>,
16370 element_bounds: gpui::Bounds<Pixels>,
16371 window: &mut Window,
16372 cx: &mut Context<Self>,
16373 ) -> Option<gpui::Bounds<Pixels>> {
16374 let text_layout_details = self.text_layout_details(window);
16375 let gpui::Size {
16376 width: em_width,
16377 height: line_height,
16378 } = self.character_size(window);
16379
16380 let snapshot = self.snapshot(window, cx);
16381 let scroll_position = snapshot.scroll_position();
16382 let scroll_left = scroll_position.x * em_width;
16383
16384 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16385 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16386 + self.gutter_dimensions.width
16387 + self.gutter_dimensions.margin;
16388 let y = line_height * (start.row().as_f32() - scroll_position.y);
16389
16390 Some(Bounds {
16391 origin: element_bounds.origin + point(x, y),
16392 size: size(em_width, line_height),
16393 })
16394 }
16395
16396 fn character_index_for_point(
16397 &mut self,
16398 point: gpui::Point<Pixels>,
16399 _window: &mut Window,
16400 _cx: &mut Context<Self>,
16401 ) -> Option<usize> {
16402 let position_map = self.last_position_map.as_ref()?;
16403 if !position_map.text_hitbox.contains(&point) {
16404 return None;
16405 }
16406 let display_point = position_map.point_for_position(point).previous_valid;
16407 let anchor = position_map
16408 .snapshot
16409 .display_point_to_anchor(display_point, Bias::Left);
16410 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16411 Some(utf16_offset.0)
16412 }
16413}
16414
16415trait SelectionExt {
16416 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16417 fn spanned_rows(
16418 &self,
16419 include_end_if_at_line_start: bool,
16420 map: &DisplaySnapshot,
16421 ) -> Range<MultiBufferRow>;
16422}
16423
16424impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16425 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16426 let start = self
16427 .start
16428 .to_point(&map.buffer_snapshot)
16429 .to_display_point(map);
16430 let end = self
16431 .end
16432 .to_point(&map.buffer_snapshot)
16433 .to_display_point(map);
16434 if self.reversed {
16435 end..start
16436 } else {
16437 start..end
16438 }
16439 }
16440
16441 fn spanned_rows(
16442 &self,
16443 include_end_if_at_line_start: bool,
16444 map: &DisplaySnapshot,
16445 ) -> Range<MultiBufferRow> {
16446 let start = self.start.to_point(&map.buffer_snapshot);
16447 let mut end = self.end.to_point(&map.buffer_snapshot);
16448 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16449 end.row -= 1;
16450 }
16451
16452 let buffer_start = map.prev_line_boundary(start).0;
16453 let buffer_end = map.next_line_boundary(end).0;
16454 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16455 }
16456}
16457
16458impl<T: InvalidationRegion> InvalidationStack<T> {
16459 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16460 where
16461 S: Clone + ToOffset,
16462 {
16463 while let Some(region) = self.last() {
16464 let all_selections_inside_invalidation_ranges =
16465 if selections.len() == region.ranges().len() {
16466 selections
16467 .iter()
16468 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16469 .all(|(selection, invalidation_range)| {
16470 let head = selection.head().to_offset(buffer);
16471 invalidation_range.start <= head && invalidation_range.end >= head
16472 })
16473 } else {
16474 false
16475 };
16476
16477 if all_selections_inside_invalidation_ranges {
16478 break;
16479 } else {
16480 self.pop();
16481 }
16482 }
16483 }
16484}
16485
16486impl<T> Default for InvalidationStack<T> {
16487 fn default() -> Self {
16488 Self(Default::default())
16489 }
16490}
16491
16492impl<T> Deref for InvalidationStack<T> {
16493 type Target = Vec<T>;
16494
16495 fn deref(&self) -> &Self::Target {
16496 &self.0
16497 }
16498}
16499
16500impl<T> DerefMut for InvalidationStack<T> {
16501 fn deref_mut(&mut self) -> &mut Self::Target {
16502 &mut self.0
16503 }
16504}
16505
16506impl InvalidationRegion for SnippetState {
16507 fn ranges(&self) -> &[Range<Anchor>] {
16508 &self.ranges[self.active_index]
16509 }
16510}
16511
16512pub fn diagnostic_block_renderer(
16513 diagnostic: Diagnostic,
16514 max_message_rows: Option<u8>,
16515 allow_closing: bool,
16516 _is_valid: bool,
16517) -> RenderBlock {
16518 let (text_without_backticks, code_ranges) =
16519 highlight_diagnostic_message(&diagnostic, max_message_rows);
16520
16521 Arc::new(move |cx: &mut BlockContext| {
16522 let group_id: SharedString = cx.block_id.to_string().into();
16523
16524 let mut text_style = cx.window.text_style().clone();
16525 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16526 let theme_settings = ThemeSettings::get_global(cx);
16527 text_style.font_family = theme_settings.buffer_font.family.clone();
16528 text_style.font_style = theme_settings.buffer_font.style;
16529 text_style.font_features = theme_settings.buffer_font.features.clone();
16530 text_style.font_weight = theme_settings.buffer_font.weight;
16531
16532 let multi_line_diagnostic = diagnostic.message.contains('\n');
16533
16534 let buttons = |diagnostic: &Diagnostic| {
16535 if multi_line_diagnostic {
16536 v_flex()
16537 } else {
16538 h_flex()
16539 }
16540 .when(allow_closing, |div| {
16541 div.children(diagnostic.is_primary.then(|| {
16542 IconButton::new("close-block", IconName::XCircle)
16543 .icon_color(Color::Muted)
16544 .size(ButtonSize::Compact)
16545 .style(ButtonStyle::Transparent)
16546 .visible_on_hover(group_id.clone())
16547 .on_click(move |_click, window, cx| {
16548 window.dispatch_action(Box::new(Cancel), cx)
16549 })
16550 .tooltip(|window, cx| {
16551 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16552 })
16553 }))
16554 })
16555 .child(
16556 IconButton::new("copy-block", IconName::Copy)
16557 .icon_color(Color::Muted)
16558 .size(ButtonSize::Compact)
16559 .style(ButtonStyle::Transparent)
16560 .visible_on_hover(group_id.clone())
16561 .on_click({
16562 let message = diagnostic.message.clone();
16563 move |_click, _, cx| {
16564 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16565 }
16566 })
16567 .tooltip(Tooltip::text("Copy diagnostic message")),
16568 )
16569 };
16570
16571 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16572 AvailableSpace::min_size(),
16573 cx.window,
16574 cx.app,
16575 );
16576
16577 h_flex()
16578 .id(cx.block_id)
16579 .group(group_id.clone())
16580 .relative()
16581 .size_full()
16582 .block_mouse_down()
16583 .pl(cx.gutter_dimensions.width)
16584 .w(cx.max_width - cx.gutter_dimensions.full_width())
16585 .child(
16586 div()
16587 .flex()
16588 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16589 .flex_shrink(),
16590 )
16591 .child(buttons(&diagnostic))
16592 .child(div().flex().flex_shrink_0().child(
16593 StyledText::new(text_without_backticks.clone()).with_highlights(
16594 &text_style,
16595 code_ranges.iter().map(|range| {
16596 (
16597 range.clone(),
16598 HighlightStyle {
16599 font_weight: Some(FontWeight::BOLD),
16600 ..Default::default()
16601 },
16602 )
16603 }),
16604 ),
16605 ))
16606 .into_any_element()
16607 })
16608}
16609
16610fn inline_completion_edit_text(
16611 current_snapshot: &BufferSnapshot,
16612 edits: &[(Range<Anchor>, String)],
16613 edit_preview: &EditPreview,
16614 include_deletions: bool,
16615 cx: &App,
16616) -> HighlightedText {
16617 let edits = edits
16618 .iter()
16619 .map(|(anchor, text)| {
16620 (
16621 anchor.start.text_anchor..anchor.end.text_anchor,
16622 text.clone(),
16623 )
16624 })
16625 .collect::<Vec<_>>();
16626
16627 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16628}
16629
16630pub fn highlight_diagnostic_message(
16631 diagnostic: &Diagnostic,
16632 mut max_message_rows: Option<u8>,
16633) -> (SharedString, Vec<Range<usize>>) {
16634 let mut text_without_backticks = String::new();
16635 let mut code_ranges = Vec::new();
16636
16637 if let Some(source) = &diagnostic.source {
16638 text_without_backticks.push_str(source);
16639 code_ranges.push(0..source.len());
16640 text_without_backticks.push_str(": ");
16641 }
16642
16643 let mut prev_offset = 0;
16644 let mut in_code_block = false;
16645 let has_row_limit = max_message_rows.is_some();
16646 let mut newline_indices = diagnostic
16647 .message
16648 .match_indices('\n')
16649 .filter(|_| has_row_limit)
16650 .map(|(ix, _)| ix)
16651 .fuse()
16652 .peekable();
16653
16654 for (quote_ix, _) in diagnostic
16655 .message
16656 .match_indices('`')
16657 .chain([(diagnostic.message.len(), "")])
16658 {
16659 let mut first_newline_ix = None;
16660 let mut last_newline_ix = None;
16661 while let Some(newline_ix) = newline_indices.peek() {
16662 if *newline_ix < quote_ix {
16663 if first_newline_ix.is_none() {
16664 first_newline_ix = Some(*newline_ix);
16665 }
16666 last_newline_ix = Some(*newline_ix);
16667
16668 if let Some(rows_left) = &mut max_message_rows {
16669 if *rows_left == 0 {
16670 break;
16671 } else {
16672 *rows_left -= 1;
16673 }
16674 }
16675 let _ = newline_indices.next();
16676 } else {
16677 break;
16678 }
16679 }
16680 let prev_len = text_without_backticks.len();
16681 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16682 text_without_backticks.push_str(new_text);
16683 if in_code_block {
16684 code_ranges.push(prev_len..text_without_backticks.len());
16685 }
16686 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16687 in_code_block = !in_code_block;
16688 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16689 text_without_backticks.push_str("...");
16690 break;
16691 }
16692 }
16693
16694 (text_without_backticks.into(), code_ranges)
16695}
16696
16697fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16698 match severity {
16699 DiagnosticSeverity::ERROR => colors.error,
16700 DiagnosticSeverity::WARNING => colors.warning,
16701 DiagnosticSeverity::INFORMATION => colors.info,
16702 DiagnosticSeverity::HINT => colors.info,
16703 _ => colors.ignored,
16704 }
16705}
16706
16707pub fn styled_runs_for_code_label<'a>(
16708 label: &'a CodeLabel,
16709 syntax_theme: &'a theme::SyntaxTheme,
16710) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16711 let fade_out = HighlightStyle {
16712 fade_out: Some(0.35),
16713 ..Default::default()
16714 };
16715
16716 let mut prev_end = label.filter_range.end;
16717 label
16718 .runs
16719 .iter()
16720 .enumerate()
16721 .flat_map(move |(ix, (range, highlight_id))| {
16722 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16723 style
16724 } else {
16725 return Default::default();
16726 };
16727 let mut muted_style = style;
16728 muted_style.highlight(fade_out);
16729
16730 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16731 if range.start >= label.filter_range.end {
16732 if range.start > prev_end {
16733 runs.push((prev_end..range.start, fade_out));
16734 }
16735 runs.push((range.clone(), muted_style));
16736 } else if range.end <= label.filter_range.end {
16737 runs.push((range.clone(), style));
16738 } else {
16739 runs.push((range.start..label.filter_range.end, style));
16740 runs.push((label.filter_range.end..range.end, muted_style));
16741 }
16742 prev_end = cmp::max(prev_end, range.end);
16743
16744 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16745 runs.push((prev_end..label.text.len(), fade_out));
16746 }
16747
16748 runs
16749 })
16750}
16751
16752pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16753 let mut prev_index = 0;
16754 let mut prev_codepoint: Option<char> = None;
16755 text.char_indices()
16756 .chain([(text.len(), '\0')])
16757 .filter_map(move |(index, codepoint)| {
16758 let prev_codepoint = prev_codepoint.replace(codepoint)?;
16759 let is_boundary = index == text.len()
16760 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16761 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16762 if is_boundary {
16763 let chunk = &text[prev_index..index];
16764 prev_index = index;
16765 Some(chunk)
16766 } else {
16767 None
16768 }
16769 })
16770}
16771
16772pub trait RangeToAnchorExt: Sized {
16773 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16774
16775 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16776 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16777 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16778 }
16779}
16780
16781impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16782 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16783 let start_offset = self.start.to_offset(snapshot);
16784 let end_offset = self.end.to_offset(snapshot);
16785 if start_offset == end_offset {
16786 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16787 } else {
16788 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16789 }
16790 }
16791}
16792
16793pub trait RowExt {
16794 fn as_f32(&self) -> f32;
16795
16796 fn next_row(&self) -> Self;
16797
16798 fn previous_row(&self) -> Self;
16799
16800 fn minus(&self, other: Self) -> u32;
16801}
16802
16803impl RowExt for DisplayRow {
16804 fn as_f32(&self) -> f32 {
16805 self.0 as f32
16806 }
16807
16808 fn next_row(&self) -> Self {
16809 Self(self.0 + 1)
16810 }
16811
16812 fn previous_row(&self) -> Self {
16813 Self(self.0.saturating_sub(1))
16814 }
16815
16816 fn minus(&self, other: Self) -> u32 {
16817 self.0 - other.0
16818 }
16819}
16820
16821impl RowExt for MultiBufferRow {
16822 fn as_f32(&self) -> f32 {
16823 self.0 as f32
16824 }
16825
16826 fn next_row(&self) -> Self {
16827 Self(self.0 + 1)
16828 }
16829
16830 fn previous_row(&self) -> Self {
16831 Self(self.0.saturating_sub(1))
16832 }
16833
16834 fn minus(&self, other: Self) -> u32 {
16835 self.0 - other.0
16836 }
16837}
16838
16839trait RowRangeExt {
16840 type Row;
16841
16842 fn len(&self) -> usize;
16843
16844 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16845}
16846
16847impl RowRangeExt for Range<MultiBufferRow> {
16848 type Row = MultiBufferRow;
16849
16850 fn len(&self) -> usize {
16851 (self.end.0 - self.start.0) as usize
16852 }
16853
16854 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16855 (self.start.0..self.end.0).map(MultiBufferRow)
16856 }
16857}
16858
16859impl RowRangeExt for Range<DisplayRow> {
16860 type Row = DisplayRow;
16861
16862 fn len(&self) -> usize {
16863 (self.end.0 - self.start.0) as usize
16864 }
16865
16866 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16867 (self.start.0..self.end.0).map(DisplayRow)
16868 }
16869}
16870
16871/// If select range has more than one line, we
16872/// just point the cursor to range.start.
16873fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16874 if range.start.row == range.end.row {
16875 range
16876 } else {
16877 range.start..range.start
16878 }
16879}
16880pub struct KillRing(ClipboardItem);
16881impl Global for KillRing {}
16882
16883const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16884
16885fn all_edits_insertions_or_deletions(
16886 edits: &Vec<(Range<Anchor>, String)>,
16887 snapshot: &MultiBufferSnapshot,
16888) -> bool {
16889 let mut all_insertions = true;
16890 let mut all_deletions = true;
16891
16892 for (range, new_text) in edits.iter() {
16893 let range_is_empty = range.to_offset(&snapshot).is_empty();
16894 let text_is_empty = new_text.is_empty();
16895
16896 if range_is_empty != text_is_empty {
16897 if range_is_empty {
16898 all_deletions = false;
16899 } else {
16900 all_insertions = false;
16901 }
16902 } else {
16903 return false;
16904 }
16905
16906 if !all_insertions && !all_deletions {
16907 return false;
16908 }
16909 }
16910 all_insertions || all_deletions
16911}