1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod clangd_ext;
19mod code_context_menus;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod indent_guides;
29mod inlay_hint_cache;
30pub mod items;
31mod linked_editing_ranges;
32mod lsp_ext;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod proposed_changes_editor;
37mod rust_analyzer_ext;
38pub mod scroll;
39mod selections_collection;
40pub mod tasks;
41
42#[cfg(test)]
43mod editor_tests;
44#[cfg(test)]
45mod inline_completion_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50pub(crate) use actions::*;
51pub use actions::{OpenExcerpts, OpenExcerptsSplit};
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use client::{Collaborator, ParticipantIndex};
56use clock::ReplicaId;
57use collections::{BTreeMap, HashMap, HashSet, VecDeque};
58use convert_case::{Case, Casing};
59use display_map::*;
60pub use display_map::{DisplayPoint, FoldPlaceholder};
61pub use editor_settings::{
62 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
63};
64pub use editor_settings_controls::*;
65use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
66pub use element::{
67 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
68};
69use futures::{future, FutureExt};
70use fuzzy::StringMatchCandidate;
71
72use code_context_menus::{
73 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
74 CompletionsMenu, ContextMenuOrigin,
75};
76use diff::DiffHunkStatus;
77use git::blame::GitBlame;
78use gpui::{
79 div, impl_actions, linear_color_stop, linear_gradient, point, prelude::*, pulsating_between,
80 px, relative, size, Action, Animation, AnimationExt, AnyElement, App, AsyncWindowContext,
81 AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context, DispatchPhase, ElementId,
82 Entity, EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId,
83 FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Modifiers, MouseButton,
84 MouseDownEvent, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled,
85 StyledText, Subscription, Task, TextRun, TextStyle, TextStyleRefinement, UTF16Selection,
86 UnderlineStyle, UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
87};
88use highlight_matching_bracket::refresh_matching_bracket_highlights;
89use hover_popover::{hide_hover, HoverState};
90use indent_guides::ActiveIndentGuidesState;
91use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
92pub use inline_completion::Direction;
93use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
94pub use items::MAX_TAB_TITLE_LEN;
95use itertools::Itertools;
96use language::{
97 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
98 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
99 CompletionDocumentation, CursorShape, Diagnostic, EditPreview, HighlightedText, IndentKind,
100 IndentSize, InlineCompletionPreviewMode, Language, OffsetRangeExt, Point, Selection,
101 SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
102};
103use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
104use linked_editing_ranges::refresh_linked_ranges;
105use mouse_context_menu::MouseContextMenu;
106pub use proposed_changes_editor::{
107 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
108};
109use similar::{ChangeTag, TextDiff};
110use std::iter::Peekable;
111use task::{ResolvedTask, TaskTemplate, TaskVariables};
112
113use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
114pub use lsp::CompletionContext;
115use lsp::{
116 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
117 LanguageServerId, LanguageServerName,
118};
119
120use language::BufferSnapshot;
121use movement::TextLayoutDetails;
122pub use multi_buffer::{
123 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
124 ToOffset, ToPoint,
125};
126use multi_buffer::{
127 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
128 ToOffsetUtf16,
129};
130use project::{
131 lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
132 project_settings::{GitGutterSetting, ProjectSettings},
133 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
134 LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
135};
136use rand::prelude::*;
137use rpc::{proto::*, ErrorExt};
138use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
139use selections_collection::{
140 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
141};
142use serde::{Deserialize, Serialize};
143use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
144use smallvec::SmallVec;
145use snippet::Snippet;
146use std::{
147 any::TypeId,
148 borrow::Cow,
149 cell::RefCell,
150 cmp::{self, Ordering, Reverse},
151 mem,
152 num::NonZeroU32,
153 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
154 path::{Path, PathBuf},
155 rc::Rc,
156 sync::Arc,
157 time::{Duration, Instant},
158};
159pub use sum_tree::Bias;
160use sum_tree::TreeMap;
161use text::{BufferId, OffsetUtf16, Rope};
162use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
163use ui::{
164 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
165 Tooltip,
166};
167use util::{defer, maybe, post_inc, RangeExt, ResultExt, TakeUntilExt, TryFutureExt};
168use workspace::item::{ItemHandle, PreviewTabsSettings};
169use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
170use workspace::{
171 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
172};
173use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
174
175use crate::hover_links::{find_url, find_url_from_range};
176use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
177
178pub const FILE_HEADER_HEIGHT: u32 = 2;
179pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
180pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
181pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
182const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
183const MAX_LINE_LEN: usize = 1024;
184const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
185const MAX_SELECTION_HISTORY_LEN: usize = 1024;
186pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
187#[doc(hidden)]
188pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
189
190pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
191pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
192
193pub(crate) const EDIT_PREDICTION_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 range_around_target: Range<text::Anchor>,
489 snapshot: BufferSnapshot,
490 },
491}
492
493struct InlineCompletionState {
494 inlay_ids: Vec<InlayId>,
495 completion: InlineCompletion,
496 completion_id: Option<SharedString>,
497 invalidation_range: Range<Anchor>,
498}
499
500enum EditPredictionSettings {
501 Disabled,
502 Enabled {
503 show_in_menu: bool,
504 preview_requires_modifier: bool,
505 },
506}
507
508impl EditPredictionSettings {
509 pub fn is_enabled(&self) -> bool {
510 match self {
511 EditPredictionSettings::Disabled => false,
512 EditPredictionSettings::Enabled { .. } => true,
513 }
514 }
515}
516
517enum InlineCompletionHighlight {}
518
519pub enum MenuInlineCompletionsPolicy {
520 Never,
521 ByProvider,
522}
523
524#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
525struct EditorActionId(usize);
526
527impl EditorActionId {
528 pub fn post_inc(&mut self) -> Self {
529 let answer = self.0;
530
531 *self = Self(answer + 1);
532
533 Self(answer)
534 }
535}
536
537// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
538// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
539
540type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
541type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
542
543#[derive(Default)]
544struct ScrollbarMarkerState {
545 scrollbar_size: Size<Pixels>,
546 dirty: bool,
547 markers: Arc<[PaintQuad]>,
548 pending_refresh: Option<Task<Result<()>>>,
549}
550
551impl ScrollbarMarkerState {
552 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
553 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
554 }
555}
556
557#[derive(Clone, Debug)]
558struct RunnableTasks {
559 templates: Vec<(TaskSourceKind, TaskTemplate)>,
560 offset: MultiBufferOffset,
561 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
562 column: u32,
563 // Values of all named captures, including those starting with '_'
564 extra_variables: HashMap<String, String>,
565 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
566 context_range: Range<BufferOffset>,
567}
568
569impl RunnableTasks {
570 fn resolve<'a>(
571 &'a self,
572 cx: &'a task::TaskContext,
573 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
574 self.templates.iter().filter_map(|(kind, template)| {
575 template
576 .resolve_task(&kind.to_id_base(), cx)
577 .map(|task| (kind.clone(), task))
578 })
579 }
580}
581
582#[derive(Clone)]
583struct ResolvedTasks {
584 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
585 position: Anchor,
586}
587#[derive(Copy, Clone, Debug)]
588struct MultiBufferOffset(usize);
589#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
590struct BufferOffset(usize);
591
592// Addons allow storing per-editor state in other crates (e.g. Vim)
593pub trait Addon: 'static {
594 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
595
596 fn render_buffer_header_controls(
597 &self,
598 _: &ExcerptInfo,
599 _: &Window,
600 _: &App,
601 ) -> Option<AnyElement> {
602 None
603 }
604
605 fn to_any(&self) -> &dyn std::any::Any;
606}
607
608#[derive(Debug, Copy, Clone, PartialEq, Eq)]
609pub enum IsVimMode {
610 Yes,
611 No,
612}
613
614/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
615///
616/// See the [module level documentation](self) for more information.
617pub struct Editor {
618 focus_handle: FocusHandle,
619 last_focused_descendant: Option<WeakFocusHandle>,
620 /// The text buffer being edited
621 buffer: Entity<MultiBuffer>,
622 /// Map of how text in the buffer should be displayed.
623 /// Handles soft wraps, folds, fake inlay text insertions, etc.
624 pub display_map: Entity<DisplayMap>,
625 pub selections: SelectionsCollection,
626 pub scroll_manager: ScrollManager,
627 /// When inline assist editors are linked, they all render cursors because
628 /// typing enters text into each of them, even the ones that aren't focused.
629 pub(crate) show_cursor_when_unfocused: bool,
630 columnar_selection_tail: Option<Anchor>,
631 add_selections_state: Option<AddSelectionsState>,
632 select_next_state: Option<SelectNextState>,
633 select_prev_state: Option<SelectNextState>,
634 selection_history: SelectionHistory,
635 autoclose_regions: Vec<AutocloseRegion>,
636 snippet_stack: InvalidationStack<SnippetState>,
637 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
638 ime_transaction: Option<TransactionId>,
639 active_diagnostics: Option<ActiveDiagnosticGroup>,
640 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
641
642 // TODO: make this a access method
643 pub project: Option<Entity<Project>>,
644 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
645 completion_provider: Option<Box<dyn CompletionProvider>>,
646 collaboration_hub: Option<Box<dyn CollaborationHub>>,
647 blink_manager: Entity<BlinkManager>,
648 show_cursor_names: bool,
649 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
650 pub show_local_selections: bool,
651 mode: EditorMode,
652 show_breadcrumbs: bool,
653 show_gutter: bool,
654 show_scrollbars: bool,
655 show_line_numbers: Option<bool>,
656 use_relative_line_numbers: Option<bool>,
657 show_git_diff_gutter: Option<bool>,
658 show_code_actions: Option<bool>,
659 show_runnables: Option<bool>,
660 show_wrap_guides: Option<bool>,
661 show_indent_guides: Option<bool>,
662 placeholder_text: Option<Arc<str>>,
663 highlight_order: usize,
664 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
665 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
666 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
667 scrollbar_marker_state: ScrollbarMarkerState,
668 active_indent_guides_state: ActiveIndentGuidesState,
669 nav_history: Option<ItemNavHistory>,
670 context_menu: RefCell<Option<CodeContextMenu>>,
671 mouse_context_menu: Option<MouseContextMenu>,
672 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
673 signature_help_state: SignatureHelpState,
674 auto_signature_help: Option<bool>,
675 find_all_references_task_sources: Vec<Anchor>,
676 next_completion_id: CompletionId,
677 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
678 code_actions_task: Option<Task<Result<()>>>,
679 document_highlights_task: Option<Task<()>>,
680 linked_editing_range_task: Option<Task<Option<()>>>,
681 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
682 pending_rename: Option<RenameState>,
683 searchable: bool,
684 cursor_shape: CursorShape,
685 current_line_highlight: Option<CurrentLineHighlight>,
686 collapse_matches: bool,
687 autoindent_mode: Option<AutoindentMode>,
688 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
689 input_enabled: bool,
690 use_modal_editing: bool,
691 read_only: bool,
692 leader_peer_id: Option<PeerId>,
693 remote_id: Option<ViewId>,
694 hover_state: HoverState,
695 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
696 gutter_hovered: bool,
697 hovered_link_state: Option<HoveredLinkState>,
698 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
699 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
700 active_inline_completion: Option<InlineCompletionState>,
701 /// Used to prevent flickering as the user types while the menu is open
702 stale_inline_completion_in_menu: Option<InlineCompletionState>,
703 edit_prediction_settings: EditPredictionSettings,
704 inline_completions_hidden_for_vim_mode: bool,
705 show_inline_completions_override: Option<bool>,
706 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
707 previewing_inline_completion: bool,
708 inlay_hint_cache: InlayHintCache,
709 next_inlay_id: usize,
710 _subscriptions: Vec<Subscription>,
711 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
712 gutter_dimensions: GutterDimensions,
713 style: Option<EditorStyle>,
714 text_style_refinement: Option<TextStyleRefinement>,
715 next_editor_action_id: EditorActionId,
716 editor_actions:
717 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
718 use_autoclose: bool,
719 use_auto_surround: bool,
720 auto_replace_emoji_shortcode: bool,
721 show_git_blame_gutter: bool,
722 show_git_blame_inline: bool,
723 show_git_blame_inline_delay_task: Option<Task<()>>,
724 git_blame_inline_enabled: bool,
725 serialize_dirty_buffers: bool,
726 show_selection_menu: Option<bool>,
727 blame: Option<Entity<GitBlame>>,
728 blame_subscription: Option<Subscription>,
729 custom_context_menu: Option<
730 Box<
731 dyn 'static
732 + Fn(
733 &mut Self,
734 DisplayPoint,
735 &mut Window,
736 &mut Context<Self>,
737 ) -> Option<Entity<ui::ContextMenu>>,
738 >,
739 >,
740 last_bounds: Option<Bounds<Pixels>>,
741 last_position_map: Option<Rc<PositionMap>>,
742 expect_bounds_change: Option<Bounds<Pixels>>,
743 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
744 tasks_update_task: Option<Task<()>>,
745 in_project_search: bool,
746 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
747 breadcrumb_header: Option<String>,
748 focused_block: Option<FocusedBlock>,
749 next_scroll_position: NextScrollCursorCenterTopBottom,
750 addons: HashMap<TypeId, Box<dyn Addon>>,
751 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
752 selection_mark_mode: bool,
753 toggle_fold_multiple_buffers: Task<()>,
754 _scroll_cursor_center_top_bottom_task: Task<()>,
755}
756
757#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
758enum NextScrollCursorCenterTopBottom {
759 #[default]
760 Center,
761 Top,
762 Bottom,
763}
764
765impl NextScrollCursorCenterTopBottom {
766 fn next(&self) -> Self {
767 match self {
768 Self::Center => Self::Top,
769 Self::Top => Self::Bottom,
770 Self::Bottom => Self::Center,
771 }
772 }
773}
774
775#[derive(Clone)]
776pub struct EditorSnapshot {
777 pub mode: EditorMode,
778 show_gutter: bool,
779 show_line_numbers: Option<bool>,
780 show_git_diff_gutter: Option<bool>,
781 show_code_actions: Option<bool>,
782 show_runnables: Option<bool>,
783 git_blame_gutter_max_author_length: Option<usize>,
784 pub display_snapshot: DisplaySnapshot,
785 pub placeholder_text: Option<Arc<str>>,
786 is_focused: bool,
787 scroll_anchor: ScrollAnchor,
788 ongoing_scroll: OngoingScroll,
789 current_line_highlight: CurrentLineHighlight,
790 gutter_hovered: bool,
791}
792
793const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
794
795#[derive(Default, Debug, Clone, Copy)]
796pub struct GutterDimensions {
797 pub left_padding: Pixels,
798 pub right_padding: Pixels,
799 pub width: Pixels,
800 pub margin: Pixels,
801 pub git_blame_entries_width: Option<Pixels>,
802}
803
804impl GutterDimensions {
805 /// The full width of the space taken up by the gutter.
806 pub fn full_width(&self) -> Pixels {
807 self.margin + self.width
808 }
809
810 /// The width of the space reserved for the fold indicators,
811 /// use alongside 'justify_end' and `gutter_width` to
812 /// right align content with the line numbers
813 pub fn fold_area_width(&self) -> Pixels {
814 self.margin + self.right_padding
815 }
816}
817
818#[derive(Debug)]
819pub struct RemoteSelection {
820 pub replica_id: ReplicaId,
821 pub selection: Selection<Anchor>,
822 pub cursor_shape: CursorShape,
823 pub peer_id: PeerId,
824 pub line_mode: bool,
825 pub participant_index: Option<ParticipantIndex>,
826 pub user_name: Option<SharedString>,
827}
828
829#[derive(Clone, Debug)]
830struct SelectionHistoryEntry {
831 selections: Arc<[Selection<Anchor>]>,
832 select_next_state: Option<SelectNextState>,
833 select_prev_state: Option<SelectNextState>,
834 add_selections_state: Option<AddSelectionsState>,
835}
836
837enum SelectionHistoryMode {
838 Normal,
839 Undoing,
840 Redoing,
841}
842
843#[derive(Clone, PartialEq, Eq, Hash)]
844struct HoveredCursor {
845 replica_id: u16,
846 selection_id: usize,
847}
848
849impl Default for SelectionHistoryMode {
850 fn default() -> Self {
851 Self::Normal
852 }
853}
854
855#[derive(Default)]
856struct SelectionHistory {
857 #[allow(clippy::type_complexity)]
858 selections_by_transaction:
859 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
860 mode: SelectionHistoryMode,
861 undo_stack: VecDeque<SelectionHistoryEntry>,
862 redo_stack: VecDeque<SelectionHistoryEntry>,
863}
864
865impl SelectionHistory {
866 fn insert_transaction(
867 &mut self,
868 transaction_id: TransactionId,
869 selections: Arc<[Selection<Anchor>]>,
870 ) {
871 self.selections_by_transaction
872 .insert(transaction_id, (selections, None));
873 }
874
875 #[allow(clippy::type_complexity)]
876 fn transaction(
877 &self,
878 transaction_id: TransactionId,
879 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
880 self.selections_by_transaction.get(&transaction_id)
881 }
882
883 #[allow(clippy::type_complexity)]
884 fn transaction_mut(
885 &mut self,
886 transaction_id: TransactionId,
887 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
888 self.selections_by_transaction.get_mut(&transaction_id)
889 }
890
891 fn push(&mut self, entry: SelectionHistoryEntry) {
892 if !entry.selections.is_empty() {
893 match self.mode {
894 SelectionHistoryMode::Normal => {
895 self.push_undo(entry);
896 self.redo_stack.clear();
897 }
898 SelectionHistoryMode::Undoing => self.push_redo(entry),
899 SelectionHistoryMode::Redoing => self.push_undo(entry),
900 }
901 }
902 }
903
904 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
905 if self
906 .undo_stack
907 .back()
908 .map_or(true, |e| e.selections != entry.selections)
909 {
910 self.undo_stack.push_back(entry);
911 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
912 self.undo_stack.pop_front();
913 }
914 }
915 }
916
917 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
918 if self
919 .redo_stack
920 .back()
921 .map_or(true, |e| e.selections != entry.selections)
922 {
923 self.redo_stack.push_back(entry);
924 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
925 self.redo_stack.pop_front();
926 }
927 }
928 }
929}
930
931struct RowHighlight {
932 index: usize,
933 range: Range<Anchor>,
934 color: Hsla,
935 should_autoscroll: bool,
936}
937
938#[derive(Clone, Debug)]
939struct AddSelectionsState {
940 above: bool,
941 stack: Vec<usize>,
942}
943
944#[derive(Clone)]
945struct SelectNextState {
946 query: AhoCorasick,
947 wordwise: bool,
948 done: bool,
949}
950
951impl std::fmt::Debug for SelectNextState {
952 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
953 f.debug_struct(std::any::type_name::<Self>())
954 .field("wordwise", &self.wordwise)
955 .field("done", &self.done)
956 .finish()
957 }
958}
959
960#[derive(Debug)]
961struct AutocloseRegion {
962 selection_id: usize,
963 range: Range<Anchor>,
964 pair: BracketPair,
965}
966
967#[derive(Debug)]
968struct SnippetState {
969 ranges: Vec<Vec<Range<Anchor>>>,
970 active_index: usize,
971 choices: Vec<Option<Vec<String>>>,
972}
973
974#[doc(hidden)]
975pub struct RenameState {
976 pub range: Range<Anchor>,
977 pub old_name: Arc<str>,
978 pub editor: Entity<Editor>,
979 block_id: CustomBlockId,
980}
981
982struct InvalidationStack<T>(Vec<T>);
983
984struct RegisteredInlineCompletionProvider {
985 provider: Arc<dyn InlineCompletionProviderHandle>,
986 _subscription: Subscription,
987}
988
989#[derive(Debug)]
990struct ActiveDiagnosticGroup {
991 primary_range: Range<Anchor>,
992 primary_message: String,
993 group_id: usize,
994 blocks: HashMap<CustomBlockId, Diagnostic>,
995 is_valid: bool,
996}
997
998#[derive(Serialize, Deserialize, Clone, Debug)]
999pub struct ClipboardSelection {
1000 pub len: usize,
1001 pub is_entire_line: bool,
1002 pub first_line_indent: u32,
1003}
1004
1005#[derive(Debug)]
1006pub(crate) struct NavigationData {
1007 cursor_anchor: Anchor,
1008 cursor_position: Point,
1009 scroll_anchor: ScrollAnchor,
1010 scroll_top_row: u32,
1011}
1012
1013#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1014pub enum GotoDefinitionKind {
1015 Symbol,
1016 Declaration,
1017 Type,
1018 Implementation,
1019}
1020
1021#[derive(Debug, Clone)]
1022enum InlayHintRefreshReason {
1023 Toggle(bool),
1024 SettingsChange(InlayHintSettings),
1025 NewLinesShown,
1026 BufferEdited(HashSet<Arc<Language>>),
1027 RefreshRequested,
1028 ExcerptsRemoved(Vec<ExcerptId>),
1029}
1030
1031impl InlayHintRefreshReason {
1032 fn description(&self) -> &'static str {
1033 match self {
1034 Self::Toggle(_) => "toggle",
1035 Self::SettingsChange(_) => "settings change",
1036 Self::NewLinesShown => "new lines shown",
1037 Self::BufferEdited(_) => "buffer edited",
1038 Self::RefreshRequested => "refresh requested",
1039 Self::ExcerptsRemoved(_) => "excerpts removed",
1040 }
1041 }
1042}
1043
1044pub enum FormatTarget {
1045 Buffers,
1046 Ranges(Vec<Range<MultiBufferPoint>>),
1047}
1048
1049pub(crate) struct FocusedBlock {
1050 id: BlockId,
1051 focus_handle: WeakFocusHandle,
1052}
1053
1054#[derive(Clone)]
1055enum JumpData {
1056 MultiBufferRow {
1057 row: MultiBufferRow,
1058 line_offset_from_top: u32,
1059 },
1060 MultiBufferPoint {
1061 excerpt_id: ExcerptId,
1062 position: Point,
1063 anchor: text::Anchor,
1064 line_offset_from_top: u32,
1065 },
1066}
1067
1068pub enum MultibufferSelectionMode {
1069 First,
1070 All,
1071}
1072
1073impl Editor {
1074 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1075 let buffer = cx.new(|cx| Buffer::local("", cx));
1076 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1077 Self::new(
1078 EditorMode::SingleLine { auto_width: false },
1079 buffer,
1080 None,
1081 false,
1082 window,
1083 cx,
1084 )
1085 }
1086
1087 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1088 let buffer = cx.new(|cx| Buffer::local("", cx));
1089 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1090 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1091 }
1092
1093 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1094 let buffer = cx.new(|cx| Buffer::local("", cx));
1095 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1096 Self::new(
1097 EditorMode::SingleLine { auto_width: true },
1098 buffer,
1099 None,
1100 false,
1101 window,
1102 cx,
1103 )
1104 }
1105
1106 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1107 let buffer = cx.new(|cx| Buffer::local("", cx));
1108 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1109 Self::new(
1110 EditorMode::AutoHeight { max_lines },
1111 buffer,
1112 None,
1113 false,
1114 window,
1115 cx,
1116 )
1117 }
1118
1119 pub fn for_buffer(
1120 buffer: Entity<Buffer>,
1121 project: Option<Entity<Project>>,
1122 window: &mut Window,
1123 cx: &mut Context<Self>,
1124 ) -> Self {
1125 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1126 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1127 }
1128
1129 pub fn for_multibuffer(
1130 buffer: Entity<MultiBuffer>,
1131 project: Option<Entity<Project>>,
1132 show_excerpt_controls: bool,
1133 window: &mut Window,
1134 cx: &mut Context<Self>,
1135 ) -> Self {
1136 Self::new(
1137 EditorMode::Full,
1138 buffer,
1139 project,
1140 show_excerpt_controls,
1141 window,
1142 cx,
1143 )
1144 }
1145
1146 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1147 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1148 let mut clone = Self::new(
1149 self.mode,
1150 self.buffer.clone(),
1151 self.project.clone(),
1152 show_excerpt_controls,
1153 window,
1154 cx,
1155 );
1156 self.display_map.update(cx, |display_map, cx| {
1157 let snapshot = display_map.snapshot(cx);
1158 clone.display_map.update(cx, |display_map, cx| {
1159 display_map.set_state(&snapshot, cx);
1160 });
1161 });
1162 clone.selections.clone_state(&self.selections);
1163 clone.scroll_manager.clone_state(&self.scroll_manager);
1164 clone.searchable = self.searchable;
1165 clone
1166 }
1167
1168 pub fn new(
1169 mode: EditorMode,
1170 buffer: Entity<MultiBuffer>,
1171 project: Option<Entity<Project>>,
1172 show_excerpt_controls: bool,
1173 window: &mut Window,
1174 cx: &mut Context<Self>,
1175 ) -> Self {
1176 let style = window.text_style();
1177 let font_size = style.font_size.to_pixels(window.rem_size());
1178 let editor = cx.entity().downgrade();
1179 let fold_placeholder = FoldPlaceholder {
1180 constrain_width: true,
1181 render: Arc::new(move |fold_id, fold_range, _, cx| {
1182 let editor = editor.clone();
1183 div()
1184 .id(fold_id)
1185 .bg(cx.theme().colors().ghost_element_background)
1186 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1187 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1188 .rounded_sm()
1189 .size_full()
1190 .cursor_pointer()
1191 .child("⋯")
1192 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1193 .on_click(move |_, _window, cx| {
1194 editor
1195 .update(cx, |editor, cx| {
1196 editor.unfold_ranges(
1197 &[fold_range.start..fold_range.end],
1198 true,
1199 false,
1200 cx,
1201 );
1202 cx.stop_propagation();
1203 })
1204 .ok();
1205 })
1206 .into_any()
1207 }),
1208 merge_adjacent: true,
1209 ..Default::default()
1210 };
1211 let display_map = cx.new(|cx| {
1212 DisplayMap::new(
1213 buffer.clone(),
1214 style.font(),
1215 font_size,
1216 None,
1217 show_excerpt_controls,
1218 FILE_HEADER_HEIGHT,
1219 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1220 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1221 fold_placeholder,
1222 cx,
1223 )
1224 });
1225
1226 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1227
1228 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1229
1230 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1231 .then(|| language_settings::SoftWrap::None);
1232
1233 let mut project_subscriptions = Vec::new();
1234 if mode == EditorMode::Full {
1235 if let Some(project) = project.as_ref() {
1236 if buffer.read(cx).is_singleton() {
1237 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1238 cx.emit(EditorEvent::TitleChanged);
1239 }));
1240 }
1241 project_subscriptions.push(cx.subscribe_in(
1242 project,
1243 window,
1244 |editor, _, event, window, cx| {
1245 if let project::Event::RefreshInlayHints = event {
1246 editor
1247 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1248 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1249 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1250 let focus_handle = editor.focus_handle(cx);
1251 if focus_handle.is_focused(window) {
1252 let snapshot = buffer.read(cx).snapshot();
1253 for (range, snippet) in snippet_edits {
1254 let editor_range =
1255 language::range_from_lsp(*range).to_offset(&snapshot);
1256 editor
1257 .insert_snippet(
1258 &[editor_range],
1259 snippet.clone(),
1260 window,
1261 cx,
1262 )
1263 .ok();
1264 }
1265 }
1266 }
1267 }
1268 },
1269 ));
1270 if let Some(task_inventory) = project
1271 .read(cx)
1272 .task_store()
1273 .read(cx)
1274 .task_inventory()
1275 .cloned()
1276 {
1277 project_subscriptions.push(cx.observe_in(
1278 &task_inventory,
1279 window,
1280 |editor, _, window, cx| {
1281 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1282 },
1283 ));
1284 }
1285 }
1286 }
1287
1288 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1289
1290 let inlay_hint_settings =
1291 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1292 let focus_handle = cx.focus_handle();
1293 cx.on_focus(&focus_handle, window, Self::handle_focus)
1294 .detach();
1295 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1296 .detach();
1297 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1298 .detach();
1299 cx.on_blur(&focus_handle, window, Self::handle_blur)
1300 .detach();
1301
1302 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1303 Some(false)
1304 } else {
1305 None
1306 };
1307
1308 let mut code_action_providers = Vec::new();
1309 if let Some(project) = project.clone() {
1310 get_uncommitted_diff_for_buffer(
1311 &project,
1312 buffer.read(cx).all_buffers(),
1313 buffer.clone(),
1314 cx,
1315 );
1316 code_action_providers.push(Rc::new(project) as Rc<_>);
1317 }
1318
1319 let mut this = Self {
1320 focus_handle,
1321 show_cursor_when_unfocused: false,
1322 last_focused_descendant: None,
1323 buffer: buffer.clone(),
1324 display_map: display_map.clone(),
1325 selections,
1326 scroll_manager: ScrollManager::new(cx),
1327 columnar_selection_tail: None,
1328 add_selections_state: None,
1329 select_next_state: None,
1330 select_prev_state: None,
1331 selection_history: Default::default(),
1332 autoclose_regions: Default::default(),
1333 snippet_stack: Default::default(),
1334 select_larger_syntax_node_stack: Vec::new(),
1335 ime_transaction: Default::default(),
1336 active_diagnostics: None,
1337 soft_wrap_mode_override,
1338 completion_provider: project.clone().map(|project| Box::new(project) as _),
1339 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1340 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1341 project,
1342 blink_manager: blink_manager.clone(),
1343 show_local_selections: true,
1344 show_scrollbars: true,
1345 mode,
1346 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1347 show_gutter: mode == EditorMode::Full,
1348 show_line_numbers: None,
1349 use_relative_line_numbers: None,
1350 show_git_diff_gutter: None,
1351 show_code_actions: None,
1352 show_runnables: None,
1353 show_wrap_guides: None,
1354 show_indent_guides,
1355 placeholder_text: None,
1356 highlight_order: 0,
1357 highlighted_rows: HashMap::default(),
1358 background_highlights: Default::default(),
1359 gutter_highlights: TreeMap::default(),
1360 scrollbar_marker_state: ScrollbarMarkerState::default(),
1361 active_indent_guides_state: ActiveIndentGuidesState::default(),
1362 nav_history: None,
1363 context_menu: RefCell::new(None),
1364 mouse_context_menu: None,
1365 completion_tasks: Default::default(),
1366 signature_help_state: SignatureHelpState::default(),
1367 auto_signature_help: None,
1368 find_all_references_task_sources: Vec::new(),
1369 next_completion_id: 0,
1370 next_inlay_id: 0,
1371 code_action_providers,
1372 available_code_actions: Default::default(),
1373 code_actions_task: Default::default(),
1374 document_highlights_task: Default::default(),
1375 linked_editing_range_task: Default::default(),
1376 pending_rename: Default::default(),
1377 searchable: true,
1378 cursor_shape: EditorSettings::get_global(cx)
1379 .cursor_shape
1380 .unwrap_or_default(),
1381 current_line_highlight: None,
1382 autoindent_mode: Some(AutoindentMode::EachLine),
1383 collapse_matches: false,
1384 workspace: None,
1385 input_enabled: true,
1386 use_modal_editing: mode == EditorMode::Full,
1387 read_only: false,
1388 use_autoclose: true,
1389 use_auto_surround: true,
1390 auto_replace_emoji_shortcode: false,
1391 leader_peer_id: None,
1392 remote_id: None,
1393 hover_state: Default::default(),
1394 pending_mouse_down: None,
1395 hovered_link_state: Default::default(),
1396 edit_prediction_provider: None,
1397 active_inline_completion: None,
1398 stale_inline_completion_in_menu: None,
1399 previewing_inline_completion: false,
1400 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1401
1402 gutter_hovered: false,
1403 pixel_position_of_newest_cursor: None,
1404 last_bounds: None,
1405 last_position_map: None,
1406 expect_bounds_change: None,
1407 gutter_dimensions: GutterDimensions::default(),
1408 style: None,
1409 show_cursor_names: false,
1410 hovered_cursors: Default::default(),
1411 next_editor_action_id: EditorActionId::default(),
1412 editor_actions: Rc::default(),
1413 inline_completions_hidden_for_vim_mode: false,
1414 show_inline_completions_override: None,
1415 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1416 edit_prediction_settings: EditPredictionSettings::Disabled,
1417 custom_context_menu: None,
1418 show_git_blame_gutter: false,
1419 show_git_blame_inline: false,
1420 show_selection_menu: None,
1421 show_git_blame_inline_delay_task: None,
1422 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1423 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1424 .session
1425 .restore_unsaved_buffers,
1426 blame: None,
1427 blame_subscription: None,
1428 tasks: Default::default(),
1429 _subscriptions: vec![
1430 cx.observe(&buffer, Self::on_buffer_changed),
1431 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1432 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1433 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1434 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1435 cx.observe_window_activation(window, |editor, window, cx| {
1436 let active = window.is_window_active();
1437 editor.blink_manager.update(cx, |blink_manager, cx| {
1438 if active {
1439 blink_manager.enable(cx);
1440 } else {
1441 blink_manager.disable(cx);
1442 }
1443 });
1444 }),
1445 ],
1446 tasks_update_task: None,
1447 linked_edit_ranges: Default::default(),
1448 in_project_search: false,
1449 previous_search_ranges: None,
1450 breadcrumb_header: None,
1451 focused_block: None,
1452 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1453 addons: HashMap::default(),
1454 registered_buffers: HashMap::default(),
1455 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1456 selection_mark_mode: false,
1457 toggle_fold_multiple_buffers: Task::ready(()),
1458 text_style_refinement: None,
1459 };
1460 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1461 this._subscriptions.extend(project_subscriptions);
1462
1463 this.end_selection(window, cx);
1464 this.scroll_manager.show_scrollbar(window, cx);
1465
1466 if mode == EditorMode::Full {
1467 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1468 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1469
1470 if this.git_blame_inline_enabled {
1471 this.git_blame_inline_enabled = true;
1472 this.start_git_blame_inline(false, window, cx);
1473 }
1474
1475 if let Some(buffer) = buffer.read(cx).as_singleton() {
1476 if let Some(project) = this.project.as_ref() {
1477 let lsp_store = project.read(cx).lsp_store();
1478 let handle = lsp_store.update(cx, |lsp_store, cx| {
1479 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1480 });
1481 this.registered_buffers
1482 .insert(buffer.read(cx).remote_id(), handle);
1483 }
1484 }
1485 }
1486
1487 this.report_editor_event("Editor Opened", None, cx);
1488 this
1489 }
1490
1491 pub fn mouse_menu_is_focused(&self, window: &mut Window, cx: &mut App) -> bool {
1492 self.mouse_context_menu
1493 .as_ref()
1494 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1495 }
1496
1497 fn key_context(&self, window: &mut Window, cx: &mut Context<Self>) -> KeyContext {
1498 let mut key_context = KeyContext::new_with_defaults();
1499 key_context.add("Editor");
1500 let mode = match self.mode {
1501 EditorMode::SingleLine { .. } => "single_line",
1502 EditorMode::AutoHeight { .. } => "auto_height",
1503 EditorMode::Full => "full",
1504 };
1505
1506 if EditorSettings::jupyter_enabled(cx) {
1507 key_context.add("jupyter");
1508 }
1509
1510 key_context.set("mode", mode);
1511 if self.pending_rename.is_some() {
1512 key_context.add("renaming");
1513 }
1514
1515 let mut showing_completions = false;
1516
1517 match self.context_menu.borrow().as_ref() {
1518 Some(CodeContextMenu::Completions(_)) => {
1519 key_context.add("menu");
1520 key_context.add("showing_completions");
1521 showing_completions = true;
1522 }
1523 Some(CodeContextMenu::CodeActions(_)) => {
1524 key_context.add("menu");
1525 key_context.add("showing_code_actions")
1526 }
1527 None => {}
1528 }
1529
1530 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1531 if !self.focus_handle(cx).contains_focused(window, cx)
1532 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1533 {
1534 for addon in self.addons.values() {
1535 addon.extend_key_context(&mut key_context, cx)
1536 }
1537 }
1538
1539 if let Some(extension) = self
1540 .buffer
1541 .read(cx)
1542 .as_singleton()
1543 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1544 {
1545 key_context.set("extension", extension.to_string());
1546 }
1547
1548 if self.has_active_inline_completion() {
1549 key_context.add("copilot_suggestion");
1550 key_context.add("edit_prediction");
1551
1552 if showing_completions || self.edit_prediction_requires_modifier() {
1553 key_context.add(EDIT_PREDICTION_REQUIRES_MODIFIER_KEY_CONTEXT);
1554 }
1555 }
1556
1557 if self.selection_mark_mode {
1558 key_context.add("selection_mode");
1559 }
1560
1561 key_context
1562 }
1563
1564 pub fn new_file(
1565 workspace: &mut Workspace,
1566 _: &workspace::NewFile,
1567 window: &mut Window,
1568 cx: &mut Context<Workspace>,
1569 ) {
1570 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1571 "Failed to create buffer",
1572 window,
1573 cx,
1574 |e, _, _| match e.error_code() {
1575 ErrorCode::RemoteUpgradeRequired => Some(format!(
1576 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1577 e.error_tag("required").unwrap_or("the latest version")
1578 )),
1579 _ => None,
1580 },
1581 );
1582 }
1583
1584 pub fn new_in_workspace(
1585 workspace: &mut Workspace,
1586 window: &mut Window,
1587 cx: &mut Context<Workspace>,
1588 ) -> Task<Result<Entity<Editor>>> {
1589 let project = workspace.project().clone();
1590 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1591
1592 cx.spawn_in(window, |workspace, mut cx| async move {
1593 let buffer = create.await?;
1594 workspace.update_in(&mut cx, |workspace, window, cx| {
1595 let editor =
1596 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1597 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1598 editor
1599 })
1600 })
1601 }
1602
1603 fn new_file_vertical(
1604 workspace: &mut Workspace,
1605 _: &workspace::NewFileSplitVertical,
1606 window: &mut Window,
1607 cx: &mut Context<Workspace>,
1608 ) {
1609 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1610 }
1611
1612 fn new_file_horizontal(
1613 workspace: &mut Workspace,
1614 _: &workspace::NewFileSplitHorizontal,
1615 window: &mut Window,
1616 cx: &mut Context<Workspace>,
1617 ) {
1618 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1619 }
1620
1621 fn new_file_in_direction(
1622 workspace: &mut Workspace,
1623 direction: SplitDirection,
1624 window: &mut Window,
1625 cx: &mut Context<Workspace>,
1626 ) {
1627 let project = workspace.project().clone();
1628 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1629
1630 cx.spawn_in(window, |workspace, mut cx| async move {
1631 let buffer = create.await?;
1632 workspace.update_in(&mut cx, move |workspace, window, cx| {
1633 workspace.split_item(
1634 direction,
1635 Box::new(
1636 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1637 ),
1638 window,
1639 cx,
1640 )
1641 })?;
1642 anyhow::Ok(())
1643 })
1644 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1645 match e.error_code() {
1646 ErrorCode::RemoteUpgradeRequired => Some(format!(
1647 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1648 e.error_tag("required").unwrap_or("the latest version")
1649 )),
1650 _ => None,
1651 }
1652 });
1653 }
1654
1655 pub fn leader_peer_id(&self) -> Option<PeerId> {
1656 self.leader_peer_id
1657 }
1658
1659 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1660 &self.buffer
1661 }
1662
1663 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1664 self.workspace.as_ref()?.0.upgrade()
1665 }
1666
1667 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1668 self.buffer().read(cx).title(cx)
1669 }
1670
1671 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1672 let git_blame_gutter_max_author_length = self
1673 .render_git_blame_gutter(cx)
1674 .then(|| {
1675 if let Some(blame) = self.blame.as_ref() {
1676 let max_author_length =
1677 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1678 Some(max_author_length)
1679 } else {
1680 None
1681 }
1682 })
1683 .flatten();
1684
1685 EditorSnapshot {
1686 mode: self.mode,
1687 show_gutter: self.show_gutter,
1688 show_line_numbers: self.show_line_numbers,
1689 show_git_diff_gutter: self.show_git_diff_gutter,
1690 show_code_actions: self.show_code_actions,
1691 show_runnables: self.show_runnables,
1692 git_blame_gutter_max_author_length,
1693 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1694 scroll_anchor: self.scroll_manager.anchor(),
1695 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1696 placeholder_text: self.placeholder_text.clone(),
1697 is_focused: self.focus_handle.is_focused(window),
1698 current_line_highlight: self
1699 .current_line_highlight
1700 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1701 gutter_hovered: self.gutter_hovered,
1702 }
1703 }
1704
1705 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1706 self.buffer.read(cx).language_at(point, cx)
1707 }
1708
1709 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1710 self.buffer.read(cx).read(cx).file_at(point).cloned()
1711 }
1712
1713 pub fn active_excerpt(
1714 &self,
1715 cx: &App,
1716 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1717 self.buffer
1718 .read(cx)
1719 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1720 }
1721
1722 pub fn mode(&self) -> EditorMode {
1723 self.mode
1724 }
1725
1726 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1727 self.collaboration_hub.as_deref()
1728 }
1729
1730 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1731 self.collaboration_hub = Some(hub);
1732 }
1733
1734 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1735 self.in_project_search = in_project_search;
1736 }
1737
1738 pub fn set_custom_context_menu(
1739 &mut self,
1740 f: impl 'static
1741 + Fn(
1742 &mut Self,
1743 DisplayPoint,
1744 &mut Window,
1745 &mut Context<Self>,
1746 ) -> Option<Entity<ui::ContextMenu>>,
1747 ) {
1748 self.custom_context_menu = Some(Box::new(f))
1749 }
1750
1751 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1752 self.completion_provider = provider;
1753 }
1754
1755 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1756 self.semantics_provider.clone()
1757 }
1758
1759 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1760 self.semantics_provider = provider;
1761 }
1762
1763 pub fn set_edit_prediction_provider<T>(
1764 &mut self,
1765 provider: Option<Entity<T>>,
1766 window: &mut Window,
1767 cx: &mut Context<Self>,
1768 ) where
1769 T: EditPredictionProvider,
1770 {
1771 self.edit_prediction_provider =
1772 provider.map(|provider| RegisteredInlineCompletionProvider {
1773 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1774 if this.focus_handle.is_focused(window) {
1775 this.update_visible_inline_completion(window, cx);
1776 }
1777 }),
1778 provider: Arc::new(provider),
1779 });
1780 self.refresh_inline_completion(false, false, window, cx);
1781 }
1782
1783 pub fn placeholder_text(&self) -> Option<&str> {
1784 self.placeholder_text.as_deref()
1785 }
1786
1787 pub fn set_placeholder_text(
1788 &mut self,
1789 placeholder_text: impl Into<Arc<str>>,
1790 cx: &mut Context<Self>,
1791 ) {
1792 let placeholder_text = Some(placeholder_text.into());
1793 if self.placeholder_text != placeholder_text {
1794 self.placeholder_text = placeholder_text;
1795 cx.notify();
1796 }
1797 }
1798
1799 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1800 self.cursor_shape = cursor_shape;
1801
1802 // Disrupt blink for immediate user feedback that the cursor shape has changed
1803 self.blink_manager.update(cx, BlinkManager::show_cursor);
1804
1805 cx.notify();
1806 }
1807
1808 pub fn set_current_line_highlight(
1809 &mut self,
1810 current_line_highlight: Option<CurrentLineHighlight>,
1811 ) {
1812 self.current_line_highlight = current_line_highlight;
1813 }
1814
1815 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1816 self.collapse_matches = collapse_matches;
1817 }
1818
1819 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1820 let buffers = self.buffer.read(cx).all_buffers();
1821 let Some(lsp_store) = self.lsp_store(cx) else {
1822 return;
1823 };
1824 lsp_store.update(cx, |lsp_store, cx| {
1825 for buffer in buffers {
1826 self.registered_buffers
1827 .entry(buffer.read(cx).remote_id())
1828 .or_insert_with(|| {
1829 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1830 });
1831 }
1832 })
1833 }
1834
1835 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1836 if self.collapse_matches {
1837 return range.start..range.start;
1838 }
1839 range.clone()
1840 }
1841
1842 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1843 if self.display_map.read(cx).clip_at_line_ends != clip {
1844 self.display_map
1845 .update(cx, |map, _| map.clip_at_line_ends = clip);
1846 }
1847 }
1848
1849 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1850 self.input_enabled = input_enabled;
1851 }
1852
1853 pub fn set_inline_completions_hidden_for_vim_mode(
1854 &mut self,
1855 hidden: bool,
1856 window: &mut Window,
1857 cx: &mut Context<Self>,
1858 ) {
1859 if hidden != self.inline_completions_hidden_for_vim_mode {
1860 self.inline_completions_hidden_for_vim_mode = hidden;
1861 if hidden {
1862 self.update_visible_inline_completion(window, cx);
1863 } else {
1864 self.refresh_inline_completion(true, false, window, cx);
1865 }
1866 }
1867 }
1868
1869 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1870 self.menu_inline_completions_policy = value;
1871 }
1872
1873 pub fn set_autoindent(&mut self, autoindent: bool) {
1874 if autoindent {
1875 self.autoindent_mode = Some(AutoindentMode::EachLine);
1876 } else {
1877 self.autoindent_mode = None;
1878 }
1879 }
1880
1881 pub fn read_only(&self, cx: &App) -> bool {
1882 self.read_only || self.buffer.read(cx).read_only()
1883 }
1884
1885 pub fn set_read_only(&mut self, read_only: bool) {
1886 self.read_only = read_only;
1887 }
1888
1889 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1890 self.use_autoclose = autoclose;
1891 }
1892
1893 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1894 self.use_auto_surround = auto_surround;
1895 }
1896
1897 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1898 self.auto_replace_emoji_shortcode = auto_replace;
1899 }
1900
1901 pub fn toggle_inline_completions(
1902 &mut self,
1903 _: &ToggleEditPrediction,
1904 window: &mut Window,
1905 cx: &mut Context<Self>,
1906 ) {
1907 if self.show_inline_completions_override.is_some() {
1908 self.set_show_edit_predictions(None, window, cx);
1909 } else {
1910 let show_edit_predictions = !self.edit_predictions_enabled();
1911 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
1912 }
1913 }
1914
1915 pub fn set_show_edit_predictions(
1916 &mut self,
1917 show_edit_predictions: Option<bool>,
1918 window: &mut Window,
1919 cx: &mut Context<Self>,
1920 ) {
1921 self.show_inline_completions_override = show_edit_predictions;
1922 self.refresh_inline_completion(false, true, window, cx);
1923 }
1924
1925 pub fn inline_completion_start_anchor(&self) -> Option<Anchor> {
1926 let active_completion = self.active_inline_completion.as_ref()?;
1927 let result = match &active_completion.completion {
1928 InlineCompletion::Edit { edits, .. } => edits.first()?.0.start,
1929 InlineCompletion::Move { target, .. } => *target,
1930 };
1931 Some(result)
1932 }
1933
1934 fn inline_completions_disabled_in_scope(
1935 &self,
1936 buffer: &Entity<Buffer>,
1937 buffer_position: language::Anchor,
1938 cx: &App,
1939 ) -> bool {
1940 let snapshot = buffer.read(cx).snapshot();
1941 let settings = snapshot.settings_at(buffer_position, cx);
1942
1943 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1944 return false;
1945 };
1946
1947 scope.override_name().map_or(false, |scope_name| {
1948 settings
1949 .edit_predictions_disabled_in
1950 .iter()
1951 .any(|s| s == scope_name)
1952 })
1953 }
1954
1955 pub fn set_use_modal_editing(&mut self, to: bool) {
1956 self.use_modal_editing = to;
1957 }
1958
1959 pub fn use_modal_editing(&self) -> bool {
1960 self.use_modal_editing
1961 }
1962
1963 fn selections_did_change(
1964 &mut self,
1965 local: bool,
1966 old_cursor_position: &Anchor,
1967 show_completions: bool,
1968 window: &mut Window,
1969 cx: &mut Context<Self>,
1970 ) {
1971 window.invalidate_character_coordinates();
1972
1973 // Copy selections to primary selection buffer
1974 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1975 if local {
1976 let selections = self.selections.all::<usize>(cx);
1977 let buffer_handle = self.buffer.read(cx).read(cx);
1978
1979 let mut text = String::new();
1980 for (index, selection) in selections.iter().enumerate() {
1981 let text_for_selection = buffer_handle
1982 .text_for_range(selection.start..selection.end)
1983 .collect::<String>();
1984
1985 text.push_str(&text_for_selection);
1986 if index != selections.len() - 1 {
1987 text.push('\n');
1988 }
1989 }
1990
1991 if !text.is_empty() {
1992 cx.write_to_primary(ClipboardItem::new_string(text));
1993 }
1994 }
1995
1996 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
1997 self.buffer.update(cx, |buffer, cx| {
1998 buffer.set_active_selections(
1999 &self.selections.disjoint_anchors(),
2000 self.selections.line_mode,
2001 self.cursor_shape,
2002 cx,
2003 )
2004 });
2005 }
2006 let display_map = self
2007 .display_map
2008 .update(cx, |display_map, cx| display_map.snapshot(cx));
2009 let buffer = &display_map.buffer_snapshot;
2010 self.add_selections_state = None;
2011 self.select_next_state = None;
2012 self.select_prev_state = None;
2013 self.select_larger_syntax_node_stack.clear();
2014 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2015 self.snippet_stack
2016 .invalidate(&self.selections.disjoint_anchors(), buffer);
2017 self.take_rename(false, window, cx);
2018
2019 let new_cursor_position = self.selections.newest_anchor().head();
2020
2021 self.push_to_nav_history(
2022 *old_cursor_position,
2023 Some(new_cursor_position.to_point(buffer)),
2024 cx,
2025 );
2026
2027 if local {
2028 let new_cursor_position = self.selections.newest_anchor().head();
2029 let mut context_menu = self.context_menu.borrow_mut();
2030 let completion_menu = match context_menu.as_ref() {
2031 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2032 _ => {
2033 *context_menu = None;
2034 None
2035 }
2036 };
2037 if let Some(buffer_id) = new_cursor_position.buffer_id {
2038 if !self.registered_buffers.contains_key(&buffer_id) {
2039 if let Some(lsp_store) = self.lsp_store(cx) {
2040 lsp_store.update(cx, |lsp_store, cx| {
2041 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2042 return;
2043 };
2044 self.registered_buffers.insert(
2045 buffer_id,
2046 lsp_store.register_buffer_with_language_servers(&buffer, cx),
2047 );
2048 })
2049 }
2050 }
2051 }
2052
2053 if let Some(completion_menu) = completion_menu {
2054 let cursor_position = new_cursor_position.to_offset(buffer);
2055 let (word_range, kind) =
2056 buffer.surrounding_word(completion_menu.initial_position, true);
2057 if kind == Some(CharKind::Word)
2058 && word_range.to_inclusive().contains(&cursor_position)
2059 {
2060 let mut completion_menu = completion_menu.clone();
2061 drop(context_menu);
2062
2063 let query = Self::completion_query(buffer, cursor_position);
2064 cx.spawn(move |this, mut cx| async move {
2065 completion_menu
2066 .filter(query.as_deref(), cx.background_executor().clone())
2067 .await;
2068
2069 this.update(&mut cx, |this, cx| {
2070 let mut context_menu = this.context_menu.borrow_mut();
2071 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2072 else {
2073 return;
2074 };
2075
2076 if menu.id > completion_menu.id {
2077 return;
2078 }
2079
2080 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2081 drop(context_menu);
2082 cx.notify();
2083 })
2084 })
2085 .detach();
2086
2087 if show_completions {
2088 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2089 }
2090 } else {
2091 drop(context_menu);
2092 self.hide_context_menu(window, cx);
2093 }
2094 } else {
2095 drop(context_menu);
2096 }
2097
2098 hide_hover(self, cx);
2099
2100 if old_cursor_position.to_display_point(&display_map).row()
2101 != new_cursor_position.to_display_point(&display_map).row()
2102 {
2103 self.available_code_actions.take();
2104 }
2105 self.refresh_code_actions(window, cx);
2106 self.refresh_document_highlights(cx);
2107 refresh_matching_bracket_highlights(self, window, cx);
2108 self.update_visible_inline_completion(window, cx);
2109 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2110 if self.git_blame_inline_enabled {
2111 self.start_inline_blame_timer(window, cx);
2112 }
2113 }
2114
2115 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2116 cx.emit(EditorEvent::SelectionsChanged { local });
2117
2118 if self.selections.disjoint_anchors().len() == 1 {
2119 cx.emit(SearchEvent::ActiveMatchChanged)
2120 }
2121 cx.notify();
2122 }
2123
2124 pub fn change_selections<R>(
2125 &mut self,
2126 autoscroll: Option<Autoscroll>,
2127 window: &mut Window,
2128 cx: &mut Context<Self>,
2129 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2130 ) -> R {
2131 self.change_selections_inner(autoscroll, true, window, cx, change)
2132 }
2133
2134 pub fn change_selections_inner<R>(
2135 &mut self,
2136 autoscroll: Option<Autoscroll>,
2137 request_completions: bool,
2138 window: &mut Window,
2139 cx: &mut Context<Self>,
2140 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2141 ) -> R {
2142 let old_cursor_position = self.selections.newest_anchor().head();
2143 self.push_to_selection_history();
2144
2145 let (changed, result) = self.selections.change_with(cx, change);
2146
2147 if changed {
2148 if let Some(autoscroll) = autoscroll {
2149 self.request_autoscroll(autoscroll, cx);
2150 }
2151 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2152
2153 if self.should_open_signature_help_automatically(
2154 &old_cursor_position,
2155 self.signature_help_state.backspace_pressed(),
2156 cx,
2157 ) {
2158 self.show_signature_help(&ShowSignatureHelp, window, cx);
2159 }
2160 self.signature_help_state.set_backspace_pressed(false);
2161 }
2162
2163 result
2164 }
2165
2166 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2167 where
2168 I: IntoIterator<Item = (Range<S>, T)>,
2169 S: ToOffset,
2170 T: Into<Arc<str>>,
2171 {
2172 if self.read_only(cx) {
2173 return;
2174 }
2175
2176 self.buffer
2177 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2178 }
2179
2180 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2181 where
2182 I: IntoIterator<Item = (Range<S>, T)>,
2183 S: ToOffset,
2184 T: Into<Arc<str>>,
2185 {
2186 if self.read_only(cx) {
2187 return;
2188 }
2189
2190 self.buffer.update(cx, |buffer, cx| {
2191 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2192 });
2193 }
2194
2195 pub fn edit_with_block_indent<I, S, T>(
2196 &mut self,
2197 edits: I,
2198 original_indent_columns: Vec<u32>,
2199 cx: &mut Context<Self>,
2200 ) where
2201 I: IntoIterator<Item = (Range<S>, T)>,
2202 S: ToOffset,
2203 T: Into<Arc<str>>,
2204 {
2205 if self.read_only(cx) {
2206 return;
2207 }
2208
2209 self.buffer.update(cx, |buffer, cx| {
2210 buffer.edit(
2211 edits,
2212 Some(AutoindentMode::Block {
2213 original_indent_columns,
2214 }),
2215 cx,
2216 )
2217 });
2218 }
2219
2220 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2221 self.hide_context_menu(window, cx);
2222
2223 match phase {
2224 SelectPhase::Begin {
2225 position,
2226 add,
2227 click_count,
2228 } => self.begin_selection(position, add, click_count, window, cx),
2229 SelectPhase::BeginColumnar {
2230 position,
2231 goal_column,
2232 reset,
2233 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2234 SelectPhase::Extend {
2235 position,
2236 click_count,
2237 } => self.extend_selection(position, click_count, window, cx),
2238 SelectPhase::Update {
2239 position,
2240 goal_column,
2241 scroll_delta,
2242 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2243 SelectPhase::End => self.end_selection(window, cx),
2244 }
2245 }
2246
2247 fn extend_selection(
2248 &mut self,
2249 position: DisplayPoint,
2250 click_count: usize,
2251 window: &mut Window,
2252 cx: &mut Context<Self>,
2253 ) {
2254 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2255 let tail = self.selections.newest::<usize>(cx).tail();
2256 self.begin_selection(position, false, click_count, window, cx);
2257
2258 let position = position.to_offset(&display_map, Bias::Left);
2259 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2260
2261 let mut pending_selection = self
2262 .selections
2263 .pending_anchor()
2264 .expect("extend_selection not called with pending selection");
2265 if position >= tail {
2266 pending_selection.start = tail_anchor;
2267 } else {
2268 pending_selection.end = tail_anchor;
2269 pending_selection.reversed = true;
2270 }
2271
2272 let mut pending_mode = self.selections.pending_mode().unwrap();
2273 match &mut pending_mode {
2274 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2275 _ => {}
2276 }
2277
2278 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2279 s.set_pending(pending_selection, pending_mode)
2280 });
2281 }
2282
2283 fn begin_selection(
2284 &mut self,
2285 position: DisplayPoint,
2286 add: bool,
2287 click_count: usize,
2288 window: &mut Window,
2289 cx: &mut Context<Self>,
2290 ) {
2291 if !self.focus_handle.is_focused(window) {
2292 self.last_focused_descendant = None;
2293 window.focus(&self.focus_handle);
2294 }
2295
2296 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2297 let buffer = &display_map.buffer_snapshot;
2298 let newest_selection = self.selections.newest_anchor().clone();
2299 let position = display_map.clip_point(position, Bias::Left);
2300
2301 let start;
2302 let end;
2303 let mode;
2304 let mut auto_scroll;
2305 match click_count {
2306 1 => {
2307 start = buffer.anchor_before(position.to_point(&display_map));
2308 end = start;
2309 mode = SelectMode::Character;
2310 auto_scroll = true;
2311 }
2312 2 => {
2313 let range = movement::surrounding_word(&display_map, position);
2314 start = buffer.anchor_before(range.start.to_point(&display_map));
2315 end = buffer.anchor_before(range.end.to_point(&display_map));
2316 mode = SelectMode::Word(start..end);
2317 auto_scroll = true;
2318 }
2319 3 => {
2320 let position = display_map
2321 .clip_point(position, Bias::Left)
2322 .to_point(&display_map);
2323 let line_start = display_map.prev_line_boundary(position).0;
2324 let next_line_start = buffer.clip_point(
2325 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2326 Bias::Left,
2327 );
2328 start = buffer.anchor_before(line_start);
2329 end = buffer.anchor_before(next_line_start);
2330 mode = SelectMode::Line(start..end);
2331 auto_scroll = true;
2332 }
2333 _ => {
2334 start = buffer.anchor_before(0);
2335 end = buffer.anchor_before(buffer.len());
2336 mode = SelectMode::All;
2337 auto_scroll = false;
2338 }
2339 }
2340 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2341
2342 let point_to_delete: Option<usize> = {
2343 let selected_points: Vec<Selection<Point>> =
2344 self.selections.disjoint_in_range(start..end, cx);
2345
2346 if !add || click_count > 1 {
2347 None
2348 } else if !selected_points.is_empty() {
2349 Some(selected_points[0].id)
2350 } else {
2351 let clicked_point_already_selected =
2352 self.selections.disjoint.iter().find(|selection| {
2353 selection.start.to_point(buffer) == start.to_point(buffer)
2354 || selection.end.to_point(buffer) == end.to_point(buffer)
2355 });
2356
2357 clicked_point_already_selected.map(|selection| selection.id)
2358 }
2359 };
2360
2361 let selections_count = self.selections.count();
2362
2363 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2364 if let Some(point_to_delete) = point_to_delete {
2365 s.delete(point_to_delete);
2366
2367 if selections_count == 1 {
2368 s.set_pending_anchor_range(start..end, mode);
2369 }
2370 } else {
2371 if !add {
2372 s.clear_disjoint();
2373 } else if click_count > 1 {
2374 s.delete(newest_selection.id)
2375 }
2376
2377 s.set_pending_anchor_range(start..end, mode);
2378 }
2379 });
2380 }
2381
2382 fn begin_columnar_selection(
2383 &mut self,
2384 position: DisplayPoint,
2385 goal_column: u32,
2386 reset: bool,
2387 window: &mut Window,
2388 cx: &mut Context<Self>,
2389 ) {
2390 if !self.focus_handle.is_focused(window) {
2391 self.last_focused_descendant = None;
2392 window.focus(&self.focus_handle);
2393 }
2394
2395 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2396
2397 if reset {
2398 let pointer_position = display_map
2399 .buffer_snapshot
2400 .anchor_before(position.to_point(&display_map));
2401
2402 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2403 s.clear_disjoint();
2404 s.set_pending_anchor_range(
2405 pointer_position..pointer_position,
2406 SelectMode::Character,
2407 );
2408 });
2409 }
2410
2411 let tail = self.selections.newest::<Point>(cx).tail();
2412 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2413
2414 if !reset {
2415 self.select_columns(
2416 tail.to_display_point(&display_map),
2417 position,
2418 goal_column,
2419 &display_map,
2420 window,
2421 cx,
2422 );
2423 }
2424 }
2425
2426 fn update_selection(
2427 &mut self,
2428 position: DisplayPoint,
2429 goal_column: u32,
2430 scroll_delta: gpui::Point<f32>,
2431 window: &mut Window,
2432 cx: &mut Context<Self>,
2433 ) {
2434 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2435
2436 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2437 let tail = tail.to_display_point(&display_map);
2438 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2439 } else if let Some(mut pending) = self.selections.pending_anchor() {
2440 let buffer = self.buffer.read(cx).snapshot(cx);
2441 let head;
2442 let tail;
2443 let mode = self.selections.pending_mode().unwrap();
2444 match &mode {
2445 SelectMode::Character => {
2446 head = position.to_point(&display_map);
2447 tail = pending.tail().to_point(&buffer);
2448 }
2449 SelectMode::Word(original_range) => {
2450 let original_display_range = original_range.start.to_display_point(&display_map)
2451 ..original_range.end.to_display_point(&display_map);
2452 let original_buffer_range = original_display_range.start.to_point(&display_map)
2453 ..original_display_range.end.to_point(&display_map);
2454 if movement::is_inside_word(&display_map, position)
2455 || original_display_range.contains(&position)
2456 {
2457 let word_range = movement::surrounding_word(&display_map, position);
2458 if word_range.start < original_display_range.start {
2459 head = word_range.start.to_point(&display_map);
2460 } else {
2461 head = word_range.end.to_point(&display_map);
2462 }
2463 } else {
2464 head = position.to_point(&display_map);
2465 }
2466
2467 if head <= original_buffer_range.start {
2468 tail = original_buffer_range.end;
2469 } else {
2470 tail = original_buffer_range.start;
2471 }
2472 }
2473 SelectMode::Line(original_range) => {
2474 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2475
2476 let position = display_map
2477 .clip_point(position, Bias::Left)
2478 .to_point(&display_map);
2479 let line_start = display_map.prev_line_boundary(position).0;
2480 let next_line_start = buffer.clip_point(
2481 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2482 Bias::Left,
2483 );
2484
2485 if line_start < original_range.start {
2486 head = line_start
2487 } else {
2488 head = next_line_start
2489 }
2490
2491 if head <= original_range.start {
2492 tail = original_range.end;
2493 } else {
2494 tail = original_range.start;
2495 }
2496 }
2497 SelectMode::All => {
2498 return;
2499 }
2500 };
2501
2502 if head < tail {
2503 pending.start = buffer.anchor_before(head);
2504 pending.end = buffer.anchor_before(tail);
2505 pending.reversed = true;
2506 } else {
2507 pending.start = buffer.anchor_before(tail);
2508 pending.end = buffer.anchor_before(head);
2509 pending.reversed = false;
2510 }
2511
2512 self.change_selections(None, window, cx, |s| {
2513 s.set_pending(pending, mode);
2514 });
2515 } else {
2516 log::error!("update_selection dispatched with no pending selection");
2517 return;
2518 }
2519
2520 self.apply_scroll_delta(scroll_delta, window, cx);
2521 cx.notify();
2522 }
2523
2524 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2525 self.columnar_selection_tail.take();
2526 if self.selections.pending_anchor().is_some() {
2527 let selections = self.selections.all::<usize>(cx);
2528 self.change_selections(None, window, cx, |s| {
2529 s.select(selections);
2530 s.clear_pending();
2531 });
2532 }
2533 }
2534
2535 fn select_columns(
2536 &mut self,
2537 tail: DisplayPoint,
2538 head: DisplayPoint,
2539 goal_column: u32,
2540 display_map: &DisplaySnapshot,
2541 window: &mut Window,
2542 cx: &mut Context<Self>,
2543 ) {
2544 let start_row = cmp::min(tail.row(), head.row());
2545 let end_row = cmp::max(tail.row(), head.row());
2546 let start_column = cmp::min(tail.column(), goal_column);
2547 let end_column = cmp::max(tail.column(), goal_column);
2548 let reversed = start_column < tail.column();
2549
2550 let selection_ranges = (start_row.0..=end_row.0)
2551 .map(DisplayRow)
2552 .filter_map(|row| {
2553 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2554 let start = display_map
2555 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2556 .to_point(display_map);
2557 let end = display_map
2558 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2559 .to_point(display_map);
2560 if reversed {
2561 Some(end..start)
2562 } else {
2563 Some(start..end)
2564 }
2565 } else {
2566 None
2567 }
2568 })
2569 .collect::<Vec<_>>();
2570
2571 self.change_selections(None, window, cx, |s| {
2572 s.select_ranges(selection_ranges);
2573 });
2574 cx.notify();
2575 }
2576
2577 pub fn has_pending_nonempty_selection(&self) -> bool {
2578 let pending_nonempty_selection = match self.selections.pending_anchor() {
2579 Some(Selection { start, end, .. }) => start != end,
2580 None => false,
2581 };
2582
2583 pending_nonempty_selection
2584 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2585 }
2586
2587 pub fn has_pending_selection(&self) -> bool {
2588 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2589 }
2590
2591 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2592 self.selection_mark_mode = false;
2593
2594 if self.clear_expanded_diff_hunks(cx) {
2595 cx.notify();
2596 return;
2597 }
2598 if self.dismiss_menus_and_popups(true, window, cx) {
2599 return;
2600 }
2601
2602 if self.mode == EditorMode::Full
2603 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2604 {
2605 return;
2606 }
2607
2608 cx.propagate();
2609 }
2610
2611 pub fn dismiss_menus_and_popups(
2612 &mut self,
2613 is_user_requested: bool,
2614 window: &mut Window,
2615 cx: &mut Context<Self>,
2616 ) -> bool {
2617 if self.take_rename(false, window, cx).is_some() {
2618 return true;
2619 }
2620
2621 if hide_hover(self, cx) {
2622 return true;
2623 }
2624
2625 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2626 return true;
2627 }
2628
2629 if self.hide_context_menu(window, cx).is_some() {
2630 return true;
2631 }
2632
2633 if self.mouse_context_menu.take().is_some() {
2634 return true;
2635 }
2636
2637 if is_user_requested && self.discard_inline_completion(true, cx) {
2638 return true;
2639 }
2640
2641 if self.snippet_stack.pop().is_some() {
2642 return true;
2643 }
2644
2645 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2646 self.dismiss_diagnostics(cx);
2647 return true;
2648 }
2649
2650 false
2651 }
2652
2653 fn linked_editing_ranges_for(
2654 &self,
2655 selection: Range<text::Anchor>,
2656 cx: &App,
2657 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2658 if self.linked_edit_ranges.is_empty() {
2659 return None;
2660 }
2661 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2662 selection.end.buffer_id.and_then(|end_buffer_id| {
2663 if selection.start.buffer_id != Some(end_buffer_id) {
2664 return None;
2665 }
2666 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2667 let snapshot = buffer.read(cx).snapshot();
2668 self.linked_edit_ranges
2669 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2670 .map(|ranges| (ranges, snapshot, buffer))
2671 })?;
2672 use text::ToOffset as TO;
2673 // find offset from the start of current range to current cursor position
2674 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2675
2676 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2677 let start_difference = start_offset - start_byte_offset;
2678 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2679 let end_difference = end_offset - start_byte_offset;
2680 // Current range has associated linked ranges.
2681 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2682 for range in linked_ranges.iter() {
2683 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2684 let end_offset = start_offset + end_difference;
2685 let start_offset = start_offset + start_difference;
2686 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2687 continue;
2688 }
2689 if self.selections.disjoint_anchor_ranges().any(|s| {
2690 if s.start.buffer_id != selection.start.buffer_id
2691 || s.end.buffer_id != selection.end.buffer_id
2692 {
2693 return false;
2694 }
2695 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2696 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2697 }) {
2698 continue;
2699 }
2700 let start = buffer_snapshot.anchor_after(start_offset);
2701 let end = buffer_snapshot.anchor_after(end_offset);
2702 linked_edits
2703 .entry(buffer.clone())
2704 .or_default()
2705 .push(start..end);
2706 }
2707 Some(linked_edits)
2708 }
2709
2710 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2711 let text: Arc<str> = text.into();
2712
2713 if self.read_only(cx) {
2714 return;
2715 }
2716
2717 let selections = self.selections.all_adjusted(cx);
2718 let mut bracket_inserted = false;
2719 let mut edits = Vec::new();
2720 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2721 let mut new_selections = Vec::with_capacity(selections.len());
2722 let mut new_autoclose_regions = Vec::new();
2723 let snapshot = self.buffer.read(cx).read(cx);
2724
2725 for (selection, autoclose_region) in
2726 self.selections_with_autoclose_regions(selections, &snapshot)
2727 {
2728 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2729 // Determine if the inserted text matches the opening or closing
2730 // bracket of any of this language's bracket pairs.
2731 let mut bracket_pair = None;
2732 let mut is_bracket_pair_start = false;
2733 let mut is_bracket_pair_end = false;
2734 if !text.is_empty() {
2735 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2736 // and they are removing the character that triggered IME popup.
2737 for (pair, enabled) in scope.brackets() {
2738 if !pair.close && !pair.surround {
2739 continue;
2740 }
2741
2742 if enabled && pair.start.ends_with(text.as_ref()) {
2743 let prefix_len = pair.start.len() - text.len();
2744 let preceding_text_matches_prefix = prefix_len == 0
2745 || (selection.start.column >= (prefix_len as u32)
2746 && snapshot.contains_str_at(
2747 Point::new(
2748 selection.start.row,
2749 selection.start.column - (prefix_len as u32),
2750 ),
2751 &pair.start[..prefix_len],
2752 ));
2753 if preceding_text_matches_prefix {
2754 bracket_pair = Some(pair.clone());
2755 is_bracket_pair_start = true;
2756 break;
2757 }
2758 }
2759 if pair.end.as_str() == text.as_ref() {
2760 bracket_pair = Some(pair.clone());
2761 is_bracket_pair_end = true;
2762 break;
2763 }
2764 }
2765 }
2766
2767 if let Some(bracket_pair) = bracket_pair {
2768 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2769 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2770 let auto_surround =
2771 self.use_auto_surround && snapshot_settings.use_auto_surround;
2772 if selection.is_empty() {
2773 if is_bracket_pair_start {
2774 // If the inserted text is a suffix of an opening bracket and the
2775 // selection is preceded by the rest of the opening bracket, then
2776 // insert the closing bracket.
2777 let following_text_allows_autoclose = snapshot
2778 .chars_at(selection.start)
2779 .next()
2780 .map_or(true, |c| scope.should_autoclose_before(c));
2781
2782 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2783 && bracket_pair.start.len() == 1
2784 {
2785 let target = bracket_pair.start.chars().next().unwrap();
2786 let current_line_count = snapshot
2787 .reversed_chars_at(selection.start)
2788 .take_while(|&c| c != '\n')
2789 .filter(|&c| c == target)
2790 .count();
2791 current_line_count % 2 == 1
2792 } else {
2793 false
2794 };
2795
2796 if autoclose
2797 && bracket_pair.close
2798 && following_text_allows_autoclose
2799 && !is_closing_quote
2800 {
2801 let anchor = snapshot.anchor_before(selection.end);
2802 new_selections.push((selection.map(|_| anchor), text.len()));
2803 new_autoclose_regions.push((
2804 anchor,
2805 text.len(),
2806 selection.id,
2807 bracket_pair.clone(),
2808 ));
2809 edits.push((
2810 selection.range(),
2811 format!("{}{}", text, bracket_pair.end).into(),
2812 ));
2813 bracket_inserted = true;
2814 continue;
2815 }
2816 }
2817
2818 if let Some(region) = autoclose_region {
2819 // If the selection is followed by an auto-inserted closing bracket,
2820 // then don't insert that closing bracket again; just move the selection
2821 // past the closing bracket.
2822 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2823 && text.as_ref() == region.pair.end.as_str();
2824 if should_skip {
2825 let anchor = snapshot.anchor_after(selection.end);
2826 new_selections
2827 .push((selection.map(|_| anchor), region.pair.end.len()));
2828 continue;
2829 }
2830 }
2831
2832 let always_treat_brackets_as_autoclosed = snapshot
2833 .settings_at(selection.start, cx)
2834 .always_treat_brackets_as_autoclosed;
2835 if always_treat_brackets_as_autoclosed
2836 && is_bracket_pair_end
2837 && snapshot.contains_str_at(selection.end, text.as_ref())
2838 {
2839 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2840 // and the inserted text is a closing bracket and the selection is followed
2841 // by the closing bracket then move the selection past the closing bracket.
2842 let anchor = snapshot.anchor_after(selection.end);
2843 new_selections.push((selection.map(|_| anchor), text.len()));
2844 continue;
2845 }
2846 }
2847 // If an opening bracket is 1 character long and is typed while
2848 // text is selected, then surround that text with the bracket pair.
2849 else if auto_surround
2850 && bracket_pair.surround
2851 && is_bracket_pair_start
2852 && bracket_pair.start.chars().count() == 1
2853 {
2854 edits.push((selection.start..selection.start, text.clone()));
2855 edits.push((
2856 selection.end..selection.end,
2857 bracket_pair.end.as_str().into(),
2858 ));
2859 bracket_inserted = true;
2860 new_selections.push((
2861 Selection {
2862 id: selection.id,
2863 start: snapshot.anchor_after(selection.start),
2864 end: snapshot.anchor_before(selection.end),
2865 reversed: selection.reversed,
2866 goal: selection.goal,
2867 },
2868 0,
2869 ));
2870 continue;
2871 }
2872 }
2873 }
2874
2875 if self.auto_replace_emoji_shortcode
2876 && selection.is_empty()
2877 && text.as_ref().ends_with(':')
2878 {
2879 if let Some(possible_emoji_short_code) =
2880 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2881 {
2882 if !possible_emoji_short_code.is_empty() {
2883 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2884 let emoji_shortcode_start = Point::new(
2885 selection.start.row,
2886 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2887 );
2888
2889 // Remove shortcode from buffer
2890 edits.push((
2891 emoji_shortcode_start..selection.start,
2892 "".to_string().into(),
2893 ));
2894 new_selections.push((
2895 Selection {
2896 id: selection.id,
2897 start: snapshot.anchor_after(emoji_shortcode_start),
2898 end: snapshot.anchor_before(selection.start),
2899 reversed: selection.reversed,
2900 goal: selection.goal,
2901 },
2902 0,
2903 ));
2904
2905 // Insert emoji
2906 let selection_start_anchor = snapshot.anchor_after(selection.start);
2907 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2908 edits.push((selection.start..selection.end, emoji.to_string().into()));
2909
2910 continue;
2911 }
2912 }
2913 }
2914 }
2915
2916 // If not handling any auto-close operation, then just replace the selected
2917 // text with the given input and move the selection to the end of the
2918 // newly inserted text.
2919 let anchor = snapshot.anchor_after(selection.end);
2920 if !self.linked_edit_ranges.is_empty() {
2921 let start_anchor = snapshot.anchor_before(selection.start);
2922
2923 let is_word_char = text.chars().next().map_or(true, |char| {
2924 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2925 classifier.is_word(char)
2926 });
2927
2928 if is_word_char {
2929 if let Some(ranges) = self
2930 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2931 {
2932 for (buffer, edits) in ranges {
2933 linked_edits
2934 .entry(buffer.clone())
2935 .or_default()
2936 .extend(edits.into_iter().map(|range| (range, text.clone())));
2937 }
2938 }
2939 }
2940 }
2941
2942 new_selections.push((selection.map(|_| anchor), 0));
2943 edits.push((selection.start..selection.end, text.clone()));
2944 }
2945
2946 drop(snapshot);
2947
2948 self.transact(window, cx, |this, window, cx| {
2949 this.buffer.update(cx, |buffer, cx| {
2950 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2951 });
2952 for (buffer, edits) in linked_edits {
2953 buffer.update(cx, |buffer, cx| {
2954 let snapshot = buffer.snapshot();
2955 let edits = edits
2956 .into_iter()
2957 .map(|(range, text)| {
2958 use text::ToPoint as TP;
2959 let end_point = TP::to_point(&range.end, &snapshot);
2960 let start_point = TP::to_point(&range.start, &snapshot);
2961 (start_point..end_point, text)
2962 })
2963 .sorted_by_key(|(range, _)| range.start)
2964 .collect::<Vec<_>>();
2965 buffer.edit(edits, None, cx);
2966 })
2967 }
2968 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2969 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2970 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2971 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2972 .zip(new_selection_deltas)
2973 .map(|(selection, delta)| Selection {
2974 id: selection.id,
2975 start: selection.start + delta,
2976 end: selection.end + delta,
2977 reversed: selection.reversed,
2978 goal: SelectionGoal::None,
2979 })
2980 .collect::<Vec<_>>();
2981
2982 let mut i = 0;
2983 for (position, delta, selection_id, pair) in new_autoclose_regions {
2984 let position = position.to_offset(&map.buffer_snapshot) + delta;
2985 let start = map.buffer_snapshot.anchor_before(position);
2986 let end = map.buffer_snapshot.anchor_after(position);
2987 while let Some(existing_state) = this.autoclose_regions.get(i) {
2988 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2989 Ordering::Less => i += 1,
2990 Ordering::Greater => break,
2991 Ordering::Equal => {
2992 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2993 Ordering::Less => i += 1,
2994 Ordering::Equal => break,
2995 Ordering::Greater => break,
2996 }
2997 }
2998 }
2999 }
3000 this.autoclose_regions.insert(
3001 i,
3002 AutocloseRegion {
3003 selection_id,
3004 range: start..end,
3005 pair,
3006 },
3007 );
3008 }
3009
3010 let had_active_inline_completion = this.has_active_inline_completion();
3011 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3012 s.select(new_selections)
3013 });
3014
3015 if !bracket_inserted {
3016 if let Some(on_type_format_task) =
3017 this.trigger_on_type_formatting(text.to_string(), window, cx)
3018 {
3019 on_type_format_task.detach_and_log_err(cx);
3020 }
3021 }
3022
3023 let editor_settings = EditorSettings::get_global(cx);
3024 if bracket_inserted
3025 && (editor_settings.auto_signature_help
3026 || editor_settings.show_signature_help_after_edits)
3027 {
3028 this.show_signature_help(&ShowSignatureHelp, window, cx);
3029 }
3030
3031 let trigger_in_words =
3032 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3033 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3034 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3035 this.refresh_inline_completion(true, false, window, cx);
3036 });
3037 }
3038
3039 fn find_possible_emoji_shortcode_at_position(
3040 snapshot: &MultiBufferSnapshot,
3041 position: Point,
3042 ) -> Option<String> {
3043 let mut chars = Vec::new();
3044 let mut found_colon = false;
3045 for char in snapshot.reversed_chars_at(position).take(100) {
3046 // Found a possible emoji shortcode in the middle of the buffer
3047 if found_colon {
3048 if char.is_whitespace() {
3049 chars.reverse();
3050 return Some(chars.iter().collect());
3051 }
3052 // If the previous character is not a whitespace, we are in the middle of a word
3053 // and we only want to complete the shortcode if the word is made up of other emojis
3054 let mut containing_word = String::new();
3055 for ch in snapshot
3056 .reversed_chars_at(position)
3057 .skip(chars.len() + 1)
3058 .take(100)
3059 {
3060 if ch.is_whitespace() {
3061 break;
3062 }
3063 containing_word.push(ch);
3064 }
3065 let containing_word = containing_word.chars().rev().collect::<String>();
3066 if util::word_consists_of_emojis(containing_word.as_str()) {
3067 chars.reverse();
3068 return Some(chars.iter().collect());
3069 }
3070 }
3071
3072 if char.is_whitespace() || !char.is_ascii() {
3073 return None;
3074 }
3075 if char == ':' {
3076 found_colon = true;
3077 } else {
3078 chars.push(char);
3079 }
3080 }
3081 // Found a possible emoji shortcode at the beginning of the buffer
3082 chars.reverse();
3083 Some(chars.iter().collect())
3084 }
3085
3086 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3087 self.transact(window, cx, |this, window, cx| {
3088 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3089 let selections = this.selections.all::<usize>(cx);
3090 let multi_buffer = this.buffer.read(cx);
3091 let buffer = multi_buffer.snapshot(cx);
3092 selections
3093 .iter()
3094 .map(|selection| {
3095 let start_point = selection.start.to_point(&buffer);
3096 let mut indent =
3097 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3098 indent.len = cmp::min(indent.len, start_point.column);
3099 let start = selection.start;
3100 let end = selection.end;
3101 let selection_is_empty = start == end;
3102 let language_scope = buffer.language_scope_at(start);
3103 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3104 &language_scope
3105 {
3106 let leading_whitespace_len = buffer
3107 .reversed_chars_at(start)
3108 .take_while(|c| c.is_whitespace() && *c != '\n')
3109 .map(|c| c.len_utf8())
3110 .sum::<usize>();
3111
3112 let trailing_whitespace_len = buffer
3113 .chars_at(end)
3114 .take_while(|c| c.is_whitespace() && *c != '\n')
3115 .map(|c| c.len_utf8())
3116 .sum::<usize>();
3117
3118 let insert_extra_newline =
3119 language.brackets().any(|(pair, enabled)| {
3120 let pair_start = pair.start.trim_end();
3121 let pair_end = pair.end.trim_start();
3122
3123 enabled
3124 && pair.newline
3125 && buffer.contains_str_at(
3126 end + trailing_whitespace_len,
3127 pair_end,
3128 )
3129 && buffer.contains_str_at(
3130 (start - leading_whitespace_len)
3131 .saturating_sub(pair_start.len()),
3132 pair_start,
3133 )
3134 });
3135
3136 // Comment extension on newline is allowed only for cursor selections
3137 let comment_delimiter = maybe!({
3138 if !selection_is_empty {
3139 return None;
3140 }
3141
3142 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3143 return None;
3144 }
3145
3146 let delimiters = language.line_comment_prefixes();
3147 let max_len_of_delimiter =
3148 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3149 let (snapshot, range) =
3150 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3151
3152 let mut index_of_first_non_whitespace = 0;
3153 let comment_candidate = snapshot
3154 .chars_for_range(range)
3155 .skip_while(|c| {
3156 let should_skip = c.is_whitespace();
3157 if should_skip {
3158 index_of_first_non_whitespace += 1;
3159 }
3160 should_skip
3161 })
3162 .take(max_len_of_delimiter)
3163 .collect::<String>();
3164 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3165 comment_candidate.starts_with(comment_prefix.as_ref())
3166 })?;
3167 let cursor_is_placed_after_comment_marker =
3168 index_of_first_non_whitespace + comment_prefix.len()
3169 <= start_point.column as usize;
3170 if cursor_is_placed_after_comment_marker {
3171 Some(comment_prefix.clone())
3172 } else {
3173 None
3174 }
3175 });
3176 (comment_delimiter, insert_extra_newline)
3177 } else {
3178 (None, false)
3179 };
3180
3181 let capacity_for_delimiter = comment_delimiter
3182 .as_deref()
3183 .map(str::len)
3184 .unwrap_or_default();
3185 let mut new_text =
3186 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3187 new_text.push('\n');
3188 new_text.extend(indent.chars());
3189 if let Some(delimiter) = &comment_delimiter {
3190 new_text.push_str(delimiter);
3191 }
3192 if insert_extra_newline {
3193 new_text = new_text.repeat(2);
3194 }
3195
3196 let anchor = buffer.anchor_after(end);
3197 let new_selection = selection.map(|_| anchor);
3198 (
3199 (start..end, new_text),
3200 (insert_extra_newline, new_selection),
3201 )
3202 })
3203 .unzip()
3204 };
3205
3206 this.edit_with_autoindent(edits, cx);
3207 let buffer = this.buffer.read(cx).snapshot(cx);
3208 let new_selections = selection_fixup_info
3209 .into_iter()
3210 .map(|(extra_newline_inserted, new_selection)| {
3211 let mut cursor = new_selection.end.to_point(&buffer);
3212 if extra_newline_inserted {
3213 cursor.row -= 1;
3214 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3215 }
3216 new_selection.map(|_| cursor)
3217 })
3218 .collect();
3219
3220 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3221 s.select(new_selections)
3222 });
3223 this.refresh_inline_completion(true, false, window, cx);
3224 });
3225 }
3226
3227 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3228 let buffer = self.buffer.read(cx);
3229 let snapshot = buffer.snapshot(cx);
3230
3231 let mut edits = Vec::new();
3232 let mut rows = Vec::new();
3233
3234 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3235 let cursor = selection.head();
3236 let row = cursor.row;
3237
3238 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3239
3240 let newline = "\n".to_string();
3241 edits.push((start_of_line..start_of_line, newline));
3242
3243 rows.push(row + rows_inserted as u32);
3244 }
3245
3246 self.transact(window, cx, |editor, window, cx| {
3247 editor.edit(edits, cx);
3248
3249 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3250 let mut index = 0;
3251 s.move_cursors_with(|map, _, _| {
3252 let row = rows[index];
3253 index += 1;
3254
3255 let point = Point::new(row, 0);
3256 let boundary = map.next_line_boundary(point).1;
3257 let clipped = map.clip_point(boundary, Bias::Left);
3258
3259 (clipped, SelectionGoal::None)
3260 });
3261 });
3262
3263 let mut indent_edits = Vec::new();
3264 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3265 for row in rows {
3266 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3267 for (row, indent) in indents {
3268 if indent.len == 0 {
3269 continue;
3270 }
3271
3272 let text = match indent.kind {
3273 IndentKind::Space => " ".repeat(indent.len as usize),
3274 IndentKind::Tab => "\t".repeat(indent.len as usize),
3275 };
3276 let point = Point::new(row.0, 0);
3277 indent_edits.push((point..point, text));
3278 }
3279 }
3280 editor.edit(indent_edits, cx);
3281 });
3282 }
3283
3284 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3285 let buffer = self.buffer.read(cx);
3286 let snapshot = buffer.snapshot(cx);
3287
3288 let mut edits = Vec::new();
3289 let mut rows = Vec::new();
3290 let mut rows_inserted = 0;
3291
3292 for selection in self.selections.all_adjusted(cx) {
3293 let cursor = selection.head();
3294 let row = cursor.row;
3295
3296 let point = Point::new(row + 1, 0);
3297 let start_of_line = snapshot.clip_point(point, Bias::Left);
3298
3299 let newline = "\n".to_string();
3300 edits.push((start_of_line..start_of_line, newline));
3301
3302 rows_inserted += 1;
3303 rows.push(row + rows_inserted);
3304 }
3305
3306 self.transact(window, cx, |editor, window, cx| {
3307 editor.edit(edits, cx);
3308
3309 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3310 let mut index = 0;
3311 s.move_cursors_with(|map, _, _| {
3312 let row = rows[index];
3313 index += 1;
3314
3315 let point = Point::new(row, 0);
3316 let boundary = map.next_line_boundary(point).1;
3317 let clipped = map.clip_point(boundary, Bias::Left);
3318
3319 (clipped, SelectionGoal::None)
3320 });
3321 });
3322
3323 let mut indent_edits = Vec::new();
3324 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3325 for row in rows {
3326 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3327 for (row, indent) in indents {
3328 if indent.len == 0 {
3329 continue;
3330 }
3331
3332 let text = match indent.kind {
3333 IndentKind::Space => " ".repeat(indent.len as usize),
3334 IndentKind::Tab => "\t".repeat(indent.len as usize),
3335 };
3336 let point = Point::new(row.0, 0);
3337 indent_edits.push((point..point, text));
3338 }
3339 }
3340 editor.edit(indent_edits, cx);
3341 });
3342 }
3343
3344 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3345 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3346 original_indent_columns: Vec::new(),
3347 });
3348 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3349 }
3350
3351 fn insert_with_autoindent_mode(
3352 &mut self,
3353 text: &str,
3354 autoindent_mode: Option<AutoindentMode>,
3355 window: &mut Window,
3356 cx: &mut Context<Self>,
3357 ) {
3358 if self.read_only(cx) {
3359 return;
3360 }
3361
3362 let text: Arc<str> = text.into();
3363 self.transact(window, cx, |this, window, cx| {
3364 let old_selections = this.selections.all_adjusted(cx);
3365 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3366 let anchors = {
3367 let snapshot = buffer.read(cx);
3368 old_selections
3369 .iter()
3370 .map(|s| {
3371 let anchor = snapshot.anchor_after(s.head());
3372 s.map(|_| anchor)
3373 })
3374 .collect::<Vec<_>>()
3375 };
3376 buffer.edit(
3377 old_selections
3378 .iter()
3379 .map(|s| (s.start..s.end, text.clone())),
3380 autoindent_mode,
3381 cx,
3382 );
3383 anchors
3384 });
3385
3386 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3387 s.select_anchors(selection_anchors);
3388 });
3389
3390 cx.notify();
3391 });
3392 }
3393
3394 fn trigger_completion_on_input(
3395 &mut self,
3396 text: &str,
3397 trigger_in_words: bool,
3398 window: &mut Window,
3399 cx: &mut Context<Self>,
3400 ) {
3401 if self.is_completion_trigger(text, trigger_in_words, cx) {
3402 self.show_completions(
3403 &ShowCompletions {
3404 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3405 },
3406 window,
3407 cx,
3408 );
3409 } else {
3410 self.hide_context_menu(window, cx);
3411 }
3412 }
3413
3414 fn is_completion_trigger(
3415 &self,
3416 text: &str,
3417 trigger_in_words: bool,
3418 cx: &mut Context<Self>,
3419 ) -> bool {
3420 let position = self.selections.newest_anchor().head();
3421 let multibuffer = self.buffer.read(cx);
3422 let Some(buffer) = position
3423 .buffer_id
3424 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3425 else {
3426 return false;
3427 };
3428
3429 if let Some(completion_provider) = &self.completion_provider {
3430 completion_provider.is_completion_trigger(
3431 &buffer,
3432 position.text_anchor,
3433 text,
3434 trigger_in_words,
3435 cx,
3436 )
3437 } else {
3438 false
3439 }
3440 }
3441
3442 /// If any empty selections is touching the start of its innermost containing autoclose
3443 /// region, expand it to select the brackets.
3444 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3445 let selections = self.selections.all::<usize>(cx);
3446 let buffer = self.buffer.read(cx).read(cx);
3447 let new_selections = self
3448 .selections_with_autoclose_regions(selections, &buffer)
3449 .map(|(mut selection, region)| {
3450 if !selection.is_empty() {
3451 return selection;
3452 }
3453
3454 if let Some(region) = region {
3455 let mut range = region.range.to_offset(&buffer);
3456 if selection.start == range.start && range.start >= region.pair.start.len() {
3457 range.start -= region.pair.start.len();
3458 if buffer.contains_str_at(range.start, ®ion.pair.start)
3459 && buffer.contains_str_at(range.end, ®ion.pair.end)
3460 {
3461 range.end += region.pair.end.len();
3462 selection.start = range.start;
3463 selection.end = range.end;
3464
3465 return selection;
3466 }
3467 }
3468 }
3469
3470 let always_treat_brackets_as_autoclosed = buffer
3471 .settings_at(selection.start, cx)
3472 .always_treat_brackets_as_autoclosed;
3473
3474 if !always_treat_brackets_as_autoclosed {
3475 return selection;
3476 }
3477
3478 if let Some(scope) = buffer.language_scope_at(selection.start) {
3479 for (pair, enabled) in scope.brackets() {
3480 if !enabled || !pair.close {
3481 continue;
3482 }
3483
3484 if buffer.contains_str_at(selection.start, &pair.end) {
3485 let pair_start_len = pair.start.len();
3486 if buffer.contains_str_at(
3487 selection.start.saturating_sub(pair_start_len),
3488 &pair.start,
3489 ) {
3490 selection.start -= pair_start_len;
3491 selection.end += pair.end.len();
3492
3493 return selection;
3494 }
3495 }
3496 }
3497 }
3498
3499 selection
3500 })
3501 .collect();
3502
3503 drop(buffer);
3504 self.change_selections(None, window, cx, |selections| {
3505 selections.select(new_selections)
3506 });
3507 }
3508
3509 /// Iterate the given selections, and for each one, find the smallest surrounding
3510 /// autoclose region. This uses the ordering of the selections and the autoclose
3511 /// regions to avoid repeated comparisons.
3512 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3513 &'a self,
3514 selections: impl IntoIterator<Item = Selection<D>>,
3515 buffer: &'a MultiBufferSnapshot,
3516 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3517 let mut i = 0;
3518 let mut regions = self.autoclose_regions.as_slice();
3519 selections.into_iter().map(move |selection| {
3520 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3521
3522 let mut enclosing = None;
3523 while let Some(pair_state) = regions.get(i) {
3524 if pair_state.range.end.to_offset(buffer) < range.start {
3525 regions = ®ions[i + 1..];
3526 i = 0;
3527 } else if pair_state.range.start.to_offset(buffer) > range.end {
3528 break;
3529 } else {
3530 if pair_state.selection_id == selection.id {
3531 enclosing = Some(pair_state);
3532 }
3533 i += 1;
3534 }
3535 }
3536
3537 (selection, enclosing)
3538 })
3539 }
3540
3541 /// Remove any autoclose regions that no longer contain their selection.
3542 fn invalidate_autoclose_regions(
3543 &mut self,
3544 mut selections: &[Selection<Anchor>],
3545 buffer: &MultiBufferSnapshot,
3546 ) {
3547 self.autoclose_regions.retain(|state| {
3548 let mut i = 0;
3549 while let Some(selection) = selections.get(i) {
3550 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3551 selections = &selections[1..];
3552 continue;
3553 }
3554 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3555 break;
3556 }
3557 if selection.id == state.selection_id {
3558 return true;
3559 } else {
3560 i += 1;
3561 }
3562 }
3563 false
3564 });
3565 }
3566
3567 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3568 let offset = position.to_offset(buffer);
3569 let (word_range, kind) = buffer.surrounding_word(offset, true);
3570 if offset > word_range.start && kind == Some(CharKind::Word) {
3571 Some(
3572 buffer
3573 .text_for_range(word_range.start..offset)
3574 .collect::<String>(),
3575 )
3576 } else {
3577 None
3578 }
3579 }
3580
3581 pub fn toggle_inlay_hints(
3582 &mut self,
3583 _: &ToggleInlayHints,
3584 _: &mut Window,
3585 cx: &mut Context<Self>,
3586 ) {
3587 self.refresh_inlay_hints(
3588 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3589 cx,
3590 );
3591 }
3592
3593 pub fn inlay_hints_enabled(&self) -> bool {
3594 self.inlay_hint_cache.enabled
3595 }
3596
3597 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3598 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3599 return;
3600 }
3601
3602 let reason_description = reason.description();
3603 let ignore_debounce = matches!(
3604 reason,
3605 InlayHintRefreshReason::SettingsChange(_)
3606 | InlayHintRefreshReason::Toggle(_)
3607 | InlayHintRefreshReason::ExcerptsRemoved(_)
3608 );
3609 let (invalidate_cache, required_languages) = match reason {
3610 InlayHintRefreshReason::Toggle(enabled) => {
3611 self.inlay_hint_cache.enabled = enabled;
3612 if enabled {
3613 (InvalidationStrategy::RefreshRequested, None)
3614 } else {
3615 self.inlay_hint_cache.clear();
3616 self.splice_inlays(
3617 &self
3618 .visible_inlay_hints(cx)
3619 .iter()
3620 .map(|inlay| inlay.id)
3621 .collect::<Vec<InlayId>>(),
3622 Vec::new(),
3623 cx,
3624 );
3625 return;
3626 }
3627 }
3628 InlayHintRefreshReason::SettingsChange(new_settings) => {
3629 match self.inlay_hint_cache.update_settings(
3630 &self.buffer,
3631 new_settings,
3632 self.visible_inlay_hints(cx),
3633 cx,
3634 ) {
3635 ControlFlow::Break(Some(InlaySplice {
3636 to_remove,
3637 to_insert,
3638 })) => {
3639 self.splice_inlays(&to_remove, to_insert, cx);
3640 return;
3641 }
3642 ControlFlow::Break(None) => return,
3643 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3644 }
3645 }
3646 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3647 if let Some(InlaySplice {
3648 to_remove,
3649 to_insert,
3650 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3651 {
3652 self.splice_inlays(&to_remove, to_insert, cx);
3653 }
3654 return;
3655 }
3656 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3657 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3658 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3659 }
3660 InlayHintRefreshReason::RefreshRequested => {
3661 (InvalidationStrategy::RefreshRequested, None)
3662 }
3663 };
3664
3665 if let Some(InlaySplice {
3666 to_remove,
3667 to_insert,
3668 }) = self.inlay_hint_cache.spawn_hint_refresh(
3669 reason_description,
3670 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3671 invalidate_cache,
3672 ignore_debounce,
3673 cx,
3674 ) {
3675 self.splice_inlays(&to_remove, to_insert, cx);
3676 }
3677 }
3678
3679 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3680 self.display_map
3681 .read(cx)
3682 .current_inlays()
3683 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3684 .cloned()
3685 .collect()
3686 }
3687
3688 pub fn excerpts_for_inlay_hints_query(
3689 &self,
3690 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3691 cx: &mut Context<Editor>,
3692 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3693 let Some(project) = self.project.as_ref() else {
3694 return HashMap::default();
3695 };
3696 let project = project.read(cx);
3697 let multi_buffer = self.buffer().read(cx);
3698 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3699 let multi_buffer_visible_start = self
3700 .scroll_manager
3701 .anchor()
3702 .anchor
3703 .to_point(&multi_buffer_snapshot);
3704 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3705 multi_buffer_visible_start
3706 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3707 Bias::Left,
3708 );
3709 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3710 multi_buffer_snapshot
3711 .range_to_buffer_ranges(multi_buffer_visible_range)
3712 .into_iter()
3713 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3714 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3715 let buffer_file = project::File::from_dyn(buffer.file())?;
3716 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3717 let worktree_entry = buffer_worktree
3718 .read(cx)
3719 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3720 if worktree_entry.is_ignored {
3721 return None;
3722 }
3723
3724 let language = buffer.language()?;
3725 if let Some(restrict_to_languages) = restrict_to_languages {
3726 if !restrict_to_languages.contains(language) {
3727 return None;
3728 }
3729 }
3730 Some((
3731 excerpt_id,
3732 (
3733 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3734 buffer.version().clone(),
3735 excerpt_visible_range,
3736 ),
3737 ))
3738 })
3739 .collect()
3740 }
3741
3742 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3743 TextLayoutDetails {
3744 text_system: window.text_system().clone(),
3745 editor_style: self.style.clone().unwrap(),
3746 rem_size: window.rem_size(),
3747 scroll_anchor: self.scroll_manager.anchor(),
3748 visible_rows: self.visible_line_count(),
3749 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3750 }
3751 }
3752
3753 pub fn splice_inlays(
3754 &self,
3755 to_remove: &[InlayId],
3756 to_insert: Vec<Inlay>,
3757 cx: &mut Context<Self>,
3758 ) {
3759 self.display_map.update(cx, |display_map, cx| {
3760 display_map.splice_inlays(to_remove, to_insert, cx)
3761 });
3762 cx.notify();
3763 }
3764
3765 fn trigger_on_type_formatting(
3766 &self,
3767 input: String,
3768 window: &mut Window,
3769 cx: &mut Context<Self>,
3770 ) -> Option<Task<Result<()>>> {
3771 if input.len() != 1 {
3772 return None;
3773 }
3774
3775 let project = self.project.as_ref()?;
3776 let position = self.selections.newest_anchor().head();
3777 let (buffer, buffer_position) = self
3778 .buffer
3779 .read(cx)
3780 .text_anchor_for_position(position, cx)?;
3781
3782 let settings = language_settings::language_settings(
3783 buffer
3784 .read(cx)
3785 .language_at(buffer_position)
3786 .map(|l| l.name()),
3787 buffer.read(cx).file(),
3788 cx,
3789 );
3790 if !settings.use_on_type_format {
3791 return None;
3792 }
3793
3794 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3795 // hence we do LSP request & edit on host side only — add formats to host's history.
3796 let push_to_lsp_host_history = true;
3797 // If this is not the host, append its history with new edits.
3798 let push_to_client_history = project.read(cx).is_via_collab();
3799
3800 let on_type_formatting = project.update(cx, |project, cx| {
3801 project.on_type_format(
3802 buffer.clone(),
3803 buffer_position,
3804 input,
3805 push_to_lsp_host_history,
3806 cx,
3807 )
3808 });
3809 Some(cx.spawn_in(window, |editor, mut cx| async move {
3810 if let Some(transaction) = on_type_formatting.await? {
3811 if push_to_client_history {
3812 buffer
3813 .update(&mut cx, |buffer, _| {
3814 buffer.push_transaction(transaction, Instant::now());
3815 })
3816 .ok();
3817 }
3818 editor.update(&mut cx, |editor, cx| {
3819 editor.refresh_document_highlights(cx);
3820 })?;
3821 }
3822 Ok(())
3823 }))
3824 }
3825
3826 pub fn show_completions(
3827 &mut self,
3828 options: &ShowCompletions,
3829 window: &mut Window,
3830 cx: &mut Context<Self>,
3831 ) {
3832 if self.pending_rename.is_some() {
3833 return;
3834 }
3835
3836 let Some(provider) = self.completion_provider.as_ref() else {
3837 return;
3838 };
3839
3840 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3841 return;
3842 }
3843
3844 let position = self.selections.newest_anchor().head();
3845 if position.diff_base_anchor.is_some() {
3846 return;
3847 }
3848 let (buffer, buffer_position) =
3849 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3850 output
3851 } else {
3852 return;
3853 };
3854 let show_completion_documentation = buffer
3855 .read(cx)
3856 .snapshot()
3857 .settings_at(buffer_position, cx)
3858 .show_completion_documentation;
3859
3860 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3861
3862 let trigger_kind = match &options.trigger {
3863 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3864 CompletionTriggerKind::TRIGGER_CHARACTER
3865 }
3866 _ => CompletionTriggerKind::INVOKED,
3867 };
3868 let completion_context = CompletionContext {
3869 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3870 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3871 Some(String::from(trigger))
3872 } else {
3873 None
3874 }
3875 }),
3876 trigger_kind,
3877 };
3878 let completions =
3879 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3880 let sort_completions = provider.sort_completions();
3881
3882 let id = post_inc(&mut self.next_completion_id);
3883 let task = cx.spawn_in(window, |editor, mut cx| {
3884 async move {
3885 editor.update(&mut cx, |this, _| {
3886 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3887 })?;
3888 let completions = completions.await.log_err();
3889 let menu = if let Some(completions) = completions {
3890 let mut menu = CompletionsMenu::new(
3891 id,
3892 sort_completions,
3893 show_completion_documentation,
3894 position,
3895 buffer.clone(),
3896 completions.into(),
3897 );
3898
3899 menu.filter(query.as_deref(), cx.background_executor().clone())
3900 .await;
3901
3902 menu.visible().then_some(menu)
3903 } else {
3904 None
3905 };
3906
3907 editor.update_in(&mut cx, |editor, window, cx| {
3908 match editor.context_menu.borrow().as_ref() {
3909 None => {}
3910 Some(CodeContextMenu::Completions(prev_menu)) => {
3911 if prev_menu.id > id {
3912 return;
3913 }
3914 }
3915 _ => return,
3916 }
3917
3918 if editor.focus_handle.is_focused(window) && menu.is_some() {
3919 let mut menu = menu.unwrap();
3920 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3921
3922 *editor.context_menu.borrow_mut() =
3923 Some(CodeContextMenu::Completions(menu));
3924
3925 if editor.show_edit_predictions_in_menu() {
3926 editor.update_visible_inline_completion(window, cx);
3927 } else {
3928 editor.discard_inline_completion(false, cx);
3929 }
3930
3931 cx.notify();
3932 } else if editor.completion_tasks.len() <= 1 {
3933 // If there are no more completion tasks and the last menu was
3934 // empty, we should hide it.
3935 let was_hidden = editor.hide_context_menu(window, cx).is_none();
3936 // If it was already hidden and we don't show inline
3937 // completions in the menu, we should also show the
3938 // inline-completion when available.
3939 if was_hidden && editor.show_edit_predictions_in_menu() {
3940 editor.update_visible_inline_completion(window, cx);
3941 }
3942 }
3943 })?;
3944
3945 Ok::<_, anyhow::Error>(())
3946 }
3947 .log_err()
3948 });
3949
3950 self.completion_tasks.push((id, task));
3951 }
3952
3953 pub fn confirm_completion(
3954 &mut self,
3955 action: &ConfirmCompletion,
3956 window: &mut Window,
3957 cx: &mut Context<Self>,
3958 ) -> Option<Task<Result<()>>> {
3959 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
3960 }
3961
3962 pub fn compose_completion(
3963 &mut self,
3964 action: &ComposeCompletion,
3965 window: &mut Window,
3966 cx: &mut Context<Self>,
3967 ) -> Option<Task<Result<()>>> {
3968 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
3969 }
3970
3971 fn do_completion(
3972 &mut self,
3973 item_ix: Option<usize>,
3974 intent: CompletionIntent,
3975 window: &mut Window,
3976 cx: &mut Context<Editor>,
3977 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3978 use language::ToOffset as _;
3979
3980 let completions_menu =
3981 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
3982 menu
3983 } else {
3984 return None;
3985 };
3986
3987 let entries = completions_menu.entries.borrow();
3988 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
3989 if self.show_edit_predictions_in_menu() {
3990 self.discard_inline_completion(true, cx);
3991 }
3992 let candidate_id = mat.candidate_id;
3993 drop(entries);
3994
3995 let buffer_handle = completions_menu.buffer;
3996 let completion = completions_menu
3997 .completions
3998 .borrow()
3999 .get(candidate_id)?
4000 .clone();
4001 cx.stop_propagation();
4002
4003 let snippet;
4004 let text;
4005
4006 if completion.is_snippet() {
4007 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4008 text = snippet.as_ref().unwrap().text.clone();
4009 } else {
4010 snippet = None;
4011 text = completion.new_text.clone();
4012 };
4013 let selections = self.selections.all::<usize>(cx);
4014 let buffer = buffer_handle.read(cx);
4015 let old_range = completion.old_range.to_offset(buffer);
4016 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4017
4018 let newest_selection = self.selections.newest_anchor();
4019 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4020 return None;
4021 }
4022
4023 let lookbehind = newest_selection
4024 .start
4025 .text_anchor
4026 .to_offset(buffer)
4027 .saturating_sub(old_range.start);
4028 let lookahead = old_range
4029 .end
4030 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4031 let mut common_prefix_len = old_text
4032 .bytes()
4033 .zip(text.bytes())
4034 .take_while(|(a, b)| a == b)
4035 .count();
4036
4037 let snapshot = self.buffer.read(cx).snapshot(cx);
4038 let mut range_to_replace: Option<Range<isize>> = None;
4039 let mut ranges = Vec::new();
4040 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4041 for selection in &selections {
4042 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4043 let start = selection.start.saturating_sub(lookbehind);
4044 let end = selection.end + lookahead;
4045 if selection.id == newest_selection.id {
4046 range_to_replace = Some(
4047 ((start + common_prefix_len) as isize - selection.start as isize)
4048 ..(end as isize - selection.start as isize),
4049 );
4050 }
4051 ranges.push(start + common_prefix_len..end);
4052 } else {
4053 common_prefix_len = 0;
4054 ranges.clear();
4055 ranges.extend(selections.iter().map(|s| {
4056 if s.id == newest_selection.id {
4057 range_to_replace = Some(
4058 old_range.start.to_offset_utf16(&snapshot).0 as isize
4059 - selection.start as isize
4060 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4061 - selection.start as isize,
4062 );
4063 old_range.clone()
4064 } else {
4065 s.start..s.end
4066 }
4067 }));
4068 break;
4069 }
4070 if !self.linked_edit_ranges.is_empty() {
4071 let start_anchor = snapshot.anchor_before(selection.head());
4072 let end_anchor = snapshot.anchor_after(selection.tail());
4073 if let Some(ranges) = self
4074 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4075 {
4076 for (buffer, edits) in ranges {
4077 linked_edits.entry(buffer.clone()).or_default().extend(
4078 edits
4079 .into_iter()
4080 .map(|range| (range, text[common_prefix_len..].to_owned())),
4081 );
4082 }
4083 }
4084 }
4085 }
4086 let text = &text[common_prefix_len..];
4087
4088 cx.emit(EditorEvent::InputHandled {
4089 utf16_range_to_replace: range_to_replace,
4090 text: text.into(),
4091 });
4092
4093 self.transact(window, cx, |this, window, cx| {
4094 if let Some(mut snippet) = snippet {
4095 snippet.text = text.to_string();
4096 for tabstop in snippet
4097 .tabstops
4098 .iter_mut()
4099 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4100 {
4101 tabstop.start -= common_prefix_len as isize;
4102 tabstop.end -= common_prefix_len as isize;
4103 }
4104
4105 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4106 } else {
4107 this.buffer.update(cx, |buffer, cx| {
4108 buffer.edit(
4109 ranges.iter().map(|range| (range.clone(), text)),
4110 this.autoindent_mode.clone(),
4111 cx,
4112 );
4113 });
4114 }
4115 for (buffer, edits) in linked_edits {
4116 buffer.update(cx, |buffer, cx| {
4117 let snapshot = buffer.snapshot();
4118 let edits = edits
4119 .into_iter()
4120 .map(|(range, text)| {
4121 use text::ToPoint as TP;
4122 let end_point = TP::to_point(&range.end, &snapshot);
4123 let start_point = TP::to_point(&range.start, &snapshot);
4124 (start_point..end_point, text)
4125 })
4126 .sorted_by_key(|(range, _)| range.start)
4127 .collect::<Vec<_>>();
4128 buffer.edit(edits, None, cx);
4129 })
4130 }
4131
4132 this.refresh_inline_completion(true, false, window, cx);
4133 });
4134
4135 let show_new_completions_on_confirm = completion
4136 .confirm
4137 .as_ref()
4138 .map_or(false, |confirm| confirm(intent, window, cx));
4139 if show_new_completions_on_confirm {
4140 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4141 }
4142
4143 let provider = self.completion_provider.as_ref()?;
4144 drop(completion);
4145 let apply_edits = provider.apply_additional_edits_for_completion(
4146 buffer_handle,
4147 completions_menu.completions.clone(),
4148 candidate_id,
4149 true,
4150 cx,
4151 );
4152
4153 let editor_settings = EditorSettings::get_global(cx);
4154 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4155 // After the code completion is finished, users often want to know what signatures are needed.
4156 // so we should automatically call signature_help
4157 self.show_signature_help(&ShowSignatureHelp, window, cx);
4158 }
4159
4160 Some(cx.foreground_executor().spawn(async move {
4161 apply_edits.await?;
4162 Ok(())
4163 }))
4164 }
4165
4166 pub fn toggle_code_actions(
4167 &mut self,
4168 action: &ToggleCodeActions,
4169 window: &mut Window,
4170 cx: &mut Context<Self>,
4171 ) {
4172 let mut context_menu = self.context_menu.borrow_mut();
4173 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4174 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4175 // Toggle if we're selecting the same one
4176 *context_menu = None;
4177 cx.notify();
4178 return;
4179 } else {
4180 // Otherwise, clear it and start a new one
4181 *context_menu = None;
4182 cx.notify();
4183 }
4184 }
4185 drop(context_menu);
4186 let snapshot = self.snapshot(window, cx);
4187 let deployed_from_indicator = action.deployed_from_indicator;
4188 let mut task = self.code_actions_task.take();
4189 let action = action.clone();
4190 cx.spawn_in(window, |editor, mut cx| async move {
4191 while let Some(prev_task) = task {
4192 prev_task.await.log_err();
4193 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4194 }
4195
4196 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4197 if editor.focus_handle.is_focused(window) {
4198 let multibuffer_point = action
4199 .deployed_from_indicator
4200 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4201 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4202 let (buffer, buffer_row) = snapshot
4203 .buffer_snapshot
4204 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4205 .and_then(|(buffer_snapshot, range)| {
4206 editor
4207 .buffer
4208 .read(cx)
4209 .buffer(buffer_snapshot.remote_id())
4210 .map(|buffer| (buffer, range.start.row))
4211 })?;
4212 let (_, code_actions) = editor
4213 .available_code_actions
4214 .clone()
4215 .and_then(|(location, code_actions)| {
4216 let snapshot = location.buffer.read(cx).snapshot();
4217 let point_range = location.range.to_point(&snapshot);
4218 let point_range = point_range.start.row..=point_range.end.row;
4219 if point_range.contains(&buffer_row) {
4220 Some((location, code_actions))
4221 } else {
4222 None
4223 }
4224 })
4225 .unzip();
4226 let buffer_id = buffer.read(cx).remote_id();
4227 let tasks = editor
4228 .tasks
4229 .get(&(buffer_id, buffer_row))
4230 .map(|t| Arc::new(t.to_owned()));
4231 if tasks.is_none() && code_actions.is_none() {
4232 return None;
4233 }
4234
4235 editor.completion_tasks.clear();
4236 editor.discard_inline_completion(false, cx);
4237 let task_context =
4238 tasks
4239 .as_ref()
4240 .zip(editor.project.clone())
4241 .map(|(tasks, project)| {
4242 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4243 });
4244
4245 Some(cx.spawn_in(window, |editor, mut cx| async move {
4246 let task_context = match task_context {
4247 Some(task_context) => task_context.await,
4248 None => None,
4249 };
4250 let resolved_tasks =
4251 tasks.zip(task_context).map(|(tasks, task_context)| {
4252 Rc::new(ResolvedTasks {
4253 templates: tasks.resolve(&task_context).collect(),
4254 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4255 multibuffer_point.row,
4256 tasks.column,
4257 )),
4258 })
4259 });
4260 let spawn_straight_away = resolved_tasks
4261 .as_ref()
4262 .map_or(false, |tasks| tasks.templates.len() == 1)
4263 && code_actions
4264 .as_ref()
4265 .map_or(true, |actions| actions.is_empty());
4266 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4267 *editor.context_menu.borrow_mut() =
4268 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4269 buffer,
4270 actions: CodeActionContents {
4271 tasks: resolved_tasks,
4272 actions: code_actions,
4273 },
4274 selected_item: Default::default(),
4275 scroll_handle: UniformListScrollHandle::default(),
4276 deployed_from_indicator,
4277 }));
4278 if spawn_straight_away {
4279 if let Some(task) = editor.confirm_code_action(
4280 &ConfirmCodeAction { item_ix: Some(0) },
4281 window,
4282 cx,
4283 ) {
4284 cx.notify();
4285 return task;
4286 }
4287 }
4288 cx.notify();
4289 Task::ready(Ok(()))
4290 }) {
4291 task.await
4292 } else {
4293 Ok(())
4294 }
4295 }))
4296 } else {
4297 Some(Task::ready(Ok(())))
4298 }
4299 })?;
4300 if let Some(task) = spawned_test_task {
4301 task.await?;
4302 }
4303
4304 Ok::<_, anyhow::Error>(())
4305 })
4306 .detach_and_log_err(cx);
4307 }
4308
4309 pub fn confirm_code_action(
4310 &mut self,
4311 action: &ConfirmCodeAction,
4312 window: &mut Window,
4313 cx: &mut Context<Self>,
4314 ) -> Option<Task<Result<()>>> {
4315 let actions_menu =
4316 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4317 menu
4318 } else {
4319 return None;
4320 };
4321 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4322 let action = actions_menu.actions.get(action_ix)?;
4323 let title = action.label();
4324 let buffer = actions_menu.buffer;
4325 let workspace = self.workspace()?;
4326
4327 match action {
4328 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4329 workspace.update(cx, |workspace, cx| {
4330 workspace::tasks::schedule_resolved_task(
4331 workspace,
4332 task_source_kind,
4333 resolved_task,
4334 false,
4335 cx,
4336 );
4337
4338 Some(Task::ready(Ok(())))
4339 })
4340 }
4341 CodeActionsItem::CodeAction {
4342 excerpt_id,
4343 action,
4344 provider,
4345 } => {
4346 let apply_code_action =
4347 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4348 let workspace = workspace.downgrade();
4349 Some(cx.spawn_in(window, |editor, cx| async move {
4350 let project_transaction = apply_code_action.await?;
4351 Self::open_project_transaction(
4352 &editor,
4353 workspace,
4354 project_transaction,
4355 title,
4356 cx,
4357 )
4358 .await
4359 }))
4360 }
4361 }
4362 }
4363
4364 pub async fn open_project_transaction(
4365 this: &WeakEntity<Editor>,
4366 workspace: WeakEntity<Workspace>,
4367 transaction: ProjectTransaction,
4368 title: String,
4369 mut cx: AsyncWindowContext,
4370 ) -> Result<()> {
4371 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4372 cx.update(|_, cx| {
4373 entries.sort_unstable_by_key(|(buffer, _)| {
4374 buffer.read(cx).file().map(|f| f.path().clone())
4375 });
4376 })?;
4377
4378 // If the project transaction's edits are all contained within this editor, then
4379 // avoid opening a new editor to display them.
4380
4381 if let Some((buffer, transaction)) = entries.first() {
4382 if entries.len() == 1 {
4383 let excerpt = this.update(&mut cx, |editor, cx| {
4384 editor
4385 .buffer()
4386 .read(cx)
4387 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4388 })?;
4389 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4390 if excerpted_buffer == *buffer {
4391 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4392 let excerpt_range = excerpt_range.to_offset(buffer);
4393 buffer
4394 .edited_ranges_for_transaction::<usize>(transaction)
4395 .all(|range| {
4396 excerpt_range.start <= range.start
4397 && excerpt_range.end >= range.end
4398 })
4399 })?;
4400
4401 if all_edits_within_excerpt {
4402 return Ok(());
4403 }
4404 }
4405 }
4406 }
4407 } else {
4408 return Ok(());
4409 }
4410
4411 let mut ranges_to_highlight = Vec::new();
4412 let excerpt_buffer = cx.new(|cx| {
4413 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4414 for (buffer_handle, transaction) in &entries {
4415 let buffer = buffer_handle.read(cx);
4416 ranges_to_highlight.extend(
4417 multibuffer.push_excerpts_with_context_lines(
4418 buffer_handle.clone(),
4419 buffer
4420 .edited_ranges_for_transaction::<usize>(transaction)
4421 .collect(),
4422 DEFAULT_MULTIBUFFER_CONTEXT,
4423 cx,
4424 ),
4425 );
4426 }
4427 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4428 multibuffer
4429 })?;
4430
4431 workspace.update_in(&mut cx, |workspace, window, cx| {
4432 let project = workspace.project().clone();
4433 let editor = cx
4434 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4435 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4436 editor.update(cx, |editor, cx| {
4437 editor.highlight_background::<Self>(
4438 &ranges_to_highlight,
4439 |theme| theme.editor_highlighted_line_background,
4440 cx,
4441 );
4442 });
4443 })?;
4444
4445 Ok(())
4446 }
4447
4448 pub fn clear_code_action_providers(&mut self) {
4449 self.code_action_providers.clear();
4450 self.available_code_actions.take();
4451 }
4452
4453 pub fn add_code_action_provider(
4454 &mut self,
4455 provider: Rc<dyn CodeActionProvider>,
4456 window: &mut Window,
4457 cx: &mut Context<Self>,
4458 ) {
4459 if self
4460 .code_action_providers
4461 .iter()
4462 .any(|existing_provider| existing_provider.id() == provider.id())
4463 {
4464 return;
4465 }
4466
4467 self.code_action_providers.push(provider);
4468 self.refresh_code_actions(window, cx);
4469 }
4470
4471 pub fn remove_code_action_provider(
4472 &mut self,
4473 id: Arc<str>,
4474 window: &mut Window,
4475 cx: &mut Context<Self>,
4476 ) {
4477 self.code_action_providers
4478 .retain(|provider| provider.id() != id);
4479 self.refresh_code_actions(window, cx);
4480 }
4481
4482 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4483 let buffer = self.buffer.read(cx);
4484 let newest_selection = self.selections.newest_anchor().clone();
4485 if newest_selection.head().diff_base_anchor.is_some() {
4486 return None;
4487 }
4488 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4489 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4490 if start_buffer != end_buffer {
4491 return None;
4492 }
4493
4494 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4495 cx.background_executor()
4496 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4497 .await;
4498
4499 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4500 let providers = this.code_action_providers.clone();
4501 let tasks = this
4502 .code_action_providers
4503 .iter()
4504 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4505 .collect::<Vec<_>>();
4506 (providers, tasks)
4507 })?;
4508
4509 let mut actions = Vec::new();
4510 for (provider, provider_actions) in
4511 providers.into_iter().zip(future::join_all(tasks).await)
4512 {
4513 if let Some(provider_actions) = provider_actions.log_err() {
4514 actions.extend(provider_actions.into_iter().map(|action| {
4515 AvailableCodeAction {
4516 excerpt_id: newest_selection.start.excerpt_id,
4517 action,
4518 provider: provider.clone(),
4519 }
4520 }));
4521 }
4522 }
4523
4524 this.update(&mut cx, |this, cx| {
4525 this.available_code_actions = if actions.is_empty() {
4526 None
4527 } else {
4528 Some((
4529 Location {
4530 buffer: start_buffer,
4531 range: start..end,
4532 },
4533 actions.into(),
4534 ))
4535 };
4536 cx.notify();
4537 })
4538 }));
4539 None
4540 }
4541
4542 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4543 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4544 self.show_git_blame_inline = false;
4545
4546 self.show_git_blame_inline_delay_task =
4547 Some(cx.spawn_in(window, |this, mut cx| async move {
4548 cx.background_executor().timer(delay).await;
4549
4550 this.update(&mut cx, |this, cx| {
4551 this.show_git_blame_inline = true;
4552 cx.notify();
4553 })
4554 .log_err();
4555 }));
4556 }
4557 }
4558
4559 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4560 if self.pending_rename.is_some() {
4561 return None;
4562 }
4563
4564 let provider = self.semantics_provider.clone()?;
4565 let buffer = self.buffer.read(cx);
4566 let newest_selection = self.selections.newest_anchor().clone();
4567 let cursor_position = newest_selection.head();
4568 let (cursor_buffer, cursor_buffer_position) =
4569 buffer.text_anchor_for_position(cursor_position, cx)?;
4570 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4571 if cursor_buffer != tail_buffer {
4572 return None;
4573 }
4574 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4575 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4576 cx.background_executor()
4577 .timer(Duration::from_millis(debounce))
4578 .await;
4579
4580 let highlights = if let Some(highlights) = cx
4581 .update(|cx| {
4582 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4583 })
4584 .ok()
4585 .flatten()
4586 {
4587 highlights.await.log_err()
4588 } else {
4589 None
4590 };
4591
4592 if let Some(highlights) = highlights {
4593 this.update(&mut cx, |this, cx| {
4594 if this.pending_rename.is_some() {
4595 return;
4596 }
4597
4598 let buffer_id = cursor_position.buffer_id;
4599 let buffer = this.buffer.read(cx);
4600 if !buffer
4601 .text_anchor_for_position(cursor_position, cx)
4602 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4603 {
4604 return;
4605 }
4606
4607 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4608 let mut write_ranges = Vec::new();
4609 let mut read_ranges = Vec::new();
4610 for highlight in highlights {
4611 for (excerpt_id, excerpt_range) in
4612 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4613 {
4614 let start = highlight
4615 .range
4616 .start
4617 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4618 let end = highlight
4619 .range
4620 .end
4621 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4622 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4623 continue;
4624 }
4625
4626 let range = Anchor {
4627 buffer_id,
4628 excerpt_id,
4629 text_anchor: start,
4630 diff_base_anchor: None,
4631 }..Anchor {
4632 buffer_id,
4633 excerpt_id,
4634 text_anchor: end,
4635 diff_base_anchor: None,
4636 };
4637 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4638 write_ranges.push(range);
4639 } else {
4640 read_ranges.push(range);
4641 }
4642 }
4643 }
4644
4645 this.highlight_background::<DocumentHighlightRead>(
4646 &read_ranges,
4647 |theme| theme.editor_document_highlight_read_background,
4648 cx,
4649 );
4650 this.highlight_background::<DocumentHighlightWrite>(
4651 &write_ranges,
4652 |theme| theme.editor_document_highlight_write_background,
4653 cx,
4654 );
4655 cx.notify();
4656 })
4657 .log_err();
4658 }
4659 }));
4660 None
4661 }
4662
4663 pub fn refresh_inline_completion(
4664 &mut self,
4665 debounce: bool,
4666 user_requested: bool,
4667 window: &mut Window,
4668 cx: &mut Context<Self>,
4669 ) -> Option<()> {
4670 let provider = self.edit_prediction_provider()?;
4671 let cursor = self.selections.newest_anchor().head();
4672 let (buffer, cursor_buffer_position) =
4673 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4674
4675 if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4676 self.discard_inline_completion(false, cx);
4677 return None;
4678 }
4679
4680 if !user_requested
4681 && (!self.should_show_edit_predictions()
4682 || !self.is_focused(window)
4683 || buffer.read(cx).is_empty())
4684 {
4685 self.discard_inline_completion(false, cx);
4686 return None;
4687 }
4688
4689 self.update_visible_inline_completion(window, cx);
4690 provider.refresh(
4691 self.project.clone(),
4692 buffer,
4693 cursor_buffer_position,
4694 debounce,
4695 cx,
4696 );
4697 Some(())
4698 }
4699
4700 fn show_edit_predictions_in_menu(&self) -> bool {
4701 match self.edit_prediction_settings {
4702 EditPredictionSettings::Disabled => false,
4703 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4704 }
4705 }
4706
4707 pub fn edit_predictions_enabled(&self) -> bool {
4708 match self.edit_prediction_settings {
4709 EditPredictionSettings::Disabled => false,
4710 EditPredictionSettings::Enabled { .. } => true,
4711 }
4712 }
4713
4714 fn edit_prediction_requires_modifier(&self) -> bool {
4715 match self.edit_prediction_settings {
4716 EditPredictionSettings::Disabled => false,
4717 EditPredictionSettings::Enabled {
4718 preview_requires_modifier,
4719 ..
4720 } => preview_requires_modifier,
4721 }
4722 }
4723
4724 fn edit_prediction_settings_at_position(
4725 &self,
4726 buffer: &Entity<Buffer>,
4727 buffer_position: language::Anchor,
4728 cx: &App,
4729 ) -> EditPredictionSettings {
4730 if self.mode != EditorMode::Full
4731 || !self.show_inline_completions_override.unwrap_or(true)
4732 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
4733 {
4734 return EditPredictionSettings::Disabled;
4735 }
4736
4737 let buffer = buffer.read(cx);
4738
4739 let file = buffer.file();
4740
4741 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
4742 return EditPredictionSettings::Disabled;
4743 };
4744
4745 let by_provider = matches!(
4746 self.menu_inline_completions_policy,
4747 MenuInlineCompletionsPolicy::ByProvider
4748 );
4749
4750 let show_in_menu = by_provider
4751 && EditorSettings::get_global(cx).show_edit_predictions_in_menu
4752 && self
4753 .edit_prediction_provider
4754 .as_ref()
4755 .map_or(false, |provider| {
4756 provider.provider.show_completions_in_menu()
4757 });
4758
4759 let preview_requires_modifier = all_language_settings(file, cx)
4760 .inline_completions_preview_mode()
4761 == InlineCompletionPreviewMode::WhenHoldingModifier;
4762
4763 EditPredictionSettings::Enabled {
4764 show_in_menu,
4765 preview_requires_modifier,
4766 }
4767 }
4768
4769 fn should_show_edit_predictions(&self) -> bool {
4770 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
4771 }
4772
4773 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
4774 let cursor = self.selections.newest_anchor().head();
4775 if let Some((buffer, cursor_position)) =
4776 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4777 {
4778 self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
4779 } else {
4780 false
4781 }
4782 }
4783
4784 fn inline_completions_enabled_in_buffer(
4785 &self,
4786 buffer: &Entity<Buffer>,
4787 buffer_position: language::Anchor,
4788 cx: &App,
4789 ) -> bool {
4790 maybe!({
4791 let provider = self.edit_prediction_provider()?;
4792 if !provider.is_enabled(&buffer, buffer_position, cx) {
4793 return Some(false);
4794 }
4795 let buffer = buffer.read(cx);
4796 let Some(file) = buffer.file() else {
4797 return Some(true);
4798 };
4799 let settings = all_language_settings(Some(file), cx);
4800 Some(settings.inline_completions_enabled_for_path(file.path()))
4801 })
4802 .unwrap_or(false)
4803 }
4804
4805 fn cycle_inline_completion(
4806 &mut self,
4807 direction: Direction,
4808 window: &mut Window,
4809 cx: &mut Context<Self>,
4810 ) -> Option<()> {
4811 let provider = self.edit_prediction_provider()?;
4812 let cursor = self.selections.newest_anchor().head();
4813 let (buffer, cursor_buffer_position) =
4814 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4815 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
4816 return None;
4817 }
4818
4819 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4820 self.update_visible_inline_completion(window, cx);
4821
4822 Some(())
4823 }
4824
4825 pub fn show_inline_completion(
4826 &mut self,
4827 _: &ShowEditPrediction,
4828 window: &mut Window,
4829 cx: &mut Context<Self>,
4830 ) {
4831 if !self.has_active_inline_completion() {
4832 self.refresh_inline_completion(false, true, window, cx);
4833 return;
4834 }
4835
4836 self.update_visible_inline_completion(window, cx);
4837 }
4838
4839 pub fn display_cursor_names(
4840 &mut self,
4841 _: &DisplayCursorNames,
4842 window: &mut Window,
4843 cx: &mut Context<Self>,
4844 ) {
4845 self.show_cursor_names(window, cx);
4846 }
4847
4848 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4849 self.show_cursor_names = true;
4850 cx.notify();
4851 cx.spawn_in(window, |this, mut cx| async move {
4852 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4853 this.update(&mut cx, |this, cx| {
4854 this.show_cursor_names = false;
4855 cx.notify()
4856 })
4857 .ok()
4858 })
4859 .detach();
4860 }
4861
4862 pub fn next_edit_prediction(
4863 &mut self,
4864 _: &NextEditPrediction,
4865 window: &mut Window,
4866 cx: &mut Context<Self>,
4867 ) {
4868 if self.has_active_inline_completion() {
4869 self.cycle_inline_completion(Direction::Next, window, cx);
4870 } else {
4871 let is_copilot_disabled = self
4872 .refresh_inline_completion(false, true, window, cx)
4873 .is_none();
4874 if is_copilot_disabled {
4875 cx.propagate();
4876 }
4877 }
4878 }
4879
4880 pub fn previous_edit_prediction(
4881 &mut self,
4882 _: &PreviousEditPrediction,
4883 window: &mut Window,
4884 cx: &mut Context<Self>,
4885 ) {
4886 if self.has_active_inline_completion() {
4887 self.cycle_inline_completion(Direction::Prev, window, cx);
4888 } else {
4889 let is_copilot_disabled = self
4890 .refresh_inline_completion(false, true, window, cx)
4891 .is_none();
4892 if is_copilot_disabled {
4893 cx.propagate();
4894 }
4895 }
4896 }
4897
4898 pub fn accept_edit_prediction(
4899 &mut self,
4900 _: &AcceptEditPrediction,
4901 window: &mut Window,
4902 cx: &mut Context<Self>,
4903 ) {
4904 let buffer = self.buffer.read(cx);
4905 let snapshot = buffer.snapshot(cx);
4906 let selection = self.selections.newest_adjusted(cx);
4907 let cursor = selection.head();
4908 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
4909 let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
4910 if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
4911 {
4912 if cursor.column < suggested_indent.len
4913 && cursor.column <= current_indent.len
4914 && current_indent.len <= suggested_indent.len
4915 {
4916 self.tab(&Default::default(), window, cx);
4917 return;
4918 }
4919 }
4920
4921 if self.show_edit_predictions_in_menu() {
4922 self.hide_context_menu(window, cx);
4923 }
4924
4925 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4926 return;
4927 };
4928
4929 self.report_inline_completion_event(
4930 active_inline_completion.completion_id.clone(),
4931 true,
4932 cx,
4933 );
4934
4935 match &active_inline_completion.completion {
4936 InlineCompletion::Move { target, .. } => {
4937 let target = *target;
4938 // Note that this is also done in vim's handler of the Tab action.
4939 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
4940 selections.select_anchor_ranges([target..target]);
4941 });
4942 }
4943 InlineCompletion::Edit { edits, .. } => {
4944 if let Some(provider) = self.edit_prediction_provider() {
4945 provider.accept(cx);
4946 }
4947
4948 let snapshot = self.buffer.read(cx).snapshot(cx);
4949 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4950
4951 self.buffer.update(cx, |buffer, cx| {
4952 buffer.edit(edits.iter().cloned(), None, cx)
4953 });
4954
4955 self.change_selections(None, window, cx, |s| {
4956 s.select_anchor_ranges([last_edit_end..last_edit_end])
4957 });
4958
4959 self.update_visible_inline_completion(window, cx);
4960 if self.active_inline_completion.is_none() {
4961 self.refresh_inline_completion(true, true, window, cx);
4962 }
4963
4964 cx.notify();
4965 }
4966 }
4967 }
4968
4969 pub fn accept_partial_inline_completion(
4970 &mut self,
4971 _: &AcceptPartialEditPrediction,
4972 window: &mut Window,
4973 cx: &mut Context<Self>,
4974 ) {
4975 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4976 return;
4977 };
4978 if self.selections.count() != 1 {
4979 return;
4980 }
4981
4982 self.report_inline_completion_event(
4983 active_inline_completion.completion_id.clone(),
4984 true,
4985 cx,
4986 );
4987
4988 match &active_inline_completion.completion {
4989 InlineCompletion::Move { target, .. } => {
4990 let target = *target;
4991 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
4992 selections.select_anchor_ranges([target..target]);
4993 });
4994 }
4995 InlineCompletion::Edit { edits, .. } => {
4996 // Find an insertion that starts at the cursor position.
4997 let snapshot = self.buffer.read(cx).snapshot(cx);
4998 let cursor_offset = self.selections.newest::<usize>(cx).head();
4999 let insertion = edits.iter().find_map(|(range, text)| {
5000 let range = range.to_offset(&snapshot);
5001 if range.is_empty() && range.start == cursor_offset {
5002 Some(text)
5003 } else {
5004 None
5005 }
5006 });
5007
5008 if let Some(text) = insertion {
5009 let mut partial_completion = text
5010 .chars()
5011 .by_ref()
5012 .take_while(|c| c.is_alphabetic())
5013 .collect::<String>();
5014 if partial_completion.is_empty() {
5015 partial_completion = text
5016 .chars()
5017 .by_ref()
5018 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5019 .collect::<String>();
5020 }
5021
5022 cx.emit(EditorEvent::InputHandled {
5023 utf16_range_to_replace: None,
5024 text: partial_completion.clone().into(),
5025 });
5026
5027 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5028
5029 self.refresh_inline_completion(true, true, window, cx);
5030 cx.notify();
5031 } else {
5032 self.accept_edit_prediction(&Default::default(), window, cx);
5033 }
5034 }
5035 }
5036 }
5037
5038 fn discard_inline_completion(
5039 &mut self,
5040 should_report_inline_completion_event: bool,
5041 cx: &mut Context<Self>,
5042 ) -> bool {
5043 if should_report_inline_completion_event {
5044 let completion_id = self
5045 .active_inline_completion
5046 .as_ref()
5047 .and_then(|active_completion| active_completion.completion_id.clone());
5048
5049 self.report_inline_completion_event(completion_id, false, cx);
5050 }
5051
5052 if let Some(provider) = self.edit_prediction_provider() {
5053 provider.discard(cx);
5054 }
5055
5056 self.take_active_inline_completion(cx)
5057 }
5058
5059 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5060 let Some(provider) = self.edit_prediction_provider() else {
5061 return;
5062 };
5063
5064 let Some((_, buffer, _)) = self
5065 .buffer
5066 .read(cx)
5067 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5068 else {
5069 return;
5070 };
5071
5072 let extension = buffer
5073 .read(cx)
5074 .file()
5075 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5076
5077 let event_type = match accepted {
5078 true => "Edit Prediction Accepted",
5079 false => "Edit Prediction Discarded",
5080 };
5081 telemetry::event!(
5082 event_type,
5083 provider = provider.name(),
5084 prediction_id = id,
5085 suggestion_accepted = accepted,
5086 file_extension = extension,
5087 );
5088 }
5089
5090 pub fn has_active_inline_completion(&self) -> bool {
5091 self.active_inline_completion.is_some()
5092 }
5093
5094 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5095 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5096 return false;
5097 };
5098
5099 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5100 self.clear_highlights::<InlineCompletionHighlight>(cx);
5101 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5102 true
5103 }
5104
5105 /// Returns true when we're displaying the inline completion popover below the cursor
5106 /// like we are not previewing and the LSP autocomplete menu is visible
5107 /// or we are in `when_holding_modifier` mode.
5108 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5109 if self.previewing_inline_completion
5110 || !self.show_edit_predictions_in_menu()
5111 || !self.edit_predictions_enabled()
5112 {
5113 return false;
5114 }
5115
5116 if self.has_visible_completions_menu() {
5117 return true;
5118 }
5119
5120 has_completion && self.edit_prediction_requires_modifier()
5121 }
5122
5123 fn handle_modifiers_changed(
5124 &mut self,
5125 modifiers: Modifiers,
5126 position_map: &PositionMap,
5127 window: &mut Window,
5128 cx: &mut Context<Self>,
5129 ) {
5130 if self.show_edit_predictions_in_menu() {
5131 let accept_binding =
5132 AcceptEditPredictionBinding::resolve(self.focus_handle(cx), window);
5133 if let Some(accept_keystroke) = accept_binding.keystroke() {
5134 let was_previewing_inline_completion = self.previewing_inline_completion;
5135 self.previewing_inline_completion = modifiers == accept_keystroke.modifiers
5136 && accept_keystroke.modifiers.modified();
5137 if self.previewing_inline_completion != was_previewing_inline_completion {
5138 self.update_visible_inline_completion(window, cx);
5139 }
5140 }
5141 }
5142
5143 let mouse_position = window.mouse_position();
5144 if !position_map.text_hitbox.is_hovered(window) {
5145 return;
5146 }
5147
5148 self.update_hovered_link(
5149 position_map.point_for_position(mouse_position),
5150 &position_map.snapshot,
5151 modifiers,
5152 window,
5153 cx,
5154 )
5155 }
5156
5157 fn update_visible_inline_completion(
5158 &mut self,
5159 _window: &mut Window,
5160 cx: &mut Context<Self>,
5161 ) -> Option<()> {
5162 let selection = self.selections.newest_anchor();
5163 let cursor = selection.head();
5164 let multibuffer = self.buffer.read(cx).snapshot(cx);
5165 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5166 let excerpt_id = cursor.excerpt_id;
5167
5168 let show_in_menu = self.show_edit_predictions_in_menu();
5169 let completions_menu_has_precedence = !show_in_menu
5170 && (self.context_menu.borrow().is_some()
5171 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5172
5173 if completions_menu_has_precedence
5174 || !offset_selection.is_empty()
5175 || self
5176 .active_inline_completion
5177 .as_ref()
5178 .map_or(false, |completion| {
5179 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5180 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5181 !invalidation_range.contains(&offset_selection.head())
5182 })
5183 {
5184 self.discard_inline_completion(false, cx);
5185 return None;
5186 }
5187
5188 self.take_active_inline_completion(cx);
5189 let Some(provider) = self.edit_prediction_provider() else {
5190 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5191 return None;
5192 };
5193
5194 let (buffer, cursor_buffer_position) =
5195 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5196
5197 self.edit_prediction_settings =
5198 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5199
5200 if !self.edit_prediction_settings.is_enabled() {
5201 self.discard_inline_completion(false, cx);
5202 return None;
5203 }
5204
5205 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5206 let edits = inline_completion
5207 .edits
5208 .into_iter()
5209 .flat_map(|(range, new_text)| {
5210 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5211 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5212 Some((start..end, new_text))
5213 })
5214 .collect::<Vec<_>>();
5215 if edits.is_empty() {
5216 return None;
5217 }
5218
5219 let first_edit_start = edits.first().unwrap().0.start;
5220 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5221 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5222
5223 let last_edit_end = edits.last().unwrap().0.end;
5224 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5225 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5226
5227 let cursor_row = cursor.to_point(&multibuffer).row;
5228
5229 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5230
5231 let mut inlay_ids = Vec::new();
5232 let invalidation_row_range;
5233 let move_invalidation_row_range = if cursor_row < edit_start_row {
5234 Some(cursor_row..edit_end_row)
5235 } else if cursor_row > edit_end_row {
5236 Some(edit_start_row..cursor_row)
5237 } else {
5238 None
5239 };
5240 let is_move =
5241 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5242 let completion = if is_move {
5243 invalidation_row_range =
5244 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5245 let target = first_edit_start;
5246 let target_point = text::ToPoint::to_point(&target.text_anchor, &snapshot);
5247 // TODO: Base this off of TreeSitter or word boundaries?
5248 let target_excerpt_begin = snapshot.anchor_before(snapshot.clip_point(
5249 Point::new(target_point.row, target_point.column.saturating_sub(20)),
5250 Bias::Left,
5251 ));
5252 let target_excerpt_end = snapshot.anchor_after(snapshot.clip_point(
5253 Point::new(target_point.row, target_point.column + 20),
5254 Bias::Right,
5255 ));
5256 let range_around_target = target_excerpt_begin..target_excerpt_end;
5257 InlineCompletion::Move {
5258 target,
5259 range_around_target,
5260 snapshot,
5261 }
5262 } else {
5263 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5264 && !self.inline_completions_hidden_for_vim_mode;
5265 if show_completions_in_buffer {
5266 if edits
5267 .iter()
5268 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5269 {
5270 let mut inlays = Vec::new();
5271 for (range, new_text) in &edits {
5272 let inlay = Inlay::inline_completion(
5273 post_inc(&mut self.next_inlay_id),
5274 range.start,
5275 new_text.as_str(),
5276 );
5277 inlay_ids.push(inlay.id);
5278 inlays.push(inlay);
5279 }
5280
5281 self.splice_inlays(&[], inlays, cx);
5282 } else {
5283 let background_color = cx.theme().status().deleted_background;
5284 self.highlight_text::<InlineCompletionHighlight>(
5285 edits.iter().map(|(range, _)| range.clone()).collect(),
5286 HighlightStyle {
5287 background_color: Some(background_color),
5288 ..Default::default()
5289 },
5290 cx,
5291 );
5292 }
5293 }
5294
5295 invalidation_row_range = edit_start_row..edit_end_row;
5296
5297 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5298 if provider.show_tab_accept_marker() {
5299 EditDisplayMode::TabAccept
5300 } else {
5301 EditDisplayMode::Inline
5302 }
5303 } else {
5304 EditDisplayMode::DiffPopover
5305 };
5306
5307 InlineCompletion::Edit {
5308 edits,
5309 edit_preview: inline_completion.edit_preview,
5310 display_mode,
5311 snapshot,
5312 }
5313 };
5314
5315 let invalidation_range = multibuffer
5316 .anchor_before(Point::new(invalidation_row_range.start, 0))
5317 ..multibuffer.anchor_after(Point::new(
5318 invalidation_row_range.end,
5319 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5320 ));
5321
5322 self.stale_inline_completion_in_menu = None;
5323 self.active_inline_completion = Some(InlineCompletionState {
5324 inlay_ids,
5325 completion,
5326 completion_id: inline_completion.id,
5327 invalidation_range,
5328 });
5329
5330 cx.notify();
5331
5332 Some(())
5333 }
5334
5335 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5336 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5337 }
5338
5339 fn render_code_actions_indicator(
5340 &self,
5341 _style: &EditorStyle,
5342 row: DisplayRow,
5343 is_active: bool,
5344 cx: &mut Context<Self>,
5345 ) -> Option<IconButton> {
5346 if self.available_code_actions.is_some() {
5347 Some(
5348 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5349 .shape(ui::IconButtonShape::Square)
5350 .icon_size(IconSize::XSmall)
5351 .icon_color(Color::Muted)
5352 .toggle_state(is_active)
5353 .tooltip({
5354 let focus_handle = self.focus_handle.clone();
5355 move |window, cx| {
5356 Tooltip::for_action_in(
5357 "Toggle Code Actions",
5358 &ToggleCodeActions {
5359 deployed_from_indicator: None,
5360 },
5361 &focus_handle,
5362 window,
5363 cx,
5364 )
5365 }
5366 })
5367 .on_click(cx.listener(move |editor, _e, window, cx| {
5368 window.focus(&editor.focus_handle(cx));
5369 editor.toggle_code_actions(
5370 &ToggleCodeActions {
5371 deployed_from_indicator: Some(row),
5372 },
5373 window,
5374 cx,
5375 );
5376 })),
5377 )
5378 } else {
5379 None
5380 }
5381 }
5382
5383 fn clear_tasks(&mut self) {
5384 self.tasks.clear()
5385 }
5386
5387 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5388 if self.tasks.insert(key, value).is_some() {
5389 // This case should hopefully be rare, but just in case...
5390 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5391 }
5392 }
5393
5394 fn build_tasks_context(
5395 project: &Entity<Project>,
5396 buffer: &Entity<Buffer>,
5397 buffer_row: u32,
5398 tasks: &Arc<RunnableTasks>,
5399 cx: &mut Context<Self>,
5400 ) -> Task<Option<task::TaskContext>> {
5401 let position = Point::new(buffer_row, tasks.column);
5402 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5403 let location = Location {
5404 buffer: buffer.clone(),
5405 range: range_start..range_start,
5406 };
5407 // Fill in the environmental variables from the tree-sitter captures
5408 let mut captured_task_variables = TaskVariables::default();
5409 for (capture_name, value) in tasks.extra_variables.clone() {
5410 captured_task_variables.insert(
5411 task::VariableName::Custom(capture_name.into()),
5412 value.clone(),
5413 );
5414 }
5415 project.update(cx, |project, cx| {
5416 project.task_store().update(cx, |task_store, cx| {
5417 task_store.task_context_for_location(captured_task_variables, location, cx)
5418 })
5419 })
5420 }
5421
5422 pub fn spawn_nearest_task(
5423 &mut self,
5424 action: &SpawnNearestTask,
5425 window: &mut Window,
5426 cx: &mut Context<Self>,
5427 ) {
5428 let Some((workspace, _)) = self.workspace.clone() else {
5429 return;
5430 };
5431 let Some(project) = self.project.clone() else {
5432 return;
5433 };
5434
5435 // Try to find a closest, enclosing node using tree-sitter that has a
5436 // task
5437 let Some((buffer, buffer_row, tasks)) = self
5438 .find_enclosing_node_task(cx)
5439 // Or find the task that's closest in row-distance.
5440 .or_else(|| self.find_closest_task(cx))
5441 else {
5442 return;
5443 };
5444
5445 let reveal_strategy = action.reveal;
5446 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5447 cx.spawn_in(window, |_, mut cx| async move {
5448 let context = task_context.await?;
5449 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5450
5451 let resolved = resolved_task.resolved.as_mut()?;
5452 resolved.reveal = reveal_strategy;
5453
5454 workspace
5455 .update(&mut cx, |workspace, cx| {
5456 workspace::tasks::schedule_resolved_task(
5457 workspace,
5458 task_source_kind,
5459 resolved_task,
5460 false,
5461 cx,
5462 );
5463 })
5464 .ok()
5465 })
5466 .detach();
5467 }
5468
5469 fn find_closest_task(
5470 &mut self,
5471 cx: &mut Context<Self>,
5472 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5473 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5474
5475 let ((buffer_id, row), tasks) = self
5476 .tasks
5477 .iter()
5478 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5479
5480 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5481 let tasks = Arc::new(tasks.to_owned());
5482 Some((buffer, *row, tasks))
5483 }
5484
5485 fn find_enclosing_node_task(
5486 &mut self,
5487 cx: &mut Context<Self>,
5488 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5489 let snapshot = self.buffer.read(cx).snapshot(cx);
5490 let offset = self.selections.newest::<usize>(cx).head();
5491 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5492 let buffer_id = excerpt.buffer().remote_id();
5493
5494 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5495 let mut cursor = layer.node().walk();
5496
5497 while cursor.goto_first_child_for_byte(offset).is_some() {
5498 if cursor.node().end_byte() == offset {
5499 cursor.goto_next_sibling();
5500 }
5501 }
5502
5503 // Ascend to the smallest ancestor that contains the range and has a task.
5504 loop {
5505 let node = cursor.node();
5506 let node_range = node.byte_range();
5507 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5508
5509 // Check if this node contains our offset
5510 if node_range.start <= offset && node_range.end >= offset {
5511 // If it contains offset, check for task
5512 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5513 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5514 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5515 }
5516 }
5517
5518 if !cursor.goto_parent() {
5519 break;
5520 }
5521 }
5522 None
5523 }
5524
5525 fn render_run_indicator(
5526 &self,
5527 _style: &EditorStyle,
5528 is_active: bool,
5529 row: DisplayRow,
5530 cx: &mut Context<Self>,
5531 ) -> IconButton {
5532 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5533 .shape(ui::IconButtonShape::Square)
5534 .icon_size(IconSize::XSmall)
5535 .icon_color(Color::Muted)
5536 .toggle_state(is_active)
5537 .on_click(cx.listener(move |editor, _e, window, cx| {
5538 window.focus(&editor.focus_handle(cx));
5539 editor.toggle_code_actions(
5540 &ToggleCodeActions {
5541 deployed_from_indicator: Some(row),
5542 },
5543 window,
5544 cx,
5545 );
5546 }))
5547 }
5548
5549 pub fn context_menu_visible(&self) -> bool {
5550 !self.previewing_inline_completion
5551 && self
5552 .context_menu
5553 .borrow()
5554 .as_ref()
5555 .map_or(false, |menu| menu.visible())
5556 }
5557
5558 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5559 self.context_menu
5560 .borrow()
5561 .as_ref()
5562 .map(|menu| menu.origin())
5563 }
5564
5565 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5566 px(30.)
5567 }
5568
5569 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5570 if self.read_only(cx) {
5571 cx.theme().players().read_only()
5572 } else {
5573 self.style.as_ref().unwrap().local_player
5574 }
5575 }
5576
5577 #[allow(clippy::too_many_arguments)]
5578 fn render_edit_prediction_cursor_popover(
5579 &self,
5580 min_width: Pixels,
5581 max_width: Pixels,
5582 cursor_point: Point,
5583 style: &EditorStyle,
5584 accept_keystroke: &gpui::Keystroke,
5585 window: &Window,
5586 cx: &mut Context<Editor>,
5587 ) -> Option<AnyElement> {
5588 let provider = self.edit_prediction_provider.as_ref()?;
5589
5590 if provider.provider.needs_terms_acceptance(cx) {
5591 return Some(
5592 h_flex()
5593 .h(self.edit_prediction_cursor_popover_height())
5594 .min_w(min_width)
5595 .flex_1()
5596 .px_2()
5597 .gap_3()
5598 .elevation_2(cx)
5599 .hover(|style| style.bg(cx.theme().colors().element_hover))
5600 .id("accept-terms")
5601 .cursor_pointer()
5602 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5603 .on_click(cx.listener(|this, _event, window, cx| {
5604 cx.stop_propagation();
5605 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
5606 window.dispatch_action(
5607 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
5608 cx,
5609 );
5610 }))
5611 .child(
5612 h_flex()
5613 .flex_1()
5614 .gap_2()
5615 .child(Icon::new(IconName::ZedPredict))
5616 .child(Label::new("Accept Terms of Service"))
5617 .child(div().w_full())
5618 .child(
5619 Icon::new(IconName::ArrowUpRight)
5620 .color(Color::Muted)
5621 .size(IconSize::Small),
5622 )
5623 .into_any_element(),
5624 )
5625 .into_any(),
5626 );
5627 }
5628
5629 let is_refreshing = provider.provider.is_refreshing(cx);
5630
5631 fn pending_completion_container() -> Div {
5632 h_flex()
5633 .h_full()
5634 .flex_1()
5635 .gap_2()
5636 .child(Icon::new(IconName::ZedPredict))
5637 }
5638
5639 let completion = match &self.active_inline_completion {
5640 Some(completion) => self.render_edit_prediction_cursor_popover_preview(
5641 completion,
5642 cursor_point,
5643 style,
5644 window,
5645 cx,
5646 )?,
5647
5648 None if is_refreshing => match &self.stale_inline_completion_in_menu {
5649 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
5650 stale_completion,
5651 cursor_point,
5652 style,
5653 window,
5654 cx,
5655 )?,
5656
5657 None => {
5658 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
5659 }
5660 },
5661
5662 None => pending_completion_container().child(Label::new("No Prediction")),
5663 };
5664
5665 let buffer_font = theme::ThemeSettings::get_global(cx).buffer_font.clone();
5666 let completion = completion.font(buffer_font.clone());
5667
5668 let completion = if is_refreshing {
5669 completion
5670 .with_animation(
5671 "loading-completion",
5672 Animation::new(Duration::from_secs(2))
5673 .repeat()
5674 .with_easing(pulsating_between(0.4, 0.8)),
5675 |label, delta| label.opacity(delta),
5676 )
5677 .into_any_element()
5678 } else {
5679 completion.into_any_element()
5680 };
5681
5682 let has_completion = self.active_inline_completion.is_some();
5683
5684 Some(
5685 h_flex()
5686 .h(self.edit_prediction_cursor_popover_height())
5687 .min_w(min_width)
5688 .max_w(max_width)
5689 .flex_1()
5690 .px_2()
5691 .elevation_2(cx)
5692 .child(completion)
5693 .child(ui::Divider::vertical())
5694 .child(
5695 h_flex()
5696 .h_full()
5697 .gap_1()
5698 .pl_2()
5699 .child(h_flex().font(buffer_font.clone()).gap_1().children(
5700 ui::render_modifiers(
5701 &accept_keystroke.modifiers,
5702 PlatformStyle::platform(),
5703 Some(if !has_completion {
5704 Color::Muted
5705 } else {
5706 Color::Default
5707 }),
5708 None,
5709 true,
5710 ),
5711 ))
5712 .child(Label::new("Preview").into_any_element())
5713 .opacity(if has_completion { 1.0 } else { 0.4 }),
5714 )
5715 .into_any(),
5716 )
5717 }
5718
5719 fn render_edit_prediction_cursor_popover_preview(
5720 &self,
5721 completion: &InlineCompletionState,
5722 cursor_point: Point,
5723 style: &EditorStyle,
5724 window: &Window,
5725 cx: &mut Context<Editor>,
5726 ) -> Option<Div> {
5727 use text::ToPoint as _;
5728
5729 fn render_relative_row_jump(
5730 prefix: impl Into<String>,
5731 current_row: u32,
5732 target_row: u32,
5733 ) -> Div {
5734 let (row_diff, arrow) = if target_row < current_row {
5735 (current_row - target_row, IconName::ArrowUp)
5736 } else {
5737 (target_row - current_row, IconName::ArrowDown)
5738 };
5739
5740 h_flex()
5741 .child(
5742 Label::new(format!("{}{}", prefix.into(), row_diff))
5743 .color(Color::Muted)
5744 .size(LabelSize::Small),
5745 )
5746 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
5747 }
5748
5749 match &completion.completion {
5750 InlineCompletion::Edit {
5751 edits,
5752 edit_preview,
5753 snapshot,
5754 display_mode: _,
5755 } => {
5756 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
5757
5758 let highlighted_edits = crate::inline_completion_edit_text(
5759 &snapshot,
5760 &edits,
5761 edit_preview.as_ref()?,
5762 true,
5763 cx,
5764 );
5765
5766 let len_total = highlighted_edits.text.len();
5767 let first_line = &highlighted_edits.text
5768 [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
5769 let first_line_len = first_line.len();
5770
5771 let first_highlight_start = highlighted_edits
5772 .highlights
5773 .first()
5774 .map_or(0, |(range, _)| range.start);
5775 let drop_prefix_len = first_line
5776 .char_indices()
5777 .find(|(_, c)| !c.is_whitespace())
5778 .map_or(first_highlight_start, |(ix, _)| {
5779 ix.min(first_highlight_start)
5780 });
5781
5782 let preview_text = &first_line[drop_prefix_len..];
5783 let preview_len = preview_text.len();
5784 let highlights = highlighted_edits
5785 .highlights
5786 .into_iter()
5787 .take_until(|(range, _)| range.start > first_line_len)
5788 .map(|(range, style)| {
5789 (
5790 range.start - drop_prefix_len
5791 ..(range.end - drop_prefix_len).min(preview_len),
5792 style,
5793 )
5794 });
5795
5796 let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
5797 .with_highlights(&style.text, highlights);
5798
5799 let preview = h_flex()
5800 .gap_1()
5801 .min_w_16()
5802 .child(styled_text)
5803 .when(len_total > first_line_len, |parent| parent.child("…"));
5804
5805 let left = if first_edit_row != cursor_point.row {
5806 render_relative_row_jump("", cursor_point.row, first_edit_row)
5807 .into_any_element()
5808 } else {
5809 Icon::new(IconName::ZedPredict).into_any_element()
5810 };
5811
5812 Some(
5813 h_flex()
5814 .h_full()
5815 .flex_1()
5816 .gap_2()
5817 .pr_1()
5818 .overflow_x_hidden()
5819 .child(left)
5820 .child(preview),
5821 )
5822 }
5823
5824 InlineCompletion::Move {
5825 target,
5826 range_around_target,
5827 snapshot,
5828 } => {
5829 let highlighted_text = snapshot.highlighted_text_for_range(
5830 range_around_target.clone(),
5831 None,
5832 &style.syntax,
5833 );
5834 let base = h_flex().gap_3().flex_1().child(render_relative_row_jump(
5835 "Jump ",
5836 cursor_point.row,
5837 target.text_anchor.to_point(&snapshot).row,
5838 ));
5839
5840 if highlighted_text.text.is_empty() {
5841 return Some(base);
5842 }
5843
5844 let cursor_color = self.current_user_player_color(cx).cursor;
5845
5846 let start_point = range_around_target.start.to_point(&snapshot);
5847 let end_point = range_around_target.end.to_point(&snapshot);
5848 let target_point = target.text_anchor.to_point(&snapshot);
5849
5850 let styled_text = highlighted_text.to_styled_text(&style.text);
5851 let text_len = highlighted_text.text.len();
5852
5853 let cursor_relative_position = window
5854 .text_system()
5855 .layout_line(
5856 highlighted_text.text,
5857 style.text.font_size.to_pixels(window.rem_size()),
5858 // We don't need to include highlights
5859 // because we are only using this for the cursor position
5860 &[TextRun {
5861 len: text_len,
5862 font: style.text.font(),
5863 color: style.text.color,
5864 background_color: None,
5865 underline: None,
5866 strikethrough: None,
5867 }],
5868 )
5869 .log_err()
5870 .map(|line| {
5871 line.x_for_index(
5872 target_point.column.saturating_sub(start_point.column) as usize
5873 )
5874 });
5875
5876 let fade_before = start_point.column > 0;
5877 let fade_after = end_point.column < snapshot.line_len(end_point.row);
5878
5879 let background = cx.theme().colors().elevated_surface_background;
5880
5881 let preview = h_flex()
5882 .relative()
5883 .child(styled_text)
5884 .when(fade_before, |parent| {
5885 parent.child(div().absolute().top_0().left_0().w_4().h_full().bg(
5886 linear_gradient(
5887 90.,
5888 linear_color_stop(background, 0.),
5889 linear_color_stop(background.opacity(0.), 1.),
5890 ),
5891 ))
5892 })
5893 .when(fade_after, |parent| {
5894 parent.child(div().absolute().top_0().right_0().w_4().h_full().bg(
5895 linear_gradient(
5896 -90.,
5897 linear_color_stop(background, 0.),
5898 linear_color_stop(background.opacity(0.), 1.),
5899 ),
5900 ))
5901 })
5902 .when_some(cursor_relative_position, |parent, position| {
5903 parent.child(
5904 div()
5905 .w(px(2.))
5906 .h_full()
5907 .bg(cursor_color)
5908 .absolute()
5909 .top_0()
5910 .left(position),
5911 )
5912 });
5913
5914 Some(base.child(preview))
5915 }
5916 }
5917 }
5918
5919 fn render_context_menu(
5920 &self,
5921 style: &EditorStyle,
5922 max_height_in_lines: u32,
5923 y_flipped: bool,
5924 window: &mut Window,
5925 cx: &mut Context<Editor>,
5926 ) -> Option<AnyElement> {
5927 let menu = self.context_menu.borrow();
5928 let menu = menu.as_ref()?;
5929 if !menu.visible() {
5930 return None;
5931 };
5932 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
5933 }
5934
5935 fn render_context_menu_aside(
5936 &self,
5937 style: &EditorStyle,
5938 max_size: Size<Pixels>,
5939 cx: &mut Context<Editor>,
5940 ) -> Option<AnyElement> {
5941 self.context_menu.borrow().as_ref().and_then(|menu| {
5942 if menu.visible() {
5943 menu.render_aside(
5944 style,
5945 max_size,
5946 self.workspace.as_ref().map(|(w, _)| w.clone()),
5947 cx,
5948 )
5949 } else {
5950 None
5951 }
5952 })
5953 }
5954
5955 fn hide_context_menu(
5956 &mut self,
5957 window: &mut Window,
5958 cx: &mut Context<Self>,
5959 ) -> Option<CodeContextMenu> {
5960 cx.notify();
5961 self.completion_tasks.clear();
5962 let context_menu = self.context_menu.borrow_mut().take();
5963 self.stale_inline_completion_in_menu.take();
5964 self.update_visible_inline_completion(window, cx);
5965 context_menu
5966 }
5967
5968 fn show_snippet_choices(
5969 &mut self,
5970 choices: &Vec<String>,
5971 selection: Range<Anchor>,
5972 cx: &mut Context<Self>,
5973 ) {
5974 if selection.start.buffer_id.is_none() {
5975 return;
5976 }
5977 let buffer_id = selection.start.buffer_id.unwrap();
5978 let buffer = self.buffer().read(cx).buffer(buffer_id);
5979 let id = post_inc(&mut self.next_completion_id);
5980
5981 if let Some(buffer) = buffer {
5982 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5983 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5984 ));
5985 }
5986 }
5987
5988 pub fn insert_snippet(
5989 &mut self,
5990 insertion_ranges: &[Range<usize>],
5991 snippet: Snippet,
5992 window: &mut Window,
5993 cx: &mut Context<Self>,
5994 ) -> Result<()> {
5995 struct Tabstop<T> {
5996 is_end_tabstop: bool,
5997 ranges: Vec<Range<T>>,
5998 choices: Option<Vec<String>>,
5999 }
6000
6001 let tabstops = self.buffer.update(cx, |buffer, cx| {
6002 let snippet_text: Arc<str> = snippet.text.clone().into();
6003 buffer.edit(
6004 insertion_ranges
6005 .iter()
6006 .cloned()
6007 .map(|range| (range, snippet_text.clone())),
6008 Some(AutoindentMode::EachLine),
6009 cx,
6010 );
6011
6012 let snapshot = &*buffer.read(cx);
6013 let snippet = &snippet;
6014 snippet
6015 .tabstops
6016 .iter()
6017 .map(|tabstop| {
6018 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6019 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6020 });
6021 let mut tabstop_ranges = tabstop
6022 .ranges
6023 .iter()
6024 .flat_map(|tabstop_range| {
6025 let mut delta = 0_isize;
6026 insertion_ranges.iter().map(move |insertion_range| {
6027 let insertion_start = insertion_range.start as isize + delta;
6028 delta +=
6029 snippet.text.len() as isize - insertion_range.len() as isize;
6030
6031 let start = ((insertion_start + tabstop_range.start) as usize)
6032 .min(snapshot.len());
6033 let end = ((insertion_start + tabstop_range.end) as usize)
6034 .min(snapshot.len());
6035 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6036 })
6037 })
6038 .collect::<Vec<_>>();
6039 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6040
6041 Tabstop {
6042 is_end_tabstop,
6043 ranges: tabstop_ranges,
6044 choices: tabstop.choices.clone(),
6045 }
6046 })
6047 .collect::<Vec<_>>()
6048 });
6049 if let Some(tabstop) = tabstops.first() {
6050 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6051 s.select_ranges(tabstop.ranges.iter().cloned());
6052 });
6053
6054 if let Some(choices) = &tabstop.choices {
6055 if let Some(selection) = tabstop.ranges.first() {
6056 self.show_snippet_choices(choices, selection.clone(), cx)
6057 }
6058 }
6059
6060 // If we're already at the last tabstop and it's at the end of the snippet,
6061 // we're done, we don't need to keep the state around.
6062 if !tabstop.is_end_tabstop {
6063 let choices = tabstops
6064 .iter()
6065 .map(|tabstop| tabstop.choices.clone())
6066 .collect();
6067
6068 let ranges = tabstops
6069 .into_iter()
6070 .map(|tabstop| tabstop.ranges)
6071 .collect::<Vec<_>>();
6072
6073 self.snippet_stack.push(SnippetState {
6074 active_index: 0,
6075 ranges,
6076 choices,
6077 });
6078 }
6079
6080 // Check whether the just-entered snippet ends with an auto-closable bracket.
6081 if self.autoclose_regions.is_empty() {
6082 let snapshot = self.buffer.read(cx).snapshot(cx);
6083 for selection in &mut self.selections.all::<Point>(cx) {
6084 let selection_head = selection.head();
6085 let Some(scope) = snapshot.language_scope_at(selection_head) else {
6086 continue;
6087 };
6088
6089 let mut bracket_pair = None;
6090 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
6091 let prev_chars = snapshot
6092 .reversed_chars_at(selection_head)
6093 .collect::<String>();
6094 for (pair, enabled) in scope.brackets() {
6095 if enabled
6096 && pair.close
6097 && prev_chars.starts_with(pair.start.as_str())
6098 && next_chars.starts_with(pair.end.as_str())
6099 {
6100 bracket_pair = Some(pair.clone());
6101 break;
6102 }
6103 }
6104 if let Some(pair) = bracket_pair {
6105 let start = snapshot.anchor_after(selection_head);
6106 let end = snapshot.anchor_after(selection_head);
6107 self.autoclose_regions.push(AutocloseRegion {
6108 selection_id: selection.id,
6109 range: start..end,
6110 pair,
6111 });
6112 }
6113 }
6114 }
6115 }
6116 Ok(())
6117 }
6118
6119 pub fn move_to_next_snippet_tabstop(
6120 &mut self,
6121 window: &mut Window,
6122 cx: &mut Context<Self>,
6123 ) -> bool {
6124 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6125 }
6126
6127 pub fn move_to_prev_snippet_tabstop(
6128 &mut self,
6129 window: &mut Window,
6130 cx: &mut Context<Self>,
6131 ) -> bool {
6132 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6133 }
6134
6135 pub fn move_to_snippet_tabstop(
6136 &mut self,
6137 bias: Bias,
6138 window: &mut Window,
6139 cx: &mut Context<Self>,
6140 ) -> bool {
6141 if let Some(mut snippet) = self.snippet_stack.pop() {
6142 match bias {
6143 Bias::Left => {
6144 if snippet.active_index > 0 {
6145 snippet.active_index -= 1;
6146 } else {
6147 self.snippet_stack.push(snippet);
6148 return false;
6149 }
6150 }
6151 Bias::Right => {
6152 if snippet.active_index + 1 < snippet.ranges.len() {
6153 snippet.active_index += 1;
6154 } else {
6155 self.snippet_stack.push(snippet);
6156 return false;
6157 }
6158 }
6159 }
6160 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6161 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6162 s.select_anchor_ranges(current_ranges.iter().cloned())
6163 });
6164
6165 if let Some(choices) = &snippet.choices[snippet.active_index] {
6166 if let Some(selection) = current_ranges.first() {
6167 self.show_snippet_choices(&choices, selection.clone(), cx);
6168 }
6169 }
6170
6171 // If snippet state is not at the last tabstop, push it back on the stack
6172 if snippet.active_index + 1 < snippet.ranges.len() {
6173 self.snippet_stack.push(snippet);
6174 }
6175 return true;
6176 }
6177 }
6178
6179 false
6180 }
6181
6182 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6183 self.transact(window, cx, |this, window, cx| {
6184 this.select_all(&SelectAll, window, cx);
6185 this.insert("", window, cx);
6186 });
6187 }
6188
6189 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6190 self.transact(window, cx, |this, window, cx| {
6191 this.select_autoclose_pair(window, cx);
6192 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6193 if !this.linked_edit_ranges.is_empty() {
6194 let selections = this.selections.all::<MultiBufferPoint>(cx);
6195 let snapshot = this.buffer.read(cx).snapshot(cx);
6196
6197 for selection in selections.iter() {
6198 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6199 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6200 if selection_start.buffer_id != selection_end.buffer_id {
6201 continue;
6202 }
6203 if let Some(ranges) =
6204 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6205 {
6206 for (buffer, entries) in ranges {
6207 linked_ranges.entry(buffer).or_default().extend(entries);
6208 }
6209 }
6210 }
6211 }
6212
6213 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6214 if !this.selections.line_mode {
6215 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6216 for selection in &mut selections {
6217 if selection.is_empty() {
6218 let old_head = selection.head();
6219 let mut new_head =
6220 movement::left(&display_map, old_head.to_display_point(&display_map))
6221 .to_point(&display_map);
6222 if let Some((buffer, line_buffer_range)) = display_map
6223 .buffer_snapshot
6224 .buffer_line_for_row(MultiBufferRow(old_head.row))
6225 {
6226 let indent_size =
6227 buffer.indent_size_for_line(line_buffer_range.start.row);
6228 let indent_len = match indent_size.kind {
6229 IndentKind::Space => {
6230 buffer.settings_at(line_buffer_range.start, cx).tab_size
6231 }
6232 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6233 };
6234 if old_head.column <= indent_size.len && old_head.column > 0 {
6235 let indent_len = indent_len.get();
6236 new_head = cmp::min(
6237 new_head,
6238 MultiBufferPoint::new(
6239 old_head.row,
6240 ((old_head.column - 1) / indent_len) * indent_len,
6241 ),
6242 );
6243 }
6244 }
6245
6246 selection.set_head(new_head, SelectionGoal::None);
6247 }
6248 }
6249 }
6250
6251 this.signature_help_state.set_backspace_pressed(true);
6252 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6253 s.select(selections)
6254 });
6255 this.insert("", window, cx);
6256 let empty_str: Arc<str> = Arc::from("");
6257 for (buffer, edits) in linked_ranges {
6258 let snapshot = buffer.read(cx).snapshot();
6259 use text::ToPoint as TP;
6260
6261 let edits = edits
6262 .into_iter()
6263 .map(|range| {
6264 let end_point = TP::to_point(&range.end, &snapshot);
6265 let mut start_point = TP::to_point(&range.start, &snapshot);
6266
6267 if end_point == start_point {
6268 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6269 .saturating_sub(1);
6270 start_point =
6271 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6272 };
6273
6274 (start_point..end_point, empty_str.clone())
6275 })
6276 .sorted_by_key(|(range, _)| range.start)
6277 .collect::<Vec<_>>();
6278 buffer.update(cx, |this, cx| {
6279 this.edit(edits, None, cx);
6280 })
6281 }
6282 this.refresh_inline_completion(true, false, window, cx);
6283 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6284 });
6285 }
6286
6287 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6288 self.transact(window, cx, |this, window, cx| {
6289 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6290 let line_mode = s.line_mode;
6291 s.move_with(|map, selection| {
6292 if selection.is_empty() && !line_mode {
6293 let cursor = movement::right(map, selection.head());
6294 selection.end = cursor;
6295 selection.reversed = true;
6296 selection.goal = SelectionGoal::None;
6297 }
6298 })
6299 });
6300 this.insert("", window, cx);
6301 this.refresh_inline_completion(true, false, window, cx);
6302 });
6303 }
6304
6305 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6306 if self.move_to_prev_snippet_tabstop(window, cx) {
6307 return;
6308 }
6309
6310 self.outdent(&Outdent, window, cx);
6311 }
6312
6313 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6314 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6315 return;
6316 }
6317
6318 let mut selections = self.selections.all_adjusted(cx);
6319 let buffer = self.buffer.read(cx);
6320 let snapshot = buffer.snapshot(cx);
6321 let rows_iter = selections.iter().map(|s| s.head().row);
6322 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6323
6324 let mut edits = Vec::new();
6325 let mut prev_edited_row = 0;
6326 let mut row_delta = 0;
6327 for selection in &mut selections {
6328 if selection.start.row != prev_edited_row {
6329 row_delta = 0;
6330 }
6331 prev_edited_row = selection.end.row;
6332
6333 // If the selection is non-empty, then increase the indentation of the selected lines.
6334 if !selection.is_empty() {
6335 row_delta =
6336 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6337 continue;
6338 }
6339
6340 // If the selection is empty and the cursor is in the leading whitespace before the
6341 // suggested indentation, then auto-indent the line.
6342 let cursor = selection.head();
6343 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6344 if let Some(suggested_indent) =
6345 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6346 {
6347 if cursor.column < suggested_indent.len
6348 && cursor.column <= current_indent.len
6349 && current_indent.len <= suggested_indent.len
6350 {
6351 selection.start = Point::new(cursor.row, suggested_indent.len);
6352 selection.end = selection.start;
6353 if row_delta == 0 {
6354 edits.extend(Buffer::edit_for_indent_size_adjustment(
6355 cursor.row,
6356 current_indent,
6357 suggested_indent,
6358 ));
6359 row_delta = suggested_indent.len - current_indent.len;
6360 }
6361 continue;
6362 }
6363 }
6364
6365 // Otherwise, insert a hard or soft tab.
6366 let settings = buffer.settings_at(cursor, cx);
6367 let tab_size = if settings.hard_tabs {
6368 IndentSize::tab()
6369 } else {
6370 let tab_size = settings.tab_size.get();
6371 let char_column = snapshot
6372 .text_for_range(Point::new(cursor.row, 0)..cursor)
6373 .flat_map(str::chars)
6374 .count()
6375 + row_delta as usize;
6376 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6377 IndentSize::spaces(chars_to_next_tab_stop)
6378 };
6379 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6380 selection.end = selection.start;
6381 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6382 row_delta += tab_size.len;
6383 }
6384
6385 self.transact(window, cx, |this, window, cx| {
6386 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6387 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6388 s.select(selections)
6389 });
6390 this.refresh_inline_completion(true, false, window, cx);
6391 });
6392 }
6393
6394 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6395 if self.read_only(cx) {
6396 return;
6397 }
6398 let mut selections = self.selections.all::<Point>(cx);
6399 let mut prev_edited_row = 0;
6400 let mut row_delta = 0;
6401 let mut edits = Vec::new();
6402 let buffer = self.buffer.read(cx);
6403 let snapshot = buffer.snapshot(cx);
6404 for selection in &mut selections {
6405 if selection.start.row != prev_edited_row {
6406 row_delta = 0;
6407 }
6408 prev_edited_row = selection.end.row;
6409
6410 row_delta =
6411 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6412 }
6413
6414 self.transact(window, cx, |this, window, cx| {
6415 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6416 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6417 s.select(selections)
6418 });
6419 });
6420 }
6421
6422 fn indent_selection(
6423 buffer: &MultiBuffer,
6424 snapshot: &MultiBufferSnapshot,
6425 selection: &mut Selection<Point>,
6426 edits: &mut Vec<(Range<Point>, String)>,
6427 delta_for_start_row: u32,
6428 cx: &App,
6429 ) -> u32 {
6430 let settings = buffer.settings_at(selection.start, cx);
6431 let tab_size = settings.tab_size.get();
6432 let indent_kind = if settings.hard_tabs {
6433 IndentKind::Tab
6434 } else {
6435 IndentKind::Space
6436 };
6437 let mut start_row = selection.start.row;
6438 let mut end_row = selection.end.row + 1;
6439
6440 // If a selection ends at the beginning of a line, don't indent
6441 // that last line.
6442 if selection.end.column == 0 && selection.end.row > selection.start.row {
6443 end_row -= 1;
6444 }
6445
6446 // Avoid re-indenting a row that has already been indented by a
6447 // previous selection, but still update this selection's column
6448 // to reflect that indentation.
6449 if delta_for_start_row > 0 {
6450 start_row += 1;
6451 selection.start.column += delta_for_start_row;
6452 if selection.end.row == selection.start.row {
6453 selection.end.column += delta_for_start_row;
6454 }
6455 }
6456
6457 let mut delta_for_end_row = 0;
6458 let has_multiple_rows = start_row + 1 != end_row;
6459 for row in start_row..end_row {
6460 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6461 let indent_delta = match (current_indent.kind, indent_kind) {
6462 (IndentKind::Space, IndentKind::Space) => {
6463 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6464 IndentSize::spaces(columns_to_next_tab_stop)
6465 }
6466 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6467 (_, IndentKind::Tab) => IndentSize::tab(),
6468 };
6469
6470 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6471 0
6472 } else {
6473 selection.start.column
6474 };
6475 let row_start = Point::new(row, start);
6476 edits.push((
6477 row_start..row_start,
6478 indent_delta.chars().collect::<String>(),
6479 ));
6480
6481 // Update this selection's endpoints to reflect the indentation.
6482 if row == selection.start.row {
6483 selection.start.column += indent_delta.len;
6484 }
6485 if row == selection.end.row {
6486 selection.end.column += indent_delta.len;
6487 delta_for_end_row = indent_delta.len;
6488 }
6489 }
6490
6491 if selection.start.row == selection.end.row {
6492 delta_for_start_row + delta_for_end_row
6493 } else {
6494 delta_for_end_row
6495 }
6496 }
6497
6498 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6499 if self.read_only(cx) {
6500 return;
6501 }
6502 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6503 let selections = self.selections.all::<Point>(cx);
6504 let mut deletion_ranges = Vec::new();
6505 let mut last_outdent = None;
6506 {
6507 let buffer = self.buffer.read(cx);
6508 let snapshot = buffer.snapshot(cx);
6509 for selection in &selections {
6510 let settings = buffer.settings_at(selection.start, cx);
6511 let tab_size = settings.tab_size.get();
6512 let mut rows = selection.spanned_rows(false, &display_map);
6513
6514 // Avoid re-outdenting a row that has already been outdented by a
6515 // previous selection.
6516 if let Some(last_row) = last_outdent {
6517 if last_row == rows.start {
6518 rows.start = rows.start.next_row();
6519 }
6520 }
6521 let has_multiple_rows = rows.len() > 1;
6522 for row in rows.iter_rows() {
6523 let indent_size = snapshot.indent_size_for_line(row);
6524 if indent_size.len > 0 {
6525 let deletion_len = match indent_size.kind {
6526 IndentKind::Space => {
6527 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6528 if columns_to_prev_tab_stop == 0 {
6529 tab_size
6530 } else {
6531 columns_to_prev_tab_stop
6532 }
6533 }
6534 IndentKind::Tab => 1,
6535 };
6536 let start = if has_multiple_rows
6537 || deletion_len > selection.start.column
6538 || indent_size.len < selection.start.column
6539 {
6540 0
6541 } else {
6542 selection.start.column - deletion_len
6543 };
6544 deletion_ranges.push(
6545 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6546 );
6547 last_outdent = Some(row);
6548 }
6549 }
6550 }
6551 }
6552
6553 self.transact(window, cx, |this, window, cx| {
6554 this.buffer.update(cx, |buffer, cx| {
6555 let empty_str: Arc<str> = Arc::default();
6556 buffer.edit(
6557 deletion_ranges
6558 .into_iter()
6559 .map(|range| (range, empty_str.clone())),
6560 None,
6561 cx,
6562 );
6563 });
6564 let selections = this.selections.all::<usize>(cx);
6565 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6566 s.select(selections)
6567 });
6568 });
6569 }
6570
6571 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6572 if self.read_only(cx) {
6573 return;
6574 }
6575 let selections = self
6576 .selections
6577 .all::<usize>(cx)
6578 .into_iter()
6579 .map(|s| s.range());
6580
6581 self.transact(window, cx, |this, window, cx| {
6582 this.buffer.update(cx, |buffer, cx| {
6583 buffer.autoindent_ranges(selections, cx);
6584 });
6585 let selections = this.selections.all::<usize>(cx);
6586 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6587 s.select(selections)
6588 });
6589 });
6590 }
6591
6592 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6593 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6594 let selections = self.selections.all::<Point>(cx);
6595
6596 let mut new_cursors = Vec::new();
6597 let mut edit_ranges = Vec::new();
6598 let mut selections = selections.iter().peekable();
6599 while let Some(selection) = selections.next() {
6600 let mut rows = selection.spanned_rows(false, &display_map);
6601 let goal_display_column = selection.head().to_display_point(&display_map).column();
6602
6603 // Accumulate contiguous regions of rows that we want to delete.
6604 while let Some(next_selection) = selections.peek() {
6605 let next_rows = next_selection.spanned_rows(false, &display_map);
6606 if next_rows.start <= rows.end {
6607 rows.end = next_rows.end;
6608 selections.next().unwrap();
6609 } else {
6610 break;
6611 }
6612 }
6613
6614 let buffer = &display_map.buffer_snapshot;
6615 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6616 let edit_end;
6617 let cursor_buffer_row;
6618 if buffer.max_point().row >= rows.end.0 {
6619 // If there's a line after the range, delete the \n from the end of the row range
6620 // and position the cursor on the next line.
6621 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6622 cursor_buffer_row = rows.end;
6623 } else {
6624 // If there isn't a line after the range, delete the \n from the line before the
6625 // start of the row range and position the cursor there.
6626 edit_start = edit_start.saturating_sub(1);
6627 edit_end = buffer.len();
6628 cursor_buffer_row = rows.start.previous_row();
6629 }
6630
6631 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6632 *cursor.column_mut() =
6633 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6634
6635 new_cursors.push((
6636 selection.id,
6637 buffer.anchor_after(cursor.to_point(&display_map)),
6638 ));
6639 edit_ranges.push(edit_start..edit_end);
6640 }
6641
6642 self.transact(window, cx, |this, window, cx| {
6643 let buffer = this.buffer.update(cx, |buffer, cx| {
6644 let empty_str: Arc<str> = Arc::default();
6645 buffer.edit(
6646 edit_ranges
6647 .into_iter()
6648 .map(|range| (range, empty_str.clone())),
6649 None,
6650 cx,
6651 );
6652 buffer.snapshot(cx)
6653 });
6654 let new_selections = new_cursors
6655 .into_iter()
6656 .map(|(id, cursor)| {
6657 let cursor = cursor.to_point(&buffer);
6658 Selection {
6659 id,
6660 start: cursor,
6661 end: cursor,
6662 reversed: false,
6663 goal: SelectionGoal::None,
6664 }
6665 })
6666 .collect();
6667
6668 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6669 s.select(new_selections);
6670 });
6671 });
6672 }
6673
6674 pub fn join_lines_impl(
6675 &mut self,
6676 insert_whitespace: bool,
6677 window: &mut Window,
6678 cx: &mut Context<Self>,
6679 ) {
6680 if self.read_only(cx) {
6681 return;
6682 }
6683 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6684 for selection in self.selections.all::<Point>(cx) {
6685 let start = MultiBufferRow(selection.start.row);
6686 // Treat single line selections as if they include the next line. Otherwise this action
6687 // would do nothing for single line selections individual cursors.
6688 let end = if selection.start.row == selection.end.row {
6689 MultiBufferRow(selection.start.row + 1)
6690 } else {
6691 MultiBufferRow(selection.end.row)
6692 };
6693
6694 if let Some(last_row_range) = row_ranges.last_mut() {
6695 if start <= last_row_range.end {
6696 last_row_range.end = end;
6697 continue;
6698 }
6699 }
6700 row_ranges.push(start..end);
6701 }
6702
6703 let snapshot = self.buffer.read(cx).snapshot(cx);
6704 let mut cursor_positions = Vec::new();
6705 for row_range in &row_ranges {
6706 let anchor = snapshot.anchor_before(Point::new(
6707 row_range.end.previous_row().0,
6708 snapshot.line_len(row_range.end.previous_row()),
6709 ));
6710 cursor_positions.push(anchor..anchor);
6711 }
6712
6713 self.transact(window, cx, |this, window, cx| {
6714 for row_range in row_ranges.into_iter().rev() {
6715 for row in row_range.iter_rows().rev() {
6716 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6717 let next_line_row = row.next_row();
6718 let indent = snapshot.indent_size_for_line(next_line_row);
6719 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6720
6721 let replace =
6722 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6723 " "
6724 } else {
6725 ""
6726 };
6727
6728 this.buffer.update(cx, |buffer, cx| {
6729 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6730 });
6731 }
6732 }
6733
6734 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6735 s.select_anchor_ranges(cursor_positions)
6736 });
6737 });
6738 }
6739
6740 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6741 self.join_lines_impl(true, window, cx);
6742 }
6743
6744 pub fn sort_lines_case_sensitive(
6745 &mut self,
6746 _: &SortLinesCaseSensitive,
6747 window: &mut Window,
6748 cx: &mut Context<Self>,
6749 ) {
6750 self.manipulate_lines(window, cx, |lines| lines.sort())
6751 }
6752
6753 pub fn sort_lines_case_insensitive(
6754 &mut self,
6755 _: &SortLinesCaseInsensitive,
6756 window: &mut Window,
6757 cx: &mut Context<Self>,
6758 ) {
6759 self.manipulate_lines(window, cx, |lines| {
6760 lines.sort_by_key(|line| line.to_lowercase())
6761 })
6762 }
6763
6764 pub fn unique_lines_case_insensitive(
6765 &mut self,
6766 _: &UniqueLinesCaseInsensitive,
6767 window: &mut Window,
6768 cx: &mut Context<Self>,
6769 ) {
6770 self.manipulate_lines(window, cx, |lines| {
6771 let mut seen = HashSet::default();
6772 lines.retain(|line| seen.insert(line.to_lowercase()));
6773 })
6774 }
6775
6776 pub fn unique_lines_case_sensitive(
6777 &mut self,
6778 _: &UniqueLinesCaseSensitive,
6779 window: &mut Window,
6780 cx: &mut Context<Self>,
6781 ) {
6782 self.manipulate_lines(window, cx, |lines| {
6783 let mut seen = HashSet::default();
6784 lines.retain(|line| seen.insert(*line));
6785 })
6786 }
6787
6788 pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
6789 let mut revert_changes = HashMap::default();
6790 let snapshot = self.snapshot(window, cx);
6791 for hunk in snapshot
6792 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
6793 {
6794 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6795 }
6796 if !revert_changes.is_empty() {
6797 self.transact(window, cx, |editor, window, cx| {
6798 editor.revert(revert_changes, window, cx);
6799 });
6800 }
6801 }
6802
6803 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
6804 let Some(project) = self.project.clone() else {
6805 return;
6806 };
6807 self.reload(project, window, cx)
6808 .detach_and_notify_err(window, cx);
6809 }
6810
6811 pub fn revert_selected_hunks(
6812 &mut self,
6813 _: &RevertSelectedHunks,
6814 window: &mut Window,
6815 cx: &mut Context<Self>,
6816 ) {
6817 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
6818 self.revert_hunks_in_ranges(selections, window, cx);
6819 }
6820
6821 fn revert_hunks_in_ranges(
6822 &mut self,
6823 ranges: impl Iterator<Item = Range<Point>>,
6824 window: &mut Window,
6825 cx: &mut Context<Editor>,
6826 ) {
6827 let mut revert_changes = HashMap::default();
6828 let snapshot = self.snapshot(window, cx);
6829 for hunk in &snapshot.hunks_for_ranges(ranges) {
6830 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6831 }
6832 if !revert_changes.is_empty() {
6833 self.transact(window, cx, |editor, window, cx| {
6834 editor.revert(revert_changes, window, cx);
6835 });
6836 }
6837 }
6838
6839 pub fn open_active_item_in_terminal(
6840 &mut self,
6841 _: &OpenInTerminal,
6842 window: &mut Window,
6843 cx: &mut Context<Self>,
6844 ) {
6845 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6846 let project_path = buffer.read(cx).project_path(cx)?;
6847 let project = self.project.as_ref()?.read(cx);
6848 let entry = project.entry_for_path(&project_path, cx)?;
6849 let parent = match &entry.canonical_path {
6850 Some(canonical_path) => canonical_path.to_path_buf(),
6851 None => project.absolute_path(&project_path, cx)?,
6852 }
6853 .parent()?
6854 .to_path_buf();
6855 Some(parent)
6856 }) {
6857 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
6858 }
6859 }
6860
6861 pub fn prepare_revert_change(
6862 &self,
6863 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6864 hunk: &MultiBufferDiffHunk,
6865 cx: &mut App,
6866 ) -> Option<()> {
6867 let buffer = self.buffer.read(cx);
6868 let diff = buffer.diff_for(hunk.buffer_id)?;
6869 let buffer = buffer.buffer(hunk.buffer_id)?;
6870 let buffer = buffer.read(cx);
6871 let original_text = diff
6872 .read(cx)
6873 .snapshot
6874 .base_text
6875 .as_ref()?
6876 .as_rope()
6877 .slice(hunk.diff_base_byte_range.clone());
6878 let buffer_snapshot = buffer.snapshot();
6879 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6880 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6881 probe
6882 .0
6883 .start
6884 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6885 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6886 }) {
6887 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6888 Some(())
6889 } else {
6890 None
6891 }
6892 }
6893
6894 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
6895 self.manipulate_lines(window, cx, |lines| lines.reverse())
6896 }
6897
6898 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
6899 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
6900 }
6901
6902 fn manipulate_lines<Fn>(
6903 &mut self,
6904 window: &mut Window,
6905 cx: &mut Context<Self>,
6906 mut callback: Fn,
6907 ) where
6908 Fn: FnMut(&mut Vec<&str>),
6909 {
6910 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6911 let buffer = self.buffer.read(cx).snapshot(cx);
6912
6913 let mut edits = Vec::new();
6914
6915 let selections = self.selections.all::<Point>(cx);
6916 let mut selections = selections.iter().peekable();
6917 let mut contiguous_row_selections = Vec::new();
6918 let mut new_selections = Vec::new();
6919 let mut added_lines = 0;
6920 let mut removed_lines = 0;
6921
6922 while let Some(selection) = selections.next() {
6923 let (start_row, end_row) = consume_contiguous_rows(
6924 &mut contiguous_row_selections,
6925 selection,
6926 &display_map,
6927 &mut selections,
6928 );
6929
6930 let start_point = Point::new(start_row.0, 0);
6931 let end_point = Point::new(
6932 end_row.previous_row().0,
6933 buffer.line_len(end_row.previous_row()),
6934 );
6935 let text = buffer
6936 .text_for_range(start_point..end_point)
6937 .collect::<String>();
6938
6939 let mut lines = text.split('\n').collect_vec();
6940
6941 let lines_before = lines.len();
6942 callback(&mut lines);
6943 let lines_after = lines.len();
6944
6945 edits.push((start_point..end_point, lines.join("\n")));
6946
6947 // Selections must change based on added and removed line count
6948 let start_row =
6949 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6950 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6951 new_selections.push(Selection {
6952 id: selection.id,
6953 start: start_row,
6954 end: end_row,
6955 goal: SelectionGoal::None,
6956 reversed: selection.reversed,
6957 });
6958
6959 if lines_after > lines_before {
6960 added_lines += lines_after - lines_before;
6961 } else if lines_before > lines_after {
6962 removed_lines += lines_before - lines_after;
6963 }
6964 }
6965
6966 self.transact(window, cx, |this, window, cx| {
6967 let buffer = this.buffer.update(cx, |buffer, cx| {
6968 buffer.edit(edits, None, cx);
6969 buffer.snapshot(cx)
6970 });
6971
6972 // Recalculate offsets on newly edited buffer
6973 let new_selections = new_selections
6974 .iter()
6975 .map(|s| {
6976 let start_point = Point::new(s.start.0, 0);
6977 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6978 Selection {
6979 id: s.id,
6980 start: buffer.point_to_offset(start_point),
6981 end: buffer.point_to_offset(end_point),
6982 goal: s.goal,
6983 reversed: s.reversed,
6984 }
6985 })
6986 .collect();
6987
6988 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6989 s.select(new_selections);
6990 });
6991
6992 this.request_autoscroll(Autoscroll::fit(), cx);
6993 });
6994 }
6995
6996 pub fn convert_to_upper_case(
6997 &mut self,
6998 _: &ConvertToUpperCase,
6999 window: &mut Window,
7000 cx: &mut Context<Self>,
7001 ) {
7002 self.manipulate_text(window, cx, |text| text.to_uppercase())
7003 }
7004
7005 pub fn convert_to_lower_case(
7006 &mut self,
7007 _: &ConvertToLowerCase,
7008 window: &mut Window,
7009 cx: &mut Context<Self>,
7010 ) {
7011 self.manipulate_text(window, cx, |text| text.to_lowercase())
7012 }
7013
7014 pub fn convert_to_title_case(
7015 &mut self,
7016 _: &ConvertToTitleCase,
7017 window: &mut Window,
7018 cx: &mut Context<Self>,
7019 ) {
7020 self.manipulate_text(window, cx, |text| {
7021 text.split('\n')
7022 .map(|line| line.to_case(Case::Title))
7023 .join("\n")
7024 })
7025 }
7026
7027 pub fn convert_to_snake_case(
7028 &mut self,
7029 _: &ConvertToSnakeCase,
7030 window: &mut Window,
7031 cx: &mut Context<Self>,
7032 ) {
7033 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7034 }
7035
7036 pub fn convert_to_kebab_case(
7037 &mut self,
7038 _: &ConvertToKebabCase,
7039 window: &mut Window,
7040 cx: &mut Context<Self>,
7041 ) {
7042 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7043 }
7044
7045 pub fn convert_to_upper_camel_case(
7046 &mut self,
7047 _: &ConvertToUpperCamelCase,
7048 window: &mut Window,
7049 cx: &mut Context<Self>,
7050 ) {
7051 self.manipulate_text(window, cx, |text| {
7052 text.split('\n')
7053 .map(|line| line.to_case(Case::UpperCamel))
7054 .join("\n")
7055 })
7056 }
7057
7058 pub fn convert_to_lower_camel_case(
7059 &mut self,
7060 _: &ConvertToLowerCamelCase,
7061 window: &mut Window,
7062 cx: &mut Context<Self>,
7063 ) {
7064 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
7065 }
7066
7067 pub fn convert_to_opposite_case(
7068 &mut self,
7069 _: &ConvertToOppositeCase,
7070 window: &mut Window,
7071 cx: &mut Context<Self>,
7072 ) {
7073 self.manipulate_text(window, cx, |text| {
7074 text.chars()
7075 .fold(String::with_capacity(text.len()), |mut t, c| {
7076 if c.is_uppercase() {
7077 t.extend(c.to_lowercase());
7078 } else {
7079 t.extend(c.to_uppercase());
7080 }
7081 t
7082 })
7083 })
7084 }
7085
7086 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
7087 where
7088 Fn: FnMut(&str) -> String,
7089 {
7090 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7091 let buffer = self.buffer.read(cx).snapshot(cx);
7092
7093 let mut new_selections = Vec::new();
7094 let mut edits = Vec::new();
7095 let mut selection_adjustment = 0i32;
7096
7097 for selection in self.selections.all::<usize>(cx) {
7098 let selection_is_empty = selection.is_empty();
7099
7100 let (start, end) = if selection_is_empty {
7101 let word_range = movement::surrounding_word(
7102 &display_map,
7103 selection.start.to_display_point(&display_map),
7104 );
7105 let start = word_range.start.to_offset(&display_map, Bias::Left);
7106 let end = word_range.end.to_offset(&display_map, Bias::Left);
7107 (start, end)
7108 } else {
7109 (selection.start, selection.end)
7110 };
7111
7112 let text = buffer.text_for_range(start..end).collect::<String>();
7113 let old_length = text.len() as i32;
7114 let text = callback(&text);
7115
7116 new_selections.push(Selection {
7117 start: (start as i32 - selection_adjustment) as usize,
7118 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
7119 goal: SelectionGoal::None,
7120 ..selection
7121 });
7122
7123 selection_adjustment += old_length - text.len() as i32;
7124
7125 edits.push((start..end, text));
7126 }
7127
7128 self.transact(window, cx, |this, window, cx| {
7129 this.buffer.update(cx, |buffer, cx| {
7130 buffer.edit(edits, None, cx);
7131 });
7132
7133 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7134 s.select(new_selections);
7135 });
7136
7137 this.request_autoscroll(Autoscroll::fit(), cx);
7138 });
7139 }
7140
7141 pub fn duplicate(
7142 &mut self,
7143 upwards: bool,
7144 whole_lines: bool,
7145 window: &mut Window,
7146 cx: &mut Context<Self>,
7147 ) {
7148 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7149 let buffer = &display_map.buffer_snapshot;
7150 let selections = self.selections.all::<Point>(cx);
7151
7152 let mut edits = Vec::new();
7153 let mut selections_iter = selections.iter().peekable();
7154 while let Some(selection) = selections_iter.next() {
7155 let mut rows = selection.spanned_rows(false, &display_map);
7156 // duplicate line-wise
7157 if whole_lines || selection.start == selection.end {
7158 // Avoid duplicating the same lines twice.
7159 while let Some(next_selection) = selections_iter.peek() {
7160 let next_rows = next_selection.spanned_rows(false, &display_map);
7161 if next_rows.start < rows.end {
7162 rows.end = next_rows.end;
7163 selections_iter.next().unwrap();
7164 } else {
7165 break;
7166 }
7167 }
7168
7169 // Copy the text from the selected row region and splice it either at the start
7170 // or end of the region.
7171 let start = Point::new(rows.start.0, 0);
7172 let end = Point::new(
7173 rows.end.previous_row().0,
7174 buffer.line_len(rows.end.previous_row()),
7175 );
7176 let text = buffer
7177 .text_for_range(start..end)
7178 .chain(Some("\n"))
7179 .collect::<String>();
7180 let insert_location = if upwards {
7181 Point::new(rows.end.0, 0)
7182 } else {
7183 start
7184 };
7185 edits.push((insert_location..insert_location, text));
7186 } else {
7187 // duplicate character-wise
7188 let start = selection.start;
7189 let end = selection.end;
7190 let text = buffer.text_for_range(start..end).collect::<String>();
7191 edits.push((selection.end..selection.end, text));
7192 }
7193 }
7194
7195 self.transact(window, cx, |this, _, cx| {
7196 this.buffer.update(cx, |buffer, cx| {
7197 buffer.edit(edits, None, cx);
7198 });
7199
7200 this.request_autoscroll(Autoscroll::fit(), cx);
7201 });
7202 }
7203
7204 pub fn duplicate_line_up(
7205 &mut self,
7206 _: &DuplicateLineUp,
7207 window: &mut Window,
7208 cx: &mut Context<Self>,
7209 ) {
7210 self.duplicate(true, true, window, cx);
7211 }
7212
7213 pub fn duplicate_line_down(
7214 &mut self,
7215 _: &DuplicateLineDown,
7216 window: &mut Window,
7217 cx: &mut Context<Self>,
7218 ) {
7219 self.duplicate(false, true, window, cx);
7220 }
7221
7222 pub fn duplicate_selection(
7223 &mut self,
7224 _: &DuplicateSelection,
7225 window: &mut Window,
7226 cx: &mut Context<Self>,
7227 ) {
7228 self.duplicate(false, false, window, cx);
7229 }
7230
7231 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7232 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7233 let buffer = self.buffer.read(cx).snapshot(cx);
7234
7235 let mut edits = Vec::new();
7236 let mut unfold_ranges = Vec::new();
7237 let mut refold_creases = Vec::new();
7238
7239 let selections = self.selections.all::<Point>(cx);
7240 let mut selections = selections.iter().peekable();
7241 let mut contiguous_row_selections = Vec::new();
7242 let mut new_selections = Vec::new();
7243
7244 while let Some(selection) = selections.next() {
7245 // Find all the selections that span a contiguous row range
7246 let (start_row, end_row) = consume_contiguous_rows(
7247 &mut contiguous_row_selections,
7248 selection,
7249 &display_map,
7250 &mut selections,
7251 );
7252
7253 // Move the text spanned by the row range to be before the line preceding the row range
7254 if start_row.0 > 0 {
7255 let range_to_move = Point::new(
7256 start_row.previous_row().0,
7257 buffer.line_len(start_row.previous_row()),
7258 )
7259 ..Point::new(
7260 end_row.previous_row().0,
7261 buffer.line_len(end_row.previous_row()),
7262 );
7263 let insertion_point = display_map
7264 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7265 .0;
7266
7267 // Don't move lines across excerpts
7268 if buffer
7269 .excerpt_containing(insertion_point..range_to_move.end)
7270 .is_some()
7271 {
7272 let text = buffer
7273 .text_for_range(range_to_move.clone())
7274 .flat_map(|s| s.chars())
7275 .skip(1)
7276 .chain(['\n'])
7277 .collect::<String>();
7278
7279 edits.push((
7280 buffer.anchor_after(range_to_move.start)
7281 ..buffer.anchor_before(range_to_move.end),
7282 String::new(),
7283 ));
7284 let insertion_anchor = buffer.anchor_after(insertion_point);
7285 edits.push((insertion_anchor..insertion_anchor, text));
7286
7287 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7288
7289 // Move selections up
7290 new_selections.extend(contiguous_row_selections.drain(..).map(
7291 |mut selection| {
7292 selection.start.row -= row_delta;
7293 selection.end.row -= row_delta;
7294 selection
7295 },
7296 ));
7297
7298 // Move folds up
7299 unfold_ranges.push(range_to_move.clone());
7300 for fold in display_map.folds_in_range(
7301 buffer.anchor_before(range_to_move.start)
7302 ..buffer.anchor_after(range_to_move.end),
7303 ) {
7304 let mut start = fold.range.start.to_point(&buffer);
7305 let mut end = fold.range.end.to_point(&buffer);
7306 start.row -= row_delta;
7307 end.row -= row_delta;
7308 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7309 }
7310 }
7311 }
7312
7313 // If we didn't move line(s), preserve the existing selections
7314 new_selections.append(&mut contiguous_row_selections);
7315 }
7316
7317 self.transact(window, cx, |this, window, cx| {
7318 this.unfold_ranges(&unfold_ranges, true, true, cx);
7319 this.buffer.update(cx, |buffer, cx| {
7320 for (range, text) in edits {
7321 buffer.edit([(range, text)], None, cx);
7322 }
7323 });
7324 this.fold_creases(refold_creases, true, window, cx);
7325 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7326 s.select(new_selections);
7327 })
7328 });
7329 }
7330
7331 pub fn move_line_down(
7332 &mut self,
7333 _: &MoveLineDown,
7334 window: &mut Window,
7335 cx: &mut Context<Self>,
7336 ) {
7337 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7338 let buffer = self.buffer.read(cx).snapshot(cx);
7339
7340 let mut edits = Vec::new();
7341 let mut unfold_ranges = Vec::new();
7342 let mut refold_creases = Vec::new();
7343
7344 let selections = self.selections.all::<Point>(cx);
7345 let mut selections = selections.iter().peekable();
7346 let mut contiguous_row_selections = Vec::new();
7347 let mut new_selections = Vec::new();
7348
7349 while let Some(selection) = selections.next() {
7350 // Find all the selections that span a contiguous row range
7351 let (start_row, end_row) = consume_contiguous_rows(
7352 &mut contiguous_row_selections,
7353 selection,
7354 &display_map,
7355 &mut selections,
7356 );
7357
7358 // Move the text spanned by the row range to be after the last line of the row range
7359 if end_row.0 <= buffer.max_point().row {
7360 let range_to_move =
7361 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7362 let insertion_point = display_map
7363 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7364 .0;
7365
7366 // Don't move lines across excerpt boundaries
7367 if buffer
7368 .excerpt_containing(range_to_move.start..insertion_point)
7369 .is_some()
7370 {
7371 let mut text = String::from("\n");
7372 text.extend(buffer.text_for_range(range_to_move.clone()));
7373 text.pop(); // Drop trailing newline
7374 edits.push((
7375 buffer.anchor_after(range_to_move.start)
7376 ..buffer.anchor_before(range_to_move.end),
7377 String::new(),
7378 ));
7379 let insertion_anchor = buffer.anchor_after(insertion_point);
7380 edits.push((insertion_anchor..insertion_anchor, text));
7381
7382 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7383
7384 // Move selections down
7385 new_selections.extend(contiguous_row_selections.drain(..).map(
7386 |mut selection| {
7387 selection.start.row += row_delta;
7388 selection.end.row += row_delta;
7389 selection
7390 },
7391 ));
7392
7393 // Move folds down
7394 unfold_ranges.push(range_to_move.clone());
7395 for fold in display_map.folds_in_range(
7396 buffer.anchor_before(range_to_move.start)
7397 ..buffer.anchor_after(range_to_move.end),
7398 ) {
7399 let mut start = fold.range.start.to_point(&buffer);
7400 let mut end = fold.range.end.to_point(&buffer);
7401 start.row += row_delta;
7402 end.row += row_delta;
7403 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7404 }
7405 }
7406 }
7407
7408 // If we didn't move line(s), preserve the existing selections
7409 new_selections.append(&mut contiguous_row_selections);
7410 }
7411
7412 self.transact(window, cx, |this, window, cx| {
7413 this.unfold_ranges(&unfold_ranges, true, true, cx);
7414 this.buffer.update(cx, |buffer, cx| {
7415 for (range, text) in edits {
7416 buffer.edit([(range, text)], None, cx);
7417 }
7418 });
7419 this.fold_creases(refold_creases, true, window, cx);
7420 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7421 s.select(new_selections)
7422 });
7423 });
7424 }
7425
7426 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7427 let text_layout_details = &self.text_layout_details(window);
7428 self.transact(window, cx, |this, window, cx| {
7429 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7430 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7431 let line_mode = s.line_mode;
7432 s.move_with(|display_map, selection| {
7433 if !selection.is_empty() || line_mode {
7434 return;
7435 }
7436
7437 let mut head = selection.head();
7438 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7439 if head.column() == display_map.line_len(head.row()) {
7440 transpose_offset = display_map
7441 .buffer_snapshot
7442 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7443 }
7444
7445 if transpose_offset == 0 {
7446 return;
7447 }
7448
7449 *head.column_mut() += 1;
7450 head = display_map.clip_point(head, Bias::Right);
7451 let goal = SelectionGoal::HorizontalPosition(
7452 display_map
7453 .x_for_display_point(head, text_layout_details)
7454 .into(),
7455 );
7456 selection.collapse_to(head, goal);
7457
7458 let transpose_start = display_map
7459 .buffer_snapshot
7460 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7461 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7462 let transpose_end = display_map
7463 .buffer_snapshot
7464 .clip_offset(transpose_offset + 1, Bias::Right);
7465 if let Some(ch) =
7466 display_map.buffer_snapshot.chars_at(transpose_start).next()
7467 {
7468 edits.push((transpose_start..transpose_offset, String::new()));
7469 edits.push((transpose_end..transpose_end, ch.to_string()));
7470 }
7471 }
7472 });
7473 edits
7474 });
7475 this.buffer
7476 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7477 let selections = this.selections.all::<usize>(cx);
7478 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7479 s.select(selections);
7480 });
7481 });
7482 }
7483
7484 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7485 self.rewrap_impl(IsVimMode::No, cx)
7486 }
7487
7488 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7489 let buffer = self.buffer.read(cx).snapshot(cx);
7490 let selections = self.selections.all::<Point>(cx);
7491 let mut selections = selections.iter().peekable();
7492
7493 let mut edits = Vec::new();
7494 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7495
7496 while let Some(selection) = selections.next() {
7497 let mut start_row = selection.start.row;
7498 let mut end_row = selection.end.row;
7499
7500 // Skip selections that overlap with a range that has already been rewrapped.
7501 let selection_range = start_row..end_row;
7502 if rewrapped_row_ranges
7503 .iter()
7504 .any(|range| range.overlaps(&selection_range))
7505 {
7506 continue;
7507 }
7508
7509 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7510
7511 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7512 match language_scope.language_name().as_ref() {
7513 "Markdown" | "Plain Text" => {
7514 should_rewrap = true;
7515 }
7516 _ => {}
7517 }
7518 }
7519
7520 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7521
7522 // Since not all lines in the selection may be at the same indent
7523 // level, choose the indent size that is the most common between all
7524 // of the lines.
7525 //
7526 // If there is a tie, we use the deepest indent.
7527 let (indent_size, indent_end) = {
7528 let mut indent_size_occurrences = HashMap::default();
7529 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7530
7531 for row in start_row..=end_row {
7532 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7533 rows_by_indent_size.entry(indent).or_default().push(row);
7534 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7535 }
7536
7537 let indent_size = indent_size_occurrences
7538 .into_iter()
7539 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7540 .map(|(indent, _)| indent)
7541 .unwrap_or_default();
7542 let row = rows_by_indent_size[&indent_size][0];
7543 let indent_end = Point::new(row, indent_size.len);
7544
7545 (indent_size, indent_end)
7546 };
7547
7548 let mut line_prefix = indent_size.chars().collect::<String>();
7549
7550 if let Some(comment_prefix) =
7551 buffer
7552 .language_scope_at(selection.head())
7553 .and_then(|language| {
7554 language
7555 .line_comment_prefixes()
7556 .iter()
7557 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7558 .cloned()
7559 })
7560 {
7561 line_prefix.push_str(&comment_prefix);
7562 should_rewrap = true;
7563 }
7564
7565 if !should_rewrap {
7566 continue;
7567 }
7568
7569 if selection.is_empty() {
7570 'expand_upwards: while start_row > 0 {
7571 let prev_row = start_row - 1;
7572 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7573 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7574 {
7575 start_row = prev_row;
7576 } else {
7577 break 'expand_upwards;
7578 }
7579 }
7580
7581 'expand_downwards: while end_row < buffer.max_point().row {
7582 let next_row = end_row + 1;
7583 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7584 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7585 {
7586 end_row = next_row;
7587 } else {
7588 break 'expand_downwards;
7589 }
7590 }
7591 }
7592
7593 let start = Point::new(start_row, 0);
7594 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7595 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7596 let Some(lines_without_prefixes) = selection_text
7597 .lines()
7598 .map(|line| {
7599 line.strip_prefix(&line_prefix)
7600 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7601 .ok_or_else(|| {
7602 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7603 })
7604 })
7605 .collect::<Result<Vec<_>, _>>()
7606 .log_err()
7607 else {
7608 continue;
7609 };
7610
7611 let wrap_column = buffer
7612 .settings_at(Point::new(start_row, 0), cx)
7613 .preferred_line_length as usize;
7614 let wrapped_text = wrap_with_prefix(
7615 line_prefix,
7616 lines_without_prefixes.join(" "),
7617 wrap_column,
7618 tab_size,
7619 );
7620
7621 // TODO: should always use char-based diff while still supporting cursor behavior that
7622 // matches vim.
7623 let diff = match is_vim_mode {
7624 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7625 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7626 };
7627 let mut offset = start.to_offset(&buffer);
7628 let mut moved_since_edit = true;
7629
7630 for change in diff.iter_all_changes() {
7631 let value = change.value();
7632 match change.tag() {
7633 ChangeTag::Equal => {
7634 offset += value.len();
7635 moved_since_edit = true;
7636 }
7637 ChangeTag::Delete => {
7638 let start = buffer.anchor_after(offset);
7639 let end = buffer.anchor_before(offset + value.len());
7640
7641 if moved_since_edit {
7642 edits.push((start..end, String::new()));
7643 } else {
7644 edits.last_mut().unwrap().0.end = end;
7645 }
7646
7647 offset += value.len();
7648 moved_since_edit = false;
7649 }
7650 ChangeTag::Insert => {
7651 if moved_since_edit {
7652 let anchor = buffer.anchor_after(offset);
7653 edits.push((anchor..anchor, value.to_string()));
7654 } else {
7655 edits.last_mut().unwrap().1.push_str(value);
7656 }
7657
7658 moved_since_edit = false;
7659 }
7660 }
7661 }
7662
7663 rewrapped_row_ranges.push(start_row..=end_row);
7664 }
7665
7666 self.buffer
7667 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7668 }
7669
7670 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7671 let mut text = String::new();
7672 let buffer = self.buffer.read(cx).snapshot(cx);
7673 let mut selections = self.selections.all::<Point>(cx);
7674 let mut clipboard_selections = Vec::with_capacity(selections.len());
7675 {
7676 let max_point = buffer.max_point();
7677 let mut is_first = true;
7678 for selection in &mut selections {
7679 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7680 if is_entire_line {
7681 selection.start = Point::new(selection.start.row, 0);
7682 if !selection.is_empty() && selection.end.column == 0 {
7683 selection.end = cmp::min(max_point, selection.end);
7684 } else {
7685 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7686 }
7687 selection.goal = SelectionGoal::None;
7688 }
7689 if is_first {
7690 is_first = false;
7691 } else {
7692 text += "\n";
7693 }
7694 let mut len = 0;
7695 for chunk in buffer.text_for_range(selection.start..selection.end) {
7696 text.push_str(chunk);
7697 len += chunk.len();
7698 }
7699 clipboard_selections.push(ClipboardSelection {
7700 len,
7701 is_entire_line,
7702 first_line_indent: buffer
7703 .indent_size_for_line(MultiBufferRow(selection.start.row))
7704 .len,
7705 });
7706 }
7707 }
7708
7709 self.transact(window, cx, |this, window, cx| {
7710 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7711 s.select(selections);
7712 });
7713 this.insert("", window, cx);
7714 });
7715 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7716 }
7717
7718 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
7719 let item = self.cut_common(window, cx);
7720 cx.write_to_clipboard(item);
7721 }
7722
7723 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
7724 self.change_selections(None, window, cx, |s| {
7725 s.move_with(|snapshot, sel| {
7726 if sel.is_empty() {
7727 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7728 }
7729 });
7730 });
7731 let item = self.cut_common(window, cx);
7732 cx.set_global(KillRing(item))
7733 }
7734
7735 pub fn kill_ring_yank(
7736 &mut self,
7737 _: &KillRingYank,
7738 window: &mut Window,
7739 cx: &mut Context<Self>,
7740 ) {
7741 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7742 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7743 (kill_ring.text().to_string(), kill_ring.metadata_json())
7744 } else {
7745 return;
7746 }
7747 } else {
7748 return;
7749 };
7750 self.do_paste(&text, metadata, false, window, cx);
7751 }
7752
7753 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
7754 let selections = self.selections.all::<Point>(cx);
7755 let buffer = self.buffer.read(cx).read(cx);
7756 let mut text = String::new();
7757
7758 let mut clipboard_selections = Vec::with_capacity(selections.len());
7759 {
7760 let max_point = buffer.max_point();
7761 let mut is_first = true;
7762 for selection in selections.iter() {
7763 let mut start = selection.start;
7764 let mut end = selection.end;
7765 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7766 if is_entire_line {
7767 start = Point::new(start.row, 0);
7768 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7769 }
7770 if is_first {
7771 is_first = false;
7772 } else {
7773 text += "\n";
7774 }
7775 let mut len = 0;
7776 for chunk in buffer.text_for_range(start..end) {
7777 text.push_str(chunk);
7778 len += chunk.len();
7779 }
7780 clipboard_selections.push(ClipboardSelection {
7781 len,
7782 is_entire_line,
7783 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7784 });
7785 }
7786 }
7787
7788 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7789 text,
7790 clipboard_selections,
7791 ));
7792 }
7793
7794 pub fn do_paste(
7795 &mut self,
7796 text: &String,
7797 clipboard_selections: Option<Vec<ClipboardSelection>>,
7798 handle_entire_lines: bool,
7799 window: &mut Window,
7800 cx: &mut Context<Self>,
7801 ) {
7802 if self.read_only(cx) {
7803 return;
7804 }
7805
7806 let clipboard_text = Cow::Borrowed(text);
7807
7808 self.transact(window, cx, |this, window, cx| {
7809 if let Some(mut clipboard_selections) = clipboard_selections {
7810 let old_selections = this.selections.all::<usize>(cx);
7811 let all_selections_were_entire_line =
7812 clipboard_selections.iter().all(|s| s.is_entire_line);
7813 let first_selection_indent_column =
7814 clipboard_selections.first().map(|s| s.first_line_indent);
7815 if clipboard_selections.len() != old_selections.len() {
7816 clipboard_selections.drain(..);
7817 }
7818 let cursor_offset = this.selections.last::<usize>(cx).head();
7819 let mut auto_indent_on_paste = true;
7820
7821 this.buffer.update(cx, |buffer, cx| {
7822 let snapshot = buffer.read(cx);
7823 auto_indent_on_paste =
7824 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7825
7826 let mut start_offset = 0;
7827 let mut edits = Vec::new();
7828 let mut original_indent_columns = Vec::new();
7829 for (ix, selection) in old_selections.iter().enumerate() {
7830 let to_insert;
7831 let entire_line;
7832 let original_indent_column;
7833 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7834 let end_offset = start_offset + clipboard_selection.len;
7835 to_insert = &clipboard_text[start_offset..end_offset];
7836 entire_line = clipboard_selection.is_entire_line;
7837 start_offset = end_offset + 1;
7838 original_indent_column = Some(clipboard_selection.first_line_indent);
7839 } else {
7840 to_insert = clipboard_text.as_str();
7841 entire_line = all_selections_were_entire_line;
7842 original_indent_column = first_selection_indent_column
7843 }
7844
7845 // If the corresponding selection was empty when this slice of the
7846 // clipboard text was written, then the entire line containing the
7847 // selection was copied. If this selection is also currently empty,
7848 // then paste the line before the current line of the buffer.
7849 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7850 let column = selection.start.to_point(&snapshot).column as usize;
7851 let line_start = selection.start - column;
7852 line_start..line_start
7853 } else {
7854 selection.range()
7855 };
7856
7857 edits.push((range, to_insert));
7858 original_indent_columns.extend(original_indent_column);
7859 }
7860 drop(snapshot);
7861
7862 buffer.edit(
7863 edits,
7864 if auto_indent_on_paste {
7865 Some(AutoindentMode::Block {
7866 original_indent_columns,
7867 })
7868 } else {
7869 None
7870 },
7871 cx,
7872 );
7873 });
7874
7875 let selections = this.selections.all::<usize>(cx);
7876 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7877 s.select(selections)
7878 });
7879 } else {
7880 this.insert(&clipboard_text, window, cx);
7881 }
7882 });
7883 }
7884
7885 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
7886 if let Some(item) = cx.read_from_clipboard() {
7887 let entries = item.entries();
7888
7889 match entries.first() {
7890 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7891 // of all the pasted entries.
7892 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7893 .do_paste(
7894 clipboard_string.text(),
7895 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7896 true,
7897 window,
7898 cx,
7899 ),
7900 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
7901 }
7902 }
7903 }
7904
7905 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
7906 if self.read_only(cx) {
7907 return;
7908 }
7909
7910 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7911 if let Some((selections, _)) =
7912 self.selection_history.transaction(transaction_id).cloned()
7913 {
7914 self.change_selections(None, window, cx, |s| {
7915 s.select_anchors(selections.to_vec());
7916 });
7917 }
7918 self.request_autoscroll(Autoscroll::fit(), cx);
7919 self.unmark_text(window, cx);
7920 self.refresh_inline_completion(true, false, window, cx);
7921 cx.emit(EditorEvent::Edited { transaction_id });
7922 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7923 }
7924 }
7925
7926 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
7927 if self.read_only(cx) {
7928 return;
7929 }
7930
7931 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7932 if let Some((_, Some(selections))) =
7933 self.selection_history.transaction(transaction_id).cloned()
7934 {
7935 self.change_selections(None, window, cx, |s| {
7936 s.select_anchors(selections.to_vec());
7937 });
7938 }
7939 self.request_autoscroll(Autoscroll::fit(), cx);
7940 self.unmark_text(window, cx);
7941 self.refresh_inline_completion(true, false, window, cx);
7942 cx.emit(EditorEvent::Edited { transaction_id });
7943 }
7944 }
7945
7946 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
7947 self.buffer
7948 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7949 }
7950
7951 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
7952 self.buffer
7953 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7954 }
7955
7956 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
7957 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7958 let line_mode = s.line_mode;
7959 s.move_with(|map, selection| {
7960 let cursor = if selection.is_empty() && !line_mode {
7961 movement::left(map, selection.start)
7962 } else {
7963 selection.start
7964 };
7965 selection.collapse_to(cursor, SelectionGoal::None);
7966 });
7967 })
7968 }
7969
7970 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
7971 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7972 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7973 })
7974 }
7975
7976 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
7977 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7978 let line_mode = s.line_mode;
7979 s.move_with(|map, selection| {
7980 let cursor = if selection.is_empty() && !line_mode {
7981 movement::right(map, selection.end)
7982 } else {
7983 selection.end
7984 };
7985 selection.collapse_to(cursor, SelectionGoal::None)
7986 });
7987 })
7988 }
7989
7990 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
7991 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7992 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7993 })
7994 }
7995
7996 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
7997 if self.take_rename(true, window, cx).is_some() {
7998 return;
7999 }
8000
8001 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8002 cx.propagate();
8003 return;
8004 }
8005
8006 let text_layout_details = &self.text_layout_details(window);
8007 let selection_count = self.selections.count();
8008 let first_selection = self.selections.first_anchor();
8009
8010 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8011 let line_mode = s.line_mode;
8012 s.move_with(|map, selection| {
8013 if !selection.is_empty() && !line_mode {
8014 selection.goal = SelectionGoal::None;
8015 }
8016 let (cursor, goal) = movement::up(
8017 map,
8018 selection.start,
8019 selection.goal,
8020 false,
8021 text_layout_details,
8022 );
8023 selection.collapse_to(cursor, goal);
8024 });
8025 });
8026
8027 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8028 {
8029 cx.propagate();
8030 }
8031 }
8032
8033 pub fn move_up_by_lines(
8034 &mut self,
8035 action: &MoveUpByLines,
8036 window: &mut Window,
8037 cx: &mut Context<Self>,
8038 ) {
8039 if self.take_rename(true, window, cx).is_some() {
8040 return;
8041 }
8042
8043 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8044 cx.propagate();
8045 return;
8046 }
8047
8048 let text_layout_details = &self.text_layout_details(window);
8049
8050 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8051 let line_mode = s.line_mode;
8052 s.move_with(|map, selection| {
8053 if !selection.is_empty() && !line_mode {
8054 selection.goal = SelectionGoal::None;
8055 }
8056 let (cursor, goal) = movement::up_by_rows(
8057 map,
8058 selection.start,
8059 action.lines,
8060 selection.goal,
8061 false,
8062 text_layout_details,
8063 );
8064 selection.collapse_to(cursor, goal);
8065 });
8066 })
8067 }
8068
8069 pub fn move_down_by_lines(
8070 &mut self,
8071 action: &MoveDownByLines,
8072 window: &mut Window,
8073 cx: &mut Context<Self>,
8074 ) {
8075 if self.take_rename(true, window, cx).is_some() {
8076 return;
8077 }
8078
8079 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8080 cx.propagate();
8081 return;
8082 }
8083
8084 let text_layout_details = &self.text_layout_details(window);
8085
8086 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8087 let line_mode = s.line_mode;
8088 s.move_with(|map, selection| {
8089 if !selection.is_empty() && !line_mode {
8090 selection.goal = SelectionGoal::None;
8091 }
8092 let (cursor, goal) = movement::down_by_rows(
8093 map,
8094 selection.start,
8095 action.lines,
8096 selection.goal,
8097 false,
8098 text_layout_details,
8099 );
8100 selection.collapse_to(cursor, goal);
8101 });
8102 })
8103 }
8104
8105 pub fn select_down_by_lines(
8106 &mut self,
8107 action: &SelectDownByLines,
8108 window: &mut Window,
8109 cx: &mut Context<Self>,
8110 ) {
8111 let text_layout_details = &self.text_layout_details(window);
8112 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8113 s.move_heads_with(|map, head, goal| {
8114 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
8115 })
8116 })
8117 }
8118
8119 pub fn select_up_by_lines(
8120 &mut self,
8121 action: &SelectUpByLines,
8122 window: &mut Window,
8123 cx: &mut Context<Self>,
8124 ) {
8125 let text_layout_details = &self.text_layout_details(window);
8126 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8127 s.move_heads_with(|map, head, goal| {
8128 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8129 })
8130 })
8131 }
8132
8133 pub fn select_page_up(
8134 &mut self,
8135 _: &SelectPageUp,
8136 window: &mut Window,
8137 cx: &mut Context<Self>,
8138 ) {
8139 let Some(row_count) = self.visible_row_count() else {
8140 return;
8141 };
8142
8143 let text_layout_details = &self.text_layout_details(window);
8144
8145 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8146 s.move_heads_with(|map, head, goal| {
8147 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8148 })
8149 })
8150 }
8151
8152 pub fn move_page_up(
8153 &mut self,
8154 action: &MovePageUp,
8155 window: &mut Window,
8156 cx: &mut Context<Self>,
8157 ) {
8158 if self.take_rename(true, window, cx).is_some() {
8159 return;
8160 }
8161
8162 if self
8163 .context_menu
8164 .borrow_mut()
8165 .as_mut()
8166 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8167 .unwrap_or(false)
8168 {
8169 return;
8170 }
8171
8172 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8173 cx.propagate();
8174 return;
8175 }
8176
8177 let Some(row_count) = self.visible_row_count() else {
8178 return;
8179 };
8180
8181 let autoscroll = if action.center_cursor {
8182 Autoscroll::center()
8183 } else {
8184 Autoscroll::fit()
8185 };
8186
8187 let text_layout_details = &self.text_layout_details(window);
8188
8189 self.change_selections(Some(autoscroll), window, cx, |s| {
8190 let line_mode = s.line_mode;
8191 s.move_with(|map, selection| {
8192 if !selection.is_empty() && !line_mode {
8193 selection.goal = SelectionGoal::None;
8194 }
8195 let (cursor, goal) = movement::up_by_rows(
8196 map,
8197 selection.end,
8198 row_count,
8199 selection.goal,
8200 false,
8201 text_layout_details,
8202 );
8203 selection.collapse_to(cursor, goal);
8204 });
8205 });
8206 }
8207
8208 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8209 let text_layout_details = &self.text_layout_details(window);
8210 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8211 s.move_heads_with(|map, head, goal| {
8212 movement::up(map, head, goal, false, text_layout_details)
8213 })
8214 })
8215 }
8216
8217 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8218 self.take_rename(true, window, cx);
8219
8220 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8221 cx.propagate();
8222 return;
8223 }
8224
8225 let text_layout_details = &self.text_layout_details(window);
8226 let selection_count = self.selections.count();
8227 let first_selection = self.selections.first_anchor();
8228
8229 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8230 let line_mode = s.line_mode;
8231 s.move_with(|map, selection| {
8232 if !selection.is_empty() && !line_mode {
8233 selection.goal = SelectionGoal::None;
8234 }
8235 let (cursor, goal) = movement::down(
8236 map,
8237 selection.end,
8238 selection.goal,
8239 false,
8240 text_layout_details,
8241 );
8242 selection.collapse_to(cursor, goal);
8243 });
8244 });
8245
8246 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8247 {
8248 cx.propagate();
8249 }
8250 }
8251
8252 pub fn select_page_down(
8253 &mut self,
8254 _: &SelectPageDown,
8255 window: &mut Window,
8256 cx: &mut Context<Self>,
8257 ) {
8258 let Some(row_count) = self.visible_row_count() else {
8259 return;
8260 };
8261
8262 let text_layout_details = &self.text_layout_details(window);
8263
8264 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8265 s.move_heads_with(|map, head, goal| {
8266 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8267 })
8268 })
8269 }
8270
8271 pub fn move_page_down(
8272 &mut self,
8273 action: &MovePageDown,
8274 window: &mut Window,
8275 cx: &mut Context<Self>,
8276 ) {
8277 if self.take_rename(true, window, cx).is_some() {
8278 return;
8279 }
8280
8281 if self
8282 .context_menu
8283 .borrow_mut()
8284 .as_mut()
8285 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8286 .unwrap_or(false)
8287 {
8288 return;
8289 }
8290
8291 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8292 cx.propagate();
8293 return;
8294 }
8295
8296 let Some(row_count) = self.visible_row_count() else {
8297 return;
8298 };
8299
8300 let autoscroll = if action.center_cursor {
8301 Autoscroll::center()
8302 } else {
8303 Autoscroll::fit()
8304 };
8305
8306 let text_layout_details = &self.text_layout_details(window);
8307 self.change_selections(Some(autoscroll), window, cx, |s| {
8308 let line_mode = s.line_mode;
8309 s.move_with(|map, selection| {
8310 if !selection.is_empty() && !line_mode {
8311 selection.goal = SelectionGoal::None;
8312 }
8313 let (cursor, goal) = movement::down_by_rows(
8314 map,
8315 selection.end,
8316 row_count,
8317 selection.goal,
8318 false,
8319 text_layout_details,
8320 );
8321 selection.collapse_to(cursor, goal);
8322 });
8323 });
8324 }
8325
8326 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8327 let text_layout_details = &self.text_layout_details(window);
8328 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8329 s.move_heads_with(|map, head, goal| {
8330 movement::down(map, head, goal, false, text_layout_details)
8331 })
8332 });
8333 }
8334
8335 pub fn context_menu_first(
8336 &mut self,
8337 _: &ContextMenuFirst,
8338 _window: &mut Window,
8339 cx: &mut Context<Self>,
8340 ) {
8341 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8342 context_menu.select_first(self.completion_provider.as_deref(), cx);
8343 }
8344 }
8345
8346 pub fn context_menu_prev(
8347 &mut self,
8348 _: &ContextMenuPrev,
8349 _window: &mut Window,
8350 cx: &mut Context<Self>,
8351 ) {
8352 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8353 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8354 }
8355 }
8356
8357 pub fn context_menu_next(
8358 &mut self,
8359 _: &ContextMenuNext,
8360 _window: &mut Window,
8361 cx: &mut Context<Self>,
8362 ) {
8363 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8364 context_menu.select_next(self.completion_provider.as_deref(), cx);
8365 }
8366 }
8367
8368 pub fn context_menu_last(
8369 &mut self,
8370 _: &ContextMenuLast,
8371 _window: &mut Window,
8372 cx: &mut Context<Self>,
8373 ) {
8374 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8375 context_menu.select_last(self.completion_provider.as_deref(), cx);
8376 }
8377 }
8378
8379 pub fn move_to_previous_word_start(
8380 &mut self,
8381 _: &MoveToPreviousWordStart,
8382 window: &mut Window,
8383 cx: &mut Context<Self>,
8384 ) {
8385 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8386 s.move_cursors_with(|map, head, _| {
8387 (
8388 movement::previous_word_start(map, head),
8389 SelectionGoal::None,
8390 )
8391 });
8392 })
8393 }
8394
8395 pub fn move_to_previous_subword_start(
8396 &mut self,
8397 _: &MoveToPreviousSubwordStart,
8398 window: &mut Window,
8399 cx: &mut Context<Self>,
8400 ) {
8401 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8402 s.move_cursors_with(|map, head, _| {
8403 (
8404 movement::previous_subword_start(map, head),
8405 SelectionGoal::None,
8406 )
8407 });
8408 })
8409 }
8410
8411 pub fn select_to_previous_word_start(
8412 &mut self,
8413 _: &SelectToPreviousWordStart,
8414 window: &mut Window,
8415 cx: &mut Context<Self>,
8416 ) {
8417 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8418 s.move_heads_with(|map, head, _| {
8419 (
8420 movement::previous_word_start(map, head),
8421 SelectionGoal::None,
8422 )
8423 });
8424 })
8425 }
8426
8427 pub fn select_to_previous_subword_start(
8428 &mut self,
8429 _: &SelectToPreviousSubwordStart,
8430 window: &mut Window,
8431 cx: &mut Context<Self>,
8432 ) {
8433 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8434 s.move_heads_with(|map, head, _| {
8435 (
8436 movement::previous_subword_start(map, head),
8437 SelectionGoal::None,
8438 )
8439 });
8440 })
8441 }
8442
8443 pub fn delete_to_previous_word_start(
8444 &mut self,
8445 action: &DeleteToPreviousWordStart,
8446 window: &mut Window,
8447 cx: &mut Context<Self>,
8448 ) {
8449 self.transact(window, cx, |this, window, cx| {
8450 this.select_autoclose_pair(window, cx);
8451 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8452 let line_mode = s.line_mode;
8453 s.move_with(|map, selection| {
8454 if selection.is_empty() && !line_mode {
8455 let cursor = if action.ignore_newlines {
8456 movement::previous_word_start(map, selection.head())
8457 } else {
8458 movement::previous_word_start_or_newline(map, selection.head())
8459 };
8460 selection.set_head(cursor, SelectionGoal::None);
8461 }
8462 });
8463 });
8464 this.insert("", window, cx);
8465 });
8466 }
8467
8468 pub fn delete_to_previous_subword_start(
8469 &mut self,
8470 _: &DeleteToPreviousSubwordStart,
8471 window: &mut Window,
8472 cx: &mut Context<Self>,
8473 ) {
8474 self.transact(window, cx, |this, window, cx| {
8475 this.select_autoclose_pair(window, cx);
8476 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8477 let line_mode = s.line_mode;
8478 s.move_with(|map, selection| {
8479 if selection.is_empty() && !line_mode {
8480 let cursor = movement::previous_subword_start(map, selection.head());
8481 selection.set_head(cursor, SelectionGoal::None);
8482 }
8483 });
8484 });
8485 this.insert("", window, cx);
8486 });
8487 }
8488
8489 pub fn move_to_next_word_end(
8490 &mut self,
8491 _: &MoveToNextWordEnd,
8492 window: &mut Window,
8493 cx: &mut Context<Self>,
8494 ) {
8495 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8496 s.move_cursors_with(|map, head, _| {
8497 (movement::next_word_end(map, head), SelectionGoal::None)
8498 });
8499 })
8500 }
8501
8502 pub fn move_to_next_subword_end(
8503 &mut self,
8504 _: &MoveToNextSubwordEnd,
8505 window: &mut Window,
8506 cx: &mut Context<Self>,
8507 ) {
8508 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8509 s.move_cursors_with(|map, head, _| {
8510 (movement::next_subword_end(map, head), SelectionGoal::None)
8511 });
8512 })
8513 }
8514
8515 pub fn select_to_next_word_end(
8516 &mut self,
8517 _: &SelectToNextWordEnd,
8518 window: &mut Window,
8519 cx: &mut Context<Self>,
8520 ) {
8521 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8522 s.move_heads_with(|map, head, _| {
8523 (movement::next_word_end(map, head), SelectionGoal::None)
8524 });
8525 })
8526 }
8527
8528 pub fn select_to_next_subword_end(
8529 &mut self,
8530 _: &SelectToNextSubwordEnd,
8531 window: &mut Window,
8532 cx: &mut Context<Self>,
8533 ) {
8534 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8535 s.move_heads_with(|map, head, _| {
8536 (movement::next_subword_end(map, head), SelectionGoal::None)
8537 });
8538 })
8539 }
8540
8541 pub fn delete_to_next_word_end(
8542 &mut self,
8543 action: &DeleteToNextWordEnd,
8544 window: &mut Window,
8545 cx: &mut Context<Self>,
8546 ) {
8547 self.transact(window, cx, |this, window, cx| {
8548 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8549 let line_mode = s.line_mode;
8550 s.move_with(|map, selection| {
8551 if selection.is_empty() && !line_mode {
8552 let cursor = if action.ignore_newlines {
8553 movement::next_word_end(map, selection.head())
8554 } else {
8555 movement::next_word_end_or_newline(map, selection.head())
8556 };
8557 selection.set_head(cursor, SelectionGoal::None);
8558 }
8559 });
8560 });
8561 this.insert("", window, cx);
8562 });
8563 }
8564
8565 pub fn delete_to_next_subword_end(
8566 &mut self,
8567 _: &DeleteToNextSubwordEnd,
8568 window: &mut Window,
8569 cx: &mut Context<Self>,
8570 ) {
8571 self.transact(window, cx, |this, window, cx| {
8572 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8573 s.move_with(|map, selection| {
8574 if selection.is_empty() {
8575 let cursor = movement::next_subword_end(map, selection.head());
8576 selection.set_head(cursor, SelectionGoal::None);
8577 }
8578 });
8579 });
8580 this.insert("", window, cx);
8581 });
8582 }
8583
8584 pub fn move_to_beginning_of_line(
8585 &mut self,
8586 action: &MoveToBeginningOfLine,
8587 window: &mut Window,
8588 cx: &mut Context<Self>,
8589 ) {
8590 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8591 s.move_cursors_with(|map, head, _| {
8592 (
8593 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8594 SelectionGoal::None,
8595 )
8596 });
8597 })
8598 }
8599
8600 pub fn select_to_beginning_of_line(
8601 &mut self,
8602 action: &SelectToBeginningOfLine,
8603 window: &mut Window,
8604 cx: &mut Context<Self>,
8605 ) {
8606 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8607 s.move_heads_with(|map, head, _| {
8608 (
8609 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8610 SelectionGoal::None,
8611 )
8612 });
8613 });
8614 }
8615
8616 pub fn delete_to_beginning_of_line(
8617 &mut self,
8618 _: &DeleteToBeginningOfLine,
8619 window: &mut Window,
8620 cx: &mut Context<Self>,
8621 ) {
8622 self.transact(window, cx, |this, window, cx| {
8623 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8624 s.move_with(|_, selection| {
8625 selection.reversed = true;
8626 });
8627 });
8628
8629 this.select_to_beginning_of_line(
8630 &SelectToBeginningOfLine {
8631 stop_at_soft_wraps: false,
8632 },
8633 window,
8634 cx,
8635 );
8636 this.backspace(&Backspace, window, cx);
8637 });
8638 }
8639
8640 pub fn move_to_end_of_line(
8641 &mut self,
8642 action: &MoveToEndOfLine,
8643 window: &mut Window,
8644 cx: &mut Context<Self>,
8645 ) {
8646 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8647 s.move_cursors_with(|map, head, _| {
8648 (
8649 movement::line_end(map, head, action.stop_at_soft_wraps),
8650 SelectionGoal::None,
8651 )
8652 });
8653 })
8654 }
8655
8656 pub fn select_to_end_of_line(
8657 &mut self,
8658 action: &SelectToEndOfLine,
8659 window: &mut Window,
8660 cx: &mut Context<Self>,
8661 ) {
8662 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8663 s.move_heads_with(|map, head, _| {
8664 (
8665 movement::line_end(map, head, action.stop_at_soft_wraps),
8666 SelectionGoal::None,
8667 )
8668 });
8669 })
8670 }
8671
8672 pub fn delete_to_end_of_line(
8673 &mut self,
8674 _: &DeleteToEndOfLine,
8675 window: &mut Window,
8676 cx: &mut Context<Self>,
8677 ) {
8678 self.transact(window, cx, |this, window, cx| {
8679 this.select_to_end_of_line(
8680 &SelectToEndOfLine {
8681 stop_at_soft_wraps: false,
8682 },
8683 window,
8684 cx,
8685 );
8686 this.delete(&Delete, window, cx);
8687 });
8688 }
8689
8690 pub fn cut_to_end_of_line(
8691 &mut self,
8692 _: &CutToEndOfLine,
8693 window: &mut Window,
8694 cx: &mut Context<Self>,
8695 ) {
8696 self.transact(window, cx, |this, window, cx| {
8697 this.select_to_end_of_line(
8698 &SelectToEndOfLine {
8699 stop_at_soft_wraps: false,
8700 },
8701 window,
8702 cx,
8703 );
8704 this.cut(&Cut, window, cx);
8705 });
8706 }
8707
8708 pub fn move_to_start_of_paragraph(
8709 &mut self,
8710 _: &MoveToStartOfParagraph,
8711 window: &mut Window,
8712 cx: &mut Context<Self>,
8713 ) {
8714 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8715 cx.propagate();
8716 return;
8717 }
8718
8719 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8720 s.move_with(|map, selection| {
8721 selection.collapse_to(
8722 movement::start_of_paragraph(map, selection.head(), 1),
8723 SelectionGoal::None,
8724 )
8725 });
8726 })
8727 }
8728
8729 pub fn move_to_end_of_paragraph(
8730 &mut self,
8731 _: &MoveToEndOfParagraph,
8732 window: &mut Window,
8733 cx: &mut Context<Self>,
8734 ) {
8735 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8736 cx.propagate();
8737 return;
8738 }
8739
8740 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8741 s.move_with(|map, selection| {
8742 selection.collapse_to(
8743 movement::end_of_paragraph(map, selection.head(), 1),
8744 SelectionGoal::None,
8745 )
8746 });
8747 })
8748 }
8749
8750 pub fn select_to_start_of_paragraph(
8751 &mut self,
8752 _: &SelectToStartOfParagraph,
8753 window: &mut Window,
8754 cx: &mut Context<Self>,
8755 ) {
8756 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8757 cx.propagate();
8758 return;
8759 }
8760
8761 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8762 s.move_heads_with(|map, head, _| {
8763 (
8764 movement::start_of_paragraph(map, head, 1),
8765 SelectionGoal::None,
8766 )
8767 });
8768 })
8769 }
8770
8771 pub fn select_to_end_of_paragraph(
8772 &mut self,
8773 _: &SelectToEndOfParagraph,
8774 window: &mut Window,
8775 cx: &mut Context<Self>,
8776 ) {
8777 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8778 cx.propagate();
8779 return;
8780 }
8781
8782 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8783 s.move_heads_with(|map, head, _| {
8784 (
8785 movement::end_of_paragraph(map, head, 1),
8786 SelectionGoal::None,
8787 )
8788 });
8789 })
8790 }
8791
8792 pub fn move_to_beginning(
8793 &mut self,
8794 _: &MoveToBeginning,
8795 window: &mut Window,
8796 cx: &mut Context<Self>,
8797 ) {
8798 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8799 cx.propagate();
8800 return;
8801 }
8802
8803 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8804 s.select_ranges(vec![0..0]);
8805 });
8806 }
8807
8808 pub fn select_to_beginning(
8809 &mut self,
8810 _: &SelectToBeginning,
8811 window: &mut Window,
8812 cx: &mut Context<Self>,
8813 ) {
8814 let mut selection = self.selections.last::<Point>(cx);
8815 selection.set_head(Point::zero(), SelectionGoal::None);
8816
8817 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8818 s.select(vec![selection]);
8819 });
8820 }
8821
8822 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
8823 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8824 cx.propagate();
8825 return;
8826 }
8827
8828 let cursor = self.buffer.read(cx).read(cx).len();
8829 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8830 s.select_ranges(vec![cursor..cursor])
8831 });
8832 }
8833
8834 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8835 self.nav_history = nav_history;
8836 }
8837
8838 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8839 self.nav_history.as_ref()
8840 }
8841
8842 fn push_to_nav_history(
8843 &mut self,
8844 cursor_anchor: Anchor,
8845 new_position: Option<Point>,
8846 cx: &mut Context<Self>,
8847 ) {
8848 if let Some(nav_history) = self.nav_history.as_mut() {
8849 let buffer = self.buffer.read(cx).read(cx);
8850 let cursor_position = cursor_anchor.to_point(&buffer);
8851 let scroll_state = self.scroll_manager.anchor();
8852 let scroll_top_row = scroll_state.top_row(&buffer);
8853 drop(buffer);
8854
8855 if let Some(new_position) = new_position {
8856 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8857 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8858 return;
8859 }
8860 }
8861
8862 nav_history.push(
8863 Some(NavigationData {
8864 cursor_anchor,
8865 cursor_position,
8866 scroll_anchor: scroll_state,
8867 scroll_top_row,
8868 }),
8869 cx,
8870 );
8871 }
8872 }
8873
8874 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
8875 let buffer = self.buffer.read(cx).snapshot(cx);
8876 let mut selection = self.selections.first::<usize>(cx);
8877 selection.set_head(buffer.len(), SelectionGoal::None);
8878 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8879 s.select(vec![selection]);
8880 });
8881 }
8882
8883 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
8884 let end = self.buffer.read(cx).read(cx).len();
8885 self.change_selections(None, window, cx, |s| {
8886 s.select_ranges(vec![0..end]);
8887 });
8888 }
8889
8890 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
8891 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8892 let mut selections = self.selections.all::<Point>(cx);
8893 let max_point = display_map.buffer_snapshot.max_point();
8894 for selection in &mut selections {
8895 let rows = selection.spanned_rows(true, &display_map);
8896 selection.start = Point::new(rows.start.0, 0);
8897 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8898 selection.reversed = false;
8899 }
8900 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8901 s.select(selections);
8902 });
8903 }
8904
8905 pub fn split_selection_into_lines(
8906 &mut self,
8907 _: &SplitSelectionIntoLines,
8908 window: &mut Window,
8909 cx: &mut Context<Self>,
8910 ) {
8911 let mut to_unfold = Vec::new();
8912 let mut new_selection_ranges = Vec::new();
8913 {
8914 let selections = self.selections.all::<Point>(cx);
8915 let buffer = self.buffer.read(cx).read(cx);
8916 for selection in selections {
8917 for row in selection.start.row..selection.end.row {
8918 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8919 new_selection_ranges.push(cursor..cursor);
8920 }
8921 new_selection_ranges.push(selection.end..selection.end);
8922 to_unfold.push(selection.start..selection.end);
8923 }
8924 }
8925 self.unfold_ranges(&to_unfold, true, true, cx);
8926 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8927 s.select_ranges(new_selection_ranges);
8928 });
8929 }
8930
8931 pub fn add_selection_above(
8932 &mut self,
8933 _: &AddSelectionAbove,
8934 window: &mut Window,
8935 cx: &mut Context<Self>,
8936 ) {
8937 self.add_selection(true, window, cx);
8938 }
8939
8940 pub fn add_selection_below(
8941 &mut self,
8942 _: &AddSelectionBelow,
8943 window: &mut Window,
8944 cx: &mut Context<Self>,
8945 ) {
8946 self.add_selection(false, window, cx);
8947 }
8948
8949 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
8950 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8951 let mut selections = self.selections.all::<Point>(cx);
8952 let text_layout_details = self.text_layout_details(window);
8953 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8954 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8955 let range = oldest_selection.display_range(&display_map).sorted();
8956
8957 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8958 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8959 let positions = start_x.min(end_x)..start_x.max(end_x);
8960
8961 selections.clear();
8962 let mut stack = Vec::new();
8963 for row in range.start.row().0..=range.end.row().0 {
8964 if let Some(selection) = self.selections.build_columnar_selection(
8965 &display_map,
8966 DisplayRow(row),
8967 &positions,
8968 oldest_selection.reversed,
8969 &text_layout_details,
8970 ) {
8971 stack.push(selection.id);
8972 selections.push(selection);
8973 }
8974 }
8975
8976 if above {
8977 stack.reverse();
8978 }
8979
8980 AddSelectionsState { above, stack }
8981 });
8982
8983 let last_added_selection = *state.stack.last().unwrap();
8984 let mut new_selections = Vec::new();
8985 if above == state.above {
8986 let end_row = if above {
8987 DisplayRow(0)
8988 } else {
8989 display_map.max_point().row()
8990 };
8991
8992 'outer: for selection in selections {
8993 if selection.id == last_added_selection {
8994 let range = selection.display_range(&display_map).sorted();
8995 debug_assert_eq!(range.start.row(), range.end.row());
8996 let mut row = range.start.row();
8997 let positions =
8998 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8999 px(start)..px(end)
9000 } else {
9001 let start_x =
9002 display_map.x_for_display_point(range.start, &text_layout_details);
9003 let end_x =
9004 display_map.x_for_display_point(range.end, &text_layout_details);
9005 start_x.min(end_x)..start_x.max(end_x)
9006 };
9007
9008 while row != end_row {
9009 if above {
9010 row.0 -= 1;
9011 } else {
9012 row.0 += 1;
9013 }
9014
9015 if let Some(new_selection) = self.selections.build_columnar_selection(
9016 &display_map,
9017 row,
9018 &positions,
9019 selection.reversed,
9020 &text_layout_details,
9021 ) {
9022 state.stack.push(new_selection.id);
9023 if above {
9024 new_selections.push(new_selection);
9025 new_selections.push(selection);
9026 } else {
9027 new_selections.push(selection);
9028 new_selections.push(new_selection);
9029 }
9030
9031 continue 'outer;
9032 }
9033 }
9034 }
9035
9036 new_selections.push(selection);
9037 }
9038 } else {
9039 new_selections = selections;
9040 new_selections.retain(|s| s.id != last_added_selection);
9041 state.stack.pop();
9042 }
9043
9044 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9045 s.select(new_selections);
9046 });
9047 if state.stack.len() > 1 {
9048 self.add_selections_state = Some(state);
9049 }
9050 }
9051
9052 pub fn select_next_match_internal(
9053 &mut self,
9054 display_map: &DisplaySnapshot,
9055 replace_newest: bool,
9056 autoscroll: Option<Autoscroll>,
9057 window: &mut Window,
9058 cx: &mut Context<Self>,
9059 ) -> Result<()> {
9060 fn select_next_match_ranges(
9061 this: &mut Editor,
9062 range: Range<usize>,
9063 replace_newest: bool,
9064 auto_scroll: Option<Autoscroll>,
9065 window: &mut Window,
9066 cx: &mut Context<Editor>,
9067 ) {
9068 this.unfold_ranges(&[range.clone()], false, true, cx);
9069 this.change_selections(auto_scroll, window, cx, |s| {
9070 if replace_newest {
9071 s.delete(s.newest_anchor().id);
9072 }
9073 s.insert_range(range.clone());
9074 });
9075 }
9076
9077 let buffer = &display_map.buffer_snapshot;
9078 let mut selections = self.selections.all::<usize>(cx);
9079 if let Some(mut select_next_state) = self.select_next_state.take() {
9080 let query = &select_next_state.query;
9081 if !select_next_state.done {
9082 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9083 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9084 let mut next_selected_range = None;
9085
9086 let bytes_after_last_selection =
9087 buffer.bytes_in_range(last_selection.end..buffer.len());
9088 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
9089 let query_matches = query
9090 .stream_find_iter(bytes_after_last_selection)
9091 .map(|result| (last_selection.end, result))
9092 .chain(
9093 query
9094 .stream_find_iter(bytes_before_first_selection)
9095 .map(|result| (0, result)),
9096 );
9097
9098 for (start_offset, query_match) in query_matches {
9099 let query_match = query_match.unwrap(); // can only fail due to I/O
9100 let offset_range =
9101 start_offset + query_match.start()..start_offset + query_match.end();
9102 let display_range = offset_range.start.to_display_point(display_map)
9103 ..offset_range.end.to_display_point(display_map);
9104
9105 if !select_next_state.wordwise
9106 || (!movement::is_inside_word(display_map, display_range.start)
9107 && !movement::is_inside_word(display_map, display_range.end))
9108 {
9109 // TODO: This is n^2, because we might check all the selections
9110 if !selections
9111 .iter()
9112 .any(|selection| selection.range().overlaps(&offset_range))
9113 {
9114 next_selected_range = Some(offset_range);
9115 break;
9116 }
9117 }
9118 }
9119
9120 if let Some(next_selected_range) = next_selected_range {
9121 select_next_match_ranges(
9122 self,
9123 next_selected_range,
9124 replace_newest,
9125 autoscroll,
9126 window,
9127 cx,
9128 );
9129 } else {
9130 select_next_state.done = true;
9131 }
9132 }
9133
9134 self.select_next_state = Some(select_next_state);
9135 } else {
9136 let mut only_carets = true;
9137 let mut same_text_selected = true;
9138 let mut selected_text = None;
9139
9140 let mut selections_iter = selections.iter().peekable();
9141 while let Some(selection) = selections_iter.next() {
9142 if selection.start != selection.end {
9143 only_carets = false;
9144 }
9145
9146 if same_text_selected {
9147 if selected_text.is_none() {
9148 selected_text =
9149 Some(buffer.text_for_range(selection.range()).collect::<String>());
9150 }
9151
9152 if let Some(next_selection) = selections_iter.peek() {
9153 if next_selection.range().len() == selection.range().len() {
9154 let next_selected_text = buffer
9155 .text_for_range(next_selection.range())
9156 .collect::<String>();
9157 if Some(next_selected_text) != selected_text {
9158 same_text_selected = false;
9159 selected_text = None;
9160 }
9161 } else {
9162 same_text_selected = false;
9163 selected_text = None;
9164 }
9165 }
9166 }
9167 }
9168
9169 if only_carets {
9170 for selection in &mut selections {
9171 let word_range = movement::surrounding_word(
9172 display_map,
9173 selection.start.to_display_point(display_map),
9174 );
9175 selection.start = word_range.start.to_offset(display_map, Bias::Left);
9176 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9177 selection.goal = SelectionGoal::None;
9178 selection.reversed = false;
9179 select_next_match_ranges(
9180 self,
9181 selection.start..selection.end,
9182 replace_newest,
9183 autoscroll,
9184 window,
9185 cx,
9186 );
9187 }
9188
9189 if selections.len() == 1 {
9190 let selection = selections
9191 .last()
9192 .expect("ensured that there's only one selection");
9193 let query = buffer
9194 .text_for_range(selection.start..selection.end)
9195 .collect::<String>();
9196 let is_empty = query.is_empty();
9197 let select_state = SelectNextState {
9198 query: AhoCorasick::new(&[query])?,
9199 wordwise: true,
9200 done: is_empty,
9201 };
9202 self.select_next_state = Some(select_state);
9203 } else {
9204 self.select_next_state = None;
9205 }
9206 } else if let Some(selected_text) = selected_text {
9207 self.select_next_state = Some(SelectNextState {
9208 query: AhoCorasick::new(&[selected_text])?,
9209 wordwise: false,
9210 done: false,
9211 });
9212 self.select_next_match_internal(
9213 display_map,
9214 replace_newest,
9215 autoscroll,
9216 window,
9217 cx,
9218 )?;
9219 }
9220 }
9221 Ok(())
9222 }
9223
9224 pub fn select_all_matches(
9225 &mut self,
9226 _action: &SelectAllMatches,
9227 window: &mut Window,
9228 cx: &mut Context<Self>,
9229 ) -> Result<()> {
9230 self.push_to_selection_history();
9231 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9232
9233 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9234 let Some(select_next_state) = self.select_next_state.as_mut() else {
9235 return Ok(());
9236 };
9237 if select_next_state.done {
9238 return Ok(());
9239 }
9240
9241 let mut new_selections = self.selections.all::<usize>(cx);
9242
9243 let buffer = &display_map.buffer_snapshot;
9244 let query_matches = select_next_state
9245 .query
9246 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9247
9248 for query_match in query_matches {
9249 let query_match = query_match.unwrap(); // can only fail due to I/O
9250 let offset_range = query_match.start()..query_match.end();
9251 let display_range = offset_range.start.to_display_point(&display_map)
9252 ..offset_range.end.to_display_point(&display_map);
9253
9254 if !select_next_state.wordwise
9255 || (!movement::is_inside_word(&display_map, display_range.start)
9256 && !movement::is_inside_word(&display_map, display_range.end))
9257 {
9258 self.selections.change_with(cx, |selections| {
9259 new_selections.push(Selection {
9260 id: selections.new_selection_id(),
9261 start: offset_range.start,
9262 end: offset_range.end,
9263 reversed: false,
9264 goal: SelectionGoal::None,
9265 });
9266 });
9267 }
9268 }
9269
9270 new_selections.sort_by_key(|selection| selection.start);
9271 let mut ix = 0;
9272 while ix + 1 < new_selections.len() {
9273 let current_selection = &new_selections[ix];
9274 let next_selection = &new_selections[ix + 1];
9275 if current_selection.range().overlaps(&next_selection.range()) {
9276 if current_selection.id < next_selection.id {
9277 new_selections.remove(ix + 1);
9278 } else {
9279 new_selections.remove(ix);
9280 }
9281 } else {
9282 ix += 1;
9283 }
9284 }
9285
9286 let reversed = self.selections.oldest::<usize>(cx).reversed;
9287
9288 for selection in new_selections.iter_mut() {
9289 selection.reversed = reversed;
9290 }
9291
9292 select_next_state.done = true;
9293 self.unfold_ranges(
9294 &new_selections
9295 .iter()
9296 .map(|selection| selection.range())
9297 .collect::<Vec<_>>(),
9298 false,
9299 false,
9300 cx,
9301 );
9302 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9303 selections.select(new_selections)
9304 });
9305
9306 Ok(())
9307 }
9308
9309 pub fn select_next(
9310 &mut self,
9311 action: &SelectNext,
9312 window: &mut Window,
9313 cx: &mut Context<Self>,
9314 ) -> Result<()> {
9315 self.push_to_selection_history();
9316 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9317 self.select_next_match_internal(
9318 &display_map,
9319 action.replace_newest,
9320 Some(Autoscroll::newest()),
9321 window,
9322 cx,
9323 )?;
9324 Ok(())
9325 }
9326
9327 pub fn select_previous(
9328 &mut self,
9329 action: &SelectPrevious,
9330 window: &mut Window,
9331 cx: &mut Context<Self>,
9332 ) -> Result<()> {
9333 self.push_to_selection_history();
9334 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9335 let buffer = &display_map.buffer_snapshot;
9336 let mut selections = self.selections.all::<usize>(cx);
9337 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9338 let query = &select_prev_state.query;
9339 if !select_prev_state.done {
9340 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9341 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9342 let mut next_selected_range = None;
9343 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9344 let bytes_before_last_selection =
9345 buffer.reversed_bytes_in_range(0..last_selection.start);
9346 let bytes_after_first_selection =
9347 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9348 let query_matches = query
9349 .stream_find_iter(bytes_before_last_selection)
9350 .map(|result| (last_selection.start, result))
9351 .chain(
9352 query
9353 .stream_find_iter(bytes_after_first_selection)
9354 .map(|result| (buffer.len(), result)),
9355 );
9356 for (end_offset, query_match) in query_matches {
9357 let query_match = query_match.unwrap(); // can only fail due to I/O
9358 let offset_range =
9359 end_offset - query_match.end()..end_offset - query_match.start();
9360 let display_range = offset_range.start.to_display_point(&display_map)
9361 ..offset_range.end.to_display_point(&display_map);
9362
9363 if !select_prev_state.wordwise
9364 || (!movement::is_inside_word(&display_map, display_range.start)
9365 && !movement::is_inside_word(&display_map, display_range.end))
9366 {
9367 next_selected_range = Some(offset_range);
9368 break;
9369 }
9370 }
9371
9372 if let Some(next_selected_range) = next_selected_range {
9373 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9374 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9375 if action.replace_newest {
9376 s.delete(s.newest_anchor().id);
9377 }
9378 s.insert_range(next_selected_range);
9379 });
9380 } else {
9381 select_prev_state.done = true;
9382 }
9383 }
9384
9385 self.select_prev_state = Some(select_prev_state);
9386 } else {
9387 let mut only_carets = true;
9388 let mut same_text_selected = true;
9389 let mut selected_text = None;
9390
9391 let mut selections_iter = selections.iter().peekable();
9392 while let Some(selection) = selections_iter.next() {
9393 if selection.start != selection.end {
9394 only_carets = false;
9395 }
9396
9397 if same_text_selected {
9398 if selected_text.is_none() {
9399 selected_text =
9400 Some(buffer.text_for_range(selection.range()).collect::<String>());
9401 }
9402
9403 if let Some(next_selection) = selections_iter.peek() {
9404 if next_selection.range().len() == selection.range().len() {
9405 let next_selected_text = buffer
9406 .text_for_range(next_selection.range())
9407 .collect::<String>();
9408 if Some(next_selected_text) != selected_text {
9409 same_text_selected = false;
9410 selected_text = None;
9411 }
9412 } else {
9413 same_text_selected = false;
9414 selected_text = None;
9415 }
9416 }
9417 }
9418 }
9419
9420 if only_carets {
9421 for selection in &mut selections {
9422 let word_range = movement::surrounding_word(
9423 &display_map,
9424 selection.start.to_display_point(&display_map),
9425 );
9426 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9427 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9428 selection.goal = SelectionGoal::None;
9429 selection.reversed = false;
9430 }
9431 if selections.len() == 1 {
9432 let selection = selections
9433 .last()
9434 .expect("ensured that there's only one selection");
9435 let query = buffer
9436 .text_for_range(selection.start..selection.end)
9437 .collect::<String>();
9438 let is_empty = query.is_empty();
9439 let select_state = SelectNextState {
9440 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9441 wordwise: true,
9442 done: is_empty,
9443 };
9444 self.select_prev_state = Some(select_state);
9445 } else {
9446 self.select_prev_state = None;
9447 }
9448
9449 self.unfold_ranges(
9450 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9451 false,
9452 true,
9453 cx,
9454 );
9455 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9456 s.select(selections);
9457 });
9458 } else if let Some(selected_text) = selected_text {
9459 self.select_prev_state = Some(SelectNextState {
9460 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9461 wordwise: false,
9462 done: false,
9463 });
9464 self.select_previous(action, window, cx)?;
9465 }
9466 }
9467 Ok(())
9468 }
9469
9470 pub fn toggle_comments(
9471 &mut self,
9472 action: &ToggleComments,
9473 window: &mut Window,
9474 cx: &mut Context<Self>,
9475 ) {
9476 if self.read_only(cx) {
9477 return;
9478 }
9479 let text_layout_details = &self.text_layout_details(window);
9480 self.transact(window, cx, |this, window, cx| {
9481 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9482 let mut edits = Vec::new();
9483 let mut selection_edit_ranges = Vec::new();
9484 let mut last_toggled_row = None;
9485 let snapshot = this.buffer.read(cx).read(cx);
9486 let empty_str: Arc<str> = Arc::default();
9487 let mut suffixes_inserted = Vec::new();
9488 let ignore_indent = action.ignore_indent;
9489
9490 fn comment_prefix_range(
9491 snapshot: &MultiBufferSnapshot,
9492 row: MultiBufferRow,
9493 comment_prefix: &str,
9494 comment_prefix_whitespace: &str,
9495 ignore_indent: bool,
9496 ) -> Range<Point> {
9497 let indent_size = if ignore_indent {
9498 0
9499 } else {
9500 snapshot.indent_size_for_line(row).len
9501 };
9502
9503 let start = Point::new(row.0, indent_size);
9504
9505 let mut line_bytes = snapshot
9506 .bytes_in_range(start..snapshot.max_point())
9507 .flatten()
9508 .copied();
9509
9510 // If this line currently begins with the line comment prefix, then record
9511 // the range containing the prefix.
9512 if line_bytes
9513 .by_ref()
9514 .take(comment_prefix.len())
9515 .eq(comment_prefix.bytes())
9516 {
9517 // Include any whitespace that matches the comment prefix.
9518 let matching_whitespace_len = line_bytes
9519 .zip(comment_prefix_whitespace.bytes())
9520 .take_while(|(a, b)| a == b)
9521 .count() as u32;
9522 let end = Point::new(
9523 start.row,
9524 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9525 );
9526 start..end
9527 } else {
9528 start..start
9529 }
9530 }
9531
9532 fn comment_suffix_range(
9533 snapshot: &MultiBufferSnapshot,
9534 row: MultiBufferRow,
9535 comment_suffix: &str,
9536 comment_suffix_has_leading_space: bool,
9537 ) -> Range<Point> {
9538 let end = Point::new(row.0, snapshot.line_len(row));
9539 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9540
9541 let mut line_end_bytes = snapshot
9542 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9543 .flatten()
9544 .copied();
9545
9546 let leading_space_len = if suffix_start_column > 0
9547 && line_end_bytes.next() == Some(b' ')
9548 && comment_suffix_has_leading_space
9549 {
9550 1
9551 } else {
9552 0
9553 };
9554
9555 // If this line currently begins with the line comment prefix, then record
9556 // the range containing the prefix.
9557 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9558 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9559 start..end
9560 } else {
9561 end..end
9562 }
9563 }
9564
9565 // TODO: Handle selections that cross excerpts
9566 for selection in &mut selections {
9567 let start_column = snapshot
9568 .indent_size_for_line(MultiBufferRow(selection.start.row))
9569 .len;
9570 let language = if let Some(language) =
9571 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9572 {
9573 language
9574 } else {
9575 continue;
9576 };
9577
9578 selection_edit_ranges.clear();
9579
9580 // If multiple selections contain a given row, avoid processing that
9581 // row more than once.
9582 let mut start_row = MultiBufferRow(selection.start.row);
9583 if last_toggled_row == Some(start_row) {
9584 start_row = start_row.next_row();
9585 }
9586 let end_row =
9587 if selection.end.row > selection.start.row && selection.end.column == 0 {
9588 MultiBufferRow(selection.end.row - 1)
9589 } else {
9590 MultiBufferRow(selection.end.row)
9591 };
9592 last_toggled_row = Some(end_row);
9593
9594 if start_row > end_row {
9595 continue;
9596 }
9597
9598 // If the language has line comments, toggle those.
9599 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9600
9601 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9602 if ignore_indent {
9603 full_comment_prefixes = full_comment_prefixes
9604 .into_iter()
9605 .map(|s| Arc::from(s.trim_end()))
9606 .collect();
9607 }
9608
9609 if !full_comment_prefixes.is_empty() {
9610 let first_prefix = full_comment_prefixes
9611 .first()
9612 .expect("prefixes is non-empty");
9613 let prefix_trimmed_lengths = full_comment_prefixes
9614 .iter()
9615 .map(|p| p.trim_end_matches(' ').len())
9616 .collect::<SmallVec<[usize; 4]>>();
9617
9618 let mut all_selection_lines_are_comments = true;
9619
9620 for row in start_row.0..=end_row.0 {
9621 let row = MultiBufferRow(row);
9622 if start_row < end_row && snapshot.is_line_blank(row) {
9623 continue;
9624 }
9625
9626 let prefix_range = full_comment_prefixes
9627 .iter()
9628 .zip(prefix_trimmed_lengths.iter().copied())
9629 .map(|(prefix, trimmed_prefix_len)| {
9630 comment_prefix_range(
9631 snapshot.deref(),
9632 row,
9633 &prefix[..trimmed_prefix_len],
9634 &prefix[trimmed_prefix_len..],
9635 ignore_indent,
9636 )
9637 })
9638 .max_by_key(|range| range.end.column - range.start.column)
9639 .expect("prefixes is non-empty");
9640
9641 if prefix_range.is_empty() {
9642 all_selection_lines_are_comments = false;
9643 }
9644
9645 selection_edit_ranges.push(prefix_range);
9646 }
9647
9648 if all_selection_lines_are_comments {
9649 edits.extend(
9650 selection_edit_ranges
9651 .iter()
9652 .cloned()
9653 .map(|range| (range, empty_str.clone())),
9654 );
9655 } else {
9656 let min_column = selection_edit_ranges
9657 .iter()
9658 .map(|range| range.start.column)
9659 .min()
9660 .unwrap_or(0);
9661 edits.extend(selection_edit_ranges.iter().map(|range| {
9662 let position = Point::new(range.start.row, min_column);
9663 (position..position, first_prefix.clone())
9664 }));
9665 }
9666 } else if let Some((full_comment_prefix, comment_suffix)) =
9667 language.block_comment_delimiters()
9668 {
9669 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9670 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9671 let prefix_range = comment_prefix_range(
9672 snapshot.deref(),
9673 start_row,
9674 comment_prefix,
9675 comment_prefix_whitespace,
9676 ignore_indent,
9677 );
9678 let suffix_range = comment_suffix_range(
9679 snapshot.deref(),
9680 end_row,
9681 comment_suffix.trim_start_matches(' '),
9682 comment_suffix.starts_with(' '),
9683 );
9684
9685 if prefix_range.is_empty() || suffix_range.is_empty() {
9686 edits.push((
9687 prefix_range.start..prefix_range.start,
9688 full_comment_prefix.clone(),
9689 ));
9690 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9691 suffixes_inserted.push((end_row, comment_suffix.len()));
9692 } else {
9693 edits.push((prefix_range, empty_str.clone()));
9694 edits.push((suffix_range, empty_str.clone()));
9695 }
9696 } else {
9697 continue;
9698 }
9699 }
9700
9701 drop(snapshot);
9702 this.buffer.update(cx, |buffer, cx| {
9703 buffer.edit(edits, None, cx);
9704 });
9705
9706 // Adjust selections so that they end before any comment suffixes that
9707 // were inserted.
9708 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9709 let mut selections = this.selections.all::<Point>(cx);
9710 let snapshot = this.buffer.read(cx).read(cx);
9711 for selection in &mut selections {
9712 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9713 match row.cmp(&MultiBufferRow(selection.end.row)) {
9714 Ordering::Less => {
9715 suffixes_inserted.next();
9716 continue;
9717 }
9718 Ordering::Greater => break,
9719 Ordering::Equal => {
9720 if selection.end.column == snapshot.line_len(row) {
9721 if selection.is_empty() {
9722 selection.start.column -= suffix_len as u32;
9723 }
9724 selection.end.column -= suffix_len as u32;
9725 }
9726 break;
9727 }
9728 }
9729 }
9730 }
9731
9732 drop(snapshot);
9733 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9734 s.select(selections)
9735 });
9736
9737 let selections = this.selections.all::<Point>(cx);
9738 let selections_on_single_row = selections.windows(2).all(|selections| {
9739 selections[0].start.row == selections[1].start.row
9740 && selections[0].end.row == selections[1].end.row
9741 && selections[0].start.row == selections[0].end.row
9742 });
9743 let selections_selecting = selections
9744 .iter()
9745 .any(|selection| selection.start != selection.end);
9746 let advance_downwards = action.advance_downwards
9747 && selections_on_single_row
9748 && !selections_selecting
9749 && !matches!(this.mode, EditorMode::SingleLine { .. });
9750
9751 if advance_downwards {
9752 let snapshot = this.buffer.read(cx).snapshot(cx);
9753
9754 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9755 s.move_cursors_with(|display_snapshot, display_point, _| {
9756 let mut point = display_point.to_point(display_snapshot);
9757 point.row += 1;
9758 point = snapshot.clip_point(point, Bias::Left);
9759 let display_point = point.to_display_point(display_snapshot);
9760 let goal = SelectionGoal::HorizontalPosition(
9761 display_snapshot
9762 .x_for_display_point(display_point, text_layout_details)
9763 .into(),
9764 );
9765 (display_point, goal)
9766 })
9767 });
9768 }
9769 });
9770 }
9771
9772 pub fn select_enclosing_symbol(
9773 &mut self,
9774 _: &SelectEnclosingSymbol,
9775 window: &mut Window,
9776 cx: &mut Context<Self>,
9777 ) {
9778 let buffer = self.buffer.read(cx).snapshot(cx);
9779 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9780
9781 fn update_selection(
9782 selection: &Selection<usize>,
9783 buffer_snap: &MultiBufferSnapshot,
9784 ) -> Option<Selection<usize>> {
9785 let cursor = selection.head();
9786 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9787 for symbol in symbols.iter().rev() {
9788 let start = symbol.range.start.to_offset(buffer_snap);
9789 let end = symbol.range.end.to_offset(buffer_snap);
9790 let new_range = start..end;
9791 if start < selection.start || end > selection.end {
9792 return Some(Selection {
9793 id: selection.id,
9794 start: new_range.start,
9795 end: new_range.end,
9796 goal: SelectionGoal::None,
9797 reversed: selection.reversed,
9798 });
9799 }
9800 }
9801 None
9802 }
9803
9804 let mut selected_larger_symbol = false;
9805 let new_selections = old_selections
9806 .iter()
9807 .map(|selection| match update_selection(selection, &buffer) {
9808 Some(new_selection) => {
9809 if new_selection.range() != selection.range() {
9810 selected_larger_symbol = true;
9811 }
9812 new_selection
9813 }
9814 None => selection.clone(),
9815 })
9816 .collect::<Vec<_>>();
9817
9818 if selected_larger_symbol {
9819 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9820 s.select(new_selections);
9821 });
9822 }
9823 }
9824
9825 pub fn select_larger_syntax_node(
9826 &mut self,
9827 _: &SelectLargerSyntaxNode,
9828 window: &mut Window,
9829 cx: &mut Context<Self>,
9830 ) {
9831 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9832 let buffer = self.buffer.read(cx).snapshot(cx);
9833 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9834
9835 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9836 let mut selected_larger_node = false;
9837 let new_selections = old_selections
9838 .iter()
9839 .map(|selection| {
9840 let old_range = selection.start..selection.end;
9841 let mut new_range = old_range.clone();
9842 let mut new_node = None;
9843 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
9844 {
9845 new_node = Some(node);
9846 new_range = containing_range;
9847 if !display_map.intersects_fold(new_range.start)
9848 && !display_map.intersects_fold(new_range.end)
9849 {
9850 break;
9851 }
9852 }
9853
9854 if let Some(node) = new_node {
9855 // Log the ancestor, to support using this action as a way to explore TreeSitter
9856 // nodes. Parent and grandparent are also logged because this operation will not
9857 // visit nodes that have the same range as their parent.
9858 log::info!("Node: {node:?}");
9859 let parent = node.parent();
9860 log::info!("Parent: {parent:?}");
9861 let grandparent = parent.and_then(|x| x.parent());
9862 log::info!("Grandparent: {grandparent:?}");
9863 }
9864
9865 selected_larger_node |= new_range != old_range;
9866 Selection {
9867 id: selection.id,
9868 start: new_range.start,
9869 end: new_range.end,
9870 goal: SelectionGoal::None,
9871 reversed: selection.reversed,
9872 }
9873 })
9874 .collect::<Vec<_>>();
9875
9876 if selected_larger_node {
9877 stack.push(old_selections);
9878 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9879 s.select(new_selections);
9880 });
9881 }
9882 self.select_larger_syntax_node_stack = stack;
9883 }
9884
9885 pub fn select_smaller_syntax_node(
9886 &mut self,
9887 _: &SelectSmallerSyntaxNode,
9888 window: &mut Window,
9889 cx: &mut Context<Self>,
9890 ) {
9891 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9892 if let Some(selections) = stack.pop() {
9893 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9894 s.select(selections.to_vec());
9895 });
9896 }
9897 self.select_larger_syntax_node_stack = stack;
9898 }
9899
9900 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
9901 if !EditorSettings::get_global(cx).gutter.runnables {
9902 self.clear_tasks();
9903 return Task::ready(());
9904 }
9905 let project = self.project.as_ref().map(Entity::downgrade);
9906 cx.spawn_in(window, |this, mut cx| async move {
9907 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
9908 let Some(project) = project.and_then(|p| p.upgrade()) else {
9909 return;
9910 };
9911 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9912 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9913 }) else {
9914 return;
9915 };
9916
9917 let hide_runnables = project
9918 .update(&mut cx, |project, cx| {
9919 // Do not display any test indicators in non-dev server remote projects.
9920 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9921 })
9922 .unwrap_or(true);
9923 if hide_runnables {
9924 return;
9925 }
9926 let new_rows =
9927 cx.background_executor()
9928 .spawn({
9929 let snapshot = display_snapshot.clone();
9930 async move {
9931 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9932 }
9933 })
9934 .await;
9935
9936 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9937 this.update(&mut cx, |this, _| {
9938 this.clear_tasks();
9939 for (key, value) in rows {
9940 this.insert_tasks(key, value);
9941 }
9942 })
9943 .ok();
9944 })
9945 }
9946 fn fetch_runnable_ranges(
9947 snapshot: &DisplaySnapshot,
9948 range: Range<Anchor>,
9949 ) -> Vec<language::RunnableRange> {
9950 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9951 }
9952
9953 fn runnable_rows(
9954 project: Entity<Project>,
9955 snapshot: DisplaySnapshot,
9956 runnable_ranges: Vec<RunnableRange>,
9957 mut cx: AsyncWindowContext,
9958 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9959 runnable_ranges
9960 .into_iter()
9961 .filter_map(|mut runnable| {
9962 let tasks = cx
9963 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9964 .ok()?;
9965 if tasks.is_empty() {
9966 return None;
9967 }
9968
9969 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9970
9971 let row = snapshot
9972 .buffer_snapshot
9973 .buffer_line_for_row(MultiBufferRow(point.row))?
9974 .1
9975 .start
9976 .row;
9977
9978 let context_range =
9979 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9980 Some((
9981 (runnable.buffer_id, row),
9982 RunnableTasks {
9983 templates: tasks,
9984 offset: MultiBufferOffset(runnable.run_range.start),
9985 context_range,
9986 column: point.column,
9987 extra_variables: runnable.extra_captures,
9988 },
9989 ))
9990 })
9991 .collect()
9992 }
9993
9994 fn templates_with_tags(
9995 project: &Entity<Project>,
9996 runnable: &mut Runnable,
9997 cx: &mut App,
9998 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9999 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10000 let (worktree_id, file) = project
10001 .buffer_for_id(runnable.buffer, cx)
10002 .and_then(|buffer| buffer.read(cx).file())
10003 .map(|file| (file.worktree_id(cx), file.clone()))
10004 .unzip();
10005
10006 (
10007 project.task_store().read(cx).task_inventory().cloned(),
10008 worktree_id,
10009 file,
10010 )
10011 });
10012
10013 let tags = mem::take(&mut runnable.tags);
10014 let mut tags: Vec<_> = tags
10015 .into_iter()
10016 .flat_map(|tag| {
10017 let tag = tag.0.clone();
10018 inventory
10019 .as_ref()
10020 .into_iter()
10021 .flat_map(|inventory| {
10022 inventory.read(cx).list_tasks(
10023 file.clone(),
10024 Some(runnable.language.clone()),
10025 worktree_id,
10026 cx,
10027 )
10028 })
10029 .filter(move |(_, template)| {
10030 template.tags.iter().any(|source_tag| source_tag == &tag)
10031 })
10032 })
10033 .sorted_by_key(|(kind, _)| kind.to_owned())
10034 .collect();
10035 if let Some((leading_tag_source, _)) = tags.first() {
10036 // Strongest source wins; if we have worktree tag binding, prefer that to
10037 // global and language bindings;
10038 // if we have a global binding, prefer that to language binding.
10039 let first_mismatch = tags
10040 .iter()
10041 .position(|(tag_source, _)| tag_source != leading_tag_source);
10042 if let Some(index) = first_mismatch {
10043 tags.truncate(index);
10044 }
10045 }
10046
10047 tags
10048 }
10049
10050 pub fn move_to_enclosing_bracket(
10051 &mut self,
10052 _: &MoveToEnclosingBracket,
10053 window: &mut Window,
10054 cx: &mut Context<Self>,
10055 ) {
10056 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10057 s.move_offsets_with(|snapshot, selection| {
10058 let Some(enclosing_bracket_ranges) =
10059 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10060 else {
10061 return;
10062 };
10063
10064 let mut best_length = usize::MAX;
10065 let mut best_inside = false;
10066 let mut best_in_bracket_range = false;
10067 let mut best_destination = None;
10068 for (open, close) in enclosing_bracket_ranges {
10069 let close = close.to_inclusive();
10070 let length = close.end() - open.start;
10071 let inside = selection.start >= open.end && selection.end <= *close.start();
10072 let in_bracket_range = open.to_inclusive().contains(&selection.head())
10073 || close.contains(&selection.head());
10074
10075 // If best is next to a bracket and current isn't, skip
10076 if !in_bracket_range && best_in_bracket_range {
10077 continue;
10078 }
10079
10080 // Prefer smaller lengths unless best is inside and current isn't
10081 if length > best_length && (best_inside || !inside) {
10082 continue;
10083 }
10084
10085 best_length = length;
10086 best_inside = inside;
10087 best_in_bracket_range = in_bracket_range;
10088 best_destination = Some(
10089 if close.contains(&selection.start) && close.contains(&selection.end) {
10090 if inside {
10091 open.end
10092 } else {
10093 open.start
10094 }
10095 } else if inside {
10096 *close.start()
10097 } else {
10098 *close.end()
10099 },
10100 );
10101 }
10102
10103 if let Some(destination) = best_destination {
10104 selection.collapse_to(destination, SelectionGoal::None);
10105 }
10106 })
10107 });
10108 }
10109
10110 pub fn undo_selection(
10111 &mut self,
10112 _: &UndoSelection,
10113 window: &mut Window,
10114 cx: &mut Context<Self>,
10115 ) {
10116 self.end_selection(window, cx);
10117 self.selection_history.mode = SelectionHistoryMode::Undoing;
10118 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10119 self.change_selections(None, window, cx, |s| {
10120 s.select_anchors(entry.selections.to_vec())
10121 });
10122 self.select_next_state = entry.select_next_state;
10123 self.select_prev_state = entry.select_prev_state;
10124 self.add_selections_state = entry.add_selections_state;
10125 self.request_autoscroll(Autoscroll::newest(), cx);
10126 }
10127 self.selection_history.mode = SelectionHistoryMode::Normal;
10128 }
10129
10130 pub fn redo_selection(
10131 &mut self,
10132 _: &RedoSelection,
10133 window: &mut Window,
10134 cx: &mut Context<Self>,
10135 ) {
10136 self.end_selection(window, cx);
10137 self.selection_history.mode = SelectionHistoryMode::Redoing;
10138 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10139 self.change_selections(None, window, cx, |s| {
10140 s.select_anchors(entry.selections.to_vec())
10141 });
10142 self.select_next_state = entry.select_next_state;
10143 self.select_prev_state = entry.select_prev_state;
10144 self.add_selections_state = entry.add_selections_state;
10145 self.request_autoscroll(Autoscroll::newest(), cx);
10146 }
10147 self.selection_history.mode = SelectionHistoryMode::Normal;
10148 }
10149
10150 pub fn expand_excerpts(
10151 &mut self,
10152 action: &ExpandExcerpts,
10153 _: &mut Window,
10154 cx: &mut Context<Self>,
10155 ) {
10156 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10157 }
10158
10159 pub fn expand_excerpts_down(
10160 &mut self,
10161 action: &ExpandExcerptsDown,
10162 _: &mut Window,
10163 cx: &mut Context<Self>,
10164 ) {
10165 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10166 }
10167
10168 pub fn expand_excerpts_up(
10169 &mut self,
10170 action: &ExpandExcerptsUp,
10171 _: &mut Window,
10172 cx: &mut Context<Self>,
10173 ) {
10174 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10175 }
10176
10177 pub fn expand_excerpts_for_direction(
10178 &mut self,
10179 lines: u32,
10180 direction: ExpandExcerptDirection,
10181
10182 cx: &mut Context<Self>,
10183 ) {
10184 let selections = self.selections.disjoint_anchors();
10185
10186 let lines = if lines == 0 {
10187 EditorSettings::get_global(cx).expand_excerpt_lines
10188 } else {
10189 lines
10190 };
10191
10192 self.buffer.update(cx, |buffer, cx| {
10193 let snapshot = buffer.snapshot(cx);
10194 let mut excerpt_ids = selections
10195 .iter()
10196 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10197 .collect::<Vec<_>>();
10198 excerpt_ids.sort();
10199 excerpt_ids.dedup();
10200 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10201 })
10202 }
10203
10204 pub fn expand_excerpt(
10205 &mut self,
10206 excerpt: ExcerptId,
10207 direction: ExpandExcerptDirection,
10208 cx: &mut Context<Self>,
10209 ) {
10210 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10211 self.buffer.update(cx, |buffer, cx| {
10212 buffer.expand_excerpts([excerpt], lines, direction, cx)
10213 })
10214 }
10215
10216 pub fn go_to_singleton_buffer_point(
10217 &mut self,
10218 point: Point,
10219 window: &mut Window,
10220 cx: &mut Context<Self>,
10221 ) {
10222 self.go_to_singleton_buffer_range(point..point, window, cx);
10223 }
10224
10225 pub fn go_to_singleton_buffer_range(
10226 &mut self,
10227 range: Range<Point>,
10228 window: &mut Window,
10229 cx: &mut Context<Self>,
10230 ) {
10231 let multibuffer = self.buffer().read(cx);
10232 let Some(buffer) = multibuffer.as_singleton() else {
10233 return;
10234 };
10235 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10236 return;
10237 };
10238 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10239 return;
10240 };
10241 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10242 s.select_anchor_ranges([start..end])
10243 });
10244 }
10245
10246 fn go_to_diagnostic(
10247 &mut self,
10248 _: &GoToDiagnostic,
10249 window: &mut Window,
10250 cx: &mut Context<Self>,
10251 ) {
10252 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10253 }
10254
10255 fn go_to_prev_diagnostic(
10256 &mut self,
10257 _: &GoToPrevDiagnostic,
10258 window: &mut Window,
10259 cx: &mut Context<Self>,
10260 ) {
10261 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10262 }
10263
10264 pub fn go_to_diagnostic_impl(
10265 &mut self,
10266 direction: Direction,
10267 window: &mut Window,
10268 cx: &mut Context<Self>,
10269 ) {
10270 let buffer = self.buffer.read(cx).snapshot(cx);
10271 let selection = self.selections.newest::<usize>(cx);
10272
10273 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10274 if direction == Direction::Next {
10275 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10276 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10277 return;
10278 };
10279 self.activate_diagnostics(
10280 buffer_id,
10281 popover.local_diagnostic.diagnostic.group_id,
10282 window,
10283 cx,
10284 );
10285 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10286 let primary_range_start = active_diagnostics.primary_range.start;
10287 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10288 let mut new_selection = s.newest_anchor().clone();
10289 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10290 s.select_anchors(vec![new_selection.clone()]);
10291 });
10292 self.refresh_inline_completion(false, true, window, cx);
10293 }
10294 return;
10295 }
10296 }
10297
10298 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10299 active_diagnostics
10300 .primary_range
10301 .to_offset(&buffer)
10302 .to_inclusive()
10303 });
10304 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10305 if active_primary_range.contains(&selection.head()) {
10306 *active_primary_range.start()
10307 } else {
10308 selection.head()
10309 }
10310 } else {
10311 selection.head()
10312 };
10313 let snapshot = self.snapshot(window, cx);
10314 loop {
10315 let mut diagnostics;
10316 if direction == Direction::Prev {
10317 diagnostics = buffer
10318 .diagnostics_in_range::<usize>(0..search_start)
10319 .collect::<Vec<_>>();
10320 diagnostics.reverse();
10321 } else {
10322 diagnostics = buffer
10323 .diagnostics_in_range::<usize>(search_start..buffer.len())
10324 .collect::<Vec<_>>();
10325 };
10326 let group = diagnostics
10327 .into_iter()
10328 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10329 // relies on diagnostics_in_range to return diagnostics with the same starting range to
10330 // be sorted in a stable way
10331 // skip until we are at current active diagnostic, if it exists
10332 .skip_while(|entry| {
10333 let is_in_range = match direction {
10334 Direction::Prev => entry.range.end > search_start,
10335 Direction::Next => entry.range.start < search_start,
10336 };
10337 is_in_range
10338 && self
10339 .active_diagnostics
10340 .as_ref()
10341 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
10342 })
10343 .find_map(|entry| {
10344 if entry.diagnostic.is_primary
10345 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
10346 && entry.range.start != entry.range.end
10347 // if we match with the active diagnostic, skip it
10348 && Some(entry.diagnostic.group_id)
10349 != self.active_diagnostics.as_ref().map(|d| d.group_id)
10350 {
10351 Some((entry.range, entry.diagnostic.group_id))
10352 } else {
10353 None
10354 }
10355 });
10356
10357 if let Some((primary_range, group_id)) = group {
10358 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10359 return;
10360 };
10361 self.activate_diagnostics(buffer_id, group_id, window, cx);
10362 if self.active_diagnostics.is_some() {
10363 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10364 s.select(vec![Selection {
10365 id: selection.id,
10366 start: primary_range.start,
10367 end: primary_range.start,
10368 reversed: false,
10369 goal: SelectionGoal::None,
10370 }]);
10371 });
10372 self.refresh_inline_completion(false, true, window, cx);
10373 }
10374 break;
10375 } else {
10376 // Cycle around to the start of the buffer, potentially moving back to the start of
10377 // the currently active diagnostic.
10378 active_primary_range.take();
10379 if direction == Direction::Prev {
10380 if search_start == buffer.len() {
10381 break;
10382 } else {
10383 search_start = buffer.len();
10384 }
10385 } else if search_start == 0 {
10386 break;
10387 } else {
10388 search_start = 0;
10389 }
10390 }
10391 }
10392 }
10393
10394 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10395 let snapshot = self.snapshot(window, cx);
10396 let selection = self.selections.newest::<Point>(cx);
10397 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10398 }
10399
10400 fn go_to_hunk_after_position(
10401 &mut self,
10402 snapshot: &EditorSnapshot,
10403 position: Point,
10404 window: &mut Window,
10405 cx: &mut Context<Editor>,
10406 ) -> Option<MultiBufferDiffHunk> {
10407 let mut hunk = snapshot
10408 .buffer_snapshot
10409 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10410 .find(|hunk| hunk.row_range.start.0 > position.row);
10411 if hunk.is_none() {
10412 hunk = snapshot
10413 .buffer_snapshot
10414 .diff_hunks_in_range(Point::zero()..position)
10415 .find(|hunk| hunk.row_range.end.0 < position.row)
10416 }
10417 if let Some(hunk) = &hunk {
10418 let destination = Point::new(hunk.row_range.start.0, 0);
10419 self.unfold_ranges(&[destination..destination], false, false, cx);
10420 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10421 s.select_ranges(vec![destination..destination]);
10422 });
10423 }
10424
10425 hunk
10426 }
10427
10428 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10429 let snapshot = self.snapshot(window, cx);
10430 let selection = self.selections.newest::<Point>(cx);
10431 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10432 }
10433
10434 fn go_to_hunk_before_position(
10435 &mut self,
10436 snapshot: &EditorSnapshot,
10437 position: Point,
10438 window: &mut Window,
10439 cx: &mut Context<Editor>,
10440 ) -> Option<MultiBufferDiffHunk> {
10441 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10442 if hunk.is_none() {
10443 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10444 }
10445 if let Some(hunk) = &hunk {
10446 let destination = Point::new(hunk.row_range.start.0, 0);
10447 self.unfold_ranges(&[destination..destination], false, false, cx);
10448 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10449 s.select_ranges(vec![destination..destination]);
10450 });
10451 }
10452
10453 hunk
10454 }
10455
10456 pub fn go_to_definition(
10457 &mut self,
10458 _: &GoToDefinition,
10459 window: &mut Window,
10460 cx: &mut Context<Self>,
10461 ) -> Task<Result<Navigated>> {
10462 let definition =
10463 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10464 cx.spawn_in(window, |editor, mut cx| async move {
10465 if definition.await? == Navigated::Yes {
10466 return Ok(Navigated::Yes);
10467 }
10468 match editor.update_in(&mut cx, |editor, window, cx| {
10469 editor.find_all_references(&FindAllReferences, window, cx)
10470 })? {
10471 Some(references) => references.await,
10472 None => Ok(Navigated::No),
10473 }
10474 })
10475 }
10476
10477 pub fn go_to_declaration(
10478 &mut self,
10479 _: &GoToDeclaration,
10480 window: &mut Window,
10481 cx: &mut Context<Self>,
10482 ) -> Task<Result<Navigated>> {
10483 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10484 }
10485
10486 pub fn go_to_declaration_split(
10487 &mut self,
10488 _: &GoToDeclaration,
10489 window: &mut Window,
10490 cx: &mut Context<Self>,
10491 ) -> Task<Result<Navigated>> {
10492 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10493 }
10494
10495 pub fn go_to_implementation(
10496 &mut self,
10497 _: &GoToImplementation,
10498 window: &mut Window,
10499 cx: &mut Context<Self>,
10500 ) -> Task<Result<Navigated>> {
10501 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10502 }
10503
10504 pub fn go_to_implementation_split(
10505 &mut self,
10506 _: &GoToImplementationSplit,
10507 window: &mut Window,
10508 cx: &mut Context<Self>,
10509 ) -> Task<Result<Navigated>> {
10510 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10511 }
10512
10513 pub fn go_to_type_definition(
10514 &mut self,
10515 _: &GoToTypeDefinition,
10516 window: &mut Window,
10517 cx: &mut Context<Self>,
10518 ) -> Task<Result<Navigated>> {
10519 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10520 }
10521
10522 pub fn go_to_definition_split(
10523 &mut self,
10524 _: &GoToDefinitionSplit,
10525 window: &mut Window,
10526 cx: &mut Context<Self>,
10527 ) -> Task<Result<Navigated>> {
10528 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10529 }
10530
10531 pub fn go_to_type_definition_split(
10532 &mut self,
10533 _: &GoToTypeDefinitionSplit,
10534 window: &mut Window,
10535 cx: &mut Context<Self>,
10536 ) -> Task<Result<Navigated>> {
10537 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10538 }
10539
10540 fn go_to_definition_of_kind(
10541 &mut self,
10542 kind: GotoDefinitionKind,
10543 split: bool,
10544 window: &mut Window,
10545 cx: &mut Context<Self>,
10546 ) -> Task<Result<Navigated>> {
10547 let Some(provider) = self.semantics_provider.clone() else {
10548 return Task::ready(Ok(Navigated::No));
10549 };
10550 let head = self.selections.newest::<usize>(cx).head();
10551 let buffer = self.buffer.read(cx);
10552 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10553 text_anchor
10554 } else {
10555 return Task::ready(Ok(Navigated::No));
10556 };
10557
10558 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10559 return Task::ready(Ok(Navigated::No));
10560 };
10561
10562 cx.spawn_in(window, |editor, mut cx| async move {
10563 let definitions = definitions.await?;
10564 let navigated = editor
10565 .update_in(&mut cx, |editor, window, cx| {
10566 editor.navigate_to_hover_links(
10567 Some(kind),
10568 definitions
10569 .into_iter()
10570 .filter(|location| {
10571 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10572 })
10573 .map(HoverLink::Text)
10574 .collect::<Vec<_>>(),
10575 split,
10576 window,
10577 cx,
10578 )
10579 })?
10580 .await?;
10581 anyhow::Ok(navigated)
10582 })
10583 }
10584
10585 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10586 let selection = self.selections.newest_anchor();
10587 let head = selection.head();
10588 let tail = selection.tail();
10589
10590 let Some((buffer, start_position)) =
10591 self.buffer.read(cx).text_anchor_for_position(head, cx)
10592 else {
10593 return;
10594 };
10595
10596 let end_position = if head != tail {
10597 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10598 return;
10599 };
10600 Some(pos)
10601 } else {
10602 None
10603 };
10604
10605 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10606 let url = if let Some(end_pos) = end_position {
10607 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10608 } else {
10609 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10610 };
10611
10612 if let Some(url) = url {
10613 editor.update(&mut cx, |_, cx| {
10614 cx.open_url(&url);
10615 })
10616 } else {
10617 Ok(())
10618 }
10619 });
10620
10621 url_finder.detach();
10622 }
10623
10624 pub fn open_selected_filename(
10625 &mut self,
10626 _: &OpenSelectedFilename,
10627 window: &mut Window,
10628 cx: &mut Context<Self>,
10629 ) {
10630 let Some(workspace) = self.workspace() else {
10631 return;
10632 };
10633
10634 let position = self.selections.newest_anchor().head();
10635
10636 let Some((buffer, buffer_position)) =
10637 self.buffer.read(cx).text_anchor_for_position(position, cx)
10638 else {
10639 return;
10640 };
10641
10642 let project = self.project.clone();
10643
10644 cx.spawn_in(window, |_, mut cx| async move {
10645 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10646
10647 if let Some((_, path)) = result {
10648 workspace
10649 .update_in(&mut cx, |workspace, window, cx| {
10650 workspace.open_resolved_path(path, window, cx)
10651 })?
10652 .await?;
10653 }
10654 anyhow::Ok(())
10655 })
10656 .detach();
10657 }
10658
10659 pub(crate) fn navigate_to_hover_links(
10660 &mut self,
10661 kind: Option<GotoDefinitionKind>,
10662 mut definitions: Vec<HoverLink>,
10663 split: bool,
10664 window: &mut Window,
10665 cx: &mut Context<Editor>,
10666 ) -> Task<Result<Navigated>> {
10667 // If there is one definition, just open it directly
10668 if definitions.len() == 1 {
10669 let definition = definitions.pop().unwrap();
10670
10671 enum TargetTaskResult {
10672 Location(Option<Location>),
10673 AlreadyNavigated,
10674 }
10675
10676 let target_task = match definition {
10677 HoverLink::Text(link) => {
10678 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10679 }
10680 HoverLink::InlayHint(lsp_location, server_id) => {
10681 let computation =
10682 self.compute_target_location(lsp_location, server_id, window, cx);
10683 cx.background_executor().spawn(async move {
10684 let location = computation.await?;
10685 Ok(TargetTaskResult::Location(location))
10686 })
10687 }
10688 HoverLink::Url(url) => {
10689 cx.open_url(&url);
10690 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10691 }
10692 HoverLink::File(path) => {
10693 if let Some(workspace) = self.workspace() {
10694 cx.spawn_in(window, |_, mut cx| async move {
10695 workspace
10696 .update_in(&mut cx, |workspace, window, cx| {
10697 workspace.open_resolved_path(path, window, cx)
10698 })?
10699 .await
10700 .map(|_| TargetTaskResult::AlreadyNavigated)
10701 })
10702 } else {
10703 Task::ready(Ok(TargetTaskResult::Location(None)))
10704 }
10705 }
10706 };
10707 cx.spawn_in(window, |editor, mut cx| async move {
10708 let target = match target_task.await.context("target resolution task")? {
10709 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10710 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10711 TargetTaskResult::Location(Some(target)) => target,
10712 };
10713
10714 editor.update_in(&mut cx, |editor, window, cx| {
10715 let Some(workspace) = editor.workspace() else {
10716 return Navigated::No;
10717 };
10718 let pane = workspace.read(cx).active_pane().clone();
10719
10720 let range = target.range.to_point(target.buffer.read(cx));
10721 let range = editor.range_for_match(&range);
10722 let range = collapse_multiline_range(range);
10723
10724 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10725 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10726 } else {
10727 window.defer(cx, move |window, cx| {
10728 let target_editor: Entity<Self> =
10729 workspace.update(cx, |workspace, cx| {
10730 let pane = if split {
10731 workspace.adjacent_pane(window, cx)
10732 } else {
10733 workspace.active_pane().clone()
10734 };
10735
10736 workspace.open_project_item(
10737 pane,
10738 target.buffer.clone(),
10739 true,
10740 true,
10741 window,
10742 cx,
10743 )
10744 });
10745 target_editor.update(cx, |target_editor, cx| {
10746 // When selecting a definition in a different buffer, disable the nav history
10747 // to avoid creating a history entry at the previous cursor location.
10748 pane.update(cx, |pane, _| pane.disable_history());
10749 target_editor.go_to_singleton_buffer_range(range, window, cx);
10750 pane.update(cx, |pane, _| pane.enable_history());
10751 });
10752 });
10753 }
10754 Navigated::Yes
10755 })
10756 })
10757 } else if !definitions.is_empty() {
10758 cx.spawn_in(window, |editor, mut cx| async move {
10759 let (title, location_tasks, workspace) = editor
10760 .update_in(&mut cx, |editor, window, cx| {
10761 let tab_kind = match kind {
10762 Some(GotoDefinitionKind::Implementation) => "Implementations",
10763 _ => "Definitions",
10764 };
10765 let title = definitions
10766 .iter()
10767 .find_map(|definition| match definition {
10768 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10769 let buffer = origin.buffer.read(cx);
10770 format!(
10771 "{} for {}",
10772 tab_kind,
10773 buffer
10774 .text_for_range(origin.range.clone())
10775 .collect::<String>()
10776 )
10777 }),
10778 HoverLink::InlayHint(_, _) => None,
10779 HoverLink::Url(_) => None,
10780 HoverLink::File(_) => None,
10781 })
10782 .unwrap_or(tab_kind.to_string());
10783 let location_tasks = definitions
10784 .into_iter()
10785 .map(|definition| match definition {
10786 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10787 HoverLink::InlayHint(lsp_location, server_id) => editor
10788 .compute_target_location(lsp_location, server_id, window, cx),
10789 HoverLink::Url(_) => Task::ready(Ok(None)),
10790 HoverLink::File(_) => Task::ready(Ok(None)),
10791 })
10792 .collect::<Vec<_>>();
10793 (title, location_tasks, editor.workspace().clone())
10794 })
10795 .context("location tasks preparation")?;
10796
10797 let locations = future::join_all(location_tasks)
10798 .await
10799 .into_iter()
10800 .filter_map(|location| location.transpose())
10801 .collect::<Result<_>>()
10802 .context("location tasks")?;
10803
10804 let Some(workspace) = workspace else {
10805 return Ok(Navigated::No);
10806 };
10807 let opened = workspace
10808 .update_in(&mut cx, |workspace, window, cx| {
10809 Self::open_locations_in_multibuffer(
10810 workspace,
10811 locations,
10812 title,
10813 split,
10814 MultibufferSelectionMode::First,
10815 window,
10816 cx,
10817 )
10818 })
10819 .ok();
10820
10821 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10822 })
10823 } else {
10824 Task::ready(Ok(Navigated::No))
10825 }
10826 }
10827
10828 fn compute_target_location(
10829 &self,
10830 lsp_location: lsp::Location,
10831 server_id: LanguageServerId,
10832 window: &mut Window,
10833 cx: &mut Context<Self>,
10834 ) -> Task<anyhow::Result<Option<Location>>> {
10835 let Some(project) = self.project.clone() else {
10836 return Task::ready(Ok(None));
10837 };
10838
10839 cx.spawn_in(window, move |editor, mut cx| async move {
10840 let location_task = editor.update(&mut cx, |_, cx| {
10841 project.update(cx, |project, cx| {
10842 let language_server_name = project
10843 .language_server_statuses(cx)
10844 .find(|(id, _)| server_id == *id)
10845 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10846 language_server_name.map(|language_server_name| {
10847 project.open_local_buffer_via_lsp(
10848 lsp_location.uri.clone(),
10849 server_id,
10850 language_server_name,
10851 cx,
10852 )
10853 })
10854 })
10855 })?;
10856 let location = match location_task {
10857 Some(task) => Some({
10858 let target_buffer_handle = task.await.context("open local buffer")?;
10859 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10860 let target_start = target_buffer
10861 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10862 let target_end = target_buffer
10863 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10864 target_buffer.anchor_after(target_start)
10865 ..target_buffer.anchor_before(target_end)
10866 })?;
10867 Location {
10868 buffer: target_buffer_handle,
10869 range,
10870 }
10871 }),
10872 None => None,
10873 };
10874 Ok(location)
10875 })
10876 }
10877
10878 pub fn find_all_references(
10879 &mut self,
10880 _: &FindAllReferences,
10881 window: &mut Window,
10882 cx: &mut Context<Self>,
10883 ) -> Option<Task<Result<Navigated>>> {
10884 let selection = self.selections.newest::<usize>(cx);
10885 let multi_buffer = self.buffer.read(cx);
10886 let head = selection.head();
10887
10888 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10889 let head_anchor = multi_buffer_snapshot.anchor_at(
10890 head,
10891 if head < selection.tail() {
10892 Bias::Right
10893 } else {
10894 Bias::Left
10895 },
10896 );
10897
10898 match self
10899 .find_all_references_task_sources
10900 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10901 {
10902 Ok(_) => {
10903 log::info!(
10904 "Ignoring repeated FindAllReferences invocation with the position of already running task"
10905 );
10906 return None;
10907 }
10908 Err(i) => {
10909 self.find_all_references_task_sources.insert(i, head_anchor);
10910 }
10911 }
10912
10913 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10914 let workspace = self.workspace()?;
10915 let project = workspace.read(cx).project().clone();
10916 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10917 Some(cx.spawn_in(window, |editor, mut cx| async move {
10918 let _cleanup = defer({
10919 let mut cx = cx.clone();
10920 move || {
10921 let _ = editor.update(&mut cx, |editor, _| {
10922 if let Ok(i) =
10923 editor
10924 .find_all_references_task_sources
10925 .binary_search_by(|anchor| {
10926 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10927 })
10928 {
10929 editor.find_all_references_task_sources.remove(i);
10930 }
10931 });
10932 }
10933 });
10934
10935 let locations = references.await?;
10936 if locations.is_empty() {
10937 return anyhow::Ok(Navigated::No);
10938 }
10939
10940 workspace.update_in(&mut cx, |workspace, window, cx| {
10941 let title = locations
10942 .first()
10943 .as_ref()
10944 .map(|location| {
10945 let buffer = location.buffer.read(cx);
10946 format!(
10947 "References to `{}`",
10948 buffer
10949 .text_for_range(location.range.clone())
10950 .collect::<String>()
10951 )
10952 })
10953 .unwrap();
10954 Self::open_locations_in_multibuffer(
10955 workspace,
10956 locations,
10957 title,
10958 false,
10959 MultibufferSelectionMode::First,
10960 window,
10961 cx,
10962 );
10963 Navigated::Yes
10964 })
10965 }))
10966 }
10967
10968 /// Opens a multibuffer with the given project locations in it
10969 pub fn open_locations_in_multibuffer(
10970 workspace: &mut Workspace,
10971 mut locations: Vec<Location>,
10972 title: String,
10973 split: bool,
10974 multibuffer_selection_mode: MultibufferSelectionMode,
10975 window: &mut Window,
10976 cx: &mut Context<Workspace>,
10977 ) {
10978 // If there are multiple definitions, open them in a multibuffer
10979 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10980 let mut locations = locations.into_iter().peekable();
10981 let mut ranges = Vec::new();
10982 let capability = workspace.project().read(cx).capability();
10983
10984 let excerpt_buffer = cx.new(|cx| {
10985 let mut multibuffer = MultiBuffer::new(capability);
10986 while let Some(location) = locations.next() {
10987 let buffer = location.buffer.read(cx);
10988 let mut ranges_for_buffer = Vec::new();
10989 let range = location.range.to_offset(buffer);
10990 ranges_for_buffer.push(range.clone());
10991
10992 while let Some(next_location) = locations.peek() {
10993 if next_location.buffer == location.buffer {
10994 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10995 locations.next();
10996 } else {
10997 break;
10998 }
10999 }
11000
11001 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11002 ranges.extend(multibuffer.push_excerpts_with_context_lines(
11003 location.buffer.clone(),
11004 ranges_for_buffer,
11005 DEFAULT_MULTIBUFFER_CONTEXT,
11006 cx,
11007 ))
11008 }
11009
11010 multibuffer.with_title(title)
11011 });
11012
11013 let editor = cx.new(|cx| {
11014 Editor::for_multibuffer(
11015 excerpt_buffer,
11016 Some(workspace.project().clone()),
11017 true,
11018 window,
11019 cx,
11020 )
11021 });
11022 editor.update(cx, |editor, cx| {
11023 match multibuffer_selection_mode {
11024 MultibufferSelectionMode::First => {
11025 if let Some(first_range) = ranges.first() {
11026 editor.change_selections(None, window, cx, |selections| {
11027 selections.clear_disjoint();
11028 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11029 });
11030 }
11031 editor.highlight_background::<Self>(
11032 &ranges,
11033 |theme| theme.editor_highlighted_line_background,
11034 cx,
11035 );
11036 }
11037 MultibufferSelectionMode::All => {
11038 editor.change_selections(None, window, cx, |selections| {
11039 selections.clear_disjoint();
11040 selections.select_anchor_ranges(ranges);
11041 });
11042 }
11043 }
11044 editor.register_buffers_with_language_servers(cx);
11045 });
11046
11047 let item = Box::new(editor);
11048 let item_id = item.item_id();
11049
11050 if split {
11051 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11052 } else {
11053 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11054 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11055 pane.close_current_preview_item(window, cx)
11056 } else {
11057 None
11058 }
11059 });
11060 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11061 }
11062 workspace.active_pane().update(cx, |pane, cx| {
11063 pane.set_preview_item_id(Some(item_id), cx);
11064 });
11065 }
11066
11067 pub fn rename(
11068 &mut self,
11069 _: &Rename,
11070 window: &mut Window,
11071 cx: &mut Context<Self>,
11072 ) -> Option<Task<Result<()>>> {
11073 use language::ToOffset as _;
11074
11075 let provider = self.semantics_provider.clone()?;
11076 let selection = self.selections.newest_anchor().clone();
11077 let (cursor_buffer, cursor_buffer_position) = self
11078 .buffer
11079 .read(cx)
11080 .text_anchor_for_position(selection.head(), cx)?;
11081 let (tail_buffer, cursor_buffer_position_end) = self
11082 .buffer
11083 .read(cx)
11084 .text_anchor_for_position(selection.tail(), cx)?;
11085 if tail_buffer != cursor_buffer {
11086 return None;
11087 }
11088
11089 let snapshot = cursor_buffer.read(cx).snapshot();
11090 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11091 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11092 let prepare_rename = provider
11093 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11094 .unwrap_or_else(|| Task::ready(Ok(None)));
11095 drop(snapshot);
11096
11097 Some(cx.spawn_in(window, |this, mut cx| async move {
11098 let rename_range = if let Some(range) = prepare_rename.await? {
11099 Some(range)
11100 } else {
11101 this.update(&mut cx, |this, cx| {
11102 let buffer = this.buffer.read(cx).snapshot(cx);
11103 let mut buffer_highlights = this
11104 .document_highlights_for_position(selection.head(), &buffer)
11105 .filter(|highlight| {
11106 highlight.start.excerpt_id == selection.head().excerpt_id
11107 && highlight.end.excerpt_id == selection.head().excerpt_id
11108 });
11109 buffer_highlights
11110 .next()
11111 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11112 })?
11113 };
11114 if let Some(rename_range) = rename_range {
11115 this.update_in(&mut cx, |this, window, cx| {
11116 let snapshot = cursor_buffer.read(cx).snapshot();
11117 let rename_buffer_range = rename_range.to_offset(&snapshot);
11118 let cursor_offset_in_rename_range =
11119 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11120 let cursor_offset_in_rename_range_end =
11121 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11122
11123 this.take_rename(false, window, cx);
11124 let buffer = this.buffer.read(cx).read(cx);
11125 let cursor_offset = selection.head().to_offset(&buffer);
11126 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11127 let rename_end = rename_start + rename_buffer_range.len();
11128 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11129 let mut old_highlight_id = None;
11130 let old_name: Arc<str> = buffer
11131 .chunks(rename_start..rename_end, true)
11132 .map(|chunk| {
11133 if old_highlight_id.is_none() {
11134 old_highlight_id = chunk.syntax_highlight_id;
11135 }
11136 chunk.text
11137 })
11138 .collect::<String>()
11139 .into();
11140
11141 drop(buffer);
11142
11143 // Position the selection in the rename editor so that it matches the current selection.
11144 this.show_local_selections = false;
11145 let rename_editor = cx.new(|cx| {
11146 let mut editor = Editor::single_line(window, cx);
11147 editor.buffer.update(cx, |buffer, cx| {
11148 buffer.edit([(0..0, old_name.clone())], None, cx)
11149 });
11150 let rename_selection_range = match cursor_offset_in_rename_range
11151 .cmp(&cursor_offset_in_rename_range_end)
11152 {
11153 Ordering::Equal => {
11154 editor.select_all(&SelectAll, window, cx);
11155 return editor;
11156 }
11157 Ordering::Less => {
11158 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11159 }
11160 Ordering::Greater => {
11161 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11162 }
11163 };
11164 if rename_selection_range.end > old_name.len() {
11165 editor.select_all(&SelectAll, window, cx);
11166 } else {
11167 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11168 s.select_ranges([rename_selection_range]);
11169 });
11170 }
11171 editor
11172 });
11173 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11174 if e == &EditorEvent::Focused {
11175 cx.emit(EditorEvent::FocusedIn)
11176 }
11177 })
11178 .detach();
11179
11180 let write_highlights =
11181 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11182 let read_highlights =
11183 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11184 let ranges = write_highlights
11185 .iter()
11186 .flat_map(|(_, ranges)| ranges.iter())
11187 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11188 .cloned()
11189 .collect();
11190
11191 this.highlight_text::<Rename>(
11192 ranges,
11193 HighlightStyle {
11194 fade_out: Some(0.6),
11195 ..Default::default()
11196 },
11197 cx,
11198 );
11199 let rename_focus_handle = rename_editor.focus_handle(cx);
11200 window.focus(&rename_focus_handle);
11201 let block_id = this.insert_blocks(
11202 [BlockProperties {
11203 style: BlockStyle::Flex,
11204 placement: BlockPlacement::Below(range.start),
11205 height: 1,
11206 render: Arc::new({
11207 let rename_editor = rename_editor.clone();
11208 move |cx: &mut BlockContext| {
11209 let mut text_style = cx.editor_style.text.clone();
11210 if let Some(highlight_style) = old_highlight_id
11211 .and_then(|h| h.style(&cx.editor_style.syntax))
11212 {
11213 text_style = text_style.highlight(highlight_style);
11214 }
11215 div()
11216 .block_mouse_down()
11217 .pl(cx.anchor_x)
11218 .child(EditorElement::new(
11219 &rename_editor,
11220 EditorStyle {
11221 background: cx.theme().system().transparent,
11222 local_player: cx.editor_style.local_player,
11223 text: text_style,
11224 scrollbar_width: cx.editor_style.scrollbar_width,
11225 syntax: cx.editor_style.syntax.clone(),
11226 status: cx.editor_style.status.clone(),
11227 inlay_hints_style: HighlightStyle {
11228 font_weight: Some(FontWeight::BOLD),
11229 ..make_inlay_hints_style(cx.app)
11230 },
11231 inline_completion_styles: make_suggestion_styles(
11232 cx.app,
11233 ),
11234 ..EditorStyle::default()
11235 },
11236 ))
11237 .into_any_element()
11238 }
11239 }),
11240 priority: 0,
11241 }],
11242 Some(Autoscroll::fit()),
11243 cx,
11244 )[0];
11245 this.pending_rename = Some(RenameState {
11246 range,
11247 old_name,
11248 editor: rename_editor,
11249 block_id,
11250 });
11251 })?;
11252 }
11253
11254 Ok(())
11255 }))
11256 }
11257
11258 pub fn confirm_rename(
11259 &mut self,
11260 _: &ConfirmRename,
11261 window: &mut Window,
11262 cx: &mut Context<Self>,
11263 ) -> Option<Task<Result<()>>> {
11264 let rename = self.take_rename(false, window, cx)?;
11265 let workspace = self.workspace()?.downgrade();
11266 let (buffer, start) = self
11267 .buffer
11268 .read(cx)
11269 .text_anchor_for_position(rename.range.start, cx)?;
11270 let (end_buffer, _) = self
11271 .buffer
11272 .read(cx)
11273 .text_anchor_for_position(rename.range.end, cx)?;
11274 if buffer != end_buffer {
11275 return None;
11276 }
11277
11278 let old_name = rename.old_name;
11279 let new_name = rename.editor.read(cx).text(cx);
11280
11281 let rename = self.semantics_provider.as_ref()?.perform_rename(
11282 &buffer,
11283 start,
11284 new_name.clone(),
11285 cx,
11286 )?;
11287
11288 Some(cx.spawn_in(window, |editor, mut cx| async move {
11289 let project_transaction = rename.await?;
11290 Self::open_project_transaction(
11291 &editor,
11292 workspace,
11293 project_transaction,
11294 format!("Rename: {} → {}", old_name, new_name),
11295 cx.clone(),
11296 )
11297 .await?;
11298
11299 editor.update(&mut cx, |editor, cx| {
11300 editor.refresh_document_highlights(cx);
11301 })?;
11302 Ok(())
11303 }))
11304 }
11305
11306 fn take_rename(
11307 &mut self,
11308 moving_cursor: bool,
11309 window: &mut Window,
11310 cx: &mut Context<Self>,
11311 ) -> Option<RenameState> {
11312 let rename = self.pending_rename.take()?;
11313 if rename.editor.focus_handle(cx).is_focused(window) {
11314 window.focus(&self.focus_handle);
11315 }
11316
11317 self.remove_blocks(
11318 [rename.block_id].into_iter().collect(),
11319 Some(Autoscroll::fit()),
11320 cx,
11321 );
11322 self.clear_highlights::<Rename>(cx);
11323 self.show_local_selections = true;
11324
11325 if moving_cursor {
11326 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11327 editor.selections.newest::<usize>(cx).head()
11328 });
11329
11330 // Update the selection to match the position of the selection inside
11331 // the rename editor.
11332 let snapshot = self.buffer.read(cx).read(cx);
11333 let rename_range = rename.range.to_offset(&snapshot);
11334 let cursor_in_editor = snapshot
11335 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11336 .min(rename_range.end);
11337 drop(snapshot);
11338
11339 self.change_selections(None, window, cx, |s| {
11340 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11341 });
11342 } else {
11343 self.refresh_document_highlights(cx);
11344 }
11345
11346 Some(rename)
11347 }
11348
11349 pub fn pending_rename(&self) -> Option<&RenameState> {
11350 self.pending_rename.as_ref()
11351 }
11352
11353 fn format(
11354 &mut self,
11355 _: &Format,
11356 window: &mut Window,
11357 cx: &mut Context<Self>,
11358 ) -> Option<Task<Result<()>>> {
11359 let project = match &self.project {
11360 Some(project) => project.clone(),
11361 None => return None,
11362 };
11363
11364 Some(self.perform_format(
11365 project,
11366 FormatTrigger::Manual,
11367 FormatTarget::Buffers,
11368 window,
11369 cx,
11370 ))
11371 }
11372
11373 fn format_selections(
11374 &mut self,
11375 _: &FormatSelections,
11376 window: &mut Window,
11377 cx: &mut Context<Self>,
11378 ) -> Option<Task<Result<()>>> {
11379 let project = match &self.project {
11380 Some(project) => project.clone(),
11381 None => return None,
11382 };
11383
11384 let ranges = self
11385 .selections
11386 .all_adjusted(cx)
11387 .into_iter()
11388 .map(|selection| selection.range())
11389 .collect_vec();
11390
11391 Some(self.perform_format(
11392 project,
11393 FormatTrigger::Manual,
11394 FormatTarget::Ranges(ranges),
11395 window,
11396 cx,
11397 ))
11398 }
11399
11400 fn perform_format(
11401 &mut self,
11402 project: Entity<Project>,
11403 trigger: FormatTrigger,
11404 target: FormatTarget,
11405 window: &mut Window,
11406 cx: &mut Context<Self>,
11407 ) -> Task<Result<()>> {
11408 let buffer = self.buffer.clone();
11409 let (buffers, target) = match target {
11410 FormatTarget::Buffers => {
11411 let mut buffers = buffer.read(cx).all_buffers();
11412 if trigger == FormatTrigger::Save {
11413 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11414 }
11415 (buffers, LspFormatTarget::Buffers)
11416 }
11417 FormatTarget::Ranges(selection_ranges) => {
11418 let multi_buffer = buffer.read(cx);
11419 let snapshot = multi_buffer.read(cx);
11420 let mut buffers = HashSet::default();
11421 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11422 BTreeMap::new();
11423 for selection_range in selection_ranges {
11424 for (buffer, buffer_range, _) in
11425 snapshot.range_to_buffer_ranges(selection_range)
11426 {
11427 let buffer_id = buffer.remote_id();
11428 let start = buffer.anchor_before(buffer_range.start);
11429 let end = buffer.anchor_after(buffer_range.end);
11430 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11431 buffer_id_to_ranges
11432 .entry(buffer_id)
11433 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11434 .or_insert_with(|| vec![start..end]);
11435 }
11436 }
11437 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11438 }
11439 };
11440
11441 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11442 let format = project.update(cx, |project, cx| {
11443 project.format(buffers, target, true, trigger, cx)
11444 });
11445
11446 cx.spawn_in(window, |_, mut cx| async move {
11447 let transaction = futures::select_biased! {
11448 () = timeout => {
11449 log::warn!("timed out waiting for formatting");
11450 None
11451 }
11452 transaction = format.log_err().fuse() => transaction,
11453 };
11454
11455 buffer
11456 .update(&mut cx, |buffer, cx| {
11457 if let Some(transaction) = transaction {
11458 if !buffer.is_singleton() {
11459 buffer.push_transaction(&transaction.0, cx);
11460 }
11461 }
11462
11463 cx.notify();
11464 })
11465 .ok();
11466
11467 Ok(())
11468 })
11469 }
11470
11471 fn restart_language_server(
11472 &mut self,
11473 _: &RestartLanguageServer,
11474 _: &mut Window,
11475 cx: &mut Context<Self>,
11476 ) {
11477 if let Some(project) = self.project.clone() {
11478 self.buffer.update(cx, |multi_buffer, cx| {
11479 project.update(cx, |project, cx| {
11480 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11481 });
11482 })
11483 }
11484 }
11485
11486 fn cancel_language_server_work(
11487 workspace: &mut Workspace,
11488 _: &actions::CancelLanguageServerWork,
11489 _: &mut Window,
11490 cx: &mut Context<Workspace>,
11491 ) {
11492 let project = workspace.project();
11493 let buffers = workspace
11494 .active_item(cx)
11495 .and_then(|item| item.act_as::<Editor>(cx))
11496 .map_or(HashSet::default(), |editor| {
11497 editor.read(cx).buffer.read(cx).all_buffers()
11498 });
11499 project.update(cx, |project, cx| {
11500 project.cancel_language_server_work_for_buffers(buffers, cx);
11501 });
11502 }
11503
11504 fn show_character_palette(
11505 &mut self,
11506 _: &ShowCharacterPalette,
11507 window: &mut Window,
11508 _: &mut Context<Self>,
11509 ) {
11510 window.show_character_palette();
11511 }
11512
11513 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11514 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11515 let buffer = self.buffer.read(cx).snapshot(cx);
11516 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11517 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11518 let is_valid = buffer
11519 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11520 .any(|entry| {
11521 entry.diagnostic.is_primary
11522 && !entry.range.is_empty()
11523 && entry.range.start == primary_range_start
11524 && entry.diagnostic.message == active_diagnostics.primary_message
11525 });
11526
11527 if is_valid != active_diagnostics.is_valid {
11528 active_diagnostics.is_valid = is_valid;
11529 let mut new_styles = HashMap::default();
11530 for (block_id, diagnostic) in &active_diagnostics.blocks {
11531 new_styles.insert(
11532 *block_id,
11533 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11534 );
11535 }
11536 self.display_map.update(cx, |display_map, _cx| {
11537 display_map.replace_blocks(new_styles)
11538 });
11539 }
11540 }
11541 }
11542
11543 fn activate_diagnostics(
11544 &mut self,
11545 buffer_id: BufferId,
11546 group_id: usize,
11547 window: &mut Window,
11548 cx: &mut Context<Self>,
11549 ) {
11550 self.dismiss_diagnostics(cx);
11551 let snapshot = self.snapshot(window, cx);
11552 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11553 let buffer = self.buffer.read(cx).snapshot(cx);
11554
11555 let mut primary_range = None;
11556 let mut primary_message = None;
11557 let diagnostic_group = buffer
11558 .diagnostic_group(buffer_id, group_id)
11559 .filter_map(|entry| {
11560 let start = entry.range.start;
11561 let end = entry.range.end;
11562 if snapshot.is_line_folded(MultiBufferRow(start.row))
11563 && (start.row == end.row
11564 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11565 {
11566 return None;
11567 }
11568 if entry.diagnostic.is_primary {
11569 primary_range = Some(entry.range.clone());
11570 primary_message = Some(entry.diagnostic.message.clone());
11571 }
11572 Some(entry)
11573 })
11574 .collect::<Vec<_>>();
11575 let primary_range = primary_range?;
11576 let primary_message = primary_message?;
11577
11578 let blocks = display_map
11579 .insert_blocks(
11580 diagnostic_group.iter().map(|entry| {
11581 let diagnostic = entry.diagnostic.clone();
11582 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11583 BlockProperties {
11584 style: BlockStyle::Fixed,
11585 placement: BlockPlacement::Below(
11586 buffer.anchor_after(entry.range.start),
11587 ),
11588 height: message_height,
11589 render: diagnostic_block_renderer(diagnostic, None, true, true),
11590 priority: 0,
11591 }
11592 }),
11593 cx,
11594 )
11595 .into_iter()
11596 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11597 .collect();
11598
11599 Some(ActiveDiagnosticGroup {
11600 primary_range: buffer.anchor_before(primary_range.start)
11601 ..buffer.anchor_after(primary_range.end),
11602 primary_message,
11603 group_id,
11604 blocks,
11605 is_valid: true,
11606 })
11607 });
11608 }
11609
11610 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11611 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11612 self.display_map.update(cx, |display_map, cx| {
11613 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11614 });
11615 cx.notify();
11616 }
11617 }
11618
11619 pub fn set_selections_from_remote(
11620 &mut self,
11621 selections: Vec<Selection<Anchor>>,
11622 pending_selection: Option<Selection<Anchor>>,
11623 window: &mut Window,
11624 cx: &mut Context<Self>,
11625 ) {
11626 let old_cursor_position = self.selections.newest_anchor().head();
11627 self.selections.change_with(cx, |s| {
11628 s.select_anchors(selections);
11629 if let Some(pending_selection) = pending_selection {
11630 s.set_pending(pending_selection, SelectMode::Character);
11631 } else {
11632 s.clear_pending();
11633 }
11634 });
11635 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11636 }
11637
11638 fn push_to_selection_history(&mut self) {
11639 self.selection_history.push(SelectionHistoryEntry {
11640 selections: self.selections.disjoint_anchors(),
11641 select_next_state: self.select_next_state.clone(),
11642 select_prev_state: self.select_prev_state.clone(),
11643 add_selections_state: self.add_selections_state.clone(),
11644 });
11645 }
11646
11647 pub fn transact(
11648 &mut self,
11649 window: &mut Window,
11650 cx: &mut Context<Self>,
11651 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11652 ) -> Option<TransactionId> {
11653 self.start_transaction_at(Instant::now(), window, cx);
11654 update(self, window, cx);
11655 self.end_transaction_at(Instant::now(), cx)
11656 }
11657
11658 pub fn start_transaction_at(
11659 &mut self,
11660 now: Instant,
11661 window: &mut Window,
11662 cx: &mut Context<Self>,
11663 ) {
11664 self.end_selection(window, cx);
11665 if let Some(tx_id) = self
11666 .buffer
11667 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11668 {
11669 self.selection_history
11670 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11671 cx.emit(EditorEvent::TransactionBegun {
11672 transaction_id: tx_id,
11673 })
11674 }
11675 }
11676
11677 pub fn end_transaction_at(
11678 &mut self,
11679 now: Instant,
11680 cx: &mut Context<Self>,
11681 ) -> Option<TransactionId> {
11682 if let Some(transaction_id) = self
11683 .buffer
11684 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11685 {
11686 if let Some((_, end_selections)) =
11687 self.selection_history.transaction_mut(transaction_id)
11688 {
11689 *end_selections = Some(self.selections.disjoint_anchors());
11690 } else {
11691 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11692 }
11693
11694 cx.emit(EditorEvent::Edited { transaction_id });
11695 Some(transaction_id)
11696 } else {
11697 None
11698 }
11699 }
11700
11701 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11702 if self.selection_mark_mode {
11703 self.change_selections(None, window, cx, |s| {
11704 s.move_with(|_, sel| {
11705 sel.collapse_to(sel.head(), SelectionGoal::None);
11706 });
11707 })
11708 }
11709 self.selection_mark_mode = true;
11710 cx.notify();
11711 }
11712
11713 pub fn swap_selection_ends(
11714 &mut self,
11715 _: &actions::SwapSelectionEnds,
11716 window: &mut Window,
11717 cx: &mut Context<Self>,
11718 ) {
11719 self.change_selections(None, window, cx, |s| {
11720 s.move_with(|_, sel| {
11721 if sel.start != sel.end {
11722 sel.reversed = !sel.reversed
11723 }
11724 });
11725 });
11726 self.request_autoscroll(Autoscroll::newest(), cx);
11727 cx.notify();
11728 }
11729
11730 pub fn toggle_fold(
11731 &mut self,
11732 _: &actions::ToggleFold,
11733 window: &mut Window,
11734 cx: &mut Context<Self>,
11735 ) {
11736 if self.is_singleton(cx) {
11737 let selection = self.selections.newest::<Point>(cx);
11738
11739 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11740 let range = if selection.is_empty() {
11741 let point = selection.head().to_display_point(&display_map);
11742 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11743 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11744 .to_point(&display_map);
11745 start..end
11746 } else {
11747 selection.range()
11748 };
11749 if display_map.folds_in_range(range).next().is_some() {
11750 self.unfold_lines(&Default::default(), window, cx)
11751 } else {
11752 self.fold(&Default::default(), window, cx)
11753 }
11754 } else {
11755 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11756 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11757 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11758 .map(|(snapshot, _, _)| snapshot.remote_id())
11759 .collect();
11760
11761 for buffer_id in buffer_ids {
11762 if self.is_buffer_folded(buffer_id, cx) {
11763 self.unfold_buffer(buffer_id, cx);
11764 } else {
11765 self.fold_buffer(buffer_id, cx);
11766 }
11767 }
11768 }
11769 }
11770
11771 pub fn toggle_fold_recursive(
11772 &mut self,
11773 _: &actions::ToggleFoldRecursive,
11774 window: &mut Window,
11775 cx: &mut Context<Self>,
11776 ) {
11777 let selection = self.selections.newest::<Point>(cx);
11778
11779 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11780 let range = if selection.is_empty() {
11781 let point = selection.head().to_display_point(&display_map);
11782 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11783 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11784 .to_point(&display_map);
11785 start..end
11786 } else {
11787 selection.range()
11788 };
11789 if display_map.folds_in_range(range).next().is_some() {
11790 self.unfold_recursive(&Default::default(), window, cx)
11791 } else {
11792 self.fold_recursive(&Default::default(), window, cx)
11793 }
11794 }
11795
11796 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11797 if self.is_singleton(cx) {
11798 let mut to_fold = Vec::new();
11799 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11800 let selections = self.selections.all_adjusted(cx);
11801
11802 for selection in selections {
11803 let range = selection.range().sorted();
11804 let buffer_start_row = range.start.row;
11805
11806 if range.start.row != range.end.row {
11807 let mut found = false;
11808 let mut row = range.start.row;
11809 while row <= range.end.row {
11810 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11811 {
11812 found = true;
11813 row = crease.range().end.row + 1;
11814 to_fold.push(crease);
11815 } else {
11816 row += 1
11817 }
11818 }
11819 if found {
11820 continue;
11821 }
11822 }
11823
11824 for row in (0..=range.start.row).rev() {
11825 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11826 if crease.range().end.row >= buffer_start_row {
11827 to_fold.push(crease);
11828 if row <= range.start.row {
11829 break;
11830 }
11831 }
11832 }
11833 }
11834 }
11835
11836 self.fold_creases(to_fold, true, window, cx);
11837 } else {
11838 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11839
11840 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11841 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11842 .map(|(snapshot, _, _)| snapshot.remote_id())
11843 .collect();
11844 for buffer_id in buffer_ids {
11845 self.fold_buffer(buffer_id, cx);
11846 }
11847 }
11848 }
11849
11850 fn fold_at_level(
11851 &mut self,
11852 fold_at: &FoldAtLevel,
11853 window: &mut Window,
11854 cx: &mut Context<Self>,
11855 ) {
11856 if !self.buffer.read(cx).is_singleton() {
11857 return;
11858 }
11859
11860 let fold_at_level = fold_at.0;
11861 let snapshot = self.buffer.read(cx).snapshot(cx);
11862 let mut to_fold = Vec::new();
11863 let mut stack = vec![(0, snapshot.max_row().0, 1)];
11864
11865 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11866 while start_row < end_row {
11867 match self
11868 .snapshot(window, cx)
11869 .crease_for_buffer_row(MultiBufferRow(start_row))
11870 {
11871 Some(crease) => {
11872 let nested_start_row = crease.range().start.row + 1;
11873 let nested_end_row = crease.range().end.row;
11874
11875 if current_level < fold_at_level {
11876 stack.push((nested_start_row, nested_end_row, current_level + 1));
11877 } else if current_level == fold_at_level {
11878 to_fold.push(crease);
11879 }
11880
11881 start_row = nested_end_row + 1;
11882 }
11883 None => start_row += 1,
11884 }
11885 }
11886 }
11887
11888 self.fold_creases(to_fold, true, window, cx);
11889 }
11890
11891 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11892 if self.buffer.read(cx).is_singleton() {
11893 let mut fold_ranges = Vec::new();
11894 let snapshot = self.buffer.read(cx).snapshot(cx);
11895
11896 for row in 0..snapshot.max_row().0 {
11897 if let Some(foldable_range) = self
11898 .snapshot(window, cx)
11899 .crease_for_buffer_row(MultiBufferRow(row))
11900 {
11901 fold_ranges.push(foldable_range);
11902 }
11903 }
11904
11905 self.fold_creases(fold_ranges, true, window, cx);
11906 } else {
11907 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11908 editor
11909 .update_in(&mut cx, |editor, _, cx| {
11910 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11911 editor.fold_buffer(buffer_id, cx);
11912 }
11913 })
11914 .ok();
11915 });
11916 }
11917 }
11918
11919 pub fn fold_function_bodies(
11920 &mut self,
11921 _: &actions::FoldFunctionBodies,
11922 window: &mut Window,
11923 cx: &mut Context<Self>,
11924 ) {
11925 let snapshot = self.buffer.read(cx).snapshot(cx);
11926
11927 let ranges = snapshot
11928 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11929 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11930 .collect::<Vec<_>>();
11931
11932 let creases = ranges
11933 .into_iter()
11934 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11935 .collect();
11936
11937 self.fold_creases(creases, true, window, cx);
11938 }
11939
11940 pub fn fold_recursive(
11941 &mut self,
11942 _: &actions::FoldRecursive,
11943 window: &mut Window,
11944 cx: &mut Context<Self>,
11945 ) {
11946 let mut to_fold = Vec::new();
11947 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11948 let selections = self.selections.all_adjusted(cx);
11949
11950 for selection in selections {
11951 let range = selection.range().sorted();
11952 let buffer_start_row = range.start.row;
11953
11954 if range.start.row != range.end.row {
11955 let mut found = false;
11956 for row in range.start.row..=range.end.row {
11957 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11958 found = true;
11959 to_fold.push(crease);
11960 }
11961 }
11962 if found {
11963 continue;
11964 }
11965 }
11966
11967 for row in (0..=range.start.row).rev() {
11968 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11969 if crease.range().end.row >= buffer_start_row {
11970 to_fold.push(crease);
11971 } else {
11972 break;
11973 }
11974 }
11975 }
11976 }
11977
11978 self.fold_creases(to_fold, true, window, cx);
11979 }
11980
11981 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11982 let buffer_row = fold_at.buffer_row;
11983 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11984
11985 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11986 let autoscroll = self
11987 .selections
11988 .all::<Point>(cx)
11989 .iter()
11990 .any(|selection| crease.range().overlaps(&selection.range()));
11991
11992 self.fold_creases(vec![crease], autoscroll, window, cx);
11993 }
11994 }
11995
11996 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
11997 if self.is_singleton(cx) {
11998 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11999 let buffer = &display_map.buffer_snapshot;
12000 let selections = self.selections.all::<Point>(cx);
12001 let ranges = selections
12002 .iter()
12003 .map(|s| {
12004 let range = s.display_range(&display_map).sorted();
12005 let mut start = range.start.to_point(&display_map);
12006 let mut end = range.end.to_point(&display_map);
12007 start.column = 0;
12008 end.column = buffer.line_len(MultiBufferRow(end.row));
12009 start..end
12010 })
12011 .collect::<Vec<_>>();
12012
12013 self.unfold_ranges(&ranges, true, true, cx);
12014 } else {
12015 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12016 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12017 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12018 .map(|(snapshot, _, _)| snapshot.remote_id())
12019 .collect();
12020 for buffer_id in buffer_ids {
12021 self.unfold_buffer(buffer_id, cx);
12022 }
12023 }
12024 }
12025
12026 pub fn unfold_recursive(
12027 &mut self,
12028 _: &UnfoldRecursive,
12029 _window: &mut Window,
12030 cx: &mut Context<Self>,
12031 ) {
12032 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12033 let selections = self.selections.all::<Point>(cx);
12034 let ranges = selections
12035 .iter()
12036 .map(|s| {
12037 let mut range = s.display_range(&display_map).sorted();
12038 *range.start.column_mut() = 0;
12039 *range.end.column_mut() = display_map.line_len(range.end.row());
12040 let start = range.start.to_point(&display_map);
12041 let end = range.end.to_point(&display_map);
12042 start..end
12043 })
12044 .collect::<Vec<_>>();
12045
12046 self.unfold_ranges(&ranges, true, true, cx);
12047 }
12048
12049 pub fn unfold_at(
12050 &mut self,
12051 unfold_at: &UnfoldAt,
12052 _window: &mut Window,
12053 cx: &mut Context<Self>,
12054 ) {
12055 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12056
12057 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12058 ..Point::new(
12059 unfold_at.buffer_row.0,
12060 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12061 );
12062
12063 let autoscroll = self
12064 .selections
12065 .all::<Point>(cx)
12066 .iter()
12067 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12068
12069 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12070 }
12071
12072 pub fn unfold_all(
12073 &mut self,
12074 _: &actions::UnfoldAll,
12075 _window: &mut Window,
12076 cx: &mut Context<Self>,
12077 ) {
12078 if self.buffer.read(cx).is_singleton() {
12079 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12080 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12081 } else {
12082 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12083 editor
12084 .update(&mut cx, |editor, cx| {
12085 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12086 editor.unfold_buffer(buffer_id, cx);
12087 }
12088 })
12089 .ok();
12090 });
12091 }
12092 }
12093
12094 pub fn fold_selected_ranges(
12095 &mut self,
12096 _: &FoldSelectedRanges,
12097 window: &mut Window,
12098 cx: &mut Context<Self>,
12099 ) {
12100 let selections = self.selections.all::<Point>(cx);
12101 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12102 let line_mode = self.selections.line_mode;
12103 let ranges = selections
12104 .into_iter()
12105 .map(|s| {
12106 if line_mode {
12107 let start = Point::new(s.start.row, 0);
12108 let end = Point::new(
12109 s.end.row,
12110 display_map
12111 .buffer_snapshot
12112 .line_len(MultiBufferRow(s.end.row)),
12113 );
12114 Crease::simple(start..end, display_map.fold_placeholder.clone())
12115 } else {
12116 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12117 }
12118 })
12119 .collect::<Vec<_>>();
12120 self.fold_creases(ranges, true, window, cx);
12121 }
12122
12123 pub fn fold_ranges<T: ToOffset + Clone>(
12124 &mut self,
12125 ranges: Vec<Range<T>>,
12126 auto_scroll: bool,
12127 window: &mut Window,
12128 cx: &mut Context<Self>,
12129 ) {
12130 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12131 let ranges = ranges
12132 .into_iter()
12133 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12134 .collect::<Vec<_>>();
12135 self.fold_creases(ranges, auto_scroll, window, cx);
12136 }
12137
12138 pub fn fold_creases<T: ToOffset + Clone>(
12139 &mut self,
12140 creases: Vec<Crease<T>>,
12141 auto_scroll: bool,
12142 window: &mut Window,
12143 cx: &mut Context<Self>,
12144 ) {
12145 if creases.is_empty() {
12146 return;
12147 }
12148
12149 let mut buffers_affected = HashSet::default();
12150 let multi_buffer = self.buffer().read(cx);
12151 for crease in &creases {
12152 if let Some((_, buffer, _)) =
12153 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12154 {
12155 buffers_affected.insert(buffer.read(cx).remote_id());
12156 };
12157 }
12158
12159 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12160
12161 if auto_scroll {
12162 self.request_autoscroll(Autoscroll::fit(), cx);
12163 }
12164
12165 cx.notify();
12166
12167 if let Some(active_diagnostics) = self.active_diagnostics.take() {
12168 // Clear diagnostics block when folding a range that contains it.
12169 let snapshot = self.snapshot(window, cx);
12170 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12171 drop(snapshot);
12172 self.active_diagnostics = Some(active_diagnostics);
12173 self.dismiss_diagnostics(cx);
12174 } else {
12175 self.active_diagnostics = Some(active_diagnostics);
12176 }
12177 }
12178
12179 self.scrollbar_marker_state.dirty = true;
12180 }
12181
12182 /// Removes any folds whose ranges intersect any of the given ranges.
12183 pub fn unfold_ranges<T: ToOffset + Clone>(
12184 &mut self,
12185 ranges: &[Range<T>],
12186 inclusive: bool,
12187 auto_scroll: bool,
12188 cx: &mut Context<Self>,
12189 ) {
12190 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12191 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12192 });
12193 }
12194
12195 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12196 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12197 return;
12198 }
12199 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12200 self.display_map
12201 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12202 cx.emit(EditorEvent::BufferFoldToggled {
12203 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12204 folded: true,
12205 });
12206 cx.notify();
12207 }
12208
12209 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12210 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12211 return;
12212 }
12213 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12214 self.display_map.update(cx, |display_map, cx| {
12215 display_map.unfold_buffer(buffer_id, cx);
12216 });
12217 cx.emit(EditorEvent::BufferFoldToggled {
12218 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12219 folded: false,
12220 });
12221 cx.notify();
12222 }
12223
12224 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12225 self.display_map.read(cx).is_buffer_folded(buffer)
12226 }
12227
12228 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12229 self.display_map.read(cx).folded_buffers()
12230 }
12231
12232 /// Removes any folds with the given ranges.
12233 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12234 &mut self,
12235 ranges: &[Range<T>],
12236 type_id: TypeId,
12237 auto_scroll: bool,
12238 cx: &mut Context<Self>,
12239 ) {
12240 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12241 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12242 });
12243 }
12244
12245 fn remove_folds_with<T: ToOffset + Clone>(
12246 &mut self,
12247 ranges: &[Range<T>],
12248 auto_scroll: bool,
12249 cx: &mut Context<Self>,
12250 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12251 ) {
12252 if ranges.is_empty() {
12253 return;
12254 }
12255
12256 let mut buffers_affected = HashSet::default();
12257 let multi_buffer = self.buffer().read(cx);
12258 for range in ranges {
12259 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12260 buffers_affected.insert(buffer.read(cx).remote_id());
12261 };
12262 }
12263
12264 self.display_map.update(cx, update);
12265
12266 if auto_scroll {
12267 self.request_autoscroll(Autoscroll::fit(), cx);
12268 }
12269
12270 cx.notify();
12271 self.scrollbar_marker_state.dirty = true;
12272 self.active_indent_guides_state.dirty = true;
12273 }
12274
12275 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12276 self.display_map.read(cx).fold_placeholder.clone()
12277 }
12278
12279 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12280 self.buffer.update(cx, |buffer, cx| {
12281 buffer.set_all_diff_hunks_expanded(cx);
12282 });
12283 }
12284
12285 pub fn expand_all_diff_hunks(
12286 &mut self,
12287 _: &ExpandAllHunkDiffs,
12288 _window: &mut Window,
12289 cx: &mut Context<Self>,
12290 ) {
12291 self.buffer.update(cx, |buffer, cx| {
12292 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12293 });
12294 }
12295
12296 pub fn toggle_selected_diff_hunks(
12297 &mut self,
12298 _: &ToggleSelectedDiffHunks,
12299 _window: &mut Window,
12300 cx: &mut Context<Self>,
12301 ) {
12302 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12303 self.toggle_diff_hunks_in_ranges(ranges, cx);
12304 }
12305
12306 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12307 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12308 self.buffer
12309 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12310 }
12311
12312 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12313 self.buffer.update(cx, |buffer, cx| {
12314 let ranges = vec![Anchor::min()..Anchor::max()];
12315 if !buffer.all_diff_hunks_expanded()
12316 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12317 {
12318 buffer.collapse_diff_hunks(ranges, cx);
12319 true
12320 } else {
12321 false
12322 }
12323 })
12324 }
12325
12326 fn toggle_diff_hunks_in_ranges(
12327 &mut self,
12328 ranges: Vec<Range<Anchor>>,
12329 cx: &mut Context<'_, Editor>,
12330 ) {
12331 self.buffer.update(cx, |buffer, cx| {
12332 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12333 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12334 })
12335 }
12336
12337 fn toggle_diff_hunks_in_ranges_narrow(
12338 &mut self,
12339 ranges: Vec<Range<Anchor>>,
12340 cx: &mut Context<'_, Editor>,
12341 ) {
12342 self.buffer.update(cx, |buffer, cx| {
12343 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12344 buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12345 })
12346 }
12347
12348 pub(crate) fn apply_all_diff_hunks(
12349 &mut self,
12350 _: &ApplyAllDiffHunks,
12351 window: &mut Window,
12352 cx: &mut Context<Self>,
12353 ) {
12354 let buffers = self.buffer.read(cx).all_buffers();
12355 for branch_buffer in buffers {
12356 branch_buffer.update(cx, |branch_buffer, cx| {
12357 branch_buffer.merge_into_base(Vec::new(), cx);
12358 });
12359 }
12360
12361 if let Some(project) = self.project.clone() {
12362 self.save(true, project, window, cx).detach_and_log_err(cx);
12363 }
12364 }
12365
12366 pub(crate) fn apply_selected_diff_hunks(
12367 &mut self,
12368 _: &ApplyDiffHunk,
12369 window: &mut Window,
12370 cx: &mut Context<Self>,
12371 ) {
12372 let snapshot = self.snapshot(window, cx);
12373 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12374 let mut ranges_by_buffer = HashMap::default();
12375 self.transact(window, cx, |editor, _window, cx| {
12376 for hunk in hunks {
12377 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12378 ranges_by_buffer
12379 .entry(buffer.clone())
12380 .or_insert_with(Vec::new)
12381 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12382 }
12383 }
12384
12385 for (buffer, ranges) in ranges_by_buffer {
12386 buffer.update(cx, |buffer, cx| {
12387 buffer.merge_into_base(ranges, cx);
12388 });
12389 }
12390 });
12391
12392 if let Some(project) = self.project.clone() {
12393 self.save(true, project, window, cx).detach_and_log_err(cx);
12394 }
12395 }
12396
12397 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12398 if hovered != self.gutter_hovered {
12399 self.gutter_hovered = hovered;
12400 cx.notify();
12401 }
12402 }
12403
12404 pub fn insert_blocks(
12405 &mut self,
12406 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12407 autoscroll: Option<Autoscroll>,
12408 cx: &mut Context<Self>,
12409 ) -> Vec<CustomBlockId> {
12410 let blocks = self
12411 .display_map
12412 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12413 if let Some(autoscroll) = autoscroll {
12414 self.request_autoscroll(autoscroll, cx);
12415 }
12416 cx.notify();
12417 blocks
12418 }
12419
12420 pub fn resize_blocks(
12421 &mut self,
12422 heights: HashMap<CustomBlockId, u32>,
12423 autoscroll: Option<Autoscroll>,
12424 cx: &mut Context<Self>,
12425 ) {
12426 self.display_map
12427 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12428 if let Some(autoscroll) = autoscroll {
12429 self.request_autoscroll(autoscroll, cx);
12430 }
12431 cx.notify();
12432 }
12433
12434 pub fn replace_blocks(
12435 &mut self,
12436 renderers: HashMap<CustomBlockId, RenderBlock>,
12437 autoscroll: Option<Autoscroll>,
12438 cx: &mut Context<Self>,
12439 ) {
12440 self.display_map
12441 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12442 if let Some(autoscroll) = autoscroll {
12443 self.request_autoscroll(autoscroll, cx);
12444 }
12445 cx.notify();
12446 }
12447
12448 pub fn remove_blocks(
12449 &mut self,
12450 block_ids: HashSet<CustomBlockId>,
12451 autoscroll: Option<Autoscroll>,
12452 cx: &mut Context<Self>,
12453 ) {
12454 self.display_map.update(cx, |display_map, cx| {
12455 display_map.remove_blocks(block_ids, cx)
12456 });
12457 if let Some(autoscroll) = autoscroll {
12458 self.request_autoscroll(autoscroll, cx);
12459 }
12460 cx.notify();
12461 }
12462
12463 pub fn row_for_block(
12464 &self,
12465 block_id: CustomBlockId,
12466 cx: &mut Context<Self>,
12467 ) -> Option<DisplayRow> {
12468 self.display_map
12469 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12470 }
12471
12472 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12473 self.focused_block = Some(focused_block);
12474 }
12475
12476 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12477 self.focused_block.take()
12478 }
12479
12480 pub fn insert_creases(
12481 &mut self,
12482 creases: impl IntoIterator<Item = Crease<Anchor>>,
12483 cx: &mut Context<Self>,
12484 ) -> Vec<CreaseId> {
12485 self.display_map
12486 .update(cx, |map, cx| map.insert_creases(creases, cx))
12487 }
12488
12489 pub fn remove_creases(
12490 &mut self,
12491 ids: impl IntoIterator<Item = CreaseId>,
12492 cx: &mut Context<Self>,
12493 ) {
12494 self.display_map
12495 .update(cx, |map, cx| map.remove_creases(ids, cx));
12496 }
12497
12498 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12499 self.display_map
12500 .update(cx, |map, cx| map.snapshot(cx))
12501 .longest_row()
12502 }
12503
12504 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12505 self.display_map
12506 .update(cx, |map, cx| map.snapshot(cx))
12507 .max_point()
12508 }
12509
12510 pub fn text(&self, cx: &App) -> String {
12511 self.buffer.read(cx).read(cx).text()
12512 }
12513
12514 pub fn is_empty(&self, cx: &App) -> bool {
12515 self.buffer.read(cx).read(cx).is_empty()
12516 }
12517
12518 pub fn text_option(&self, cx: &App) -> Option<String> {
12519 let text = self.text(cx);
12520 let text = text.trim();
12521
12522 if text.is_empty() {
12523 return None;
12524 }
12525
12526 Some(text.to_string())
12527 }
12528
12529 pub fn set_text(
12530 &mut self,
12531 text: impl Into<Arc<str>>,
12532 window: &mut Window,
12533 cx: &mut Context<Self>,
12534 ) {
12535 self.transact(window, cx, |this, _, cx| {
12536 this.buffer
12537 .read(cx)
12538 .as_singleton()
12539 .expect("you can only call set_text on editors for singleton buffers")
12540 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12541 });
12542 }
12543
12544 pub fn display_text(&self, cx: &mut App) -> String {
12545 self.display_map
12546 .update(cx, |map, cx| map.snapshot(cx))
12547 .text()
12548 }
12549
12550 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12551 let mut wrap_guides = smallvec::smallvec![];
12552
12553 if self.show_wrap_guides == Some(false) {
12554 return wrap_guides;
12555 }
12556
12557 let settings = self.buffer.read(cx).settings_at(0, cx);
12558 if settings.show_wrap_guides {
12559 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12560 wrap_guides.push((soft_wrap as usize, true));
12561 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12562 wrap_guides.push((soft_wrap as usize, true));
12563 }
12564 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12565 }
12566
12567 wrap_guides
12568 }
12569
12570 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12571 let settings = self.buffer.read(cx).settings_at(0, cx);
12572 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12573 match mode {
12574 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12575 SoftWrap::None
12576 }
12577 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12578 language_settings::SoftWrap::PreferredLineLength => {
12579 SoftWrap::Column(settings.preferred_line_length)
12580 }
12581 language_settings::SoftWrap::Bounded => {
12582 SoftWrap::Bounded(settings.preferred_line_length)
12583 }
12584 }
12585 }
12586
12587 pub fn set_soft_wrap_mode(
12588 &mut self,
12589 mode: language_settings::SoftWrap,
12590
12591 cx: &mut Context<Self>,
12592 ) {
12593 self.soft_wrap_mode_override = Some(mode);
12594 cx.notify();
12595 }
12596
12597 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12598 self.text_style_refinement = Some(style);
12599 }
12600
12601 /// called by the Element so we know what style we were most recently rendered with.
12602 pub(crate) fn set_style(
12603 &mut self,
12604 style: EditorStyle,
12605 window: &mut Window,
12606 cx: &mut Context<Self>,
12607 ) {
12608 let rem_size = window.rem_size();
12609 self.display_map.update(cx, |map, cx| {
12610 map.set_font(
12611 style.text.font(),
12612 style.text.font_size.to_pixels(rem_size),
12613 cx,
12614 )
12615 });
12616 self.style = Some(style);
12617 }
12618
12619 pub fn style(&self) -> Option<&EditorStyle> {
12620 self.style.as_ref()
12621 }
12622
12623 // Called by the element. This method is not designed to be called outside of the editor
12624 // element's layout code because it does not notify when rewrapping is computed synchronously.
12625 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12626 self.display_map
12627 .update(cx, |map, cx| map.set_wrap_width(width, cx))
12628 }
12629
12630 pub fn set_soft_wrap(&mut self) {
12631 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12632 }
12633
12634 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12635 if self.soft_wrap_mode_override.is_some() {
12636 self.soft_wrap_mode_override.take();
12637 } else {
12638 let soft_wrap = match self.soft_wrap_mode(cx) {
12639 SoftWrap::GitDiff => return,
12640 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12641 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12642 language_settings::SoftWrap::None
12643 }
12644 };
12645 self.soft_wrap_mode_override = Some(soft_wrap);
12646 }
12647 cx.notify();
12648 }
12649
12650 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12651 let Some(workspace) = self.workspace() else {
12652 return;
12653 };
12654 let fs = workspace.read(cx).app_state().fs.clone();
12655 let current_show = TabBarSettings::get_global(cx).show;
12656 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12657 setting.show = Some(!current_show);
12658 });
12659 }
12660
12661 pub fn toggle_indent_guides(
12662 &mut self,
12663 _: &ToggleIndentGuides,
12664 _: &mut Window,
12665 cx: &mut Context<Self>,
12666 ) {
12667 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12668 self.buffer
12669 .read(cx)
12670 .settings_at(0, cx)
12671 .indent_guides
12672 .enabled
12673 });
12674 self.show_indent_guides = Some(!currently_enabled);
12675 cx.notify();
12676 }
12677
12678 fn should_show_indent_guides(&self) -> Option<bool> {
12679 self.show_indent_guides
12680 }
12681
12682 pub fn toggle_line_numbers(
12683 &mut self,
12684 _: &ToggleLineNumbers,
12685 _: &mut Window,
12686 cx: &mut Context<Self>,
12687 ) {
12688 let mut editor_settings = EditorSettings::get_global(cx).clone();
12689 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12690 EditorSettings::override_global(editor_settings, cx);
12691 }
12692
12693 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12694 self.use_relative_line_numbers
12695 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12696 }
12697
12698 pub fn toggle_relative_line_numbers(
12699 &mut self,
12700 _: &ToggleRelativeLineNumbers,
12701 _: &mut Window,
12702 cx: &mut Context<Self>,
12703 ) {
12704 let is_relative = self.should_use_relative_line_numbers(cx);
12705 self.set_relative_line_number(Some(!is_relative), cx)
12706 }
12707
12708 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12709 self.use_relative_line_numbers = is_relative;
12710 cx.notify();
12711 }
12712
12713 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12714 self.show_gutter = show_gutter;
12715 cx.notify();
12716 }
12717
12718 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12719 self.show_scrollbars = show_scrollbars;
12720 cx.notify();
12721 }
12722
12723 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12724 self.show_line_numbers = Some(show_line_numbers);
12725 cx.notify();
12726 }
12727
12728 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12729 self.show_git_diff_gutter = Some(show_git_diff_gutter);
12730 cx.notify();
12731 }
12732
12733 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12734 self.show_code_actions = Some(show_code_actions);
12735 cx.notify();
12736 }
12737
12738 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12739 self.show_runnables = Some(show_runnables);
12740 cx.notify();
12741 }
12742
12743 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12744 if self.display_map.read(cx).masked != masked {
12745 self.display_map.update(cx, |map, _| map.masked = masked);
12746 }
12747 cx.notify()
12748 }
12749
12750 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12751 self.show_wrap_guides = Some(show_wrap_guides);
12752 cx.notify();
12753 }
12754
12755 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12756 self.show_indent_guides = Some(show_indent_guides);
12757 cx.notify();
12758 }
12759
12760 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12761 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12762 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12763 if let Some(dir) = file.abs_path(cx).parent() {
12764 return Some(dir.to_owned());
12765 }
12766 }
12767
12768 if let Some(project_path) = buffer.read(cx).project_path(cx) {
12769 return Some(project_path.path.to_path_buf());
12770 }
12771 }
12772
12773 None
12774 }
12775
12776 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12777 self.active_excerpt(cx)?
12778 .1
12779 .read(cx)
12780 .file()
12781 .and_then(|f| f.as_local())
12782 }
12783
12784 fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12785 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12786 let project_path = buffer.read(cx).project_path(cx)?;
12787 let project = self.project.as_ref()?.read(cx);
12788 project.absolute_path(&project_path, cx)
12789 })
12790 }
12791
12792 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12793 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12794 let project_path = buffer.read(cx).project_path(cx)?;
12795 let project = self.project.as_ref()?.read(cx);
12796 let entry = project.entry_for_path(&project_path, cx)?;
12797 let path = entry.path.to_path_buf();
12798 Some(path)
12799 })
12800 }
12801
12802 pub fn reveal_in_finder(
12803 &mut self,
12804 _: &RevealInFileManager,
12805 _window: &mut Window,
12806 cx: &mut Context<Self>,
12807 ) {
12808 if let Some(target) = self.target_file(cx) {
12809 cx.reveal_path(&target.abs_path(cx));
12810 }
12811 }
12812
12813 pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12814 if let Some(path) = self.target_file_abs_path(cx) {
12815 if let Some(path) = path.to_str() {
12816 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12817 }
12818 }
12819 }
12820
12821 pub fn copy_relative_path(
12822 &mut self,
12823 _: &CopyRelativePath,
12824 _window: &mut Window,
12825 cx: &mut Context<Self>,
12826 ) {
12827 if let Some(path) = self.target_file_path(cx) {
12828 if let Some(path) = path.to_str() {
12829 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12830 }
12831 }
12832 }
12833
12834 pub fn toggle_git_blame(
12835 &mut self,
12836 _: &ToggleGitBlame,
12837 window: &mut Window,
12838 cx: &mut Context<Self>,
12839 ) {
12840 self.show_git_blame_gutter = !self.show_git_blame_gutter;
12841
12842 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12843 self.start_git_blame(true, window, cx);
12844 }
12845
12846 cx.notify();
12847 }
12848
12849 pub fn toggle_git_blame_inline(
12850 &mut self,
12851 _: &ToggleGitBlameInline,
12852 window: &mut Window,
12853 cx: &mut Context<Self>,
12854 ) {
12855 self.toggle_git_blame_inline_internal(true, window, cx);
12856 cx.notify();
12857 }
12858
12859 pub fn git_blame_inline_enabled(&self) -> bool {
12860 self.git_blame_inline_enabled
12861 }
12862
12863 pub fn toggle_selection_menu(
12864 &mut self,
12865 _: &ToggleSelectionMenu,
12866 _: &mut Window,
12867 cx: &mut Context<Self>,
12868 ) {
12869 self.show_selection_menu = self
12870 .show_selection_menu
12871 .map(|show_selections_menu| !show_selections_menu)
12872 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12873
12874 cx.notify();
12875 }
12876
12877 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12878 self.show_selection_menu
12879 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12880 }
12881
12882 fn start_git_blame(
12883 &mut self,
12884 user_triggered: bool,
12885 window: &mut Window,
12886 cx: &mut Context<Self>,
12887 ) {
12888 if let Some(project) = self.project.as_ref() {
12889 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12890 return;
12891 };
12892
12893 if buffer.read(cx).file().is_none() {
12894 return;
12895 }
12896
12897 let focused = self.focus_handle(cx).contains_focused(window, cx);
12898
12899 let project = project.clone();
12900 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12901 self.blame_subscription =
12902 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12903 self.blame = Some(blame);
12904 }
12905 }
12906
12907 fn toggle_git_blame_inline_internal(
12908 &mut self,
12909 user_triggered: bool,
12910 window: &mut Window,
12911 cx: &mut Context<Self>,
12912 ) {
12913 if self.git_blame_inline_enabled {
12914 self.git_blame_inline_enabled = false;
12915 self.show_git_blame_inline = false;
12916 self.show_git_blame_inline_delay_task.take();
12917 } else {
12918 self.git_blame_inline_enabled = true;
12919 self.start_git_blame_inline(user_triggered, window, cx);
12920 }
12921
12922 cx.notify();
12923 }
12924
12925 fn start_git_blame_inline(
12926 &mut self,
12927 user_triggered: bool,
12928 window: &mut Window,
12929 cx: &mut Context<Self>,
12930 ) {
12931 self.start_git_blame(user_triggered, window, cx);
12932
12933 if ProjectSettings::get_global(cx)
12934 .git
12935 .inline_blame_delay()
12936 .is_some()
12937 {
12938 self.start_inline_blame_timer(window, cx);
12939 } else {
12940 self.show_git_blame_inline = true
12941 }
12942 }
12943
12944 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12945 self.blame.as_ref()
12946 }
12947
12948 pub fn show_git_blame_gutter(&self) -> bool {
12949 self.show_git_blame_gutter
12950 }
12951
12952 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12953 self.show_git_blame_gutter && self.has_blame_entries(cx)
12954 }
12955
12956 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12957 self.show_git_blame_inline
12958 && self.focus_handle.is_focused(window)
12959 && !self.newest_selection_head_on_empty_line(cx)
12960 && self.has_blame_entries(cx)
12961 }
12962
12963 fn has_blame_entries(&self, cx: &App) -> bool {
12964 self.blame()
12965 .map_or(false, |blame| blame.read(cx).has_generated_entries())
12966 }
12967
12968 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12969 let cursor_anchor = self.selections.newest_anchor().head();
12970
12971 let snapshot = self.buffer.read(cx).snapshot(cx);
12972 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12973
12974 snapshot.line_len(buffer_row) == 0
12975 }
12976
12977 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12978 let buffer_and_selection = maybe!({
12979 let selection = self.selections.newest::<Point>(cx);
12980 let selection_range = selection.range();
12981
12982 let multi_buffer = self.buffer().read(cx);
12983 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12984 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12985
12986 let (buffer, range, _) = if selection.reversed {
12987 buffer_ranges.first()
12988 } else {
12989 buffer_ranges.last()
12990 }?;
12991
12992 let selection = text::ToPoint::to_point(&range.start, &buffer).row
12993 ..text::ToPoint::to_point(&range.end, &buffer).row;
12994 Some((
12995 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
12996 selection,
12997 ))
12998 });
12999
13000 let Some((buffer, selection)) = buffer_and_selection else {
13001 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13002 };
13003
13004 let Some(project) = self.project.as_ref() else {
13005 return Task::ready(Err(anyhow!("editor does not have project")));
13006 };
13007
13008 project.update(cx, |project, cx| {
13009 project.get_permalink_to_line(&buffer, selection, cx)
13010 })
13011 }
13012
13013 pub fn copy_permalink_to_line(
13014 &mut self,
13015 _: &CopyPermalinkToLine,
13016 window: &mut Window,
13017 cx: &mut Context<Self>,
13018 ) {
13019 let permalink_task = self.get_permalink_to_line(cx);
13020 let workspace = self.workspace();
13021
13022 cx.spawn_in(window, |_, mut cx| async move {
13023 match permalink_task.await {
13024 Ok(permalink) => {
13025 cx.update(|_, cx| {
13026 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13027 })
13028 .ok();
13029 }
13030 Err(err) => {
13031 let message = format!("Failed to copy permalink: {err}");
13032
13033 Err::<(), anyhow::Error>(err).log_err();
13034
13035 if let Some(workspace) = workspace {
13036 workspace
13037 .update_in(&mut cx, |workspace, _, cx| {
13038 struct CopyPermalinkToLine;
13039
13040 workspace.show_toast(
13041 Toast::new(
13042 NotificationId::unique::<CopyPermalinkToLine>(),
13043 message,
13044 ),
13045 cx,
13046 )
13047 })
13048 .ok();
13049 }
13050 }
13051 }
13052 })
13053 .detach();
13054 }
13055
13056 pub fn copy_file_location(
13057 &mut self,
13058 _: &CopyFileLocation,
13059 _: &mut Window,
13060 cx: &mut Context<Self>,
13061 ) {
13062 let selection = self.selections.newest::<Point>(cx).start.row + 1;
13063 if let Some(file) = self.target_file(cx) {
13064 if let Some(path) = file.path().to_str() {
13065 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13066 }
13067 }
13068 }
13069
13070 pub fn open_permalink_to_line(
13071 &mut self,
13072 _: &OpenPermalinkToLine,
13073 window: &mut Window,
13074 cx: &mut Context<Self>,
13075 ) {
13076 let permalink_task = self.get_permalink_to_line(cx);
13077 let workspace = self.workspace();
13078
13079 cx.spawn_in(window, |_, mut cx| async move {
13080 match permalink_task.await {
13081 Ok(permalink) => {
13082 cx.update(|_, cx| {
13083 cx.open_url(permalink.as_ref());
13084 })
13085 .ok();
13086 }
13087 Err(err) => {
13088 let message = format!("Failed to open permalink: {err}");
13089
13090 Err::<(), anyhow::Error>(err).log_err();
13091
13092 if let Some(workspace) = workspace {
13093 workspace
13094 .update(&mut cx, |workspace, cx| {
13095 struct OpenPermalinkToLine;
13096
13097 workspace.show_toast(
13098 Toast::new(
13099 NotificationId::unique::<OpenPermalinkToLine>(),
13100 message,
13101 ),
13102 cx,
13103 )
13104 })
13105 .ok();
13106 }
13107 }
13108 }
13109 })
13110 .detach();
13111 }
13112
13113 pub fn insert_uuid_v4(
13114 &mut self,
13115 _: &InsertUuidV4,
13116 window: &mut Window,
13117 cx: &mut Context<Self>,
13118 ) {
13119 self.insert_uuid(UuidVersion::V4, window, cx);
13120 }
13121
13122 pub fn insert_uuid_v7(
13123 &mut self,
13124 _: &InsertUuidV7,
13125 window: &mut Window,
13126 cx: &mut Context<Self>,
13127 ) {
13128 self.insert_uuid(UuidVersion::V7, window, cx);
13129 }
13130
13131 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13132 self.transact(window, cx, |this, window, cx| {
13133 let edits = this
13134 .selections
13135 .all::<Point>(cx)
13136 .into_iter()
13137 .map(|selection| {
13138 let uuid = match version {
13139 UuidVersion::V4 => uuid::Uuid::new_v4(),
13140 UuidVersion::V7 => uuid::Uuid::now_v7(),
13141 };
13142
13143 (selection.range(), uuid.to_string())
13144 });
13145 this.edit(edits, cx);
13146 this.refresh_inline_completion(true, false, window, cx);
13147 });
13148 }
13149
13150 pub fn open_selections_in_multibuffer(
13151 &mut self,
13152 _: &OpenSelectionsInMultibuffer,
13153 window: &mut Window,
13154 cx: &mut Context<Self>,
13155 ) {
13156 let multibuffer = self.buffer.read(cx);
13157
13158 let Some(buffer) = multibuffer.as_singleton() else {
13159 return;
13160 };
13161
13162 let Some(workspace) = self.workspace() else {
13163 return;
13164 };
13165
13166 let locations = self
13167 .selections
13168 .disjoint_anchors()
13169 .iter()
13170 .map(|range| Location {
13171 buffer: buffer.clone(),
13172 range: range.start.text_anchor..range.end.text_anchor,
13173 })
13174 .collect::<Vec<_>>();
13175
13176 let title = multibuffer.title(cx).to_string();
13177
13178 cx.spawn_in(window, |_, mut cx| async move {
13179 workspace.update_in(&mut cx, |workspace, window, cx| {
13180 Self::open_locations_in_multibuffer(
13181 workspace,
13182 locations,
13183 format!("Selections for '{title}'"),
13184 false,
13185 MultibufferSelectionMode::All,
13186 window,
13187 cx,
13188 );
13189 })
13190 })
13191 .detach();
13192 }
13193
13194 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13195 /// last highlight added will be used.
13196 ///
13197 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13198 pub fn highlight_rows<T: 'static>(
13199 &mut self,
13200 range: Range<Anchor>,
13201 color: Hsla,
13202 should_autoscroll: bool,
13203 cx: &mut Context<Self>,
13204 ) {
13205 let snapshot = self.buffer().read(cx).snapshot(cx);
13206 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13207 let ix = row_highlights.binary_search_by(|highlight| {
13208 Ordering::Equal
13209 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13210 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13211 });
13212
13213 if let Err(mut ix) = ix {
13214 let index = post_inc(&mut self.highlight_order);
13215
13216 // If this range intersects with the preceding highlight, then merge it with
13217 // the preceding highlight. Otherwise insert a new highlight.
13218 let mut merged = false;
13219 if ix > 0 {
13220 let prev_highlight = &mut row_highlights[ix - 1];
13221 if prev_highlight
13222 .range
13223 .end
13224 .cmp(&range.start, &snapshot)
13225 .is_ge()
13226 {
13227 ix -= 1;
13228 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13229 prev_highlight.range.end = range.end;
13230 }
13231 merged = true;
13232 prev_highlight.index = index;
13233 prev_highlight.color = color;
13234 prev_highlight.should_autoscroll = should_autoscroll;
13235 }
13236 }
13237
13238 if !merged {
13239 row_highlights.insert(
13240 ix,
13241 RowHighlight {
13242 range: range.clone(),
13243 index,
13244 color,
13245 should_autoscroll,
13246 },
13247 );
13248 }
13249
13250 // If any of the following highlights intersect with this one, merge them.
13251 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13252 let highlight = &row_highlights[ix];
13253 if next_highlight
13254 .range
13255 .start
13256 .cmp(&highlight.range.end, &snapshot)
13257 .is_le()
13258 {
13259 if next_highlight
13260 .range
13261 .end
13262 .cmp(&highlight.range.end, &snapshot)
13263 .is_gt()
13264 {
13265 row_highlights[ix].range.end = next_highlight.range.end;
13266 }
13267 row_highlights.remove(ix + 1);
13268 } else {
13269 break;
13270 }
13271 }
13272 }
13273 }
13274
13275 /// Remove any highlighted row ranges of the given type that intersect the
13276 /// given ranges.
13277 pub fn remove_highlighted_rows<T: 'static>(
13278 &mut self,
13279 ranges_to_remove: Vec<Range<Anchor>>,
13280 cx: &mut Context<Self>,
13281 ) {
13282 let snapshot = self.buffer().read(cx).snapshot(cx);
13283 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13284 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13285 row_highlights.retain(|highlight| {
13286 while let Some(range_to_remove) = ranges_to_remove.peek() {
13287 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13288 Ordering::Less | Ordering::Equal => {
13289 ranges_to_remove.next();
13290 }
13291 Ordering::Greater => {
13292 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13293 Ordering::Less | Ordering::Equal => {
13294 return false;
13295 }
13296 Ordering::Greater => break,
13297 }
13298 }
13299 }
13300 }
13301
13302 true
13303 })
13304 }
13305
13306 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13307 pub fn clear_row_highlights<T: 'static>(&mut self) {
13308 self.highlighted_rows.remove(&TypeId::of::<T>());
13309 }
13310
13311 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13312 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13313 self.highlighted_rows
13314 .get(&TypeId::of::<T>())
13315 .map_or(&[] as &[_], |vec| vec.as_slice())
13316 .iter()
13317 .map(|highlight| (highlight.range.clone(), highlight.color))
13318 }
13319
13320 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13321 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13322 /// Allows to ignore certain kinds of highlights.
13323 pub fn highlighted_display_rows(
13324 &self,
13325 window: &mut Window,
13326 cx: &mut App,
13327 ) -> BTreeMap<DisplayRow, Hsla> {
13328 let snapshot = self.snapshot(window, cx);
13329 let mut used_highlight_orders = HashMap::default();
13330 self.highlighted_rows
13331 .iter()
13332 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13333 .fold(
13334 BTreeMap::<DisplayRow, Hsla>::new(),
13335 |mut unique_rows, highlight| {
13336 let start = highlight.range.start.to_display_point(&snapshot);
13337 let end = highlight.range.end.to_display_point(&snapshot);
13338 let start_row = start.row().0;
13339 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13340 && end.column() == 0
13341 {
13342 end.row().0.saturating_sub(1)
13343 } else {
13344 end.row().0
13345 };
13346 for row in start_row..=end_row {
13347 let used_index =
13348 used_highlight_orders.entry(row).or_insert(highlight.index);
13349 if highlight.index >= *used_index {
13350 *used_index = highlight.index;
13351 unique_rows.insert(DisplayRow(row), highlight.color);
13352 }
13353 }
13354 unique_rows
13355 },
13356 )
13357 }
13358
13359 pub fn highlighted_display_row_for_autoscroll(
13360 &self,
13361 snapshot: &DisplaySnapshot,
13362 ) -> Option<DisplayRow> {
13363 self.highlighted_rows
13364 .values()
13365 .flat_map(|highlighted_rows| highlighted_rows.iter())
13366 .filter_map(|highlight| {
13367 if highlight.should_autoscroll {
13368 Some(highlight.range.start.to_display_point(snapshot).row())
13369 } else {
13370 None
13371 }
13372 })
13373 .min()
13374 }
13375
13376 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13377 self.highlight_background::<SearchWithinRange>(
13378 ranges,
13379 |colors| colors.editor_document_highlight_read_background,
13380 cx,
13381 )
13382 }
13383
13384 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13385 self.breadcrumb_header = Some(new_header);
13386 }
13387
13388 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13389 self.clear_background_highlights::<SearchWithinRange>(cx);
13390 }
13391
13392 pub fn highlight_background<T: 'static>(
13393 &mut self,
13394 ranges: &[Range<Anchor>],
13395 color_fetcher: fn(&ThemeColors) -> Hsla,
13396 cx: &mut Context<Self>,
13397 ) {
13398 self.background_highlights
13399 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13400 self.scrollbar_marker_state.dirty = true;
13401 cx.notify();
13402 }
13403
13404 pub fn clear_background_highlights<T: 'static>(
13405 &mut self,
13406 cx: &mut Context<Self>,
13407 ) -> Option<BackgroundHighlight> {
13408 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13409 if !text_highlights.1.is_empty() {
13410 self.scrollbar_marker_state.dirty = true;
13411 cx.notify();
13412 }
13413 Some(text_highlights)
13414 }
13415
13416 pub fn highlight_gutter<T: 'static>(
13417 &mut self,
13418 ranges: &[Range<Anchor>],
13419 color_fetcher: fn(&App) -> Hsla,
13420 cx: &mut Context<Self>,
13421 ) {
13422 self.gutter_highlights
13423 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13424 cx.notify();
13425 }
13426
13427 pub fn clear_gutter_highlights<T: 'static>(
13428 &mut self,
13429 cx: &mut Context<Self>,
13430 ) -> Option<GutterHighlight> {
13431 cx.notify();
13432 self.gutter_highlights.remove(&TypeId::of::<T>())
13433 }
13434
13435 #[cfg(feature = "test-support")]
13436 pub fn all_text_background_highlights(
13437 &self,
13438 window: &mut Window,
13439 cx: &mut Context<Self>,
13440 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13441 let snapshot = self.snapshot(window, cx);
13442 let buffer = &snapshot.buffer_snapshot;
13443 let start = buffer.anchor_before(0);
13444 let end = buffer.anchor_after(buffer.len());
13445 let theme = cx.theme().colors();
13446 self.background_highlights_in_range(start..end, &snapshot, theme)
13447 }
13448
13449 #[cfg(feature = "test-support")]
13450 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13451 let snapshot = self.buffer().read(cx).snapshot(cx);
13452
13453 let highlights = self
13454 .background_highlights
13455 .get(&TypeId::of::<items::BufferSearchHighlights>());
13456
13457 if let Some((_color, ranges)) = highlights {
13458 ranges
13459 .iter()
13460 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13461 .collect_vec()
13462 } else {
13463 vec![]
13464 }
13465 }
13466
13467 fn document_highlights_for_position<'a>(
13468 &'a self,
13469 position: Anchor,
13470 buffer: &'a MultiBufferSnapshot,
13471 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13472 let read_highlights = self
13473 .background_highlights
13474 .get(&TypeId::of::<DocumentHighlightRead>())
13475 .map(|h| &h.1);
13476 let write_highlights = self
13477 .background_highlights
13478 .get(&TypeId::of::<DocumentHighlightWrite>())
13479 .map(|h| &h.1);
13480 let left_position = position.bias_left(buffer);
13481 let right_position = position.bias_right(buffer);
13482 read_highlights
13483 .into_iter()
13484 .chain(write_highlights)
13485 .flat_map(move |ranges| {
13486 let start_ix = match ranges.binary_search_by(|probe| {
13487 let cmp = probe.end.cmp(&left_position, buffer);
13488 if cmp.is_ge() {
13489 Ordering::Greater
13490 } else {
13491 Ordering::Less
13492 }
13493 }) {
13494 Ok(i) | Err(i) => i,
13495 };
13496
13497 ranges[start_ix..]
13498 .iter()
13499 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13500 })
13501 }
13502
13503 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13504 self.background_highlights
13505 .get(&TypeId::of::<T>())
13506 .map_or(false, |(_, highlights)| !highlights.is_empty())
13507 }
13508
13509 pub fn background_highlights_in_range(
13510 &self,
13511 search_range: Range<Anchor>,
13512 display_snapshot: &DisplaySnapshot,
13513 theme: &ThemeColors,
13514 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13515 let mut results = Vec::new();
13516 for (color_fetcher, ranges) in self.background_highlights.values() {
13517 let color = color_fetcher(theme);
13518 let start_ix = match ranges.binary_search_by(|probe| {
13519 let cmp = probe
13520 .end
13521 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13522 if cmp.is_gt() {
13523 Ordering::Greater
13524 } else {
13525 Ordering::Less
13526 }
13527 }) {
13528 Ok(i) | Err(i) => i,
13529 };
13530 for range in &ranges[start_ix..] {
13531 if range
13532 .start
13533 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13534 .is_ge()
13535 {
13536 break;
13537 }
13538
13539 let start = range.start.to_display_point(display_snapshot);
13540 let end = range.end.to_display_point(display_snapshot);
13541 results.push((start..end, color))
13542 }
13543 }
13544 results
13545 }
13546
13547 pub fn background_highlight_row_ranges<T: 'static>(
13548 &self,
13549 search_range: Range<Anchor>,
13550 display_snapshot: &DisplaySnapshot,
13551 count: usize,
13552 ) -> Vec<RangeInclusive<DisplayPoint>> {
13553 let mut results = Vec::new();
13554 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13555 return vec![];
13556 };
13557
13558 let start_ix = match ranges.binary_search_by(|probe| {
13559 let cmp = probe
13560 .end
13561 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13562 if cmp.is_gt() {
13563 Ordering::Greater
13564 } else {
13565 Ordering::Less
13566 }
13567 }) {
13568 Ok(i) | Err(i) => i,
13569 };
13570 let mut push_region = |start: Option<Point>, end: Option<Point>| {
13571 if let (Some(start_display), Some(end_display)) = (start, end) {
13572 results.push(
13573 start_display.to_display_point(display_snapshot)
13574 ..=end_display.to_display_point(display_snapshot),
13575 );
13576 }
13577 };
13578 let mut start_row: Option<Point> = None;
13579 let mut end_row: Option<Point> = None;
13580 if ranges.len() > count {
13581 return Vec::new();
13582 }
13583 for range in &ranges[start_ix..] {
13584 if range
13585 .start
13586 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13587 .is_ge()
13588 {
13589 break;
13590 }
13591 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13592 if let Some(current_row) = &end_row {
13593 if end.row == current_row.row {
13594 continue;
13595 }
13596 }
13597 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13598 if start_row.is_none() {
13599 assert_eq!(end_row, None);
13600 start_row = Some(start);
13601 end_row = Some(end);
13602 continue;
13603 }
13604 if let Some(current_end) = end_row.as_mut() {
13605 if start.row > current_end.row + 1 {
13606 push_region(start_row, end_row);
13607 start_row = Some(start);
13608 end_row = Some(end);
13609 } else {
13610 // Merge two hunks.
13611 *current_end = end;
13612 }
13613 } else {
13614 unreachable!();
13615 }
13616 }
13617 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13618 push_region(start_row, end_row);
13619 results
13620 }
13621
13622 pub fn gutter_highlights_in_range(
13623 &self,
13624 search_range: Range<Anchor>,
13625 display_snapshot: &DisplaySnapshot,
13626 cx: &App,
13627 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13628 let mut results = Vec::new();
13629 for (color_fetcher, ranges) in self.gutter_highlights.values() {
13630 let color = color_fetcher(cx);
13631 let start_ix = match ranges.binary_search_by(|probe| {
13632 let cmp = probe
13633 .end
13634 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13635 if cmp.is_gt() {
13636 Ordering::Greater
13637 } else {
13638 Ordering::Less
13639 }
13640 }) {
13641 Ok(i) | Err(i) => i,
13642 };
13643 for range in &ranges[start_ix..] {
13644 if range
13645 .start
13646 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13647 .is_ge()
13648 {
13649 break;
13650 }
13651
13652 let start = range.start.to_display_point(display_snapshot);
13653 let end = range.end.to_display_point(display_snapshot);
13654 results.push((start..end, color))
13655 }
13656 }
13657 results
13658 }
13659
13660 /// Get the text ranges corresponding to the redaction query
13661 pub fn redacted_ranges(
13662 &self,
13663 search_range: Range<Anchor>,
13664 display_snapshot: &DisplaySnapshot,
13665 cx: &App,
13666 ) -> Vec<Range<DisplayPoint>> {
13667 display_snapshot
13668 .buffer_snapshot
13669 .redacted_ranges(search_range, |file| {
13670 if let Some(file) = file {
13671 file.is_private()
13672 && EditorSettings::get(
13673 Some(SettingsLocation {
13674 worktree_id: file.worktree_id(cx),
13675 path: file.path().as_ref(),
13676 }),
13677 cx,
13678 )
13679 .redact_private_values
13680 } else {
13681 false
13682 }
13683 })
13684 .map(|range| {
13685 range.start.to_display_point(display_snapshot)
13686 ..range.end.to_display_point(display_snapshot)
13687 })
13688 .collect()
13689 }
13690
13691 pub fn highlight_text<T: 'static>(
13692 &mut self,
13693 ranges: Vec<Range<Anchor>>,
13694 style: HighlightStyle,
13695 cx: &mut Context<Self>,
13696 ) {
13697 self.display_map.update(cx, |map, _| {
13698 map.highlight_text(TypeId::of::<T>(), ranges, style)
13699 });
13700 cx.notify();
13701 }
13702
13703 pub(crate) fn highlight_inlays<T: 'static>(
13704 &mut self,
13705 highlights: Vec<InlayHighlight>,
13706 style: HighlightStyle,
13707 cx: &mut Context<Self>,
13708 ) {
13709 self.display_map.update(cx, |map, _| {
13710 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13711 });
13712 cx.notify();
13713 }
13714
13715 pub fn text_highlights<'a, T: 'static>(
13716 &'a self,
13717 cx: &'a App,
13718 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13719 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13720 }
13721
13722 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13723 let cleared = self
13724 .display_map
13725 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13726 if cleared {
13727 cx.notify();
13728 }
13729 }
13730
13731 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13732 (self.read_only(cx) || self.blink_manager.read(cx).visible())
13733 && self.focus_handle.is_focused(window)
13734 }
13735
13736 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13737 self.show_cursor_when_unfocused = is_enabled;
13738 cx.notify();
13739 }
13740
13741 pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13742 self.project
13743 .as_ref()
13744 .map(|project| project.read(cx).lsp_store())
13745 }
13746
13747 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13748 cx.notify();
13749 }
13750
13751 fn on_buffer_event(
13752 &mut self,
13753 multibuffer: &Entity<MultiBuffer>,
13754 event: &multi_buffer::Event,
13755 window: &mut Window,
13756 cx: &mut Context<Self>,
13757 ) {
13758 match event {
13759 multi_buffer::Event::Edited {
13760 singleton_buffer_edited,
13761 edited_buffer: buffer_edited,
13762 } => {
13763 self.scrollbar_marker_state.dirty = true;
13764 self.active_indent_guides_state.dirty = true;
13765 self.refresh_active_diagnostics(cx);
13766 self.refresh_code_actions(window, cx);
13767 if self.has_active_inline_completion() {
13768 self.update_visible_inline_completion(window, cx);
13769 }
13770 if let Some(buffer) = buffer_edited {
13771 let buffer_id = buffer.read(cx).remote_id();
13772 if !self.registered_buffers.contains_key(&buffer_id) {
13773 if let Some(lsp_store) = self.lsp_store(cx) {
13774 lsp_store.update(cx, |lsp_store, cx| {
13775 self.registered_buffers.insert(
13776 buffer_id,
13777 lsp_store.register_buffer_with_language_servers(&buffer, cx),
13778 );
13779 })
13780 }
13781 }
13782 }
13783 cx.emit(EditorEvent::BufferEdited);
13784 cx.emit(SearchEvent::MatchesInvalidated);
13785 if *singleton_buffer_edited {
13786 if let Some(project) = &self.project {
13787 let project = project.read(cx);
13788 #[allow(clippy::mutable_key_type)]
13789 let languages_affected = multibuffer
13790 .read(cx)
13791 .all_buffers()
13792 .into_iter()
13793 .filter_map(|buffer| {
13794 let buffer = buffer.read(cx);
13795 let language = buffer.language()?;
13796 if project.is_local()
13797 && project
13798 .language_servers_for_local_buffer(buffer, cx)
13799 .count()
13800 == 0
13801 {
13802 None
13803 } else {
13804 Some(language)
13805 }
13806 })
13807 .cloned()
13808 .collect::<HashSet<_>>();
13809 if !languages_affected.is_empty() {
13810 self.refresh_inlay_hints(
13811 InlayHintRefreshReason::BufferEdited(languages_affected),
13812 cx,
13813 );
13814 }
13815 }
13816 }
13817
13818 let Some(project) = &self.project else { return };
13819 let (telemetry, is_via_ssh) = {
13820 let project = project.read(cx);
13821 let telemetry = project.client().telemetry().clone();
13822 let is_via_ssh = project.is_via_ssh();
13823 (telemetry, is_via_ssh)
13824 };
13825 refresh_linked_ranges(self, window, cx);
13826 telemetry.log_edit_event("editor", is_via_ssh);
13827 }
13828 multi_buffer::Event::ExcerptsAdded {
13829 buffer,
13830 predecessor,
13831 excerpts,
13832 } => {
13833 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13834 let buffer_id = buffer.read(cx).remote_id();
13835 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
13836 if let Some(project) = &self.project {
13837 get_uncommitted_diff_for_buffer(
13838 project,
13839 [buffer.clone()],
13840 self.buffer.clone(),
13841 cx,
13842 );
13843 }
13844 }
13845 cx.emit(EditorEvent::ExcerptsAdded {
13846 buffer: buffer.clone(),
13847 predecessor: *predecessor,
13848 excerpts: excerpts.clone(),
13849 });
13850 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13851 }
13852 multi_buffer::Event::ExcerptsRemoved { ids } => {
13853 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13854 let buffer = self.buffer.read(cx);
13855 self.registered_buffers
13856 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13857 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13858 }
13859 multi_buffer::Event::ExcerptsEdited { ids } => {
13860 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13861 }
13862 multi_buffer::Event::ExcerptsExpanded { ids } => {
13863 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13864 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13865 }
13866 multi_buffer::Event::Reparsed(buffer_id) => {
13867 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13868
13869 cx.emit(EditorEvent::Reparsed(*buffer_id));
13870 }
13871 multi_buffer::Event::DiffHunksToggled => {
13872 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13873 }
13874 multi_buffer::Event::LanguageChanged(buffer_id) => {
13875 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13876 cx.emit(EditorEvent::Reparsed(*buffer_id));
13877 cx.notify();
13878 }
13879 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13880 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13881 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13882 cx.emit(EditorEvent::TitleChanged)
13883 }
13884 // multi_buffer::Event::DiffBaseChanged => {
13885 // self.scrollbar_marker_state.dirty = true;
13886 // cx.emit(EditorEvent::DiffBaseChanged);
13887 // cx.notify();
13888 // }
13889 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13890 multi_buffer::Event::DiagnosticsUpdated => {
13891 self.refresh_active_diagnostics(cx);
13892 self.scrollbar_marker_state.dirty = true;
13893 cx.notify();
13894 }
13895 _ => {}
13896 };
13897 }
13898
13899 fn on_display_map_changed(
13900 &mut self,
13901 _: Entity<DisplayMap>,
13902 _: &mut Window,
13903 cx: &mut Context<Self>,
13904 ) {
13905 cx.notify();
13906 }
13907
13908 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13909 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13910 self.refresh_inline_completion(true, false, window, cx);
13911 self.refresh_inlay_hints(
13912 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13913 self.selections.newest_anchor().head(),
13914 &self.buffer.read(cx).snapshot(cx),
13915 cx,
13916 )),
13917 cx,
13918 );
13919
13920 let old_cursor_shape = self.cursor_shape;
13921
13922 {
13923 let editor_settings = EditorSettings::get_global(cx);
13924 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13925 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13926 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13927 }
13928
13929 if old_cursor_shape != self.cursor_shape {
13930 cx.emit(EditorEvent::CursorShapeChanged);
13931 }
13932
13933 let project_settings = ProjectSettings::get_global(cx);
13934 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13935
13936 if self.mode == EditorMode::Full {
13937 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13938 if self.git_blame_inline_enabled != inline_blame_enabled {
13939 self.toggle_git_blame_inline_internal(false, window, cx);
13940 }
13941 }
13942
13943 cx.notify();
13944 }
13945
13946 pub fn set_searchable(&mut self, searchable: bool) {
13947 self.searchable = searchable;
13948 }
13949
13950 pub fn searchable(&self) -> bool {
13951 self.searchable
13952 }
13953
13954 fn open_proposed_changes_editor(
13955 &mut self,
13956 _: &OpenProposedChangesEditor,
13957 window: &mut Window,
13958 cx: &mut Context<Self>,
13959 ) {
13960 let Some(workspace) = self.workspace() else {
13961 cx.propagate();
13962 return;
13963 };
13964
13965 let selections = self.selections.all::<usize>(cx);
13966 let multi_buffer = self.buffer.read(cx);
13967 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13968 let mut new_selections_by_buffer = HashMap::default();
13969 for selection in selections {
13970 for (buffer, range, _) in
13971 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13972 {
13973 let mut range = range.to_point(buffer);
13974 range.start.column = 0;
13975 range.end.column = buffer.line_len(range.end.row);
13976 new_selections_by_buffer
13977 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13978 .or_insert(Vec::new())
13979 .push(range)
13980 }
13981 }
13982
13983 let proposed_changes_buffers = new_selections_by_buffer
13984 .into_iter()
13985 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13986 .collect::<Vec<_>>();
13987 let proposed_changes_editor = cx.new(|cx| {
13988 ProposedChangesEditor::new(
13989 "Proposed changes",
13990 proposed_changes_buffers,
13991 self.project.clone(),
13992 window,
13993 cx,
13994 )
13995 });
13996
13997 window.defer(cx, move |window, cx| {
13998 workspace.update(cx, |workspace, cx| {
13999 workspace.active_pane().update(cx, |pane, cx| {
14000 pane.add_item(
14001 Box::new(proposed_changes_editor),
14002 true,
14003 true,
14004 None,
14005 window,
14006 cx,
14007 );
14008 });
14009 });
14010 });
14011 }
14012
14013 pub fn open_excerpts_in_split(
14014 &mut self,
14015 _: &OpenExcerptsSplit,
14016 window: &mut Window,
14017 cx: &mut Context<Self>,
14018 ) {
14019 self.open_excerpts_common(None, true, window, cx)
14020 }
14021
14022 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14023 self.open_excerpts_common(None, false, window, cx)
14024 }
14025
14026 fn open_excerpts_common(
14027 &mut self,
14028 jump_data: Option<JumpData>,
14029 split: bool,
14030 window: &mut Window,
14031 cx: &mut Context<Self>,
14032 ) {
14033 let Some(workspace) = self.workspace() else {
14034 cx.propagate();
14035 return;
14036 };
14037
14038 if self.buffer.read(cx).is_singleton() {
14039 cx.propagate();
14040 return;
14041 }
14042
14043 let mut new_selections_by_buffer = HashMap::default();
14044 match &jump_data {
14045 Some(JumpData::MultiBufferPoint {
14046 excerpt_id,
14047 position,
14048 anchor,
14049 line_offset_from_top,
14050 }) => {
14051 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14052 if let Some(buffer) = multi_buffer_snapshot
14053 .buffer_id_for_excerpt(*excerpt_id)
14054 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14055 {
14056 let buffer_snapshot = buffer.read(cx).snapshot();
14057 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14058 language::ToPoint::to_point(anchor, &buffer_snapshot)
14059 } else {
14060 buffer_snapshot.clip_point(*position, Bias::Left)
14061 };
14062 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14063 new_selections_by_buffer.insert(
14064 buffer,
14065 (
14066 vec![jump_to_offset..jump_to_offset],
14067 Some(*line_offset_from_top),
14068 ),
14069 );
14070 }
14071 }
14072 Some(JumpData::MultiBufferRow {
14073 row,
14074 line_offset_from_top,
14075 }) => {
14076 let point = MultiBufferPoint::new(row.0, 0);
14077 if let Some((buffer, buffer_point, _)) =
14078 self.buffer.read(cx).point_to_buffer_point(point, cx)
14079 {
14080 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14081 new_selections_by_buffer
14082 .entry(buffer)
14083 .or_insert((Vec::new(), Some(*line_offset_from_top)))
14084 .0
14085 .push(buffer_offset..buffer_offset)
14086 }
14087 }
14088 None => {
14089 let selections = self.selections.all::<usize>(cx);
14090 let multi_buffer = self.buffer.read(cx);
14091 for selection in selections {
14092 for (buffer, mut range, _) in multi_buffer
14093 .snapshot(cx)
14094 .range_to_buffer_ranges(selection.range())
14095 {
14096 // When editing branch buffers, jump to the corresponding location
14097 // in their base buffer.
14098 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14099 let buffer = buffer_handle.read(cx);
14100 if let Some(base_buffer) = buffer.base_buffer() {
14101 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14102 buffer_handle = base_buffer;
14103 }
14104
14105 if selection.reversed {
14106 mem::swap(&mut range.start, &mut range.end);
14107 }
14108 new_selections_by_buffer
14109 .entry(buffer_handle)
14110 .or_insert((Vec::new(), None))
14111 .0
14112 .push(range)
14113 }
14114 }
14115 }
14116 }
14117
14118 if new_selections_by_buffer.is_empty() {
14119 return;
14120 }
14121
14122 // We defer the pane interaction because we ourselves are a workspace item
14123 // and activating a new item causes the pane to call a method on us reentrantly,
14124 // which panics if we're on the stack.
14125 window.defer(cx, move |window, cx| {
14126 workspace.update(cx, |workspace, cx| {
14127 let pane = if split {
14128 workspace.adjacent_pane(window, cx)
14129 } else {
14130 workspace.active_pane().clone()
14131 };
14132
14133 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14134 let editor = buffer
14135 .read(cx)
14136 .file()
14137 .is_none()
14138 .then(|| {
14139 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14140 // so `workspace.open_project_item` will never find them, always opening a new editor.
14141 // Instead, we try to activate the existing editor in the pane first.
14142 let (editor, pane_item_index) =
14143 pane.read(cx).items().enumerate().find_map(|(i, item)| {
14144 let editor = item.downcast::<Editor>()?;
14145 let singleton_buffer =
14146 editor.read(cx).buffer().read(cx).as_singleton()?;
14147 if singleton_buffer == buffer {
14148 Some((editor, i))
14149 } else {
14150 None
14151 }
14152 })?;
14153 pane.update(cx, |pane, cx| {
14154 pane.activate_item(pane_item_index, true, true, window, cx)
14155 });
14156 Some(editor)
14157 })
14158 .flatten()
14159 .unwrap_or_else(|| {
14160 workspace.open_project_item::<Self>(
14161 pane.clone(),
14162 buffer,
14163 true,
14164 true,
14165 window,
14166 cx,
14167 )
14168 });
14169
14170 editor.update(cx, |editor, cx| {
14171 let autoscroll = match scroll_offset {
14172 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14173 None => Autoscroll::newest(),
14174 };
14175 let nav_history = editor.nav_history.take();
14176 editor.change_selections(Some(autoscroll), window, cx, |s| {
14177 s.select_ranges(ranges);
14178 });
14179 editor.nav_history = nav_history;
14180 });
14181 }
14182 })
14183 });
14184 }
14185
14186 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14187 let snapshot = self.buffer.read(cx).read(cx);
14188 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14189 Some(
14190 ranges
14191 .iter()
14192 .map(move |range| {
14193 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14194 })
14195 .collect(),
14196 )
14197 }
14198
14199 fn selection_replacement_ranges(
14200 &self,
14201 range: Range<OffsetUtf16>,
14202 cx: &mut App,
14203 ) -> Vec<Range<OffsetUtf16>> {
14204 let selections = self.selections.all::<OffsetUtf16>(cx);
14205 let newest_selection = selections
14206 .iter()
14207 .max_by_key(|selection| selection.id)
14208 .unwrap();
14209 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14210 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14211 let snapshot = self.buffer.read(cx).read(cx);
14212 selections
14213 .into_iter()
14214 .map(|mut selection| {
14215 selection.start.0 =
14216 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14217 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14218 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14219 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14220 })
14221 .collect()
14222 }
14223
14224 fn report_editor_event(
14225 &self,
14226 event_type: &'static str,
14227 file_extension: Option<String>,
14228 cx: &App,
14229 ) {
14230 if cfg!(any(test, feature = "test-support")) {
14231 return;
14232 }
14233
14234 let Some(project) = &self.project else { return };
14235
14236 // If None, we are in a file without an extension
14237 let file = self
14238 .buffer
14239 .read(cx)
14240 .as_singleton()
14241 .and_then(|b| b.read(cx).file());
14242 let file_extension = file_extension.or(file
14243 .as_ref()
14244 .and_then(|file| Path::new(file.file_name(cx)).extension())
14245 .and_then(|e| e.to_str())
14246 .map(|a| a.to_string()));
14247
14248 let vim_mode = cx
14249 .global::<SettingsStore>()
14250 .raw_user_settings()
14251 .get("vim_mode")
14252 == Some(&serde_json::Value::Bool(true));
14253
14254 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14255 let copilot_enabled = edit_predictions_provider
14256 == language::language_settings::EditPredictionProvider::Copilot;
14257 let copilot_enabled_for_language = self
14258 .buffer
14259 .read(cx)
14260 .settings_at(0, cx)
14261 .show_edit_predictions;
14262
14263 let project = project.read(cx);
14264 telemetry::event!(
14265 event_type,
14266 file_extension,
14267 vim_mode,
14268 copilot_enabled,
14269 copilot_enabled_for_language,
14270 edit_predictions_provider,
14271 is_via_ssh = project.is_via_ssh(),
14272 );
14273 }
14274
14275 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14276 /// with each line being an array of {text, highlight} objects.
14277 fn copy_highlight_json(
14278 &mut self,
14279 _: &CopyHighlightJson,
14280 window: &mut Window,
14281 cx: &mut Context<Self>,
14282 ) {
14283 #[derive(Serialize)]
14284 struct Chunk<'a> {
14285 text: String,
14286 highlight: Option<&'a str>,
14287 }
14288
14289 let snapshot = self.buffer.read(cx).snapshot(cx);
14290 let range = self
14291 .selected_text_range(false, window, cx)
14292 .and_then(|selection| {
14293 if selection.range.is_empty() {
14294 None
14295 } else {
14296 Some(selection.range)
14297 }
14298 })
14299 .unwrap_or_else(|| 0..snapshot.len());
14300
14301 let chunks = snapshot.chunks(range, true);
14302 let mut lines = Vec::new();
14303 let mut line: VecDeque<Chunk> = VecDeque::new();
14304
14305 let Some(style) = self.style.as_ref() else {
14306 return;
14307 };
14308
14309 for chunk in chunks {
14310 let highlight = chunk
14311 .syntax_highlight_id
14312 .and_then(|id| id.name(&style.syntax));
14313 let mut chunk_lines = chunk.text.split('\n').peekable();
14314 while let Some(text) = chunk_lines.next() {
14315 let mut merged_with_last_token = false;
14316 if let Some(last_token) = line.back_mut() {
14317 if last_token.highlight == highlight {
14318 last_token.text.push_str(text);
14319 merged_with_last_token = true;
14320 }
14321 }
14322
14323 if !merged_with_last_token {
14324 line.push_back(Chunk {
14325 text: text.into(),
14326 highlight,
14327 });
14328 }
14329
14330 if chunk_lines.peek().is_some() {
14331 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14332 line.pop_front();
14333 }
14334 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14335 line.pop_back();
14336 }
14337
14338 lines.push(mem::take(&mut line));
14339 }
14340 }
14341 }
14342
14343 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14344 return;
14345 };
14346 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14347 }
14348
14349 pub fn open_context_menu(
14350 &mut self,
14351 _: &OpenContextMenu,
14352 window: &mut Window,
14353 cx: &mut Context<Self>,
14354 ) {
14355 self.request_autoscroll(Autoscroll::newest(), cx);
14356 let position = self.selections.newest_display(cx).start;
14357 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14358 }
14359
14360 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14361 &self.inlay_hint_cache
14362 }
14363
14364 pub fn replay_insert_event(
14365 &mut self,
14366 text: &str,
14367 relative_utf16_range: Option<Range<isize>>,
14368 window: &mut Window,
14369 cx: &mut Context<Self>,
14370 ) {
14371 if !self.input_enabled {
14372 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14373 return;
14374 }
14375 if let Some(relative_utf16_range) = relative_utf16_range {
14376 let selections = self.selections.all::<OffsetUtf16>(cx);
14377 self.change_selections(None, window, cx, |s| {
14378 let new_ranges = selections.into_iter().map(|range| {
14379 let start = OffsetUtf16(
14380 range
14381 .head()
14382 .0
14383 .saturating_add_signed(relative_utf16_range.start),
14384 );
14385 let end = OffsetUtf16(
14386 range
14387 .head()
14388 .0
14389 .saturating_add_signed(relative_utf16_range.end),
14390 );
14391 start..end
14392 });
14393 s.select_ranges(new_ranges);
14394 });
14395 }
14396
14397 self.handle_input(text, window, cx);
14398 }
14399
14400 pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14401 let Some(provider) = self.semantics_provider.as_ref() else {
14402 return false;
14403 };
14404
14405 let mut supports = false;
14406 self.buffer().read(cx).for_each_buffer(|buffer| {
14407 supports |= provider.supports_inlay_hints(buffer, cx);
14408 });
14409 supports
14410 }
14411 pub fn is_focused(&self, window: &mut Window) -> bool {
14412 self.focus_handle.is_focused(window)
14413 }
14414
14415 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14416 cx.emit(EditorEvent::Focused);
14417
14418 if let Some(descendant) = self
14419 .last_focused_descendant
14420 .take()
14421 .and_then(|descendant| descendant.upgrade())
14422 {
14423 window.focus(&descendant);
14424 } else {
14425 if let Some(blame) = self.blame.as_ref() {
14426 blame.update(cx, GitBlame::focus)
14427 }
14428
14429 self.blink_manager.update(cx, BlinkManager::enable);
14430 self.show_cursor_names(window, cx);
14431 self.buffer.update(cx, |buffer, cx| {
14432 buffer.finalize_last_transaction(cx);
14433 if self.leader_peer_id.is_none() {
14434 buffer.set_active_selections(
14435 &self.selections.disjoint_anchors(),
14436 self.selections.line_mode,
14437 self.cursor_shape,
14438 cx,
14439 );
14440 }
14441 });
14442 }
14443 }
14444
14445 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14446 cx.emit(EditorEvent::FocusedIn)
14447 }
14448
14449 fn handle_focus_out(
14450 &mut self,
14451 event: FocusOutEvent,
14452 _window: &mut Window,
14453 _cx: &mut Context<Self>,
14454 ) {
14455 if event.blurred != self.focus_handle {
14456 self.last_focused_descendant = Some(event.blurred);
14457 }
14458 }
14459
14460 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14461 self.blink_manager.update(cx, BlinkManager::disable);
14462 self.buffer
14463 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14464
14465 if let Some(blame) = self.blame.as_ref() {
14466 blame.update(cx, GitBlame::blur)
14467 }
14468 if !self.hover_state.focused(window, cx) {
14469 hide_hover(self, cx);
14470 }
14471
14472 self.hide_context_menu(window, cx);
14473 cx.emit(EditorEvent::Blurred);
14474 cx.notify();
14475 }
14476
14477 pub fn register_action<A: Action>(
14478 &mut self,
14479 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14480 ) -> Subscription {
14481 let id = self.next_editor_action_id.post_inc();
14482 let listener = Arc::new(listener);
14483 self.editor_actions.borrow_mut().insert(
14484 id,
14485 Box::new(move |window, _| {
14486 let listener = listener.clone();
14487 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14488 let action = action.downcast_ref().unwrap();
14489 if phase == DispatchPhase::Bubble {
14490 listener(action, window, cx)
14491 }
14492 })
14493 }),
14494 );
14495
14496 let editor_actions = self.editor_actions.clone();
14497 Subscription::new(move || {
14498 editor_actions.borrow_mut().remove(&id);
14499 })
14500 }
14501
14502 pub fn file_header_size(&self) -> u32 {
14503 FILE_HEADER_HEIGHT
14504 }
14505
14506 pub fn revert(
14507 &mut self,
14508 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14509 window: &mut Window,
14510 cx: &mut Context<Self>,
14511 ) {
14512 self.buffer().update(cx, |multi_buffer, cx| {
14513 for (buffer_id, changes) in revert_changes {
14514 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14515 buffer.update(cx, |buffer, cx| {
14516 buffer.edit(
14517 changes.into_iter().map(|(range, text)| {
14518 (range, text.to_string().map(Arc::<str>::from))
14519 }),
14520 None,
14521 cx,
14522 );
14523 });
14524 }
14525 }
14526 });
14527 self.change_selections(None, window, cx, |selections| selections.refresh());
14528 }
14529
14530 pub fn to_pixel_point(
14531 &self,
14532 source: multi_buffer::Anchor,
14533 editor_snapshot: &EditorSnapshot,
14534 window: &mut Window,
14535 ) -> Option<gpui::Point<Pixels>> {
14536 let source_point = source.to_display_point(editor_snapshot);
14537 self.display_to_pixel_point(source_point, editor_snapshot, window)
14538 }
14539
14540 pub fn display_to_pixel_point(
14541 &self,
14542 source: DisplayPoint,
14543 editor_snapshot: &EditorSnapshot,
14544 window: &mut Window,
14545 ) -> Option<gpui::Point<Pixels>> {
14546 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14547 let text_layout_details = self.text_layout_details(window);
14548 let scroll_top = text_layout_details
14549 .scroll_anchor
14550 .scroll_position(editor_snapshot)
14551 .y;
14552
14553 if source.row().as_f32() < scroll_top.floor() {
14554 return None;
14555 }
14556 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14557 let source_y = line_height * (source.row().as_f32() - scroll_top);
14558 Some(gpui::Point::new(source_x, source_y))
14559 }
14560
14561 pub fn has_visible_completions_menu(&self) -> bool {
14562 !self.previewing_inline_completion
14563 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14564 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14565 })
14566 }
14567
14568 pub fn register_addon<T: Addon>(&mut self, instance: T) {
14569 self.addons
14570 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14571 }
14572
14573 pub fn unregister_addon<T: Addon>(&mut self) {
14574 self.addons.remove(&std::any::TypeId::of::<T>());
14575 }
14576
14577 pub fn addon<T: Addon>(&self) -> Option<&T> {
14578 let type_id = std::any::TypeId::of::<T>();
14579 self.addons
14580 .get(&type_id)
14581 .and_then(|item| item.to_any().downcast_ref::<T>())
14582 }
14583
14584 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14585 let text_layout_details = self.text_layout_details(window);
14586 let style = &text_layout_details.editor_style;
14587 let font_id = window.text_system().resolve_font(&style.text.font());
14588 let font_size = style.text.font_size.to_pixels(window.rem_size());
14589 let line_height = style.text.line_height_in_pixels(window.rem_size());
14590 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14591
14592 gpui::Size::new(em_width, line_height)
14593 }
14594}
14595
14596fn get_uncommitted_diff_for_buffer(
14597 project: &Entity<Project>,
14598 buffers: impl IntoIterator<Item = Entity<Buffer>>,
14599 buffer: Entity<MultiBuffer>,
14600 cx: &mut App,
14601) {
14602 let mut tasks = Vec::new();
14603 project.update(cx, |project, cx| {
14604 for buffer in buffers {
14605 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14606 }
14607 });
14608 cx.spawn(|mut cx| async move {
14609 let diffs = futures::future::join_all(tasks).await;
14610 buffer
14611 .update(&mut cx, |buffer, cx| {
14612 for diff in diffs.into_iter().flatten() {
14613 buffer.add_diff(diff, cx);
14614 }
14615 })
14616 .ok();
14617 })
14618 .detach();
14619}
14620
14621fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14622 let tab_size = tab_size.get() as usize;
14623 let mut width = offset;
14624
14625 for ch in text.chars() {
14626 width += if ch == '\t' {
14627 tab_size - (width % tab_size)
14628 } else {
14629 1
14630 };
14631 }
14632
14633 width - offset
14634}
14635
14636#[cfg(test)]
14637mod tests {
14638 use super::*;
14639
14640 #[test]
14641 fn test_string_size_with_expanded_tabs() {
14642 let nz = |val| NonZeroU32::new(val).unwrap();
14643 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14644 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14645 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14646 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14647 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14648 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14649 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14650 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14651 }
14652}
14653
14654/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14655struct WordBreakingTokenizer<'a> {
14656 input: &'a str,
14657}
14658
14659impl<'a> WordBreakingTokenizer<'a> {
14660 fn new(input: &'a str) -> Self {
14661 Self { input }
14662 }
14663}
14664
14665fn is_char_ideographic(ch: char) -> bool {
14666 use unicode_script::Script::*;
14667 use unicode_script::UnicodeScript;
14668 matches!(ch.script(), Han | Tangut | Yi)
14669}
14670
14671fn is_grapheme_ideographic(text: &str) -> bool {
14672 text.chars().any(is_char_ideographic)
14673}
14674
14675fn is_grapheme_whitespace(text: &str) -> bool {
14676 text.chars().any(|x| x.is_whitespace())
14677}
14678
14679fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14680 text.chars().next().map_or(false, |ch| {
14681 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14682 })
14683}
14684
14685#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14686struct WordBreakToken<'a> {
14687 token: &'a str,
14688 grapheme_len: usize,
14689 is_whitespace: bool,
14690}
14691
14692impl<'a> Iterator for WordBreakingTokenizer<'a> {
14693 /// Yields a span, the count of graphemes in the token, and whether it was
14694 /// whitespace. Note that it also breaks at word boundaries.
14695 type Item = WordBreakToken<'a>;
14696
14697 fn next(&mut self) -> Option<Self::Item> {
14698 use unicode_segmentation::UnicodeSegmentation;
14699 if self.input.is_empty() {
14700 return None;
14701 }
14702
14703 let mut iter = self.input.graphemes(true).peekable();
14704 let mut offset = 0;
14705 let mut graphemes = 0;
14706 if let Some(first_grapheme) = iter.next() {
14707 let is_whitespace = is_grapheme_whitespace(first_grapheme);
14708 offset += first_grapheme.len();
14709 graphemes += 1;
14710 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14711 if let Some(grapheme) = iter.peek().copied() {
14712 if should_stay_with_preceding_ideograph(grapheme) {
14713 offset += grapheme.len();
14714 graphemes += 1;
14715 }
14716 }
14717 } else {
14718 let mut words = self.input[offset..].split_word_bound_indices().peekable();
14719 let mut next_word_bound = words.peek().copied();
14720 if next_word_bound.map_or(false, |(i, _)| i == 0) {
14721 next_word_bound = words.next();
14722 }
14723 while let Some(grapheme) = iter.peek().copied() {
14724 if next_word_bound.map_or(false, |(i, _)| i == offset) {
14725 break;
14726 };
14727 if is_grapheme_whitespace(grapheme) != is_whitespace {
14728 break;
14729 };
14730 offset += grapheme.len();
14731 graphemes += 1;
14732 iter.next();
14733 }
14734 }
14735 let token = &self.input[..offset];
14736 self.input = &self.input[offset..];
14737 if is_whitespace {
14738 Some(WordBreakToken {
14739 token: " ",
14740 grapheme_len: 1,
14741 is_whitespace: true,
14742 })
14743 } else {
14744 Some(WordBreakToken {
14745 token,
14746 grapheme_len: graphemes,
14747 is_whitespace: false,
14748 })
14749 }
14750 } else {
14751 None
14752 }
14753 }
14754}
14755
14756#[test]
14757fn test_word_breaking_tokenizer() {
14758 let tests: &[(&str, &[(&str, usize, bool)])] = &[
14759 ("", &[]),
14760 (" ", &[(" ", 1, true)]),
14761 ("Ʒ", &[("Ʒ", 1, false)]),
14762 ("Ǽ", &[("Ǽ", 1, false)]),
14763 ("⋑", &[("⋑", 1, false)]),
14764 ("⋑⋑", &[("⋑⋑", 2, false)]),
14765 (
14766 "原理,进而",
14767 &[
14768 ("原", 1, false),
14769 ("理,", 2, false),
14770 ("进", 1, false),
14771 ("而", 1, false),
14772 ],
14773 ),
14774 (
14775 "hello world",
14776 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14777 ),
14778 (
14779 "hello, world",
14780 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14781 ),
14782 (
14783 " hello world",
14784 &[
14785 (" ", 1, true),
14786 ("hello", 5, false),
14787 (" ", 1, true),
14788 ("world", 5, false),
14789 ],
14790 ),
14791 (
14792 "这是什么 \n 钢笔",
14793 &[
14794 ("这", 1, false),
14795 ("是", 1, false),
14796 ("什", 1, false),
14797 ("么", 1, false),
14798 (" ", 1, true),
14799 ("钢", 1, false),
14800 ("笔", 1, false),
14801 ],
14802 ),
14803 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14804 ];
14805
14806 for (input, result) in tests {
14807 assert_eq!(
14808 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14809 result
14810 .iter()
14811 .copied()
14812 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14813 token,
14814 grapheme_len,
14815 is_whitespace,
14816 })
14817 .collect::<Vec<_>>()
14818 );
14819 }
14820}
14821
14822fn wrap_with_prefix(
14823 line_prefix: String,
14824 unwrapped_text: String,
14825 wrap_column: usize,
14826 tab_size: NonZeroU32,
14827) -> String {
14828 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14829 let mut wrapped_text = String::new();
14830 let mut current_line = line_prefix.clone();
14831
14832 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14833 let mut current_line_len = line_prefix_len;
14834 for WordBreakToken {
14835 token,
14836 grapheme_len,
14837 is_whitespace,
14838 } in tokenizer
14839 {
14840 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14841 wrapped_text.push_str(current_line.trim_end());
14842 wrapped_text.push('\n');
14843 current_line.truncate(line_prefix.len());
14844 current_line_len = line_prefix_len;
14845 if !is_whitespace {
14846 current_line.push_str(token);
14847 current_line_len += grapheme_len;
14848 }
14849 } else if !is_whitespace {
14850 current_line.push_str(token);
14851 current_line_len += grapheme_len;
14852 } else if current_line_len != line_prefix_len {
14853 current_line.push(' ');
14854 current_line_len += 1;
14855 }
14856 }
14857
14858 if !current_line.is_empty() {
14859 wrapped_text.push_str(¤t_line);
14860 }
14861 wrapped_text
14862}
14863
14864#[test]
14865fn test_wrap_with_prefix() {
14866 assert_eq!(
14867 wrap_with_prefix(
14868 "# ".to_string(),
14869 "abcdefg".to_string(),
14870 4,
14871 NonZeroU32::new(4).unwrap()
14872 ),
14873 "# abcdefg"
14874 );
14875 assert_eq!(
14876 wrap_with_prefix(
14877 "".to_string(),
14878 "\thello world".to_string(),
14879 8,
14880 NonZeroU32::new(4).unwrap()
14881 ),
14882 "hello\nworld"
14883 );
14884 assert_eq!(
14885 wrap_with_prefix(
14886 "// ".to_string(),
14887 "xx \nyy zz aa bb cc".to_string(),
14888 12,
14889 NonZeroU32::new(4).unwrap()
14890 ),
14891 "// xx yy zz\n// aa bb cc"
14892 );
14893 assert_eq!(
14894 wrap_with_prefix(
14895 String::new(),
14896 "这是什么 \n 钢笔".to_string(),
14897 3,
14898 NonZeroU32::new(4).unwrap()
14899 ),
14900 "这是什\n么 钢\n笔"
14901 );
14902}
14903
14904pub trait CollaborationHub {
14905 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14906 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14907 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14908}
14909
14910impl CollaborationHub for Entity<Project> {
14911 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14912 self.read(cx).collaborators()
14913 }
14914
14915 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14916 self.read(cx).user_store().read(cx).participant_indices()
14917 }
14918
14919 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14920 let this = self.read(cx);
14921 let user_ids = this.collaborators().values().map(|c| c.user_id);
14922 this.user_store().read_with(cx, |user_store, cx| {
14923 user_store.participant_names(user_ids, cx)
14924 })
14925 }
14926}
14927
14928pub trait SemanticsProvider {
14929 fn hover(
14930 &self,
14931 buffer: &Entity<Buffer>,
14932 position: text::Anchor,
14933 cx: &mut App,
14934 ) -> Option<Task<Vec<project::Hover>>>;
14935
14936 fn inlay_hints(
14937 &self,
14938 buffer_handle: Entity<Buffer>,
14939 range: Range<text::Anchor>,
14940 cx: &mut App,
14941 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14942
14943 fn resolve_inlay_hint(
14944 &self,
14945 hint: InlayHint,
14946 buffer_handle: Entity<Buffer>,
14947 server_id: LanguageServerId,
14948 cx: &mut App,
14949 ) -> Option<Task<anyhow::Result<InlayHint>>>;
14950
14951 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
14952
14953 fn document_highlights(
14954 &self,
14955 buffer: &Entity<Buffer>,
14956 position: text::Anchor,
14957 cx: &mut App,
14958 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14959
14960 fn definitions(
14961 &self,
14962 buffer: &Entity<Buffer>,
14963 position: text::Anchor,
14964 kind: GotoDefinitionKind,
14965 cx: &mut App,
14966 ) -> Option<Task<Result<Vec<LocationLink>>>>;
14967
14968 fn range_for_rename(
14969 &self,
14970 buffer: &Entity<Buffer>,
14971 position: text::Anchor,
14972 cx: &mut App,
14973 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14974
14975 fn perform_rename(
14976 &self,
14977 buffer: &Entity<Buffer>,
14978 position: text::Anchor,
14979 new_name: String,
14980 cx: &mut App,
14981 ) -> Option<Task<Result<ProjectTransaction>>>;
14982}
14983
14984pub trait CompletionProvider {
14985 fn completions(
14986 &self,
14987 buffer: &Entity<Buffer>,
14988 buffer_position: text::Anchor,
14989 trigger: CompletionContext,
14990 window: &mut Window,
14991 cx: &mut Context<Editor>,
14992 ) -> Task<Result<Vec<Completion>>>;
14993
14994 fn resolve_completions(
14995 &self,
14996 buffer: Entity<Buffer>,
14997 completion_indices: Vec<usize>,
14998 completions: Rc<RefCell<Box<[Completion]>>>,
14999 cx: &mut Context<Editor>,
15000 ) -> Task<Result<bool>>;
15001
15002 fn apply_additional_edits_for_completion(
15003 &self,
15004 _buffer: Entity<Buffer>,
15005 _completions: Rc<RefCell<Box<[Completion]>>>,
15006 _completion_index: usize,
15007 _push_to_history: bool,
15008 _cx: &mut Context<Editor>,
15009 ) -> Task<Result<Option<language::Transaction>>> {
15010 Task::ready(Ok(None))
15011 }
15012
15013 fn is_completion_trigger(
15014 &self,
15015 buffer: &Entity<Buffer>,
15016 position: language::Anchor,
15017 text: &str,
15018 trigger_in_words: bool,
15019 cx: &mut Context<Editor>,
15020 ) -> bool;
15021
15022 fn sort_completions(&self) -> bool {
15023 true
15024 }
15025}
15026
15027pub trait CodeActionProvider {
15028 fn id(&self) -> Arc<str>;
15029
15030 fn code_actions(
15031 &self,
15032 buffer: &Entity<Buffer>,
15033 range: Range<text::Anchor>,
15034 window: &mut Window,
15035 cx: &mut App,
15036 ) -> Task<Result<Vec<CodeAction>>>;
15037
15038 fn apply_code_action(
15039 &self,
15040 buffer_handle: Entity<Buffer>,
15041 action: CodeAction,
15042 excerpt_id: ExcerptId,
15043 push_to_history: bool,
15044 window: &mut Window,
15045 cx: &mut App,
15046 ) -> Task<Result<ProjectTransaction>>;
15047}
15048
15049impl CodeActionProvider for Entity<Project> {
15050 fn id(&self) -> Arc<str> {
15051 "project".into()
15052 }
15053
15054 fn code_actions(
15055 &self,
15056 buffer: &Entity<Buffer>,
15057 range: Range<text::Anchor>,
15058 _window: &mut Window,
15059 cx: &mut App,
15060 ) -> Task<Result<Vec<CodeAction>>> {
15061 self.update(cx, |project, cx| {
15062 project.code_actions(buffer, range, None, cx)
15063 })
15064 }
15065
15066 fn apply_code_action(
15067 &self,
15068 buffer_handle: Entity<Buffer>,
15069 action: CodeAction,
15070 _excerpt_id: ExcerptId,
15071 push_to_history: bool,
15072 _window: &mut Window,
15073 cx: &mut App,
15074 ) -> Task<Result<ProjectTransaction>> {
15075 self.update(cx, |project, cx| {
15076 project.apply_code_action(buffer_handle, action, push_to_history, cx)
15077 })
15078 }
15079}
15080
15081fn snippet_completions(
15082 project: &Project,
15083 buffer: &Entity<Buffer>,
15084 buffer_position: text::Anchor,
15085 cx: &mut App,
15086) -> Task<Result<Vec<Completion>>> {
15087 let language = buffer.read(cx).language_at(buffer_position);
15088 let language_name = language.as_ref().map(|language| language.lsp_id());
15089 let snippet_store = project.snippets().read(cx);
15090 let snippets = snippet_store.snippets_for(language_name, cx);
15091
15092 if snippets.is_empty() {
15093 return Task::ready(Ok(vec![]));
15094 }
15095 let snapshot = buffer.read(cx).text_snapshot();
15096 let chars: String = snapshot
15097 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15098 .collect();
15099
15100 let scope = language.map(|language| language.default_scope());
15101 let executor = cx.background_executor().clone();
15102
15103 cx.background_executor().spawn(async move {
15104 let classifier = CharClassifier::new(scope).for_completion(true);
15105 let mut last_word = chars
15106 .chars()
15107 .take_while(|c| classifier.is_word(*c))
15108 .collect::<String>();
15109 last_word = last_word.chars().rev().collect();
15110
15111 if last_word.is_empty() {
15112 return Ok(vec![]);
15113 }
15114
15115 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15116 let to_lsp = |point: &text::Anchor| {
15117 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15118 point_to_lsp(end)
15119 };
15120 let lsp_end = to_lsp(&buffer_position);
15121
15122 let candidates = snippets
15123 .iter()
15124 .enumerate()
15125 .flat_map(|(ix, snippet)| {
15126 snippet
15127 .prefix
15128 .iter()
15129 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15130 })
15131 .collect::<Vec<StringMatchCandidate>>();
15132
15133 let mut matches = fuzzy::match_strings(
15134 &candidates,
15135 &last_word,
15136 last_word.chars().any(|c| c.is_uppercase()),
15137 100,
15138 &Default::default(),
15139 executor,
15140 )
15141 .await;
15142
15143 // Remove all candidates where the query's start does not match the start of any word in the candidate
15144 if let Some(query_start) = last_word.chars().next() {
15145 matches.retain(|string_match| {
15146 split_words(&string_match.string).any(|word| {
15147 // Check that the first codepoint of the word as lowercase matches the first
15148 // codepoint of the query as lowercase
15149 word.chars()
15150 .flat_map(|codepoint| codepoint.to_lowercase())
15151 .zip(query_start.to_lowercase())
15152 .all(|(word_cp, query_cp)| word_cp == query_cp)
15153 })
15154 });
15155 }
15156
15157 let matched_strings = matches
15158 .into_iter()
15159 .map(|m| m.string)
15160 .collect::<HashSet<_>>();
15161
15162 let result: Vec<Completion> = snippets
15163 .into_iter()
15164 .filter_map(|snippet| {
15165 let matching_prefix = snippet
15166 .prefix
15167 .iter()
15168 .find(|prefix| matched_strings.contains(*prefix))?;
15169 let start = as_offset - last_word.len();
15170 let start = snapshot.anchor_before(start);
15171 let range = start..buffer_position;
15172 let lsp_start = to_lsp(&start);
15173 let lsp_range = lsp::Range {
15174 start: lsp_start,
15175 end: lsp_end,
15176 };
15177 Some(Completion {
15178 old_range: range,
15179 new_text: snippet.body.clone(),
15180 resolved: false,
15181 label: CodeLabel {
15182 text: matching_prefix.clone(),
15183 runs: vec![],
15184 filter_range: 0..matching_prefix.len(),
15185 },
15186 server_id: LanguageServerId(usize::MAX),
15187 documentation: snippet
15188 .description
15189 .clone()
15190 .map(CompletionDocumentation::SingleLine),
15191 lsp_completion: lsp::CompletionItem {
15192 label: snippet.prefix.first().unwrap().clone(),
15193 kind: Some(CompletionItemKind::SNIPPET),
15194 label_details: snippet.description.as_ref().map(|description| {
15195 lsp::CompletionItemLabelDetails {
15196 detail: Some(description.clone()),
15197 description: None,
15198 }
15199 }),
15200 insert_text_format: Some(InsertTextFormat::SNIPPET),
15201 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15202 lsp::InsertReplaceEdit {
15203 new_text: snippet.body.clone(),
15204 insert: lsp_range,
15205 replace: lsp_range,
15206 },
15207 )),
15208 filter_text: Some(snippet.body.clone()),
15209 sort_text: Some(char::MAX.to_string()),
15210 ..Default::default()
15211 },
15212 confirm: None,
15213 })
15214 })
15215 .collect();
15216
15217 Ok(result)
15218 })
15219}
15220
15221impl CompletionProvider for Entity<Project> {
15222 fn completions(
15223 &self,
15224 buffer: &Entity<Buffer>,
15225 buffer_position: text::Anchor,
15226 options: CompletionContext,
15227 _window: &mut Window,
15228 cx: &mut Context<Editor>,
15229 ) -> Task<Result<Vec<Completion>>> {
15230 self.update(cx, |project, cx| {
15231 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15232 let project_completions = project.completions(buffer, buffer_position, options, cx);
15233 cx.background_executor().spawn(async move {
15234 let mut completions = project_completions.await?;
15235 let snippets_completions = snippets.await?;
15236 completions.extend(snippets_completions);
15237 Ok(completions)
15238 })
15239 })
15240 }
15241
15242 fn resolve_completions(
15243 &self,
15244 buffer: Entity<Buffer>,
15245 completion_indices: Vec<usize>,
15246 completions: Rc<RefCell<Box<[Completion]>>>,
15247 cx: &mut Context<Editor>,
15248 ) -> Task<Result<bool>> {
15249 self.update(cx, |project, cx| {
15250 project.lsp_store().update(cx, |lsp_store, cx| {
15251 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15252 })
15253 })
15254 }
15255
15256 fn apply_additional_edits_for_completion(
15257 &self,
15258 buffer: Entity<Buffer>,
15259 completions: Rc<RefCell<Box<[Completion]>>>,
15260 completion_index: usize,
15261 push_to_history: bool,
15262 cx: &mut Context<Editor>,
15263 ) -> Task<Result<Option<language::Transaction>>> {
15264 self.update(cx, |project, cx| {
15265 project.lsp_store().update(cx, |lsp_store, cx| {
15266 lsp_store.apply_additional_edits_for_completion(
15267 buffer,
15268 completions,
15269 completion_index,
15270 push_to_history,
15271 cx,
15272 )
15273 })
15274 })
15275 }
15276
15277 fn is_completion_trigger(
15278 &self,
15279 buffer: &Entity<Buffer>,
15280 position: language::Anchor,
15281 text: &str,
15282 trigger_in_words: bool,
15283 cx: &mut Context<Editor>,
15284 ) -> bool {
15285 let mut chars = text.chars();
15286 let char = if let Some(char) = chars.next() {
15287 char
15288 } else {
15289 return false;
15290 };
15291 if chars.next().is_some() {
15292 return false;
15293 }
15294
15295 let buffer = buffer.read(cx);
15296 let snapshot = buffer.snapshot();
15297 if !snapshot.settings_at(position, cx).show_completions_on_input {
15298 return false;
15299 }
15300 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15301 if trigger_in_words && classifier.is_word(char) {
15302 return true;
15303 }
15304
15305 buffer.completion_triggers().contains(text)
15306 }
15307}
15308
15309impl SemanticsProvider for Entity<Project> {
15310 fn hover(
15311 &self,
15312 buffer: &Entity<Buffer>,
15313 position: text::Anchor,
15314 cx: &mut App,
15315 ) -> Option<Task<Vec<project::Hover>>> {
15316 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15317 }
15318
15319 fn document_highlights(
15320 &self,
15321 buffer: &Entity<Buffer>,
15322 position: text::Anchor,
15323 cx: &mut App,
15324 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15325 Some(self.update(cx, |project, cx| {
15326 project.document_highlights(buffer, position, cx)
15327 }))
15328 }
15329
15330 fn definitions(
15331 &self,
15332 buffer: &Entity<Buffer>,
15333 position: text::Anchor,
15334 kind: GotoDefinitionKind,
15335 cx: &mut App,
15336 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15337 Some(self.update(cx, |project, cx| match kind {
15338 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15339 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15340 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15341 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15342 }))
15343 }
15344
15345 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15346 // TODO: make this work for remote projects
15347 self.read(cx)
15348 .language_servers_for_local_buffer(buffer.read(cx), cx)
15349 .any(
15350 |(_, server)| match server.capabilities().inlay_hint_provider {
15351 Some(lsp::OneOf::Left(enabled)) => enabled,
15352 Some(lsp::OneOf::Right(_)) => true,
15353 None => false,
15354 },
15355 )
15356 }
15357
15358 fn inlay_hints(
15359 &self,
15360 buffer_handle: Entity<Buffer>,
15361 range: Range<text::Anchor>,
15362 cx: &mut App,
15363 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15364 Some(self.update(cx, |project, cx| {
15365 project.inlay_hints(buffer_handle, range, cx)
15366 }))
15367 }
15368
15369 fn resolve_inlay_hint(
15370 &self,
15371 hint: InlayHint,
15372 buffer_handle: Entity<Buffer>,
15373 server_id: LanguageServerId,
15374 cx: &mut App,
15375 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15376 Some(self.update(cx, |project, cx| {
15377 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15378 }))
15379 }
15380
15381 fn range_for_rename(
15382 &self,
15383 buffer: &Entity<Buffer>,
15384 position: text::Anchor,
15385 cx: &mut App,
15386 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15387 Some(self.update(cx, |project, cx| {
15388 let buffer = buffer.clone();
15389 let task = project.prepare_rename(buffer.clone(), position, cx);
15390 cx.spawn(|_, mut cx| async move {
15391 Ok(match task.await? {
15392 PrepareRenameResponse::Success(range) => Some(range),
15393 PrepareRenameResponse::InvalidPosition => None,
15394 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15395 // Fallback on using TreeSitter info to determine identifier range
15396 buffer.update(&mut cx, |buffer, _| {
15397 let snapshot = buffer.snapshot();
15398 let (range, kind) = snapshot.surrounding_word(position);
15399 if kind != Some(CharKind::Word) {
15400 return None;
15401 }
15402 Some(
15403 snapshot.anchor_before(range.start)
15404 ..snapshot.anchor_after(range.end),
15405 )
15406 })?
15407 }
15408 })
15409 })
15410 }))
15411 }
15412
15413 fn perform_rename(
15414 &self,
15415 buffer: &Entity<Buffer>,
15416 position: text::Anchor,
15417 new_name: String,
15418 cx: &mut App,
15419 ) -> Option<Task<Result<ProjectTransaction>>> {
15420 Some(self.update(cx, |project, cx| {
15421 project.perform_rename(buffer.clone(), position, new_name, cx)
15422 }))
15423 }
15424}
15425
15426fn inlay_hint_settings(
15427 location: Anchor,
15428 snapshot: &MultiBufferSnapshot,
15429 cx: &mut Context<Editor>,
15430) -> InlayHintSettings {
15431 let file = snapshot.file_at(location);
15432 let language = snapshot.language_at(location).map(|l| l.name());
15433 language_settings(language, file, cx).inlay_hints
15434}
15435
15436fn consume_contiguous_rows(
15437 contiguous_row_selections: &mut Vec<Selection<Point>>,
15438 selection: &Selection<Point>,
15439 display_map: &DisplaySnapshot,
15440 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15441) -> (MultiBufferRow, MultiBufferRow) {
15442 contiguous_row_selections.push(selection.clone());
15443 let start_row = MultiBufferRow(selection.start.row);
15444 let mut end_row = ending_row(selection, display_map);
15445
15446 while let Some(next_selection) = selections.peek() {
15447 if next_selection.start.row <= end_row.0 {
15448 end_row = ending_row(next_selection, display_map);
15449 contiguous_row_selections.push(selections.next().unwrap().clone());
15450 } else {
15451 break;
15452 }
15453 }
15454 (start_row, end_row)
15455}
15456
15457fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15458 if next_selection.end.column > 0 || next_selection.is_empty() {
15459 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15460 } else {
15461 MultiBufferRow(next_selection.end.row)
15462 }
15463}
15464
15465impl EditorSnapshot {
15466 pub fn remote_selections_in_range<'a>(
15467 &'a self,
15468 range: &'a Range<Anchor>,
15469 collaboration_hub: &dyn CollaborationHub,
15470 cx: &'a App,
15471 ) -> impl 'a + Iterator<Item = RemoteSelection> {
15472 let participant_names = collaboration_hub.user_names(cx);
15473 let participant_indices = collaboration_hub.user_participant_indices(cx);
15474 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15475 let collaborators_by_replica_id = collaborators_by_peer_id
15476 .iter()
15477 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15478 .collect::<HashMap<_, _>>();
15479 self.buffer_snapshot
15480 .selections_in_range(range, false)
15481 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15482 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15483 let participant_index = participant_indices.get(&collaborator.user_id).copied();
15484 let user_name = participant_names.get(&collaborator.user_id).cloned();
15485 Some(RemoteSelection {
15486 replica_id,
15487 selection,
15488 cursor_shape,
15489 line_mode,
15490 participant_index,
15491 peer_id: collaborator.peer_id,
15492 user_name,
15493 })
15494 })
15495 }
15496
15497 pub fn hunks_for_ranges(
15498 &self,
15499 ranges: impl Iterator<Item = Range<Point>>,
15500 ) -> Vec<MultiBufferDiffHunk> {
15501 let mut hunks = Vec::new();
15502 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15503 HashMap::default();
15504 for query_range in ranges {
15505 let query_rows =
15506 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15507 for hunk in self.buffer_snapshot.diff_hunks_in_range(
15508 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15509 ) {
15510 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15511 // when the caret is just above or just below the deleted hunk.
15512 let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15513 let related_to_selection = if allow_adjacent {
15514 hunk.row_range.overlaps(&query_rows)
15515 || hunk.row_range.start == query_rows.end
15516 || hunk.row_range.end == query_rows.start
15517 } else {
15518 hunk.row_range.overlaps(&query_rows)
15519 };
15520 if related_to_selection {
15521 if !processed_buffer_rows
15522 .entry(hunk.buffer_id)
15523 .or_default()
15524 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15525 {
15526 continue;
15527 }
15528 hunks.push(hunk);
15529 }
15530 }
15531 }
15532
15533 hunks
15534 }
15535
15536 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15537 self.display_snapshot.buffer_snapshot.language_at(position)
15538 }
15539
15540 pub fn is_focused(&self) -> bool {
15541 self.is_focused
15542 }
15543
15544 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15545 self.placeholder_text.as_ref()
15546 }
15547
15548 pub fn scroll_position(&self) -> gpui::Point<f32> {
15549 self.scroll_anchor.scroll_position(&self.display_snapshot)
15550 }
15551
15552 fn gutter_dimensions(
15553 &self,
15554 font_id: FontId,
15555 font_size: Pixels,
15556 max_line_number_width: Pixels,
15557 cx: &App,
15558 ) -> Option<GutterDimensions> {
15559 if !self.show_gutter {
15560 return None;
15561 }
15562
15563 let descent = cx.text_system().descent(font_id, font_size);
15564 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15565 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15566
15567 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15568 matches!(
15569 ProjectSettings::get_global(cx).git.git_gutter,
15570 Some(GitGutterSetting::TrackedFiles)
15571 )
15572 });
15573 let gutter_settings = EditorSettings::get_global(cx).gutter;
15574 let show_line_numbers = self
15575 .show_line_numbers
15576 .unwrap_or(gutter_settings.line_numbers);
15577 let line_gutter_width = if show_line_numbers {
15578 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15579 let min_width_for_number_on_gutter = em_advance * 4.0;
15580 max_line_number_width.max(min_width_for_number_on_gutter)
15581 } else {
15582 0.0.into()
15583 };
15584
15585 let show_code_actions = self
15586 .show_code_actions
15587 .unwrap_or(gutter_settings.code_actions);
15588
15589 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15590
15591 let git_blame_entries_width =
15592 self.git_blame_gutter_max_author_length
15593 .map(|max_author_length| {
15594 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15595
15596 /// The number of characters to dedicate to gaps and margins.
15597 const SPACING_WIDTH: usize = 4;
15598
15599 let max_char_count = max_author_length
15600 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15601 + ::git::SHORT_SHA_LENGTH
15602 + MAX_RELATIVE_TIMESTAMP.len()
15603 + SPACING_WIDTH;
15604
15605 em_advance * max_char_count
15606 });
15607
15608 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15609 left_padding += if show_code_actions || show_runnables {
15610 em_width * 3.0
15611 } else if show_git_gutter && show_line_numbers {
15612 em_width * 2.0
15613 } else if show_git_gutter || show_line_numbers {
15614 em_width
15615 } else {
15616 px(0.)
15617 };
15618
15619 let right_padding = if gutter_settings.folds && show_line_numbers {
15620 em_width * 4.0
15621 } else if gutter_settings.folds {
15622 em_width * 3.0
15623 } else if show_line_numbers {
15624 em_width
15625 } else {
15626 px(0.)
15627 };
15628
15629 Some(GutterDimensions {
15630 left_padding,
15631 right_padding,
15632 width: line_gutter_width + left_padding + right_padding,
15633 margin: -descent,
15634 git_blame_entries_width,
15635 })
15636 }
15637
15638 pub fn render_crease_toggle(
15639 &self,
15640 buffer_row: MultiBufferRow,
15641 row_contains_cursor: bool,
15642 editor: Entity<Editor>,
15643 window: &mut Window,
15644 cx: &mut App,
15645 ) -> Option<AnyElement> {
15646 let folded = self.is_line_folded(buffer_row);
15647 let mut is_foldable = false;
15648
15649 if let Some(crease) = self
15650 .crease_snapshot
15651 .query_row(buffer_row, &self.buffer_snapshot)
15652 {
15653 is_foldable = true;
15654 match crease {
15655 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15656 if let Some(render_toggle) = render_toggle {
15657 let toggle_callback =
15658 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15659 if folded {
15660 editor.update(cx, |editor, cx| {
15661 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15662 });
15663 } else {
15664 editor.update(cx, |editor, cx| {
15665 editor.unfold_at(
15666 &crate::UnfoldAt { buffer_row },
15667 window,
15668 cx,
15669 )
15670 });
15671 }
15672 });
15673 return Some((render_toggle)(
15674 buffer_row,
15675 folded,
15676 toggle_callback,
15677 window,
15678 cx,
15679 ));
15680 }
15681 }
15682 }
15683 }
15684
15685 is_foldable |= self.starts_indent(buffer_row);
15686
15687 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15688 Some(
15689 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15690 .toggle_state(folded)
15691 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15692 if folded {
15693 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15694 } else {
15695 this.fold_at(&FoldAt { buffer_row }, window, cx);
15696 }
15697 }))
15698 .into_any_element(),
15699 )
15700 } else {
15701 None
15702 }
15703 }
15704
15705 pub fn render_crease_trailer(
15706 &self,
15707 buffer_row: MultiBufferRow,
15708 window: &mut Window,
15709 cx: &mut App,
15710 ) -> Option<AnyElement> {
15711 let folded = self.is_line_folded(buffer_row);
15712 if let Crease::Inline { render_trailer, .. } = self
15713 .crease_snapshot
15714 .query_row(buffer_row, &self.buffer_snapshot)?
15715 {
15716 let render_trailer = render_trailer.as_ref()?;
15717 Some(render_trailer(buffer_row, folded, window, cx))
15718 } else {
15719 None
15720 }
15721 }
15722}
15723
15724impl Deref for EditorSnapshot {
15725 type Target = DisplaySnapshot;
15726
15727 fn deref(&self) -> &Self::Target {
15728 &self.display_snapshot
15729 }
15730}
15731
15732#[derive(Clone, Debug, PartialEq, Eq)]
15733pub enum EditorEvent {
15734 InputIgnored {
15735 text: Arc<str>,
15736 },
15737 InputHandled {
15738 utf16_range_to_replace: Option<Range<isize>>,
15739 text: Arc<str>,
15740 },
15741 ExcerptsAdded {
15742 buffer: Entity<Buffer>,
15743 predecessor: ExcerptId,
15744 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15745 },
15746 ExcerptsRemoved {
15747 ids: Vec<ExcerptId>,
15748 },
15749 BufferFoldToggled {
15750 ids: Vec<ExcerptId>,
15751 folded: bool,
15752 },
15753 ExcerptsEdited {
15754 ids: Vec<ExcerptId>,
15755 },
15756 ExcerptsExpanded {
15757 ids: Vec<ExcerptId>,
15758 },
15759 BufferEdited,
15760 Edited {
15761 transaction_id: clock::Lamport,
15762 },
15763 Reparsed(BufferId),
15764 Focused,
15765 FocusedIn,
15766 Blurred,
15767 DirtyChanged,
15768 Saved,
15769 TitleChanged,
15770 DiffBaseChanged,
15771 SelectionsChanged {
15772 local: bool,
15773 },
15774 ScrollPositionChanged {
15775 local: bool,
15776 autoscroll: bool,
15777 },
15778 Closed,
15779 TransactionUndone {
15780 transaction_id: clock::Lamport,
15781 },
15782 TransactionBegun {
15783 transaction_id: clock::Lamport,
15784 },
15785 Reloaded,
15786 CursorShapeChanged,
15787}
15788
15789impl EventEmitter<EditorEvent> for Editor {}
15790
15791impl Focusable for Editor {
15792 fn focus_handle(&self, _cx: &App) -> FocusHandle {
15793 self.focus_handle.clone()
15794 }
15795}
15796
15797impl Render for Editor {
15798 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15799 let settings = ThemeSettings::get_global(cx);
15800
15801 let mut text_style = match self.mode {
15802 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15803 color: cx.theme().colors().editor_foreground,
15804 font_family: settings.ui_font.family.clone(),
15805 font_features: settings.ui_font.features.clone(),
15806 font_fallbacks: settings.ui_font.fallbacks.clone(),
15807 font_size: rems(0.875).into(),
15808 font_weight: settings.ui_font.weight,
15809 line_height: relative(settings.buffer_line_height.value()),
15810 ..Default::default()
15811 },
15812 EditorMode::Full => TextStyle {
15813 color: cx.theme().colors().editor_foreground,
15814 font_family: settings.buffer_font.family.clone(),
15815 font_features: settings.buffer_font.features.clone(),
15816 font_fallbacks: settings.buffer_font.fallbacks.clone(),
15817 font_size: settings.buffer_font_size().into(),
15818 font_weight: settings.buffer_font.weight,
15819 line_height: relative(settings.buffer_line_height.value()),
15820 ..Default::default()
15821 },
15822 };
15823 if let Some(text_style_refinement) = &self.text_style_refinement {
15824 text_style.refine(text_style_refinement)
15825 }
15826
15827 let background = match self.mode {
15828 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15829 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15830 EditorMode::Full => cx.theme().colors().editor_background,
15831 };
15832
15833 EditorElement::new(
15834 &cx.entity(),
15835 EditorStyle {
15836 background,
15837 local_player: cx.theme().players().local(),
15838 text: text_style,
15839 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15840 syntax: cx.theme().syntax().clone(),
15841 status: cx.theme().status().clone(),
15842 inlay_hints_style: make_inlay_hints_style(cx),
15843 inline_completion_styles: make_suggestion_styles(cx),
15844 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15845 },
15846 )
15847 }
15848}
15849
15850impl EntityInputHandler for Editor {
15851 fn text_for_range(
15852 &mut self,
15853 range_utf16: Range<usize>,
15854 adjusted_range: &mut Option<Range<usize>>,
15855 _: &mut Window,
15856 cx: &mut Context<Self>,
15857 ) -> Option<String> {
15858 let snapshot = self.buffer.read(cx).read(cx);
15859 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15860 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15861 if (start.0..end.0) != range_utf16 {
15862 adjusted_range.replace(start.0..end.0);
15863 }
15864 Some(snapshot.text_for_range(start..end).collect())
15865 }
15866
15867 fn selected_text_range(
15868 &mut self,
15869 ignore_disabled_input: bool,
15870 _: &mut Window,
15871 cx: &mut Context<Self>,
15872 ) -> Option<UTF16Selection> {
15873 // Prevent the IME menu from appearing when holding down an alphabetic key
15874 // while input is disabled.
15875 if !ignore_disabled_input && !self.input_enabled {
15876 return None;
15877 }
15878
15879 let selection = self.selections.newest::<OffsetUtf16>(cx);
15880 let range = selection.range();
15881
15882 Some(UTF16Selection {
15883 range: range.start.0..range.end.0,
15884 reversed: selection.reversed,
15885 })
15886 }
15887
15888 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15889 let snapshot = self.buffer.read(cx).read(cx);
15890 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15891 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15892 }
15893
15894 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15895 self.clear_highlights::<InputComposition>(cx);
15896 self.ime_transaction.take();
15897 }
15898
15899 fn replace_text_in_range(
15900 &mut self,
15901 range_utf16: Option<Range<usize>>,
15902 text: &str,
15903 window: &mut Window,
15904 cx: &mut Context<Self>,
15905 ) {
15906 if !self.input_enabled {
15907 cx.emit(EditorEvent::InputIgnored { text: text.into() });
15908 return;
15909 }
15910
15911 self.transact(window, cx, |this, window, cx| {
15912 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15913 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15914 Some(this.selection_replacement_ranges(range_utf16, cx))
15915 } else {
15916 this.marked_text_ranges(cx)
15917 };
15918
15919 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15920 let newest_selection_id = this.selections.newest_anchor().id;
15921 this.selections
15922 .all::<OffsetUtf16>(cx)
15923 .iter()
15924 .zip(ranges_to_replace.iter())
15925 .find_map(|(selection, range)| {
15926 if selection.id == newest_selection_id {
15927 Some(
15928 (range.start.0 as isize - selection.head().0 as isize)
15929 ..(range.end.0 as isize - selection.head().0 as isize),
15930 )
15931 } else {
15932 None
15933 }
15934 })
15935 });
15936
15937 cx.emit(EditorEvent::InputHandled {
15938 utf16_range_to_replace: range_to_replace,
15939 text: text.into(),
15940 });
15941
15942 if let Some(new_selected_ranges) = new_selected_ranges {
15943 this.change_selections(None, window, cx, |selections| {
15944 selections.select_ranges(new_selected_ranges)
15945 });
15946 this.backspace(&Default::default(), window, cx);
15947 }
15948
15949 this.handle_input(text, window, cx);
15950 });
15951
15952 if let Some(transaction) = self.ime_transaction {
15953 self.buffer.update(cx, |buffer, cx| {
15954 buffer.group_until_transaction(transaction, cx);
15955 });
15956 }
15957
15958 self.unmark_text(window, cx);
15959 }
15960
15961 fn replace_and_mark_text_in_range(
15962 &mut self,
15963 range_utf16: Option<Range<usize>>,
15964 text: &str,
15965 new_selected_range_utf16: Option<Range<usize>>,
15966 window: &mut Window,
15967 cx: &mut Context<Self>,
15968 ) {
15969 if !self.input_enabled {
15970 return;
15971 }
15972
15973 let transaction = self.transact(window, cx, |this, window, cx| {
15974 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15975 let snapshot = this.buffer.read(cx).read(cx);
15976 if let Some(relative_range_utf16) = range_utf16.as_ref() {
15977 for marked_range in &mut marked_ranges {
15978 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15979 marked_range.start.0 += relative_range_utf16.start;
15980 marked_range.start =
15981 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15982 marked_range.end =
15983 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15984 }
15985 }
15986 Some(marked_ranges)
15987 } else if let Some(range_utf16) = range_utf16 {
15988 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15989 Some(this.selection_replacement_ranges(range_utf16, cx))
15990 } else {
15991 None
15992 };
15993
15994 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
15995 let newest_selection_id = this.selections.newest_anchor().id;
15996 this.selections
15997 .all::<OffsetUtf16>(cx)
15998 .iter()
15999 .zip(ranges_to_replace.iter())
16000 .find_map(|(selection, range)| {
16001 if selection.id == newest_selection_id {
16002 Some(
16003 (range.start.0 as isize - selection.head().0 as isize)
16004 ..(range.end.0 as isize - selection.head().0 as isize),
16005 )
16006 } else {
16007 None
16008 }
16009 })
16010 });
16011
16012 cx.emit(EditorEvent::InputHandled {
16013 utf16_range_to_replace: range_to_replace,
16014 text: text.into(),
16015 });
16016
16017 if let Some(ranges) = ranges_to_replace {
16018 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16019 }
16020
16021 let marked_ranges = {
16022 let snapshot = this.buffer.read(cx).read(cx);
16023 this.selections
16024 .disjoint_anchors()
16025 .iter()
16026 .map(|selection| {
16027 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16028 })
16029 .collect::<Vec<_>>()
16030 };
16031
16032 if text.is_empty() {
16033 this.unmark_text(window, cx);
16034 } else {
16035 this.highlight_text::<InputComposition>(
16036 marked_ranges.clone(),
16037 HighlightStyle {
16038 underline: Some(UnderlineStyle {
16039 thickness: px(1.),
16040 color: None,
16041 wavy: false,
16042 }),
16043 ..Default::default()
16044 },
16045 cx,
16046 );
16047 }
16048
16049 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16050 let use_autoclose = this.use_autoclose;
16051 let use_auto_surround = this.use_auto_surround;
16052 this.set_use_autoclose(false);
16053 this.set_use_auto_surround(false);
16054 this.handle_input(text, window, cx);
16055 this.set_use_autoclose(use_autoclose);
16056 this.set_use_auto_surround(use_auto_surround);
16057
16058 if let Some(new_selected_range) = new_selected_range_utf16 {
16059 let snapshot = this.buffer.read(cx).read(cx);
16060 let new_selected_ranges = marked_ranges
16061 .into_iter()
16062 .map(|marked_range| {
16063 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16064 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16065 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16066 snapshot.clip_offset_utf16(new_start, Bias::Left)
16067 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16068 })
16069 .collect::<Vec<_>>();
16070
16071 drop(snapshot);
16072 this.change_selections(None, window, cx, |selections| {
16073 selections.select_ranges(new_selected_ranges)
16074 });
16075 }
16076 });
16077
16078 self.ime_transaction = self.ime_transaction.or(transaction);
16079 if let Some(transaction) = self.ime_transaction {
16080 self.buffer.update(cx, |buffer, cx| {
16081 buffer.group_until_transaction(transaction, cx);
16082 });
16083 }
16084
16085 if self.text_highlights::<InputComposition>(cx).is_none() {
16086 self.ime_transaction.take();
16087 }
16088 }
16089
16090 fn bounds_for_range(
16091 &mut self,
16092 range_utf16: Range<usize>,
16093 element_bounds: gpui::Bounds<Pixels>,
16094 window: &mut Window,
16095 cx: &mut Context<Self>,
16096 ) -> Option<gpui::Bounds<Pixels>> {
16097 let text_layout_details = self.text_layout_details(window);
16098 let gpui::Size {
16099 width: em_width,
16100 height: line_height,
16101 } = self.character_size(window);
16102
16103 let snapshot = self.snapshot(window, cx);
16104 let scroll_position = snapshot.scroll_position();
16105 let scroll_left = scroll_position.x * em_width;
16106
16107 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16108 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16109 + self.gutter_dimensions.width
16110 + self.gutter_dimensions.margin;
16111 let y = line_height * (start.row().as_f32() - scroll_position.y);
16112
16113 Some(Bounds {
16114 origin: element_bounds.origin + point(x, y),
16115 size: size(em_width, line_height),
16116 })
16117 }
16118
16119 fn character_index_for_point(
16120 &mut self,
16121 point: gpui::Point<Pixels>,
16122 _window: &mut Window,
16123 _cx: &mut Context<Self>,
16124 ) -> Option<usize> {
16125 let position_map = self.last_position_map.as_ref()?;
16126 if !position_map.text_hitbox.contains(&point) {
16127 return None;
16128 }
16129 let display_point = position_map.point_for_position(point).previous_valid;
16130 let anchor = position_map
16131 .snapshot
16132 .display_point_to_anchor(display_point, Bias::Left);
16133 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16134 Some(utf16_offset.0)
16135 }
16136}
16137
16138trait SelectionExt {
16139 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16140 fn spanned_rows(
16141 &self,
16142 include_end_if_at_line_start: bool,
16143 map: &DisplaySnapshot,
16144 ) -> Range<MultiBufferRow>;
16145}
16146
16147impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16148 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16149 let start = self
16150 .start
16151 .to_point(&map.buffer_snapshot)
16152 .to_display_point(map);
16153 let end = self
16154 .end
16155 .to_point(&map.buffer_snapshot)
16156 .to_display_point(map);
16157 if self.reversed {
16158 end..start
16159 } else {
16160 start..end
16161 }
16162 }
16163
16164 fn spanned_rows(
16165 &self,
16166 include_end_if_at_line_start: bool,
16167 map: &DisplaySnapshot,
16168 ) -> Range<MultiBufferRow> {
16169 let start = self.start.to_point(&map.buffer_snapshot);
16170 let mut end = self.end.to_point(&map.buffer_snapshot);
16171 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16172 end.row -= 1;
16173 }
16174
16175 let buffer_start = map.prev_line_boundary(start).0;
16176 let buffer_end = map.next_line_boundary(end).0;
16177 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16178 }
16179}
16180
16181impl<T: InvalidationRegion> InvalidationStack<T> {
16182 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16183 where
16184 S: Clone + ToOffset,
16185 {
16186 while let Some(region) = self.last() {
16187 let all_selections_inside_invalidation_ranges =
16188 if selections.len() == region.ranges().len() {
16189 selections
16190 .iter()
16191 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16192 .all(|(selection, invalidation_range)| {
16193 let head = selection.head().to_offset(buffer);
16194 invalidation_range.start <= head && invalidation_range.end >= head
16195 })
16196 } else {
16197 false
16198 };
16199
16200 if all_selections_inside_invalidation_ranges {
16201 break;
16202 } else {
16203 self.pop();
16204 }
16205 }
16206 }
16207}
16208
16209impl<T> Default for InvalidationStack<T> {
16210 fn default() -> Self {
16211 Self(Default::default())
16212 }
16213}
16214
16215impl<T> Deref for InvalidationStack<T> {
16216 type Target = Vec<T>;
16217
16218 fn deref(&self) -> &Self::Target {
16219 &self.0
16220 }
16221}
16222
16223impl<T> DerefMut for InvalidationStack<T> {
16224 fn deref_mut(&mut self) -> &mut Self::Target {
16225 &mut self.0
16226 }
16227}
16228
16229impl InvalidationRegion for SnippetState {
16230 fn ranges(&self) -> &[Range<Anchor>] {
16231 &self.ranges[self.active_index]
16232 }
16233}
16234
16235pub fn diagnostic_block_renderer(
16236 diagnostic: Diagnostic,
16237 max_message_rows: Option<u8>,
16238 allow_closing: bool,
16239 _is_valid: bool,
16240) -> RenderBlock {
16241 let (text_without_backticks, code_ranges) =
16242 highlight_diagnostic_message(&diagnostic, max_message_rows);
16243
16244 Arc::new(move |cx: &mut BlockContext| {
16245 let group_id: SharedString = cx.block_id.to_string().into();
16246
16247 let mut text_style = cx.window.text_style().clone();
16248 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16249 let theme_settings = ThemeSettings::get_global(cx);
16250 text_style.font_family = theme_settings.buffer_font.family.clone();
16251 text_style.font_style = theme_settings.buffer_font.style;
16252 text_style.font_features = theme_settings.buffer_font.features.clone();
16253 text_style.font_weight = theme_settings.buffer_font.weight;
16254
16255 let multi_line_diagnostic = diagnostic.message.contains('\n');
16256
16257 let buttons = |diagnostic: &Diagnostic| {
16258 if multi_line_diagnostic {
16259 v_flex()
16260 } else {
16261 h_flex()
16262 }
16263 .when(allow_closing, |div| {
16264 div.children(diagnostic.is_primary.then(|| {
16265 IconButton::new("close-block", IconName::XCircle)
16266 .icon_color(Color::Muted)
16267 .size(ButtonSize::Compact)
16268 .style(ButtonStyle::Transparent)
16269 .visible_on_hover(group_id.clone())
16270 .on_click(move |_click, window, cx| {
16271 window.dispatch_action(Box::new(Cancel), cx)
16272 })
16273 .tooltip(|window, cx| {
16274 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16275 })
16276 }))
16277 })
16278 .child(
16279 IconButton::new("copy-block", IconName::Copy)
16280 .icon_color(Color::Muted)
16281 .size(ButtonSize::Compact)
16282 .style(ButtonStyle::Transparent)
16283 .visible_on_hover(group_id.clone())
16284 .on_click({
16285 let message = diagnostic.message.clone();
16286 move |_click, _, cx| {
16287 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16288 }
16289 })
16290 .tooltip(Tooltip::text("Copy diagnostic message")),
16291 )
16292 };
16293
16294 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16295 AvailableSpace::min_size(),
16296 cx.window,
16297 cx.app,
16298 );
16299
16300 h_flex()
16301 .id(cx.block_id)
16302 .group(group_id.clone())
16303 .relative()
16304 .size_full()
16305 .block_mouse_down()
16306 .pl(cx.gutter_dimensions.width)
16307 .w(cx.max_width - cx.gutter_dimensions.full_width())
16308 .child(
16309 div()
16310 .flex()
16311 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16312 .flex_shrink(),
16313 )
16314 .child(buttons(&diagnostic))
16315 .child(div().flex().flex_shrink_0().child(
16316 StyledText::new(text_without_backticks.clone()).with_highlights(
16317 &text_style,
16318 code_ranges.iter().map(|range| {
16319 (
16320 range.clone(),
16321 HighlightStyle {
16322 font_weight: Some(FontWeight::BOLD),
16323 ..Default::default()
16324 },
16325 )
16326 }),
16327 ),
16328 ))
16329 .into_any_element()
16330 })
16331}
16332
16333fn inline_completion_edit_text(
16334 current_snapshot: &BufferSnapshot,
16335 edits: &[(Range<Anchor>, String)],
16336 edit_preview: &EditPreview,
16337 include_deletions: bool,
16338 cx: &App,
16339) -> HighlightedText {
16340 let edits = edits
16341 .iter()
16342 .map(|(anchor, text)| {
16343 (
16344 anchor.start.text_anchor..anchor.end.text_anchor,
16345 text.clone(),
16346 )
16347 })
16348 .collect::<Vec<_>>();
16349
16350 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16351}
16352
16353pub fn highlight_diagnostic_message(
16354 diagnostic: &Diagnostic,
16355 mut max_message_rows: Option<u8>,
16356) -> (SharedString, Vec<Range<usize>>) {
16357 let mut text_without_backticks = String::new();
16358 let mut code_ranges = Vec::new();
16359
16360 if let Some(source) = &diagnostic.source {
16361 text_without_backticks.push_str(source);
16362 code_ranges.push(0..source.len());
16363 text_without_backticks.push_str(": ");
16364 }
16365
16366 let mut prev_offset = 0;
16367 let mut in_code_block = false;
16368 let has_row_limit = max_message_rows.is_some();
16369 let mut newline_indices = diagnostic
16370 .message
16371 .match_indices('\n')
16372 .filter(|_| has_row_limit)
16373 .map(|(ix, _)| ix)
16374 .fuse()
16375 .peekable();
16376
16377 for (quote_ix, _) in diagnostic
16378 .message
16379 .match_indices('`')
16380 .chain([(diagnostic.message.len(), "")])
16381 {
16382 let mut first_newline_ix = None;
16383 let mut last_newline_ix = None;
16384 while let Some(newline_ix) = newline_indices.peek() {
16385 if *newline_ix < quote_ix {
16386 if first_newline_ix.is_none() {
16387 first_newline_ix = Some(*newline_ix);
16388 }
16389 last_newline_ix = Some(*newline_ix);
16390
16391 if let Some(rows_left) = &mut max_message_rows {
16392 if *rows_left == 0 {
16393 break;
16394 } else {
16395 *rows_left -= 1;
16396 }
16397 }
16398 let _ = newline_indices.next();
16399 } else {
16400 break;
16401 }
16402 }
16403 let prev_len = text_without_backticks.len();
16404 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16405 text_without_backticks.push_str(new_text);
16406 if in_code_block {
16407 code_ranges.push(prev_len..text_without_backticks.len());
16408 }
16409 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16410 in_code_block = !in_code_block;
16411 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16412 text_without_backticks.push_str("...");
16413 break;
16414 }
16415 }
16416
16417 (text_without_backticks.into(), code_ranges)
16418}
16419
16420fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16421 match severity {
16422 DiagnosticSeverity::ERROR => colors.error,
16423 DiagnosticSeverity::WARNING => colors.warning,
16424 DiagnosticSeverity::INFORMATION => colors.info,
16425 DiagnosticSeverity::HINT => colors.info,
16426 _ => colors.ignored,
16427 }
16428}
16429
16430pub fn styled_runs_for_code_label<'a>(
16431 label: &'a CodeLabel,
16432 syntax_theme: &'a theme::SyntaxTheme,
16433) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16434 let fade_out = HighlightStyle {
16435 fade_out: Some(0.35),
16436 ..Default::default()
16437 };
16438
16439 let mut prev_end = label.filter_range.end;
16440 label
16441 .runs
16442 .iter()
16443 .enumerate()
16444 .flat_map(move |(ix, (range, highlight_id))| {
16445 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16446 style
16447 } else {
16448 return Default::default();
16449 };
16450 let mut muted_style = style;
16451 muted_style.highlight(fade_out);
16452
16453 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16454 if range.start >= label.filter_range.end {
16455 if range.start > prev_end {
16456 runs.push((prev_end..range.start, fade_out));
16457 }
16458 runs.push((range.clone(), muted_style));
16459 } else if range.end <= label.filter_range.end {
16460 runs.push((range.clone(), style));
16461 } else {
16462 runs.push((range.start..label.filter_range.end, style));
16463 runs.push((label.filter_range.end..range.end, muted_style));
16464 }
16465 prev_end = cmp::max(prev_end, range.end);
16466
16467 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16468 runs.push((prev_end..label.text.len(), fade_out));
16469 }
16470
16471 runs
16472 })
16473}
16474
16475pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16476 let mut prev_index = 0;
16477 let mut prev_codepoint: Option<char> = None;
16478 text.char_indices()
16479 .chain([(text.len(), '\0')])
16480 .filter_map(move |(index, codepoint)| {
16481 let prev_codepoint = prev_codepoint.replace(codepoint)?;
16482 let is_boundary = index == text.len()
16483 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16484 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16485 if is_boundary {
16486 let chunk = &text[prev_index..index];
16487 prev_index = index;
16488 Some(chunk)
16489 } else {
16490 None
16491 }
16492 })
16493}
16494
16495pub trait RangeToAnchorExt: Sized {
16496 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16497
16498 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16499 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16500 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16501 }
16502}
16503
16504impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16505 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16506 let start_offset = self.start.to_offset(snapshot);
16507 let end_offset = self.end.to_offset(snapshot);
16508 if start_offset == end_offset {
16509 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16510 } else {
16511 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16512 }
16513 }
16514}
16515
16516pub trait RowExt {
16517 fn as_f32(&self) -> f32;
16518
16519 fn next_row(&self) -> Self;
16520
16521 fn previous_row(&self) -> Self;
16522
16523 fn minus(&self, other: Self) -> u32;
16524}
16525
16526impl RowExt for DisplayRow {
16527 fn as_f32(&self) -> f32 {
16528 self.0 as f32
16529 }
16530
16531 fn next_row(&self) -> Self {
16532 Self(self.0 + 1)
16533 }
16534
16535 fn previous_row(&self) -> Self {
16536 Self(self.0.saturating_sub(1))
16537 }
16538
16539 fn minus(&self, other: Self) -> u32 {
16540 self.0 - other.0
16541 }
16542}
16543
16544impl RowExt for MultiBufferRow {
16545 fn as_f32(&self) -> f32 {
16546 self.0 as f32
16547 }
16548
16549 fn next_row(&self) -> Self {
16550 Self(self.0 + 1)
16551 }
16552
16553 fn previous_row(&self) -> Self {
16554 Self(self.0.saturating_sub(1))
16555 }
16556
16557 fn minus(&self, other: Self) -> u32 {
16558 self.0 - other.0
16559 }
16560}
16561
16562trait RowRangeExt {
16563 type Row;
16564
16565 fn len(&self) -> usize;
16566
16567 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16568}
16569
16570impl RowRangeExt for Range<MultiBufferRow> {
16571 type Row = MultiBufferRow;
16572
16573 fn len(&self) -> usize {
16574 (self.end.0 - self.start.0) as usize
16575 }
16576
16577 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16578 (self.start.0..self.end.0).map(MultiBufferRow)
16579 }
16580}
16581
16582impl RowRangeExt for Range<DisplayRow> {
16583 type Row = DisplayRow;
16584
16585 fn len(&self) -> usize {
16586 (self.end.0 - self.start.0) as usize
16587 }
16588
16589 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16590 (self.start.0..self.end.0).map(DisplayRow)
16591 }
16592}
16593
16594/// If select range has more than one line, we
16595/// just point the cursor to range.start.
16596fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16597 if range.start.row == range.end.row {
16598 range
16599 } else {
16600 range.start..range.start
16601 }
16602}
16603pub struct KillRing(ClipboardItem);
16604impl Global for KillRing {}
16605
16606const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16607
16608fn all_edits_insertions_or_deletions(
16609 edits: &Vec<(Range<Anchor>, String)>,
16610 snapshot: &MultiBufferSnapshot,
16611) -> bool {
16612 let mut all_insertions = true;
16613 let mut all_deletions = true;
16614
16615 for (range, new_text) in edits.iter() {
16616 let range_is_empty = range.to_offset(&snapshot).is_empty();
16617 let text_is_empty = new_text.is_empty();
16618
16619 if range_is_empty != text_is_empty {
16620 if range_is_empty {
16621 all_deletions = false;
16622 } else {
16623 all_insertions = false;
16624 }
16625 } else {
16626 return false;
16627 }
16628
16629 if !all_insertions && !all_deletions {
16630 return false;
16631 }
16632 }
16633 all_insertions || all_deletions
16634}