1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod clangd_ext;
19mod code_context_menus;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod indent_guides;
29mod inlay_hint_cache;
30pub mod items;
31mod linked_editing_ranges;
32mod lsp_ext;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod proposed_changes_editor;
37mod rust_analyzer_ext;
38pub mod scroll;
39mod selections_collection;
40pub mod tasks;
41
42#[cfg(test)]
43mod editor_tests;
44#[cfg(test)]
45mod inline_completion_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50use ::git::diff::DiffHunkStatus;
51pub(crate) use actions::*;
52pub use actions::{OpenExcerpts, OpenExcerptsSplit};
53use aho_corasick::AhoCorasick;
54use anyhow::{anyhow, Context as _, Result};
55use blink_manager::BlinkManager;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{
63 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
64};
65pub use editor_settings_controls::*;
66use element::LineWithInvisibles;
67pub use element::{
68 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
69};
70use futures::{future, FutureExt};
71use fuzzy::StringMatchCandidate;
72
73use code_context_menus::{
74 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
75 CompletionsMenu, ContextMenuOrigin,
76};
77use git::blame::GitBlame;
78use gpui::{
79 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
80 AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry,
81 ClipboardItem, Context, DispatchPhase, ElementId, Entity, EntityInputHandler, EventEmitter,
82 FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla,
83 InteractiveText, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad, ParentElement,
84 Pixels, Render, SharedString, Size, Styled, StyledText, Subscription, Task, TextStyle,
85 TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity,
86 WeakFocusHandle, Window,
87};
88use highlight_matching_bracket::refresh_matching_bracket_highlights;
89use hover_popover::{hide_hover, HoverState};
90use indent_guides::ActiveIndentGuidesState;
91use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
92pub use inline_completion::Direction;
93use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
94pub use items::MAX_TAB_TITLE_LEN;
95use itertools::Itertools;
96use language::{
97 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
98 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
99 CompletionDocumentation, CursorShape, Diagnostic, EditPreview, HighlightedText, IndentKind,
100 IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
101 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::{self, 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 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
128};
129use project::{
130 lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
131 project_settings::{GitGutterSetting, ProjectSettings},
132 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
133 LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
134};
135use rand::prelude::*;
136use rpc::{proto::*, ErrorExt};
137use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
138use selections_collection::{
139 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
140};
141use serde::{Deserialize, Serialize};
142use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
143use smallvec::SmallVec;
144use snippet::Snippet;
145use std::{
146 any::TypeId,
147 borrow::Cow,
148 cell::RefCell,
149 cmp::{self, Ordering, Reverse},
150 mem,
151 num::NonZeroU32,
152 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
153 path::{Path, PathBuf},
154 rc::Rc,
155 sync::Arc,
156 time::{Duration, Instant},
157};
158pub use sum_tree::Bias;
159use sum_tree::TreeMap;
160use text::{BufferId, OffsetUtf16, Rope};
161use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
162use ui::{
163 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
164 Tooltip,
165};
166use util::{defer, maybe, post_inc, RangeExt, ResultExt, TakeUntilExt, TryFutureExt};
167use workspace::item::{ItemHandle, PreviewTabsSettings};
168use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
169use workspace::{
170 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
171};
172use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
173
174use crate::hover_links::{find_url, find_url_from_range};
175use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
176
177pub const FILE_HEADER_HEIGHT: u32 = 2;
178pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
179pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
180pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
181const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
182const MAX_LINE_LEN: usize = 1024;
183const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
184const MAX_SELECTION_HISTORY_LEN: usize = 1024;
185pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
186#[doc(hidden)]
187pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
188
189pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
190pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
191
192pub fn render_parsed_markdown(
193 element_id: impl Into<ElementId>,
194 parsed: &language::ParsedMarkdown,
195 editor_style: &EditorStyle,
196 workspace: Option<WeakEntity<Workspace>>,
197 cx: &mut App,
198) -> InteractiveText {
199 let code_span_background_color = cx
200 .theme()
201 .colors()
202 .editor_document_highlight_read_background;
203
204 let highlights = gpui::combine_highlights(
205 parsed.highlights.iter().filter_map(|(range, highlight)| {
206 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
207 Some((range.clone(), highlight))
208 }),
209 parsed
210 .regions
211 .iter()
212 .zip(&parsed.region_ranges)
213 .filter_map(|(region, range)| {
214 if region.code {
215 Some((
216 range.clone(),
217 HighlightStyle {
218 background_color: Some(code_span_background_color),
219 ..Default::default()
220 },
221 ))
222 } else {
223 None
224 }
225 }),
226 );
227
228 let mut links = Vec::new();
229 let mut link_ranges = Vec::new();
230 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
231 if let Some(link) = region.link.clone() {
232 links.push(link);
233 link_ranges.push(range.clone());
234 }
235 }
236
237 InteractiveText::new(
238 element_id,
239 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
240 )
241 .on_click(
242 link_ranges,
243 move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
244 markdown::Link::Web { url } => cx.open_url(url),
245 markdown::Link::Path { path } => {
246 if let Some(workspace) = &workspace {
247 _ = workspace.update(cx, |workspace, cx| {
248 workspace
249 .open_abs_path(path.clone(), false, window, cx)
250 .detach();
251 });
252 }
253 }
254 },
255 )
256}
257
258#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
259pub enum InlayId {
260 InlineCompletion(usize),
261 Hint(usize),
262}
263
264impl InlayId {
265 fn id(&self) -> usize {
266 match self {
267 Self::InlineCompletion(id) => *id,
268 Self::Hint(id) => *id,
269 }
270 }
271}
272
273enum DocumentHighlightRead {}
274enum DocumentHighlightWrite {}
275enum InputComposition {}
276
277#[derive(Debug, Copy, Clone, PartialEq, Eq)]
278pub enum Navigated {
279 Yes,
280 No,
281}
282
283impl Navigated {
284 pub fn from_bool(yes: bool) -> Navigated {
285 if yes {
286 Navigated::Yes
287 } else {
288 Navigated::No
289 }
290 }
291}
292
293pub fn init_settings(cx: &mut App) {
294 EditorSettings::register(cx);
295}
296
297pub fn init(cx: &mut App) {
298 init_settings(cx);
299
300 workspace::register_project_item::<Editor>(cx);
301 workspace::FollowableViewRegistry::register::<Editor>(cx);
302 workspace::register_serializable_item::<Editor>(cx);
303
304 cx.observe_new(
305 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
306 workspace.register_action(Editor::new_file);
307 workspace.register_action(Editor::new_file_vertical);
308 workspace.register_action(Editor::new_file_horizontal);
309 },
310 )
311 .detach();
312
313 cx.on_action(move |_: &workspace::NewFile, cx| {
314 let app_state = workspace::AppState::global(cx);
315 if let Some(app_state) = app_state.upgrade() {
316 workspace::open_new(
317 Default::default(),
318 app_state,
319 cx,
320 |workspace, window, cx| {
321 Editor::new_file(workspace, &Default::default(), window, cx)
322 },
323 )
324 .detach();
325 }
326 });
327 cx.on_action(move |_: &workspace::NewWindow, cx| {
328 let app_state = workspace::AppState::global(cx);
329 if let Some(app_state) = app_state.upgrade() {
330 workspace::open_new(
331 Default::default(),
332 app_state,
333 cx,
334 |workspace, window, cx| {
335 cx.activate(true);
336 Editor::new_file(workspace, &Default::default(), window, cx)
337 },
338 )
339 .detach();
340 }
341 });
342}
343
344pub struct SearchWithinRange;
345
346trait InvalidationRegion {
347 fn ranges(&self) -> &[Range<Anchor>];
348}
349
350#[derive(Clone, Debug, PartialEq)]
351pub enum SelectPhase {
352 Begin {
353 position: DisplayPoint,
354 add: bool,
355 click_count: usize,
356 },
357 BeginColumnar {
358 position: DisplayPoint,
359 reset: bool,
360 goal_column: u32,
361 },
362 Extend {
363 position: DisplayPoint,
364 click_count: usize,
365 },
366 Update {
367 position: DisplayPoint,
368 goal_column: u32,
369 scroll_delta: gpui::Point<f32>,
370 },
371 End,
372}
373
374#[derive(Clone, Debug)]
375pub enum SelectMode {
376 Character,
377 Word(Range<Anchor>),
378 Line(Range<Anchor>),
379 All,
380}
381
382#[derive(Copy, Clone, PartialEq, Eq, Debug)]
383pub enum EditorMode {
384 SingleLine { auto_width: bool },
385 AutoHeight { max_lines: usize },
386 Full,
387}
388
389#[derive(Copy, Clone, Debug)]
390pub enum SoftWrap {
391 /// Prefer not to wrap at all.
392 ///
393 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
394 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
395 GitDiff,
396 /// Prefer a single line generally, unless an overly long line is encountered.
397 None,
398 /// Soft wrap lines that exceed the editor width.
399 EditorWidth,
400 /// Soft wrap lines at the preferred line length.
401 Column(u32),
402 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
403 Bounded(u32),
404}
405
406#[derive(Clone)]
407pub struct EditorStyle {
408 pub background: Hsla,
409 pub local_player: PlayerColor,
410 pub text: TextStyle,
411 pub scrollbar_width: Pixels,
412 pub syntax: Arc<SyntaxTheme>,
413 pub status: StatusColors,
414 pub inlay_hints_style: HighlightStyle,
415 pub inline_completion_styles: InlineCompletionStyles,
416 pub unnecessary_code_fade: f32,
417}
418
419impl Default for EditorStyle {
420 fn default() -> Self {
421 Self {
422 background: Hsla::default(),
423 local_player: PlayerColor::default(),
424 text: TextStyle::default(),
425 scrollbar_width: Pixels::default(),
426 syntax: Default::default(),
427 // HACK: Status colors don't have a real default.
428 // We should look into removing the status colors from the editor
429 // style and retrieve them directly from the theme.
430 status: StatusColors::dark(),
431 inlay_hints_style: HighlightStyle::default(),
432 inline_completion_styles: InlineCompletionStyles {
433 insertion: HighlightStyle::default(),
434 whitespace: HighlightStyle::default(),
435 },
436 unnecessary_code_fade: Default::default(),
437 }
438 }
439}
440
441pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
442 let show_background = language_settings::language_settings(None, None, cx)
443 .inlay_hints
444 .show_background;
445
446 HighlightStyle {
447 color: Some(cx.theme().status().hint),
448 background_color: show_background.then(|| cx.theme().status().hint_background),
449 ..HighlightStyle::default()
450 }
451}
452
453pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
454 InlineCompletionStyles {
455 insertion: HighlightStyle {
456 color: Some(cx.theme().status().predictive),
457 ..HighlightStyle::default()
458 },
459 whitespace: HighlightStyle {
460 background_color: Some(cx.theme().status().created_background),
461 ..HighlightStyle::default()
462 },
463 }
464}
465
466type CompletionId = usize;
467
468pub(crate) enum EditDisplayMode {
469 TabAccept,
470 DiffPopover,
471 Inline,
472}
473
474enum InlineCompletion {
475 Edit {
476 edits: Vec<(Range<Anchor>, String)>,
477 edit_preview: Option<EditPreview>,
478 display_mode: EditDisplayMode,
479 snapshot: BufferSnapshot,
480 },
481 Move {
482 target: Anchor,
483 range_around_target: Range<text::Anchor>,
484 snapshot: BufferSnapshot,
485 },
486}
487
488struct InlineCompletionState {
489 inlay_ids: Vec<InlayId>,
490 completion: InlineCompletion,
491 invalidation_range: Range<Anchor>,
492}
493
494impl InlineCompletionState {
495 pub fn is_move(&self) -> bool {
496 match &self.completion {
497 InlineCompletion::Move { .. } => true,
498 _ => false,
499 }
500 }
501}
502
503enum InlineCompletionHighlight {}
504
505pub enum MenuInlineCompletionsPolicy {
506 Never,
507 ByProvider,
508}
509
510#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
511struct EditorActionId(usize);
512
513impl EditorActionId {
514 pub fn post_inc(&mut self) -> Self {
515 let answer = self.0;
516
517 *self = Self(answer + 1);
518
519 Self(answer)
520 }
521}
522
523// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
524// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
525
526type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
527type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
528
529#[derive(Default)]
530struct ScrollbarMarkerState {
531 scrollbar_size: Size<Pixels>,
532 dirty: bool,
533 markers: Arc<[PaintQuad]>,
534 pending_refresh: Option<Task<Result<()>>>,
535}
536
537impl ScrollbarMarkerState {
538 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
539 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
540 }
541}
542
543#[derive(Clone, Debug)]
544struct RunnableTasks {
545 templates: Vec<(TaskSourceKind, TaskTemplate)>,
546 offset: MultiBufferOffset,
547 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
548 column: u32,
549 // Values of all named captures, including those starting with '_'
550 extra_variables: HashMap<String, String>,
551 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
552 context_range: Range<BufferOffset>,
553}
554
555impl RunnableTasks {
556 fn resolve<'a>(
557 &'a self,
558 cx: &'a task::TaskContext,
559 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
560 self.templates.iter().filter_map(|(kind, template)| {
561 template
562 .resolve_task(&kind.to_id_base(), cx)
563 .map(|task| (kind.clone(), task))
564 })
565 }
566}
567
568#[derive(Clone)]
569struct ResolvedTasks {
570 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
571 position: Anchor,
572}
573#[derive(Copy, Clone, Debug)]
574struct MultiBufferOffset(usize);
575#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
576struct BufferOffset(usize);
577
578// Addons allow storing per-editor state in other crates (e.g. Vim)
579pub trait Addon: 'static {
580 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
581
582 fn to_any(&self) -> &dyn std::any::Any;
583}
584
585#[derive(Debug, Copy, Clone, PartialEq, Eq)]
586pub enum IsVimMode {
587 Yes,
588 No,
589}
590
591/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
592///
593/// See the [module level documentation](self) for more information.
594pub struct Editor {
595 focus_handle: FocusHandle,
596 last_focused_descendant: Option<WeakFocusHandle>,
597 /// The text buffer being edited
598 buffer: Entity<MultiBuffer>,
599 /// Map of how text in the buffer should be displayed.
600 /// Handles soft wraps, folds, fake inlay text insertions, etc.
601 pub display_map: Entity<DisplayMap>,
602 pub selections: SelectionsCollection,
603 pub scroll_manager: ScrollManager,
604 /// When inline assist editors are linked, they all render cursors because
605 /// typing enters text into each of them, even the ones that aren't focused.
606 pub(crate) show_cursor_when_unfocused: bool,
607 columnar_selection_tail: Option<Anchor>,
608 add_selections_state: Option<AddSelectionsState>,
609 select_next_state: Option<SelectNextState>,
610 select_prev_state: Option<SelectNextState>,
611 selection_history: SelectionHistory,
612 autoclose_regions: Vec<AutocloseRegion>,
613 snippet_stack: InvalidationStack<SnippetState>,
614 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
615 ime_transaction: Option<TransactionId>,
616 active_diagnostics: Option<ActiveDiagnosticGroup>,
617 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
618
619 // TODO: make this a access method
620 pub project: Option<Entity<Project>>,
621 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
622 completion_provider: Option<Box<dyn CompletionProvider>>,
623 collaboration_hub: Option<Box<dyn CollaborationHub>>,
624 blink_manager: Entity<BlinkManager>,
625 show_cursor_names: bool,
626 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
627 pub show_local_selections: bool,
628 mode: EditorMode,
629 show_breadcrumbs: bool,
630 show_gutter: bool,
631 show_scrollbars: bool,
632 show_line_numbers: Option<bool>,
633 use_relative_line_numbers: Option<bool>,
634 show_git_diff_gutter: Option<bool>,
635 show_code_actions: Option<bool>,
636 show_runnables: Option<bool>,
637 show_wrap_guides: Option<bool>,
638 show_indent_guides: Option<bool>,
639 placeholder_text: Option<Arc<str>>,
640 highlight_order: usize,
641 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
642 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
643 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
644 scrollbar_marker_state: ScrollbarMarkerState,
645 active_indent_guides_state: ActiveIndentGuidesState,
646 nav_history: Option<ItemNavHistory>,
647 context_menu: RefCell<Option<CodeContextMenu>>,
648 mouse_context_menu: Option<MouseContextMenu>,
649 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
650 signature_help_state: SignatureHelpState,
651 auto_signature_help: Option<bool>,
652 find_all_references_task_sources: Vec<Anchor>,
653 next_completion_id: CompletionId,
654 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
655 code_actions_task: Option<Task<Result<()>>>,
656 document_highlights_task: Option<Task<()>>,
657 linked_editing_range_task: Option<Task<Option<()>>>,
658 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
659 pending_rename: Option<RenameState>,
660 searchable: bool,
661 cursor_shape: CursorShape,
662 current_line_highlight: Option<CurrentLineHighlight>,
663 collapse_matches: bool,
664 autoindent_mode: Option<AutoindentMode>,
665 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
666 input_enabled: bool,
667 use_modal_editing: bool,
668 read_only: bool,
669 leader_peer_id: Option<PeerId>,
670 remote_id: Option<ViewId>,
671 hover_state: HoverState,
672 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
673 gutter_hovered: bool,
674 hovered_link_state: Option<HoveredLinkState>,
675 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
676 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
677 active_inline_completion: Option<InlineCompletionState>,
678 /// Used to prevent flickering as the user types while the menu is open
679 stale_inline_completion_in_menu: Option<InlineCompletionState>,
680 // enable_inline_completions is a switch that Vim can use to disable
681 // inline completions based on its mode.
682 enable_inline_completions: bool,
683 show_inline_completions_override: Option<bool>,
684 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
685 inlay_hint_cache: InlayHintCache,
686 next_inlay_id: usize,
687 _subscriptions: Vec<Subscription>,
688 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
689 gutter_dimensions: GutterDimensions,
690 style: Option<EditorStyle>,
691 text_style_refinement: Option<TextStyleRefinement>,
692 next_editor_action_id: EditorActionId,
693 editor_actions:
694 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
695 use_autoclose: bool,
696 use_auto_surround: bool,
697 auto_replace_emoji_shortcode: bool,
698 show_git_blame_gutter: bool,
699 show_git_blame_inline: bool,
700 show_git_blame_inline_delay_task: Option<Task<()>>,
701 git_blame_inline_enabled: bool,
702 serialize_dirty_buffers: bool,
703 show_selection_menu: Option<bool>,
704 blame: Option<Entity<GitBlame>>,
705 blame_subscription: Option<Subscription>,
706 custom_context_menu: Option<
707 Box<
708 dyn 'static
709 + Fn(
710 &mut Self,
711 DisplayPoint,
712 &mut Window,
713 &mut Context<Self>,
714 ) -> Option<Entity<ui::ContextMenu>>,
715 >,
716 >,
717 last_bounds: Option<Bounds<Pixels>>,
718 expect_bounds_change: Option<Bounds<Pixels>>,
719 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
720 tasks_update_task: Option<Task<()>>,
721 in_project_search: bool,
722 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
723 breadcrumb_header: Option<String>,
724 focused_block: Option<FocusedBlock>,
725 next_scroll_position: NextScrollCursorCenterTopBottom,
726 addons: HashMap<TypeId, Box<dyn Addon>>,
727 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
728 selection_mark_mode: bool,
729 toggle_fold_multiple_buffers: Task<()>,
730 _scroll_cursor_center_top_bottom_task: Task<()>,
731}
732
733#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
734enum NextScrollCursorCenterTopBottom {
735 #[default]
736 Center,
737 Top,
738 Bottom,
739}
740
741impl NextScrollCursorCenterTopBottom {
742 fn next(&self) -> Self {
743 match self {
744 Self::Center => Self::Top,
745 Self::Top => Self::Bottom,
746 Self::Bottom => Self::Center,
747 }
748 }
749}
750
751#[derive(Clone)]
752pub struct EditorSnapshot {
753 pub mode: EditorMode,
754 show_gutter: bool,
755 show_line_numbers: Option<bool>,
756 show_git_diff_gutter: Option<bool>,
757 show_code_actions: Option<bool>,
758 show_runnables: Option<bool>,
759 git_blame_gutter_max_author_length: Option<usize>,
760 pub display_snapshot: DisplaySnapshot,
761 pub placeholder_text: Option<Arc<str>>,
762 is_focused: bool,
763 scroll_anchor: ScrollAnchor,
764 ongoing_scroll: OngoingScroll,
765 current_line_highlight: CurrentLineHighlight,
766 gutter_hovered: bool,
767}
768
769const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
770
771#[derive(Default, Debug, Clone, Copy)]
772pub struct GutterDimensions {
773 pub left_padding: Pixels,
774 pub right_padding: Pixels,
775 pub width: Pixels,
776 pub margin: Pixels,
777 pub git_blame_entries_width: Option<Pixels>,
778}
779
780impl GutterDimensions {
781 /// The full width of the space taken up by the gutter.
782 pub fn full_width(&self) -> Pixels {
783 self.margin + self.width
784 }
785
786 /// The width of the space reserved for the fold indicators,
787 /// use alongside 'justify_end' and `gutter_width` to
788 /// right align content with the line numbers
789 pub fn fold_area_width(&self) -> Pixels {
790 self.margin + self.right_padding
791 }
792}
793
794#[derive(Debug)]
795pub struct RemoteSelection {
796 pub replica_id: ReplicaId,
797 pub selection: Selection<Anchor>,
798 pub cursor_shape: CursorShape,
799 pub peer_id: PeerId,
800 pub line_mode: bool,
801 pub participant_index: Option<ParticipantIndex>,
802 pub user_name: Option<SharedString>,
803}
804
805#[derive(Clone, Debug)]
806struct SelectionHistoryEntry {
807 selections: Arc<[Selection<Anchor>]>,
808 select_next_state: Option<SelectNextState>,
809 select_prev_state: Option<SelectNextState>,
810 add_selections_state: Option<AddSelectionsState>,
811}
812
813enum SelectionHistoryMode {
814 Normal,
815 Undoing,
816 Redoing,
817}
818
819#[derive(Clone, PartialEq, Eq, Hash)]
820struct HoveredCursor {
821 replica_id: u16,
822 selection_id: usize,
823}
824
825impl Default for SelectionHistoryMode {
826 fn default() -> Self {
827 Self::Normal
828 }
829}
830
831#[derive(Default)]
832struct SelectionHistory {
833 #[allow(clippy::type_complexity)]
834 selections_by_transaction:
835 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
836 mode: SelectionHistoryMode,
837 undo_stack: VecDeque<SelectionHistoryEntry>,
838 redo_stack: VecDeque<SelectionHistoryEntry>,
839}
840
841impl SelectionHistory {
842 fn insert_transaction(
843 &mut self,
844 transaction_id: TransactionId,
845 selections: Arc<[Selection<Anchor>]>,
846 ) {
847 self.selections_by_transaction
848 .insert(transaction_id, (selections, None));
849 }
850
851 #[allow(clippy::type_complexity)]
852 fn transaction(
853 &self,
854 transaction_id: TransactionId,
855 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
856 self.selections_by_transaction.get(&transaction_id)
857 }
858
859 #[allow(clippy::type_complexity)]
860 fn transaction_mut(
861 &mut self,
862 transaction_id: TransactionId,
863 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
864 self.selections_by_transaction.get_mut(&transaction_id)
865 }
866
867 fn push(&mut self, entry: SelectionHistoryEntry) {
868 if !entry.selections.is_empty() {
869 match self.mode {
870 SelectionHistoryMode::Normal => {
871 self.push_undo(entry);
872 self.redo_stack.clear();
873 }
874 SelectionHistoryMode::Undoing => self.push_redo(entry),
875 SelectionHistoryMode::Redoing => self.push_undo(entry),
876 }
877 }
878 }
879
880 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
881 if self
882 .undo_stack
883 .back()
884 .map_or(true, |e| e.selections != entry.selections)
885 {
886 self.undo_stack.push_back(entry);
887 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
888 self.undo_stack.pop_front();
889 }
890 }
891 }
892
893 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
894 if self
895 .redo_stack
896 .back()
897 .map_or(true, |e| e.selections != entry.selections)
898 {
899 self.redo_stack.push_back(entry);
900 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
901 self.redo_stack.pop_front();
902 }
903 }
904 }
905}
906
907struct RowHighlight {
908 index: usize,
909 range: Range<Anchor>,
910 color: Hsla,
911 should_autoscroll: bool,
912}
913
914#[derive(Clone, Debug)]
915struct AddSelectionsState {
916 above: bool,
917 stack: Vec<usize>,
918}
919
920#[derive(Clone)]
921struct SelectNextState {
922 query: AhoCorasick,
923 wordwise: bool,
924 done: bool,
925}
926
927impl std::fmt::Debug for SelectNextState {
928 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
929 f.debug_struct(std::any::type_name::<Self>())
930 .field("wordwise", &self.wordwise)
931 .field("done", &self.done)
932 .finish()
933 }
934}
935
936#[derive(Debug)]
937struct AutocloseRegion {
938 selection_id: usize,
939 range: Range<Anchor>,
940 pair: BracketPair,
941}
942
943#[derive(Debug)]
944struct SnippetState {
945 ranges: Vec<Vec<Range<Anchor>>>,
946 active_index: usize,
947 choices: Vec<Option<Vec<String>>>,
948}
949
950#[doc(hidden)]
951pub struct RenameState {
952 pub range: Range<Anchor>,
953 pub old_name: Arc<str>,
954 pub editor: Entity<Editor>,
955 block_id: CustomBlockId,
956}
957
958struct InvalidationStack<T>(Vec<T>);
959
960struct RegisteredInlineCompletionProvider {
961 provider: Arc<dyn InlineCompletionProviderHandle>,
962 _subscription: Subscription,
963}
964
965#[derive(Debug)]
966struct ActiveDiagnosticGroup {
967 primary_range: Range<Anchor>,
968 primary_message: String,
969 group_id: usize,
970 blocks: HashMap<CustomBlockId, Diagnostic>,
971 is_valid: bool,
972}
973
974#[derive(Serialize, Deserialize, Clone, Debug)]
975pub struct ClipboardSelection {
976 pub len: usize,
977 pub is_entire_line: bool,
978 pub first_line_indent: u32,
979}
980
981#[derive(Debug)]
982pub(crate) struct NavigationData {
983 cursor_anchor: Anchor,
984 cursor_position: Point,
985 scroll_anchor: ScrollAnchor,
986 scroll_top_row: u32,
987}
988
989#[derive(Debug, Clone, Copy, PartialEq, Eq)]
990pub enum GotoDefinitionKind {
991 Symbol,
992 Declaration,
993 Type,
994 Implementation,
995}
996
997#[derive(Debug, Clone)]
998enum InlayHintRefreshReason {
999 Toggle(bool),
1000 SettingsChange(InlayHintSettings),
1001 NewLinesShown,
1002 BufferEdited(HashSet<Arc<Language>>),
1003 RefreshRequested,
1004 ExcerptsRemoved(Vec<ExcerptId>),
1005}
1006
1007impl InlayHintRefreshReason {
1008 fn description(&self) -> &'static str {
1009 match self {
1010 Self::Toggle(_) => "toggle",
1011 Self::SettingsChange(_) => "settings change",
1012 Self::NewLinesShown => "new lines shown",
1013 Self::BufferEdited(_) => "buffer edited",
1014 Self::RefreshRequested => "refresh requested",
1015 Self::ExcerptsRemoved(_) => "excerpts removed",
1016 }
1017 }
1018}
1019
1020pub enum FormatTarget {
1021 Buffers,
1022 Ranges(Vec<Range<MultiBufferPoint>>),
1023}
1024
1025pub(crate) struct FocusedBlock {
1026 id: BlockId,
1027 focus_handle: WeakFocusHandle,
1028}
1029
1030#[derive(Clone)]
1031enum JumpData {
1032 MultiBufferRow {
1033 row: MultiBufferRow,
1034 line_offset_from_top: u32,
1035 },
1036 MultiBufferPoint {
1037 excerpt_id: ExcerptId,
1038 position: Point,
1039 anchor: text::Anchor,
1040 line_offset_from_top: u32,
1041 },
1042}
1043
1044pub enum MultibufferSelectionMode {
1045 First,
1046 All,
1047}
1048
1049impl Editor {
1050 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1051 let buffer = cx.new(|cx| Buffer::local("", cx));
1052 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1053 Self::new(
1054 EditorMode::SingleLine { auto_width: false },
1055 buffer,
1056 None,
1057 false,
1058 window,
1059 cx,
1060 )
1061 }
1062
1063 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1064 let buffer = cx.new(|cx| Buffer::local("", cx));
1065 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1066 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1067 }
1068
1069 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1070 let buffer = cx.new(|cx| Buffer::local("", cx));
1071 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1072 Self::new(
1073 EditorMode::SingleLine { auto_width: true },
1074 buffer,
1075 None,
1076 false,
1077 window,
1078 cx,
1079 )
1080 }
1081
1082 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1083 let buffer = cx.new(|cx| Buffer::local("", cx));
1084 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1085 Self::new(
1086 EditorMode::AutoHeight { max_lines },
1087 buffer,
1088 None,
1089 false,
1090 window,
1091 cx,
1092 )
1093 }
1094
1095 pub fn for_buffer(
1096 buffer: Entity<Buffer>,
1097 project: Option<Entity<Project>>,
1098 window: &mut Window,
1099 cx: &mut Context<Self>,
1100 ) -> Self {
1101 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1102 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1103 }
1104
1105 pub fn for_multibuffer(
1106 buffer: Entity<MultiBuffer>,
1107 project: Option<Entity<Project>>,
1108 show_excerpt_controls: bool,
1109 window: &mut Window,
1110 cx: &mut Context<Self>,
1111 ) -> Self {
1112 Self::new(
1113 EditorMode::Full,
1114 buffer,
1115 project,
1116 show_excerpt_controls,
1117 window,
1118 cx,
1119 )
1120 }
1121
1122 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1123 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1124 let mut clone = Self::new(
1125 self.mode,
1126 self.buffer.clone(),
1127 self.project.clone(),
1128 show_excerpt_controls,
1129 window,
1130 cx,
1131 );
1132 self.display_map.update(cx, |display_map, cx| {
1133 let snapshot = display_map.snapshot(cx);
1134 clone.display_map.update(cx, |display_map, cx| {
1135 display_map.set_state(&snapshot, cx);
1136 });
1137 });
1138 clone.selections.clone_state(&self.selections);
1139 clone.scroll_manager.clone_state(&self.scroll_manager);
1140 clone.searchable = self.searchable;
1141 clone
1142 }
1143
1144 pub fn new(
1145 mode: EditorMode,
1146 buffer: Entity<MultiBuffer>,
1147 project: Option<Entity<Project>>,
1148 show_excerpt_controls: bool,
1149 window: &mut Window,
1150 cx: &mut Context<Self>,
1151 ) -> Self {
1152 let style = window.text_style();
1153 let font_size = style.font_size.to_pixels(window.rem_size());
1154 let editor = cx.entity().downgrade();
1155 let fold_placeholder = FoldPlaceholder {
1156 constrain_width: true,
1157 render: Arc::new(move |fold_id, fold_range, _, cx| {
1158 let editor = editor.clone();
1159 div()
1160 .id(fold_id)
1161 .bg(cx.theme().colors().ghost_element_background)
1162 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1163 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1164 .rounded_sm()
1165 .size_full()
1166 .cursor_pointer()
1167 .child("⋯")
1168 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1169 .on_click(move |_, _window, cx| {
1170 editor
1171 .update(cx, |editor, cx| {
1172 editor.unfold_ranges(
1173 &[fold_range.start..fold_range.end],
1174 true,
1175 false,
1176 cx,
1177 );
1178 cx.stop_propagation();
1179 })
1180 .ok();
1181 })
1182 .into_any()
1183 }),
1184 merge_adjacent: true,
1185 ..Default::default()
1186 };
1187 let display_map = cx.new(|cx| {
1188 DisplayMap::new(
1189 buffer.clone(),
1190 style.font(),
1191 font_size,
1192 None,
1193 show_excerpt_controls,
1194 FILE_HEADER_HEIGHT,
1195 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1196 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1197 fold_placeholder,
1198 cx,
1199 )
1200 });
1201
1202 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1203
1204 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1205
1206 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1207 .then(|| language_settings::SoftWrap::None);
1208
1209 let mut project_subscriptions = Vec::new();
1210 if mode == EditorMode::Full {
1211 if let Some(project) = project.as_ref() {
1212 if buffer.read(cx).is_singleton() {
1213 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1214 cx.emit(EditorEvent::TitleChanged);
1215 }));
1216 }
1217 project_subscriptions.push(cx.subscribe_in(
1218 project,
1219 window,
1220 |editor, _, event, window, cx| {
1221 if let project::Event::RefreshInlayHints = event {
1222 editor
1223 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1224 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1225 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1226 let focus_handle = editor.focus_handle(cx);
1227 if focus_handle.is_focused(window) {
1228 let snapshot = buffer.read(cx).snapshot();
1229 for (range, snippet) in snippet_edits {
1230 let editor_range =
1231 language::range_from_lsp(*range).to_offset(&snapshot);
1232 editor
1233 .insert_snippet(
1234 &[editor_range],
1235 snippet.clone(),
1236 window,
1237 cx,
1238 )
1239 .ok();
1240 }
1241 }
1242 }
1243 }
1244 },
1245 ));
1246 if let Some(task_inventory) = project
1247 .read(cx)
1248 .task_store()
1249 .read(cx)
1250 .task_inventory()
1251 .cloned()
1252 {
1253 project_subscriptions.push(cx.observe_in(
1254 &task_inventory,
1255 window,
1256 |editor, _, window, cx| {
1257 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1258 },
1259 ));
1260 }
1261 }
1262 }
1263
1264 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1265
1266 let inlay_hint_settings =
1267 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1268 let focus_handle = cx.focus_handle();
1269 cx.on_focus(&focus_handle, window, Self::handle_focus)
1270 .detach();
1271 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1272 .detach();
1273 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1274 .detach();
1275 cx.on_blur(&focus_handle, window, Self::handle_blur)
1276 .detach();
1277
1278 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1279 Some(false)
1280 } else {
1281 None
1282 };
1283
1284 let mut code_action_providers = Vec::new();
1285 if let Some(project) = project.clone() {
1286 get_unstaged_changes_for_buffers(
1287 &project,
1288 buffer.read(cx).all_buffers(),
1289 buffer.clone(),
1290 cx,
1291 );
1292 code_action_providers.push(Rc::new(project) as Rc<_>);
1293 }
1294
1295 let mut this = Self {
1296 focus_handle,
1297 show_cursor_when_unfocused: false,
1298 last_focused_descendant: None,
1299 buffer: buffer.clone(),
1300 display_map: display_map.clone(),
1301 selections,
1302 scroll_manager: ScrollManager::new(cx),
1303 columnar_selection_tail: None,
1304 add_selections_state: None,
1305 select_next_state: None,
1306 select_prev_state: None,
1307 selection_history: Default::default(),
1308 autoclose_regions: Default::default(),
1309 snippet_stack: Default::default(),
1310 select_larger_syntax_node_stack: Vec::new(),
1311 ime_transaction: Default::default(),
1312 active_diagnostics: None,
1313 soft_wrap_mode_override,
1314 completion_provider: project.clone().map(|project| Box::new(project) as _),
1315 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1316 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1317 project,
1318 blink_manager: blink_manager.clone(),
1319 show_local_selections: true,
1320 show_scrollbars: true,
1321 mode,
1322 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1323 show_gutter: mode == EditorMode::Full,
1324 show_line_numbers: None,
1325 use_relative_line_numbers: None,
1326 show_git_diff_gutter: None,
1327 show_code_actions: None,
1328 show_runnables: None,
1329 show_wrap_guides: None,
1330 show_indent_guides,
1331 placeholder_text: None,
1332 highlight_order: 0,
1333 highlighted_rows: HashMap::default(),
1334 background_highlights: Default::default(),
1335 gutter_highlights: TreeMap::default(),
1336 scrollbar_marker_state: ScrollbarMarkerState::default(),
1337 active_indent_guides_state: ActiveIndentGuidesState::default(),
1338 nav_history: None,
1339 context_menu: RefCell::new(None),
1340 mouse_context_menu: None,
1341 completion_tasks: Default::default(),
1342 signature_help_state: SignatureHelpState::default(),
1343 auto_signature_help: None,
1344 find_all_references_task_sources: Vec::new(),
1345 next_completion_id: 0,
1346 next_inlay_id: 0,
1347 code_action_providers,
1348 available_code_actions: Default::default(),
1349 code_actions_task: Default::default(),
1350 document_highlights_task: Default::default(),
1351 linked_editing_range_task: Default::default(),
1352 pending_rename: Default::default(),
1353 searchable: true,
1354 cursor_shape: EditorSettings::get_global(cx)
1355 .cursor_shape
1356 .unwrap_or_default(),
1357 current_line_highlight: None,
1358 autoindent_mode: Some(AutoindentMode::EachLine),
1359 collapse_matches: false,
1360 workspace: None,
1361 input_enabled: true,
1362 use_modal_editing: mode == EditorMode::Full,
1363 read_only: false,
1364 use_autoclose: true,
1365 use_auto_surround: true,
1366 auto_replace_emoji_shortcode: false,
1367 leader_peer_id: None,
1368 remote_id: None,
1369 hover_state: Default::default(),
1370 pending_mouse_down: None,
1371 hovered_link_state: Default::default(),
1372 inline_completion_provider: None,
1373 active_inline_completion: None,
1374 stale_inline_completion_in_menu: None,
1375 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1376
1377 gutter_hovered: false,
1378 pixel_position_of_newest_cursor: None,
1379 last_bounds: None,
1380 expect_bounds_change: None,
1381 gutter_dimensions: GutterDimensions::default(),
1382 style: None,
1383 show_cursor_names: false,
1384 hovered_cursors: Default::default(),
1385 next_editor_action_id: EditorActionId::default(),
1386 editor_actions: Rc::default(),
1387 show_inline_completions_override: None,
1388 enable_inline_completions: true,
1389 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1390 custom_context_menu: None,
1391 show_git_blame_gutter: false,
1392 show_git_blame_inline: false,
1393 show_selection_menu: None,
1394 show_git_blame_inline_delay_task: None,
1395 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1396 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1397 .session
1398 .restore_unsaved_buffers,
1399 blame: None,
1400 blame_subscription: None,
1401 tasks: Default::default(),
1402 _subscriptions: vec![
1403 cx.observe(&buffer, Self::on_buffer_changed),
1404 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1405 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1406 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1407 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1408 cx.observe_window_activation(window, |editor, window, cx| {
1409 let active = window.is_window_active();
1410 editor.blink_manager.update(cx, |blink_manager, cx| {
1411 if active {
1412 blink_manager.enable(cx);
1413 } else {
1414 blink_manager.disable(cx);
1415 }
1416 });
1417 }),
1418 ],
1419 tasks_update_task: None,
1420 linked_edit_ranges: Default::default(),
1421 in_project_search: false,
1422 previous_search_ranges: None,
1423 breadcrumb_header: None,
1424 focused_block: None,
1425 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1426 addons: HashMap::default(),
1427 registered_buffers: HashMap::default(),
1428 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1429 selection_mark_mode: false,
1430 toggle_fold_multiple_buffers: Task::ready(()),
1431 text_style_refinement: None,
1432 };
1433 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1434 this._subscriptions.extend(project_subscriptions);
1435
1436 this.end_selection(window, cx);
1437 this.scroll_manager.show_scrollbar(window, cx);
1438
1439 if mode == EditorMode::Full {
1440 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1441 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1442
1443 if this.git_blame_inline_enabled {
1444 this.git_blame_inline_enabled = true;
1445 this.start_git_blame_inline(false, window, cx);
1446 }
1447
1448 if let Some(buffer) = buffer.read(cx).as_singleton() {
1449 if let Some(project) = this.project.as_ref() {
1450 let lsp_store = project.read(cx).lsp_store();
1451 let handle = lsp_store.update(cx, |lsp_store, cx| {
1452 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1453 });
1454 this.registered_buffers
1455 .insert(buffer.read(cx).remote_id(), handle);
1456 }
1457 }
1458 }
1459
1460 this.report_editor_event("Editor Opened", None, cx);
1461 this
1462 }
1463
1464 pub fn mouse_menu_is_focused(&self, window: &mut Window, cx: &mut App) -> bool {
1465 self.mouse_context_menu
1466 .as_ref()
1467 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1468 }
1469
1470 fn key_context(&self, window: &mut Window, cx: &mut Context<Self>) -> KeyContext {
1471 let mut key_context = KeyContext::new_with_defaults();
1472 key_context.add("Editor");
1473 let mode = match self.mode {
1474 EditorMode::SingleLine { .. } => "single_line",
1475 EditorMode::AutoHeight { .. } => "auto_height",
1476 EditorMode::Full => "full",
1477 };
1478
1479 if EditorSettings::jupyter_enabled(cx) {
1480 key_context.add("jupyter");
1481 }
1482
1483 key_context.set("mode", mode);
1484 if self.pending_rename.is_some() {
1485 key_context.add("renaming");
1486 }
1487 match self.context_menu.borrow().as_ref() {
1488 Some(CodeContextMenu::Completions(_)) => {
1489 key_context.add("menu");
1490 key_context.add("showing_completions");
1491 }
1492 Some(CodeContextMenu::CodeActions(_)) => {
1493 key_context.add("menu");
1494 key_context.add("showing_code_actions")
1495 }
1496 None => {}
1497 }
1498
1499 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1500 if !self.focus_handle(cx).contains_focused(window, cx)
1501 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1502 {
1503 for addon in self.addons.values() {
1504 addon.extend_key_context(&mut key_context, cx)
1505 }
1506 }
1507
1508 if let Some(extension) = self
1509 .buffer
1510 .read(cx)
1511 .as_singleton()
1512 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1513 {
1514 key_context.set("extension", extension.to_string());
1515 }
1516
1517 if self.has_active_inline_completion() {
1518 key_context.add("copilot_suggestion");
1519 key_context.add("inline_completion");
1520 }
1521
1522 if self.selection_mark_mode {
1523 key_context.add("selection_mode");
1524 }
1525
1526 key_context
1527 }
1528
1529 pub fn new_file(
1530 workspace: &mut Workspace,
1531 _: &workspace::NewFile,
1532 window: &mut Window,
1533 cx: &mut Context<Workspace>,
1534 ) {
1535 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1536 "Failed to create buffer",
1537 window,
1538 cx,
1539 |e, _, _| match e.error_code() {
1540 ErrorCode::RemoteUpgradeRequired => Some(format!(
1541 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1542 e.error_tag("required").unwrap_or("the latest version")
1543 )),
1544 _ => None,
1545 },
1546 );
1547 }
1548
1549 pub fn new_in_workspace(
1550 workspace: &mut Workspace,
1551 window: &mut Window,
1552 cx: &mut Context<Workspace>,
1553 ) -> Task<Result<Entity<Editor>>> {
1554 let project = workspace.project().clone();
1555 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1556
1557 cx.spawn_in(window, |workspace, mut cx| async move {
1558 let buffer = create.await?;
1559 workspace.update_in(&mut cx, |workspace, window, cx| {
1560 let editor =
1561 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1562 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1563 editor
1564 })
1565 })
1566 }
1567
1568 fn new_file_vertical(
1569 workspace: &mut Workspace,
1570 _: &workspace::NewFileSplitVertical,
1571 window: &mut Window,
1572 cx: &mut Context<Workspace>,
1573 ) {
1574 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1575 }
1576
1577 fn new_file_horizontal(
1578 workspace: &mut Workspace,
1579 _: &workspace::NewFileSplitHorizontal,
1580 window: &mut Window,
1581 cx: &mut Context<Workspace>,
1582 ) {
1583 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1584 }
1585
1586 fn new_file_in_direction(
1587 workspace: &mut Workspace,
1588 direction: SplitDirection,
1589 window: &mut Window,
1590 cx: &mut Context<Workspace>,
1591 ) {
1592 let project = workspace.project().clone();
1593 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1594
1595 cx.spawn_in(window, |workspace, mut cx| async move {
1596 let buffer = create.await?;
1597 workspace.update_in(&mut cx, move |workspace, window, cx| {
1598 workspace.split_item(
1599 direction,
1600 Box::new(
1601 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1602 ),
1603 window,
1604 cx,
1605 )
1606 })?;
1607 anyhow::Ok(())
1608 })
1609 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1610 match e.error_code() {
1611 ErrorCode::RemoteUpgradeRequired => Some(format!(
1612 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1613 e.error_tag("required").unwrap_or("the latest version")
1614 )),
1615 _ => None,
1616 }
1617 });
1618 }
1619
1620 pub fn leader_peer_id(&self) -> Option<PeerId> {
1621 self.leader_peer_id
1622 }
1623
1624 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1625 &self.buffer
1626 }
1627
1628 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1629 self.workspace.as_ref()?.0.upgrade()
1630 }
1631
1632 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1633 self.buffer().read(cx).title(cx)
1634 }
1635
1636 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1637 let git_blame_gutter_max_author_length = self
1638 .render_git_blame_gutter(cx)
1639 .then(|| {
1640 if let Some(blame) = self.blame.as_ref() {
1641 let max_author_length =
1642 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1643 Some(max_author_length)
1644 } else {
1645 None
1646 }
1647 })
1648 .flatten();
1649
1650 EditorSnapshot {
1651 mode: self.mode,
1652 show_gutter: self.show_gutter,
1653 show_line_numbers: self.show_line_numbers,
1654 show_git_diff_gutter: self.show_git_diff_gutter,
1655 show_code_actions: self.show_code_actions,
1656 show_runnables: self.show_runnables,
1657 git_blame_gutter_max_author_length,
1658 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1659 scroll_anchor: self.scroll_manager.anchor(),
1660 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1661 placeholder_text: self.placeholder_text.clone(),
1662 is_focused: self.focus_handle.is_focused(window),
1663 current_line_highlight: self
1664 .current_line_highlight
1665 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1666 gutter_hovered: self.gutter_hovered,
1667 }
1668 }
1669
1670 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1671 self.buffer.read(cx).language_at(point, cx)
1672 }
1673
1674 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1675 self.buffer.read(cx).read(cx).file_at(point).cloned()
1676 }
1677
1678 pub fn active_excerpt(
1679 &self,
1680 cx: &App,
1681 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1682 self.buffer
1683 .read(cx)
1684 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1685 }
1686
1687 pub fn mode(&self) -> EditorMode {
1688 self.mode
1689 }
1690
1691 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1692 self.collaboration_hub.as_deref()
1693 }
1694
1695 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1696 self.collaboration_hub = Some(hub);
1697 }
1698
1699 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1700 self.in_project_search = in_project_search;
1701 }
1702
1703 pub fn set_custom_context_menu(
1704 &mut self,
1705 f: impl 'static
1706 + Fn(
1707 &mut Self,
1708 DisplayPoint,
1709 &mut Window,
1710 &mut Context<Self>,
1711 ) -> Option<Entity<ui::ContextMenu>>,
1712 ) {
1713 self.custom_context_menu = Some(Box::new(f))
1714 }
1715
1716 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1717 self.completion_provider = provider;
1718 }
1719
1720 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1721 self.semantics_provider.clone()
1722 }
1723
1724 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1725 self.semantics_provider = provider;
1726 }
1727
1728 pub fn set_inline_completion_provider<T>(
1729 &mut self,
1730 provider: Option<Entity<T>>,
1731 window: &mut Window,
1732 cx: &mut Context<Self>,
1733 ) where
1734 T: InlineCompletionProvider,
1735 {
1736 self.inline_completion_provider =
1737 provider.map(|provider| RegisteredInlineCompletionProvider {
1738 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1739 if this.focus_handle.is_focused(window) {
1740 this.update_visible_inline_completion(window, cx);
1741 }
1742 }),
1743 provider: Arc::new(provider),
1744 });
1745 self.refresh_inline_completion(false, false, window, cx);
1746 }
1747
1748 pub fn placeholder_text(&self) -> Option<&str> {
1749 self.placeholder_text.as_deref()
1750 }
1751
1752 pub fn set_placeholder_text(
1753 &mut self,
1754 placeholder_text: impl Into<Arc<str>>,
1755 cx: &mut Context<Self>,
1756 ) {
1757 let placeholder_text = Some(placeholder_text.into());
1758 if self.placeholder_text != placeholder_text {
1759 self.placeholder_text = placeholder_text;
1760 cx.notify();
1761 }
1762 }
1763
1764 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1765 self.cursor_shape = cursor_shape;
1766
1767 // Disrupt blink for immediate user feedback that the cursor shape has changed
1768 self.blink_manager.update(cx, BlinkManager::show_cursor);
1769
1770 cx.notify();
1771 }
1772
1773 pub fn set_current_line_highlight(
1774 &mut self,
1775 current_line_highlight: Option<CurrentLineHighlight>,
1776 ) {
1777 self.current_line_highlight = current_line_highlight;
1778 }
1779
1780 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1781 self.collapse_matches = collapse_matches;
1782 }
1783
1784 pub fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1785 let buffers = self.buffer.read(cx).all_buffers();
1786 let Some(lsp_store) = self.lsp_store(cx) else {
1787 return;
1788 };
1789 lsp_store.update(cx, |lsp_store, cx| {
1790 for buffer in buffers {
1791 self.registered_buffers
1792 .entry(buffer.read(cx).remote_id())
1793 .or_insert_with(|| {
1794 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1795 });
1796 }
1797 })
1798 }
1799
1800 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1801 if self.collapse_matches {
1802 return range.start..range.start;
1803 }
1804 range.clone()
1805 }
1806
1807 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1808 if self.display_map.read(cx).clip_at_line_ends != clip {
1809 self.display_map
1810 .update(cx, |map, _| map.clip_at_line_ends = clip);
1811 }
1812 }
1813
1814 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1815 self.input_enabled = input_enabled;
1816 }
1817
1818 pub fn set_inline_completions_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
1819 self.enable_inline_completions = enabled;
1820 if !self.enable_inline_completions {
1821 self.take_active_inline_completion(cx);
1822 cx.notify();
1823 }
1824 }
1825
1826 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1827 self.menu_inline_completions_policy = value;
1828 }
1829
1830 pub fn set_autoindent(&mut self, autoindent: bool) {
1831 if autoindent {
1832 self.autoindent_mode = Some(AutoindentMode::EachLine);
1833 } else {
1834 self.autoindent_mode = None;
1835 }
1836 }
1837
1838 pub fn read_only(&self, cx: &App) -> bool {
1839 self.read_only || self.buffer.read(cx).read_only()
1840 }
1841
1842 pub fn set_read_only(&mut self, read_only: bool) {
1843 self.read_only = read_only;
1844 }
1845
1846 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1847 self.use_autoclose = autoclose;
1848 }
1849
1850 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1851 self.use_auto_surround = auto_surround;
1852 }
1853
1854 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1855 self.auto_replace_emoji_shortcode = auto_replace;
1856 }
1857
1858 pub fn toggle_inline_completions(
1859 &mut self,
1860 _: &ToggleInlineCompletions,
1861 window: &mut Window,
1862 cx: &mut Context<Self>,
1863 ) {
1864 if self.show_inline_completions_override.is_some() {
1865 self.set_show_inline_completions(None, window, cx);
1866 } else {
1867 let cursor = self.selections.newest_anchor().head();
1868 if let Some((buffer, cursor_buffer_position)) =
1869 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1870 {
1871 let show_inline_completions =
1872 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
1873 self.set_show_inline_completions(Some(show_inline_completions), window, cx);
1874 }
1875 }
1876 }
1877
1878 pub fn set_show_inline_completions(
1879 &mut self,
1880 show_inline_completions: Option<bool>,
1881 window: &mut Window,
1882 cx: &mut Context<Self>,
1883 ) {
1884 self.show_inline_completions_override = show_inline_completions;
1885 self.refresh_inline_completion(false, true, window, cx);
1886 }
1887
1888 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
1889 let cursor = self.selections.newest_anchor().head();
1890 if let Some((buffer, buffer_position)) =
1891 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1892 {
1893 self.should_show_inline_completions(&buffer, buffer_position, cx)
1894 } else {
1895 false
1896 }
1897 }
1898
1899 fn should_show_inline_completions(
1900 &self,
1901 buffer: &Entity<Buffer>,
1902 buffer_position: language::Anchor,
1903 cx: &App,
1904 ) -> bool {
1905 if !self.snippet_stack.is_empty() {
1906 return false;
1907 }
1908
1909 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
1910 return false;
1911 }
1912
1913 if let Some(provider) = self.inline_completion_provider() {
1914 if let Some(show_inline_completions) = self.show_inline_completions_override {
1915 show_inline_completions
1916 } else {
1917 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
1918 }
1919 } else {
1920 false
1921 }
1922 }
1923
1924 fn inline_completions_disabled_in_scope(
1925 &self,
1926 buffer: &Entity<Buffer>,
1927 buffer_position: language::Anchor,
1928 cx: &App,
1929 ) -> bool {
1930 let snapshot = buffer.read(cx).snapshot();
1931 let settings = snapshot.settings_at(buffer_position, cx);
1932
1933 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1934 return false;
1935 };
1936
1937 scope.override_name().map_or(false, |scope_name| {
1938 settings
1939 .inline_completions_disabled_in
1940 .iter()
1941 .any(|s| s == scope_name)
1942 })
1943 }
1944
1945 pub fn set_use_modal_editing(&mut self, to: bool) {
1946 self.use_modal_editing = to;
1947 }
1948
1949 pub fn use_modal_editing(&self) -> bool {
1950 self.use_modal_editing
1951 }
1952
1953 fn selections_did_change(
1954 &mut self,
1955 local: bool,
1956 old_cursor_position: &Anchor,
1957 show_completions: bool,
1958 window: &mut Window,
1959 cx: &mut Context<Self>,
1960 ) {
1961 window.invalidate_character_coordinates();
1962
1963 // Copy selections to primary selection buffer
1964 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1965 if local {
1966 let selections = self.selections.all::<usize>(cx);
1967 let buffer_handle = self.buffer.read(cx).read(cx);
1968
1969 let mut text = String::new();
1970 for (index, selection) in selections.iter().enumerate() {
1971 let text_for_selection = buffer_handle
1972 .text_for_range(selection.start..selection.end)
1973 .collect::<String>();
1974
1975 text.push_str(&text_for_selection);
1976 if index != selections.len() - 1 {
1977 text.push('\n');
1978 }
1979 }
1980
1981 if !text.is_empty() {
1982 cx.write_to_primary(ClipboardItem::new_string(text));
1983 }
1984 }
1985
1986 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
1987 self.buffer.update(cx, |buffer, cx| {
1988 buffer.set_active_selections(
1989 &self.selections.disjoint_anchors(),
1990 self.selections.line_mode,
1991 self.cursor_shape,
1992 cx,
1993 )
1994 });
1995 }
1996 let display_map = self
1997 .display_map
1998 .update(cx, |display_map, cx| display_map.snapshot(cx));
1999 let buffer = &display_map.buffer_snapshot;
2000 self.add_selections_state = None;
2001 self.select_next_state = None;
2002 self.select_prev_state = None;
2003 self.select_larger_syntax_node_stack.clear();
2004 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2005 self.snippet_stack
2006 .invalidate(&self.selections.disjoint_anchors(), buffer);
2007 self.take_rename(false, window, cx);
2008
2009 let new_cursor_position = self.selections.newest_anchor().head();
2010
2011 self.push_to_nav_history(
2012 *old_cursor_position,
2013 Some(new_cursor_position.to_point(buffer)),
2014 cx,
2015 );
2016
2017 if local {
2018 let new_cursor_position = self.selections.newest_anchor().head();
2019 let mut context_menu = self.context_menu.borrow_mut();
2020 let completion_menu = match context_menu.as_ref() {
2021 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2022 _ => {
2023 *context_menu = None;
2024 None
2025 }
2026 };
2027
2028 if let Some(completion_menu) = completion_menu {
2029 let cursor_position = new_cursor_position.to_offset(buffer);
2030 let (word_range, kind) =
2031 buffer.surrounding_word(completion_menu.initial_position, true);
2032 if kind == Some(CharKind::Word)
2033 && word_range.to_inclusive().contains(&cursor_position)
2034 {
2035 let mut completion_menu = completion_menu.clone();
2036 drop(context_menu);
2037
2038 let query = Self::completion_query(buffer, cursor_position);
2039 cx.spawn(move |this, mut cx| async move {
2040 completion_menu
2041 .filter(query.as_deref(), cx.background_executor().clone())
2042 .await;
2043
2044 this.update(&mut cx, |this, cx| {
2045 let mut context_menu = this.context_menu.borrow_mut();
2046 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2047 else {
2048 return;
2049 };
2050
2051 if menu.id > completion_menu.id {
2052 return;
2053 }
2054
2055 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2056 drop(context_menu);
2057 cx.notify();
2058 })
2059 })
2060 .detach();
2061
2062 if show_completions {
2063 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2064 }
2065 } else {
2066 drop(context_menu);
2067 self.hide_context_menu(window, cx);
2068 }
2069 } else {
2070 drop(context_menu);
2071 }
2072
2073 hide_hover(self, cx);
2074
2075 if old_cursor_position.to_display_point(&display_map).row()
2076 != new_cursor_position.to_display_point(&display_map).row()
2077 {
2078 self.available_code_actions.take();
2079 }
2080 self.refresh_code_actions(window, cx);
2081 self.refresh_document_highlights(cx);
2082 refresh_matching_bracket_highlights(self, window, cx);
2083 self.update_visible_inline_completion(window, cx);
2084 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2085 if self.git_blame_inline_enabled {
2086 self.start_inline_blame_timer(window, cx);
2087 }
2088 }
2089
2090 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2091 cx.emit(EditorEvent::SelectionsChanged { local });
2092
2093 if self.selections.disjoint_anchors().len() == 1 {
2094 cx.emit(SearchEvent::ActiveMatchChanged)
2095 }
2096 cx.notify();
2097 }
2098
2099 pub fn change_selections<R>(
2100 &mut self,
2101 autoscroll: Option<Autoscroll>,
2102 window: &mut Window,
2103 cx: &mut Context<Self>,
2104 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2105 ) -> R {
2106 self.change_selections_inner(autoscroll, true, window, cx, change)
2107 }
2108
2109 pub fn change_selections_inner<R>(
2110 &mut self,
2111 autoscroll: Option<Autoscroll>,
2112 request_completions: bool,
2113 window: &mut Window,
2114 cx: &mut Context<Self>,
2115 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2116 ) -> R {
2117 let old_cursor_position = self.selections.newest_anchor().head();
2118 self.push_to_selection_history();
2119
2120 let (changed, result) = self.selections.change_with(cx, change);
2121
2122 if changed {
2123 if let Some(autoscroll) = autoscroll {
2124 self.request_autoscroll(autoscroll, cx);
2125 }
2126 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2127
2128 if self.should_open_signature_help_automatically(
2129 &old_cursor_position,
2130 self.signature_help_state.backspace_pressed(),
2131 cx,
2132 ) {
2133 self.show_signature_help(&ShowSignatureHelp, window, cx);
2134 }
2135 self.signature_help_state.set_backspace_pressed(false);
2136 }
2137
2138 result
2139 }
2140
2141 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2142 where
2143 I: IntoIterator<Item = (Range<S>, T)>,
2144 S: ToOffset,
2145 T: Into<Arc<str>>,
2146 {
2147 if self.read_only(cx) {
2148 return;
2149 }
2150
2151 self.buffer
2152 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2153 }
2154
2155 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2156 where
2157 I: IntoIterator<Item = (Range<S>, T)>,
2158 S: ToOffset,
2159 T: Into<Arc<str>>,
2160 {
2161 if self.read_only(cx) {
2162 return;
2163 }
2164
2165 self.buffer.update(cx, |buffer, cx| {
2166 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2167 });
2168 }
2169
2170 pub fn edit_with_block_indent<I, S, T>(
2171 &mut self,
2172 edits: I,
2173 original_indent_columns: Vec<u32>,
2174 cx: &mut Context<Self>,
2175 ) where
2176 I: IntoIterator<Item = (Range<S>, T)>,
2177 S: ToOffset,
2178 T: Into<Arc<str>>,
2179 {
2180 if self.read_only(cx) {
2181 return;
2182 }
2183
2184 self.buffer.update(cx, |buffer, cx| {
2185 buffer.edit(
2186 edits,
2187 Some(AutoindentMode::Block {
2188 original_indent_columns,
2189 }),
2190 cx,
2191 )
2192 });
2193 }
2194
2195 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2196 self.hide_context_menu(window, cx);
2197
2198 match phase {
2199 SelectPhase::Begin {
2200 position,
2201 add,
2202 click_count,
2203 } => self.begin_selection(position, add, click_count, window, cx),
2204 SelectPhase::BeginColumnar {
2205 position,
2206 goal_column,
2207 reset,
2208 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2209 SelectPhase::Extend {
2210 position,
2211 click_count,
2212 } => self.extend_selection(position, click_count, window, cx),
2213 SelectPhase::Update {
2214 position,
2215 goal_column,
2216 scroll_delta,
2217 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2218 SelectPhase::End => self.end_selection(window, cx),
2219 }
2220 }
2221
2222 fn extend_selection(
2223 &mut self,
2224 position: DisplayPoint,
2225 click_count: usize,
2226 window: &mut Window,
2227 cx: &mut Context<Self>,
2228 ) {
2229 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2230 let tail = self.selections.newest::<usize>(cx).tail();
2231 self.begin_selection(position, false, click_count, window, cx);
2232
2233 let position = position.to_offset(&display_map, Bias::Left);
2234 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2235
2236 let mut pending_selection = self
2237 .selections
2238 .pending_anchor()
2239 .expect("extend_selection not called with pending selection");
2240 if position >= tail {
2241 pending_selection.start = tail_anchor;
2242 } else {
2243 pending_selection.end = tail_anchor;
2244 pending_selection.reversed = true;
2245 }
2246
2247 let mut pending_mode = self.selections.pending_mode().unwrap();
2248 match &mut pending_mode {
2249 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2250 _ => {}
2251 }
2252
2253 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2254 s.set_pending(pending_selection, pending_mode)
2255 });
2256 }
2257
2258 fn begin_selection(
2259 &mut self,
2260 position: DisplayPoint,
2261 add: bool,
2262 click_count: usize,
2263 window: &mut Window,
2264 cx: &mut Context<Self>,
2265 ) {
2266 if !self.focus_handle.is_focused(window) {
2267 self.last_focused_descendant = None;
2268 window.focus(&self.focus_handle);
2269 }
2270
2271 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2272 let buffer = &display_map.buffer_snapshot;
2273 let newest_selection = self.selections.newest_anchor().clone();
2274 let position = display_map.clip_point(position, Bias::Left);
2275
2276 let start;
2277 let end;
2278 let mode;
2279 let mut auto_scroll;
2280 match click_count {
2281 1 => {
2282 start = buffer.anchor_before(position.to_point(&display_map));
2283 end = start;
2284 mode = SelectMode::Character;
2285 auto_scroll = true;
2286 }
2287 2 => {
2288 let range = movement::surrounding_word(&display_map, position);
2289 start = buffer.anchor_before(range.start.to_point(&display_map));
2290 end = buffer.anchor_before(range.end.to_point(&display_map));
2291 mode = SelectMode::Word(start..end);
2292 auto_scroll = true;
2293 }
2294 3 => {
2295 let position = display_map
2296 .clip_point(position, Bias::Left)
2297 .to_point(&display_map);
2298 let line_start = display_map.prev_line_boundary(position).0;
2299 let next_line_start = buffer.clip_point(
2300 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2301 Bias::Left,
2302 );
2303 start = buffer.anchor_before(line_start);
2304 end = buffer.anchor_before(next_line_start);
2305 mode = SelectMode::Line(start..end);
2306 auto_scroll = true;
2307 }
2308 _ => {
2309 start = buffer.anchor_before(0);
2310 end = buffer.anchor_before(buffer.len());
2311 mode = SelectMode::All;
2312 auto_scroll = false;
2313 }
2314 }
2315 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2316
2317 let point_to_delete: Option<usize> = {
2318 let selected_points: Vec<Selection<Point>> =
2319 self.selections.disjoint_in_range(start..end, cx);
2320
2321 if !add || click_count > 1 {
2322 None
2323 } else if !selected_points.is_empty() {
2324 Some(selected_points[0].id)
2325 } else {
2326 let clicked_point_already_selected =
2327 self.selections.disjoint.iter().find(|selection| {
2328 selection.start.to_point(buffer) == start.to_point(buffer)
2329 || selection.end.to_point(buffer) == end.to_point(buffer)
2330 });
2331
2332 clicked_point_already_selected.map(|selection| selection.id)
2333 }
2334 };
2335
2336 let selections_count = self.selections.count();
2337
2338 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2339 if let Some(point_to_delete) = point_to_delete {
2340 s.delete(point_to_delete);
2341
2342 if selections_count == 1 {
2343 s.set_pending_anchor_range(start..end, mode);
2344 }
2345 } else {
2346 if !add {
2347 s.clear_disjoint();
2348 } else if click_count > 1 {
2349 s.delete(newest_selection.id)
2350 }
2351
2352 s.set_pending_anchor_range(start..end, mode);
2353 }
2354 });
2355 }
2356
2357 fn begin_columnar_selection(
2358 &mut self,
2359 position: DisplayPoint,
2360 goal_column: u32,
2361 reset: bool,
2362 window: &mut Window,
2363 cx: &mut Context<Self>,
2364 ) {
2365 if !self.focus_handle.is_focused(window) {
2366 self.last_focused_descendant = None;
2367 window.focus(&self.focus_handle);
2368 }
2369
2370 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2371
2372 if reset {
2373 let pointer_position = display_map
2374 .buffer_snapshot
2375 .anchor_before(position.to_point(&display_map));
2376
2377 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2378 s.clear_disjoint();
2379 s.set_pending_anchor_range(
2380 pointer_position..pointer_position,
2381 SelectMode::Character,
2382 );
2383 });
2384 }
2385
2386 let tail = self.selections.newest::<Point>(cx).tail();
2387 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2388
2389 if !reset {
2390 self.select_columns(
2391 tail.to_display_point(&display_map),
2392 position,
2393 goal_column,
2394 &display_map,
2395 window,
2396 cx,
2397 );
2398 }
2399 }
2400
2401 fn update_selection(
2402 &mut self,
2403 position: DisplayPoint,
2404 goal_column: u32,
2405 scroll_delta: gpui::Point<f32>,
2406 window: &mut Window,
2407 cx: &mut Context<Self>,
2408 ) {
2409 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2410
2411 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2412 let tail = tail.to_display_point(&display_map);
2413 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2414 } else if let Some(mut pending) = self.selections.pending_anchor() {
2415 let buffer = self.buffer.read(cx).snapshot(cx);
2416 let head;
2417 let tail;
2418 let mode = self.selections.pending_mode().unwrap();
2419 match &mode {
2420 SelectMode::Character => {
2421 head = position.to_point(&display_map);
2422 tail = pending.tail().to_point(&buffer);
2423 }
2424 SelectMode::Word(original_range) => {
2425 let original_display_range = original_range.start.to_display_point(&display_map)
2426 ..original_range.end.to_display_point(&display_map);
2427 let original_buffer_range = original_display_range.start.to_point(&display_map)
2428 ..original_display_range.end.to_point(&display_map);
2429 if movement::is_inside_word(&display_map, position)
2430 || original_display_range.contains(&position)
2431 {
2432 let word_range = movement::surrounding_word(&display_map, position);
2433 if word_range.start < original_display_range.start {
2434 head = word_range.start.to_point(&display_map);
2435 } else {
2436 head = word_range.end.to_point(&display_map);
2437 }
2438 } else {
2439 head = position.to_point(&display_map);
2440 }
2441
2442 if head <= original_buffer_range.start {
2443 tail = original_buffer_range.end;
2444 } else {
2445 tail = original_buffer_range.start;
2446 }
2447 }
2448 SelectMode::Line(original_range) => {
2449 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2450
2451 let position = display_map
2452 .clip_point(position, Bias::Left)
2453 .to_point(&display_map);
2454 let line_start = display_map.prev_line_boundary(position).0;
2455 let next_line_start = buffer.clip_point(
2456 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2457 Bias::Left,
2458 );
2459
2460 if line_start < original_range.start {
2461 head = line_start
2462 } else {
2463 head = next_line_start
2464 }
2465
2466 if head <= original_range.start {
2467 tail = original_range.end;
2468 } else {
2469 tail = original_range.start;
2470 }
2471 }
2472 SelectMode::All => {
2473 return;
2474 }
2475 };
2476
2477 if head < tail {
2478 pending.start = buffer.anchor_before(head);
2479 pending.end = buffer.anchor_before(tail);
2480 pending.reversed = true;
2481 } else {
2482 pending.start = buffer.anchor_before(tail);
2483 pending.end = buffer.anchor_before(head);
2484 pending.reversed = false;
2485 }
2486
2487 self.change_selections(None, window, cx, |s| {
2488 s.set_pending(pending, mode);
2489 });
2490 } else {
2491 log::error!("update_selection dispatched with no pending selection");
2492 return;
2493 }
2494
2495 self.apply_scroll_delta(scroll_delta, window, cx);
2496 cx.notify();
2497 }
2498
2499 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2500 self.columnar_selection_tail.take();
2501 if self.selections.pending_anchor().is_some() {
2502 let selections = self.selections.all::<usize>(cx);
2503 self.change_selections(None, window, cx, |s| {
2504 s.select(selections);
2505 s.clear_pending();
2506 });
2507 }
2508 }
2509
2510 fn select_columns(
2511 &mut self,
2512 tail: DisplayPoint,
2513 head: DisplayPoint,
2514 goal_column: u32,
2515 display_map: &DisplaySnapshot,
2516 window: &mut Window,
2517 cx: &mut Context<Self>,
2518 ) {
2519 let start_row = cmp::min(tail.row(), head.row());
2520 let end_row = cmp::max(tail.row(), head.row());
2521 let start_column = cmp::min(tail.column(), goal_column);
2522 let end_column = cmp::max(tail.column(), goal_column);
2523 let reversed = start_column < tail.column();
2524
2525 let selection_ranges = (start_row.0..=end_row.0)
2526 .map(DisplayRow)
2527 .filter_map(|row| {
2528 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2529 let start = display_map
2530 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2531 .to_point(display_map);
2532 let end = display_map
2533 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2534 .to_point(display_map);
2535 if reversed {
2536 Some(end..start)
2537 } else {
2538 Some(start..end)
2539 }
2540 } else {
2541 None
2542 }
2543 })
2544 .collect::<Vec<_>>();
2545
2546 self.change_selections(None, window, cx, |s| {
2547 s.select_ranges(selection_ranges);
2548 });
2549 cx.notify();
2550 }
2551
2552 pub fn has_pending_nonempty_selection(&self) -> bool {
2553 let pending_nonempty_selection = match self.selections.pending_anchor() {
2554 Some(Selection { start, end, .. }) => start != end,
2555 None => false,
2556 };
2557
2558 pending_nonempty_selection
2559 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2560 }
2561
2562 pub fn has_pending_selection(&self) -> bool {
2563 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2564 }
2565
2566 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2567 self.selection_mark_mode = false;
2568
2569 if self.clear_expanded_diff_hunks(cx) {
2570 cx.notify();
2571 return;
2572 }
2573 if self.dismiss_menus_and_popups(true, window, cx) {
2574 return;
2575 }
2576
2577 if self.mode == EditorMode::Full
2578 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2579 {
2580 return;
2581 }
2582
2583 cx.propagate();
2584 }
2585
2586 pub fn dismiss_menus_and_popups(
2587 &mut self,
2588 should_report_inline_completion_event: bool,
2589 window: &mut Window,
2590 cx: &mut Context<Self>,
2591 ) -> bool {
2592 if self.take_rename(false, window, cx).is_some() {
2593 return true;
2594 }
2595
2596 if hide_hover(self, cx) {
2597 return true;
2598 }
2599
2600 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2601 return true;
2602 }
2603
2604 if self.hide_context_menu(window, cx).is_some() {
2605 return true;
2606 }
2607
2608 if self.mouse_context_menu.take().is_some() {
2609 return true;
2610 }
2611
2612 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2613 return true;
2614 }
2615
2616 if self.snippet_stack.pop().is_some() {
2617 return true;
2618 }
2619
2620 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2621 self.dismiss_diagnostics(cx);
2622 return true;
2623 }
2624
2625 false
2626 }
2627
2628 fn linked_editing_ranges_for(
2629 &self,
2630 selection: Range<text::Anchor>,
2631 cx: &App,
2632 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2633 if self.linked_edit_ranges.is_empty() {
2634 return None;
2635 }
2636 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2637 selection.end.buffer_id.and_then(|end_buffer_id| {
2638 if selection.start.buffer_id != Some(end_buffer_id) {
2639 return None;
2640 }
2641 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2642 let snapshot = buffer.read(cx).snapshot();
2643 self.linked_edit_ranges
2644 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2645 .map(|ranges| (ranges, snapshot, buffer))
2646 })?;
2647 use text::ToOffset as TO;
2648 // find offset from the start of current range to current cursor position
2649 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2650
2651 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2652 let start_difference = start_offset - start_byte_offset;
2653 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2654 let end_difference = end_offset - start_byte_offset;
2655 // Current range has associated linked ranges.
2656 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2657 for range in linked_ranges.iter() {
2658 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2659 let end_offset = start_offset + end_difference;
2660 let start_offset = start_offset + start_difference;
2661 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2662 continue;
2663 }
2664 if self.selections.disjoint_anchor_ranges().any(|s| {
2665 if s.start.buffer_id != selection.start.buffer_id
2666 || s.end.buffer_id != selection.end.buffer_id
2667 {
2668 return false;
2669 }
2670 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2671 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2672 }) {
2673 continue;
2674 }
2675 let start = buffer_snapshot.anchor_after(start_offset);
2676 let end = buffer_snapshot.anchor_after(end_offset);
2677 linked_edits
2678 .entry(buffer.clone())
2679 .or_default()
2680 .push(start..end);
2681 }
2682 Some(linked_edits)
2683 }
2684
2685 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2686 let text: Arc<str> = text.into();
2687
2688 if self.read_only(cx) {
2689 return;
2690 }
2691
2692 let selections = self.selections.all_adjusted(cx);
2693 let mut bracket_inserted = false;
2694 let mut edits = Vec::new();
2695 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2696 let mut new_selections = Vec::with_capacity(selections.len());
2697 let mut new_autoclose_regions = Vec::new();
2698 let snapshot = self.buffer.read(cx).read(cx);
2699
2700 for (selection, autoclose_region) in
2701 self.selections_with_autoclose_regions(selections, &snapshot)
2702 {
2703 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2704 // Determine if the inserted text matches the opening or closing
2705 // bracket of any of this language's bracket pairs.
2706 let mut bracket_pair = None;
2707 let mut is_bracket_pair_start = false;
2708 let mut is_bracket_pair_end = false;
2709 if !text.is_empty() {
2710 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2711 // and they are removing the character that triggered IME popup.
2712 for (pair, enabled) in scope.brackets() {
2713 if !pair.close && !pair.surround {
2714 continue;
2715 }
2716
2717 if enabled && pair.start.ends_with(text.as_ref()) {
2718 let prefix_len = pair.start.len() - text.len();
2719 let preceding_text_matches_prefix = prefix_len == 0
2720 || (selection.start.column >= (prefix_len as u32)
2721 && snapshot.contains_str_at(
2722 Point::new(
2723 selection.start.row,
2724 selection.start.column - (prefix_len as u32),
2725 ),
2726 &pair.start[..prefix_len],
2727 ));
2728 if preceding_text_matches_prefix {
2729 bracket_pair = Some(pair.clone());
2730 is_bracket_pair_start = true;
2731 break;
2732 }
2733 }
2734 if pair.end.as_str() == text.as_ref() {
2735 bracket_pair = Some(pair.clone());
2736 is_bracket_pair_end = true;
2737 break;
2738 }
2739 }
2740 }
2741
2742 if let Some(bracket_pair) = bracket_pair {
2743 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2744 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2745 let auto_surround =
2746 self.use_auto_surround && snapshot_settings.use_auto_surround;
2747 if selection.is_empty() {
2748 if is_bracket_pair_start {
2749 // If the inserted text is a suffix of an opening bracket and the
2750 // selection is preceded by the rest of the opening bracket, then
2751 // insert the closing bracket.
2752 let following_text_allows_autoclose = snapshot
2753 .chars_at(selection.start)
2754 .next()
2755 .map_or(true, |c| scope.should_autoclose_before(c));
2756
2757 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2758 && bracket_pair.start.len() == 1
2759 {
2760 let target = bracket_pair.start.chars().next().unwrap();
2761 let current_line_count = snapshot
2762 .reversed_chars_at(selection.start)
2763 .take_while(|&c| c != '\n')
2764 .filter(|&c| c == target)
2765 .count();
2766 current_line_count % 2 == 1
2767 } else {
2768 false
2769 };
2770
2771 if autoclose
2772 && bracket_pair.close
2773 && following_text_allows_autoclose
2774 && !is_closing_quote
2775 {
2776 let anchor = snapshot.anchor_before(selection.end);
2777 new_selections.push((selection.map(|_| anchor), text.len()));
2778 new_autoclose_regions.push((
2779 anchor,
2780 text.len(),
2781 selection.id,
2782 bracket_pair.clone(),
2783 ));
2784 edits.push((
2785 selection.range(),
2786 format!("{}{}", text, bracket_pair.end).into(),
2787 ));
2788 bracket_inserted = true;
2789 continue;
2790 }
2791 }
2792
2793 if let Some(region) = autoclose_region {
2794 // If the selection is followed by an auto-inserted closing bracket,
2795 // then don't insert that closing bracket again; just move the selection
2796 // past the closing bracket.
2797 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2798 && text.as_ref() == region.pair.end.as_str();
2799 if should_skip {
2800 let anchor = snapshot.anchor_after(selection.end);
2801 new_selections
2802 .push((selection.map(|_| anchor), region.pair.end.len()));
2803 continue;
2804 }
2805 }
2806
2807 let always_treat_brackets_as_autoclosed = snapshot
2808 .settings_at(selection.start, cx)
2809 .always_treat_brackets_as_autoclosed;
2810 if always_treat_brackets_as_autoclosed
2811 && is_bracket_pair_end
2812 && snapshot.contains_str_at(selection.end, text.as_ref())
2813 {
2814 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2815 // and the inserted text is a closing bracket and the selection is followed
2816 // by the closing bracket then move the selection past the closing bracket.
2817 let anchor = snapshot.anchor_after(selection.end);
2818 new_selections.push((selection.map(|_| anchor), text.len()));
2819 continue;
2820 }
2821 }
2822 // If an opening bracket is 1 character long and is typed while
2823 // text is selected, then surround that text with the bracket pair.
2824 else if auto_surround
2825 && bracket_pair.surround
2826 && is_bracket_pair_start
2827 && bracket_pair.start.chars().count() == 1
2828 {
2829 edits.push((selection.start..selection.start, text.clone()));
2830 edits.push((
2831 selection.end..selection.end,
2832 bracket_pair.end.as_str().into(),
2833 ));
2834 bracket_inserted = true;
2835 new_selections.push((
2836 Selection {
2837 id: selection.id,
2838 start: snapshot.anchor_after(selection.start),
2839 end: snapshot.anchor_before(selection.end),
2840 reversed: selection.reversed,
2841 goal: selection.goal,
2842 },
2843 0,
2844 ));
2845 continue;
2846 }
2847 }
2848 }
2849
2850 if self.auto_replace_emoji_shortcode
2851 && selection.is_empty()
2852 && text.as_ref().ends_with(':')
2853 {
2854 if let Some(possible_emoji_short_code) =
2855 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2856 {
2857 if !possible_emoji_short_code.is_empty() {
2858 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2859 let emoji_shortcode_start = Point::new(
2860 selection.start.row,
2861 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2862 );
2863
2864 // Remove shortcode from buffer
2865 edits.push((
2866 emoji_shortcode_start..selection.start,
2867 "".to_string().into(),
2868 ));
2869 new_selections.push((
2870 Selection {
2871 id: selection.id,
2872 start: snapshot.anchor_after(emoji_shortcode_start),
2873 end: snapshot.anchor_before(selection.start),
2874 reversed: selection.reversed,
2875 goal: selection.goal,
2876 },
2877 0,
2878 ));
2879
2880 // Insert emoji
2881 let selection_start_anchor = snapshot.anchor_after(selection.start);
2882 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2883 edits.push((selection.start..selection.end, emoji.to_string().into()));
2884
2885 continue;
2886 }
2887 }
2888 }
2889 }
2890
2891 // If not handling any auto-close operation, then just replace the selected
2892 // text with the given input and move the selection to the end of the
2893 // newly inserted text.
2894 let anchor = snapshot.anchor_after(selection.end);
2895 if !self.linked_edit_ranges.is_empty() {
2896 let start_anchor = snapshot.anchor_before(selection.start);
2897
2898 let is_word_char = text.chars().next().map_or(true, |char| {
2899 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2900 classifier.is_word(char)
2901 });
2902
2903 if is_word_char {
2904 if let Some(ranges) = self
2905 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2906 {
2907 for (buffer, edits) in ranges {
2908 linked_edits
2909 .entry(buffer.clone())
2910 .or_default()
2911 .extend(edits.into_iter().map(|range| (range, text.clone())));
2912 }
2913 }
2914 }
2915 }
2916
2917 new_selections.push((selection.map(|_| anchor), 0));
2918 edits.push((selection.start..selection.end, text.clone()));
2919 }
2920
2921 drop(snapshot);
2922
2923 self.transact(window, cx, |this, window, cx| {
2924 this.buffer.update(cx, |buffer, cx| {
2925 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2926 });
2927 for (buffer, edits) in linked_edits {
2928 buffer.update(cx, |buffer, cx| {
2929 let snapshot = buffer.snapshot();
2930 let edits = edits
2931 .into_iter()
2932 .map(|(range, text)| {
2933 use text::ToPoint as TP;
2934 let end_point = TP::to_point(&range.end, &snapshot);
2935 let start_point = TP::to_point(&range.start, &snapshot);
2936 (start_point..end_point, text)
2937 })
2938 .sorted_by_key(|(range, _)| range.start)
2939 .collect::<Vec<_>>();
2940 buffer.edit(edits, None, cx);
2941 })
2942 }
2943 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2944 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2945 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2946 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2947 .zip(new_selection_deltas)
2948 .map(|(selection, delta)| Selection {
2949 id: selection.id,
2950 start: selection.start + delta,
2951 end: selection.end + delta,
2952 reversed: selection.reversed,
2953 goal: SelectionGoal::None,
2954 })
2955 .collect::<Vec<_>>();
2956
2957 let mut i = 0;
2958 for (position, delta, selection_id, pair) in new_autoclose_regions {
2959 let position = position.to_offset(&map.buffer_snapshot) + delta;
2960 let start = map.buffer_snapshot.anchor_before(position);
2961 let end = map.buffer_snapshot.anchor_after(position);
2962 while let Some(existing_state) = this.autoclose_regions.get(i) {
2963 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2964 Ordering::Less => i += 1,
2965 Ordering::Greater => break,
2966 Ordering::Equal => {
2967 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2968 Ordering::Less => i += 1,
2969 Ordering::Equal => break,
2970 Ordering::Greater => break,
2971 }
2972 }
2973 }
2974 }
2975 this.autoclose_regions.insert(
2976 i,
2977 AutocloseRegion {
2978 selection_id,
2979 range: start..end,
2980 pair,
2981 },
2982 );
2983 }
2984
2985 let had_active_inline_completion = this.has_active_inline_completion();
2986 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
2987 s.select(new_selections)
2988 });
2989
2990 if !bracket_inserted {
2991 if let Some(on_type_format_task) =
2992 this.trigger_on_type_formatting(text.to_string(), window, cx)
2993 {
2994 on_type_format_task.detach_and_log_err(cx);
2995 }
2996 }
2997
2998 let editor_settings = EditorSettings::get_global(cx);
2999 if bracket_inserted
3000 && (editor_settings.auto_signature_help
3001 || editor_settings.show_signature_help_after_edits)
3002 {
3003 this.show_signature_help(&ShowSignatureHelp, window, cx);
3004 }
3005
3006 let trigger_in_words =
3007 this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
3008 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3009 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3010 this.refresh_inline_completion(true, false, window, cx);
3011 });
3012 }
3013
3014 fn find_possible_emoji_shortcode_at_position(
3015 snapshot: &MultiBufferSnapshot,
3016 position: Point,
3017 ) -> Option<String> {
3018 let mut chars = Vec::new();
3019 let mut found_colon = false;
3020 for char in snapshot.reversed_chars_at(position).take(100) {
3021 // Found a possible emoji shortcode in the middle of the buffer
3022 if found_colon {
3023 if char.is_whitespace() {
3024 chars.reverse();
3025 return Some(chars.iter().collect());
3026 }
3027 // If the previous character is not a whitespace, we are in the middle of a word
3028 // and we only want to complete the shortcode if the word is made up of other emojis
3029 let mut containing_word = String::new();
3030 for ch in snapshot
3031 .reversed_chars_at(position)
3032 .skip(chars.len() + 1)
3033 .take(100)
3034 {
3035 if ch.is_whitespace() {
3036 break;
3037 }
3038 containing_word.push(ch);
3039 }
3040 let containing_word = containing_word.chars().rev().collect::<String>();
3041 if util::word_consists_of_emojis(containing_word.as_str()) {
3042 chars.reverse();
3043 return Some(chars.iter().collect());
3044 }
3045 }
3046
3047 if char.is_whitespace() || !char.is_ascii() {
3048 return None;
3049 }
3050 if char == ':' {
3051 found_colon = true;
3052 } else {
3053 chars.push(char);
3054 }
3055 }
3056 // Found a possible emoji shortcode at the beginning of the buffer
3057 chars.reverse();
3058 Some(chars.iter().collect())
3059 }
3060
3061 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3062 self.transact(window, cx, |this, window, cx| {
3063 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3064 let selections = this.selections.all::<usize>(cx);
3065 let multi_buffer = this.buffer.read(cx);
3066 let buffer = multi_buffer.snapshot(cx);
3067 selections
3068 .iter()
3069 .map(|selection| {
3070 let start_point = selection.start.to_point(&buffer);
3071 let mut indent =
3072 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3073 indent.len = cmp::min(indent.len, start_point.column);
3074 let start = selection.start;
3075 let end = selection.end;
3076 let selection_is_empty = start == end;
3077 let language_scope = buffer.language_scope_at(start);
3078 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3079 &language_scope
3080 {
3081 let leading_whitespace_len = buffer
3082 .reversed_chars_at(start)
3083 .take_while(|c| c.is_whitespace() && *c != '\n')
3084 .map(|c| c.len_utf8())
3085 .sum::<usize>();
3086
3087 let trailing_whitespace_len = buffer
3088 .chars_at(end)
3089 .take_while(|c| c.is_whitespace() && *c != '\n')
3090 .map(|c| c.len_utf8())
3091 .sum::<usize>();
3092
3093 let insert_extra_newline =
3094 language.brackets().any(|(pair, enabled)| {
3095 let pair_start = pair.start.trim_end();
3096 let pair_end = pair.end.trim_start();
3097
3098 enabled
3099 && pair.newline
3100 && buffer.contains_str_at(
3101 end + trailing_whitespace_len,
3102 pair_end,
3103 )
3104 && buffer.contains_str_at(
3105 (start - leading_whitespace_len)
3106 .saturating_sub(pair_start.len()),
3107 pair_start,
3108 )
3109 });
3110
3111 // Comment extension on newline is allowed only for cursor selections
3112 let comment_delimiter = maybe!({
3113 if !selection_is_empty {
3114 return None;
3115 }
3116
3117 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3118 return None;
3119 }
3120
3121 let delimiters = language.line_comment_prefixes();
3122 let max_len_of_delimiter =
3123 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3124 let (snapshot, range) =
3125 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3126
3127 let mut index_of_first_non_whitespace = 0;
3128 let comment_candidate = snapshot
3129 .chars_for_range(range)
3130 .skip_while(|c| {
3131 let should_skip = c.is_whitespace();
3132 if should_skip {
3133 index_of_first_non_whitespace += 1;
3134 }
3135 should_skip
3136 })
3137 .take(max_len_of_delimiter)
3138 .collect::<String>();
3139 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3140 comment_candidate.starts_with(comment_prefix.as_ref())
3141 })?;
3142 let cursor_is_placed_after_comment_marker =
3143 index_of_first_non_whitespace + comment_prefix.len()
3144 <= start_point.column as usize;
3145 if cursor_is_placed_after_comment_marker {
3146 Some(comment_prefix.clone())
3147 } else {
3148 None
3149 }
3150 });
3151 (comment_delimiter, insert_extra_newline)
3152 } else {
3153 (None, false)
3154 };
3155
3156 let capacity_for_delimiter = comment_delimiter
3157 .as_deref()
3158 .map(str::len)
3159 .unwrap_or_default();
3160 let mut new_text =
3161 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3162 new_text.push('\n');
3163 new_text.extend(indent.chars());
3164 if let Some(delimiter) = &comment_delimiter {
3165 new_text.push_str(delimiter);
3166 }
3167 if insert_extra_newline {
3168 new_text = new_text.repeat(2);
3169 }
3170
3171 let anchor = buffer.anchor_after(end);
3172 let new_selection = selection.map(|_| anchor);
3173 (
3174 (start..end, new_text),
3175 (insert_extra_newline, new_selection),
3176 )
3177 })
3178 .unzip()
3179 };
3180
3181 this.edit_with_autoindent(edits, cx);
3182 let buffer = this.buffer.read(cx).snapshot(cx);
3183 let new_selections = selection_fixup_info
3184 .into_iter()
3185 .map(|(extra_newline_inserted, new_selection)| {
3186 let mut cursor = new_selection.end.to_point(&buffer);
3187 if extra_newline_inserted {
3188 cursor.row -= 1;
3189 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3190 }
3191 new_selection.map(|_| cursor)
3192 })
3193 .collect();
3194
3195 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3196 s.select(new_selections)
3197 });
3198 this.refresh_inline_completion(true, false, window, cx);
3199 });
3200 }
3201
3202 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3203 let buffer = self.buffer.read(cx);
3204 let snapshot = buffer.snapshot(cx);
3205
3206 let mut edits = Vec::new();
3207 let mut rows = Vec::new();
3208
3209 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3210 let cursor = selection.head();
3211 let row = cursor.row;
3212
3213 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3214
3215 let newline = "\n".to_string();
3216 edits.push((start_of_line..start_of_line, newline));
3217
3218 rows.push(row + rows_inserted as u32);
3219 }
3220
3221 self.transact(window, cx, |editor, window, cx| {
3222 editor.edit(edits, cx);
3223
3224 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3225 let mut index = 0;
3226 s.move_cursors_with(|map, _, _| {
3227 let row = rows[index];
3228 index += 1;
3229
3230 let point = Point::new(row, 0);
3231 let boundary = map.next_line_boundary(point).1;
3232 let clipped = map.clip_point(boundary, Bias::Left);
3233
3234 (clipped, SelectionGoal::None)
3235 });
3236 });
3237
3238 let mut indent_edits = Vec::new();
3239 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3240 for row in rows {
3241 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3242 for (row, indent) in indents {
3243 if indent.len == 0 {
3244 continue;
3245 }
3246
3247 let text = match indent.kind {
3248 IndentKind::Space => " ".repeat(indent.len as usize),
3249 IndentKind::Tab => "\t".repeat(indent.len as usize),
3250 };
3251 let point = Point::new(row.0, 0);
3252 indent_edits.push((point..point, text));
3253 }
3254 }
3255 editor.edit(indent_edits, cx);
3256 });
3257 }
3258
3259 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3260 let buffer = self.buffer.read(cx);
3261 let snapshot = buffer.snapshot(cx);
3262
3263 let mut edits = Vec::new();
3264 let mut rows = Vec::new();
3265 let mut rows_inserted = 0;
3266
3267 for selection in self.selections.all_adjusted(cx) {
3268 let cursor = selection.head();
3269 let row = cursor.row;
3270
3271 let point = Point::new(row + 1, 0);
3272 let start_of_line = snapshot.clip_point(point, Bias::Left);
3273
3274 let newline = "\n".to_string();
3275 edits.push((start_of_line..start_of_line, newline));
3276
3277 rows_inserted += 1;
3278 rows.push(row + rows_inserted);
3279 }
3280
3281 self.transact(window, cx, |editor, window, cx| {
3282 editor.edit(edits, cx);
3283
3284 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3285 let mut index = 0;
3286 s.move_cursors_with(|map, _, _| {
3287 let row = rows[index];
3288 index += 1;
3289
3290 let point = Point::new(row, 0);
3291 let boundary = map.next_line_boundary(point).1;
3292 let clipped = map.clip_point(boundary, Bias::Left);
3293
3294 (clipped, SelectionGoal::None)
3295 });
3296 });
3297
3298 let mut indent_edits = Vec::new();
3299 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3300 for row in rows {
3301 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3302 for (row, indent) in indents {
3303 if indent.len == 0 {
3304 continue;
3305 }
3306
3307 let text = match indent.kind {
3308 IndentKind::Space => " ".repeat(indent.len as usize),
3309 IndentKind::Tab => "\t".repeat(indent.len as usize),
3310 };
3311 let point = Point::new(row.0, 0);
3312 indent_edits.push((point..point, text));
3313 }
3314 }
3315 editor.edit(indent_edits, cx);
3316 });
3317 }
3318
3319 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3320 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3321 original_indent_columns: Vec::new(),
3322 });
3323 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3324 }
3325
3326 fn insert_with_autoindent_mode(
3327 &mut self,
3328 text: &str,
3329 autoindent_mode: Option<AutoindentMode>,
3330 window: &mut Window,
3331 cx: &mut Context<Self>,
3332 ) {
3333 if self.read_only(cx) {
3334 return;
3335 }
3336
3337 let text: Arc<str> = text.into();
3338 self.transact(window, cx, |this, window, cx| {
3339 let old_selections = this.selections.all_adjusted(cx);
3340 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3341 let anchors = {
3342 let snapshot = buffer.read(cx);
3343 old_selections
3344 .iter()
3345 .map(|s| {
3346 let anchor = snapshot.anchor_after(s.head());
3347 s.map(|_| anchor)
3348 })
3349 .collect::<Vec<_>>()
3350 };
3351 buffer.edit(
3352 old_selections
3353 .iter()
3354 .map(|s| (s.start..s.end, text.clone())),
3355 autoindent_mode,
3356 cx,
3357 );
3358 anchors
3359 });
3360
3361 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3362 s.select_anchors(selection_anchors);
3363 });
3364
3365 cx.notify();
3366 });
3367 }
3368
3369 fn trigger_completion_on_input(
3370 &mut self,
3371 text: &str,
3372 trigger_in_words: bool,
3373 window: &mut Window,
3374 cx: &mut Context<Self>,
3375 ) {
3376 if self.is_completion_trigger(text, trigger_in_words, cx) {
3377 self.show_completions(
3378 &ShowCompletions {
3379 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3380 },
3381 window,
3382 cx,
3383 );
3384 } else {
3385 self.hide_context_menu(window, cx);
3386 }
3387 }
3388
3389 fn is_completion_trigger(
3390 &self,
3391 text: &str,
3392 trigger_in_words: bool,
3393 cx: &mut Context<Self>,
3394 ) -> bool {
3395 let position = self.selections.newest_anchor().head();
3396 let multibuffer = self.buffer.read(cx);
3397 let Some(buffer) = position
3398 .buffer_id
3399 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3400 else {
3401 return false;
3402 };
3403
3404 if let Some(completion_provider) = &self.completion_provider {
3405 completion_provider.is_completion_trigger(
3406 &buffer,
3407 position.text_anchor,
3408 text,
3409 trigger_in_words,
3410 cx,
3411 )
3412 } else {
3413 false
3414 }
3415 }
3416
3417 /// If any empty selections is touching the start of its innermost containing autoclose
3418 /// region, expand it to select the brackets.
3419 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3420 let selections = self.selections.all::<usize>(cx);
3421 let buffer = self.buffer.read(cx).read(cx);
3422 let new_selections = self
3423 .selections_with_autoclose_regions(selections, &buffer)
3424 .map(|(mut selection, region)| {
3425 if !selection.is_empty() {
3426 return selection;
3427 }
3428
3429 if let Some(region) = region {
3430 let mut range = region.range.to_offset(&buffer);
3431 if selection.start == range.start && range.start >= region.pair.start.len() {
3432 range.start -= region.pair.start.len();
3433 if buffer.contains_str_at(range.start, ®ion.pair.start)
3434 && buffer.contains_str_at(range.end, ®ion.pair.end)
3435 {
3436 range.end += region.pair.end.len();
3437 selection.start = range.start;
3438 selection.end = range.end;
3439
3440 return selection;
3441 }
3442 }
3443 }
3444
3445 let always_treat_brackets_as_autoclosed = buffer
3446 .settings_at(selection.start, cx)
3447 .always_treat_brackets_as_autoclosed;
3448
3449 if !always_treat_brackets_as_autoclosed {
3450 return selection;
3451 }
3452
3453 if let Some(scope) = buffer.language_scope_at(selection.start) {
3454 for (pair, enabled) in scope.brackets() {
3455 if !enabled || !pair.close {
3456 continue;
3457 }
3458
3459 if buffer.contains_str_at(selection.start, &pair.end) {
3460 let pair_start_len = pair.start.len();
3461 if buffer.contains_str_at(
3462 selection.start.saturating_sub(pair_start_len),
3463 &pair.start,
3464 ) {
3465 selection.start -= pair_start_len;
3466 selection.end += pair.end.len();
3467
3468 return selection;
3469 }
3470 }
3471 }
3472 }
3473
3474 selection
3475 })
3476 .collect();
3477
3478 drop(buffer);
3479 self.change_selections(None, window, cx, |selections| {
3480 selections.select(new_selections)
3481 });
3482 }
3483
3484 /// Iterate the given selections, and for each one, find the smallest surrounding
3485 /// autoclose region. This uses the ordering of the selections and the autoclose
3486 /// regions to avoid repeated comparisons.
3487 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3488 &'a self,
3489 selections: impl IntoIterator<Item = Selection<D>>,
3490 buffer: &'a MultiBufferSnapshot,
3491 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3492 let mut i = 0;
3493 let mut regions = self.autoclose_regions.as_slice();
3494 selections.into_iter().map(move |selection| {
3495 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3496
3497 let mut enclosing = None;
3498 while let Some(pair_state) = regions.get(i) {
3499 if pair_state.range.end.to_offset(buffer) < range.start {
3500 regions = ®ions[i + 1..];
3501 i = 0;
3502 } else if pair_state.range.start.to_offset(buffer) > range.end {
3503 break;
3504 } else {
3505 if pair_state.selection_id == selection.id {
3506 enclosing = Some(pair_state);
3507 }
3508 i += 1;
3509 }
3510 }
3511
3512 (selection, enclosing)
3513 })
3514 }
3515
3516 /// Remove any autoclose regions that no longer contain their selection.
3517 fn invalidate_autoclose_regions(
3518 &mut self,
3519 mut selections: &[Selection<Anchor>],
3520 buffer: &MultiBufferSnapshot,
3521 ) {
3522 self.autoclose_regions.retain(|state| {
3523 let mut i = 0;
3524 while let Some(selection) = selections.get(i) {
3525 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3526 selections = &selections[1..];
3527 continue;
3528 }
3529 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3530 break;
3531 }
3532 if selection.id == state.selection_id {
3533 return true;
3534 } else {
3535 i += 1;
3536 }
3537 }
3538 false
3539 });
3540 }
3541
3542 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3543 let offset = position.to_offset(buffer);
3544 let (word_range, kind) = buffer.surrounding_word(offset, true);
3545 if offset > word_range.start && kind == Some(CharKind::Word) {
3546 Some(
3547 buffer
3548 .text_for_range(word_range.start..offset)
3549 .collect::<String>(),
3550 )
3551 } else {
3552 None
3553 }
3554 }
3555
3556 pub fn toggle_inlay_hints(
3557 &mut self,
3558 _: &ToggleInlayHints,
3559 _: &mut Window,
3560 cx: &mut Context<Self>,
3561 ) {
3562 self.refresh_inlay_hints(
3563 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3564 cx,
3565 );
3566 }
3567
3568 pub fn inlay_hints_enabled(&self) -> bool {
3569 self.inlay_hint_cache.enabled
3570 }
3571
3572 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3573 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3574 return;
3575 }
3576
3577 let reason_description = reason.description();
3578 let ignore_debounce = matches!(
3579 reason,
3580 InlayHintRefreshReason::SettingsChange(_)
3581 | InlayHintRefreshReason::Toggle(_)
3582 | InlayHintRefreshReason::ExcerptsRemoved(_)
3583 );
3584 let (invalidate_cache, required_languages) = match reason {
3585 InlayHintRefreshReason::Toggle(enabled) => {
3586 self.inlay_hint_cache.enabled = enabled;
3587 if enabled {
3588 (InvalidationStrategy::RefreshRequested, None)
3589 } else {
3590 self.inlay_hint_cache.clear();
3591 self.splice_inlays(
3592 &self
3593 .visible_inlay_hints(cx)
3594 .iter()
3595 .map(|inlay| inlay.id)
3596 .collect::<Vec<InlayId>>(),
3597 Vec::new(),
3598 cx,
3599 );
3600 return;
3601 }
3602 }
3603 InlayHintRefreshReason::SettingsChange(new_settings) => {
3604 match self.inlay_hint_cache.update_settings(
3605 &self.buffer,
3606 new_settings,
3607 self.visible_inlay_hints(cx),
3608 cx,
3609 ) {
3610 ControlFlow::Break(Some(InlaySplice {
3611 to_remove,
3612 to_insert,
3613 })) => {
3614 self.splice_inlays(&to_remove, to_insert, cx);
3615 return;
3616 }
3617 ControlFlow::Break(None) => return,
3618 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3619 }
3620 }
3621 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3622 if let Some(InlaySplice {
3623 to_remove,
3624 to_insert,
3625 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3626 {
3627 self.splice_inlays(&to_remove, to_insert, cx);
3628 }
3629 return;
3630 }
3631 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3632 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3633 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3634 }
3635 InlayHintRefreshReason::RefreshRequested => {
3636 (InvalidationStrategy::RefreshRequested, None)
3637 }
3638 };
3639
3640 if let Some(InlaySplice {
3641 to_remove,
3642 to_insert,
3643 }) = self.inlay_hint_cache.spawn_hint_refresh(
3644 reason_description,
3645 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3646 invalidate_cache,
3647 ignore_debounce,
3648 cx,
3649 ) {
3650 self.splice_inlays(&to_remove, to_insert, cx);
3651 }
3652 }
3653
3654 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3655 self.display_map
3656 .read(cx)
3657 .current_inlays()
3658 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3659 .cloned()
3660 .collect()
3661 }
3662
3663 pub fn excerpts_for_inlay_hints_query(
3664 &self,
3665 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3666 cx: &mut Context<Editor>,
3667 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3668 let Some(project) = self.project.as_ref() else {
3669 return HashMap::default();
3670 };
3671 let project = project.read(cx);
3672 let multi_buffer = self.buffer().read(cx);
3673 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3674 let multi_buffer_visible_start = self
3675 .scroll_manager
3676 .anchor()
3677 .anchor
3678 .to_point(&multi_buffer_snapshot);
3679 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3680 multi_buffer_visible_start
3681 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3682 Bias::Left,
3683 );
3684 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3685 multi_buffer_snapshot
3686 .range_to_buffer_ranges(multi_buffer_visible_range)
3687 .into_iter()
3688 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3689 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3690 let buffer_file = project::File::from_dyn(buffer.file())?;
3691 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3692 let worktree_entry = buffer_worktree
3693 .read(cx)
3694 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3695 if worktree_entry.is_ignored {
3696 return None;
3697 }
3698
3699 let language = buffer.language()?;
3700 if let Some(restrict_to_languages) = restrict_to_languages {
3701 if !restrict_to_languages.contains(language) {
3702 return None;
3703 }
3704 }
3705 Some((
3706 excerpt_id,
3707 (
3708 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3709 buffer.version().clone(),
3710 excerpt_visible_range,
3711 ),
3712 ))
3713 })
3714 .collect()
3715 }
3716
3717 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3718 TextLayoutDetails {
3719 text_system: window.text_system().clone(),
3720 editor_style: self.style.clone().unwrap(),
3721 rem_size: window.rem_size(),
3722 scroll_anchor: self.scroll_manager.anchor(),
3723 visible_rows: self.visible_line_count(),
3724 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3725 }
3726 }
3727
3728 pub fn splice_inlays(
3729 &self,
3730 to_remove: &[InlayId],
3731 to_insert: Vec<Inlay>,
3732 cx: &mut Context<Self>,
3733 ) {
3734 self.display_map.update(cx, |display_map, cx| {
3735 display_map.splice_inlays(to_remove, to_insert, cx)
3736 });
3737 cx.notify();
3738 }
3739
3740 fn trigger_on_type_formatting(
3741 &self,
3742 input: String,
3743 window: &mut Window,
3744 cx: &mut Context<Self>,
3745 ) -> Option<Task<Result<()>>> {
3746 if input.len() != 1 {
3747 return None;
3748 }
3749
3750 let project = self.project.as_ref()?;
3751 let position = self.selections.newest_anchor().head();
3752 let (buffer, buffer_position) = self
3753 .buffer
3754 .read(cx)
3755 .text_anchor_for_position(position, cx)?;
3756
3757 let settings = language_settings::language_settings(
3758 buffer
3759 .read(cx)
3760 .language_at(buffer_position)
3761 .map(|l| l.name()),
3762 buffer.read(cx).file(),
3763 cx,
3764 );
3765 if !settings.use_on_type_format {
3766 return None;
3767 }
3768
3769 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3770 // hence we do LSP request & edit on host side only — add formats to host's history.
3771 let push_to_lsp_host_history = true;
3772 // If this is not the host, append its history with new edits.
3773 let push_to_client_history = project.read(cx).is_via_collab();
3774
3775 let on_type_formatting = project.update(cx, |project, cx| {
3776 project.on_type_format(
3777 buffer.clone(),
3778 buffer_position,
3779 input,
3780 push_to_lsp_host_history,
3781 cx,
3782 )
3783 });
3784 Some(cx.spawn_in(window, |editor, mut cx| async move {
3785 if let Some(transaction) = on_type_formatting.await? {
3786 if push_to_client_history {
3787 buffer
3788 .update(&mut cx, |buffer, _| {
3789 buffer.push_transaction(transaction, Instant::now());
3790 })
3791 .ok();
3792 }
3793 editor.update(&mut cx, |editor, cx| {
3794 editor.refresh_document_highlights(cx);
3795 })?;
3796 }
3797 Ok(())
3798 }))
3799 }
3800
3801 pub fn show_completions(
3802 &mut self,
3803 options: &ShowCompletions,
3804 window: &mut Window,
3805 cx: &mut Context<Self>,
3806 ) {
3807 if self.pending_rename.is_some() {
3808 return;
3809 }
3810
3811 let Some(provider) = self.completion_provider.as_ref() else {
3812 return;
3813 };
3814
3815 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3816 return;
3817 }
3818
3819 let position = self.selections.newest_anchor().head();
3820 if position.diff_base_anchor.is_some() {
3821 return;
3822 }
3823 let (buffer, buffer_position) =
3824 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3825 output
3826 } else {
3827 return;
3828 };
3829 let show_completion_documentation = buffer
3830 .read(cx)
3831 .snapshot()
3832 .settings_at(buffer_position, cx)
3833 .show_completion_documentation;
3834
3835 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3836
3837 let trigger_kind = match &options.trigger {
3838 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3839 CompletionTriggerKind::TRIGGER_CHARACTER
3840 }
3841 _ => CompletionTriggerKind::INVOKED,
3842 };
3843 let completion_context = CompletionContext {
3844 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3845 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3846 Some(String::from(trigger))
3847 } else {
3848 None
3849 }
3850 }),
3851 trigger_kind,
3852 };
3853 let completions =
3854 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3855 let sort_completions = provider.sort_completions();
3856
3857 let id = post_inc(&mut self.next_completion_id);
3858 let task = cx.spawn_in(window, |editor, mut cx| {
3859 async move {
3860 editor.update(&mut cx, |this, _| {
3861 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3862 })?;
3863 let completions = completions.await.log_err();
3864 let menu = if let Some(completions) = completions {
3865 let mut menu = CompletionsMenu::new(
3866 id,
3867 sort_completions,
3868 show_completion_documentation,
3869 position,
3870 buffer.clone(),
3871 completions.into(),
3872 );
3873
3874 menu.filter(query.as_deref(), cx.background_executor().clone())
3875 .await;
3876
3877 menu.visible().then_some(menu)
3878 } else {
3879 None
3880 };
3881
3882 editor.update_in(&mut cx, |editor, window, cx| {
3883 match editor.context_menu.borrow().as_ref() {
3884 None => {}
3885 Some(CodeContextMenu::Completions(prev_menu)) => {
3886 if prev_menu.id > id {
3887 return;
3888 }
3889 }
3890 _ => return,
3891 }
3892
3893 if editor.focus_handle.is_focused(window) && menu.is_some() {
3894 let mut menu = menu.unwrap();
3895 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3896
3897 *editor.context_menu.borrow_mut() =
3898 Some(CodeContextMenu::Completions(menu));
3899
3900 if editor.show_inline_completions_in_menu(cx) {
3901 editor.update_visible_inline_completion(window, cx);
3902 } else {
3903 editor.discard_inline_completion(false, cx);
3904 }
3905
3906 cx.notify();
3907 } else if editor.completion_tasks.len() <= 1 {
3908 // If there are no more completion tasks and the last menu was
3909 // empty, we should hide it.
3910 let was_hidden = editor.hide_context_menu(window, cx).is_none();
3911 // If it was already hidden and we don't show inline
3912 // completions in the menu, we should also show the
3913 // inline-completion when available.
3914 if was_hidden && editor.show_inline_completions_in_menu(cx) {
3915 editor.update_visible_inline_completion(window, cx);
3916 }
3917 }
3918 })?;
3919
3920 Ok::<_, anyhow::Error>(())
3921 }
3922 .log_err()
3923 });
3924
3925 self.completion_tasks.push((id, task));
3926 }
3927
3928 pub fn confirm_completion(
3929 &mut self,
3930 action: &ConfirmCompletion,
3931 window: &mut Window,
3932 cx: &mut Context<Self>,
3933 ) -> Option<Task<Result<()>>> {
3934 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
3935 }
3936
3937 pub fn compose_completion(
3938 &mut self,
3939 action: &ComposeCompletion,
3940 window: &mut Window,
3941 cx: &mut Context<Self>,
3942 ) -> Option<Task<Result<()>>> {
3943 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
3944 }
3945
3946 fn toggle_zed_predict_onboarding(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3947 window.dispatch_action(zed_actions::OpenZedPredictOnboarding.boxed_clone(), cx);
3948 }
3949
3950 fn do_completion(
3951 &mut self,
3952 item_ix: Option<usize>,
3953 intent: CompletionIntent,
3954 window: &mut Window,
3955 cx: &mut Context<Editor>,
3956 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3957 use language::ToOffset as _;
3958
3959 let completions_menu =
3960 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
3961 menu
3962 } else {
3963 return None;
3964 };
3965
3966 let entries = completions_menu.entries.borrow();
3967 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
3968 if self.show_inline_completions_in_menu(cx) {
3969 self.discard_inline_completion(true, cx);
3970 }
3971 let candidate_id = mat.candidate_id;
3972 drop(entries);
3973
3974 let buffer_handle = completions_menu.buffer;
3975 let completion = completions_menu
3976 .completions
3977 .borrow()
3978 .get(candidate_id)?
3979 .clone();
3980 cx.stop_propagation();
3981
3982 let snippet;
3983 let text;
3984
3985 if completion.is_snippet() {
3986 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3987 text = snippet.as_ref().unwrap().text.clone();
3988 } else {
3989 snippet = None;
3990 text = completion.new_text.clone();
3991 };
3992 let selections = self.selections.all::<usize>(cx);
3993 let buffer = buffer_handle.read(cx);
3994 let old_range = completion.old_range.to_offset(buffer);
3995 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3996
3997 let newest_selection = self.selections.newest_anchor();
3998 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3999 return None;
4000 }
4001
4002 let lookbehind = newest_selection
4003 .start
4004 .text_anchor
4005 .to_offset(buffer)
4006 .saturating_sub(old_range.start);
4007 let lookahead = old_range
4008 .end
4009 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4010 let mut common_prefix_len = old_text
4011 .bytes()
4012 .zip(text.bytes())
4013 .take_while(|(a, b)| a == b)
4014 .count();
4015
4016 let snapshot = self.buffer.read(cx).snapshot(cx);
4017 let mut range_to_replace: Option<Range<isize>> = None;
4018 let mut ranges = Vec::new();
4019 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4020 for selection in &selections {
4021 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4022 let start = selection.start.saturating_sub(lookbehind);
4023 let end = selection.end + lookahead;
4024 if selection.id == newest_selection.id {
4025 range_to_replace = Some(
4026 ((start + common_prefix_len) as isize - selection.start as isize)
4027 ..(end as isize - selection.start as isize),
4028 );
4029 }
4030 ranges.push(start + common_prefix_len..end);
4031 } else {
4032 common_prefix_len = 0;
4033 ranges.clear();
4034 ranges.extend(selections.iter().map(|s| {
4035 if s.id == newest_selection.id {
4036 range_to_replace = Some(
4037 old_range.start.to_offset_utf16(&snapshot).0 as isize
4038 - selection.start as isize
4039 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4040 - selection.start as isize,
4041 );
4042 old_range.clone()
4043 } else {
4044 s.start..s.end
4045 }
4046 }));
4047 break;
4048 }
4049 if !self.linked_edit_ranges.is_empty() {
4050 let start_anchor = snapshot.anchor_before(selection.head());
4051 let end_anchor = snapshot.anchor_after(selection.tail());
4052 if let Some(ranges) = self
4053 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4054 {
4055 for (buffer, edits) in ranges {
4056 linked_edits.entry(buffer.clone()).or_default().extend(
4057 edits
4058 .into_iter()
4059 .map(|range| (range, text[common_prefix_len..].to_owned())),
4060 );
4061 }
4062 }
4063 }
4064 }
4065 let text = &text[common_prefix_len..];
4066
4067 cx.emit(EditorEvent::InputHandled {
4068 utf16_range_to_replace: range_to_replace,
4069 text: text.into(),
4070 });
4071
4072 self.transact(window, cx, |this, window, cx| {
4073 if let Some(mut snippet) = snippet {
4074 snippet.text = text.to_string();
4075 for tabstop in snippet
4076 .tabstops
4077 .iter_mut()
4078 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4079 {
4080 tabstop.start -= common_prefix_len as isize;
4081 tabstop.end -= common_prefix_len as isize;
4082 }
4083
4084 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4085 } else {
4086 this.buffer.update(cx, |buffer, cx| {
4087 buffer.edit(
4088 ranges.iter().map(|range| (range.clone(), text)),
4089 this.autoindent_mode.clone(),
4090 cx,
4091 );
4092 });
4093 }
4094 for (buffer, edits) in linked_edits {
4095 buffer.update(cx, |buffer, cx| {
4096 let snapshot = buffer.snapshot();
4097 let edits = edits
4098 .into_iter()
4099 .map(|(range, text)| {
4100 use text::ToPoint as TP;
4101 let end_point = TP::to_point(&range.end, &snapshot);
4102 let start_point = TP::to_point(&range.start, &snapshot);
4103 (start_point..end_point, text)
4104 })
4105 .sorted_by_key(|(range, _)| range.start)
4106 .collect::<Vec<_>>();
4107 buffer.edit(edits, None, cx);
4108 })
4109 }
4110
4111 this.refresh_inline_completion(true, false, window, cx);
4112 });
4113
4114 let show_new_completions_on_confirm = completion
4115 .confirm
4116 .as_ref()
4117 .map_or(false, |confirm| confirm(intent, window, cx));
4118 if show_new_completions_on_confirm {
4119 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4120 }
4121
4122 let provider = self.completion_provider.as_ref()?;
4123 drop(completion);
4124 let apply_edits = provider.apply_additional_edits_for_completion(
4125 buffer_handle,
4126 completions_menu.completions.clone(),
4127 candidate_id,
4128 true,
4129 cx,
4130 );
4131
4132 let editor_settings = EditorSettings::get_global(cx);
4133 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4134 // After the code completion is finished, users often want to know what signatures are needed.
4135 // so we should automatically call signature_help
4136 self.show_signature_help(&ShowSignatureHelp, window, cx);
4137 }
4138
4139 Some(cx.foreground_executor().spawn(async move {
4140 apply_edits.await?;
4141 Ok(())
4142 }))
4143 }
4144
4145 pub fn toggle_code_actions(
4146 &mut self,
4147 action: &ToggleCodeActions,
4148 window: &mut Window,
4149 cx: &mut Context<Self>,
4150 ) {
4151 let mut context_menu = self.context_menu.borrow_mut();
4152 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4153 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4154 // Toggle if we're selecting the same one
4155 *context_menu = None;
4156 cx.notify();
4157 return;
4158 } else {
4159 // Otherwise, clear it and start a new one
4160 *context_menu = None;
4161 cx.notify();
4162 }
4163 }
4164 drop(context_menu);
4165 let snapshot = self.snapshot(window, cx);
4166 let deployed_from_indicator = action.deployed_from_indicator;
4167 let mut task = self.code_actions_task.take();
4168 let action = action.clone();
4169 cx.spawn_in(window, |editor, mut cx| async move {
4170 while let Some(prev_task) = task {
4171 prev_task.await.log_err();
4172 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4173 }
4174
4175 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4176 if editor.focus_handle.is_focused(window) {
4177 let multibuffer_point = action
4178 .deployed_from_indicator
4179 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4180 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4181 let (buffer, buffer_row) = snapshot
4182 .buffer_snapshot
4183 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4184 .and_then(|(buffer_snapshot, range)| {
4185 editor
4186 .buffer
4187 .read(cx)
4188 .buffer(buffer_snapshot.remote_id())
4189 .map(|buffer| (buffer, range.start.row))
4190 })?;
4191 let (_, code_actions) = editor
4192 .available_code_actions
4193 .clone()
4194 .and_then(|(location, code_actions)| {
4195 let snapshot = location.buffer.read(cx).snapshot();
4196 let point_range = location.range.to_point(&snapshot);
4197 let point_range = point_range.start.row..=point_range.end.row;
4198 if point_range.contains(&buffer_row) {
4199 Some((location, code_actions))
4200 } else {
4201 None
4202 }
4203 })
4204 .unzip();
4205 let buffer_id = buffer.read(cx).remote_id();
4206 let tasks = editor
4207 .tasks
4208 .get(&(buffer_id, buffer_row))
4209 .map(|t| Arc::new(t.to_owned()));
4210 if tasks.is_none() && code_actions.is_none() {
4211 return None;
4212 }
4213
4214 editor.completion_tasks.clear();
4215 editor.discard_inline_completion(false, cx);
4216 let task_context =
4217 tasks
4218 .as_ref()
4219 .zip(editor.project.clone())
4220 .map(|(tasks, project)| {
4221 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4222 });
4223
4224 Some(cx.spawn_in(window, |editor, mut cx| async move {
4225 let task_context = match task_context {
4226 Some(task_context) => task_context.await,
4227 None => None,
4228 };
4229 let resolved_tasks =
4230 tasks.zip(task_context).map(|(tasks, task_context)| {
4231 Rc::new(ResolvedTasks {
4232 templates: tasks.resolve(&task_context).collect(),
4233 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4234 multibuffer_point.row,
4235 tasks.column,
4236 )),
4237 })
4238 });
4239 let spawn_straight_away = resolved_tasks
4240 .as_ref()
4241 .map_or(false, |tasks| tasks.templates.len() == 1)
4242 && code_actions
4243 .as_ref()
4244 .map_or(true, |actions| actions.is_empty());
4245 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4246 *editor.context_menu.borrow_mut() =
4247 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4248 buffer,
4249 actions: CodeActionContents {
4250 tasks: resolved_tasks,
4251 actions: code_actions,
4252 },
4253 selected_item: Default::default(),
4254 scroll_handle: UniformListScrollHandle::default(),
4255 deployed_from_indicator,
4256 }));
4257 if spawn_straight_away {
4258 if let Some(task) = editor.confirm_code_action(
4259 &ConfirmCodeAction { item_ix: Some(0) },
4260 window,
4261 cx,
4262 ) {
4263 cx.notify();
4264 return task;
4265 }
4266 }
4267 cx.notify();
4268 Task::ready(Ok(()))
4269 }) {
4270 task.await
4271 } else {
4272 Ok(())
4273 }
4274 }))
4275 } else {
4276 Some(Task::ready(Ok(())))
4277 }
4278 })?;
4279 if let Some(task) = spawned_test_task {
4280 task.await?;
4281 }
4282
4283 Ok::<_, anyhow::Error>(())
4284 })
4285 .detach_and_log_err(cx);
4286 }
4287
4288 pub fn confirm_code_action(
4289 &mut self,
4290 action: &ConfirmCodeAction,
4291 window: &mut Window,
4292 cx: &mut Context<Self>,
4293 ) -> Option<Task<Result<()>>> {
4294 let actions_menu =
4295 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4296 menu
4297 } else {
4298 return None;
4299 };
4300 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4301 let action = actions_menu.actions.get(action_ix)?;
4302 let title = action.label();
4303 let buffer = actions_menu.buffer;
4304 let workspace = self.workspace()?;
4305
4306 match action {
4307 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4308 workspace.update(cx, |workspace, cx| {
4309 workspace::tasks::schedule_resolved_task(
4310 workspace,
4311 task_source_kind,
4312 resolved_task,
4313 false,
4314 cx,
4315 );
4316
4317 Some(Task::ready(Ok(())))
4318 })
4319 }
4320 CodeActionsItem::CodeAction {
4321 excerpt_id,
4322 action,
4323 provider,
4324 } => {
4325 let apply_code_action =
4326 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4327 let workspace = workspace.downgrade();
4328 Some(cx.spawn_in(window, |editor, cx| async move {
4329 let project_transaction = apply_code_action.await?;
4330 Self::open_project_transaction(
4331 &editor,
4332 workspace,
4333 project_transaction,
4334 title,
4335 cx,
4336 )
4337 .await
4338 }))
4339 }
4340 }
4341 }
4342
4343 pub async fn open_project_transaction(
4344 this: &WeakEntity<Editor>,
4345 workspace: WeakEntity<Workspace>,
4346 transaction: ProjectTransaction,
4347 title: String,
4348 mut cx: AsyncWindowContext,
4349 ) -> Result<()> {
4350 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4351 cx.update(|_, cx| {
4352 entries.sort_unstable_by_key(|(buffer, _)| {
4353 buffer.read(cx).file().map(|f| f.path().clone())
4354 });
4355 })?;
4356
4357 // If the project transaction's edits are all contained within this editor, then
4358 // avoid opening a new editor to display them.
4359
4360 if let Some((buffer, transaction)) = entries.first() {
4361 if entries.len() == 1 {
4362 let excerpt = this.update(&mut cx, |editor, cx| {
4363 editor
4364 .buffer()
4365 .read(cx)
4366 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4367 })?;
4368 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4369 if excerpted_buffer == *buffer {
4370 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4371 let excerpt_range = excerpt_range.to_offset(buffer);
4372 buffer
4373 .edited_ranges_for_transaction::<usize>(transaction)
4374 .all(|range| {
4375 excerpt_range.start <= range.start
4376 && excerpt_range.end >= range.end
4377 })
4378 })?;
4379
4380 if all_edits_within_excerpt {
4381 return Ok(());
4382 }
4383 }
4384 }
4385 }
4386 } else {
4387 return Ok(());
4388 }
4389
4390 let mut ranges_to_highlight = Vec::new();
4391 let excerpt_buffer = cx.new(|cx| {
4392 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4393 for (buffer_handle, transaction) in &entries {
4394 let buffer = buffer_handle.read(cx);
4395 ranges_to_highlight.extend(
4396 multibuffer.push_excerpts_with_context_lines(
4397 buffer_handle.clone(),
4398 buffer
4399 .edited_ranges_for_transaction::<usize>(transaction)
4400 .collect(),
4401 DEFAULT_MULTIBUFFER_CONTEXT,
4402 cx,
4403 ),
4404 );
4405 }
4406 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4407 multibuffer
4408 })?;
4409
4410 workspace.update_in(&mut cx, |workspace, window, cx| {
4411 let project = workspace.project().clone();
4412 let editor = cx
4413 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4414 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4415 editor.update(cx, |editor, cx| {
4416 editor.highlight_background::<Self>(
4417 &ranges_to_highlight,
4418 |theme| theme.editor_highlighted_line_background,
4419 cx,
4420 );
4421 });
4422 })?;
4423
4424 Ok(())
4425 }
4426
4427 pub fn clear_code_action_providers(&mut self) {
4428 self.code_action_providers.clear();
4429 self.available_code_actions.take();
4430 }
4431
4432 pub fn add_code_action_provider(
4433 &mut self,
4434 provider: Rc<dyn CodeActionProvider>,
4435 window: &mut Window,
4436 cx: &mut Context<Self>,
4437 ) {
4438 if self
4439 .code_action_providers
4440 .iter()
4441 .any(|existing_provider| existing_provider.id() == provider.id())
4442 {
4443 return;
4444 }
4445
4446 self.code_action_providers.push(provider);
4447 self.refresh_code_actions(window, cx);
4448 }
4449
4450 pub fn remove_code_action_provider(
4451 &mut self,
4452 id: Arc<str>,
4453 window: &mut Window,
4454 cx: &mut Context<Self>,
4455 ) {
4456 self.code_action_providers
4457 .retain(|provider| provider.id() != id);
4458 self.refresh_code_actions(window, cx);
4459 }
4460
4461 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4462 let buffer = self.buffer.read(cx);
4463 let newest_selection = self.selections.newest_anchor().clone();
4464 if newest_selection.head().diff_base_anchor.is_some() {
4465 return None;
4466 }
4467 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4468 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4469 if start_buffer != end_buffer {
4470 return None;
4471 }
4472
4473 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4474 cx.background_executor()
4475 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4476 .await;
4477
4478 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4479 let providers = this.code_action_providers.clone();
4480 let tasks = this
4481 .code_action_providers
4482 .iter()
4483 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4484 .collect::<Vec<_>>();
4485 (providers, tasks)
4486 })?;
4487
4488 let mut actions = Vec::new();
4489 for (provider, provider_actions) in
4490 providers.into_iter().zip(future::join_all(tasks).await)
4491 {
4492 if let Some(provider_actions) = provider_actions.log_err() {
4493 actions.extend(provider_actions.into_iter().map(|action| {
4494 AvailableCodeAction {
4495 excerpt_id: newest_selection.start.excerpt_id,
4496 action,
4497 provider: provider.clone(),
4498 }
4499 }));
4500 }
4501 }
4502
4503 this.update(&mut cx, |this, cx| {
4504 this.available_code_actions = if actions.is_empty() {
4505 None
4506 } else {
4507 Some((
4508 Location {
4509 buffer: start_buffer,
4510 range: start..end,
4511 },
4512 actions.into(),
4513 ))
4514 };
4515 cx.notify();
4516 })
4517 }));
4518 None
4519 }
4520
4521 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4522 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4523 self.show_git_blame_inline = false;
4524
4525 self.show_git_blame_inline_delay_task =
4526 Some(cx.spawn_in(window, |this, mut cx| async move {
4527 cx.background_executor().timer(delay).await;
4528
4529 this.update(&mut cx, |this, cx| {
4530 this.show_git_blame_inline = true;
4531 cx.notify();
4532 })
4533 .log_err();
4534 }));
4535 }
4536 }
4537
4538 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4539 if self.pending_rename.is_some() {
4540 return None;
4541 }
4542
4543 let provider = self.semantics_provider.clone()?;
4544 let buffer = self.buffer.read(cx);
4545 let newest_selection = self.selections.newest_anchor().clone();
4546 let cursor_position = newest_selection.head();
4547 let (cursor_buffer, cursor_buffer_position) =
4548 buffer.text_anchor_for_position(cursor_position, cx)?;
4549 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4550 if cursor_buffer != tail_buffer {
4551 return None;
4552 }
4553 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4554 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4555 cx.background_executor()
4556 .timer(Duration::from_millis(debounce))
4557 .await;
4558
4559 let highlights = if let Some(highlights) = cx
4560 .update(|cx| {
4561 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4562 })
4563 .ok()
4564 .flatten()
4565 {
4566 highlights.await.log_err()
4567 } else {
4568 None
4569 };
4570
4571 if let Some(highlights) = highlights {
4572 this.update(&mut cx, |this, cx| {
4573 if this.pending_rename.is_some() {
4574 return;
4575 }
4576
4577 let buffer_id = cursor_position.buffer_id;
4578 let buffer = this.buffer.read(cx);
4579 if !buffer
4580 .text_anchor_for_position(cursor_position, cx)
4581 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4582 {
4583 return;
4584 }
4585
4586 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4587 let mut write_ranges = Vec::new();
4588 let mut read_ranges = Vec::new();
4589 for highlight in highlights {
4590 for (excerpt_id, excerpt_range) in
4591 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4592 {
4593 let start = highlight
4594 .range
4595 .start
4596 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4597 let end = highlight
4598 .range
4599 .end
4600 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4601 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4602 continue;
4603 }
4604
4605 let range = Anchor {
4606 buffer_id,
4607 excerpt_id,
4608 text_anchor: start,
4609 diff_base_anchor: None,
4610 }..Anchor {
4611 buffer_id,
4612 excerpt_id,
4613 text_anchor: end,
4614 diff_base_anchor: None,
4615 };
4616 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4617 write_ranges.push(range);
4618 } else {
4619 read_ranges.push(range);
4620 }
4621 }
4622 }
4623
4624 this.highlight_background::<DocumentHighlightRead>(
4625 &read_ranges,
4626 |theme| theme.editor_document_highlight_read_background,
4627 cx,
4628 );
4629 this.highlight_background::<DocumentHighlightWrite>(
4630 &write_ranges,
4631 |theme| theme.editor_document_highlight_write_background,
4632 cx,
4633 );
4634 cx.notify();
4635 })
4636 .log_err();
4637 }
4638 }));
4639 None
4640 }
4641
4642 pub fn refresh_inline_completion(
4643 &mut self,
4644 debounce: bool,
4645 user_requested: bool,
4646 window: &mut Window,
4647 cx: &mut Context<Self>,
4648 ) -> Option<()> {
4649 let provider = self.inline_completion_provider()?;
4650 let cursor = self.selections.newest_anchor().head();
4651 let (buffer, cursor_buffer_position) =
4652 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4653
4654 if !user_requested
4655 && (!self.enable_inline_completions
4656 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4657 || !self.is_focused(window)
4658 || buffer.read(cx).is_empty())
4659 {
4660 self.discard_inline_completion(false, cx);
4661 return None;
4662 }
4663
4664 self.update_visible_inline_completion(window, cx);
4665 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4666 Some(())
4667 }
4668
4669 fn cycle_inline_completion(
4670 &mut self,
4671 direction: Direction,
4672 window: &mut Window,
4673 cx: &mut Context<Self>,
4674 ) -> Option<()> {
4675 let provider = self.inline_completion_provider()?;
4676 let cursor = self.selections.newest_anchor().head();
4677 let (buffer, cursor_buffer_position) =
4678 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4679 if !self.enable_inline_completions
4680 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4681 {
4682 return None;
4683 }
4684
4685 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4686 self.update_visible_inline_completion(window, cx);
4687
4688 Some(())
4689 }
4690
4691 pub fn show_inline_completion(
4692 &mut self,
4693 _: &ShowInlineCompletion,
4694 window: &mut Window,
4695 cx: &mut Context<Self>,
4696 ) {
4697 if !self.has_active_inline_completion() {
4698 self.refresh_inline_completion(false, true, window, cx);
4699 return;
4700 }
4701
4702 self.update_visible_inline_completion(window, cx);
4703 }
4704
4705 pub fn display_cursor_names(
4706 &mut self,
4707 _: &DisplayCursorNames,
4708 window: &mut Window,
4709 cx: &mut Context<Self>,
4710 ) {
4711 self.show_cursor_names(window, cx);
4712 }
4713
4714 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4715 self.show_cursor_names = true;
4716 cx.notify();
4717 cx.spawn_in(window, |this, mut cx| async move {
4718 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4719 this.update(&mut cx, |this, cx| {
4720 this.show_cursor_names = false;
4721 cx.notify()
4722 })
4723 .ok()
4724 })
4725 .detach();
4726 }
4727
4728 pub fn next_inline_completion(
4729 &mut self,
4730 _: &NextInlineCompletion,
4731 window: &mut Window,
4732 cx: &mut Context<Self>,
4733 ) {
4734 if self.has_active_inline_completion() {
4735 self.cycle_inline_completion(Direction::Next, window, cx);
4736 } else {
4737 let is_copilot_disabled = self
4738 .refresh_inline_completion(false, true, window, cx)
4739 .is_none();
4740 if is_copilot_disabled {
4741 cx.propagate();
4742 }
4743 }
4744 }
4745
4746 pub fn previous_inline_completion(
4747 &mut self,
4748 _: &PreviousInlineCompletion,
4749 window: &mut Window,
4750 cx: &mut Context<Self>,
4751 ) {
4752 if self.has_active_inline_completion() {
4753 self.cycle_inline_completion(Direction::Prev, window, cx);
4754 } else {
4755 let is_copilot_disabled = self
4756 .refresh_inline_completion(false, true, window, cx)
4757 .is_none();
4758 if is_copilot_disabled {
4759 cx.propagate();
4760 }
4761 }
4762 }
4763
4764 pub fn accept_inline_completion(
4765 &mut self,
4766 _: &AcceptInlineCompletion,
4767 window: &mut Window,
4768 cx: &mut Context<Self>,
4769 ) {
4770 let buffer = self.buffer.read(cx);
4771 let snapshot = buffer.snapshot(cx);
4772 let selection = self.selections.newest_adjusted(cx);
4773 let cursor = selection.head();
4774 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
4775 let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
4776 if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
4777 {
4778 if cursor.column < suggested_indent.len
4779 && cursor.column <= current_indent.len
4780 && current_indent.len <= suggested_indent.len
4781 {
4782 self.tab(&Default::default(), window, cx);
4783 return;
4784 }
4785 }
4786
4787 if self.show_inline_completions_in_menu(cx) {
4788 self.hide_context_menu(window, cx);
4789 }
4790
4791 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4792 return;
4793 };
4794
4795 self.report_inline_completion_event(true, cx);
4796
4797 match &active_inline_completion.completion {
4798 InlineCompletion::Move { target, .. } => {
4799 let target = *target;
4800 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
4801 selections.select_anchor_ranges([target..target]);
4802 });
4803 }
4804 InlineCompletion::Edit { edits, .. } => {
4805 if let Some(provider) = self.inline_completion_provider() {
4806 provider.accept(cx);
4807 }
4808
4809 let snapshot = self.buffer.read(cx).snapshot(cx);
4810 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4811
4812 self.buffer.update(cx, |buffer, cx| {
4813 buffer.edit(edits.iter().cloned(), None, cx)
4814 });
4815
4816 self.change_selections(None, window, cx, |s| {
4817 s.select_anchor_ranges([last_edit_end..last_edit_end])
4818 });
4819
4820 self.update_visible_inline_completion(window, cx);
4821 if self.active_inline_completion.is_none() {
4822 self.refresh_inline_completion(true, true, window, cx);
4823 }
4824
4825 cx.notify();
4826 }
4827 }
4828 }
4829
4830 pub fn accept_partial_inline_completion(
4831 &mut self,
4832 _: &AcceptPartialInlineCompletion,
4833 window: &mut Window,
4834 cx: &mut Context<Self>,
4835 ) {
4836 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4837 return;
4838 };
4839 if self.selections.count() != 1 {
4840 return;
4841 }
4842
4843 self.report_inline_completion_event(true, cx);
4844
4845 match &active_inline_completion.completion {
4846 InlineCompletion::Move { target, .. } => {
4847 let target = *target;
4848 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
4849 selections.select_anchor_ranges([target..target]);
4850 });
4851 }
4852 InlineCompletion::Edit { edits, .. } => {
4853 // Find an insertion that starts at the cursor position.
4854 let snapshot = self.buffer.read(cx).snapshot(cx);
4855 let cursor_offset = self.selections.newest::<usize>(cx).head();
4856 let insertion = edits.iter().find_map(|(range, text)| {
4857 let range = range.to_offset(&snapshot);
4858 if range.is_empty() && range.start == cursor_offset {
4859 Some(text)
4860 } else {
4861 None
4862 }
4863 });
4864
4865 if let Some(text) = insertion {
4866 let mut partial_completion = text
4867 .chars()
4868 .by_ref()
4869 .take_while(|c| c.is_alphabetic())
4870 .collect::<String>();
4871 if partial_completion.is_empty() {
4872 partial_completion = text
4873 .chars()
4874 .by_ref()
4875 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4876 .collect::<String>();
4877 }
4878
4879 cx.emit(EditorEvent::InputHandled {
4880 utf16_range_to_replace: None,
4881 text: partial_completion.clone().into(),
4882 });
4883
4884 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
4885
4886 self.refresh_inline_completion(true, true, window, cx);
4887 cx.notify();
4888 } else {
4889 self.accept_inline_completion(&Default::default(), window, cx);
4890 }
4891 }
4892 }
4893 }
4894
4895 fn discard_inline_completion(
4896 &mut self,
4897 should_report_inline_completion_event: bool,
4898 cx: &mut Context<Self>,
4899 ) -> bool {
4900 if should_report_inline_completion_event {
4901 self.report_inline_completion_event(false, cx);
4902 }
4903
4904 if let Some(provider) = self.inline_completion_provider() {
4905 provider.discard(cx);
4906 }
4907
4908 self.take_active_inline_completion(cx)
4909 }
4910
4911 fn report_inline_completion_event(&self, accepted: bool, cx: &App) {
4912 let Some(provider) = self.inline_completion_provider() else {
4913 return;
4914 };
4915
4916 let Some((_, buffer, _)) = self
4917 .buffer
4918 .read(cx)
4919 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4920 else {
4921 return;
4922 };
4923
4924 let extension = buffer
4925 .read(cx)
4926 .file()
4927 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4928
4929 let event_type = match accepted {
4930 true => "Inline Completion Accepted",
4931 false => "Inline Completion Discarded",
4932 };
4933 telemetry::event!(
4934 event_type,
4935 provider = provider.name(),
4936 suggestion_accepted = accepted,
4937 file_extension = extension,
4938 );
4939 }
4940
4941 pub fn has_active_inline_completion(&self) -> bool {
4942 self.active_inline_completion.is_some()
4943 }
4944
4945 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
4946 let Some(active_inline_completion) = self.active_inline_completion.take() else {
4947 return false;
4948 };
4949
4950 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
4951 self.clear_highlights::<InlineCompletionHighlight>(cx);
4952 self.stale_inline_completion_in_menu = Some(active_inline_completion);
4953 true
4954 }
4955
4956 fn update_inline_completion_preview(
4957 &mut self,
4958 modifiers: &Modifiers,
4959 window: &mut Window,
4960 cx: &mut Context<Self>,
4961 ) {
4962 // Moves jump directly with a preview step
4963
4964 if self
4965 .active_inline_completion
4966 .as_ref()
4967 .map_or(true, |c| c.is_move())
4968 {
4969 cx.notify();
4970 return;
4971 }
4972
4973 if !self.show_inline_completions_in_menu(cx) {
4974 return;
4975 }
4976
4977 let mut menu_borrow = self.context_menu.borrow_mut();
4978
4979 let Some(CodeContextMenu::Completions(completions_menu)) = menu_borrow.as_mut() else {
4980 return;
4981 };
4982
4983 if completions_menu.is_empty()
4984 || completions_menu.previewing_inline_completion == modifiers.alt
4985 {
4986 return;
4987 }
4988
4989 completions_menu.set_previewing_inline_completion(modifiers.alt);
4990 drop(menu_borrow);
4991 self.update_visible_inline_completion(window, cx);
4992 }
4993
4994 fn update_visible_inline_completion(
4995 &mut self,
4996 _window: &mut Window,
4997 cx: &mut Context<Self>,
4998 ) -> Option<()> {
4999 let selection = self.selections.newest_anchor();
5000 let cursor = selection.head();
5001 let multibuffer = self.buffer.read(cx).snapshot(cx);
5002 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5003 let excerpt_id = cursor.excerpt_id;
5004
5005 let show_in_menu = self.show_inline_completions_in_menu(cx);
5006 let completions_menu_has_precedence = !show_in_menu
5007 && (self.context_menu.borrow().is_some()
5008 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5009 if completions_menu_has_precedence
5010 || !offset_selection.is_empty()
5011 || !self.enable_inline_completions
5012 || self
5013 .active_inline_completion
5014 .as_ref()
5015 .map_or(false, |completion| {
5016 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5017 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5018 !invalidation_range.contains(&offset_selection.head())
5019 })
5020 {
5021 self.discard_inline_completion(false, cx);
5022 return None;
5023 }
5024
5025 self.take_active_inline_completion(cx);
5026 let provider = self.inline_completion_provider()?;
5027
5028 let (buffer, cursor_buffer_position) =
5029 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5030
5031 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5032 let edits = inline_completion
5033 .edits
5034 .into_iter()
5035 .flat_map(|(range, new_text)| {
5036 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5037 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5038 Some((start..end, new_text))
5039 })
5040 .collect::<Vec<_>>();
5041 if edits.is_empty() {
5042 return None;
5043 }
5044
5045 let first_edit_start = edits.first().unwrap().0.start;
5046 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5047 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5048
5049 let last_edit_end = edits.last().unwrap().0.end;
5050 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5051 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5052
5053 let cursor_row = cursor.to_point(&multibuffer).row;
5054
5055 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5056
5057 let mut inlay_ids = Vec::new();
5058 let invalidation_row_range;
5059 let move_invalidation_row_range = if cursor_row < edit_start_row {
5060 Some(cursor_row..edit_end_row)
5061 } else if cursor_row > edit_end_row {
5062 Some(edit_start_row..cursor_row)
5063 } else {
5064 None
5065 };
5066 let completion = if let Some(move_invalidation_row_range) = move_invalidation_row_range {
5067 invalidation_row_range = move_invalidation_row_range;
5068 let target = first_edit_start;
5069 let target_point = text::ToPoint::to_point(&target.text_anchor, &snapshot);
5070 // TODO: Base this off of TreeSitter or word boundaries?
5071 let target_excerpt_begin = snapshot.anchor_before(snapshot.clip_point(
5072 Point::new(target_point.row, target_point.column.saturating_sub(20)),
5073 Bias::Left,
5074 ));
5075 let target_excerpt_end = snapshot.anchor_after(snapshot.clip_point(
5076 Point::new(target_point.row, target_point.column + 20),
5077 Bias::Right,
5078 ));
5079 let range_around_target = target_excerpt_begin..target_excerpt_end;
5080 InlineCompletion::Move {
5081 target,
5082 range_around_target,
5083 snapshot,
5084 }
5085 } else {
5086 if !show_in_menu || !self.has_active_completions_menu() {
5087 if edits
5088 .iter()
5089 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5090 {
5091 let mut inlays = Vec::new();
5092 for (range, new_text) in &edits {
5093 let inlay = Inlay::inline_completion(
5094 post_inc(&mut self.next_inlay_id),
5095 range.start,
5096 new_text.as_str(),
5097 );
5098 inlay_ids.push(inlay.id);
5099 inlays.push(inlay);
5100 }
5101
5102 self.splice_inlays(&[], inlays, cx);
5103 } else {
5104 let background_color = cx.theme().status().deleted_background;
5105 self.highlight_text::<InlineCompletionHighlight>(
5106 edits.iter().map(|(range, _)| range.clone()).collect(),
5107 HighlightStyle {
5108 background_color: Some(background_color),
5109 ..Default::default()
5110 },
5111 cx,
5112 );
5113 }
5114 }
5115
5116 invalidation_row_range = edit_start_row..edit_end_row;
5117
5118 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5119 if provider.show_tab_accept_marker() {
5120 EditDisplayMode::TabAccept
5121 } else {
5122 EditDisplayMode::Inline
5123 }
5124 } else {
5125 EditDisplayMode::DiffPopover
5126 };
5127
5128 InlineCompletion::Edit {
5129 edits,
5130 edit_preview: inline_completion.edit_preview,
5131 display_mode,
5132 snapshot,
5133 }
5134 };
5135
5136 let invalidation_range = multibuffer
5137 .anchor_before(Point::new(invalidation_row_range.start, 0))
5138 ..multibuffer.anchor_after(Point::new(
5139 invalidation_row_range.end,
5140 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5141 ));
5142
5143 self.stale_inline_completion_in_menu = None;
5144 self.active_inline_completion = Some(InlineCompletionState {
5145 inlay_ids,
5146 completion,
5147 invalidation_range,
5148 });
5149
5150 cx.notify();
5151
5152 Some(())
5153 }
5154
5155 pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5156 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5157 }
5158
5159 fn show_inline_completions_in_menu(&self, cx: &App) -> bool {
5160 let by_provider = matches!(
5161 self.menu_inline_completions_policy,
5162 MenuInlineCompletionsPolicy::ByProvider
5163 );
5164
5165 by_provider
5166 && EditorSettings::get_global(cx).show_inline_completions_in_menu
5167 && self
5168 .inline_completion_provider()
5169 .map_or(false, |provider| provider.show_completions_in_menu())
5170 }
5171
5172 fn render_code_actions_indicator(
5173 &self,
5174 _style: &EditorStyle,
5175 row: DisplayRow,
5176 is_active: bool,
5177 cx: &mut Context<Self>,
5178 ) -> Option<IconButton> {
5179 if self.available_code_actions.is_some() {
5180 Some(
5181 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5182 .shape(ui::IconButtonShape::Square)
5183 .icon_size(IconSize::XSmall)
5184 .icon_color(Color::Muted)
5185 .toggle_state(is_active)
5186 .tooltip({
5187 let focus_handle = self.focus_handle.clone();
5188 move |window, cx| {
5189 Tooltip::for_action_in(
5190 "Toggle Code Actions",
5191 &ToggleCodeActions {
5192 deployed_from_indicator: None,
5193 },
5194 &focus_handle,
5195 window,
5196 cx,
5197 )
5198 }
5199 })
5200 .on_click(cx.listener(move |editor, _e, window, cx| {
5201 window.focus(&editor.focus_handle(cx));
5202 editor.toggle_code_actions(
5203 &ToggleCodeActions {
5204 deployed_from_indicator: Some(row),
5205 },
5206 window,
5207 cx,
5208 );
5209 })),
5210 )
5211 } else {
5212 None
5213 }
5214 }
5215
5216 fn clear_tasks(&mut self) {
5217 self.tasks.clear()
5218 }
5219
5220 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5221 if self.tasks.insert(key, value).is_some() {
5222 // This case should hopefully be rare, but just in case...
5223 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5224 }
5225 }
5226
5227 fn build_tasks_context(
5228 project: &Entity<Project>,
5229 buffer: &Entity<Buffer>,
5230 buffer_row: u32,
5231 tasks: &Arc<RunnableTasks>,
5232 cx: &mut Context<Self>,
5233 ) -> Task<Option<task::TaskContext>> {
5234 let position = Point::new(buffer_row, tasks.column);
5235 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5236 let location = Location {
5237 buffer: buffer.clone(),
5238 range: range_start..range_start,
5239 };
5240 // Fill in the environmental variables from the tree-sitter captures
5241 let mut captured_task_variables = TaskVariables::default();
5242 for (capture_name, value) in tasks.extra_variables.clone() {
5243 captured_task_variables.insert(
5244 task::VariableName::Custom(capture_name.into()),
5245 value.clone(),
5246 );
5247 }
5248 project.update(cx, |project, cx| {
5249 project.task_store().update(cx, |task_store, cx| {
5250 task_store.task_context_for_location(captured_task_variables, location, cx)
5251 })
5252 })
5253 }
5254
5255 pub fn spawn_nearest_task(
5256 &mut self,
5257 action: &SpawnNearestTask,
5258 window: &mut Window,
5259 cx: &mut Context<Self>,
5260 ) {
5261 let Some((workspace, _)) = self.workspace.clone() else {
5262 return;
5263 };
5264 let Some(project) = self.project.clone() else {
5265 return;
5266 };
5267
5268 // Try to find a closest, enclosing node using tree-sitter that has a
5269 // task
5270 let Some((buffer, buffer_row, tasks)) = self
5271 .find_enclosing_node_task(cx)
5272 // Or find the task that's closest in row-distance.
5273 .or_else(|| self.find_closest_task(cx))
5274 else {
5275 return;
5276 };
5277
5278 let reveal_strategy = action.reveal;
5279 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5280 cx.spawn_in(window, |_, mut cx| async move {
5281 let context = task_context.await?;
5282 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5283
5284 let resolved = resolved_task.resolved.as_mut()?;
5285 resolved.reveal = reveal_strategy;
5286
5287 workspace
5288 .update(&mut cx, |workspace, cx| {
5289 workspace::tasks::schedule_resolved_task(
5290 workspace,
5291 task_source_kind,
5292 resolved_task,
5293 false,
5294 cx,
5295 );
5296 })
5297 .ok()
5298 })
5299 .detach();
5300 }
5301
5302 fn find_closest_task(
5303 &mut self,
5304 cx: &mut Context<Self>,
5305 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5306 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5307
5308 let ((buffer_id, row), tasks) = self
5309 .tasks
5310 .iter()
5311 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5312
5313 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5314 let tasks = Arc::new(tasks.to_owned());
5315 Some((buffer, *row, tasks))
5316 }
5317
5318 fn find_enclosing_node_task(
5319 &mut self,
5320 cx: &mut Context<Self>,
5321 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5322 let snapshot = self.buffer.read(cx).snapshot(cx);
5323 let offset = self.selections.newest::<usize>(cx).head();
5324 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5325 let buffer_id = excerpt.buffer().remote_id();
5326
5327 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5328 let mut cursor = layer.node().walk();
5329
5330 while cursor.goto_first_child_for_byte(offset).is_some() {
5331 if cursor.node().end_byte() == offset {
5332 cursor.goto_next_sibling();
5333 }
5334 }
5335
5336 // Ascend to the smallest ancestor that contains the range and has a task.
5337 loop {
5338 let node = cursor.node();
5339 let node_range = node.byte_range();
5340 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5341
5342 // Check if this node contains our offset
5343 if node_range.start <= offset && node_range.end >= offset {
5344 // If it contains offset, check for task
5345 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5346 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5347 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5348 }
5349 }
5350
5351 if !cursor.goto_parent() {
5352 break;
5353 }
5354 }
5355 None
5356 }
5357
5358 fn render_run_indicator(
5359 &self,
5360 _style: &EditorStyle,
5361 is_active: bool,
5362 row: DisplayRow,
5363 cx: &mut Context<Self>,
5364 ) -> IconButton {
5365 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5366 .shape(ui::IconButtonShape::Square)
5367 .icon_size(IconSize::XSmall)
5368 .icon_color(Color::Muted)
5369 .toggle_state(is_active)
5370 .on_click(cx.listener(move |editor, _e, window, cx| {
5371 window.focus(&editor.focus_handle(cx));
5372 editor.toggle_code_actions(
5373 &ToggleCodeActions {
5374 deployed_from_indicator: Some(row),
5375 },
5376 window,
5377 cx,
5378 );
5379 }))
5380 }
5381
5382 pub fn context_menu_visible(&self) -> bool {
5383 self.context_menu
5384 .borrow()
5385 .as_ref()
5386 .map_or(false, |menu| menu.visible())
5387 }
5388
5389 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5390 self.context_menu
5391 .borrow()
5392 .as_ref()
5393 .map(|menu| menu.origin())
5394 }
5395
5396 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5397 px(32.)
5398 }
5399
5400 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5401 if self.read_only(cx) {
5402 cx.theme().players().read_only()
5403 } else {
5404 self.style.as_ref().unwrap().local_player
5405 }
5406 }
5407
5408 fn render_edit_prediction_cursor_popover(
5409 &self,
5410 max_width: Pixels,
5411 cursor_point: Point,
5412 style: &EditorStyle,
5413 accept_keystroke: &gpui::Keystroke,
5414 window: &Window,
5415 cx: &mut Context<Editor>,
5416 ) -> Option<AnyElement> {
5417 let provider = self.inline_completion_provider.as_ref()?;
5418
5419 if provider.provider.needs_terms_acceptance(cx) {
5420 return Some(
5421 h_flex()
5422 .h(self.edit_prediction_cursor_popover_height())
5423 .flex_1()
5424 .px_2()
5425 .gap_3()
5426 .elevation_2(cx)
5427 .hover(|style| style.bg(cx.theme().colors().element_hover))
5428 .id("accept-terms")
5429 .cursor_pointer()
5430 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5431 .on_click(cx.listener(|this, _event, window, cx| {
5432 cx.stop_propagation();
5433 this.toggle_zed_predict_onboarding(window, cx)
5434 }))
5435 .child(
5436 h_flex()
5437 .w_full()
5438 .gap_2()
5439 .child(Icon::new(IconName::ZedPredict))
5440 .child(Label::new("Accept Terms of Service"))
5441 .child(div().w_full())
5442 .child(Icon::new(IconName::ArrowUpRight))
5443 .into_any_element(),
5444 )
5445 .into_any(),
5446 );
5447 }
5448
5449 let is_refreshing = provider.provider.is_refreshing(cx);
5450
5451 fn pending_completion_container() -> Div {
5452 h_flex().gap_3().child(Icon::new(IconName::ZedPredict))
5453 }
5454
5455 let completion = match &self.active_inline_completion {
5456 Some(completion) => self.render_edit_prediction_cursor_popover_preview(
5457 completion,
5458 cursor_point,
5459 style,
5460 cx,
5461 )?,
5462
5463 None if is_refreshing => match &self.stale_inline_completion_in_menu {
5464 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
5465 stale_completion,
5466 cursor_point,
5467 style,
5468 cx,
5469 )?,
5470
5471 None => {
5472 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
5473 }
5474 },
5475
5476 None => pending_completion_container().child(Label::new("No Prediction")),
5477 };
5478
5479 let buffer_font = theme::ThemeSettings::get_global(cx).buffer_font.clone();
5480 let completion = completion.font(buffer_font.clone());
5481
5482 let completion = if is_refreshing {
5483 completion
5484 .with_animation(
5485 "loading-completion",
5486 Animation::new(Duration::from_secs(2))
5487 .repeat()
5488 .with_easing(pulsating_between(0.4, 0.8)),
5489 |label, delta| label.opacity(delta),
5490 )
5491 .into_any_element()
5492 } else {
5493 completion.into_any_element()
5494 };
5495
5496 let has_completion = self.active_inline_completion.is_some();
5497
5498 Some(
5499 h_flex()
5500 .h(self.edit_prediction_cursor_popover_height())
5501 .max_w(max_width)
5502 .flex_1()
5503 .px_2()
5504 .gap_3()
5505 .elevation_2(cx)
5506 .child(completion)
5507 .child(div().w_full())
5508 .child(
5509 h_flex()
5510 .border_l_1()
5511 .border_color(cx.theme().colors().border_variant)
5512 .pl_2()
5513 .child(
5514 h_flex()
5515 .font(buffer_font.clone())
5516 .p_1()
5517 .rounded_sm()
5518 .children(ui::render_modifiers(
5519 &accept_keystroke.modifiers,
5520 PlatformStyle::platform(),
5521 if window.modifiers() == accept_keystroke.modifiers {
5522 Some(Color::Accent)
5523 } else {
5524 None
5525 },
5526 )),
5527 )
5528 .opacity(if has_completion { 1.0 } else { 0.1 })
5529 .child(
5530 if self
5531 .active_inline_completion
5532 .as_ref()
5533 .map_or(false, |c| c.is_move())
5534 {
5535 div()
5536 .child(ui::Key::new(&accept_keystroke.key, None))
5537 .font(buffer_font.clone())
5538 .into_any()
5539 } else {
5540 Label::new("Preview").color(Color::Muted).into_any_element()
5541 },
5542 ),
5543 )
5544 .into_any(),
5545 )
5546 }
5547
5548 fn render_edit_prediction_cursor_popover_preview(
5549 &self,
5550 completion: &InlineCompletionState,
5551 cursor_point: Point,
5552 style: &EditorStyle,
5553 cx: &mut Context<Editor>,
5554 ) -> Option<Div> {
5555 use text::ToPoint as _;
5556
5557 fn render_relative_row_jump(
5558 prefix: impl Into<String>,
5559 current_row: u32,
5560 target_row: u32,
5561 ) -> Div {
5562 let (row_diff, arrow) = if target_row < current_row {
5563 (current_row - target_row, IconName::ArrowUp)
5564 } else {
5565 (target_row - current_row, IconName::ArrowDown)
5566 };
5567
5568 h_flex()
5569 .child(
5570 Label::new(format!("{}{}", prefix.into(), row_diff))
5571 .color(Color::Muted)
5572 .size(LabelSize::Small),
5573 )
5574 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
5575 }
5576
5577 match &completion.completion {
5578 InlineCompletion::Edit {
5579 edits,
5580 edit_preview,
5581 snapshot,
5582 display_mode: _,
5583 } => {
5584 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
5585
5586 let highlighted_edits = crate::inline_completion_edit_text(
5587 &snapshot,
5588 &edits,
5589 edit_preview.as_ref()?,
5590 true,
5591 cx,
5592 );
5593
5594 let len_total = highlighted_edits.text.len();
5595 let first_line = &highlighted_edits.text
5596 [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
5597 let first_line_len = first_line.len();
5598
5599 let first_highlight_start = highlighted_edits
5600 .highlights
5601 .first()
5602 .map_or(0, |(range, _)| range.start);
5603 let drop_prefix_len = first_line
5604 .char_indices()
5605 .find(|(_, c)| !c.is_whitespace())
5606 .map_or(first_highlight_start, |(ix, _)| {
5607 ix.min(first_highlight_start)
5608 });
5609
5610 let preview_text = &first_line[drop_prefix_len..];
5611 let preview_len = preview_text.len();
5612 let highlights = highlighted_edits
5613 .highlights
5614 .into_iter()
5615 .take_until(|(range, _)| range.start > first_line_len)
5616 .map(|(range, style)| {
5617 (
5618 range.start - drop_prefix_len
5619 ..(range.end - drop_prefix_len).min(preview_len),
5620 style,
5621 )
5622 });
5623
5624 let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
5625 .with_highlights(&style.text, highlights);
5626
5627 let preview = h_flex()
5628 .gap_1()
5629 .child(styled_text)
5630 .when(len_total > first_line_len, |parent| parent.child("…"));
5631
5632 let left = if first_edit_row != cursor_point.row {
5633 render_relative_row_jump("", cursor_point.row, first_edit_row)
5634 .into_any_element()
5635 } else {
5636 Icon::new(IconName::ZedPredict).into_any_element()
5637 };
5638
5639 Some(h_flex().gap_3().child(left).child(preview))
5640 }
5641
5642 InlineCompletion::Move {
5643 target,
5644 range_around_target,
5645 snapshot,
5646 } => {
5647 let mut highlighted_text = snapshot.highlighted_text_for_range(
5648 range_around_target.clone(),
5649 None,
5650 &style.syntax,
5651 );
5652 let cursor_color = self.current_user_player_color(cx).cursor;
5653 let target_ix =
5654 text::ToOffset::to_offset(&target.text_anchor, &snapshot).saturating_sub(
5655 text::ToOffset::to_offset(&range_around_target.start, &snapshot),
5656 );
5657 highlighted_text.highlights = gpui::combine_highlights(
5658 highlighted_text.highlights,
5659 iter::once((
5660 target_ix..target_ix + 1,
5661 HighlightStyle {
5662 background_color: Some(cursor_color),
5663 ..Default::default()
5664 },
5665 )),
5666 )
5667 .collect::<Vec<_>>();
5668
5669 let start_point = range_around_target.start.to_point(&snapshot);
5670 let end_point = range_around_target.end.to_point(&snapshot);
5671 let ellipsis_before = start_point.column > 0;
5672 let ellipsis_after = end_point.column < snapshot.line_len(end_point.row);
5673
5674 Some(
5675 h_flex()
5676 .gap_3()
5677 .child(render_relative_row_jump(
5678 "Jump ",
5679 cursor_point.row,
5680 target.text_anchor.to_point(&snapshot).row,
5681 ))
5682 .when(!highlighted_text.text.is_empty(), |parent| {
5683 parent.child(
5684 h_flex()
5685 .when(ellipsis_before, |parent| parent.child("…"))
5686 .child(highlighted_text.to_styled_text(&style.text))
5687 .when(ellipsis_after, |parent| parent.child("…")),
5688 )
5689 }),
5690 )
5691 }
5692 }
5693 }
5694
5695 fn render_context_menu(
5696 &self,
5697 style: &EditorStyle,
5698 max_height_in_lines: u32,
5699 y_flipped: bool,
5700 window: &mut Window,
5701 cx: &mut Context<Editor>,
5702 ) -> Option<AnyElement> {
5703 let menu = self.context_menu.borrow();
5704 let menu = menu.as_ref()?;
5705 if !menu.visible() {
5706 return None;
5707 };
5708 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
5709 }
5710
5711 fn render_context_menu_aside(
5712 &self,
5713 style: &EditorStyle,
5714 max_size: Size<Pixels>,
5715 cx: &mut Context<Editor>,
5716 ) -> Option<AnyElement> {
5717 self.context_menu.borrow().as_ref().and_then(|menu| {
5718 if menu.visible() {
5719 menu.render_aside(
5720 style,
5721 max_size,
5722 self.workspace.as_ref().map(|(w, _)| w.clone()),
5723 cx,
5724 )
5725 } else {
5726 None
5727 }
5728 })
5729 }
5730
5731 fn hide_context_menu(
5732 &mut self,
5733 window: &mut Window,
5734 cx: &mut Context<Self>,
5735 ) -> Option<CodeContextMenu> {
5736 cx.notify();
5737 self.completion_tasks.clear();
5738 let context_menu = self.context_menu.borrow_mut().take();
5739 self.stale_inline_completion_in_menu.take();
5740 if context_menu.is_some() {
5741 self.update_visible_inline_completion(window, cx);
5742 }
5743 context_menu
5744 }
5745
5746 fn show_snippet_choices(
5747 &mut self,
5748 choices: &Vec<String>,
5749 selection: Range<Anchor>,
5750 cx: &mut Context<Self>,
5751 ) {
5752 if selection.start.buffer_id.is_none() {
5753 return;
5754 }
5755 let buffer_id = selection.start.buffer_id.unwrap();
5756 let buffer = self.buffer().read(cx).buffer(buffer_id);
5757 let id = post_inc(&mut self.next_completion_id);
5758
5759 if let Some(buffer) = buffer {
5760 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5761 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5762 ));
5763 }
5764 }
5765
5766 pub fn insert_snippet(
5767 &mut self,
5768 insertion_ranges: &[Range<usize>],
5769 snippet: Snippet,
5770 window: &mut Window,
5771 cx: &mut Context<Self>,
5772 ) -> Result<()> {
5773 struct Tabstop<T> {
5774 is_end_tabstop: bool,
5775 ranges: Vec<Range<T>>,
5776 choices: Option<Vec<String>>,
5777 }
5778
5779 let tabstops = self.buffer.update(cx, |buffer, cx| {
5780 let snippet_text: Arc<str> = snippet.text.clone().into();
5781 buffer.edit(
5782 insertion_ranges
5783 .iter()
5784 .cloned()
5785 .map(|range| (range, snippet_text.clone())),
5786 Some(AutoindentMode::EachLine),
5787 cx,
5788 );
5789
5790 let snapshot = &*buffer.read(cx);
5791 let snippet = &snippet;
5792 snippet
5793 .tabstops
5794 .iter()
5795 .map(|tabstop| {
5796 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5797 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5798 });
5799 let mut tabstop_ranges = tabstop
5800 .ranges
5801 .iter()
5802 .flat_map(|tabstop_range| {
5803 let mut delta = 0_isize;
5804 insertion_ranges.iter().map(move |insertion_range| {
5805 let insertion_start = insertion_range.start as isize + delta;
5806 delta +=
5807 snippet.text.len() as isize - insertion_range.len() as isize;
5808
5809 let start = ((insertion_start + tabstop_range.start) as usize)
5810 .min(snapshot.len());
5811 let end = ((insertion_start + tabstop_range.end) as usize)
5812 .min(snapshot.len());
5813 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5814 })
5815 })
5816 .collect::<Vec<_>>();
5817 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5818
5819 Tabstop {
5820 is_end_tabstop,
5821 ranges: tabstop_ranges,
5822 choices: tabstop.choices.clone(),
5823 }
5824 })
5825 .collect::<Vec<_>>()
5826 });
5827 if let Some(tabstop) = tabstops.first() {
5828 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
5829 s.select_ranges(tabstop.ranges.iter().cloned());
5830 });
5831
5832 if let Some(choices) = &tabstop.choices {
5833 if let Some(selection) = tabstop.ranges.first() {
5834 self.show_snippet_choices(choices, selection.clone(), cx)
5835 }
5836 }
5837
5838 // If we're already at the last tabstop and it's at the end of the snippet,
5839 // we're done, we don't need to keep the state around.
5840 if !tabstop.is_end_tabstop {
5841 let choices = tabstops
5842 .iter()
5843 .map(|tabstop| tabstop.choices.clone())
5844 .collect();
5845
5846 let ranges = tabstops
5847 .into_iter()
5848 .map(|tabstop| tabstop.ranges)
5849 .collect::<Vec<_>>();
5850
5851 self.snippet_stack.push(SnippetState {
5852 active_index: 0,
5853 ranges,
5854 choices,
5855 });
5856 }
5857
5858 // Check whether the just-entered snippet ends with an auto-closable bracket.
5859 if self.autoclose_regions.is_empty() {
5860 let snapshot = self.buffer.read(cx).snapshot(cx);
5861 for selection in &mut self.selections.all::<Point>(cx) {
5862 let selection_head = selection.head();
5863 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5864 continue;
5865 };
5866
5867 let mut bracket_pair = None;
5868 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5869 let prev_chars = snapshot
5870 .reversed_chars_at(selection_head)
5871 .collect::<String>();
5872 for (pair, enabled) in scope.brackets() {
5873 if enabled
5874 && pair.close
5875 && prev_chars.starts_with(pair.start.as_str())
5876 && next_chars.starts_with(pair.end.as_str())
5877 {
5878 bracket_pair = Some(pair.clone());
5879 break;
5880 }
5881 }
5882 if let Some(pair) = bracket_pair {
5883 let start = snapshot.anchor_after(selection_head);
5884 let end = snapshot.anchor_after(selection_head);
5885 self.autoclose_regions.push(AutocloseRegion {
5886 selection_id: selection.id,
5887 range: start..end,
5888 pair,
5889 });
5890 }
5891 }
5892 }
5893 }
5894 Ok(())
5895 }
5896
5897 pub fn move_to_next_snippet_tabstop(
5898 &mut self,
5899 window: &mut Window,
5900 cx: &mut Context<Self>,
5901 ) -> bool {
5902 self.move_to_snippet_tabstop(Bias::Right, window, cx)
5903 }
5904
5905 pub fn move_to_prev_snippet_tabstop(
5906 &mut self,
5907 window: &mut Window,
5908 cx: &mut Context<Self>,
5909 ) -> bool {
5910 self.move_to_snippet_tabstop(Bias::Left, window, cx)
5911 }
5912
5913 pub fn move_to_snippet_tabstop(
5914 &mut self,
5915 bias: Bias,
5916 window: &mut Window,
5917 cx: &mut Context<Self>,
5918 ) -> bool {
5919 if let Some(mut snippet) = self.snippet_stack.pop() {
5920 match bias {
5921 Bias::Left => {
5922 if snippet.active_index > 0 {
5923 snippet.active_index -= 1;
5924 } else {
5925 self.snippet_stack.push(snippet);
5926 return false;
5927 }
5928 }
5929 Bias::Right => {
5930 if snippet.active_index + 1 < snippet.ranges.len() {
5931 snippet.active_index += 1;
5932 } else {
5933 self.snippet_stack.push(snippet);
5934 return false;
5935 }
5936 }
5937 }
5938 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5939 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
5940 s.select_anchor_ranges(current_ranges.iter().cloned())
5941 });
5942
5943 if let Some(choices) = &snippet.choices[snippet.active_index] {
5944 if let Some(selection) = current_ranges.first() {
5945 self.show_snippet_choices(&choices, selection.clone(), cx);
5946 }
5947 }
5948
5949 // If snippet state is not at the last tabstop, push it back on the stack
5950 if snippet.active_index + 1 < snippet.ranges.len() {
5951 self.snippet_stack.push(snippet);
5952 }
5953 return true;
5954 }
5955 }
5956
5957 false
5958 }
5959
5960 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5961 self.transact(window, cx, |this, window, cx| {
5962 this.select_all(&SelectAll, window, cx);
5963 this.insert("", window, cx);
5964 });
5965 }
5966
5967 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
5968 self.transact(window, cx, |this, window, cx| {
5969 this.select_autoclose_pair(window, cx);
5970 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5971 if !this.linked_edit_ranges.is_empty() {
5972 let selections = this.selections.all::<MultiBufferPoint>(cx);
5973 let snapshot = this.buffer.read(cx).snapshot(cx);
5974
5975 for selection in selections.iter() {
5976 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5977 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5978 if selection_start.buffer_id != selection_end.buffer_id {
5979 continue;
5980 }
5981 if let Some(ranges) =
5982 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5983 {
5984 for (buffer, entries) in ranges {
5985 linked_ranges.entry(buffer).or_default().extend(entries);
5986 }
5987 }
5988 }
5989 }
5990
5991 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5992 if !this.selections.line_mode {
5993 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5994 for selection in &mut selections {
5995 if selection.is_empty() {
5996 let old_head = selection.head();
5997 let mut new_head =
5998 movement::left(&display_map, old_head.to_display_point(&display_map))
5999 .to_point(&display_map);
6000 if let Some((buffer, line_buffer_range)) = display_map
6001 .buffer_snapshot
6002 .buffer_line_for_row(MultiBufferRow(old_head.row))
6003 {
6004 let indent_size =
6005 buffer.indent_size_for_line(line_buffer_range.start.row);
6006 let indent_len = match indent_size.kind {
6007 IndentKind::Space => {
6008 buffer.settings_at(line_buffer_range.start, cx).tab_size
6009 }
6010 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6011 };
6012 if old_head.column <= indent_size.len && old_head.column > 0 {
6013 let indent_len = indent_len.get();
6014 new_head = cmp::min(
6015 new_head,
6016 MultiBufferPoint::new(
6017 old_head.row,
6018 ((old_head.column - 1) / indent_len) * indent_len,
6019 ),
6020 );
6021 }
6022 }
6023
6024 selection.set_head(new_head, SelectionGoal::None);
6025 }
6026 }
6027 }
6028
6029 this.signature_help_state.set_backspace_pressed(true);
6030 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6031 s.select(selections)
6032 });
6033 this.insert("", window, cx);
6034 let empty_str: Arc<str> = Arc::from("");
6035 for (buffer, edits) in linked_ranges {
6036 let snapshot = buffer.read(cx).snapshot();
6037 use text::ToPoint as TP;
6038
6039 let edits = edits
6040 .into_iter()
6041 .map(|range| {
6042 let end_point = TP::to_point(&range.end, &snapshot);
6043 let mut start_point = TP::to_point(&range.start, &snapshot);
6044
6045 if end_point == start_point {
6046 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6047 .saturating_sub(1);
6048 start_point =
6049 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6050 };
6051
6052 (start_point..end_point, empty_str.clone())
6053 })
6054 .sorted_by_key(|(range, _)| range.start)
6055 .collect::<Vec<_>>();
6056 buffer.update(cx, |this, cx| {
6057 this.edit(edits, None, cx);
6058 })
6059 }
6060 this.refresh_inline_completion(true, false, window, cx);
6061 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6062 });
6063 }
6064
6065 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6066 self.transact(window, cx, |this, window, cx| {
6067 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6068 let line_mode = s.line_mode;
6069 s.move_with(|map, selection| {
6070 if selection.is_empty() && !line_mode {
6071 let cursor = movement::right(map, selection.head());
6072 selection.end = cursor;
6073 selection.reversed = true;
6074 selection.goal = SelectionGoal::None;
6075 }
6076 })
6077 });
6078 this.insert("", window, cx);
6079 this.refresh_inline_completion(true, false, window, cx);
6080 });
6081 }
6082
6083 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6084 if self.move_to_prev_snippet_tabstop(window, cx) {
6085 return;
6086 }
6087
6088 self.outdent(&Outdent, window, cx);
6089 }
6090
6091 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6092 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6093 return;
6094 }
6095
6096 let mut selections = self.selections.all_adjusted(cx);
6097 let buffer = self.buffer.read(cx);
6098 let snapshot = buffer.snapshot(cx);
6099 let rows_iter = selections.iter().map(|s| s.head().row);
6100 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6101
6102 let mut edits = Vec::new();
6103 let mut prev_edited_row = 0;
6104 let mut row_delta = 0;
6105 for selection in &mut selections {
6106 if selection.start.row != prev_edited_row {
6107 row_delta = 0;
6108 }
6109 prev_edited_row = selection.end.row;
6110
6111 // If the selection is non-empty, then increase the indentation of the selected lines.
6112 if !selection.is_empty() {
6113 row_delta =
6114 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6115 continue;
6116 }
6117
6118 // If the selection is empty and the cursor is in the leading whitespace before the
6119 // suggested indentation, then auto-indent the line.
6120 let cursor = selection.head();
6121 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6122 if let Some(suggested_indent) =
6123 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6124 {
6125 if cursor.column < suggested_indent.len
6126 && cursor.column <= current_indent.len
6127 && current_indent.len <= suggested_indent.len
6128 {
6129 selection.start = Point::new(cursor.row, suggested_indent.len);
6130 selection.end = selection.start;
6131 if row_delta == 0 {
6132 edits.extend(Buffer::edit_for_indent_size_adjustment(
6133 cursor.row,
6134 current_indent,
6135 suggested_indent,
6136 ));
6137 row_delta = suggested_indent.len - current_indent.len;
6138 }
6139 continue;
6140 }
6141 }
6142
6143 // Otherwise, insert a hard or soft tab.
6144 let settings = buffer.settings_at(cursor, cx);
6145 let tab_size = if settings.hard_tabs {
6146 IndentSize::tab()
6147 } else {
6148 let tab_size = settings.tab_size.get();
6149 let char_column = snapshot
6150 .text_for_range(Point::new(cursor.row, 0)..cursor)
6151 .flat_map(str::chars)
6152 .count()
6153 + row_delta as usize;
6154 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6155 IndentSize::spaces(chars_to_next_tab_stop)
6156 };
6157 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6158 selection.end = selection.start;
6159 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6160 row_delta += tab_size.len;
6161 }
6162
6163 self.transact(window, cx, |this, window, cx| {
6164 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6165 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6166 s.select(selections)
6167 });
6168 this.refresh_inline_completion(true, false, window, cx);
6169 });
6170 }
6171
6172 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6173 if self.read_only(cx) {
6174 return;
6175 }
6176 let mut selections = self.selections.all::<Point>(cx);
6177 let mut prev_edited_row = 0;
6178 let mut row_delta = 0;
6179 let mut edits = Vec::new();
6180 let buffer = self.buffer.read(cx);
6181 let snapshot = buffer.snapshot(cx);
6182 for selection in &mut selections {
6183 if selection.start.row != prev_edited_row {
6184 row_delta = 0;
6185 }
6186 prev_edited_row = selection.end.row;
6187
6188 row_delta =
6189 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6190 }
6191
6192 self.transact(window, cx, |this, window, cx| {
6193 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6194 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6195 s.select(selections)
6196 });
6197 });
6198 }
6199
6200 fn indent_selection(
6201 buffer: &MultiBuffer,
6202 snapshot: &MultiBufferSnapshot,
6203 selection: &mut Selection<Point>,
6204 edits: &mut Vec<(Range<Point>, String)>,
6205 delta_for_start_row: u32,
6206 cx: &App,
6207 ) -> u32 {
6208 let settings = buffer.settings_at(selection.start, cx);
6209 let tab_size = settings.tab_size.get();
6210 let indent_kind = if settings.hard_tabs {
6211 IndentKind::Tab
6212 } else {
6213 IndentKind::Space
6214 };
6215 let mut start_row = selection.start.row;
6216 let mut end_row = selection.end.row + 1;
6217
6218 // If a selection ends at the beginning of a line, don't indent
6219 // that last line.
6220 if selection.end.column == 0 && selection.end.row > selection.start.row {
6221 end_row -= 1;
6222 }
6223
6224 // Avoid re-indenting a row that has already been indented by a
6225 // previous selection, but still update this selection's column
6226 // to reflect that indentation.
6227 if delta_for_start_row > 0 {
6228 start_row += 1;
6229 selection.start.column += delta_for_start_row;
6230 if selection.end.row == selection.start.row {
6231 selection.end.column += delta_for_start_row;
6232 }
6233 }
6234
6235 let mut delta_for_end_row = 0;
6236 let has_multiple_rows = start_row + 1 != end_row;
6237 for row in start_row..end_row {
6238 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6239 let indent_delta = match (current_indent.kind, indent_kind) {
6240 (IndentKind::Space, IndentKind::Space) => {
6241 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6242 IndentSize::spaces(columns_to_next_tab_stop)
6243 }
6244 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6245 (_, IndentKind::Tab) => IndentSize::tab(),
6246 };
6247
6248 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6249 0
6250 } else {
6251 selection.start.column
6252 };
6253 let row_start = Point::new(row, start);
6254 edits.push((
6255 row_start..row_start,
6256 indent_delta.chars().collect::<String>(),
6257 ));
6258
6259 // Update this selection's endpoints to reflect the indentation.
6260 if row == selection.start.row {
6261 selection.start.column += indent_delta.len;
6262 }
6263 if row == selection.end.row {
6264 selection.end.column += indent_delta.len;
6265 delta_for_end_row = indent_delta.len;
6266 }
6267 }
6268
6269 if selection.start.row == selection.end.row {
6270 delta_for_start_row + delta_for_end_row
6271 } else {
6272 delta_for_end_row
6273 }
6274 }
6275
6276 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6277 if self.read_only(cx) {
6278 return;
6279 }
6280 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6281 let selections = self.selections.all::<Point>(cx);
6282 let mut deletion_ranges = Vec::new();
6283 let mut last_outdent = None;
6284 {
6285 let buffer = self.buffer.read(cx);
6286 let snapshot = buffer.snapshot(cx);
6287 for selection in &selections {
6288 let settings = buffer.settings_at(selection.start, cx);
6289 let tab_size = settings.tab_size.get();
6290 let mut rows = selection.spanned_rows(false, &display_map);
6291
6292 // Avoid re-outdenting a row that has already been outdented by a
6293 // previous selection.
6294 if let Some(last_row) = last_outdent {
6295 if last_row == rows.start {
6296 rows.start = rows.start.next_row();
6297 }
6298 }
6299 let has_multiple_rows = rows.len() > 1;
6300 for row in rows.iter_rows() {
6301 let indent_size = snapshot.indent_size_for_line(row);
6302 if indent_size.len > 0 {
6303 let deletion_len = match indent_size.kind {
6304 IndentKind::Space => {
6305 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6306 if columns_to_prev_tab_stop == 0 {
6307 tab_size
6308 } else {
6309 columns_to_prev_tab_stop
6310 }
6311 }
6312 IndentKind::Tab => 1,
6313 };
6314 let start = if has_multiple_rows
6315 || deletion_len > selection.start.column
6316 || indent_size.len < selection.start.column
6317 {
6318 0
6319 } else {
6320 selection.start.column - deletion_len
6321 };
6322 deletion_ranges.push(
6323 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6324 );
6325 last_outdent = Some(row);
6326 }
6327 }
6328 }
6329 }
6330
6331 self.transact(window, cx, |this, window, cx| {
6332 this.buffer.update(cx, |buffer, cx| {
6333 let empty_str: Arc<str> = Arc::default();
6334 buffer.edit(
6335 deletion_ranges
6336 .into_iter()
6337 .map(|range| (range, empty_str.clone())),
6338 None,
6339 cx,
6340 );
6341 });
6342 let selections = this.selections.all::<usize>(cx);
6343 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6344 s.select(selections)
6345 });
6346 });
6347 }
6348
6349 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6350 if self.read_only(cx) {
6351 return;
6352 }
6353 let selections = self
6354 .selections
6355 .all::<usize>(cx)
6356 .into_iter()
6357 .map(|s| s.range());
6358
6359 self.transact(window, cx, |this, window, cx| {
6360 this.buffer.update(cx, |buffer, cx| {
6361 buffer.autoindent_ranges(selections, cx);
6362 });
6363 let selections = this.selections.all::<usize>(cx);
6364 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6365 s.select(selections)
6366 });
6367 });
6368 }
6369
6370 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6371 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6372 let selections = self.selections.all::<Point>(cx);
6373
6374 let mut new_cursors = Vec::new();
6375 let mut edit_ranges = Vec::new();
6376 let mut selections = selections.iter().peekable();
6377 while let Some(selection) = selections.next() {
6378 let mut rows = selection.spanned_rows(false, &display_map);
6379 let goal_display_column = selection.head().to_display_point(&display_map).column();
6380
6381 // Accumulate contiguous regions of rows that we want to delete.
6382 while let Some(next_selection) = selections.peek() {
6383 let next_rows = next_selection.spanned_rows(false, &display_map);
6384 if next_rows.start <= rows.end {
6385 rows.end = next_rows.end;
6386 selections.next().unwrap();
6387 } else {
6388 break;
6389 }
6390 }
6391
6392 let buffer = &display_map.buffer_snapshot;
6393 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6394 let edit_end;
6395 let cursor_buffer_row;
6396 if buffer.max_point().row >= rows.end.0 {
6397 // If there's a line after the range, delete the \n from the end of the row range
6398 // and position the cursor on the next line.
6399 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6400 cursor_buffer_row = rows.end;
6401 } else {
6402 // If there isn't a line after the range, delete the \n from the line before the
6403 // start of the row range and position the cursor there.
6404 edit_start = edit_start.saturating_sub(1);
6405 edit_end = buffer.len();
6406 cursor_buffer_row = rows.start.previous_row();
6407 }
6408
6409 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6410 *cursor.column_mut() =
6411 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6412
6413 new_cursors.push((
6414 selection.id,
6415 buffer.anchor_after(cursor.to_point(&display_map)),
6416 ));
6417 edit_ranges.push(edit_start..edit_end);
6418 }
6419
6420 self.transact(window, cx, |this, window, cx| {
6421 let buffer = this.buffer.update(cx, |buffer, cx| {
6422 let empty_str: Arc<str> = Arc::default();
6423 buffer.edit(
6424 edit_ranges
6425 .into_iter()
6426 .map(|range| (range, empty_str.clone())),
6427 None,
6428 cx,
6429 );
6430 buffer.snapshot(cx)
6431 });
6432 let new_selections = new_cursors
6433 .into_iter()
6434 .map(|(id, cursor)| {
6435 let cursor = cursor.to_point(&buffer);
6436 Selection {
6437 id,
6438 start: cursor,
6439 end: cursor,
6440 reversed: false,
6441 goal: SelectionGoal::None,
6442 }
6443 })
6444 .collect();
6445
6446 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6447 s.select(new_selections);
6448 });
6449 });
6450 }
6451
6452 pub fn join_lines_impl(
6453 &mut self,
6454 insert_whitespace: bool,
6455 window: &mut Window,
6456 cx: &mut Context<Self>,
6457 ) {
6458 if self.read_only(cx) {
6459 return;
6460 }
6461 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6462 for selection in self.selections.all::<Point>(cx) {
6463 let start = MultiBufferRow(selection.start.row);
6464 // Treat single line selections as if they include the next line. Otherwise this action
6465 // would do nothing for single line selections individual cursors.
6466 let end = if selection.start.row == selection.end.row {
6467 MultiBufferRow(selection.start.row + 1)
6468 } else {
6469 MultiBufferRow(selection.end.row)
6470 };
6471
6472 if let Some(last_row_range) = row_ranges.last_mut() {
6473 if start <= last_row_range.end {
6474 last_row_range.end = end;
6475 continue;
6476 }
6477 }
6478 row_ranges.push(start..end);
6479 }
6480
6481 let snapshot = self.buffer.read(cx).snapshot(cx);
6482 let mut cursor_positions = Vec::new();
6483 for row_range in &row_ranges {
6484 let anchor = snapshot.anchor_before(Point::new(
6485 row_range.end.previous_row().0,
6486 snapshot.line_len(row_range.end.previous_row()),
6487 ));
6488 cursor_positions.push(anchor..anchor);
6489 }
6490
6491 self.transact(window, cx, |this, window, cx| {
6492 for row_range in row_ranges.into_iter().rev() {
6493 for row in row_range.iter_rows().rev() {
6494 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6495 let next_line_row = row.next_row();
6496 let indent = snapshot.indent_size_for_line(next_line_row);
6497 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6498
6499 let replace =
6500 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6501 " "
6502 } else {
6503 ""
6504 };
6505
6506 this.buffer.update(cx, |buffer, cx| {
6507 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6508 });
6509 }
6510 }
6511
6512 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6513 s.select_anchor_ranges(cursor_positions)
6514 });
6515 });
6516 }
6517
6518 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6519 self.join_lines_impl(true, window, cx);
6520 }
6521
6522 pub fn sort_lines_case_sensitive(
6523 &mut self,
6524 _: &SortLinesCaseSensitive,
6525 window: &mut Window,
6526 cx: &mut Context<Self>,
6527 ) {
6528 self.manipulate_lines(window, cx, |lines| lines.sort())
6529 }
6530
6531 pub fn sort_lines_case_insensitive(
6532 &mut self,
6533 _: &SortLinesCaseInsensitive,
6534 window: &mut Window,
6535 cx: &mut Context<Self>,
6536 ) {
6537 self.manipulate_lines(window, cx, |lines| {
6538 lines.sort_by_key(|line| line.to_lowercase())
6539 })
6540 }
6541
6542 pub fn unique_lines_case_insensitive(
6543 &mut self,
6544 _: &UniqueLinesCaseInsensitive,
6545 window: &mut Window,
6546 cx: &mut Context<Self>,
6547 ) {
6548 self.manipulate_lines(window, cx, |lines| {
6549 let mut seen = HashSet::default();
6550 lines.retain(|line| seen.insert(line.to_lowercase()));
6551 })
6552 }
6553
6554 pub fn unique_lines_case_sensitive(
6555 &mut self,
6556 _: &UniqueLinesCaseSensitive,
6557 window: &mut Window,
6558 cx: &mut Context<Self>,
6559 ) {
6560 self.manipulate_lines(window, cx, |lines| {
6561 let mut seen = HashSet::default();
6562 lines.retain(|line| seen.insert(*line));
6563 })
6564 }
6565
6566 pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
6567 let mut revert_changes = HashMap::default();
6568 let snapshot = self.snapshot(window, cx);
6569 for hunk in snapshot
6570 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
6571 {
6572 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6573 }
6574 if !revert_changes.is_empty() {
6575 self.transact(window, cx, |editor, window, cx| {
6576 editor.revert(revert_changes, window, cx);
6577 });
6578 }
6579 }
6580
6581 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
6582 let Some(project) = self.project.clone() else {
6583 return;
6584 };
6585 self.reload(project, window, cx)
6586 .detach_and_notify_err(window, cx);
6587 }
6588
6589 pub fn revert_selected_hunks(
6590 &mut self,
6591 _: &RevertSelectedHunks,
6592 window: &mut Window,
6593 cx: &mut Context<Self>,
6594 ) {
6595 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
6596 self.revert_hunks_in_ranges(selections, window, cx);
6597 }
6598
6599 fn revert_hunks_in_ranges(
6600 &mut self,
6601 ranges: impl Iterator<Item = Range<Point>>,
6602 window: &mut Window,
6603 cx: &mut Context<Editor>,
6604 ) {
6605 let mut revert_changes = HashMap::default();
6606 let snapshot = self.snapshot(window, cx);
6607 for hunk in &snapshot.hunks_for_ranges(ranges) {
6608 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6609 }
6610 if !revert_changes.is_empty() {
6611 self.transact(window, cx, |editor, window, cx| {
6612 editor.revert(revert_changes, window, cx);
6613 });
6614 }
6615 }
6616
6617 pub fn open_active_item_in_terminal(
6618 &mut self,
6619 _: &OpenInTerminal,
6620 window: &mut Window,
6621 cx: &mut Context<Self>,
6622 ) {
6623 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6624 let project_path = buffer.read(cx).project_path(cx)?;
6625 let project = self.project.as_ref()?.read(cx);
6626 let entry = project.entry_for_path(&project_path, cx)?;
6627 let parent = match &entry.canonical_path {
6628 Some(canonical_path) => canonical_path.to_path_buf(),
6629 None => project.absolute_path(&project_path, cx)?,
6630 }
6631 .parent()?
6632 .to_path_buf();
6633 Some(parent)
6634 }) {
6635 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
6636 }
6637 }
6638
6639 pub fn prepare_revert_change(
6640 &self,
6641 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6642 hunk: &MultiBufferDiffHunk,
6643 cx: &mut App,
6644 ) -> Option<()> {
6645 let buffer = self.buffer.read(cx);
6646 let change_set = buffer.change_set_for(hunk.buffer_id)?;
6647 let buffer = buffer.buffer(hunk.buffer_id)?;
6648 let buffer = buffer.read(cx);
6649 let original_text = change_set
6650 .read(cx)
6651 .base_text
6652 .as_ref()?
6653 .as_rope()
6654 .slice(hunk.diff_base_byte_range.clone());
6655 let buffer_snapshot = buffer.snapshot();
6656 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6657 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6658 probe
6659 .0
6660 .start
6661 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6662 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6663 }) {
6664 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6665 Some(())
6666 } else {
6667 None
6668 }
6669 }
6670
6671 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
6672 self.manipulate_lines(window, cx, |lines| lines.reverse())
6673 }
6674
6675 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
6676 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
6677 }
6678
6679 fn manipulate_lines<Fn>(
6680 &mut self,
6681 window: &mut Window,
6682 cx: &mut Context<Self>,
6683 mut callback: Fn,
6684 ) where
6685 Fn: FnMut(&mut Vec<&str>),
6686 {
6687 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6688 let buffer = self.buffer.read(cx).snapshot(cx);
6689
6690 let mut edits = Vec::new();
6691
6692 let selections = self.selections.all::<Point>(cx);
6693 let mut selections = selections.iter().peekable();
6694 let mut contiguous_row_selections = Vec::new();
6695 let mut new_selections = Vec::new();
6696 let mut added_lines = 0;
6697 let mut removed_lines = 0;
6698
6699 while let Some(selection) = selections.next() {
6700 let (start_row, end_row) = consume_contiguous_rows(
6701 &mut contiguous_row_selections,
6702 selection,
6703 &display_map,
6704 &mut selections,
6705 );
6706
6707 let start_point = Point::new(start_row.0, 0);
6708 let end_point = Point::new(
6709 end_row.previous_row().0,
6710 buffer.line_len(end_row.previous_row()),
6711 );
6712 let text = buffer
6713 .text_for_range(start_point..end_point)
6714 .collect::<String>();
6715
6716 let mut lines = text.split('\n').collect_vec();
6717
6718 let lines_before = lines.len();
6719 callback(&mut lines);
6720 let lines_after = lines.len();
6721
6722 edits.push((start_point..end_point, lines.join("\n")));
6723
6724 // Selections must change based on added and removed line count
6725 let start_row =
6726 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6727 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6728 new_selections.push(Selection {
6729 id: selection.id,
6730 start: start_row,
6731 end: end_row,
6732 goal: SelectionGoal::None,
6733 reversed: selection.reversed,
6734 });
6735
6736 if lines_after > lines_before {
6737 added_lines += lines_after - lines_before;
6738 } else if lines_before > lines_after {
6739 removed_lines += lines_before - lines_after;
6740 }
6741 }
6742
6743 self.transact(window, cx, |this, window, cx| {
6744 let buffer = this.buffer.update(cx, |buffer, cx| {
6745 buffer.edit(edits, None, cx);
6746 buffer.snapshot(cx)
6747 });
6748
6749 // Recalculate offsets on newly edited buffer
6750 let new_selections = new_selections
6751 .iter()
6752 .map(|s| {
6753 let start_point = Point::new(s.start.0, 0);
6754 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6755 Selection {
6756 id: s.id,
6757 start: buffer.point_to_offset(start_point),
6758 end: buffer.point_to_offset(end_point),
6759 goal: s.goal,
6760 reversed: s.reversed,
6761 }
6762 })
6763 .collect();
6764
6765 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6766 s.select(new_selections);
6767 });
6768
6769 this.request_autoscroll(Autoscroll::fit(), cx);
6770 });
6771 }
6772
6773 pub fn convert_to_upper_case(
6774 &mut self,
6775 _: &ConvertToUpperCase,
6776 window: &mut Window,
6777 cx: &mut Context<Self>,
6778 ) {
6779 self.manipulate_text(window, cx, |text| text.to_uppercase())
6780 }
6781
6782 pub fn convert_to_lower_case(
6783 &mut self,
6784 _: &ConvertToLowerCase,
6785 window: &mut Window,
6786 cx: &mut Context<Self>,
6787 ) {
6788 self.manipulate_text(window, cx, |text| text.to_lowercase())
6789 }
6790
6791 pub fn convert_to_title_case(
6792 &mut self,
6793 _: &ConvertToTitleCase,
6794 window: &mut Window,
6795 cx: &mut Context<Self>,
6796 ) {
6797 self.manipulate_text(window, cx, |text| {
6798 text.split('\n')
6799 .map(|line| line.to_case(Case::Title))
6800 .join("\n")
6801 })
6802 }
6803
6804 pub fn convert_to_snake_case(
6805 &mut self,
6806 _: &ConvertToSnakeCase,
6807 window: &mut Window,
6808 cx: &mut Context<Self>,
6809 ) {
6810 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
6811 }
6812
6813 pub fn convert_to_kebab_case(
6814 &mut self,
6815 _: &ConvertToKebabCase,
6816 window: &mut Window,
6817 cx: &mut Context<Self>,
6818 ) {
6819 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
6820 }
6821
6822 pub fn convert_to_upper_camel_case(
6823 &mut self,
6824 _: &ConvertToUpperCamelCase,
6825 window: &mut Window,
6826 cx: &mut Context<Self>,
6827 ) {
6828 self.manipulate_text(window, cx, |text| {
6829 text.split('\n')
6830 .map(|line| line.to_case(Case::UpperCamel))
6831 .join("\n")
6832 })
6833 }
6834
6835 pub fn convert_to_lower_camel_case(
6836 &mut self,
6837 _: &ConvertToLowerCamelCase,
6838 window: &mut Window,
6839 cx: &mut Context<Self>,
6840 ) {
6841 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
6842 }
6843
6844 pub fn convert_to_opposite_case(
6845 &mut self,
6846 _: &ConvertToOppositeCase,
6847 window: &mut Window,
6848 cx: &mut Context<Self>,
6849 ) {
6850 self.manipulate_text(window, cx, |text| {
6851 text.chars()
6852 .fold(String::with_capacity(text.len()), |mut t, c| {
6853 if c.is_uppercase() {
6854 t.extend(c.to_lowercase());
6855 } else {
6856 t.extend(c.to_uppercase());
6857 }
6858 t
6859 })
6860 })
6861 }
6862
6863 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
6864 where
6865 Fn: FnMut(&str) -> String,
6866 {
6867 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6868 let buffer = self.buffer.read(cx).snapshot(cx);
6869
6870 let mut new_selections = Vec::new();
6871 let mut edits = Vec::new();
6872 let mut selection_adjustment = 0i32;
6873
6874 for selection in self.selections.all::<usize>(cx) {
6875 let selection_is_empty = selection.is_empty();
6876
6877 let (start, end) = if selection_is_empty {
6878 let word_range = movement::surrounding_word(
6879 &display_map,
6880 selection.start.to_display_point(&display_map),
6881 );
6882 let start = word_range.start.to_offset(&display_map, Bias::Left);
6883 let end = word_range.end.to_offset(&display_map, Bias::Left);
6884 (start, end)
6885 } else {
6886 (selection.start, selection.end)
6887 };
6888
6889 let text = buffer.text_for_range(start..end).collect::<String>();
6890 let old_length = text.len() as i32;
6891 let text = callback(&text);
6892
6893 new_selections.push(Selection {
6894 start: (start as i32 - selection_adjustment) as usize,
6895 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6896 goal: SelectionGoal::None,
6897 ..selection
6898 });
6899
6900 selection_adjustment += old_length - text.len() as i32;
6901
6902 edits.push((start..end, text));
6903 }
6904
6905 self.transact(window, cx, |this, window, cx| {
6906 this.buffer.update(cx, |buffer, cx| {
6907 buffer.edit(edits, None, cx);
6908 });
6909
6910 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6911 s.select(new_selections);
6912 });
6913
6914 this.request_autoscroll(Autoscroll::fit(), cx);
6915 });
6916 }
6917
6918 pub fn duplicate(
6919 &mut self,
6920 upwards: bool,
6921 whole_lines: bool,
6922 window: &mut Window,
6923 cx: &mut Context<Self>,
6924 ) {
6925 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6926 let buffer = &display_map.buffer_snapshot;
6927 let selections = self.selections.all::<Point>(cx);
6928
6929 let mut edits = Vec::new();
6930 let mut selections_iter = selections.iter().peekable();
6931 while let Some(selection) = selections_iter.next() {
6932 let mut rows = selection.spanned_rows(false, &display_map);
6933 // duplicate line-wise
6934 if whole_lines || selection.start == selection.end {
6935 // Avoid duplicating the same lines twice.
6936 while let Some(next_selection) = selections_iter.peek() {
6937 let next_rows = next_selection.spanned_rows(false, &display_map);
6938 if next_rows.start < rows.end {
6939 rows.end = next_rows.end;
6940 selections_iter.next().unwrap();
6941 } else {
6942 break;
6943 }
6944 }
6945
6946 // Copy the text from the selected row region and splice it either at the start
6947 // or end of the region.
6948 let start = Point::new(rows.start.0, 0);
6949 let end = Point::new(
6950 rows.end.previous_row().0,
6951 buffer.line_len(rows.end.previous_row()),
6952 );
6953 let text = buffer
6954 .text_for_range(start..end)
6955 .chain(Some("\n"))
6956 .collect::<String>();
6957 let insert_location = if upwards {
6958 Point::new(rows.end.0, 0)
6959 } else {
6960 start
6961 };
6962 edits.push((insert_location..insert_location, text));
6963 } else {
6964 // duplicate character-wise
6965 let start = selection.start;
6966 let end = selection.end;
6967 let text = buffer.text_for_range(start..end).collect::<String>();
6968 edits.push((selection.end..selection.end, text));
6969 }
6970 }
6971
6972 self.transact(window, cx, |this, _, cx| {
6973 this.buffer.update(cx, |buffer, cx| {
6974 buffer.edit(edits, None, cx);
6975 });
6976
6977 this.request_autoscroll(Autoscroll::fit(), cx);
6978 });
6979 }
6980
6981 pub fn duplicate_line_up(
6982 &mut self,
6983 _: &DuplicateLineUp,
6984 window: &mut Window,
6985 cx: &mut Context<Self>,
6986 ) {
6987 self.duplicate(true, true, window, cx);
6988 }
6989
6990 pub fn duplicate_line_down(
6991 &mut self,
6992 _: &DuplicateLineDown,
6993 window: &mut Window,
6994 cx: &mut Context<Self>,
6995 ) {
6996 self.duplicate(false, true, window, cx);
6997 }
6998
6999 pub fn duplicate_selection(
7000 &mut self,
7001 _: &DuplicateSelection,
7002 window: &mut Window,
7003 cx: &mut Context<Self>,
7004 ) {
7005 self.duplicate(false, false, window, cx);
7006 }
7007
7008 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7009 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7010 let buffer = self.buffer.read(cx).snapshot(cx);
7011
7012 let mut edits = Vec::new();
7013 let mut unfold_ranges = Vec::new();
7014 let mut refold_creases = Vec::new();
7015
7016 let selections = self.selections.all::<Point>(cx);
7017 let mut selections = selections.iter().peekable();
7018 let mut contiguous_row_selections = Vec::new();
7019 let mut new_selections = Vec::new();
7020
7021 while let Some(selection) = selections.next() {
7022 // Find all the selections that span a contiguous row range
7023 let (start_row, end_row) = consume_contiguous_rows(
7024 &mut contiguous_row_selections,
7025 selection,
7026 &display_map,
7027 &mut selections,
7028 );
7029
7030 // Move the text spanned by the row range to be before the line preceding the row range
7031 if start_row.0 > 0 {
7032 let range_to_move = Point::new(
7033 start_row.previous_row().0,
7034 buffer.line_len(start_row.previous_row()),
7035 )
7036 ..Point::new(
7037 end_row.previous_row().0,
7038 buffer.line_len(end_row.previous_row()),
7039 );
7040 let insertion_point = display_map
7041 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7042 .0;
7043
7044 // Don't move lines across excerpts
7045 if buffer
7046 .excerpt_containing(insertion_point..range_to_move.end)
7047 .is_some()
7048 {
7049 let text = buffer
7050 .text_for_range(range_to_move.clone())
7051 .flat_map(|s| s.chars())
7052 .skip(1)
7053 .chain(['\n'])
7054 .collect::<String>();
7055
7056 edits.push((
7057 buffer.anchor_after(range_to_move.start)
7058 ..buffer.anchor_before(range_to_move.end),
7059 String::new(),
7060 ));
7061 let insertion_anchor = buffer.anchor_after(insertion_point);
7062 edits.push((insertion_anchor..insertion_anchor, text));
7063
7064 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7065
7066 // Move selections up
7067 new_selections.extend(contiguous_row_selections.drain(..).map(
7068 |mut selection| {
7069 selection.start.row -= row_delta;
7070 selection.end.row -= row_delta;
7071 selection
7072 },
7073 ));
7074
7075 // Move folds up
7076 unfold_ranges.push(range_to_move.clone());
7077 for fold in display_map.folds_in_range(
7078 buffer.anchor_before(range_to_move.start)
7079 ..buffer.anchor_after(range_to_move.end),
7080 ) {
7081 let mut start = fold.range.start.to_point(&buffer);
7082 let mut end = fold.range.end.to_point(&buffer);
7083 start.row -= row_delta;
7084 end.row -= row_delta;
7085 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7086 }
7087 }
7088 }
7089
7090 // If we didn't move line(s), preserve the existing selections
7091 new_selections.append(&mut contiguous_row_selections);
7092 }
7093
7094 self.transact(window, cx, |this, window, cx| {
7095 this.unfold_ranges(&unfold_ranges, true, true, cx);
7096 this.buffer.update(cx, |buffer, cx| {
7097 for (range, text) in edits {
7098 buffer.edit([(range, text)], None, cx);
7099 }
7100 });
7101 this.fold_creases(refold_creases, true, window, cx);
7102 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7103 s.select(new_selections);
7104 })
7105 });
7106 }
7107
7108 pub fn move_line_down(
7109 &mut self,
7110 _: &MoveLineDown,
7111 window: &mut Window,
7112 cx: &mut Context<Self>,
7113 ) {
7114 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7115 let buffer = self.buffer.read(cx).snapshot(cx);
7116
7117 let mut edits = Vec::new();
7118 let mut unfold_ranges = Vec::new();
7119 let mut refold_creases = Vec::new();
7120
7121 let selections = self.selections.all::<Point>(cx);
7122 let mut selections = selections.iter().peekable();
7123 let mut contiguous_row_selections = Vec::new();
7124 let mut new_selections = Vec::new();
7125
7126 while let Some(selection) = selections.next() {
7127 // Find all the selections that span a contiguous row range
7128 let (start_row, end_row) = consume_contiguous_rows(
7129 &mut contiguous_row_selections,
7130 selection,
7131 &display_map,
7132 &mut selections,
7133 );
7134
7135 // Move the text spanned by the row range to be after the last line of the row range
7136 if end_row.0 <= buffer.max_point().row {
7137 let range_to_move =
7138 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7139 let insertion_point = display_map
7140 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7141 .0;
7142
7143 // Don't move lines across excerpt boundaries
7144 if buffer
7145 .excerpt_containing(range_to_move.start..insertion_point)
7146 .is_some()
7147 {
7148 let mut text = String::from("\n");
7149 text.extend(buffer.text_for_range(range_to_move.clone()));
7150 text.pop(); // Drop trailing newline
7151 edits.push((
7152 buffer.anchor_after(range_to_move.start)
7153 ..buffer.anchor_before(range_to_move.end),
7154 String::new(),
7155 ));
7156 let insertion_anchor = buffer.anchor_after(insertion_point);
7157 edits.push((insertion_anchor..insertion_anchor, text));
7158
7159 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7160
7161 // Move selections down
7162 new_selections.extend(contiguous_row_selections.drain(..).map(
7163 |mut selection| {
7164 selection.start.row += row_delta;
7165 selection.end.row += row_delta;
7166 selection
7167 },
7168 ));
7169
7170 // Move folds down
7171 unfold_ranges.push(range_to_move.clone());
7172 for fold in display_map.folds_in_range(
7173 buffer.anchor_before(range_to_move.start)
7174 ..buffer.anchor_after(range_to_move.end),
7175 ) {
7176 let mut start = fold.range.start.to_point(&buffer);
7177 let mut end = fold.range.end.to_point(&buffer);
7178 start.row += row_delta;
7179 end.row += row_delta;
7180 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7181 }
7182 }
7183 }
7184
7185 // If we didn't move line(s), preserve the existing selections
7186 new_selections.append(&mut contiguous_row_selections);
7187 }
7188
7189 self.transact(window, cx, |this, window, cx| {
7190 this.unfold_ranges(&unfold_ranges, true, true, cx);
7191 this.buffer.update(cx, |buffer, cx| {
7192 for (range, text) in edits {
7193 buffer.edit([(range, text)], None, cx);
7194 }
7195 });
7196 this.fold_creases(refold_creases, true, window, cx);
7197 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7198 s.select(new_selections)
7199 });
7200 });
7201 }
7202
7203 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7204 let text_layout_details = &self.text_layout_details(window);
7205 self.transact(window, cx, |this, window, cx| {
7206 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7207 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7208 let line_mode = s.line_mode;
7209 s.move_with(|display_map, selection| {
7210 if !selection.is_empty() || line_mode {
7211 return;
7212 }
7213
7214 let mut head = selection.head();
7215 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7216 if head.column() == display_map.line_len(head.row()) {
7217 transpose_offset = display_map
7218 .buffer_snapshot
7219 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7220 }
7221
7222 if transpose_offset == 0 {
7223 return;
7224 }
7225
7226 *head.column_mut() += 1;
7227 head = display_map.clip_point(head, Bias::Right);
7228 let goal = SelectionGoal::HorizontalPosition(
7229 display_map
7230 .x_for_display_point(head, text_layout_details)
7231 .into(),
7232 );
7233 selection.collapse_to(head, goal);
7234
7235 let transpose_start = display_map
7236 .buffer_snapshot
7237 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7238 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7239 let transpose_end = display_map
7240 .buffer_snapshot
7241 .clip_offset(transpose_offset + 1, Bias::Right);
7242 if let Some(ch) =
7243 display_map.buffer_snapshot.chars_at(transpose_start).next()
7244 {
7245 edits.push((transpose_start..transpose_offset, String::new()));
7246 edits.push((transpose_end..transpose_end, ch.to_string()));
7247 }
7248 }
7249 });
7250 edits
7251 });
7252 this.buffer
7253 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7254 let selections = this.selections.all::<usize>(cx);
7255 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7256 s.select(selections);
7257 });
7258 });
7259 }
7260
7261 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7262 self.rewrap_impl(IsVimMode::No, cx)
7263 }
7264
7265 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7266 let buffer = self.buffer.read(cx).snapshot(cx);
7267 let selections = self.selections.all::<Point>(cx);
7268 let mut selections = selections.iter().peekable();
7269
7270 let mut edits = Vec::new();
7271 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7272
7273 while let Some(selection) = selections.next() {
7274 let mut start_row = selection.start.row;
7275 let mut end_row = selection.end.row;
7276
7277 // Skip selections that overlap with a range that has already been rewrapped.
7278 let selection_range = start_row..end_row;
7279 if rewrapped_row_ranges
7280 .iter()
7281 .any(|range| range.overlaps(&selection_range))
7282 {
7283 continue;
7284 }
7285
7286 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7287
7288 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7289 match language_scope.language_name().as_ref() {
7290 "Markdown" | "Plain Text" => {
7291 should_rewrap = true;
7292 }
7293 _ => {}
7294 }
7295 }
7296
7297 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7298
7299 // Since not all lines in the selection may be at the same indent
7300 // level, choose the indent size that is the most common between all
7301 // of the lines.
7302 //
7303 // If there is a tie, we use the deepest indent.
7304 let (indent_size, indent_end) = {
7305 let mut indent_size_occurrences = HashMap::default();
7306 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7307
7308 for row in start_row..=end_row {
7309 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7310 rows_by_indent_size.entry(indent).or_default().push(row);
7311 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7312 }
7313
7314 let indent_size = indent_size_occurrences
7315 .into_iter()
7316 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7317 .map(|(indent, _)| indent)
7318 .unwrap_or_default();
7319 let row = rows_by_indent_size[&indent_size][0];
7320 let indent_end = Point::new(row, indent_size.len);
7321
7322 (indent_size, indent_end)
7323 };
7324
7325 let mut line_prefix = indent_size.chars().collect::<String>();
7326
7327 if let Some(comment_prefix) =
7328 buffer
7329 .language_scope_at(selection.head())
7330 .and_then(|language| {
7331 language
7332 .line_comment_prefixes()
7333 .iter()
7334 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7335 .cloned()
7336 })
7337 {
7338 line_prefix.push_str(&comment_prefix);
7339 should_rewrap = true;
7340 }
7341
7342 if !should_rewrap {
7343 continue;
7344 }
7345
7346 if selection.is_empty() {
7347 'expand_upwards: while start_row > 0 {
7348 let prev_row = start_row - 1;
7349 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7350 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7351 {
7352 start_row = prev_row;
7353 } else {
7354 break 'expand_upwards;
7355 }
7356 }
7357
7358 'expand_downwards: while end_row < buffer.max_point().row {
7359 let next_row = end_row + 1;
7360 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7361 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7362 {
7363 end_row = next_row;
7364 } else {
7365 break 'expand_downwards;
7366 }
7367 }
7368 }
7369
7370 let start = Point::new(start_row, 0);
7371 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7372 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7373 let Some(lines_without_prefixes) = selection_text
7374 .lines()
7375 .map(|line| {
7376 line.strip_prefix(&line_prefix)
7377 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7378 .ok_or_else(|| {
7379 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7380 })
7381 })
7382 .collect::<Result<Vec<_>, _>>()
7383 .log_err()
7384 else {
7385 continue;
7386 };
7387
7388 let wrap_column = buffer
7389 .settings_at(Point::new(start_row, 0), cx)
7390 .preferred_line_length as usize;
7391 let wrapped_text = wrap_with_prefix(
7392 line_prefix,
7393 lines_without_prefixes.join(" "),
7394 wrap_column,
7395 tab_size,
7396 );
7397
7398 // TODO: should always use char-based diff while still supporting cursor behavior that
7399 // matches vim.
7400 let diff = match is_vim_mode {
7401 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7402 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7403 };
7404 let mut offset = start.to_offset(&buffer);
7405 let mut moved_since_edit = true;
7406
7407 for change in diff.iter_all_changes() {
7408 let value = change.value();
7409 match change.tag() {
7410 ChangeTag::Equal => {
7411 offset += value.len();
7412 moved_since_edit = true;
7413 }
7414 ChangeTag::Delete => {
7415 let start = buffer.anchor_after(offset);
7416 let end = buffer.anchor_before(offset + value.len());
7417
7418 if moved_since_edit {
7419 edits.push((start..end, String::new()));
7420 } else {
7421 edits.last_mut().unwrap().0.end = end;
7422 }
7423
7424 offset += value.len();
7425 moved_since_edit = false;
7426 }
7427 ChangeTag::Insert => {
7428 if moved_since_edit {
7429 let anchor = buffer.anchor_after(offset);
7430 edits.push((anchor..anchor, value.to_string()));
7431 } else {
7432 edits.last_mut().unwrap().1.push_str(value);
7433 }
7434
7435 moved_since_edit = false;
7436 }
7437 }
7438 }
7439
7440 rewrapped_row_ranges.push(start_row..=end_row);
7441 }
7442
7443 self.buffer
7444 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7445 }
7446
7447 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7448 let mut text = String::new();
7449 let buffer = self.buffer.read(cx).snapshot(cx);
7450 let mut selections = self.selections.all::<Point>(cx);
7451 let mut clipboard_selections = Vec::with_capacity(selections.len());
7452 {
7453 let max_point = buffer.max_point();
7454 let mut is_first = true;
7455 for selection in &mut selections {
7456 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7457 if is_entire_line {
7458 selection.start = Point::new(selection.start.row, 0);
7459 if !selection.is_empty() && selection.end.column == 0 {
7460 selection.end = cmp::min(max_point, selection.end);
7461 } else {
7462 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7463 }
7464 selection.goal = SelectionGoal::None;
7465 }
7466 if is_first {
7467 is_first = false;
7468 } else {
7469 text += "\n";
7470 }
7471 let mut len = 0;
7472 for chunk in buffer.text_for_range(selection.start..selection.end) {
7473 text.push_str(chunk);
7474 len += chunk.len();
7475 }
7476 clipboard_selections.push(ClipboardSelection {
7477 len,
7478 is_entire_line,
7479 first_line_indent: buffer
7480 .indent_size_for_line(MultiBufferRow(selection.start.row))
7481 .len,
7482 });
7483 }
7484 }
7485
7486 self.transact(window, cx, |this, window, cx| {
7487 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7488 s.select(selections);
7489 });
7490 this.insert("", window, cx);
7491 });
7492 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7493 }
7494
7495 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
7496 let item = self.cut_common(window, cx);
7497 cx.write_to_clipboard(item);
7498 }
7499
7500 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
7501 self.change_selections(None, window, cx, |s| {
7502 s.move_with(|snapshot, sel| {
7503 if sel.is_empty() {
7504 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7505 }
7506 });
7507 });
7508 let item = self.cut_common(window, cx);
7509 cx.set_global(KillRing(item))
7510 }
7511
7512 pub fn kill_ring_yank(
7513 &mut self,
7514 _: &KillRingYank,
7515 window: &mut Window,
7516 cx: &mut Context<Self>,
7517 ) {
7518 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7519 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7520 (kill_ring.text().to_string(), kill_ring.metadata_json())
7521 } else {
7522 return;
7523 }
7524 } else {
7525 return;
7526 };
7527 self.do_paste(&text, metadata, false, window, cx);
7528 }
7529
7530 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
7531 let selections = self.selections.all::<Point>(cx);
7532 let buffer = self.buffer.read(cx).read(cx);
7533 let mut text = String::new();
7534
7535 let mut clipboard_selections = Vec::with_capacity(selections.len());
7536 {
7537 let max_point = buffer.max_point();
7538 let mut is_first = true;
7539 for selection in selections.iter() {
7540 let mut start = selection.start;
7541 let mut end = selection.end;
7542 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7543 if is_entire_line {
7544 start = Point::new(start.row, 0);
7545 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7546 }
7547 if is_first {
7548 is_first = false;
7549 } else {
7550 text += "\n";
7551 }
7552 let mut len = 0;
7553 for chunk in buffer.text_for_range(start..end) {
7554 text.push_str(chunk);
7555 len += chunk.len();
7556 }
7557 clipboard_selections.push(ClipboardSelection {
7558 len,
7559 is_entire_line,
7560 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7561 });
7562 }
7563 }
7564
7565 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7566 text,
7567 clipboard_selections,
7568 ));
7569 }
7570
7571 pub fn do_paste(
7572 &mut self,
7573 text: &String,
7574 clipboard_selections: Option<Vec<ClipboardSelection>>,
7575 handle_entire_lines: bool,
7576 window: &mut Window,
7577 cx: &mut Context<Self>,
7578 ) {
7579 if self.read_only(cx) {
7580 return;
7581 }
7582
7583 let clipboard_text = Cow::Borrowed(text);
7584
7585 self.transact(window, cx, |this, window, cx| {
7586 if let Some(mut clipboard_selections) = clipboard_selections {
7587 let old_selections = this.selections.all::<usize>(cx);
7588 let all_selections_were_entire_line =
7589 clipboard_selections.iter().all(|s| s.is_entire_line);
7590 let first_selection_indent_column =
7591 clipboard_selections.first().map(|s| s.first_line_indent);
7592 if clipboard_selections.len() != old_selections.len() {
7593 clipboard_selections.drain(..);
7594 }
7595 let cursor_offset = this.selections.last::<usize>(cx).head();
7596 let mut auto_indent_on_paste = true;
7597
7598 this.buffer.update(cx, |buffer, cx| {
7599 let snapshot = buffer.read(cx);
7600 auto_indent_on_paste =
7601 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7602
7603 let mut start_offset = 0;
7604 let mut edits = Vec::new();
7605 let mut original_indent_columns = Vec::new();
7606 for (ix, selection) in old_selections.iter().enumerate() {
7607 let to_insert;
7608 let entire_line;
7609 let original_indent_column;
7610 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7611 let end_offset = start_offset + clipboard_selection.len;
7612 to_insert = &clipboard_text[start_offset..end_offset];
7613 entire_line = clipboard_selection.is_entire_line;
7614 start_offset = end_offset + 1;
7615 original_indent_column = Some(clipboard_selection.first_line_indent);
7616 } else {
7617 to_insert = clipboard_text.as_str();
7618 entire_line = all_selections_were_entire_line;
7619 original_indent_column = first_selection_indent_column
7620 }
7621
7622 // If the corresponding selection was empty when this slice of the
7623 // clipboard text was written, then the entire line containing the
7624 // selection was copied. If this selection is also currently empty,
7625 // then paste the line before the current line of the buffer.
7626 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7627 let column = selection.start.to_point(&snapshot).column as usize;
7628 let line_start = selection.start - column;
7629 line_start..line_start
7630 } else {
7631 selection.range()
7632 };
7633
7634 edits.push((range, to_insert));
7635 original_indent_columns.extend(original_indent_column);
7636 }
7637 drop(snapshot);
7638
7639 buffer.edit(
7640 edits,
7641 if auto_indent_on_paste {
7642 Some(AutoindentMode::Block {
7643 original_indent_columns,
7644 })
7645 } else {
7646 None
7647 },
7648 cx,
7649 );
7650 });
7651
7652 let selections = this.selections.all::<usize>(cx);
7653 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7654 s.select(selections)
7655 });
7656 } else {
7657 this.insert(&clipboard_text, window, cx);
7658 }
7659 });
7660 }
7661
7662 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
7663 if let Some(item) = cx.read_from_clipboard() {
7664 let entries = item.entries();
7665
7666 match entries.first() {
7667 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7668 // of all the pasted entries.
7669 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7670 .do_paste(
7671 clipboard_string.text(),
7672 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7673 true,
7674 window,
7675 cx,
7676 ),
7677 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
7678 }
7679 }
7680 }
7681
7682 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
7683 if self.read_only(cx) {
7684 return;
7685 }
7686
7687 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7688 if let Some((selections, _)) =
7689 self.selection_history.transaction(transaction_id).cloned()
7690 {
7691 self.change_selections(None, window, cx, |s| {
7692 s.select_anchors(selections.to_vec());
7693 });
7694 }
7695 self.request_autoscroll(Autoscroll::fit(), cx);
7696 self.unmark_text(window, cx);
7697 self.refresh_inline_completion(true, false, window, cx);
7698 cx.emit(EditorEvent::Edited { transaction_id });
7699 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7700 }
7701 }
7702
7703 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
7704 if self.read_only(cx) {
7705 return;
7706 }
7707
7708 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7709 if let Some((_, Some(selections))) =
7710 self.selection_history.transaction(transaction_id).cloned()
7711 {
7712 self.change_selections(None, window, cx, |s| {
7713 s.select_anchors(selections.to_vec());
7714 });
7715 }
7716 self.request_autoscroll(Autoscroll::fit(), cx);
7717 self.unmark_text(window, cx);
7718 self.refresh_inline_completion(true, false, window, cx);
7719 cx.emit(EditorEvent::Edited { transaction_id });
7720 }
7721 }
7722
7723 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
7724 self.buffer
7725 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7726 }
7727
7728 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
7729 self.buffer
7730 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7731 }
7732
7733 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
7734 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7735 let line_mode = s.line_mode;
7736 s.move_with(|map, selection| {
7737 let cursor = if selection.is_empty() && !line_mode {
7738 movement::left(map, selection.start)
7739 } else {
7740 selection.start
7741 };
7742 selection.collapse_to(cursor, SelectionGoal::None);
7743 });
7744 })
7745 }
7746
7747 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
7748 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7749 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7750 })
7751 }
7752
7753 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
7754 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7755 let line_mode = s.line_mode;
7756 s.move_with(|map, selection| {
7757 let cursor = if selection.is_empty() && !line_mode {
7758 movement::right(map, selection.end)
7759 } else {
7760 selection.end
7761 };
7762 selection.collapse_to(cursor, SelectionGoal::None)
7763 });
7764 })
7765 }
7766
7767 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
7768 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7769 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7770 })
7771 }
7772
7773 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
7774 if self.take_rename(true, window, cx).is_some() {
7775 return;
7776 }
7777
7778 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7779 cx.propagate();
7780 return;
7781 }
7782
7783 let text_layout_details = &self.text_layout_details(window);
7784 let selection_count = self.selections.count();
7785 let first_selection = self.selections.first_anchor();
7786
7787 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7788 let line_mode = s.line_mode;
7789 s.move_with(|map, selection| {
7790 if !selection.is_empty() && !line_mode {
7791 selection.goal = SelectionGoal::None;
7792 }
7793 let (cursor, goal) = movement::up(
7794 map,
7795 selection.start,
7796 selection.goal,
7797 false,
7798 text_layout_details,
7799 );
7800 selection.collapse_to(cursor, goal);
7801 });
7802 });
7803
7804 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7805 {
7806 cx.propagate();
7807 }
7808 }
7809
7810 pub fn move_up_by_lines(
7811 &mut self,
7812 action: &MoveUpByLines,
7813 window: &mut Window,
7814 cx: &mut Context<Self>,
7815 ) {
7816 if self.take_rename(true, window, cx).is_some() {
7817 return;
7818 }
7819
7820 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7821 cx.propagate();
7822 return;
7823 }
7824
7825 let text_layout_details = &self.text_layout_details(window);
7826
7827 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7828 let line_mode = s.line_mode;
7829 s.move_with(|map, selection| {
7830 if !selection.is_empty() && !line_mode {
7831 selection.goal = SelectionGoal::None;
7832 }
7833 let (cursor, goal) = movement::up_by_rows(
7834 map,
7835 selection.start,
7836 action.lines,
7837 selection.goal,
7838 false,
7839 text_layout_details,
7840 );
7841 selection.collapse_to(cursor, goal);
7842 });
7843 })
7844 }
7845
7846 pub fn move_down_by_lines(
7847 &mut self,
7848 action: &MoveDownByLines,
7849 window: &mut Window,
7850 cx: &mut Context<Self>,
7851 ) {
7852 if self.take_rename(true, window, cx).is_some() {
7853 return;
7854 }
7855
7856 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7857 cx.propagate();
7858 return;
7859 }
7860
7861 let text_layout_details = &self.text_layout_details(window);
7862
7863 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7864 let line_mode = s.line_mode;
7865 s.move_with(|map, selection| {
7866 if !selection.is_empty() && !line_mode {
7867 selection.goal = SelectionGoal::None;
7868 }
7869 let (cursor, goal) = movement::down_by_rows(
7870 map,
7871 selection.start,
7872 action.lines,
7873 selection.goal,
7874 false,
7875 text_layout_details,
7876 );
7877 selection.collapse_to(cursor, goal);
7878 });
7879 })
7880 }
7881
7882 pub fn select_down_by_lines(
7883 &mut self,
7884 action: &SelectDownByLines,
7885 window: &mut Window,
7886 cx: &mut Context<Self>,
7887 ) {
7888 let text_layout_details = &self.text_layout_details(window);
7889 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7890 s.move_heads_with(|map, head, goal| {
7891 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7892 })
7893 })
7894 }
7895
7896 pub fn select_up_by_lines(
7897 &mut self,
7898 action: &SelectUpByLines,
7899 window: &mut Window,
7900 cx: &mut Context<Self>,
7901 ) {
7902 let text_layout_details = &self.text_layout_details(window);
7903 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7904 s.move_heads_with(|map, head, goal| {
7905 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7906 })
7907 })
7908 }
7909
7910 pub fn select_page_up(
7911 &mut self,
7912 _: &SelectPageUp,
7913 window: &mut Window,
7914 cx: &mut Context<Self>,
7915 ) {
7916 let Some(row_count) = self.visible_row_count() else {
7917 return;
7918 };
7919
7920 let text_layout_details = &self.text_layout_details(window);
7921
7922 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7923 s.move_heads_with(|map, head, goal| {
7924 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7925 })
7926 })
7927 }
7928
7929 pub fn move_page_up(
7930 &mut self,
7931 action: &MovePageUp,
7932 window: &mut Window,
7933 cx: &mut Context<Self>,
7934 ) {
7935 if self.take_rename(true, window, cx).is_some() {
7936 return;
7937 }
7938
7939 if self
7940 .context_menu
7941 .borrow_mut()
7942 .as_mut()
7943 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7944 .unwrap_or(false)
7945 {
7946 return;
7947 }
7948
7949 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7950 cx.propagate();
7951 return;
7952 }
7953
7954 let Some(row_count) = self.visible_row_count() else {
7955 return;
7956 };
7957
7958 let autoscroll = if action.center_cursor {
7959 Autoscroll::center()
7960 } else {
7961 Autoscroll::fit()
7962 };
7963
7964 let text_layout_details = &self.text_layout_details(window);
7965
7966 self.change_selections(Some(autoscroll), window, cx, |s| {
7967 let line_mode = s.line_mode;
7968 s.move_with(|map, selection| {
7969 if !selection.is_empty() && !line_mode {
7970 selection.goal = SelectionGoal::None;
7971 }
7972 let (cursor, goal) = movement::up_by_rows(
7973 map,
7974 selection.end,
7975 row_count,
7976 selection.goal,
7977 false,
7978 text_layout_details,
7979 );
7980 selection.collapse_to(cursor, goal);
7981 });
7982 });
7983 }
7984
7985 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
7986 let text_layout_details = &self.text_layout_details(window);
7987 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7988 s.move_heads_with(|map, head, goal| {
7989 movement::up(map, head, goal, false, text_layout_details)
7990 })
7991 })
7992 }
7993
7994 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
7995 self.take_rename(true, window, cx);
7996
7997 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7998 cx.propagate();
7999 return;
8000 }
8001
8002 let text_layout_details = &self.text_layout_details(window);
8003 let selection_count = self.selections.count();
8004 let first_selection = self.selections.first_anchor();
8005
8006 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8007 let line_mode = s.line_mode;
8008 s.move_with(|map, selection| {
8009 if !selection.is_empty() && !line_mode {
8010 selection.goal = SelectionGoal::None;
8011 }
8012 let (cursor, goal) = movement::down(
8013 map,
8014 selection.end,
8015 selection.goal,
8016 false,
8017 text_layout_details,
8018 );
8019 selection.collapse_to(cursor, goal);
8020 });
8021 });
8022
8023 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8024 {
8025 cx.propagate();
8026 }
8027 }
8028
8029 pub fn select_page_down(
8030 &mut self,
8031 _: &SelectPageDown,
8032 window: &mut Window,
8033 cx: &mut Context<Self>,
8034 ) {
8035 let Some(row_count) = self.visible_row_count() else {
8036 return;
8037 };
8038
8039 let text_layout_details = &self.text_layout_details(window);
8040
8041 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8042 s.move_heads_with(|map, head, goal| {
8043 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8044 })
8045 })
8046 }
8047
8048 pub fn move_page_down(
8049 &mut self,
8050 action: &MovePageDown,
8051 window: &mut Window,
8052 cx: &mut Context<Self>,
8053 ) {
8054 if self.take_rename(true, window, cx).is_some() {
8055 return;
8056 }
8057
8058 if self
8059 .context_menu
8060 .borrow_mut()
8061 .as_mut()
8062 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8063 .unwrap_or(false)
8064 {
8065 return;
8066 }
8067
8068 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8069 cx.propagate();
8070 return;
8071 }
8072
8073 let Some(row_count) = self.visible_row_count() else {
8074 return;
8075 };
8076
8077 let autoscroll = if action.center_cursor {
8078 Autoscroll::center()
8079 } else {
8080 Autoscroll::fit()
8081 };
8082
8083 let text_layout_details = &self.text_layout_details(window);
8084 self.change_selections(Some(autoscroll), window, cx, |s| {
8085 let line_mode = s.line_mode;
8086 s.move_with(|map, selection| {
8087 if !selection.is_empty() && !line_mode {
8088 selection.goal = SelectionGoal::None;
8089 }
8090 let (cursor, goal) = movement::down_by_rows(
8091 map,
8092 selection.end,
8093 row_count,
8094 selection.goal,
8095 false,
8096 text_layout_details,
8097 );
8098 selection.collapse_to(cursor, goal);
8099 });
8100 });
8101 }
8102
8103 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8104 let text_layout_details = &self.text_layout_details(window);
8105 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8106 s.move_heads_with(|map, head, goal| {
8107 movement::down(map, head, goal, false, text_layout_details)
8108 })
8109 });
8110 }
8111
8112 pub fn context_menu_first(
8113 &mut self,
8114 _: &ContextMenuFirst,
8115 _window: &mut Window,
8116 cx: &mut Context<Self>,
8117 ) {
8118 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8119 context_menu.select_first(self.completion_provider.as_deref(), cx);
8120 }
8121 }
8122
8123 pub fn context_menu_prev(
8124 &mut self,
8125 _: &ContextMenuPrev,
8126 _window: &mut Window,
8127 cx: &mut Context<Self>,
8128 ) {
8129 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8130 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8131 }
8132 }
8133
8134 pub fn context_menu_next(
8135 &mut self,
8136 _: &ContextMenuNext,
8137 _window: &mut Window,
8138 cx: &mut Context<Self>,
8139 ) {
8140 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8141 context_menu.select_next(self.completion_provider.as_deref(), cx);
8142 }
8143 }
8144
8145 pub fn context_menu_last(
8146 &mut self,
8147 _: &ContextMenuLast,
8148 _window: &mut Window,
8149 cx: &mut Context<Self>,
8150 ) {
8151 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8152 context_menu.select_last(self.completion_provider.as_deref(), cx);
8153 }
8154 }
8155
8156 pub fn move_to_previous_word_start(
8157 &mut self,
8158 _: &MoveToPreviousWordStart,
8159 window: &mut Window,
8160 cx: &mut Context<Self>,
8161 ) {
8162 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8163 s.move_cursors_with(|map, head, _| {
8164 (
8165 movement::previous_word_start(map, head),
8166 SelectionGoal::None,
8167 )
8168 });
8169 })
8170 }
8171
8172 pub fn move_to_previous_subword_start(
8173 &mut self,
8174 _: &MoveToPreviousSubwordStart,
8175 window: &mut Window,
8176 cx: &mut Context<Self>,
8177 ) {
8178 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8179 s.move_cursors_with(|map, head, _| {
8180 (
8181 movement::previous_subword_start(map, head),
8182 SelectionGoal::None,
8183 )
8184 });
8185 })
8186 }
8187
8188 pub fn select_to_previous_word_start(
8189 &mut self,
8190 _: &SelectToPreviousWordStart,
8191 window: &mut Window,
8192 cx: &mut Context<Self>,
8193 ) {
8194 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8195 s.move_heads_with(|map, head, _| {
8196 (
8197 movement::previous_word_start(map, head),
8198 SelectionGoal::None,
8199 )
8200 });
8201 })
8202 }
8203
8204 pub fn select_to_previous_subword_start(
8205 &mut self,
8206 _: &SelectToPreviousSubwordStart,
8207 window: &mut Window,
8208 cx: &mut Context<Self>,
8209 ) {
8210 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8211 s.move_heads_with(|map, head, _| {
8212 (
8213 movement::previous_subword_start(map, head),
8214 SelectionGoal::None,
8215 )
8216 });
8217 })
8218 }
8219
8220 pub fn delete_to_previous_word_start(
8221 &mut self,
8222 action: &DeleteToPreviousWordStart,
8223 window: &mut Window,
8224 cx: &mut Context<Self>,
8225 ) {
8226 self.transact(window, cx, |this, window, cx| {
8227 this.select_autoclose_pair(window, cx);
8228 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8229 let line_mode = s.line_mode;
8230 s.move_with(|map, selection| {
8231 if selection.is_empty() && !line_mode {
8232 let cursor = if action.ignore_newlines {
8233 movement::previous_word_start(map, selection.head())
8234 } else {
8235 movement::previous_word_start_or_newline(map, selection.head())
8236 };
8237 selection.set_head(cursor, SelectionGoal::None);
8238 }
8239 });
8240 });
8241 this.insert("", window, cx);
8242 });
8243 }
8244
8245 pub fn delete_to_previous_subword_start(
8246 &mut self,
8247 _: &DeleteToPreviousSubwordStart,
8248 window: &mut Window,
8249 cx: &mut Context<Self>,
8250 ) {
8251 self.transact(window, cx, |this, window, cx| {
8252 this.select_autoclose_pair(window, cx);
8253 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8254 let line_mode = s.line_mode;
8255 s.move_with(|map, selection| {
8256 if selection.is_empty() && !line_mode {
8257 let cursor = movement::previous_subword_start(map, selection.head());
8258 selection.set_head(cursor, SelectionGoal::None);
8259 }
8260 });
8261 });
8262 this.insert("", window, cx);
8263 });
8264 }
8265
8266 pub fn move_to_next_word_end(
8267 &mut self,
8268 _: &MoveToNextWordEnd,
8269 window: &mut Window,
8270 cx: &mut Context<Self>,
8271 ) {
8272 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8273 s.move_cursors_with(|map, head, _| {
8274 (movement::next_word_end(map, head), SelectionGoal::None)
8275 });
8276 })
8277 }
8278
8279 pub fn move_to_next_subword_end(
8280 &mut self,
8281 _: &MoveToNextSubwordEnd,
8282 window: &mut Window,
8283 cx: &mut Context<Self>,
8284 ) {
8285 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8286 s.move_cursors_with(|map, head, _| {
8287 (movement::next_subword_end(map, head), SelectionGoal::None)
8288 });
8289 })
8290 }
8291
8292 pub fn select_to_next_word_end(
8293 &mut self,
8294 _: &SelectToNextWordEnd,
8295 window: &mut Window,
8296 cx: &mut Context<Self>,
8297 ) {
8298 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8299 s.move_heads_with(|map, head, _| {
8300 (movement::next_word_end(map, head), SelectionGoal::None)
8301 });
8302 })
8303 }
8304
8305 pub fn select_to_next_subword_end(
8306 &mut self,
8307 _: &SelectToNextSubwordEnd,
8308 window: &mut Window,
8309 cx: &mut Context<Self>,
8310 ) {
8311 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8312 s.move_heads_with(|map, head, _| {
8313 (movement::next_subword_end(map, head), SelectionGoal::None)
8314 });
8315 })
8316 }
8317
8318 pub fn delete_to_next_word_end(
8319 &mut self,
8320 action: &DeleteToNextWordEnd,
8321 window: &mut Window,
8322 cx: &mut Context<Self>,
8323 ) {
8324 self.transact(window, cx, |this, window, cx| {
8325 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8326 let line_mode = s.line_mode;
8327 s.move_with(|map, selection| {
8328 if selection.is_empty() && !line_mode {
8329 let cursor = if action.ignore_newlines {
8330 movement::next_word_end(map, selection.head())
8331 } else {
8332 movement::next_word_end_or_newline(map, selection.head())
8333 };
8334 selection.set_head(cursor, SelectionGoal::None);
8335 }
8336 });
8337 });
8338 this.insert("", window, cx);
8339 });
8340 }
8341
8342 pub fn delete_to_next_subword_end(
8343 &mut self,
8344 _: &DeleteToNextSubwordEnd,
8345 window: &mut Window,
8346 cx: &mut Context<Self>,
8347 ) {
8348 self.transact(window, cx, |this, window, cx| {
8349 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8350 s.move_with(|map, selection| {
8351 if selection.is_empty() {
8352 let cursor = movement::next_subword_end(map, selection.head());
8353 selection.set_head(cursor, SelectionGoal::None);
8354 }
8355 });
8356 });
8357 this.insert("", window, cx);
8358 });
8359 }
8360
8361 pub fn move_to_beginning_of_line(
8362 &mut self,
8363 action: &MoveToBeginningOfLine,
8364 window: &mut Window,
8365 cx: &mut Context<Self>,
8366 ) {
8367 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8368 s.move_cursors_with(|map, head, _| {
8369 (
8370 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8371 SelectionGoal::None,
8372 )
8373 });
8374 })
8375 }
8376
8377 pub fn select_to_beginning_of_line(
8378 &mut self,
8379 action: &SelectToBeginningOfLine,
8380 window: &mut Window,
8381 cx: &mut Context<Self>,
8382 ) {
8383 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8384 s.move_heads_with(|map, head, _| {
8385 (
8386 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8387 SelectionGoal::None,
8388 )
8389 });
8390 });
8391 }
8392
8393 pub fn delete_to_beginning_of_line(
8394 &mut self,
8395 _: &DeleteToBeginningOfLine,
8396 window: &mut Window,
8397 cx: &mut Context<Self>,
8398 ) {
8399 self.transact(window, cx, |this, window, cx| {
8400 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8401 s.move_with(|_, selection| {
8402 selection.reversed = true;
8403 });
8404 });
8405
8406 this.select_to_beginning_of_line(
8407 &SelectToBeginningOfLine {
8408 stop_at_soft_wraps: false,
8409 },
8410 window,
8411 cx,
8412 );
8413 this.backspace(&Backspace, window, cx);
8414 });
8415 }
8416
8417 pub fn move_to_end_of_line(
8418 &mut self,
8419 action: &MoveToEndOfLine,
8420 window: &mut Window,
8421 cx: &mut Context<Self>,
8422 ) {
8423 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8424 s.move_cursors_with(|map, head, _| {
8425 (
8426 movement::line_end(map, head, action.stop_at_soft_wraps),
8427 SelectionGoal::None,
8428 )
8429 });
8430 })
8431 }
8432
8433 pub fn select_to_end_of_line(
8434 &mut self,
8435 action: &SelectToEndOfLine,
8436 window: &mut Window,
8437 cx: &mut Context<Self>,
8438 ) {
8439 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8440 s.move_heads_with(|map, head, _| {
8441 (
8442 movement::line_end(map, head, action.stop_at_soft_wraps),
8443 SelectionGoal::None,
8444 )
8445 });
8446 })
8447 }
8448
8449 pub fn delete_to_end_of_line(
8450 &mut self,
8451 _: &DeleteToEndOfLine,
8452 window: &mut Window,
8453 cx: &mut Context<Self>,
8454 ) {
8455 self.transact(window, cx, |this, window, cx| {
8456 this.select_to_end_of_line(
8457 &SelectToEndOfLine {
8458 stop_at_soft_wraps: false,
8459 },
8460 window,
8461 cx,
8462 );
8463 this.delete(&Delete, window, cx);
8464 });
8465 }
8466
8467 pub fn cut_to_end_of_line(
8468 &mut self,
8469 _: &CutToEndOfLine,
8470 window: &mut Window,
8471 cx: &mut Context<Self>,
8472 ) {
8473 self.transact(window, cx, |this, window, cx| {
8474 this.select_to_end_of_line(
8475 &SelectToEndOfLine {
8476 stop_at_soft_wraps: false,
8477 },
8478 window,
8479 cx,
8480 );
8481 this.cut(&Cut, window, cx);
8482 });
8483 }
8484
8485 pub fn move_to_start_of_paragraph(
8486 &mut self,
8487 _: &MoveToStartOfParagraph,
8488 window: &mut Window,
8489 cx: &mut Context<Self>,
8490 ) {
8491 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8492 cx.propagate();
8493 return;
8494 }
8495
8496 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8497 s.move_with(|map, selection| {
8498 selection.collapse_to(
8499 movement::start_of_paragraph(map, selection.head(), 1),
8500 SelectionGoal::None,
8501 )
8502 });
8503 })
8504 }
8505
8506 pub fn move_to_end_of_paragraph(
8507 &mut self,
8508 _: &MoveToEndOfParagraph,
8509 window: &mut Window,
8510 cx: &mut Context<Self>,
8511 ) {
8512 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8513 cx.propagate();
8514 return;
8515 }
8516
8517 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8518 s.move_with(|map, selection| {
8519 selection.collapse_to(
8520 movement::end_of_paragraph(map, selection.head(), 1),
8521 SelectionGoal::None,
8522 )
8523 });
8524 })
8525 }
8526
8527 pub fn select_to_start_of_paragraph(
8528 &mut self,
8529 _: &SelectToStartOfParagraph,
8530 window: &mut Window,
8531 cx: &mut Context<Self>,
8532 ) {
8533 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8534 cx.propagate();
8535 return;
8536 }
8537
8538 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8539 s.move_heads_with(|map, head, _| {
8540 (
8541 movement::start_of_paragraph(map, head, 1),
8542 SelectionGoal::None,
8543 )
8544 });
8545 })
8546 }
8547
8548 pub fn select_to_end_of_paragraph(
8549 &mut self,
8550 _: &SelectToEndOfParagraph,
8551 window: &mut Window,
8552 cx: &mut Context<Self>,
8553 ) {
8554 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8555 cx.propagate();
8556 return;
8557 }
8558
8559 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8560 s.move_heads_with(|map, head, _| {
8561 (
8562 movement::end_of_paragraph(map, head, 1),
8563 SelectionGoal::None,
8564 )
8565 });
8566 })
8567 }
8568
8569 pub fn move_to_beginning(
8570 &mut self,
8571 _: &MoveToBeginning,
8572 window: &mut Window,
8573 cx: &mut Context<Self>,
8574 ) {
8575 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8576 cx.propagate();
8577 return;
8578 }
8579
8580 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8581 s.select_ranges(vec![0..0]);
8582 });
8583 }
8584
8585 pub fn select_to_beginning(
8586 &mut self,
8587 _: &SelectToBeginning,
8588 window: &mut Window,
8589 cx: &mut Context<Self>,
8590 ) {
8591 let mut selection = self.selections.last::<Point>(cx);
8592 selection.set_head(Point::zero(), SelectionGoal::None);
8593
8594 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8595 s.select(vec![selection]);
8596 });
8597 }
8598
8599 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
8600 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8601 cx.propagate();
8602 return;
8603 }
8604
8605 let cursor = self.buffer.read(cx).read(cx).len();
8606 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8607 s.select_ranges(vec![cursor..cursor])
8608 });
8609 }
8610
8611 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8612 self.nav_history = nav_history;
8613 }
8614
8615 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8616 self.nav_history.as_ref()
8617 }
8618
8619 fn push_to_nav_history(
8620 &mut self,
8621 cursor_anchor: Anchor,
8622 new_position: Option<Point>,
8623 cx: &mut Context<Self>,
8624 ) {
8625 if let Some(nav_history) = self.nav_history.as_mut() {
8626 let buffer = self.buffer.read(cx).read(cx);
8627 let cursor_position = cursor_anchor.to_point(&buffer);
8628 let scroll_state = self.scroll_manager.anchor();
8629 let scroll_top_row = scroll_state.top_row(&buffer);
8630 drop(buffer);
8631
8632 if let Some(new_position) = new_position {
8633 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8634 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8635 return;
8636 }
8637 }
8638
8639 nav_history.push(
8640 Some(NavigationData {
8641 cursor_anchor,
8642 cursor_position,
8643 scroll_anchor: scroll_state,
8644 scroll_top_row,
8645 }),
8646 cx,
8647 );
8648 }
8649 }
8650
8651 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
8652 let buffer = self.buffer.read(cx).snapshot(cx);
8653 let mut selection = self.selections.first::<usize>(cx);
8654 selection.set_head(buffer.len(), SelectionGoal::None);
8655 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8656 s.select(vec![selection]);
8657 });
8658 }
8659
8660 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
8661 let end = self.buffer.read(cx).read(cx).len();
8662 self.change_selections(None, window, cx, |s| {
8663 s.select_ranges(vec![0..end]);
8664 });
8665 }
8666
8667 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
8668 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8669 let mut selections = self.selections.all::<Point>(cx);
8670 let max_point = display_map.buffer_snapshot.max_point();
8671 for selection in &mut selections {
8672 let rows = selection.spanned_rows(true, &display_map);
8673 selection.start = Point::new(rows.start.0, 0);
8674 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8675 selection.reversed = false;
8676 }
8677 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8678 s.select(selections);
8679 });
8680 }
8681
8682 pub fn split_selection_into_lines(
8683 &mut self,
8684 _: &SplitSelectionIntoLines,
8685 window: &mut Window,
8686 cx: &mut Context<Self>,
8687 ) {
8688 let mut to_unfold = Vec::new();
8689 let mut new_selection_ranges = Vec::new();
8690 {
8691 let selections = self.selections.all::<Point>(cx);
8692 let buffer = self.buffer.read(cx).read(cx);
8693 for selection in selections {
8694 for row in selection.start.row..selection.end.row {
8695 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8696 new_selection_ranges.push(cursor..cursor);
8697 }
8698 new_selection_ranges.push(selection.end..selection.end);
8699 to_unfold.push(selection.start..selection.end);
8700 }
8701 }
8702 self.unfold_ranges(&to_unfold, true, true, cx);
8703 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8704 s.select_ranges(new_selection_ranges);
8705 });
8706 }
8707
8708 pub fn add_selection_above(
8709 &mut self,
8710 _: &AddSelectionAbove,
8711 window: &mut Window,
8712 cx: &mut Context<Self>,
8713 ) {
8714 self.add_selection(true, window, cx);
8715 }
8716
8717 pub fn add_selection_below(
8718 &mut self,
8719 _: &AddSelectionBelow,
8720 window: &mut Window,
8721 cx: &mut Context<Self>,
8722 ) {
8723 self.add_selection(false, window, cx);
8724 }
8725
8726 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
8727 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8728 let mut selections = self.selections.all::<Point>(cx);
8729 let text_layout_details = self.text_layout_details(window);
8730 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8731 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8732 let range = oldest_selection.display_range(&display_map).sorted();
8733
8734 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8735 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8736 let positions = start_x.min(end_x)..start_x.max(end_x);
8737
8738 selections.clear();
8739 let mut stack = Vec::new();
8740 for row in range.start.row().0..=range.end.row().0 {
8741 if let Some(selection) = self.selections.build_columnar_selection(
8742 &display_map,
8743 DisplayRow(row),
8744 &positions,
8745 oldest_selection.reversed,
8746 &text_layout_details,
8747 ) {
8748 stack.push(selection.id);
8749 selections.push(selection);
8750 }
8751 }
8752
8753 if above {
8754 stack.reverse();
8755 }
8756
8757 AddSelectionsState { above, stack }
8758 });
8759
8760 let last_added_selection = *state.stack.last().unwrap();
8761 let mut new_selections = Vec::new();
8762 if above == state.above {
8763 let end_row = if above {
8764 DisplayRow(0)
8765 } else {
8766 display_map.max_point().row()
8767 };
8768
8769 'outer: for selection in selections {
8770 if selection.id == last_added_selection {
8771 let range = selection.display_range(&display_map).sorted();
8772 debug_assert_eq!(range.start.row(), range.end.row());
8773 let mut row = range.start.row();
8774 let positions =
8775 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8776 px(start)..px(end)
8777 } else {
8778 let start_x =
8779 display_map.x_for_display_point(range.start, &text_layout_details);
8780 let end_x =
8781 display_map.x_for_display_point(range.end, &text_layout_details);
8782 start_x.min(end_x)..start_x.max(end_x)
8783 };
8784
8785 while row != end_row {
8786 if above {
8787 row.0 -= 1;
8788 } else {
8789 row.0 += 1;
8790 }
8791
8792 if let Some(new_selection) = self.selections.build_columnar_selection(
8793 &display_map,
8794 row,
8795 &positions,
8796 selection.reversed,
8797 &text_layout_details,
8798 ) {
8799 state.stack.push(new_selection.id);
8800 if above {
8801 new_selections.push(new_selection);
8802 new_selections.push(selection);
8803 } else {
8804 new_selections.push(selection);
8805 new_selections.push(new_selection);
8806 }
8807
8808 continue 'outer;
8809 }
8810 }
8811 }
8812
8813 new_selections.push(selection);
8814 }
8815 } else {
8816 new_selections = selections;
8817 new_selections.retain(|s| s.id != last_added_selection);
8818 state.stack.pop();
8819 }
8820
8821 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8822 s.select(new_selections);
8823 });
8824 if state.stack.len() > 1 {
8825 self.add_selections_state = Some(state);
8826 }
8827 }
8828
8829 pub fn select_next_match_internal(
8830 &mut self,
8831 display_map: &DisplaySnapshot,
8832 replace_newest: bool,
8833 autoscroll: Option<Autoscroll>,
8834 window: &mut Window,
8835 cx: &mut Context<Self>,
8836 ) -> Result<()> {
8837 fn select_next_match_ranges(
8838 this: &mut Editor,
8839 range: Range<usize>,
8840 replace_newest: bool,
8841 auto_scroll: Option<Autoscroll>,
8842 window: &mut Window,
8843 cx: &mut Context<Editor>,
8844 ) {
8845 this.unfold_ranges(&[range.clone()], false, true, cx);
8846 this.change_selections(auto_scroll, window, cx, |s| {
8847 if replace_newest {
8848 s.delete(s.newest_anchor().id);
8849 }
8850 s.insert_range(range.clone());
8851 });
8852 }
8853
8854 let buffer = &display_map.buffer_snapshot;
8855 let mut selections = self.selections.all::<usize>(cx);
8856 if let Some(mut select_next_state) = self.select_next_state.take() {
8857 let query = &select_next_state.query;
8858 if !select_next_state.done {
8859 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8860 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8861 let mut next_selected_range = None;
8862
8863 let bytes_after_last_selection =
8864 buffer.bytes_in_range(last_selection.end..buffer.len());
8865 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8866 let query_matches = query
8867 .stream_find_iter(bytes_after_last_selection)
8868 .map(|result| (last_selection.end, result))
8869 .chain(
8870 query
8871 .stream_find_iter(bytes_before_first_selection)
8872 .map(|result| (0, result)),
8873 );
8874
8875 for (start_offset, query_match) in query_matches {
8876 let query_match = query_match.unwrap(); // can only fail due to I/O
8877 let offset_range =
8878 start_offset + query_match.start()..start_offset + query_match.end();
8879 let display_range = offset_range.start.to_display_point(display_map)
8880 ..offset_range.end.to_display_point(display_map);
8881
8882 if !select_next_state.wordwise
8883 || (!movement::is_inside_word(display_map, display_range.start)
8884 && !movement::is_inside_word(display_map, display_range.end))
8885 {
8886 // TODO: This is n^2, because we might check all the selections
8887 if !selections
8888 .iter()
8889 .any(|selection| selection.range().overlaps(&offset_range))
8890 {
8891 next_selected_range = Some(offset_range);
8892 break;
8893 }
8894 }
8895 }
8896
8897 if let Some(next_selected_range) = next_selected_range {
8898 select_next_match_ranges(
8899 self,
8900 next_selected_range,
8901 replace_newest,
8902 autoscroll,
8903 window,
8904 cx,
8905 );
8906 } else {
8907 select_next_state.done = true;
8908 }
8909 }
8910
8911 self.select_next_state = Some(select_next_state);
8912 } else {
8913 let mut only_carets = true;
8914 let mut same_text_selected = true;
8915 let mut selected_text = None;
8916
8917 let mut selections_iter = selections.iter().peekable();
8918 while let Some(selection) = selections_iter.next() {
8919 if selection.start != selection.end {
8920 only_carets = false;
8921 }
8922
8923 if same_text_selected {
8924 if selected_text.is_none() {
8925 selected_text =
8926 Some(buffer.text_for_range(selection.range()).collect::<String>());
8927 }
8928
8929 if let Some(next_selection) = selections_iter.peek() {
8930 if next_selection.range().len() == selection.range().len() {
8931 let next_selected_text = buffer
8932 .text_for_range(next_selection.range())
8933 .collect::<String>();
8934 if Some(next_selected_text) != selected_text {
8935 same_text_selected = false;
8936 selected_text = None;
8937 }
8938 } else {
8939 same_text_selected = false;
8940 selected_text = None;
8941 }
8942 }
8943 }
8944 }
8945
8946 if only_carets {
8947 for selection in &mut selections {
8948 let word_range = movement::surrounding_word(
8949 display_map,
8950 selection.start.to_display_point(display_map),
8951 );
8952 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8953 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8954 selection.goal = SelectionGoal::None;
8955 selection.reversed = false;
8956 select_next_match_ranges(
8957 self,
8958 selection.start..selection.end,
8959 replace_newest,
8960 autoscroll,
8961 window,
8962 cx,
8963 );
8964 }
8965
8966 if selections.len() == 1 {
8967 let selection = selections
8968 .last()
8969 .expect("ensured that there's only one selection");
8970 let query = buffer
8971 .text_for_range(selection.start..selection.end)
8972 .collect::<String>();
8973 let is_empty = query.is_empty();
8974 let select_state = SelectNextState {
8975 query: AhoCorasick::new(&[query])?,
8976 wordwise: true,
8977 done: is_empty,
8978 };
8979 self.select_next_state = Some(select_state);
8980 } else {
8981 self.select_next_state = None;
8982 }
8983 } else if let Some(selected_text) = selected_text {
8984 self.select_next_state = Some(SelectNextState {
8985 query: AhoCorasick::new(&[selected_text])?,
8986 wordwise: false,
8987 done: false,
8988 });
8989 self.select_next_match_internal(
8990 display_map,
8991 replace_newest,
8992 autoscroll,
8993 window,
8994 cx,
8995 )?;
8996 }
8997 }
8998 Ok(())
8999 }
9000
9001 pub fn select_all_matches(
9002 &mut self,
9003 _action: &SelectAllMatches,
9004 window: &mut Window,
9005 cx: &mut Context<Self>,
9006 ) -> Result<()> {
9007 self.push_to_selection_history();
9008 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9009
9010 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9011 let Some(select_next_state) = self.select_next_state.as_mut() else {
9012 return Ok(());
9013 };
9014 if select_next_state.done {
9015 return Ok(());
9016 }
9017
9018 let mut new_selections = self.selections.all::<usize>(cx);
9019
9020 let buffer = &display_map.buffer_snapshot;
9021 let query_matches = select_next_state
9022 .query
9023 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9024
9025 for query_match in query_matches {
9026 let query_match = query_match.unwrap(); // can only fail due to I/O
9027 let offset_range = query_match.start()..query_match.end();
9028 let display_range = offset_range.start.to_display_point(&display_map)
9029 ..offset_range.end.to_display_point(&display_map);
9030
9031 if !select_next_state.wordwise
9032 || (!movement::is_inside_word(&display_map, display_range.start)
9033 && !movement::is_inside_word(&display_map, display_range.end))
9034 {
9035 self.selections.change_with(cx, |selections| {
9036 new_selections.push(Selection {
9037 id: selections.new_selection_id(),
9038 start: offset_range.start,
9039 end: offset_range.end,
9040 reversed: false,
9041 goal: SelectionGoal::None,
9042 });
9043 });
9044 }
9045 }
9046
9047 new_selections.sort_by_key(|selection| selection.start);
9048 let mut ix = 0;
9049 while ix + 1 < new_selections.len() {
9050 let current_selection = &new_selections[ix];
9051 let next_selection = &new_selections[ix + 1];
9052 if current_selection.range().overlaps(&next_selection.range()) {
9053 if current_selection.id < next_selection.id {
9054 new_selections.remove(ix + 1);
9055 } else {
9056 new_selections.remove(ix);
9057 }
9058 } else {
9059 ix += 1;
9060 }
9061 }
9062
9063 let reversed = self.selections.oldest::<usize>(cx).reversed;
9064
9065 for selection in new_selections.iter_mut() {
9066 selection.reversed = reversed;
9067 }
9068
9069 select_next_state.done = true;
9070 self.unfold_ranges(
9071 &new_selections
9072 .iter()
9073 .map(|selection| selection.range())
9074 .collect::<Vec<_>>(),
9075 false,
9076 false,
9077 cx,
9078 );
9079 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9080 selections.select(new_selections)
9081 });
9082
9083 Ok(())
9084 }
9085
9086 pub fn select_next(
9087 &mut self,
9088 action: &SelectNext,
9089 window: &mut Window,
9090 cx: &mut Context<Self>,
9091 ) -> Result<()> {
9092 self.push_to_selection_history();
9093 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9094 self.select_next_match_internal(
9095 &display_map,
9096 action.replace_newest,
9097 Some(Autoscroll::newest()),
9098 window,
9099 cx,
9100 )?;
9101 Ok(())
9102 }
9103
9104 pub fn select_previous(
9105 &mut self,
9106 action: &SelectPrevious,
9107 window: &mut Window,
9108 cx: &mut Context<Self>,
9109 ) -> Result<()> {
9110 self.push_to_selection_history();
9111 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9112 let buffer = &display_map.buffer_snapshot;
9113 let mut selections = self.selections.all::<usize>(cx);
9114 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9115 let query = &select_prev_state.query;
9116 if !select_prev_state.done {
9117 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9118 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9119 let mut next_selected_range = None;
9120 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9121 let bytes_before_last_selection =
9122 buffer.reversed_bytes_in_range(0..last_selection.start);
9123 let bytes_after_first_selection =
9124 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9125 let query_matches = query
9126 .stream_find_iter(bytes_before_last_selection)
9127 .map(|result| (last_selection.start, result))
9128 .chain(
9129 query
9130 .stream_find_iter(bytes_after_first_selection)
9131 .map(|result| (buffer.len(), result)),
9132 );
9133 for (end_offset, query_match) in query_matches {
9134 let query_match = query_match.unwrap(); // can only fail due to I/O
9135 let offset_range =
9136 end_offset - query_match.end()..end_offset - query_match.start();
9137 let display_range = offset_range.start.to_display_point(&display_map)
9138 ..offset_range.end.to_display_point(&display_map);
9139
9140 if !select_prev_state.wordwise
9141 || (!movement::is_inside_word(&display_map, display_range.start)
9142 && !movement::is_inside_word(&display_map, display_range.end))
9143 {
9144 next_selected_range = Some(offset_range);
9145 break;
9146 }
9147 }
9148
9149 if let Some(next_selected_range) = next_selected_range {
9150 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9151 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9152 if action.replace_newest {
9153 s.delete(s.newest_anchor().id);
9154 }
9155 s.insert_range(next_selected_range);
9156 });
9157 } else {
9158 select_prev_state.done = true;
9159 }
9160 }
9161
9162 self.select_prev_state = Some(select_prev_state);
9163 } else {
9164 let mut only_carets = true;
9165 let mut same_text_selected = true;
9166 let mut selected_text = None;
9167
9168 let mut selections_iter = selections.iter().peekable();
9169 while let Some(selection) = selections_iter.next() {
9170 if selection.start != selection.end {
9171 only_carets = false;
9172 }
9173
9174 if same_text_selected {
9175 if selected_text.is_none() {
9176 selected_text =
9177 Some(buffer.text_for_range(selection.range()).collect::<String>());
9178 }
9179
9180 if let Some(next_selection) = selections_iter.peek() {
9181 if next_selection.range().len() == selection.range().len() {
9182 let next_selected_text = buffer
9183 .text_for_range(next_selection.range())
9184 .collect::<String>();
9185 if Some(next_selected_text) != selected_text {
9186 same_text_selected = false;
9187 selected_text = None;
9188 }
9189 } else {
9190 same_text_selected = false;
9191 selected_text = None;
9192 }
9193 }
9194 }
9195 }
9196
9197 if only_carets {
9198 for selection in &mut selections {
9199 let word_range = movement::surrounding_word(
9200 &display_map,
9201 selection.start.to_display_point(&display_map),
9202 );
9203 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9204 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9205 selection.goal = SelectionGoal::None;
9206 selection.reversed = false;
9207 }
9208 if selections.len() == 1 {
9209 let selection = selections
9210 .last()
9211 .expect("ensured that there's only one selection");
9212 let query = buffer
9213 .text_for_range(selection.start..selection.end)
9214 .collect::<String>();
9215 let is_empty = query.is_empty();
9216 let select_state = SelectNextState {
9217 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9218 wordwise: true,
9219 done: is_empty,
9220 };
9221 self.select_prev_state = Some(select_state);
9222 } else {
9223 self.select_prev_state = None;
9224 }
9225
9226 self.unfold_ranges(
9227 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9228 false,
9229 true,
9230 cx,
9231 );
9232 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9233 s.select(selections);
9234 });
9235 } else if let Some(selected_text) = selected_text {
9236 self.select_prev_state = Some(SelectNextState {
9237 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9238 wordwise: false,
9239 done: false,
9240 });
9241 self.select_previous(action, window, cx)?;
9242 }
9243 }
9244 Ok(())
9245 }
9246
9247 pub fn toggle_comments(
9248 &mut self,
9249 action: &ToggleComments,
9250 window: &mut Window,
9251 cx: &mut Context<Self>,
9252 ) {
9253 if self.read_only(cx) {
9254 return;
9255 }
9256 let text_layout_details = &self.text_layout_details(window);
9257 self.transact(window, cx, |this, window, cx| {
9258 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9259 let mut edits = Vec::new();
9260 let mut selection_edit_ranges = Vec::new();
9261 let mut last_toggled_row = None;
9262 let snapshot = this.buffer.read(cx).read(cx);
9263 let empty_str: Arc<str> = Arc::default();
9264 let mut suffixes_inserted = Vec::new();
9265 let ignore_indent = action.ignore_indent;
9266
9267 fn comment_prefix_range(
9268 snapshot: &MultiBufferSnapshot,
9269 row: MultiBufferRow,
9270 comment_prefix: &str,
9271 comment_prefix_whitespace: &str,
9272 ignore_indent: bool,
9273 ) -> Range<Point> {
9274 let indent_size = if ignore_indent {
9275 0
9276 } else {
9277 snapshot.indent_size_for_line(row).len
9278 };
9279
9280 let start = Point::new(row.0, indent_size);
9281
9282 let mut line_bytes = snapshot
9283 .bytes_in_range(start..snapshot.max_point())
9284 .flatten()
9285 .copied();
9286
9287 // If this line currently begins with the line comment prefix, then record
9288 // the range containing the prefix.
9289 if line_bytes
9290 .by_ref()
9291 .take(comment_prefix.len())
9292 .eq(comment_prefix.bytes())
9293 {
9294 // Include any whitespace that matches the comment prefix.
9295 let matching_whitespace_len = line_bytes
9296 .zip(comment_prefix_whitespace.bytes())
9297 .take_while(|(a, b)| a == b)
9298 .count() as u32;
9299 let end = Point::new(
9300 start.row,
9301 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9302 );
9303 start..end
9304 } else {
9305 start..start
9306 }
9307 }
9308
9309 fn comment_suffix_range(
9310 snapshot: &MultiBufferSnapshot,
9311 row: MultiBufferRow,
9312 comment_suffix: &str,
9313 comment_suffix_has_leading_space: bool,
9314 ) -> Range<Point> {
9315 let end = Point::new(row.0, snapshot.line_len(row));
9316 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9317
9318 let mut line_end_bytes = snapshot
9319 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9320 .flatten()
9321 .copied();
9322
9323 let leading_space_len = if suffix_start_column > 0
9324 && line_end_bytes.next() == Some(b' ')
9325 && comment_suffix_has_leading_space
9326 {
9327 1
9328 } else {
9329 0
9330 };
9331
9332 // If this line currently begins with the line comment prefix, then record
9333 // the range containing the prefix.
9334 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9335 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9336 start..end
9337 } else {
9338 end..end
9339 }
9340 }
9341
9342 // TODO: Handle selections that cross excerpts
9343 for selection in &mut selections {
9344 let start_column = snapshot
9345 .indent_size_for_line(MultiBufferRow(selection.start.row))
9346 .len;
9347 let language = if let Some(language) =
9348 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9349 {
9350 language
9351 } else {
9352 continue;
9353 };
9354
9355 selection_edit_ranges.clear();
9356
9357 // If multiple selections contain a given row, avoid processing that
9358 // row more than once.
9359 let mut start_row = MultiBufferRow(selection.start.row);
9360 if last_toggled_row == Some(start_row) {
9361 start_row = start_row.next_row();
9362 }
9363 let end_row =
9364 if selection.end.row > selection.start.row && selection.end.column == 0 {
9365 MultiBufferRow(selection.end.row - 1)
9366 } else {
9367 MultiBufferRow(selection.end.row)
9368 };
9369 last_toggled_row = Some(end_row);
9370
9371 if start_row > end_row {
9372 continue;
9373 }
9374
9375 // If the language has line comments, toggle those.
9376 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9377
9378 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9379 if ignore_indent {
9380 full_comment_prefixes = full_comment_prefixes
9381 .into_iter()
9382 .map(|s| Arc::from(s.trim_end()))
9383 .collect();
9384 }
9385
9386 if !full_comment_prefixes.is_empty() {
9387 let first_prefix = full_comment_prefixes
9388 .first()
9389 .expect("prefixes is non-empty");
9390 let prefix_trimmed_lengths = full_comment_prefixes
9391 .iter()
9392 .map(|p| p.trim_end_matches(' ').len())
9393 .collect::<SmallVec<[usize; 4]>>();
9394
9395 let mut all_selection_lines_are_comments = true;
9396
9397 for row in start_row.0..=end_row.0 {
9398 let row = MultiBufferRow(row);
9399 if start_row < end_row && snapshot.is_line_blank(row) {
9400 continue;
9401 }
9402
9403 let prefix_range = full_comment_prefixes
9404 .iter()
9405 .zip(prefix_trimmed_lengths.iter().copied())
9406 .map(|(prefix, trimmed_prefix_len)| {
9407 comment_prefix_range(
9408 snapshot.deref(),
9409 row,
9410 &prefix[..trimmed_prefix_len],
9411 &prefix[trimmed_prefix_len..],
9412 ignore_indent,
9413 )
9414 })
9415 .max_by_key(|range| range.end.column - range.start.column)
9416 .expect("prefixes is non-empty");
9417
9418 if prefix_range.is_empty() {
9419 all_selection_lines_are_comments = false;
9420 }
9421
9422 selection_edit_ranges.push(prefix_range);
9423 }
9424
9425 if all_selection_lines_are_comments {
9426 edits.extend(
9427 selection_edit_ranges
9428 .iter()
9429 .cloned()
9430 .map(|range| (range, empty_str.clone())),
9431 );
9432 } else {
9433 let min_column = selection_edit_ranges
9434 .iter()
9435 .map(|range| range.start.column)
9436 .min()
9437 .unwrap_or(0);
9438 edits.extend(selection_edit_ranges.iter().map(|range| {
9439 let position = Point::new(range.start.row, min_column);
9440 (position..position, first_prefix.clone())
9441 }));
9442 }
9443 } else if let Some((full_comment_prefix, comment_suffix)) =
9444 language.block_comment_delimiters()
9445 {
9446 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9447 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9448 let prefix_range = comment_prefix_range(
9449 snapshot.deref(),
9450 start_row,
9451 comment_prefix,
9452 comment_prefix_whitespace,
9453 ignore_indent,
9454 );
9455 let suffix_range = comment_suffix_range(
9456 snapshot.deref(),
9457 end_row,
9458 comment_suffix.trim_start_matches(' '),
9459 comment_suffix.starts_with(' '),
9460 );
9461
9462 if prefix_range.is_empty() || suffix_range.is_empty() {
9463 edits.push((
9464 prefix_range.start..prefix_range.start,
9465 full_comment_prefix.clone(),
9466 ));
9467 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9468 suffixes_inserted.push((end_row, comment_suffix.len()));
9469 } else {
9470 edits.push((prefix_range, empty_str.clone()));
9471 edits.push((suffix_range, empty_str.clone()));
9472 }
9473 } else {
9474 continue;
9475 }
9476 }
9477
9478 drop(snapshot);
9479 this.buffer.update(cx, |buffer, cx| {
9480 buffer.edit(edits, None, cx);
9481 });
9482
9483 // Adjust selections so that they end before any comment suffixes that
9484 // were inserted.
9485 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9486 let mut selections = this.selections.all::<Point>(cx);
9487 let snapshot = this.buffer.read(cx).read(cx);
9488 for selection in &mut selections {
9489 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9490 match row.cmp(&MultiBufferRow(selection.end.row)) {
9491 Ordering::Less => {
9492 suffixes_inserted.next();
9493 continue;
9494 }
9495 Ordering::Greater => break,
9496 Ordering::Equal => {
9497 if selection.end.column == snapshot.line_len(row) {
9498 if selection.is_empty() {
9499 selection.start.column -= suffix_len as u32;
9500 }
9501 selection.end.column -= suffix_len as u32;
9502 }
9503 break;
9504 }
9505 }
9506 }
9507 }
9508
9509 drop(snapshot);
9510 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9511 s.select(selections)
9512 });
9513
9514 let selections = this.selections.all::<Point>(cx);
9515 let selections_on_single_row = selections.windows(2).all(|selections| {
9516 selections[0].start.row == selections[1].start.row
9517 && selections[0].end.row == selections[1].end.row
9518 && selections[0].start.row == selections[0].end.row
9519 });
9520 let selections_selecting = selections
9521 .iter()
9522 .any(|selection| selection.start != selection.end);
9523 let advance_downwards = action.advance_downwards
9524 && selections_on_single_row
9525 && !selections_selecting
9526 && !matches!(this.mode, EditorMode::SingleLine { .. });
9527
9528 if advance_downwards {
9529 let snapshot = this.buffer.read(cx).snapshot(cx);
9530
9531 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9532 s.move_cursors_with(|display_snapshot, display_point, _| {
9533 let mut point = display_point.to_point(display_snapshot);
9534 point.row += 1;
9535 point = snapshot.clip_point(point, Bias::Left);
9536 let display_point = point.to_display_point(display_snapshot);
9537 let goal = SelectionGoal::HorizontalPosition(
9538 display_snapshot
9539 .x_for_display_point(display_point, text_layout_details)
9540 .into(),
9541 );
9542 (display_point, goal)
9543 })
9544 });
9545 }
9546 });
9547 }
9548
9549 pub fn select_enclosing_symbol(
9550 &mut self,
9551 _: &SelectEnclosingSymbol,
9552 window: &mut Window,
9553 cx: &mut Context<Self>,
9554 ) {
9555 let buffer = self.buffer.read(cx).snapshot(cx);
9556 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9557
9558 fn update_selection(
9559 selection: &Selection<usize>,
9560 buffer_snap: &MultiBufferSnapshot,
9561 ) -> Option<Selection<usize>> {
9562 let cursor = selection.head();
9563 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9564 for symbol in symbols.iter().rev() {
9565 let start = symbol.range.start.to_offset(buffer_snap);
9566 let end = symbol.range.end.to_offset(buffer_snap);
9567 let new_range = start..end;
9568 if start < selection.start || end > selection.end {
9569 return Some(Selection {
9570 id: selection.id,
9571 start: new_range.start,
9572 end: new_range.end,
9573 goal: SelectionGoal::None,
9574 reversed: selection.reversed,
9575 });
9576 }
9577 }
9578 None
9579 }
9580
9581 let mut selected_larger_symbol = false;
9582 let new_selections = old_selections
9583 .iter()
9584 .map(|selection| match update_selection(selection, &buffer) {
9585 Some(new_selection) => {
9586 if new_selection.range() != selection.range() {
9587 selected_larger_symbol = true;
9588 }
9589 new_selection
9590 }
9591 None => selection.clone(),
9592 })
9593 .collect::<Vec<_>>();
9594
9595 if selected_larger_symbol {
9596 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9597 s.select(new_selections);
9598 });
9599 }
9600 }
9601
9602 pub fn select_larger_syntax_node(
9603 &mut self,
9604 _: &SelectLargerSyntaxNode,
9605 window: &mut Window,
9606 cx: &mut Context<Self>,
9607 ) {
9608 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9609 let buffer = self.buffer.read(cx).snapshot(cx);
9610 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9611
9612 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9613 let mut selected_larger_node = false;
9614 let new_selections = old_selections
9615 .iter()
9616 .map(|selection| {
9617 let old_range = selection.start..selection.end;
9618 let mut new_range = old_range.clone();
9619 let mut new_node = None;
9620 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
9621 {
9622 new_node = Some(node);
9623 new_range = containing_range;
9624 if !display_map.intersects_fold(new_range.start)
9625 && !display_map.intersects_fold(new_range.end)
9626 {
9627 break;
9628 }
9629 }
9630
9631 if let Some(node) = new_node {
9632 // Log the ancestor, to support using this action as a way to explore TreeSitter
9633 // nodes. Parent and grandparent are also logged because this operation will not
9634 // visit nodes that have the same range as their parent.
9635 log::info!("Node: {node:?}");
9636 let parent = node.parent();
9637 log::info!("Parent: {parent:?}");
9638 let grandparent = parent.and_then(|x| x.parent());
9639 log::info!("Grandparent: {grandparent:?}");
9640 }
9641
9642 selected_larger_node |= new_range != old_range;
9643 Selection {
9644 id: selection.id,
9645 start: new_range.start,
9646 end: new_range.end,
9647 goal: SelectionGoal::None,
9648 reversed: selection.reversed,
9649 }
9650 })
9651 .collect::<Vec<_>>();
9652
9653 if selected_larger_node {
9654 stack.push(old_selections);
9655 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9656 s.select(new_selections);
9657 });
9658 }
9659 self.select_larger_syntax_node_stack = stack;
9660 }
9661
9662 pub fn select_smaller_syntax_node(
9663 &mut self,
9664 _: &SelectSmallerSyntaxNode,
9665 window: &mut Window,
9666 cx: &mut Context<Self>,
9667 ) {
9668 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9669 if let Some(selections) = stack.pop() {
9670 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9671 s.select(selections.to_vec());
9672 });
9673 }
9674 self.select_larger_syntax_node_stack = stack;
9675 }
9676
9677 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
9678 if !EditorSettings::get_global(cx).gutter.runnables {
9679 self.clear_tasks();
9680 return Task::ready(());
9681 }
9682 let project = self.project.as_ref().map(Entity::downgrade);
9683 cx.spawn_in(window, |this, mut cx| async move {
9684 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
9685 let Some(project) = project.and_then(|p| p.upgrade()) else {
9686 return;
9687 };
9688 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9689 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9690 }) else {
9691 return;
9692 };
9693
9694 let hide_runnables = project
9695 .update(&mut cx, |project, cx| {
9696 // Do not display any test indicators in non-dev server remote projects.
9697 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9698 })
9699 .unwrap_or(true);
9700 if hide_runnables {
9701 return;
9702 }
9703 let new_rows =
9704 cx.background_executor()
9705 .spawn({
9706 let snapshot = display_snapshot.clone();
9707 async move {
9708 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9709 }
9710 })
9711 .await;
9712
9713 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9714 this.update(&mut cx, |this, _| {
9715 this.clear_tasks();
9716 for (key, value) in rows {
9717 this.insert_tasks(key, value);
9718 }
9719 })
9720 .ok();
9721 })
9722 }
9723 fn fetch_runnable_ranges(
9724 snapshot: &DisplaySnapshot,
9725 range: Range<Anchor>,
9726 ) -> Vec<language::RunnableRange> {
9727 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9728 }
9729
9730 fn runnable_rows(
9731 project: Entity<Project>,
9732 snapshot: DisplaySnapshot,
9733 runnable_ranges: Vec<RunnableRange>,
9734 mut cx: AsyncWindowContext,
9735 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9736 runnable_ranges
9737 .into_iter()
9738 .filter_map(|mut runnable| {
9739 let tasks = cx
9740 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9741 .ok()?;
9742 if tasks.is_empty() {
9743 return None;
9744 }
9745
9746 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9747
9748 let row = snapshot
9749 .buffer_snapshot
9750 .buffer_line_for_row(MultiBufferRow(point.row))?
9751 .1
9752 .start
9753 .row;
9754
9755 let context_range =
9756 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9757 Some((
9758 (runnable.buffer_id, row),
9759 RunnableTasks {
9760 templates: tasks,
9761 offset: MultiBufferOffset(runnable.run_range.start),
9762 context_range,
9763 column: point.column,
9764 extra_variables: runnable.extra_captures,
9765 },
9766 ))
9767 })
9768 .collect()
9769 }
9770
9771 fn templates_with_tags(
9772 project: &Entity<Project>,
9773 runnable: &mut Runnable,
9774 cx: &mut App,
9775 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9776 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9777 let (worktree_id, file) = project
9778 .buffer_for_id(runnable.buffer, cx)
9779 .and_then(|buffer| buffer.read(cx).file())
9780 .map(|file| (file.worktree_id(cx), file.clone()))
9781 .unzip();
9782
9783 (
9784 project.task_store().read(cx).task_inventory().cloned(),
9785 worktree_id,
9786 file,
9787 )
9788 });
9789
9790 let tags = mem::take(&mut runnable.tags);
9791 let mut tags: Vec<_> = tags
9792 .into_iter()
9793 .flat_map(|tag| {
9794 let tag = tag.0.clone();
9795 inventory
9796 .as_ref()
9797 .into_iter()
9798 .flat_map(|inventory| {
9799 inventory.read(cx).list_tasks(
9800 file.clone(),
9801 Some(runnable.language.clone()),
9802 worktree_id,
9803 cx,
9804 )
9805 })
9806 .filter(move |(_, template)| {
9807 template.tags.iter().any(|source_tag| source_tag == &tag)
9808 })
9809 })
9810 .sorted_by_key(|(kind, _)| kind.to_owned())
9811 .collect();
9812 if let Some((leading_tag_source, _)) = tags.first() {
9813 // Strongest source wins; if we have worktree tag binding, prefer that to
9814 // global and language bindings;
9815 // if we have a global binding, prefer that to language binding.
9816 let first_mismatch = tags
9817 .iter()
9818 .position(|(tag_source, _)| tag_source != leading_tag_source);
9819 if let Some(index) = first_mismatch {
9820 tags.truncate(index);
9821 }
9822 }
9823
9824 tags
9825 }
9826
9827 pub fn move_to_enclosing_bracket(
9828 &mut self,
9829 _: &MoveToEnclosingBracket,
9830 window: &mut Window,
9831 cx: &mut Context<Self>,
9832 ) {
9833 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9834 s.move_offsets_with(|snapshot, selection| {
9835 let Some(enclosing_bracket_ranges) =
9836 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9837 else {
9838 return;
9839 };
9840
9841 let mut best_length = usize::MAX;
9842 let mut best_inside = false;
9843 let mut best_in_bracket_range = false;
9844 let mut best_destination = None;
9845 for (open, close) in enclosing_bracket_ranges {
9846 let close = close.to_inclusive();
9847 let length = close.end() - open.start;
9848 let inside = selection.start >= open.end && selection.end <= *close.start();
9849 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9850 || close.contains(&selection.head());
9851
9852 // If best is next to a bracket and current isn't, skip
9853 if !in_bracket_range && best_in_bracket_range {
9854 continue;
9855 }
9856
9857 // Prefer smaller lengths unless best is inside and current isn't
9858 if length > best_length && (best_inside || !inside) {
9859 continue;
9860 }
9861
9862 best_length = length;
9863 best_inside = inside;
9864 best_in_bracket_range = in_bracket_range;
9865 best_destination = Some(
9866 if close.contains(&selection.start) && close.contains(&selection.end) {
9867 if inside {
9868 open.end
9869 } else {
9870 open.start
9871 }
9872 } else if inside {
9873 *close.start()
9874 } else {
9875 *close.end()
9876 },
9877 );
9878 }
9879
9880 if let Some(destination) = best_destination {
9881 selection.collapse_to(destination, SelectionGoal::None);
9882 }
9883 })
9884 });
9885 }
9886
9887 pub fn undo_selection(
9888 &mut self,
9889 _: &UndoSelection,
9890 window: &mut Window,
9891 cx: &mut Context<Self>,
9892 ) {
9893 self.end_selection(window, cx);
9894 self.selection_history.mode = SelectionHistoryMode::Undoing;
9895 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9896 self.change_selections(None, window, cx, |s| {
9897 s.select_anchors(entry.selections.to_vec())
9898 });
9899 self.select_next_state = entry.select_next_state;
9900 self.select_prev_state = entry.select_prev_state;
9901 self.add_selections_state = entry.add_selections_state;
9902 self.request_autoscroll(Autoscroll::newest(), cx);
9903 }
9904 self.selection_history.mode = SelectionHistoryMode::Normal;
9905 }
9906
9907 pub fn redo_selection(
9908 &mut self,
9909 _: &RedoSelection,
9910 window: &mut Window,
9911 cx: &mut Context<Self>,
9912 ) {
9913 self.end_selection(window, cx);
9914 self.selection_history.mode = SelectionHistoryMode::Redoing;
9915 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9916 self.change_selections(None, window, cx, |s| {
9917 s.select_anchors(entry.selections.to_vec())
9918 });
9919 self.select_next_state = entry.select_next_state;
9920 self.select_prev_state = entry.select_prev_state;
9921 self.add_selections_state = entry.add_selections_state;
9922 self.request_autoscroll(Autoscroll::newest(), cx);
9923 }
9924 self.selection_history.mode = SelectionHistoryMode::Normal;
9925 }
9926
9927 pub fn expand_excerpts(
9928 &mut self,
9929 action: &ExpandExcerpts,
9930 _: &mut Window,
9931 cx: &mut Context<Self>,
9932 ) {
9933 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9934 }
9935
9936 pub fn expand_excerpts_down(
9937 &mut self,
9938 action: &ExpandExcerptsDown,
9939 _: &mut Window,
9940 cx: &mut Context<Self>,
9941 ) {
9942 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9943 }
9944
9945 pub fn expand_excerpts_up(
9946 &mut self,
9947 action: &ExpandExcerptsUp,
9948 _: &mut Window,
9949 cx: &mut Context<Self>,
9950 ) {
9951 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9952 }
9953
9954 pub fn expand_excerpts_for_direction(
9955 &mut self,
9956 lines: u32,
9957 direction: ExpandExcerptDirection,
9958
9959 cx: &mut Context<Self>,
9960 ) {
9961 let selections = self.selections.disjoint_anchors();
9962
9963 let lines = if lines == 0 {
9964 EditorSettings::get_global(cx).expand_excerpt_lines
9965 } else {
9966 lines
9967 };
9968
9969 self.buffer.update(cx, |buffer, cx| {
9970 let snapshot = buffer.snapshot(cx);
9971 let mut excerpt_ids = selections
9972 .iter()
9973 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
9974 .collect::<Vec<_>>();
9975 excerpt_ids.sort();
9976 excerpt_ids.dedup();
9977 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
9978 })
9979 }
9980
9981 pub fn expand_excerpt(
9982 &mut self,
9983 excerpt: ExcerptId,
9984 direction: ExpandExcerptDirection,
9985 cx: &mut Context<Self>,
9986 ) {
9987 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9988 self.buffer.update(cx, |buffer, cx| {
9989 buffer.expand_excerpts([excerpt], lines, direction, cx)
9990 })
9991 }
9992
9993 pub fn go_to_singleton_buffer_point(
9994 &mut self,
9995 point: Point,
9996 window: &mut Window,
9997 cx: &mut Context<Self>,
9998 ) {
9999 self.go_to_singleton_buffer_range(point..point, window, cx);
10000 }
10001
10002 pub fn go_to_singleton_buffer_range(
10003 &mut self,
10004 range: Range<Point>,
10005 window: &mut Window,
10006 cx: &mut Context<Self>,
10007 ) {
10008 let multibuffer = self.buffer().read(cx);
10009 let Some(buffer) = multibuffer.as_singleton() else {
10010 return;
10011 };
10012 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10013 return;
10014 };
10015 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10016 return;
10017 };
10018 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10019 s.select_anchor_ranges([start..end])
10020 });
10021 }
10022
10023 fn go_to_diagnostic(
10024 &mut self,
10025 _: &GoToDiagnostic,
10026 window: &mut Window,
10027 cx: &mut Context<Self>,
10028 ) {
10029 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10030 }
10031
10032 fn go_to_prev_diagnostic(
10033 &mut self,
10034 _: &GoToPrevDiagnostic,
10035 window: &mut Window,
10036 cx: &mut Context<Self>,
10037 ) {
10038 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10039 }
10040
10041 pub fn go_to_diagnostic_impl(
10042 &mut self,
10043 direction: Direction,
10044 window: &mut Window,
10045 cx: &mut Context<Self>,
10046 ) {
10047 let buffer = self.buffer.read(cx).snapshot(cx);
10048 let selection = self.selections.newest::<usize>(cx);
10049
10050 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10051 if direction == Direction::Next {
10052 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10053 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10054 return;
10055 };
10056 self.activate_diagnostics(
10057 buffer_id,
10058 popover.local_diagnostic.diagnostic.group_id,
10059 window,
10060 cx,
10061 );
10062 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10063 let primary_range_start = active_diagnostics.primary_range.start;
10064 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10065 let mut new_selection = s.newest_anchor().clone();
10066 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10067 s.select_anchors(vec![new_selection.clone()]);
10068 });
10069 self.refresh_inline_completion(false, true, window, cx);
10070 }
10071 return;
10072 }
10073 }
10074
10075 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10076 active_diagnostics
10077 .primary_range
10078 .to_offset(&buffer)
10079 .to_inclusive()
10080 });
10081 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10082 if active_primary_range.contains(&selection.head()) {
10083 *active_primary_range.start()
10084 } else {
10085 selection.head()
10086 }
10087 } else {
10088 selection.head()
10089 };
10090 let snapshot = self.snapshot(window, cx);
10091 loop {
10092 let mut diagnostics;
10093 if direction == Direction::Prev {
10094 diagnostics = buffer
10095 .diagnostics_in_range::<_, usize>(0..search_start)
10096 .collect::<Vec<_>>();
10097 diagnostics.reverse();
10098 } else {
10099 diagnostics = buffer
10100 .diagnostics_in_range::<_, usize>(search_start..buffer.len())
10101 .collect::<Vec<_>>();
10102 };
10103 let group = diagnostics
10104 .into_iter()
10105 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10106 // relies on diagnostics_in_range to return diagnostics with the same starting range to
10107 // be sorted in a stable way
10108 // skip until we are at current active diagnostic, if it exists
10109 .skip_while(|entry| {
10110 let is_in_range = match direction {
10111 Direction::Prev => entry.range.end > search_start,
10112 Direction::Next => entry.range.start < search_start,
10113 };
10114 is_in_range
10115 && self
10116 .active_diagnostics
10117 .as_ref()
10118 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
10119 })
10120 .find_map(|entry| {
10121 if entry.diagnostic.is_primary
10122 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
10123 && entry.range.start != entry.range.end
10124 // if we match with the active diagnostic, skip it
10125 && Some(entry.diagnostic.group_id)
10126 != self.active_diagnostics.as_ref().map(|d| d.group_id)
10127 {
10128 Some((entry.range, entry.diagnostic.group_id))
10129 } else {
10130 None
10131 }
10132 });
10133
10134 if let Some((primary_range, group_id)) = group {
10135 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10136 return;
10137 };
10138 self.activate_diagnostics(buffer_id, group_id, window, cx);
10139 if self.active_diagnostics.is_some() {
10140 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10141 s.select(vec![Selection {
10142 id: selection.id,
10143 start: primary_range.start,
10144 end: primary_range.start,
10145 reversed: false,
10146 goal: SelectionGoal::None,
10147 }]);
10148 });
10149 self.refresh_inline_completion(false, true, window, cx);
10150 }
10151 break;
10152 } else {
10153 // Cycle around to the start of the buffer, potentially moving back to the start of
10154 // the currently active diagnostic.
10155 active_primary_range.take();
10156 if direction == Direction::Prev {
10157 if search_start == buffer.len() {
10158 break;
10159 } else {
10160 search_start = buffer.len();
10161 }
10162 } else if search_start == 0 {
10163 break;
10164 } else {
10165 search_start = 0;
10166 }
10167 }
10168 }
10169 }
10170
10171 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10172 let snapshot = self.snapshot(window, cx);
10173 let selection = self.selections.newest::<Point>(cx);
10174 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10175 }
10176
10177 fn go_to_hunk_after_position(
10178 &mut self,
10179 snapshot: &EditorSnapshot,
10180 position: Point,
10181 window: &mut Window,
10182 cx: &mut Context<Editor>,
10183 ) -> Option<MultiBufferDiffHunk> {
10184 let mut hunk = snapshot
10185 .buffer_snapshot
10186 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10187 .find(|hunk| hunk.row_range.start.0 > position.row);
10188 if hunk.is_none() {
10189 hunk = snapshot
10190 .buffer_snapshot
10191 .diff_hunks_in_range(Point::zero()..position)
10192 .find(|hunk| hunk.row_range.end.0 < position.row)
10193 }
10194 if let Some(hunk) = &hunk {
10195 let destination = Point::new(hunk.row_range.start.0, 0);
10196 self.unfold_ranges(&[destination..destination], false, false, cx);
10197 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10198 s.select_ranges(vec![destination..destination]);
10199 });
10200 }
10201
10202 hunk
10203 }
10204
10205 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10206 let snapshot = self.snapshot(window, cx);
10207 let selection = self.selections.newest::<Point>(cx);
10208 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10209 }
10210
10211 fn go_to_hunk_before_position(
10212 &mut self,
10213 snapshot: &EditorSnapshot,
10214 position: Point,
10215 window: &mut Window,
10216 cx: &mut Context<Editor>,
10217 ) -> Option<MultiBufferDiffHunk> {
10218 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10219 if hunk.is_none() {
10220 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10221 }
10222 if let Some(hunk) = &hunk {
10223 let destination = Point::new(hunk.row_range.start.0, 0);
10224 self.unfold_ranges(&[destination..destination], false, false, cx);
10225 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10226 s.select_ranges(vec![destination..destination]);
10227 });
10228 }
10229
10230 hunk
10231 }
10232
10233 pub fn go_to_definition(
10234 &mut self,
10235 _: &GoToDefinition,
10236 window: &mut Window,
10237 cx: &mut Context<Self>,
10238 ) -> Task<Result<Navigated>> {
10239 let definition =
10240 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10241 cx.spawn_in(window, |editor, mut cx| async move {
10242 if definition.await? == Navigated::Yes {
10243 return Ok(Navigated::Yes);
10244 }
10245 match editor.update_in(&mut cx, |editor, window, cx| {
10246 editor.find_all_references(&FindAllReferences, window, cx)
10247 })? {
10248 Some(references) => references.await,
10249 None => Ok(Navigated::No),
10250 }
10251 })
10252 }
10253
10254 pub fn go_to_declaration(
10255 &mut self,
10256 _: &GoToDeclaration,
10257 window: &mut Window,
10258 cx: &mut Context<Self>,
10259 ) -> Task<Result<Navigated>> {
10260 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10261 }
10262
10263 pub fn go_to_declaration_split(
10264 &mut self,
10265 _: &GoToDeclaration,
10266 window: &mut Window,
10267 cx: &mut Context<Self>,
10268 ) -> Task<Result<Navigated>> {
10269 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10270 }
10271
10272 pub fn go_to_implementation(
10273 &mut self,
10274 _: &GoToImplementation,
10275 window: &mut Window,
10276 cx: &mut Context<Self>,
10277 ) -> Task<Result<Navigated>> {
10278 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10279 }
10280
10281 pub fn go_to_implementation_split(
10282 &mut self,
10283 _: &GoToImplementationSplit,
10284 window: &mut Window,
10285 cx: &mut Context<Self>,
10286 ) -> Task<Result<Navigated>> {
10287 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10288 }
10289
10290 pub fn go_to_type_definition(
10291 &mut self,
10292 _: &GoToTypeDefinition,
10293 window: &mut Window,
10294 cx: &mut Context<Self>,
10295 ) -> Task<Result<Navigated>> {
10296 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10297 }
10298
10299 pub fn go_to_definition_split(
10300 &mut self,
10301 _: &GoToDefinitionSplit,
10302 window: &mut Window,
10303 cx: &mut Context<Self>,
10304 ) -> Task<Result<Navigated>> {
10305 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10306 }
10307
10308 pub fn go_to_type_definition_split(
10309 &mut self,
10310 _: &GoToTypeDefinitionSplit,
10311 window: &mut Window,
10312 cx: &mut Context<Self>,
10313 ) -> Task<Result<Navigated>> {
10314 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10315 }
10316
10317 fn go_to_definition_of_kind(
10318 &mut self,
10319 kind: GotoDefinitionKind,
10320 split: bool,
10321 window: &mut Window,
10322 cx: &mut Context<Self>,
10323 ) -> Task<Result<Navigated>> {
10324 let Some(provider) = self.semantics_provider.clone() else {
10325 return Task::ready(Ok(Navigated::No));
10326 };
10327 let head = self.selections.newest::<usize>(cx).head();
10328 let buffer = self.buffer.read(cx);
10329 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10330 text_anchor
10331 } else {
10332 return Task::ready(Ok(Navigated::No));
10333 };
10334
10335 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10336 return Task::ready(Ok(Navigated::No));
10337 };
10338
10339 cx.spawn_in(window, |editor, mut cx| async move {
10340 let definitions = definitions.await?;
10341 let navigated = editor
10342 .update_in(&mut cx, |editor, window, cx| {
10343 editor.navigate_to_hover_links(
10344 Some(kind),
10345 definitions
10346 .into_iter()
10347 .filter(|location| {
10348 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10349 })
10350 .map(HoverLink::Text)
10351 .collect::<Vec<_>>(),
10352 split,
10353 window,
10354 cx,
10355 )
10356 })?
10357 .await?;
10358 anyhow::Ok(navigated)
10359 })
10360 }
10361
10362 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10363 let selection = self.selections.newest_anchor();
10364 let head = selection.head();
10365 let tail = selection.tail();
10366
10367 let Some((buffer, start_position)) =
10368 self.buffer.read(cx).text_anchor_for_position(head, cx)
10369 else {
10370 return;
10371 };
10372
10373 let end_position = if head != tail {
10374 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10375 return;
10376 };
10377 Some(pos)
10378 } else {
10379 None
10380 };
10381
10382 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10383 let url = if let Some(end_pos) = end_position {
10384 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10385 } else {
10386 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10387 };
10388
10389 if let Some(url) = url {
10390 editor.update(&mut cx, |_, cx| {
10391 cx.open_url(&url);
10392 })
10393 } else {
10394 Ok(())
10395 }
10396 });
10397
10398 url_finder.detach();
10399 }
10400
10401 pub fn open_selected_filename(
10402 &mut self,
10403 _: &OpenSelectedFilename,
10404 window: &mut Window,
10405 cx: &mut Context<Self>,
10406 ) {
10407 let Some(workspace) = self.workspace() else {
10408 return;
10409 };
10410
10411 let position = self.selections.newest_anchor().head();
10412
10413 let Some((buffer, buffer_position)) =
10414 self.buffer.read(cx).text_anchor_for_position(position, cx)
10415 else {
10416 return;
10417 };
10418
10419 let project = self.project.clone();
10420
10421 cx.spawn_in(window, |_, mut cx| async move {
10422 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10423
10424 if let Some((_, path)) = result {
10425 workspace
10426 .update_in(&mut cx, |workspace, window, cx| {
10427 workspace.open_resolved_path(path, window, cx)
10428 })?
10429 .await?;
10430 }
10431 anyhow::Ok(())
10432 })
10433 .detach();
10434 }
10435
10436 pub(crate) fn navigate_to_hover_links(
10437 &mut self,
10438 kind: Option<GotoDefinitionKind>,
10439 mut definitions: Vec<HoverLink>,
10440 split: bool,
10441 window: &mut Window,
10442 cx: &mut Context<Editor>,
10443 ) -> Task<Result<Navigated>> {
10444 // If there is one definition, just open it directly
10445 if definitions.len() == 1 {
10446 let definition = definitions.pop().unwrap();
10447
10448 enum TargetTaskResult {
10449 Location(Option<Location>),
10450 AlreadyNavigated,
10451 }
10452
10453 let target_task = match definition {
10454 HoverLink::Text(link) => {
10455 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10456 }
10457 HoverLink::InlayHint(lsp_location, server_id) => {
10458 let computation =
10459 self.compute_target_location(lsp_location, server_id, window, cx);
10460 cx.background_executor().spawn(async move {
10461 let location = computation.await?;
10462 Ok(TargetTaskResult::Location(location))
10463 })
10464 }
10465 HoverLink::Url(url) => {
10466 cx.open_url(&url);
10467 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10468 }
10469 HoverLink::File(path) => {
10470 if let Some(workspace) = self.workspace() {
10471 cx.spawn_in(window, |_, mut cx| async move {
10472 workspace
10473 .update_in(&mut cx, |workspace, window, cx| {
10474 workspace.open_resolved_path(path, window, cx)
10475 })?
10476 .await
10477 .map(|_| TargetTaskResult::AlreadyNavigated)
10478 })
10479 } else {
10480 Task::ready(Ok(TargetTaskResult::Location(None)))
10481 }
10482 }
10483 };
10484 cx.spawn_in(window, |editor, mut cx| async move {
10485 let target = match target_task.await.context("target resolution task")? {
10486 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10487 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10488 TargetTaskResult::Location(Some(target)) => target,
10489 };
10490
10491 editor.update_in(&mut cx, |editor, window, cx| {
10492 let Some(workspace) = editor.workspace() else {
10493 return Navigated::No;
10494 };
10495 let pane = workspace.read(cx).active_pane().clone();
10496
10497 let range = target.range.to_point(target.buffer.read(cx));
10498 let range = editor.range_for_match(&range);
10499 let range = collapse_multiline_range(range);
10500
10501 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10502 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10503 } else {
10504 window.defer(cx, move |window, cx| {
10505 let target_editor: Entity<Self> =
10506 workspace.update(cx, |workspace, cx| {
10507 let pane = if split {
10508 workspace.adjacent_pane(window, cx)
10509 } else {
10510 workspace.active_pane().clone()
10511 };
10512
10513 workspace.open_project_item(
10514 pane,
10515 target.buffer.clone(),
10516 true,
10517 true,
10518 window,
10519 cx,
10520 )
10521 });
10522 target_editor.update(cx, |target_editor, cx| {
10523 // When selecting a definition in a different buffer, disable the nav history
10524 // to avoid creating a history entry at the previous cursor location.
10525 pane.update(cx, |pane, _| pane.disable_history());
10526 target_editor.go_to_singleton_buffer_range(range, window, cx);
10527 pane.update(cx, |pane, _| pane.enable_history());
10528 });
10529 });
10530 }
10531 Navigated::Yes
10532 })
10533 })
10534 } else if !definitions.is_empty() {
10535 cx.spawn_in(window, |editor, mut cx| async move {
10536 let (title, location_tasks, workspace) = editor
10537 .update_in(&mut cx, |editor, window, cx| {
10538 let tab_kind = match kind {
10539 Some(GotoDefinitionKind::Implementation) => "Implementations",
10540 _ => "Definitions",
10541 };
10542 let title = definitions
10543 .iter()
10544 .find_map(|definition| match definition {
10545 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10546 let buffer = origin.buffer.read(cx);
10547 format!(
10548 "{} for {}",
10549 tab_kind,
10550 buffer
10551 .text_for_range(origin.range.clone())
10552 .collect::<String>()
10553 )
10554 }),
10555 HoverLink::InlayHint(_, _) => None,
10556 HoverLink::Url(_) => None,
10557 HoverLink::File(_) => None,
10558 })
10559 .unwrap_or(tab_kind.to_string());
10560 let location_tasks = definitions
10561 .into_iter()
10562 .map(|definition| match definition {
10563 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10564 HoverLink::InlayHint(lsp_location, server_id) => editor
10565 .compute_target_location(lsp_location, server_id, window, cx),
10566 HoverLink::Url(_) => Task::ready(Ok(None)),
10567 HoverLink::File(_) => Task::ready(Ok(None)),
10568 })
10569 .collect::<Vec<_>>();
10570 (title, location_tasks, editor.workspace().clone())
10571 })
10572 .context("location tasks preparation")?;
10573
10574 let locations = future::join_all(location_tasks)
10575 .await
10576 .into_iter()
10577 .filter_map(|location| location.transpose())
10578 .collect::<Result<_>>()
10579 .context("location tasks")?;
10580
10581 let Some(workspace) = workspace else {
10582 return Ok(Navigated::No);
10583 };
10584 let opened = workspace
10585 .update_in(&mut cx, |workspace, window, cx| {
10586 Self::open_locations_in_multibuffer(
10587 workspace,
10588 locations,
10589 title,
10590 split,
10591 MultibufferSelectionMode::First,
10592 window,
10593 cx,
10594 )
10595 })
10596 .ok();
10597
10598 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10599 })
10600 } else {
10601 Task::ready(Ok(Navigated::No))
10602 }
10603 }
10604
10605 fn compute_target_location(
10606 &self,
10607 lsp_location: lsp::Location,
10608 server_id: LanguageServerId,
10609 window: &mut Window,
10610 cx: &mut Context<Self>,
10611 ) -> Task<anyhow::Result<Option<Location>>> {
10612 let Some(project) = self.project.clone() else {
10613 return Task::ready(Ok(None));
10614 };
10615
10616 cx.spawn_in(window, move |editor, mut cx| async move {
10617 let location_task = editor.update(&mut cx, |_, cx| {
10618 project.update(cx, |project, cx| {
10619 let language_server_name = project
10620 .language_server_statuses(cx)
10621 .find(|(id, _)| server_id == *id)
10622 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10623 language_server_name.map(|language_server_name| {
10624 project.open_local_buffer_via_lsp(
10625 lsp_location.uri.clone(),
10626 server_id,
10627 language_server_name,
10628 cx,
10629 )
10630 })
10631 })
10632 })?;
10633 let location = match location_task {
10634 Some(task) => Some({
10635 let target_buffer_handle = task.await.context("open local buffer")?;
10636 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10637 let target_start = target_buffer
10638 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10639 let target_end = target_buffer
10640 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10641 target_buffer.anchor_after(target_start)
10642 ..target_buffer.anchor_before(target_end)
10643 })?;
10644 Location {
10645 buffer: target_buffer_handle,
10646 range,
10647 }
10648 }),
10649 None => None,
10650 };
10651 Ok(location)
10652 })
10653 }
10654
10655 pub fn find_all_references(
10656 &mut self,
10657 _: &FindAllReferences,
10658 window: &mut Window,
10659 cx: &mut Context<Self>,
10660 ) -> Option<Task<Result<Navigated>>> {
10661 let selection = self.selections.newest::<usize>(cx);
10662 let multi_buffer = self.buffer.read(cx);
10663 let head = selection.head();
10664
10665 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10666 let head_anchor = multi_buffer_snapshot.anchor_at(
10667 head,
10668 if head < selection.tail() {
10669 Bias::Right
10670 } else {
10671 Bias::Left
10672 },
10673 );
10674
10675 match self
10676 .find_all_references_task_sources
10677 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10678 {
10679 Ok(_) => {
10680 log::info!(
10681 "Ignoring repeated FindAllReferences invocation with the position of already running task"
10682 );
10683 return None;
10684 }
10685 Err(i) => {
10686 self.find_all_references_task_sources.insert(i, head_anchor);
10687 }
10688 }
10689
10690 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10691 let workspace = self.workspace()?;
10692 let project = workspace.read(cx).project().clone();
10693 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10694 Some(cx.spawn_in(window, |editor, mut cx| async move {
10695 let _cleanup = defer({
10696 let mut cx = cx.clone();
10697 move || {
10698 let _ = editor.update(&mut cx, |editor, _| {
10699 if let Ok(i) =
10700 editor
10701 .find_all_references_task_sources
10702 .binary_search_by(|anchor| {
10703 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10704 })
10705 {
10706 editor.find_all_references_task_sources.remove(i);
10707 }
10708 });
10709 }
10710 });
10711
10712 let locations = references.await?;
10713 if locations.is_empty() {
10714 return anyhow::Ok(Navigated::No);
10715 }
10716
10717 workspace.update_in(&mut cx, |workspace, window, cx| {
10718 let title = locations
10719 .first()
10720 .as_ref()
10721 .map(|location| {
10722 let buffer = location.buffer.read(cx);
10723 format!(
10724 "References to `{}`",
10725 buffer
10726 .text_for_range(location.range.clone())
10727 .collect::<String>()
10728 )
10729 })
10730 .unwrap();
10731 Self::open_locations_in_multibuffer(
10732 workspace,
10733 locations,
10734 title,
10735 false,
10736 MultibufferSelectionMode::First,
10737 window,
10738 cx,
10739 );
10740 Navigated::Yes
10741 })
10742 }))
10743 }
10744
10745 /// Opens a multibuffer with the given project locations in it
10746 pub fn open_locations_in_multibuffer(
10747 workspace: &mut Workspace,
10748 mut locations: Vec<Location>,
10749 title: String,
10750 split: bool,
10751 multibuffer_selection_mode: MultibufferSelectionMode,
10752 window: &mut Window,
10753 cx: &mut Context<Workspace>,
10754 ) {
10755 // If there are multiple definitions, open them in a multibuffer
10756 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10757 let mut locations = locations.into_iter().peekable();
10758 let mut ranges = Vec::new();
10759 let capability = workspace.project().read(cx).capability();
10760
10761 let excerpt_buffer = cx.new(|cx| {
10762 let mut multibuffer = MultiBuffer::new(capability);
10763 while let Some(location) = locations.next() {
10764 let buffer = location.buffer.read(cx);
10765 let mut ranges_for_buffer = Vec::new();
10766 let range = location.range.to_offset(buffer);
10767 ranges_for_buffer.push(range.clone());
10768
10769 while let Some(next_location) = locations.peek() {
10770 if next_location.buffer == location.buffer {
10771 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10772 locations.next();
10773 } else {
10774 break;
10775 }
10776 }
10777
10778 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10779 ranges.extend(multibuffer.push_excerpts_with_context_lines(
10780 location.buffer.clone(),
10781 ranges_for_buffer,
10782 DEFAULT_MULTIBUFFER_CONTEXT,
10783 cx,
10784 ))
10785 }
10786
10787 multibuffer.with_title(title)
10788 });
10789
10790 let editor = cx.new(|cx| {
10791 Editor::for_multibuffer(
10792 excerpt_buffer,
10793 Some(workspace.project().clone()),
10794 true,
10795 window,
10796 cx,
10797 )
10798 });
10799 editor.update(cx, |editor, cx| {
10800 match multibuffer_selection_mode {
10801 MultibufferSelectionMode::First => {
10802 if let Some(first_range) = ranges.first() {
10803 editor.change_selections(None, window, cx, |selections| {
10804 selections.clear_disjoint();
10805 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10806 });
10807 }
10808 editor.highlight_background::<Self>(
10809 &ranges,
10810 |theme| theme.editor_highlighted_line_background,
10811 cx,
10812 );
10813 }
10814 MultibufferSelectionMode::All => {
10815 editor.change_selections(None, window, cx, |selections| {
10816 selections.clear_disjoint();
10817 selections.select_anchor_ranges(ranges);
10818 });
10819 }
10820 }
10821 editor.register_buffers_with_language_servers(cx);
10822 });
10823
10824 let item = Box::new(editor);
10825 let item_id = item.item_id();
10826
10827 if split {
10828 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
10829 } else {
10830 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10831 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10832 pane.close_current_preview_item(window, cx)
10833 } else {
10834 None
10835 }
10836 });
10837 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
10838 }
10839 workspace.active_pane().update(cx, |pane, cx| {
10840 pane.set_preview_item_id(Some(item_id), cx);
10841 });
10842 }
10843
10844 pub fn rename(
10845 &mut self,
10846 _: &Rename,
10847 window: &mut Window,
10848 cx: &mut Context<Self>,
10849 ) -> Option<Task<Result<()>>> {
10850 use language::ToOffset as _;
10851
10852 let provider = self.semantics_provider.clone()?;
10853 let selection = self.selections.newest_anchor().clone();
10854 let (cursor_buffer, cursor_buffer_position) = self
10855 .buffer
10856 .read(cx)
10857 .text_anchor_for_position(selection.head(), cx)?;
10858 let (tail_buffer, cursor_buffer_position_end) = self
10859 .buffer
10860 .read(cx)
10861 .text_anchor_for_position(selection.tail(), cx)?;
10862 if tail_buffer != cursor_buffer {
10863 return None;
10864 }
10865
10866 let snapshot = cursor_buffer.read(cx).snapshot();
10867 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10868 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10869 let prepare_rename = provider
10870 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10871 .unwrap_or_else(|| Task::ready(Ok(None)));
10872 drop(snapshot);
10873
10874 Some(cx.spawn_in(window, |this, mut cx| async move {
10875 let rename_range = if let Some(range) = prepare_rename.await? {
10876 Some(range)
10877 } else {
10878 this.update(&mut cx, |this, cx| {
10879 let buffer = this.buffer.read(cx).snapshot(cx);
10880 let mut buffer_highlights = this
10881 .document_highlights_for_position(selection.head(), &buffer)
10882 .filter(|highlight| {
10883 highlight.start.excerpt_id == selection.head().excerpt_id
10884 && highlight.end.excerpt_id == selection.head().excerpt_id
10885 });
10886 buffer_highlights
10887 .next()
10888 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10889 })?
10890 };
10891 if let Some(rename_range) = rename_range {
10892 this.update_in(&mut cx, |this, window, cx| {
10893 let snapshot = cursor_buffer.read(cx).snapshot();
10894 let rename_buffer_range = rename_range.to_offset(&snapshot);
10895 let cursor_offset_in_rename_range =
10896 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10897 let cursor_offset_in_rename_range_end =
10898 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10899
10900 this.take_rename(false, window, cx);
10901 let buffer = this.buffer.read(cx).read(cx);
10902 let cursor_offset = selection.head().to_offset(&buffer);
10903 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10904 let rename_end = rename_start + rename_buffer_range.len();
10905 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10906 let mut old_highlight_id = None;
10907 let old_name: Arc<str> = buffer
10908 .chunks(rename_start..rename_end, true)
10909 .map(|chunk| {
10910 if old_highlight_id.is_none() {
10911 old_highlight_id = chunk.syntax_highlight_id;
10912 }
10913 chunk.text
10914 })
10915 .collect::<String>()
10916 .into();
10917
10918 drop(buffer);
10919
10920 // Position the selection in the rename editor so that it matches the current selection.
10921 this.show_local_selections = false;
10922 let rename_editor = cx.new(|cx| {
10923 let mut editor = Editor::single_line(window, cx);
10924 editor.buffer.update(cx, |buffer, cx| {
10925 buffer.edit([(0..0, old_name.clone())], None, cx)
10926 });
10927 let rename_selection_range = match cursor_offset_in_rename_range
10928 .cmp(&cursor_offset_in_rename_range_end)
10929 {
10930 Ordering::Equal => {
10931 editor.select_all(&SelectAll, window, cx);
10932 return editor;
10933 }
10934 Ordering::Less => {
10935 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10936 }
10937 Ordering::Greater => {
10938 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10939 }
10940 };
10941 if rename_selection_range.end > old_name.len() {
10942 editor.select_all(&SelectAll, window, cx);
10943 } else {
10944 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10945 s.select_ranges([rename_selection_range]);
10946 });
10947 }
10948 editor
10949 });
10950 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10951 if e == &EditorEvent::Focused {
10952 cx.emit(EditorEvent::FocusedIn)
10953 }
10954 })
10955 .detach();
10956
10957 let write_highlights =
10958 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10959 let read_highlights =
10960 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10961 let ranges = write_highlights
10962 .iter()
10963 .flat_map(|(_, ranges)| ranges.iter())
10964 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10965 .cloned()
10966 .collect();
10967
10968 this.highlight_text::<Rename>(
10969 ranges,
10970 HighlightStyle {
10971 fade_out: Some(0.6),
10972 ..Default::default()
10973 },
10974 cx,
10975 );
10976 let rename_focus_handle = rename_editor.focus_handle(cx);
10977 window.focus(&rename_focus_handle);
10978 let block_id = this.insert_blocks(
10979 [BlockProperties {
10980 style: BlockStyle::Flex,
10981 placement: BlockPlacement::Below(range.start),
10982 height: 1,
10983 render: Arc::new({
10984 let rename_editor = rename_editor.clone();
10985 move |cx: &mut BlockContext| {
10986 let mut text_style = cx.editor_style.text.clone();
10987 if let Some(highlight_style) = old_highlight_id
10988 .and_then(|h| h.style(&cx.editor_style.syntax))
10989 {
10990 text_style = text_style.highlight(highlight_style);
10991 }
10992 div()
10993 .block_mouse_down()
10994 .pl(cx.anchor_x)
10995 .child(EditorElement::new(
10996 &rename_editor,
10997 EditorStyle {
10998 background: cx.theme().system().transparent,
10999 local_player: cx.editor_style.local_player,
11000 text: text_style,
11001 scrollbar_width: cx.editor_style.scrollbar_width,
11002 syntax: cx.editor_style.syntax.clone(),
11003 status: cx.editor_style.status.clone(),
11004 inlay_hints_style: HighlightStyle {
11005 font_weight: Some(FontWeight::BOLD),
11006 ..make_inlay_hints_style(cx.app)
11007 },
11008 inline_completion_styles: make_suggestion_styles(
11009 cx.app,
11010 ),
11011 ..EditorStyle::default()
11012 },
11013 ))
11014 .into_any_element()
11015 }
11016 }),
11017 priority: 0,
11018 }],
11019 Some(Autoscroll::fit()),
11020 cx,
11021 )[0];
11022 this.pending_rename = Some(RenameState {
11023 range,
11024 old_name,
11025 editor: rename_editor,
11026 block_id,
11027 });
11028 })?;
11029 }
11030
11031 Ok(())
11032 }))
11033 }
11034
11035 pub fn confirm_rename(
11036 &mut self,
11037 _: &ConfirmRename,
11038 window: &mut Window,
11039 cx: &mut Context<Self>,
11040 ) -> Option<Task<Result<()>>> {
11041 let rename = self.take_rename(false, window, cx)?;
11042 let workspace = self.workspace()?.downgrade();
11043 let (buffer, start) = self
11044 .buffer
11045 .read(cx)
11046 .text_anchor_for_position(rename.range.start, cx)?;
11047 let (end_buffer, _) = self
11048 .buffer
11049 .read(cx)
11050 .text_anchor_for_position(rename.range.end, cx)?;
11051 if buffer != end_buffer {
11052 return None;
11053 }
11054
11055 let old_name = rename.old_name;
11056 let new_name = rename.editor.read(cx).text(cx);
11057
11058 let rename = self.semantics_provider.as_ref()?.perform_rename(
11059 &buffer,
11060 start,
11061 new_name.clone(),
11062 cx,
11063 )?;
11064
11065 Some(cx.spawn_in(window, |editor, mut cx| async move {
11066 let project_transaction = rename.await?;
11067 Self::open_project_transaction(
11068 &editor,
11069 workspace,
11070 project_transaction,
11071 format!("Rename: {} → {}", old_name, new_name),
11072 cx.clone(),
11073 )
11074 .await?;
11075
11076 editor.update(&mut cx, |editor, cx| {
11077 editor.refresh_document_highlights(cx);
11078 })?;
11079 Ok(())
11080 }))
11081 }
11082
11083 fn take_rename(
11084 &mut self,
11085 moving_cursor: bool,
11086 window: &mut Window,
11087 cx: &mut Context<Self>,
11088 ) -> Option<RenameState> {
11089 let rename = self.pending_rename.take()?;
11090 if rename.editor.focus_handle(cx).is_focused(window) {
11091 window.focus(&self.focus_handle);
11092 }
11093
11094 self.remove_blocks(
11095 [rename.block_id].into_iter().collect(),
11096 Some(Autoscroll::fit()),
11097 cx,
11098 );
11099 self.clear_highlights::<Rename>(cx);
11100 self.show_local_selections = true;
11101
11102 if moving_cursor {
11103 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11104 editor.selections.newest::<usize>(cx).head()
11105 });
11106
11107 // Update the selection to match the position of the selection inside
11108 // the rename editor.
11109 let snapshot = self.buffer.read(cx).read(cx);
11110 let rename_range = rename.range.to_offset(&snapshot);
11111 let cursor_in_editor = snapshot
11112 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11113 .min(rename_range.end);
11114 drop(snapshot);
11115
11116 self.change_selections(None, window, cx, |s| {
11117 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11118 });
11119 } else {
11120 self.refresh_document_highlights(cx);
11121 }
11122
11123 Some(rename)
11124 }
11125
11126 pub fn pending_rename(&self) -> Option<&RenameState> {
11127 self.pending_rename.as_ref()
11128 }
11129
11130 fn format(
11131 &mut self,
11132 _: &Format,
11133 window: &mut Window,
11134 cx: &mut Context<Self>,
11135 ) -> Option<Task<Result<()>>> {
11136 let project = match &self.project {
11137 Some(project) => project.clone(),
11138 None => return None,
11139 };
11140
11141 Some(self.perform_format(
11142 project,
11143 FormatTrigger::Manual,
11144 FormatTarget::Buffers,
11145 window,
11146 cx,
11147 ))
11148 }
11149
11150 fn format_selections(
11151 &mut self,
11152 _: &FormatSelections,
11153 window: &mut Window,
11154 cx: &mut Context<Self>,
11155 ) -> Option<Task<Result<()>>> {
11156 let project = match &self.project {
11157 Some(project) => project.clone(),
11158 None => return None,
11159 };
11160
11161 let ranges = self
11162 .selections
11163 .all_adjusted(cx)
11164 .into_iter()
11165 .map(|selection| selection.range())
11166 .collect_vec();
11167
11168 Some(self.perform_format(
11169 project,
11170 FormatTrigger::Manual,
11171 FormatTarget::Ranges(ranges),
11172 window,
11173 cx,
11174 ))
11175 }
11176
11177 fn perform_format(
11178 &mut self,
11179 project: Entity<Project>,
11180 trigger: FormatTrigger,
11181 target: FormatTarget,
11182 window: &mut Window,
11183 cx: &mut Context<Self>,
11184 ) -> Task<Result<()>> {
11185 let buffer = self.buffer.clone();
11186 let (buffers, target) = match target {
11187 FormatTarget::Buffers => {
11188 let mut buffers = buffer.read(cx).all_buffers();
11189 if trigger == FormatTrigger::Save {
11190 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11191 }
11192 (buffers, LspFormatTarget::Buffers)
11193 }
11194 FormatTarget::Ranges(selection_ranges) => {
11195 let multi_buffer = buffer.read(cx);
11196 let snapshot = multi_buffer.read(cx);
11197 let mut buffers = HashSet::default();
11198 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11199 BTreeMap::new();
11200 for selection_range in selection_ranges {
11201 for (buffer, buffer_range, _) in
11202 snapshot.range_to_buffer_ranges(selection_range)
11203 {
11204 let buffer_id = buffer.remote_id();
11205 let start = buffer.anchor_before(buffer_range.start);
11206 let end = buffer.anchor_after(buffer_range.end);
11207 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11208 buffer_id_to_ranges
11209 .entry(buffer_id)
11210 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11211 .or_insert_with(|| vec![start..end]);
11212 }
11213 }
11214 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11215 }
11216 };
11217
11218 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11219 let format = project.update(cx, |project, cx| {
11220 project.format(buffers, target, true, trigger, cx)
11221 });
11222
11223 cx.spawn_in(window, |_, mut cx| async move {
11224 let transaction = futures::select_biased! {
11225 () = timeout => {
11226 log::warn!("timed out waiting for formatting");
11227 None
11228 }
11229 transaction = format.log_err().fuse() => transaction,
11230 };
11231
11232 buffer
11233 .update(&mut cx, |buffer, cx| {
11234 if let Some(transaction) = transaction {
11235 if !buffer.is_singleton() {
11236 buffer.push_transaction(&transaction.0, cx);
11237 }
11238 }
11239
11240 cx.notify();
11241 })
11242 .ok();
11243
11244 Ok(())
11245 })
11246 }
11247
11248 fn restart_language_server(
11249 &mut self,
11250 _: &RestartLanguageServer,
11251 _: &mut Window,
11252 cx: &mut Context<Self>,
11253 ) {
11254 if let Some(project) = self.project.clone() {
11255 self.buffer.update(cx, |multi_buffer, cx| {
11256 project.update(cx, |project, cx| {
11257 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11258 });
11259 })
11260 }
11261 }
11262
11263 fn cancel_language_server_work(
11264 &mut self,
11265 _: &actions::CancelLanguageServerWork,
11266 _: &mut Window,
11267 cx: &mut Context<Self>,
11268 ) {
11269 if let Some(project) = self.project.clone() {
11270 self.buffer.update(cx, |multi_buffer, cx| {
11271 project.update(cx, |project, cx| {
11272 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
11273 });
11274 })
11275 }
11276 }
11277
11278 fn show_character_palette(
11279 &mut self,
11280 _: &ShowCharacterPalette,
11281 window: &mut Window,
11282 _: &mut Context<Self>,
11283 ) {
11284 window.show_character_palette();
11285 }
11286
11287 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11288 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11289 let buffer = self.buffer.read(cx).snapshot(cx);
11290 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11291 let is_valid = buffer
11292 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone())
11293 .any(|entry| {
11294 entry.diagnostic.is_primary
11295 && !entry.range.is_empty()
11296 && entry.range.start == primary_range_start
11297 && entry.diagnostic.message == active_diagnostics.primary_message
11298 });
11299
11300 if is_valid != active_diagnostics.is_valid {
11301 active_diagnostics.is_valid = is_valid;
11302 let mut new_styles = HashMap::default();
11303 for (block_id, diagnostic) in &active_diagnostics.blocks {
11304 new_styles.insert(
11305 *block_id,
11306 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11307 );
11308 }
11309 self.display_map.update(cx, |display_map, _cx| {
11310 display_map.replace_blocks(new_styles)
11311 });
11312 }
11313 }
11314 }
11315
11316 fn activate_diagnostics(
11317 &mut self,
11318 buffer_id: BufferId,
11319 group_id: usize,
11320 window: &mut Window,
11321 cx: &mut Context<Self>,
11322 ) {
11323 self.dismiss_diagnostics(cx);
11324 let snapshot = self.snapshot(window, cx);
11325 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11326 let buffer = self.buffer.read(cx).snapshot(cx);
11327
11328 let mut primary_range = None;
11329 let mut primary_message = None;
11330 let diagnostic_group = buffer
11331 .diagnostic_group(buffer_id, group_id)
11332 .filter_map(|entry| {
11333 let start = entry.range.start;
11334 let end = entry.range.end;
11335 if snapshot.is_line_folded(MultiBufferRow(start.row))
11336 && (start.row == end.row
11337 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11338 {
11339 return None;
11340 }
11341 if entry.diagnostic.is_primary {
11342 primary_range = Some(entry.range.clone());
11343 primary_message = Some(entry.diagnostic.message.clone());
11344 }
11345 Some(entry)
11346 })
11347 .collect::<Vec<_>>();
11348 let primary_range = primary_range?;
11349 let primary_message = primary_message?;
11350
11351 let blocks = display_map
11352 .insert_blocks(
11353 diagnostic_group.iter().map(|entry| {
11354 let diagnostic = entry.diagnostic.clone();
11355 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11356 BlockProperties {
11357 style: BlockStyle::Fixed,
11358 placement: BlockPlacement::Below(
11359 buffer.anchor_after(entry.range.start),
11360 ),
11361 height: message_height,
11362 render: diagnostic_block_renderer(diagnostic, None, true, true),
11363 priority: 0,
11364 }
11365 }),
11366 cx,
11367 )
11368 .into_iter()
11369 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11370 .collect();
11371
11372 Some(ActiveDiagnosticGroup {
11373 primary_range: buffer.anchor_before(primary_range.start)
11374 ..buffer.anchor_after(primary_range.end),
11375 primary_message,
11376 group_id,
11377 blocks,
11378 is_valid: true,
11379 })
11380 });
11381 }
11382
11383 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11384 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11385 self.display_map.update(cx, |display_map, cx| {
11386 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11387 });
11388 cx.notify();
11389 }
11390 }
11391
11392 pub fn set_selections_from_remote(
11393 &mut self,
11394 selections: Vec<Selection<Anchor>>,
11395 pending_selection: Option<Selection<Anchor>>,
11396 window: &mut Window,
11397 cx: &mut Context<Self>,
11398 ) {
11399 let old_cursor_position = self.selections.newest_anchor().head();
11400 self.selections.change_with(cx, |s| {
11401 s.select_anchors(selections);
11402 if let Some(pending_selection) = pending_selection {
11403 s.set_pending(pending_selection, SelectMode::Character);
11404 } else {
11405 s.clear_pending();
11406 }
11407 });
11408 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11409 }
11410
11411 fn push_to_selection_history(&mut self) {
11412 self.selection_history.push(SelectionHistoryEntry {
11413 selections: self.selections.disjoint_anchors(),
11414 select_next_state: self.select_next_state.clone(),
11415 select_prev_state: self.select_prev_state.clone(),
11416 add_selections_state: self.add_selections_state.clone(),
11417 });
11418 }
11419
11420 pub fn transact(
11421 &mut self,
11422 window: &mut Window,
11423 cx: &mut Context<Self>,
11424 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11425 ) -> Option<TransactionId> {
11426 self.start_transaction_at(Instant::now(), window, cx);
11427 update(self, window, cx);
11428 self.end_transaction_at(Instant::now(), cx)
11429 }
11430
11431 pub fn start_transaction_at(
11432 &mut self,
11433 now: Instant,
11434 window: &mut Window,
11435 cx: &mut Context<Self>,
11436 ) {
11437 self.end_selection(window, cx);
11438 if let Some(tx_id) = self
11439 .buffer
11440 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11441 {
11442 self.selection_history
11443 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11444 cx.emit(EditorEvent::TransactionBegun {
11445 transaction_id: tx_id,
11446 })
11447 }
11448 }
11449
11450 pub fn end_transaction_at(
11451 &mut self,
11452 now: Instant,
11453 cx: &mut Context<Self>,
11454 ) -> Option<TransactionId> {
11455 if let Some(transaction_id) = self
11456 .buffer
11457 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11458 {
11459 if let Some((_, end_selections)) =
11460 self.selection_history.transaction_mut(transaction_id)
11461 {
11462 *end_selections = Some(self.selections.disjoint_anchors());
11463 } else {
11464 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11465 }
11466
11467 cx.emit(EditorEvent::Edited { transaction_id });
11468 Some(transaction_id)
11469 } else {
11470 None
11471 }
11472 }
11473
11474 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11475 if self.selection_mark_mode {
11476 self.change_selections(None, window, cx, |s| {
11477 s.move_with(|_, sel| {
11478 sel.collapse_to(sel.head(), SelectionGoal::None);
11479 });
11480 })
11481 }
11482 self.selection_mark_mode = true;
11483 cx.notify();
11484 }
11485
11486 pub fn swap_selection_ends(
11487 &mut self,
11488 _: &actions::SwapSelectionEnds,
11489 window: &mut Window,
11490 cx: &mut Context<Self>,
11491 ) {
11492 self.change_selections(None, window, cx, |s| {
11493 s.move_with(|_, sel| {
11494 if sel.start != sel.end {
11495 sel.reversed = !sel.reversed
11496 }
11497 });
11498 });
11499 self.request_autoscroll(Autoscroll::newest(), cx);
11500 cx.notify();
11501 }
11502
11503 pub fn toggle_fold(
11504 &mut self,
11505 _: &actions::ToggleFold,
11506 window: &mut Window,
11507 cx: &mut Context<Self>,
11508 ) {
11509 if self.is_singleton(cx) {
11510 let selection = self.selections.newest::<Point>(cx);
11511
11512 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11513 let range = if selection.is_empty() {
11514 let point = selection.head().to_display_point(&display_map);
11515 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11516 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11517 .to_point(&display_map);
11518 start..end
11519 } else {
11520 selection.range()
11521 };
11522 if display_map.folds_in_range(range).next().is_some() {
11523 self.unfold_lines(&Default::default(), window, cx)
11524 } else {
11525 self.fold(&Default::default(), window, cx)
11526 }
11527 } else {
11528 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11529 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11530 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11531 .map(|(snapshot, _, _)| snapshot.remote_id())
11532 .collect();
11533
11534 for buffer_id in buffer_ids {
11535 if self.is_buffer_folded(buffer_id, cx) {
11536 self.unfold_buffer(buffer_id, cx);
11537 } else {
11538 self.fold_buffer(buffer_id, cx);
11539 }
11540 }
11541 }
11542 }
11543
11544 pub fn toggle_fold_recursive(
11545 &mut self,
11546 _: &actions::ToggleFoldRecursive,
11547 window: &mut Window,
11548 cx: &mut Context<Self>,
11549 ) {
11550 let selection = self.selections.newest::<Point>(cx);
11551
11552 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11553 let range = if selection.is_empty() {
11554 let point = selection.head().to_display_point(&display_map);
11555 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11556 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11557 .to_point(&display_map);
11558 start..end
11559 } else {
11560 selection.range()
11561 };
11562 if display_map.folds_in_range(range).next().is_some() {
11563 self.unfold_recursive(&Default::default(), window, cx)
11564 } else {
11565 self.fold_recursive(&Default::default(), window, cx)
11566 }
11567 }
11568
11569 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11570 if self.is_singleton(cx) {
11571 let mut to_fold = Vec::new();
11572 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11573 let selections = self.selections.all_adjusted(cx);
11574
11575 for selection in selections {
11576 let range = selection.range().sorted();
11577 let buffer_start_row = range.start.row;
11578
11579 if range.start.row != range.end.row {
11580 let mut found = false;
11581 let mut row = range.start.row;
11582 while row <= range.end.row {
11583 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11584 {
11585 found = true;
11586 row = crease.range().end.row + 1;
11587 to_fold.push(crease);
11588 } else {
11589 row += 1
11590 }
11591 }
11592 if found {
11593 continue;
11594 }
11595 }
11596
11597 for row in (0..=range.start.row).rev() {
11598 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11599 if crease.range().end.row >= buffer_start_row {
11600 to_fold.push(crease);
11601 if row <= range.start.row {
11602 break;
11603 }
11604 }
11605 }
11606 }
11607 }
11608
11609 self.fold_creases(to_fold, true, window, cx);
11610 } else {
11611 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11612
11613 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11614 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11615 .map(|(snapshot, _, _)| snapshot.remote_id())
11616 .collect();
11617 for buffer_id in buffer_ids {
11618 self.fold_buffer(buffer_id, cx);
11619 }
11620 }
11621 }
11622
11623 fn fold_at_level(
11624 &mut self,
11625 fold_at: &FoldAtLevel,
11626 window: &mut Window,
11627 cx: &mut Context<Self>,
11628 ) {
11629 if !self.buffer.read(cx).is_singleton() {
11630 return;
11631 }
11632
11633 let fold_at_level = fold_at.level;
11634 let snapshot = self.buffer.read(cx).snapshot(cx);
11635 let mut to_fold = Vec::new();
11636 let mut stack = vec![(0, snapshot.max_row().0, 1)];
11637
11638 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11639 while start_row < end_row {
11640 match self
11641 .snapshot(window, cx)
11642 .crease_for_buffer_row(MultiBufferRow(start_row))
11643 {
11644 Some(crease) => {
11645 let nested_start_row = crease.range().start.row + 1;
11646 let nested_end_row = crease.range().end.row;
11647
11648 if current_level < fold_at_level {
11649 stack.push((nested_start_row, nested_end_row, current_level + 1));
11650 } else if current_level == fold_at_level {
11651 to_fold.push(crease);
11652 }
11653
11654 start_row = nested_end_row + 1;
11655 }
11656 None => start_row += 1,
11657 }
11658 }
11659 }
11660
11661 self.fold_creases(to_fold, true, window, cx);
11662 }
11663
11664 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11665 if self.buffer.read(cx).is_singleton() {
11666 let mut fold_ranges = Vec::new();
11667 let snapshot = self.buffer.read(cx).snapshot(cx);
11668
11669 for row in 0..snapshot.max_row().0 {
11670 if let Some(foldable_range) = self
11671 .snapshot(window, cx)
11672 .crease_for_buffer_row(MultiBufferRow(row))
11673 {
11674 fold_ranges.push(foldable_range);
11675 }
11676 }
11677
11678 self.fold_creases(fold_ranges, true, window, cx);
11679 } else {
11680 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11681 editor
11682 .update_in(&mut cx, |editor, _, cx| {
11683 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11684 editor.fold_buffer(buffer_id, cx);
11685 }
11686 })
11687 .ok();
11688 });
11689 }
11690 }
11691
11692 pub fn fold_function_bodies(
11693 &mut self,
11694 _: &actions::FoldFunctionBodies,
11695 window: &mut Window,
11696 cx: &mut Context<Self>,
11697 ) {
11698 let snapshot = self.buffer.read(cx).snapshot(cx);
11699
11700 let ranges = snapshot
11701 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11702 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11703 .collect::<Vec<_>>();
11704
11705 let creases = ranges
11706 .into_iter()
11707 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11708 .collect();
11709
11710 self.fold_creases(creases, true, window, cx);
11711 }
11712
11713 pub fn fold_recursive(
11714 &mut self,
11715 _: &actions::FoldRecursive,
11716 window: &mut Window,
11717 cx: &mut Context<Self>,
11718 ) {
11719 let mut to_fold = Vec::new();
11720 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11721 let selections = self.selections.all_adjusted(cx);
11722
11723 for selection in selections {
11724 let range = selection.range().sorted();
11725 let buffer_start_row = range.start.row;
11726
11727 if range.start.row != range.end.row {
11728 let mut found = false;
11729 for row in range.start.row..=range.end.row {
11730 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11731 found = true;
11732 to_fold.push(crease);
11733 }
11734 }
11735 if found {
11736 continue;
11737 }
11738 }
11739
11740 for row in (0..=range.start.row).rev() {
11741 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11742 if crease.range().end.row >= buffer_start_row {
11743 to_fold.push(crease);
11744 } else {
11745 break;
11746 }
11747 }
11748 }
11749 }
11750
11751 self.fold_creases(to_fold, true, window, cx);
11752 }
11753
11754 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11755 let buffer_row = fold_at.buffer_row;
11756 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11757
11758 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11759 let autoscroll = self
11760 .selections
11761 .all::<Point>(cx)
11762 .iter()
11763 .any(|selection| crease.range().overlaps(&selection.range()));
11764
11765 self.fold_creases(vec![crease], autoscroll, window, cx);
11766 }
11767 }
11768
11769 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
11770 if self.is_singleton(cx) {
11771 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11772 let buffer = &display_map.buffer_snapshot;
11773 let selections = self.selections.all::<Point>(cx);
11774 let ranges = selections
11775 .iter()
11776 .map(|s| {
11777 let range = s.display_range(&display_map).sorted();
11778 let mut start = range.start.to_point(&display_map);
11779 let mut end = range.end.to_point(&display_map);
11780 start.column = 0;
11781 end.column = buffer.line_len(MultiBufferRow(end.row));
11782 start..end
11783 })
11784 .collect::<Vec<_>>();
11785
11786 self.unfold_ranges(&ranges, true, true, cx);
11787 } else {
11788 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11789 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11790 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11791 .map(|(snapshot, _, _)| snapshot.remote_id())
11792 .collect();
11793 for buffer_id in buffer_ids {
11794 self.unfold_buffer(buffer_id, cx);
11795 }
11796 }
11797 }
11798
11799 pub fn unfold_recursive(
11800 &mut self,
11801 _: &UnfoldRecursive,
11802 _window: &mut Window,
11803 cx: &mut Context<Self>,
11804 ) {
11805 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11806 let selections = self.selections.all::<Point>(cx);
11807 let ranges = selections
11808 .iter()
11809 .map(|s| {
11810 let mut range = s.display_range(&display_map).sorted();
11811 *range.start.column_mut() = 0;
11812 *range.end.column_mut() = display_map.line_len(range.end.row());
11813 let start = range.start.to_point(&display_map);
11814 let end = range.end.to_point(&display_map);
11815 start..end
11816 })
11817 .collect::<Vec<_>>();
11818
11819 self.unfold_ranges(&ranges, true, true, cx);
11820 }
11821
11822 pub fn unfold_at(
11823 &mut self,
11824 unfold_at: &UnfoldAt,
11825 _window: &mut Window,
11826 cx: &mut Context<Self>,
11827 ) {
11828 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11829
11830 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11831 ..Point::new(
11832 unfold_at.buffer_row.0,
11833 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11834 );
11835
11836 let autoscroll = self
11837 .selections
11838 .all::<Point>(cx)
11839 .iter()
11840 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11841
11842 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
11843 }
11844
11845 pub fn unfold_all(
11846 &mut self,
11847 _: &actions::UnfoldAll,
11848 _window: &mut Window,
11849 cx: &mut Context<Self>,
11850 ) {
11851 if self.buffer.read(cx).is_singleton() {
11852 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11853 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11854 } else {
11855 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
11856 editor
11857 .update(&mut cx, |editor, cx| {
11858 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11859 editor.unfold_buffer(buffer_id, cx);
11860 }
11861 })
11862 .ok();
11863 });
11864 }
11865 }
11866
11867 pub fn fold_selected_ranges(
11868 &mut self,
11869 _: &FoldSelectedRanges,
11870 window: &mut Window,
11871 cx: &mut Context<Self>,
11872 ) {
11873 let selections = self.selections.all::<Point>(cx);
11874 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11875 let line_mode = self.selections.line_mode;
11876 let ranges = selections
11877 .into_iter()
11878 .map(|s| {
11879 if line_mode {
11880 let start = Point::new(s.start.row, 0);
11881 let end = Point::new(
11882 s.end.row,
11883 display_map
11884 .buffer_snapshot
11885 .line_len(MultiBufferRow(s.end.row)),
11886 );
11887 Crease::simple(start..end, display_map.fold_placeholder.clone())
11888 } else {
11889 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11890 }
11891 })
11892 .collect::<Vec<_>>();
11893 self.fold_creases(ranges, true, window, cx);
11894 }
11895
11896 pub fn fold_ranges<T: ToOffset + Clone>(
11897 &mut self,
11898 ranges: Vec<Range<T>>,
11899 auto_scroll: bool,
11900 window: &mut Window,
11901 cx: &mut Context<Self>,
11902 ) {
11903 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11904 let ranges = ranges
11905 .into_iter()
11906 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
11907 .collect::<Vec<_>>();
11908 self.fold_creases(ranges, auto_scroll, window, cx);
11909 }
11910
11911 pub fn fold_creases<T: ToOffset + Clone>(
11912 &mut self,
11913 creases: Vec<Crease<T>>,
11914 auto_scroll: bool,
11915 window: &mut Window,
11916 cx: &mut Context<Self>,
11917 ) {
11918 if creases.is_empty() {
11919 return;
11920 }
11921
11922 let mut buffers_affected = HashSet::default();
11923 let multi_buffer = self.buffer().read(cx);
11924 for crease in &creases {
11925 if let Some((_, buffer, _)) =
11926 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11927 {
11928 buffers_affected.insert(buffer.read(cx).remote_id());
11929 };
11930 }
11931
11932 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11933
11934 if auto_scroll {
11935 self.request_autoscroll(Autoscroll::fit(), cx);
11936 }
11937
11938 cx.notify();
11939
11940 if let Some(active_diagnostics) = self.active_diagnostics.take() {
11941 // Clear diagnostics block when folding a range that contains it.
11942 let snapshot = self.snapshot(window, cx);
11943 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11944 drop(snapshot);
11945 self.active_diagnostics = Some(active_diagnostics);
11946 self.dismiss_diagnostics(cx);
11947 } else {
11948 self.active_diagnostics = Some(active_diagnostics);
11949 }
11950 }
11951
11952 self.scrollbar_marker_state.dirty = true;
11953 }
11954
11955 /// Removes any folds whose ranges intersect any of the given ranges.
11956 pub fn unfold_ranges<T: ToOffset + Clone>(
11957 &mut self,
11958 ranges: &[Range<T>],
11959 inclusive: bool,
11960 auto_scroll: bool,
11961 cx: &mut Context<Self>,
11962 ) {
11963 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11964 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11965 });
11966 }
11967
11968 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
11969 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
11970 return;
11971 }
11972 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
11973 self.display_map
11974 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
11975 cx.emit(EditorEvent::BufferFoldToggled {
11976 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11977 folded: true,
11978 });
11979 cx.notify();
11980 }
11981
11982 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
11983 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
11984 return;
11985 }
11986 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
11987 self.display_map.update(cx, |display_map, cx| {
11988 display_map.unfold_buffer(buffer_id, cx);
11989 });
11990 cx.emit(EditorEvent::BufferFoldToggled {
11991 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11992 folded: false,
11993 });
11994 cx.notify();
11995 }
11996
11997 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
11998 self.display_map.read(cx).is_buffer_folded(buffer)
11999 }
12000
12001 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12002 self.display_map.read(cx).folded_buffers()
12003 }
12004
12005 /// Removes any folds with the given ranges.
12006 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12007 &mut self,
12008 ranges: &[Range<T>],
12009 type_id: TypeId,
12010 auto_scroll: bool,
12011 cx: &mut Context<Self>,
12012 ) {
12013 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12014 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12015 });
12016 }
12017
12018 fn remove_folds_with<T: ToOffset + Clone>(
12019 &mut self,
12020 ranges: &[Range<T>],
12021 auto_scroll: bool,
12022 cx: &mut Context<Self>,
12023 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12024 ) {
12025 if ranges.is_empty() {
12026 return;
12027 }
12028
12029 let mut buffers_affected = HashSet::default();
12030 let multi_buffer = self.buffer().read(cx);
12031 for range in ranges {
12032 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12033 buffers_affected.insert(buffer.read(cx).remote_id());
12034 };
12035 }
12036
12037 self.display_map.update(cx, update);
12038
12039 if auto_scroll {
12040 self.request_autoscroll(Autoscroll::fit(), cx);
12041 }
12042
12043 cx.notify();
12044 self.scrollbar_marker_state.dirty = true;
12045 self.active_indent_guides_state.dirty = true;
12046 }
12047
12048 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12049 self.display_map.read(cx).fold_placeholder.clone()
12050 }
12051
12052 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12053 self.buffer.update(cx, |buffer, cx| {
12054 buffer.set_all_diff_hunks_expanded(cx);
12055 });
12056 }
12057
12058 pub fn expand_all_diff_hunks(
12059 &mut self,
12060 _: &ExpandAllHunkDiffs,
12061 _window: &mut Window,
12062 cx: &mut Context<Self>,
12063 ) {
12064 self.buffer.update(cx, |buffer, cx| {
12065 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12066 });
12067 }
12068
12069 pub fn toggle_selected_diff_hunks(
12070 &mut self,
12071 _: &ToggleSelectedDiffHunks,
12072 _window: &mut Window,
12073 cx: &mut Context<Self>,
12074 ) {
12075 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12076 self.toggle_diff_hunks_in_ranges(ranges, cx);
12077 }
12078
12079 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12080 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12081 self.buffer
12082 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12083 }
12084
12085 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12086 self.buffer.update(cx, |buffer, cx| {
12087 let ranges = vec![Anchor::min()..Anchor::max()];
12088 if !buffer.all_diff_hunks_expanded()
12089 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12090 {
12091 buffer.collapse_diff_hunks(ranges, cx);
12092 true
12093 } else {
12094 false
12095 }
12096 })
12097 }
12098
12099 fn toggle_diff_hunks_in_ranges(
12100 &mut self,
12101 ranges: Vec<Range<Anchor>>,
12102 cx: &mut Context<'_, Editor>,
12103 ) {
12104 self.buffer.update(cx, |buffer, cx| {
12105 if buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx) {
12106 buffer.collapse_diff_hunks(ranges, cx)
12107 } else {
12108 buffer.expand_diff_hunks(ranges, cx)
12109 }
12110 })
12111 }
12112
12113 pub(crate) fn apply_all_diff_hunks(
12114 &mut self,
12115 _: &ApplyAllDiffHunks,
12116 window: &mut Window,
12117 cx: &mut Context<Self>,
12118 ) {
12119 let buffers = self.buffer.read(cx).all_buffers();
12120 for branch_buffer in buffers {
12121 branch_buffer.update(cx, |branch_buffer, cx| {
12122 branch_buffer.merge_into_base(Vec::new(), cx);
12123 });
12124 }
12125
12126 if let Some(project) = self.project.clone() {
12127 self.save(true, project, window, cx).detach_and_log_err(cx);
12128 }
12129 }
12130
12131 pub(crate) fn apply_selected_diff_hunks(
12132 &mut self,
12133 _: &ApplyDiffHunk,
12134 window: &mut Window,
12135 cx: &mut Context<Self>,
12136 ) {
12137 let snapshot = self.snapshot(window, cx);
12138 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12139 let mut ranges_by_buffer = HashMap::default();
12140 self.transact(window, cx, |editor, _window, cx| {
12141 for hunk in hunks {
12142 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12143 ranges_by_buffer
12144 .entry(buffer.clone())
12145 .or_insert_with(Vec::new)
12146 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12147 }
12148 }
12149
12150 for (buffer, ranges) in ranges_by_buffer {
12151 buffer.update(cx, |buffer, cx| {
12152 buffer.merge_into_base(ranges, cx);
12153 });
12154 }
12155 });
12156
12157 if let Some(project) = self.project.clone() {
12158 self.save(true, project, window, cx).detach_and_log_err(cx);
12159 }
12160 }
12161
12162 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12163 if hovered != self.gutter_hovered {
12164 self.gutter_hovered = hovered;
12165 cx.notify();
12166 }
12167 }
12168
12169 pub fn insert_blocks(
12170 &mut self,
12171 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12172 autoscroll: Option<Autoscroll>,
12173 cx: &mut Context<Self>,
12174 ) -> Vec<CustomBlockId> {
12175 let blocks = self
12176 .display_map
12177 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12178 if let Some(autoscroll) = autoscroll {
12179 self.request_autoscroll(autoscroll, cx);
12180 }
12181 cx.notify();
12182 blocks
12183 }
12184
12185 pub fn resize_blocks(
12186 &mut self,
12187 heights: HashMap<CustomBlockId, u32>,
12188 autoscroll: Option<Autoscroll>,
12189 cx: &mut Context<Self>,
12190 ) {
12191 self.display_map
12192 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12193 if let Some(autoscroll) = autoscroll {
12194 self.request_autoscroll(autoscroll, cx);
12195 }
12196 cx.notify();
12197 }
12198
12199 pub fn replace_blocks(
12200 &mut self,
12201 renderers: HashMap<CustomBlockId, RenderBlock>,
12202 autoscroll: Option<Autoscroll>,
12203 cx: &mut Context<Self>,
12204 ) {
12205 self.display_map
12206 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12207 if let Some(autoscroll) = autoscroll {
12208 self.request_autoscroll(autoscroll, cx);
12209 }
12210 cx.notify();
12211 }
12212
12213 pub fn remove_blocks(
12214 &mut self,
12215 block_ids: HashSet<CustomBlockId>,
12216 autoscroll: Option<Autoscroll>,
12217 cx: &mut Context<Self>,
12218 ) {
12219 self.display_map.update(cx, |display_map, cx| {
12220 display_map.remove_blocks(block_ids, cx)
12221 });
12222 if let Some(autoscroll) = autoscroll {
12223 self.request_autoscroll(autoscroll, cx);
12224 }
12225 cx.notify();
12226 }
12227
12228 pub fn row_for_block(
12229 &self,
12230 block_id: CustomBlockId,
12231 cx: &mut Context<Self>,
12232 ) -> Option<DisplayRow> {
12233 self.display_map
12234 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12235 }
12236
12237 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12238 self.focused_block = Some(focused_block);
12239 }
12240
12241 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12242 self.focused_block.take()
12243 }
12244
12245 pub fn insert_creases(
12246 &mut self,
12247 creases: impl IntoIterator<Item = Crease<Anchor>>,
12248 cx: &mut Context<Self>,
12249 ) -> Vec<CreaseId> {
12250 self.display_map
12251 .update(cx, |map, cx| map.insert_creases(creases, cx))
12252 }
12253
12254 pub fn remove_creases(
12255 &mut self,
12256 ids: impl IntoIterator<Item = CreaseId>,
12257 cx: &mut Context<Self>,
12258 ) {
12259 self.display_map
12260 .update(cx, |map, cx| map.remove_creases(ids, cx));
12261 }
12262
12263 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12264 self.display_map
12265 .update(cx, |map, cx| map.snapshot(cx))
12266 .longest_row()
12267 }
12268
12269 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12270 self.display_map
12271 .update(cx, |map, cx| map.snapshot(cx))
12272 .max_point()
12273 }
12274
12275 pub fn text(&self, cx: &App) -> String {
12276 self.buffer.read(cx).read(cx).text()
12277 }
12278
12279 pub fn is_empty(&self, cx: &App) -> bool {
12280 self.buffer.read(cx).read(cx).is_empty()
12281 }
12282
12283 pub fn text_option(&self, cx: &App) -> Option<String> {
12284 let text = self.text(cx);
12285 let text = text.trim();
12286
12287 if text.is_empty() {
12288 return None;
12289 }
12290
12291 Some(text.to_string())
12292 }
12293
12294 pub fn set_text(
12295 &mut self,
12296 text: impl Into<Arc<str>>,
12297 window: &mut Window,
12298 cx: &mut Context<Self>,
12299 ) {
12300 self.transact(window, cx, |this, _, cx| {
12301 this.buffer
12302 .read(cx)
12303 .as_singleton()
12304 .expect("you can only call set_text on editors for singleton buffers")
12305 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12306 });
12307 }
12308
12309 pub fn display_text(&self, cx: &mut App) -> String {
12310 self.display_map
12311 .update(cx, |map, cx| map.snapshot(cx))
12312 .text()
12313 }
12314
12315 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12316 let mut wrap_guides = smallvec::smallvec![];
12317
12318 if self.show_wrap_guides == Some(false) {
12319 return wrap_guides;
12320 }
12321
12322 let settings = self.buffer.read(cx).settings_at(0, cx);
12323 if settings.show_wrap_guides {
12324 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12325 wrap_guides.push((soft_wrap as usize, true));
12326 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12327 wrap_guides.push((soft_wrap as usize, true));
12328 }
12329 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12330 }
12331
12332 wrap_guides
12333 }
12334
12335 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12336 let settings = self.buffer.read(cx).settings_at(0, cx);
12337 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12338 match mode {
12339 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12340 SoftWrap::None
12341 }
12342 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12343 language_settings::SoftWrap::PreferredLineLength => {
12344 SoftWrap::Column(settings.preferred_line_length)
12345 }
12346 language_settings::SoftWrap::Bounded => {
12347 SoftWrap::Bounded(settings.preferred_line_length)
12348 }
12349 }
12350 }
12351
12352 pub fn set_soft_wrap_mode(
12353 &mut self,
12354 mode: language_settings::SoftWrap,
12355
12356 cx: &mut Context<Self>,
12357 ) {
12358 self.soft_wrap_mode_override = Some(mode);
12359 cx.notify();
12360 }
12361
12362 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12363 self.text_style_refinement = Some(style);
12364 }
12365
12366 /// called by the Element so we know what style we were most recently rendered with.
12367 pub(crate) fn set_style(
12368 &mut self,
12369 style: EditorStyle,
12370 window: &mut Window,
12371 cx: &mut Context<Self>,
12372 ) {
12373 let rem_size = window.rem_size();
12374 self.display_map.update(cx, |map, cx| {
12375 map.set_font(
12376 style.text.font(),
12377 style.text.font_size.to_pixels(rem_size),
12378 cx,
12379 )
12380 });
12381 self.style = Some(style);
12382 }
12383
12384 pub fn style(&self) -> Option<&EditorStyle> {
12385 self.style.as_ref()
12386 }
12387
12388 // Called by the element. This method is not designed to be called outside of the editor
12389 // element's layout code because it does not notify when rewrapping is computed synchronously.
12390 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12391 self.display_map
12392 .update(cx, |map, cx| map.set_wrap_width(width, cx))
12393 }
12394
12395 pub fn set_soft_wrap(&mut self) {
12396 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12397 }
12398
12399 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12400 if self.soft_wrap_mode_override.is_some() {
12401 self.soft_wrap_mode_override.take();
12402 } else {
12403 let soft_wrap = match self.soft_wrap_mode(cx) {
12404 SoftWrap::GitDiff => return,
12405 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12406 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12407 language_settings::SoftWrap::None
12408 }
12409 };
12410 self.soft_wrap_mode_override = Some(soft_wrap);
12411 }
12412 cx.notify();
12413 }
12414
12415 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12416 let Some(workspace) = self.workspace() else {
12417 return;
12418 };
12419 let fs = workspace.read(cx).app_state().fs.clone();
12420 let current_show = TabBarSettings::get_global(cx).show;
12421 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12422 setting.show = Some(!current_show);
12423 });
12424 }
12425
12426 pub fn toggle_indent_guides(
12427 &mut self,
12428 _: &ToggleIndentGuides,
12429 _: &mut Window,
12430 cx: &mut Context<Self>,
12431 ) {
12432 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12433 self.buffer
12434 .read(cx)
12435 .settings_at(0, cx)
12436 .indent_guides
12437 .enabled
12438 });
12439 self.show_indent_guides = Some(!currently_enabled);
12440 cx.notify();
12441 }
12442
12443 fn should_show_indent_guides(&self) -> Option<bool> {
12444 self.show_indent_guides
12445 }
12446
12447 pub fn toggle_line_numbers(
12448 &mut self,
12449 _: &ToggleLineNumbers,
12450 _: &mut Window,
12451 cx: &mut Context<Self>,
12452 ) {
12453 let mut editor_settings = EditorSettings::get_global(cx).clone();
12454 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12455 EditorSettings::override_global(editor_settings, cx);
12456 }
12457
12458 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12459 self.use_relative_line_numbers
12460 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12461 }
12462
12463 pub fn toggle_relative_line_numbers(
12464 &mut self,
12465 _: &ToggleRelativeLineNumbers,
12466 _: &mut Window,
12467 cx: &mut Context<Self>,
12468 ) {
12469 let is_relative = self.should_use_relative_line_numbers(cx);
12470 self.set_relative_line_number(Some(!is_relative), cx)
12471 }
12472
12473 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12474 self.use_relative_line_numbers = is_relative;
12475 cx.notify();
12476 }
12477
12478 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12479 self.show_gutter = show_gutter;
12480 cx.notify();
12481 }
12482
12483 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12484 self.show_scrollbars = show_scrollbars;
12485 cx.notify();
12486 }
12487
12488 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12489 self.show_line_numbers = Some(show_line_numbers);
12490 cx.notify();
12491 }
12492
12493 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12494 self.show_git_diff_gutter = Some(show_git_diff_gutter);
12495 cx.notify();
12496 }
12497
12498 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12499 self.show_code_actions = Some(show_code_actions);
12500 cx.notify();
12501 }
12502
12503 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12504 self.show_runnables = Some(show_runnables);
12505 cx.notify();
12506 }
12507
12508 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12509 if self.display_map.read(cx).masked != masked {
12510 self.display_map.update(cx, |map, _| map.masked = masked);
12511 }
12512 cx.notify()
12513 }
12514
12515 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12516 self.show_wrap_guides = Some(show_wrap_guides);
12517 cx.notify();
12518 }
12519
12520 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12521 self.show_indent_guides = Some(show_indent_guides);
12522 cx.notify();
12523 }
12524
12525 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12526 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12527 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12528 if let Some(dir) = file.abs_path(cx).parent() {
12529 return Some(dir.to_owned());
12530 }
12531 }
12532
12533 if let Some(project_path) = buffer.read(cx).project_path(cx) {
12534 return Some(project_path.path.to_path_buf());
12535 }
12536 }
12537
12538 None
12539 }
12540
12541 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12542 self.active_excerpt(cx)?
12543 .1
12544 .read(cx)
12545 .file()
12546 .and_then(|f| f.as_local())
12547 }
12548
12549 fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12550 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12551 let project_path = buffer.read(cx).project_path(cx)?;
12552 let project = self.project.as_ref()?.read(cx);
12553 project.absolute_path(&project_path, cx)
12554 })
12555 }
12556
12557 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12558 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12559 let project_path = buffer.read(cx).project_path(cx)?;
12560 let project = self.project.as_ref()?.read(cx);
12561 let entry = project.entry_for_path(&project_path, cx)?;
12562 let path = entry.path.to_path_buf();
12563 Some(path)
12564 })
12565 }
12566
12567 pub fn reveal_in_finder(
12568 &mut self,
12569 _: &RevealInFileManager,
12570 _window: &mut Window,
12571 cx: &mut Context<Self>,
12572 ) {
12573 if let Some(target) = self.target_file(cx) {
12574 cx.reveal_path(&target.abs_path(cx));
12575 }
12576 }
12577
12578 pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12579 if let Some(path) = self.target_file_abs_path(cx) {
12580 if let Some(path) = path.to_str() {
12581 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12582 }
12583 }
12584 }
12585
12586 pub fn copy_relative_path(
12587 &mut self,
12588 _: &CopyRelativePath,
12589 _window: &mut Window,
12590 cx: &mut Context<Self>,
12591 ) {
12592 if let Some(path) = self.target_file_path(cx) {
12593 if let Some(path) = path.to_str() {
12594 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12595 }
12596 }
12597 }
12598
12599 pub fn toggle_git_blame(
12600 &mut self,
12601 _: &ToggleGitBlame,
12602 window: &mut Window,
12603 cx: &mut Context<Self>,
12604 ) {
12605 self.show_git_blame_gutter = !self.show_git_blame_gutter;
12606
12607 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12608 self.start_git_blame(true, window, cx);
12609 }
12610
12611 cx.notify();
12612 }
12613
12614 pub fn toggle_git_blame_inline(
12615 &mut self,
12616 _: &ToggleGitBlameInline,
12617 window: &mut Window,
12618 cx: &mut Context<Self>,
12619 ) {
12620 self.toggle_git_blame_inline_internal(true, window, cx);
12621 cx.notify();
12622 }
12623
12624 pub fn git_blame_inline_enabled(&self) -> bool {
12625 self.git_blame_inline_enabled
12626 }
12627
12628 pub fn toggle_selection_menu(
12629 &mut self,
12630 _: &ToggleSelectionMenu,
12631 _: &mut Window,
12632 cx: &mut Context<Self>,
12633 ) {
12634 self.show_selection_menu = self
12635 .show_selection_menu
12636 .map(|show_selections_menu| !show_selections_menu)
12637 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12638
12639 cx.notify();
12640 }
12641
12642 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12643 self.show_selection_menu
12644 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12645 }
12646
12647 fn start_git_blame(
12648 &mut self,
12649 user_triggered: bool,
12650 window: &mut Window,
12651 cx: &mut Context<Self>,
12652 ) {
12653 if let Some(project) = self.project.as_ref() {
12654 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12655 return;
12656 };
12657
12658 if buffer.read(cx).file().is_none() {
12659 return;
12660 }
12661
12662 let focused = self.focus_handle(cx).contains_focused(window, cx);
12663
12664 let project = project.clone();
12665 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12666 self.blame_subscription =
12667 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12668 self.blame = Some(blame);
12669 }
12670 }
12671
12672 fn toggle_git_blame_inline_internal(
12673 &mut self,
12674 user_triggered: bool,
12675 window: &mut Window,
12676 cx: &mut Context<Self>,
12677 ) {
12678 if self.git_blame_inline_enabled {
12679 self.git_blame_inline_enabled = false;
12680 self.show_git_blame_inline = false;
12681 self.show_git_blame_inline_delay_task.take();
12682 } else {
12683 self.git_blame_inline_enabled = true;
12684 self.start_git_blame_inline(user_triggered, window, cx);
12685 }
12686
12687 cx.notify();
12688 }
12689
12690 fn start_git_blame_inline(
12691 &mut self,
12692 user_triggered: bool,
12693 window: &mut Window,
12694 cx: &mut Context<Self>,
12695 ) {
12696 self.start_git_blame(user_triggered, window, cx);
12697
12698 if ProjectSettings::get_global(cx)
12699 .git
12700 .inline_blame_delay()
12701 .is_some()
12702 {
12703 self.start_inline_blame_timer(window, cx);
12704 } else {
12705 self.show_git_blame_inline = true
12706 }
12707 }
12708
12709 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12710 self.blame.as_ref()
12711 }
12712
12713 pub fn show_git_blame_gutter(&self) -> bool {
12714 self.show_git_blame_gutter
12715 }
12716
12717 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12718 self.show_git_blame_gutter && self.has_blame_entries(cx)
12719 }
12720
12721 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12722 self.show_git_blame_inline
12723 && self.focus_handle.is_focused(window)
12724 && !self.newest_selection_head_on_empty_line(cx)
12725 && self.has_blame_entries(cx)
12726 }
12727
12728 fn has_blame_entries(&self, cx: &App) -> bool {
12729 self.blame()
12730 .map_or(false, |blame| blame.read(cx).has_generated_entries())
12731 }
12732
12733 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12734 let cursor_anchor = self.selections.newest_anchor().head();
12735
12736 let snapshot = self.buffer.read(cx).snapshot(cx);
12737 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12738
12739 snapshot.line_len(buffer_row) == 0
12740 }
12741
12742 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12743 let buffer_and_selection = maybe!({
12744 let selection = self.selections.newest::<Point>(cx);
12745 let selection_range = selection.range();
12746
12747 let multi_buffer = self.buffer().read(cx);
12748 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12749 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12750
12751 let (buffer, range, _) = if selection.reversed {
12752 buffer_ranges.first()
12753 } else {
12754 buffer_ranges.last()
12755 }?;
12756
12757 let selection = text::ToPoint::to_point(&range.start, &buffer).row
12758 ..text::ToPoint::to_point(&range.end, &buffer).row;
12759 Some((
12760 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
12761 selection,
12762 ))
12763 });
12764
12765 let Some((buffer, selection)) = buffer_and_selection else {
12766 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12767 };
12768
12769 let Some(project) = self.project.as_ref() else {
12770 return Task::ready(Err(anyhow!("editor does not have project")));
12771 };
12772
12773 project.update(cx, |project, cx| {
12774 project.get_permalink_to_line(&buffer, selection, cx)
12775 })
12776 }
12777
12778 pub fn copy_permalink_to_line(
12779 &mut self,
12780 _: &CopyPermalinkToLine,
12781 window: &mut Window,
12782 cx: &mut Context<Self>,
12783 ) {
12784 let permalink_task = self.get_permalink_to_line(cx);
12785 let workspace = self.workspace();
12786
12787 cx.spawn_in(window, |_, mut cx| async move {
12788 match permalink_task.await {
12789 Ok(permalink) => {
12790 cx.update(|_, cx| {
12791 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12792 })
12793 .ok();
12794 }
12795 Err(err) => {
12796 let message = format!("Failed to copy permalink: {err}");
12797
12798 Err::<(), anyhow::Error>(err).log_err();
12799
12800 if let Some(workspace) = workspace {
12801 workspace
12802 .update_in(&mut cx, |workspace, _, cx| {
12803 struct CopyPermalinkToLine;
12804
12805 workspace.show_toast(
12806 Toast::new(
12807 NotificationId::unique::<CopyPermalinkToLine>(),
12808 message,
12809 ),
12810 cx,
12811 )
12812 })
12813 .ok();
12814 }
12815 }
12816 }
12817 })
12818 .detach();
12819 }
12820
12821 pub fn copy_file_location(
12822 &mut self,
12823 _: &CopyFileLocation,
12824 _: &mut Window,
12825 cx: &mut Context<Self>,
12826 ) {
12827 let selection = self.selections.newest::<Point>(cx).start.row + 1;
12828 if let Some(file) = self.target_file(cx) {
12829 if let Some(path) = file.path().to_str() {
12830 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
12831 }
12832 }
12833 }
12834
12835 pub fn open_permalink_to_line(
12836 &mut self,
12837 _: &OpenPermalinkToLine,
12838 window: &mut Window,
12839 cx: &mut Context<Self>,
12840 ) {
12841 let permalink_task = self.get_permalink_to_line(cx);
12842 let workspace = self.workspace();
12843
12844 cx.spawn_in(window, |_, mut cx| async move {
12845 match permalink_task.await {
12846 Ok(permalink) => {
12847 cx.update(|_, cx| {
12848 cx.open_url(permalink.as_ref());
12849 })
12850 .ok();
12851 }
12852 Err(err) => {
12853 let message = format!("Failed to open permalink: {err}");
12854
12855 Err::<(), anyhow::Error>(err).log_err();
12856
12857 if let Some(workspace) = workspace {
12858 workspace
12859 .update(&mut cx, |workspace, cx| {
12860 struct OpenPermalinkToLine;
12861
12862 workspace.show_toast(
12863 Toast::new(
12864 NotificationId::unique::<OpenPermalinkToLine>(),
12865 message,
12866 ),
12867 cx,
12868 )
12869 })
12870 .ok();
12871 }
12872 }
12873 }
12874 })
12875 .detach();
12876 }
12877
12878 pub fn insert_uuid_v4(
12879 &mut self,
12880 _: &InsertUuidV4,
12881 window: &mut Window,
12882 cx: &mut Context<Self>,
12883 ) {
12884 self.insert_uuid(UuidVersion::V4, window, cx);
12885 }
12886
12887 pub fn insert_uuid_v7(
12888 &mut self,
12889 _: &InsertUuidV7,
12890 window: &mut Window,
12891 cx: &mut Context<Self>,
12892 ) {
12893 self.insert_uuid(UuidVersion::V7, window, cx);
12894 }
12895
12896 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
12897 self.transact(window, cx, |this, window, cx| {
12898 let edits = this
12899 .selections
12900 .all::<Point>(cx)
12901 .into_iter()
12902 .map(|selection| {
12903 let uuid = match version {
12904 UuidVersion::V4 => uuid::Uuid::new_v4(),
12905 UuidVersion::V7 => uuid::Uuid::now_v7(),
12906 };
12907
12908 (selection.range(), uuid.to_string())
12909 });
12910 this.edit(edits, cx);
12911 this.refresh_inline_completion(true, false, window, cx);
12912 });
12913 }
12914
12915 pub fn open_selections_in_multibuffer(
12916 &mut self,
12917 _: &OpenSelectionsInMultibuffer,
12918 window: &mut Window,
12919 cx: &mut Context<Self>,
12920 ) {
12921 let multibuffer = self.buffer.read(cx);
12922
12923 let Some(buffer) = multibuffer.as_singleton() else {
12924 return;
12925 };
12926
12927 let Some(workspace) = self.workspace() else {
12928 return;
12929 };
12930
12931 let locations = self
12932 .selections
12933 .disjoint_anchors()
12934 .iter()
12935 .map(|range| Location {
12936 buffer: buffer.clone(),
12937 range: range.start.text_anchor..range.end.text_anchor,
12938 })
12939 .collect::<Vec<_>>();
12940
12941 let title = multibuffer.title(cx).to_string();
12942
12943 cx.spawn_in(window, |_, mut cx| async move {
12944 workspace.update_in(&mut cx, |workspace, window, cx| {
12945 Self::open_locations_in_multibuffer(
12946 workspace,
12947 locations,
12948 format!("Selections for '{title}'"),
12949 false,
12950 MultibufferSelectionMode::All,
12951 window,
12952 cx,
12953 );
12954 })
12955 })
12956 .detach();
12957 }
12958
12959 /// Adds a row highlight for the given range. If a row has multiple highlights, the
12960 /// last highlight added will be used.
12961 ///
12962 /// If the range ends at the beginning of a line, then that line will not be highlighted.
12963 pub fn highlight_rows<T: 'static>(
12964 &mut self,
12965 range: Range<Anchor>,
12966 color: Hsla,
12967 should_autoscroll: bool,
12968 cx: &mut Context<Self>,
12969 ) {
12970 let snapshot = self.buffer().read(cx).snapshot(cx);
12971 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12972 let ix = row_highlights.binary_search_by(|highlight| {
12973 Ordering::Equal
12974 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
12975 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
12976 });
12977
12978 if let Err(mut ix) = ix {
12979 let index = post_inc(&mut self.highlight_order);
12980
12981 // If this range intersects with the preceding highlight, then merge it with
12982 // the preceding highlight. Otherwise insert a new highlight.
12983 let mut merged = false;
12984 if ix > 0 {
12985 let prev_highlight = &mut row_highlights[ix - 1];
12986 if prev_highlight
12987 .range
12988 .end
12989 .cmp(&range.start, &snapshot)
12990 .is_ge()
12991 {
12992 ix -= 1;
12993 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
12994 prev_highlight.range.end = range.end;
12995 }
12996 merged = true;
12997 prev_highlight.index = index;
12998 prev_highlight.color = color;
12999 prev_highlight.should_autoscroll = should_autoscroll;
13000 }
13001 }
13002
13003 if !merged {
13004 row_highlights.insert(
13005 ix,
13006 RowHighlight {
13007 range: range.clone(),
13008 index,
13009 color,
13010 should_autoscroll,
13011 },
13012 );
13013 }
13014
13015 // If any of the following highlights intersect with this one, merge them.
13016 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13017 let highlight = &row_highlights[ix];
13018 if next_highlight
13019 .range
13020 .start
13021 .cmp(&highlight.range.end, &snapshot)
13022 .is_le()
13023 {
13024 if next_highlight
13025 .range
13026 .end
13027 .cmp(&highlight.range.end, &snapshot)
13028 .is_gt()
13029 {
13030 row_highlights[ix].range.end = next_highlight.range.end;
13031 }
13032 row_highlights.remove(ix + 1);
13033 } else {
13034 break;
13035 }
13036 }
13037 }
13038 }
13039
13040 /// Remove any highlighted row ranges of the given type that intersect the
13041 /// given ranges.
13042 pub fn remove_highlighted_rows<T: 'static>(
13043 &mut self,
13044 ranges_to_remove: Vec<Range<Anchor>>,
13045 cx: &mut Context<Self>,
13046 ) {
13047 let snapshot = self.buffer().read(cx).snapshot(cx);
13048 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13049 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13050 row_highlights.retain(|highlight| {
13051 while let Some(range_to_remove) = ranges_to_remove.peek() {
13052 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13053 Ordering::Less | Ordering::Equal => {
13054 ranges_to_remove.next();
13055 }
13056 Ordering::Greater => {
13057 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13058 Ordering::Less | Ordering::Equal => {
13059 return false;
13060 }
13061 Ordering::Greater => break,
13062 }
13063 }
13064 }
13065 }
13066
13067 true
13068 })
13069 }
13070
13071 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13072 pub fn clear_row_highlights<T: 'static>(&mut self) {
13073 self.highlighted_rows.remove(&TypeId::of::<T>());
13074 }
13075
13076 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13077 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13078 self.highlighted_rows
13079 .get(&TypeId::of::<T>())
13080 .map_or(&[] as &[_], |vec| vec.as_slice())
13081 .iter()
13082 .map(|highlight| (highlight.range.clone(), highlight.color))
13083 }
13084
13085 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13086 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13087 /// Allows to ignore certain kinds of highlights.
13088 pub fn highlighted_display_rows(
13089 &self,
13090 window: &mut Window,
13091 cx: &mut App,
13092 ) -> BTreeMap<DisplayRow, Hsla> {
13093 let snapshot = self.snapshot(window, cx);
13094 let mut used_highlight_orders = HashMap::default();
13095 self.highlighted_rows
13096 .iter()
13097 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13098 .fold(
13099 BTreeMap::<DisplayRow, Hsla>::new(),
13100 |mut unique_rows, highlight| {
13101 let start = highlight.range.start.to_display_point(&snapshot);
13102 let end = highlight.range.end.to_display_point(&snapshot);
13103 let start_row = start.row().0;
13104 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13105 && end.column() == 0
13106 {
13107 end.row().0.saturating_sub(1)
13108 } else {
13109 end.row().0
13110 };
13111 for row in start_row..=end_row {
13112 let used_index =
13113 used_highlight_orders.entry(row).or_insert(highlight.index);
13114 if highlight.index >= *used_index {
13115 *used_index = highlight.index;
13116 unique_rows.insert(DisplayRow(row), highlight.color);
13117 }
13118 }
13119 unique_rows
13120 },
13121 )
13122 }
13123
13124 pub fn highlighted_display_row_for_autoscroll(
13125 &self,
13126 snapshot: &DisplaySnapshot,
13127 ) -> Option<DisplayRow> {
13128 self.highlighted_rows
13129 .values()
13130 .flat_map(|highlighted_rows| highlighted_rows.iter())
13131 .filter_map(|highlight| {
13132 if highlight.should_autoscroll {
13133 Some(highlight.range.start.to_display_point(snapshot).row())
13134 } else {
13135 None
13136 }
13137 })
13138 .min()
13139 }
13140
13141 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13142 self.highlight_background::<SearchWithinRange>(
13143 ranges,
13144 |colors| colors.editor_document_highlight_read_background,
13145 cx,
13146 )
13147 }
13148
13149 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13150 self.breadcrumb_header = Some(new_header);
13151 }
13152
13153 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13154 self.clear_background_highlights::<SearchWithinRange>(cx);
13155 }
13156
13157 pub fn highlight_background<T: 'static>(
13158 &mut self,
13159 ranges: &[Range<Anchor>],
13160 color_fetcher: fn(&ThemeColors) -> Hsla,
13161 cx: &mut Context<Self>,
13162 ) {
13163 self.background_highlights
13164 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13165 self.scrollbar_marker_state.dirty = true;
13166 cx.notify();
13167 }
13168
13169 pub fn clear_background_highlights<T: 'static>(
13170 &mut self,
13171 cx: &mut Context<Self>,
13172 ) -> Option<BackgroundHighlight> {
13173 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13174 if !text_highlights.1.is_empty() {
13175 self.scrollbar_marker_state.dirty = true;
13176 cx.notify();
13177 }
13178 Some(text_highlights)
13179 }
13180
13181 pub fn highlight_gutter<T: 'static>(
13182 &mut self,
13183 ranges: &[Range<Anchor>],
13184 color_fetcher: fn(&App) -> Hsla,
13185 cx: &mut Context<Self>,
13186 ) {
13187 self.gutter_highlights
13188 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13189 cx.notify();
13190 }
13191
13192 pub fn clear_gutter_highlights<T: 'static>(
13193 &mut self,
13194 cx: &mut Context<Self>,
13195 ) -> Option<GutterHighlight> {
13196 cx.notify();
13197 self.gutter_highlights.remove(&TypeId::of::<T>())
13198 }
13199
13200 #[cfg(feature = "test-support")]
13201 pub fn all_text_background_highlights(
13202 &self,
13203 window: &mut Window,
13204 cx: &mut Context<Self>,
13205 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13206 let snapshot = self.snapshot(window, cx);
13207 let buffer = &snapshot.buffer_snapshot;
13208 let start = buffer.anchor_before(0);
13209 let end = buffer.anchor_after(buffer.len());
13210 let theme = cx.theme().colors();
13211 self.background_highlights_in_range(start..end, &snapshot, theme)
13212 }
13213
13214 #[cfg(feature = "test-support")]
13215 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13216 let snapshot = self.buffer().read(cx).snapshot(cx);
13217
13218 let highlights = self
13219 .background_highlights
13220 .get(&TypeId::of::<items::BufferSearchHighlights>());
13221
13222 if let Some((_color, ranges)) = highlights {
13223 ranges
13224 .iter()
13225 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13226 .collect_vec()
13227 } else {
13228 vec![]
13229 }
13230 }
13231
13232 fn document_highlights_for_position<'a>(
13233 &'a self,
13234 position: Anchor,
13235 buffer: &'a MultiBufferSnapshot,
13236 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13237 let read_highlights = self
13238 .background_highlights
13239 .get(&TypeId::of::<DocumentHighlightRead>())
13240 .map(|h| &h.1);
13241 let write_highlights = self
13242 .background_highlights
13243 .get(&TypeId::of::<DocumentHighlightWrite>())
13244 .map(|h| &h.1);
13245 let left_position = position.bias_left(buffer);
13246 let right_position = position.bias_right(buffer);
13247 read_highlights
13248 .into_iter()
13249 .chain(write_highlights)
13250 .flat_map(move |ranges| {
13251 let start_ix = match ranges.binary_search_by(|probe| {
13252 let cmp = probe.end.cmp(&left_position, buffer);
13253 if cmp.is_ge() {
13254 Ordering::Greater
13255 } else {
13256 Ordering::Less
13257 }
13258 }) {
13259 Ok(i) | Err(i) => i,
13260 };
13261
13262 ranges[start_ix..]
13263 .iter()
13264 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13265 })
13266 }
13267
13268 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13269 self.background_highlights
13270 .get(&TypeId::of::<T>())
13271 .map_or(false, |(_, highlights)| !highlights.is_empty())
13272 }
13273
13274 pub fn background_highlights_in_range(
13275 &self,
13276 search_range: Range<Anchor>,
13277 display_snapshot: &DisplaySnapshot,
13278 theme: &ThemeColors,
13279 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13280 let mut results = Vec::new();
13281 for (color_fetcher, ranges) in self.background_highlights.values() {
13282 let color = color_fetcher(theme);
13283 let start_ix = match ranges.binary_search_by(|probe| {
13284 let cmp = probe
13285 .end
13286 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13287 if cmp.is_gt() {
13288 Ordering::Greater
13289 } else {
13290 Ordering::Less
13291 }
13292 }) {
13293 Ok(i) | Err(i) => i,
13294 };
13295 for range in &ranges[start_ix..] {
13296 if range
13297 .start
13298 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13299 .is_ge()
13300 {
13301 break;
13302 }
13303
13304 let start = range.start.to_display_point(display_snapshot);
13305 let end = range.end.to_display_point(display_snapshot);
13306 results.push((start..end, color))
13307 }
13308 }
13309 results
13310 }
13311
13312 pub fn background_highlight_row_ranges<T: 'static>(
13313 &self,
13314 search_range: Range<Anchor>,
13315 display_snapshot: &DisplaySnapshot,
13316 count: usize,
13317 ) -> Vec<RangeInclusive<DisplayPoint>> {
13318 let mut results = Vec::new();
13319 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13320 return vec![];
13321 };
13322
13323 let start_ix = match ranges.binary_search_by(|probe| {
13324 let cmp = probe
13325 .end
13326 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13327 if cmp.is_gt() {
13328 Ordering::Greater
13329 } else {
13330 Ordering::Less
13331 }
13332 }) {
13333 Ok(i) | Err(i) => i,
13334 };
13335 let mut push_region = |start: Option<Point>, end: Option<Point>| {
13336 if let (Some(start_display), Some(end_display)) = (start, end) {
13337 results.push(
13338 start_display.to_display_point(display_snapshot)
13339 ..=end_display.to_display_point(display_snapshot),
13340 );
13341 }
13342 };
13343 let mut start_row: Option<Point> = None;
13344 let mut end_row: Option<Point> = None;
13345 if ranges.len() > count {
13346 return Vec::new();
13347 }
13348 for range in &ranges[start_ix..] {
13349 if range
13350 .start
13351 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13352 .is_ge()
13353 {
13354 break;
13355 }
13356 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13357 if let Some(current_row) = &end_row {
13358 if end.row == current_row.row {
13359 continue;
13360 }
13361 }
13362 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13363 if start_row.is_none() {
13364 assert_eq!(end_row, None);
13365 start_row = Some(start);
13366 end_row = Some(end);
13367 continue;
13368 }
13369 if let Some(current_end) = end_row.as_mut() {
13370 if start.row > current_end.row + 1 {
13371 push_region(start_row, end_row);
13372 start_row = Some(start);
13373 end_row = Some(end);
13374 } else {
13375 // Merge two hunks.
13376 *current_end = end;
13377 }
13378 } else {
13379 unreachable!();
13380 }
13381 }
13382 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13383 push_region(start_row, end_row);
13384 results
13385 }
13386
13387 pub fn gutter_highlights_in_range(
13388 &self,
13389 search_range: Range<Anchor>,
13390 display_snapshot: &DisplaySnapshot,
13391 cx: &App,
13392 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13393 let mut results = Vec::new();
13394 for (color_fetcher, ranges) in self.gutter_highlights.values() {
13395 let color = color_fetcher(cx);
13396 let start_ix = match ranges.binary_search_by(|probe| {
13397 let cmp = probe
13398 .end
13399 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13400 if cmp.is_gt() {
13401 Ordering::Greater
13402 } else {
13403 Ordering::Less
13404 }
13405 }) {
13406 Ok(i) | Err(i) => i,
13407 };
13408 for range in &ranges[start_ix..] {
13409 if range
13410 .start
13411 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13412 .is_ge()
13413 {
13414 break;
13415 }
13416
13417 let start = range.start.to_display_point(display_snapshot);
13418 let end = range.end.to_display_point(display_snapshot);
13419 results.push((start..end, color))
13420 }
13421 }
13422 results
13423 }
13424
13425 /// Get the text ranges corresponding to the redaction query
13426 pub fn redacted_ranges(
13427 &self,
13428 search_range: Range<Anchor>,
13429 display_snapshot: &DisplaySnapshot,
13430 cx: &App,
13431 ) -> Vec<Range<DisplayPoint>> {
13432 display_snapshot
13433 .buffer_snapshot
13434 .redacted_ranges(search_range, |file| {
13435 if let Some(file) = file {
13436 file.is_private()
13437 && EditorSettings::get(
13438 Some(SettingsLocation {
13439 worktree_id: file.worktree_id(cx),
13440 path: file.path().as_ref(),
13441 }),
13442 cx,
13443 )
13444 .redact_private_values
13445 } else {
13446 false
13447 }
13448 })
13449 .map(|range| {
13450 range.start.to_display_point(display_snapshot)
13451 ..range.end.to_display_point(display_snapshot)
13452 })
13453 .collect()
13454 }
13455
13456 pub fn highlight_text<T: 'static>(
13457 &mut self,
13458 ranges: Vec<Range<Anchor>>,
13459 style: HighlightStyle,
13460 cx: &mut Context<Self>,
13461 ) {
13462 self.display_map.update(cx, |map, _| {
13463 map.highlight_text(TypeId::of::<T>(), ranges, style)
13464 });
13465 cx.notify();
13466 }
13467
13468 pub(crate) fn highlight_inlays<T: 'static>(
13469 &mut self,
13470 highlights: Vec<InlayHighlight>,
13471 style: HighlightStyle,
13472 cx: &mut Context<Self>,
13473 ) {
13474 self.display_map.update(cx, |map, _| {
13475 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13476 });
13477 cx.notify();
13478 }
13479
13480 pub fn text_highlights<'a, T: 'static>(
13481 &'a self,
13482 cx: &'a App,
13483 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13484 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13485 }
13486
13487 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13488 let cleared = self
13489 .display_map
13490 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13491 if cleared {
13492 cx.notify();
13493 }
13494 }
13495
13496 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13497 (self.read_only(cx) || self.blink_manager.read(cx).visible())
13498 && self.focus_handle.is_focused(window)
13499 }
13500
13501 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13502 self.show_cursor_when_unfocused = is_enabled;
13503 cx.notify();
13504 }
13505
13506 pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13507 self.project
13508 .as_ref()
13509 .map(|project| project.read(cx).lsp_store())
13510 }
13511
13512 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13513 cx.notify();
13514 }
13515
13516 fn on_buffer_event(
13517 &mut self,
13518 multibuffer: &Entity<MultiBuffer>,
13519 event: &multi_buffer::Event,
13520 window: &mut Window,
13521 cx: &mut Context<Self>,
13522 ) {
13523 match event {
13524 multi_buffer::Event::Edited {
13525 singleton_buffer_edited,
13526 edited_buffer: buffer_edited,
13527 } => {
13528 self.scrollbar_marker_state.dirty = true;
13529 self.active_indent_guides_state.dirty = true;
13530 self.refresh_active_diagnostics(cx);
13531 self.refresh_code_actions(window, cx);
13532 if self.has_active_inline_completion() {
13533 self.update_visible_inline_completion(window, cx);
13534 }
13535 if let Some(buffer) = buffer_edited {
13536 let buffer_id = buffer.read(cx).remote_id();
13537 if !self.registered_buffers.contains_key(&buffer_id) {
13538 if let Some(lsp_store) = self.lsp_store(cx) {
13539 lsp_store.update(cx, |lsp_store, cx| {
13540 self.registered_buffers.insert(
13541 buffer_id,
13542 lsp_store.register_buffer_with_language_servers(&buffer, cx),
13543 );
13544 })
13545 }
13546 }
13547 }
13548 cx.emit(EditorEvent::BufferEdited);
13549 cx.emit(SearchEvent::MatchesInvalidated);
13550 if *singleton_buffer_edited {
13551 if let Some(project) = &self.project {
13552 let project = project.read(cx);
13553 #[allow(clippy::mutable_key_type)]
13554 let languages_affected = multibuffer
13555 .read(cx)
13556 .all_buffers()
13557 .into_iter()
13558 .filter_map(|buffer| {
13559 let buffer = buffer.read(cx);
13560 let language = buffer.language()?;
13561 if project.is_local()
13562 && project
13563 .language_servers_for_local_buffer(buffer, cx)
13564 .count()
13565 == 0
13566 {
13567 None
13568 } else {
13569 Some(language)
13570 }
13571 })
13572 .cloned()
13573 .collect::<HashSet<_>>();
13574 if !languages_affected.is_empty() {
13575 self.refresh_inlay_hints(
13576 InlayHintRefreshReason::BufferEdited(languages_affected),
13577 cx,
13578 );
13579 }
13580 }
13581 }
13582
13583 let Some(project) = &self.project else { return };
13584 let (telemetry, is_via_ssh) = {
13585 let project = project.read(cx);
13586 let telemetry = project.client().telemetry().clone();
13587 let is_via_ssh = project.is_via_ssh();
13588 (telemetry, is_via_ssh)
13589 };
13590 refresh_linked_ranges(self, window, cx);
13591 telemetry.log_edit_event("editor", is_via_ssh);
13592 }
13593 multi_buffer::Event::ExcerptsAdded {
13594 buffer,
13595 predecessor,
13596 excerpts,
13597 } => {
13598 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13599 let buffer_id = buffer.read(cx).remote_id();
13600 if self.buffer.read(cx).change_set_for(buffer_id).is_none() {
13601 if let Some(project) = &self.project {
13602 get_unstaged_changes_for_buffers(
13603 project,
13604 [buffer.clone()],
13605 self.buffer.clone(),
13606 cx,
13607 );
13608 }
13609 }
13610 cx.emit(EditorEvent::ExcerptsAdded {
13611 buffer: buffer.clone(),
13612 predecessor: *predecessor,
13613 excerpts: excerpts.clone(),
13614 });
13615 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13616 }
13617 multi_buffer::Event::ExcerptsRemoved { ids } => {
13618 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13619 let buffer = self.buffer.read(cx);
13620 self.registered_buffers
13621 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13622 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13623 }
13624 multi_buffer::Event::ExcerptsEdited { ids } => {
13625 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13626 }
13627 multi_buffer::Event::ExcerptsExpanded { ids } => {
13628 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13629 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13630 }
13631 multi_buffer::Event::Reparsed(buffer_id) => {
13632 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13633
13634 cx.emit(EditorEvent::Reparsed(*buffer_id));
13635 }
13636 multi_buffer::Event::DiffHunksToggled => {
13637 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13638 }
13639 multi_buffer::Event::LanguageChanged(buffer_id) => {
13640 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13641 cx.emit(EditorEvent::Reparsed(*buffer_id));
13642 cx.notify();
13643 }
13644 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13645 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13646 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13647 cx.emit(EditorEvent::TitleChanged)
13648 }
13649 // multi_buffer::Event::DiffBaseChanged => {
13650 // self.scrollbar_marker_state.dirty = true;
13651 // cx.emit(EditorEvent::DiffBaseChanged);
13652 // cx.notify();
13653 // }
13654 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13655 multi_buffer::Event::DiagnosticsUpdated => {
13656 self.refresh_active_diagnostics(cx);
13657 self.scrollbar_marker_state.dirty = true;
13658 cx.notify();
13659 }
13660 _ => {}
13661 };
13662 }
13663
13664 fn on_display_map_changed(
13665 &mut self,
13666 _: Entity<DisplayMap>,
13667 _: &mut Window,
13668 cx: &mut Context<Self>,
13669 ) {
13670 cx.notify();
13671 }
13672
13673 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13674 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13675 self.refresh_inline_completion(true, false, window, cx);
13676 self.refresh_inlay_hints(
13677 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13678 self.selections.newest_anchor().head(),
13679 &self.buffer.read(cx).snapshot(cx),
13680 cx,
13681 )),
13682 cx,
13683 );
13684
13685 let old_cursor_shape = self.cursor_shape;
13686
13687 {
13688 let editor_settings = EditorSettings::get_global(cx);
13689 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13690 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13691 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13692 }
13693
13694 if old_cursor_shape != self.cursor_shape {
13695 cx.emit(EditorEvent::CursorShapeChanged);
13696 }
13697
13698 let project_settings = ProjectSettings::get_global(cx);
13699 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13700
13701 if self.mode == EditorMode::Full {
13702 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13703 if self.git_blame_inline_enabled != inline_blame_enabled {
13704 self.toggle_git_blame_inline_internal(false, window, cx);
13705 }
13706 }
13707
13708 cx.notify();
13709 }
13710
13711 pub fn set_searchable(&mut self, searchable: bool) {
13712 self.searchable = searchable;
13713 }
13714
13715 pub fn searchable(&self) -> bool {
13716 self.searchable
13717 }
13718
13719 fn open_proposed_changes_editor(
13720 &mut self,
13721 _: &OpenProposedChangesEditor,
13722 window: &mut Window,
13723 cx: &mut Context<Self>,
13724 ) {
13725 let Some(workspace) = self.workspace() else {
13726 cx.propagate();
13727 return;
13728 };
13729
13730 let selections = self.selections.all::<usize>(cx);
13731 let multi_buffer = self.buffer.read(cx);
13732 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13733 let mut new_selections_by_buffer = HashMap::default();
13734 for selection in selections {
13735 for (buffer, range, _) in
13736 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13737 {
13738 let mut range = range.to_point(buffer);
13739 range.start.column = 0;
13740 range.end.column = buffer.line_len(range.end.row);
13741 new_selections_by_buffer
13742 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13743 .or_insert(Vec::new())
13744 .push(range)
13745 }
13746 }
13747
13748 let proposed_changes_buffers = new_selections_by_buffer
13749 .into_iter()
13750 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13751 .collect::<Vec<_>>();
13752 let proposed_changes_editor = cx.new(|cx| {
13753 ProposedChangesEditor::new(
13754 "Proposed changes",
13755 proposed_changes_buffers,
13756 self.project.clone(),
13757 window,
13758 cx,
13759 )
13760 });
13761
13762 window.defer(cx, move |window, cx| {
13763 workspace.update(cx, |workspace, cx| {
13764 workspace.active_pane().update(cx, |pane, cx| {
13765 pane.add_item(
13766 Box::new(proposed_changes_editor),
13767 true,
13768 true,
13769 None,
13770 window,
13771 cx,
13772 );
13773 });
13774 });
13775 });
13776 }
13777
13778 pub fn open_excerpts_in_split(
13779 &mut self,
13780 _: &OpenExcerptsSplit,
13781 window: &mut Window,
13782 cx: &mut Context<Self>,
13783 ) {
13784 self.open_excerpts_common(None, true, window, cx)
13785 }
13786
13787 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
13788 self.open_excerpts_common(None, false, window, cx)
13789 }
13790
13791 fn open_excerpts_common(
13792 &mut self,
13793 jump_data: Option<JumpData>,
13794 split: bool,
13795 window: &mut Window,
13796 cx: &mut Context<Self>,
13797 ) {
13798 let Some(workspace) = self.workspace() else {
13799 cx.propagate();
13800 return;
13801 };
13802
13803 if self.buffer.read(cx).is_singleton() {
13804 cx.propagate();
13805 return;
13806 }
13807
13808 let mut new_selections_by_buffer = HashMap::default();
13809 match &jump_data {
13810 Some(JumpData::MultiBufferPoint {
13811 excerpt_id,
13812 position,
13813 anchor,
13814 line_offset_from_top,
13815 }) => {
13816 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13817 if let Some(buffer) = multi_buffer_snapshot
13818 .buffer_id_for_excerpt(*excerpt_id)
13819 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
13820 {
13821 let buffer_snapshot = buffer.read(cx).snapshot();
13822 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
13823 language::ToPoint::to_point(anchor, &buffer_snapshot)
13824 } else {
13825 buffer_snapshot.clip_point(*position, Bias::Left)
13826 };
13827 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
13828 new_selections_by_buffer.insert(
13829 buffer,
13830 (
13831 vec![jump_to_offset..jump_to_offset],
13832 Some(*line_offset_from_top),
13833 ),
13834 );
13835 }
13836 }
13837 Some(JumpData::MultiBufferRow {
13838 row,
13839 line_offset_from_top,
13840 }) => {
13841 let point = MultiBufferPoint::new(row.0, 0);
13842 if let Some((buffer, buffer_point, _)) =
13843 self.buffer.read(cx).point_to_buffer_point(point, cx)
13844 {
13845 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
13846 new_selections_by_buffer
13847 .entry(buffer)
13848 .or_insert((Vec::new(), Some(*line_offset_from_top)))
13849 .0
13850 .push(buffer_offset..buffer_offset)
13851 }
13852 }
13853 None => {
13854 let selections = self.selections.all::<usize>(cx);
13855 let multi_buffer = self.buffer.read(cx);
13856 for selection in selections {
13857 for (buffer, mut range, _) in multi_buffer
13858 .snapshot(cx)
13859 .range_to_buffer_ranges(selection.range())
13860 {
13861 // When editing branch buffers, jump to the corresponding location
13862 // in their base buffer.
13863 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
13864 let buffer = buffer_handle.read(cx);
13865 if let Some(base_buffer) = buffer.base_buffer() {
13866 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
13867 buffer_handle = base_buffer;
13868 }
13869
13870 if selection.reversed {
13871 mem::swap(&mut range.start, &mut range.end);
13872 }
13873 new_selections_by_buffer
13874 .entry(buffer_handle)
13875 .or_insert((Vec::new(), None))
13876 .0
13877 .push(range)
13878 }
13879 }
13880 }
13881 }
13882
13883 if new_selections_by_buffer.is_empty() {
13884 return;
13885 }
13886
13887 // We defer the pane interaction because we ourselves are a workspace item
13888 // and activating a new item causes the pane to call a method on us reentrantly,
13889 // which panics if we're on the stack.
13890 window.defer(cx, move |window, cx| {
13891 workspace.update(cx, |workspace, cx| {
13892 let pane = if split {
13893 workspace.adjacent_pane(window, cx)
13894 } else {
13895 workspace.active_pane().clone()
13896 };
13897
13898 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
13899 let editor = buffer
13900 .read(cx)
13901 .file()
13902 .is_none()
13903 .then(|| {
13904 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
13905 // so `workspace.open_project_item` will never find them, always opening a new editor.
13906 // Instead, we try to activate the existing editor in the pane first.
13907 let (editor, pane_item_index) =
13908 pane.read(cx).items().enumerate().find_map(|(i, item)| {
13909 let editor = item.downcast::<Editor>()?;
13910 let singleton_buffer =
13911 editor.read(cx).buffer().read(cx).as_singleton()?;
13912 if singleton_buffer == buffer {
13913 Some((editor, i))
13914 } else {
13915 None
13916 }
13917 })?;
13918 pane.update(cx, |pane, cx| {
13919 pane.activate_item(pane_item_index, true, true, window, cx)
13920 });
13921 Some(editor)
13922 })
13923 .flatten()
13924 .unwrap_or_else(|| {
13925 workspace.open_project_item::<Self>(
13926 pane.clone(),
13927 buffer,
13928 true,
13929 true,
13930 window,
13931 cx,
13932 )
13933 });
13934
13935 editor.update(cx, |editor, cx| {
13936 let autoscroll = match scroll_offset {
13937 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
13938 None => Autoscroll::newest(),
13939 };
13940 let nav_history = editor.nav_history.take();
13941 editor.change_selections(Some(autoscroll), window, cx, |s| {
13942 s.select_ranges(ranges);
13943 });
13944 editor.nav_history = nav_history;
13945 });
13946 }
13947 })
13948 });
13949 }
13950
13951 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
13952 let snapshot = self.buffer.read(cx).read(cx);
13953 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
13954 Some(
13955 ranges
13956 .iter()
13957 .map(move |range| {
13958 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
13959 })
13960 .collect(),
13961 )
13962 }
13963
13964 fn selection_replacement_ranges(
13965 &self,
13966 range: Range<OffsetUtf16>,
13967 cx: &mut App,
13968 ) -> Vec<Range<OffsetUtf16>> {
13969 let selections = self.selections.all::<OffsetUtf16>(cx);
13970 let newest_selection = selections
13971 .iter()
13972 .max_by_key(|selection| selection.id)
13973 .unwrap();
13974 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
13975 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
13976 let snapshot = self.buffer.read(cx).read(cx);
13977 selections
13978 .into_iter()
13979 .map(|mut selection| {
13980 selection.start.0 =
13981 (selection.start.0 as isize).saturating_add(start_delta) as usize;
13982 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
13983 snapshot.clip_offset_utf16(selection.start, Bias::Left)
13984 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
13985 })
13986 .collect()
13987 }
13988
13989 fn report_editor_event(
13990 &self,
13991 event_type: &'static str,
13992 file_extension: Option<String>,
13993 cx: &App,
13994 ) {
13995 if cfg!(any(test, feature = "test-support")) {
13996 return;
13997 }
13998
13999 let Some(project) = &self.project else { return };
14000
14001 // If None, we are in a file without an extension
14002 let file = self
14003 .buffer
14004 .read(cx)
14005 .as_singleton()
14006 .and_then(|b| b.read(cx).file());
14007 let file_extension = file_extension.or(file
14008 .as_ref()
14009 .and_then(|file| Path::new(file.file_name(cx)).extension())
14010 .and_then(|e| e.to_str())
14011 .map(|a| a.to_string()));
14012
14013 let vim_mode = cx
14014 .global::<SettingsStore>()
14015 .raw_user_settings()
14016 .get("vim_mode")
14017 == Some(&serde_json::Value::Bool(true));
14018
14019 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
14020 == language::language_settings::InlineCompletionProvider::Copilot;
14021 let copilot_enabled_for_language = self
14022 .buffer
14023 .read(cx)
14024 .settings_at(0, cx)
14025 .show_inline_completions;
14026
14027 let project = project.read(cx);
14028 telemetry::event!(
14029 event_type,
14030 file_extension,
14031 vim_mode,
14032 copilot_enabled,
14033 copilot_enabled_for_language,
14034 is_via_ssh = project.is_via_ssh(),
14035 );
14036 }
14037
14038 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14039 /// with each line being an array of {text, highlight} objects.
14040 fn copy_highlight_json(
14041 &mut self,
14042 _: &CopyHighlightJson,
14043 window: &mut Window,
14044 cx: &mut Context<Self>,
14045 ) {
14046 #[derive(Serialize)]
14047 struct Chunk<'a> {
14048 text: String,
14049 highlight: Option<&'a str>,
14050 }
14051
14052 let snapshot = self.buffer.read(cx).snapshot(cx);
14053 let range = self
14054 .selected_text_range(false, window, cx)
14055 .and_then(|selection| {
14056 if selection.range.is_empty() {
14057 None
14058 } else {
14059 Some(selection.range)
14060 }
14061 })
14062 .unwrap_or_else(|| 0..snapshot.len());
14063
14064 let chunks = snapshot.chunks(range, true);
14065 let mut lines = Vec::new();
14066 let mut line: VecDeque<Chunk> = VecDeque::new();
14067
14068 let Some(style) = self.style.as_ref() else {
14069 return;
14070 };
14071
14072 for chunk in chunks {
14073 let highlight = chunk
14074 .syntax_highlight_id
14075 .and_then(|id| id.name(&style.syntax));
14076 let mut chunk_lines = chunk.text.split('\n').peekable();
14077 while let Some(text) = chunk_lines.next() {
14078 let mut merged_with_last_token = false;
14079 if let Some(last_token) = line.back_mut() {
14080 if last_token.highlight == highlight {
14081 last_token.text.push_str(text);
14082 merged_with_last_token = true;
14083 }
14084 }
14085
14086 if !merged_with_last_token {
14087 line.push_back(Chunk {
14088 text: text.into(),
14089 highlight,
14090 });
14091 }
14092
14093 if chunk_lines.peek().is_some() {
14094 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14095 line.pop_front();
14096 }
14097 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14098 line.pop_back();
14099 }
14100
14101 lines.push(mem::take(&mut line));
14102 }
14103 }
14104 }
14105
14106 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14107 return;
14108 };
14109 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14110 }
14111
14112 pub fn open_context_menu(
14113 &mut self,
14114 _: &OpenContextMenu,
14115 window: &mut Window,
14116 cx: &mut Context<Self>,
14117 ) {
14118 self.request_autoscroll(Autoscroll::newest(), cx);
14119 let position = self.selections.newest_display(cx).start;
14120 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14121 }
14122
14123 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14124 &self.inlay_hint_cache
14125 }
14126
14127 pub fn replay_insert_event(
14128 &mut self,
14129 text: &str,
14130 relative_utf16_range: Option<Range<isize>>,
14131 window: &mut Window,
14132 cx: &mut Context<Self>,
14133 ) {
14134 if !self.input_enabled {
14135 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14136 return;
14137 }
14138 if let Some(relative_utf16_range) = relative_utf16_range {
14139 let selections = self.selections.all::<OffsetUtf16>(cx);
14140 self.change_selections(None, window, cx, |s| {
14141 let new_ranges = selections.into_iter().map(|range| {
14142 let start = OffsetUtf16(
14143 range
14144 .head()
14145 .0
14146 .saturating_add_signed(relative_utf16_range.start),
14147 );
14148 let end = OffsetUtf16(
14149 range
14150 .head()
14151 .0
14152 .saturating_add_signed(relative_utf16_range.end),
14153 );
14154 start..end
14155 });
14156 s.select_ranges(new_ranges);
14157 });
14158 }
14159
14160 self.handle_input(text, window, cx);
14161 }
14162
14163 pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14164 let Some(provider) = self.semantics_provider.as_ref() else {
14165 return false;
14166 };
14167
14168 let mut supports = false;
14169 self.buffer().read(cx).for_each_buffer(|buffer| {
14170 supports |= provider.supports_inlay_hints(buffer, cx);
14171 });
14172 supports
14173 }
14174 pub fn is_focused(&self, window: &mut Window) -> bool {
14175 self.focus_handle.is_focused(window)
14176 }
14177
14178 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14179 cx.emit(EditorEvent::Focused);
14180
14181 if let Some(descendant) = self
14182 .last_focused_descendant
14183 .take()
14184 .and_then(|descendant| descendant.upgrade())
14185 {
14186 window.focus(&descendant);
14187 } else {
14188 if let Some(blame) = self.blame.as_ref() {
14189 blame.update(cx, GitBlame::focus)
14190 }
14191
14192 self.blink_manager.update(cx, BlinkManager::enable);
14193 self.show_cursor_names(window, cx);
14194 self.buffer.update(cx, |buffer, cx| {
14195 buffer.finalize_last_transaction(cx);
14196 if self.leader_peer_id.is_none() {
14197 buffer.set_active_selections(
14198 &self.selections.disjoint_anchors(),
14199 self.selections.line_mode,
14200 self.cursor_shape,
14201 cx,
14202 );
14203 }
14204 });
14205 }
14206 }
14207
14208 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14209 cx.emit(EditorEvent::FocusedIn)
14210 }
14211
14212 fn handle_focus_out(
14213 &mut self,
14214 event: FocusOutEvent,
14215 _window: &mut Window,
14216 _cx: &mut Context<Self>,
14217 ) {
14218 if event.blurred != self.focus_handle {
14219 self.last_focused_descendant = Some(event.blurred);
14220 }
14221 }
14222
14223 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14224 self.blink_manager.update(cx, BlinkManager::disable);
14225 self.buffer
14226 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14227
14228 if let Some(blame) = self.blame.as_ref() {
14229 blame.update(cx, GitBlame::blur)
14230 }
14231 if !self.hover_state.focused(window, cx) {
14232 hide_hover(self, cx);
14233 }
14234
14235 self.hide_context_menu(window, cx);
14236 cx.emit(EditorEvent::Blurred);
14237 cx.notify();
14238 }
14239
14240 pub fn register_action<A: Action>(
14241 &mut self,
14242 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14243 ) -> Subscription {
14244 let id = self.next_editor_action_id.post_inc();
14245 let listener = Arc::new(listener);
14246 self.editor_actions.borrow_mut().insert(
14247 id,
14248 Box::new(move |window, _| {
14249 let listener = listener.clone();
14250 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14251 let action = action.downcast_ref().unwrap();
14252 if phase == DispatchPhase::Bubble {
14253 listener(action, window, cx)
14254 }
14255 })
14256 }),
14257 );
14258
14259 let editor_actions = self.editor_actions.clone();
14260 Subscription::new(move || {
14261 editor_actions.borrow_mut().remove(&id);
14262 })
14263 }
14264
14265 pub fn file_header_size(&self) -> u32 {
14266 FILE_HEADER_HEIGHT
14267 }
14268
14269 pub fn revert(
14270 &mut self,
14271 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14272 window: &mut Window,
14273 cx: &mut Context<Self>,
14274 ) {
14275 self.buffer().update(cx, |multi_buffer, cx| {
14276 for (buffer_id, changes) in revert_changes {
14277 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14278 buffer.update(cx, |buffer, cx| {
14279 buffer.edit(
14280 changes.into_iter().map(|(range, text)| {
14281 (range, text.to_string().map(Arc::<str>::from))
14282 }),
14283 None,
14284 cx,
14285 );
14286 });
14287 }
14288 }
14289 });
14290 self.change_selections(None, window, cx, |selections| selections.refresh());
14291 }
14292
14293 pub fn to_pixel_point(
14294 &self,
14295 source: multi_buffer::Anchor,
14296 editor_snapshot: &EditorSnapshot,
14297 window: &mut Window,
14298 ) -> Option<gpui::Point<Pixels>> {
14299 let source_point = source.to_display_point(editor_snapshot);
14300 self.display_to_pixel_point(source_point, editor_snapshot, window)
14301 }
14302
14303 pub fn display_to_pixel_point(
14304 &self,
14305 source: DisplayPoint,
14306 editor_snapshot: &EditorSnapshot,
14307 window: &mut Window,
14308 ) -> Option<gpui::Point<Pixels>> {
14309 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14310 let text_layout_details = self.text_layout_details(window);
14311 let scroll_top = text_layout_details
14312 .scroll_anchor
14313 .scroll_position(editor_snapshot)
14314 .y;
14315
14316 if source.row().as_f32() < scroll_top.floor() {
14317 return None;
14318 }
14319 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14320 let source_y = line_height * (source.row().as_f32() - scroll_top);
14321 Some(gpui::Point::new(source_x, source_y))
14322 }
14323
14324 pub fn has_active_completions_menu(&self) -> bool {
14325 self.context_menu.borrow().as_ref().map_or(false, |menu| {
14326 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14327 })
14328 }
14329
14330 pub fn register_addon<T: Addon>(&mut self, instance: T) {
14331 self.addons
14332 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14333 }
14334
14335 pub fn unregister_addon<T: Addon>(&mut self) {
14336 self.addons.remove(&std::any::TypeId::of::<T>());
14337 }
14338
14339 pub fn addon<T: Addon>(&self) -> Option<&T> {
14340 let type_id = std::any::TypeId::of::<T>();
14341 self.addons
14342 .get(&type_id)
14343 .and_then(|item| item.to_any().downcast_ref::<T>())
14344 }
14345
14346 fn character_size(&self, window: &mut Window) -> gpui::Point<Pixels> {
14347 let text_layout_details = self.text_layout_details(window);
14348 let style = &text_layout_details.editor_style;
14349 let font_id = window.text_system().resolve_font(&style.text.font());
14350 let font_size = style.text.font_size.to_pixels(window.rem_size());
14351 let line_height = style.text.line_height_in_pixels(window.rem_size());
14352 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14353
14354 gpui::Point::new(em_width, line_height)
14355 }
14356}
14357
14358fn get_unstaged_changes_for_buffers(
14359 project: &Entity<Project>,
14360 buffers: impl IntoIterator<Item = Entity<Buffer>>,
14361 buffer: Entity<MultiBuffer>,
14362 cx: &mut App,
14363) {
14364 let mut tasks = Vec::new();
14365 project.update(cx, |project, cx| {
14366 for buffer in buffers {
14367 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
14368 }
14369 });
14370 cx.spawn(|mut cx| async move {
14371 let change_sets = futures::future::join_all(tasks).await;
14372 buffer
14373 .update(&mut cx, |buffer, cx| {
14374 for change_set in change_sets {
14375 if let Some(change_set) = change_set.log_err() {
14376 buffer.add_change_set(change_set, cx);
14377 }
14378 }
14379 })
14380 .ok();
14381 })
14382 .detach();
14383}
14384
14385fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14386 let tab_size = tab_size.get() as usize;
14387 let mut width = offset;
14388
14389 for ch in text.chars() {
14390 width += if ch == '\t' {
14391 tab_size - (width % tab_size)
14392 } else {
14393 1
14394 };
14395 }
14396
14397 width - offset
14398}
14399
14400#[cfg(test)]
14401mod tests {
14402 use super::*;
14403
14404 #[test]
14405 fn test_string_size_with_expanded_tabs() {
14406 let nz = |val| NonZeroU32::new(val).unwrap();
14407 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14408 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14409 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14410 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14411 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14412 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14413 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14414 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14415 }
14416}
14417
14418/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14419struct WordBreakingTokenizer<'a> {
14420 input: &'a str,
14421}
14422
14423impl<'a> WordBreakingTokenizer<'a> {
14424 fn new(input: &'a str) -> Self {
14425 Self { input }
14426 }
14427}
14428
14429fn is_char_ideographic(ch: char) -> bool {
14430 use unicode_script::Script::*;
14431 use unicode_script::UnicodeScript;
14432 matches!(ch.script(), Han | Tangut | Yi)
14433}
14434
14435fn is_grapheme_ideographic(text: &str) -> bool {
14436 text.chars().any(is_char_ideographic)
14437}
14438
14439fn is_grapheme_whitespace(text: &str) -> bool {
14440 text.chars().any(|x| x.is_whitespace())
14441}
14442
14443fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14444 text.chars().next().map_or(false, |ch| {
14445 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14446 })
14447}
14448
14449#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14450struct WordBreakToken<'a> {
14451 token: &'a str,
14452 grapheme_len: usize,
14453 is_whitespace: bool,
14454}
14455
14456impl<'a> Iterator for WordBreakingTokenizer<'a> {
14457 /// Yields a span, the count of graphemes in the token, and whether it was
14458 /// whitespace. Note that it also breaks at word boundaries.
14459 type Item = WordBreakToken<'a>;
14460
14461 fn next(&mut self) -> Option<Self::Item> {
14462 use unicode_segmentation::UnicodeSegmentation;
14463 if self.input.is_empty() {
14464 return None;
14465 }
14466
14467 let mut iter = self.input.graphemes(true).peekable();
14468 let mut offset = 0;
14469 let mut graphemes = 0;
14470 if let Some(first_grapheme) = iter.next() {
14471 let is_whitespace = is_grapheme_whitespace(first_grapheme);
14472 offset += first_grapheme.len();
14473 graphemes += 1;
14474 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14475 if let Some(grapheme) = iter.peek().copied() {
14476 if should_stay_with_preceding_ideograph(grapheme) {
14477 offset += grapheme.len();
14478 graphemes += 1;
14479 }
14480 }
14481 } else {
14482 let mut words = self.input[offset..].split_word_bound_indices().peekable();
14483 let mut next_word_bound = words.peek().copied();
14484 if next_word_bound.map_or(false, |(i, _)| i == 0) {
14485 next_word_bound = words.next();
14486 }
14487 while let Some(grapheme) = iter.peek().copied() {
14488 if next_word_bound.map_or(false, |(i, _)| i == offset) {
14489 break;
14490 };
14491 if is_grapheme_whitespace(grapheme) != is_whitespace {
14492 break;
14493 };
14494 offset += grapheme.len();
14495 graphemes += 1;
14496 iter.next();
14497 }
14498 }
14499 let token = &self.input[..offset];
14500 self.input = &self.input[offset..];
14501 if is_whitespace {
14502 Some(WordBreakToken {
14503 token: " ",
14504 grapheme_len: 1,
14505 is_whitespace: true,
14506 })
14507 } else {
14508 Some(WordBreakToken {
14509 token,
14510 grapheme_len: graphemes,
14511 is_whitespace: false,
14512 })
14513 }
14514 } else {
14515 None
14516 }
14517 }
14518}
14519
14520#[test]
14521fn test_word_breaking_tokenizer() {
14522 let tests: &[(&str, &[(&str, usize, bool)])] = &[
14523 ("", &[]),
14524 (" ", &[(" ", 1, true)]),
14525 ("Ʒ", &[("Ʒ", 1, false)]),
14526 ("Ǽ", &[("Ǽ", 1, false)]),
14527 ("⋑", &[("⋑", 1, false)]),
14528 ("⋑⋑", &[("⋑⋑", 2, false)]),
14529 (
14530 "原理,进而",
14531 &[
14532 ("原", 1, false),
14533 ("理,", 2, false),
14534 ("进", 1, false),
14535 ("而", 1, false),
14536 ],
14537 ),
14538 (
14539 "hello world",
14540 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14541 ),
14542 (
14543 "hello, world",
14544 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14545 ),
14546 (
14547 " hello world",
14548 &[
14549 (" ", 1, true),
14550 ("hello", 5, false),
14551 (" ", 1, true),
14552 ("world", 5, false),
14553 ],
14554 ),
14555 (
14556 "这是什么 \n 钢笔",
14557 &[
14558 ("这", 1, false),
14559 ("是", 1, false),
14560 ("什", 1, false),
14561 ("么", 1, false),
14562 (" ", 1, true),
14563 ("钢", 1, false),
14564 ("笔", 1, false),
14565 ],
14566 ),
14567 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14568 ];
14569
14570 for (input, result) in tests {
14571 assert_eq!(
14572 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14573 result
14574 .iter()
14575 .copied()
14576 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14577 token,
14578 grapheme_len,
14579 is_whitespace,
14580 })
14581 .collect::<Vec<_>>()
14582 );
14583 }
14584}
14585
14586fn wrap_with_prefix(
14587 line_prefix: String,
14588 unwrapped_text: String,
14589 wrap_column: usize,
14590 tab_size: NonZeroU32,
14591) -> String {
14592 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14593 let mut wrapped_text = String::new();
14594 let mut current_line = line_prefix.clone();
14595
14596 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14597 let mut current_line_len = line_prefix_len;
14598 for WordBreakToken {
14599 token,
14600 grapheme_len,
14601 is_whitespace,
14602 } in tokenizer
14603 {
14604 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14605 wrapped_text.push_str(current_line.trim_end());
14606 wrapped_text.push('\n');
14607 current_line.truncate(line_prefix.len());
14608 current_line_len = line_prefix_len;
14609 if !is_whitespace {
14610 current_line.push_str(token);
14611 current_line_len += grapheme_len;
14612 }
14613 } else if !is_whitespace {
14614 current_line.push_str(token);
14615 current_line_len += grapheme_len;
14616 } else if current_line_len != line_prefix_len {
14617 current_line.push(' ');
14618 current_line_len += 1;
14619 }
14620 }
14621
14622 if !current_line.is_empty() {
14623 wrapped_text.push_str(¤t_line);
14624 }
14625 wrapped_text
14626}
14627
14628#[test]
14629fn test_wrap_with_prefix() {
14630 assert_eq!(
14631 wrap_with_prefix(
14632 "# ".to_string(),
14633 "abcdefg".to_string(),
14634 4,
14635 NonZeroU32::new(4).unwrap()
14636 ),
14637 "# abcdefg"
14638 );
14639 assert_eq!(
14640 wrap_with_prefix(
14641 "".to_string(),
14642 "\thello world".to_string(),
14643 8,
14644 NonZeroU32::new(4).unwrap()
14645 ),
14646 "hello\nworld"
14647 );
14648 assert_eq!(
14649 wrap_with_prefix(
14650 "// ".to_string(),
14651 "xx \nyy zz aa bb cc".to_string(),
14652 12,
14653 NonZeroU32::new(4).unwrap()
14654 ),
14655 "// xx yy zz\n// aa bb cc"
14656 );
14657 assert_eq!(
14658 wrap_with_prefix(
14659 String::new(),
14660 "这是什么 \n 钢笔".to_string(),
14661 3,
14662 NonZeroU32::new(4).unwrap()
14663 ),
14664 "这是什\n么 钢\n笔"
14665 );
14666}
14667
14668pub trait CollaborationHub {
14669 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14670 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14671 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14672}
14673
14674impl CollaborationHub for Entity<Project> {
14675 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14676 self.read(cx).collaborators()
14677 }
14678
14679 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14680 self.read(cx).user_store().read(cx).participant_indices()
14681 }
14682
14683 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14684 let this = self.read(cx);
14685 let user_ids = this.collaborators().values().map(|c| c.user_id);
14686 this.user_store().read_with(cx, |user_store, cx| {
14687 user_store.participant_names(user_ids, cx)
14688 })
14689 }
14690}
14691
14692pub trait SemanticsProvider {
14693 fn hover(
14694 &self,
14695 buffer: &Entity<Buffer>,
14696 position: text::Anchor,
14697 cx: &mut App,
14698 ) -> Option<Task<Vec<project::Hover>>>;
14699
14700 fn inlay_hints(
14701 &self,
14702 buffer_handle: Entity<Buffer>,
14703 range: Range<text::Anchor>,
14704 cx: &mut App,
14705 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14706
14707 fn resolve_inlay_hint(
14708 &self,
14709 hint: InlayHint,
14710 buffer_handle: Entity<Buffer>,
14711 server_id: LanguageServerId,
14712 cx: &mut App,
14713 ) -> Option<Task<anyhow::Result<InlayHint>>>;
14714
14715 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
14716
14717 fn document_highlights(
14718 &self,
14719 buffer: &Entity<Buffer>,
14720 position: text::Anchor,
14721 cx: &mut App,
14722 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14723
14724 fn definitions(
14725 &self,
14726 buffer: &Entity<Buffer>,
14727 position: text::Anchor,
14728 kind: GotoDefinitionKind,
14729 cx: &mut App,
14730 ) -> Option<Task<Result<Vec<LocationLink>>>>;
14731
14732 fn range_for_rename(
14733 &self,
14734 buffer: &Entity<Buffer>,
14735 position: text::Anchor,
14736 cx: &mut App,
14737 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14738
14739 fn perform_rename(
14740 &self,
14741 buffer: &Entity<Buffer>,
14742 position: text::Anchor,
14743 new_name: String,
14744 cx: &mut App,
14745 ) -> Option<Task<Result<ProjectTransaction>>>;
14746}
14747
14748pub trait CompletionProvider {
14749 fn completions(
14750 &self,
14751 buffer: &Entity<Buffer>,
14752 buffer_position: text::Anchor,
14753 trigger: CompletionContext,
14754 window: &mut Window,
14755 cx: &mut Context<Editor>,
14756 ) -> Task<Result<Vec<Completion>>>;
14757
14758 fn resolve_completions(
14759 &self,
14760 buffer: Entity<Buffer>,
14761 completion_indices: Vec<usize>,
14762 completions: Rc<RefCell<Box<[Completion]>>>,
14763 cx: &mut Context<Editor>,
14764 ) -> Task<Result<bool>>;
14765
14766 fn apply_additional_edits_for_completion(
14767 &self,
14768 _buffer: Entity<Buffer>,
14769 _completions: Rc<RefCell<Box<[Completion]>>>,
14770 _completion_index: usize,
14771 _push_to_history: bool,
14772 _cx: &mut Context<Editor>,
14773 ) -> Task<Result<Option<language::Transaction>>> {
14774 Task::ready(Ok(None))
14775 }
14776
14777 fn is_completion_trigger(
14778 &self,
14779 buffer: &Entity<Buffer>,
14780 position: language::Anchor,
14781 text: &str,
14782 trigger_in_words: bool,
14783 cx: &mut Context<Editor>,
14784 ) -> bool;
14785
14786 fn sort_completions(&self) -> bool {
14787 true
14788 }
14789}
14790
14791pub trait CodeActionProvider {
14792 fn id(&self) -> Arc<str>;
14793
14794 fn code_actions(
14795 &self,
14796 buffer: &Entity<Buffer>,
14797 range: Range<text::Anchor>,
14798 window: &mut Window,
14799 cx: &mut App,
14800 ) -> Task<Result<Vec<CodeAction>>>;
14801
14802 fn apply_code_action(
14803 &self,
14804 buffer_handle: Entity<Buffer>,
14805 action: CodeAction,
14806 excerpt_id: ExcerptId,
14807 push_to_history: bool,
14808 window: &mut Window,
14809 cx: &mut App,
14810 ) -> Task<Result<ProjectTransaction>>;
14811}
14812
14813impl CodeActionProvider for Entity<Project> {
14814 fn id(&self) -> Arc<str> {
14815 "project".into()
14816 }
14817
14818 fn code_actions(
14819 &self,
14820 buffer: &Entity<Buffer>,
14821 range: Range<text::Anchor>,
14822 _window: &mut Window,
14823 cx: &mut App,
14824 ) -> Task<Result<Vec<CodeAction>>> {
14825 self.update(cx, |project, cx| {
14826 project.code_actions(buffer, range, None, cx)
14827 })
14828 }
14829
14830 fn apply_code_action(
14831 &self,
14832 buffer_handle: Entity<Buffer>,
14833 action: CodeAction,
14834 _excerpt_id: ExcerptId,
14835 push_to_history: bool,
14836 _window: &mut Window,
14837 cx: &mut App,
14838 ) -> Task<Result<ProjectTransaction>> {
14839 self.update(cx, |project, cx| {
14840 project.apply_code_action(buffer_handle, action, push_to_history, cx)
14841 })
14842 }
14843}
14844
14845fn snippet_completions(
14846 project: &Project,
14847 buffer: &Entity<Buffer>,
14848 buffer_position: text::Anchor,
14849 cx: &mut App,
14850) -> Task<Result<Vec<Completion>>> {
14851 let language = buffer.read(cx).language_at(buffer_position);
14852 let language_name = language.as_ref().map(|language| language.lsp_id());
14853 let snippet_store = project.snippets().read(cx);
14854 let snippets = snippet_store.snippets_for(language_name, cx);
14855
14856 if snippets.is_empty() {
14857 return Task::ready(Ok(vec![]));
14858 }
14859 let snapshot = buffer.read(cx).text_snapshot();
14860 let chars: String = snapshot
14861 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
14862 .collect();
14863
14864 let scope = language.map(|language| language.default_scope());
14865 let executor = cx.background_executor().clone();
14866
14867 cx.background_executor().spawn(async move {
14868 let classifier = CharClassifier::new(scope).for_completion(true);
14869 let mut last_word = chars
14870 .chars()
14871 .take_while(|c| classifier.is_word(*c))
14872 .collect::<String>();
14873 last_word = last_word.chars().rev().collect();
14874
14875 if last_word.is_empty() {
14876 return Ok(vec![]);
14877 }
14878
14879 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
14880 let to_lsp = |point: &text::Anchor| {
14881 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
14882 point_to_lsp(end)
14883 };
14884 let lsp_end = to_lsp(&buffer_position);
14885
14886 let candidates = snippets
14887 .iter()
14888 .enumerate()
14889 .flat_map(|(ix, snippet)| {
14890 snippet
14891 .prefix
14892 .iter()
14893 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
14894 })
14895 .collect::<Vec<StringMatchCandidate>>();
14896
14897 let mut matches = fuzzy::match_strings(
14898 &candidates,
14899 &last_word,
14900 last_word.chars().any(|c| c.is_uppercase()),
14901 100,
14902 &Default::default(),
14903 executor,
14904 )
14905 .await;
14906
14907 // Remove all candidates where the query's start does not match the start of any word in the candidate
14908 if let Some(query_start) = last_word.chars().next() {
14909 matches.retain(|string_match| {
14910 split_words(&string_match.string).any(|word| {
14911 // Check that the first codepoint of the word as lowercase matches the first
14912 // codepoint of the query as lowercase
14913 word.chars()
14914 .flat_map(|codepoint| codepoint.to_lowercase())
14915 .zip(query_start.to_lowercase())
14916 .all(|(word_cp, query_cp)| word_cp == query_cp)
14917 })
14918 });
14919 }
14920
14921 let matched_strings = matches
14922 .into_iter()
14923 .map(|m| m.string)
14924 .collect::<HashSet<_>>();
14925
14926 let result: Vec<Completion> = snippets
14927 .into_iter()
14928 .filter_map(|snippet| {
14929 let matching_prefix = snippet
14930 .prefix
14931 .iter()
14932 .find(|prefix| matched_strings.contains(*prefix))?;
14933 let start = as_offset - last_word.len();
14934 let start = snapshot.anchor_before(start);
14935 let range = start..buffer_position;
14936 let lsp_start = to_lsp(&start);
14937 let lsp_range = lsp::Range {
14938 start: lsp_start,
14939 end: lsp_end,
14940 };
14941 Some(Completion {
14942 old_range: range,
14943 new_text: snippet.body.clone(),
14944 resolved: false,
14945 label: CodeLabel {
14946 text: matching_prefix.clone(),
14947 runs: vec![],
14948 filter_range: 0..matching_prefix.len(),
14949 },
14950 server_id: LanguageServerId(usize::MAX),
14951 documentation: snippet
14952 .description
14953 .clone()
14954 .map(CompletionDocumentation::SingleLine),
14955 lsp_completion: lsp::CompletionItem {
14956 label: snippet.prefix.first().unwrap().clone(),
14957 kind: Some(CompletionItemKind::SNIPPET),
14958 label_details: snippet.description.as_ref().map(|description| {
14959 lsp::CompletionItemLabelDetails {
14960 detail: Some(description.clone()),
14961 description: None,
14962 }
14963 }),
14964 insert_text_format: Some(InsertTextFormat::SNIPPET),
14965 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
14966 lsp::InsertReplaceEdit {
14967 new_text: snippet.body.clone(),
14968 insert: lsp_range,
14969 replace: lsp_range,
14970 },
14971 )),
14972 filter_text: Some(snippet.body.clone()),
14973 sort_text: Some(char::MAX.to_string()),
14974 ..Default::default()
14975 },
14976 confirm: None,
14977 })
14978 })
14979 .collect();
14980
14981 Ok(result)
14982 })
14983}
14984
14985impl CompletionProvider for Entity<Project> {
14986 fn completions(
14987 &self,
14988 buffer: &Entity<Buffer>,
14989 buffer_position: text::Anchor,
14990 options: CompletionContext,
14991 _window: &mut Window,
14992 cx: &mut Context<Editor>,
14993 ) -> Task<Result<Vec<Completion>>> {
14994 self.update(cx, |project, cx| {
14995 let snippets = snippet_completions(project, buffer, buffer_position, cx);
14996 let project_completions = project.completions(buffer, buffer_position, options, cx);
14997 cx.background_executor().spawn(async move {
14998 let mut completions = project_completions.await?;
14999 let snippets_completions = snippets.await?;
15000 completions.extend(snippets_completions);
15001 Ok(completions)
15002 })
15003 })
15004 }
15005
15006 fn resolve_completions(
15007 &self,
15008 buffer: Entity<Buffer>,
15009 completion_indices: Vec<usize>,
15010 completions: Rc<RefCell<Box<[Completion]>>>,
15011 cx: &mut Context<Editor>,
15012 ) -> Task<Result<bool>> {
15013 self.update(cx, |project, cx| {
15014 project.lsp_store().update(cx, |lsp_store, cx| {
15015 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15016 })
15017 })
15018 }
15019
15020 fn apply_additional_edits_for_completion(
15021 &self,
15022 buffer: Entity<Buffer>,
15023 completions: Rc<RefCell<Box<[Completion]>>>,
15024 completion_index: usize,
15025 push_to_history: bool,
15026 cx: &mut Context<Editor>,
15027 ) -> Task<Result<Option<language::Transaction>>> {
15028 self.update(cx, |project, cx| {
15029 project.lsp_store().update(cx, |lsp_store, cx| {
15030 lsp_store.apply_additional_edits_for_completion(
15031 buffer,
15032 completions,
15033 completion_index,
15034 push_to_history,
15035 cx,
15036 )
15037 })
15038 })
15039 }
15040
15041 fn is_completion_trigger(
15042 &self,
15043 buffer: &Entity<Buffer>,
15044 position: language::Anchor,
15045 text: &str,
15046 trigger_in_words: bool,
15047 cx: &mut Context<Editor>,
15048 ) -> bool {
15049 let mut chars = text.chars();
15050 let char = if let Some(char) = chars.next() {
15051 char
15052 } else {
15053 return false;
15054 };
15055 if chars.next().is_some() {
15056 return false;
15057 }
15058
15059 let buffer = buffer.read(cx);
15060 let snapshot = buffer.snapshot();
15061 if !snapshot.settings_at(position, cx).show_completions_on_input {
15062 return false;
15063 }
15064 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15065 if trigger_in_words && classifier.is_word(char) {
15066 return true;
15067 }
15068
15069 buffer.completion_triggers().contains(text)
15070 }
15071}
15072
15073impl SemanticsProvider for Entity<Project> {
15074 fn hover(
15075 &self,
15076 buffer: &Entity<Buffer>,
15077 position: text::Anchor,
15078 cx: &mut App,
15079 ) -> Option<Task<Vec<project::Hover>>> {
15080 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15081 }
15082
15083 fn document_highlights(
15084 &self,
15085 buffer: &Entity<Buffer>,
15086 position: text::Anchor,
15087 cx: &mut App,
15088 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15089 Some(self.update(cx, |project, cx| {
15090 project.document_highlights(buffer, position, cx)
15091 }))
15092 }
15093
15094 fn definitions(
15095 &self,
15096 buffer: &Entity<Buffer>,
15097 position: text::Anchor,
15098 kind: GotoDefinitionKind,
15099 cx: &mut App,
15100 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15101 Some(self.update(cx, |project, cx| match kind {
15102 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15103 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15104 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15105 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15106 }))
15107 }
15108
15109 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15110 // TODO: make this work for remote projects
15111 self.read(cx)
15112 .language_servers_for_local_buffer(buffer.read(cx), cx)
15113 .any(
15114 |(_, server)| match server.capabilities().inlay_hint_provider {
15115 Some(lsp::OneOf::Left(enabled)) => enabled,
15116 Some(lsp::OneOf::Right(_)) => true,
15117 None => false,
15118 },
15119 )
15120 }
15121
15122 fn inlay_hints(
15123 &self,
15124 buffer_handle: Entity<Buffer>,
15125 range: Range<text::Anchor>,
15126 cx: &mut App,
15127 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15128 Some(self.update(cx, |project, cx| {
15129 project.inlay_hints(buffer_handle, range, cx)
15130 }))
15131 }
15132
15133 fn resolve_inlay_hint(
15134 &self,
15135 hint: InlayHint,
15136 buffer_handle: Entity<Buffer>,
15137 server_id: LanguageServerId,
15138 cx: &mut App,
15139 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15140 Some(self.update(cx, |project, cx| {
15141 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15142 }))
15143 }
15144
15145 fn range_for_rename(
15146 &self,
15147 buffer: &Entity<Buffer>,
15148 position: text::Anchor,
15149 cx: &mut App,
15150 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15151 Some(self.update(cx, |project, cx| {
15152 let buffer = buffer.clone();
15153 let task = project.prepare_rename(buffer.clone(), position, cx);
15154 cx.spawn(|_, mut cx| async move {
15155 Ok(match task.await? {
15156 PrepareRenameResponse::Success(range) => Some(range),
15157 PrepareRenameResponse::InvalidPosition => None,
15158 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15159 // Fallback on using TreeSitter info to determine identifier range
15160 buffer.update(&mut cx, |buffer, _| {
15161 let snapshot = buffer.snapshot();
15162 let (range, kind) = snapshot.surrounding_word(position);
15163 if kind != Some(CharKind::Word) {
15164 return None;
15165 }
15166 Some(
15167 snapshot.anchor_before(range.start)
15168 ..snapshot.anchor_after(range.end),
15169 )
15170 })?
15171 }
15172 })
15173 })
15174 }))
15175 }
15176
15177 fn perform_rename(
15178 &self,
15179 buffer: &Entity<Buffer>,
15180 position: text::Anchor,
15181 new_name: String,
15182 cx: &mut App,
15183 ) -> Option<Task<Result<ProjectTransaction>>> {
15184 Some(self.update(cx, |project, cx| {
15185 project.perform_rename(buffer.clone(), position, new_name, cx)
15186 }))
15187 }
15188}
15189
15190fn inlay_hint_settings(
15191 location: Anchor,
15192 snapshot: &MultiBufferSnapshot,
15193 cx: &mut Context<Editor>,
15194) -> InlayHintSettings {
15195 let file = snapshot.file_at(location);
15196 let language = snapshot.language_at(location).map(|l| l.name());
15197 language_settings(language, file, cx).inlay_hints
15198}
15199
15200fn consume_contiguous_rows(
15201 contiguous_row_selections: &mut Vec<Selection<Point>>,
15202 selection: &Selection<Point>,
15203 display_map: &DisplaySnapshot,
15204 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15205) -> (MultiBufferRow, MultiBufferRow) {
15206 contiguous_row_selections.push(selection.clone());
15207 let start_row = MultiBufferRow(selection.start.row);
15208 let mut end_row = ending_row(selection, display_map);
15209
15210 while let Some(next_selection) = selections.peek() {
15211 if next_selection.start.row <= end_row.0 {
15212 end_row = ending_row(next_selection, display_map);
15213 contiguous_row_selections.push(selections.next().unwrap().clone());
15214 } else {
15215 break;
15216 }
15217 }
15218 (start_row, end_row)
15219}
15220
15221fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15222 if next_selection.end.column > 0 || next_selection.is_empty() {
15223 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15224 } else {
15225 MultiBufferRow(next_selection.end.row)
15226 }
15227}
15228
15229impl EditorSnapshot {
15230 pub fn remote_selections_in_range<'a>(
15231 &'a self,
15232 range: &'a Range<Anchor>,
15233 collaboration_hub: &dyn CollaborationHub,
15234 cx: &'a App,
15235 ) -> impl 'a + Iterator<Item = RemoteSelection> {
15236 let participant_names = collaboration_hub.user_names(cx);
15237 let participant_indices = collaboration_hub.user_participant_indices(cx);
15238 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15239 let collaborators_by_replica_id = collaborators_by_peer_id
15240 .iter()
15241 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15242 .collect::<HashMap<_, _>>();
15243 self.buffer_snapshot
15244 .selections_in_range(range, false)
15245 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15246 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15247 let participant_index = participant_indices.get(&collaborator.user_id).copied();
15248 let user_name = participant_names.get(&collaborator.user_id).cloned();
15249 Some(RemoteSelection {
15250 replica_id,
15251 selection,
15252 cursor_shape,
15253 line_mode,
15254 participant_index,
15255 peer_id: collaborator.peer_id,
15256 user_name,
15257 })
15258 })
15259 }
15260
15261 pub fn hunks_for_ranges(
15262 &self,
15263 ranges: impl Iterator<Item = Range<Point>>,
15264 ) -> Vec<MultiBufferDiffHunk> {
15265 let mut hunks = Vec::new();
15266 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15267 HashMap::default();
15268 for query_range in ranges {
15269 let query_rows =
15270 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15271 for hunk in self.buffer_snapshot.diff_hunks_in_range(
15272 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15273 ) {
15274 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15275 // when the caret is just above or just below the deleted hunk.
15276 let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15277 let related_to_selection = if allow_adjacent {
15278 hunk.row_range.overlaps(&query_rows)
15279 || hunk.row_range.start == query_rows.end
15280 || hunk.row_range.end == query_rows.start
15281 } else {
15282 hunk.row_range.overlaps(&query_rows)
15283 };
15284 if related_to_selection {
15285 if !processed_buffer_rows
15286 .entry(hunk.buffer_id)
15287 .or_default()
15288 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15289 {
15290 continue;
15291 }
15292 hunks.push(hunk);
15293 }
15294 }
15295 }
15296
15297 hunks
15298 }
15299
15300 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15301 self.display_snapshot.buffer_snapshot.language_at(position)
15302 }
15303
15304 pub fn is_focused(&self) -> bool {
15305 self.is_focused
15306 }
15307
15308 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15309 self.placeholder_text.as_ref()
15310 }
15311
15312 pub fn scroll_position(&self) -> gpui::Point<f32> {
15313 self.scroll_anchor.scroll_position(&self.display_snapshot)
15314 }
15315
15316 fn gutter_dimensions(
15317 &self,
15318 font_id: FontId,
15319 font_size: Pixels,
15320 max_line_number_width: Pixels,
15321 cx: &App,
15322 ) -> Option<GutterDimensions> {
15323 if !self.show_gutter {
15324 return None;
15325 }
15326
15327 let descent = cx.text_system().descent(font_id, font_size);
15328 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15329 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15330
15331 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15332 matches!(
15333 ProjectSettings::get_global(cx).git.git_gutter,
15334 Some(GitGutterSetting::TrackedFiles)
15335 )
15336 });
15337 let gutter_settings = EditorSettings::get_global(cx).gutter;
15338 let show_line_numbers = self
15339 .show_line_numbers
15340 .unwrap_or(gutter_settings.line_numbers);
15341 let line_gutter_width = if show_line_numbers {
15342 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15343 let min_width_for_number_on_gutter = em_advance * 4.0;
15344 max_line_number_width.max(min_width_for_number_on_gutter)
15345 } else {
15346 0.0.into()
15347 };
15348
15349 let show_code_actions = self
15350 .show_code_actions
15351 .unwrap_or(gutter_settings.code_actions);
15352
15353 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15354
15355 let git_blame_entries_width =
15356 self.git_blame_gutter_max_author_length
15357 .map(|max_author_length| {
15358 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15359
15360 /// The number of characters to dedicate to gaps and margins.
15361 const SPACING_WIDTH: usize = 4;
15362
15363 let max_char_count = max_author_length
15364 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15365 + ::git::SHORT_SHA_LENGTH
15366 + MAX_RELATIVE_TIMESTAMP.len()
15367 + SPACING_WIDTH;
15368
15369 em_advance * max_char_count
15370 });
15371
15372 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15373 left_padding += if show_code_actions || show_runnables {
15374 em_width * 3.0
15375 } else if show_git_gutter && show_line_numbers {
15376 em_width * 2.0
15377 } else if show_git_gutter || show_line_numbers {
15378 em_width
15379 } else {
15380 px(0.)
15381 };
15382
15383 let right_padding = if gutter_settings.folds && show_line_numbers {
15384 em_width * 4.0
15385 } else if gutter_settings.folds {
15386 em_width * 3.0
15387 } else if show_line_numbers {
15388 em_width
15389 } else {
15390 px(0.)
15391 };
15392
15393 Some(GutterDimensions {
15394 left_padding,
15395 right_padding,
15396 width: line_gutter_width + left_padding + right_padding,
15397 margin: -descent,
15398 git_blame_entries_width,
15399 })
15400 }
15401
15402 pub fn render_crease_toggle(
15403 &self,
15404 buffer_row: MultiBufferRow,
15405 row_contains_cursor: bool,
15406 editor: Entity<Editor>,
15407 window: &mut Window,
15408 cx: &mut App,
15409 ) -> Option<AnyElement> {
15410 let folded = self.is_line_folded(buffer_row);
15411 let mut is_foldable = false;
15412
15413 if let Some(crease) = self
15414 .crease_snapshot
15415 .query_row(buffer_row, &self.buffer_snapshot)
15416 {
15417 is_foldable = true;
15418 match crease {
15419 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15420 if let Some(render_toggle) = render_toggle {
15421 let toggle_callback =
15422 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15423 if folded {
15424 editor.update(cx, |editor, cx| {
15425 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15426 });
15427 } else {
15428 editor.update(cx, |editor, cx| {
15429 editor.unfold_at(
15430 &crate::UnfoldAt { buffer_row },
15431 window,
15432 cx,
15433 )
15434 });
15435 }
15436 });
15437 return Some((render_toggle)(
15438 buffer_row,
15439 folded,
15440 toggle_callback,
15441 window,
15442 cx,
15443 ));
15444 }
15445 }
15446 }
15447 }
15448
15449 is_foldable |= self.starts_indent(buffer_row);
15450
15451 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15452 Some(
15453 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15454 .toggle_state(folded)
15455 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15456 if folded {
15457 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15458 } else {
15459 this.fold_at(&FoldAt { buffer_row }, window, cx);
15460 }
15461 }))
15462 .into_any_element(),
15463 )
15464 } else {
15465 None
15466 }
15467 }
15468
15469 pub fn render_crease_trailer(
15470 &self,
15471 buffer_row: MultiBufferRow,
15472 window: &mut Window,
15473 cx: &mut App,
15474 ) -> Option<AnyElement> {
15475 let folded = self.is_line_folded(buffer_row);
15476 if let Crease::Inline { render_trailer, .. } = self
15477 .crease_snapshot
15478 .query_row(buffer_row, &self.buffer_snapshot)?
15479 {
15480 let render_trailer = render_trailer.as_ref()?;
15481 Some(render_trailer(buffer_row, folded, window, cx))
15482 } else {
15483 None
15484 }
15485 }
15486}
15487
15488impl Deref for EditorSnapshot {
15489 type Target = DisplaySnapshot;
15490
15491 fn deref(&self) -> &Self::Target {
15492 &self.display_snapshot
15493 }
15494}
15495
15496#[derive(Clone, Debug, PartialEq, Eq)]
15497pub enum EditorEvent {
15498 InputIgnored {
15499 text: Arc<str>,
15500 },
15501 InputHandled {
15502 utf16_range_to_replace: Option<Range<isize>>,
15503 text: Arc<str>,
15504 },
15505 ExcerptsAdded {
15506 buffer: Entity<Buffer>,
15507 predecessor: ExcerptId,
15508 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15509 },
15510 ExcerptsRemoved {
15511 ids: Vec<ExcerptId>,
15512 },
15513 BufferFoldToggled {
15514 ids: Vec<ExcerptId>,
15515 folded: bool,
15516 },
15517 ExcerptsEdited {
15518 ids: Vec<ExcerptId>,
15519 },
15520 ExcerptsExpanded {
15521 ids: Vec<ExcerptId>,
15522 },
15523 BufferEdited,
15524 Edited {
15525 transaction_id: clock::Lamport,
15526 },
15527 Reparsed(BufferId),
15528 Focused,
15529 FocusedIn,
15530 Blurred,
15531 DirtyChanged,
15532 Saved,
15533 TitleChanged,
15534 DiffBaseChanged,
15535 SelectionsChanged {
15536 local: bool,
15537 },
15538 ScrollPositionChanged {
15539 local: bool,
15540 autoscroll: bool,
15541 },
15542 Closed,
15543 TransactionUndone {
15544 transaction_id: clock::Lamport,
15545 },
15546 TransactionBegun {
15547 transaction_id: clock::Lamport,
15548 },
15549 Reloaded,
15550 CursorShapeChanged,
15551}
15552
15553impl EventEmitter<EditorEvent> for Editor {}
15554
15555impl Focusable for Editor {
15556 fn focus_handle(&self, _cx: &App) -> FocusHandle {
15557 self.focus_handle.clone()
15558 }
15559}
15560
15561impl Render for Editor {
15562 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15563 let settings = ThemeSettings::get_global(cx);
15564
15565 let mut text_style = match self.mode {
15566 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15567 color: cx.theme().colors().editor_foreground,
15568 font_family: settings.ui_font.family.clone(),
15569 font_features: settings.ui_font.features.clone(),
15570 font_fallbacks: settings.ui_font.fallbacks.clone(),
15571 font_size: rems(0.875).into(),
15572 font_weight: settings.ui_font.weight,
15573 line_height: relative(settings.buffer_line_height.value()),
15574 ..Default::default()
15575 },
15576 EditorMode::Full => TextStyle {
15577 color: cx.theme().colors().editor_foreground,
15578 font_family: settings.buffer_font.family.clone(),
15579 font_features: settings.buffer_font.features.clone(),
15580 font_fallbacks: settings.buffer_font.fallbacks.clone(),
15581 font_size: settings.buffer_font_size().into(),
15582 font_weight: settings.buffer_font.weight,
15583 line_height: relative(settings.buffer_line_height.value()),
15584 ..Default::default()
15585 },
15586 };
15587 if let Some(text_style_refinement) = &self.text_style_refinement {
15588 text_style.refine(text_style_refinement)
15589 }
15590
15591 let background = match self.mode {
15592 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15593 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15594 EditorMode::Full => cx.theme().colors().editor_background,
15595 };
15596
15597 EditorElement::new(
15598 &cx.entity(),
15599 EditorStyle {
15600 background,
15601 local_player: cx.theme().players().local(),
15602 text: text_style,
15603 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15604 syntax: cx.theme().syntax().clone(),
15605 status: cx.theme().status().clone(),
15606 inlay_hints_style: make_inlay_hints_style(cx),
15607 inline_completion_styles: make_suggestion_styles(cx),
15608 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15609 },
15610 )
15611 }
15612}
15613
15614impl EntityInputHandler for Editor {
15615 fn text_for_range(
15616 &mut self,
15617 range_utf16: Range<usize>,
15618 adjusted_range: &mut Option<Range<usize>>,
15619 _: &mut Window,
15620 cx: &mut Context<Self>,
15621 ) -> Option<String> {
15622 let snapshot = self.buffer.read(cx).read(cx);
15623 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15624 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15625 if (start.0..end.0) != range_utf16 {
15626 adjusted_range.replace(start.0..end.0);
15627 }
15628 Some(snapshot.text_for_range(start..end).collect())
15629 }
15630
15631 fn selected_text_range(
15632 &mut self,
15633 ignore_disabled_input: bool,
15634 _: &mut Window,
15635 cx: &mut Context<Self>,
15636 ) -> Option<UTF16Selection> {
15637 // Prevent the IME menu from appearing when holding down an alphabetic key
15638 // while input is disabled.
15639 if !ignore_disabled_input && !self.input_enabled {
15640 return None;
15641 }
15642
15643 let selection = self.selections.newest::<OffsetUtf16>(cx);
15644 let range = selection.range();
15645
15646 Some(UTF16Selection {
15647 range: range.start.0..range.end.0,
15648 reversed: selection.reversed,
15649 })
15650 }
15651
15652 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15653 let snapshot = self.buffer.read(cx).read(cx);
15654 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15655 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15656 }
15657
15658 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15659 self.clear_highlights::<InputComposition>(cx);
15660 self.ime_transaction.take();
15661 }
15662
15663 fn replace_text_in_range(
15664 &mut self,
15665 range_utf16: Option<Range<usize>>,
15666 text: &str,
15667 window: &mut Window,
15668 cx: &mut Context<Self>,
15669 ) {
15670 if !self.input_enabled {
15671 cx.emit(EditorEvent::InputIgnored { text: text.into() });
15672 return;
15673 }
15674
15675 self.transact(window, cx, |this, window, cx| {
15676 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15677 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15678 Some(this.selection_replacement_ranges(range_utf16, cx))
15679 } else {
15680 this.marked_text_ranges(cx)
15681 };
15682
15683 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15684 let newest_selection_id = this.selections.newest_anchor().id;
15685 this.selections
15686 .all::<OffsetUtf16>(cx)
15687 .iter()
15688 .zip(ranges_to_replace.iter())
15689 .find_map(|(selection, range)| {
15690 if selection.id == newest_selection_id {
15691 Some(
15692 (range.start.0 as isize - selection.head().0 as isize)
15693 ..(range.end.0 as isize - selection.head().0 as isize),
15694 )
15695 } else {
15696 None
15697 }
15698 })
15699 });
15700
15701 cx.emit(EditorEvent::InputHandled {
15702 utf16_range_to_replace: range_to_replace,
15703 text: text.into(),
15704 });
15705
15706 if let Some(new_selected_ranges) = new_selected_ranges {
15707 this.change_selections(None, window, cx, |selections| {
15708 selections.select_ranges(new_selected_ranges)
15709 });
15710 this.backspace(&Default::default(), window, cx);
15711 }
15712
15713 this.handle_input(text, window, cx);
15714 });
15715
15716 if let Some(transaction) = self.ime_transaction {
15717 self.buffer.update(cx, |buffer, cx| {
15718 buffer.group_until_transaction(transaction, cx);
15719 });
15720 }
15721
15722 self.unmark_text(window, cx);
15723 }
15724
15725 fn replace_and_mark_text_in_range(
15726 &mut self,
15727 range_utf16: Option<Range<usize>>,
15728 text: &str,
15729 new_selected_range_utf16: Option<Range<usize>>,
15730 window: &mut Window,
15731 cx: &mut Context<Self>,
15732 ) {
15733 if !self.input_enabled {
15734 return;
15735 }
15736
15737 let transaction = self.transact(window, cx, |this, window, cx| {
15738 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15739 let snapshot = this.buffer.read(cx).read(cx);
15740 if let Some(relative_range_utf16) = range_utf16.as_ref() {
15741 for marked_range in &mut marked_ranges {
15742 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15743 marked_range.start.0 += relative_range_utf16.start;
15744 marked_range.start =
15745 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15746 marked_range.end =
15747 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15748 }
15749 }
15750 Some(marked_ranges)
15751 } else if let Some(range_utf16) = range_utf16 {
15752 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15753 Some(this.selection_replacement_ranges(range_utf16, cx))
15754 } else {
15755 None
15756 };
15757
15758 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
15759 let newest_selection_id = this.selections.newest_anchor().id;
15760 this.selections
15761 .all::<OffsetUtf16>(cx)
15762 .iter()
15763 .zip(ranges_to_replace.iter())
15764 .find_map(|(selection, range)| {
15765 if selection.id == newest_selection_id {
15766 Some(
15767 (range.start.0 as isize - selection.head().0 as isize)
15768 ..(range.end.0 as isize - selection.head().0 as isize),
15769 )
15770 } else {
15771 None
15772 }
15773 })
15774 });
15775
15776 cx.emit(EditorEvent::InputHandled {
15777 utf16_range_to_replace: range_to_replace,
15778 text: text.into(),
15779 });
15780
15781 if let Some(ranges) = ranges_to_replace {
15782 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
15783 }
15784
15785 let marked_ranges = {
15786 let snapshot = this.buffer.read(cx).read(cx);
15787 this.selections
15788 .disjoint_anchors()
15789 .iter()
15790 .map(|selection| {
15791 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
15792 })
15793 .collect::<Vec<_>>()
15794 };
15795
15796 if text.is_empty() {
15797 this.unmark_text(window, cx);
15798 } else {
15799 this.highlight_text::<InputComposition>(
15800 marked_ranges.clone(),
15801 HighlightStyle {
15802 underline: Some(UnderlineStyle {
15803 thickness: px(1.),
15804 color: None,
15805 wavy: false,
15806 }),
15807 ..Default::default()
15808 },
15809 cx,
15810 );
15811 }
15812
15813 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
15814 let use_autoclose = this.use_autoclose;
15815 let use_auto_surround = this.use_auto_surround;
15816 this.set_use_autoclose(false);
15817 this.set_use_auto_surround(false);
15818 this.handle_input(text, window, cx);
15819 this.set_use_autoclose(use_autoclose);
15820 this.set_use_auto_surround(use_auto_surround);
15821
15822 if let Some(new_selected_range) = new_selected_range_utf16 {
15823 let snapshot = this.buffer.read(cx).read(cx);
15824 let new_selected_ranges = marked_ranges
15825 .into_iter()
15826 .map(|marked_range| {
15827 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
15828 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
15829 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
15830 snapshot.clip_offset_utf16(new_start, Bias::Left)
15831 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
15832 })
15833 .collect::<Vec<_>>();
15834
15835 drop(snapshot);
15836 this.change_selections(None, window, cx, |selections| {
15837 selections.select_ranges(new_selected_ranges)
15838 });
15839 }
15840 });
15841
15842 self.ime_transaction = self.ime_transaction.or(transaction);
15843 if let Some(transaction) = self.ime_transaction {
15844 self.buffer.update(cx, |buffer, cx| {
15845 buffer.group_until_transaction(transaction, cx);
15846 });
15847 }
15848
15849 if self.text_highlights::<InputComposition>(cx).is_none() {
15850 self.ime_transaction.take();
15851 }
15852 }
15853
15854 fn bounds_for_range(
15855 &mut self,
15856 range_utf16: Range<usize>,
15857 element_bounds: gpui::Bounds<Pixels>,
15858 window: &mut Window,
15859 cx: &mut Context<Self>,
15860 ) -> Option<gpui::Bounds<Pixels>> {
15861 let text_layout_details = self.text_layout_details(window);
15862 let gpui::Point {
15863 x: em_width,
15864 y: line_height,
15865 } = self.character_size(window);
15866
15867 let snapshot = self.snapshot(window, cx);
15868 let scroll_position = snapshot.scroll_position();
15869 let scroll_left = scroll_position.x * em_width;
15870
15871 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
15872 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
15873 + self.gutter_dimensions.width
15874 + self.gutter_dimensions.margin;
15875 let y = line_height * (start.row().as_f32() - scroll_position.y);
15876
15877 Some(Bounds {
15878 origin: element_bounds.origin + point(x, y),
15879 size: size(em_width, line_height),
15880 })
15881 }
15882}
15883
15884trait SelectionExt {
15885 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
15886 fn spanned_rows(
15887 &self,
15888 include_end_if_at_line_start: bool,
15889 map: &DisplaySnapshot,
15890 ) -> Range<MultiBufferRow>;
15891}
15892
15893impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
15894 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
15895 let start = self
15896 .start
15897 .to_point(&map.buffer_snapshot)
15898 .to_display_point(map);
15899 let end = self
15900 .end
15901 .to_point(&map.buffer_snapshot)
15902 .to_display_point(map);
15903 if self.reversed {
15904 end..start
15905 } else {
15906 start..end
15907 }
15908 }
15909
15910 fn spanned_rows(
15911 &self,
15912 include_end_if_at_line_start: bool,
15913 map: &DisplaySnapshot,
15914 ) -> Range<MultiBufferRow> {
15915 let start = self.start.to_point(&map.buffer_snapshot);
15916 let mut end = self.end.to_point(&map.buffer_snapshot);
15917 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
15918 end.row -= 1;
15919 }
15920
15921 let buffer_start = map.prev_line_boundary(start).0;
15922 let buffer_end = map.next_line_boundary(end).0;
15923 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
15924 }
15925}
15926
15927impl<T: InvalidationRegion> InvalidationStack<T> {
15928 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
15929 where
15930 S: Clone + ToOffset,
15931 {
15932 while let Some(region) = self.last() {
15933 let all_selections_inside_invalidation_ranges =
15934 if selections.len() == region.ranges().len() {
15935 selections
15936 .iter()
15937 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
15938 .all(|(selection, invalidation_range)| {
15939 let head = selection.head().to_offset(buffer);
15940 invalidation_range.start <= head && invalidation_range.end >= head
15941 })
15942 } else {
15943 false
15944 };
15945
15946 if all_selections_inside_invalidation_ranges {
15947 break;
15948 } else {
15949 self.pop();
15950 }
15951 }
15952 }
15953}
15954
15955impl<T> Default for InvalidationStack<T> {
15956 fn default() -> Self {
15957 Self(Default::default())
15958 }
15959}
15960
15961impl<T> Deref for InvalidationStack<T> {
15962 type Target = Vec<T>;
15963
15964 fn deref(&self) -> &Self::Target {
15965 &self.0
15966 }
15967}
15968
15969impl<T> DerefMut for InvalidationStack<T> {
15970 fn deref_mut(&mut self) -> &mut Self::Target {
15971 &mut self.0
15972 }
15973}
15974
15975impl InvalidationRegion for SnippetState {
15976 fn ranges(&self) -> &[Range<Anchor>] {
15977 &self.ranges[self.active_index]
15978 }
15979}
15980
15981pub fn diagnostic_block_renderer(
15982 diagnostic: Diagnostic,
15983 max_message_rows: Option<u8>,
15984 allow_closing: bool,
15985 _is_valid: bool,
15986) -> RenderBlock {
15987 let (text_without_backticks, code_ranges) =
15988 highlight_diagnostic_message(&diagnostic, max_message_rows);
15989
15990 Arc::new(move |cx: &mut BlockContext| {
15991 let group_id: SharedString = cx.block_id.to_string().into();
15992
15993 let mut text_style = cx.window.text_style().clone();
15994 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
15995 let theme_settings = ThemeSettings::get_global(cx);
15996 text_style.font_family = theme_settings.buffer_font.family.clone();
15997 text_style.font_style = theme_settings.buffer_font.style;
15998 text_style.font_features = theme_settings.buffer_font.features.clone();
15999 text_style.font_weight = theme_settings.buffer_font.weight;
16000
16001 let multi_line_diagnostic = diagnostic.message.contains('\n');
16002
16003 let buttons = |diagnostic: &Diagnostic| {
16004 if multi_line_diagnostic {
16005 v_flex()
16006 } else {
16007 h_flex()
16008 }
16009 .when(allow_closing, |div| {
16010 div.children(diagnostic.is_primary.then(|| {
16011 IconButton::new("close-block", IconName::XCircle)
16012 .icon_color(Color::Muted)
16013 .size(ButtonSize::Compact)
16014 .style(ButtonStyle::Transparent)
16015 .visible_on_hover(group_id.clone())
16016 .on_click(move |_click, window, cx| {
16017 window.dispatch_action(Box::new(Cancel), cx)
16018 })
16019 .tooltip(|window, cx| {
16020 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16021 })
16022 }))
16023 })
16024 .child(
16025 IconButton::new("copy-block", IconName::Copy)
16026 .icon_color(Color::Muted)
16027 .size(ButtonSize::Compact)
16028 .style(ButtonStyle::Transparent)
16029 .visible_on_hover(group_id.clone())
16030 .on_click({
16031 let message = diagnostic.message.clone();
16032 move |_click, _, cx| {
16033 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16034 }
16035 })
16036 .tooltip(Tooltip::text("Copy diagnostic message")),
16037 )
16038 };
16039
16040 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16041 AvailableSpace::min_size(),
16042 cx.window,
16043 cx.app,
16044 );
16045
16046 h_flex()
16047 .id(cx.block_id)
16048 .group(group_id.clone())
16049 .relative()
16050 .size_full()
16051 .block_mouse_down()
16052 .pl(cx.gutter_dimensions.width)
16053 .w(cx.max_width - cx.gutter_dimensions.full_width())
16054 .child(
16055 div()
16056 .flex()
16057 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16058 .flex_shrink(),
16059 )
16060 .child(buttons(&diagnostic))
16061 .child(div().flex().flex_shrink_0().child(
16062 StyledText::new(text_without_backticks.clone()).with_highlights(
16063 &text_style,
16064 code_ranges.iter().map(|range| {
16065 (
16066 range.clone(),
16067 HighlightStyle {
16068 font_weight: Some(FontWeight::BOLD),
16069 ..Default::default()
16070 },
16071 )
16072 }),
16073 ),
16074 ))
16075 .into_any_element()
16076 })
16077}
16078
16079fn inline_completion_edit_text(
16080 current_snapshot: &BufferSnapshot,
16081 edits: &[(Range<Anchor>, String)],
16082 edit_preview: &EditPreview,
16083 include_deletions: bool,
16084 cx: &App,
16085) -> HighlightedText {
16086 let edits = edits
16087 .iter()
16088 .map(|(anchor, text)| {
16089 (
16090 anchor.start.text_anchor..anchor.end.text_anchor,
16091 text.clone(),
16092 )
16093 })
16094 .collect::<Vec<_>>();
16095
16096 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16097}
16098
16099pub fn highlight_diagnostic_message(
16100 diagnostic: &Diagnostic,
16101 mut max_message_rows: Option<u8>,
16102) -> (SharedString, Vec<Range<usize>>) {
16103 let mut text_without_backticks = String::new();
16104 let mut code_ranges = Vec::new();
16105
16106 if let Some(source) = &diagnostic.source {
16107 text_without_backticks.push_str(source);
16108 code_ranges.push(0..source.len());
16109 text_without_backticks.push_str(": ");
16110 }
16111
16112 let mut prev_offset = 0;
16113 let mut in_code_block = false;
16114 let has_row_limit = max_message_rows.is_some();
16115 let mut newline_indices = diagnostic
16116 .message
16117 .match_indices('\n')
16118 .filter(|_| has_row_limit)
16119 .map(|(ix, _)| ix)
16120 .fuse()
16121 .peekable();
16122
16123 for (quote_ix, _) in diagnostic
16124 .message
16125 .match_indices('`')
16126 .chain([(diagnostic.message.len(), "")])
16127 {
16128 let mut first_newline_ix = None;
16129 let mut last_newline_ix = None;
16130 while let Some(newline_ix) = newline_indices.peek() {
16131 if *newline_ix < quote_ix {
16132 if first_newline_ix.is_none() {
16133 first_newline_ix = Some(*newline_ix);
16134 }
16135 last_newline_ix = Some(*newline_ix);
16136
16137 if let Some(rows_left) = &mut max_message_rows {
16138 if *rows_left == 0 {
16139 break;
16140 } else {
16141 *rows_left -= 1;
16142 }
16143 }
16144 let _ = newline_indices.next();
16145 } else {
16146 break;
16147 }
16148 }
16149 let prev_len = text_without_backticks.len();
16150 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16151 text_without_backticks.push_str(new_text);
16152 if in_code_block {
16153 code_ranges.push(prev_len..text_without_backticks.len());
16154 }
16155 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16156 in_code_block = !in_code_block;
16157 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16158 text_without_backticks.push_str("...");
16159 break;
16160 }
16161 }
16162
16163 (text_without_backticks.into(), code_ranges)
16164}
16165
16166fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16167 match severity {
16168 DiagnosticSeverity::ERROR => colors.error,
16169 DiagnosticSeverity::WARNING => colors.warning,
16170 DiagnosticSeverity::INFORMATION => colors.info,
16171 DiagnosticSeverity::HINT => colors.info,
16172 _ => colors.ignored,
16173 }
16174}
16175
16176pub fn styled_runs_for_code_label<'a>(
16177 label: &'a CodeLabel,
16178 syntax_theme: &'a theme::SyntaxTheme,
16179) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16180 let fade_out = HighlightStyle {
16181 fade_out: Some(0.35),
16182 ..Default::default()
16183 };
16184
16185 let mut prev_end = label.filter_range.end;
16186 label
16187 .runs
16188 .iter()
16189 .enumerate()
16190 .flat_map(move |(ix, (range, highlight_id))| {
16191 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16192 style
16193 } else {
16194 return Default::default();
16195 };
16196 let mut muted_style = style;
16197 muted_style.highlight(fade_out);
16198
16199 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16200 if range.start >= label.filter_range.end {
16201 if range.start > prev_end {
16202 runs.push((prev_end..range.start, fade_out));
16203 }
16204 runs.push((range.clone(), muted_style));
16205 } else if range.end <= label.filter_range.end {
16206 runs.push((range.clone(), style));
16207 } else {
16208 runs.push((range.start..label.filter_range.end, style));
16209 runs.push((label.filter_range.end..range.end, muted_style));
16210 }
16211 prev_end = cmp::max(prev_end, range.end);
16212
16213 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16214 runs.push((prev_end..label.text.len(), fade_out));
16215 }
16216
16217 runs
16218 })
16219}
16220
16221pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16222 let mut prev_index = 0;
16223 let mut prev_codepoint: Option<char> = None;
16224 text.char_indices()
16225 .chain([(text.len(), '\0')])
16226 .filter_map(move |(index, codepoint)| {
16227 let prev_codepoint = prev_codepoint.replace(codepoint)?;
16228 let is_boundary = index == text.len()
16229 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16230 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16231 if is_boundary {
16232 let chunk = &text[prev_index..index];
16233 prev_index = index;
16234 Some(chunk)
16235 } else {
16236 None
16237 }
16238 })
16239}
16240
16241pub trait RangeToAnchorExt: Sized {
16242 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16243
16244 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16245 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16246 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16247 }
16248}
16249
16250impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16251 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16252 let start_offset = self.start.to_offset(snapshot);
16253 let end_offset = self.end.to_offset(snapshot);
16254 if start_offset == end_offset {
16255 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16256 } else {
16257 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16258 }
16259 }
16260}
16261
16262pub trait RowExt {
16263 fn as_f32(&self) -> f32;
16264
16265 fn next_row(&self) -> Self;
16266
16267 fn previous_row(&self) -> Self;
16268
16269 fn minus(&self, other: Self) -> u32;
16270}
16271
16272impl RowExt for DisplayRow {
16273 fn as_f32(&self) -> f32 {
16274 self.0 as f32
16275 }
16276
16277 fn next_row(&self) -> Self {
16278 Self(self.0 + 1)
16279 }
16280
16281 fn previous_row(&self) -> Self {
16282 Self(self.0.saturating_sub(1))
16283 }
16284
16285 fn minus(&self, other: Self) -> u32 {
16286 self.0 - other.0
16287 }
16288}
16289
16290impl RowExt for MultiBufferRow {
16291 fn as_f32(&self) -> f32 {
16292 self.0 as f32
16293 }
16294
16295 fn next_row(&self) -> Self {
16296 Self(self.0 + 1)
16297 }
16298
16299 fn previous_row(&self) -> Self {
16300 Self(self.0.saturating_sub(1))
16301 }
16302
16303 fn minus(&self, other: Self) -> u32 {
16304 self.0 - other.0
16305 }
16306}
16307
16308trait RowRangeExt {
16309 type Row;
16310
16311 fn len(&self) -> usize;
16312
16313 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16314}
16315
16316impl RowRangeExt for Range<MultiBufferRow> {
16317 type Row = MultiBufferRow;
16318
16319 fn len(&self) -> usize {
16320 (self.end.0 - self.start.0) as usize
16321 }
16322
16323 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16324 (self.start.0..self.end.0).map(MultiBufferRow)
16325 }
16326}
16327
16328impl RowRangeExt for Range<DisplayRow> {
16329 type Row = DisplayRow;
16330
16331 fn len(&self) -> usize {
16332 (self.end.0 - self.start.0) as usize
16333 }
16334
16335 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16336 (self.start.0..self.end.0).map(DisplayRow)
16337 }
16338}
16339
16340/// If select range has more than one line, we
16341/// just point the cursor to range.start.
16342fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16343 if range.start.row == range.end.row {
16344 range
16345 } else {
16346 range.start..range.start
16347 }
16348}
16349pub struct KillRing(ClipboardItem);
16350impl Global for KillRing {}
16351
16352const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16353
16354fn all_edits_insertions_or_deletions(
16355 edits: &Vec<(Range<Anchor>, String)>,
16356 snapshot: &MultiBufferSnapshot,
16357) -> bool {
16358 let mut all_insertions = true;
16359 let mut all_deletions = true;
16360
16361 for (range, new_text) in edits.iter() {
16362 let range_is_empty = range.to_offset(&snapshot).is_empty();
16363 let text_is_empty = new_text.is_empty();
16364
16365 if range_is_empty != text_is_empty {
16366 if range_is_empty {
16367 all_deletions = false;
16368 } else {
16369 all_insertions = false;
16370 }
16371 } else {
16372 return false;
16373 }
16374
16375 if !all_insertions && !all_deletions {
16376 return false;
16377 }
16378 }
16379 all_insertions || all_deletions
16380}