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 client::{Collaborator, ParticipantIndex};
56use clock::ReplicaId;
57use collections::{BTreeMap, HashMap, HashSet, VecDeque};
58use convert_case::{Case, Casing};
59use display_map::*;
60pub use display_map::{DisplayPoint, FoldPlaceholder};
61pub use editor_settings::{
62 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
63};
64pub use editor_settings_controls::*;
65use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
66pub use element::{
67 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
68};
69use futures::{future, FutureExt};
70use fuzzy::StringMatchCandidate;
71
72use code_context_menus::{
73 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
74 CompletionsMenu, ContextMenuOrigin,
75};
76use git::blame::GitBlame;
77use gpui::{
78 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
79 AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
80 ClipboardEntry, ClipboardItem, Context, DispatchPhase, ElementId, Entity, EntityInputHandler,
81 EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
82 HighlightStyle, Hsla, InteractiveText, KeyContext, Modifiers, MouseButton, MouseDownEvent,
83 PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription,
84 Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
85 WeakEntity, WeakFocusHandle, Window,
86};
87use highlight_matching_bracket::refresh_matching_bracket_highlights;
88use hover_popover::{hide_hover, HoverState};
89use indent_guides::ActiveIndentGuidesState;
90use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
91pub use inline_completion::Direction;
92use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
93pub use items::MAX_TAB_TITLE_LEN;
94use itertools::Itertools;
95use language::{
96 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
97 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
98 CompletionDocumentation, CursorShape, Diagnostic, EditPreview, HighlightedText, IndentKind,
99 IndentSize, InlineCompletionPreviewMode, Language, OffsetRangeExt, Point, Selection,
100 SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
101};
102use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
103use linked_editing_ranges::refresh_linked_ranges;
104use mouse_context_menu::MouseContextMenu;
105pub use proposed_changes_editor::{
106 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
107};
108use similar::{ChangeTag, TextDiff};
109use std::iter::Peekable;
110use task::{ResolvedTask, TaskTemplate, TaskVariables};
111
112use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
113pub use lsp::CompletionContext;
114use lsp::{
115 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
116 LanguageServerId, LanguageServerName,
117};
118
119use language::BufferSnapshot;
120use movement::TextLayoutDetails;
121pub use multi_buffer::{
122 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
123 ToOffset, ToPoint,
124};
125use multi_buffer::{
126 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
127 ToOffsetUtf16,
128};
129use project::{
130 lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
131 project_settings::{GitGutterSetting, ProjectSettings},
132 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
133 LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
134};
135use rand::prelude::*;
136use rpc::{proto::*, ErrorExt};
137use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
138use selections_collection::{
139 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
140};
141use serde::{Deserialize, Serialize};
142use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
143use smallvec::SmallVec;
144use snippet::Snippet;
145use std::{
146 any::TypeId,
147 borrow::Cow,
148 cell::RefCell,
149 cmp::{self, Ordering, Reverse},
150 mem,
151 num::NonZeroU32,
152 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
153 path::{Path, PathBuf},
154 rc::Rc,
155 sync::Arc,
156 time::{Duration, Instant},
157};
158pub use sum_tree::Bias;
159use sum_tree::TreeMap;
160use text::{BufferId, OffsetUtf16, Rope};
161use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
162use ui::{
163 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
164 Tooltip,
165};
166use util::{defer, maybe, post_inc, RangeExt, ResultExt, TakeUntilExt, TryFutureExt};
167use workspace::item::{ItemHandle, PreviewTabsSettings};
168use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
169use workspace::{
170 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
171};
172use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
173
174use crate::hover_links::{find_url, find_url_from_range};
175use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
176
177pub const FILE_HEADER_HEIGHT: u32 = 2;
178pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
179pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
180pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
181const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
182const MAX_LINE_LEN: usize = 1024;
183const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
184const MAX_SELECTION_HISTORY_LEN: usize = 1024;
185pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
186#[doc(hidden)]
187pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
188
189pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
190pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
191
192pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
193pub(crate) const EDIT_PREDICTION_REQUIRES_MODIFIER_KEY_CONTEXT: &str =
194 "edit_prediction_requires_modifier";
195
196pub fn render_parsed_markdown(
197 element_id: impl Into<ElementId>,
198 parsed: &language::ParsedMarkdown,
199 editor_style: &EditorStyle,
200 workspace: Option<WeakEntity<Workspace>>,
201 cx: &mut App,
202) -> InteractiveText {
203 let code_span_background_color = cx
204 .theme()
205 .colors()
206 .editor_document_highlight_read_background;
207
208 let highlights = gpui::combine_highlights(
209 parsed.highlights.iter().filter_map(|(range, highlight)| {
210 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
211 Some((range.clone(), highlight))
212 }),
213 parsed
214 .regions
215 .iter()
216 .zip(&parsed.region_ranges)
217 .filter_map(|(region, range)| {
218 if region.code {
219 Some((
220 range.clone(),
221 HighlightStyle {
222 background_color: Some(code_span_background_color),
223 ..Default::default()
224 },
225 ))
226 } else {
227 None
228 }
229 }),
230 );
231
232 let mut links = Vec::new();
233 let mut link_ranges = Vec::new();
234 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
235 if let Some(link) = region.link.clone() {
236 links.push(link);
237 link_ranges.push(range.clone());
238 }
239 }
240
241 InteractiveText::new(
242 element_id,
243 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
244 )
245 .on_click(
246 link_ranges,
247 move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
248 markdown::Link::Web { url } => cx.open_url(url),
249 markdown::Link::Path { path } => {
250 if let Some(workspace) = &workspace {
251 _ = workspace.update(cx, |workspace, cx| {
252 workspace
253 .open_abs_path(path.clone(), false, window, cx)
254 .detach();
255 });
256 }
257 }
258 },
259 )
260}
261
262#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
263pub enum InlayId {
264 InlineCompletion(usize),
265 Hint(usize),
266}
267
268impl InlayId {
269 fn id(&self) -> usize {
270 match self {
271 Self::InlineCompletion(id) => *id,
272 Self::Hint(id) => *id,
273 }
274 }
275}
276
277enum DocumentHighlightRead {}
278enum DocumentHighlightWrite {}
279enum InputComposition {}
280
281#[derive(Debug, Copy, Clone, PartialEq, Eq)]
282pub enum Navigated {
283 Yes,
284 No,
285}
286
287impl Navigated {
288 pub fn from_bool(yes: bool) -> Navigated {
289 if yes {
290 Navigated::Yes
291 } else {
292 Navigated::No
293 }
294 }
295}
296
297pub fn init_settings(cx: &mut App) {
298 EditorSettings::register(cx);
299}
300
301pub fn init(cx: &mut App) {
302 init_settings(cx);
303
304 workspace::register_project_item::<Editor>(cx);
305 workspace::FollowableViewRegistry::register::<Editor>(cx);
306 workspace::register_serializable_item::<Editor>(cx);
307
308 cx.observe_new(
309 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
310 workspace.register_action(Editor::new_file);
311 workspace.register_action(Editor::new_file_vertical);
312 workspace.register_action(Editor::new_file_horizontal);
313 workspace.register_action(Editor::cancel_language_server_work);
314 },
315 )
316 .detach();
317
318 cx.on_action(move |_: &workspace::NewFile, cx| {
319 let app_state = workspace::AppState::global(cx);
320 if let Some(app_state) = app_state.upgrade() {
321 workspace::open_new(
322 Default::default(),
323 app_state,
324 cx,
325 |workspace, window, cx| {
326 Editor::new_file(workspace, &Default::default(), window, cx)
327 },
328 )
329 .detach();
330 }
331 });
332 cx.on_action(move |_: &workspace::NewWindow, cx| {
333 let app_state = workspace::AppState::global(cx);
334 if let Some(app_state) = app_state.upgrade() {
335 workspace::open_new(
336 Default::default(),
337 app_state,
338 cx,
339 |workspace, window, cx| {
340 cx.activate(true);
341 Editor::new_file(workspace, &Default::default(), window, cx)
342 },
343 )
344 .detach();
345 }
346 });
347}
348
349pub struct SearchWithinRange;
350
351trait InvalidationRegion {
352 fn ranges(&self) -> &[Range<Anchor>];
353}
354
355#[derive(Clone, Debug, PartialEq)]
356pub enum SelectPhase {
357 Begin {
358 position: DisplayPoint,
359 add: bool,
360 click_count: usize,
361 },
362 BeginColumnar {
363 position: DisplayPoint,
364 reset: bool,
365 goal_column: u32,
366 },
367 Extend {
368 position: DisplayPoint,
369 click_count: usize,
370 },
371 Update {
372 position: DisplayPoint,
373 goal_column: u32,
374 scroll_delta: gpui::Point<f32>,
375 },
376 End,
377}
378
379#[derive(Clone, Debug)]
380pub enum SelectMode {
381 Character,
382 Word(Range<Anchor>),
383 Line(Range<Anchor>),
384 All,
385}
386
387#[derive(Copy, Clone, PartialEq, Eq, Debug)]
388pub enum EditorMode {
389 SingleLine { auto_width: bool },
390 AutoHeight { max_lines: usize },
391 Full,
392}
393
394#[derive(Copy, Clone, Debug)]
395pub enum SoftWrap {
396 /// Prefer not to wrap at all.
397 ///
398 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
399 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
400 GitDiff,
401 /// Prefer a single line generally, unless an overly long line is encountered.
402 None,
403 /// Soft wrap lines that exceed the editor width.
404 EditorWidth,
405 /// Soft wrap lines at the preferred line length.
406 Column(u32),
407 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
408 Bounded(u32),
409}
410
411#[derive(Clone)]
412pub struct EditorStyle {
413 pub background: Hsla,
414 pub local_player: PlayerColor,
415 pub text: TextStyle,
416 pub scrollbar_width: Pixels,
417 pub syntax: Arc<SyntaxTheme>,
418 pub status: StatusColors,
419 pub inlay_hints_style: HighlightStyle,
420 pub inline_completion_styles: InlineCompletionStyles,
421 pub unnecessary_code_fade: f32,
422}
423
424impl Default for EditorStyle {
425 fn default() -> Self {
426 Self {
427 background: Hsla::default(),
428 local_player: PlayerColor::default(),
429 text: TextStyle::default(),
430 scrollbar_width: Pixels::default(),
431 syntax: Default::default(),
432 // HACK: Status colors don't have a real default.
433 // We should look into removing the status colors from the editor
434 // style and retrieve them directly from the theme.
435 status: StatusColors::dark(),
436 inlay_hints_style: HighlightStyle::default(),
437 inline_completion_styles: InlineCompletionStyles {
438 insertion: HighlightStyle::default(),
439 whitespace: HighlightStyle::default(),
440 },
441 unnecessary_code_fade: Default::default(),
442 }
443 }
444}
445
446pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
447 let show_background = language_settings::language_settings(None, None, cx)
448 .inlay_hints
449 .show_background;
450
451 HighlightStyle {
452 color: Some(cx.theme().status().hint),
453 background_color: show_background.then(|| cx.theme().status().hint_background),
454 ..HighlightStyle::default()
455 }
456}
457
458pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
459 InlineCompletionStyles {
460 insertion: HighlightStyle {
461 color: Some(cx.theme().status().predictive),
462 ..HighlightStyle::default()
463 },
464 whitespace: HighlightStyle {
465 background_color: Some(cx.theme().status().created_background),
466 ..HighlightStyle::default()
467 },
468 }
469}
470
471type CompletionId = usize;
472
473pub(crate) enum EditDisplayMode {
474 TabAccept,
475 DiffPopover,
476 Inline,
477}
478
479enum InlineCompletion {
480 Edit {
481 edits: Vec<(Range<Anchor>, String)>,
482 edit_preview: Option<EditPreview>,
483 display_mode: EditDisplayMode,
484 snapshot: BufferSnapshot,
485 },
486 Move {
487 target: Anchor,
488 snapshot: BufferSnapshot,
489 },
490}
491
492struct InlineCompletionState {
493 inlay_ids: Vec<InlayId>,
494 completion: InlineCompletion,
495 completion_id: Option<SharedString>,
496 invalidation_range: Range<Anchor>,
497}
498
499enum EditPredictionSettings {
500 Disabled,
501 Enabled {
502 show_in_menu: bool,
503 preview_requires_modifier: bool,
504 },
505}
506
507impl EditPredictionSettings {
508 pub fn is_enabled(&self) -> bool {
509 match self {
510 EditPredictionSettings::Disabled => false,
511 EditPredictionSettings::Enabled { .. } => true,
512 }
513 }
514}
515
516enum InlineCompletionHighlight {}
517
518pub enum MenuInlineCompletionsPolicy {
519 Never,
520 ByProvider,
521}
522
523// TODO az do we need this?
524#[derive(Clone)]
525pub enum EditPredictionPreview {
526 /// Modifier is not pressed
527 Inactive,
528 /// Modifier pressed, animating to active
529 MovingTo {
530 animation: Range<Instant>,
531 scroll_position_at_start: Option<gpui::Point<f32>>,
532 target_point: DisplayPoint,
533 },
534 Arrived {
535 scroll_position_at_start: Option<gpui::Point<f32>>,
536 scroll_position_at_arrival: Option<gpui::Point<f32>>,
537 target_point: Option<DisplayPoint>,
538 },
539 /// Modifier released, animating from active
540 MovingFrom {
541 animation: Range<Instant>,
542 target_point: DisplayPoint,
543 },
544}
545
546impl EditPredictionPreview {
547 fn start(
548 &mut self,
549 completion: &InlineCompletion,
550 snapshot: &EditorSnapshot,
551 cursor: DisplayPoint,
552 ) -> bool {
553 if matches!(self, Self::MovingTo { .. } | Self::Arrived { .. }) {
554 return false;
555 }
556 (*self, _) = Self::start_now(completion, snapshot, cursor);
557 true
558 }
559
560 fn restart(
561 &mut self,
562 completion: &InlineCompletion,
563 snapshot: &EditorSnapshot,
564 cursor: DisplayPoint,
565 ) -> bool {
566 match self {
567 Self::Inactive => false,
568 Self::MovingTo { target_point, .. }
569 | Self::Arrived {
570 target_point: Some(target_point),
571 ..
572 } => {
573 let (new_preview, new_target_point) = Self::start_now(completion, snapshot, cursor);
574
575 if new_target_point != Some(*target_point) {
576 *self = new_preview;
577 return true;
578 }
579
580 false
581 }
582 Self::Arrived {
583 target_point: None, ..
584 } => {
585 let (new_preview, _) = Self::start_now(completion, snapshot, cursor);
586
587 *self = new_preview;
588 true
589 }
590 Self::MovingFrom { .. } => false,
591 }
592 }
593
594 fn start_now(
595 completion: &InlineCompletion,
596 snapshot: &EditorSnapshot,
597 cursor: DisplayPoint,
598 ) -> (Self, Option<DisplayPoint>) {
599 let now = Instant::now();
600 match completion {
601 InlineCompletion::Edit { .. } => (
602 Self::Arrived {
603 target_point: None,
604 scroll_position_at_start: None,
605 scroll_position_at_arrival: None,
606 },
607 None,
608 ),
609 InlineCompletion::Move { target, .. } => {
610 let target_point = target.to_display_point(&snapshot.display_snapshot);
611 let duration = Self::animation_duration(cursor, target_point);
612
613 (
614 Self::MovingTo {
615 animation: now..now + duration,
616 scroll_position_at_start: Some(snapshot.scroll_position()),
617 target_point,
618 },
619 Some(target_point),
620 )
621 }
622 }
623 }
624
625 fn animation_duration(a: DisplayPoint, b: DisplayPoint) -> Duration {
626 const SPEED: f32 = 8.0;
627
628 let row_diff = b.row().0.abs_diff(a.row().0);
629 let column_diff = b.column().abs_diff(a.column());
630 let distance = ((row_diff.pow(2) + column_diff.pow(2)) as f32).sqrt();
631 Duration::from_millis((distance * SPEED) as u64)
632 }
633
634 fn end(
635 &mut self,
636 cursor: DisplayPoint,
637 scroll_pixel_position: gpui::Point<Pixels>,
638 window: &mut Window,
639 cx: &mut Context<Editor>,
640 ) -> bool {
641 let (scroll_position, target_point) = match self {
642 Self::MovingTo {
643 scroll_position_at_start,
644 target_point,
645 ..
646 }
647 | Self::Arrived {
648 scroll_position_at_start,
649 scroll_position_at_arrival: None,
650 target_point: Some(target_point),
651 ..
652 } => (*scroll_position_at_start, target_point),
653 Self::Arrived {
654 scroll_position_at_start,
655 scroll_position_at_arrival: Some(scroll_at_arrival),
656 target_point: Some(target_point),
657 } => {
658 const TOLERANCE: f32 = 4.0;
659
660 let diff = *scroll_at_arrival - scroll_pixel_position.map(|p| p.0);
661
662 if diff.x.abs() < TOLERANCE && diff.y.abs() < TOLERANCE {
663 (*scroll_position_at_start, target_point)
664 } else {
665 (None, target_point)
666 }
667 }
668 Self::Arrived {
669 target_point: None, ..
670 } => {
671 *self = Self::Inactive;
672 return true;
673 }
674 Self::MovingFrom { .. } | Self::Inactive => return false,
675 };
676
677 let now = Instant::now();
678 let duration = Self::animation_duration(cursor, *target_point);
679 let target_point = *target_point;
680
681 *self = Self::MovingFrom {
682 animation: now..now + duration,
683 target_point,
684 };
685
686 if let Some(scroll_position) = scroll_position {
687 cx.spawn_in(window, |editor, mut cx| async move {
688 smol::Timer::after(duration).await;
689 editor
690 .update_in(&mut cx, |editor, window, cx| {
691 if let Self::MovingFrom { .. } | Self::Inactive =
692 editor.edit_prediction_preview
693 {
694 editor.set_scroll_position(scroll_position, window, cx)
695 }
696 })
697 .log_err();
698 })
699 .detach();
700 }
701
702 true
703 }
704
705 /// Whether the preview is active or we are animating to or from it.
706 fn is_active(&self) -> bool {
707 matches!(
708 self,
709 Self::MovingTo { .. } | Self::Arrived { .. } | Self::MovingFrom { .. }
710 )
711 }
712
713 /// Returns true if the preview is active, not cancelled, and the animation is settled.
714 fn is_active_settled(&self) -> bool {
715 matches!(self, Self::Arrived { .. })
716 }
717
718 #[allow(clippy::too_many_arguments)]
719 fn move_state(
720 &mut self,
721 snapshot: &EditorSnapshot,
722 visible_row_range: Range<DisplayRow>,
723 line_layouts: &[LineWithInvisibles],
724 scroll_pixel_position: gpui::Point<Pixels>,
725 line_height: Pixels,
726 target: Anchor,
727 cursor: Option<DisplayPoint>,
728 ) -> Option<EditPredictionMoveState> {
729 let delta = match self {
730 Self::Inactive => return None,
731 Self::Arrived { .. } => 1.,
732 Self::MovingTo {
733 animation,
734 scroll_position_at_start: original_scroll_position,
735 target_point,
736 } => {
737 let now = Instant::now();
738 if animation.end < now {
739 *self = Self::Arrived {
740 scroll_position_at_start: *original_scroll_position,
741 scroll_position_at_arrival: Some(scroll_pixel_position.map(|p| p.0)),
742 target_point: Some(*target_point),
743 };
744 1.0
745 } else {
746 (now - animation.start).as_secs_f32()
747 / (animation.end - animation.start).as_secs_f32()
748 }
749 }
750 Self::MovingFrom { animation, .. } => {
751 let now = Instant::now();
752 if animation.end < now {
753 *self = Self::Inactive;
754 return None;
755 } else {
756 let delta = (now - animation.start).as_secs_f32()
757 / (animation.end - animation.start).as_secs_f32();
758 1.0 - delta
759 }
760 }
761 };
762
763 let cursor = cursor?;
764
765 if !visible_row_range.contains(&cursor.row()) {
766 return None;
767 }
768
769 let target_position = target.to_display_point(&snapshot.display_snapshot);
770
771 if !visible_row_range.contains(&target_position.row()) {
772 return None;
773 }
774
775 let target_row_layout =
776 &line_layouts[target_position.row().minus(visible_row_range.start) as usize];
777 let target_column = target_position.column() as usize;
778
779 let target_character_x = target_row_layout.x_for_index(target_column);
780
781 let target_x = target_character_x - scroll_pixel_position.x;
782 let target_y =
783 (target_position.row().as_f32() - scroll_pixel_position.y / line_height) * line_height;
784
785 let origin_x = line_layouts[cursor.row().minus(visible_row_range.start) as usize]
786 .x_for_index(cursor.column() as usize);
787 let origin_y =
788 (cursor.row().as_f32() - scroll_pixel_position.y / line_height) * line_height;
789
790 let delta = 1.0 - (-10.0 * delta).exp2();
791
792 let x = origin_x + (target_x - origin_x) * delta;
793 let y = origin_y + (target_y - origin_y) * delta;
794
795 Some(EditPredictionMoveState {
796 delta,
797 position: point(x, y),
798 })
799 }
800}
801
802pub(crate) struct EditPredictionMoveState {
803 delta: f32,
804 position: gpui::Point<Pixels>,
805}
806
807impl EditPredictionMoveState {
808 pub fn is_animation_completed(&self) -> bool {
809 self.delta >= 1.
810 }
811}
812
813#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
814struct EditorActionId(usize);
815
816impl EditorActionId {
817 pub fn post_inc(&mut self) -> Self {
818 let answer = self.0;
819
820 *self = Self(answer + 1);
821
822 Self(answer)
823 }
824}
825
826// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
827// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
828
829type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
830type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
831
832#[derive(Default)]
833struct ScrollbarMarkerState {
834 scrollbar_size: Size<Pixels>,
835 dirty: bool,
836 markers: Arc<[PaintQuad]>,
837 pending_refresh: Option<Task<Result<()>>>,
838}
839
840impl ScrollbarMarkerState {
841 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
842 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
843 }
844}
845
846#[derive(Clone, Debug)]
847struct RunnableTasks {
848 templates: Vec<(TaskSourceKind, TaskTemplate)>,
849 offset: MultiBufferOffset,
850 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
851 column: u32,
852 // Values of all named captures, including those starting with '_'
853 extra_variables: HashMap<String, String>,
854 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
855 context_range: Range<BufferOffset>,
856}
857
858impl RunnableTasks {
859 fn resolve<'a>(
860 &'a self,
861 cx: &'a task::TaskContext,
862 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
863 self.templates.iter().filter_map(|(kind, template)| {
864 template
865 .resolve_task(&kind.to_id_base(), cx)
866 .map(|task| (kind.clone(), task))
867 })
868 }
869}
870
871#[derive(Clone)]
872struct ResolvedTasks {
873 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
874 position: Anchor,
875}
876#[derive(Copy, Clone, Debug)]
877struct MultiBufferOffset(usize);
878#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
879struct BufferOffset(usize);
880
881// Addons allow storing per-editor state in other crates (e.g. Vim)
882pub trait Addon: 'static {
883 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
884
885 fn render_buffer_header_controls(
886 &self,
887 _: &ExcerptInfo,
888 _: &Window,
889 _: &App,
890 ) -> Option<AnyElement> {
891 None
892 }
893
894 fn to_any(&self) -> &dyn std::any::Any;
895}
896
897#[derive(Debug, Copy, Clone, PartialEq, Eq)]
898pub enum IsVimMode {
899 Yes,
900 No,
901}
902
903/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
904///
905/// See the [module level documentation](self) for more information.
906pub struct Editor {
907 focus_handle: FocusHandle,
908 last_focused_descendant: Option<WeakFocusHandle>,
909 /// The text buffer being edited
910 buffer: Entity<MultiBuffer>,
911 /// Map of how text in the buffer should be displayed.
912 /// Handles soft wraps, folds, fake inlay text insertions, etc.
913 pub display_map: Entity<DisplayMap>,
914 pub selections: SelectionsCollection,
915 pub scroll_manager: ScrollManager,
916 /// When inline assist editors are linked, they all render cursors because
917 /// typing enters text into each of them, even the ones that aren't focused.
918 pub(crate) show_cursor_when_unfocused: bool,
919 columnar_selection_tail: Option<Anchor>,
920 add_selections_state: Option<AddSelectionsState>,
921 select_next_state: Option<SelectNextState>,
922 select_prev_state: Option<SelectNextState>,
923 selection_history: SelectionHistory,
924 autoclose_regions: Vec<AutocloseRegion>,
925 snippet_stack: InvalidationStack<SnippetState>,
926 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
927 ime_transaction: Option<TransactionId>,
928 active_diagnostics: Option<ActiveDiagnosticGroup>,
929 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
930
931 // TODO: make this a access method
932 pub project: Option<Entity<Project>>,
933 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
934 completion_provider: Option<Box<dyn CompletionProvider>>,
935 collaboration_hub: Option<Box<dyn CollaborationHub>>,
936 blink_manager: Entity<BlinkManager>,
937 show_cursor_names: bool,
938 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
939 pub show_local_selections: bool,
940 mode: EditorMode,
941 show_breadcrumbs: bool,
942 show_gutter: bool,
943 show_scrollbars: bool,
944 show_line_numbers: Option<bool>,
945 use_relative_line_numbers: Option<bool>,
946 show_git_diff_gutter: Option<bool>,
947 show_code_actions: Option<bool>,
948 show_runnables: Option<bool>,
949 show_wrap_guides: Option<bool>,
950 show_indent_guides: Option<bool>,
951 placeholder_text: Option<Arc<str>>,
952 highlight_order: usize,
953 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
954 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
955 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
956 scrollbar_marker_state: ScrollbarMarkerState,
957 active_indent_guides_state: ActiveIndentGuidesState,
958 nav_history: Option<ItemNavHistory>,
959 context_menu: RefCell<Option<CodeContextMenu>>,
960 mouse_context_menu: Option<MouseContextMenu>,
961 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
962 signature_help_state: SignatureHelpState,
963 auto_signature_help: Option<bool>,
964 find_all_references_task_sources: Vec<Anchor>,
965 next_completion_id: CompletionId,
966 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
967 code_actions_task: Option<Task<Result<()>>>,
968 document_highlights_task: Option<Task<()>>,
969 linked_editing_range_task: Option<Task<Option<()>>>,
970 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
971 pending_rename: Option<RenameState>,
972 searchable: bool,
973 cursor_shape: CursorShape,
974 current_line_highlight: Option<CurrentLineHighlight>,
975 collapse_matches: bool,
976 autoindent_mode: Option<AutoindentMode>,
977 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
978 input_enabled: bool,
979 use_modal_editing: bool,
980 read_only: bool,
981 leader_peer_id: Option<PeerId>,
982 remote_id: Option<ViewId>,
983 hover_state: HoverState,
984 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
985 gutter_hovered: bool,
986 hovered_link_state: Option<HoveredLinkState>,
987 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
988 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
989 active_inline_completion: Option<InlineCompletionState>,
990 /// Used to prevent flickering as the user types while the menu is open
991 stale_inline_completion_in_menu: Option<InlineCompletionState>,
992 edit_prediction_settings: EditPredictionSettings,
993 inline_completions_hidden_for_vim_mode: bool,
994 show_inline_completions_override: Option<bool>,
995 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
996 edit_prediction_preview: EditPredictionPreview,
997 inlay_hint_cache: InlayHintCache,
998 next_inlay_id: usize,
999 _subscriptions: Vec<Subscription>,
1000 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
1001 gutter_dimensions: GutterDimensions,
1002 style: Option<EditorStyle>,
1003 text_style_refinement: Option<TextStyleRefinement>,
1004 next_editor_action_id: EditorActionId,
1005 editor_actions:
1006 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
1007 use_autoclose: bool,
1008 use_auto_surround: bool,
1009 auto_replace_emoji_shortcode: bool,
1010 show_git_blame_gutter: bool,
1011 show_git_blame_inline: bool,
1012 show_git_blame_inline_delay_task: Option<Task<()>>,
1013 distinguish_unstaged_diff_hunks: bool,
1014 git_blame_inline_enabled: bool,
1015 serialize_dirty_buffers: bool,
1016 show_selection_menu: Option<bool>,
1017 blame: Option<Entity<GitBlame>>,
1018 blame_subscription: Option<Subscription>,
1019 custom_context_menu: Option<
1020 Box<
1021 dyn 'static
1022 + Fn(
1023 &mut Self,
1024 DisplayPoint,
1025 &mut Window,
1026 &mut Context<Self>,
1027 ) -> Option<Entity<ui::ContextMenu>>,
1028 >,
1029 >,
1030 last_bounds: Option<Bounds<Pixels>>,
1031 last_position_map: Option<Rc<PositionMap>>,
1032 expect_bounds_change: Option<Bounds<Pixels>>,
1033 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
1034 tasks_update_task: Option<Task<()>>,
1035 in_project_search: bool,
1036 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
1037 breadcrumb_header: Option<String>,
1038 focused_block: Option<FocusedBlock>,
1039 next_scroll_position: NextScrollCursorCenterTopBottom,
1040 addons: HashMap<TypeId, Box<dyn Addon>>,
1041 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
1042 selection_mark_mode: bool,
1043 toggle_fold_multiple_buffers: Task<()>,
1044 _scroll_cursor_center_top_bottom_task: Task<()>,
1045}
1046
1047#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
1048enum NextScrollCursorCenterTopBottom {
1049 #[default]
1050 Center,
1051 Top,
1052 Bottom,
1053}
1054
1055impl NextScrollCursorCenterTopBottom {
1056 fn next(&self) -> Self {
1057 match self {
1058 Self::Center => Self::Top,
1059 Self::Top => Self::Bottom,
1060 Self::Bottom => Self::Center,
1061 }
1062 }
1063}
1064
1065#[derive(Clone)]
1066pub struct EditorSnapshot {
1067 pub mode: EditorMode,
1068 show_gutter: bool,
1069 show_line_numbers: Option<bool>,
1070 show_git_diff_gutter: Option<bool>,
1071 show_code_actions: Option<bool>,
1072 show_runnables: Option<bool>,
1073 git_blame_gutter_max_author_length: Option<usize>,
1074 pub display_snapshot: DisplaySnapshot,
1075 pub placeholder_text: Option<Arc<str>>,
1076 is_focused: bool,
1077 scroll_anchor: ScrollAnchor,
1078 ongoing_scroll: OngoingScroll,
1079 current_line_highlight: CurrentLineHighlight,
1080 gutter_hovered: bool,
1081}
1082
1083const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
1084
1085#[derive(Default, Debug, Clone, Copy)]
1086pub struct GutterDimensions {
1087 pub left_padding: Pixels,
1088 pub right_padding: Pixels,
1089 pub width: Pixels,
1090 pub margin: Pixels,
1091 pub git_blame_entries_width: Option<Pixels>,
1092}
1093
1094impl GutterDimensions {
1095 /// The full width of the space taken up by the gutter.
1096 pub fn full_width(&self) -> Pixels {
1097 self.margin + self.width
1098 }
1099
1100 /// The width of the space reserved for the fold indicators,
1101 /// use alongside 'justify_end' and `gutter_width` to
1102 /// right align content with the line numbers
1103 pub fn fold_area_width(&self) -> Pixels {
1104 self.margin + self.right_padding
1105 }
1106}
1107
1108#[derive(Debug)]
1109pub struct RemoteSelection {
1110 pub replica_id: ReplicaId,
1111 pub selection: Selection<Anchor>,
1112 pub cursor_shape: CursorShape,
1113 pub peer_id: PeerId,
1114 pub line_mode: bool,
1115 pub participant_index: Option<ParticipantIndex>,
1116 pub user_name: Option<SharedString>,
1117}
1118
1119#[derive(Clone, Debug)]
1120struct SelectionHistoryEntry {
1121 selections: Arc<[Selection<Anchor>]>,
1122 select_next_state: Option<SelectNextState>,
1123 select_prev_state: Option<SelectNextState>,
1124 add_selections_state: Option<AddSelectionsState>,
1125}
1126
1127enum SelectionHistoryMode {
1128 Normal,
1129 Undoing,
1130 Redoing,
1131}
1132
1133#[derive(Clone, PartialEq, Eq, Hash)]
1134struct HoveredCursor {
1135 replica_id: u16,
1136 selection_id: usize,
1137}
1138
1139impl Default for SelectionHistoryMode {
1140 fn default() -> Self {
1141 Self::Normal
1142 }
1143}
1144
1145#[derive(Default)]
1146struct SelectionHistory {
1147 #[allow(clippy::type_complexity)]
1148 selections_by_transaction:
1149 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
1150 mode: SelectionHistoryMode,
1151 undo_stack: VecDeque<SelectionHistoryEntry>,
1152 redo_stack: VecDeque<SelectionHistoryEntry>,
1153}
1154
1155impl SelectionHistory {
1156 fn insert_transaction(
1157 &mut self,
1158 transaction_id: TransactionId,
1159 selections: Arc<[Selection<Anchor>]>,
1160 ) {
1161 self.selections_by_transaction
1162 .insert(transaction_id, (selections, None));
1163 }
1164
1165 #[allow(clippy::type_complexity)]
1166 fn transaction(
1167 &self,
1168 transaction_id: TransactionId,
1169 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
1170 self.selections_by_transaction.get(&transaction_id)
1171 }
1172
1173 #[allow(clippy::type_complexity)]
1174 fn transaction_mut(
1175 &mut self,
1176 transaction_id: TransactionId,
1177 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
1178 self.selections_by_transaction.get_mut(&transaction_id)
1179 }
1180
1181 fn push(&mut self, entry: SelectionHistoryEntry) {
1182 if !entry.selections.is_empty() {
1183 match self.mode {
1184 SelectionHistoryMode::Normal => {
1185 self.push_undo(entry);
1186 self.redo_stack.clear();
1187 }
1188 SelectionHistoryMode::Undoing => self.push_redo(entry),
1189 SelectionHistoryMode::Redoing => self.push_undo(entry),
1190 }
1191 }
1192 }
1193
1194 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
1195 if self
1196 .undo_stack
1197 .back()
1198 .map_or(true, |e| e.selections != entry.selections)
1199 {
1200 self.undo_stack.push_back(entry);
1201 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1202 self.undo_stack.pop_front();
1203 }
1204 }
1205 }
1206
1207 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
1208 if self
1209 .redo_stack
1210 .back()
1211 .map_or(true, |e| e.selections != entry.selections)
1212 {
1213 self.redo_stack.push_back(entry);
1214 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1215 self.redo_stack.pop_front();
1216 }
1217 }
1218 }
1219}
1220
1221struct RowHighlight {
1222 index: usize,
1223 range: Range<Anchor>,
1224 color: Hsla,
1225 should_autoscroll: bool,
1226}
1227
1228#[derive(Clone, Debug)]
1229struct AddSelectionsState {
1230 above: bool,
1231 stack: Vec<usize>,
1232}
1233
1234#[derive(Clone)]
1235struct SelectNextState {
1236 query: AhoCorasick,
1237 wordwise: bool,
1238 done: bool,
1239}
1240
1241impl std::fmt::Debug for SelectNextState {
1242 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1243 f.debug_struct(std::any::type_name::<Self>())
1244 .field("wordwise", &self.wordwise)
1245 .field("done", &self.done)
1246 .finish()
1247 }
1248}
1249
1250#[derive(Debug)]
1251struct AutocloseRegion {
1252 selection_id: usize,
1253 range: Range<Anchor>,
1254 pair: BracketPair,
1255}
1256
1257#[derive(Debug)]
1258struct SnippetState {
1259 ranges: Vec<Vec<Range<Anchor>>>,
1260 active_index: usize,
1261 choices: Vec<Option<Vec<String>>>,
1262}
1263
1264#[doc(hidden)]
1265pub struct RenameState {
1266 pub range: Range<Anchor>,
1267 pub old_name: Arc<str>,
1268 pub editor: Entity<Editor>,
1269 block_id: CustomBlockId,
1270}
1271
1272struct InvalidationStack<T>(Vec<T>);
1273
1274struct RegisteredInlineCompletionProvider {
1275 provider: Arc<dyn InlineCompletionProviderHandle>,
1276 _subscription: Subscription,
1277}
1278
1279#[derive(Debug)]
1280struct ActiveDiagnosticGroup {
1281 primary_range: Range<Anchor>,
1282 primary_message: String,
1283 group_id: usize,
1284 blocks: HashMap<CustomBlockId, Diagnostic>,
1285 is_valid: bool,
1286}
1287
1288#[derive(Serialize, Deserialize, Clone, Debug)]
1289pub struct ClipboardSelection {
1290 pub len: usize,
1291 pub is_entire_line: bool,
1292 pub first_line_indent: u32,
1293}
1294
1295#[derive(Debug)]
1296pub(crate) struct NavigationData {
1297 cursor_anchor: Anchor,
1298 cursor_position: Point,
1299 scroll_anchor: ScrollAnchor,
1300 scroll_top_row: u32,
1301}
1302
1303#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1304pub enum GotoDefinitionKind {
1305 Symbol,
1306 Declaration,
1307 Type,
1308 Implementation,
1309}
1310
1311#[derive(Debug, Clone)]
1312enum InlayHintRefreshReason {
1313 Toggle(bool),
1314 SettingsChange(InlayHintSettings),
1315 NewLinesShown,
1316 BufferEdited(HashSet<Arc<Language>>),
1317 RefreshRequested,
1318 ExcerptsRemoved(Vec<ExcerptId>),
1319}
1320
1321impl InlayHintRefreshReason {
1322 fn description(&self) -> &'static str {
1323 match self {
1324 Self::Toggle(_) => "toggle",
1325 Self::SettingsChange(_) => "settings change",
1326 Self::NewLinesShown => "new lines shown",
1327 Self::BufferEdited(_) => "buffer edited",
1328 Self::RefreshRequested => "refresh requested",
1329 Self::ExcerptsRemoved(_) => "excerpts removed",
1330 }
1331 }
1332}
1333
1334pub enum FormatTarget {
1335 Buffers,
1336 Ranges(Vec<Range<MultiBufferPoint>>),
1337}
1338
1339pub(crate) struct FocusedBlock {
1340 id: BlockId,
1341 focus_handle: WeakFocusHandle,
1342}
1343
1344#[derive(Clone)]
1345enum JumpData {
1346 MultiBufferRow {
1347 row: MultiBufferRow,
1348 line_offset_from_top: u32,
1349 },
1350 MultiBufferPoint {
1351 excerpt_id: ExcerptId,
1352 position: Point,
1353 anchor: text::Anchor,
1354 line_offset_from_top: u32,
1355 },
1356}
1357
1358pub enum MultibufferSelectionMode {
1359 First,
1360 All,
1361}
1362
1363impl Editor {
1364 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1365 let buffer = cx.new(|cx| Buffer::local("", cx));
1366 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1367 Self::new(
1368 EditorMode::SingleLine { auto_width: false },
1369 buffer,
1370 None,
1371 false,
1372 window,
1373 cx,
1374 )
1375 }
1376
1377 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1378 let buffer = cx.new(|cx| Buffer::local("", cx));
1379 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1380 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1381 }
1382
1383 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1384 let buffer = cx.new(|cx| Buffer::local("", cx));
1385 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1386 Self::new(
1387 EditorMode::SingleLine { auto_width: true },
1388 buffer,
1389 None,
1390 false,
1391 window,
1392 cx,
1393 )
1394 }
1395
1396 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1397 let buffer = cx.new(|cx| Buffer::local("", cx));
1398 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1399 Self::new(
1400 EditorMode::AutoHeight { max_lines },
1401 buffer,
1402 None,
1403 false,
1404 window,
1405 cx,
1406 )
1407 }
1408
1409 pub fn for_buffer(
1410 buffer: Entity<Buffer>,
1411 project: Option<Entity<Project>>,
1412 window: &mut Window,
1413 cx: &mut Context<Self>,
1414 ) -> Self {
1415 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1416 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1417 }
1418
1419 pub fn for_multibuffer(
1420 buffer: Entity<MultiBuffer>,
1421 project: Option<Entity<Project>>,
1422 show_excerpt_controls: bool,
1423 window: &mut Window,
1424 cx: &mut Context<Self>,
1425 ) -> Self {
1426 Self::new(
1427 EditorMode::Full,
1428 buffer,
1429 project,
1430 show_excerpt_controls,
1431 window,
1432 cx,
1433 )
1434 }
1435
1436 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1437 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1438 let mut clone = Self::new(
1439 self.mode,
1440 self.buffer.clone(),
1441 self.project.clone(),
1442 show_excerpt_controls,
1443 window,
1444 cx,
1445 );
1446 self.display_map.update(cx, |display_map, cx| {
1447 let snapshot = display_map.snapshot(cx);
1448 clone.display_map.update(cx, |display_map, cx| {
1449 display_map.set_state(&snapshot, cx);
1450 });
1451 });
1452 clone.selections.clone_state(&self.selections);
1453 clone.scroll_manager.clone_state(&self.scroll_manager);
1454 clone.searchable = self.searchable;
1455 clone
1456 }
1457
1458 pub fn new(
1459 mode: EditorMode,
1460 buffer: Entity<MultiBuffer>,
1461 project: Option<Entity<Project>>,
1462 show_excerpt_controls: bool,
1463 window: &mut Window,
1464 cx: &mut Context<Self>,
1465 ) -> Self {
1466 let style = window.text_style();
1467 let font_size = style.font_size.to_pixels(window.rem_size());
1468 let editor = cx.entity().downgrade();
1469 let fold_placeholder = FoldPlaceholder {
1470 constrain_width: true,
1471 render: Arc::new(move |fold_id, fold_range, _, cx| {
1472 let editor = editor.clone();
1473 div()
1474 .id(fold_id)
1475 .bg(cx.theme().colors().ghost_element_background)
1476 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1477 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1478 .rounded_sm()
1479 .size_full()
1480 .cursor_pointer()
1481 .child("⋯")
1482 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1483 .on_click(move |_, _window, cx| {
1484 editor
1485 .update(cx, |editor, cx| {
1486 editor.unfold_ranges(
1487 &[fold_range.start..fold_range.end],
1488 true,
1489 false,
1490 cx,
1491 );
1492 cx.stop_propagation();
1493 })
1494 .ok();
1495 })
1496 .into_any()
1497 }),
1498 merge_adjacent: true,
1499 ..Default::default()
1500 };
1501 let display_map = cx.new(|cx| {
1502 DisplayMap::new(
1503 buffer.clone(),
1504 style.font(),
1505 font_size,
1506 None,
1507 show_excerpt_controls,
1508 FILE_HEADER_HEIGHT,
1509 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1510 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1511 fold_placeholder,
1512 cx,
1513 )
1514 });
1515
1516 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1517
1518 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1519
1520 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1521 .then(|| language_settings::SoftWrap::None);
1522
1523 let mut project_subscriptions = Vec::new();
1524 if mode == EditorMode::Full {
1525 if let Some(project) = project.as_ref() {
1526 if buffer.read(cx).is_singleton() {
1527 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1528 cx.emit(EditorEvent::TitleChanged);
1529 }));
1530 }
1531 project_subscriptions.push(cx.subscribe_in(
1532 project,
1533 window,
1534 |editor, _, event, window, cx| {
1535 if let project::Event::RefreshInlayHints = event {
1536 editor
1537 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1538 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1539 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1540 let focus_handle = editor.focus_handle(cx);
1541 if focus_handle.is_focused(window) {
1542 let snapshot = buffer.read(cx).snapshot();
1543 for (range, snippet) in snippet_edits {
1544 let editor_range =
1545 language::range_from_lsp(*range).to_offset(&snapshot);
1546 editor
1547 .insert_snippet(
1548 &[editor_range],
1549 snippet.clone(),
1550 window,
1551 cx,
1552 )
1553 .ok();
1554 }
1555 }
1556 }
1557 }
1558 },
1559 ));
1560 if let Some(task_inventory) = project
1561 .read(cx)
1562 .task_store()
1563 .read(cx)
1564 .task_inventory()
1565 .cloned()
1566 {
1567 project_subscriptions.push(cx.observe_in(
1568 &task_inventory,
1569 window,
1570 |editor, _, window, cx| {
1571 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1572 },
1573 ));
1574 }
1575 }
1576 }
1577
1578 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1579
1580 let inlay_hint_settings =
1581 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1582 let focus_handle = cx.focus_handle();
1583 cx.on_focus(&focus_handle, window, Self::handle_focus)
1584 .detach();
1585 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1586 .detach();
1587 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1588 .detach();
1589 cx.on_blur(&focus_handle, window, Self::handle_blur)
1590 .detach();
1591
1592 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1593 Some(false)
1594 } else {
1595 None
1596 };
1597
1598 let mut code_action_providers = Vec::new();
1599 if let Some(project) = project.clone() {
1600 get_uncommitted_diff_for_buffer(
1601 &project,
1602 buffer.read(cx).all_buffers(),
1603 buffer.clone(),
1604 cx,
1605 );
1606 code_action_providers.push(Rc::new(project) as Rc<_>);
1607 }
1608
1609 let mut this = Self {
1610 focus_handle,
1611 show_cursor_when_unfocused: false,
1612 last_focused_descendant: None,
1613 buffer: buffer.clone(),
1614 display_map: display_map.clone(),
1615 selections,
1616 scroll_manager: ScrollManager::new(cx),
1617 columnar_selection_tail: None,
1618 add_selections_state: None,
1619 select_next_state: None,
1620 select_prev_state: None,
1621 selection_history: Default::default(),
1622 autoclose_regions: Default::default(),
1623 snippet_stack: Default::default(),
1624 select_larger_syntax_node_stack: Vec::new(),
1625 ime_transaction: Default::default(),
1626 active_diagnostics: None,
1627 soft_wrap_mode_override,
1628 completion_provider: project.clone().map(|project| Box::new(project) as _),
1629 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1630 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1631 project,
1632 blink_manager: blink_manager.clone(),
1633 show_local_selections: true,
1634 show_scrollbars: true,
1635 mode,
1636 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1637 show_gutter: mode == EditorMode::Full,
1638 show_line_numbers: None,
1639 use_relative_line_numbers: None,
1640 show_git_diff_gutter: None,
1641 show_code_actions: None,
1642 show_runnables: None,
1643 show_wrap_guides: None,
1644 show_indent_guides,
1645 placeholder_text: None,
1646 highlight_order: 0,
1647 highlighted_rows: HashMap::default(),
1648 background_highlights: Default::default(),
1649 gutter_highlights: TreeMap::default(),
1650 scrollbar_marker_state: ScrollbarMarkerState::default(),
1651 active_indent_guides_state: ActiveIndentGuidesState::default(),
1652 nav_history: None,
1653 context_menu: RefCell::new(None),
1654 mouse_context_menu: None,
1655 completion_tasks: Default::default(),
1656 signature_help_state: SignatureHelpState::default(),
1657 auto_signature_help: None,
1658 find_all_references_task_sources: Vec::new(),
1659 next_completion_id: 0,
1660 next_inlay_id: 0,
1661 code_action_providers,
1662 available_code_actions: Default::default(),
1663 code_actions_task: Default::default(),
1664 document_highlights_task: Default::default(),
1665 linked_editing_range_task: Default::default(),
1666 pending_rename: Default::default(),
1667 searchable: true,
1668 cursor_shape: EditorSettings::get_global(cx)
1669 .cursor_shape
1670 .unwrap_or_default(),
1671 current_line_highlight: None,
1672 autoindent_mode: Some(AutoindentMode::EachLine),
1673 collapse_matches: false,
1674 workspace: None,
1675 input_enabled: true,
1676 use_modal_editing: mode == EditorMode::Full,
1677 read_only: false,
1678 use_autoclose: true,
1679 use_auto_surround: true,
1680 auto_replace_emoji_shortcode: false,
1681 leader_peer_id: None,
1682 remote_id: None,
1683 hover_state: Default::default(),
1684 pending_mouse_down: None,
1685 hovered_link_state: Default::default(),
1686 edit_prediction_provider: None,
1687 active_inline_completion: None,
1688 stale_inline_completion_in_menu: None,
1689 edit_prediction_preview: EditPredictionPreview::Inactive,
1690 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1691
1692 gutter_hovered: false,
1693 pixel_position_of_newest_cursor: None,
1694 last_bounds: None,
1695 last_position_map: None,
1696 expect_bounds_change: None,
1697 gutter_dimensions: GutterDimensions::default(),
1698 style: None,
1699 show_cursor_names: false,
1700 hovered_cursors: Default::default(),
1701 next_editor_action_id: EditorActionId::default(),
1702 editor_actions: Rc::default(),
1703 inline_completions_hidden_for_vim_mode: false,
1704 show_inline_completions_override: None,
1705 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1706 edit_prediction_settings: EditPredictionSettings::Disabled,
1707 custom_context_menu: None,
1708 show_git_blame_gutter: false,
1709 show_git_blame_inline: false,
1710 distinguish_unstaged_diff_hunks: false,
1711 show_selection_menu: None,
1712 show_git_blame_inline_delay_task: None,
1713 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1714 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1715 .session
1716 .restore_unsaved_buffers,
1717 blame: None,
1718 blame_subscription: None,
1719 tasks: Default::default(),
1720 _subscriptions: vec![
1721 cx.observe(&buffer, Self::on_buffer_changed),
1722 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1723 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1724 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1725 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1726 cx.observe_window_activation(window, |editor, window, cx| {
1727 let active = window.is_window_active();
1728 editor.blink_manager.update(cx, |blink_manager, cx| {
1729 if active {
1730 blink_manager.enable(cx);
1731 } else {
1732 blink_manager.disable(cx);
1733 }
1734 });
1735 }),
1736 ],
1737 tasks_update_task: None,
1738 linked_edit_ranges: Default::default(),
1739 in_project_search: false,
1740 previous_search_ranges: None,
1741 breadcrumb_header: None,
1742 focused_block: None,
1743 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1744 addons: HashMap::default(),
1745 registered_buffers: HashMap::default(),
1746 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1747 selection_mark_mode: false,
1748 toggle_fold_multiple_buffers: Task::ready(()),
1749 text_style_refinement: None,
1750 };
1751 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1752 this._subscriptions.extend(project_subscriptions);
1753
1754 this.end_selection(window, cx);
1755 this.scroll_manager.show_scrollbar(window, cx);
1756
1757 if mode == EditorMode::Full {
1758 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1759 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1760
1761 if this.git_blame_inline_enabled {
1762 this.git_blame_inline_enabled = true;
1763 this.start_git_blame_inline(false, window, cx);
1764 }
1765
1766 if let Some(buffer) = buffer.read(cx).as_singleton() {
1767 if let Some(project) = this.project.as_ref() {
1768 let lsp_store = project.read(cx).lsp_store();
1769 let handle = lsp_store.update(cx, |lsp_store, cx| {
1770 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1771 });
1772 this.registered_buffers
1773 .insert(buffer.read(cx).remote_id(), handle);
1774 }
1775 }
1776 }
1777
1778 this.report_editor_event("Editor Opened", None, cx);
1779 this
1780 }
1781
1782 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1783 self.mouse_context_menu
1784 .as_ref()
1785 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1786 }
1787
1788 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1789 let mut key_context = KeyContext::new_with_defaults();
1790 key_context.add("Editor");
1791 let mode = match self.mode {
1792 EditorMode::SingleLine { .. } => "single_line",
1793 EditorMode::AutoHeight { .. } => "auto_height",
1794 EditorMode::Full => "full",
1795 };
1796
1797 if EditorSettings::jupyter_enabled(cx) {
1798 key_context.add("jupyter");
1799 }
1800
1801 key_context.set("mode", mode);
1802 if self.pending_rename.is_some() {
1803 key_context.add("renaming");
1804 }
1805
1806 let mut showing_completions = false;
1807
1808 match self.context_menu.borrow().as_ref() {
1809 Some(CodeContextMenu::Completions(_)) => {
1810 key_context.add("menu");
1811 key_context.add("showing_completions");
1812 showing_completions = true;
1813 }
1814 Some(CodeContextMenu::CodeActions(_)) => {
1815 key_context.add("menu");
1816 key_context.add("showing_code_actions")
1817 }
1818 None => {}
1819 }
1820
1821 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1822 if !self.focus_handle(cx).contains_focused(window, cx)
1823 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1824 {
1825 for addon in self.addons.values() {
1826 addon.extend_key_context(&mut key_context, cx)
1827 }
1828 }
1829
1830 if let Some(extension) = self
1831 .buffer
1832 .read(cx)
1833 .as_singleton()
1834 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1835 {
1836 key_context.set("extension", extension.to_string());
1837 }
1838
1839 if self.has_active_inline_completion() {
1840 key_context.add("copilot_suggestion");
1841 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1842
1843 if showing_completions || self.edit_prediction_requires_modifier() {
1844 key_context.add(EDIT_PREDICTION_REQUIRES_MODIFIER_KEY_CONTEXT);
1845 }
1846 }
1847
1848 if self.selection_mark_mode {
1849 key_context.add("selection_mode");
1850 }
1851
1852 key_context
1853 }
1854
1855 pub fn accept_edit_prediction_keybind(
1856 &self,
1857 window: &Window,
1858 cx: &App,
1859 ) -> AcceptEditPredictionBinding {
1860 let mut context = self.key_context(window, cx);
1861 context.add(EDIT_PREDICTION_KEY_CONTEXT);
1862
1863 AcceptEditPredictionBinding(
1864 window
1865 .bindings_for_action_in_context(&AcceptEditPrediction, context)
1866 .into_iter()
1867 .rev()
1868 .next(),
1869 )
1870 }
1871
1872 pub fn new_file(
1873 workspace: &mut Workspace,
1874 _: &workspace::NewFile,
1875 window: &mut Window,
1876 cx: &mut Context<Workspace>,
1877 ) {
1878 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1879 "Failed to create buffer",
1880 window,
1881 cx,
1882 |e, _, _| match e.error_code() {
1883 ErrorCode::RemoteUpgradeRequired => Some(format!(
1884 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1885 e.error_tag("required").unwrap_or("the latest version")
1886 )),
1887 _ => None,
1888 },
1889 );
1890 }
1891
1892 pub fn new_in_workspace(
1893 workspace: &mut Workspace,
1894 window: &mut Window,
1895 cx: &mut Context<Workspace>,
1896 ) -> Task<Result<Entity<Editor>>> {
1897 let project = workspace.project().clone();
1898 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1899
1900 cx.spawn_in(window, |workspace, mut cx| async move {
1901 let buffer = create.await?;
1902 workspace.update_in(&mut cx, |workspace, window, cx| {
1903 let editor =
1904 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1905 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1906 editor
1907 })
1908 })
1909 }
1910
1911 fn new_file_vertical(
1912 workspace: &mut Workspace,
1913 _: &workspace::NewFileSplitVertical,
1914 window: &mut Window,
1915 cx: &mut Context<Workspace>,
1916 ) {
1917 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1918 }
1919
1920 fn new_file_horizontal(
1921 workspace: &mut Workspace,
1922 _: &workspace::NewFileSplitHorizontal,
1923 window: &mut Window,
1924 cx: &mut Context<Workspace>,
1925 ) {
1926 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1927 }
1928
1929 fn new_file_in_direction(
1930 workspace: &mut Workspace,
1931 direction: SplitDirection,
1932 window: &mut Window,
1933 cx: &mut Context<Workspace>,
1934 ) {
1935 let project = workspace.project().clone();
1936 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1937
1938 cx.spawn_in(window, |workspace, mut cx| async move {
1939 let buffer = create.await?;
1940 workspace.update_in(&mut cx, move |workspace, window, cx| {
1941 workspace.split_item(
1942 direction,
1943 Box::new(
1944 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1945 ),
1946 window,
1947 cx,
1948 )
1949 })?;
1950 anyhow::Ok(())
1951 })
1952 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1953 match e.error_code() {
1954 ErrorCode::RemoteUpgradeRequired => Some(format!(
1955 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1956 e.error_tag("required").unwrap_or("the latest version")
1957 )),
1958 _ => None,
1959 }
1960 });
1961 }
1962
1963 pub fn leader_peer_id(&self) -> Option<PeerId> {
1964 self.leader_peer_id
1965 }
1966
1967 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1968 &self.buffer
1969 }
1970
1971 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1972 self.workspace.as_ref()?.0.upgrade()
1973 }
1974
1975 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1976 self.buffer().read(cx).title(cx)
1977 }
1978
1979 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1980 let git_blame_gutter_max_author_length = self
1981 .render_git_blame_gutter(cx)
1982 .then(|| {
1983 if let Some(blame) = self.blame.as_ref() {
1984 let max_author_length =
1985 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1986 Some(max_author_length)
1987 } else {
1988 None
1989 }
1990 })
1991 .flatten();
1992
1993 EditorSnapshot {
1994 mode: self.mode,
1995 show_gutter: self.show_gutter,
1996 show_line_numbers: self.show_line_numbers,
1997 show_git_diff_gutter: self.show_git_diff_gutter,
1998 show_code_actions: self.show_code_actions,
1999 show_runnables: self.show_runnables,
2000 git_blame_gutter_max_author_length,
2001 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2002 scroll_anchor: self.scroll_manager.anchor(),
2003 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2004 placeholder_text: self.placeholder_text.clone(),
2005 is_focused: self.focus_handle.is_focused(window),
2006 current_line_highlight: self
2007 .current_line_highlight
2008 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2009 gutter_hovered: self.gutter_hovered,
2010 }
2011 }
2012
2013 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
2014 self.buffer.read(cx).language_at(point, cx)
2015 }
2016
2017 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
2018 self.buffer.read(cx).read(cx).file_at(point).cloned()
2019 }
2020
2021 pub fn active_excerpt(
2022 &self,
2023 cx: &App,
2024 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
2025 self.buffer
2026 .read(cx)
2027 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2028 }
2029
2030 pub fn mode(&self) -> EditorMode {
2031 self.mode
2032 }
2033
2034 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2035 self.collaboration_hub.as_deref()
2036 }
2037
2038 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2039 self.collaboration_hub = Some(hub);
2040 }
2041
2042 pub fn set_in_project_search(&mut self, in_project_search: bool) {
2043 self.in_project_search = in_project_search;
2044 }
2045
2046 pub fn set_custom_context_menu(
2047 &mut self,
2048 f: impl 'static
2049 + Fn(
2050 &mut Self,
2051 DisplayPoint,
2052 &mut Window,
2053 &mut Context<Self>,
2054 ) -> Option<Entity<ui::ContextMenu>>,
2055 ) {
2056 self.custom_context_menu = Some(Box::new(f))
2057 }
2058
2059 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2060 self.completion_provider = provider;
2061 }
2062
2063 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2064 self.semantics_provider.clone()
2065 }
2066
2067 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2068 self.semantics_provider = provider;
2069 }
2070
2071 pub fn set_edit_prediction_provider<T>(
2072 &mut self,
2073 provider: Option<Entity<T>>,
2074 window: &mut Window,
2075 cx: &mut Context<Self>,
2076 ) where
2077 T: EditPredictionProvider,
2078 {
2079 self.edit_prediction_provider =
2080 provider.map(|provider| RegisteredInlineCompletionProvider {
2081 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
2082 if this.focus_handle.is_focused(window) {
2083 this.update_visible_inline_completion(window, cx);
2084 }
2085 }),
2086 provider: Arc::new(provider),
2087 });
2088 self.refresh_inline_completion(false, false, window, cx);
2089 }
2090
2091 pub fn placeholder_text(&self) -> Option<&str> {
2092 self.placeholder_text.as_deref()
2093 }
2094
2095 pub fn set_placeholder_text(
2096 &mut self,
2097 placeholder_text: impl Into<Arc<str>>,
2098 cx: &mut Context<Self>,
2099 ) {
2100 let placeholder_text = Some(placeholder_text.into());
2101 if self.placeholder_text != placeholder_text {
2102 self.placeholder_text = placeholder_text;
2103 cx.notify();
2104 }
2105 }
2106
2107 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
2108 self.cursor_shape = cursor_shape;
2109
2110 // Disrupt blink for immediate user feedback that the cursor shape has changed
2111 self.blink_manager.update(cx, BlinkManager::show_cursor);
2112
2113 cx.notify();
2114 }
2115
2116 pub fn set_current_line_highlight(
2117 &mut self,
2118 current_line_highlight: Option<CurrentLineHighlight>,
2119 ) {
2120 self.current_line_highlight = current_line_highlight;
2121 }
2122
2123 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2124 self.collapse_matches = collapse_matches;
2125 }
2126
2127 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
2128 let buffers = self.buffer.read(cx).all_buffers();
2129 let Some(lsp_store) = self.lsp_store(cx) else {
2130 return;
2131 };
2132 lsp_store.update(cx, |lsp_store, cx| {
2133 for buffer in buffers {
2134 self.registered_buffers
2135 .entry(buffer.read(cx).remote_id())
2136 .or_insert_with(|| {
2137 lsp_store.register_buffer_with_language_servers(&buffer, cx)
2138 });
2139 }
2140 })
2141 }
2142
2143 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2144 if self.collapse_matches {
2145 return range.start..range.start;
2146 }
2147 range.clone()
2148 }
2149
2150 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
2151 if self.display_map.read(cx).clip_at_line_ends != clip {
2152 self.display_map
2153 .update(cx, |map, _| map.clip_at_line_ends = clip);
2154 }
2155 }
2156
2157 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2158 self.input_enabled = input_enabled;
2159 }
2160
2161 pub fn set_inline_completions_hidden_for_vim_mode(
2162 &mut self,
2163 hidden: bool,
2164 window: &mut Window,
2165 cx: &mut Context<Self>,
2166 ) {
2167 if hidden != self.inline_completions_hidden_for_vim_mode {
2168 self.inline_completions_hidden_for_vim_mode = hidden;
2169 if hidden {
2170 self.update_visible_inline_completion(window, cx);
2171 } else {
2172 self.refresh_inline_completion(true, false, window, cx);
2173 }
2174 }
2175 }
2176
2177 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
2178 self.menu_inline_completions_policy = value;
2179 }
2180
2181 pub fn set_autoindent(&mut self, autoindent: bool) {
2182 if autoindent {
2183 self.autoindent_mode = Some(AutoindentMode::EachLine);
2184 } else {
2185 self.autoindent_mode = None;
2186 }
2187 }
2188
2189 pub fn read_only(&self, cx: &App) -> bool {
2190 self.read_only || self.buffer.read(cx).read_only()
2191 }
2192
2193 pub fn set_read_only(&mut self, read_only: bool) {
2194 self.read_only = read_only;
2195 }
2196
2197 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2198 self.use_autoclose = autoclose;
2199 }
2200
2201 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2202 self.use_auto_surround = auto_surround;
2203 }
2204
2205 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2206 self.auto_replace_emoji_shortcode = auto_replace;
2207 }
2208
2209 pub fn toggle_inline_completions(
2210 &mut self,
2211 _: &ToggleEditPrediction,
2212 window: &mut Window,
2213 cx: &mut Context<Self>,
2214 ) {
2215 if self.show_inline_completions_override.is_some() {
2216 self.set_show_edit_predictions(None, window, cx);
2217 } else {
2218 let show_edit_predictions = !self.edit_predictions_enabled();
2219 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2220 }
2221 }
2222
2223 pub fn set_show_edit_predictions(
2224 &mut self,
2225 show_edit_predictions: Option<bool>,
2226 window: &mut Window,
2227 cx: &mut Context<Self>,
2228 ) {
2229 self.show_inline_completions_override = show_edit_predictions;
2230 self.refresh_inline_completion(false, true, window, cx);
2231 }
2232
2233 fn inline_completions_disabled_in_scope(
2234 &self,
2235 buffer: &Entity<Buffer>,
2236 buffer_position: language::Anchor,
2237 cx: &App,
2238 ) -> bool {
2239 let snapshot = buffer.read(cx).snapshot();
2240 let settings = snapshot.settings_at(buffer_position, cx);
2241
2242 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2243 return false;
2244 };
2245
2246 scope.override_name().map_or(false, |scope_name| {
2247 settings
2248 .edit_predictions_disabled_in
2249 .iter()
2250 .any(|s| s == scope_name)
2251 })
2252 }
2253
2254 pub fn set_use_modal_editing(&mut self, to: bool) {
2255 self.use_modal_editing = to;
2256 }
2257
2258 pub fn use_modal_editing(&self) -> bool {
2259 self.use_modal_editing
2260 }
2261
2262 fn selections_did_change(
2263 &mut self,
2264 local: bool,
2265 old_cursor_position: &Anchor,
2266 show_completions: bool,
2267 window: &mut Window,
2268 cx: &mut Context<Self>,
2269 ) {
2270 window.invalidate_character_coordinates();
2271
2272 // Copy selections to primary selection buffer
2273 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2274 if local {
2275 let selections = self.selections.all::<usize>(cx);
2276 let buffer_handle = self.buffer.read(cx).read(cx);
2277
2278 let mut text = String::new();
2279 for (index, selection) in selections.iter().enumerate() {
2280 let text_for_selection = buffer_handle
2281 .text_for_range(selection.start..selection.end)
2282 .collect::<String>();
2283
2284 text.push_str(&text_for_selection);
2285 if index != selections.len() - 1 {
2286 text.push('\n');
2287 }
2288 }
2289
2290 if !text.is_empty() {
2291 cx.write_to_primary(ClipboardItem::new_string(text));
2292 }
2293 }
2294
2295 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2296 self.buffer.update(cx, |buffer, cx| {
2297 buffer.set_active_selections(
2298 &self.selections.disjoint_anchors(),
2299 self.selections.line_mode,
2300 self.cursor_shape,
2301 cx,
2302 )
2303 });
2304 }
2305 let display_map = self
2306 .display_map
2307 .update(cx, |display_map, cx| display_map.snapshot(cx));
2308 let buffer = &display_map.buffer_snapshot;
2309 self.add_selections_state = None;
2310 self.select_next_state = None;
2311 self.select_prev_state = None;
2312 self.select_larger_syntax_node_stack.clear();
2313 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2314 self.snippet_stack
2315 .invalidate(&self.selections.disjoint_anchors(), buffer);
2316 self.take_rename(false, window, cx);
2317
2318 let new_cursor_position = self.selections.newest_anchor().head();
2319
2320 self.push_to_nav_history(
2321 *old_cursor_position,
2322 Some(new_cursor_position.to_point(buffer)),
2323 cx,
2324 );
2325
2326 if local {
2327 let new_cursor_position = self.selections.newest_anchor().head();
2328 let mut context_menu = self.context_menu.borrow_mut();
2329 let completion_menu = match context_menu.as_ref() {
2330 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2331 _ => {
2332 *context_menu = None;
2333 None
2334 }
2335 };
2336 if let Some(buffer_id) = new_cursor_position.buffer_id {
2337 if !self.registered_buffers.contains_key(&buffer_id) {
2338 if let Some(lsp_store) = self.lsp_store(cx) {
2339 lsp_store.update(cx, |lsp_store, cx| {
2340 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2341 return;
2342 };
2343 self.registered_buffers.insert(
2344 buffer_id,
2345 lsp_store.register_buffer_with_language_servers(&buffer, cx),
2346 );
2347 })
2348 }
2349 }
2350 }
2351
2352 if let Some(completion_menu) = completion_menu {
2353 let cursor_position = new_cursor_position.to_offset(buffer);
2354 let (word_range, kind) =
2355 buffer.surrounding_word(completion_menu.initial_position, true);
2356 if kind == Some(CharKind::Word)
2357 && word_range.to_inclusive().contains(&cursor_position)
2358 {
2359 let mut completion_menu = completion_menu.clone();
2360 drop(context_menu);
2361
2362 let query = Self::completion_query(buffer, cursor_position);
2363 cx.spawn(move |this, mut cx| async move {
2364 completion_menu
2365 .filter(query.as_deref(), cx.background_executor().clone())
2366 .await;
2367
2368 this.update(&mut cx, |this, cx| {
2369 let mut context_menu = this.context_menu.borrow_mut();
2370 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2371 else {
2372 return;
2373 };
2374
2375 if menu.id > completion_menu.id {
2376 return;
2377 }
2378
2379 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2380 drop(context_menu);
2381 cx.notify();
2382 })
2383 })
2384 .detach();
2385
2386 if show_completions {
2387 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2388 }
2389 } else {
2390 drop(context_menu);
2391 self.hide_context_menu(window, cx);
2392 }
2393 } else {
2394 drop(context_menu);
2395 }
2396
2397 hide_hover(self, cx);
2398
2399 if old_cursor_position.to_display_point(&display_map).row()
2400 != new_cursor_position.to_display_point(&display_map).row()
2401 {
2402 self.available_code_actions.take();
2403 }
2404 self.refresh_code_actions(window, cx);
2405 self.refresh_document_highlights(cx);
2406 refresh_matching_bracket_highlights(self, window, cx);
2407 self.update_visible_inline_completion(window, cx);
2408 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2409 if self.git_blame_inline_enabled {
2410 self.start_inline_blame_timer(window, cx);
2411 }
2412 }
2413
2414 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2415 cx.emit(EditorEvent::SelectionsChanged { local });
2416
2417 if self.selections.disjoint_anchors().len() == 1 {
2418 cx.emit(SearchEvent::ActiveMatchChanged)
2419 }
2420 cx.notify();
2421 }
2422
2423 pub fn change_selections<R>(
2424 &mut self,
2425 autoscroll: Option<Autoscroll>,
2426 window: &mut Window,
2427 cx: &mut Context<Self>,
2428 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2429 ) -> R {
2430 self.change_selections_inner(autoscroll, true, window, cx, change)
2431 }
2432
2433 pub fn change_selections_inner<R>(
2434 &mut self,
2435 autoscroll: Option<Autoscroll>,
2436 request_completions: bool,
2437 window: &mut Window,
2438 cx: &mut Context<Self>,
2439 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2440 ) -> R {
2441 let old_cursor_position = self.selections.newest_anchor().head();
2442 self.push_to_selection_history();
2443
2444 let (changed, result) = self.selections.change_with(cx, change);
2445
2446 if changed {
2447 if let Some(autoscroll) = autoscroll {
2448 self.request_autoscroll(autoscroll, cx);
2449 }
2450 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2451
2452 if self.should_open_signature_help_automatically(
2453 &old_cursor_position,
2454 self.signature_help_state.backspace_pressed(),
2455 cx,
2456 ) {
2457 self.show_signature_help(&ShowSignatureHelp, window, cx);
2458 }
2459 self.signature_help_state.set_backspace_pressed(false);
2460 }
2461
2462 result
2463 }
2464
2465 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2466 where
2467 I: IntoIterator<Item = (Range<S>, T)>,
2468 S: ToOffset,
2469 T: Into<Arc<str>>,
2470 {
2471 if self.read_only(cx) {
2472 return;
2473 }
2474
2475 self.buffer
2476 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2477 }
2478
2479 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2480 where
2481 I: IntoIterator<Item = (Range<S>, T)>,
2482 S: ToOffset,
2483 T: Into<Arc<str>>,
2484 {
2485 if self.read_only(cx) {
2486 return;
2487 }
2488
2489 self.buffer.update(cx, |buffer, cx| {
2490 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2491 });
2492 }
2493
2494 pub fn edit_with_block_indent<I, S, T>(
2495 &mut self,
2496 edits: I,
2497 original_indent_columns: Vec<u32>,
2498 cx: &mut Context<Self>,
2499 ) where
2500 I: IntoIterator<Item = (Range<S>, T)>,
2501 S: ToOffset,
2502 T: Into<Arc<str>>,
2503 {
2504 if self.read_only(cx) {
2505 return;
2506 }
2507
2508 self.buffer.update(cx, |buffer, cx| {
2509 buffer.edit(
2510 edits,
2511 Some(AutoindentMode::Block {
2512 original_indent_columns,
2513 }),
2514 cx,
2515 )
2516 });
2517 }
2518
2519 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2520 self.hide_context_menu(window, cx);
2521
2522 match phase {
2523 SelectPhase::Begin {
2524 position,
2525 add,
2526 click_count,
2527 } => self.begin_selection(position, add, click_count, window, cx),
2528 SelectPhase::BeginColumnar {
2529 position,
2530 goal_column,
2531 reset,
2532 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2533 SelectPhase::Extend {
2534 position,
2535 click_count,
2536 } => self.extend_selection(position, click_count, window, cx),
2537 SelectPhase::Update {
2538 position,
2539 goal_column,
2540 scroll_delta,
2541 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2542 SelectPhase::End => self.end_selection(window, cx),
2543 }
2544 }
2545
2546 fn extend_selection(
2547 &mut self,
2548 position: DisplayPoint,
2549 click_count: usize,
2550 window: &mut Window,
2551 cx: &mut Context<Self>,
2552 ) {
2553 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2554 let tail = self.selections.newest::<usize>(cx).tail();
2555 self.begin_selection(position, false, click_count, window, cx);
2556
2557 let position = position.to_offset(&display_map, Bias::Left);
2558 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2559
2560 let mut pending_selection = self
2561 .selections
2562 .pending_anchor()
2563 .expect("extend_selection not called with pending selection");
2564 if position >= tail {
2565 pending_selection.start = tail_anchor;
2566 } else {
2567 pending_selection.end = tail_anchor;
2568 pending_selection.reversed = true;
2569 }
2570
2571 let mut pending_mode = self.selections.pending_mode().unwrap();
2572 match &mut pending_mode {
2573 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2574 _ => {}
2575 }
2576
2577 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2578 s.set_pending(pending_selection, pending_mode)
2579 });
2580 }
2581
2582 fn begin_selection(
2583 &mut self,
2584 position: DisplayPoint,
2585 add: bool,
2586 click_count: usize,
2587 window: &mut Window,
2588 cx: &mut Context<Self>,
2589 ) {
2590 if !self.focus_handle.is_focused(window) {
2591 self.last_focused_descendant = None;
2592 window.focus(&self.focus_handle);
2593 }
2594
2595 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2596 let buffer = &display_map.buffer_snapshot;
2597 let newest_selection = self.selections.newest_anchor().clone();
2598 let position = display_map.clip_point(position, Bias::Left);
2599
2600 let start;
2601 let end;
2602 let mode;
2603 let mut auto_scroll;
2604 match click_count {
2605 1 => {
2606 start = buffer.anchor_before(position.to_point(&display_map));
2607 end = start;
2608 mode = SelectMode::Character;
2609 auto_scroll = true;
2610 }
2611 2 => {
2612 let range = movement::surrounding_word(&display_map, position);
2613 start = buffer.anchor_before(range.start.to_point(&display_map));
2614 end = buffer.anchor_before(range.end.to_point(&display_map));
2615 mode = SelectMode::Word(start..end);
2616 auto_scroll = true;
2617 }
2618 3 => {
2619 let position = display_map
2620 .clip_point(position, Bias::Left)
2621 .to_point(&display_map);
2622 let line_start = display_map.prev_line_boundary(position).0;
2623 let next_line_start = buffer.clip_point(
2624 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2625 Bias::Left,
2626 );
2627 start = buffer.anchor_before(line_start);
2628 end = buffer.anchor_before(next_line_start);
2629 mode = SelectMode::Line(start..end);
2630 auto_scroll = true;
2631 }
2632 _ => {
2633 start = buffer.anchor_before(0);
2634 end = buffer.anchor_before(buffer.len());
2635 mode = SelectMode::All;
2636 auto_scroll = false;
2637 }
2638 }
2639 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2640
2641 let point_to_delete: Option<usize> = {
2642 let selected_points: Vec<Selection<Point>> =
2643 self.selections.disjoint_in_range(start..end, cx);
2644
2645 if !add || click_count > 1 {
2646 None
2647 } else if !selected_points.is_empty() {
2648 Some(selected_points[0].id)
2649 } else {
2650 let clicked_point_already_selected =
2651 self.selections.disjoint.iter().find(|selection| {
2652 selection.start.to_point(buffer) == start.to_point(buffer)
2653 || selection.end.to_point(buffer) == end.to_point(buffer)
2654 });
2655
2656 clicked_point_already_selected.map(|selection| selection.id)
2657 }
2658 };
2659
2660 let selections_count = self.selections.count();
2661
2662 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2663 if let Some(point_to_delete) = point_to_delete {
2664 s.delete(point_to_delete);
2665
2666 if selections_count == 1 {
2667 s.set_pending_anchor_range(start..end, mode);
2668 }
2669 } else {
2670 if !add {
2671 s.clear_disjoint();
2672 } else if click_count > 1 {
2673 s.delete(newest_selection.id)
2674 }
2675
2676 s.set_pending_anchor_range(start..end, mode);
2677 }
2678 });
2679 }
2680
2681 fn begin_columnar_selection(
2682 &mut self,
2683 position: DisplayPoint,
2684 goal_column: u32,
2685 reset: bool,
2686 window: &mut Window,
2687 cx: &mut Context<Self>,
2688 ) {
2689 if !self.focus_handle.is_focused(window) {
2690 self.last_focused_descendant = None;
2691 window.focus(&self.focus_handle);
2692 }
2693
2694 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2695
2696 if reset {
2697 let pointer_position = display_map
2698 .buffer_snapshot
2699 .anchor_before(position.to_point(&display_map));
2700
2701 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2702 s.clear_disjoint();
2703 s.set_pending_anchor_range(
2704 pointer_position..pointer_position,
2705 SelectMode::Character,
2706 );
2707 });
2708 }
2709
2710 let tail = self.selections.newest::<Point>(cx).tail();
2711 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2712
2713 if !reset {
2714 self.select_columns(
2715 tail.to_display_point(&display_map),
2716 position,
2717 goal_column,
2718 &display_map,
2719 window,
2720 cx,
2721 );
2722 }
2723 }
2724
2725 fn update_selection(
2726 &mut self,
2727 position: DisplayPoint,
2728 goal_column: u32,
2729 scroll_delta: gpui::Point<f32>,
2730 window: &mut Window,
2731 cx: &mut Context<Self>,
2732 ) {
2733 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2734
2735 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2736 let tail = tail.to_display_point(&display_map);
2737 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2738 } else if let Some(mut pending) = self.selections.pending_anchor() {
2739 let buffer = self.buffer.read(cx).snapshot(cx);
2740 let head;
2741 let tail;
2742 let mode = self.selections.pending_mode().unwrap();
2743 match &mode {
2744 SelectMode::Character => {
2745 head = position.to_point(&display_map);
2746 tail = pending.tail().to_point(&buffer);
2747 }
2748 SelectMode::Word(original_range) => {
2749 let original_display_range = original_range.start.to_display_point(&display_map)
2750 ..original_range.end.to_display_point(&display_map);
2751 let original_buffer_range = original_display_range.start.to_point(&display_map)
2752 ..original_display_range.end.to_point(&display_map);
2753 if movement::is_inside_word(&display_map, position)
2754 || original_display_range.contains(&position)
2755 {
2756 let word_range = movement::surrounding_word(&display_map, position);
2757 if word_range.start < original_display_range.start {
2758 head = word_range.start.to_point(&display_map);
2759 } else {
2760 head = word_range.end.to_point(&display_map);
2761 }
2762 } else {
2763 head = position.to_point(&display_map);
2764 }
2765
2766 if head <= original_buffer_range.start {
2767 tail = original_buffer_range.end;
2768 } else {
2769 tail = original_buffer_range.start;
2770 }
2771 }
2772 SelectMode::Line(original_range) => {
2773 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2774
2775 let position = display_map
2776 .clip_point(position, Bias::Left)
2777 .to_point(&display_map);
2778 let line_start = display_map.prev_line_boundary(position).0;
2779 let next_line_start = buffer.clip_point(
2780 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2781 Bias::Left,
2782 );
2783
2784 if line_start < original_range.start {
2785 head = line_start
2786 } else {
2787 head = next_line_start
2788 }
2789
2790 if head <= original_range.start {
2791 tail = original_range.end;
2792 } else {
2793 tail = original_range.start;
2794 }
2795 }
2796 SelectMode::All => {
2797 return;
2798 }
2799 };
2800
2801 if head < tail {
2802 pending.start = buffer.anchor_before(head);
2803 pending.end = buffer.anchor_before(tail);
2804 pending.reversed = true;
2805 } else {
2806 pending.start = buffer.anchor_before(tail);
2807 pending.end = buffer.anchor_before(head);
2808 pending.reversed = false;
2809 }
2810
2811 self.change_selections(None, window, cx, |s| {
2812 s.set_pending(pending, mode);
2813 });
2814 } else {
2815 log::error!("update_selection dispatched with no pending selection");
2816 return;
2817 }
2818
2819 self.apply_scroll_delta(scroll_delta, window, cx);
2820 cx.notify();
2821 }
2822
2823 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2824 self.columnar_selection_tail.take();
2825 if self.selections.pending_anchor().is_some() {
2826 let selections = self.selections.all::<usize>(cx);
2827 self.change_selections(None, window, cx, |s| {
2828 s.select(selections);
2829 s.clear_pending();
2830 });
2831 }
2832 }
2833
2834 fn select_columns(
2835 &mut self,
2836 tail: DisplayPoint,
2837 head: DisplayPoint,
2838 goal_column: u32,
2839 display_map: &DisplaySnapshot,
2840 window: &mut Window,
2841 cx: &mut Context<Self>,
2842 ) {
2843 let start_row = cmp::min(tail.row(), head.row());
2844 let end_row = cmp::max(tail.row(), head.row());
2845 let start_column = cmp::min(tail.column(), goal_column);
2846 let end_column = cmp::max(tail.column(), goal_column);
2847 let reversed = start_column < tail.column();
2848
2849 let selection_ranges = (start_row.0..=end_row.0)
2850 .map(DisplayRow)
2851 .filter_map(|row| {
2852 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2853 let start = display_map
2854 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2855 .to_point(display_map);
2856 let end = display_map
2857 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2858 .to_point(display_map);
2859 if reversed {
2860 Some(end..start)
2861 } else {
2862 Some(start..end)
2863 }
2864 } else {
2865 None
2866 }
2867 })
2868 .collect::<Vec<_>>();
2869
2870 self.change_selections(None, window, cx, |s| {
2871 s.select_ranges(selection_ranges);
2872 });
2873 cx.notify();
2874 }
2875
2876 pub fn has_pending_nonempty_selection(&self) -> bool {
2877 let pending_nonempty_selection = match self.selections.pending_anchor() {
2878 Some(Selection { start, end, .. }) => start != end,
2879 None => false,
2880 };
2881
2882 pending_nonempty_selection
2883 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2884 }
2885
2886 pub fn has_pending_selection(&self) -> bool {
2887 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2888 }
2889
2890 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2891 self.selection_mark_mode = false;
2892
2893 if self.clear_expanded_diff_hunks(cx) {
2894 cx.notify();
2895 return;
2896 }
2897 if self.dismiss_menus_and_popups(true, window, cx) {
2898 return;
2899 }
2900
2901 if self.mode == EditorMode::Full
2902 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2903 {
2904 return;
2905 }
2906
2907 cx.propagate();
2908 }
2909
2910 pub fn dismiss_menus_and_popups(
2911 &mut self,
2912 is_user_requested: bool,
2913 window: &mut Window,
2914 cx: &mut Context<Self>,
2915 ) -> bool {
2916 if self.take_rename(false, window, cx).is_some() {
2917 return true;
2918 }
2919
2920 if hide_hover(self, cx) {
2921 return true;
2922 }
2923
2924 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2925 return true;
2926 }
2927
2928 if self.hide_context_menu(window, cx).is_some() {
2929 return true;
2930 }
2931
2932 if self.mouse_context_menu.take().is_some() {
2933 return true;
2934 }
2935
2936 if is_user_requested && self.discard_inline_completion(true, cx) {
2937 return true;
2938 }
2939
2940 if self.snippet_stack.pop().is_some() {
2941 return true;
2942 }
2943
2944 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2945 self.dismiss_diagnostics(cx);
2946 return true;
2947 }
2948
2949 false
2950 }
2951
2952 fn linked_editing_ranges_for(
2953 &self,
2954 selection: Range<text::Anchor>,
2955 cx: &App,
2956 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2957 if self.linked_edit_ranges.is_empty() {
2958 return None;
2959 }
2960 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2961 selection.end.buffer_id.and_then(|end_buffer_id| {
2962 if selection.start.buffer_id != Some(end_buffer_id) {
2963 return None;
2964 }
2965 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2966 let snapshot = buffer.read(cx).snapshot();
2967 self.linked_edit_ranges
2968 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2969 .map(|ranges| (ranges, snapshot, buffer))
2970 })?;
2971 use text::ToOffset as TO;
2972 // find offset from the start of current range to current cursor position
2973 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2974
2975 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2976 let start_difference = start_offset - start_byte_offset;
2977 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2978 let end_difference = end_offset - start_byte_offset;
2979 // Current range has associated linked ranges.
2980 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2981 for range in linked_ranges.iter() {
2982 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2983 let end_offset = start_offset + end_difference;
2984 let start_offset = start_offset + start_difference;
2985 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2986 continue;
2987 }
2988 if self.selections.disjoint_anchor_ranges().any(|s| {
2989 if s.start.buffer_id != selection.start.buffer_id
2990 || s.end.buffer_id != selection.end.buffer_id
2991 {
2992 return false;
2993 }
2994 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2995 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2996 }) {
2997 continue;
2998 }
2999 let start = buffer_snapshot.anchor_after(start_offset);
3000 let end = buffer_snapshot.anchor_after(end_offset);
3001 linked_edits
3002 .entry(buffer.clone())
3003 .or_default()
3004 .push(start..end);
3005 }
3006 Some(linked_edits)
3007 }
3008
3009 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3010 let text: Arc<str> = text.into();
3011
3012 if self.read_only(cx) {
3013 return;
3014 }
3015
3016 let selections = self.selections.all_adjusted(cx);
3017 let mut bracket_inserted = false;
3018 let mut edits = Vec::new();
3019 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3020 let mut new_selections = Vec::with_capacity(selections.len());
3021 let mut new_autoclose_regions = Vec::new();
3022 let snapshot = self.buffer.read(cx).read(cx);
3023
3024 for (selection, autoclose_region) in
3025 self.selections_with_autoclose_regions(selections, &snapshot)
3026 {
3027 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3028 // Determine if the inserted text matches the opening or closing
3029 // bracket of any of this language's bracket pairs.
3030 let mut bracket_pair = None;
3031 let mut is_bracket_pair_start = false;
3032 let mut is_bracket_pair_end = false;
3033 if !text.is_empty() {
3034 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3035 // and they are removing the character that triggered IME popup.
3036 for (pair, enabled) in scope.brackets() {
3037 if !pair.close && !pair.surround {
3038 continue;
3039 }
3040
3041 if enabled && pair.start.ends_with(text.as_ref()) {
3042 let prefix_len = pair.start.len() - text.len();
3043 let preceding_text_matches_prefix = prefix_len == 0
3044 || (selection.start.column >= (prefix_len as u32)
3045 && snapshot.contains_str_at(
3046 Point::new(
3047 selection.start.row,
3048 selection.start.column - (prefix_len as u32),
3049 ),
3050 &pair.start[..prefix_len],
3051 ));
3052 if preceding_text_matches_prefix {
3053 bracket_pair = Some(pair.clone());
3054 is_bracket_pair_start = true;
3055 break;
3056 }
3057 }
3058 if pair.end.as_str() == text.as_ref() {
3059 bracket_pair = Some(pair.clone());
3060 is_bracket_pair_end = true;
3061 break;
3062 }
3063 }
3064 }
3065
3066 if let Some(bracket_pair) = bracket_pair {
3067 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3068 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3069 let auto_surround =
3070 self.use_auto_surround && snapshot_settings.use_auto_surround;
3071 if selection.is_empty() {
3072 if is_bracket_pair_start {
3073 // If the inserted text is a suffix of an opening bracket and the
3074 // selection is preceded by the rest of the opening bracket, then
3075 // insert the closing bracket.
3076 let following_text_allows_autoclose = snapshot
3077 .chars_at(selection.start)
3078 .next()
3079 .map_or(true, |c| scope.should_autoclose_before(c));
3080
3081 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3082 && bracket_pair.start.len() == 1
3083 {
3084 let target = bracket_pair.start.chars().next().unwrap();
3085 let current_line_count = snapshot
3086 .reversed_chars_at(selection.start)
3087 .take_while(|&c| c != '\n')
3088 .filter(|&c| c == target)
3089 .count();
3090 current_line_count % 2 == 1
3091 } else {
3092 false
3093 };
3094
3095 if autoclose
3096 && bracket_pair.close
3097 && following_text_allows_autoclose
3098 && !is_closing_quote
3099 {
3100 let anchor = snapshot.anchor_before(selection.end);
3101 new_selections.push((selection.map(|_| anchor), text.len()));
3102 new_autoclose_regions.push((
3103 anchor,
3104 text.len(),
3105 selection.id,
3106 bracket_pair.clone(),
3107 ));
3108 edits.push((
3109 selection.range(),
3110 format!("{}{}", text, bracket_pair.end).into(),
3111 ));
3112 bracket_inserted = true;
3113 continue;
3114 }
3115 }
3116
3117 if let Some(region) = autoclose_region {
3118 // If the selection is followed by an auto-inserted closing bracket,
3119 // then don't insert that closing bracket again; just move the selection
3120 // past the closing bracket.
3121 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3122 && text.as_ref() == region.pair.end.as_str();
3123 if should_skip {
3124 let anchor = snapshot.anchor_after(selection.end);
3125 new_selections
3126 .push((selection.map(|_| anchor), region.pair.end.len()));
3127 continue;
3128 }
3129 }
3130
3131 let always_treat_brackets_as_autoclosed = snapshot
3132 .settings_at(selection.start, cx)
3133 .always_treat_brackets_as_autoclosed;
3134 if always_treat_brackets_as_autoclosed
3135 && is_bracket_pair_end
3136 && snapshot.contains_str_at(selection.end, text.as_ref())
3137 {
3138 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3139 // and the inserted text is a closing bracket and the selection is followed
3140 // by the closing bracket then move the selection past the closing bracket.
3141 let anchor = snapshot.anchor_after(selection.end);
3142 new_selections.push((selection.map(|_| anchor), text.len()));
3143 continue;
3144 }
3145 }
3146 // If an opening bracket is 1 character long and is typed while
3147 // text is selected, then surround that text with the bracket pair.
3148 else if auto_surround
3149 && bracket_pair.surround
3150 && is_bracket_pair_start
3151 && bracket_pair.start.chars().count() == 1
3152 {
3153 edits.push((selection.start..selection.start, text.clone()));
3154 edits.push((
3155 selection.end..selection.end,
3156 bracket_pair.end.as_str().into(),
3157 ));
3158 bracket_inserted = true;
3159 new_selections.push((
3160 Selection {
3161 id: selection.id,
3162 start: snapshot.anchor_after(selection.start),
3163 end: snapshot.anchor_before(selection.end),
3164 reversed: selection.reversed,
3165 goal: selection.goal,
3166 },
3167 0,
3168 ));
3169 continue;
3170 }
3171 }
3172 }
3173
3174 if self.auto_replace_emoji_shortcode
3175 && selection.is_empty()
3176 && text.as_ref().ends_with(':')
3177 {
3178 if let Some(possible_emoji_short_code) =
3179 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3180 {
3181 if !possible_emoji_short_code.is_empty() {
3182 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3183 let emoji_shortcode_start = Point::new(
3184 selection.start.row,
3185 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3186 );
3187
3188 // Remove shortcode from buffer
3189 edits.push((
3190 emoji_shortcode_start..selection.start,
3191 "".to_string().into(),
3192 ));
3193 new_selections.push((
3194 Selection {
3195 id: selection.id,
3196 start: snapshot.anchor_after(emoji_shortcode_start),
3197 end: snapshot.anchor_before(selection.start),
3198 reversed: selection.reversed,
3199 goal: selection.goal,
3200 },
3201 0,
3202 ));
3203
3204 // Insert emoji
3205 let selection_start_anchor = snapshot.anchor_after(selection.start);
3206 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3207 edits.push((selection.start..selection.end, emoji.to_string().into()));
3208
3209 continue;
3210 }
3211 }
3212 }
3213 }
3214
3215 // If not handling any auto-close operation, then just replace the selected
3216 // text with the given input and move the selection to the end of the
3217 // newly inserted text.
3218 let anchor = snapshot.anchor_after(selection.end);
3219 if !self.linked_edit_ranges.is_empty() {
3220 let start_anchor = snapshot.anchor_before(selection.start);
3221
3222 let is_word_char = text.chars().next().map_or(true, |char| {
3223 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3224 classifier.is_word(char)
3225 });
3226
3227 if is_word_char {
3228 if let Some(ranges) = self
3229 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3230 {
3231 for (buffer, edits) in ranges {
3232 linked_edits
3233 .entry(buffer.clone())
3234 .or_default()
3235 .extend(edits.into_iter().map(|range| (range, text.clone())));
3236 }
3237 }
3238 }
3239 }
3240
3241 new_selections.push((selection.map(|_| anchor), 0));
3242 edits.push((selection.start..selection.end, text.clone()));
3243 }
3244
3245 drop(snapshot);
3246
3247 self.transact(window, cx, |this, window, cx| {
3248 this.buffer.update(cx, |buffer, cx| {
3249 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3250 });
3251 for (buffer, edits) in linked_edits {
3252 buffer.update(cx, |buffer, cx| {
3253 let snapshot = buffer.snapshot();
3254 let edits = edits
3255 .into_iter()
3256 .map(|(range, text)| {
3257 use text::ToPoint as TP;
3258 let end_point = TP::to_point(&range.end, &snapshot);
3259 let start_point = TP::to_point(&range.start, &snapshot);
3260 (start_point..end_point, text)
3261 })
3262 .sorted_by_key(|(range, _)| range.start)
3263 .collect::<Vec<_>>();
3264 buffer.edit(edits, None, cx);
3265 })
3266 }
3267 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3268 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3269 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3270 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3271 .zip(new_selection_deltas)
3272 .map(|(selection, delta)| Selection {
3273 id: selection.id,
3274 start: selection.start + delta,
3275 end: selection.end + delta,
3276 reversed: selection.reversed,
3277 goal: SelectionGoal::None,
3278 })
3279 .collect::<Vec<_>>();
3280
3281 let mut i = 0;
3282 for (position, delta, selection_id, pair) in new_autoclose_regions {
3283 let position = position.to_offset(&map.buffer_snapshot) + delta;
3284 let start = map.buffer_snapshot.anchor_before(position);
3285 let end = map.buffer_snapshot.anchor_after(position);
3286 while let Some(existing_state) = this.autoclose_regions.get(i) {
3287 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3288 Ordering::Less => i += 1,
3289 Ordering::Greater => break,
3290 Ordering::Equal => {
3291 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3292 Ordering::Less => i += 1,
3293 Ordering::Equal => break,
3294 Ordering::Greater => break,
3295 }
3296 }
3297 }
3298 }
3299 this.autoclose_regions.insert(
3300 i,
3301 AutocloseRegion {
3302 selection_id,
3303 range: start..end,
3304 pair,
3305 },
3306 );
3307 }
3308
3309 let had_active_inline_completion = this.has_active_inline_completion();
3310 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3311 s.select(new_selections)
3312 });
3313
3314 if !bracket_inserted {
3315 if let Some(on_type_format_task) =
3316 this.trigger_on_type_formatting(text.to_string(), window, cx)
3317 {
3318 on_type_format_task.detach_and_log_err(cx);
3319 }
3320 }
3321
3322 let editor_settings = EditorSettings::get_global(cx);
3323 if bracket_inserted
3324 && (editor_settings.auto_signature_help
3325 || editor_settings.show_signature_help_after_edits)
3326 {
3327 this.show_signature_help(&ShowSignatureHelp, window, cx);
3328 }
3329
3330 let trigger_in_words =
3331 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3332 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3333 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3334 this.refresh_inline_completion(true, false, window, cx);
3335 });
3336 }
3337
3338 fn find_possible_emoji_shortcode_at_position(
3339 snapshot: &MultiBufferSnapshot,
3340 position: Point,
3341 ) -> Option<String> {
3342 let mut chars = Vec::new();
3343 let mut found_colon = false;
3344 for char in snapshot.reversed_chars_at(position).take(100) {
3345 // Found a possible emoji shortcode in the middle of the buffer
3346 if found_colon {
3347 if char.is_whitespace() {
3348 chars.reverse();
3349 return Some(chars.iter().collect());
3350 }
3351 // If the previous character is not a whitespace, we are in the middle of a word
3352 // and we only want to complete the shortcode if the word is made up of other emojis
3353 let mut containing_word = String::new();
3354 for ch in snapshot
3355 .reversed_chars_at(position)
3356 .skip(chars.len() + 1)
3357 .take(100)
3358 {
3359 if ch.is_whitespace() {
3360 break;
3361 }
3362 containing_word.push(ch);
3363 }
3364 let containing_word = containing_word.chars().rev().collect::<String>();
3365 if util::word_consists_of_emojis(containing_word.as_str()) {
3366 chars.reverse();
3367 return Some(chars.iter().collect());
3368 }
3369 }
3370
3371 if char.is_whitespace() || !char.is_ascii() {
3372 return None;
3373 }
3374 if char == ':' {
3375 found_colon = true;
3376 } else {
3377 chars.push(char);
3378 }
3379 }
3380 // Found a possible emoji shortcode at the beginning of the buffer
3381 chars.reverse();
3382 Some(chars.iter().collect())
3383 }
3384
3385 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3386 self.transact(window, cx, |this, window, cx| {
3387 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3388 let selections = this.selections.all::<usize>(cx);
3389 let multi_buffer = this.buffer.read(cx);
3390 let buffer = multi_buffer.snapshot(cx);
3391 selections
3392 .iter()
3393 .map(|selection| {
3394 let start_point = selection.start.to_point(&buffer);
3395 let mut indent =
3396 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3397 indent.len = cmp::min(indent.len, start_point.column);
3398 let start = selection.start;
3399 let end = selection.end;
3400 let selection_is_empty = start == end;
3401 let language_scope = buffer.language_scope_at(start);
3402 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3403 &language_scope
3404 {
3405 let leading_whitespace_len = buffer
3406 .reversed_chars_at(start)
3407 .take_while(|c| c.is_whitespace() && *c != '\n')
3408 .map(|c| c.len_utf8())
3409 .sum::<usize>();
3410
3411 let trailing_whitespace_len = buffer
3412 .chars_at(end)
3413 .take_while(|c| c.is_whitespace() && *c != '\n')
3414 .map(|c| c.len_utf8())
3415 .sum::<usize>();
3416
3417 let insert_extra_newline =
3418 language.brackets().any(|(pair, enabled)| {
3419 let pair_start = pair.start.trim_end();
3420 let pair_end = pair.end.trim_start();
3421
3422 enabled
3423 && pair.newline
3424 && buffer.contains_str_at(
3425 end + trailing_whitespace_len,
3426 pair_end,
3427 )
3428 && buffer.contains_str_at(
3429 (start - leading_whitespace_len)
3430 .saturating_sub(pair_start.len()),
3431 pair_start,
3432 )
3433 });
3434
3435 // Comment extension on newline is allowed only for cursor selections
3436 let comment_delimiter = maybe!({
3437 if !selection_is_empty {
3438 return None;
3439 }
3440
3441 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3442 return None;
3443 }
3444
3445 let delimiters = language.line_comment_prefixes();
3446 let max_len_of_delimiter =
3447 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3448 let (snapshot, range) =
3449 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3450
3451 let mut index_of_first_non_whitespace = 0;
3452 let comment_candidate = snapshot
3453 .chars_for_range(range)
3454 .skip_while(|c| {
3455 let should_skip = c.is_whitespace();
3456 if should_skip {
3457 index_of_first_non_whitespace += 1;
3458 }
3459 should_skip
3460 })
3461 .take(max_len_of_delimiter)
3462 .collect::<String>();
3463 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3464 comment_candidate.starts_with(comment_prefix.as_ref())
3465 })?;
3466 let cursor_is_placed_after_comment_marker =
3467 index_of_first_non_whitespace + comment_prefix.len()
3468 <= start_point.column as usize;
3469 if cursor_is_placed_after_comment_marker {
3470 Some(comment_prefix.clone())
3471 } else {
3472 None
3473 }
3474 });
3475 (comment_delimiter, insert_extra_newline)
3476 } else {
3477 (None, false)
3478 };
3479
3480 let capacity_for_delimiter = comment_delimiter
3481 .as_deref()
3482 .map(str::len)
3483 .unwrap_or_default();
3484 let mut new_text =
3485 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3486 new_text.push('\n');
3487 new_text.extend(indent.chars());
3488 if let Some(delimiter) = &comment_delimiter {
3489 new_text.push_str(delimiter);
3490 }
3491 if insert_extra_newline {
3492 new_text = new_text.repeat(2);
3493 }
3494
3495 let anchor = buffer.anchor_after(end);
3496 let new_selection = selection.map(|_| anchor);
3497 (
3498 (start..end, new_text),
3499 (insert_extra_newline, new_selection),
3500 )
3501 })
3502 .unzip()
3503 };
3504
3505 this.edit_with_autoindent(edits, cx);
3506 let buffer = this.buffer.read(cx).snapshot(cx);
3507 let new_selections = selection_fixup_info
3508 .into_iter()
3509 .map(|(extra_newline_inserted, new_selection)| {
3510 let mut cursor = new_selection.end.to_point(&buffer);
3511 if extra_newline_inserted {
3512 cursor.row -= 1;
3513 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3514 }
3515 new_selection.map(|_| cursor)
3516 })
3517 .collect();
3518
3519 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3520 s.select(new_selections)
3521 });
3522 this.refresh_inline_completion(true, false, window, cx);
3523 });
3524 }
3525
3526 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3527 let buffer = self.buffer.read(cx);
3528 let snapshot = buffer.snapshot(cx);
3529
3530 let mut edits = Vec::new();
3531 let mut rows = Vec::new();
3532
3533 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3534 let cursor = selection.head();
3535 let row = cursor.row;
3536
3537 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3538
3539 let newline = "\n".to_string();
3540 edits.push((start_of_line..start_of_line, newline));
3541
3542 rows.push(row + rows_inserted as u32);
3543 }
3544
3545 self.transact(window, cx, |editor, window, cx| {
3546 editor.edit(edits, cx);
3547
3548 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3549 let mut index = 0;
3550 s.move_cursors_with(|map, _, _| {
3551 let row = rows[index];
3552 index += 1;
3553
3554 let point = Point::new(row, 0);
3555 let boundary = map.next_line_boundary(point).1;
3556 let clipped = map.clip_point(boundary, Bias::Left);
3557
3558 (clipped, SelectionGoal::None)
3559 });
3560 });
3561
3562 let mut indent_edits = Vec::new();
3563 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3564 for row in rows {
3565 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3566 for (row, indent) in indents {
3567 if indent.len == 0 {
3568 continue;
3569 }
3570
3571 let text = match indent.kind {
3572 IndentKind::Space => " ".repeat(indent.len as usize),
3573 IndentKind::Tab => "\t".repeat(indent.len as usize),
3574 };
3575 let point = Point::new(row.0, 0);
3576 indent_edits.push((point..point, text));
3577 }
3578 }
3579 editor.edit(indent_edits, cx);
3580 });
3581 }
3582
3583 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3584 let buffer = self.buffer.read(cx);
3585 let snapshot = buffer.snapshot(cx);
3586
3587 let mut edits = Vec::new();
3588 let mut rows = Vec::new();
3589 let mut rows_inserted = 0;
3590
3591 for selection in self.selections.all_adjusted(cx) {
3592 let cursor = selection.head();
3593 let row = cursor.row;
3594
3595 let point = Point::new(row + 1, 0);
3596 let start_of_line = snapshot.clip_point(point, Bias::Left);
3597
3598 let newline = "\n".to_string();
3599 edits.push((start_of_line..start_of_line, newline));
3600
3601 rows_inserted += 1;
3602 rows.push(row + rows_inserted);
3603 }
3604
3605 self.transact(window, cx, |editor, window, cx| {
3606 editor.edit(edits, cx);
3607
3608 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3609 let mut index = 0;
3610 s.move_cursors_with(|map, _, _| {
3611 let row = rows[index];
3612 index += 1;
3613
3614 let point = Point::new(row, 0);
3615 let boundary = map.next_line_boundary(point).1;
3616 let clipped = map.clip_point(boundary, Bias::Left);
3617
3618 (clipped, SelectionGoal::None)
3619 });
3620 });
3621
3622 let mut indent_edits = Vec::new();
3623 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3624 for row in rows {
3625 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3626 for (row, indent) in indents {
3627 if indent.len == 0 {
3628 continue;
3629 }
3630
3631 let text = match indent.kind {
3632 IndentKind::Space => " ".repeat(indent.len as usize),
3633 IndentKind::Tab => "\t".repeat(indent.len as usize),
3634 };
3635 let point = Point::new(row.0, 0);
3636 indent_edits.push((point..point, text));
3637 }
3638 }
3639 editor.edit(indent_edits, cx);
3640 });
3641 }
3642
3643 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3644 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3645 original_indent_columns: Vec::new(),
3646 });
3647 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3648 }
3649
3650 fn insert_with_autoindent_mode(
3651 &mut self,
3652 text: &str,
3653 autoindent_mode: Option<AutoindentMode>,
3654 window: &mut Window,
3655 cx: &mut Context<Self>,
3656 ) {
3657 if self.read_only(cx) {
3658 return;
3659 }
3660
3661 let text: Arc<str> = text.into();
3662 self.transact(window, cx, |this, window, cx| {
3663 let old_selections = this.selections.all_adjusted(cx);
3664 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3665 let anchors = {
3666 let snapshot = buffer.read(cx);
3667 old_selections
3668 .iter()
3669 .map(|s| {
3670 let anchor = snapshot.anchor_after(s.head());
3671 s.map(|_| anchor)
3672 })
3673 .collect::<Vec<_>>()
3674 };
3675 buffer.edit(
3676 old_selections
3677 .iter()
3678 .map(|s| (s.start..s.end, text.clone())),
3679 autoindent_mode,
3680 cx,
3681 );
3682 anchors
3683 });
3684
3685 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3686 s.select_anchors(selection_anchors);
3687 });
3688
3689 cx.notify();
3690 });
3691 }
3692
3693 fn trigger_completion_on_input(
3694 &mut self,
3695 text: &str,
3696 trigger_in_words: bool,
3697 window: &mut Window,
3698 cx: &mut Context<Self>,
3699 ) {
3700 if self.is_completion_trigger(text, trigger_in_words, cx) {
3701 self.show_completions(
3702 &ShowCompletions {
3703 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3704 },
3705 window,
3706 cx,
3707 );
3708 } else {
3709 self.hide_context_menu(window, cx);
3710 }
3711 }
3712
3713 fn is_completion_trigger(
3714 &self,
3715 text: &str,
3716 trigger_in_words: bool,
3717 cx: &mut Context<Self>,
3718 ) -> bool {
3719 let position = self.selections.newest_anchor().head();
3720 let multibuffer = self.buffer.read(cx);
3721 let Some(buffer) = position
3722 .buffer_id
3723 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3724 else {
3725 return false;
3726 };
3727
3728 if let Some(completion_provider) = &self.completion_provider {
3729 completion_provider.is_completion_trigger(
3730 &buffer,
3731 position.text_anchor,
3732 text,
3733 trigger_in_words,
3734 cx,
3735 )
3736 } else {
3737 false
3738 }
3739 }
3740
3741 /// If any empty selections is touching the start of its innermost containing autoclose
3742 /// region, expand it to select the brackets.
3743 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3744 let selections = self.selections.all::<usize>(cx);
3745 let buffer = self.buffer.read(cx).read(cx);
3746 let new_selections = self
3747 .selections_with_autoclose_regions(selections, &buffer)
3748 .map(|(mut selection, region)| {
3749 if !selection.is_empty() {
3750 return selection;
3751 }
3752
3753 if let Some(region) = region {
3754 let mut range = region.range.to_offset(&buffer);
3755 if selection.start == range.start && range.start >= region.pair.start.len() {
3756 range.start -= region.pair.start.len();
3757 if buffer.contains_str_at(range.start, ®ion.pair.start)
3758 && buffer.contains_str_at(range.end, ®ion.pair.end)
3759 {
3760 range.end += region.pair.end.len();
3761 selection.start = range.start;
3762 selection.end = range.end;
3763
3764 return selection;
3765 }
3766 }
3767 }
3768
3769 let always_treat_brackets_as_autoclosed = buffer
3770 .settings_at(selection.start, cx)
3771 .always_treat_brackets_as_autoclosed;
3772
3773 if !always_treat_brackets_as_autoclosed {
3774 return selection;
3775 }
3776
3777 if let Some(scope) = buffer.language_scope_at(selection.start) {
3778 for (pair, enabled) in scope.brackets() {
3779 if !enabled || !pair.close {
3780 continue;
3781 }
3782
3783 if buffer.contains_str_at(selection.start, &pair.end) {
3784 let pair_start_len = pair.start.len();
3785 if buffer.contains_str_at(
3786 selection.start.saturating_sub(pair_start_len),
3787 &pair.start,
3788 ) {
3789 selection.start -= pair_start_len;
3790 selection.end += pair.end.len();
3791
3792 return selection;
3793 }
3794 }
3795 }
3796 }
3797
3798 selection
3799 })
3800 .collect();
3801
3802 drop(buffer);
3803 self.change_selections(None, window, cx, |selections| {
3804 selections.select(new_selections)
3805 });
3806 }
3807
3808 /// Iterate the given selections, and for each one, find the smallest surrounding
3809 /// autoclose region. This uses the ordering of the selections and the autoclose
3810 /// regions to avoid repeated comparisons.
3811 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3812 &'a self,
3813 selections: impl IntoIterator<Item = Selection<D>>,
3814 buffer: &'a MultiBufferSnapshot,
3815 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3816 let mut i = 0;
3817 let mut regions = self.autoclose_regions.as_slice();
3818 selections.into_iter().map(move |selection| {
3819 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3820
3821 let mut enclosing = None;
3822 while let Some(pair_state) = regions.get(i) {
3823 if pair_state.range.end.to_offset(buffer) < range.start {
3824 regions = ®ions[i + 1..];
3825 i = 0;
3826 } else if pair_state.range.start.to_offset(buffer) > range.end {
3827 break;
3828 } else {
3829 if pair_state.selection_id == selection.id {
3830 enclosing = Some(pair_state);
3831 }
3832 i += 1;
3833 }
3834 }
3835
3836 (selection, enclosing)
3837 })
3838 }
3839
3840 /// Remove any autoclose regions that no longer contain their selection.
3841 fn invalidate_autoclose_regions(
3842 &mut self,
3843 mut selections: &[Selection<Anchor>],
3844 buffer: &MultiBufferSnapshot,
3845 ) {
3846 self.autoclose_regions.retain(|state| {
3847 let mut i = 0;
3848 while let Some(selection) = selections.get(i) {
3849 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3850 selections = &selections[1..];
3851 continue;
3852 }
3853 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3854 break;
3855 }
3856 if selection.id == state.selection_id {
3857 return true;
3858 } else {
3859 i += 1;
3860 }
3861 }
3862 false
3863 });
3864 }
3865
3866 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3867 let offset = position.to_offset(buffer);
3868 let (word_range, kind) = buffer.surrounding_word(offset, true);
3869 if offset > word_range.start && kind == Some(CharKind::Word) {
3870 Some(
3871 buffer
3872 .text_for_range(word_range.start..offset)
3873 .collect::<String>(),
3874 )
3875 } else {
3876 None
3877 }
3878 }
3879
3880 pub fn toggle_inlay_hints(
3881 &mut self,
3882 _: &ToggleInlayHints,
3883 _: &mut Window,
3884 cx: &mut Context<Self>,
3885 ) {
3886 self.refresh_inlay_hints(
3887 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3888 cx,
3889 );
3890 }
3891
3892 pub fn inlay_hints_enabled(&self) -> bool {
3893 self.inlay_hint_cache.enabled
3894 }
3895
3896 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3897 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3898 return;
3899 }
3900
3901 let reason_description = reason.description();
3902 let ignore_debounce = matches!(
3903 reason,
3904 InlayHintRefreshReason::SettingsChange(_)
3905 | InlayHintRefreshReason::Toggle(_)
3906 | InlayHintRefreshReason::ExcerptsRemoved(_)
3907 );
3908 let (invalidate_cache, required_languages) = match reason {
3909 InlayHintRefreshReason::Toggle(enabled) => {
3910 self.inlay_hint_cache.enabled = enabled;
3911 if enabled {
3912 (InvalidationStrategy::RefreshRequested, None)
3913 } else {
3914 self.inlay_hint_cache.clear();
3915 self.splice_inlays(
3916 &self
3917 .visible_inlay_hints(cx)
3918 .iter()
3919 .map(|inlay| inlay.id)
3920 .collect::<Vec<InlayId>>(),
3921 Vec::new(),
3922 cx,
3923 );
3924 return;
3925 }
3926 }
3927 InlayHintRefreshReason::SettingsChange(new_settings) => {
3928 match self.inlay_hint_cache.update_settings(
3929 &self.buffer,
3930 new_settings,
3931 self.visible_inlay_hints(cx),
3932 cx,
3933 ) {
3934 ControlFlow::Break(Some(InlaySplice {
3935 to_remove,
3936 to_insert,
3937 })) => {
3938 self.splice_inlays(&to_remove, to_insert, cx);
3939 return;
3940 }
3941 ControlFlow::Break(None) => return,
3942 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3943 }
3944 }
3945 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3946 if let Some(InlaySplice {
3947 to_remove,
3948 to_insert,
3949 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3950 {
3951 self.splice_inlays(&to_remove, to_insert, cx);
3952 }
3953 return;
3954 }
3955 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3956 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3957 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3958 }
3959 InlayHintRefreshReason::RefreshRequested => {
3960 (InvalidationStrategy::RefreshRequested, None)
3961 }
3962 };
3963
3964 if let Some(InlaySplice {
3965 to_remove,
3966 to_insert,
3967 }) = self.inlay_hint_cache.spawn_hint_refresh(
3968 reason_description,
3969 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3970 invalidate_cache,
3971 ignore_debounce,
3972 cx,
3973 ) {
3974 self.splice_inlays(&to_remove, to_insert, cx);
3975 }
3976 }
3977
3978 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3979 self.display_map
3980 .read(cx)
3981 .current_inlays()
3982 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3983 .cloned()
3984 .collect()
3985 }
3986
3987 pub fn excerpts_for_inlay_hints_query(
3988 &self,
3989 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3990 cx: &mut Context<Editor>,
3991 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3992 let Some(project) = self.project.as_ref() else {
3993 return HashMap::default();
3994 };
3995 let project = project.read(cx);
3996 let multi_buffer = self.buffer().read(cx);
3997 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3998 let multi_buffer_visible_start = self
3999 .scroll_manager
4000 .anchor()
4001 .anchor
4002 .to_point(&multi_buffer_snapshot);
4003 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4004 multi_buffer_visible_start
4005 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4006 Bias::Left,
4007 );
4008 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4009 multi_buffer_snapshot
4010 .range_to_buffer_ranges(multi_buffer_visible_range)
4011 .into_iter()
4012 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4013 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4014 let buffer_file = project::File::from_dyn(buffer.file())?;
4015 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4016 let worktree_entry = buffer_worktree
4017 .read(cx)
4018 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4019 if worktree_entry.is_ignored {
4020 return None;
4021 }
4022
4023 let language = buffer.language()?;
4024 if let Some(restrict_to_languages) = restrict_to_languages {
4025 if !restrict_to_languages.contains(language) {
4026 return None;
4027 }
4028 }
4029 Some((
4030 excerpt_id,
4031 (
4032 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4033 buffer.version().clone(),
4034 excerpt_visible_range,
4035 ),
4036 ))
4037 })
4038 .collect()
4039 }
4040
4041 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4042 TextLayoutDetails {
4043 text_system: window.text_system().clone(),
4044 editor_style: self.style.clone().unwrap(),
4045 rem_size: window.rem_size(),
4046 scroll_anchor: self.scroll_manager.anchor(),
4047 visible_rows: self.visible_line_count(),
4048 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4049 }
4050 }
4051
4052 pub fn splice_inlays(
4053 &self,
4054 to_remove: &[InlayId],
4055 to_insert: Vec<Inlay>,
4056 cx: &mut Context<Self>,
4057 ) {
4058 self.display_map.update(cx, |display_map, cx| {
4059 display_map.splice_inlays(to_remove, to_insert, cx)
4060 });
4061 cx.notify();
4062 }
4063
4064 fn trigger_on_type_formatting(
4065 &self,
4066 input: String,
4067 window: &mut Window,
4068 cx: &mut Context<Self>,
4069 ) -> Option<Task<Result<()>>> {
4070 if input.len() != 1 {
4071 return None;
4072 }
4073
4074 let project = self.project.as_ref()?;
4075 let position = self.selections.newest_anchor().head();
4076 let (buffer, buffer_position) = self
4077 .buffer
4078 .read(cx)
4079 .text_anchor_for_position(position, cx)?;
4080
4081 let settings = language_settings::language_settings(
4082 buffer
4083 .read(cx)
4084 .language_at(buffer_position)
4085 .map(|l| l.name()),
4086 buffer.read(cx).file(),
4087 cx,
4088 );
4089 if !settings.use_on_type_format {
4090 return None;
4091 }
4092
4093 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4094 // hence we do LSP request & edit on host side only — add formats to host's history.
4095 let push_to_lsp_host_history = true;
4096 // If this is not the host, append its history with new edits.
4097 let push_to_client_history = project.read(cx).is_via_collab();
4098
4099 let on_type_formatting = project.update(cx, |project, cx| {
4100 project.on_type_format(
4101 buffer.clone(),
4102 buffer_position,
4103 input,
4104 push_to_lsp_host_history,
4105 cx,
4106 )
4107 });
4108 Some(cx.spawn_in(window, |editor, mut cx| async move {
4109 if let Some(transaction) = on_type_formatting.await? {
4110 if push_to_client_history {
4111 buffer
4112 .update(&mut cx, |buffer, _| {
4113 buffer.push_transaction(transaction, Instant::now());
4114 })
4115 .ok();
4116 }
4117 editor.update(&mut cx, |editor, cx| {
4118 editor.refresh_document_highlights(cx);
4119 })?;
4120 }
4121 Ok(())
4122 }))
4123 }
4124
4125 pub fn show_completions(
4126 &mut self,
4127 options: &ShowCompletions,
4128 window: &mut Window,
4129 cx: &mut Context<Self>,
4130 ) {
4131 if self.pending_rename.is_some() {
4132 return;
4133 }
4134
4135 let Some(provider) = self.completion_provider.as_ref() else {
4136 return;
4137 };
4138
4139 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4140 return;
4141 }
4142
4143 let position = self.selections.newest_anchor().head();
4144 if position.diff_base_anchor.is_some() {
4145 return;
4146 }
4147 let (buffer, buffer_position) =
4148 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4149 output
4150 } else {
4151 return;
4152 };
4153 let show_completion_documentation = buffer
4154 .read(cx)
4155 .snapshot()
4156 .settings_at(buffer_position, cx)
4157 .show_completion_documentation;
4158
4159 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4160
4161 let trigger_kind = match &options.trigger {
4162 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4163 CompletionTriggerKind::TRIGGER_CHARACTER
4164 }
4165 _ => CompletionTriggerKind::INVOKED,
4166 };
4167 let completion_context = CompletionContext {
4168 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4169 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4170 Some(String::from(trigger))
4171 } else {
4172 None
4173 }
4174 }),
4175 trigger_kind,
4176 };
4177 let completions =
4178 provider.completions(&buffer, buffer_position, completion_context, window, cx);
4179 let sort_completions = provider.sort_completions();
4180
4181 let id = post_inc(&mut self.next_completion_id);
4182 let task = cx.spawn_in(window, |editor, mut cx| {
4183 async move {
4184 editor.update(&mut cx, |this, _| {
4185 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4186 })?;
4187 let completions = completions.await.log_err();
4188 let menu = if let Some(completions) = completions {
4189 let mut menu = CompletionsMenu::new(
4190 id,
4191 sort_completions,
4192 show_completion_documentation,
4193 position,
4194 buffer.clone(),
4195 completions.into(),
4196 );
4197
4198 menu.filter(query.as_deref(), cx.background_executor().clone())
4199 .await;
4200
4201 menu.visible().then_some(menu)
4202 } else {
4203 None
4204 };
4205
4206 editor.update_in(&mut cx, |editor, window, cx| {
4207 match editor.context_menu.borrow().as_ref() {
4208 None => {}
4209 Some(CodeContextMenu::Completions(prev_menu)) => {
4210 if prev_menu.id > id {
4211 return;
4212 }
4213 }
4214 _ => return,
4215 }
4216
4217 if editor.focus_handle.is_focused(window) && menu.is_some() {
4218 let mut menu = menu.unwrap();
4219 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4220
4221 *editor.context_menu.borrow_mut() =
4222 Some(CodeContextMenu::Completions(menu));
4223
4224 if editor.show_edit_predictions_in_menu() {
4225 editor.update_visible_inline_completion(window, cx);
4226 } else {
4227 editor.discard_inline_completion(false, cx);
4228 }
4229
4230 cx.notify();
4231 } else if editor.completion_tasks.len() <= 1 {
4232 // If there are no more completion tasks and the last menu was
4233 // empty, we should hide it.
4234 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4235 // If it was already hidden and we don't show inline
4236 // completions in the menu, we should also show the
4237 // inline-completion when available.
4238 if was_hidden && editor.show_edit_predictions_in_menu() {
4239 editor.update_visible_inline_completion(window, cx);
4240 }
4241 }
4242 })?;
4243
4244 Ok::<_, anyhow::Error>(())
4245 }
4246 .log_err()
4247 });
4248
4249 self.completion_tasks.push((id, task));
4250 }
4251
4252 pub fn confirm_completion(
4253 &mut self,
4254 action: &ConfirmCompletion,
4255 window: &mut Window,
4256 cx: &mut Context<Self>,
4257 ) -> Option<Task<Result<()>>> {
4258 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4259 }
4260
4261 pub fn compose_completion(
4262 &mut self,
4263 action: &ComposeCompletion,
4264 window: &mut Window,
4265 cx: &mut Context<Self>,
4266 ) -> Option<Task<Result<()>>> {
4267 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4268 }
4269
4270 fn do_completion(
4271 &mut self,
4272 item_ix: Option<usize>,
4273 intent: CompletionIntent,
4274 window: &mut Window,
4275 cx: &mut Context<Editor>,
4276 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4277 use language::ToOffset as _;
4278
4279 let completions_menu =
4280 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4281 menu
4282 } else {
4283 return None;
4284 };
4285
4286 let entries = completions_menu.entries.borrow();
4287 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4288 if self.show_edit_predictions_in_menu() {
4289 self.discard_inline_completion(true, cx);
4290 }
4291 let candidate_id = mat.candidate_id;
4292 drop(entries);
4293
4294 let buffer_handle = completions_menu.buffer;
4295 let completion = completions_menu
4296 .completions
4297 .borrow()
4298 .get(candidate_id)?
4299 .clone();
4300 cx.stop_propagation();
4301
4302 let snippet;
4303 let text;
4304
4305 if completion.is_snippet() {
4306 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4307 text = snippet.as_ref().unwrap().text.clone();
4308 } else {
4309 snippet = None;
4310 text = completion.new_text.clone();
4311 };
4312 let selections = self.selections.all::<usize>(cx);
4313 let buffer = buffer_handle.read(cx);
4314 let old_range = completion.old_range.to_offset(buffer);
4315 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4316
4317 let newest_selection = self.selections.newest_anchor();
4318 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4319 return None;
4320 }
4321
4322 let lookbehind = newest_selection
4323 .start
4324 .text_anchor
4325 .to_offset(buffer)
4326 .saturating_sub(old_range.start);
4327 let lookahead = old_range
4328 .end
4329 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4330 let mut common_prefix_len = old_text
4331 .bytes()
4332 .zip(text.bytes())
4333 .take_while(|(a, b)| a == b)
4334 .count();
4335
4336 let snapshot = self.buffer.read(cx).snapshot(cx);
4337 let mut range_to_replace: Option<Range<isize>> = None;
4338 let mut ranges = Vec::new();
4339 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4340 for selection in &selections {
4341 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4342 let start = selection.start.saturating_sub(lookbehind);
4343 let end = selection.end + lookahead;
4344 if selection.id == newest_selection.id {
4345 range_to_replace = Some(
4346 ((start + common_prefix_len) as isize - selection.start as isize)
4347 ..(end as isize - selection.start as isize),
4348 );
4349 }
4350 ranges.push(start + common_prefix_len..end);
4351 } else {
4352 common_prefix_len = 0;
4353 ranges.clear();
4354 ranges.extend(selections.iter().map(|s| {
4355 if s.id == newest_selection.id {
4356 range_to_replace = Some(
4357 old_range.start.to_offset_utf16(&snapshot).0 as isize
4358 - selection.start as isize
4359 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4360 - selection.start as isize,
4361 );
4362 old_range.clone()
4363 } else {
4364 s.start..s.end
4365 }
4366 }));
4367 break;
4368 }
4369 if !self.linked_edit_ranges.is_empty() {
4370 let start_anchor = snapshot.anchor_before(selection.head());
4371 let end_anchor = snapshot.anchor_after(selection.tail());
4372 if let Some(ranges) = self
4373 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4374 {
4375 for (buffer, edits) in ranges {
4376 linked_edits.entry(buffer.clone()).or_default().extend(
4377 edits
4378 .into_iter()
4379 .map(|range| (range, text[common_prefix_len..].to_owned())),
4380 );
4381 }
4382 }
4383 }
4384 }
4385 let text = &text[common_prefix_len..];
4386
4387 cx.emit(EditorEvent::InputHandled {
4388 utf16_range_to_replace: range_to_replace,
4389 text: text.into(),
4390 });
4391
4392 self.transact(window, cx, |this, window, cx| {
4393 if let Some(mut snippet) = snippet {
4394 snippet.text = text.to_string();
4395 for tabstop in snippet
4396 .tabstops
4397 .iter_mut()
4398 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4399 {
4400 tabstop.start -= common_prefix_len as isize;
4401 tabstop.end -= common_prefix_len as isize;
4402 }
4403
4404 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4405 } else {
4406 this.buffer.update(cx, |buffer, cx| {
4407 buffer.edit(
4408 ranges.iter().map(|range| (range.clone(), text)),
4409 this.autoindent_mode.clone(),
4410 cx,
4411 );
4412 });
4413 }
4414 for (buffer, edits) in linked_edits {
4415 buffer.update(cx, |buffer, cx| {
4416 let snapshot = buffer.snapshot();
4417 let edits = edits
4418 .into_iter()
4419 .map(|(range, text)| {
4420 use text::ToPoint as TP;
4421 let end_point = TP::to_point(&range.end, &snapshot);
4422 let start_point = TP::to_point(&range.start, &snapshot);
4423 (start_point..end_point, text)
4424 })
4425 .sorted_by_key(|(range, _)| range.start)
4426 .collect::<Vec<_>>();
4427 buffer.edit(edits, None, cx);
4428 })
4429 }
4430
4431 this.refresh_inline_completion(true, false, window, cx);
4432 });
4433
4434 let show_new_completions_on_confirm = completion
4435 .confirm
4436 .as_ref()
4437 .map_or(false, |confirm| confirm(intent, window, cx));
4438 if show_new_completions_on_confirm {
4439 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4440 }
4441
4442 let provider = self.completion_provider.as_ref()?;
4443 drop(completion);
4444 let apply_edits = provider.apply_additional_edits_for_completion(
4445 buffer_handle,
4446 completions_menu.completions.clone(),
4447 candidate_id,
4448 true,
4449 cx,
4450 );
4451
4452 let editor_settings = EditorSettings::get_global(cx);
4453 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4454 // After the code completion is finished, users often want to know what signatures are needed.
4455 // so we should automatically call signature_help
4456 self.show_signature_help(&ShowSignatureHelp, window, cx);
4457 }
4458
4459 Some(cx.foreground_executor().spawn(async move {
4460 apply_edits.await?;
4461 Ok(())
4462 }))
4463 }
4464
4465 pub fn toggle_code_actions(
4466 &mut self,
4467 action: &ToggleCodeActions,
4468 window: &mut Window,
4469 cx: &mut Context<Self>,
4470 ) {
4471 let mut context_menu = self.context_menu.borrow_mut();
4472 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4473 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4474 // Toggle if we're selecting the same one
4475 *context_menu = None;
4476 cx.notify();
4477 return;
4478 } else {
4479 // Otherwise, clear it and start a new one
4480 *context_menu = None;
4481 cx.notify();
4482 }
4483 }
4484 drop(context_menu);
4485 let snapshot = self.snapshot(window, cx);
4486 let deployed_from_indicator = action.deployed_from_indicator;
4487 let mut task = self.code_actions_task.take();
4488 let action = action.clone();
4489 cx.spawn_in(window, |editor, mut cx| async move {
4490 while let Some(prev_task) = task {
4491 prev_task.await.log_err();
4492 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4493 }
4494
4495 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4496 if editor.focus_handle.is_focused(window) {
4497 let multibuffer_point = action
4498 .deployed_from_indicator
4499 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4500 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4501 let (buffer, buffer_row) = snapshot
4502 .buffer_snapshot
4503 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4504 .and_then(|(buffer_snapshot, range)| {
4505 editor
4506 .buffer
4507 .read(cx)
4508 .buffer(buffer_snapshot.remote_id())
4509 .map(|buffer| (buffer, range.start.row))
4510 })?;
4511 let (_, code_actions) = editor
4512 .available_code_actions
4513 .clone()
4514 .and_then(|(location, code_actions)| {
4515 let snapshot = location.buffer.read(cx).snapshot();
4516 let point_range = location.range.to_point(&snapshot);
4517 let point_range = point_range.start.row..=point_range.end.row;
4518 if point_range.contains(&buffer_row) {
4519 Some((location, code_actions))
4520 } else {
4521 None
4522 }
4523 })
4524 .unzip();
4525 let buffer_id = buffer.read(cx).remote_id();
4526 let tasks = editor
4527 .tasks
4528 .get(&(buffer_id, buffer_row))
4529 .map(|t| Arc::new(t.to_owned()));
4530 if tasks.is_none() && code_actions.is_none() {
4531 return None;
4532 }
4533
4534 editor.completion_tasks.clear();
4535 editor.discard_inline_completion(false, cx);
4536 let task_context =
4537 tasks
4538 .as_ref()
4539 .zip(editor.project.clone())
4540 .map(|(tasks, project)| {
4541 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4542 });
4543
4544 Some(cx.spawn_in(window, |editor, mut cx| async move {
4545 let task_context = match task_context {
4546 Some(task_context) => task_context.await,
4547 None => None,
4548 };
4549 let resolved_tasks =
4550 tasks.zip(task_context).map(|(tasks, task_context)| {
4551 Rc::new(ResolvedTasks {
4552 templates: tasks.resolve(&task_context).collect(),
4553 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4554 multibuffer_point.row,
4555 tasks.column,
4556 )),
4557 })
4558 });
4559 let spawn_straight_away = resolved_tasks
4560 .as_ref()
4561 .map_or(false, |tasks| tasks.templates.len() == 1)
4562 && code_actions
4563 .as_ref()
4564 .map_or(true, |actions| actions.is_empty());
4565 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4566 *editor.context_menu.borrow_mut() =
4567 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4568 buffer,
4569 actions: CodeActionContents {
4570 tasks: resolved_tasks,
4571 actions: code_actions,
4572 },
4573 selected_item: Default::default(),
4574 scroll_handle: UniformListScrollHandle::default(),
4575 deployed_from_indicator,
4576 }));
4577 if spawn_straight_away {
4578 if let Some(task) = editor.confirm_code_action(
4579 &ConfirmCodeAction { item_ix: Some(0) },
4580 window,
4581 cx,
4582 ) {
4583 cx.notify();
4584 return task;
4585 }
4586 }
4587 cx.notify();
4588 Task::ready(Ok(()))
4589 }) {
4590 task.await
4591 } else {
4592 Ok(())
4593 }
4594 }))
4595 } else {
4596 Some(Task::ready(Ok(())))
4597 }
4598 })?;
4599 if let Some(task) = spawned_test_task {
4600 task.await?;
4601 }
4602
4603 Ok::<_, anyhow::Error>(())
4604 })
4605 .detach_and_log_err(cx);
4606 }
4607
4608 pub fn confirm_code_action(
4609 &mut self,
4610 action: &ConfirmCodeAction,
4611 window: &mut Window,
4612 cx: &mut Context<Self>,
4613 ) -> Option<Task<Result<()>>> {
4614 let actions_menu =
4615 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4616 menu
4617 } else {
4618 return None;
4619 };
4620 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4621 let action = actions_menu.actions.get(action_ix)?;
4622 let title = action.label();
4623 let buffer = actions_menu.buffer;
4624 let workspace = self.workspace()?;
4625
4626 match action {
4627 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4628 workspace.update(cx, |workspace, cx| {
4629 workspace::tasks::schedule_resolved_task(
4630 workspace,
4631 task_source_kind,
4632 resolved_task,
4633 false,
4634 cx,
4635 );
4636
4637 Some(Task::ready(Ok(())))
4638 })
4639 }
4640 CodeActionsItem::CodeAction {
4641 excerpt_id,
4642 action,
4643 provider,
4644 } => {
4645 let apply_code_action =
4646 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4647 let workspace = workspace.downgrade();
4648 Some(cx.spawn_in(window, |editor, cx| async move {
4649 let project_transaction = apply_code_action.await?;
4650 Self::open_project_transaction(
4651 &editor,
4652 workspace,
4653 project_transaction,
4654 title,
4655 cx,
4656 )
4657 .await
4658 }))
4659 }
4660 }
4661 }
4662
4663 pub async fn open_project_transaction(
4664 this: &WeakEntity<Editor>,
4665 workspace: WeakEntity<Workspace>,
4666 transaction: ProjectTransaction,
4667 title: String,
4668 mut cx: AsyncWindowContext,
4669 ) -> Result<()> {
4670 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4671 cx.update(|_, cx| {
4672 entries.sort_unstable_by_key(|(buffer, _)| {
4673 buffer.read(cx).file().map(|f| f.path().clone())
4674 });
4675 })?;
4676
4677 // If the project transaction's edits are all contained within this editor, then
4678 // avoid opening a new editor to display them.
4679
4680 if let Some((buffer, transaction)) = entries.first() {
4681 if entries.len() == 1 {
4682 let excerpt = this.update(&mut cx, |editor, cx| {
4683 editor
4684 .buffer()
4685 .read(cx)
4686 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4687 })?;
4688 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4689 if excerpted_buffer == *buffer {
4690 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4691 let excerpt_range = excerpt_range.to_offset(buffer);
4692 buffer
4693 .edited_ranges_for_transaction::<usize>(transaction)
4694 .all(|range| {
4695 excerpt_range.start <= range.start
4696 && excerpt_range.end >= range.end
4697 })
4698 })?;
4699
4700 if all_edits_within_excerpt {
4701 return Ok(());
4702 }
4703 }
4704 }
4705 }
4706 } else {
4707 return Ok(());
4708 }
4709
4710 let mut ranges_to_highlight = Vec::new();
4711 let excerpt_buffer = cx.new(|cx| {
4712 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4713 for (buffer_handle, transaction) in &entries {
4714 let buffer = buffer_handle.read(cx);
4715 ranges_to_highlight.extend(
4716 multibuffer.push_excerpts_with_context_lines(
4717 buffer_handle.clone(),
4718 buffer
4719 .edited_ranges_for_transaction::<usize>(transaction)
4720 .collect(),
4721 DEFAULT_MULTIBUFFER_CONTEXT,
4722 cx,
4723 ),
4724 );
4725 }
4726 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4727 multibuffer
4728 })?;
4729
4730 workspace.update_in(&mut cx, |workspace, window, cx| {
4731 let project = workspace.project().clone();
4732 let editor = cx
4733 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4734 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4735 editor.update(cx, |editor, cx| {
4736 editor.highlight_background::<Self>(
4737 &ranges_to_highlight,
4738 |theme| theme.editor_highlighted_line_background,
4739 cx,
4740 );
4741 });
4742 })?;
4743
4744 Ok(())
4745 }
4746
4747 pub fn clear_code_action_providers(&mut self) {
4748 self.code_action_providers.clear();
4749 self.available_code_actions.take();
4750 }
4751
4752 pub fn add_code_action_provider(
4753 &mut self,
4754 provider: Rc<dyn CodeActionProvider>,
4755 window: &mut Window,
4756 cx: &mut Context<Self>,
4757 ) {
4758 if self
4759 .code_action_providers
4760 .iter()
4761 .any(|existing_provider| existing_provider.id() == provider.id())
4762 {
4763 return;
4764 }
4765
4766 self.code_action_providers.push(provider);
4767 self.refresh_code_actions(window, cx);
4768 }
4769
4770 pub fn remove_code_action_provider(
4771 &mut self,
4772 id: Arc<str>,
4773 window: &mut Window,
4774 cx: &mut Context<Self>,
4775 ) {
4776 self.code_action_providers
4777 .retain(|provider| provider.id() != id);
4778 self.refresh_code_actions(window, cx);
4779 }
4780
4781 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4782 let buffer = self.buffer.read(cx);
4783 let newest_selection = self.selections.newest_anchor().clone();
4784 if newest_selection.head().diff_base_anchor.is_some() {
4785 return None;
4786 }
4787 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4788 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4789 if start_buffer != end_buffer {
4790 return None;
4791 }
4792
4793 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4794 cx.background_executor()
4795 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4796 .await;
4797
4798 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4799 let providers = this.code_action_providers.clone();
4800 let tasks = this
4801 .code_action_providers
4802 .iter()
4803 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4804 .collect::<Vec<_>>();
4805 (providers, tasks)
4806 })?;
4807
4808 let mut actions = Vec::new();
4809 for (provider, provider_actions) in
4810 providers.into_iter().zip(future::join_all(tasks).await)
4811 {
4812 if let Some(provider_actions) = provider_actions.log_err() {
4813 actions.extend(provider_actions.into_iter().map(|action| {
4814 AvailableCodeAction {
4815 excerpt_id: newest_selection.start.excerpt_id,
4816 action,
4817 provider: provider.clone(),
4818 }
4819 }));
4820 }
4821 }
4822
4823 this.update(&mut cx, |this, cx| {
4824 this.available_code_actions = if actions.is_empty() {
4825 None
4826 } else {
4827 Some((
4828 Location {
4829 buffer: start_buffer,
4830 range: start..end,
4831 },
4832 actions.into(),
4833 ))
4834 };
4835 cx.notify();
4836 })
4837 }));
4838 None
4839 }
4840
4841 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4842 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4843 self.show_git_blame_inline = false;
4844
4845 self.show_git_blame_inline_delay_task =
4846 Some(cx.spawn_in(window, |this, mut cx| async move {
4847 cx.background_executor().timer(delay).await;
4848
4849 this.update(&mut cx, |this, cx| {
4850 this.show_git_blame_inline = true;
4851 cx.notify();
4852 })
4853 .log_err();
4854 }));
4855 }
4856 }
4857
4858 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4859 if self.pending_rename.is_some() {
4860 return None;
4861 }
4862
4863 let provider = self.semantics_provider.clone()?;
4864 let buffer = self.buffer.read(cx);
4865 let newest_selection = self.selections.newest_anchor().clone();
4866 let cursor_position = newest_selection.head();
4867 let (cursor_buffer, cursor_buffer_position) =
4868 buffer.text_anchor_for_position(cursor_position, cx)?;
4869 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4870 if cursor_buffer != tail_buffer {
4871 return None;
4872 }
4873 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4874 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4875 cx.background_executor()
4876 .timer(Duration::from_millis(debounce))
4877 .await;
4878
4879 let highlights = if let Some(highlights) = cx
4880 .update(|cx| {
4881 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4882 })
4883 .ok()
4884 .flatten()
4885 {
4886 highlights.await.log_err()
4887 } else {
4888 None
4889 };
4890
4891 if let Some(highlights) = highlights {
4892 this.update(&mut cx, |this, cx| {
4893 if this.pending_rename.is_some() {
4894 return;
4895 }
4896
4897 let buffer_id = cursor_position.buffer_id;
4898 let buffer = this.buffer.read(cx);
4899 if !buffer
4900 .text_anchor_for_position(cursor_position, cx)
4901 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4902 {
4903 return;
4904 }
4905
4906 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4907 let mut write_ranges = Vec::new();
4908 let mut read_ranges = Vec::new();
4909 for highlight in highlights {
4910 for (excerpt_id, excerpt_range) in
4911 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4912 {
4913 let start = highlight
4914 .range
4915 .start
4916 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4917 let end = highlight
4918 .range
4919 .end
4920 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4921 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4922 continue;
4923 }
4924
4925 let range = Anchor {
4926 buffer_id,
4927 excerpt_id,
4928 text_anchor: start,
4929 diff_base_anchor: None,
4930 }..Anchor {
4931 buffer_id,
4932 excerpt_id,
4933 text_anchor: end,
4934 diff_base_anchor: None,
4935 };
4936 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4937 write_ranges.push(range);
4938 } else {
4939 read_ranges.push(range);
4940 }
4941 }
4942 }
4943
4944 this.highlight_background::<DocumentHighlightRead>(
4945 &read_ranges,
4946 |theme| theme.editor_document_highlight_read_background,
4947 cx,
4948 );
4949 this.highlight_background::<DocumentHighlightWrite>(
4950 &write_ranges,
4951 |theme| theme.editor_document_highlight_write_background,
4952 cx,
4953 );
4954 cx.notify();
4955 })
4956 .log_err();
4957 }
4958 }));
4959 None
4960 }
4961
4962 pub fn refresh_inline_completion(
4963 &mut self,
4964 debounce: bool,
4965 user_requested: bool,
4966 window: &mut Window,
4967 cx: &mut Context<Self>,
4968 ) -> Option<()> {
4969 let provider = self.edit_prediction_provider()?;
4970 let cursor = self.selections.newest_anchor().head();
4971 let (buffer, cursor_buffer_position) =
4972 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4973
4974 if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4975 self.discard_inline_completion(false, cx);
4976 return None;
4977 }
4978
4979 if !user_requested
4980 && (!self.should_show_edit_predictions()
4981 || !self.is_focused(window)
4982 || buffer.read(cx).is_empty())
4983 {
4984 self.discard_inline_completion(false, cx);
4985 return None;
4986 }
4987
4988 self.update_visible_inline_completion(window, cx);
4989 provider.refresh(
4990 self.project.clone(),
4991 buffer,
4992 cursor_buffer_position,
4993 debounce,
4994 cx,
4995 );
4996 Some(())
4997 }
4998
4999 fn show_edit_predictions_in_menu(&self) -> bool {
5000 match self.edit_prediction_settings {
5001 EditPredictionSettings::Disabled => false,
5002 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5003 }
5004 }
5005
5006 pub fn edit_predictions_enabled(&self) -> bool {
5007 match self.edit_prediction_settings {
5008 EditPredictionSettings::Disabled => false,
5009 EditPredictionSettings::Enabled { .. } => true,
5010 }
5011 }
5012
5013 fn edit_prediction_requires_modifier(&self) -> bool {
5014 match self.edit_prediction_settings {
5015 EditPredictionSettings::Disabled => false,
5016 EditPredictionSettings::Enabled {
5017 preview_requires_modifier,
5018 ..
5019 } => preview_requires_modifier,
5020 }
5021 }
5022
5023 fn edit_prediction_settings_at_position(
5024 &self,
5025 buffer: &Entity<Buffer>,
5026 buffer_position: language::Anchor,
5027 cx: &App,
5028 ) -> EditPredictionSettings {
5029 if self.mode != EditorMode::Full
5030 || !self.show_inline_completions_override.unwrap_or(true)
5031 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5032 {
5033 return EditPredictionSettings::Disabled;
5034 }
5035
5036 let buffer = buffer.read(cx);
5037
5038 let file = buffer.file();
5039
5040 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5041 return EditPredictionSettings::Disabled;
5042 };
5043
5044 let by_provider = matches!(
5045 self.menu_inline_completions_policy,
5046 MenuInlineCompletionsPolicy::ByProvider
5047 );
5048
5049 let show_in_menu = by_provider
5050 && EditorSettings::get_global(cx).show_edit_predictions_in_menu
5051 && self
5052 .edit_prediction_provider
5053 .as_ref()
5054 .map_or(false, |provider| {
5055 provider.provider.show_completions_in_menu()
5056 });
5057
5058 let preview_requires_modifier = all_language_settings(file, cx)
5059 .inline_completions_preview_mode()
5060 == InlineCompletionPreviewMode::WhenHoldingModifier;
5061
5062 EditPredictionSettings::Enabled {
5063 show_in_menu,
5064 preview_requires_modifier,
5065 }
5066 }
5067
5068 fn should_show_edit_predictions(&self) -> bool {
5069 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5070 }
5071
5072 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
5073 let cursor = self.selections.newest_anchor().head();
5074 if let Some((buffer, cursor_position)) =
5075 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5076 {
5077 self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
5078 } else {
5079 false
5080 }
5081 }
5082
5083 fn inline_completions_enabled_in_buffer(
5084 &self,
5085 buffer: &Entity<Buffer>,
5086 buffer_position: language::Anchor,
5087 cx: &App,
5088 ) -> bool {
5089 maybe!({
5090 let provider = self.edit_prediction_provider()?;
5091 if !provider.is_enabled(&buffer, buffer_position, cx) {
5092 return Some(false);
5093 }
5094 let buffer = buffer.read(cx);
5095 let Some(file) = buffer.file() else {
5096 return Some(true);
5097 };
5098 let settings = all_language_settings(Some(file), cx);
5099 Some(settings.inline_completions_enabled_for_path(file.path()))
5100 })
5101 .unwrap_or(false)
5102 }
5103
5104 fn cycle_inline_completion(
5105 &mut self,
5106 direction: Direction,
5107 window: &mut Window,
5108 cx: &mut Context<Self>,
5109 ) -> Option<()> {
5110 let provider = self.edit_prediction_provider()?;
5111 let cursor = self.selections.newest_anchor().head();
5112 let (buffer, cursor_buffer_position) =
5113 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5114 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5115 return None;
5116 }
5117
5118 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5119 self.update_visible_inline_completion(window, cx);
5120
5121 Some(())
5122 }
5123
5124 pub fn show_inline_completion(
5125 &mut self,
5126 _: &ShowEditPrediction,
5127 window: &mut Window,
5128 cx: &mut Context<Self>,
5129 ) {
5130 if !self.has_active_inline_completion() {
5131 self.refresh_inline_completion(false, true, window, cx);
5132 return;
5133 }
5134
5135 self.update_visible_inline_completion(window, cx);
5136 }
5137
5138 pub fn display_cursor_names(
5139 &mut self,
5140 _: &DisplayCursorNames,
5141 window: &mut Window,
5142 cx: &mut Context<Self>,
5143 ) {
5144 self.show_cursor_names(window, cx);
5145 }
5146
5147 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5148 self.show_cursor_names = true;
5149 cx.notify();
5150 cx.spawn_in(window, |this, mut cx| async move {
5151 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5152 this.update(&mut cx, |this, cx| {
5153 this.show_cursor_names = false;
5154 cx.notify()
5155 })
5156 .ok()
5157 })
5158 .detach();
5159 }
5160
5161 pub fn next_edit_prediction(
5162 &mut self,
5163 _: &NextEditPrediction,
5164 window: &mut Window,
5165 cx: &mut Context<Self>,
5166 ) {
5167 if self.has_active_inline_completion() {
5168 self.cycle_inline_completion(Direction::Next, window, cx);
5169 } else {
5170 let is_copilot_disabled = self
5171 .refresh_inline_completion(false, true, window, cx)
5172 .is_none();
5173 if is_copilot_disabled {
5174 cx.propagate();
5175 }
5176 }
5177 }
5178
5179 pub fn previous_edit_prediction(
5180 &mut self,
5181 _: &PreviousEditPrediction,
5182 window: &mut Window,
5183 cx: &mut Context<Self>,
5184 ) {
5185 if self.has_active_inline_completion() {
5186 self.cycle_inline_completion(Direction::Prev, window, cx);
5187 } else {
5188 let is_copilot_disabled = self
5189 .refresh_inline_completion(false, true, window, cx)
5190 .is_none();
5191 if is_copilot_disabled {
5192 cx.propagate();
5193 }
5194 }
5195 }
5196
5197 pub fn accept_edit_prediction(
5198 &mut self,
5199 _: &AcceptEditPrediction,
5200 window: &mut Window,
5201 cx: &mut Context<Self>,
5202 ) {
5203 let buffer = self.buffer.read(cx);
5204 let snapshot = buffer.snapshot(cx);
5205 let selection = self.selections.newest_adjusted(cx);
5206 let cursor = selection.head();
5207 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5208 let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
5209 if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5210 {
5211 if cursor.column < suggested_indent.len
5212 && cursor.column <= current_indent.len
5213 && current_indent.len <= suggested_indent.len
5214 {
5215 self.tab(&Default::default(), window, cx);
5216 return;
5217 }
5218 }
5219
5220 if self.show_edit_predictions_in_menu() {
5221 self.hide_context_menu(window, cx);
5222 }
5223
5224 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5225 return;
5226 };
5227
5228 self.report_inline_completion_event(
5229 active_inline_completion.completion_id.clone(),
5230 true,
5231 cx,
5232 );
5233
5234 match &active_inline_completion.completion {
5235 InlineCompletion::Move { target, .. } => {
5236 let target = *target;
5237 // Note that this is also done in vim's handler of the Tab action.
5238 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5239 selections.select_anchor_ranges([target..target]);
5240 });
5241 }
5242 InlineCompletion::Edit { edits, .. } => {
5243 if let Some(provider) = self.edit_prediction_provider() {
5244 provider.accept(cx);
5245 }
5246
5247 let snapshot = self.buffer.read(cx).snapshot(cx);
5248 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5249
5250 self.buffer.update(cx, |buffer, cx| {
5251 buffer.edit(edits.iter().cloned(), None, cx)
5252 });
5253
5254 self.change_selections(None, window, cx, |s| {
5255 s.select_anchor_ranges([last_edit_end..last_edit_end])
5256 });
5257
5258 self.update_visible_inline_completion(window, cx);
5259 if self.active_inline_completion.is_none() {
5260 self.refresh_inline_completion(true, true, window, cx);
5261 }
5262
5263 cx.notify();
5264 }
5265 }
5266 }
5267
5268 pub fn accept_partial_inline_completion(
5269 &mut self,
5270 _: &AcceptPartialEditPrediction,
5271 window: &mut Window,
5272 cx: &mut Context<Self>,
5273 ) {
5274 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5275 return;
5276 };
5277 if self.selections.count() != 1 {
5278 return;
5279 }
5280
5281 self.report_inline_completion_event(
5282 active_inline_completion.completion_id.clone(),
5283 true,
5284 cx,
5285 );
5286
5287 match &active_inline_completion.completion {
5288 InlineCompletion::Move { target, .. } => {
5289 let target = *target;
5290 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5291 selections.select_anchor_ranges([target..target]);
5292 });
5293 }
5294 InlineCompletion::Edit { edits, .. } => {
5295 // Find an insertion that starts at the cursor position.
5296 let snapshot = self.buffer.read(cx).snapshot(cx);
5297 let cursor_offset = self.selections.newest::<usize>(cx).head();
5298 let insertion = edits.iter().find_map(|(range, text)| {
5299 let range = range.to_offset(&snapshot);
5300 if range.is_empty() && range.start == cursor_offset {
5301 Some(text)
5302 } else {
5303 None
5304 }
5305 });
5306
5307 if let Some(text) = insertion {
5308 let mut partial_completion = text
5309 .chars()
5310 .by_ref()
5311 .take_while(|c| c.is_alphabetic())
5312 .collect::<String>();
5313 if partial_completion.is_empty() {
5314 partial_completion = text
5315 .chars()
5316 .by_ref()
5317 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5318 .collect::<String>();
5319 }
5320
5321 cx.emit(EditorEvent::InputHandled {
5322 utf16_range_to_replace: None,
5323 text: partial_completion.clone().into(),
5324 });
5325
5326 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5327
5328 self.refresh_inline_completion(true, true, window, cx);
5329 cx.notify();
5330 } else {
5331 self.accept_edit_prediction(&Default::default(), window, cx);
5332 }
5333 }
5334 }
5335 }
5336
5337 fn discard_inline_completion(
5338 &mut self,
5339 should_report_inline_completion_event: bool,
5340 cx: &mut Context<Self>,
5341 ) -> bool {
5342 if should_report_inline_completion_event {
5343 let completion_id = self
5344 .active_inline_completion
5345 .as_ref()
5346 .and_then(|active_completion| active_completion.completion_id.clone());
5347
5348 self.report_inline_completion_event(completion_id, false, cx);
5349 }
5350
5351 if let Some(provider) = self.edit_prediction_provider() {
5352 provider.discard(cx);
5353 }
5354
5355 self.take_active_inline_completion(cx)
5356 }
5357
5358 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5359 let Some(provider) = self.edit_prediction_provider() else {
5360 return;
5361 };
5362
5363 let Some((_, buffer, _)) = self
5364 .buffer
5365 .read(cx)
5366 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5367 else {
5368 return;
5369 };
5370
5371 let extension = buffer
5372 .read(cx)
5373 .file()
5374 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5375
5376 let event_type = match accepted {
5377 true => "Edit Prediction Accepted",
5378 false => "Edit Prediction Discarded",
5379 };
5380 telemetry::event!(
5381 event_type,
5382 provider = provider.name(),
5383 prediction_id = id,
5384 suggestion_accepted = accepted,
5385 file_extension = extension,
5386 );
5387 }
5388
5389 pub fn has_active_inline_completion(&self) -> bool {
5390 self.active_inline_completion.is_some()
5391 }
5392
5393 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5394 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5395 return false;
5396 };
5397
5398 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5399 self.clear_highlights::<InlineCompletionHighlight>(cx);
5400 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5401 true
5402 }
5403
5404 /// Returns true when we're displaying the edit prediction popover below the cursor
5405 /// like we are not previewing and the LSP autocomplete menu is visible
5406 /// or we are in `when_holding_modifier` mode.
5407 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5408 if self.edit_prediction_preview.is_active()
5409 || !self.show_edit_predictions_in_menu()
5410 || !self.edit_predictions_enabled()
5411 {
5412 return false;
5413 }
5414
5415 if self.has_visible_completions_menu() {
5416 return true;
5417 }
5418
5419 has_completion && self.edit_prediction_requires_modifier()
5420 }
5421
5422 fn handle_modifiers_changed(
5423 &mut self,
5424 modifiers: Modifiers,
5425 position_map: &PositionMap,
5426 window: &mut Window,
5427 cx: &mut Context<Self>,
5428 ) {
5429 if self.show_edit_predictions_in_menu() {
5430 self.update_edit_prediction_preview(&modifiers, position_map, window, cx);
5431 }
5432
5433 let mouse_position = window.mouse_position();
5434 if !position_map.text_hitbox.is_hovered(window) {
5435 return;
5436 }
5437
5438 self.update_hovered_link(
5439 position_map.point_for_position(mouse_position),
5440 &position_map.snapshot,
5441 modifiers,
5442 window,
5443 cx,
5444 )
5445 }
5446
5447 fn update_edit_prediction_preview(
5448 &mut self,
5449 modifiers: &Modifiers,
5450 position_map: &PositionMap,
5451 window: &mut Window,
5452 cx: &mut Context<Self>,
5453 ) {
5454 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5455 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5456 return;
5457 };
5458
5459 if &accept_keystroke.modifiers == modifiers {
5460 if let Some(completion) = self.active_inline_completion.as_ref() {
5461 if self.edit_prediction_preview.start(
5462 &completion.completion,
5463 &position_map.snapshot,
5464 self.selections
5465 .newest_anchor()
5466 .head()
5467 .to_display_point(&position_map.snapshot),
5468 ) {
5469 self.request_autoscroll(Autoscroll::fit(), cx);
5470 self.update_visible_inline_completion(window, cx);
5471 cx.notify();
5472 }
5473 }
5474 } else if self.edit_prediction_preview.end(
5475 self.selections
5476 .newest_anchor()
5477 .head()
5478 .to_display_point(&position_map.snapshot),
5479 position_map.scroll_pixel_position,
5480 window,
5481 cx,
5482 ) {
5483 self.update_visible_inline_completion(window, cx);
5484 cx.notify();
5485 }
5486 }
5487
5488 fn update_visible_inline_completion(
5489 &mut self,
5490 window: &mut Window,
5491 cx: &mut Context<Self>,
5492 ) -> Option<()> {
5493 let selection = self.selections.newest_anchor();
5494 let cursor = selection.head();
5495 let multibuffer = self.buffer.read(cx).snapshot(cx);
5496 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5497 let excerpt_id = cursor.excerpt_id;
5498
5499 let show_in_menu = self.show_edit_predictions_in_menu();
5500 let completions_menu_has_precedence = !show_in_menu
5501 && (self.context_menu.borrow().is_some()
5502 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5503
5504 if completions_menu_has_precedence
5505 || !offset_selection.is_empty()
5506 || self
5507 .active_inline_completion
5508 .as_ref()
5509 .map_or(false, |completion| {
5510 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5511 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5512 !invalidation_range.contains(&offset_selection.head())
5513 })
5514 {
5515 self.discard_inline_completion(false, cx);
5516 return None;
5517 }
5518
5519 self.take_active_inline_completion(cx);
5520 let Some(provider) = self.edit_prediction_provider() else {
5521 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5522 return None;
5523 };
5524
5525 let (buffer, cursor_buffer_position) =
5526 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5527
5528 self.edit_prediction_settings =
5529 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5530
5531 if !self.edit_prediction_settings.is_enabled() {
5532 self.discard_inline_completion(false, cx);
5533 return None;
5534 }
5535
5536 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5537 let edits = inline_completion
5538 .edits
5539 .into_iter()
5540 .flat_map(|(range, new_text)| {
5541 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5542 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5543 Some((start..end, new_text))
5544 })
5545 .collect::<Vec<_>>();
5546 if edits.is_empty() {
5547 return None;
5548 }
5549
5550 let first_edit_start = edits.first().unwrap().0.start;
5551 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5552 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5553
5554 let last_edit_end = edits.last().unwrap().0.end;
5555 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5556 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5557
5558 let cursor_row = cursor.to_point(&multibuffer).row;
5559
5560 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5561
5562 let mut inlay_ids = Vec::new();
5563 let invalidation_row_range;
5564 let move_invalidation_row_range = if cursor_row < edit_start_row {
5565 Some(cursor_row..edit_end_row)
5566 } else if cursor_row > edit_end_row {
5567 Some(edit_start_row..cursor_row)
5568 } else {
5569 None
5570 };
5571 let is_move =
5572 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5573 let completion = if is_move {
5574 invalidation_row_range =
5575 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5576 let target = first_edit_start;
5577 InlineCompletion::Move { target, snapshot }
5578 } else {
5579 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5580 && !self.inline_completions_hidden_for_vim_mode;
5581
5582 if show_completions_in_buffer {
5583 if edits
5584 .iter()
5585 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5586 {
5587 let mut inlays = Vec::new();
5588 for (range, new_text) in &edits {
5589 let inlay = Inlay::inline_completion(
5590 post_inc(&mut self.next_inlay_id),
5591 range.start,
5592 new_text.as_str(),
5593 );
5594 inlay_ids.push(inlay.id);
5595 inlays.push(inlay);
5596 }
5597
5598 self.splice_inlays(&[], inlays, cx);
5599 } else {
5600 let background_color = cx.theme().status().deleted_background;
5601 self.highlight_text::<InlineCompletionHighlight>(
5602 edits.iter().map(|(range, _)| range.clone()).collect(),
5603 HighlightStyle {
5604 background_color: Some(background_color),
5605 ..Default::default()
5606 },
5607 cx,
5608 );
5609 }
5610 }
5611
5612 invalidation_row_range = edit_start_row..edit_end_row;
5613
5614 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5615 if provider.show_tab_accept_marker() {
5616 EditDisplayMode::TabAccept
5617 } else {
5618 EditDisplayMode::Inline
5619 }
5620 } else {
5621 EditDisplayMode::DiffPopover
5622 };
5623
5624 InlineCompletion::Edit {
5625 edits,
5626 edit_preview: inline_completion.edit_preview,
5627 display_mode,
5628 snapshot,
5629 }
5630 };
5631
5632 let invalidation_range = multibuffer
5633 .anchor_before(Point::new(invalidation_row_range.start, 0))
5634 ..multibuffer.anchor_after(Point::new(
5635 invalidation_row_range.end,
5636 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5637 ));
5638
5639 self.stale_inline_completion_in_menu = None;
5640 let editor_snapshot = self.snapshot(window, cx);
5641 if self.edit_prediction_preview.restart(
5642 &completion,
5643 &editor_snapshot,
5644 cursor.to_display_point(&editor_snapshot),
5645 ) {
5646 self.request_autoscroll(Autoscroll::fit(), cx);
5647 }
5648
5649 self.active_inline_completion = Some(InlineCompletionState {
5650 inlay_ids,
5651 completion,
5652 completion_id: inline_completion.id,
5653 invalidation_range,
5654 });
5655
5656 cx.notify();
5657
5658 Some(())
5659 }
5660
5661 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5662 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5663 }
5664
5665 fn render_code_actions_indicator(
5666 &self,
5667 _style: &EditorStyle,
5668 row: DisplayRow,
5669 is_active: bool,
5670 cx: &mut Context<Self>,
5671 ) -> Option<IconButton> {
5672 if self.available_code_actions.is_some() {
5673 Some(
5674 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5675 .shape(ui::IconButtonShape::Square)
5676 .icon_size(IconSize::XSmall)
5677 .icon_color(Color::Muted)
5678 .toggle_state(is_active)
5679 .tooltip({
5680 let focus_handle = self.focus_handle.clone();
5681 move |window, cx| {
5682 Tooltip::for_action_in(
5683 "Toggle Code Actions",
5684 &ToggleCodeActions {
5685 deployed_from_indicator: None,
5686 },
5687 &focus_handle,
5688 window,
5689 cx,
5690 )
5691 }
5692 })
5693 .on_click(cx.listener(move |editor, _e, window, cx| {
5694 window.focus(&editor.focus_handle(cx));
5695 editor.toggle_code_actions(
5696 &ToggleCodeActions {
5697 deployed_from_indicator: Some(row),
5698 },
5699 window,
5700 cx,
5701 );
5702 })),
5703 )
5704 } else {
5705 None
5706 }
5707 }
5708
5709 fn clear_tasks(&mut self) {
5710 self.tasks.clear()
5711 }
5712
5713 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5714 if self.tasks.insert(key, value).is_some() {
5715 // This case should hopefully be rare, but just in case...
5716 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5717 }
5718 }
5719
5720 fn build_tasks_context(
5721 project: &Entity<Project>,
5722 buffer: &Entity<Buffer>,
5723 buffer_row: u32,
5724 tasks: &Arc<RunnableTasks>,
5725 cx: &mut Context<Self>,
5726 ) -> Task<Option<task::TaskContext>> {
5727 let position = Point::new(buffer_row, tasks.column);
5728 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5729 let location = Location {
5730 buffer: buffer.clone(),
5731 range: range_start..range_start,
5732 };
5733 // Fill in the environmental variables from the tree-sitter captures
5734 let mut captured_task_variables = TaskVariables::default();
5735 for (capture_name, value) in tasks.extra_variables.clone() {
5736 captured_task_variables.insert(
5737 task::VariableName::Custom(capture_name.into()),
5738 value.clone(),
5739 );
5740 }
5741 project.update(cx, |project, cx| {
5742 project.task_store().update(cx, |task_store, cx| {
5743 task_store.task_context_for_location(captured_task_variables, location, cx)
5744 })
5745 })
5746 }
5747
5748 pub fn spawn_nearest_task(
5749 &mut self,
5750 action: &SpawnNearestTask,
5751 window: &mut Window,
5752 cx: &mut Context<Self>,
5753 ) {
5754 let Some((workspace, _)) = self.workspace.clone() else {
5755 return;
5756 };
5757 let Some(project) = self.project.clone() else {
5758 return;
5759 };
5760
5761 // Try to find a closest, enclosing node using tree-sitter that has a
5762 // task
5763 let Some((buffer, buffer_row, tasks)) = self
5764 .find_enclosing_node_task(cx)
5765 // Or find the task that's closest in row-distance.
5766 .or_else(|| self.find_closest_task(cx))
5767 else {
5768 return;
5769 };
5770
5771 let reveal_strategy = action.reveal;
5772 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5773 cx.spawn_in(window, |_, mut cx| async move {
5774 let context = task_context.await?;
5775 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5776
5777 let resolved = resolved_task.resolved.as_mut()?;
5778 resolved.reveal = reveal_strategy;
5779
5780 workspace
5781 .update(&mut cx, |workspace, cx| {
5782 workspace::tasks::schedule_resolved_task(
5783 workspace,
5784 task_source_kind,
5785 resolved_task,
5786 false,
5787 cx,
5788 );
5789 })
5790 .ok()
5791 })
5792 .detach();
5793 }
5794
5795 fn find_closest_task(
5796 &mut self,
5797 cx: &mut Context<Self>,
5798 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5799 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5800
5801 let ((buffer_id, row), tasks) = self
5802 .tasks
5803 .iter()
5804 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5805
5806 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5807 let tasks = Arc::new(tasks.to_owned());
5808 Some((buffer, *row, tasks))
5809 }
5810
5811 fn find_enclosing_node_task(
5812 &mut self,
5813 cx: &mut Context<Self>,
5814 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5815 let snapshot = self.buffer.read(cx).snapshot(cx);
5816 let offset = self.selections.newest::<usize>(cx).head();
5817 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5818 let buffer_id = excerpt.buffer().remote_id();
5819
5820 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5821 let mut cursor = layer.node().walk();
5822
5823 while cursor.goto_first_child_for_byte(offset).is_some() {
5824 if cursor.node().end_byte() == offset {
5825 cursor.goto_next_sibling();
5826 }
5827 }
5828
5829 // Ascend to the smallest ancestor that contains the range and has a task.
5830 loop {
5831 let node = cursor.node();
5832 let node_range = node.byte_range();
5833 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5834
5835 // Check if this node contains our offset
5836 if node_range.start <= offset && node_range.end >= offset {
5837 // If it contains offset, check for task
5838 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5839 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5840 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5841 }
5842 }
5843
5844 if !cursor.goto_parent() {
5845 break;
5846 }
5847 }
5848 None
5849 }
5850
5851 fn render_run_indicator(
5852 &self,
5853 _style: &EditorStyle,
5854 is_active: bool,
5855 row: DisplayRow,
5856 cx: &mut Context<Self>,
5857 ) -> IconButton {
5858 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5859 .shape(ui::IconButtonShape::Square)
5860 .icon_size(IconSize::XSmall)
5861 .icon_color(Color::Muted)
5862 .toggle_state(is_active)
5863 .on_click(cx.listener(move |editor, _e, window, cx| {
5864 window.focus(&editor.focus_handle(cx));
5865 editor.toggle_code_actions(
5866 &ToggleCodeActions {
5867 deployed_from_indicator: Some(row),
5868 },
5869 window,
5870 cx,
5871 );
5872 }))
5873 }
5874
5875 pub fn context_menu_visible(&self) -> bool {
5876 !self.edit_prediction_preview.is_active()
5877 && self
5878 .context_menu
5879 .borrow()
5880 .as_ref()
5881 .map_or(false, |menu| menu.visible())
5882 }
5883
5884 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5885 self.context_menu
5886 .borrow()
5887 .as_ref()
5888 .map(|menu| menu.origin())
5889 }
5890
5891 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5892 px(30.)
5893 }
5894
5895 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5896 if self.read_only(cx) {
5897 cx.theme().players().read_only()
5898 } else {
5899 self.style.as_ref().unwrap().local_player
5900 }
5901 }
5902
5903 #[allow(clippy::too_many_arguments)]
5904 fn render_edit_prediction_cursor_popover(
5905 &self,
5906 min_width: Pixels,
5907 max_width: Pixels,
5908 cursor_point: Point,
5909 style: &EditorStyle,
5910 accept_keystroke: &gpui::Keystroke,
5911 _window: &Window,
5912 cx: &mut Context<Editor>,
5913 ) -> Option<AnyElement> {
5914 let provider = self.edit_prediction_provider.as_ref()?;
5915
5916 if provider.provider.needs_terms_acceptance(cx) {
5917 return Some(
5918 h_flex()
5919 .min_w(min_width)
5920 .flex_1()
5921 .px_2()
5922 .py_1()
5923 .gap_3()
5924 .elevation_2(cx)
5925 .hover(|style| style.bg(cx.theme().colors().element_hover))
5926 .id("accept-terms")
5927 .cursor_pointer()
5928 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5929 .on_click(cx.listener(|this, _event, window, cx| {
5930 cx.stop_propagation();
5931 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
5932 window.dispatch_action(
5933 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
5934 cx,
5935 );
5936 }))
5937 .child(
5938 h_flex()
5939 .flex_1()
5940 .gap_2()
5941 .child(Icon::new(IconName::ZedPredict))
5942 .child(Label::new("Accept Terms of Service"))
5943 .child(div().w_full())
5944 .child(
5945 Icon::new(IconName::ArrowUpRight)
5946 .color(Color::Muted)
5947 .size(IconSize::Small),
5948 )
5949 .into_any_element(),
5950 )
5951 .into_any(),
5952 );
5953 }
5954
5955 let is_refreshing = provider.provider.is_refreshing(cx);
5956
5957 fn pending_completion_container() -> Div {
5958 h_flex()
5959 .h_full()
5960 .flex_1()
5961 .gap_2()
5962 .child(Icon::new(IconName::ZedPredict))
5963 }
5964
5965 let completion = match &self.active_inline_completion {
5966 Some(completion) => match &completion.completion {
5967 InlineCompletion::Move {
5968 target, snapshot, ..
5969 } if !self.has_visible_completions_menu() => {
5970 use text::ToPoint as _;
5971
5972 return Some(
5973 h_flex()
5974 .px_2()
5975 .py_1()
5976 .elevation_2(cx)
5977 .border_color(cx.theme().colors().border)
5978 .rounded_tl(px(0.))
5979 .gap_2()
5980 .child(
5981 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
5982 Icon::new(IconName::ZedPredictDown)
5983 } else {
5984 Icon::new(IconName::ZedPredictUp)
5985 },
5986 )
5987 .child(Label::new("Hold"))
5988 .children(ui::render_modifiers(
5989 &accept_keystroke.modifiers,
5990 PlatformStyle::platform(),
5991 Some(Color::Default),
5992 None,
5993 true,
5994 ))
5995 .into_any(),
5996 );
5997 }
5998 _ => self.render_edit_prediction_cursor_popover_preview(
5999 completion,
6000 cursor_point,
6001 style,
6002 cx,
6003 )?,
6004 },
6005
6006 None if is_refreshing => match &self.stale_inline_completion_in_menu {
6007 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
6008 stale_completion,
6009 cursor_point,
6010 style,
6011 cx,
6012 )?,
6013
6014 None => {
6015 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
6016 }
6017 },
6018
6019 None => pending_completion_container().child(Label::new("No Prediction")),
6020 };
6021
6022 let completion = if is_refreshing {
6023 completion
6024 .with_animation(
6025 "loading-completion",
6026 Animation::new(Duration::from_secs(2))
6027 .repeat()
6028 .with_easing(pulsating_between(0.4, 0.8)),
6029 |label, delta| label.opacity(delta),
6030 )
6031 .into_any_element()
6032 } else {
6033 completion.into_any_element()
6034 };
6035
6036 let has_completion = self.active_inline_completion.is_some();
6037
6038 Some(
6039 h_flex()
6040 .min_w(min_width)
6041 .max_w(max_width)
6042 .flex_1()
6043 .px_2()
6044 .py_1()
6045 .elevation_2(cx)
6046 .border_color(cx.theme().colors().border)
6047 .child(completion)
6048 .child(ui::Divider::vertical())
6049 .child(
6050 h_flex()
6051 .h_full()
6052 .gap_1()
6053 .pl_2()
6054 .child(
6055 h_flex()
6056 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6057 .gap_1()
6058 .children(ui::render_modifiers(
6059 &accept_keystroke.modifiers,
6060 PlatformStyle::platform(),
6061 Some(if !has_completion {
6062 Color::Muted
6063 } else {
6064 Color::Default
6065 }),
6066 None,
6067 true,
6068 )),
6069 )
6070 .child(Label::new("Preview").into_any_element())
6071 .opacity(if has_completion { 1.0 } else { 0.4 }),
6072 )
6073 .into_any(),
6074 )
6075 }
6076
6077 fn render_edit_prediction_cursor_popover_preview(
6078 &self,
6079 completion: &InlineCompletionState,
6080 cursor_point: Point,
6081 style: &EditorStyle,
6082 cx: &mut Context<Editor>,
6083 ) -> Option<Div> {
6084 use text::ToPoint as _;
6085
6086 fn render_relative_row_jump(
6087 prefix: impl Into<String>,
6088 current_row: u32,
6089 target_row: u32,
6090 ) -> Div {
6091 let (row_diff, arrow) = if target_row < current_row {
6092 (current_row - target_row, IconName::ArrowUp)
6093 } else {
6094 (target_row - current_row, IconName::ArrowDown)
6095 };
6096
6097 h_flex()
6098 .child(
6099 Label::new(format!("{}{}", prefix.into(), row_diff))
6100 .color(Color::Muted)
6101 .size(LabelSize::Small),
6102 )
6103 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6104 }
6105
6106 match &completion.completion {
6107 InlineCompletion::Move {
6108 target, snapshot, ..
6109 } => Some(
6110 h_flex()
6111 .px_2()
6112 .gap_2()
6113 .flex_1()
6114 .child(
6115 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6116 Icon::new(IconName::ZedPredictDown)
6117 } else {
6118 Icon::new(IconName::ZedPredictUp)
6119 },
6120 )
6121 .child(Label::new("Jump to Edit")),
6122 ),
6123
6124 InlineCompletion::Edit {
6125 edits,
6126 edit_preview,
6127 snapshot,
6128 display_mode: _,
6129 } => {
6130 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
6131
6132 let highlighted_edits = crate::inline_completion_edit_text(
6133 &snapshot,
6134 &edits,
6135 edit_preview.as_ref()?,
6136 true,
6137 cx,
6138 );
6139
6140 let len_total = highlighted_edits.text.len();
6141 let first_line = &highlighted_edits.text
6142 [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
6143 let first_line_len = first_line.len();
6144
6145 let first_highlight_start = highlighted_edits
6146 .highlights
6147 .first()
6148 .map_or(0, |(range, _)| range.start);
6149 let drop_prefix_len = first_line
6150 .char_indices()
6151 .find(|(_, c)| !c.is_whitespace())
6152 .map_or(first_highlight_start, |(ix, _)| {
6153 ix.min(first_highlight_start)
6154 });
6155
6156 let preview_text = &first_line[drop_prefix_len..];
6157 let preview_len = preview_text.len();
6158 let highlights = highlighted_edits
6159 .highlights
6160 .into_iter()
6161 .take_until(|(range, _)| range.start > first_line_len)
6162 .map(|(range, style)| {
6163 (
6164 range.start - drop_prefix_len
6165 ..(range.end - drop_prefix_len).min(preview_len),
6166 style,
6167 )
6168 });
6169
6170 let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
6171 .with_highlights(&style.text, highlights);
6172
6173 let preview = h_flex()
6174 .gap_1()
6175 .min_w_16()
6176 .child(styled_text)
6177 .when(len_total > first_line_len, |parent| parent.child("…"));
6178
6179 let left = if first_edit_row != cursor_point.row {
6180 render_relative_row_jump("", cursor_point.row, first_edit_row)
6181 .into_any_element()
6182 } else {
6183 Icon::new(IconName::ZedPredict).into_any_element()
6184 };
6185
6186 Some(
6187 h_flex()
6188 .h_full()
6189 .flex_1()
6190 .gap_2()
6191 .pr_1()
6192 .overflow_x_hidden()
6193 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6194 .child(left)
6195 .child(preview),
6196 )
6197 }
6198 }
6199 }
6200
6201 fn render_context_menu(
6202 &self,
6203 style: &EditorStyle,
6204 max_height_in_lines: u32,
6205 y_flipped: bool,
6206 window: &mut Window,
6207 cx: &mut Context<Editor>,
6208 ) -> Option<AnyElement> {
6209 let menu = self.context_menu.borrow();
6210 let menu = menu.as_ref()?;
6211 if !menu.visible() {
6212 return None;
6213 };
6214 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6215 }
6216
6217 fn render_context_menu_aside(
6218 &self,
6219 style: &EditorStyle,
6220 max_size: Size<Pixels>,
6221 cx: &mut Context<Editor>,
6222 ) -> Option<AnyElement> {
6223 self.context_menu.borrow().as_ref().and_then(|menu| {
6224 if menu.visible() {
6225 menu.render_aside(
6226 style,
6227 max_size,
6228 self.workspace.as_ref().map(|(w, _)| w.clone()),
6229 cx,
6230 )
6231 } else {
6232 None
6233 }
6234 })
6235 }
6236
6237 fn hide_context_menu(
6238 &mut self,
6239 window: &mut Window,
6240 cx: &mut Context<Self>,
6241 ) -> Option<CodeContextMenu> {
6242 cx.notify();
6243 self.completion_tasks.clear();
6244 let context_menu = self.context_menu.borrow_mut().take();
6245 self.stale_inline_completion_in_menu.take();
6246 self.update_visible_inline_completion(window, cx);
6247 context_menu
6248 }
6249
6250 fn show_snippet_choices(
6251 &mut self,
6252 choices: &Vec<String>,
6253 selection: Range<Anchor>,
6254 cx: &mut Context<Self>,
6255 ) {
6256 if selection.start.buffer_id.is_none() {
6257 return;
6258 }
6259 let buffer_id = selection.start.buffer_id.unwrap();
6260 let buffer = self.buffer().read(cx).buffer(buffer_id);
6261 let id = post_inc(&mut self.next_completion_id);
6262
6263 if let Some(buffer) = buffer {
6264 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6265 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6266 ));
6267 }
6268 }
6269
6270 pub fn insert_snippet(
6271 &mut self,
6272 insertion_ranges: &[Range<usize>],
6273 snippet: Snippet,
6274 window: &mut Window,
6275 cx: &mut Context<Self>,
6276 ) -> Result<()> {
6277 struct Tabstop<T> {
6278 is_end_tabstop: bool,
6279 ranges: Vec<Range<T>>,
6280 choices: Option<Vec<String>>,
6281 }
6282
6283 let tabstops = self.buffer.update(cx, |buffer, cx| {
6284 let snippet_text: Arc<str> = snippet.text.clone().into();
6285 buffer.edit(
6286 insertion_ranges
6287 .iter()
6288 .cloned()
6289 .map(|range| (range, snippet_text.clone())),
6290 Some(AutoindentMode::EachLine),
6291 cx,
6292 );
6293
6294 let snapshot = &*buffer.read(cx);
6295 let snippet = &snippet;
6296 snippet
6297 .tabstops
6298 .iter()
6299 .map(|tabstop| {
6300 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6301 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6302 });
6303 let mut tabstop_ranges = tabstop
6304 .ranges
6305 .iter()
6306 .flat_map(|tabstop_range| {
6307 let mut delta = 0_isize;
6308 insertion_ranges.iter().map(move |insertion_range| {
6309 let insertion_start = insertion_range.start as isize + delta;
6310 delta +=
6311 snippet.text.len() as isize - insertion_range.len() as isize;
6312
6313 let start = ((insertion_start + tabstop_range.start) as usize)
6314 .min(snapshot.len());
6315 let end = ((insertion_start + tabstop_range.end) as usize)
6316 .min(snapshot.len());
6317 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6318 })
6319 })
6320 .collect::<Vec<_>>();
6321 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6322
6323 Tabstop {
6324 is_end_tabstop,
6325 ranges: tabstop_ranges,
6326 choices: tabstop.choices.clone(),
6327 }
6328 })
6329 .collect::<Vec<_>>()
6330 });
6331 if let Some(tabstop) = tabstops.first() {
6332 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6333 s.select_ranges(tabstop.ranges.iter().cloned());
6334 });
6335
6336 if let Some(choices) = &tabstop.choices {
6337 if let Some(selection) = tabstop.ranges.first() {
6338 self.show_snippet_choices(choices, selection.clone(), cx)
6339 }
6340 }
6341
6342 // If we're already at the last tabstop and it's at the end of the snippet,
6343 // we're done, we don't need to keep the state around.
6344 if !tabstop.is_end_tabstop {
6345 let choices = tabstops
6346 .iter()
6347 .map(|tabstop| tabstop.choices.clone())
6348 .collect();
6349
6350 let ranges = tabstops
6351 .into_iter()
6352 .map(|tabstop| tabstop.ranges)
6353 .collect::<Vec<_>>();
6354
6355 self.snippet_stack.push(SnippetState {
6356 active_index: 0,
6357 ranges,
6358 choices,
6359 });
6360 }
6361
6362 // Check whether the just-entered snippet ends with an auto-closable bracket.
6363 if self.autoclose_regions.is_empty() {
6364 let snapshot = self.buffer.read(cx).snapshot(cx);
6365 for selection in &mut self.selections.all::<Point>(cx) {
6366 let selection_head = selection.head();
6367 let Some(scope) = snapshot.language_scope_at(selection_head) else {
6368 continue;
6369 };
6370
6371 let mut bracket_pair = None;
6372 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
6373 let prev_chars = snapshot
6374 .reversed_chars_at(selection_head)
6375 .collect::<String>();
6376 for (pair, enabled) in scope.brackets() {
6377 if enabled
6378 && pair.close
6379 && prev_chars.starts_with(pair.start.as_str())
6380 && next_chars.starts_with(pair.end.as_str())
6381 {
6382 bracket_pair = Some(pair.clone());
6383 break;
6384 }
6385 }
6386 if let Some(pair) = bracket_pair {
6387 let start = snapshot.anchor_after(selection_head);
6388 let end = snapshot.anchor_after(selection_head);
6389 self.autoclose_regions.push(AutocloseRegion {
6390 selection_id: selection.id,
6391 range: start..end,
6392 pair,
6393 });
6394 }
6395 }
6396 }
6397 }
6398 Ok(())
6399 }
6400
6401 pub fn move_to_next_snippet_tabstop(
6402 &mut self,
6403 window: &mut Window,
6404 cx: &mut Context<Self>,
6405 ) -> bool {
6406 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6407 }
6408
6409 pub fn move_to_prev_snippet_tabstop(
6410 &mut self,
6411 window: &mut Window,
6412 cx: &mut Context<Self>,
6413 ) -> bool {
6414 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6415 }
6416
6417 pub fn move_to_snippet_tabstop(
6418 &mut self,
6419 bias: Bias,
6420 window: &mut Window,
6421 cx: &mut Context<Self>,
6422 ) -> bool {
6423 if let Some(mut snippet) = self.snippet_stack.pop() {
6424 match bias {
6425 Bias::Left => {
6426 if snippet.active_index > 0 {
6427 snippet.active_index -= 1;
6428 } else {
6429 self.snippet_stack.push(snippet);
6430 return false;
6431 }
6432 }
6433 Bias::Right => {
6434 if snippet.active_index + 1 < snippet.ranges.len() {
6435 snippet.active_index += 1;
6436 } else {
6437 self.snippet_stack.push(snippet);
6438 return false;
6439 }
6440 }
6441 }
6442 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6443 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6444 s.select_anchor_ranges(current_ranges.iter().cloned())
6445 });
6446
6447 if let Some(choices) = &snippet.choices[snippet.active_index] {
6448 if let Some(selection) = current_ranges.first() {
6449 self.show_snippet_choices(&choices, selection.clone(), cx);
6450 }
6451 }
6452
6453 // If snippet state is not at the last tabstop, push it back on the stack
6454 if snippet.active_index + 1 < snippet.ranges.len() {
6455 self.snippet_stack.push(snippet);
6456 }
6457 return true;
6458 }
6459 }
6460
6461 false
6462 }
6463
6464 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6465 self.transact(window, cx, |this, window, cx| {
6466 this.select_all(&SelectAll, window, cx);
6467 this.insert("", window, cx);
6468 });
6469 }
6470
6471 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6472 self.transact(window, cx, |this, window, cx| {
6473 this.select_autoclose_pair(window, cx);
6474 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6475 if !this.linked_edit_ranges.is_empty() {
6476 let selections = this.selections.all::<MultiBufferPoint>(cx);
6477 let snapshot = this.buffer.read(cx).snapshot(cx);
6478
6479 for selection in selections.iter() {
6480 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6481 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6482 if selection_start.buffer_id != selection_end.buffer_id {
6483 continue;
6484 }
6485 if let Some(ranges) =
6486 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6487 {
6488 for (buffer, entries) in ranges {
6489 linked_ranges.entry(buffer).or_default().extend(entries);
6490 }
6491 }
6492 }
6493 }
6494
6495 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6496 if !this.selections.line_mode {
6497 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6498 for selection in &mut selections {
6499 if selection.is_empty() {
6500 let old_head = selection.head();
6501 let mut new_head =
6502 movement::left(&display_map, old_head.to_display_point(&display_map))
6503 .to_point(&display_map);
6504 if let Some((buffer, line_buffer_range)) = display_map
6505 .buffer_snapshot
6506 .buffer_line_for_row(MultiBufferRow(old_head.row))
6507 {
6508 let indent_size =
6509 buffer.indent_size_for_line(line_buffer_range.start.row);
6510 let indent_len = match indent_size.kind {
6511 IndentKind::Space => {
6512 buffer.settings_at(line_buffer_range.start, cx).tab_size
6513 }
6514 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6515 };
6516 if old_head.column <= indent_size.len && old_head.column > 0 {
6517 let indent_len = indent_len.get();
6518 new_head = cmp::min(
6519 new_head,
6520 MultiBufferPoint::new(
6521 old_head.row,
6522 ((old_head.column - 1) / indent_len) * indent_len,
6523 ),
6524 );
6525 }
6526 }
6527
6528 selection.set_head(new_head, SelectionGoal::None);
6529 }
6530 }
6531 }
6532
6533 this.signature_help_state.set_backspace_pressed(true);
6534 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6535 s.select(selections)
6536 });
6537 this.insert("", window, cx);
6538 let empty_str: Arc<str> = Arc::from("");
6539 for (buffer, edits) in linked_ranges {
6540 let snapshot = buffer.read(cx).snapshot();
6541 use text::ToPoint as TP;
6542
6543 let edits = edits
6544 .into_iter()
6545 .map(|range| {
6546 let end_point = TP::to_point(&range.end, &snapshot);
6547 let mut start_point = TP::to_point(&range.start, &snapshot);
6548
6549 if end_point == start_point {
6550 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6551 .saturating_sub(1);
6552 start_point =
6553 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6554 };
6555
6556 (start_point..end_point, empty_str.clone())
6557 })
6558 .sorted_by_key(|(range, _)| range.start)
6559 .collect::<Vec<_>>();
6560 buffer.update(cx, |this, cx| {
6561 this.edit(edits, None, cx);
6562 })
6563 }
6564 this.refresh_inline_completion(true, false, window, cx);
6565 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6566 });
6567 }
6568
6569 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6570 self.transact(window, cx, |this, window, cx| {
6571 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6572 let line_mode = s.line_mode;
6573 s.move_with(|map, selection| {
6574 if selection.is_empty() && !line_mode {
6575 let cursor = movement::right(map, selection.head());
6576 selection.end = cursor;
6577 selection.reversed = true;
6578 selection.goal = SelectionGoal::None;
6579 }
6580 })
6581 });
6582 this.insert("", window, cx);
6583 this.refresh_inline_completion(true, false, window, cx);
6584 });
6585 }
6586
6587 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6588 if self.move_to_prev_snippet_tabstop(window, cx) {
6589 return;
6590 }
6591
6592 self.outdent(&Outdent, window, cx);
6593 }
6594
6595 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6596 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6597 return;
6598 }
6599
6600 let mut selections = self.selections.all_adjusted(cx);
6601 let buffer = self.buffer.read(cx);
6602 let snapshot = buffer.snapshot(cx);
6603 let rows_iter = selections.iter().map(|s| s.head().row);
6604 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6605
6606 let mut edits = Vec::new();
6607 let mut prev_edited_row = 0;
6608 let mut row_delta = 0;
6609 for selection in &mut selections {
6610 if selection.start.row != prev_edited_row {
6611 row_delta = 0;
6612 }
6613 prev_edited_row = selection.end.row;
6614
6615 // If the selection is non-empty, then increase the indentation of the selected lines.
6616 if !selection.is_empty() {
6617 row_delta =
6618 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6619 continue;
6620 }
6621
6622 // If the selection is empty and the cursor is in the leading whitespace before the
6623 // suggested indentation, then auto-indent the line.
6624 let cursor = selection.head();
6625 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6626 if let Some(suggested_indent) =
6627 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6628 {
6629 if cursor.column < suggested_indent.len
6630 && cursor.column <= current_indent.len
6631 && current_indent.len <= suggested_indent.len
6632 {
6633 selection.start = Point::new(cursor.row, suggested_indent.len);
6634 selection.end = selection.start;
6635 if row_delta == 0 {
6636 edits.extend(Buffer::edit_for_indent_size_adjustment(
6637 cursor.row,
6638 current_indent,
6639 suggested_indent,
6640 ));
6641 row_delta = suggested_indent.len - current_indent.len;
6642 }
6643 continue;
6644 }
6645 }
6646
6647 // Otherwise, insert a hard or soft tab.
6648 let settings = buffer.settings_at(cursor, cx);
6649 let tab_size = if settings.hard_tabs {
6650 IndentSize::tab()
6651 } else {
6652 let tab_size = settings.tab_size.get();
6653 let char_column = snapshot
6654 .text_for_range(Point::new(cursor.row, 0)..cursor)
6655 .flat_map(str::chars)
6656 .count()
6657 + row_delta as usize;
6658 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6659 IndentSize::spaces(chars_to_next_tab_stop)
6660 };
6661 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6662 selection.end = selection.start;
6663 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6664 row_delta += tab_size.len;
6665 }
6666
6667 self.transact(window, cx, |this, window, cx| {
6668 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6669 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6670 s.select(selections)
6671 });
6672 this.refresh_inline_completion(true, false, window, cx);
6673 });
6674 }
6675
6676 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6677 if self.read_only(cx) {
6678 return;
6679 }
6680 let mut selections = self.selections.all::<Point>(cx);
6681 let mut prev_edited_row = 0;
6682 let mut row_delta = 0;
6683 let mut edits = Vec::new();
6684 let buffer = self.buffer.read(cx);
6685 let snapshot = buffer.snapshot(cx);
6686 for selection in &mut selections {
6687 if selection.start.row != prev_edited_row {
6688 row_delta = 0;
6689 }
6690 prev_edited_row = selection.end.row;
6691
6692 row_delta =
6693 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6694 }
6695
6696 self.transact(window, cx, |this, window, cx| {
6697 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6698 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6699 s.select(selections)
6700 });
6701 });
6702 }
6703
6704 fn indent_selection(
6705 buffer: &MultiBuffer,
6706 snapshot: &MultiBufferSnapshot,
6707 selection: &mut Selection<Point>,
6708 edits: &mut Vec<(Range<Point>, String)>,
6709 delta_for_start_row: u32,
6710 cx: &App,
6711 ) -> u32 {
6712 let settings = buffer.settings_at(selection.start, cx);
6713 let tab_size = settings.tab_size.get();
6714 let indent_kind = if settings.hard_tabs {
6715 IndentKind::Tab
6716 } else {
6717 IndentKind::Space
6718 };
6719 let mut start_row = selection.start.row;
6720 let mut end_row = selection.end.row + 1;
6721
6722 // If a selection ends at the beginning of a line, don't indent
6723 // that last line.
6724 if selection.end.column == 0 && selection.end.row > selection.start.row {
6725 end_row -= 1;
6726 }
6727
6728 // Avoid re-indenting a row that has already been indented by a
6729 // previous selection, but still update this selection's column
6730 // to reflect that indentation.
6731 if delta_for_start_row > 0 {
6732 start_row += 1;
6733 selection.start.column += delta_for_start_row;
6734 if selection.end.row == selection.start.row {
6735 selection.end.column += delta_for_start_row;
6736 }
6737 }
6738
6739 let mut delta_for_end_row = 0;
6740 let has_multiple_rows = start_row + 1 != end_row;
6741 for row in start_row..end_row {
6742 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6743 let indent_delta = match (current_indent.kind, indent_kind) {
6744 (IndentKind::Space, IndentKind::Space) => {
6745 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6746 IndentSize::spaces(columns_to_next_tab_stop)
6747 }
6748 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6749 (_, IndentKind::Tab) => IndentSize::tab(),
6750 };
6751
6752 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6753 0
6754 } else {
6755 selection.start.column
6756 };
6757 let row_start = Point::new(row, start);
6758 edits.push((
6759 row_start..row_start,
6760 indent_delta.chars().collect::<String>(),
6761 ));
6762
6763 // Update this selection's endpoints to reflect the indentation.
6764 if row == selection.start.row {
6765 selection.start.column += indent_delta.len;
6766 }
6767 if row == selection.end.row {
6768 selection.end.column += indent_delta.len;
6769 delta_for_end_row = indent_delta.len;
6770 }
6771 }
6772
6773 if selection.start.row == selection.end.row {
6774 delta_for_start_row + delta_for_end_row
6775 } else {
6776 delta_for_end_row
6777 }
6778 }
6779
6780 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6781 if self.read_only(cx) {
6782 return;
6783 }
6784 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6785 let selections = self.selections.all::<Point>(cx);
6786 let mut deletion_ranges = Vec::new();
6787 let mut last_outdent = None;
6788 {
6789 let buffer = self.buffer.read(cx);
6790 let snapshot = buffer.snapshot(cx);
6791 for selection in &selections {
6792 let settings = buffer.settings_at(selection.start, cx);
6793 let tab_size = settings.tab_size.get();
6794 let mut rows = selection.spanned_rows(false, &display_map);
6795
6796 // Avoid re-outdenting a row that has already been outdented by a
6797 // previous selection.
6798 if let Some(last_row) = last_outdent {
6799 if last_row == rows.start {
6800 rows.start = rows.start.next_row();
6801 }
6802 }
6803 let has_multiple_rows = rows.len() > 1;
6804 for row in rows.iter_rows() {
6805 let indent_size = snapshot.indent_size_for_line(row);
6806 if indent_size.len > 0 {
6807 let deletion_len = match indent_size.kind {
6808 IndentKind::Space => {
6809 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6810 if columns_to_prev_tab_stop == 0 {
6811 tab_size
6812 } else {
6813 columns_to_prev_tab_stop
6814 }
6815 }
6816 IndentKind::Tab => 1,
6817 };
6818 let start = if has_multiple_rows
6819 || deletion_len > selection.start.column
6820 || indent_size.len < selection.start.column
6821 {
6822 0
6823 } else {
6824 selection.start.column - deletion_len
6825 };
6826 deletion_ranges.push(
6827 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6828 );
6829 last_outdent = Some(row);
6830 }
6831 }
6832 }
6833 }
6834
6835 self.transact(window, cx, |this, window, cx| {
6836 this.buffer.update(cx, |buffer, cx| {
6837 let empty_str: Arc<str> = Arc::default();
6838 buffer.edit(
6839 deletion_ranges
6840 .into_iter()
6841 .map(|range| (range, empty_str.clone())),
6842 None,
6843 cx,
6844 );
6845 });
6846 let selections = this.selections.all::<usize>(cx);
6847 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6848 s.select(selections)
6849 });
6850 });
6851 }
6852
6853 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6854 if self.read_only(cx) {
6855 return;
6856 }
6857 let selections = self
6858 .selections
6859 .all::<usize>(cx)
6860 .into_iter()
6861 .map(|s| s.range());
6862
6863 self.transact(window, cx, |this, window, cx| {
6864 this.buffer.update(cx, |buffer, cx| {
6865 buffer.autoindent_ranges(selections, cx);
6866 });
6867 let selections = this.selections.all::<usize>(cx);
6868 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6869 s.select(selections)
6870 });
6871 });
6872 }
6873
6874 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6875 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6876 let selections = self.selections.all::<Point>(cx);
6877
6878 let mut new_cursors = Vec::new();
6879 let mut edit_ranges = Vec::new();
6880 let mut selections = selections.iter().peekable();
6881 while let Some(selection) = selections.next() {
6882 let mut rows = selection.spanned_rows(false, &display_map);
6883 let goal_display_column = selection.head().to_display_point(&display_map).column();
6884
6885 // Accumulate contiguous regions of rows that we want to delete.
6886 while let Some(next_selection) = selections.peek() {
6887 let next_rows = next_selection.spanned_rows(false, &display_map);
6888 if next_rows.start <= rows.end {
6889 rows.end = next_rows.end;
6890 selections.next().unwrap();
6891 } else {
6892 break;
6893 }
6894 }
6895
6896 let buffer = &display_map.buffer_snapshot;
6897 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6898 let edit_end;
6899 let cursor_buffer_row;
6900 if buffer.max_point().row >= rows.end.0 {
6901 // If there's a line after the range, delete the \n from the end of the row range
6902 // and position the cursor on the next line.
6903 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6904 cursor_buffer_row = rows.end;
6905 } else {
6906 // If there isn't a line after the range, delete the \n from the line before the
6907 // start of the row range and position the cursor there.
6908 edit_start = edit_start.saturating_sub(1);
6909 edit_end = buffer.len();
6910 cursor_buffer_row = rows.start.previous_row();
6911 }
6912
6913 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6914 *cursor.column_mut() =
6915 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6916
6917 new_cursors.push((
6918 selection.id,
6919 buffer.anchor_after(cursor.to_point(&display_map)),
6920 ));
6921 edit_ranges.push(edit_start..edit_end);
6922 }
6923
6924 self.transact(window, cx, |this, window, cx| {
6925 let buffer = this.buffer.update(cx, |buffer, cx| {
6926 let empty_str: Arc<str> = Arc::default();
6927 buffer.edit(
6928 edit_ranges
6929 .into_iter()
6930 .map(|range| (range, empty_str.clone())),
6931 None,
6932 cx,
6933 );
6934 buffer.snapshot(cx)
6935 });
6936 let new_selections = new_cursors
6937 .into_iter()
6938 .map(|(id, cursor)| {
6939 let cursor = cursor.to_point(&buffer);
6940 Selection {
6941 id,
6942 start: cursor,
6943 end: cursor,
6944 reversed: false,
6945 goal: SelectionGoal::None,
6946 }
6947 })
6948 .collect();
6949
6950 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6951 s.select(new_selections);
6952 });
6953 });
6954 }
6955
6956 pub fn join_lines_impl(
6957 &mut self,
6958 insert_whitespace: bool,
6959 window: &mut Window,
6960 cx: &mut Context<Self>,
6961 ) {
6962 if self.read_only(cx) {
6963 return;
6964 }
6965 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6966 for selection in self.selections.all::<Point>(cx) {
6967 let start = MultiBufferRow(selection.start.row);
6968 // Treat single line selections as if they include the next line. Otherwise this action
6969 // would do nothing for single line selections individual cursors.
6970 let end = if selection.start.row == selection.end.row {
6971 MultiBufferRow(selection.start.row + 1)
6972 } else {
6973 MultiBufferRow(selection.end.row)
6974 };
6975
6976 if let Some(last_row_range) = row_ranges.last_mut() {
6977 if start <= last_row_range.end {
6978 last_row_range.end = end;
6979 continue;
6980 }
6981 }
6982 row_ranges.push(start..end);
6983 }
6984
6985 let snapshot = self.buffer.read(cx).snapshot(cx);
6986 let mut cursor_positions = Vec::new();
6987 for row_range in &row_ranges {
6988 let anchor = snapshot.anchor_before(Point::new(
6989 row_range.end.previous_row().0,
6990 snapshot.line_len(row_range.end.previous_row()),
6991 ));
6992 cursor_positions.push(anchor..anchor);
6993 }
6994
6995 self.transact(window, cx, |this, window, cx| {
6996 for row_range in row_ranges.into_iter().rev() {
6997 for row in row_range.iter_rows().rev() {
6998 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6999 let next_line_row = row.next_row();
7000 let indent = snapshot.indent_size_for_line(next_line_row);
7001 let start_of_next_line = Point::new(next_line_row.0, indent.len);
7002
7003 let replace =
7004 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
7005 " "
7006 } else {
7007 ""
7008 };
7009
7010 this.buffer.update(cx, |buffer, cx| {
7011 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
7012 });
7013 }
7014 }
7015
7016 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7017 s.select_anchor_ranges(cursor_positions)
7018 });
7019 });
7020 }
7021
7022 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
7023 self.join_lines_impl(true, window, cx);
7024 }
7025
7026 pub fn sort_lines_case_sensitive(
7027 &mut self,
7028 _: &SortLinesCaseSensitive,
7029 window: &mut Window,
7030 cx: &mut Context<Self>,
7031 ) {
7032 self.manipulate_lines(window, cx, |lines| lines.sort())
7033 }
7034
7035 pub fn sort_lines_case_insensitive(
7036 &mut self,
7037 _: &SortLinesCaseInsensitive,
7038 window: &mut Window,
7039 cx: &mut Context<Self>,
7040 ) {
7041 self.manipulate_lines(window, cx, |lines| {
7042 lines.sort_by_key(|line| line.to_lowercase())
7043 })
7044 }
7045
7046 pub fn unique_lines_case_insensitive(
7047 &mut self,
7048 _: &UniqueLinesCaseInsensitive,
7049 window: &mut Window,
7050 cx: &mut Context<Self>,
7051 ) {
7052 self.manipulate_lines(window, cx, |lines| {
7053 let mut seen = HashSet::default();
7054 lines.retain(|line| seen.insert(line.to_lowercase()));
7055 })
7056 }
7057
7058 pub fn unique_lines_case_sensitive(
7059 &mut self,
7060 _: &UniqueLinesCaseSensitive,
7061 window: &mut Window,
7062 cx: &mut Context<Self>,
7063 ) {
7064 self.manipulate_lines(window, cx, |lines| {
7065 let mut seen = HashSet::default();
7066 lines.retain(|line| seen.insert(*line));
7067 })
7068 }
7069
7070 pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
7071 let mut revert_changes = HashMap::default();
7072 let snapshot = self.snapshot(window, cx);
7073 for hunk in snapshot
7074 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
7075 {
7076 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
7077 }
7078 if !revert_changes.is_empty() {
7079 self.transact(window, cx, |editor, window, cx| {
7080 editor.revert(revert_changes, window, cx);
7081 });
7082 }
7083 }
7084
7085 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7086 let Some(project) = self.project.clone() else {
7087 return;
7088 };
7089 self.reload(project, window, cx)
7090 .detach_and_notify_err(window, cx);
7091 }
7092
7093 pub fn revert_selected_hunks(
7094 &mut self,
7095 _: &RevertSelectedHunks,
7096 window: &mut Window,
7097 cx: &mut Context<Self>,
7098 ) {
7099 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
7100 self.revert_hunks_in_ranges(selections, window, cx);
7101 }
7102
7103 fn revert_hunks_in_ranges(
7104 &mut self,
7105 ranges: impl Iterator<Item = Range<Point>>,
7106 window: &mut Window,
7107 cx: &mut Context<Editor>,
7108 ) {
7109 let mut revert_changes = HashMap::default();
7110 let snapshot = self.snapshot(window, cx);
7111 for hunk in &snapshot.hunks_for_ranges(ranges) {
7112 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
7113 }
7114 if !revert_changes.is_empty() {
7115 self.transact(window, cx, |editor, window, cx| {
7116 editor.revert(revert_changes, window, cx);
7117 });
7118 }
7119 }
7120
7121 pub fn open_active_item_in_terminal(
7122 &mut self,
7123 _: &OpenInTerminal,
7124 window: &mut Window,
7125 cx: &mut Context<Self>,
7126 ) {
7127 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7128 let project_path = buffer.read(cx).project_path(cx)?;
7129 let project = self.project.as_ref()?.read(cx);
7130 let entry = project.entry_for_path(&project_path, cx)?;
7131 let parent = match &entry.canonical_path {
7132 Some(canonical_path) => canonical_path.to_path_buf(),
7133 None => project.absolute_path(&project_path, cx)?,
7134 }
7135 .parent()?
7136 .to_path_buf();
7137 Some(parent)
7138 }) {
7139 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7140 }
7141 }
7142
7143 pub fn prepare_revert_change(
7144 &self,
7145 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7146 hunk: &MultiBufferDiffHunk,
7147 cx: &mut App,
7148 ) -> Option<()> {
7149 let buffer = self.buffer.read(cx);
7150 let diff = buffer.diff_for(hunk.buffer_id)?;
7151 let buffer = buffer.buffer(hunk.buffer_id)?;
7152 let buffer = buffer.read(cx);
7153 let original_text = diff
7154 .read(cx)
7155 .base_text()
7156 .as_ref()?
7157 .as_rope()
7158 .slice(hunk.diff_base_byte_range.clone());
7159 let buffer_snapshot = buffer.snapshot();
7160 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7161 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7162 probe
7163 .0
7164 .start
7165 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7166 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7167 }) {
7168 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7169 Some(())
7170 } else {
7171 None
7172 }
7173 }
7174
7175 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7176 self.manipulate_lines(window, cx, |lines| lines.reverse())
7177 }
7178
7179 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7180 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7181 }
7182
7183 fn manipulate_lines<Fn>(
7184 &mut self,
7185 window: &mut Window,
7186 cx: &mut Context<Self>,
7187 mut callback: Fn,
7188 ) where
7189 Fn: FnMut(&mut Vec<&str>),
7190 {
7191 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7192 let buffer = self.buffer.read(cx).snapshot(cx);
7193
7194 let mut edits = Vec::new();
7195
7196 let selections = self.selections.all::<Point>(cx);
7197 let mut selections = selections.iter().peekable();
7198 let mut contiguous_row_selections = Vec::new();
7199 let mut new_selections = Vec::new();
7200 let mut added_lines = 0;
7201 let mut removed_lines = 0;
7202
7203 while let Some(selection) = selections.next() {
7204 let (start_row, end_row) = consume_contiguous_rows(
7205 &mut contiguous_row_selections,
7206 selection,
7207 &display_map,
7208 &mut selections,
7209 );
7210
7211 let start_point = Point::new(start_row.0, 0);
7212 let end_point = Point::new(
7213 end_row.previous_row().0,
7214 buffer.line_len(end_row.previous_row()),
7215 );
7216 let text = buffer
7217 .text_for_range(start_point..end_point)
7218 .collect::<String>();
7219
7220 let mut lines = text.split('\n').collect_vec();
7221
7222 let lines_before = lines.len();
7223 callback(&mut lines);
7224 let lines_after = lines.len();
7225
7226 edits.push((start_point..end_point, lines.join("\n")));
7227
7228 // Selections must change based on added and removed line count
7229 let start_row =
7230 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7231 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7232 new_selections.push(Selection {
7233 id: selection.id,
7234 start: start_row,
7235 end: end_row,
7236 goal: SelectionGoal::None,
7237 reversed: selection.reversed,
7238 });
7239
7240 if lines_after > lines_before {
7241 added_lines += lines_after - lines_before;
7242 } else if lines_before > lines_after {
7243 removed_lines += lines_before - lines_after;
7244 }
7245 }
7246
7247 self.transact(window, cx, |this, window, cx| {
7248 let buffer = this.buffer.update(cx, |buffer, cx| {
7249 buffer.edit(edits, None, cx);
7250 buffer.snapshot(cx)
7251 });
7252
7253 // Recalculate offsets on newly edited buffer
7254 let new_selections = new_selections
7255 .iter()
7256 .map(|s| {
7257 let start_point = Point::new(s.start.0, 0);
7258 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
7259 Selection {
7260 id: s.id,
7261 start: buffer.point_to_offset(start_point),
7262 end: buffer.point_to_offset(end_point),
7263 goal: s.goal,
7264 reversed: s.reversed,
7265 }
7266 })
7267 .collect();
7268
7269 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7270 s.select(new_selections);
7271 });
7272
7273 this.request_autoscroll(Autoscroll::fit(), cx);
7274 });
7275 }
7276
7277 pub fn convert_to_upper_case(
7278 &mut self,
7279 _: &ConvertToUpperCase,
7280 window: &mut Window,
7281 cx: &mut Context<Self>,
7282 ) {
7283 self.manipulate_text(window, cx, |text| text.to_uppercase())
7284 }
7285
7286 pub fn convert_to_lower_case(
7287 &mut self,
7288 _: &ConvertToLowerCase,
7289 window: &mut Window,
7290 cx: &mut Context<Self>,
7291 ) {
7292 self.manipulate_text(window, cx, |text| text.to_lowercase())
7293 }
7294
7295 pub fn convert_to_title_case(
7296 &mut self,
7297 _: &ConvertToTitleCase,
7298 window: &mut Window,
7299 cx: &mut Context<Self>,
7300 ) {
7301 self.manipulate_text(window, cx, |text| {
7302 text.split('\n')
7303 .map(|line| line.to_case(Case::Title))
7304 .join("\n")
7305 })
7306 }
7307
7308 pub fn convert_to_snake_case(
7309 &mut self,
7310 _: &ConvertToSnakeCase,
7311 window: &mut Window,
7312 cx: &mut Context<Self>,
7313 ) {
7314 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7315 }
7316
7317 pub fn convert_to_kebab_case(
7318 &mut self,
7319 _: &ConvertToKebabCase,
7320 window: &mut Window,
7321 cx: &mut Context<Self>,
7322 ) {
7323 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7324 }
7325
7326 pub fn convert_to_upper_camel_case(
7327 &mut self,
7328 _: &ConvertToUpperCamelCase,
7329 window: &mut Window,
7330 cx: &mut Context<Self>,
7331 ) {
7332 self.manipulate_text(window, cx, |text| {
7333 text.split('\n')
7334 .map(|line| line.to_case(Case::UpperCamel))
7335 .join("\n")
7336 })
7337 }
7338
7339 pub fn convert_to_lower_camel_case(
7340 &mut self,
7341 _: &ConvertToLowerCamelCase,
7342 window: &mut Window,
7343 cx: &mut Context<Self>,
7344 ) {
7345 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
7346 }
7347
7348 pub fn convert_to_opposite_case(
7349 &mut self,
7350 _: &ConvertToOppositeCase,
7351 window: &mut Window,
7352 cx: &mut Context<Self>,
7353 ) {
7354 self.manipulate_text(window, cx, |text| {
7355 text.chars()
7356 .fold(String::with_capacity(text.len()), |mut t, c| {
7357 if c.is_uppercase() {
7358 t.extend(c.to_lowercase());
7359 } else {
7360 t.extend(c.to_uppercase());
7361 }
7362 t
7363 })
7364 })
7365 }
7366
7367 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
7368 where
7369 Fn: FnMut(&str) -> String,
7370 {
7371 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7372 let buffer = self.buffer.read(cx).snapshot(cx);
7373
7374 let mut new_selections = Vec::new();
7375 let mut edits = Vec::new();
7376 let mut selection_adjustment = 0i32;
7377
7378 for selection in self.selections.all::<usize>(cx) {
7379 let selection_is_empty = selection.is_empty();
7380
7381 let (start, end) = if selection_is_empty {
7382 let word_range = movement::surrounding_word(
7383 &display_map,
7384 selection.start.to_display_point(&display_map),
7385 );
7386 let start = word_range.start.to_offset(&display_map, Bias::Left);
7387 let end = word_range.end.to_offset(&display_map, Bias::Left);
7388 (start, end)
7389 } else {
7390 (selection.start, selection.end)
7391 };
7392
7393 let text = buffer.text_for_range(start..end).collect::<String>();
7394 let old_length = text.len() as i32;
7395 let text = callback(&text);
7396
7397 new_selections.push(Selection {
7398 start: (start as i32 - selection_adjustment) as usize,
7399 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
7400 goal: SelectionGoal::None,
7401 ..selection
7402 });
7403
7404 selection_adjustment += old_length - text.len() as i32;
7405
7406 edits.push((start..end, text));
7407 }
7408
7409 self.transact(window, cx, |this, window, cx| {
7410 this.buffer.update(cx, |buffer, cx| {
7411 buffer.edit(edits, None, cx);
7412 });
7413
7414 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7415 s.select(new_selections);
7416 });
7417
7418 this.request_autoscroll(Autoscroll::fit(), cx);
7419 });
7420 }
7421
7422 pub fn duplicate(
7423 &mut self,
7424 upwards: bool,
7425 whole_lines: bool,
7426 window: &mut Window,
7427 cx: &mut Context<Self>,
7428 ) {
7429 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7430 let buffer = &display_map.buffer_snapshot;
7431 let selections = self.selections.all::<Point>(cx);
7432
7433 let mut edits = Vec::new();
7434 let mut selections_iter = selections.iter().peekable();
7435 while let Some(selection) = selections_iter.next() {
7436 let mut rows = selection.spanned_rows(false, &display_map);
7437 // duplicate line-wise
7438 if whole_lines || selection.start == selection.end {
7439 // Avoid duplicating the same lines twice.
7440 while let Some(next_selection) = selections_iter.peek() {
7441 let next_rows = next_selection.spanned_rows(false, &display_map);
7442 if next_rows.start < rows.end {
7443 rows.end = next_rows.end;
7444 selections_iter.next().unwrap();
7445 } else {
7446 break;
7447 }
7448 }
7449
7450 // Copy the text from the selected row region and splice it either at the start
7451 // or end of the region.
7452 let start = Point::new(rows.start.0, 0);
7453 let end = Point::new(
7454 rows.end.previous_row().0,
7455 buffer.line_len(rows.end.previous_row()),
7456 );
7457 let text = buffer
7458 .text_for_range(start..end)
7459 .chain(Some("\n"))
7460 .collect::<String>();
7461 let insert_location = if upwards {
7462 Point::new(rows.end.0, 0)
7463 } else {
7464 start
7465 };
7466 edits.push((insert_location..insert_location, text));
7467 } else {
7468 // duplicate character-wise
7469 let start = selection.start;
7470 let end = selection.end;
7471 let text = buffer.text_for_range(start..end).collect::<String>();
7472 edits.push((selection.end..selection.end, text));
7473 }
7474 }
7475
7476 self.transact(window, cx, |this, _, cx| {
7477 this.buffer.update(cx, |buffer, cx| {
7478 buffer.edit(edits, None, cx);
7479 });
7480
7481 this.request_autoscroll(Autoscroll::fit(), cx);
7482 });
7483 }
7484
7485 pub fn duplicate_line_up(
7486 &mut self,
7487 _: &DuplicateLineUp,
7488 window: &mut Window,
7489 cx: &mut Context<Self>,
7490 ) {
7491 self.duplicate(true, true, window, cx);
7492 }
7493
7494 pub fn duplicate_line_down(
7495 &mut self,
7496 _: &DuplicateLineDown,
7497 window: &mut Window,
7498 cx: &mut Context<Self>,
7499 ) {
7500 self.duplicate(false, true, window, cx);
7501 }
7502
7503 pub fn duplicate_selection(
7504 &mut self,
7505 _: &DuplicateSelection,
7506 window: &mut Window,
7507 cx: &mut Context<Self>,
7508 ) {
7509 self.duplicate(false, false, window, cx);
7510 }
7511
7512 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7513 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7514 let buffer = self.buffer.read(cx).snapshot(cx);
7515
7516 let mut edits = Vec::new();
7517 let mut unfold_ranges = Vec::new();
7518 let mut refold_creases = Vec::new();
7519
7520 let selections = self.selections.all::<Point>(cx);
7521 let mut selections = selections.iter().peekable();
7522 let mut contiguous_row_selections = Vec::new();
7523 let mut new_selections = Vec::new();
7524
7525 while let Some(selection) = selections.next() {
7526 // Find all the selections that span a contiguous row range
7527 let (start_row, end_row) = consume_contiguous_rows(
7528 &mut contiguous_row_selections,
7529 selection,
7530 &display_map,
7531 &mut selections,
7532 );
7533
7534 // Move the text spanned by the row range to be before the line preceding the row range
7535 if start_row.0 > 0 {
7536 let range_to_move = Point::new(
7537 start_row.previous_row().0,
7538 buffer.line_len(start_row.previous_row()),
7539 )
7540 ..Point::new(
7541 end_row.previous_row().0,
7542 buffer.line_len(end_row.previous_row()),
7543 );
7544 let insertion_point = display_map
7545 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7546 .0;
7547
7548 // Don't move lines across excerpts
7549 if buffer
7550 .excerpt_containing(insertion_point..range_to_move.end)
7551 .is_some()
7552 {
7553 let text = buffer
7554 .text_for_range(range_to_move.clone())
7555 .flat_map(|s| s.chars())
7556 .skip(1)
7557 .chain(['\n'])
7558 .collect::<String>();
7559
7560 edits.push((
7561 buffer.anchor_after(range_to_move.start)
7562 ..buffer.anchor_before(range_to_move.end),
7563 String::new(),
7564 ));
7565 let insertion_anchor = buffer.anchor_after(insertion_point);
7566 edits.push((insertion_anchor..insertion_anchor, text));
7567
7568 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7569
7570 // Move selections up
7571 new_selections.extend(contiguous_row_selections.drain(..).map(
7572 |mut selection| {
7573 selection.start.row -= row_delta;
7574 selection.end.row -= row_delta;
7575 selection
7576 },
7577 ));
7578
7579 // Move folds up
7580 unfold_ranges.push(range_to_move.clone());
7581 for fold in display_map.folds_in_range(
7582 buffer.anchor_before(range_to_move.start)
7583 ..buffer.anchor_after(range_to_move.end),
7584 ) {
7585 let mut start = fold.range.start.to_point(&buffer);
7586 let mut end = fold.range.end.to_point(&buffer);
7587 start.row -= row_delta;
7588 end.row -= row_delta;
7589 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7590 }
7591 }
7592 }
7593
7594 // If we didn't move line(s), preserve the existing selections
7595 new_selections.append(&mut contiguous_row_selections);
7596 }
7597
7598 self.transact(window, cx, |this, window, cx| {
7599 this.unfold_ranges(&unfold_ranges, true, true, cx);
7600 this.buffer.update(cx, |buffer, cx| {
7601 for (range, text) in edits {
7602 buffer.edit([(range, text)], None, cx);
7603 }
7604 });
7605 this.fold_creases(refold_creases, true, window, cx);
7606 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7607 s.select(new_selections);
7608 })
7609 });
7610 }
7611
7612 pub fn move_line_down(
7613 &mut self,
7614 _: &MoveLineDown,
7615 window: &mut Window,
7616 cx: &mut Context<Self>,
7617 ) {
7618 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7619 let buffer = self.buffer.read(cx).snapshot(cx);
7620
7621 let mut edits = Vec::new();
7622 let mut unfold_ranges = Vec::new();
7623 let mut refold_creases = Vec::new();
7624
7625 let selections = self.selections.all::<Point>(cx);
7626 let mut selections = selections.iter().peekable();
7627 let mut contiguous_row_selections = Vec::new();
7628 let mut new_selections = Vec::new();
7629
7630 while let Some(selection) = selections.next() {
7631 // Find all the selections that span a contiguous row range
7632 let (start_row, end_row) = consume_contiguous_rows(
7633 &mut contiguous_row_selections,
7634 selection,
7635 &display_map,
7636 &mut selections,
7637 );
7638
7639 // Move the text spanned by the row range to be after the last line of the row range
7640 if end_row.0 <= buffer.max_point().row {
7641 let range_to_move =
7642 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7643 let insertion_point = display_map
7644 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7645 .0;
7646
7647 // Don't move lines across excerpt boundaries
7648 if buffer
7649 .excerpt_containing(range_to_move.start..insertion_point)
7650 .is_some()
7651 {
7652 let mut text = String::from("\n");
7653 text.extend(buffer.text_for_range(range_to_move.clone()));
7654 text.pop(); // Drop trailing newline
7655 edits.push((
7656 buffer.anchor_after(range_to_move.start)
7657 ..buffer.anchor_before(range_to_move.end),
7658 String::new(),
7659 ));
7660 let insertion_anchor = buffer.anchor_after(insertion_point);
7661 edits.push((insertion_anchor..insertion_anchor, text));
7662
7663 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7664
7665 // Move selections down
7666 new_selections.extend(contiguous_row_selections.drain(..).map(
7667 |mut selection| {
7668 selection.start.row += row_delta;
7669 selection.end.row += row_delta;
7670 selection
7671 },
7672 ));
7673
7674 // Move folds down
7675 unfold_ranges.push(range_to_move.clone());
7676 for fold in display_map.folds_in_range(
7677 buffer.anchor_before(range_to_move.start)
7678 ..buffer.anchor_after(range_to_move.end),
7679 ) {
7680 let mut start = fold.range.start.to_point(&buffer);
7681 let mut end = fold.range.end.to_point(&buffer);
7682 start.row += row_delta;
7683 end.row += row_delta;
7684 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7685 }
7686 }
7687 }
7688
7689 // If we didn't move line(s), preserve the existing selections
7690 new_selections.append(&mut contiguous_row_selections);
7691 }
7692
7693 self.transact(window, cx, |this, window, cx| {
7694 this.unfold_ranges(&unfold_ranges, true, true, cx);
7695 this.buffer.update(cx, |buffer, cx| {
7696 for (range, text) in edits {
7697 buffer.edit([(range, text)], None, cx);
7698 }
7699 });
7700 this.fold_creases(refold_creases, true, window, cx);
7701 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7702 s.select(new_selections)
7703 });
7704 });
7705 }
7706
7707 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7708 let text_layout_details = &self.text_layout_details(window);
7709 self.transact(window, cx, |this, window, cx| {
7710 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7711 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7712 let line_mode = s.line_mode;
7713 s.move_with(|display_map, selection| {
7714 if !selection.is_empty() || line_mode {
7715 return;
7716 }
7717
7718 let mut head = selection.head();
7719 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7720 if head.column() == display_map.line_len(head.row()) {
7721 transpose_offset = display_map
7722 .buffer_snapshot
7723 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7724 }
7725
7726 if transpose_offset == 0 {
7727 return;
7728 }
7729
7730 *head.column_mut() += 1;
7731 head = display_map.clip_point(head, Bias::Right);
7732 let goal = SelectionGoal::HorizontalPosition(
7733 display_map
7734 .x_for_display_point(head, text_layout_details)
7735 .into(),
7736 );
7737 selection.collapse_to(head, goal);
7738
7739 let transpose_start = display_map
7740 .buffer_snapshot
7741 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7742 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7743 let transpose_end = display_map
7744 .buffer_snapshot
7745 .clip_offset(transpose_offset + 1, Bias::Right);
7746 if let Some(ch) =
7747 display_map.buffer_snapshot.chars_at(transpose_start).next()
7748 {
7749 edits.push((transpose_start..transpose_offset, String::new()));
7750 edits.push((transpose_end..transpose_end, ch.to_string()));
7751 }
7752 }
7753 });
7754 edits
7755 });
7756 this.buffer
7757 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7758 let selections = this.selections.all::<usize>(cx);
7759 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7760 s.select(selections);
7761 });
7762 });
7763 }
7764
7765 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7766 self.rewrap_impl(IsVimMode::No, cx)
7767 }
7768
7769 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7770 let buffer = self.buffer.read(cx).snapshot(cx);
7771 let selections = self.selections.all::<Point>(cx);
7772 let mut selections = selections.iter().peekable();
7773
7774 let mut edits = Vec::new();
7775 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7776
7777 while let Some(selection) = selections.next() {
7778 let mut start_row = selection.start.row;
7779 let mut end_row = selection.end.row;
7780
7781 // Skip selections that overlap with a range that has already been rewrapped.
7782 let selection_range = start_row..end_row;
7783 if rewrapped_row_ranges
7784 .iter()
7785 .any(|range| range.overlaps(&selection_range))
7786 {
7787 continue;
7788 }
7789
7790 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7791
7792 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7793 match language_scope.language_name().as_ref() {
7794 "Markdown" | "Plain Text" => {
7795 should_rewrap = true;
7796 }
7797 _ => {}
7798 }
7799 }
7800
7801 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7802
7803 // Since not all lines in the selection may be at the same indent
7804 // level, choose the indent size that is the most common between all
7805 // of the lines.
7806 //
7807 // If there is a tie, we use the deepest indent.
7808 let (indent_size, indent_end) = {
7809 let mut indent_size_occurrences = HashMap::default();
7810 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7811
7812 for row in start_row..=end_row {
7813 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7814 rows_by_indent_size.entry(indent).or_default().push(row);
7815 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7816 }
7817
7818 let indent_size = indent_size_occurrences
7819 .into_iter()
7820 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7821 .map(|(indent, _)| indent)
7822 .unwrap_or_default();
7823 let row = rows_by_indent_size[&indent_size][0];
7824 let indent_end = Point::new(row, indent_size.len);
7825
7826 (indent_size, indent_end)
7827 };
7828
7829 let mut line_prefix = indent_size.chars().collect::<String>();
7830
7831 if let Some(comment_prefix) =
7832 buffer
7833 .language_scope_at(selection.head())
7834 .and_then(|language| {
7835 language
7836 .line_comment_prefixes()
7837 .iter()
7838 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7839 .cloned()
7840 })
7841 {
7842 line_prefix.push_str(&comment_prefix);
7843 should_rewrap = true;
7844 }
7845
7846 if !should_rewrap {
7847 continue;
7848 }
7849
7850 if selection.is_empty() {
7851 'expand_upwards: while start_row > 0 {
7852 let prev_row = start_row - 1;
7853 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7854 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7855 {
7856 start_row = prev_row;
7857 } else {
7858 break 'expand_upwards;
7859 }
7860 }
7861
7862 'expand_downwards: while end_row < buffer.max_point().row {
7863 let next_row = end_row + 1;
7864 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7865 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7866 {
7867 end_row = next_row;
7868 } else {
7869 break 'expand_downwards;
7870 }
7871 }
7872 }
7873
7874 let start = Point::new(start_row, 0);
7875 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7876 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7877 let Some(lines_without_prefixes) = selection_text
7878 .lines()
7879 .map(|line| {
7880 line.strip_prefix(&line_prefix)
7881 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7882 .ok_or_else(|| {
7883 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7884 })
7885 })
7886 .collect::<Result<Vec<_>, _>>()
7887 .log_err()
7888 else {
7889 continue;
7890 };
7891
7892 let wrap_column = buffer
7893 .settings_at(Point::new(start_row, 0), cx)
7894 .preferred_line_length as usize;
7895 let wrapped_text = wrap_with_prefix(
7896 line_prefix,
7897 lines_without_prefixes.join(" "),
7898 wrap_column,
7899 tab_size,
7900 );
7901
7902 // TODO: should always use char-based diff while still supporting cursor behavior that
7903 // matches vim.
7904 let diff = match is_vim_mode {
7905 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7906 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7907 };
7908 let mut offset = start.to_offset(&buffer);
7909 let mut moved_since_edit = true;
7910
7911 for change in diff.iter_all_changes() {
7912 let value = change.value();
7913 match change.tag() {
7914 ChangeTag::Equal => {
7915 offset += value.len();
7916 moved_since_edit = true;
7917 }
7918 ChangeTag::Delete => {
7919 let start = buffer.anchor_after(offset);
7920 let end = buffer.anchor_before(offset + value.len());
7921
7922 if moved_since_edit {
7923 edits.push((start..end, String::new()));
7924 } else {
7925 edits.last_mut().unwrap().0.end = end;
7926 }
7927
7928 offset += value.len();
7929 moved_since_edit = false;
7930 }
7931 ChangeTag::Insert => {
7932 if moved_since_edit {
7933 let anchor = buffer.anchor_after(offset);
7934 edits.push((anchor..anchor, value.to_string()));
7935 } else {
7936 edits.last_mut().unwrap().1.push_str(value);
7937 }
7938
7939 moved_since_edit = false;
7940 }
7941 }
7942 }
7943
7944 rewrapped_row_ranges.push(start_row..=end_row);
7945 }
7946
7947 self.buffer
7948 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7949 }
7950
7951 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7952 let mut text = String::new();
7953 let buffer = self.buffer.read(cx).snapshot(cx);
7954 let mut selections = self.selections.all::<Point>(cx);
7955 let mut clipboard_selections = Vec::with_capacity(selections.len());
7956 {
7957 let max_point = buffer.max_point();
7958 let mut is_first = true;
7959 for selection in &mut selections {
7960 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7961 if is_entire_line {
7962 selection.start = Point::new(selection.start.row, 0);
7963 if !selection.is_empty() && selection.end.column == 0 {
7964 selection.end = cmp::min(max_point, selection.end);
7965 } else {
7966 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7967 }
7968 selection.goal = SelectionGoal::None;
7969 }
7970 if is_first {
7971 is_first = false;
7972 } else {
7973 text += "\n";
7974 }
7975 let mut len = 0;
7976 for chunk in buffer.text_for_range(selection.start..selection.end) {
7977 text.push_str(chunk);
7978 len += chunk.len();
7979 }
7980 clipboard_selections.push(ClipboardSelection {
7981 len,
7982 is_entire_line,
7983 first_line_indent: buffer
7984 .indent_size_for_line(MultiBufferRow(selection.start.row))
7985 .len,
7986 });
7987 }
7988 }
7989
7990 self.transact(window, cx, |this, window, cx| {
7991 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7992 s.select(selections);
7993 });
7994 this.insert("", window, cx);
7995 });
7996 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7997 }
7998
7999 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
8000 let item = self.cut_common(window, cx);
8001 cx.write_to_clipboard(item);
8002 }
8003
8004 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
8005 self.change_selections(None, window, cx, |s| {
8006 s.move_with(|snapshot, sel| {
8007 if sel.is_empty() {
8008 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
8009 }
8010 });
8011 });
8012 let item = self.cut_common(window, cx);
8013 cx.set_global(KillRing(item))
8014 }
8015
8016 pub fn kill_ring_yank(
8017 &mut self,
8018 _: &KillRingYank,
8019 window: &mut Window,
8020 cx: &mut Context<Self>,
8021 ) {
8022 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
8023 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
8024 (kill_ring.text().to_string(), kill_ring.metadata_json())
8025 } else {
8026 return;
8027 }
8028 } else {
8029 return;
8030 };
8031 self.do_paste(&text, metadata, false, window, cx);
8032 }
8033
8034 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
8035 let selections = self.selections.all::<Point>(cx);
8036 let buffer = self.buffer.read(cx).read(cx);
8037 let mut text = String::new();
8038
8039 let mut clipboard_selections = Vec::with_capacity(selections.len());
8040 {
8041 let max_point = buffer.max_point();
8042 let mut is_first = true;
8043 for selection in selections.iter() {
8044 let mut start = selection.start;
8045 let mut end = selection.end;
8046 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8047 if is_entire_line {
8048 start = Point::new(start.row, 0);
8049 end = cmp::min(max_point, Point::new(end.row + 1, 0));
8050 }
8051 if is_first {
8052 is_first = false;
8053 } else {
8054 text += "\n";
8055 }
8056 let mut len = 0;
8057 for chunk in buffer.text_for_range(start..end) {
8058 text.push_str(chunk);
8059 len += chunk.len();
8060 }
8061 clipboard_selections.push(ClipboardSelection {
8062 len,
8063 is_entire_line,
8064 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
8065 });
8066 }
8067 }
8068
8069 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
8070 text,
8071 clipboard_selections,
8072 ));
8073 }
8074
8075 pub fn do_paste(
8076 &mut self,
8077 text: &String,
8078 clipboard_selections: Option<Vec<ClipboardSelection>>,
8079 handle_entire_lines: bool,
8080 window: &mut Window,
8081 cx: &mut Context<Self>,
8082 ) {
8083 if self.read_only(cx) {
8084 return;
8085 }
8086
8087 let clipboard_text = Cow::Borrowed(text);
8088
8089 self.transact(window, cx, |this, window, cx| {
8090 if let Some(mut clipboard_selections) = clipboard_selections {
8091 let old_selections = this.selections.all::<usize>(cx);
8092 let all_selections_were_entire_line =
8093 clipboard_selections.iter().all(|s| s.is_entire_line);
8094 let first_selection_indent_column =
8095 clipboard_selections.first().map(|s| s.first_line_indent);
8096 if clipboard_selections.len() != old_selections.len() {
8097 clipboard_selections.drain(..);
8098 }
8099 let cursor_offset = this.selections.last::<usize>(cx).head();
8100 let mut auto_indent_on_paste = true;
8101
8102 this.buffer.update(cx, |buffer, cx| {
8103 let snapshot = buffer.read(cx);
8104 auto_indent_on_paste =
8105 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
8106
8107 let mut start_offset = 0;
8108 let mut edits = Vec::new();
8109 let mut original_indent_columns = Vec::new();
8110 for (ix, selection) in old_selections.iter().enumerate() {
8111 let to_insert;
8112 let entire_line;
8113 let original_indent_column;
8114 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
8115 let end_offset = start_offset + clipboard_selection.len;
8116 to_insert = &clipboard_text[start_offset..end_offset];
8117 entire_line = clipboard_selection.is_entire_line;
8118 start_offset = end_offset + 1;
8119 original_indent_column = Some(clipboard_selection.first_line_indent);
8120 } else {
8121 to_insert = clipboard_text.as_str();
8122 entire_line = all_selections_were_entire_line;
8123 original_indent_column = first_selection_indent_column
8124 }
8125
8126 // If the corresponding selection was empty when this slice of the
8127 // clipboard text was written, then the entire line containing the
8128 // selection was copied. If this selection is also currently empty,
8129 // then paste the line before the current line of the buffer.
8130 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8131 let column = selection.start.to_point(&snapshot).column as usize;
8132 let line_start = selection.start - column;
8133 line_start..line_start
8134 } else {
8135 selection.range()
8136 };
8137
8138 edits.push((range, to_insert));
8139 original_indent_columns.extend(original_indent_column);
8140 }
8141 drop(snapshot);
8142
8143 buffer.edit(
8144 edits,
8145 if auto_indent_on_paste {
8146 Some(AutoindentMode::Block {
8147 original_indent_columns,
8148 })
8149 } else {
8150 None
8151 },
8152 cx,
8153 );
8154 });
8155
8156 let selections = this.selections.all::<usize>(cx);
8157 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8158 s.select(selections)
8159 });
8160 } else {
8161 this.insert(&clipboard_text, window, cx);
8162 }
8163 });
8164 }
8165
8166 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8167 if let Some(item) = cx.read_from_clipboard() {
8168 let entries = item.entries();
8169
8170 match entries.first() {
8171 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8172 // of all the pasted entries.
8173 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8174 .do_paste(
8175 clipboard_string.text(),
8176 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8177 true,
8178 window,
8179 cx,
8180 ),
8181 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8182 }
8183 }
8184 }
8185
8186 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8187 if self.read_only(cx) {
8188 return;
8189 }
8190
8191 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8192 if let Some((selections, _)) =
8193 self.selection_history.transaction(transaction_id).cloned()
8194 {
8195 self.change_selections(None, window, cx, |s| {
8196 s.select_anchors(selections.to_vec());
8197 });
8198 }
8199 self.request_autoscroll(Autoscroll::fit(), cx);
8200 self.unmark_text(window, cx);
8201 self.refresh_inline_completion(true, false, window, cx);
8202 cx.emit(EditorEvent::Edited { transaction_id });
8203 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8204 }
8205 }
8206
8207 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8208 if self.read_only(cx) {
8209 return;
8210 }
8211
8212 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8213 if let Some((_, Some(selections))) =
8214 self.selection_history.transaction(transaction_id).cloned()
8215 {
8216 self.change_selections(None, window, cx, |s| {
8217 s.select_anchors(selections.to_vec());
8218 });
8219 }
8220 self.request_autoscroll(Autoscroll::fit(), cx);
8221 self.unmark_text(window, cx);
8222 self.refresh_inline_completion(true, false, window, cx);
8223 cx.emit(EditorEvent::Edited { transaction_id });
8224 }
8225 }
8226
8227 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8228 self.buffer
8229 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8230 }
8231
8232 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8233 self.buffer
8234 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8235 }
8236
8237 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8238 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8239 let line_mode = s.line_mode;
8240 s.move_with(|map, selection| {
8241 let cursor = if selection.is_empty() && !line_mode {
8242 movement::left(map, selection.start)
8243 } else {
8244 selection.start
8245 };
8246 selection.collapse_to(cursor, SelectionGoal::None);
8247 });
8248 })
8249 }
8250
8251 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8252 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8253 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8254 })
8255 }
8256
8257 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8258 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8259 let line_mode = s.line_mode;
8260 s.move_with(|map, selection| {
8261 let cursor = if selection.is_empty() && !line_mode {
8262 movement::right(map, selection.end)
8263 } else {
8264 selection.end
8265 };
8266 selection.collapse_to(cursor, SelectionGoal::None)
8267 });
8268 })
8269 }
8270
8271 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
8272 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8273 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
8274 })
8275 }
8276
8277 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
8278 if self.take_rename(true, window, cx).is_some() {
8279 return;
8280 }
8281
8282 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8283 cx.propagate();
8284 return;
8285 }
8286
8287 let text_layout_details = &self.text_layout_details(window);
8288 let selection_count = self.selections.count();
8289 let first_selection = self.selections.first_anchor();
8290
8291 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8292 let line_mode = s.line_mode;
8293 s.move_with(|map, selection| {
8294 if !selection.is_empty() && !line_mode {
8295 selection.goal = SelectionGoal::None;
8296 }
8297 let (cursor, goal) = movement::up(
8298 map,
8299 selection.start,
8300 selection.goal,
8301 false,
8302 text_layout_details,
8303 );
8304 selection.collapse_to(cursor, goal);
8305 });
8306 });
8307
8308 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8309 {
8310 cx.propagate();
8311 }
8312 }
8313
8314 pub fn move_up_by_lines(
8315 &mut self,
8316 action: &MoveUpByLines,
8317 window: &mut Window,
8318 cx: &mut Context<Self>,
8319 ) {
8320 if self.take_rename(true, window, cx).is_some() {
8321 return;
8322 }
8323
8324 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8325 cx.propagate();
8326 return;
8327 }
8328
8329 let text_layout_details = &self.text_layout_details(window);
8330
8331 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8332 let line_mode = s.line_mode;
8333 s.move_with(|map, selection| {
8334 if !selection.is_empty() && !line_mode {
8335 selection.goal = SelectionGoal::None;
8336 }
8337 let (cursor, goal) = movement::up_by_rows(
8338 map,
8339 selection.start,
8340 action.lines,
8341 selection.goal,
8342 false,
8343 text_layout_details,
8344 );
8345 selection.collapse_to(cursor, goal);
8346 });
8347 })
8348 }
8349
8350 pub fn move_down_by_lines(
8351 &mut self,
8352 action: &MoveDownByLines,
8353 window: &mut Window,
8354 cx: &mut Context<Self>,
8355 ) {
8356 if self.take_rename(true, window, cx).is_some() {
8357 return;
8358 }
8359
8360 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8361 cx.propagate();
8362 return;
8363 }
8364
8365 let text_layout_details = &self.text_layout_details(window);
8366
8367 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8368 let line_mode = s.line_mode;
8369 s.move_with(|map, selection| {
8370 if !selection.is_empty() && !line_mode {
8371 selection.goal = SelectionGoal::None;
8372 }
8373 let (cursor, goal) = movement::down_by_rows(
8374 map,
8375 selection.start,
8376 action.lines,
8377 selection.goal,
8378 false,
8379 text_layout_details,
8380 );
8381 selection.collapse_to(cursor, goal);
8382 });
8383 })
8384 }
8385
8386 pub fn select_down_by_lines(
8387 &mut self,
8388 action: &SelectDownByLines,
8389 window: &mut Window,
8390 cx: &mut Context<Self>,
8391 ) {
8392 let text_layout_details = &self.text_layout_details(window);
8393 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8394 s.move_heads_with(|map, head, goal| {
8395 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
8396 })
8397 })
8398 }
8399
8400 pub fn select_up_by_lines(
8401 &mut self,
8402 action: &SelectUpByLines,
8403 window: &mut Window,
8404 cx: &mut Context<Self>,
8405 ) {
8406 let text_layout_details = &self.text_layout_details(window);
8407 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8408 s.move_heads_with(|map, head, goal| {
8409 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8410 })
8411 })
8412 }
8413
8414 pub fn select_page_up(
8415 &mut self,
8416 _: &SelectPageUp,
8417 window: &mut Window,
8418 cx: &mut Context<Self>,
8419 ) {
8420 let Some(row_count) = self.visible_row_count() else {
8421 return;
8422 };
8423
8424 let text_layout_details = &self.text_layout_details(window);
8425
8426 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8427 s.move_heads_with(|map, head, goal| {
8428 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8429 })
8430 })
8431 }
8432
8433 pub fn move_page_up(
8434 &mut self,
8435 action: &MovePageUp,
8436 window: &mut Window,
8437 cx: &mut Context<Self>,
8438 ) {
8439 if self.take_rename(true, window, cx).is_some() {
8440 return;
8441 }
8442
8443 if self
8444 .context_menu
8445 .borrow_mut()
8446 .as_mut()
8447 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8448 .unwrap_or(false)
8449 {
8450 return;
8451 }
8452
8453 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8454 cx.propagate();
8455 return;
8456 }
8457
8458 let Some(row_count) = self.visible_row_count() else {
8459 return;
8460 };
8461
8462 let autoscroll = if action.center_cursor {
8463 Autoscroll::center()
8464 } else {
8465 Autoscroll::fit()
8466 };
8467
8468 let text_layout_details = &self.text_layout_details(window);
8469
8470 self.change_selections(Some(autoscroll), window, cx, |s| {
8471 let line_mode = s.line_mode;
8472 s.move_with(|map, selection| {
8473 if !selection.is_empty() && !line_mode {
8474 selection.goal = SelectionGoal::None;
8475 }
8476 let (cursor, goal) = movement::up_by_rows(
8477 map,
8478 selection.end,
8479 row_count,
8480 selection.goal,
8481 false,
8482 text_layout_details,
8483 );
8484 selection.collapse_to(cursor, goal);
8485 });
8486 });
8487 }
8488
8489 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8490 let text_layout_details = &self.text_layout_details(window);
8491 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8492 s.move_heads_with(|map, head, goal| {
8493 movement::up(map, head, goal, false, text_layout_details)
8494 })
8495 })
8496 }
8497
8498 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8499 self.take_rename(true, window, cx);
8500
8501 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8502 cx.propagate();
8503 return;
8504 }
8505
8506 let text_layout_details = &self.text_layout_details(window);
8507 let selection_count = self.selections.count();
8508 let first_selection = self.selections.first_anchor();
8509
8510 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8511 let line_mode = s.line_mode;
8512 s.move_with(|map, selection| {
8513 if !selection.is_empty() && !line_mode {
8514 selection.goal = SelectionGoal::None;
8515 }
8516 let (cursor, goal) = movement::down(
8517 map,
8518 selection.end,
8519 selection.goal,
8520 false,
8521 text_layout_details,
8522 );
8523 selection.collapse_to(cursor, goal);
8524 });
8525 });
8526
8527 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8528 {
8529 cx.propagate();
8530 }
8531 }
8532
8533 pub fn select_page_down(
8534 &mut self,
8535 _: &SelectPageDown,
8536 window: &mut Window,
8537 cx: &mut Context<Self>,
8538 ) {
8539 let Some(row_count) = self.visible_row_count() else {
8540 return;
8541 };
8542
8543 let text_layout_details = &self.text_layout_details(window);
8544
8545 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8546 s.move_heads_with(|map, head, goal| {
8547 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8548 })
8549 })
8550 }
8551
8552 pub fn move_page_down(
8553 &mut self,
8554 action: &MovePageDown,
8555 window: &mut Window,
8556 cx: &mut Context<Self>,
8557 ) {
8558 if self.take_rename(true, window, cx).is_some() {
8559 return;
8560 }
8561
8562 if self
8563 .context_menu
8564 .borrow_mut()
8565 .as_mut()
8566 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8567 .unwrap_or(false)
8568 {
8569 return;
8570 }
8571
8572 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8573 cx.propagate();
8574 return;
8575 }
8576
8577 let Some(row_count) = self.visible_row_count() else {
8578 return;
8579 };
8580
8581 let autoscroll = if action.center_cursor {
8582 Autoscroll::center()
8583 } else {
8584 Autoscroll::fit()
8585 };
8586
8587 let text_layout_details = &self.text_layout_details(window);
8588 self.change_selections(Some(autoscroll), window, cx, |s| {
8589 let line_mode = s.line_mode;
8590 s.move_with(|map, selection| {
8591 if !selection.is_empty() && !line_mode {
8592 selection.goal = SelectionGoal::None;
8593 }
8594 let (cursor, goal) = movement::down_by_rows(
8595 map,
8596 selection.end,
8597 row_count,
8598 selection.goal,
8599 false,
8600 text_layout_details,
8601 );
8602 selection.collapse_to(cursor, goal);
8603 });
8604 });
8605 }
8606
8607 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8608 let text_layout_details = &self.text_layout_details(window);
8609 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8610 s.move_heads_with(|map, head, goal| {
8611 movement::down(map, head, goal, false, text_layout_details)
8612 })
8613 });
8614 }
8615
8616 pub fn context_menu_first(
8617 &mut self,
8618 _: &ContextMenuFirst,
8619 _window: &mut Window,
8620 cx: &mut Context<Self>,
8621 ) {
8622 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8623 context_menu.select_first(self.completion_provider.as_deref(), cx);
8624 }
8625 }
8626
8627 pub fn context_menu_prev(
8628 &mut self,
8629 _: &ContextMenuPrev,
8630 _window: &mut Window,
8631 cx: &mut Context<Self>,
8632 ) {
8633 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8634 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8635 }
8636 }
8637
8638 pub fn context_menu_next(
8639 &mut self,
8640 _: &ContextMenuNext,
8641 _window: &mut Window,
8642 cx: &mut Context<Self>,
8643 ) {
8644 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8645 context_menu.select_next(self.completion_provider.as_deref(), cx);
8646 }
8647 }
8648
8649 pub fn context_menu_last(
8650 &mut self,
8651 _: &ContextMenuLast,
8652 _window: &mut Window,
8653 cx: &mut Context<Self>,
8654 ) {
8655 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8656 context_menu.select_last(self.completion_provider.as_deref(), cx);
8657 }
8658 }
8659
8660 pub fn move_to_previous_word_start(
8661 &mut self,
8662 _: &MoveToPreviousWordStart,
8663 window: &mut Window,
8664 cx: &mut Context<Self>,
8665 ) {
8666 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8667 s.move_cursors_with(|map, head, _| {
8668 (
8669 movement::previous_word_start(map, head),
8670 SelectionGoal::None,
8671 )
8672 });
8673 })
8674 }
8675
8676 pub fn move_to_previous_subword_start(
8677 &mut self,
8678 _: &MoveToPreviousSubwordStart,
8679 window: &mut Window,
8680 cx: &mut Context<Self>,
8681 ) {
8682 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8683 s.move_cursors_with(|map, head, _| {
8684 (
8685 movement::previous_subword_start(map, head),
8686 SelectionGoal::None,
8687 )
8688 });
8689 })
8690 }
8691
8692 pub fn select_to_previous_word_start(
8693 &mut self,
8694 _: &SelectToPreviousWordStart,
8695 window: &mut Window,
8696 cx: &mut Context<Self>,
8697 ) {
8698 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8699 s.move_heads_with(|map, head, _| {
8700 (
8701 movement::previous_word_start(map, head),
8702 SelectionGoal::None,
8703 )
8704 });
8705 })
8706 }
8707
8708 pub fn select_to_previous_subword_start(
8709 &mut self,
8710 _: &SelectToPreviousSubwordStart,
8711 window: &mut Window,
8712 cx: &mut Context<Self>,
8713 ) {
8714 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8715 s.move_heads_with(|map, head, _| {
8716 (
8717 movement::previous_subword_start(map, head),
8718 SelectionGoal::None,
8719 )
8720 });
8721 })
8722 }
8723
8724 pub fn delete_to_previous_word_start(
8725 &mut self,
8726 action: &DeleteToPreviousWordStart,
8727 window: &mut Window,
8728 cx: &mut Context<Self>,
8729 ) {
8730 self.transact(window, cx, |this, window, cx| {
8731 this.select_autoclose_pair(window, cx);
8732 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8733 let line_mode = s.line_mode;
8734 s.move_with(|map, selection| {
8735 if selection.is_empty() && !line_mode {
8736 let cursor = if action.ignore_newlines {
8737 movement::previous_word_start(map, selection.head())
8738 } else {
8739 movement::previous_word_start_or_newline(map, selection.head())
8740 };
8741 selection.set_head(cursor, SelectionGoal::None);
8742 }
8743 });
8744 });
8745 this.insert("", window, cx);
8746 });
8747 }
8748
8749 pub fn delete_to_previous_subword_start(
8750 &mut self,
8751 _: &DeleteToPreviousSubwordStart,
8752 window: &mut Window,
8753 cx: &mut Context<Self>,
8754 ) {
8755 self.transact(window, cx, |this, window, cx| {
8756 this.select_autoclose_pair(window, cx);
8757 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8758 let line_mode = s.line_mode;
8759 s.move_with(|map, selection| {
8760 if selection.is_empty() && !line_mode {
8761 let cursor = movement::previous_subword_start(map, selection.head());
8762 selection.set_head(cursor, SelectionGoal::None);
8763 }
8764 });
8765 });
8766 this.insert("", window, cx);
8767 });
8768 }
8769
8770 pub fn move_to_next_word_end(
8771 &mut self,
8772 _: &MoveToNextWordEnd,
8773 window: &mut Window,
8774 cx: &mut Context<Self>,
8775 ) {
8776 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8777 s.move_cursors_with(|map, head, _| {
8778 (movement::next_word_end(map, head), SelectionGoal::None)
8779 });
8780 })
8781 }
8782
8783 pub fn move_to_next_subword_end(
8784 &mut self,
8785 _: &MoveToNextSubwordEnd,
8786 window: &mut Window,
8787 cx: &mut Context<Self>,
8788 ) {
8789 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8790 s.move_cursors_with(|map, head, _| {
8791 (movement::next_subword_end(map, head), SelectionGoal::None)
8792 });
8793 })
8794 }
8795
8796 pub fn select_to_next_word_end(
8797 &mut self,
8798 _: &SelectToNextWordEnd,
8799 window: &mut Window,
8800 cx: &mut Context<Self>,
8801 ) {
8802 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8803 s.move_heads_with(|map, head, _| {
8804 (movement::next_word_end(map, head), SelectionGoal::None)
8805 });
8806 })
8807 }
8808
8809 pub fn select_to_next_subword_end(
8810 &mut self,
8811 _: &SelectToNextSubwordEnd,
8812 window: &mut Window,
8813 cx: &mut Context<Self>,
8814 ) {
8815 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8816 s.move_heads_with(|map, head, _| {
8817 (movement::next_subword_end(map, head), SelectionGoal::None)
8818 });
8819 })
8820 }
8821
8822 pub fn delete_to_next_word_end(
8823 &mut self,
8824 action: &DeleteToNextWordEnd,
8825 window: &mut Window,
8826 cx: &mut Context<Self>,
8827 ) {
8828 self.transact(window, cx, |this, window, cx| {
8829 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8830 let line_mode = s.line_mode;
8831 s.move_with(|map, selection| {
8832 if selection.is_empty() && !line_mode {
8833 let cursor = if action.ignore_newlines {
8834 movement::next_word_end(map, selection.head())
8835 } else {
8836 movement::next_word_end_or_newline(map, selection.head())
8837 };
8838 selection.set_head(cursor, SelectionGoal::None);
8839 }
8840 });
8841 });
8842 this.insert("", window, cx);
8843 });
8844 }
8845
8846 pub fn delete_to_next_subword_end(
8847 &mut self,
8848 _: &DeleteToNextSubwordEnd,
8849 window: &mut Window,
8850 cx: &mut Context<Self>,
8851 ) {
8852 self.transact(window, cx, |this, window, cx| {
8853 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8854 s.move_with(|map, selection| {
8855 if selection.is_empty() {
8856 let cursor = movement::next_subword_end(map, selection.head());
8857 selection.set_head(cursor, SelectionGoal::None);
8858 }
8859 });
8860 });
8861 this.insert("", window, cx);
8862 });
8863 }
8864
8865 pub fn move_to_beginning_of_line(
8866 &mut self,
8867 action: &MoveToBeginningOfLine,
8868 window: &mut Window,
8869 cx: &mut Context<Self>,
8870 ) {
8871 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8872 s.move_cursors_with(|map, head, _| {
8873 (
8874 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8875 SelectionGoal::None,
8876 )
8877 });
8878 })
8879 }
8880
8881 pub fn select_to_beginning_of_line(
8882 &mut self,
8883 action: &SelectToBeginningOfLine,
8884 window: &mut Window,
8885 cx: &mut Context<Self>,
8886 ) {
8887 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8888 s.move_heads_with(|map, head, _| {
8889 (
8890 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8891 SelectionGoal::None,
8892 )
8893 });
8894 });
8895 }
8896
8897 pub fn delete_to_beginning_of_line(
8898 &mut self,
8899 _: &DeleteToBeginningOfLine,
8900 window: &mut Window,
8901 cx: &mut Context<Self>,
8902 ) {
8903 self.transact(window, cx, |this, window, cx| {
8904 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8905 s.move_with(|_, selection| {
8906 selection.reversed = true;
8907 });
8908 });
8909
8910 this.select_to_beginning_of_line(
8911 &SelectToBeginningOfLine {
8912 stop_at_soft_wraps: false,
8913 },
8914 window,
8915 cx,
8916 );
8917 this.backspace(&Backspace, window, cx);
8918 });
8919 }
8920
8921 pub fn move_to_end_of_line(
8922 &mut self,
8923 action: &MoveToEndOfLine,
8924 window: &mut Window,
8925 cx: &mut Context<Self>,
8926 ) {
8927 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8928 s.move_cursors_with(|map, head, _| {
8929 (
8930 movement::line_end(map, head, action.stop_at_soft_wraps),
8931 SelectionGoal::None,
8932 )
8933 });
8934 })
8935 }
8936
8937 pub fn select_to_end_of_line(
8938 &mut self,
8939 action: &SelectToEndOfLine,
8940 window: &mut Window,
8941 cx: &mut Context<Self>,
8942 ) {
8943 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8944 s.move_heads_with(|map, head, _| {
8945 (
8946 movement::line_end(map, head, action.stop_at_soft_wraps),
8947 SelectionGoal::None,
8948 )
8949 });
8950 })
8951 }
8952
8953 pub fn delete_to_end_of_line(
8954 &mut self,
8955 _: &DeleteToEndOfLine,
8956 window: &mut Window,
8957 cx: &mut Context<Self>,
8958 ) {
8959 self.transact(window, cx, |this, window, cx| {
8960 this.select_to_end_of_line(
8961 &SelectToEndOfLine {
8962 stop_at_soft_wraps: false,
8963 },
8964 window,
8965 cx,
8966 );
8967 this.delete(&Delete, window, cx);
8968 });
8969 }
8970
8971 pub fn cut_to_end_of_line(
8972 &mut self,
8973 _: &CutToEndOfLine,
8974 window: &mut Window,
8975 cx: &mut Context<Self>,
8976 ) {
8977 self.transact(window, cx, |this, window, cx| {
8978 this.select_to_end_of_line(
8979 &SelectToEndOfLine {
8980 stop_at_soft_wraps: false,
8981 },
8982 window,
8983 cx,
8984 );
8985 this.cut(&Cut, window, cx);
8986 });
8987 }
8988
8989 pub fn move_to_start_of_paragraph(
8990 &mut self,
8991 _: &MoveToStartOfParagraph,
8992 window: &mut Window,
8993 cx: &mut Context<Self>,
8994 ) {
8995 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8996 cx.propagate();
8997 return;
8998 }
8999
9000 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9001 s.move_with(|map, selection| {
9002 selection.collapse_to(
9003 movement::start_of_paragraph(map, selection.head(), 1),
9004 SelectionGoal::None,
9005 )
9006 });
9007 })
9008 }
9009
9010 pub fn move_to_end_of_paragraph(
9011 &mut self,
9012 _: &MoveToEndOfParagraph,
9013 window: &mut Window,
9014 cx: &mut Context<Self>,
9015 ) {
9016 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9017 cx.propagate();
9018 return;
9019 }
9020
9021 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9022 s.move_with(|map, selection| {
9023 selection.collapse_to(
9024 movement::end_of_paragraph(map, selection.head(), 1),
9025 SelectionGoal::None,
9026 )
9027 });
9028 })
9029 }
9030
9031 pub fn select_to_start_of_paragraph(
9032 &mut self,
9033 _: &SelectToStartOfParagraph,
9034 window: &mut Window,
9035 cx: &mut Context<Self>,
9036 ) {
9037 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9038 cx.propagate();
9039 return;
9040 }
9041
9042 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9043 s.move_heads_with(|map, head, _| {
9044 (
9045 movement::start_of_paragraph(map, head, 1),
9046 SelectionGoal::None,
9047 )
9048 });
9049 })
9050 }
9051
9052 pub fn select_to_end_of_paragraph(
9053 &mut self,
9054 _: &SelectToEndOfParagraph,
9055 window: &mut Window,
9056 cx: &mut Context<Self>,
9057 ) {
9058 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9059 cx.propagate();
9060 return;
9061 }
9062
9063 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9064 s.move_heads_with(|map, head, _| {
9065 (
9066 movement::end_of_paragraph(map, head, 1),
9067 SelectionGoal::None,
9068 )
9069 });
9070 })
9071 }
9072
9073 pub fn move_to_beginning(
9074 &mut self,
9075 _: &MoveToBeginning,
9076 window: &mut Window,
9077 cx: &mut Context<Self>,
9078 ) {
9079 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9080 cx.propagate();
9081 return;
9082 }
9083
9084 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9085 s.select_ranges(vec![0..0]);
9086 });
9087 }
9088
9089 pub fn select_to_beginning(
9090 &mut self,
9091 _: &SelectToBeginning,
9092 window: &mut Window,
9093 cx: &mut Context<Self>,
9094 ) {
9095 let mut selection = self.selections.last::<Point>(cx);
9096 selection.set_head(Point::zero(), SelectionGoal::None);
9097
9098 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9099 s.select(vec![selection]);
9100 });
9101 }
9102
9103 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
9104 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9105 cx.propagate();
9106 return;
9107 }
9108
9109 let cursor = self.buffer.read(cx).read(cx).len();
9110 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9111 s.select_ranges(vec![cursor..cursor])
9112 });
9113 }
9114
9115 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
9116 self.nav_history = nav_history;
9117 }
9118
9119 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
9120 self.nav_history.as_ref()
9121 }
9122
9123 fn push_to_nav_history(
9124 &mut self,
9125 cursor_anchor: Anchor,
9126 new_position: Option<Point>,
9127 cx: &mut Context<Self>,
9128 ) {
9129 if let Some(nav_history) = self.nav_history.as_mut() {
9130 let buffer = self.buffer.read(cx).read(cx);
9131 let cursor_position = cursor_anchor.to_point(&buffer);
9132 let scroll_state = self.scroll_manager.anchor();
9133 let scroll_top_row = scroll_state.top_row(&buffer);
9134 drop(buffer);
9135
9136 if let Some(new_position) = new_position {
9137 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
9138 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
9139 return;
9140 }
9141 }
9142
9143 nav_history.push(
9144 Some(NavigationData {
9145 cursor_anchor,
9146 cursor_position,
9147 scroll_anchor: scroll_state,
9148 scroll_top_row,
9149 }),
9150 cx,
9151 );
9152 }
9153 }
9154
9155 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
9156 let buffer = self.buffer.read(cx).snapshot(cx);
9157 let mut selection = self.selections.first::<usize>(cx);
9158 selection.set_head(buffer.len(), SelectionGoal::None);
9159 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9160 s.select(vec![selection]);
9161 });
9162 }
9163
9164 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
9165 let end = self.buffer.read(cx).read(cx).len();
9166 self.change_selections(None, window, cx, |s| {
9167 s.select_ranges(vec![0..end]);
9168 });
9169 }
9170
9171 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
9172 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9173 let mut selections = self.selections.all::<Point>(cx);
9174 let max_point = display_map.buffer_snapshot.max_point();
9175 for selection in &mut selections {
9176 let rows = selection.spanned_rows(true, &display_map);
9177 selection.start = Point::new(rows.start.0, 0);
9178 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
9179 selection.reversed = false;
9180 }
9181 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9182 s.select(selections);
9183 });
9184 }
9185
9186 pub fn split_selection_into_lines(
9187 &mut self,
9188 _: &SplitSelectionIntoLines,
9189 window: &mut Window,
9190 cx: &mut Context<Self>,
9191 ) {
9192 let mut to_unfold = Vec::new();
9193 let mut new_selection_ranges = Vec::new();
9194 {
9195 let selections = self.selections.all::<Point>(cx);
9196 let buffer = self.buffer.read(cx).read(cx);
9197 for selection in selections {
9198 for row in selection.start.row..selection.end.row {
9199 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
9200 new_selection_ranges.push(cursor..cursor);
9201 }
9202 new_selection_ranges.push(selection.end..selection.end);
9203 to_unfold.push(selection.start..selection.end);
9204 }
9205 }
9206 self.unfold_ranges(&to_unfold, true, true, cx);
9207 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9208 s.select_ranges(new_selection_ranges);
9209 });
9210 }
9211
9212 pub fn add_selection_above(
9213 &mut self,
9214 _: &AddSelectionAbove,
9215 window: &mut Window,
9216 cx: &mut Context<Self>,
9217 ) {
9218 self.add_selection(true, window, cx);
9219 }
9220
9221 pub fn add_selection_below(
9222 &mut self,
9223 _: &AddSelectionBelow,
9224 window: &mut Window,
9225 cx: &mut Context<Self>,
9226 ) {
9227 self.add_selection(false, window, cx);
9228 }
9229
9230 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
9231 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9232 let mut selections = self.selections.all::<Point>(cx);
9233 let text_layout_details = self.text_layout_details(window);
9234 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
9235 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
9236 let range = oldest_selection.display_range(&display_map).sorted();
9237
9238 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
9239 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
9240 let positions = start_x.min(end_x)..start_x.max(end_x);
9241
9242 selections.clear();
9243 let mut stack = Vec::new();
9244 for row in range.start.row().0..=range.end.row().0 {
9245 if let Some(selection) = self.selections.build_columnar_selection(
9246 &display_map,
9247 DisplayRow(row),
9248 &positions,
9249 oldest_selection.reversed,
9250 &text_layout_details,
9251 ) {
9252 stack.push(selection.id);
9253 selections.push(selection);
9254 }
9255 }
9256
9257 if above {
9258 stack.reverse();
9259 }
9260
9261 AddSelectionsState { above, stack }
9262 });
9263
9264 let last_added_selection = *state.stack.last().unwrap();
9265 let mut new_selections = Vec::new();
9266 if above == state.above {
9267 let end_row = if above {
9268 DisplayRow(0)
9269 } else {
9270 display_map.max_point().row()
9271 };
9272
9273 'outer: for selection in selections {
9274 if selection.id == last_added_selection {
9275 let range = selection.display_range(&display_map).sorted();
9276 debug_assert_eq!(range.start.row(), range.end.row());
9277 let mut row = range.start.row();
9278 let positions =
9279 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
9280 px(start)..px(end)
9281 } else {
9282 let start_x =
9283 display_map.x_for_display_point(range.start, &text_layout_details);
9284 let end_x =
9285 display_map.x_for_display_point(range.end, &text_layout_details);
9286 start_x.min(end_x)..start_x.max(end_x)
9287 };
9288
9289 while row != end_row {
9290 if above {
9291 row.0 -= 1;
9292 } else {
9293 row.0 += 1;
9294 }
9295
9296 if let Some(new_selection) = self.selections.build_columnar_selection(
9297 &display_map,
9298 row,
9299 &positions,
9300 selection.reversed,
9301 &text_layout_details,
9302 ) {
9303 state.stack.push(new_selection.id);
9304 if above {
9305 new_selections.push(new_selection);
9306 new_selections.push(selection);
9307 } else {
9308 new_selections.push(selection);
9309 new_selections.push(new_selection);
9310 }
9311
9312 continue 'outer;
9313 }
9314 }
9315 }
9316
9317 new_selections.push(selection);
9318 }
9319 } else {
9320 new_selections = selections;
9321 new_selections.retain(|s| s.id != last_added_selection);
9322 state.stack.pop();
9323 }
9324
9325 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9326 s.select(new_selections);
9327 });
9328 if state.stack.len() > 1 {
9329 self.add_selections_state = Some(state);
9330 }
9331 }
9332
9333 pub fn select_next_match_internal(
9334 &mut self,
9335 display_map: &DisplaySnapshot,
9336 replace_newest: bool,
9337 autoscroll: Option<Autoscroll>,
9338 window: &mut Window,
9339 cx: &mut Context<Self>,
9340 ) -> Result<()> {
9341 fn select_next_match_ranges(
9342 this: &mut Editor,
9343 range: Range<usize>,
9344 replace_newest: bool,
9345 auto_scroll: Option<Autoscroll>,
9346 window: &mut Window,
9347 cx: &mut Context<Editor>,
9348 ) {
9349 this.unfold_ranges(&[range.clone()], false, true, cx);
9350 this.change_selections(auto_scroll, window, cx, |s| {
9351 if replace_newest {
9352 s.delete(s.newest_anchor().id);
9353 }
9354 s.insert_range(range.clone());
9355 });
9356 }
9357
9358 let buffer = &display_map.buffer_snapshot;
9359 let mut selections = self.selections.all::<usize>(cx);
9360 if let Some(mut select_next_state) = self.select_next_state.take() {
9361 let query = &select_next_state.query;
9362 if !select_next_state.done {
9363 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9364 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9365 let mut next_selected_range = None;
9366
9367 let bytes_after_last_selection =
9368 buffer.bytes_in_range(last_selection.end..buffer.len());
9369 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
9370 let query_matches = query
9371 .stream_find_iter(bytes_after_last_selection)
9372 .map(|result| (last_selection.end, result))
9373 .chain(
9374 query
9375 .stream_find_iter(bytes_before_first_selection)
9376 .map(|result| (0, result)),
9377 );
9378
9379 for (start_offset, query_match) in query_matches {
9380 let query_match = query_match.unwrap(); // can only fail due to I/O
9381 let offset_range =
9382 start_offset + query_match.start()..start_offset + query_match.end();
9383 let display_range = offset_range.start.to_display_point(display_map)
9384 ..offset_range.end.to_display_point(display_map);
9385
9386 if !select_next_state.wordwise
9387 || (!movement::is_inside_word(display_map, display_range.start)
9388 && !movement::is_inside_word(display_map, display_range.end))
9389 {
9390 // TODO: This is n^2, because we might check all the selections
9391 if !selections
9392 .iter()
9393 .any(|selection| selection.range().overlaps(&offset_range))
9394 {
9395 next_selected_range = Some(offset_range);
9396 break;
9397 }
9398 }
9399 }
9400
9401 if let Some(next_selected_range) = next_selected_range {
9402 select_next_match_ranges(
9403 self,
9404 next_selected_range,
9405 replace_newest,
9406 autoscroll,
9407 window,
9408 cx,
9409 );
9410 } else {
9411 select_next_state.done = true;
9412 }
9413 }
9414
9415 self.select_next_state = Some(select_next_state);
9416 } else {
9417 let mut only_carets = true;
9418 let mut same_text_selected = true;
9419 let mut selected_text = None;
9420
9421 let mut selections_iter = selections.iter().peekable();
9422 while let Some(selection) = selections_iter.next() {
9423 if selection.start != selection.end {
9424 only_carets = false;
9425 }
9426
9427 if same_text_selected {
9428 if selected_text.is_none() {
9429 selected_text =
9430 Some(buffer.text_for_range(selection.range()).collect::<String>());
9431 }
9432
9433 if let Some(next_selection) = selections_iter.peek() {
9434 if next_selection.range().len() == selection.range().len() {
9435 let next_selected_text = buffer
9436 .text_for_range(next_selection.range())
9437 .collect::<String>();
9438 if Some(next_selected_text) != selected_text {
9439 same_text_selected = false;
9440 selected_text = None;
9441 }
9442 } else {
9443 same_text_selected = false;
9444 selected_text = None;
9445 }
9446 }
9447 }
9448 }
9449
9450 if only_carets {
9451 for selection in &mut selections {
9452 let word_range = movement::surrounding_word(
9453 display_map,
9454 selection.start.to_display_point(display_map),
9455 );
9456 selection.start = word_range.start.to_offset(display_map, Bias::Left);
9457 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9458 selection.goal = SelectionGoal::None;
9459 selection.reversed = false;
9460 select_next_match_ranges(
9461 self,
9462 selection.start..selection.end,
9463 replace_newest,
9464 autoscroll,
9465 window,
9466 cx,
9467 );
9468 }
9469
9470 if selections.len() == 1 {
9471 let selection = selections
9472 .last()
9473 .expect("ensured that there's only one selection");
9474 let query = buffer
9475 .text_for_range(selection.start..selection.end)
9476 .collect::<String>();
9477 let is_empty = query.is_empty();
9478 let select_state = SelectNextState {
9479 query: AhoCorasick::new(&[query])?,
9480 wordwise: true,
9481 done: is_empty,
9482 };
9483 self.select_next_state = Some(select_state);
9484 } else {
9485 self.select_next_state = None;
9486 }
9487 } else if let Some(selected_text) = selected_text {
9488 self.select_next_state = Some(SelectNextState {
9489 query: AhoCorasick::new(&[selected_text])?,
9490 wordwise: false,
9491 done: false,
9492 });
9493 self.select_next_match_internal(
9494 display_map,
9495 replace_newest,
9496 autoscroll,
9497 window,
9498 cx,
9499 )?;
9500 }
9501 }
9502 Ok(())
9503 }
9504
9505 pub fn select_all_matches(
9506 &mut self,
9507 _action: &SelectAllMatches,
9508 window: &mut Window,
9509 cx: &mut Context<Self>,
9510 ) -> Result<()> {
9511 self.push_to_selection_history();
9512 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9513
9514 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9515 let Some(select_next_state) = self.select_next_state.as_mut() else {
9516 return Ok(());
9517 };
9518 if select_next_state.done {
9519 return Ok(());
9520 }
9521
9522 let mut new_selections = self.selections.all::<usize>(cx);
9523
9524 let buffer = &display_map.buffer_snapshot;
9525 let query_matches = select_next_state
9526 .query
9527 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9528
9529 for query_match in query_matches {
9530 let query_match = query_match.unwrap(); // can only fail due to I/O
9531 let offset_range = query_match.start()..query_match.end();
9532 let display_range = offset_range.start.to_display_point(&display_map)
9533 ..offset_range.end.to_display_point(&display_map);
9534
9535 if !select_next_state.wordwise
9536 || (!movement::is_inside_word(&display_map, display_range.start)
9537 && !movement::is_inside_word(&display_map, display_range.end))
9538 {
9539 self.selections.change_with(cx, |selections| {
9540 new_selections.push(Selection {
9541 id: selections.new_selection_id(),
9542 start: offset_range.start,
9543 end: offset_range.end,
9544 reversed: false,
9545 goal: SelectionGoal::None,
9546 });
9547 });
9548 }
9549 }
9550
9551 new_selections.sort_by_key(|selection| selection.start);
9552 let mut ix = 0;
9553 while ix + 1 < new_selections.len() {
9554 let current_selection = &new_selections[ix];
9555 let next_selection = &new_selections[ix + 1];
9556 if current_selection.range().overlaps(&next_selection.range()) {
9557 if current_selection.id < next_selection.id {
9558 new_selections.remove(ix + 1);
9559 } else {
9560 new_selections.remove(ix);
9561 }
9562 } else {
9563 ix += 1;
9564 }
9565 }
9566
9567 let reversed = self.selections.oldest::<usize>(cx).reversed;
9568
9569 for selection in new_selections.iter_mut() {
9570 selection.reversed = reversed;
9571 }
9572
9573 select_next_state.done = true;
9574 self.unfold_ranges(
9575 &new_selections
9576 .iter()
9577 .map(|selection| selection.range())
9578 .collect::<Vec<_>>(),
9579 false,
9580 false,
9581 cx,
9582 );
9583 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9584 selections.select(new_selections)
9585 });
9586
9587 Ok(())
9588 }
9589
9590 pub fn select_next(
9591 &mut self,
9592 action: &SelectNext,
9593 window: &mut Window,
9594 cx: &mut Context<Self>,
9595 ) -> Result<()> {
9596 self.push_to_selection_history();
9597 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9598 self.select_next_match_internal(
9599 &display_map,
9600 action.replace_newest,
9601 Some(Autoscroll::newest()),
9602 window,
9603 cx,
9604 )?;
9605 Ok(())
9606 }
9607
9608 pub fn select_previous(
9609 &mut self,
9610 action: &SelectPrevious,
9611 window: &mut Window,
9612 cx: &mut Context<Self>,
9613 ) -> Result<()> {
9614 self.push_to_selection_history();
9615 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9616 let buffer = &display_map.buffer_snapshot;
9617 let mut selections = self.selections.all::<usize>(cx);
9618 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9619 let query = &select_prev_state.query;
9620 if !select_prev_state.done {
9621 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9622 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9623 let mut next_selected_range = None;
9624 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9625 let bytes_before_last_selection =
9626 buffer.reversed_bytes_in_range(0..last_selection.start);
9627 let bytes_after_first_selection =
9628 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9629 let query_matches = query
9630 .stream_find_iter(bytes_before_last_selection)
9631 .map(|result| (last_selection.start, result))
9632 .chain(
9633 query
9634 .stream_find_iter(bytes_after_first_selection)
9635 .map(|result| (buffer.len(), result)),
9636 );
9637 for (end_offset, query_match) in query_matches {
9638 let query_match = query_match.unwrap(); // can only fail due to I/O
9639 let offset_range =
9640 end_offset - query_match.end()..end_offset - query_match.start();
9641 let display_range = offset_range.start.to_display_point(&display_map)
9642 ..offset_range.end.to_display_point(&display_map);
9643
9644 if !select_prev_state.wordwise
9645 || (!movement::is_inside_word(&display_map, display_range.start)
9646 && !movement::is_inside_word(&display_map, display_range.end))
9647 {
9648 next_selected_range = Some(offset_range);
9649 break;
9650 }
9651 }
9652
9653 if let Some(next_selected_range) = next_selected_range {
9654 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9655 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9656 if action.replace_newest {
9657 s.delete(s.newest_anchor().id);
9658 }
9659 s.insert_range(next_selected_range);
9660 });
9661 } else {
9662 select_prev_state.done = true;
9663 }
9664 }
9665
9666 self.select_prev_state = Some(select_prev_state);
9667 } else {
9668 let mut only_carets = true;
9669 let mut same_text_selected = true;
9670 let mut selected_text = None;
9671
9672 let mut selections_iter = selections.iter().peekable();
9673 while let Some(selection) = selections_iter.next() {
9674 if selection.start != selection.end {
9675 only_carets = false;
9676 }
9677
9678 if same_text_selected {
9679 if selected_text.is_none() {
9680 selected_text =
9681 Some(buffer.text_for_range(selection.range()).collect::<String>());
9682 }
9683
9684 if let Some(next_selection) = selections_iter.peek() {
9685 if next_selection.range().len() == selection.range().len() {
9686 let next_selected_text = buffer
9687 .text_for_range(next_selection.range())
9688 .collect::<String>();
9689 if Some(next_selected_text) != selected_text {
9690 same_text_selected = false;
9691 selected_text = None;
9692 }
9693 } else {
9694 same_text_selected = false;
9695 selected_text = None;
9696 }
9697 }
9698 }
9699 }
9700
9701 if only_carets {
9702 for selection in &mut selections {
9703 let word_range = movement::surrounding_word(
9704 &display_map,
9705 selection.start.to_display_point(&display_map),
9706 );
9707 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9708 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9709 selection.goal = SelectionGoal::None;
9710 selection.reversed = false;
9711 }
9712 if selections.len() == 1 {
9713 let selection = selections
9714 .last()
9715 .expect("ensured that there's only one selection");
9716 let query = buffer
9717 .text_for_range(selection.start..selection.end)
9718 .collect::<String>();
9719 let is_empty = query.is_empty();
9720 let select_state = SelectNextState {
9721 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9722 wordwise: true,
9723 done: is_empty,
9724 };
9725 self.select_prev_state = Some(select_state);
9726 } else {
9727 self.select_prev_state = None;
9728 }
9729
9730 self.unfold_ranges(
9731 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9732 false,
9733 true,
9734 cx,
9735 );
9736 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9737 s.select(selections);
9738 });
9739 } else if let Some(selected_text) = selected_text {
9740 self.select_prev_state = Some(SelectNextState {
9741 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9742 wordwise: false,
9743 done: false,
9744 });
9745 self.select_previous(action, window, cx)?;
9746 }
9747 }
9748 Ok(())
9749 }
9750
9751 pub fn toggle_comments(
9752 &mut self,
9753 action: &ToggleComments,
9754 window: &mut Window,
9755 cx: &mut Context<Self>,
9756 ) {
9757 if self.read_only(cx) {
9758 return;
9759 }
9760 let text_layout_details = &self.text_layout_details(window);
9761 self.transact(window, cx, |this, window, cx| {
9762 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9763 let mut edits = Vec::new();
9764 let mut selection_edit_ranges = Vec::new();
9765 let mut last_toggled_row = None;
9766 let snapshot = this.buffer.read(cx).read(cx);
9767 let empty_str: Arc<str> = Arc::default();
9768 let mut suffixes_inserted = Vec::new();
9769 let ignore_indent = action.ignore_indent;
9770
9771 fn comment_prefix_range(
9772 snapshot: &MultiBufferSnapshot,
9773 row: MultiBufferRow,
9774 comment_prefix: &str,
9775 comment_prefix_whitespace: &str,
9776 ignore_indent: bool,
9777 ) -> Range<Point> {
9778 let indent_size = if ignore_indent {
9779 0
9780 } else {
9781 snapshot.indent_size_for_line(row).len
9782 };
9783
9784 let start = Point::new(row.0, indent_size);
9785
9786 let mut line_bytes = snapshot
9787 .bytes_in_range(start..snapshot.max_point())
9788 .flatten()
9789 .copied();
9790
9791 // If this line currently begins with the line comment prefix, then record
9792 // the range containing the prefix.
9793 if line_bytes
9794 .by_ref()
9795 .take(comment_prefix.len())
9796 .eq(comment_prefix.bytes())
9797 {
9798 // Include any whitespace that matches the comment prefix.
9799 let matching_whitespace_len = line_bytes
9800 .zip(comment_prefix_whitespace.bytes())
9801 .take_while(|(a, b)| a == b)
9802 .count() as u32;
9803 let end = Point::new(
9804 start.row,
9805 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9806 );
9807 start..end
9808 } else {
9809 start..start
9810 }
9811 }
9812
9813 fn comment_suffix_range(
9814 snapshot: &MultiBufferSnapshot,
9815 row: MultiBufferRow,
9816 comment_suffix: &str,
9817 comment_suffix_has_leading_space: bool,
9818 ) -> Range<Point> {
9819 let end = Point::new(row.0, snapshot.line_len(row));
9820 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9821
9822 let mut line_end_bytes = snapshot
9823 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9824 .flatten()
9825 .copied();
9826
9827 let leading_space_len = if suffix_start_column > 0
9828 && line_end_bytes.next() == Some(b' ')
9829 && comment_suffix_has_leading_space
9830 {
9831 1
9832 } else {
9833 0
9834 };
9835
9836 // If this line currently begins with the line comment prefix, then record
9837 // the range containing the prefix.
9838 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9839 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9840 start..end
9841 } else {
9842 end..end
9843 }
9844 }
9845
9846 // TODO: Handle selections that cross excerpts
9847 for selection in &mut selections {
9848 let start_column = snapshot
9849 .indent_size_for_line(MultiBufferRow(selection.start.row))
9850 .len;
9851 let language = if let Some(language) =
9852 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9853 {
9854 language
9855 } else {
9856 continue;
9857 };
9858
9859 selection_edit_ranges.clear();
9860
9861 // If multiple selections contain a given row, avoid processing that
9862 // row more than once.
9863 let mut start_row = MultiBufferRow(selection.start.row);
9864 if last_toggled_row == Some(start_row) {
9865 start_row = start_row.next_row();
9866 }
9867 let end_row =
9868 if selection.end.row > selection.start.row && selection.end.column == 0 {
9869 MultiBufferRow(selection.end.row - 1)
9870 } else {
9871 MultiBufferRow(selection.end.row)
9872 };
9873 last_toggled_row = Some(end_row);
9874
9875 if start_row > end_row {
9876 continue;
9877 }
9878
9879 // If the language has line comments, toggle those.
9880 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9881
9882 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9883 if ignore_indent {
9884 full_comment_prefixes = full_comment_prefixes
9885 .into_iter()
9886 .map(|s| Arc::from(s.trim_end()))
9887 .collect();
9888 }
9889
9890 if !full_comment_prefixes.is_empty() {
9891 let first_prefix = full_comment_prefixes
9892 .first()
9893 .expect("prefixes is non-empty");
9894 let prefix_trimmed_lengths = full_comment_prefixes
9895 .iter()
9896 .map(|p| p.trim_end_matches(' ').len())
9897 .collect::<SmallVec<[usize; 4]>>();
9898
9899 let mut all_selection_lines_are_comments = true;
9900
9901 for row in start_row.0..=end_row.0 {
9902 let row = MultiBufferRow(row);
9903 if start_row < end_row && snapshot.is_line_blank(row) {
9904 continue;
9905 }
9906
9907 let prefix_range = full_comment_prefixes
9908 .iter()
9909 .zip(prefix_trimmed_lengths.iter().copied())
9910 .map(|(prefix, trimmed_prefix_len)| {
9911 comment_prefix_range(
9912 snapshot.deref(),
9913 row,
9914 &prefix[..trimmed_prefix_len],
9915 &prefix[trimmed_prefix_len..],
9916 ignore_indent,
9917 )
9918 })
9919 .max_by_key(|range| range.end.column - range.start.column)
9920 .expect("prefixes is non-empty");
9921
9922 if prefix_range.is_empty() {
9923 all_selection_lines_are_comments = false;
9924 }
9925
9926 selection_edit_ranges.push(prefix_range);
9927 }
9928
9929 if all_selection_lines_are_comments {
9930 edits.extend(
9931 selection_edit_ranges
9932 .iter()
9933 .cloned()
9934 .map(|range| (range, empty_str.clone())),
9935 );
9936 } else {
9937 let min_column = selection_edit_ranges
9938 .iter()
9939 .map(|range| range.start.column)
9940 .min()
9941 .unwrap_or(0);
9942 edits.extend(selection_edit_ranges.iter().map(|range| {
9943 let position = Point::new(range.start.row, min_column);
9944 (position..position, first_prefix.clone())
9945 }));
9946 }
9947 } else if let Some((full_comment_prefix, comment_suffix)) =
9948 language.block_comment_delimiters()
9949 {
9950 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9951 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9952 let prefix_range = comment_prefix_range(
9953 snapshot.deref(),
9954 start_row,
9955 comment_prefix,
9956 comment_prefix_whitespace,
9957 ignore_indent,
9958 );
9959 let suffix_range = comment_suffix_range(
9960 snapshot.deref(),
9961 end_row,
9962 comment_suffix.trim_start_matches(' '),
9963 comment_suffix.starts_with(' '),
9964 );
9965
9966 if prefix_range.is_empty() || suffix_range.is_empty() {
9967 edits.push((
9968 prefix_range.start..prefix_range.start,
9969 full_comment_prefix.clone(),
9970 ));
9971 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9972 suffixes_inserted.push((end_row, comment_suffix.len()));
9973 } else {
9974 edits.push((prefix_range, empty_str.clone()));
9975 edits.push((suffix_range, empty_str.clone()));
9976 }
9977 } else {
9978 continue;
9979 }
9980 }
9981
9982 drop(snapshot);
9983 this.buffer.update(cx, |buffer, cx| {
9984 buffer.edit(edits, None, cx);
9985 });
9986
9987 // Adjust selections so that they end before any comment suffixes that
9988 // were inserted.
9989 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9990 let mut selections = this.selections.all::<Point>(cx);
9991 let snapshot = this.buffer.read(cx).read(cx);
9992 for selection in &mut selections {
9993 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9994 match row.cmp(&MultiBufferRow(selection.end.row)) {
9995 Ordering::Less => {
9996 suffixes_inserted.next();
9997 continue;
9998 }
9999 Ordering::Greater => break,
10000 Ordering::Equal => {
10001 if selection.end.column == snapshot.line_len(row) {
10002 if selection.is_empty() {
10003 selection.start.column -= suffix_len as u32;
10004 }
10005 selection.end.column -= suffix_len as u32;
10006 }
10007 break;
10008 }
10009 }
10010 }
10011 }
10012
10013 drop(snapshot);
10014 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10015 s.select(selections)
10016 });
10017
10018 let selections = this.selections.all::<Point>(cx);
10019 let selections_on_single_row = selections.windows(2).all(|selections| {
10020 selections[0].start.row == selections[1].start.row
10021 && selections[0].end.row == selections[1].end.row
10022 && selections[0].start.row == selections[0].end.row
10023 });
10024 let selections_selecting = selections
10025 .iter()
10026 .any(|selection| selection.start != selection.end);
10027 let advance_downwards = action.advance_downwards
10028 && selections_on_single_row
10029 && !selections_selecting
10030 && !matches!(this.mode, EditorMode::SingleLine { .. });
10031
10032 if advance_downwards {
10033 let snapshot = this.buffer.read(cx).snapshot(cx);
10034
10035 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10036 s.move_cursors_with(|display_snapshot, display_point, _| {
10037 let mut point = display_point.to_point(display_snapshot);
10038 point.row += 1;
10039 point = snapshot.clip_point(point, Bias::Left);
10040 let display_point = point.to_display_point(display_snapshot);
10041 let goal = SelectionGoal::HorizontalPosition(
10042 display_snapshot
10043 .x_for_display_point(display_point, text_layout_details)
10044 .into(),
10045 );
10046 (display_point, goal)
10047 })
10048 });
10049 }
10050 });
10051 }
10052
10053 pub fn select_enclosing_symbol(
10054 &mut self,
10055 _: &SelectEnclosingSymbol,
10056 window: &mut Window,
10057 cx: &mut Context<Self>,
10058 ) {
10059 let buffer = self.buffer.read(cx).snapshot(cx);
10060 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10061
10062 fn update_selection(
10063 selection: &Selection<usize>,
10064 buffer_snap: &MultiBufferSnapshot,
10065 ) -> Option<Selection<usize>> {
10066 let cursor = selection.head();
10067 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10068 for symbol in symbols.iter().rev() {
10069 let start = symbol.range.start.to_offset(buffer_snap);
10070 let end = symbol.range.end.to_offset(buffer_snap);
10071 let new_range = start..end;
10072 if start < selection.start || end > selection.end {
10073 return Some(Selection {
10074 id: selection.id,
10075 start: new_range.start,
10076 end: new_range.end,
10077 goal: SelectionGoal::None,
10078 reversed: selection.reversed,
10079 });
10080 }
10081 }
10082 None
10083 }
10084
10085 let mut selected_larger_symbol = false;
10086 let new_selections = old_selections
10087 .iter()
10088 .map(|selection| match update_selection(selection, &buffer) {
10089 Some(new_selection) => {
10090 if new_selection.range() != selection.range() {
10091 selected_larger_symbol = true;
10092 }
10093 new_selection
10094 }
10095 None => selection.clone(),
10096 })
10097 .collect::<Vec<_>>();
10098
10099 if selected_larger_symbol {
10100 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10101 s.select(new_selections);
10102 });
10103 }
10104 }
10105
10106 pub fn select_larger_syntax_node(
10107 &mut self,
10108 _: &SelectLargerSyntaxNode,
10109 window: &mut Window,
10110 cx: &mut Context<Self>,
10111 ) {
10112 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10113 let buffer = self.buffer.read(cx).snapshot(cx);
10114 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10115
10116 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10117 let mut selected_larger_node = false;
10118 let new_selections = old_selections
10119 .iter()
10120 .map(|selection| {
10121 let old_range = selection.start..selection.end;
10122 let mut new_range = old_range.clone();
10123 let mut new_node = None;
10124 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10125 {
10126 new_node = Some(node);
10127 new_range = containing_range;
10128 if !display_map.intersects_fold(new_range.start)
10129 && !display_map.intersects_fold(new_range.end)
10130 {
10131 break;
10132 }
10133 }
10134
10135 if let Some(node) = new_node {
10136 // Log the ancestor, to support using this action as a way to explore TreeSitter
10137 // nodes. Parent and grandparent are also logged because this operation will not
10138 // visit nodes that have the same range as their parent.
10139 log::info!("Node: {node:?}");
10140 let parent = node.parent();
10141 log::info!("Parent: {parent:?}");
10142 let grandparent = parent.and_then(|x| x.parent());
10143 log::info!("Grandparent: {grandparent:?}");
10144 }
10145
10146 selected_larger_node |= new_range != old_range;
10147 Selection {
10148 id: selection.id,
10149 start: new_range.start,
10150 end: new_range.end,
10151 goal: SelectionGoal::None,
10152 reversed: selection.reversed,
10153 }
10154 })
10155 .collect::<Vec<_>>();
10156
10157 if selected_larger_node {
10158 stack.push(old_selections);
10159 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10160 s.select(new_selections);
10161 });
10162 }
10163 self.select_larger_syntax_node_stack = stack;
10164 }
10165
10166 pub fn select_smaller_syntax_node(
10167 &mut self,
10168 _: &SelectSmallerSyntaxNode,
10169 window: &mut Window,
10170 cx: &mut Context<Self>,
10171 ) {
10172 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10173 if let Some(selections) = stack.pop() {
10174 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10175 s.select(selections.to_vec());
10176 });
10177 }
10178 self.select_larger_syntax_node_stack = stack;
10179 }
10180
10181 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10182 if !EditorSettings::get_global(cx).gutter.runnables {
10183 self.clear_tasks();
10184 return Task::ready(());
10185 }
10186 let project = self.project.as_ref().map(Entity::downgrade);
10187 cx.spawn_in(window, |this, mut cx| async move {
10188 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10189 let Some(project) = project.and_then(|p| p.upgrade()) else {
10190 return;
10191 };
10192 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10193 this.display_map.update(cx, |map, cx| map.snapshot(cx))
10194 }) else {
10195 return;
10196 };
10197
10198 let hide_runnables = project
10199 .update(&mut cx, |project, cx| {
10200 // Do not display any test indicators in non-dev server remote projects.
10201 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10202 })
10203 .unwrap_or(true);
10204 if hide_runnables {
10205 return;
10206 }
10207 let new_rows =
10208 cx.background_executor()
10209 .spawn({
10210 let snapshot = display_snapshot.clone();
10211 async move {
10212 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10213 }
10214 })
10215 .await;
10216
10217 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10218 this.update(&mut cx, |this, _| {
10219 this.clear_tasks();
10220 for (key, value) in rows {
10221 this.insert_tasks(key, value);
10222 }
10223 })
10224 .ok();
10225 })
10226 }
10227 fn fetch_runnable_ranges(
10228 snapshot: &DisplaySnapshot,
10229 range: Range<Anchor>,
10230 ) -> Vec<language::RunnableRange> {
10231 snapshot.buffer_snapshot.runnable_ranges(range).collect()
10232 }
10233
10234 fn runnable_rows(
10235 project: Entity<Project>,
10236 snapshot: DisplaySnapshot,
10237 runnable_ranges: Vec<RunnableRange>,
10238 mut cx: AsyncWindowContext,
10239 ) -> Vec<((BufferId, u32), RunnableTasks)> {
10240 runnable_ranges
10241 .into_iter()
10242 .filter_map(|mut runnable| {
10243 let tasks = cx
10244 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10245 .ok()?;
10246 if tasks.is_empty() {
10247 return None;
10248 }
10249
10250 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10251
10252 let row = snapshot
10253 .buffer_snapshot
10254 .buffer_line_for_row(MultiBufferRow(point.row))?
10255 .1
10256 .start
10257 .row;
10258
10259 let context_range =
10260 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10261 Some((
10262 (runnable.buffer_id, row),
10263 RunnableTasks {
10264 templates: tasks,
10265 offset: MultiBufferOffset(runnable.run_range.start),
10266 context_range,
10267 column: point.column,
10268 extra_variables: runnable.extra_captures,
10269 },
10270 ))
10271 })
10272 .collect()
10273 }
10274
10275 fn templates_with_tags(
10276 project: &Entity<Project>,
10277 runnable: &mut Runnable,
10278 cx: &mut App,
10279 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10280 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10281 let (worktree_id, file) = project
10282 .buffer_for_id(runnable.buffer, cx)
10283 .and_then(|buffer| buffer.read(cx).file())
10284 .map(|file| (file.worktree_id(cx), file.clone()))
10285 .unzip();
10286
10287 (
10288 project.task_store().read(cx).task_inventory().cloned(),
10289 worktree_id,
10290 file,
10291 )
10292 });
10293
10294 let tags = mem::take(&mut runnable.tags);
10295 let mut tags: Vec<_> = tags
10296 .into_iter()
10297 .flat_map(|tag| {
10298 let tag = tag.0.clone();
10299 inventory
10300 .as_ref()
10301 .into_iter()
10302 .flat_map(|inventory| {
10303 inventory.read(cx).list_tasks(
10304 file.clone(),
10305 Some(runnable.language.clone()),
10306 worktree_id,
10307 cx,
10308 )
10309 })
10310 .filter(move |(_, template)| {
10311 template.tags.iter().any(|source_tag| source_tag == &tag)
10312 })
10313 })
10314 .sorted_by_key(|(kind, _)| kind.to_owned())
10315 .collect();
10316 if let Some((leading_tag_source, _)) = tags.first() {
10317 // Strongest source wins; if we have worktree tag binding, prefer that to
10318 // global and language bindings;
10319 // if we have a global binding, prefer that to language binding.
10320 let first_mismatch = tags
10321 .iter()
10322 .position(|(tag_source, _)| tag_source != leading_tag_source);
10323 if let Some(index) = first_mismatch {
10324 tags.truncate(index);
10325 }
10326 }
10327
10328 tags
10329 }
10330
10331 pub fn move_to_enclosing_bracket(
10332 &mut self,
10333 _: &MoveToEnclosingBracket,
10334 window: &mut Window,
10335 cx: &mut Context<Self>,
10336 ) {
10337 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10338 s.move_offsets_with(|snapshot, selection| {
10339 let Some(enclosing_bracket_ranges) =
10340 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10341 else {
10342 return;
10343 };
10344
10345 let mut best_length = usize::MAX;
10346 let mut best_inside = false;
10347 let mut best_in_bracket_range = false;
10348 let mut best_destination = None;
10349 for (open, close) in enclosing_bracket_ranges {
10350 let close = close.to_inclusive();
10351 let length = close.end() - open.start;
10352 let inside = selection.start >= open.end && selection.end <= *close.start();
10353 let in_bracket_range = open.to_inclusive().contains(&selection.head())
10354 || close.contains(&selection.head());
10355
10356 // If best is next to a bracket and current isn't, skip
10357 if !in_bracket_range && best_in_bracket_range {
10358 continue;
10359 }
10360
10361 // Prefer smaller lengths unless best is inside and current isn't
10362 if length > best_length && (best_inside || !inside) {
10363 continue;
10364 }
10365
10366 best_length = length;
10367 best_inside = inside;
10368 best_in_bracket_range = in_bracket_range;
10369 best_destination = Some(
10370 if close.contains(&selection.start) && close.contains(&selection.end) {
10371 if inside {
10372 open.end
10373 } else {
10374 open.start
10375 }
10376 } else if inside {
10377 *close.start()
10378 } else {
10379 *close.end()
10380 },
10381 );
10382 }
10383
10384 if let Some(destination) = best_destination {
10385 selection.collapse_to(destination, SelectionGoal::None);
10386 }
10387 })
10388 });
10389 }
10390
10391 pub fn undo_selection(
10392 &mut self,
10393 _: &UndoSelection,
10394 window: &mut Window,
10395 cx: &mut Context<Self>,
10396 ) {
10397 self.end_selection(window, cx);
10398 self.selection_history.mode = SelectionHistoryMode::Undoing;
10399 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10400 self.change_selections(None, window, cx, |s| {
10401 s.select_anchors(entry.selections.to_vec())
10402 });
10403 self.select_next_state = entry.select_next_state;
10404 self.select_prev_state = entry.select_prev_state;
10405 self.add_selections_state = entry.add_selections_state;
10406 self.request_autoscroll(Autoscroll::newest(), cx);
10407 }
10408 self.selection_history.mode = SelectionHistoryMode::Normal;
10409 }
10410
10411 pub fn redo_selection(
10412 &mut self,
10413 _: &RedoSelection,
10414 window: &mut Window,
10415 cx: &mut Context<Self>,
10416 ) {
10417 self.end_selection(window, cx);
10418 self.selection_history.mode = SelectionHistoryMode::Redoing;
10419 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10420 self.change_selections(None, window, cx, |s| {
10421 s.select_anchors(entry.selections.to_vec())
10422 });
10423 self.select_next_state = entry.select_next_state;
10424 self.select_prev_state = entry.select_prev_state;
10425 self.add_selections_state = entry.add_selections_state;
10426 self.request_autoscroll(Autoscroll::newest(), cx);
10427 }
10428 self.selection_history.mode = SelectionHistoryMode::Normal;
10429 }
10430
10431 pub fn expand_excerpts(
10432 &mut self,
10433 action: &ExpandExcerpts,
10434 _: &mut Window,
10435 cx: &mut Context<Self>,
10436 ) {
10437 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10438 }
10439
10440 pub fn expand_excerpts_down(
10441 &mut self,
10442 action: &ExpandExcerptsDown,
10443 _: &mut Window,
10444 cx: &mut Context<Self>,
10445 ) {
10446 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10447 }
10448
10449 pub fn expand_excerpts_up(
10450 &mut self,
10451 action: &ExpandExcerptsUp,
10452 _: &mut Window,
10453 cx: &mut Context<Self>,
10454 ) {
10455 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10456 }
10457
10458 pub fn expand_excerpts_for_direction(
10459 &mut self,
10460 lines: u32,
10461 direction: ExpandExcerptDirection,
10462
10463 cx: &mut Context<Self>,
10464 ) {
10465 let selections = self.selections.disjoint_anchors();
10466
10467 let lines = if lines == 0 {
10468 EditorSettings::get_global(cx).expand_excerpt_lines
10469 } else {
10470 lines
10471 };
10472
10473 self.buffer.update(cx, |buffer, cx| {
10474 let snapshot = buffer.snapshot(cx);
10475 let mut excerpt_ids = selections
10476 .iter()
10477 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10478 .collect::<Vec<_>>();
10479 excerpt_ids.sort();
10480 excerpt_ids.dedup();
10481 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10482 })
10483 }
10484
10485 pub fn expand_excerpt(
10486 &mut self,
10487 excerpt: ExcerptId,
10488 direction: ExpandExcerptDirection,
10489 cx: &mut Context<Self>,
10490 ) {
10491 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10492 self.buffer.update(cx, |buffer, cx| {
10493 buffer.expand_excerpts([excerpt], lines, direction, cx)
10494 })
10495 }
10496
10497 pub fn go_to_singleton_buffer_point(
10498 &mut self,
10499 point: Point,
10500 window: &mut Window,
10501 cx: &mut Context<Self>,
10502 ) {
10503 self.go_to_singleton_buffer_range(point..point, window, cx);
10504 }
10505
10506 pub fn go_to_singleton_buffer_range(
10507 &mut self,
10508 range: Range<Point>,
10509 window: &mut Window,
10510 cx: &mut Context<Self>,
10511 ) {
10512 let multibuffer = self.buffer().read(cx);
10513 let Some(buffer) = multibuffer.as_singleton() else {
10514 return;
10515 };
10516 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10517 return;
10518 };
10519 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10520 return;
10521 };
10522 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10523 s.select_anchor_ranges([start..end])
10524 });
10525 }
10526
10527 fn go_to_diagnostic(
10528 &mut self,
10529 _: &GoToDiagnostic,
10530 window: &mut Window,
10531 cx: &mut Context<Self>,
10532 ) {
10533 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10534 }
10535
10536 fn go_to_prev_diagnostic(
10537 &mut self,
10538 _: &GoToPrevDiagnostic,
10539 window: &mut Window,
10540 cx: &mut Context<Self>,
10541 ) {
10542 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10543 }
10544
10545 pub fn go_to_diagnostic_impl(
10546 &mut self,
10547 direction: Direction,
10548 window: &mut Window,
10549 cx: &mut Context<Self>,
10550 ) {
10551 let buffer = self.buffer.read(cx).snapshot(cx);
10552 let selection = self.selections.newest::<usize>(cx);
10553
10554 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10555 if direction == Direction::Next {
10556 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10557 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10558 return;
10559 };
10560 self.activate_diagnostics(
10561 buffer_id,
10562 popover.local_diagnostic.diagnostic.group_id,
10563 window,
10564 cx,
10565 );
10566 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10567 let primary_range_start = active_diagnostics.primary_range.start;
10568 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10569 let mut new_selection = s.newest_anchor().clone();
10570 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10571 s.select_anchors(vec![new_selection.clone()]);
10572 });
10573 self.refresh_inline_completion(false, true, window, cx);
10574 }
10575 return;
10576 }
10577 }
10578
10579 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10580 active_diagnostics
10581 .primary_range
10582 .to_offset(&buffer)
10583 .to_inclusive()
10584 });
10585 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10586 if active_primary_range.contains(&selection.head()) {
10587 *active_primary_range.start()
10588 } else {
10589 selection.head()
10590 }
10591 } else {
10592 selection.head()
10593 };
10594 let snapshot = self.snapshot(window, cx);
10595 loop {
10596 let mut diagnostics;
10597 if direction == Direction::Prev {
10598 diagnostics = buffer
10599 .diagnostics_in_range::<usize>(0..search_start)
10600 .collect::<Vec<_>>();
10601 diagnostics.reverse();
10602 } else {
10603 diagnostics = buffer
10604 .diagnostics_in_range::<usize>(search_start..buffer.len())
10605 .collect::<Vec<_>>();
10606 };
10607 let group = diagnostics
10608 .into_iter()
10609 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10610 // relies on diagnostics_in_range to return diagnostics with the same starting range to
10611 // be sorted in a stable way
10612 // skip until we are at current active diagnostic, if it exists
10613 .skip_while(|entry| {
10614 let is_in_range = match direction {
10615 Direction::Prev => entry.range.end > search_start,
10616 Direction::Next => entry.range.start < search_start,
10617 };
10618 is_in_range
10619 && self
10620 .active_diagnostics
10621 .as_ref()
10622 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
10623 })
10624 .find_map(|entry| {
10625 if entry.diagnostic.is_primary
10626 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
10627 && entry.range.start != entry.range.end
10628 // if we match with the active diagnostic, skip it
10629 && Some(entry.diagnostic.group_id)
10630 != self.active_diagnostics.as_ref().map(|d| d.group_id)
10631 {
10632 Some((entry.range, entry.diagnostic.group_id))
10633 } else {
10634 None
10635 }
10636 });
10637
10638 if let Some((primary_range, group_id)) = group {
10639 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10640 return;
10641 };
10642 self.activate_diagnostics(buffer_id, group_id, window, cx);
10643 if self.active_diagnostics.is_some() {
10644 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10645 s.select(vec![Selection {
10646 id: selection.id,
10647 start: primary_range.start,
10648 end: primary_range.start,
10649 reversed: false,
10650 goal: SelectionGoal::None,
10651 }]);
10652 });
10653 self.refresh_inline_completion(false, true, window, cx);
10654 }
10655 break;
10656 } else {
10657 // Cycle around to the start of the buffer, potentially moving back to the start of
10658 // the currently active diagnostic.
10659 active_primary_range.take();
10660 if direction == Direction::Prev {
10661 if search_start == buffer.len() {
10662 break;
10663 } else {
10664 search_start = buffer.len();
10665 }
10666 } else if search_start == 0 {
10667 break;
10668 } else {
10669 search_start = 0;
10670 }
10671 }
10672 }
10673 }
10674
10675 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10676 let snapshot = self.snapshot(window, cx);
10677 let selection = self.selections.newest::<Point>(cx);
10678 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10679 }
10680
10681 fn go_to_hunk_after_position(
10682 &mut self,
10683 snapshot: &EditorSnapshot,
10684 position: Point,
10685 window: &mut Window,
10686 cx: &mut Context<Editor>,
10687 ) -> Option<MultiBufferDiffHunk> {
10688 let mut hunk = snapshot
10689 .buffer_snapshot
10690 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10691 .find(|hunk| hunk.row_range.start.0 > position.row);
10692 if hunk.is_none() {
10693 hunk = snapshot
10694 .buffer_snapshot
10695 .diff_hunks_in_range(Point::zero()..position)
10696 .find(|hunk| hunk.row_range.end.0 < position.row)
10697 }
10698 if let Some(hunk) = &hunk {
10699 let destination = Point::new(hunk.row_range.start.0, 0);
10700 self.unfold_ranges(&[destination..destination], false, false, cx);
10701 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10702 s.select_ranges(vec![destination..destination]);
10703 });
10704 }
10705
10706 hunk
10707 }
10708
10709 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10710 let snapshot = self.snapshot(window, cx);
10711 let selection = self.selections.newest::<Point>(cx);
10712 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10713 }
10714
10715 fn go_to_hunk_before_position(
10716 &mut self,
10717 snapshot: &EditorSnapshot,
10718 position: Point,
10719 window: &mut Window,
10720 cx: &mut Context<Editor>,
10721 ) -> Option<MultiBufferDiffHunk> {
10722 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10723 if hunk.is_none() {
10724 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10725 }
10726 if let Some(hunk) = &hunk {
10727 let destination = Point::new(hunk.row_range.start.0, 0);
10728 self.unfold_ranges(&[destination..destination], false, false, cx);
10729 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10730 s.select_ranges(vec![destination..destination]);
10731 });
10732 }
10733
10734 hunk
10735 }
10736
10737 pub fn go_to_definition(
10738 &mut self,
10739 _: &GoToDefinition,
10740 window: &mut Window,
10741 cx: &mut Context<Self>,
10742 ) -> Task<Result<Navigated>> {
10743 let definition =
10744 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10745 cx.spawn_in(window, |editor, mut cx| async move {
10746 if definition.await? == Navigated::Yes {
10747 return Ok(Navigated::Yes);
10748 }
10749 match editor.update_in(&mut cx, |editor, window, cx| {
10750 editor.find_all_references(&FindAllReferences, window, cx)
10751 })? {
10752 Some(references) => references.await,
10753 None => Ok(Navigated::No),
10754 }
10755 })
10756 }
10757
10758 pub fn go_to_declaration(
10759 &mut self,
10760 _: &GoToDeclaration,
10761 window: &mut Window,
10762 cx: &mut Context<Self>,
10763 ) -> Task<Result<Navigated>> {
10764 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10765 }
10766
10767 pub fn go_to_declaration_split(
10768 &mut self,
10769 _: &GoToDeclaration,
10770 window: &mut Window,
10771 cx: &mut Context<Self>,
10772 ) -> Task<Result<Navigated>> {
10773 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10774 }
10775
10776 pub fn go_to_implementation(
10777 &mut self,
10778 _: &GoToImplementation,
10779 window: &mut Window,
10780 cx: &mut Context<Self>,
10781 ) -> Task<Result<Navigated>> {
10782 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10783 }
10784
10785 pub fn go_to_implementation_split(
10786 &mut self,
10787 _: &GoToImplementationSplit,
10788 window: &mut Window,
10789 cx: &mut Context<Self>,
10790 ) -> Task<Result<Navigated>> {
10791 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10792 }
10793
10794 pub fn go_to_type_definition(
10795 &mut self,
10796 _: &GoToTypeDefinition,
10797 window: &mut Window,
10798 cx: &mut Context<Self>,
10799 ) -> Task<Result<Navigated>> {
10800 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10801 }
10802
10803 pub fn go_to_definition_split(
10804 &mut self,
10805 _: &GoToDefinitionSplit,
10806 window: &mut Window,
10807 cx: &mut Context<Self>,
10808 ) -> Task<Result<Navigated>> {
10809 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10810 }
10811
10812 pub fn go_to_type_definition_split(
10813 &mut self,
10814 _: &GoToTypeDefinitionSplit,
10815 window: &mut Window,
10816 cx: &mut Context<Self>,
10817 ) -> Task<Result<Navigated>> {
10818 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10819 }
10820
10821 fn go_to_definition_of_kind(
10822 &mut self,
10823 kind: GotoDefinitionKind,
10824 split: bool,
10825 window: &mut Window,
10826 cx: &mut Context<Self>,
10827 ) -> Task<Result<Navigated>> {
10828 let Some(provider) = self.semantics_provider.clone() else {
10829 return Task::ready(Ok(Navigated::No));
10830 };
10831 let head = self.selections.newest::<usize>(cx).head();
10832 let buffer = self.buffer.read(cx);
10833 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10834 text_anchor
10835 } else {
10836 return Task::ready(Ok(Navigated::No));
10837 };
10838
10839 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10840 return Task::ready(Ok(Navigated::No));
10841 };
10842
10843 cx.spawn_in(window, |editor, mut cx| async move {
10844 let definitions = definitions.await?;
10845 let navigated = editor
10846 .update_in(&mut cx, |editor, window, cx| {
10847 editor.navigate_to_hover_links(
10848 Some(kind),
10849 definitions
10850 .into_iter()
10851 .filter(|location| {
10852 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10853 })
10854 .map(HoverLink::Text)
10855 .collect::<Vec<_>>(),
10856 split,
10857 window,
10858 cx,
10859 )
10860 })?
10861 .await?;
10862 anyhow::Ok(navigated)
10863 })
10864 }
10865
10866 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10867 let selection = self.selections.newest_anchor();
10868 let head = selection.head();
10869 let tail = selection.tail();
10870
10871 let Some((buffer, start_position)) =
10872 self.buffer.read(cx).text_anchor_for_position(head, cx)
10873 else {
10874 return;
10875 };
10876
10877 let end_position = if head != tail {
10878 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10879 return;
10880 };
10881 Some(pos)
10882 } else {
10883 None
10884 };
10885
10886 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10887 let url = if let Some(end_pos) = end_position {
10888 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10889 } else {
10890 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10891 };
10892
10893 if let Some(url) = url {
10894 editor.update(&mut cx, |_, cx| {
10895 cx.open_url(&url);
10896 })
10897 } else {
10898 Ok(())
10899 }
10900 });
10901
10902 url_finder.detach();
10903 }
10904
10905 pub fn open_selected_filename(
10906 &mut self,
10907 _: &OpenSelectedFilename,
10908 window: &mut Window,
10909 cx: &mut Context<Self>,
10910 ) {
10911 let Some(workspace) = self.workspace() else {
10912 return;
10913 };
10914
10915 let position = self.selections.newest_anchor().head();
10916
10917 let Some((buffer, buffer_position)) =
10918 self.buffer.read(cx).text_anchor_for_position(position, cx)
10919 else {
10920 return;
10921 };
10922
10923 let project = self.project.clone();
10924
10925 cx.spawn_in(window, |_, mut cx| async move {
10926 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10927
10928 if let Some((_, path)) = result {
10929 workspace
10930 .update_in(&mut cx, |workspace, window, cx| {
10931 workspace.open_resolved_path(path, window, cx)
10932 })?
10933 .await?;
10934 }
10935 anyhow::Ok(())
10936 })
10937 .detach();
10938 }
10939
10940 pub(crate) fn navigate_to_hover_links(
10941 &mut self,
10942 kind: Option<GotoDefinitionKind>,
10943 mut definitions: Vec<HoverLink>,
10944 split: bool,
10945 window: &mut Window,
10946 cx: &mut Context<Editor>,
10947 ) -> Task<Result<Navigated>> {
10948 // If there is one definition, just open it directly
10949 if definitions.len() == 1 {
10950 let definition = definitions.pop().unwrap();
10951
10952 enum TargetTaskResult {
10953 Location(Option<Location>),
10954 AlreadyNavigated,
10955 }
10956
10957 let target_task = match definition {
10958 HoverLink::Text(link) => {
10959 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10960 }
10961 HoverLink::InlayHint(lsp_location, server_id) => {
10962 let computation =
10963 self.compute_target_location(lsp_location, server_id, window, cx);
10964 cx.background_executor().spawn(async move {
10965 let location = computation.await?;
10966 Ok(TargetTaskResult::Location(location))
10967 })
10968 }
10969 HoverLink::Url(url) => {
10970 cx.open_url(&url);
10971 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10972 }
10973 HoverLink::File(path) => {
10974 if let Some(workspace) = self.workspace() {
10975 cx.spawn_in(window, |_, mut cx| async move {
10976 workspace
10977 .update_in(&mut cx, |workspace, window, cx| {
10978 workspace.open_resolved_path(path, window, cx)
10979 })?
10980 .await
10981 .map(|_| TargetTaskResult::AlreadyNavigated)
10982 })
10983 } else {
10984 Task::ready(Ok(TargetTaskResult::Location(None)))
10985 }
10986 }
10987 };
10988 cx.spawn_in(window, |editor, mut cx| async move {
10989 let target = match target_task.await.context("target resolution task")? {
10990 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10991 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10992 TargetTaskResult::Location(Some(target)) => target,
10993 };
10994
10995 editor.update_in(&mut cx, |editor, window, cx| {
10996 let Some(workspace) = editor.workspace() else {
10997 return Navigated::No;
10998 };
10999 let pane = workspace.read(cx).active_pane().clone();
11000
11001 let range = target.range.to_point(target.buffer.read(cx));
11002 let range = editor.range_for_match(&range);
11003 let range = collapse_multiline_range(range);
11004
11005 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
11006 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11007 } else {
11008 window.defer(cx, move |window, cx| {
11009 let target_editor: Entity<Self> =
11010 workspace.update(cx, |workspace, cx| {
11011 let pane = if split {
11012 workspace.adjacent_pane(window, cx)
11013 } else {
11014 workspace.active_pane().clone()
11015 };
11016
11017 workspace.open_project_item(
11018 pane,
11019 target.buffer.clone(),
11020 true,
11021 true,
11022 window,
11023 cx,
11024 )
11025 });
11026 target_editor.update(cx, |target_editor, cx| {
11027 // When selecting a definition in a different buffer, disable the nav history
11028 // to avoid creating a history entry at the previous cursor location.
11029 pane.update(cx, |pane, _| pane.disable_history());
11030 target_editor.go_to_singleton_buffer_range(range, window, cx);
11031 pane.update(cx, |pane, _| pane.enable_history());
11032 });
11033 });
11034 }
11035 Navigated::Yes
11036 })
11037 })
11038 } else if !definitions.is_empty() {
11039 cx.spawn_in(window, |editor, mut cx| async move {
11040 let (title, location_tasks, workspace) = editor
11041 .update_in(&mut cx, |editor, window, cx| {
11042 let tab_kind = match kind {
11043 Some(GotoDefinitionKind::Implementation) => "Implementations",
11044 _ => "Definitions",
11045 };
11046 let title = definitions
11047 .iter()
11048 .find_map(|definition| match definition {
11049 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11050 let buffer = origin.buffer.read(cx);
11051 format!(
11052 "{} for {}",
11053 tab_kind,
11054 buffer
11055 .text_for_range(origin.range.clone())
11056 .collect::<String>()
11057 )
11058 }),
11059 HoverLink::InlayHint(_, _) => None,
11060 HoverLink::Url(_) => None,
11061 HoverLink::File(_) => None,
11062 })
11063 .unwrap_or(tab_kind.to_string());
11064 let location_tasks = definitions
11065 .into_iter()
11066 .map(|definition| match definition {
11067 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11068 HoverLink::InlayHint(lsp_location, server_id) => editor
11069 .compute_target_location(lsp_location, server_id, window, cx),
11070 HoverLink::Url(_) => Task::ready(Ok(None)),
11071 HoverLink::File(_) => Task::ready(Ok(None)),
11072 })
11073 .collect::<Vec<_>>();
11074 (title, location_tasks, editor.workspace().clone())
11075 })
11076 .context("location tasks preparation")?;
11077
11078 let locations = future::join_all(location_tasks)
11079 .await
11080 .into_iter()
11081 .filter_map(|location| location.transpose())
11082 .collect::<Result<_>>()
11083 .context("location tasks")?;
11084
11085 let Some(workspace) = workspace else {
11086 return Ok(Navigated::No);
11087 };
11088 let opened = workspace
11089 .update_in(&mut cx, |workspace, window, cx| {
11090 Self::open_locations_in_multibuffer(
11091 workspace,
11092 locations,
11093 title,
11094 split,
11095 MultibufferSelectionMode::First,
11096 window,
11097 cx,
11098 )
11099 })
11100 .ok();
11101
11102 anyhow::Ok(Navigated::from_bool(opened.is_some()))
11103 })
11104 } else {
11105 Task::ready(Ok(Navigated::No))
11106 }
11107 }
11108
11109 fn compute_target_location(
11110 &self,
11111 lsp_location: lsp::Location,
11112 server_id: LanguageServerId,
11113 window: &mut Window,
11114 cx: &mut Context<Self>,
11115 ) -> Task<anyhow::Result<Option<Location>>> {
11116 let Some(project) = self.project.clone() else {
11117 return Task::ready(Ok(None));
11118 };
11119
11120 cx.spawn_in(window, move |editor, mut cx| async move {
11121 let location_task = editor.update(&mut cx, |_, cx| {
11122 project.update(cx, |project, cx| {
11123 let language_server_name = project
11124 .language_server_statuses(cx)
11125 .find(|(id, _)| server_id == *id)
11126 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11127 language_server_name.map(|language_server_name| {
11128 project.open_local_buffer_via_lsp(
11129 lsp_location.uri.clone(),
11130 server_id,
11131 language_server_name,
11132 cx,
11133 )
11134 })
11135 })
11136 })?;
11137 let location = match location_task {
11138 Some(task) => Some({
11139 let target_buffer_handle = task.await.context("open local buffer")?;
11140 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11141 let target_start = target_buffer
11142 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11143 let target_end = target_buffer
11144 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11145 target_buffer.anchor_after(target_start)
11146 ..target_buffer.anchor_before(target_end)
11147 })?;
11148 Location {
11149 buffer: target_buffer_handle,
11150 range,
11151 }
11152 }),
11153 None => None,
11154 };
11155 Ok(location)
11156 })
11157 }
11158
11159 pub fn find_all_references(
11160 &mut self,
11161 _: &FindAllReferences,
11162 window: &mut Window,
11163 cx: &mut Context<Self>,
11164 ) -> Option<Task<Result<Navigated>>> {
11165 let selection = self.selections.newest::<usize>(cx);
11166 let multi_buffer = self.buffer.read(cx);
11167 let head = selection.head();
11168
11169 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11170 let head_anchor = multi_buffer_snapshot.anchor_at(
11171 head,
11172 if head < selection.tail() {
11173 Bias::Right
11174 } else {
11175 Bias::Left
11176 },
11177 );
11178
11179 match self
11180 .find_all_references_task_sources
11181 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11182 {
11183 Ok(_) => {
11184 log::info!(
11185 "Ignoring repeated FindAllReferences invocation with the position of already running task"
11186 );
11187 return None;
11188 }
11189 Err(i) => {
11190 self.find_all_references_task_sources.insert(i, head_anchor);
11191 }
11192 }
11193
11194 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11195 let workspace = self.workspace()?;
11196 let project = workspace.read(cx).project().clone();
11197 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11198 Some(cx.spawn_in(window, |editor, mut cx| async move {
11199 let _cleanup = defer({
11200 let mut cx = cx.clone();
11201 move || {
11202 let _ = editor.update(&mut cx, |editor, _| {
11203 if let Ok(i) =
11204 editor
11205 .find_all_references_task_sources
11206 .binary_search_by(|anchor| {
11207 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11208 })
11209 {
11210 editor.find_all_references_task_sources.remove(i);
11211 }
11212 });
11213 }
11214 });
11215
11216 let locations = references.await?;
11217 if locations.is_empty() {
11218 return anyhow::Ok(Navigated::No);
11219 }
11220
11221 workspace.update_in(&mut cx, |workspace, window, cx| {
11222 let title = locations
11223 .first()
11224 .as_ref()
11225 .map(|location| {
11226 let buffer = location.buffer.read(cx);
11227 format!(
11228 "References to `{}`",
11229 buffer
11230 .text_for_range(location.range.clone())
11231 .collect::<String>()
11232 )
11233 })
11234 .unwrap();
11235 Self::open_locations_in_multibuffer(
11236 workspace,
11237 locations,
11238 title,
11239 false,
11240 MultibufferSelectionMode::First,
11241 window,
11242 cx,
11243 );
11244 Navigated::Yes
11245 })
11246 }))
11247 }
11248
11249 /// Opens a multibuffer with the given project locations in it
11250 pub fn open_locations_in_multibuffer(
11251 workspace: &mut Workspace,
11252 mut locations: Vec<Location>,
11253 title: String,
11254 split: bool,
11255 multibuffer_selection_mode: MultibufferSelectionMode,
11256 window: &mut Window,
11257 cx: &mut Context<Workspace>,
11258 ) {
11259 // If there are multiple definitions, open them in a multibuffer
11260 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11261 let mut locations = locations.into_iter().peekable();
11262 let mut ranges = Vec::new();
11263 let capability = workspace.project().read(cx).capability();
11264
11265 let excerpt_buffer = cx.new(|cx| {
11266 let mut multibuffer = MultiBuffer::new(capability);
11267 while let Some(location) = locations.next() {
11268 let buffer = location.buffer.read(cx);
11269 let mut ranges_for_buffer = Vec::new();
11270 let range = location.range.to_offset(buffer);
11271 ranges_for_buffer.push(range.clone());
11272
11273 while let Some(next_location) = locations.peek() {
11274 if next_location.buffer == location.buffer {
11275 ranges_for_buffer.push(next_location.range.to_offset(buffer));
11276 locations.next();
11277 } else {
11278 break;
11279 }
11280 }
11281
11282 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11283 ranges.extend(multibuffer.push_excerpts_with_context_lines(
11284 location.buffer.clone(),
11285 ranges_for_buffer,
11286 DEFAULT_MULTIBUFFER_CONTEXT,
11287 cx,
11288 ))
11289 }
11290
11291 multibuffer.with_title(title)
11292 });
11293
11294 let editor = cx.new(|cx| {
11295 Editor::for_multibuffer(
11296 excerpt_buffer,
11297 Some(workspace.project().clone()),
11298 true,
11299 window,
11300 cx,
11301 )
11302 });
11303 editor.update(cx, |editor, cx| {
11304 match multibuffer_selection_mode {
11305 MultibufferSelectionMode::First => {
11306 if let Some(first_range) = ranges.first() {
11307 editor.change_selections(None, window, cx, |selections| {
11308 selections.clear_disjoint();
11309 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11310 });
11311 }
11312 editor.highlight_background::<Self>(
11313 &ranges,
11314 |theme| theme.editor_highlighted_line_background,
11315 cx,
11316 );
11317 }
11318 MultibufferSelectionMode::All => {
11319 editor.change_selections(None, window, cx, |selections| {
11320 selections.clear_disjoint();
11321 selections.select_anchor_ranges(ranges);
11322 });
11323 }
11324 }
11325 editor.register_buffers_with_language_servers(cx);
11326 });
11327
11328 let item = Box::new(editor);
11329 let item_id = item.item_id();
11330
11331 if split {
11332 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11333 } else {
11334 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11335 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11336 pane.close_current_preview_item(window, cx)
11337 } else {
11338 None
11339 }
11340 });
11341 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11342 }
11343 workspace.active_pane().update(cx, |pane, cx| {
11344 pane.set_preview_item_id(Some(item_id), cx);
11345 });
11346 }
11347
11348 pub fn rename(
11349 &mut self,
11350 _: &Rename,
11351 window: &mut Window,
11352 cx: &mut Context<Self>,
11353 ) -> Option<Task<Result<()>>> {
11354 use language::ToOffset as _;
11355
11356 let provider = self.semantics_provider.clone()?;
11357 let selection = self.selections.newest_anchor().clone();
11358 let (cursor_buffer, cursor_buffer_position) = self
11359 .buffer
11360 .read(cx)
11361 .text_anchor_for_position(selection.head(), cx)?;
11362 let (tail_buffer, cursor_buffer_position_end) = self
11363 .buffer
11364 .read(cx)
11365 .text_anchor_for_position(selection.tail(), cx)?;
11366 if tail_buffer != cursor_buffer {
11367 return None;
11368 }
11369
11370 let snapshot = cursor_buffer.read(cx).snapshot();
11371 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11372 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11373 let prepare_rename = provider
11374 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11375 .unwrap_or_else(|| Task::ready(Ok(None)));
11376 drop(snapshot);
11377
11378 Some(cx.spawn_in(window, |this, mut cx| async move {
11379 let rename_range = if let Some(range) = prepare_rename.await? {
11380 Some(range)
11381 } else {
11382 this.update(&mut cx, |this, cx| {
11383 let buffer = this.buffer.read(cx).snapshot(cx);
11384 let mut buffer_highlights = this
11385 .document_highlights_for_position(selection.head(), &buffer)
11386 .filter(|highlight| {
11387 highlight.start.excerpt_id == selection.head().excerpt_id
11388 && highlight.end.excerpt_id == selection.head().excerpt_id
11389 });
11390 buffer_highlights
11391 .next()
11392 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11393 })?
11394 };
11395 if let Some(rename_range) = rename_range {
11396 this.update_in(&mut cx, |this, window, cx| {
11397 let snapshot = cursor_buffer.read(cx).snapshot();
11398 let rename_buffer_range = rename_range.to_offset(&snapshot);
11399 let cursor_offset_in_rename_range =
11400 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11401 let cursor_offset_in_rename_range_end =
11402 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11403
11404 this.take_rename(false, window, cx);
11405 let buffer = this.buffer.read(cx).read(cx);
11406 let cursor_offset = selection.head().to_offset(&buffer);
11407 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11408 let rename_end = rename_start + rename_buffer_range.len();
11409 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11410 let mut old_highlight_id = None;
11411 let old_name: Arc<str> = buffer
11412 .chunks(rename_start..rename_end, true)
11413 .map(|chunk| {
11414 if old_highlight_id.is_none() {
11415 old_highlight_id = chunk.syntax_highlight_id;
11416 }
11417 chunk.text
11418 })
11419 .collect::<String>()
11420 .into();
11421
11422 drop(buffer);
11423
11424 // Position the selection in the rename editor so that it matches the current selection.
11425 this.show_local_selections = false;
11426 let rename_editor = cx.new(|cx| {
11427 let mut editor = Editor::single_line(window, cx);
11428 editor.buffer.update(cx, |buffer, cx| {
11429 buffer.edit([(0..0, old_name.clone())], None, cx)
11430 });
11431 let rename_selection_range = match cursor_offset_in_rename_range
11432 .cmp(&cursor_offset_in_rename_range_end)
11433 {
11434 Ordering::Equal => {
11435 editor.select_all(&SelectAll, window, cx);
11436 return editor;
11437 }
11438 Ordering::Less => {
11439 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11440 }
11441 Ordering::Greater => {
11442 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11443 }
11444 };
11445 if rename_selection_range.end > old_name.len() {
11446 editor.select_all(&SelectAll, window, cx);
11447 } else {
11448 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11449 s.select_ranges([rename_selection_range]);
11450 });
11451 }
11452 editor
11453 });
11454 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11455 if e == &EditorEvent::Focused {
11456 cx.emit(EditorEvent::FocusedIn)
11457 }
11458 })
11459 .detach();
11460
11461 let write_highlights =
11462 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11463 let read_highlights =
11464 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11465 let ranges = write_highlights
11466 .iter()
11467 .flat_map(|(_, ranges)| ranges.iter())
11468 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11469 .cloned()
11470 .collect();
11471
11472 this.highlight_text::<Rename>(
11473 ranges,
11474 HighlightStyle {
11475 fade_out: Some(0.6),
11476 ..Default::default()
11477 },
11478 cx,
11479 );
11480 let rename_focus_handle = rename_editor.focus_handle(cx);
11481 window.focus(&rename_focus_handle);
11482 let block_id = this.insert_blocks(
11483 [BlockProperties {
11484 style: BlockStyle::Flex,
11485 placement: BlockPlacement::Below(range.start),
11486 height: 1,
11487 render: Arc::new({
11488 let rename_editor = rename_editor.clone();
11489 move |cx: &mut BlockContext| {
11490 let mut text_style = cx.editor_style.text.clone();
11491 if let Some(highlight_style) = old_highlight_id
11492 .and_then(|h| h.style(&cx.editor_style.syntax))
11493 {
11494 text_style = text_style.highlight(highlight_style);
11495 }
11496 div()
11497 .block_mouse_down()
11498 .pl(cx.anchor_x)
11499 .child(EditorElement::new(
11500 &rename_editor,
11501 EditorStyle {
11502 background: cx.theme().system().transparent,
11503 local_player: cx.editor_style.local_player,
11504 text: text_style,
11505 scrollbar_width: cx.editor_style.scrollbar_width,
11506 syntax: cx.editor_style.syntax.clone(),
11507 status: cx.editor_style.status.clone(),
11508 inlay_hints_style: HighlightStyle {
11509 font_weight: Some(FontWeight::BOLD),
11510 ..make_inlay_hints_style(cx.app)
11511 },
11512 inline_completion_styles: make_suggestion_styles(
11513 cx.app,
11514 ),
11515 ..EditorStyle::default()
11516 },
11517 ))
11518 .into_any_element()
11519 }
11520 }),
11521 priority: 0,
11522 }],
11523 Some(Autoscroll::fit()),
11524 cx,
11525 )[0];
11526 this.pending_rename = Some(RenameState {
11527 range,
11528 old_name,
11529 editor: rename_editor,
11530 block_id,
11531 });
11532 })?;
11533 }
11534
11535 Ok(())
11536 }))
11537 }
11538
11539 pub fn confirm_rename(
11540 &mut self,
11541 _: &ConfirmRename,
11542 window: &mut Window,
11543 cx: &mut Context<Self>,
11544 ) -> Option<Task<Result<()>>> {
11545 let rename = self.take_rename(false, window, cx)?;
11546 let workspace = self.workspace()?.downgrade();
11547 let (buffer, start) = self
11548 .buffer
11549 .read(cx)
11550 .text_anchor_for_position(rename.range.start, cx)?;
11551 let (end_buffer, _) = self
11552 .buffer
11553 .read(cx)
11554 .text_anchor_for_position(rename.range.end, cx)?;
11555 if buffer != end_buffer {
11556 return None;
11557 }
11558
11559 let old_name = rename.old_name;
11560 let new_name = rename.editor.read(cx).text(cx);
11561
11562 let rename = self.semantics_provider.as_ref()?.perform_rename(
11563 &buffer,
11564 start,
11565 new_name.clone(),
11566 cx,
11567 )?;
11568
11569 Some(cx.spawn_in(window, |editor, mut cx| async move {
11570 let project_transaction = rename.await?;
11571 Self::open_project_transaction(
11572 &editor,
11573 workspace,
11574 project_transaction,
11575 format!("Rename: {} → {}", old_name, new_name),
11576 cx.clone(),
11577 )
11578 .await?;
11579
11580 editor.update(&mut cx, |editor, cx| {
11581 editor.refresh_document_highlights(cx);
11582 })?;
11583 Ok(())
11584 }))
11585 }
11586
11587 fn take_rename(
11588 &mut self,
11589 moving_cursor: bool,
11590 window: &mut Window,
11591 cx: &mut Context<Self>,
11592 ) -> Option<RenameState> {
11593 let rename = self.pending_rename.take()?;
11594 if rename.editor.focus_handle(cx).is_focused(window) {
11595 window.focus(&self.focus_handle);
11596 }
11597
11598 self.remove_blocks(
11599 [rename.block_id].into_iter().collect(),
11600 Some(Autoscroll::fit()),
11601 cx,
11602 );
11603 self.clear_highlights::<Rename>(cx);
11604 self.show_local_selections = true;
11605
11606 if moving_cursor {
11607 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11608 editor.selections.newest::<usize>(cx).head()
11609 });
11610
11611 // Update the selection to match the position of the selection inside
11612 // the rename editor.
11613 let snapshot = self.buffer.read(cx).read(cx);
11614 let rename_range = rename.range.to_offset(&snapshot);
11615 let cursor_in_editor = snapshot
11616 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11617 .min(rename_range.end);
11618 drop(snapshot);
11619
11620 self.change_selections(None, window, cx, |s| {
11621 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11622 });
11623 } else {
11624 self.refresh_document_highlights(cx);
11625 }
11626
11627 Some(rename)
11628 }
11629
11630 pub fn pending_rename(&self) -> Option<&RenameState> {
11631 self.pending_rename.as_ref()
11632 }
11633
11634 fn format(
11635 &mut self,
11636 _: &Format,
11637 window: &mut Window,
11638 cx: &mut Context<Self>,
11639 ) -> Option<Task<Result<()>>> {
11640 let project = match &self.project {
11641 Some(project) => project.clone(),
11642 None => return None,
11643 };
11644
11645 Some(self.perform_format(
11646 project,
11647 FormatTrigger::Manual,
11648 FormatTarget::Buffers,
11649 window,
11650 cx,
11651 ))
11652 }
11653
11654 fn format_selections(
11655 &mut self,
11656 _: &FormatSelections,
11657 window: &mut Window,
11658 cx: &mut Context<Self>,
11659 ) -> Option<Task<Result<()>>> {
11660 let project = match &self.project {
11661 Some(project) => project.clone(),
11662 None => return None,
11663 };
11664
11665 let ranges = self
11666 .selections
11667 .all_adjusted(cx)
11668 .into_iter()
11669 .map(|selection| selection.range())
11670 .collect_vec();
11671
11672 Some(self.perform_format(
11673 project,
11674 FormatTrigger::Manual,
11675 FormatTarget::Ranges(ranges),
11676 window,
11677 cx,
11678 ))
11679 }
11680
11681 fn perform_format(
11682 &mut self,
11683 project: Entity<Project>,
11684 trigger: FormatTrigger,
11685 target: FormatTarget,
11686 window: &mut Window,
11687 cx: &mut Context<Self>,
11688 ) -> Task<Result<()>> {
11689 let buffer = self.buffer.clone();
11690 let (buffers, target) = match target {
11691 FormatTarget::Buffers => {
11692 let mut buffers = buffer.read(cx).all_buffers();
11693 if trigger == FormatTrigger::Save {
11694 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11695 }
11696 (buffers, LspFormatTarget::Buffers)
11697 }
11698 FormatTarget::Ranges(selection_ranges) => {
11699 let multi_buffer = buffer.read(cx);
11700 let snapshot = multi_buffer.read(cx);
11701 let mut buffers = HashSet::default();
11702 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11703 BTreeMap::new();
11704 for selection_range in selection_ranges {
11705 for (buffer, buffer_range, _) in
11706 snapshot.range_to_buffer_ranges(selection_range)
11707 {
11708 let buffer_id = buffer.remote_id();
11709 let start = buffer.anchor_before(buffer_range.start);
11710 let end = buffer.anchor_after(buffer_range.end);
11711 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11712 buffer_id_to_ranges
11713 .entry(buffer_id)
11714 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11715 .or_insert_with(|| vec![start..end]);
11716 }
11717 }
11718 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11719 }
11720 };
11721
11722 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11723 let format = project.update(cx, |project, cx| {
11724 project.format(buffers, target, true, trigger, cx)
11725 });
11726
11727 cx.spawn_in(window, |_, mut cx| async move {
11728 let transaction = futures::select_biased! {
11729 () = timeout => {
11730 log::warn!("timed out waiting for formatting");
11731 None
11732 }
11733 transaction = format.log_err().fuse() => transaction,
11734 };
11735
11736 buffer
11737 .update(&mut cx, |buffer, cx| {
11738 if let Some(transaction) = transaction {
11739 if !buffer.is_singleton() {
11740 buffer.push_transaction(&transaction.0, cx);
11741 }
11742 }
11743
11744 cx.notify();
11745 })
11746 .ok();
11747
11748 Ok(())
11749 })
11750 }
11751
11752 fn restart_language_server(
11753 &mut self,
11754 _: &RestartLanguageServer,
11755 _: &mut Window,
11756 cx: &mut Context<Self>,
11757 ) {
11758 if let Some(project) = self.project.clone() {
11759 self.buffer.update(cx, |multi_buffer, cx| {
11760 project.update(cx, |project, cx| {
11761 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11762 });
11763 })
11764 }
11765 }
11766
11767 fn cancel_language_server_work(
11768 workspace: &mut Workspace,
11769 _: &actions::CancelLanguageServerWork,
11770 _: &mut Window,
11771 cx: &mut Context<Workspace>,
11772 ) {
11773 let project = workspace.project();
11774 let buffers = workspace
11775 .active_item(cx)
11776 .and_then(|item| item.act_as::<Editor>(cx))
11777 .map_or(HashSet::default(), |editor| {
11778 editor.read(cx).buffer.read(cx).all_buffers()
11779 });
11780 project.update(cx, |project, cx| {
11781 project.cancel_language_server_work_for_buffers(buffers, cx);
11782 });
11783 }
11784
11785 fn show_character_palette(
11786 &mut self,
11787 _: &ShowCharacterPalette,
11788 window: &mut Window,
11789 _: &mut Context<Self>,
11790 ) {
11791 window.show_character_palette();
11792 }
11793
11794 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11795 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11796 let buffer = self.buffer.read(cx).snapshot(cx);
11797 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11798 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11799 let is_valid = buffer
11800 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11801 .any(|entry| {
11802 entry.diagnostic.is_primary
11803 && !entry.range.is_empty()
11804 && entry.range.start == primary_range_start
11805 && entry.diagnostic.message == active_diagnostics.primary_message
11806 });
11807
11808 if is_valid != active_diagnostics.is_valid {
11809 active_diagnostics.is_valid = is_valid;
11810 let mut new_styles = HashMap::default();
11811 for (block_id, diagnostic) in &active_diagnostics.blocks {
11812 new_styles.insert(
11813 *block_id,
11814 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11815 );
11816 }
11817 self.display_map.update(cx, |display_map, _cx| {
11818 display_map.replace_blocks(new_styles)
11819 });
11820 }
11821 }
11822 }
11823
11824 fn activate_diagnostics(
11825 &mut self,
11826 buffer_id: BufferId,
11827 group_id: usize,
11828 window: &mut Window,
11829 cx: &mut Context<Self>,
11830 ) {
11831 self.dismiss_diagnostics(cx);
11832 let snapshot = self.snapshot(window, cx);
11833 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11834 let buffer = self.buffer.read(cx).snapshot(cx);
11835
11836 let mut primary_range = None;
11837 let mut primary_message = None;
11838 let diagnostic_group = buffer
11839 .diagnostic_group(buffer_id, group_id)
11840 .filter_map(|entry| {
11841 let start = entry.range.start;
11842 let end = entry.range.end;
11843 if snapshot.is_line_folded(MultiBufferRow(start.row))
11844 && (start.row == end.row
11845 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11846 {
11847 return None;
11848 }
11849 if entry.diagnostic.is_primary {
11850 primary_range = Some(entry.range.clone());
11851 primary_message = Some(entry.diagnostic.message.clone());
11852 }
11853 Some(entry)
11854 })
11855 .collect::<Vec<_>>();
11856 let primary_range = primary_range?;
11857 let primary_message = primary_message?;
11858
11859 let blocks = display_map
11860 .insert_blocks(
11861 diagnostic_group.iter().map(|entry| {
11862 let diagnostic = entry.diagnostic.clone();
11863 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11864 BlockProperties {
11865 style: BlockStyle::Fixed,
11866 placement: BlockPlacement::Below(
11867 buffer.anchor_after(entry.range.start),
11868 ),
11869 height: message_height,
11870 render: diagnostic_block_renderer(diagnostic, None, true, true),
11871 priority: 0,
11872 }
11873 }),
11874 cx,
11875 )
11876 .into_iter()
11877 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11878 .collect();
11879
11880 Some(ActiveDiagnosticGroup {
11881 primary_range: buffer.anchor_before(primary_range.start)
11882 ..buffer.anchor_after(primary_range.end),
11883 primary_message,
11884 group_id,
11885 blocks,
11886 is_valid: true,
11887 })
11888 });
11889 }
11890
11891 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11892 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11893 self.display_map.update(cx, |display_map, cx| {
11894 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11895 });
11896 cx.notify();
11897 }
11898 }
11899
11900 pub fn set_selections_from_remote(
11901 &mut self,
11902 selections: Vec<Selection<Anchor>>,
11903 pending_selection: Option<Selection<Anchor>>,
11904 window: &mut Window,
11905 cx: &mut Context<Self>,
11906 ) {
11907 let old_cursor_position = self.selections.newest_anchor().head();
11908 self.selections.change_with(cx, |s| {
11909 s.select_anchors(selections);
11910 if let Some(pending_selection) = pending_selection {
11911 s.set_pending(pending_selection, SelectMode::Character);
11912 } else {
11913 s.clear_pending();
11914 }
11915 });
11916 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11917 }
11918
11919 fn push_to_selection_history(&mut self) {
11920 self.selection_history.push(SelectionHistoryEntry {
11921 selections: self.selections.disjoint_anchors(),
11922 select_next_state: self.select_next_state.clone(),
11923 select_prev_state: self.select_prev_state.clone(),
11924 add_selections_state: self.add_selections_state.clone(),
11925 });
11926 }
11927
11928 pub fn transact(
11929 &mut self,
11930 window: &mut Window,
11931 cx: &mut Context<Self>,
11932 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11933 ) -> Option<TransactionId> {
11934 self.start_transaction_at(Instant::now(), window, cx);
11935 update(self, window, cx);
11936 self.end_transaction_at(Instant::now(), cx)
11937 }
11938
11939 pub fn start_transaction_at(
11940 &mut self,
11941 now: Instant,
11942 window: &mut Window,
11943 cx: &mut Context<Self>,
11944 ) {
11945 self.end_selection(window, cx);
11946 if let Some(tx_id) = self
11947 .buffer
11948 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11949 {
11950 self.selection_history
11951 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11952 cx.emit(EditorEvent::TransactionBegun {
11953 transaction_id: tx_id,
11954 })
11955 }
11956 }
11957
11958 pub fn end_transaction_at(
11959 &mut self,
11960 now: Instant,
11961 cx: &mut Context<Self>,
11962 ) -> Option<TransactionId> {
11963 if let Some(transaction_id) = self
11964 .buffer
11965 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11966 {
11967 if let Some((_, end_selections)) =
11968 self.selection_history.transaction_mut(transaction_id)
11969 {
11970 *end_selections = Some(self.selections.disjoint_anchors());
11971 } else {
11972 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11973 }
11974
11975 cx.emit(EditorEvent::Edited { transaction_id });
11976 Some(transaction_id)
11977 } else {
11978 None
11979 }
11980 }
11981
11982 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11983 if self.selection_mark_mode {
11984 self.change_selections(None, window, cx, |s| {
11985 s.move_with(|_, sel| {
11986 sel.collapse_to(sel.head(), SelectionGoal::None);
11987 });
11988 })
11989 }
11990 self.selection_mark_mode = true;
11991 cx.notify();
11992 }
11993
11994 pub fn swap_selection_ends(
11995 &mut self,
11996 _: &actions::SwapSelectionEnds,
11997 window: &mut Window,
11998 cx: &mut Context<Self>,
11999 ) {
12000 self.change_selections(None, window, cx, |s| {
12001 s.move_with(|_, sel| {
12002 if sel.start != sel.end {
12003 sel.reversed = !sel.reversed
12004 }
12005 });
12006 });
12007 self.request_autoscroll(Autoscroll::newest(), cx);
12008 cx.notify();
12009 }
12010
12011 pub fn toggle_fold(
12012 &mut self,
12013 _: &actions::ToggleFold,
12014 window: &mut Window,
12015 cx: &mut Context<Self>,
12016 ) {
12017 if self.is_singleton(cx) {
12018 let selection = self.selections.newest::<Point>(cx);
12019
12020 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12021 let range = if selection.is_empty() {
12022 let point = selection.head().to_display_point(&display_map);
12023 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12024 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12025 .to_point(&display_map);
12026 start..end
12027 } else {
12028 selection.range()
12029 };
12030 if display_map.folds_in_range(range).next().is_some() {
12031 self.unfold_lines(&Default::default(), window, cx)
12032 } else {
12033 self.fold(&Default::default(), window, cx)
12034 }
12035 } else {
12036 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12037 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12038 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12039 .map(|(snapshot, _, _)| snapshot.remote_id())
12040 .collect();
12041
12042 for buffer_id in buffer_ids {
12043 if self.is_buffer_folded(buffer_id, cx) {
12044 self.unfold_buffer(buffer_id, cx);
12045 } else {
12046 self.fold_buffer(buffer_id, cx);
12047 }
12048 }
12049 }
12050 }
12051
12052 pub fn toggle_fold_recursive(
12053 &mut self,
12054 _: &actions::ToggleFoldRecursive,
12055 window: &mut Window,
12056 cx: &mut Context<Self>,
12057 ) {
12058 let selection = self.selections.newest::<Point>(cx);
12059
12060 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12061 let range = if selection.is_empty() {
12062 let point = selection.head().to_display_point(&display_map);
12063 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12064 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12065 .to_point(&display_map);
12066 start..end
12067 } else {
12068 selection.range()
12069 };
12070 if display_map.folds_in_range(range).next().is_some() {
12071 self.unfold_recursive(&Default::default(), window, cx)
12072 } else {
12073 self.fold_recursive(&Default::default(), window, cx)
12074 }
12075 }
12076
12077 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12078 if self.is_singleton(cx) {
12079 let mut to_fold = Vec::new();
12080 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12081 let selections = self.selections.all_adjusted(cx);
12082
12083 for selection in selections {
12084 let range = selection.range().sorted();
12085 let buffer_start_row = range.start.row;
12086
12087 if range.start.row != range.end.row {
12088 let mut found = false;
12089 let mut row = range.start.row;
12090 while row <= range.end.row {
12091 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12092 {
12093 found = true;
12094 row = crease.range().end.row + 1;
12095 to_fold.push(crease);
12096 } else {
12097 row += 1
12098 }
12099 }
12100 if found {
12101 continue;
12102 }
12103 }
12104
12105 for row in (0..=range.start.row).rev() {
12106 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12107 if crease.range().end.row >= buffer_start_row {
12108 to_fold.push(crease);
12109 if row <= range.start.row {
12110 break;
12111 }
12112 }
12113 }
12114 }
12115 }
12116
12117 self.fold_creases(to_fold, true, window, cx);
12118 } else {
12119 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12120
12121 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12122 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12123 .map(|(snapshot, _, _)| snapshot.remote_id())
12124 .collect();
12125 for buffer_id in buffer_ids {
12126 self.fold_buffer(buffer_id, cx);
12127 }
12128 }
12129 }
12130
12131 fn fold_at_level(
12132 &mut self,
12133 fold_at: &FoldAtLevel,
12134 window: &mut Window,
12135 cx: &mut Context<Self>,
12136 ) {
12137 if !self.buffer.read(cx).is_singleton() {
12138 return;
12139 }
12140
12141 let fold_at_level = fold_at.0;
12142 let snapshot = self.buffer.read(cx).snapshot(cx);
12143 let mut to_fold = Vec::new();
12144 let mut stack = vec![(0, snapshot.max_row().0, 1)];
12145
12146 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12147 while start_row < end_row {
12148 match self
12149 .snapshot(window, cx)
12150 .crease_for_buffer_row(MultiBufferRow(start_row))
12151 {
12152 Some(crease) => {
12153 let nested_start_row = crease.range().start.row + 1;
12154 let nested_end_row = crease.range().end.row;
12155
12156 if current_level < fold_at_level {
12157 stack.push((nested_start_row, nested_end_row, current_level + 1));
12158 } else if current_level == fold_at_level {
12159 to_fold.push(crease);
12160 }
12161
12162 start_row = nested_end_row + 1;
12163 }
12164 None => start_row += 1,
12165 }
12166 }
12167 }
12168
12169 self.fold_creases(to_fold, true, window, cx);
12170 }
12171
12172 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12173 if self.buffer.read(cx).is_singleton() {
12174 let mut fold_ranges = Vec::new();
12175 let snapshot = self.buffer.read(cx).snapshot(cx);
12176
12177 for row in 0..snapshot.max_row().0 {
12178 if let Some(foldable_range) = self
12179 .snapshot(window, cx)
12180 .crease_for_buffer_row(MultiBufferRow(row))
12181 {
12182 fold_ranges.push(foldable_range);
12183 }
12184 }
12185
12186 self.fold_creases(fold_ranges, true, window, cx);
12187 } else {
12188 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12189 editor
12190 .update_in(&mut cx, |editor, _, cx| {
12191 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12192 editor.fold_buffer(buffer_id, cx);
12193 }
12194 })
12195 .ok();
12196 });
12197 }
12198 }
12199
12200 pub fn fold_function_bodies(
12201 &mut self,
12202 _: &actions::FoldFunctionBodies,
12203 window: &mut Window,
12204 cx: &mut Context<Self>,
12205 ) {
12206 let snapshot = self.buffer.read(cx).snapshot(cx);
12207
12208 let ranges = snapshot
12209 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12210 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12211 .collect::<Vec<_>>();
12212
12213 let creases = ranges
12214 .into_iter()
12215 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12216 .collect();
12217
12218 self.fold_creases(creases, true, window, cx);
12219 }
12220
12221 pub fn fold_recursive(
12222 &mut self,
12223 _: &actions::FoldRecursive,
12224 window: &mut Window,
12225 cx: &mut Context<Self>,
12226 ) {
12227 let mut to_fold = Vec::new();
12228 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12229 let selections = self.selections.all_adjusted(cx);
12230
12231 for selection in selections {
12232 let range = selection.range().sorted();
12233 let buffer_start_row = range.start.row;
12234
12235 if range.start.row != range.end.row {
12236 let mut found = false;
12237 for row in range.start.row..=range.end.row {
12238 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12239 found = true;
12240 to_fold.push(crease);
12241 }
12242 }
12243 if found {
12244 continue;
12245 }
12246 }
12247
12248 for row in (0..=range.start.row).rev() {
12249 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12250 if crease.range().end.row >= buffer_start_row {
12251 to_fold.push(crease);
12252 } else {
12253 break;
12254 }
12255 }
12256 }
12257 }
12258
12259 self.fold_creases(to_fold, true, window, cx);
12260 }
12261
12262 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12263 let buffer_row = fold_at.buffer_row;
12264 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12265
12266 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12267 let autoscroll = self
12268 .selections
12269 .all::<Point>(cx)
12270 .iter()
12271 .any(|selection| crease.range().overlaps(&selection.range()));
12272
12273 self.fold_creases(vec![crease], autoscroll, window, cx);
12274 }
12275 }
12276
12277 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12278 if self.is_singleton(cx) {
12279 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12280 let buffer = &display_map.buffer_snapshot;
12281 let selections = self.selections.all::<Point>(cx);
12282 let ranges = selections
12283 .iter()
12284 .map(|s| {
12285 let range = s.display_range(&display_map).sorted();
12286 let mut start = range.start.to_point(&display_map);
12287 let mut end = range.end.to_point(&display_map);
12288 start.column = 0;
12289 end.column = buffer.line_len(MultiBufferRow(end.row));
12290 start..end
12291 })
12292 .collect::<Vec<_>>();
12293
12294 self.unfold_ranges(&ranges, true, true, cx);
12295 } else {
12296 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12297 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12298 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12299 .map(|(snapshot, _, _)| snapshot.remote_id())
12300 .collect();
12301 for buffer_id in buffer_ids {
12302 self.unfold_buffer(buffer_id, cx);
12303 }
12304 }
12305 }
12306
12307 pub fn unfold_recursive(
12308 &mut self,
12309 _: &UnfoldRecursive,
12310 _window: &mut Window,
12311 cx: &mut Context<Self>,
12312 ) {
12313 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12314 let selections = self.selections.all::<Point>(cx);
12315 let ranges = selections
12316 .iter()
12317 .map(|s| {
12318 let mut range = s.display_range(&display_map).sorted();
12319 *range.start.column_mut() = 0;
12320 *range.end.column_mut() = display_map.line_len(range.end.row());
12321 let start = range.start.to_point(&display_map);
12322 let end = range.end.to_point(&display_map);
12323 start..end
12324 })
12325 .collect::<Vec<_>>();
12326
12327 self.unfold_ranges(&ranges, true, true, cx);
12328 }
12329
12330 pub fn unfold_at(
12331 &mut self,
12332 unfold_at: &UnfoldAt,
12333 _window: &mut Window,
12334 cx: &mut Context<Self>,
12335 ) {
12336 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12337
12338 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12339 ..Point::new(
12340 unfold_at.buffer_row.0,
12341 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12342 );
12343
12344 let autoscroll = self
12345 .selections
12346 .all::<Point>(cx)
12347 .iter()
12348 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12349
12350 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12351 }
12352
12353 pub fn unfold_all(
12354 &mut self,
12355 _: &actions::UnfoldAll,
12356 _window: &mut Window,
12357 cx: &mut Context<Self>,
12358 ) {
12359 if self.buffer.read(cx).is_singleton() {
12360 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12361 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12362 } else {
12363 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12364 editor
12365 .update(&mut cx, |editor, cx| {
12366 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12367 editor.unfold_buffer(buffer_id, cx);
12368 }
12369 })
12370 .ok();
12371 });
12372 }
12373 }
12374
12375 pub fn fold_selected_ranges(
12376 &mut self,
12377 _: &FoldSelectedRanges,
12378 window: &mut Window,
12379 cx: &mut Context<Self>,
12380 ) {
12381 let selections = self.selections.all::<Point>(cx);
12382 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12383 let line_mode = self.selections.line_mode;
12384 let ranges = selections
12385 .into_iter()
12386 .map(|s| {
12387 if line_mode {
12388 let start = Point::new(s.start.row, 0);
12389 let end = Point::new(
12390 s.end.row,
12391 display_map
12392 .buffer_snapshot
12393 .line_len(MultiBufferRow(s.end.row)),
12394 );
12395 Crease::simple(start..end, display_map.fold_placeholder.clone())
12396 } else {
12397 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12398 }
12399 })
12400 .collect::<Vec<_>>();
12401 self.fold_creases(ranges, true, window, cx);
12402 }
12403
12404 pub fn fold_ranges<T: ToOffset + Clone>(
12405 &mut self,
12406 ranges: Vec<Range<T>>,
12407 auto_scroll: bool,
12408 window: &mut Window,
12409 cx: &mut Context<Self>,
12410 ) {
12411 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12412 let ranges = ranges
12413 .into_iter()
12414 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12415 .collect::<Vec<_>>();
12416 self.fold_creases(ranges, auto_scroll, window, cx);
12417 }
12418
12419 pub fn fold_creases<T: ToOffset + Clone>(
12420 &mut self,
12421 creases: Vec<Crease<T>>,
12422 auto_scroll: bool,
12423 window: &mut Window,
12424 cx: &mut Context<Self>,
12425 ) {
12426 if creases.is_empty() {
12427 return;
12428 }
12429
12430 let mut buffers_affected = HashSet::default();
12431 let multi_buffer = self.buffer().read(cx);
12432 for crease in &creases {
12433 if let Some((_, buffer, _)) =
12434 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12435 {
12436 buffers_affected.insert(buffer.read(cx).remote_id());
12437 };
12438 }
12439
12440 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12441
12442 if auto_scroll {
12443 self.request_autoscroll(Autoscroll::fit(), cx);
12444 }
12445
12446 cx.notify();
12447
12448 if let Some(active_diagnostics) = self.active_diagnostics.take() {
12449 // Clear diagnostics block when folding a range that contains it.
12450 let snapshot = self.snapshot(window, cx);
12451 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12452 drop(snapshot);
12453 self.active_diagnostics = Some(active_diagnostics);
12454 self.dismiss_diagnostics(cx);
12455 } else {
12456 self.active_diagnostics = Some(active_diagnostics);
12457 }
12458 }
12459
12460 self.scrollbar_marker_state.dirty = true;
12461 }
12462
12463 /// Removes any folds whose ranges intersect any of the given ranges.
12464 pub fn unfold_ranges<T: ToOffset + Clone>(
12465 &mut self,
12466 ranges: &[Range<T>],
12467 inclusive: bool,
12468 auto_scroll: bool,
12469 cx: &mut Context<Self>,
12470 ) {
12471 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12472 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12473 });
12474 }
12475
12476 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12477 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12478 return;
12479 }
12480 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12481 self.display_map
12482 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12483 cx.emit(EditorEvent::BufferFoldToggled {
12484 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12485 folded: true,
12486 });
12487 cx.notify();
12488 }
12489
12490 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12491 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12492 return;
12493 }
12494 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12495 self.display_map.update(cx, |display_map, cx| {
12496 display_map.unfold_buffer(buffer_id, cx);
12497 });
12498 cx.emit(EditorEvent::BufferFoldToggled {
12499 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12500 folded: false,
12501 });
12502 cx.notify();
12503 }
12504
12505 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12506 self.display_map.read(cx).is_buffer_folded(buffer)
12507 }
12508
12509 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12510 self.display_map.read(cx).folded_buffers()
12511 }
12512
12513 /// Removes any folds with the given ranges.
12514 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12515 &mut self,
12516 ranges: &[Range<T>],
12517 type_id: TypeId,
12518 auto_scroll: bool,
12519 cx: &mut Context<Self>,
12520 ) {
12521 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12522 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12523 });
12524 }
12525
12526 fn remove_folds_with<T: ToOffset + Clone>(
12527 &mut self,
12528 ranges: &[Range<T>],
12529 auto_scroll: bool,
12530 cx: &mut Context<Self>,
12531 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12532 ) {
12533 if ranges.is_empty() {
12534 return;
12535 }
12536
12537 let mut buffers_affected = HashSet::default();
12538 let multi_buffer = self.buffer().read(cx);
12539 for range in ranges {
12540 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12541 buffers_affected.insert(buffer.read(cx).remote_id());
12542 };
12543 }
12544
12545 self.display_map.update(cx, update);
12546
12547 if auto_scroll {
12548 self.request_autoscroll(Autoscroll::fit(), cx);
12549 }
12550
12551 cx.notify();
12552 self.scrollbar_marker_state.dirty = true;
12553 self.active_indent_guides_state.dirty = true;
12554 }
12555
12556 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12557 self.display_map.read(cx).fold_placeholder.clone()
12558 }
12559
12560 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12561 self.buffer.update(cx, |buffer, cx| {
12562 buffer.set_all_diff_hunks_expanded(cx);
12563 });
12564 }
12565
12566 pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12567 self.distinguish_unstaged_diff_hunks = true;
12568 }
12569
12570 pub fn expand_all_diff_hunks(
12571 &mut self,
12572 _: &ExpandAllHunkDiffs,
12573 _window: &mut Window,
12574 cx: &mut Context<Self>,
12575 ) {
12576 self.buffer.update(cx, |buffer, cx| {
12577 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12578 });
12579 }
12580
12581 pub fn toggle_selected_diff_hunks(
12582 &mut self,
12583 _: &ToggleSelectedDiffHunks,
12584 _window: &mut Window,
12585 cx: &mut Context<Self>,
12586 ) {
12587 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12588 self.toggle_diff_hunks_in_ranges(ranges, cx);
12589 }
12590
12591 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12592 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12593 self.buffer
12594 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12595 }
12596
12597 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12598 self.buffer.update(cx, |buffer, cx| {
12599 let ranges = vec![Anchor::min()..Anchor::max()];
12600 if !buffer.all_diff_hunks_expanded()
12601 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12602 {
12603 buffer.collapse_diff_hunks(ranges, cx);
12604 true
12605 } else {
12606 false
12607 }
12608 })
12609 }
12610
12611 fn toggle_diff_hunks_in_ranges(
12612 &mut self,
12613 ranges: Vec<Range<Anchor>>,
12614 cx: &mut Context<'_, Editor>,
12615 ) {
12616 self.buffer.update(cx, |buffer, cx| {
12617 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12618 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12619 })
12620 }
12621
12622 fn toggle_diff_hunks_in_ranges_narrow(
12623 &mut self,
12624 ranges: Vec<Range<Anchor>>,
12625 cx: &mut Context<'_, Editor>,
12626 ) {
12627 self.buffer.update(cx, |buffer, cx| {
12628 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12629 buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12630 })
12631 }
12632
12633 pub(crate) fn apply_all_diff_hunks(
12634 &mut self,
12635 _: &ApplyAllDiffHunks,
12636 window: &mut Window,
12637 cx: &mut Context<Self>,
12638 ) {
12639 let buffers = self.buffer.read(cx).all_buffers();
12640 for branch_buffer in buffers {
12641 branch_buffer.update(cx, |branch_buffer, cx| {
12642 branch_buffer.merge_into_base(Vec::new(), cx);
12643 });
12644 }
12645
12646 if let Some(project) = self.project.clone() {
12647 self.save(true, project, window, cx).detach_and_log_err(cx);
12648 }
12649 }
12650
12651 pub(crate) fn apply_selected_diff_hunks(
12652 &mut self,
12653 _: &ApplyDiffHunk,
12654 window: &mut Window,
12655 cx: &mut Context<Self>,
12656 ) {
12657 let snapshot = self.snapshot(window, cx);
12658 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12659 let mut ranges_by_buffer = HashMap::default();
12660 self.transact(window, cx, |editor, _window, cx| {
12661 for hunk in hunks {
12662 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12663 ranges_by_buffer
12664 .entry(buffer.clone())
12665 .or_insert_with(Vec::new)
12666 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12667 }
12668 }
12669
12670 for (buffer, ranges) in ranges_by_buffer {
12671 buffer.update(cx, |buffer, cx| {
12672 buffer.merge_into_base(ranges, cx);
12673 });
12674 }
12675 });
12676
12677 if let Some(project) = self.project.clone() {
12678 self.save(true, project, window, cx).detach_and_log_err(cx);
12679 }
12680 }
12681
12682 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12683 if hovered != self.gutter_hovered {
12684 self.gutter_hovered = hovered;
12685 cx.notify();
12686 }
12687 }
12688
12689 pub fn insert_blocks(
12690 &mut self,
12691 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12692 autoscroll: Option<Autoscroll>,
12693 cx: &mut Context<Self>,
12694 ) -> Vec<CustomBlockId> {
12695 let blocks = self
12696 .display_map
12697 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12698 if let Some(autoscroll) = autoscroll {
12699 self.request_autoscroll(autoscroll, cx);
12700 }
12701 cx.notify();
12702 blocks
12703 }
12704
12705 pub fn resize_blocks(
12706 &mut self,
12707 heights: HashMap<CustomBlockId, u32>,
12708 autoscroll: Option<Autoscroll>,
12709 cx: &mut Context<Self>,
12710 ) {
12711 self.display_map
12712 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12713 if let Some(autoscroll) = autoscroll {
12714 self.request_autoscroll(autoscroll, cx);
12715 }
12716 cx.notify();
12717 }
12718
12719 pub fn replace_blocks(
12720 &mut self,
12721 renderers: HashMap<CustomBlockId, RenderBlock>,
12722 autoscroll: Option<Autoscroll>,
12723 cx: &mut Context<Self>,
12724 ) {
12725 self.display_map
12726 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12727 if let Some(autoscroll) = autoscroll {
12728 self.request_autoscroll(autoscroll, cx);
12729 }
12730 cx.notify();
12731 }
12732
12733 pub fn remove_blocks(
12734 &mut self,
12735 block_ids: HashSet<CustomBlockId>,
12736 autoscroll: Option<Autoscroll>,
12737 cx: &mut Context<Self>,
12738 ) {
12739 self.display_map.update(cx, |display_map, cx| {
12740 display_map.remove_blocks(block_ids, cx)
12741 });
12742 if let Some(autoscroll) = autoscroll {
12743 self.request_autoscroll(autoscroll, cx);
12744 }
12745 cx.notify();
12746 }
12747
12748 pub fn row_for_block(
12749 &self,
12750 block_id: CustomBlockId,
12751 cx: &mut Context<Self>,
12752 ) -> Option<DisplayRow> {
12753 self.display_map
12754 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12755 }
12756
12757 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12758 self.focused_block = Some(focused_block);
12759 }
12760
12761 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12762 self.focused_block.take()
12763 }
12764
12765 pub fn insert_creases(
12766 &mut self,
12767 creases: impl IntoIterator<Item = Crease<Anchor>>,
12768 cx: &mut Context<Self>,
12769 ) -> Vec<CreaseId> {
12770 self.display_map
12771 .update(cx, |map, cx| map.insert_creases(creases, cx))
12772 }
12773
12774 pub fn remove_creases(
12775 &mut self,
12776 ids: impl IntoIterator<Item = CreaseId>,
12777 cx: &mut Context<Self>,
12778 ) {
12779 self.display_map
12780 .update(cx, |map, cx| map.remove_creases(ids, cx));
12781 }
12782
12783 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12784 self.display_map
12785 .update(cx, |map, cx| map.snapshot(cx))
12786 .longest_row()
12787 }
12788
12789 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12790 self.display_map
12791 .update(cx, |map, cx| map.snapshot(cx))
12792 .max_point()
12793 }
12794
12795 pub fn text(&self, cx: &App) -> String {
12796 self.buffer.read(cx).read(cx).text()
12797 }
12798
12799 pub fn is_empty(&self, cx: &App) -> bool {
12800 self.buffer.read(cx).read(cx).is_empty()
12801 }
12802
12803 pub fn text_option(&self, cx: &App) -> Option<String> {
12804 let text = self.text(cx);
12805 let text = text.trim();
12806
12807 if text.is_empty() {
12808 return None;
12809 }
12810
12811 Some(text.to_string())
12812 }
12813
12814 pub fn set_text(
12815 &mut self,
12816 text: impl Into<Arc<str>>,
12817 window: &mut Window,
12818 cx: &mut Context<Self>,
12819 ) {
12820 self.transact(window, cx, |this, _, cx| {
12821 this.buffer
12822 .read(cx)
12823 .as_singleton()
12824 .expect("you can only call set_text on editors for singleton buffers")
12825 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12826 });
12827 }
12828
12829 pub fn display_text(&self, cx: &mut App) -> String {
12830 self.display_map
12831 .update(cx, |map, cx| map.snapshot(cx))
12832 .text()
12833 }
12834
12835 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12836 let mut wrap_guides = smallvec::smallvec![];
12837
12838 if self.show_wrap_guides == Some(false) {
12839 return wrap_guides;
12840 }
12841
12842 let settings = self.buffer.read(cx).settings_at(0, cx);
12843 if settings.show_wrap_guides {
12844 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12845 wrap_guides.push((soft_wrap as usize, true));
12846 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12847 wrap_guides.push((soft_wrap as usize, true));
12848 }
12849 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12850 }
12851
12852 wrap_guides
12853 }
12854
12855 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12856 let settings = self.buffer.read(cx).settings_at(0, cx);
12857 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12858 match mode {
12859 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12860 SoftWrap::None
12861 }
12862 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12863 language_settings::SoftWrap::PreferredLineLength => {
12864 SoftWrap::Column(settings.preferred_line_length)
12865 }
12866 language_settings::SoftWrap::Bounded => {
12867 SoftWrap::Bounded(settings.preferred_line_length)
12868 }
12869 }
12870 }
12871
12872 pub fn set_soft_wrap_mode(
12873 &mut self,
12874 mode: language_settings::SoftWrap,
12875
12876 cx: &mut Context<Self>,
12877 ) {
12878 self.soft_wrap_mode_override = Some(mode);
12879 cx.notify();
12880 }
12881
12882 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12883 self.text_style_refinement = Some(style);
12884 }
12885
12886 /// called by the Element so we know what style we were most recently rendered with.
12887 pub(crate) fn set_style(
12888 &mut self,
12889 style: EditorStyle,
12890 window: &mut Window,
12891 cx: &mut Context<Self>,
12892 ) {
12893 let rem_size = window.rem_size();
12894 self.display_map.update(cx, |map, cx| {
12895 map.set_font(
12896 style.text.font(),
12897 style.text.font_size.to_pixels(rem_size),
12898 cx,
12899 )
12900 });
12901 self.style = Some(style);
12902 }
12903
12904 pub fn style(&self) -> Option<&EditorStyle> {
12905 self.style.as_ref()
12906 }
12907
12908 // Called by the element. This method is not designed to be called outside of the editor
12909 // element's layout code because it does not notify when rewrapping is computed synchronously.
12910 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12911 self.display_map
12912 .update(cx, |map, cx| map.set_wrap_width(width, cx))
12913 }
12914
12915 pub fn set_soft_wrap(&mut self) {
12916 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12917 }
12918
12919 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12920 if self.soft_wrap_mode_override.is_some() {
12921 self.soft_wrap_mode_override.take();
12922 } else {
12923 let soft_wrap = match self.soft_wrap_mode(cx) {
12924 SoftWrap::GitDiff => return,
12925 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12926 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12927 language_settings::SoftWrap::None
12928 }
12929 };
12930 self.soft_wrap_mode_override = Some(soft_wrap);
12931 }
12932 cx.notify();
12933 }
12934
12935 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12936 let Some(workspace) = self.workspace() else {
12937 return;
12938 };
12939 let fs = workspace.read(cx).app_state().fs.clone();
12940 let current_show = TabBarSettings::get_global(cx).show;
12941 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12942 setting.show = Some(!current_show);
12943 });
12944 }
12945
12946 pub fn toggle_indent_guides(
12947 &mut self,
12948 _: &ToggleIndentGuides,
12949 _: &mut Window,
12950 cx: &mut Context<Self>,
12951 ) {
12952 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12953 self.buffer
12954 .read(cx)
12955 .settings_at(0, cx)
12956 .indent_guides
12957 .enabled
12958 });
12959 self.show_indent_guides = Some(!currently_enabled);
12960 cx.notify();
12961 }
12962
12963 fn should_show_indent_guides(&self) -> Option<bool> {
12964 self.show_indent_guides
12965 }
12966
12967 pub fn toggle_line_numbers(
12968 &mut self,
12969 _: &ToggleLineNumbers,
12970 _: &mut Window,
12971 cx: &mut Context<Self>,
12972 ) {
12973 let mut editor_settings = EditorSettings::get_global(cx).clone();
12974 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12975 EditorSettings::override_global(editor_settings, cx);
12976 }
12977
12978 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12979 self.use_relative_line_numbers
12980 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12981 }
12982
12983 pub fn toggle_relative_line_numbers(
12984 &mut self,
12985 _: &ToggleRelativeLineNumbers,
12986 _: &mut Window,
12987 cx: &mut Context<Self>,
12988 ) {
12989 let is_relative = self.should_use_relative_line_numbers(cx);
12990 self.set_relative_line_number(Some(!is_relative), cx)
12991 }
12992
12993 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12994 self.use_relative_line_numbers = is_relative;
12995 cx.notify();
12996 }
12997
12998 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12999 self.show_gutter = show_gutter;
13000 cx.notify();
13001 }
13002
13003 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13004 self.show_scrollbars = show_scrollbars;
13005 cx.notify();
13006 }
13007
13008 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13009 self.show_line_numbers = Some(show_line_numbers);
13010 cx.notify();
13011 }
13012
13013 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13014 self.show_git_diff_gutter = Some(show_git_diff_gutter);
13015 cx.notify();
13016 }
13017
13018 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13019 self.show_code_actions = Some(show_code_actions);
13020 cx.notify();
13021 }
13022
13023 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13024 self.show_runnables = Some(show_runnables);
13025 cx.notify();
13026 }
13027
13028 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13029 if self.display_map.read(cx).masked != masked {
13030 self.display_map.update(cx, |map, _| map.masked = masked);
13031 }
13032 cx.notify()
13033 }
13034
13035 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13036 self.show_wrap_guides = Some(show_wrap_guides);
13037 cx.notify();
13038 }
13039
13040 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13041 self.show_indent_guides = Some(show_indent_guides);
13042 cx.notify();
13043 }
13044
13045 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13046 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13047 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13048 if let Some(dir) = file.abs_path(cx).parent() {
13049 return Some(dir.to_owned());
13050 }
13051 }
13052
13053 if let Some(project_path) = buffer.read(cx).project_path(cx) {
13054 return Some(project_path.path.to_path_buf());
13055 }
13056 }
13057
13058 None
13059 }
13060
13061 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13062 self.active_excerpt(cx)?
13063 .1
13064 .read(cx)
13065 .file()
13066 .and_then(|f| f.as_local())
13067 }
13068
13069 fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13070 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13071 let project_path = buffer.read(cx).project_path(cx)?;
13072 let project = self.project.as_ref()?.read(cx);
13073 project.absolute_path(&project_path, cx)
13074 })
13075 }
13076
13077 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13078 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13079 let project_path = buffer.read(cx).project_path(cx)?;
13080 let project = self.project.as_ref()?.read(cx);
13081 let entry = project.entry_for_path(&project_path, cx)?;
13082 let path = entry.path.to_path_buf();
13083 Some(path)
13084 })
13085 }
13086
13087 pub fn reveal_in_finder(
13088 &mut self,
13089 _: &RevealInFileManager,
13090 _window: &mut Window,
13091 cx: &mut Context<Self>,
13092 ) {
13093 if let Some(target) = self.target_file(cx) {
13094 cx.reveal_path(&target.abs_path(cx));
13095 }
13096 }
13097
13098 pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
13099 if let Some(path) = self.target_file_abs_path(cx) {
13100 if let Some(path) = path.to_str() {
13101 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13102 }
13103 }
13104 }
13105
13106 pub fn copy_relative_path(
13107 &mut self,
13108 _: &CopyRelativePath,
13109 _window: &mut Window,
13110 cx: &mut Context<Self>,
13111 ) {
13112 if let Some(path) = self.target_file_path(cx) {
13113 if let Some(path) = path.to_str() {
13114 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13115 }
13116 }
13117 }
13118
13119 pub fn copy_file_name_without_extension(
13120 &mut self,
13121 _: &CopyFileNameWithoutExtension,
13122 _: &mut Window,
13123 cx: &mut Context<Self>,
13124 ) {
13125 if let Some(file) = self.target_file(cx) {
13126 if let Some(file_stem) = file.path().file_stem() {
13127 if let Some(name) = file_stem.to_str() {
13128 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13129 }
13130 }
13131 }
13132 }
13133
13134 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13135 if let Some(file) = self.target_file(cx) {
13136 if let Some(file_name) = file.path().file_name() {
13137 if let Some(name) = file_name.to_str() {
13138 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13139 }
13140 }
13141 }
13142 }
13143
13144 pub fn toggle_git_blame(
13145 &mut self,
13146 _: &ToggleGitBlame,
13147 window: &mut Window,
13148 cx: &mut Context<Self>,
13149 ) {
13150 self.show_git_blame_gutter = !self.show_git_blame_gutter;
13151
13152 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13153 self.start_git_blame(true, window, cx);
13154 }
13155
13156 cx.notify();
13157 }
13158
13159 pub fn toggle_git_blame_inline(
13160 &mut self,
13161 _: &ToggleGitBlameInline,
13162 window: &mut Window,
13163 cx: &mut Context<Self>,
13164 ) {
13165 self.toggle_git_blame_inline_internal(true, window, cx);
13166 cx.notify();
13167 }
13168
13169 pub fn git_blame_inline_enabled(&self) -> bool {
13170 self.git_blame_inline_enabled
13171 }
13172
13173 pub fn toggle_selection_menu(
13174 &mut self,
13175 _: &ToggleSelectionMenu,
13176 _: &mut Window,
13177 cx: &mut Context<Self>,
13178 ) {
13179 self.show_selection_menu = self
13180 .show_selection_menu
13181 .map(|show_selections_menu| !show_selections_menu)
13182 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13183
13184 cx.notify();
13185 }
13186
13187 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13188 self.show_selection_menu
13189 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13190 }
13191
13192 fn start_git_blame(
13193 &mut self,
13194 user_triggered: bool,
13195 window: &mut Window,
13196 cx: &mut Context<Self>,
13197 ) {
13198 if let Some(project) = self.project.as_ref() {
13199 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13200 return;
13201 };
13202
13203 if buffer.read(cx).file().is_none() {
13204 return;
13205 }
13206
13207 let focused = self.focus_handle(cx).contains_focused(window, cx);
13208
13209 let project = project.clone();
13210 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13211 self.blame_subscription =
13212 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13213 self.blame = Some(blame);
13214 }
13215 }
13216
13217 fn toggle_git_blame_inline_internal(
13218 &mut self,
13219 user_triggered: bool,
13220 window: &mut Window,
13221 cx: &mut Context<Self>,
13222 ) {
13223 if self.git_blame_inline_enabled {
13224 self.git_blame_inline_enabled = false;
13225 self.show_git_blame_inline = false;
13226 self.show_git_blame_inline_delay_task.take();
13227 } else {
13228 self.git_blame_inline_enabled = true;
13229 self.start_git_blame_inline(user_triggered, window, cx);
13230 }
13231
13232 cx.notify();
13233 }
13234
13235 fn start_git_blame_inline(
13236 &mut self,
13237 user_triggered: bool,
13238 window: &mut Window,
13239 cx: &mut Context<Self>,
13240 ) {
13241 self.start_git_blame(user_triggered, window, cx);
13242
13243 if ProjectSettings::get_global(cx)
13244 .git
13245 .inline_blame_delay()
13246 .is_some()
13247 {
13248 self.start_inline_blame_timer(window, cx);
13249 } else {
13250 self.show_git_blame_inline = true
13251 }
13252 }
13253
13254 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13255 self.blame.as_ref()
13256 }
13257
13258 pub fn show_git_blame_gutter(&self) -> bool {
13259 self.show_git_blame_gutter
13260 }
13261
13262 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13263 self.show_git_blame_gutter && self.has_blame_entries(cx)
13264 }
13265
13266 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13267 self.show_git_blame_inline
13268 && self.focus_handle.is_focused(window)
13269 && !self.newest_selection_head_on_empty_line(cx)
13270 && self.has_blame_entries(cx)
13271 }
13272
13273 fn has_blame_entries(&self, cx: &App) -> bool {
13274 self.blame()
13275 .map_or(false, |blame| blame.read(cx).has_generated_entries())
13276 }
13277
13278 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13279 let cursor_anchor = self.selections.newest_anchor().head();
13280
13281 let snapshot = self.buffer.read(cx).snapshot(cx);
13282 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13283
13284 snapshot.line_len(buffer_row) == 0
13285 }
13286
13287 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13288 let buffer_and_selection = maybe!({
13289 let selection = self.selections.newest::<Point>(cx);
13290 let selection_range = selection.range();
13291
13292 let multi_buffer = self.buffer().read(cx);
13293 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13294 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13295
13296 let (buffer, range, _) = if selection.reversed {
13297 buffer_ranges.first()
13298 } else {
13299 buffer_ranges.last()
13300 }?;
13301
13302 let selection = text::ToPoint::to_point(&range.start, &buffer).row
13303 ..text::ToPoint::to_point(&range.end, &buffer).row;
13304 Some((
13305 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13306 selection,
13307 ))
13308 });
13309
13310 let Some((buffer, selection)) = buffer_and_selection else {
13311 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13312 };
13313
13314 let Some(project) = self.project.as_ref() else {
13315 return Task::ready(Err(anyhow!("editor does not have project")));
13316 };
13317
13318 project.update(cx, |project, cx| {
13319 project.get_permalink_to_line(&buffer, selection, cx)
13320 })
13321 }
13322
13323 pub fn copy_permalink_to_line(
13324 &mut self,
13325 _: &CopyPermalinkToLine,
13326 window: &mut Window,
13327 cx: &mut Context<Self>,
13328 ) {
13329 let permalink_task = self.get_permalink_to_line(cx);
13330 let workspace = self.workspace();
13331
13332 cx.spawn_in(window, |_, mut cx| async move {
13333 match permalink_task.await {
13334 Ok(permalink) => {
13335 cx.update(|_, cx| {
13336 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13337 })
13338 .ok();
13339 }
13340 Err(err) => {
13341 let message = format!("Failed to copy permalink: {err}");
13342
13343 Err::<(), anyhow::Error>(err).log_err();
13344
13345 if let Some(workspace) = workspace {
13346 workspace
13347 .update_in(&mut cx, |workspace, _, cx| {
13348 struct CopyPermalinkToLine;
13349
13350 workspace.show_toast(
13351 Toast::new(
13352 NotificationId::unique::<CopyPermalinkToLine>(),
13353 message,
13354 ),
13355 cx,
13356 )
13357 })
13358 .ok();
13359 }
13360 }
13361 }
13362 })
13363 .detach();
13364 }
13365
13366 pub fn copy_file_location(
13367 &mut self,
13368 _: &CopyFileLocation,
13369 _: &mut Window,
13370 cx: &mut Context<Self>,
13371 ) {
13372 let selection = self.selections.newest::<Point>(cx).start.row + 1;
13373 if let Some(file) = self.target_file(cx) {
13374 if let Some(path) = file.path().to_str() {
13375 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13376 }
13377 }
13378 }
13379
13380 pub fn open_permalink_to_line(
13381 &mut self,
13382 _: &OpenPermalinkToLine,
13383 window: &mut Window,
13384 cx: &mut Context<Self>,
13385 ) {
13386 let permalink_task = self.get_permalink_to_line(cx);
13387 let workspace = self.workspace();
13388
13389 cx.spawn_in(window, |_, mut cx| async move {
13390 match permalink_task.await {
13391 Ok(permalink) => {
13392 cx.update(|_, cx| {
13393 cx.open_url(permalink.as_ref());
13394 })
13395 .ok();
13396 }
13397 Err(err) => {
13398 let message = format!("Failed to open permalink: {err}");
13399
13400 Err::<(), anyhow::Error>(err).log_err();
13401
13402 if let Some(workspace) = workspace {
13403 workspace
13404 .update(&mut cx, |workspace, cx| {
13405 struct OpenPermalinkToLine;
13406
13407 workspace.show_toast(
13408 Toast::new(
13409 NotificationId::unique::<OpenPermalinkToLine>(),
13410 message,
13411 ),
13412 cx,
13413 )
13414 })
13415 .ok();
13416 }
13417 }
13418 }
13419 })
13420 .detach();
13421 }
13422
13423 pub fn insert_uuid_v4(
13424 &mut self,
13425 _: &InsertUuidV4,
13426 window: &mut Window,
13427 cx: &mut Context<Self>,
13428 ) {
13429 self.insert_uuid(UuidVersion::V4, window, cx);
13430 }
13431
13432 pub fn insert_uuid_v7(
13433 &mut self,
13434 _: &InsertUuidV7,
13435 window: &mut Window,
13436 cx: &mut Context<Self>,
13437 ) {
13438 self.insert_uuid(UuidVersion::V7, window, cx);
13439 }
13440
13441 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13442 self.transact(window, cx, |this, window, cx| {
13443 let edits = this
13444 .selections
13445 .all::<Point>(cx)
13446 .into_iter()
13447 .map(|selection| {
13448 let uuid = match version {
13449 UuidVersion::V4 => uuid::Uuid::new_v4(),
13450 UuidVersion::V7 => uuid::Uuid::now_v7(),
13451 };
13452
13453 (selection.range(), uuid.to_string())
13454 });
13455 this.edit(edits, cx);
13456 this.refresh_inline_completion(true, false, window, cx);
13457 });
13458 }
13459
13460 pub fn open_selections_in_multibuffer(
13461 &mut self,
13462 _: &OpenSelectionsInMultibuffer,
13463 window: &mut Window,
13464 cx: &mut Context<Self>,
13465 ) {
13466 let multibuffer = self.buffer.read(cx);
13467
13468 let Some(buffer) = multibuffer.as_singleton() else {
13469 return;
13470 };
13471
13472 let Some(workspace) = self.workspace() else {
13473 return;
13474 };
13475
13476 let locations = self
13477 .selections
13478 .disjoint_anchors()
13479 .iter()
13480 .map(|range| Location {
13481 buffer: buffer.clone(),
13482 range: range.start.text_anchor..range.end.text_anchor,
13483 })
13484 .collect::<Vec<_>>();
13485
13486 let title = multibuffer.title(cx).to_string();
13487
13488 cx.spawn_in(window, |_, mut cx| async move {
13489 workspace.update_in(&mut cx, |workspace, window, cx| {
13490 Self::open_locations_in_multibuffer(
13491 workspace,
13492 locations,
13493 format!("Selections for '{title}'"),
13494 false,
13495 MultibufferSelectionMode::All,
13496 window,
13497 cx,
13498 );
13499 })
13500 })
13501 .detach();
13502 }
13503
13504 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13505 /// last highlight added will be used.
13506 ///
13507 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13508 pub fn highlight_rows<T: 'static>(
13509 &mut self,
13510 range: Range<Anchor>,
13511 color: Hsla,
13512 should_autoscroll: bool,
13513 cx: &mut Context<Self>,
13514 ) {
13515 let snapshot = self.buffer().read(cx).snapshot(cx);
13516 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13517 let ix = row_highlights.binary_search_by(|highlight| {
13518 Ordering::Equal
13519 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13520 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13521 });
13522
13523 if let Err(mut ix) = ix {
13524 let index = post_inc(&mut self.highlight_order);
13525
13526 // If this range intersects with the preceding highlight, then merge it with
13527 // the preceding highlight. Otherwise insert a new highlight.
13528 let mut merged = false;
13529 if ix > 0 {
13530 let prev_highlight = &mut row_highlights[ix - 1];
13531 if prev_highlight
13532 .range
13533 .end
13534 .cmp(&range.start, &snapshot)
13535 .is_ge()
13536 {
13537 ix -= 1;
13538 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13539 prev_highlight.range.end = range.end;
13540 }
13541 merged = true;
13542 prev_highlight.index = index;
13543 prev_highlight.color = color;
13544 prev_highlight.should_autoscroll = should_autoscroll;
13545 }
13546 }
13547
13548 if !merged {
13549 row_highlights.insert(
13550 ix,
13551 RowHighlight {
13552 range: range.clone(),
13553 index,
13554 color,
13555 should_autoscroll,
13556 },
13557 );
13558 }
13559
13560 // If any of the following highlights intersect with this one, merge them.
13561 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13562 let highlight = &row_highlights[ix];
13563 if next_highlight
13564 .range
13565 .start
13566 .cmp(&highlight.range.end, &snapshot)
13567 .is_le()
13568 {
13569 if next_highlight
13570 .range
13571 .end
13572 .cmp(&highlight.range.end, &snapshot)
13573 .is_gt()
13574 {
13575 row_highlights[ix].range.end = next_highlight.range.end;
13576 }
13577 row_highlights.remove(ix + 1);
13578 } else {
13579 break;
13580 }
13581 }
13582 }
13583 }
13584
13585 /// Remove any highlighted row ranges of the given type that intersect the
13586 /// given ranges.
13587 pub fn remove_highlighted_rows<T: 'static>(
13588 &mut self,
13589 ranges_to_remove: Vec<Range<Anchor>>,
13590 cx: &mut Context<Self>,
13591 ) {
13592 let snapshot = self.buffer().read(cx).snapshot(cx);
13593 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13594 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13595 row_highlights.retain(|highlight| {
13596 while let Some(range_to_remove) = ranges_to_remove.peek() {
13597 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13598 Ordering::Less | Ordering::Equal => {
13599 ranges_to_remove.next();
13600 }
13601 Ordering::Greater => {
13602 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13603 Ordering::Less | Ordering::Equal => {
13604 return false;
13605 }
13606 Ordering::Greater => break,
13607 }
13608 }
13609 }
13610 }
13611
13612 true
13613 })
13614 }
13615
13616 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13617 pub fn clear_row_highlights<T: 'static>(&mut self) {
13618 self.highlighted_rows.remove(&TypeId::of::<T>());
13619 }
13620
13621 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13622 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13623 self.highlighted_rows
13624 .get(&TypeId::of::<T>())
13625 .map_or(&[] as &[_], |vec| vec.as_slice())
13626 .iter()
13627 .map(|highlight| (highlight.range.clone(), highlight.color))
13628 }
13629
13630 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13631 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13632 /// Allows to ignore certain kinds of highlights.
13633 pub fn highlighted_display_rows(
13634 &self,
13635 window: &mut Window,
13636 cx: &mut App,
13637 ) -> BTreeMap<DisplayRow, Background> {
13638 let snapshot = self.snapshot(window, cx);
13639 let mut used_highlight_orders = HashMap::default();
13640 self.highlighted_rows
13641 .iter()
13642 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13643 .fold(
13644 BTreeMap::<DisplayRow, Background>::new(),
13645 |mut unique_rows, highlight| {
13646 let start = highlight.range.start.to_display_point(&snapshot);
13647 let end = highlight.range.end.to_display_point(&snapshot);
13648 let start_row = start.row().0;
13649 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13650 && end.column() == 0
13651 {
13652 end.row().0.saturating_sub(1)
13653 } else {
13654 end.row().0
13655 };
13656 for row in start_row..=end_row {
13657 let used_index =
13658 used_highlight_orders.entry(row).or_insert(highlight.index);
13659 if highlight.index >= *used_index {
13660 *used_index = highlight.index;
13661 unique_rows.insert(DisplayRow(row), highlight.color.into());
13662 }
13663 }
13664 unique_rows
13665 },
13666 )
13667 }
13668
13669 pub fn highlighted_display_row_for_autoscroll(
13670 &self,
13671 snapshot: &DisplaySnapshot,
13672 ) -> Option<DisplayRow> {
13673 self.highlighted_rows
13674 .values()
13675 .flat_map(|highlighted_rows| highlighted_rows.iter())
13676 .filter_map(|highlight| {
13677 if highlight.should_autoscroll {
13678 Some(highlight.range.start.to_display_point(snapshot).row())
13679 } else {
13680 None
13681 }
13682 })
13683 .min()
13684 }
13685
13686 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13687 self.highlight_background::<SearchWithinRange>(
13688 ranges,
13689 |colors| colors.editor_document_highlight_read_background,
13690 cx,
13691 )
13692 }
13693
13694 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13695 self.breadcrumb_header = Some(new_header);
13696 }
13697
13698 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13699 self.clear_background_highlights::<SearchWithinRange>(cx);
13700 }
13701
13702 pub fn highlight_background<T: 'static>(
13703 &mut self,
13704 ranges: &[Range<Anchor>],
13705 color_fetcher: fn(&ThemeColors) -> Hsla,
13706 cx: &mut Context<Self>,
13707 ) {
13708 self.background_highlights
13709 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13710 self.scrollbar_marker_state.dirty = true;
13711 cx.notify();
13712 }
13713
13714 pub fn clear_background_highlights<T: 'static>(
13715 &mut self,
13716 cx: &mut Context<Self>,
13717 ) -> Option<BackgroundHighlight> {
13718 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13719 if !text_highlights.1.is_empty() {
13720 self.scrollbar_marker_state.dirty = true;
13721 cx.notify();
13722 }
13723 Some(text_highlights)
13724 }
13725
13726 pub fn highlight_gutter<T: 'static>(
13727 &mut self,
13728 ranges: &[Range<Anchor>],
13729 color_fetcher: fn(&App) -> Hsla,
13730 cx: &mut Context<Self>,
13731 ) {
13732 self.gutter_highlights
13733 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13734 cx.notify();
13735 }
13736
13737 pub fn clear_gutter_highlights<T: 'static>(
13738 &mut self,
13739 cx: &mut Context<Self>,
13740 ) -> Option<GutterHighlight> {
13741 cx.notify();
13742 self.gutter_highlights.remove(&TypeId::of::<T>())
13743 }
13744
13745 #[cfg(feature = "test-support")]
13746 pub fn all_text_background_highlights(
13747 &self,
13748 window: &mut Window,
13749 cx: &mut Context<Self>,
13750 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13751 let snapshot = self.snapshot(window, cx);
13752 let buffer = &snapshot.buffer_snapshot;
13753 let start = buffer.anchor_before(0);
13754 let end = buffer.anchor_after(buffer.len());
13755 let theme = cx.theme().colors();
13756 self.background_highlights_in_range(start..end, &snapshot, theme)
13757 }
13758
13759 #[cfg(feature = "test-support")]
13760 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13761 let snapshot = self.buffer().read(cx).snapshot(cx);
13762
13763 let highlights = self
13764 .background_highlights
13765 .get(&TypeId::of::<items::BufferSearchHighlights>());
13766
13767 if let Some((_color, ranges)) = highlights {
13768 ranges
13769 .iter()
13770 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13771 .collect_vec()
13772 } else {
13773 vec![]
13774 }
13775 }
13776
13777 fn document_highlights_for_position<'a>(
13778 &'a self,
13779 position: Anchor,
13780 buffer: &'a MultiBufferSnapshot,
13781 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13782 let read_highlights = self
13783 .background_highlights
13784 .get(&TypeId::of::<DocumentHighlightRead>())
13785 .map(|h| &h.1);
13786 let write_highlights = self
13787 .background_highlights
13788 .get(&TypeId::of::<DocumentHighlightWrite>())
13789 .map(|h| &h.1);
13790 let left_position = position.bias_left(buffer);
13791 let right_position = position.bias_right(buffer);
13792 read_highlights
13793 .into_iter()
13794 .chain(write_highlights)
13795 .flat_map(move |ranges| {
13796 let start_ix = match ranges.binary_search_by(|probe| {
13797 let cmp = probe.end.cmp(&left_position, buffer);
13798 if cmp.is_ge() {
13799 Ordering::Greater
13800 } else {
13801 Ordering::Less
13802 }
13803 }) {
13804 Ok(i) | Err(i) => i,
13805 };
13806
13807 ranges[start_ix..]
13808 .iter()
13809 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13810 })
13811 }
13812
13813 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13814 self.background_highlights
13815 .get(&TypeId::of::<T>())
13816 .map_or(false, |(_, highlights)| !highlights.is_empty())
13817 }
13818
13819 pub fn background_highlights_in_range(
13820 &self,
13821 search_range: Range<Anchor>,
13822 display_snapshot: &DisplaySnapshot,
13823 theme: &ThemeColors,
13824 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13825 let mut results = Vec::new();
13826 for (color_fetcher, ranges) in self.background_highlights.values() {
13827 let color = color_fetcher(theme);
13828 let start_ix = match ranges.binary_search_by(|probe| {
13829 let cmp = probe
13830 .end
13831 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13832 if cmp.is_gt() {
13833 Ordering::Greater
13834 } else {
13835 Ordering::Less
13836 }
13837 }) {
13838 Ok(i) | Err(i) => i,
13839 };
13840 for range in &ranges[start_ix..] {
13841 if range
13842 .start
13843 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13844 .is_ge()
13845 {
13846 break;
13847 }
13848
13849 let start = range.start.to_display_point(display_snapshot);
13850 let end = range.end.to_display_point(display_snapshot);
13851 results.push((start..end, color))
13852 }
13853 }
13854 results
13855 }
13856
13857 pub fn background_highlight_row_ranges<T: 'static>(
13858 &self,
13859 search_range: Range<Anchor>,
13860 display_snapshot: &DisplaySnapshot,
13861 count: usize,
13862 ) -> Vec<RangeInclusive<DisplayPoint>> {
13863 let mut results = Vec::new();
13864 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13865 return vec![];
13866 };
13867
13868 let start_ix = match ranges.binary_search_by(|probe| {
13869 let cmp = probe
13870 .end
13871 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13872 if cmp.is_gt() {
13873 Ordering::Greater
13874 } else {
13875 Ordering::Less
13876 }
13877 }) {
13878 Ok(i) | Err(i) => i,
13879 };
13880 let mut push_region = |start: Option<Point>, end: Option<Point>| {
13881 if let (Some(start_display), Some(end_display)) = (start, end) {
13882 results.push(
13883 start_display.to_display_point(display_snapshot)
13884 ..=end_display.to_display_point(display_snapshot),
13885 );
13886 }
13887 };
13888 let mut start_row: Option<Point> = None;
13889 let mut end_row: Option<Point> = None;
13890 if ranges.len() > count {
13891 return Vec::new();
13892 }
13893 for range in &ranges[start_ix..] {
13894 if range
13895 .start
13896 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13897 .is_ge()
13898 {
13899 break;
13900 }
13901 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13902 if let Some(current_row) = &end_row {
13903 if end.row == current_row.row {
13904 continue;
13905 }
13906 }
13907 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13908 if start_row.is_none() {
13909 assert_eq!(end_row, None);
13910 start_row = Some(start);
13911 end_row = Some(end);
13912 continue;
13913 }
13914 if let Some(current_end) = end_row.as_mut() {
13915 if start.row > current_end.row + 1 {
13916 push_region(start_row, end_row);
13917 start_row = Some(start);
13918 end_row = Some(end);
13919 } else {
13920 // Merge two hunks.
13921 *current_end = end;
13922 }
13923 } else {
13924 unreachable!();
13925 }
13926 }
13927 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13928 push_region(start_row, end_row);
13929 results
13930 }
13931
13932 pub fn gutter_highlights_in_range(
13933 &self,
13934 search_range: Range<Anchor>,
13935 display_snapshot: &DisplaySnapshot,
13936 cx: &App,
13937 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13938 let mut results = Vec::new();
13939 for (color_fetcher, ranges) in self.gutter_highlights.values() {
13940 let color = color_fetcher(cx);
13941 let start_ix = match ranges.binary_search_by(|probe| {
13942 let cmp = probe
13943 .end
13944 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13945 if cmp.is_gt() {
13946 Ordering::Greater
13947 } else {
13948 Ordering::Less
13949 }
13950 }) {
13951 Ok(i) | Err(i) => i,
13952 };
13953 for range in &ranges[start_ix..] {
13954 if range
13955 .start
13956 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13957 .is_ge()
13958 {
13959 break;
13960 }
13961
13962 let start = range.start.to_display_point(display_snapshot);
13963 let end = range.end.to_display_point(display_snapshot);
13964 results.push((start..end, color))
13965 }
13966 }
13967 results
13968 }
13969
13970 /// Get the text ranges corresponding to the redaction query
13971 pub fn redacted_ranges(
13972 &self,
13973 search_range: Range<Anchor>,
13974 display_snapshot: &DisplaySnapshot,
13975 cx: &App,
13976 ) -> Vec<Range<DisplayPoint>> {
13977 display_snapshot
13978 .buffer_snapshot
13979 .redacted_ranges(search_range, |file| {
13980 if let Some(file) = file {
13981 file.is_private()
13982 && EditorSettings::get(
13983 Some(SettingsLocation {
13984 worktree_id: file.worktree_id(cx),
13985 path: file.path().as_ref(),
13986 }),
13987 cx,
13988 )
13989 .redact_private_values
13990 } else {
13991 false
13992 }
13993 })
13994 .map(|range| {
13995 range.start.to_display_point(display_snapshot)
13996 ..range.end.to_display_point(display_snapshot)
13997 })
13998 .collect()
13999 }
14000
14001 pub fn highlight_text<T: 'static>(
14002 &mut self,
14003 ranges: Vec<Range<Anchor>>,
14004 style: HighlightStyle,
14005 cx: &mut Context<Self>,
14006 ) {
14007 self.display_map.update(cx, |map, _| {
14008 map.highlight_text(TypeId::of::<T>(), ranges, style)
14009 });
14010 cx.notify();
14011 }
14012
14013 pub(crate) fn highlight_inlays<T: 'static>(
14014 &mut self,
14015 highlights: Vec<InlayHighlight>,
14016 style: HighlightStyle,
14017 cx: &mut Context<Self>,
14018 ) {
14019 self.display_map.update(cx, |map, _| {
14020 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14021 });
14022 cx.notify();
14023 }
14024
14025 pub fn text_highlights<'a, T: 'static>(
14026 &'a self,
14027 cx: &'a App,
14028 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14029 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14030 }
14031
14032 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14033 let cleared = self
14034 .display_map
14035 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14036 if cleared {
14037 cx.notify();
14038 }
14039 }
14040
14041 pub fn previewing_edit_prediction_move(
14042 &mut self,
14043 ) -> Option<(Anchor, &mut EditPredictionPreview)> {
14044 if !self.edit_prediction_preview.is_active() {
14045 return None;
14046 };
14047
14048 self.active_inline_completion
14049 .as_ref()
14050 .and_then(|completion| match completion.completion {
14051 InlineCompletion::Move { target, .. } => {
14052 Some((target, &mut self.edit_prediction_preview))
14053 }
14054 _ => None,
14055 })
14056 }
14057
14058 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14059 (self.read_only(cx) || self.blink_manager.read(cx).visible())
14060 && self.focus_handle.is_focused(window)
14061 }
14062
14063 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14064 self.show_cursor_when_unfocused = is_enabled;
14065 cx.notify();
14066 }
14067
14068 pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
14069 self.project
14070 .as_ref()
14071 .map(|project| project.read(cx).lsp_store())
14072 }
14073
14074 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14075 cx.notify();
14076 }
14077
14078 fn on_buffer_event(
14079 &mut self,
14080 multibuffer: &Entity<MultiBuffer>,
14081 event: &multi_buffer::Event,
14082 window: &mut Window,
14083 cx: &mut Context<Self>,
14084 ) {
14085 match event {
14086 multi_buffer::Event::Edited {
14087 singleton_buffer_edited,
14088 edited_buffer: buffer_edited,
14089 } => {
14090 self.scrollbar_marker_state.dirty = true;
14091 self.active_indent_guides_state.dirty = true;
14092 self.refresh_active_diagnostics(cx);
14093 self.refresh_code_actions(window, cx);
14094 if self.has_active_inline_completion() {
14095 self.update_visible_inline_completion(window, cx);
14096 }
14097 if let Some(buffer) = buffer_edited {
14098 let buffer_id = buffer.read(cx).remote_id();
14099 if !self.registered_buffers.contains_key(&buffer_id) {
14100 if let Some(lsp_store) = self.lsp_store(cx) {
14101 lsp_store.update(cx, |lsp_store, cx| {
14102 self.registered_buffers.insert(
14103 buffer_id,
14104 lsp_store.register_buffer_with_language_servers(&buffer, cx),
14105 );
14106 })
14107 }
14108 }
14109 }
14110 cx.emit(EditorEvent::BufferEdited);
14111 cx.emit(SearchEvent::MatchesInvalidated);
14112 if *singleton_buffer_edited {
14113 if let Some(project) = &self.project {
14114 let project = project.read(cx);
14115 #[allow(clippy::mutable_key_type)]
14116 let languages_affected = multibuffer
14117 .read(cx)
14118 .all_buffers()
14119 .into_iter()
14120 .filter_map(|buffer| {
14121 let buffer = buffer.read(cx);
14122 let language = buffer.language()?;
14123 if project.is_local()
14124 && project
14125 .language_servers_for_local_buffer(buffer, cx)
14126 .count()
14127 == 0
14128 {
14129 None
14130 } else {
14131 Some(language)
14132 }
14133 })
14134 .cloned()
14135 .collect::<HashSet<_>>();
14136 if !languages_affected.is_empty() {
14137 self.refresh_inlay_hints(
14138 InlayHintRefreshReason::BufferEdited(languages_affected),
14139 cx,
14140 );
14141 }
14142 }
14143 }
14144
14145 let Some(project) = &self.project else { return };
14146 let (telemetry, is_via_ssh) = {
14147 let project = project.read(cx);
14148 let telemetry = project.client().telemetry().clone();
14149 let is_via_ssh = project.is_via_ssh();
14150 (telemetry, is_via_ssh)
14151 };
14152 refresh_linked_ranges(self, window, cx);
14153 telemetry.log_edit_event("editor", is_via_ssh);
14154 }
14155 multi_buffer::Event::ExcerptsAdded {
14156 buffer,
14157 predecessor,
14158 excerpts,
14159 } => {
14160 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14161 let buffer_id = buffer.read(cx).remote_id();
14162 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14163 if let Some(project) = &self.project {
14164 get_uncommitted_diff_for_buffer(
14165 project,
14166 [buffer.clone()],
14167 self.buffer.clone(),
14168 cx,
14169 );
14170 }
14171 }
14172 cx.emit(EditorEvent::ExcerptsAdded {
14173 buffer: buffer.clone(),
14174 predecessor: *predecessor,
14175 excerpts: excerpts.clone(),
14176 });
14177 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14178 }
14179 multi_buffer::Event::ExcerptsRemoved { ids } => {
14180 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14181 let buffer = self.buffer.read(cx);
14182 self.registered_buffers
14183 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14184 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14185 }
14186 multi_buffer::Event::ExcerptsEdited { ids } => {
14187 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14188 }
14189 multi_buffer::Event::ExcerptsExpanded { ids } => {
14190 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14191 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14192 }
14193 multi_buffer::Event::Reparsed(buffer_id) => {
14194 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14195
14196 cx.emit(EditorEvent::Reparsed(*buffer_id));
14197 }
14198 multi_buffer::Event::DiffHunksToggled => {
14199 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14200 }
14201 multi_buffer::Event::LanguageChanged(buffer_id) => {
14202 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14203 cx.emit(EditorEvent::Reparsed(*buffer_id));
14204 cx.notify();
14205 }
14206 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14207 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14208 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14209 cx.emit(EditorEvent::TitleChanged)
14210 }
14211 // multi_buffer::Event::DiffBaseChanged => {
14212 // self.scrollbar_marker_state.dirty = true;
14213 // cx.emit(EditorEvent::DiffBaseChanged);
14214 // cx.notify();
14215 // }
14216 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14217 multi_buffer::Event::DiagnosticsUpdated => {
14218 self.refresh_active_diagnostics(cx);
14219 self.scrollbar_marker_state.dirty = true;
14220 cx.notify();
14221 }
14222 _ => {}
14223 };
14224 }
14225
14226 fn on_display_map_changed(
14227 &mut self,
14228 _: Entity<DisplayMap>,
14229 _: &mut Window,
14230 cx: &mut Context<Self>,
14231 ) {
14232 cx.notify();
14233 }
14234
14235 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14236 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14237 self.refresh_inline_completion(true, false, window, cx);
14238 self.refresh_inlay_hints(
14239 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14240 self.selections.newest_anchor().head(),
14241 &self.buffer.read(cx).snapshot(cx),
14242 cx,
14243 )),
14244 cx,
14245 );
14246
14247 let old_cursor_shape = self.cursor_shape;
14248
14249 {
14250 let editor_settings = EditorSettings::get_global(cx);
14251 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14252 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14253 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14254 }
14255
14256 if old_cursor_shape != self.cursor_shape {
14257 cx.emit(EditorEvent::CursorShapeChanged);
14258 }
14259
14260 let project_settings = ProjectSettings::get_global(cx);
14261 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14262
14263 if self.mode == EditorMode::Full {
14264 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14265 if self.git_blame_inline_enabled != inline_blame_enabled {
14266 self.toggle_git_blame_inline_internal(false, window, cx);
14267 }
14268 }
14269
14270 cx.notify();
14271 }
14272
14273 pub fn set_searchable(&mut self, searchable: bool) {
14274 self.searchable = searchable;
14275 }
14276
14277 pub fn searchable(&self) -> bool {
14278 self.searchable
14279 }
14280
14281 fn open_proposed_changes_editor(
14282 &mut self,
14283 _: &OpenProposedChangesEditor,
14284 window: &mut Window,
14285 cx: &mut Context<Self>,
14286 ) {
14287 let Some(workspace) = self.workspace() else {
14288 cx.propagate();
14289 return;
14290 };
14291
14292 let selections = self.selections.all::<usize>(cx);
14293 let multi_buffer = self.buffer.read(cx);
14294 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14295 let mut new_selections_by_buffer = HashMap::default();
14296 for selection in selections {
14297 for (buffer, range, _) in
14298 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14299 {
14300 let mut range = range.to_point(buffer);
14301 range.start.column = 0;
14302 range.end.column = buffer.line_len(range.end.row);
14303 new_selections_by_buffer
14304 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14305 .or_insert(Vec::new())
14306 .push(range)
14307 }
14308 }
14309
14310 let proposed_changes_buffers = new_selections_by_buffer
14311 .into_iter()
14312 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14313 .collect::<Vec<_>>();
14314 let proposed_changes_editor = cx.new(|cx| {
14315 ProposedChangesEditor::new(
14316 "Proposed changes",
14317 proposed_changes_buffers,
14318 self.project.clone(),
14319 window,
14320 cx,
14321 )
14322 });
14323
14324 window.defer(cx, move |window, cx| {
14325 workspace.update(cx, |workspace, cx| {
14326 workspace.active_pane().update(cx, |pane, cx| {
14327 pane.add_item(
14328 Box::new(proposed_changes_editor),
14329 true,
14330 true,
14331 None,
14332 window,
14333 cx,
14334 );
14335 });
14336 });
14337 });
14338 }
14339
14340 pub fn open_excerpts_in_split(
14341 &mut self,
14342 _: &OpenExcerptsSplit,
14343 window: &mut Window,
14344 cx: &mut Context<Self>,
14345 ) {
14346 self.open_excerpts_common(None, true, window, cx)
14347 }
14348
14349 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14350 self.open_excerpts_common(None, false, window, cx)
14351 }
14352
14353 fn open_excerpts_common(
14354 &mut self,
14355 jump_data: Option<JumpData>,
14356 split: bool,
14357 window: &mut Window,
14358 cx: &mut Context<Self>,
14359 ) {
14360 let Some(workspace) = self.workspace() else {
14361 cx.propagate();
14362 return;
14363 };
14364
14365 if self.buffer.read(cx).is_singleton() {
14366 cx.propagate();
14367 return;
14368 }
14369
14370 let mut new_selections_by_buffer = HashMap::default();
14371 match &jump_data {
14372 Some(JumpData::MultiBufferPoint {
14373 excerpt_id,
14374 position,
14375 anchor,
14376 line_offset_from_top,
14377 }) => {
14378 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14379 if let Some(buffer) = multi_buffer_snapshot
14380 .buffer_id_for_excerpt(*excerpt_id)
14381 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14382 {
14383 let buffer_snapshot = buffer.read(cx).snapshot();
14384 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14385 language::ToPoint::to_point(anchor, &buffer_snapshot)
14386 } else {
14387 buffer_snapshot.clip_point(*position, Bias::Left)
14388 };
14389 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14390 new_selections_by_buffer.insert(
14391 buffer,
14392 (
14393 vec![jump_to_offset..jump_to_offset],
14394 Some(*line_offset_from_top),
14395 ),
14396 );
14397 }
14398 }
14399 Some(JumpData::MultiBufferRow {
14400 row,
14401 line_offset_from_top,
14402 }) => {
14403 let point = MultiBufferPoint::new(row.0, 0);
14404 if let Some((buffer, buffer_point, _)) =
14405 self.buffer.read(cx).point_to_buffer_point(point, cx)
14406 {
14407 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14408 new_selections_by_buffer
14409 .entry(buffer)
14410 .or_insert((Vec::new(), Some(*line_offset_from_top)))
14411 .0
14412 .push(buffer_offset..buffer_offset)
14413 }
14414 }
14415 None => {
14416 let selections = self.selections.all::<usize>(cx);
14417 let multi_buffer = self.buffer.read(cx);
14418 for selection in selections {
14419 for (buffer, mut range, _) in multi_buffer
14420 .snapshot(cx)
14421 .range_to_buffer_ranges(selection.range())
14422 {
14423 // When editing branch buffers, jump to the corresponding location
14424 // in their base buffer.
14425 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14426 let buffer = buffer_handle.read(cx);
14427 if let Some(base_buffer) = buffer.base_buffer() {
14428 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14429 buffer_handle = base_buffer;
14430 }
14431
14432 if selection.reversed {
14433 mem::swap(&mut range.start, &mut range.end);
14434 }
14435 new_selections_by_buffer
14436 .entry(buffer_handle)
14437 .or_insert((Vec::new(), None))
14438 .0
14439 .push(range)
14440 }
14441 }
14442 }
14443 }
14444
14445 if new_selections_by_buffer.is_empty() {
14446 return;
14447 }
14448
14449 // We defer the pane interaction because we ourselves are a workspace item
14450 // and activating a new item causes the pane to call a method on us reentrantly,
14451 // which panics if we're on the stack.
14452 window.defer(cx, move |window, cx| {
14453 workspace.update(cx, |workspace, cx| {
14454 let pane = if split {
14455 workspace.adjacent_pane(window, cx)
14456 } else {
14457 workspace.active_pane().clone()
14458 };
14459
14460 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14461 let editor = buffer
14462 .read(cx)
14463 .file()
14464 .is_none()
14465 .then(|| {
14466 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14467 // so `workspace.open_project_item` will never find them, always opening a new editor.
14468 // Instead, we try to activate the existing editor in the pane first.
14469 let (editor, pane_item_index) =
14470 pane.read(cx).items().enumerate().find_map(|(i, item)| {
14471 let editor = item.downcast::<Editor>()?;
14472 let singleton_buffer =
14473 editor.read(cx).buffer().read(cx).as_singleton()?;
14474 if singleton_buffer == buffer {
14475 Some((editor, i))
14476 } else {
14477 None
14478 }
14479 })?;
14480 pane.update(cx, |pane, cx| {
14481 pane.activate_item(pane_item_index, true, true, window, cx)
14482 });
14483 Some(editor)
14484 })
14485 .flatten()
14486 .unwrap_or_else(|| {
14487 workspace.open_project_item::<Self>(
14488 pane.clone(),
14489 buffer,
14490 true,
14491 true,
14492 window,
14493 cx,
14494 )
14495 });
14496
14497 editor.update(cx, |editor, cx| {
14498 let autoscroll = match scroll_offset {
14499 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14500 None => Autoscroll::newest(),
14501 };
14502 let nav_history = editor.nav_history.take();
14503 editor.change_selections(Some(autoscroll), window, cx, |s| {
14504 s.select_ranges(ranges);
14505 });
14506 editor.nav_history = nav_history;
14507 });
14508 }
14509 })
14510 });
14511 }
14512
14513 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14514 let snapshot = self.buffer.read(cx).read(cx);
14515 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14516 Some(
14517 ranges
14518 .iter()
14519 .map(move |range| {
14520 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14521 })
14522 .collect(),
14523 )
14524 }
14525
14526 fn selection_replacement_ranges(
14527 &self,
14528 range: Range<OffsetUtf16>,
14529 cx: &mut App,
14530 ) -> Vec<Range<OffsetUtf16>> {
14531 let selections = self.selections.all::<OffsetUtf16>(cx);
14532 let newest_selection = selections
14533 .iter()
14534 .max_by_key(|selection| selection.id)
14535 .unwrap();
14536 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14537 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14538 let snapshot = self.buffer.read(cx).read(cx);
14539 selections
14540 .into_iter()
14541 .map(|mut selection| {
14542 selection.start.0 =
14543 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14544 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14545 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14546 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14547 })
14548 .collect()
14549 }
14550
14551 fn report_editor_event(
14552 &self,
14553 event_type: &'static str,
14554 file_extension: Option<String>,
14555 cx: &App,
14556 ) {
14557 if cfg!(any(test, feature = "test-support")) {
14558 return;
14559 }
14560
14561 let Some(project) = &self.project else { return };
14562
14563 // If None, we are in a file without an extension
14564 let file = self
14565 .buffer
14566 .read(cx)
14567 .as_singleton()
14568 .and_then(|b| b.read(cx).file());
14569 let file_extension = file_extension.or(file
14570 .as_ref()
14571 .and_then(|file| Path::new(file.file_name(cx)).extension())
14572 .and_then(|e| e.to_str())
14573 .map(|a| a.to_string()));
14574
14575 let vim_mode = cx
14576 .global::<SettingsStore>()
14577 .raw_user_settings()
14578 .get("vim_mode")
14579 == Some(&serde_json::Value::Bool(true));
14580
14581 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14582 let copilot_enabled = edit_predictions_provider
14583 == language::language_settings::EditPredictionProvider::Copilot;
14584 let copilot_enabled_for_language = self
14585 .buffer
14586 .read(cx)
14587 .settings_at(0, cx)
14588 .show_edit_predictions;
14589
14590 let project = project.read(cx);
14591 telemetry::event!(
14592 event_type,
14593 file_extension,
14594 vim_mode,
14595 copilot_enabled,
14596 copilot_enabled_for_language,
14597 edit_predictions_provider,
14598 is_via_ssh = project.is_via_ssh(),
14599 );
14600 }
14601
14602 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14603 /// with each line being an array of {text, highlight} objects.
14604 fn copy_highlight_json(
14605 &mut self,
14606 _: &CopyHighlightJson,
14607 window: &mut Window,
14608 cx: &mut Context<Self>,
14609 ) {
14610 #[derive(Serialize)]
14611 struct Chunk<'a> {
14612 text: String,
14613 highlight: Option<&'a str>,
14614 }
14615
14616 let snapshot = self.buffer.read(cx).snapshot(cx);
14617 let range = self
14618 .selected_text_range(false, window, cx)
14619 .and_then(|selection| {
14620 if selection.range.is_empty() {
14621 None
14622 } else {
14623 Some(selection.range)
14624 }
14625 })
14626 .unwrap_or_else(|| 0..snapshot.len());
14627
14628 let chunks = snapshot.chunks(range, true);
14629 let mut lines = Vec::new();
14630 let mut line: VecDeque<Chunk> = VecDeque::new();
14631
14632 let Some(style) = self.style.as_ref() else {
14633 return;
14634 };
14635
14636 for chunk in chunks {
14637 let highlight = chunk
14638 .syntax_highlight_id
14639 .and_then(|id| id.name(&style.syntax));
14640 let mut chunk_lines = chunk.text.split('\n').peekable();
14641 while let Some(text) = chunk_lines.next() {
14642 let mut merged_with_last_token = false;
14643 if let Some(last_token) = line.back_mut() {
14644 if last_token.highlight == highlight {
14645 last_token.text.push_str(text);
14646 merged_with_last_token = true;
14647 }
14648 }
14649
14650 if !merged_with_last_token {
14651 line.push_back(Chunk {
14652 text: text.into(),
14653 highlight,
14654 });
14655 }
14656
14657 if chunk_lines.peek().is_some() {
14658 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14659 line.pop_front();
14660 }
14661 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14662 line.pop_back();
14663 }
14664
14665 lines.push(mem::take(&mut line));
14666 }
14667 }
14668 }
14669
14670 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14671 return;
14672 };
14673 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14674 }
14675
14676 pub fn open_context_menu(
14677 &mut self,
14678 _: &OpenContextMenu,
14679 window: &mut Window,
14680 cx: &mut Context<Self>,
14681 ) {
14682 self.request_autoscroll(Autoscroll::newest(), cx);
14683 let position = self.selections.newest_display(cx).start;
14684 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14685 }
14686
14687 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14688 &self.inlay_hint_cache
14689 }
14690
14691 pub fn replay_insert_event(
14692 &mut self,
14693 text: &str,
14694 relative_utf16_range: Option<Range<isize>>,
14695 window: &mut Window,
14696 cx: &mut Context<Self>,
14697 ) {
14698 if !self.input_enabled {
14699 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14700 return;
14701 }
14702 if let Some(relative_utf16_range) = relative_utf16_range {
14703 let selections = self.selections.all::<OffsetUtf16>(cx);
14704 self.change_selections(None, window, cx, |s| {
14705 let new_ranges = selections.into_iter().map(|range| {
14706 let start = OffsetUtf16(
14707 range
14708 .head()
14709 .0
14710 .saturating_add_signed(relative_utf16_range.start),
14711 );
14712 let end = OffsetUtf16(
14713 range
14714 .head()
14715 .0
14716 .saturating_add_signed(relative_utf16_range.end),
14717 );
14718 start..end
14719 });
14720 s.select_ranges(new_ranges);
14721 });
14722 }
14723
14724 self.handle_input(text, window, cx);
14725 }
14726
14727 pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14728 let Some(provider) = self.semantics_provider.as_ref() else {
14729 return false;
14730 };
14731
14732 let mut supports = false;
14733 self.buffer().read(cx).for_each_buffer(|buffer| {
14734 supports |= provider.supports_inlay_hints(buffer, cx);
14735 });
14736 supports
14737 }
14738
14739 pub fn is_focused(&self, window: &Window) -> bool {
14740 self.focus_handle.is_focused(window)
14741 }
14742
14743 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14744 cx.emit(EditorEvent::Focused);
14745
14746 if let Some(descendant) = self
14747 .last_focused_descendant
14748 .take()
14749 .and_then(|descendant| descendant.upgrade())
14750 {
14751 window.focus(&descendant);
14752 } else {
14753 if let Some(blame) = self.blame.as_ref() {
14754 blame.update(cx, GitBlame::focus)
14755 }
14756
14757 self.blink_manager.update(cx, BlinkManager::enable);
14758 self.show_cursor_names(window, cx);
14759 self.buffer.update(cx, |buffer, cx| {
14760 buffer.finalize_last_transaction(cx);
14761 if self.leader_peer_id.is_none() {
14762 buffer.set_active_selections(
14763 &self.selections.disjoint_anchors(),
14764 self.selections.line_mode,
14765 self.cursor_shape,
14766 cx,
14767 );
14768 }
14769 });
14770 }
14771 }
14772
14773 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14774 cx.emit(EditorEvent::FocusedIn)
14775 }
14776
14777 fn handle_focus_out(
14778 &mut self,
14779 event: FocusOutEvent,
14780 _window: &mut Window,
14781 _cx: &mut Context<Self>,
14782 ) {
14783 if event.blurred != self.focus_handle {
14784 self.last_focused_descendant = Some(event.blurred);
14785 }
14786 }
14787
14788 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14789 self.blink_manager.update(cx, BlinkManager::disable);
14790 self.buffer
14791 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14792
14793 if let Some(blame) = self.blame.as_ref() {
14794 blame.update(cx, GitBlame::blur)
14795 }
14796 if !self.hover_state.focused(window, cx) {
14797 hide_hover(self, cx);
14798 }
14799
14800 self.hide_context_menu(window, cx);
14801 cx.emit(EditorEvent::Blurred);
14802 cx.notify();
14803 }
14804
14805 pub fn register_action<A: Action>(
14806 &mut self,
14807 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14808 ) -> Subscription {
14809 let id = self.next_editor_action_id.post_inc();
14810 let listener = Arc::new(listener);
14811 self.editor_actions.borrow_mut().insert(
14812 id,
14813 Box::new(move |window, _| {
14814 let listener = listener.clone();
14815 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14816 let action = action.downcast_ref().unwrap();
14817 if phase == DispatchPhase::Bubble {
14818 listener(action, window, cx)
14819 }
14820 })
14821 }),
14822 );
14823
14824 let editor_actions = self.editor_actions.clone();
14825 Subscription::new(move || {
14826 editor_actions.borrow_mut().remove(&id);
14827 })
14828 }
14829
14830 pub fn file_header_size(&self) -> u32 {
14831 FILE_HEADER_HEIGHT
14832 }
14833
14834 pub fn revert(
14835 &mut self,
14836 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14837 window: &mut Window,
14838 cx: &mut Context<Self>,
14839 ) {
14840 self.buffer().update(cx, |multi_buffer, cx| {
14841 for (buffer_id, changes) in revert_changes {
14842 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14843 buffer.update(cx, |buffer, cx| {
14844 buffer.edit(
14845 changes.into_iter().map(|(range, text)| {
14846 (range, text.to_string().map(Arc::<str>::from))
14847 }),
14848 None,
14849 cx,
14850 );
14851 });
14852 }
14853 }
14854 });
14855 self.change_selections(None, window, cx, |selections| selections.refresh());
14856 }
14857
14858 pub fn to_pixel_point(
14859 &self,
14860 source: multi_buffer::Anchor,
14861 editor_snapshot: &EditorSnapshot,
14862 window: &mut Window,
14863 ) -> Option<gpui::Point<Pixels>> {
14864 let source_point = source.to_display_point(editor_snapshot);
14865 self.display_to_pixel_point(source_point, editor_snapshot, window)
14866 }
14867
14868 pub fn display_to_pixel_point(
14869 &self,
14870 source: DisplayPoint,
14871 editor_snapshot: &EditorSnapshot,
14872 window: &mut Window,
14873 ) -> Option<gpui::Point<Pixels>> {
14874 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14875 let text_layout_details = self.text_layout_details(window);
14876 let scroll_top = text_layout_details
14877 .scroll_anchor
14878 .scroll_position(editor_snapshot)
14879 .y;
14880
14881 if source.row().as_f32() < scroll_top.floor() {
14882 return None;
14883 }
14884 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14885 let source_y = line_height * (source.row().as_f32() - scroll_top);
14886 Some(gpui::Point::new(source_x, source_y))
14887 }
14888
14889 pub fn has_visible_completions_menu(&self) -> bool {
14890 !self.edit_prediction_preview.is_active()
14891 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14892 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14893 })
14894 }
14895
14896 pub fn register_addon<T: Addon>(&mut self, instance: T) {
14897 self.addons
14898 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14899 }
14900
14901 pub fn unregister_addon<T: Addon>(&mut self) {
14902 self.addons.remove(&std::any::TypeId::of::<T>());
14903 }
14904
14905 pub fn addon<T: Addon>(&self) -> Option<&T> {
14906 let type_id = std::any::TypeId::of::<T>();
14907 self.addons
14908 .get(&type_id)
14909 .and_then(|item| item.to_any().downcast_ref::<T>())
14910 }
14911
14912 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14913 let text_layout_details = self.text_layout_details(window);
14914 let style = &text_layout_details.editor_style;
14915 let font_id = window.text_system().resolve_font(&style.text.font());
14916 let font_size = style.text.font_size.to_pixels(window.rem_size());
14917 let line_height = style.text.line_height_in_pixels(window.rem_size());
14918 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14919
14920 gpui::Size::new(em_width, line_height)
14921 }
14922}
14923
14924fn get_uncommitted_diff_for_buffer(
14925 project: &Entity<Project>,
14926 buffers: impl IntoIterator<Item = Entity<Buffer>>,
14927 buffer: Entity<MultiBuffer>,
14928 cx: &mut App,
14929) {
14930 let mut tasks = Vec::new();
14931 project.update(cx, |project, cx| {
14932 for buffer in buffers {
14933 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14934 }
14935 });
14936 cx.spawn(|mut cx| async move {
14937 let diffs = futures::future::join_all(tasks).await;
14938 buffer
14939 .update(&mut cx, |buffer, cx| {
14940 for diff in diffs.into_iter().flatten() {
14941 buffer.add_diff(diff, cx);
14942 }
14943 })
14944 .ok();
14945 })
14946 .detach();
14947}
14948
14949fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14950 let tab_size = tab_size.get() as usize;
14951 let mut width = offset;
14952
14953 for ch in text.chars() {
14954 width += if ch == '\t' {
14955 tab_size - (width % tab_size)
14956 } else {
14957 1
14958 };
14959 }
14960
14961 width - offset
14962}
14963
14964#[cfg(test)]
14965mod tests {
14966 use super::*;
14967
14968 #[test]
14969 fn test_string_size_with_expanded_tabs() {
14970 let nz = |val| NonZeroU32::new(val).unwrap();
14971 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14972 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14973 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14974 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14975 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14976 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14977 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14978 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14979 }
14980}
14981
14982/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14983struct WordBreakingTokenizer<'a> {
14984 input: &'a str,
14985}
14986
14987impl<'a> WordBreakingTokenizer<'a> {
14988 fn new(input: &'a str) -> Self {
14989 Self { input }
14990 }
14991}
14992
14993fn is_char_ideographic(ch: char) -> bool {
14994 use unicode_script::Script::*;
14995 use unicode_script::UnicodeScript;
14996 matches!(ch.script(), Han | Tangut | Yi)
14997}
14998
14999fn is_grapheme_ideographic(text: &str) -> bool {
15000 text.chars().any(is_char_ideographic)
15001}
15002
15003fn is_grapheme_whitespace(text: &str) -> bool {
15004 text.chars().any(|x| x.is_whitespace())
15005}
15006
15007fn should_stay_with_preceding_ideograph(text: &str) -> bool {
15008 text.chars().next().map_or(false, |ch| {
15009 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
15010 })
15011}
15012
15013#[derive(PartialEq, Eq, Debug, Clone, Copy)]
15014struct WordBreakToken<'a> {
15015 token: &'a str,
15016 grapheme_len: usize,
15017 is_whitespace: bool,
15018}
15019
15020impl<'a> Iterator for WordBreakingTokenizer<'a> {
15021 /// Yields a span, the count of graphemes in the token, and whether it was
15022 /// whitespace. Note that it also breaks at word boundaries.
15023 type Item = WordBreakToken<'a>;
15024
15025 fn next(&mut self) -> Option<Self::Item> {
15026 use unicode_segmentation::UnicodeSegmentation;
15027 if self.input.is_empty() {
15028 return None;
15029 }
15030
15031 let mut iter = self.input.graphemes(true).peekable();
15032 let mut offset = 0;
15033 let mut graphemes = 0;
15034 if let Some(first_grapheme) = iter.next() {
15035 let is_whitespace = is_grapheme_whitespace(first_grapheme);
15036 offset += first_grapheme.len();
15037 graphemes += 1;
15038 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15039 if let Some(grapheme) = iter.peek().copied() {
15040 if should_stay_with_preceding_ideograph(grapheme) {
15041 offset += grapheme.len();
15042 graphemes += 1;
15043 }
15044 }
15045 } else {
15046 let mut words = self.input[offset..].split_word_bound_indices().peekable();
15047 let mut next_word_bound = words.peek().copied();
15048 if next_word_bound.map_or(false, |(i, _)| i == 0) {
15049 next_word_bound = words.next();
15050 }
15051 while let Some(grapheme) = iter.peek().copied() {
15052 if next_word_bound.map_or(false, |(i, _)| i == offset) {
15053 break;
15054 };
15055 if is_grapheme_whitespace(grapheme) != is_whitespace {
15056 break;
15057 };
15058 offset += grapheme.len();
15059 graphemes += 1;
15060 iter.next();
15061 }
15062 }
15063 let token = &self.input[..offset];
15064 self.input = &self.input[offset..];
15065 if is_whitespace {
15066 Some(WordBreakToken {
15067 token: " ",
15068 grapheme_len: 1,
15069 is_whitespace: true,
15070 })
15071 } else {
15072 Some(WordBreakToken {
15073 token,
15074 grapheme_len: graphemes,
15075 is_whitespace: false,
15076 })
15077 }
15078 } else {
15079 None
15080 }
15081 }
15082}
15083
15084#[test]
15085fn test_word_breaking_tokenizer() {
15086 let tests: &[(&str, &[(&str, usize, bool)])] = &[
15087 ("", &[]),
15088 (" ", &[(" ", 1, true)]),
15089 ("Ʒ", &[("Ʒ", 1, false)]),
15090 ("Ǽ", &[("Ǽ", 1, false)]),
15091 ("⋑", &[("⋑", 1, false)]),
15092 ("⋑⋑", &[("⋑⋑", 2, false)]),
15093 (
15094 "原理,进而",
15095 &[
15096 ("原", 1, false),
15097 ("理,", 2, false),
15098 ("进", 1, false),
15099 ("而", 1, false),
15100 ],
15101 ),
15102 (
15103 "hello world",
15104 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15105 ),
15106 (
15107 "hello, world",
15108 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15109 ),
15110 (
15111 " hello world",
15112 &[
15113 (" ", 1, true),
15114 ("hello", 5, false),
15115 (" ", 1, true),
15116 ("world", 5, false),
15117 ],
15118 ),
15119 (
15120 "这是什么 \n 钢笔",
15121 &[
15122 ("这", 1, false),
15123 ("是", 1, false),
15124 ("什", 1, false),
15125 ("么", 1, false),
15126 (" ", 1, true),
15127 ("钢", 1, false),
15128 ("笔", 1, false),
15129 ],
15130 ),
15131 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15132 ];
15133
15134 for (input, result) in tests {
15135 assert_eq!(
15136 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15137 result
15138 .iter()
15139 .copied()
15140 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15141 token,
15142 grapheme_len,
15143 is_whitespace,
15144 })
15145 .collect::<Vec<_>>()
15146 );
15147 }
15148}
15149
15150fn wrap_with_prefix(
15151 line_prefix: String,
15152 unwrapped_text: String,
15153 wrap_column: usize,
15154 tab_size: NonZeroU32,
15155) -> String {
15156 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15157 let mut wrapped_text = String::new();
15158 let mut current_line = line_prefix.clone();
15159
15160 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15161 let mut current_line_len = line_prefix_len;
15162 for WordBreakToken {
15163 token,
15164 grapheme_len,
15165 is_whitespace,
15166 } in tokenizer
15167 {
15168 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15169 wrapped_text.push_str(current_line.trim_end());
15170 wrapped_text.push('\n');
15171 current_line.truncate(line_prefix.len());
15172 current_line_len = line_prefix_len;
15173 if !is_whitespace {
15174 current_line.push_str(token);
15175 current_line_len += grapheme_len;
15176 }
15177 } else if !is_whitespace {
15178 current_line.push_str(token);
15179 current_line_len += grapheme_len;
15180 } else if current_line_len != line_prefix_len {
15181 current_line.push(' ');
15182 current_line_len += 1;
15183 }
15184 }
15185
15186 if !current_line.is_empty() {
15187 wrapped_text.push_str(¤t_line);
15188 }
15189 wrapped_text
15190}
15191
15192#[test]
15193fn test_wrap_with_prefix() {
15194 assert_eq!(
15195 wrap_with_prefix(
15196 "# ".to_string(),
15197 "abcdefg".to_string(),
15198 4,
15199 NonZeroU32::new(4).unwrap()
15200 ),
15201 "# abcdefg"
15202 );
15203 assert_eq!(
15204 wrap_with_prefix(
15205 "".to_string(),
15206 "\thello world".to_string(),
15207 8,
15208 NonZeroU32::new(4).unwrap()
15209 ),
15210 "hello\nworld"
15211 );
15212 assert_eq!(
15213 wrap_with_prefix(
15214 "// ".to_string(),
15215 "xx \nyy zz aa bb cc".to_string(),
15216 12,
15217 NonZeroU32::new(4).unwrap()
15218 ),
15219 "// xx yy zz\n// aa bb cc"
15220 );
15221 assert_eq!(
15222 wrap_with_prefix(
15223 String::new(),
15224 "这是什么 \n 钢笔".to_string(),
15225 3,
15226 NonZeroU32::new(4).unwrap()
15227 ),
15228 "这是什\n么 钢\n笔"
15229 );
15230}
15231
15232pub trait CollaborationHub {
15233 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15234 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15235 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15236}
15237
15238impl CollaborationHub for Entity<Project> {
15239 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15240 self.read(cx).collaborators()
15241 }
15242
15243 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15244 self.read(cx).user_store().read(cx).participant_indices()
15245 }
15246
15247 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15248 let this = self.read(cx);
15249 let user_ids = this.collaborators().values().map(|c| c.user_id);
15250 this.user_store().read_with(cx, |user_store, cx| {
15251 user_store.participant_names(user_ids, cx)
15252 })
15253 }
15254}
15255
15256pub trait SemanticsProvider {
15257 fn hover(
15258 &self,
15259 buffer: &Entity<Buffer>,
15260 position: text::Anchor,
15261 cx: &mut App,
15262 ) -> Option<Task<Vec<project::Hover>>>;
15263
15264 fn inlay_hints(
15265 &self,
15266 buffer_handle: Entity<Buffer>,
15267 range: Range<text::Anchor>,
15268 cx: &mut App,
15269 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15270
15271 fn resolve_inlay_hint(
15272 &self,
15273 hint: InlayHint,
15274 buffer_handle: Entity<Buffer>,
15275 server_id: LanguageServerId,
15276 cx: &mut App,
15277 ) -> Option<Task<anyhow::Result<InlayHint>>>;
15278
15279 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
15280
15281 fn document_highlights(
15282 &self,
15283 buffer: &Entity<Buffer>,
15284 position: text::Anchor,
15285 cx: &mut App,
15286 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15287
15288 fn definitions(
15289 &self,
15290 buffer: &Entity<Buffer>,
15291 position: text::Anchor,
15292 kind: GotoDefinitionKind,
15293 cx: &mut App,
15294 ) -> Option<Task<Result<Vec<LocationLink>>>>;
15295
15296 fn range_for_rename(
15297 &self,
15298 buffer: &Entity<Buffer>,
15299 position: text::Anchor,
15300 cx: &mut App,
15301 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15302
15303 fn perform_rename(
15304 &self,
15305 buffer: &Entity<Buffer>,
15306 position: text::Anchor,
15307 new_name: String,
15308 cx: &mut App,
15309 ) -> Option<Task<Result<ProjectTransaction>>>;
15310}
15311
15312pub trait CompletionProvider {
15313 fn completions(
15314 &self,
15315 buffer: &Entity<Buffer>,
15316 buffer_position: text::Anchor,
15317 trigger: CompletionContext,
15318 window: &mut Window,
15319 cx: &mut Context<Editor>,
15320 ) -> Task<Result<Vec<Completion>>>;
15321
15322 fn resolve_completions(
15323 &self,
15324 buffer: Entity<Buffer>,
15325 completion_indices: Vec<usize>,
15326 completions: Rc<RefCell<Box<[Completion]>>>,
15327 cx: &mut Context<Editor>,
15328 ) -> Task<Result<bool>>;
15329
15330 fn apply_additional_edits_for_completion(
15331 &self,
15332 _buffer: Entity<Buffer>,
15333 _completions: Rc<RefCell<Box<[Completion]>>>,
15334 _completion_index: usize,
15335 _push_to_history: bool,
15336 _cx: &mut Context<Editor>,
15337 ) -> Task<Result<Option<language::Transaction>>> {
15338 Task::ready(Ok(None))
15339 }
15340
15341 fn is_completion_trigger(
15342 &self,
15343 buffer: &Entity<Buffer>,
15344 position: language::Anchor,
15345 text: &str,
15346 trigger_in_words: bool,
15347 cx: &mut Context<Editor>,
15348 ) -> bool;
15349
15350 fn sort_completions(&self) -> bool {
15351 true
15352 }
15353}
15354
15355pub trait CodeActionProvider {
15356 fn id(&self) -> Arc<str>;
15357
15358 fn code_actions(
15359 &self,
15360 buffer: &Entity<Buffer>,
15361 range: Range<text::Anchor>,
15362 window: &mut Window,
15363 cx: &mut App,
15364 ) -> Task<Result<Vec<CodeAction>>>;
15365
15366 fn apply_code_action(
15367 &self,
15368 buffer_handle: Entity<Buffer>,
15369 action: CodeAction,
15370 excerpt_id: ExcerptId,
15371 push_to_history: bool,
15372 window: &mut Window,
15373 cx: &mut App,
15374 ) -> Task<Result<ProjectTransaction>>;
15375}
15376
15377impl CodeActionProvider for Entity<Project> {
15378 fn id(&self) -> Arc<str> {
15379 "project".into()
15380 }
15381
15382 fn code_actions(
15383 &self,
15384 buffer: &Entity<Buffer>,
15385 range: Range<text::Anchor>,
15386 _window: &mut Window,
15387 cx: &mut App,
15388 ) -> Task<Result<Vec<CodeAction>>> {
15389 self.update(cx, |project, cx| {
15390 project.code_actions(buffer, range, None, cx)
15391 })
15392 }
15393
15394 fn apply_code_action(
15395 &self,
15396 buffer_handle: Entity<Buffer>,
15397 action: CodeAction,
15398 _excerpt_id: ExcerptId,
15399 push_to_history: bool,
15400 _window: &mut Window,
15401 cx: &mut App,
15402 ) -> Task<Result<ProjectTransaction>> {
15403 self.update(cx, |project, cx| {
15404 project.apply_code_action(buffer_handle, action, push_to_history, cx)
15405 })
15406 }
15407}
15408
15409fn snippet_completions(
15410 project: &Project,
15411 buffer: &Entity<Buffer>,
15412 buffer_position: text::Anchor,
15413 cx: &mut App,
15414) -> Task<Result<Vec<Completion>>> {
15415 let language = buffer.read(cx).language_at(buffer_position);
15416 let language_name = language.as_ref().map(|language| language.lsp_id());
15417 let snippet_store = project.snippets().read(cx);
15418 let snippets = snippet_store.snippets_for(language_name, cx);
15419
15420 if snippets.is_empty() {
15421 return Task::ready(Ok(vec![]));
15422 }
15423 let snapshot = buffer.read(cx).text_snapshot();
15424 let chars: String = snapshot
15425 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15426 .collect();
15427
15428 let scope = language.map(|language| language.default_scope());
15429 let executor = cx.background_executor().clone();
15430
15431 cx.background_executor().spawn(async move {
15432 let classifier = CharClassifier::new(scope).for_completion(true);
15433 let mut last_word = chars
15434 .chars()
15435 .take_while(|c| classifier.is_word(*c))
15436 .collect::<String>();
15437 last_word = last_word.chars().rev().collect();
15438
15439 if last_word.is_empty() {
15440 return Ok(vec![]);
15441 }
15442
15443 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15444 let to_lsp = |point: &text::Anchor| {
15445 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15446 point_to_lsp(end)
15447 };
15448 let lsp_end = to_lsp(&buffer_position);
15449
15450 let candidates = snippets
15451 .iter()
15452 .enumerate()
15453 .flat_map(|(ix, snippet)| {
15454 snippet
15455 .prefix
15456 .iter()
15457 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15458 })
15459 .collect::<Vec<StringMatchCandidate>>();
15460
15461 let mut matches = fuzzy::match_strings(
15462 &candidates,
15463 &last_word,
15464 last_word.chars().any(|c| c.is_uppercase()),
15465 100,
15466 &Default::default(),
15467 executor,
15468 )
15469 .await;
15470
15471 // Remove all candidates where the query's start does not match the start of any word in the candidate
15472 if let Some(query_start) = last_word.chars().next() {
15473 matches.retain(|string_match| {
15474 split_words(&string_match.string).any(|word| {
15475 // Check that the first codepoint of the word as lowercase matches the first
15476 // codepoint of the query as lowercase
15477 word.chars()
15478 .flat_map(|codepoint| codepoint.to_lowercase())
15479 .zip(query_start.to_lowercase())
15480 .all(|(word_cp, query_cp)| word_cp == query_cp)
15481 })
15482 });
15483 }
15484
15485 let matched_strings = matches
15486 .into_iter()
15487 .map(|m| m.string)
15488 .collect::<HashSet<_>>();
15489
15490 let result: Vec<Completion> = snippets
15491 .into_iter()
15492 .filter_map(|snippet| {
15493 let matching_prefix = snippet
15494 .prefix
15495 .iter()
15496 .find(|prefix| matched_strings.contains(*prefix))?;
15497 let start = as_offset - last_word.len();
15498 let start = snapshot.anchor_before(start);
15499 let range = start..buffer_position;
15500 let lsp_start = to_lsp(&start);
15501 let lsp_range = lsp::Range {
15502 start: lsp_start,
15503 end: lsp_end,
15504 };
15505 Some(Completion {
15506 old_range: range,
15507 new_text: snippet.body.clone(),
15508 resolved: false,
15509 label: CodeLabel {
15510 text: matching_prefix.clone(),
15511 runs: vec![],
15512 filter_range: 0..matching_prefix.len(),
15513 },
15514 server_id: LanguageServerId(usize::MAX),
15515 documentation: snippet
15516 .description
15517 .clone()
15518 .map(CompletionDocumentation::SingleLine),
15519 lsp_completion: lsp::CompletionItem {
15520 label: snippet.prefix.first().unwrap().clone(),
15521 kind: Some(CompletionItemKind::SNIPPET),
15522 label_details: snippet.description.as_ref().map(|description| {
15523 lsp::CompletionItemLabelDetails {
15524 detail: Some(description.clone()),
15525 description: None,
15526 }
15527 }),
15528 insert_text_format: Some(InsertTextFormat::SNIPPET),
15529 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15530 lsp::InsertReplaceEdit {
15531 new_text: snippet.body.clone(),
15532 insert: lsp_range,
15533 replace: lsp_range,
15534 },
15535 )),
15536 filter_text: Some(snippet.body.clone()),
15537 sort_text: Some(char::MAX.to_string()),
15538 ..Default::default()
15539 },
15540 confirm: None,
15541 })
15542 })
15543 .collect();
15544
15545 Ok(result)
15546 })
15547}
15548
15549impl CompletionProvider for Entity<Project> {
15550 fn completions(
15551 &self,
15552 buffer: &Entity<Buffer>,
15553 buffer_position: text::Anchor,
15554 options: CompletionContext,
15555 _window: &mut Window,
15556 cx: &mut Context<Editor>,
15557 ) -> Task<Result<Vec<Completion>>> {
15558 self.update(cx, |project, cx| {
15559 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15560 let project_completions = project.completions(buffer, buffer_position, options, cx);
15561 cx.background_executor().spawn(async move {
15562 let mut completions = project_completions.await?;
15563 let snippets_completions = snippets.await?;
15564 completions.extend(snippets_completions);
15565 Ok(completions)
15566 })
15567 })
15568 }
15569
15570 fn resolve_completions(
15571 &self,
15572 buffer: Entity<Buffer>,
15573 completion_indices: Vec<usize>,
15574 completions: Rc<RefCell<Box<[Completion]>>>,
15575 cx: &mut Context<Editor>,
15576 ) -> Task<Result<bool>> {
15577 self.update(cx, |project, cx| {
15578 project.lsp_store().update(cx, |lsp_store, cx| {
15579 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15580 })
15581 })
15582 }
15583
15584 fn apply_additional_edits_for_completion(
15585 &self,
15586 buffer: Entity<Buffer>,
15587 completions: Rc<RefCell<Box<[Completion]>>>,
15588 completion_index: usize,
15589 push_to_history: bool,
15590 cx: &mut Context<Editor>,
15591 ) -> Task<Result<Option<language::Transaction>>> {
15592 self.update(cx, |project, cx| {
15593 project.lsp_store().update(cx, |lsp_store, cx| {
15594 lsp_store.apply_additional_edits_for_completion(
15595 buffer,
15596 completions,
15597 completion_index,
15598 push_to_history,
15599 cx,
15600 )
15601 })
15602 })
15603 }
15604
15605 fn is_completion_trigger(
15606 &self,
15607 buffer: &Entity<Buffer>,
15608 position: language::Anchor,
15609 text: &str,
15610 trigger_in_words: bool,
15611 cx: &mut Context<Editor>,
15612 ) -> bool {
15613 let mut chars = text.chars();
15614 let char = if let Some(char) = chars.next() {
15615 char
15616 } else {
15617 return false;
15618 };
15619 if chars.next().is_some() {
15620 return false;
15621 }
15622
15623 let buffer = buffer.read(cx);
15624 let snapshot = buffer.snapshot();
15625 if !snapshot.settings_at(position, cx).show_completions_on_input {
15626 return false;
15627 }
15628 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15629 if trigger_in_words && classifier.is_word(char) {
15630 return true;
15631 }
15632
15633 buffer.completion_triggers().contains(text)
15634 }
15635}
15636
15637impl SemanticsProvider for Entity<Project> {
15638 fn hover(
15639 &self,
15640 buffer: &Entity<Buffer>,
15641 position: text::Anchor,
15642 cx: &mut App,
15643 ) -> Option<Task<Vec<project::Hover>>> {
15644 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15645 }
15646
15647 fn document_highlights(
15648 &self,
15649 buffer: &Entity<Buffer>,
15650 position: text::Anchor,
15651 cx: &mut App,
15652 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15653 Some(self.update(cx, |project, cx| {
15654 project.document_highlights(buffer, position, cx)
15655 }))
15656 }
15657
15658 fn definitions(
15659 &self,
15660 buffer: &Entity<Buffer>,
15661 position: text::Anchor,
15662 kind: GotoDefinitionKind,
15663 cx: &mut App,
15664 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15665 Some(self.update(cx, |project, cx| match kind {
15666 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15667 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15668 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15669 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15670 }))
15671 }
15672
15673 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15674 // TODO: make this work for remote projects
15675 self.read(cx)
15676 .language_servers_for_local_buffer(buffer.read(cx), cx)
15677 .any(
15678 |(_, server)| match server.capabilities().inlay_hint_provider {
15679 Some(lsp::OneOf::Left(enabled)) => enabled,
15680 Some(lsp::OneOf::Right(_)) => true,
15681 None => false,
15682 },
15683 )
15684 }
15685
15686 fn inlay_hints(
15687 &self,
15688 buffer_handle: Entity<Buffer>,
15689 range: Range<text::Anchor>,
15690 cx: &mut App,
15691 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15692 Some(self.update(cx, |project, cx| {
15693 project.inlay_hints(buffer_handle, range, cx)
15694 }))
15695 }
15696
15697 fn resolve_inlay_hint(
15698 &self,
15699 hint: InlayHint,
15700 buffer_handle: Entity<Buffer>,
15701 server_id: LanguageServerId,
15702 cx: &mut App,
15703 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15704 Some(self.update(cx, |project, cx| {
15705 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15706 }))
15707 }
15708
15709 fn range_for_rename(
15710 &self,
15711 buffer: &Entity<Buffer>,
15712 position: text::Anchor,
15713 cx: &mut App,
15714 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15715 Some(self.update(cx, |project, cx| {
15716 let buffer = buffer.clone();
15717 let task = project.prepare_rename(buffer.clone(), position, cx);
15718 cx.spawn(|_, mut cx| async move {
15719 Ok(match task.await? {
15720 PrepareRenameResponse::Success(range) => Some(range),
15721 PrepareRenameResponse::InvalidPosition => None,
15722 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15723 // Fallback on using TreeSitter info to determine identifier range
15724 buffer.update(&mut cx, |buffer, _| {
15725 let snapshot = buffer.snapshot();
15726 let (range, kind) = snapshot.surrounding_word(position);
15727 if kind != Some(CharKind::Word) {
15728 return None;
15729 }
15730 Some(
15731 snapshot.anchor_before(range.start)
15732 ..snapshot.anchor_after(range.end),
15733 )
15734 })?
15735 }
15736 })
15737 })
15738 }))
15739 }
15740
15741 fn perform_rename(
15742 &self,
15743 buffer: &Entity<Buffer>,
15744 position: text::Anchor,
15745 new_name: String,
15746 cx: &mut App,
15747 ) -> Option<Task<Result<ProjectTransaction>>> {
15748 Some(self.update(cx, |project, cx| {
15749 project.perform_rename(buffer.clone(), position, new_name, cx)
15750 }))
15751 }
15752}
15753
15754fn inlay_hint_settings(
15755 location: Anchor,
15756 snapshot: &MultiBufferSnapshot,
15757 cx: &mut Context<Editor>,
15758) -> InlayHintSettings {
15759 let file = snapshot.file_at(location);
15760 let language = snapshot.language_at(location).map(|l| l.name());
15761 language_settings(language, file, cx).inlay_hints
15762}
15763
15764fn consume_contiguous_rows(
15765 contiguous_row_selections: &mut Vec<Selection<Point>>,
15766 selection: &Selection<Point>,
15767 display_map: &DisplaySnapshot,
15768 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15769) -> (MultiBufferRow, MultiBufferRow) {
15770 contiguous_row_selections.push(selection.clone());
15771 let start_row = MultiBufferRow(selection.start.row);
15772 let mut end_row = ending_row(selection, display_map);
15773
15774 while let Some(next_selection) = selections.peek() {
15775 if next_selection.start.row <= end_row.0 {
15776 end_row = ending_row(next_selection, display_map);
15777 contiguous_row_selections.push(selections.next().unwrap().clone());
15778 } else {
15779 break;
15780 }
15781 }
15782 (start_row, end_row)
15783}
15784
15785fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15786 if next_selection.end.column > 0 || next_selection.is_empty() {
15787 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15788 } else {
15789 MultiBufferRow(next_selection.end.row)
15790 }
15791}
15792
15793impl EditorSnapshot {
15794 pub fn remote_selections_in_range<'a>(
15795 &'a self,
15796 range: &'a Range<Anchor>,
15797 collaboration_hub: &dyn CollaborationHub,
15798 cx: &'a App,
15799 ) -> impl 'a + Iterator<Item = RemoteSelection> {
15800 let participant_names = collaboration_hub.user_names(cx);
15801 let participant_indices = collaboration_hub.user_participant_indices(cx);
15802 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15803 let collaborators_by_replica_id = collaborators_by_peer_id
15804 .iter()
15805 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15806 .collect::<HashMap<_, _>>();
15807 self.buffer_snapshot
15808 .selections_in_range(range, false)
15809 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15810 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15811 let participant_index = participant_indices.get(&collaborator.user_id).copied();
15812 let user_name = participant_names.get(&collaborator.user_id).cloned();
15813 Some(RemoteSelection {
15814 replica_id,
15815 selection,
15816 cursor_shape,
15817 line_mode,
15818 participant_index,
15819 peer_id: collaborator.peer_id,
15820 user_name,
15821 })
15822 })
15823 }
15824
15825 pub fn hunks_for_ranges(
15826 &self,
15827 ranges: impl Iterator<Item = Range<Point>>,
15828 ) -> Vec<MultiBufferDiffHunk> {
15829 let mut hunks = Vec::new();
15830 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15831 HashMap::default();
15832 for query_range in ranges {
15833 let query_rows =
15834 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15835 for hunk in self.buffer_snapshot.diff_hunks_in_range(
15836 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15837 ) {
15838 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15839 // when the caret is just above or just below the deleted hunk.
15840 let allow_adjacent = hunk.status().is_removed();
15841 let related_to_selection = if allow_adjacent {
15842 hunk.row_range.overlaps(&query_rows)
15843 || hunk.row_range.start == query_rows.end
15844 || hunk.row_range.end == query_rows.start
15845 } else {
15846 hunk.row_range.overlaps(&query_rows)
15847 };
15848 if related_to_selection {
15849 if !processed_buffer_rows
15850 .entry(hunk.buffer_id)
15851 .or_default()
15852 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15853 {
15854 continue;
15855 }
15856 hunks.push(hunk);
15857 }
15858 }
15859 }
15860
15861 hunks
15862 }
15863
15864 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15865 self.display_snapshot.buffer_snapshot.language_at(position)
15866 }
15867
15868 pub fn is_focused(&self) -> bool {
15869 self.is_focused
15870 }
15871
15872 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15873 self.placeholder_text.as_ref()
15874 }
15875
15876 pub fn scroll_position(&self) -> gpui::Point<f32> {
15877 self.scroll_anchor.scroll_position(&self.display_snapshot)
15878 }
15879
15880 fn gutter_dimensions(
15881 &self,
15882 font_id: FontId,
15883 font_size: Pixels,
15884 max_line_number_width: Pixels,
15885 cx: &App,
15886 ) -> Option<GutterDimensions> {
15887 if !self.show_gutter {
15888 return None;
15889 }
15890
15891 let descent = cx.text_system().descent(font_id, font_size);
15892 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15893 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15894
15895 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15896 matches!(
15897 ProjectSettings::get_global(cx).git.git_gutter,
15898 Some(GitGutterSetting::TrackedFiles)
15899 )
15900 });
15901 let gutter_settings = EditorSettings::get_global(cx).gutter;
15902 let show_line_numbers = self
15903 .show_line_numbers
15904 .unwrap_or(gutter_settings.line_numbers);
15905 let line_gutter_width = if show_line_numbers {
15906 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15907 let min_width_for_number_on_gutter = em_advance * 4.0;
15908 max_line_number_width.max(min_width_for_number_on_gutter)
15909 } else {
15910 0.0.into()
15911 };
15912
15913 let show_code_actions = self
15914 .show_code_actions
15915 .unwrap_or(gutter_settings.code_actions);
15916
15917 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15918
15919 let git_blame_entries_width =
15920 self.git_blame_gutter_max_author_length
15921 .map(|max_author_length| {
15922 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15923
15924 /// The number of characters to dedicate to gaps and margins.
15925 const SPACING_WIDTH: usize = 4;
15926
15927 let max_char_count = max_author_length
15928 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15929 + ::git::SHORT_SHA_LENGTH
15930 + MAX_RELATIVE_TIMESTAMP.len()
15931 + SPACING_WIDTH;
15932
15933 em_advance * max_char_count
15934 });
15935
15936 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15937 left_padding += if show_code_actions || show_runnables {
15938 em_width * 3.0
15939 } else if show_git_gutter && show_line_numbers {
15940 em_width * 2.0
15941 } else if show_git_gutter || show_line_numbers {
15942 em_width
15943 } else {
15944 px(0.)
15945 };
15946
15947 let right_padding = if gutter_settings.folds && show_line_numbers {
15948 em_width * 4.0
15949 } else if gutter_settings.folds {
15950 em_width * 3.0
15951 } else if show_line_numbers {
15952 em_width
15953 } else {
15954 px(0.)
15955 };
15956
15957 Some(GutterDimensions {
15958 left_padding,
15959 right_padding,
15960 width: line_gutter_width + left_padding + right_padding,
15961 margin: -descent,
15962 git_blame_entries_width,
15963 })
15964 }
15965
15966 pub fn render_crease_toggle(
15967 &self,
15968 buffer_row: MultiBufferRow,
15969 row_contains_cursor: bool,
15970 editor: Entity<Editor>,
15971 window: &mut Window,
15972 cx: &mut App,
15973 ) -> Option<AnyElement> {
15974 let folded = self.is_line_folded(buffer_row);
15975 let mut is_foldable = false;
15976
15977 if let Some(crease) = self
15978 .crease_snapshot
15979 .query_row(buffer_row, &self.buffer_snapshot)
15980 {
15981 is_foldable = true;
15982 match crease {
15983 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15984 if let Some(render_toggle) = render_toggle {
15985 let toggle_callback =
15986 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15987 if folded {
15988 editor.update(cx, |editor, cx| {
15989 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15990 });
15991 } else {
15992 editor.update(cx, |editor, cx| {
15993 editor.unfold_at(
15994 &crate::UnfoldAt { buffer_row },
15995 window,
15996 cx,
15997 )
15998 });
15999 }
16000 });
16001 return Some((render_toggle)(
16002 buffer_row,
16003 folded,
16004 toggle_callback,
16005 window,
16006 cx,
16007 ));
16008 }
16009 }
16010 }
16011 }
16012
16013 is_foldable |= self.starts_indent(buffer_row);
16014
16015 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
16016 Some(
16017 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
16018 .toggle_state(folded)
16019 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
16020 if folded {
16021 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
16022 } else {
16023 this.fold_at(&FoldAt { buffer_row }, window, cx);
16024 }
16025 }))
16026 .into_any_element(),
16027 )
16028 } else {
16029 None
16030 }
16031 }
16032
16033 pub fn render_crease_trailer(
16034 &self,
16035 buffer_row: MultiBufferRow,
16036 window: &mut Window,
16037 cx: &mut App,
16038 ) -> Option<AnyElement> {
16039 let folded = self.is_line_folded(buffer_row);
16040 if let Crease::Inline { render_trailer, .. } = self
16041 .crease_snapshot
16042 .query_row(buffer_row, &self.buffer_snapshot)?
16043 {
16044 let render_trailer = render_trailer.as_ref()?;
16045 Some(render_trailer(buffer_row, folded, window, cx))
16046 } else {
16047 None
16048 }
16049 }
16050}
16051
16052impl Deref for EditorSnapshot {
16053 type Target = DisplaySnapshot;
16054
16055 fn deref(&self) -> &Self::Target {
16056 &self.display_snapshot
16057 }
16058}
16059
16060#[derive(Clone, Debug, PartialEq, Eq)]
16061pub enum EditorEvent {
16062 InputIgnored {
16063 text: Arc<str>,
16064 },
16065 InputHandled {
16066 utf16_range_to_replace: Option<Range<isize>>,
16067 text: Arc<str>,
16068 },
16069 ExcerptsAdded {
16070 buffer: Entity<Buffer>,
16071 predecessor: ExcerptId,
16072 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16073 },
16074 ExcerptsRemoved {
16075 ids: Vec<ExcerptId>,
16076 },
16077 BufferFoldToggled {
16078 ids: Vec<ExcerptId>,
16079 folded: bool,
16080 },
16081 ExcerptsEdited {
16082 ids: Vec<ExcerptId>,
16083 },
16084 ExcerptsExpanded {
16085 ids: Vec<ExcerptId>,
16086 },
16087 BufferEdited,
16088 Edited {
16089 transaction_id: clock::Lamport,
16090 },
16091 Reparsed(BufferId),
16092 Focused,
16093 FocusedIn,
16094 Blurred,
16095 DirtyChanged,
16096 Saved,
16097 TitleChanged,
16098 DiffBaseChanged,
16099 SelectionsChanged {
16100 local: bool,
16101 },
16102 ScrollPositionChanged {
16103 local: bool,
16104 autoscroll: bool,
16105 },
16106 Closed,
16107 TransactionUndone {
16108 transaction_id: clock::Lamport,
16109 },
16110 TransactionBegun {
16111 transaction_id: clock::Lamport,
16112 },
16113 Reloaded,
16114 CursorShapeChanged,
16115}
16116
16117impl EventEmitter<EditorEvent> for Editor {}
16118
16119impl Focusable for Editor {
16120 fn focus_handle(&self, _cx: &App) -> FocusHandle {
16121 self.focus_handle.clone()
16122 }
16123}
16124
16125impl Render for Editor {
16126 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16127 let settings = ThemeSettings::get_global(cx);
16128
16129 let mut text_style = match self.mode {
16130 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16131 color: cx.theme().colors().editor_foreground,
16132 font_family: settings.ui_font.family.clone(),
16133 font_features: settings.ui_font.features.clone(),
16134 font_fallbacks: settings.ui_font.fallbacks.clone(),
16135 font_size: rems(0.875).into(),
16136 font_weight: settings.ui_font.weight,
16137 line_height: relative(settings.buffer_line_height.value()),
16138 ..Default::default()
16139 },
16140 EditorMode::Full => TextStyle {
16141 color: cx.theme().colors().editor_foreground,
16142 font_family: settings.buffer_font.family.clone(),
16143 font_features: settings.buffer_font.features.clone(),
16144 font_fallbacks: settings.buffer_font.fallbacks.clone(),
16145 font_size: settings.buffer_font_size().into(),
16146 font_weight: settings.buffer_font.weight,
16147 line_height: relative(settings.buffer_line_height.value()),
16148 ..Default::default()
16149 },
16150 };
16151 if let Some(text_style_refinement) = &self.text_style_refinement {
16152 text_style.refine(text_style_refinement)
16153 }
16154
16155 let background = match self.mode {
16156 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16157 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16158 EditorMode::Full => cx.theme().colors().editor_background,
16159 };
16160
16161 EditorElement::new(
16162 &cx.entity(),
16163 EditorStyle {
16164 background,
16165 local_player: cx.theme().players().local(),
16166 text: text_style,
16167 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16168 syntax: cx.theme().syntax().clone(),
16169 status: cx.theme().status().clone(),
16170 inlay_hints_style: make_inlay_hints_style(cx),
16171 inline_completion_styles: make_suggestion_styles(cx),
16172 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16173 },
16174 )
16175 }
16176}
16177
16178impl EntityInputHandler for Editor {
16179 fn text_for_range(
16180 &mut self,
16181 range_utf16: Range<usize>,
16182 adjusted_range: &mut Option<Range<usize>>,
16183 _: &mut Window,
16184 cx: &mut Context<Self>,
16185 ) -> Option<String> {
16186 let snapshot = self.buffer.read(cx).read(cx);
16187 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16188 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16189 if (start.0..end.0) != range_utf16 {
16190 adjusted_range.replace(start.0..end.0);
16191 }
16192 Some(snapshot.text_for_range(start..end).collect())
16193 }
16194
16195 fn selected_text_range(
16196 &mut self,
16197 ignore_disabled_input: bool,
16198 _: &mut Window,
16199 cx: &mut Context<Self>,
16200 ) -> Option<UTF16Selection> {
16201 // Prevent the IME menu from appearing when holding down an alphabetic key
16202 // while input is disabled.
16203 if !ignore_disabled_input && !self.input_enabled {
16204 return None;
16205 }
16206
16207 let selection = self.selections.newest::<OffsetUtf16>(cx);
16208 let range = selection.range();
16209
16210 Some(UTF16Selection {
16211 range: range.start.0..range.end.0,
16212 reversed: selection.reversed,
16213 })
16214 }
16215
16216 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16217 let snapshot = self.buffer.read(cx).read(cx);
16218 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16219 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16220 }
16221
16222 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16223 self.clear_highlights::<InputComposition>(cx);
16224 self.ime_transaction.take();
16225 }
16226
16227 fn replace_text_in_range(
16228 &mut self,
16229 range_utf16: Option<Range<usize>>,
16230 text: &str,
16231 window: &mut Window,
16232 cx: &mut Context<Self>,
16233 ) {
16234 if !self.input_enabled {
16235 cx.emit(EditorEvent::InputIgnored { text: text.into() });
16236 return;
16237 }
16238
16239 self.transact(window, cx, |this, window, cx| {
16240 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16241 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16242 Some(this.selection_replacement_ranges(range_utf16, cx))
16243 } else {
16244 this.marked_text_ranges(cx)
16245 };
16246
16247 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16248 let newest_selection_id = this.selections.newest_anchor().id;
16249 this.selections
16250 .all::<OffsetUtf16>(cx)
16251 .iter()
16252 .zip(ranges_to_replace.iter())
16253 .find_map(|(selection, range)| {
16254 if selection.id == newest_selection_id {
16255 Some(
16256 (range.start.0 as isize - selection.head().0 as isize)
16257 ..(range.end.0 as isize - selection.head().0 as isize),
16258 )
16259 } else {
16260 None
16261 }
16262 })
16263 });
16264
16265 cx.emit(EditorEvent::InputHandled {
16266 utf16_range_to_replace: range_to_replace,
16267 text: text.into(),
16268 });
16269
16270 if let Some(new_selected_ranges) = new_selected_ranges {
16271 this.change_selections(None, window, cx, |selections| {
16272 selections.select_ranges(new_selected_ranges)
16273 });
16274 this.backspace(&Default::default(), window, cx);
16275 }
16276
16277 this.handle_input(text, window, cx);
16278 });
16279
16280 if let Some(transaction) = self.ime_transaction {
16281 self.buffer.update(cx, |buffer, cx| {
16282 buffer.group_until_transaction(transaction, cx);
16283 });
16284 }
16285
16286 self.unmark_text(window, cx);
16287 }
16288
16289 fn replace_and_mark_text_in_range(
16290 &mut self,
16291 range_utf16: Option<Range<usize>>,
16292 text: &str,
16293 new_selected_range_utf16: Option<Range<usize>>,
16294 window: &mut Window,
16295 cx: &mut Context<Self>,
16296 ) {
16297 if !self.input_enabled {
16298 return;
16299 }
16300
16301 let transaction = self.transact(window, cx, |this, window, cx| {
16302 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16303 let snapshot = this.buffer.read(cx).read(cx);
16304 if let Some(relative_range_utf16) = range_utf16.as_ref() {
16305 for marked_range in &mut marked_ranges {
16306 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16307 marked_range.start.0 += relative_range_utf16.start;
16308 marked_range.start =
16309 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16310 marked_range.end =
16311 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16312 }
16313 }
16314 Some(marked_ranges)
16315 } else if let Some(range_utf16) = range_utf16 {
16316 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16317 Some(this.selection_replacement_ranges(range_utf16, cx))
16318 } else {
16319 None
16320 };
16321
16322 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16323 let newest_selection_id = this.selections.newest_anchor().id;
16324 this.selections
16325 .all::<OffsetUtf16>(cx)
16326 .iter()
16327 .zip(ranges_to_replace.iter())
16328 .find_map(|(selection, range)| {
16329 if selection.id == newest_selection_id {
16330 Some(
16331 (range.start.0 as isize - selection.head().0 as isize)
16332 ..(range.end.0 as isize - selection.head().0 as isize),
16333 )
16334 } else {
16335 None
16336 }
16337 })
16338 });
16339
16340 cx.emit(EditorEvent::InputHandled {
16341 utf16_range_to_replace: range_to_replace,
16342 text: text.into(),
16343 });
16344
16345 if let Some(ranges) = ranges_to_replace {
16346 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16347 }
16348
16349 let marked_ranges = {
16350 let snapshot = this.buffer.read(cx).read(cx);
16351 this.selections
16352 .disjoint_anchors()
16353 .iter()
16354 .map(|selection| {
16355 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16356 })
16357 .collect::<Vec<_>>()
16358 };
16359
16360 if text.is_empty() {
16361 this.unmark_text(window, cx);
16362 } else {
16363 this.highlight_text::<InputComposition>(
16364 marked_ranges.clone(),
16365 HighlightStyle {
16366 underline: Some(UnderlineStyle {
16367 thickness: px(1.),
16368 color: None,
16369 wavy: false,
16370 }),
16371 ..Default::default()
16372 },
16373 cx,
16374 );
16375 }
16376
16377 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16378 let use_autoclose = this.use_autoclose;
16379 let use_auto_surround = this.use_auto_surround;
16380 this.set_use_autoclose(false);
16381 this.set_use_auto_surround(false);
16382 this.handle_input(text, window, cx);
16383 this.set_use_autoclose(use_autoclose);
16384 this.set_use_auto_surround(use_auto_surround);
16385
16386 if let Some(new_selected_range) = new_selected_range_utf16 {
16387 let snapshot = this.buffer.read(cx).read(cx);
16388 let new_selected_ranges = marked_ranges
16389 .into_iter()
16390 .map(|marked_range| {
16391 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16392 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16393 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16394 snapshot.clip_offset_utf16(new_start, Bias::Left)
16395 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16396 })
16397 .collect::<Vec<_>>();
16398
16399 drop(snapshot);
16400 this.change_selections(None, window, cx, |selections| {
16401 selections.select_ranges(new_selected_ranges)
16402 });
16403 }
16404 });
16405
16406 self.ime_transaction = self.ime_transaction.or(transaction);
16407 if let Some(transaction) = self.ime_transaction {
16408 self.buffer.update(cx, |buffer, cx| {
16409 buffer.group_until_transaction(transaction, cx);
16410 });
16411 }
16412
16413 if self.text_highlights::<InputComposition>(cx).is_none() {
16414 self.ime_transaction.take();
16415 }
16416 }
16417
16418 fn bounds_for_range(
16419 &mut self,
16420 range_utf16: Range<usize>,
16421 element_bounds: gpui::Bounds<Pixels>,
16422 window: &mut Window,
16423 cx: &mut Context<Self>,
16424 ) -> Option<gpui::Bounds<Pixels>> {
16425 let text_layout_details = self.text_layout_details(window);
16426 let gpui::Size {
16427 width: em_width,
16428 height: line_height,
16429 } = self.character_size(window);
16430
16431 let snapshot = self.snapshot(window, cx);
16432 let scroll_position = snapshot.scroll_position();
16433 let scroll_left = scroll_position.x * em_width;
16434
16435 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16436 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16437 + self.gutter_dimensions.width
16438 + self.gutter_dimensions.margin;
16439 let y = line_height * (start.row().as_f32() - scroll_position.y);
16440
16441 Some(Bounds {
16442 origin: element_bounds.origin + point(x, y),
16443 size: size(em_width, line_height),
16444 })
16445 }
16446
16447 fn character_index_for_point(
16448 &mut self,
16449 point: gpui::Point<Pixels>,
16450 _window: &mut Window,
16451 _cx: &mut Context<Self>,
16452 ) -> Option<usize> {
16453 let position_map = self.last_position_map.as_ref()?;
16454 if !position_map.text_hitbox.contains(&point) {
16455 return None;
16456 }
16457 let display_point = position_map.point_for_position(point).previous_valid;
16458 let anchor = position_map
16459 .snapshot
16460 .display_point_to_anchor(display_point, Bias::Left);
16461 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16462 Some(utf16_offset.0)
16463 }
16464}
16465
16466trait SelectionExt {
16467 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16468 fn spanned_rows(
16469 &self,
16470 include_end_if_at_line_start: bool,
16471 map: &DisplaySnapshot,
16472 ) -> Range<MultiBufferRow>;
16473}
16474
16475impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16476 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16477 let start = self
16478 .start
16479 .to_point(&map.buffer_snapshot)
16480 .to_display_point(map);
16481 let end = self
16482 .end
16483 .to_point(&map.buffer_snapshot)
16484 .to_display_point(map);
16485 if self.reversed {
16486 end..start
16487 } else {
16488 start..end
16489 }
16490 }
16491
16492 fn spanned_rows(
16493 &self,
16494 include_end_if_at_line_start: bool,
16495 map: &DisplaySnapshot,
16496 ) -> Range<MultiBufferRow> {
16497 let start = self.start.to_point(&map.buffer_snapshot);
16498 let mut end = self.end.to_point(&map.buffer_snapshot);
16499 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16500 end.row -= 1;
16501 }
16502
16503 let buffer_start = map.prev_line_boundary(start).0;
16504 let buffer_end = map.next_line_boundary(end).0;
16505 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16506 }
16507}
16508
16509impl<T: InvalidationRegion> InvalidationStack<T> {
16510 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16511 where
16512 S: Clone + ToOffset,
16513 {
16514 while let Some(region) = self.last() {
16515 let all_selections_inside_invalidation_ranges =
16516 if selections.len() == region.ranges().len() {
16517 selections
16518 .iter()
16519 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16520 .all(|(selection, invalidation_range)| {
16521 let head = selection.head().to_offset(buffer);
16522 invalidation_range.start <= head && invalidation_range.end >= head
16523 })
16524 } else {
16525 false
16526 };
16527
16528 if all_selections_inside_invalidation_ranges {
16529 break;
16530 } else {
16531 self.pop();
16532 }
16533 }
16534 }
16535}
16536
16537impl<T> Default for InvalidationStack<T> {
16538 fn default() -> Self {
16539 Self(Default::default())
16540 }
16541}
16542
16543impl<T> Deref for InvalidationStack<T> {
16544 type Target = Vec<T>;
16545
16546 fn deref(&self) -> &Self::Target {
16547 &self.0
16548 }
16549}
16550
16551impl<T> DerefMut for InvalidationStack<T> {
16552 fn deref_mut(&mut self) -> &mut Self::Target {
16553 &mut self.0
16554 }
16555}
16556
16557impl InvalidationRegion for SnippetState {
16558 fn ranges(&self) -> &[Range<Anchor>] {
16559 &self.ranges[self.active_index]
16560 }
16561}
16562
16563pub fn diagnostic_block_renderer(
16564 diagnostic: Diagnostic,
16565 max_message_rows: Option<u8>,
16566 allow_closing: bool,
16567 _is_valid: bool,
16568) -> RenderBlock {
16569 let (text_without_backticks, code_ranges) =
16570 highlight_diagnostic_message(&diagnostic, max_message_rows);
16571
16572 Arc::new(move |cx: &mut BlockContext| {
16573 let group_id: SharedString = cx.block_id.to_string().into();
16574
16575 let mut text_style = cx.window.text_style().clone();
16576 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16577 let theme_settings = ThemeSettings::get_global(cx);
16578 text_style.font_family = theme_settings.buffer_font.family.clone();
16579 text_style.font_style = theme_settings.buffer_font.style;
16580 text_style.font_features = theme_settings.buffer_font.features.clone();
16581 text_style.font_weight = theme_settings.buffer_font.weight;
16582
16583 let multi_line_diagnostic = diagnostic.message.contains('\n');
16584
16585 let buttons = |diagnostic: &Diagnostic| {
16586 if multi_line_diagnostic {
16587 v_flex()
16588 } else {
16589 h_flex()
16590 }
16591 .when(allow_closing, |div| {
16592 div.children(diagnostic.is_primary.then(|| {
16593 IconButton::new("close-block", IconName::XCircle)
16594 .icon_color(Color::Muted)
16595 .size(ButtonSize::Compact)
16596 .style(ButtonStyle::Transparent)
16597 .visible_on_hover(group_id.clone())
16598 .on_click(move |_click, window, cx| {
16599 window.dispatch_action(Box::new(Cancel), cx)
16600 })
16601 .tooltip(|window, cx| {
16602 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16603 })
16604 }))
16605 })
16606 .child(
16607 IconButton::new("copy-block", IconName::Copy)
16608 .icon_color(Color::Muted)
16609 .size(ButtonSize::Compact)
16610 .style(ButtonStyle::Transparent)
16611 .visible_on_hover(group_id.clone())
16612 .on_click({
16613 let message = diagnostic.message.clone();
16614 move |_click, _, cx| {
16615 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16616 }
16617 })
16618 .tooltip(Tooltip::text("Copy diagnostic message")),
16619 )
16620 };
16621
16622 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16623 AvailableSpace::min_size(),
16624 cx.window,
16625 cx.app,
16626 );
16627
16628 h_flex()
16629 .id(cx.block_id)
16630 .group(group_id.clone())
16631 .relative()
16632 .size_full()
16633 .block_mouse_down()
16634 .pl(cx.gutter_dimensions.width)
16635 .w(cx.max_width - cx.gutter_dimensions.full_width())
16636 .child(
16637 div()
16638 .flex()
16639 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16640 .flex_shrink(),
16641 )
16642 .child(buttons(&diagnostic))
16643 .child(div().flex().flex_shrink_0().child(
16644 StyledText::new(text_without_backticks.clone()).with_highlights(
16645 &text_style,
16646 code_ranges.iter().map(|range| {
16647 (
16648 range.clone(),
16649 HighlightStyle {
16650 font_weight: Some(FontWeight::BOLD),
16651 ..Default::default()
16652 },
16653 )
16654 }),
16655 ),
16656 ))
16657 .into_any_element()
16658 })
16659}
16660
16661fn inline_completion_edit_text(
16662 current_snapshot: &BufferSnapshot,
16663 edits: &[(Range<Anchor>, String)],
16664 edit_preview: &EditPreview,
16665 include_deletions: bool,
16666 cx: &App,
16667) -> HighlightedText {
16668 let edits = edits
16669 .iter()
16670 .map(|(anchor, text)| {
16671 (
16672 anchor.start.text_anchor..anchor.end.text_anchor,
16673 text.clone(),
16674 )
16675 })
16676 .collect::<Vec<_>>();
16677
16678 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16679}
16680
16681pub fn highlight_diagnostic_message(
16682 diagnostic: &Diagnostic,
16683 mut max_message_rows: Option<u8>,
16684) -> (SharedString, Vec<Range<usize>>) {
16685 let mut text_without_backticks = String::new();
16686 let mut code_ranges = Vec::new();
16687
16688 if let Some(source) = &diagnostic.source {
16689 text_without_backticks.push_str(source);
16690 code_ranges.push(0..source.len());
16691 text_without_backticks.push_str(": ");
16692 }
16693
16694 let mut prev_offset = 0;
16695 let mut in_code_block = false;
16696 let has_row_limit = max_message_rows.is_some();
16697 let mut newline_indices = diagnostic
16698 .message
16699 .match_indices('\n')
16700 .filter(|_| has_row_limit)
16701 .map(|(ix, _)| ix)
16702 .fuse()
16703 .peekable();
16704
16705 for (quote_ix, _) in diagnostic
16706 .message
16707 .match_indices('`')
16708 .chain([(diagnostic.message.len(), "")])
16709 {
16710 let mut first_newline_ix = None;
16711 let mut last_newline_ix = None;
16712 while let Some(newline_ix) = newline_indices.peek() {
16713 if *newline_ix < quote_ix {
16714 if first_newline_ix.is_none() {
16715 first_newline_ix = Some(*newline_ix);
16716 }
16717 last_newline_ix = Some(*newline_ix);
16718
16719 if let Some(rows_left) = &mut max_message_rows {
16720 if *rows_left == 0 {
16721 break;
16722 } else {
16723 *rows_left -= 1;
16724 }
16725 }
16726 let _ = newline_indices.next();
16727 } else {
16728 break;
16729 }
16730 }
16731 let prev_len = text_without_backticks.len();
16732 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16733 text_without_backticks.push_str(new_text);
16734 if in_code_block {
16735 code_ranges.push(prev_len..text_without_backticks.len());
16736 }
16737 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16738 in_code_block = !in_code_block;
16739 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16740 text_without_backticks.push_str("...");
16741 break;
16742 }
16743 }
16744
16745 (text_without_backticks.into(), code_ranges)
16746}
16747
16748fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16749 match severity {
16750 DiagnosticSeverity::ERROR => colors.error,
16751 DiagnosticSeverity::WARNING => colors.warning,
16752 DiagnosticSeverity::INFORMATION => colors.info,
16753 DiagnosticSeverity::HINT => colors.info,
16754 _ => colors.ignored,
16755 }
16756}
16757
16758pub fn styled_runs_for_code_label<'a>(
16759 label: &'a CodeLabel,
16760 syntax_theme: &'a theme::SyntaxTheme,
16761) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16762 let fade_out = HighlightStyle {
16763 fade_out: Some(0.35),
16764 ..Default::default()
16765 };
16766
16767 let mut prev_end = label.filter_range.end;
16768 label
16769 .runs
16770 .iter()
16771 .enumerate()
16772 .flat_map(move |(ix, (range, highlight_id))| {
16773 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16774 style
16775 } else {
16776 return Default::default();
16777 };
16778 let mut muted_style = style;
16779 muted_style.highlight(fade_out);
16780
16781 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16782 if range.start >= label.filter_range.end {
16783 if range.start > prev_end {
16784 runs.push((prev_end..range.start, fade_out));
16785 }
16786 runs.push((range.clone(), muted_style));
16787 } else if range.end <= label.filter_range.end {
16788 runs.push((range.clone(), style));
16789 } else {
16790 runs.push((range.start..label.filter_range.end, style));
16791 runs.push((label.filter_range.end..range.end, muted_style));
16792 }
16793 prev_end = cmp::max(prev_end, range.end);
16794
16795 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16796 runs.push((prev_end..label.text.len(), fade_out));
16797 }
16798
16799 runs
16800 })
16801}
16802
16803pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16804 let mut prev_index = 0;
16805 let mut prev_codepoint: Option<char> = None;
16806 text.char_indices()
16807 .chain([(text.len(), '\0')])
16808 .filter_map(move |(index, codepoint)| {
16809 let prev_codepoint = prev_codepoint.replace(codepoint)?;
16810 let is_boundary = index == text.len()
16811 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16812 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16813 if is_boundary {
16814 let chunk = &text[prev_index..index];
16815 prev_index = index;
16816 Some(chunk)
16817 } else {
16818 None
16819 }
16820 })
16821}
16822
16823pub trait RangeToAnchorExt: Sized {
16824 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16825
16826 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16827 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16828 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16829 }
16830}
16831
16832impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16833 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16834 let start_offset = self.start.to_offset(snapshot);
16835 let end_offset = self.end.to_offset(snapshot);
16836 if start_offset == end_offset {
16837 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16838 } else {
16839 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16840 }
16841 }
16842}
16843
16844pub trait RowExt {
16845 fn as_f32(&self) -> f32;
16846
16847 fn next_row(&self) -> Self;
16848
16849 fn previous_row(&self) -> Self;
16850
16851 fn minus(&self, other: Self) -> u32;
16852}
16853
16854impl RowExt for DisplayRow {
16855 fn as_f32(&self) -> f32 {
16856 self.0 as f32
16857 }
16858
16859 fn next_row(&self) -> Self {
16860 Self(self.0 + 1)
16861 }
16862
16863 fn previous_row(&self) -> Self {
16864 Self(self.0.saturating_sub(1))
16865 }
16866
16867 fn minus(&self, other: Self) -> u32 {
16868 self.0 - other.0
16869 }
16870}
16871
16872impl RowExt for MultiBufferRow {
16873 fn as_f32(&self) -> f32 {
16874 self.0 as f32
16875 }
16876
16877 fn next_row(&self) -> Self {
16878 Self(self.0 + 1)
16879 }
16880
16881 fn previous_row(&self) -> Self {
16882 Self(self.0.saturating_sub(1))
16883 }
16884
16885 fn minus(&self, other: Self) -> u32 {
16886 self.0 - other.0
16887 }
16888}
16889
16890trait RowRangeExt {
16891 type Row;
16892
16893 fn len(&self) -> usize;
16894
16895 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16896}
16897
16898impl RowRangeExt for Range<MultiBufferRow> {
16899 type Row = MultiBufferRow;
16900
16901 fn len(&self) -> usize {
16902 (self.end.0 - self.start.0) as usize
16903 }
16904
16905 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16906 (self.start.0..self.end.0).map(MultiBufferRow)
16907 }
16908}
16909
16910impl RowRangeExt for Range<DisplayRow> {
16911 type Row = DisplayRow;
16912
16913 fn len(&self) -> usize {
16914 (self.end.0 - self.start.0) as usize
16915 }
16916
16917 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16918 (self.start.0..self.end.0).map(DisplayRow)
16919 }
16920}
16921
16922/// If select range has more than one line, we
16923/// just point the cursor to range.start.
16924fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16925 if range.start.row == range.end.row {
16926 range
16927 } else {
16928 range.start..range.start
16929 }
16930}
16931pub struct KillRing(ClipboardItem);
16932impl Global for KillRing {}
16933
16934const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16935
16936fn all_edits_insertions_or_deletions(
16937 edits: &Vec<(Range<Anchor>, String)>,
16938 snapshot: &MultiBufferSnapshot,
16939) -> bool {
16940 let mut all_insertions = true;
16941 let mut all_deletions = true;
16942
16943 for (range, new_text) in edits.iter() {
16944 let range_is_empty = range.to_offset(&snapshot).is_empty();
16945 let text_is_empty = new_text.is_empty();
16946
16947 if range_is_empty != text_is_empty {
16948 if range_is_empty {
16949 all_deletions = false;
16950 } else {
16951 all_insertions = false;
16952 }
16953 } else {
16954 return false;
16955 }
16956
16957 if !all_insertions && !all_deletions {
16958 return false;
16959 }
16960 }
16961 all_insertions || all_deletions
16962}