1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod clangd_ext;
19mod code_context_menus;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod indent_guides;
29mod inlay_hint_cache;
30pub mod items;
31mod linked_editing_ranges;
32mod lsp_ext;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod proposed_changes_editor;
37mod rust_analyzer_ext;
38pub mod scroll;
39mod selections_collection;
40pub mod tasks;
41
42#[cfg(test)]
43mod editor_tests;
44#[cfg(test)]
45mod inline_completion_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50pub(crate) use actions::*;
51pub use actions::{OpenExcerpts, OpenExcerptsSplit};
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use client::{Collaborator, ParticipantIndex};
56use clock::ReplicaId;
57use collections::{BTreeMap, HashMap, HashSet, VecDeque};
58use convert_case::{Case, Casing};
59use display_map::*;
60pub use display_map::{DisplayPoint, FoldPlaceholder};
61pub use editor_settings::{
62 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
63};
64pub use editor_settings_controls::*;
65pub use element::{
66 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
67};
68use element::{LineWithInvisibles, PositionMap};
69use futures::{future, FutureExt};
70use fuzzy::StringMatchCandidate;
71
72use code_context_menus::{
73 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
74 CompletionsMenu, ContextMenuOrigin,
75};
76use diff::DiffHunkStatus;
77use git::blame::GitBlame;
78use gpui::{
79 div, impl_actions, linear_color_stop, linear_gradient, point, prelude::*, pulsating_between,
80 px, relative, size, Action, Animation, AnimationExt, AnyElement, App, AsyncWindowContext,
81 AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context, DispatchPhase, ElementId,
82 Entity, EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId,
83 FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Modifiers, MouseButton,
84 MouseDownEvent, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled,
85 StyledText, Subscription, Task, TextRun, TextStyle, TextStyleRefinement, UTF16Selection,
86 UnderlineStyle, UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
87};
88use highlight_matching_bracket::refresh_matching_bracket_highlights;
89use hover_popover::{hide_hover, HoverState};
90use indent_guides::ActiveIndentGuidesState;
91use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
92pub use inline_completion::Direction;
93use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
94pub use items::MAX_TAB_TITLE_LEN;
95use itertools::Itertools;
96use language::{
97 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
98 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
99 CompletionDocumentation, CursorShape, Diagnostic, EditPreview, HighlightedText, IndentKind,
100 IndentSize, InlineCompletionPreviewMode, Language, OffsetRangeExt, Point, Selection,
101 SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
102};
103use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
104use linked_editing_ranges::refresh_linked_ranges;
105use mouse_context_menu::MouseContextMenu;
106pub use proposed_changes_editor::{
107 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
108};
109use similar::{ChangeTag, TextDiff};
110use std::iter::Peekable;
111use task::{ResolvedTask, TaskTemplate, TaskVariables};
112
113use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
114pub use lsp::CompletionContext;
115use lsp::{
116 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
117 LanguageServerId, LanguageServerName,
118};
119
120use language::BufferSnapshot;
121use movement::TextLayoutDetails;
122pub use multi_buffer::{
123 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
124 ToOffset, ToPoint,
125};
126use multi_buffer::{
127 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
128 ToOffsetUtf16,
129};
130use project::{
131 lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
132 project_settings::{GitGutterSetting, ProjectSettings},
133 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
134 LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
135};
136use rand::prelude::*;
137use rpc::{proto::*, ErrorExt};
138use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
139use selections_collection::{
140 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
141};
142use serde::{Deserialize, Serialize};
143use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
144use smallvec::SmallVec;
145use snippet::Snippet;
146use std::{
147 any::TypeId,
148 borrow::Cow,
149 cell::RefCell,
150 cmp::{self, Ordering, Reverse},
151 mem,
152 num::NonZeroU32,
153 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
154 path::{Path, PathBuf},
155 rc::Rc,
156 sync::Arc,
157 time::{Duration, Instant},
158};
159pub use sum_tree::Bias;
160use sum_tree::TreeMap;
161use text::{BufferId, OffsetUtf16, Rope};
162use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
163use ui::{
164 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
165 Tooltip,
166};
167use util::{defer, maybe, post_inc, RangeExt, ResultExt, TakeUntilExt, TryFutureExt};
168use workspace::item::{ItemHandle, PreviewTabsSettings};
169use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
170use workspace::{
171 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
172};
173use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
174
175use crate::hover_links::{find_url, find_url_from_range};
176use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
177
178pub const FILE_HEADER_HEIGHT: u32 = 2;
179pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
180pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
181pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
182const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
183const MAX_LINE_LEN: usize = 1024;
184const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
185const MAX_SELECTION_HISTORY_LEN: usize = 1024;
186pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
187#[doc(hidden)]
188pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
189
190pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
191pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
192
193pub fn render_parsed_markdown(
194 element_id: impl Into<ElementId>,
195 parsed: &language::ParsedMarkdown,
196 editor_style: &EditorStyle,
197 workspace: Option<WeakEntity<Workspace>>,
198 cx: &mut App,
199) -> InteractiveText {
200 let code_span_background_color = cx
201 .theme()
202 .colors()
203 .editor_document_highlight_read_background;
204
205 let highlights = gpui::combine_highlights(
206 parsed.highlights.iter().filter_map(|(range, highlight)| {
207 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
208 Some((range.clone(), highlight))
209 }),
210 parsed
211 .regions
212 .iter()
213 .zip(&parsed.region_ranges)
214 .filter_map(|(region, range)| {
215 if region.code {
216 Some((
217 range.clone(),
218 HighlightStyle {
219 background_color: Some(code_span_background_color),
220 ..Default::default()
221 },
222 ))
223 } else {
224 None
225 }
226 }),
227 );
228
229 let mut links = Vec::new();
230 let mut link_ranges = Vec::new();
231 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
232 if let Some(link) = region.link.clone() {
233 links.push(link);
234 link_ranges.push(range.clone());
235 }
236 }
237
238 InteractiveText::new(
239 element_id,
240 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
241 )
242 .on_click(
243 link_ranges,
244 move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
245 markdown::Link::Web { url } => cx.open_url(url),
246 markdown::Link::Path { path } => {
247 if let Some(workspace) = &workspace {
248 _ = workspace.update(cx, |workspace, cx| {
249 workspace
250 .open_abs_path(path.clone(), false, window, cx)
251 .detach();
252 });
253 }
254 }
255 },
256 )
257}
258
259#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
260pub enum InlayId {
261 InlineCompletion(usize),
262 Hint(usize),
263}
264
265impl InlayId {
266 fn id(&self) -> usize {
267 match self {
268 Self::InlineCompletion(id) => *id,
269 Self::Hint(id) => *id,
270 }
271 }
272}
273
274enum DocumentHighlightRead {}
275enum DocumentHighlightWrite {}
276enum InputComposition {}
277
278#[derive(Debug, Copy, Clone, PartialEq, Eq)]
279pub enum Navigated {
280 Yes,
281 No,
282}
283
284impl Navigated {
285 pub fn from_bool(yes: bool) -> Navigated {
286 if yes {
287 Navigated::Yes
288 } else {
289 Navigated::No
290 }
291 }
292}
293
294pub fn init_settings(cx: &mut App) {
295 EditorSettings::register(cx);
296}
297
298pub fn init(cx: &mut App) {
299 init_settings(cx);
300
301 workspace::register_project_item::<Editor>(cx);
302 workspace::FollowableViewRegistry::register::<Editor>(cx);
303 workspace::register_serializable_item::<Editor>(cx);
304
305 cx.observe_new(
306 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
307 workspace.register_action(Editor::new_file);
308 workspace.register_action(Editor::new_file_vertical);
309 workspace.register_action(Editor::new_file_horizontal);
310 workspace.register_action(Editor::cancel_language_server_work);
311 },
312 )
313 .detach();
314
315 cx.on_action(move |_: &workspace::NewFile, cx| {
316 let app_state = workspace::AppState::global(cx);
317 if let Some(app_state) = app_state.upgrade() {
318 workspace::open_new(
319 Default::default(),
320 app_state,
321 cx,
322 |workspace, window, cx| {
323 Editor::new_file(workspace, &Default::default(), window, cx)
324 },
325 )
326 .detach();
327 }
328 });
329 cx.on_action(move |_: &workspace::NewWindow, cx| {
330 let app_state = workspace::AppState::global(cx);
331 if let Some(app_state) = app_state.upgrade() {
332 workspace::open_new(
333 Default::default(),
334 app_state,
335 cx,
336 |workspace, window, cx| {
337 cx.activate(true);
338 Editor::new_file(workspace, &Default::default(), window, cx)
339 },
340 )
341 .detach();
342 }
343 });
344}
345
346pub struct SearchWithinRange;
347
348trait InvalidationRegion {
349 fn ranges(&self) -> &[Range<Anchor>];
350}
351
352#[derive(Clone, Debug, PartialEq)]
353pub enum SelectPhase {
354 Begin {
355 position: DisplayPoint,
356 add: bool,
357 click_count: usize,
358 },
359 BeginColumnar {
360 position: DisplayPoint,
361 reset: bool,
362 goal_column: u32,
363 },
364 Extend {
365 position: DisplayPoint,
366 click_count: usize,
367 },
368 Update {
369 position: DisplayPoint,
370 goal_column: u32,
371 scroll_delta: gpui::Point<f32>,
372 },
373 End,
374}
375
376#[derive(Clone, Debug)]
377pub enum SelectMode {
378 Character,
379 Word(Range<Anchor>),
380 Line(Range<Anchor>),
381 All,
382}
383
384#[derive(Copy, Clone, PartialEq, Eq, Debug)]
385pub enum EditorMode {
386 SingleLine { auto_width: bool },
387 AutoHeight { max_lines: usize },
388 Full,
389}
390
391#[derive(Copy, Clone, Debug)]
392pub enum SoftWrap {
393 /// Prefer not to wrap at all.
394 ///
395 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
396 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
397 GitDiff,
398 /// Prefer a single line generally, unless an overly long line is encountered.
399 None,
400 /// Soft wrap lines that exceed the editor width.
401 EditorWidth,
402 /// Soft wrap lines at the preferred line length.
403 Column(u32),
404 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
405 Bounded(u32),
406}
407
408#[derive(Clone)]
409pub struct EditorStyle {
410 pub background: Hsla,
411 pub local_player: PlayerColor,
412 pub text: TextStyle,
413 pub scrollbar_width: Pixels,
414 pub syntax: Arc<SyntaxTheme>,
415 pub status: StatusColors,
416 pub inlay_hints_style: HighlightStyle,
417 pub inline_completion_styles: InlineCompletionStyles,
418 pub unnecessary_code_fade: f32,
419}
420
421impl Default for EditorStyle {
422 fn default() -> Self {
423 Self {
424 background: Hsla::default(),
425 local_player: PlayerColor::default(),
426 text: TextStyle::default(),
427 scrollbar_width: Pixels::default(),
428 syntax: Default::default(),
429 // HACK: Status colors don't have a real default.
430 // We should look into removing the status colors from the editor
431 // style and retrieve them directly from the theme.
432 status: StatusColors::dark(),
433 inlay_hints_style: HighlightStyle::default(),
434 inline_completion_styles: InlineCompletionStyles {
435 insertion: HighlightStyle::default(),
436 whitespace: HighlightStyle::default(),
437 },
438 unnecessary_code_fade: Default::default(),
439 }
440 }
441}
442
443pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
444 let show_background = language_settings::language_settings(None, None, cx)
445 .inlay_hints
446 .show_background;
447
448 HighlightStyle {
449 color: Some(cx.theme().status().hint),
450 background_color: show_background.then(|| cx.theme().status().hint_background),
451 ..HighlightStyle::default()
452 }
453}
454
455pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
456 InlineCompletionStyles {
457 insertion: HighlightStyle {
458 color: Some(cx.theme().status().predictive),
459 ..HighlightStyle::default()
460 },
461 whitespace: HighlightStyle {
462 background_color: Some(cx.theme().status().created_background),
463 ..HighlightStyle::default()
464 },
465 }
466}
467
468type CompletionId = usize;
469
470pub(crate) enum EditDisplayMode {
471 TabAccept,
472 DiffPopover,
473 Inline,
474}
475
476enum InlineCompletion {
477 Edit {
478 edits: Vec<(Range<Anchor>, String)>,
479 edit_preview: Option<EditPreview>,
480 display_mode: EditDisplayMode,
481 snapshot: BufferSnapshot,
482 },
483 Move {
484 target: Anchor,
485 range_around_target: Range<text::Anchor>,
486 snapshot: BufferSnapshot,
487 },
488}
489
490struct InlineCompletionState {
491 inlay_ids: Vec<InlayId>,
492 completion: InlineCompletion,
493 completion_id: Option<SharedString>,
494 invalidation_range: Range<Anchor>,
495}
496
497enum InlineCompletionHighlight {}
498
499pub enum MenuInlineCompletionsPolicy {
500 Never,
501 ByProvider,
502}
503
504#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
505struct EditorActionId(usize);
506
507impl EditorActionId {
508 pub fn post_inc(&mut self) -> Self {
509 let answer = self.0;
510
511 *self = Self(answer + 1);
512
513 Self(answer)
514 }
515}
516
517// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
518// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
519
520type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
521type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
522
523#[derive(Default)]
524struct ScrollbarMarkerState {
525 scrollbar_size: Size<Pixels>,
526 dirty: bool,
527 markers: Arc<[PaintQuad]>,
528 pending_refresh: Option<Task<Result<()>>>,
529}
530
531impl ScrollbarMarkerState {
532 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
533 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
534 }
535}
536
537#[derive(Clone, Debug)]
538struct RunnableTasks {
539 templates: Vec<(TaskSourceKind, TaskTemplate)>,
540 offset: MultiBufferOffset,
541 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
542 column: u32,
543 // Values of all named captures, including those starting with '_'
544 extra_variables: HashMap<String, String>,
545 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
546 context_range: Range<BufferOffset>,
547}
548
549impl RunnableTasks {
550 fn resolve<'a>(
551 &'a self,
552 cx: &'a task::TaskContext,
553 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
554 self.templates.iter().filter_map(|(kind, template)| {
555 template
556 .resolve_task(&kind.to_id_base(), cx)
557 .map(|task| (kind.clone(), task))
558 })
559 }
560}
561
562#[derive(Clone)]
563struct ResolvedTasks {
564 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
565 position: Anchor,
566}
567#[derive(Copy, Clone, Debug)]
568struct MultiBufferOffset(usize);
569#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
570struct BufferOffset(usize);
571
572// Addons allow storing per-editor state in other crates (e.g. Vim)
573pub trait Addon: 'static {
574 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
575
576 fn render_buffer_header_controls(
577 &self,
578 _: &ExcerptInfo,
579 _: &Window,
580 _: &App,
581 ) -> Option<AnyElement> {
582 None
583 }
584
585 fn to_any(&self) -> &dyn std::any::Any;
586}
587
588#[derive(Debug, Copy, Clone, PartialEq, Eq)]
589pub enum IsVimMode {
590 Yes,
591 No,
592}
593
594/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
595///
596/// See the [module level documentation](self) for more information.
597pub struct Editor {
598 focus_handle: FocusHandle,
599 last_focused_descendant: Option<WeakFocusHandle>,
600 /// The text buffer being edited
601 buffer: Entity<MultiBuffer>,
602 /// Map of how text in the buffer should be displayed.
603 /// Handles soft wraps, folds, fake inlay text insertions, etc.
604 pub display_map: Entity<DisplayMap>,
605 pub selections: SelectionsCollection,
606 pub scroll_manager: ScrollManager,
607 /// When inline assist editors are linked, they all render cursors because
608 /// typing enters text into each of them, even the ones that aren't focused.
609 pub(crate) show_cursor_when_unfocused: bool,
610 columnar_selection_tail: Option<Anchor>,
611 add_selections_state: Option<AddSelectionsState>,
612 select_next_state: Option<SelectNextState>,
613 select_prev_state: Option<SelectNextState>,
614 selection_history: SelectionHistory,
615 autoclose_regions: Vec<AutocloseRegion>,
616 snippet_stack: InvalidationStack<SnippetState>,
617 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
618 ime_transaction: Option<TransactionId>,
619 active_diagnostics: Option<ActiveDiagnosticGroup>,
620 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
621
622 // TODO: make this a access method
623 pub project: Option<Entity<Project>>,
624 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
625 completion_provider: Option<Box<dyn CompletionProvider>>,
626 collaboration_hub: Option<Box<dyn CollaborationHub>>,
627 blink_manager: Entity<BlinkManager>,
628 show_cursor_names: bool,
629 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
630 pub show_local_selections: bool,
631 mode: EditorMode,
632 show_breadcrumbs: bool,
633 show_gutter: bool,
634 show_scrollbars: bool,
635 show_line_numbers: Option<bool>,
636 use_relative_line_numbers: Option<bool>,
637 show_git_diff_gutter: Option<bool>,
638 show_code_actions: Option<bool>,
639 show_runnables: Option<bool>,
640 show_wrap_guides: Option<bool>,
641 show_indent_guides: Option<bool>,
642 placeholder_text: Option<Arc<str>>,
643 highlight_order: usize,
644 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
645 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
646 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
647 scrollbar_marker_state: ScrollbarMarkerState,
648 active_indent_guides_state: ActiveIndentGuidesState,
649 nav_history: Option<ItemNavHistory>,
650 context_menu: RefCell<Option<CodeContextMenu>>,
651 mouse_context_menu: Option<MouseContextMenu>,
652 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
653 signature_help_state: SignatureHelpState,
654 auto_signature_help: Option<bool>,
655 find_all_references_task_sources: Vec<Anchor>,
656 next_completion_id: CompletionId,
657 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
658 code_actions_task: Option<Task<Result<()>>>,
659 document_highlights_task: Option<Task<()>>,
660 linked_editing_range_task: Option<Task<Option<()>>>,
661 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
662 pending_rename: Option<RenameState>,
663 searchable: bool,
664 cursor_shape: CursorShape,
665 current_line_highlight: Option<CurrentLineHighlight>,
666 collapse_matches: bool,
667 autoindent_mode: Option<AutoindentMode>,
668 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
669 input_enabled: bool,
670 use_modal_editing: bool,
671 read_only: bool,
672 leader_peer_id: Option<PeerId>,
673 remote_id: Option<ViewId>,
674 hover_state: HoverState,
675 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
676 gutter_hovered: bool,
677 hovered_link_state: Option<HoveredLinkState>,
678 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
679 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
680 active_inline_completion: Option<InlineCompletionState>,
681 /// Used to prevent flickering as the user types while the menu is open
682 stale_inline_completion_in_menu: Option<InlineCompletionState>,
683 inline_completions_hidden_for_vim_mode: bool,
684 show_inline_completions_override: Option<bool>,
685 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
686 previewing_inline_completion: bool,
687 inlay_hint_cache: InlayHintCache,
688 next_inlay_id: usize,
689 _subscriptions: Vec<Subscription>,
690 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
691 gutter_dimensions: GutterDimensions,
692 style: Option<EditorStyle>,
693 text_style_refinement: Option<TextStyleRefinement>,
694 next_editor_action_id: EditorActionId,
695 editor_actions:
696 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
697 use_autoclose: bool,
698 use_auto_surround: bool,
699 auto_replace_emoji_shortcode: bool,
700 show_git_blame_gutter: bool,
701 show_git_blame_inline: bool,
702 show_git_blame_inline_delay_task: Option<Task<()>>,
703 git_blame_inline_enabled: bool,
704 serialize_dirty_buffers: bool,
705 show_selection_menu: Option<bool>,
706 blame: Option<Entity<GitBlame>>,
707 blame_subscription: Option<Subscription>,
708 custom_context_menu: Option<
709 Box<
710 dyn 'static
711 + Fn(
712 &mut Self,
713 DisplayPoint,
714 &mut Window,
715 &mut Context<Self>,
716 ) -> Option<Entity<ui::ContextMenu>>,
717 >,
718 >,
719 last_bounds: Option<Bounds<Pixels>>,
720 last_position_map: Option<Rc<PositionMap>>,
721 expect_bounds_change: Option<Bounds<Pixels>>,
722 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
723 tasks_update_task: Option<Task<()>>,
724 in_project_search: bool,
725 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
726 breadcrumb_header: Option<String>,
727 focused_block: Option<FocusedBlock>,
728 next_scroll_position: NextScrollCursorCenterTopBottom,
729 addons: HashMap<TypeId, Box<dyn Addon>>,
730 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
731 selection_mark_mode: bool,
732 toggle_fold_multiple_buffers: Task<()>,
733 _scroll_cursor_center_top_bottom_task: Task<()>,
734}
735
736#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
737enum NextScrollCursorCenterTopBottom {
738 #[default]
739 Center,
740 Top,
741 Bottom,
742}
743
744impl NextScrollCursorCenterTopBottom {
745 fn next(&self) -> Self {
746 match self {
747 Self::Center => Self::Top,
748 Self::Top => Self::Bottom,
749 Self::Bottom => Self::Center,
750 }
751 }
752}
753
754#[derive(Clone)]
755pub struct EditorSnapshot {
756 pub mode: EditorMode,
757 show_gutter: bool,
758 show_line_numbers: Option<bool>,
759 show_git_diff_gutter: Option<bool>,
760 show_code_actions: Option<bool>,
761 show_runnables: Option<bool>,
762 git_blame_gutter_max_author_length: Option<usize>,
763 pub display_snapshot: DisplaySnapshot,
764 pub placeholder_text: Option<Arc<str>>,
765 is_focused: bool,
766 scroll_anchor: ScrollAnchor,
767 ongoing_scroll: OngoingScroll,
768 current_line_highlight: CurrentLineHighlight,
769 gutter_hovered: bool,
770}
771
772const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
773
774#[derive(Default, Debug, Clone, Copy)]
775pub struct GutterDimensions {
776 pub left_padding: Pixels,
777 pub right_padding: Pixels,
778 pub width: Pixels,
779 pub margin: Pixels,
780 pub git_blame_entries_width: Option<Pixels>,
781}
782
783impl GutterDimensions {
784 /// The full width of the space taken up by the gutter.
785 pub fn full_width(&self) -> Pixels {
786 self.margin + self.width
787 }
788
789 /// The width of the space reserved for the fold indicators,
790 /// use alongside 'justify_end' and `gutter_width` to
791 /// right align content with the line numbers
792 pub fn fold_area_width(&self) -> Pixels {
793 self.margin + self.right_padding
794 }
795}
796
797#[derive(Debug)]
798pub struct RemoteSelection {
799 pub replica_id: ReplicaId,
800 pub selection: Selection<Anchor>,
801 pub cursor_shape: CursorShape,
802 pub peer_id: PeerId,
803 pub line_mode: bool,
804 pub participant_index: Option<ParticipantIndex>,
805 pub user_name: Option<SharedString>,
806}
807
808#[derive(Clone, Debug)]
809struct SelectionHistoryEntry {
810 selections: Arc<[Selection<Anchor>]>,
811 select_next_state: Option<SelectNextState>,
812 select_prev_state: Option<SelectNextState>,
813 add_selections_state: Option<AddSelectionsState>,
814}
815
816enum SelectionHistoryMode {
817 Normal,
818 Undoing,
819 Redoing,
820}
821
822#[derive(Clone, PartialEq, Eq, Hash)]
823struct HoveredCursor {
824 replica_id: u16,
825 selection_id: usize,
826}
827
828impl Default for SelectionHistoryMode {
829 fn default() -> Self {
830 Self::Normal
831 }
832}
833
834#[derive(Default)]
835struct SelectionHistory {
836 #[allow(clippy::type_complexity)]
837 selections_by_transaction:
838 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
839 mode: SelectionHistoryMode,
840 undo_stack: VecDeque<SelectionHistoryEntry>,
841 redo_stack: VecDeque<SelectionHistoryEntry>,
842}
843
844impl SelectionHistory {
845 fn insert_transaction(
846 &mut self,
847 transaction_id: TransactionId,
848 selections: Arc<[Selection<Anchor>]>,
849 ) {
850 self.selections_by_transaction
851 .insert(transaction_id, (selections, None));
852 }
853
854 #[allow(clippy::type_complexity)]
855 fn transaction(
856 &self,
857 transaction_id: TransactionId,
858 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
859 self.selections_by_transaction.get(&transaction_id)
860 }
861
862 #[allow(clippy::type_complexity)]
863 fn transaction_mut(
864 &mut self,
865 transaction_id: TransactionId,
866 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
867 self.selections_by_transaction.get_mut(&transaction_id)
868 }
869
870 fn push(&mut self, entry: SelectionHistoryEntry) {
871 if !entry.selections.is_empty() {
872 match self.mode {
873 SelectionHistoryMode::Normal => {
874 self.push_undo(entry);
875 self.redo_stack.clear();
876 }
877 SelectionHistoryMode::Undoing => self.push_redo(entry),
878 SelectionHistoryMode::Redoing => self.push_undo(entry),
879 }
880 }
881 }
882
883 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
884 if self
885 .undo_stack
886 .back()
887 .map_or(true, |e| e.selections != entry.selections)
888 {
889 self.undo_stack.push_back(entry);
890 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
891 self.undo_stack.pop_front();
892 }
893 }
894 }
895
896 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
897 if self
898 .redo_stack
899 .back()
900 .map_or(true, |e| e.selections != entry.selections)
901 {
902 self.redo_stack.push_back(entry);
903 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
904 self.redo_stack.pop_front();
905 }
906 }
907 }
908}
909
910struct RowHighlight {
911 index: usize,
912 range: Range<Anchor>,
913 color: Hsla,
914 should_autoscroll: bool,
915}
916
917#[derive(Clone, Debug)]
918struct AddSelectionsState {
919 above: bool,
920 stack: Vec<usize>,
921}
922
923#[derive(Clone)]
924struct SelectNextState {
925 query: AhoCorasick,
926 wordwise: bool,
927 done: bool,
928}
929
930impl std::fmt::Debug for SelectNextState {
931 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
932 f.debug_struct(std::any::type_name::<Self>())
933 .field("wordwise", &self.wordwise)
934 .field("done", &self.done)
935 .finish()
936 }
937}
938
939#[derive(Debug)]
940struct AutocloseRegion {
941 selection_id: usize,
942 range: Range<Anchor>,
943 pair: BracketPair,
944}
945
946#[derive(Debug)]
947struct SnippetState {
948 ranges: Vec<Vec<Range<Anchor>>>,
949 active_index: usize,
950 choices: Vec<Option<Vec<String>>>,
951}
952
953#[doc(hidden)]
954pub struct RenameState {
955 pub range: Range<Anchor>,
956 pub old_name: Arc<str>,
957 pub editor: Entity<Editor>,
958 block_id: CustomBlockId,
959}
960
961struct InvalidationStack<T>(Vec<T>);
962
963struct RegisteredInlineCompletionProvider {
964 provider: Arc<dyn InlineCompletionProviderHandle>,
965 _subscription: Subscription,
966}
967
968#[derive(Debug)]
969struct ActiveDiagnosticGroup {
970 primary_range: Range<Anchor>,
971 primary_message: String,
972 group_id: usize,
973 blocks: HashMap<CustomBlockId, Diagnostic>,
974 is_valid: bool,
975}
976
977#[derive(Serialize, Deserialize, Clone, Debug)]
978pub struct ClipboardSelection {
979 pub len: usize,
980 pub is_entire_line: bool,
981 pub first_line_indent: u32,
982}
983
984#[derive(Debug)]
985pub(crate) struct NavigationData {
986 cursor_anchor: Anchor,
987 cursor_position: Point,
988 scroll_anchor: ScrollAnchor,
989 scroll_top_row: u32,
990}
991
992#[derive(Debug, Clone, Copy, PartialEq, Eq)]
993pub enum GotoDefinitionKind {
994 Symbol,
995 Declaration,
996 Type,
997 Implementation,
998}
999
1000#[derive(Debug, Clone)]
1001enum InlayHintRefreshReason {
1002 Toggle(bool),
1003 SettingsChange(InlayHintSettings),
1004 NewLinesShown,
1005 BufferEdited(HashSet<Arc<Language>>),
1006 RefreshRequested,
1007 ExcerptsRemoved(Vec<ExcerptId>),
1008}
1009
1010impl InlayHintRefreshReason {
1011 fn description(&self) -> &'static str {
1012 match self {
1013 Self::Toggle(_) => "toggle",
1014 Self::SettingsChange(_) => "settings change",
1015 Self::NewLinesShown => "new lines shown",
1016 Self::BufferEdited(_) => "buffer edited",
1017 Self::RefreshRequested => "refresh requested",
1018 Self::ExcerptsRemoved(_) => "excerpts removed",
1019 }
1020 }
1021}
1022
1023pub enum FormatTarget {
1024 Buffers,
1025 Ranges(Vec<Range<MultiBufferPoint>>),
1026}
1027
1028pub(crate) struct FocusedBlock {
1029 id: BlockId,
1030 focus_handle: WeakFocusHandle,
1031}
1032
1033#[derive(Clone)]
1034enum JumpData {
1035 MultiBufferRow {
1036 row: MultiBufferRow,
1037 line_offset_from_top: u32,
1038 },
1039 MultiBufferPoint {
1040 excerpt_id: ExcerptId,
1041 position: Point,
1042 anchor: text::Anchor,
1043 line_offset_from_top: u32,
1044 },
1045}
1046
1047pub enum MultibufferSelectionMode {
1048 First,
1049 All,
1050}
1051
1052impl Editor {
1053 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1054 let buffer = cx.new(|cx| Buffer::local("", cx));
1055 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1056 Self::new(
1057 EditorMode::SingleLine { auto_width: false },
1058 buffer,
1059 None,
1060 false,
1061 window,
1062 cx,
1063 )
1064 }
1065
1066 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1067 let buffer = cx.new(|cx| Buffer::local("", cx));
1068 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1069 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1070 }
1071
1072 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1073 let buffer = cx.new(|cx| Buffer::local("", cx));
1074 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1075 Self::new(
1076 EditorMode::SingleLine { auto_width: true },
1077 buffer,
1078 None,
1079 false,
1080 window,
1081 cx,
1082 )
1083 }
1084
1085 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1086 let buffer = cx.new(|cx| Buffer::local("", cx));
1087 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1088 Self::new(
1089 EditorMode::AutoHeight { max_lines },
1090 buffer,
1091 None,
1092 false,
1093 window,
1094 cx,
1095 )
1096 }
1097
1098 pub fn for_buffer(
1099 buffer: Entity<Buffer>,
1100 project: Option<Entity<Project>>,
1101 window: &mut Window,
1102 cx: &mut Context<Self>,
1103 ) -> Self {
1104 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1105 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1106 }
1107
1108 pub fn for_multibuffer(
1109 buffer: Entity<MultiBuffer>,
1110 project: Option<Entity<Project>>,
1111 show_excerpt_controls: bool,
1112 window: &mut Window,
1113 cx: &mut Context<Self>,
1114 ) -> Self {
1115 Self::new(
1116 EditorMode::Full,
1117 buffer,
1118 project,
1119 show_excerpt_controls,
1120 window,
1121 cx,
1122 )
1123 }
1124
1125 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1126 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1127 let mut clone = Self::new(
1128 self.mode,
1129 self.buffer.clone(),
1130 self.project.clone(),
1131 show_excerpt_controls,
1132 window,
1133 cx,
1134 );
1135 self.display_map.update(cx, |display_map, cx| {
1136 let snapshot = display_map.snapshot(cx);
1137 clone.display_map.update(cx, |display_map, cx| {
1138 display_map.set_state(&snapshot, cx);
1139 });
1140 });
1141 clone.selections.clone_state(&self.selections);
1142 clone.scroll_manager.clone_state(&self.scroll_manager);
1143 clone.searchable = self.searchable;
1144 clone
1145 }
1146
1147 pub fn new(
1148 mode: EditorMode,
1149 buffer: Entity<MultiBuffer>,
1150 project: Option<Entity<Project>>,
1151 show_excerpt_controls: bool,
1152 window: &mut Window,
1153 cx: &mut Context<Self>,
1154 ) -> Self {
1155 let style = window.text_style();
1156 let font_size = style.font_size.to_pixels(window.rem_size());
1157 let editor = cx.entity().downgrade();
1158 let fold_placeholder = FoldPlaceholder {
1159 constrain_width: true,
1160 render: Arc::new(move |fold_id, fold_range, _, cx| {
1161 let editor = editor.clone();
1162 div()
1163 .id(fold_id)
1164 .bg(cx.theme().colors().ghost_element_background)
1165 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1166 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1167 .rounded_sm()
1168 .size_full()
1169 .cursor_pointer()
1170 .child("⋯")
1171 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1172 .on_click(move |_, _window, cx| {
1173 editor
1174 .update(cx, |editor, cx| {
1175 editor.unfold_ranges(
1176 &[fold_range.start..fold_range.end],
1177 true,
1178 false,
1179 cx,
1180 );
1181 cx.stop_propagation();
1182 })
1183 .ok();
1184 })
1185 .into_any()
1186 }),
1187 merge_adjacent: true,
1188 ..Default::default()
1189 };
1190 let display_map = cx.new(|cx| {
1191 DisplayMap::new(
1192 buffer.clone(),
1193 style.font(),
1194 font_size,
1195 None,
1196 show_excerpt_controls,
1197 FILE_HEADER_HEIGHT,
1198 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1199 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1200 fold_placeholder,
1201 cx,
1202 )
1203 });
1204
1205 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1206
1207 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1208
1209 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1210 .then(|| language_settings::SoftWrap::None);
1211
1212 let mut project_subscriptions = Vec::new();
1213 if mode == EditorMode::Full {
1214 if let Some(project) = project.as_ref() {
1215 if buffer.read(cx).is_singleton() {
1216 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1217 cx.emit(EditorEvent::TitleChanged);
1218 }));
1219 }
1220 project_subscriptions.push(cx.subscribe_in(
1221 project,
1222 window,
1223 |editor, _, event, window, cx| {
1224 if let project::Event::RefreshInlayHints = event {
1225 editor
1226 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1227 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1228 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1229 let focus_handle = editor.focus_handle(cx);
1230 if focus_handle.is_focused(window) {
1231 let snapshot = buffer.read(cx).snapshot();
1232 for (range, snippet) in snippet_edits {
1233 let editor_range =
1234 language::range_from_lsp(*range).to_offset(&snapshot);
1235 editor
1236 .insert_snippet(
1237 &[editor_range],
1238 snippet.clone(),
1239 window,
1240 cx,
1241 )
1242 .ok();
1243 }
1244 }
1245 }
1246 }
1247 },
1248 ));
1249 if let Some(task_inventory) = project
1250 .read(cx)
1251 .task_store()
1252 .read(cx)
1253 .task_inventory()
1254 .cloned()
1255 {
1256 project_subscriptions.push(cx.observe_in(
1257 &task_inventory,
1258 window,
1259 |editor, _, window, cx| {
1260 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1261 },
1262 ));
1263 }
1264 }
1265 }
1266
1267 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1268
1269 let inlay_hint_settings =
1270 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1271 let focus_handle = cx.focus_handle();
1272 cx.on_focus(&focus_handle, window, Self::handle_focus)
1273 .detach();
1274 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1275 .detach();
1276 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1277 .detach();
1278 cx.on_blur(&focus_handle, window, Self::handle_blur)
1279 .detach();
1280
1281 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1282 Some(false)
1283 } else {
1284 None
1285 };
1286
1287 let mut code_action_providers = Vec::new();
1288 if let Some(project) = project.clone() {
1289 get_uncommitted_diff_for_buffer(
1290 &project,
1291 buffer.read(cx).all_buffers(),
1292 buffer.clone(),
1293 cx,
1294 );
1295 code_action_providers.push(Rc::new(project) as Rc<_>);
1296 }
1297
1298 let mut this = Self {
1299 focus_handle,
1300 show_cursor_when_unfocused: false,
1301 last_focused_descendant: None,
1302 buffer: buffer.clone(),
1303 display_map: display_map.clone(),
1304 selections,
1305 scroll_manager: ScrollManager::new(cx),
1306 columnar_selection_tail: None,
1307 add_selections_state: None,
1308 select_next_state: None,
1309 select_prev_state: None,
1310 selection_history: Default::default(),
1311 autoclose_regions: Default::default(),
1312 snippet_stack: Default::default(),
1313 select_larger_syntax_node_stack: Vec::new(),
1314 ime_transaction: Default::default(),
1315 active_diagnostics: None,
1316 soft_wrap_mode_override,
1317 completion_provider: project.clone().map(|project| Box::new(project) as _),
1318 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1319 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1320 project,
1321 blink_manager: blink_manager.clone(),
1322 show_local_selections: true,
1323 show_scrollbars: true,
1324 mode,
1325 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1326 show_gutter: mode == EditorMode::Full,
1327 show_line_numbers: None,
1328 use_relative_line_numbers: None,
1329 show_git_diff_gutter: None,
1330 show_code_actions: None,
1331 show_runnables: None,
1332 show_wrap_guides: None,
1333 show_indent_guides,
1334 placeholder_text: None,
1335 highlight_order: 0,
1336 highlighted_rows: HashMap::default(),
1337 background_highlights: Default::default(),
1338 gutter_highlights: TreeMap::default(),
1339 scrollbar_marker_state: ScrollbarMarkerState::default(),
1340 active_indent_guides_state: ActiveIndentGuidesState::default(),
1341 nav_history: None,
1342 context_menu: RefCell::new(None),
1343 mouse_context_menu: None,
1344 completion_tasks: Default::default(),
1345 signature_help_state: SignatureHelpState::default(),
1346 auto_signature_help: None,
1347 find_all_references_task_sources: Vec::new(),
1348 next_completion_id: 0,
1349 next_inlay_id: 0,
1350 code_action_providers,
1351 available_code_actions: Default::default(),
1352 code_actions_task: Default::default(),
1353 document_highlights_task: Default::default(),
1354 linked_editing_range_task: Default::default(),
1355 pending_rename: Default::default(),
1356 searchable: true,
1357 cursor_shape: EditorSettings::get_global(cx)
1358 .cursor_shape
1359 .unwrap_or_default(),
1360 current_line_highlight: None,
1361 autoindent_mode: Some(AutoindentMode::EachLine),
1362 collapse_matches: false,
1363 workspace: None,
1364 input_enabled: true,
1365 use_modal_editing: mode == EditorMode::Full,
1366 read_only: false,
1367 use_autoclose: true,
1368 use_auto_surround: true,
1369 auto_replace_emoji_shortcode: false,
1370 leader_peer_id: None,
1371 remote_id: None,
1372 hover_state: Default::default(),
1373 pending_mouse_down: None,
1374 hovered_link_state: Default::default(),
1375 edit_prediction_provider: None,
1376 active_inline_completion: None,
1377 stale_inline_completion_in_menu: None,
1378 previewing_inline_completion: false,
1379 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1380
1381 gutter_hovered: false,
1382 pixel_position_of_newest_cursor: None,
1383 last_bounds: None,
1384 last_position_map: None,
1385 expect_bounds_change: None,
1386 gutter_dimensions: GutterDimensions::default(),
1387 style: None,
1388 show_cursor_names: false,
1389 hovered_cursors: Default::default(),
1390 next_editor_action_id: EditorActionId::default(),
1391 editor_actions: Rc::default(),
1392 inline_completions_hidden_for_vim_mode: false,
1393 show_inline_completions_override: None,
1394 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1395 custom_context_menu: None,
1396 show_git_blame_gutter: false,
1397 show_git_blame_inline: false,
1398 show_selection_menu: None,
1399 show_git_blame_inline_delay_task: None,
1400 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1401 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1402 .session
1403 .restore_unsaved_buffers,
1404 blame: None,
1405 blame_subscription: None,
1406 tasks: Default::default(),
1407 _subscriptions: vec![
1408 cx.observe(&buffer, Self::on_buffer_changed),
1409 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1410 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1411 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1412 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1413 cx.observe_window_activation(window, |editor, window, cx| {
1414 let active = window.is_window_active();
1415 editor.blink_manager.update(cx, |blink_manager, cx| {
1416 if active {
1417 blink_manager.enable(cx);
1418 } else {
1419 blink_manager.disable(cx);
1420 }
1421 });
1422 }),
1423 ],
1424 tasks_update_task: None,
1425 linked_edit_ranges: Default::default(),
1426 in_project_search: false,
1427 previous_search_ranges: None,
1428 breadcrumb_header: None,
1429 focused_block: None,
1430 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1431 addons: HashMap::default(),
1432 registered_buffers: HashMap::default(),
1433 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1434 selection_mark_mode: false,
1435 toggle_fold_multiple_buffers: Task::ready(()),
1436 text_style_refinement: None,
1437 };
1438 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1439 this._subscriptions.extend(project_subscriptions);
1440
1441 this.end_selection(window, cx);
1442 this.scroll_manager.show_scrollbar(window, cx);
1443
1444 if mode == EditorMode::Full {
1445 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1446 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1447
1448 if this.git_blame_inline_enabled {
1449 this.git_blame_inline_enabled = true;
1450 this.start_git_blame_inline(false, window, cx);
1451 }
1452
1453 if let Some(buffer) = buffer.read(cx).as_singleton() {
1454 if let Some(project) = this.project.as_ref() {
1455 let lsp_store = project.read(cx).lsp_store();
1456 let handle = lsp_store.update(cx, |lsp_store, cx| {
1457 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1458 });
1459 this.registered_buffers
1460 .insert(buffer.read(cx).remote_id(), handle);
1461 }
1462 }
1463 }
1464
1465 this.report_editor_event("Editor Opened", None, cx);
1466 this
1467 }
1468
1469 pub fn mouse_menu_is_focused(&self, window: &mut Window, cx: &mut App) -> bool {
1470 self.mouse_context_menu
1471 .as_ref()
1472 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1473 }
1474
1475 fn key_context(&self, window: &mut Window, cx: &mut Context<Self>) -> KeyContext {
1476 let mut key_context = KeyContext::new_with_defaults();
1477 key_context.add("Editor");
1478 let mode = match self.mode {
1479 EditorMode::SingleLine { .. } => "single_line",
1480 EditorMode::AutoHeight { .. } => "auto_height",
1481 EditorMode::Full => "full",
1482 };
1483
1484 if EditorSettings::jupyter_enabled(cx) {
1485 key_context.add("jupyter");
1486 }
1487
1488 key_context.set("mode", mode);
1489 if self.pending_rename.is_some() {
1490 key_context.add("renaming");
1491 }
1492
1493 let mut showing_completions = false;
1494
1495 match self.context_menu.borrow().as_ref() {
1496 Some(CodeContextMenu::Completions(_)) => {
1497 key_context.add("menu");
1498 key_context.add("showing_completions");
1499 showing_completions = true;
1500 }
1501 Some(CodeContextMenu::CodeActions(_)) => {
1502 key_context.add("menu");
1503 key_context.add("showing_code_actions")
1504 }
1505 None => {}
1506 }
1507
1508 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1509 if !self.focus_handle(cx).contains_focused(window, cx)
1510 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1511 {
1512 for addon in self.addons.values() {
1513 addon.extend_key_context(&mut key_context, cx)
1514 }
1515 }
1516
1517 if let Some(extension) = self
1518 .buffer
1519 .read(cx)
1520 .as_singleton()
1521 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1522 {
1523 key_context.set("extension", extension.to_string());
1524 }
1525
1526 if self.has_active_inline_completion() {
1527 key_context.add("copilot_suggestion");
1528 key_context.add("edit_prediction");
1529
1530 if showing_completions || self.edit_prediction_requires_modifier(cx) {
1531 key_context.add("edit_prediction_requires_modifier");
1532 }
1533 }
1534
1535 if self.selection_mark_mode {
1536 key_context.add("selection_mode");
1537 }
1538
1539 key_context
1540 }
1541
1542 pub fn new_file(
1543 workspace: &mut Workspace,
1544 _: &workspace::NewFile,
1545 window: &mut Window,
1546 cx: &mut Context<Workspace>,
1547 ) {
1548 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1549 "Failed to create buffer",
1550 window,
1551 cx,
1552 |e, _, _| match e.error_code() {
1553 ErrorCode::RemoteUpgradeRequired => Some(format!(
1554 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1555 e.error_tag("required").unwrap_or("the latest version")
1556 )),
1557 _ => None,
1558 },
1559 );
1560 }
1561
1562 pub fn new_in_workspace(
1563 workspace: &mut Workspace,
1564 window: &mut Window,
1565 cx: &mut Context<Workspace>,
1566 ) -> Task<Result<Entity<Editor>>> {
1567 let project = workspace.project().clone();
1568 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1569
1570 cx.spawn_in(window, |workspace, mut cx| async move {
1571 let buffer = create.await?;
1572 workspace.update_in(&mut cx, |workspace, window, cx| {
1573 let editor =
1574 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1575 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1576 editor
1577 })
1578 })
1579 }
1580
1581 fn new_file_vertical(
1582 workspace: &mut Workspace,
1583 _: &workspace::NewFileSplitVertical,
1584 window: &mut Window,
1585 cx: &mut Context<Workspace>,
1586 ) {
1587 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1588 }
1589
1590 fn new_file_horizontal(
1591 workspace: &mut Workspace,
1592 _: &workspace::NewFileSplitHorizontal,
1593 window: &mut Window,
1594 cx: &mut Context<Workspace>,
1595 ) {
1596 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1597 }
1598
1599 fn new_file_in_direction(
1600 workspace: &mut Workspace,
1601 direction: SplitDirection,
1602 window: &mut Window,
1603 cx: &mut Context<Workspace>,
1604 ) {
1605 let project = workspace.project().clone();
1606 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1607
1608 cx.spawn_in(window, |workspace, mut cx| async move {
1609 let buffer = create.await?;
1610 workspace.update_in(&mut cx, move |workspace, window, cx| {
1611 workspace.split_item(
1612 direction,
1613 Box::new(
1614 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1615 ),
1616 window,
1617 cx,
1618 )
1619 })?;
1620 anyhow::Ok(())
1621 })
1622 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1623 match e.error_code() {
1624 ErrorCode::RemoteUpgradeRequired => Some(format!(
1625 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1626 e.error_tag("required").unwrap_or("the latest version")
1627 )),
1628 _ => None,
1629 }
1630 });
1631 }
1632
1633 pub fn leader_peer_id(&self) -> Option<PeerId> {
1634 self.leader_peer_id
1635 }
1636
1637 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1638 &self.buffer
1639 }
1640
1641 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1642 self.workspace.as_ref()?.0.upgrade()
1643 }
1644
1645 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1646 self.buffer().read(cx).title(cx)
1647 }
1648
1649 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1650 let git_blame_gutter_max_author_length = self
1651 .render_git_blame_gutter(cx)
1652 .then(|| {
1653 if let Some(blame) = self.blame.as_ref() {
1654 let max_author_length =
1655 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1656 Some(max_author_length)
1657 } else {
1658 None
1659 }
1660 })
1661 .flatten();
1662
1663 EditorSnapshot {
1664 mode: self.mode,
1665 show_gutter: self.show_gutter,
1666 show_line_numbers: self.show_line_numbers,
1667 show_git_diff_gutter: self.show_git_diff_gutter,
1668 show_code_actions: self.show_code_actions,
1669 show_runnables: self.show_runnables,
1670 git_blame_gutter_max_author_length,
1671 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1672 scroll_anchor: self.scroll_manager.anchor(),
1673 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1674 placeholder_text: self.placeholder_text.clone(),
1675 is_focused: self.focus_handle.is_focused(window),
1676 current_line_highlight: self
1677 .current_line_highlight
1678 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1679 gutter_hovered: self.gutter_hovered,
1680 }
1681 }
1682
1683 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1684 self.buffer.read(cx).language_at(point, cx)
1685 }
1686
1687 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1688 self.buffer.read(cx).read(cx).file_at(point).cloned()
1689 }
1690
1691 pub fn active_excerpt(
1692 &self,
1693 cx: &App,
1694 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1695 self.buffer
1696 .read(cx)
1697 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1698 }
1699
1700 pub fn mode(&self) -> EditorMode {
1701 self.mode
1702 }
1703
1704 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1705 self.collaboration_hub.as_deref()
1706 }
1707
1708 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1709 self.collaboration_hub = Some(hub);
1710 }
1711
1712 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1713 self.in_project_search = in_project_search;
1714 }
1715
1716 pub fn set_custom_context_menu(
1717 &mut self,
1718 f: impl 'static
1719 + Fn(
1720 &mut Self,
1721 DisplayPoint,
1722 &mut Window,
1723 &mut Context<Self>,
1724 ) -> Option<Entity<ui::ContextMenu>>,
1725 ) {
1726 self.custom_context_menu = Some(Box::new(f))
1727 }
1728
1729 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1730 self.completion_provider = provider;
1731 }
1732
1733 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1734 self.semantics_provider.clone()
1735 }
1736
1737 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1738 self.semantics_provider = provider;
1739 }
1740
1741 pub fn set_edit_prediction_provider<T>(
1742 &mut self,
1743 provider: Option<Entity<T>>,
1744 window: &mut Window,
1745 cx: &mut Context<Self>,
1746 ) where
1747 T: EditPredictionProvider,
1748 {
1749 self.edit_prediction_provider =
1750 provider.map(|provider| RegisteredInlineCompletionProvider {
1751 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1752 if this.focus_handle.is_focused(window) {
1753 this.update_visible_inline_completion(window, cx);
1754 }
1755 }),
1756 provider: Arc::new(provider),
1757 });
1758 self.refresh_inline_completion(false, false, window, cx);
1759 }
1760
1761 pub fn placeholder_text(&self) -> Option<&str> {
1762 self.placeholder_text.as_deref()
1763 }
1764
1765 pub fn set_placeholder_text(
1766 &mut self,
1767 placeholder_text: impl Into<Arc<str>>,
1768 cx: &mut Context<Self>,
1769 ) {
1770 let placeholder_text = Some(placeholder_text.into());
1771 if self.placeholder_text != placeholder_text {
1772 self.placeholder_text = placeholder_text;
1773 cx.notify();
1774 }
1775 }
1776
1777 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1778 self.cursor_shape = cursor_shape;
1779
1780 // Disrupt blink for immediate user feedback that the cursor shape has changed
1781 self.blink_manager.update(cx, BlinkManager::show_cursor);
1782
1783 cx.notify();
1784 }
1785
1786 pub fn set_current_line_highlight(
1787 &mut self,
1788 current_line_highlight: Option<CurrentLineHighlight>,
1789 ) {
1790 self.current_line_highlight = current_line_highlight;
1791 }
1792
1793 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1794 self.collapse_matches = collapse_matches;
1795 }
1796
1797 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1798 let buffers = self.buffer.read(cx).all_buffers();
1799 let Some(lsp_store) = self.lsp_store(cx) else {
1800 return;
1801 };
1802 lsp_store.update(cx, |lsp_store, cx| {
1803 for buffer in buffers {
1804 self.registered_buffers
1805 .entry(buffer.read(cx).remote_id())
1806 .or_insert_with(|| {
1807 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1808 });
1809 }
1810 })
1811 }
1812
1813 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1814 if self.collapse_matches {
1815 return range.start..range.start;
1816 }
1817 range.clone()
1818 }
1819
1820 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1821 if self.display_map.read(cx).clip_at_line_ends != clip {
1822 self.display_map
1823 .update(cx, |map, _| map.clip_at_line_ends = clip);
1824 }
1825 }
1826
1827 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1828 self.input_enabled = input_enabled;
1829 }
1830
1831 pub fn set_inline_completions_hidden_for_vim_mode(
1832 &mut self,
1833 hidden: bool,
1834 window: &mut Window,
1835 cx: &mut Context<Self>,
1836 ) {
1837 if hidden != self.inline_completions_hidden_for_vim_mode {
1838 self.inline_completions_hidden_for_vim_mode = hidden;
1839 if hidden {
1840 self.update_visible_inline_completion(window, cx);
1841 } else {
1842 self.refresh_inline_completion(true, false, window, cx);
1843 }
1844 }
1845 }
1846
1847 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1848 self.menu_inline_completions_policy = value;
1849 }
1850
1851 pub fn set_autoindent(&mut self, autoindent: bool) {
1852 if autoindent {
1853 self.autoindent_mode = Some(AutoindentMode::EachLine);
1854 } else {
1855 self.autoindent_mode = None;
1856 }
1857 }
1858
1859 pub fn read_only(&self, cx: &App) -> bool {
1860 self.read_only || self.buffer.read(cx).read_only()
1861 }
1862
1863 pub fn set_read_only(&mut self, read_only: bool) {
1864 self.read_only = read_only;
1865 }
1866
1867 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1868 self.use_autoclose = autoclose;
1869 }
1870
1871 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1872 self.use_auto_surround = auto_surround;
1873 }
1874
1875 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1876 self.auto_replace_emoji_shortcode = auto_replace;
1877 }
1878
1879 pub fn toggle_inline_completions(
1880 &mut self,
1881 _: &ToggleEditPrediction,
1882 window: &mut Window,
1883 cx: &mut Context<Self>,
1884 ) {
1885 if self.show_inline_completions_override.is_some() {
1886 self.set_show_inline_completions(None, window, cx);
1887 } else {
1888 let cursor = self.selections.newest_anchor().head();
1889 if let Some((buffer, cursor_buffer_position)) =
1890 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1891 {
1892 let show_inline_completions = !self.should_show_inline_completions_in_buffer(
1893 &buffer,
1894 cursor_buffer_position,
1895 cx,
1896 );
1897 self.set_show_inline_completions(Some(show_inline_completions), window, cx);
1898 }
1899 }
1900 }
1901
1902 pub fn set_show_inline_completions(
1903 &mut self,
1904 show_edit_predictions: Option<bool>,
1905 window: &mut Window,
1906 cx: &mut Context<Self>,
1907 ) {
1908 self.show_inline_completions_override = show_edit_predictions;
1909 self.refresh_inline_completion(false, true, window, cx);
1910 }
1911
1912 pub fn inline_completion_start_anchor(&self) -> Option<Anchor> {
1913 let active_completion = self.active_inline_completion.as_ref()?;
1914 let result = match &active_completion.completion {
1915 InlineCompletion::Edit { edits, .. } => edits.first()?.0.start,
1916 InlineCompletion::Move { target, .. } => *target,
1917 };
1918 Some(result)
1919 }
1920
1921 fn inline_completions_disabled_in_scope(
1922 &self,
1923 buffer: &Entity<Buffer>,
1924 buffer_position: language::Anchor,
1925 cx: &App,
1926 ) -> bool {
1927 let snapshot = buffer.read(cx).snapshot();
1928 let settings = snapshot.settings_at(buffer_position, cx);
1929
1930 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1931 return false;
1932 };
1933
1934 scope.override_name().map_or(false, |scope_name| {
1935 settings
1936 .edit_predictions_disabled_in
1937 .iter()
1938 .any(|s| s == scope_name)
1939 })
1940 }
1941
1942 pub fn set_use_modal_editing(&mut self, to: bool) {
1943 self.use_modal_editing = to;
1944 }
1945
1946 pub fn use_modal_editing(&self) -> bool {
1947 self.use_modal_editing
1948 }
1949
1950 fn selections_did_change(
1951 &mut self,
1952 local: bool,
1953 old_cursor_position: &Anchor,
1954 show_completions: bool,
1955 window: &mut Window,
1956 cx: &mut Context<Self>,
1957 ) {
1958 window.invalidate_character_coordinates();
1959
1960 // Copy selections to primary selection buffer
1961 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1962 if local {
1963 let selections = self.selections.all::<usize>(cx);
1964 let buffer_handle = self.buffer.read(cx).read(cx);
1965
1966 let mut text = String::new();
1967 for (index, selection) in selections.iter().enumerate() {
1968 let text_for_selection = buffer_handle
1969 .text_for_range(selection.start..selection.end)
1970 .collect::<String>();
1971
1972 text.push_str(&text_for_selection);
1973 if index != selections.len() - 1 {
1974 text.push('\n');
1975 }
1976 }
1977
1978 if !text.is_empty() {
1979 cx.write_to_primary(ClipboardItem::new_string(text));
1980 }
1981 }
1982
1983 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
1984 self.buffer.update(cx, |buffer, cx| {
1985 buffer.set_active_selections(
1986 &self.selections.disjoint_anchors(),
1987 self.selections.line_mode,
1988 self.cursor_shape,
1989 cx,
1990 )
1991 });
1992 }
1993 let display_map = self
1994 .display_map
1995 .update(cx, |display_map, cx| display_map.snapshot(cx));
1996 let buffer = &display_map.buffer_snapshot;
1997 self.add_selections_state = None;
1998 self.select_next_state = None;
1999 self.select_prev_state = None;
2000 self.select_larger_syntax_node_stack.clear();
2001 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2002 self.snippet_stack
2003 .invalidate(&self.selections.disjoint_anchors(), buffer);
2004 self.take_rename(false, window, cx);
2005
2006 let new_cursor_position = self.selections.newest_anchor().head();
2007
2008 self.push_to_nav_history(
2009 *old_cursor_position,
2010 Some(new_cursor_position.to_point(buffer)),
2011 cx,
2012 );
2013
2014 if local {
2015 let new_cursor_position = self.selections.newest_anchor().head();
2016 let mut context_menu = self.context_menu.borrow_mut();
2017 let completion_menu = match context_menu.as_ref() {
2018 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2019 _ => {
2020 *context_menu = None;
2021 None
2022 }
2023 };
2024 if let Some(buffer_id) = new_cursor_position.buffer_id {
2025 if !self.registered_buffers.contains_key(&buffer_id) {
2026 if let Some(lsp_store) = self.lsp_store(cx) {
2027 lsp_store.update(cx, |lsp_store, cx| {
2028 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2029 return;
2030 };
2031 self.registered_buffers.insert(
2032 buffer_id,
2033 lsp_store.register_buffer_with_language_servers(&buffer, cx),
2034 );
2035 })
2036 }
2037 }
2038 }
2039
2040 if let Some(completion_menu) = completion_menu {
2041 let cursor_position = new_cursor_position.to_offset(buffer);
2042 let (word_range, kind) =
2043 buffer.surrounding_word(completion_menu.initial_position, true);
2044 if kind == Some(CharKind::Word)
2045 && word_range.to_inclusive().contains(&cursor_position)
2046 {
2047 let mut completion_menu = completion_menu.clone();
2048 drop(context_menu);
2049
2050 let query = Self::completion_query(buffer, cursor_position);
2051 cx.spawn(move |this, mut cx| async move {
2052 completion_menu
2053 .filter(query.as_deref(), cx.background_executor().clone())
2054 .await;
2055
2056 this.update(&mut cx, |this, cx| {
2057 let mut context_menu = this.context_menu.borrow_mut();
2058 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2059 else {
2060 return;
2061 };
2062
2063 if menu.id > completion_menu.id {
2064 return;
2065 }
2066
2067 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2068 drop(context_menu);
2069 cx.notify();
2070 })
2071 })
2072 .detach();
2073
2074 if show_completions {
2075 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2076 }
2077 } else {
2078 drop(context_menu);
2079 self.hide_context_menu(window, cx);
2080 }
2081 } else {
2082 drop(context_menu);
2083 }
2084
2085 hide_hover(self, cx);
2086
2087 if old_cursor_position.to_display_point(&display_map).row()
2088 != new_cursor_position.to_display_point(&display_map).row()
2089 {
2090 self.available_code_actions.take();
2091 }
2092 self.refresh_code_actions(window, cx);
2093 self.refresh_document_highlights(cx);
2094 refresh_matching_bracket_highlights(self, window, cx);
2095 self.update_visible_inline_completion(window, cx);
2096 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2097 if self.git_blame_inline_enabled {
2098 self.start_inline_blame_timer(window, cx);
2099 }
2100 }
2101
2102 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2103 cx.emit(EditorEvent::SelectionsChanged { local });
2104
2105 if self.selections.disjoint_anchors().len() == 1 {
2106 cx.emit(SearchEvent::ActiveMatchChanged)
2107 }
2108 cx.notify();
2109 }
2110
2111 pub fn change_selections<R>(
2112 &mut self,
2113 autoscroll: Option<Autoscroll>,
2114 window: &mut Window,
2115 cx: &mut Context<Self>,
2116 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2117 ) -> R {
2118 self.change_selections_inner(autoscroll, true, window, cx, change)
2119 }
2120
2121 pub fn change_selections_inner<R>(
2122 &mut self,
2123 autoscroll: Option<Autoscroll>,
2124 request_completions: bool,
2125 window: &mut Window,
2126 cx: &mut Context<Self>,
2127 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2128 ) -> R {
2129 let old_cursor_position = self.selections.newest_anchor().head();
2130 self.push_to_selection_history();
2131
2132 let (changed, result) = self.selections.change_with(cx, change);
2133
2134 if changed {
2135 if let Some(autoscroll) = autoscroll {
2136 self.request_autoscroll(autoscroll, cx);
2137 }
2138 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2139
2140 if self.should_open_signature_help_automatically(
2141 &old_cursor_position,
2142 self.signature_help_state.backspace_pressed(),
2143 cx,
2144 ) {
2145 self.show_signature_help(&ShowSignatureHelp, window, cx);
2146 }
2147 self.signature_help_state.set_backspace_pressed(false);
2148 }
2149
2150 result
2151 }
2152
2153 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2154 where
2155 I: IntoIterator<Item = (Range<S>, T)>,
2156 S: ToOffset,
2157 T: Into<Arc<str>>,
2158 {
2159 if self.read_only(cx) {
2160 return;
2161 }
2162
2163 self.buffer
2164 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2165 }
2166
2167 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2168 where
2169 I: IntoIterator<Item = (Range<S>, T)>,
2170 S: ToOffset,
2171 T: Into<Arc<str>>,
2172 {
2173 if self.read_only(cx) {
2174 return;
2175 }
2176
2177 self.buffer.update(cx, |buffer, cx| {
2178 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2179 });
2180 }
2181
2182 pub fn edit_with_block_indent<I, S, T>(
2183 &mut self,
2184 edits: I,
2185 original_indent_columns: Vec<u32>,
2186 cx: &mut Context<Self>,
2187 ) where
2188 I: IntoIterator<Item = (Range<S>, T)>,
2189 S: ToOffset,
2190 T: Into<Arc<str>>,
2191 {
2192 if self.read_only(cx) {
2193 return;
2194 }
2195
2196 self.buffer.update(cx, |buffer, cx| {
2197 buffer.edit(
2198 edits,
2199 Some(AutoindentMode::Block {
2200 original_indent_columns,
2201 }),
2202 cx,
2203 )
2204 });
2205 }
2206
2207 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2208 self.hide_context_menu(window, cx);
2209
2210 match phase {
2211 SelectPhase::Begin {
2212 position,
2213 add,
2214 click_count,
2215 } => self.begin_selection(position, add, click_count, window, cx),
2216 SelectPhase::BeginColumnar {
2217 position,
2218 goal_column,
2219 reset,
2220 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2221 SelectPhase::Extend {
2222 position,
2223 click_count,
2224 } => self.extend_selection(position, click_count, window, cx),
2225 SelectPhase::Update {
2226 position,
2227 goal_column,
2228 scroll_delta,
2229 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2230 SelectPhase::End => self.end_selection(window, cx),
2231 }
2232 }
2233
2234 fn extend_selection(
2235 &mut self,
2236 position: DisplayPoint,
2237 click_count: usize,
2238 window: &mut Window,
2239 cx: &mut Context<Self>,
2240 ) {
2241 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2242 let tail = self.selections.newest::<usize>(cx).tail();
2243 self.begin_selection(position, false, click_count, window, cx);
2244
2245 let position = position.to_offset(&display_map, Bias::Left);
2246 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2247
2248 let mut pending_selection = self
2249 .selections
2250 .pending_anchor()
2251 .expect("extend_selection not called with pending selection");
2252 if position >= tail {
2253 pending_selection.start = tail_anchor;
2254 } else {
2255 pending_selection.end = tail_anchor;
2256 pending_selection.reversed = true;
2257 }
2258
2259 let mut pending_mode = self.selections.pending_mode().unwrap();
2260 match &mut pending_mode {
2261 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2262 _ => {}
2263 }
2264
2265 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2266 s.set_pending(pending_selection, pending_mode)
2267 });
2268 }
2269
2270 fn begin_selection(
2271 &mut self,
2272 position: DisplayPoint,
2273 add: bool,
2274 click_count: usize,
2275 window: &mut Window,
2276 cx: &mut Context<Self>,
2277 ) {
2278 if !self.focus_handle.is_focused(window) {
2279 self.last_focused_descendant = None;
2280 window.focus(&self.focus_handle);
2281 }
2282
2283 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2284 let buffer = &display_map.buffer_snapshot;
2285 let newest_selection = self.selections.newest_anchor().clone();
2286 let position = display_map.clip_point(position, Bias::Left);
2287
2288 let start;
2289 let end;
2290 let mode;
2291 let mut auto_scroll;
2292 match click_count {
2293 1 => {
2294 start = buffer.anchor_before(position.to_point(&display_map));
2295 end = start;
2296 mode = SelectMode::Character;
2297 auto_scroll = true;
2298 }
2299 2 => {
2300 let range = movement::surrounding_word(&display_map, position);
2301 start = buffer.anchor_before(range.start.to_point(&display_map));
2302 end = buffer.anchor_before(range.end.to_point(&display_map));
2303 mode = SelectMode::Word(start..end);
2304 auto_scroll = true;
2305 }
2306 3 => {
2307 let position = display_map
2308 .clip_point(position, Bias::Left)
2309 .to_point(&display_map);
2310 let line_start = display_map.prev_line_boundary(position).0;
2311 let next_line_start = buffer.clip_point(
2312 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2313 Bias::Left,
2314 );
2315 start = buffer.anchor_before(line_start);
2316 end = buffer.anchor_before(next_line_start);
2317 mode = SelectMode::Line(start..end);
2318 auto_scroll = true;
2319 }
2320 _ => {
2321 start = buffer.anchor_before(0);
2322 end = buffer.anchor_before(buffer.len());
2323 mode = SelectMode::All;
2324 auto_scroll = false;
2325 }
2326 }
2327 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2328
2329 let point_to_delete: Option<usize> = {
2330 let selected_points: Vec<Selection<Point>> =
2331 self.selections.disjoint_in_range(start..end, cx);
2332
2333 if !add || click_count > 1 {
2334 None
2335 } else if !selected_points.is_empty() {
2336 Some(selected_points[0].id)
2337 } else {
2338 let clicked_point_already_selected =
2339 self.selections.disjoint.iter().find(|selection| {
2340 selection.start.to_point(buffer) == start.to_point(buffer)
2341 || selection.end.to_point(buffer) == end.to_point(buffer)
2342 });
2343
2344 clicked_point_already_selected.map(|selection| selection.id)
2345 }
2346 };
2347
2348 let selections_count = self.selections.count();
2349
2350 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2351 if let Some(point_to_delete) = point_to_delete {
2352 s.delete(point_to_delete);
2353
2354 if selections_count == 1 {
2355 s.set_pending_anchor_range(start..end, mode);
2356 }
2357 } else {
2358 if !add {
2359 s.clear_disjoint();
2360 } else if click_count > 1 {
2361 s.delete(newest_selection.id)
2362 }
2363
2364 s.set_pending_anchor_range(start..end, mode);
2365 }
2366 });
2367 }
2368
2369 fn begin_columnar_selection(
2370 &mut self,
2371 position: DisplayPoint,
2372 goal_column: u32,
2373 reset: bool,
2374 window: &mut Window,
2375 cx: &mut Context<Self>,
2376 ) {
2377 if !self.focus_handle.is_focused(window) {
2378 self.last_focused_descendant = None;
2379 window.focus(&self.focus_handle);
2380 }
2381
2382 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2383
2384 if reset {
2385 let pointer_position = display_map
2386 .buffer_snapshot
2387 .anchor_before(position.to_point(&display_map));
2388
2389 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2390 s.clear_disjoint();
2391 s.set_pending_anchor_range(
2392 pointer_position..pointer_position,
2393 SelectMode::Character,
2394 );
2395 });
2396 }
2397
2398 let tail = self.selections.newest::<Point>(cx).tail();
2399 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2400
2401 if !reset {
2402 self.select_columns(
2403 tail.to_display_point(&display_map),
2404 position,
2405 goal_column,
2406 &display_map,
2407 window,
2408 cx,
2409 );
2410 }
2411 }
2412
2413 fn update_selection(
2414 &mut self,
2415 position: DisplayPoint,
2416 goal_column: u32,
2417 scroll_delta: gpui::Point<f32>,
2418 window: &mut Window,
2419 cx: &mut Context<Self>,
2420 ) {
2421 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2422
2423 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2424 let tail = tail.to_display_point(&display_map);
2425 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2426 } else if let Some(mut pending) = self.selections.pending_anchor() {
2427 let buffer = self.buffer.read(cx).snapshot(cx);
2428 let head;
2429 let tail;
2430 let mode = self.selections.pending_mode().unwrap();
2431 match &mode {
2432 SelectMode::Character => {
2433 head = position.to_point(&display_map);
2434 tail = pending.tail().to_point(&buffer);
2435 }
2436 SelectMode::Word(original_range) => {
2437 let original_display_range = original_range.start.to_display_point(&display_map)
2438 ..original_range.end.to_display_point(&display_map);
2439 let original_buffer_range = original_display_range.start.to_point(&display_map)
2440 ..original_display_range.end.to_point(&display_map);
2441 if movement::is_inside_word(&display_map, position)
2442 || original_display_range.contains(&position)
2443 {
2444 let word_range = movement::surrounding_word(&display_map, position);
2445 if word_range.start < original_display_range.start {
2446 head = word_range.start.to_point(&display_map);
2447 } else {
2448 head = word_range.end.to_point(&display_map);
2449 }
2450 } else {
2451 head = position.to_point(&display_map);
2452 }
2453
2454 if head <= original_buffer_range.start {
2455 tail = original_buffer_range.end;
2456 } else {
2457 tail = original_buffer_range.start;
2458 }
2459 }
2460 SelectMode::Line(original_range) => {
2461 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2462
2463 let position = display_map
2464 .clip_point(position, Bias::Left)
2465 .to_point(&display_map);
2466 let line_start = display_map.prev_line_boundary(position).0;
2467 let next_line_start = buffer.clip_point(
2468 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2469 Bias::Left,
2470 );
2471
2472 if line_start < original_range.start {
2473 head = line_start
2474 } else {
2475 head = next_line_start
2476 }
2477
2478 if head <= original_range.start {
2479 tail = original_range.end;
2480 } else {
2481 tail = original_range.start;
2482 }
2483 }
2484 SelectMode::All => {
2485 return;
2486 }
2487 };
2488
2489 if head < tail {
2490 pending.start = buffer.anchor_before(head);
2491 pending.end = buffer.anchor_before(tail);
2492 pending.reversed = true;
2493 } else {
2494 pending.start = buffer.anchor_before(tail);
2495 pending.end = buffer.anchor_before(head);
2496 pending.reversed = false;
2497 }
2498
2499 self.change_selections(None, window, cx, |s| {
2500 s.set_pending(pending, mode);
2501 });
2502 } else {
2503 log::error!("update_selection dispatched with no pending selection");
2504 return;
2505 }
2506
2507 self.apply_scroll_delta(scroll_delta, window, cx);
2508 cx.notify();
2509 }
2510
2511 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2512 self.columnar_selection_tail.take();
2513 if self.selections.pending_anchor().is_some() {
2514 let selections = self.selections.all::<usize>(cx);
2515 self.change_selections(None, window, cx, |s| {
2516 s.select(selections);
2517 s.clear_pending();
2518 });
2519 }
2520 }
2521
2522 fn select_columns(
2523 &mut self,
2524 tail: DisplayPoint,
2525 head: DisplayPoint,
2526 goal_column: u32,
2527 display_map: &DisplaySnapshot,
2528 window: &mut Window,
2529 cx: &mut Context<Self>,
2530 ) {
2531 let start_row = cmp::min(tail.row(), head.row());
2532 let end_row = cmp::max(tail.row(), head.row());
2533 let start_column = cmp::min(tail.column(), goal_column);
2534 let end_column = cmp::max(tail.column(), goal_column);
2535 let reversed = start_column < tail.column();
2536
2537 let selection_ranges = (start_row.0..=end_row.0)
2538 .map(DisplayRow)
2539 .filter_map(|row| {
2540 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2541 let start = display_map
2542 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2543 .to_point(display_map);
2544 let end = display_map
2545 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2546 .to_point(display_map);
2547 if reversed {
2548 Some(end..start)
2549 } else {
2550 Some(start..end)
2551 }
2552 } else {
2553 None
2554 }
2555 })
2556 .collect::<Vec<_>>();
2557
2558 self.change_selections(None, window, cx, |s| {
2559 s.select_ranges(selection_ranges);
2560 });
2561 cx.notify();
2562 }
2563
2564 pub fn has_pending_nonempty_selection(&self) -> bool {
2565 let pending_nonempty_selection = match self.selections.pending_anchor() {
2566 Some(Selection { start, end, .. }) => start != end,
2567 None => false,
2568 };
2569
2570 pending_nonempty_selection
2571 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2572 }
2573
2574 pub fn has_pending_selection(&self) -> bool {
2575 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2576 }
2577
2578 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2579 self.selection_mark_mode = false;
2580
2581 if self.clear_expanded_diff_hunks(cx) {
2582 cx.notify();
2583 return;
2584 }
2585 if self.dismiss_menus_and_popups(true, window, cx) {
2586 return;
2587 }
2588
2589 if self.mode == EditorMode::Full
2590 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2591 {
2592 return;
2593 }
2594
2595 cx.propagate();
2596 }
2597
2598 pub fn dismiss_menus_and_popups(
2599 &mut self,
2600 is_user_requested: bool,
2601 window: &mut Window,
2602 cx: &mut Context<Self>,
2603 ) -> bool {
2604 if self.take_rename(false, window, cx).is_some() {
2605 return true;
2606 }
2607
2608 if hide_hover(self, cx) {
2609 return true;
2610 }
2611
2612 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2613 return true;
2614 }
2615
2616 if self.hide_context_menu(window, cx).is_some() {
2617 return true;
2618 }
2619
2620 if self.mouse_context_menu.take().is_some() {
2621 return true;
2622 }
2623
2624 if is_user_requested && self.discard_inline_completion(true, cx) {
2625 return true;
2626 }
2627
2628 if self.snippet_stack.pop().is_some() {
2629 return true;
2630 }
2631
2632 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2633 self.dismiss_diagnostics(cx);
2634 return true;
2635 }
2636
2637 false
2638 }
2639
2640 fn linked_editing_ranges_for(
2641 &self,
2642 selection: Range<text::Anchor>,
2643 cx: &App,
2644 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2645 if self.linked_edit_ranges.is_empty() {
2646 return None;
2647 }
2648 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2649 selection.end.buffer_id.and_then(|end_buffer_id| {
2650 if selection.start.buffer_id != Some(end_buffer_id) {
2651 return None;
2652 }
2653 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2654 let snapshot = buffer.read(cx).snapshot();
2655 self.linked_edit_ranges
2656 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2657 .map(|ranges| (ranges, snapshot, buffer))
2658 })?;
2659 use text::ToOffset as TO;
2660 // find offset from the start of current range to current cursor position
2661 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2662
2663 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2664 let start_difference = start_offset - start_byte_offset;
2665 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2666 let end_difference = end_offset - start_byte_offset;
2667 // Current range has associated linked ranges.
2668 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2669 for range in linked_ranges.iter() {
2670 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2671 let end_offset = start_offset + end_difference;
2672 let start_offset = start_offset + start_difference;
2673 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2674 continue;
2675 }
2676 if self.selections.disjoint_anchor_ranges().any(|s| {
2677 if s.start.buffer_id != selection.start.buffer_id
2678 || s.end.buffer_id != selection.end.buffer_id
2679 {
2680 return false;
2681 }
2682 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2683 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2684 }) {
2685 continue;
2686 }
2687 let start = buffer_snapshot.anchor_after(start_offset);
2688 let end = buffer_snapshot.anchor_after(end_offset);
2689 linked_edits
2690 .entry(buffer.clone())
2691 .or_default()
2692 .push(start..end);
2693 }
2694 Some(linked_edits)
2695 }
2696
2697 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2698 let text: Arc<str> = text.into();
2699
2700 if self.read_only(cx) {
2701 return;
2702 }
2703
2704 let selections = self.selections.all_adjusted(cx);
2705 let mut bracket_inserted = false;
2706 let mut edits = Vec::new();
2707 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2708 let mut new_selections = Vec::with_capacity(selections.len());
2709 let mut new_autoclose_regions = Vec::new();
2710 let snapshot = self.buffer.read(cx).read(cx);
2711
2712 for (selection, autoclose_region) in
2713 self.selections_with_autoclose_regions(selections, &snapshot)
2714 {
2715 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2716 // Determine if the inserted text matches the opening or closing
2717 // bracket of any of this language's bracket pairs.
2718 let mut bracket_pair = None;
2719 let mut is_bracket_pair_start = false;
2720 let mut is_bracket_pair_end = false;
2721 if !text.is_empty() {
2722 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2723 // and they are removing the character that triggered IME popup.
2724 for (pair, enabled) in scope.brackets() {
2725 if !pair.close && !pair.surround {
2726 continue;
2727 }
2728
2729 if enabled && pair.start.ends_with(text.as_ref()) {
2730 let prefix_len = pair.start.len() - text.len();
2731 let preceding_text_matches_prefix = prefix_len == 0
2732 || (selection.start.column >= (prefix_len as u32)
2733 && snapshot.contains_str_at(
2734 Point::new(
2735 selection.start.row,
2736 selection.start.column - (prefix_len as u32),
2737 ),
2738 &pair.start[..prefix_len],
2739 ));
2740 if preceding_text_matches_prefix {
2741 bracket_pair = Some(pair.clone());
2742 is_bracket_pair_start = true;
2743 break;
2744 }
2745 }
2746 if pair.end.as_str() == text.as_ref() {
2747 bracket_pair = Some(pair.clone());
2748 is_bracket_pair_end = true;
2749 break;
2750 }
2751 }
2752 }
2753
2754 if let Some(bracket_pair) = bracket_pair {
2755 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2756 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2757 let auto_surround =
2758 self.use_auto_surround && snapshot_settings.use_auto_surround;
2759 if selection.is_empty() {
2760 if is_bracket_pair_start {
2761 // If the inserted text is a suffix of an opening bracket and the
2762 // selection is preceded by the rest of the opening bracket, then
2763 // insert the closing bracket.
2764 let following_text_allows_autoclose = snapshot
2765 .chars_at(selection.start)
2766 .next()
2767 .map_or(true, |c| scope.should_autoclose_before(c));
2768
2769 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2770 && bracket_pair.start.len() == 1
2771 {
2772 let target = bracket_pair.start.chars().next().unwrap();
2773 let current_line_count = snapshot
2774 .reversed_chars_at(selection.start)
2775 .take_while(|&c| c != '\n')
2776 .filter(|&c| c == target)
2777 .count();
2778 current_line_count % 2 == 1
2779 } else {
2780 false
2781 };
2782
2783 if autoclose
2784 && bracket_pair.close
2785 && following_text_allows_autoclose
2786 && !is_closing_quote
2787 {
2788 let anchor = snapshot.anchor_before(selection.end);
2789 new_selections.push((selection.map(|_| anchor), text.len()));
2790 new_autoclose_regions.push((
2791 anchor,
2792 text.len(),
2793 selection.id,
2794 bracket_pair.clone(),
2795 ));
2796 edits.push((
2797 selection.range(),
2798 format!("{}{}", text, bracket_pair.end).into(),
2799 ));
2800 bracket_inserted = true;
2801 continue;
2802 }
2803 }
2804
2805 if let Some(region) = autoclose_region {
2806 // If the selection is followed by an auto-inserted closing bracket,
2807 // then don't insert that closing bracket again; just move the selection
2808 // past the closing bracket.
2809 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2810 && text.as_ref() == region.pair.end.as_str();
2811 if should_skip {
2812 let anchor = snapshot.anchor_after(selection.end);
2813 new_selections
2814 .push((selection.map(|_| anchor), region.pair.end.len()));
2815 continue;
2816 }
2817 }
2818
2819 let always_treat_brackets_as_autoclosed = snapshot
2820 .settings_at(selection.start, cx)
2821 .always_treat_brackets_as_autoclosed;
2822 if always_treat_brackets_as_autoclosed
2823 && is_bracket_pair_end
2824 && snapshot.contains_str_at(selection.end, text.as_ref())
2825 {
2826 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2827 // and the inserted text is a closing bracket and the selection is followed
2828 // by the closing bracket then move the selection past the closing bracket.
2829 let anchor = snapshot.anchor_after(selection.end);
2830 new_selections.push((selection.map(|_| anchor), text.len()));
2831 continue;
2832 }
2833 }
2834 // If an opening bracket is 1 character long and is typed while
2835 // text is selected, then surround that text with the bracket pair.
2836 else if auto_surround
2837 && bracket_pair.surround
2838 && is_bracket_pair_start
2839 && bracket_pair.start.chars().count() == 1
2840 {
2841 edits.push((selection.start..selection.start, text.clone()));
2842 edits.push((
2843 selection.end..selection.end,
2844 bracket_pair.end.as_str().into(),
2845 ));
2846 bracket_inserted = true;
2847 new_selections.push((
2848 Selection {
2849 id: selection.id,
2850 start: snapshot.anchor_after(selection.start),
2851 end: snapshot.anchor_before(selection.end),
2852 reversed: selection.reversed,
2853 goal: selection.goal,
2854 },
2855 0,
2856 ));
2857 continue;
2858 }
2859 }
2860 }
2861
2862 if self.auto_replace_emoji_shortcode
2863 && selection.is_empty()
2864 && text.as_ref().ends_with(':')
2865 {
2866 if let Some(possible_emoji_short_code) =
2867 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2868 {
2869 if !possible_emoji_short_code.is_empty() {
2870 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2871 let emoji_shortcode_start = Point::new(
2872 selection.start.row,
2873 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2874 );
2875
2876 // Remove shortcode from buffer
2877 edits.push((
2878 emoji_shortcode_start..selection.start,
2879 "".to_string().into(),
2880 ));
2881 new_selections.push((
2882 Selection {
2883 id: selection.id,
2884 start: snapshot.anchor_after(emoji_shortcode_start),
2885 end: snapshot.anchor_before(selection.start),
2886 reversed: selection.reversed,
2887 goal: selection.goal,
2888 },
2889 0,
2890 ));
2891
2892 // Insert emoji
2893 let selection_start_anchor = snapshot.anchor_after(selection.start);
2894 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2895 edits.push((selection.start..selection.end, emoji.to_string().into()));
2896
2897 continue;
2898 }
2899 }
2900 }
2901 }
2902
2903 // If not handling any auto-close operation, then just replace the selected
2904 // text with the given input and move the selection to the end of the
2905 // newly inserted text.
2906 let anchor = snapshot.anchor_after(selection.end);
2907 if !self.linked_edit_ranges.is_empty() {
2908 let start_anchor = snapshot.anchor_before(selection.start);
2909
2910 let is_word_char = text.chars().next().map_or(true, |char| {
2911 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2912 classifier.is_word(char)
2913 });
2914
2915 if is_word_char {
2916 if let Some(ranges) = self
2917 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2918 {
2919 for (buffer, edits) in ranges {
2920 linked_edits
2921 .entry(buffer.clone())
2922 .or_default()
2923 .extend(edits.into_iter().map(|range| (range, text.clone())));
2924 }
2925 }
2926 }
2927 }
2928
2929 new_selections.push((selection.map(|_| anchor), 0));
2930 edits.push((selection.start..selection.end, text.clone()));
2931 }
2932
2933 drop(snapshot);
2934
2935 self.transact(window, cx, |this, window, cx| {
2936 this.buffer.update(cx, |buffer, cx| {
2937 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2938 });
2939 for (buffer, edits) in linked_edits {
2940 buffer.update(cx, |buffer, cx| {
2941 let snapshot = buffer.snapshot();
2942 let edits = edits
2943 .into_iter()
2944 .map(|(range, text)| {
2945 use text::ToPoint as TP;
2946 let end_point = TP::to_point(&range.end, &snapshot);
2947 let start_point = TP::to_point(&range.start, &snapshot);
2948 (start_point..end_point, text)
2949 })
2950 .sorted_by_key(|(range, _)| range.start)
2951 .collect::<Vec<_>>();
2952 buffer.edit(edits, None, cx);
2953 })
2954 }
2955 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2956 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2957 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2958 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2959 .zip(new_selection_deltas)
2960 .map(|(selection, delta)| Selection {
2961 id: selection.id,
2962 start: selection.start + delta,
2963 end: selection.end + delta,
2964 reversed: selection.reversed,
2965 goal: SelectionGoal::None,
2966 })
2967 .collect::<Vec<_>>();
2968
2969 let mut i = 0;
2970 for (position, delta, selection_id, pair) in new_autoclose_regions {
2971 let position = position.to_offset(&map.buffer_snapshot) + delta;
2972 let start = map.buffer_snapshot.anchor_before(position);
2973 let end = map.buffer_snapshot.anchor_after(position);
2974 while let Some(existing_state) = this.autoclose_regions.get(i) {
2975 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2976 Ordering::Less => i += 1,
2977 Ordering::Greater => break,
2978 Ordering::Equal => {
2979 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2980 Ordering::Less => i += 1,
2981 Ordering::Equal => break,
2982 Ordering::Greater => break,
2983 }
2984 }
2985 }
2986 }
2987 this.autoclose_regions.insert(
2988 i,
2989 AutocloseRegion {
2990 selection_id,
2991 range: start..end,
2992 pair,
2993 },
2994 );
2995 }
2996
2997 let had_active_inline_completion = this.has_active_inline_completion();
2998 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
2999 s.select(new_selections)
3000 });
3001
3002 if !bracket_inserted {
3003 if let Some(on_type_format_task) =
3004 this.trigger_on_type_formatting(text.to_string(), window, cx)
3005 {
3006 on_type_format_task.detach_and_log_err(cx);
3007 }
3008 }
3009
3010 let editor_settings = EditorSettings::get_global(cx);
3011 if bracket_inserted
3012 && (editor_settings.auto_signature_help
3013 || editor_settings.show_signature_help_after_edits)
3014 {
3015 this.show_signature_help(&ShowSignatureHelp, window, cx);
3016 }
3017
3018 let trigger_in_words =
3019 this.show_edit_predictions_in_menu(cx) || !had_active_inline_completion;
3020 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3021 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3022 this.refresh_inline_completion(true, false, window, cx);
3023 });
3024 }
3025
3026 fn find_possible_emoji_shortcode_at_position(
3027 snapshot: &MultiBufferSnapshot,
3028 position: Point,
3029 ) -> Option<String> {
3030 let mut chars = Vec::new();
3031 let mut found_colon = false;
3032 for char in snapshot.reversed_chars_at(position).take(100) {
3033 // Found a possible emoji shortcode in the middle of the buffer
3034 if found_colon {
3035 if char.is_whitespace() {
3036 chars.reverse();
3037 return Some(chars.iter().collect());
3038 }
3039 // If the previous character is not a whitespace, we are in the middle of a word
3040 // and we only want to complete the shortcode if the word is made up of other emojis
3041 let mut containing_word = String::new();
3042 for ch in snapshot
3043 .reversed_chars_at(position)
3044 .skip(chars.len() + 1)
3045 .take(100)
3046 {
3047 if ch.is_whitespace() {
3048 break;
3049 }
3050 containing_word.push(ch);
3051 }
3052 let containing_word = containing_word.chars().rev().collect::<String>();
3053 if util::word_consists_of_emojis(containing_word.as_str()) {
3054 chars.reverse();
3055 return Some(chars.iter().collect());
3056 }
3057 }
3058
3059 if char.is_whitespace() || !char.is_ascii() {
3060 return None;
3061 }
3062 if char == ':' {
3063 found_colon = true;
3064 } else {
3065 chars.push(char);
3066 }
3067 }
3068 // Found a possible emoji shortcode at the beginning of the buffer
3069 chars.reverse();
3070 Some(chars.iter().collect())
3071 }
3072
3073 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3074 self.transact(window, cx, |this, window, cx| {
3075 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3076 let selections = this.selections.all::<usize>(cx);
3077 let multi_buffer = this.buffer.read(cx);
3078 let buffer = multi_buffer.snapshot(cx);
3079 selections
3080 .iter()
3081 .map(|selection| {
3082 let start_point = selection.start.to_point(&buffer);
3083 let mut indent =
3084 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3085 indent.len = cmp::min(indent.len, start_point.column);
3086 let start = selection.start;
3087 let end = selection.end;
3088 let selection_is_empty = start == end;
3089 let language_scope = buffer.language_scope_at(start);
3090 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3091 &language_scope
3092 {
3093 let leading_whitespace_len = buffer
3094 .reversed_chars_at(start)
3095 .take_while(|c| c.is_whitespace() && *c != '\n')
3096 .map(|c| c.len_utf8())
3097 .sum::<usize>();
3098
3099 let trailing_whitespace_len = buffer
3100 .chars_at(end)
3101 .take_while(|c| c.is_whitespace() && *c != '\n')
3102 .map(|c| c.len_utf8())
3103 .sum::<usize>();
3104
3105 let insert_extra_newline =
3106 language.brackets().any(|(pair, enabled)| {
3107 let pair_start = pair.start.trim_end();
3108 let pair_end = pair.end.trim_start();
3109
3110 enabled
3111 && pair.newline
3112 && buffer.contains_str_at(
3113 end + trailing_whitespace_len,
3114 pair_end,
3115 )
3116 && buffer.contains_str_at(
3117 (start - leading_whitespace_len)
3118 .saturating_sub(pair_start.len()),
3119 pair_start,
3120 )
3121 });
3122
3123 // Comment extension on newline is allowed only for cursor selections
3124 let comment_delimiter = maybe!({
3125 if !selection_is_empty {
3126 return None;
3127 }
3128
3129 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3130 return None;
3131 }
3132
3133 let delimiters = language.line_comment_prefixes();
3134 let max_len_of_delimiter =
3135 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3136 let (snapshot, range) =
3137 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3138
3139 let mut index_of_first_non_whitespace = 0;
3140 let comment_candidate = snapshot
3141 .chars_for_range(range)
3142 .skip_while(|c| {
3143 let should_skip = c.is_whitespace();
3144 if should_skip {
3145 index_of_first_non_whitespace += 1;
3146 }
3147 should_skip
3148 })
3149 .take(max_len_of_delimiter)
3150 .collect::<String>();
3151 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3152 comment_candidate.starts_with(comment_prefix.as_ref())
3153 })?;
3154 let cursor_is_placed_after_comment_marker =
3155 index_of_first_non_whitespace + comment_prefix.len()
3156 <= start_point.column as usize;
3157 if cursor_is_placed_after_comment_marker {
3158 Some(comment_prefix.clone())
3159 } else {
3160 None
3161 }
3162 });
3163 (comment_delimiter, insert_extra_newline)
3164 } else {
3165 (None, false)
3166 };
3167
3168 let capacity_for_delimiter = comment_delimiter
3169 .as_deref()
3170 .map(str::len)
3171 .unwrap_or_default();
3172 let mut new_text =
3173 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3174 new_text.push('\n');
3175 new_text.extend(indent.chars());
3176 if let Some(delimiter) = &comment_delimiter {
3177 new_text.push_str(delimiter);
3178 }
3179 if insert_extra_newline {
3180 new_text = new_text.repeat(2);
3181 }
3182
3183 let anchor = buffer.anchor_after(end);
3184 let new_selection = selection.map(|_| anchor);
3185 (
3186 (start..end, new_text),
3187 (insert_extra_newline, new_selection),
3188 )
3189 })
3190 .unzip()
3191 };
3192
3193 this.edit_with_autoindent(edits, cx);
3194 let buffer = this.buffer.read(cx).snapshot(cx);
3195 let new_selections = selection_fixup_info
3196 .into_iter()
3197 .map(|(extra_newline_inserted, new_selection)| {
3198 let mut cursor = new_selection.end.to_point(&buffer);
3199 if extra_newline_inserted {
3200 cursor.row -= 1;
3201 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3202 }
3203 new_selection.map(|_| cursor)
3204 })
3205 .collect();
3206
3207 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3208 s.select(new_selections)
3209 });
3210 this.refresh_inline_completion(true, false, window, cx);
3211 });
3212 }
3213
3214 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3215 let buffer = self.buffer.read(cx);
3216 let snapshot = buffer.snapshot(cx);
3217
3218 let mut edits = Vec::new();
3219 let mut rows = Vec::new();
3220
3221 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3222 let cursor = selection.head();
3223 let row = cursor.row;
3224
3225 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3226
3227 let newline = "\n".to_string();
3228 edits.push((start_of_line..start_of_line, newline));
3229
3230 rows.push(row + rows_inserted as u32);
3231 }
3232
3233 self.transact(window, cx, |editor, window, cx| {
3234 editor.edit(edits, cx);
3235
3236 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3237 let mut index = 0;
3238 s.move_cursors_with(|map, _, _| {
3239 let row = rows[index];
3240 index += 1;
3241
3242 let point = Point::new(row, 0);
3243 let boundary = map.next_line_boundary(point).1;
3244 let clipped = map.clip_point(boundary, Bias::Left);
3245
3246 (clipped, SelectionGoal::None)
3247 });
3248 });
3249
3250 let mut indent_edits = Vec::new();
3251 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3252 for row in rows {
3253 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3254 for (row, indent) in indents {
3255 if indent.len == 0 {
3256 continue;
3257 }
3258
3259 let text = match indent.kind {
3260 IndentKind::Space => " ".repeat(indent.len as usize),
3261 IndentKind::Tab => "\t".repeat(indent.len as usize),
3262 };
3263 let point = Point::new(row.0, 0);
3264 indent_edits.push((point..point, text));
3265 }
3266 }
3267 editor.edit(indent_edits, cx);
3268 });
3269 }
3270
3271 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3272 let buffer = self.buffer.read(cx);
3273 let snapshot = buffer.snapshot(cx);
3274
3275 let mut edits = Vec::new();
3276 let mut rows = Vec::new();
3277 let mut rows_inserted = 0;
3278
3279 for selection in self.selections.all_adjusted(cx) {
3280 let cursor = selection.head();
3281 let row = cursor.row;
3282
3283 let point = Point::new(row + 1, 0);
3284 let start_of_line = snapshot.clip_point(point, Bias::Left);
3285
3286 let newline = "\n".to_string();
3287 edits.push((start_of_line..start_of_line, newline));
3288
3289 rows_inserted += 1;
3290 rows.push(row + rows_inserted);
3291 }
3292
3293 self.transact(window, cx, |editor, window, cx| {
3294 editor.edit(edits, cx);
3295
3296 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3297 let mut index = 0;
3298 s.move_cursors_with(|map, _, _| {
3299 let row = rows[index];
3300 index += 1;
3301
3302 let point = Point::new(row, 0);
3303 let boundary = map.next_line_boundary(point).1;
3304 let clipped = map.clip_point(boundary, Bias::Left);
3305
3306 (clipped, SelectionGoal::None)
3307 });
3308 });
3309
3310 let mut indent_edits = Vec::new();
3311 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3312 for row in rows {
3313 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3314 for (row, indent) in indents {
3315 if indent.len == 0 {
3316 continue;
3317 }
3318
3319 let text = match indent.kind {
3320 IndentKind::Space => " ".repeat(indent.len as usize),
3321 IndentKind::Tab => "\t".repeat(indent.len as usize),
3322 };
3323 let point = Point::new(row.0, 0);
3324 indent_edits.push((point..point, text));
3325 }
3326 }
3327 editor.edit(indent_edits, cx);
3328 });
3329 }
3330
3331 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3332 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3333 original_indent_columns: Vec::new(),
3334 });
3335 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3336 }
3337
3338 fn insert_with_autoindent_mode(
3339 &mut self,
3340 text: &str,
3341 autoindent_mode: Option<AutoindentMode>,
3342 window: &mut Window,
3343 cx: &mut Context<Self>,
3344 ) {
3345 if self.read_only(cx) {
3346 return;
3347 }
3348
3349 let text: Arc<str> = text.into();
3350 self.transact(window, cx, |this, window, cx| {
3351 let old_selections = this.selections.all_adjusted(cx);
3352 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3353 let anchors = {
3354 let snapshot = buffer.read(cx);
3355 old_selections
3356 .iter()
3357 .map(|s| {
3358 let anchor = snapshot.anchor_after(s.head());
3359 s.map(|_| anchor)
3360 })
3361 .collect::<Vec<_>>()
3362 };
3363 buffer.edit(
3364 old_selections
3365 .iter()
3366 .map(|s| (s.start..s.end, text.clone())),
3367 autoindent_mode,
3368 cx,
3369 );
3370 anchors
3371 });
3372
3373 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3374 s.select_anchors(selection_anchors);
3375 });
3376
3377 cx.notify();
3378 });
3379 }
3380
3381 fn trigger_completion_on_input(
3382 &mut self,
3383 text: &str,
3384 trigger_in_words: bool,
3385 window: &mut Window,
3386 cx: &mut Context<Self>,
3387 ) {
3388 if self.is_completion_trigger(text, trigger_in_words, cx) {
3389 self.show_completions(
3390 &ShowCompletions {
3391 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3392 },
3393 window,
3394 cx,
3395 );
3396 } else {
3397 self.hide_context_menu(window, cx);
3398 }
3399 }
3400
3401 fn is_completion_trigger(
3402 &self,
3403 text: &str,
3404 trigger_in_words: bool,
3405 cx: &mut Context<Self>,
3406 ) -> bool {
3407 let position = self.selections.newest_anchor().head();
3408 let multibuffer = self.buffer.read(cx);
3409 let Some(buffer) = position
3410 .buffer_id
3411 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3412 else {
3413 return false;
3414 };
3415
3416 if let Some(completion_provider) = &self.completion_provider {
3417 completion_provider.is_completion_trigger(
3418 &buffer,
3419 position.text_anchor,
3420 text,
3421 trigger_in_words,
3422 cx,
3423 )
3424 } else {
3425 false
3426 }
3427 }
3428
3429 /// If any empty selections is touching the start of its innermost containing autoclose
3430 /// region, expand it to select the brackets.
3431 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3432 let selections = self.selections.all::<usize>(cx);
3433 let buffer = self.buffer.read(cx).read(cx);
3434 let new_selections = self
3435 .selections_with_autoclose_regions(selections, &buffer)
3436 .map(|(mut selection, region)| {
3437 if !selection.is_empty() {
3438 return selection;
3439 }
3440
3441 if let Some(region) = region {
3442 let mut range = region.range.to_offset(&buffer);
3443 if selection.start == range.start && range.start >= region.pair.start.len() {
3444 range.start -= region.pair.start.len();
3445 if buffer.contains_str_at(range.start, ®ion.pair.start)
3446 && buffer.contains_str_at(range.end, ®ion.pair.end)
3447 {
3448 range.end += region.pair.end.len();
3449 selection.start = range.start;
3450 selection.end = range.end;
3451
3452 return selection;
3453 }
3454 }
3455 }
3456
3457 let always_treat_brackets_as_autoclosed = buffer
3458 .settings_at(selection.start, cx)
3459 .always_treat_brackets_as_autoclosed;
3460
3461 if !always_treat_brackets_as_autoclosed {
3462 return selection;
3463 }
3464
3465 if let Some(scope) = buffer.language_scope_at(selection.start) {
3466 for (pair, enabled) in scope.brackets() {
3467 if !enabled || !pair.close {
3468 continue;
3469 }
3470
3471 if buffer.contains_str_at(selection.start, &pair.end) {
3472 let pair_start_len = pair.start.len();
3473 if buffer.contains_str_at(
3474 selection.start.saturating_sub(pair_start_len),
3475 &pair.start,
3476 ) {
3477 selection.start -= pair_start_len;
3478 selection.end += pair.end.len();
3479
3480 return selection;
3481 }
3482 }
3483 }
3484 }
3485
3486 selection
3487 })
3488 .collect();
3489
3490 drop(buffer);
3491 self.change_selections(None, window, cx, |selections| {
3492 selections.select(new_selections)
3493 });
3494 }
3495
3496 /// Iterate the given selections, and for each one, find the smallest surrounding
3497 /// autoclose region. This uses the ordering of the selections and the autoclose
3498 /// regions to avoid repeated comparisons.
3499 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3500 &'a self,
3501 selections: impl IntoIterator<Item = Selection<D>>,
3502 buffer: &'a MultiBufferSnapshot,
3503 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3504 let mut i = 0;
3505 let mut regions = self.autoclose_regions.as_slice();
3506 selections.into_iter().map(move |selection| {
3507 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3508
3509 let mut enclosing = None;
3510 while let Some(pair_state) = regions.get(i) {
3511 if pair_state.range.end.to_offset(buffer) < range.start {
3512 regions = ®ions[i + 1..];
3513 i = 0;
3514 } else if pair_state.range.start.to_offset(buffer) > range.end {
3515 break;
3516 } else {
3517 if pair_state.selection_id == selection.id {
3518 enclosing = Some(pair_state);
3519 }
3520 i += 1;
3521 }
3522 }
3523
3524 (selection, enclosing)
3525 })
3526 }
3527
3528 /// Remove any autoclose regions that no longer contain their selection.
3529 fn invalidate_autoclose_regions(
3530 &mut self,
3531 mut selections: &[Selection<Anchor>],
3532 buffer: &MultiBufferSnapshot,
3533 ) {
3534 self.autoclose_regions.retain(|state| {
3535 let mut i = 0;
3536 while let Some(selection) = selections.get(i) {
3537 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3538 selections = &selections[1..];
3539 continue;
3540 }
3541 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3542 break;
3543 }
3544 if selection.id == state.selection_id {
3545 return true;
3546 } else {
3547 i += 1;
3548 }
3549 }
3550 false
3551 });
3552 }
3553
3554 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3555 let offset = position.to_offset(buffer);
3556 let (word_range, kind) = buffer.surrounding_word(offset, true);
3557 if offset > word_range.start && kind == Some(CharKind::Word) {
3558 Some(
3559 buffer
3560 .text_for_range(word_range.start..offset)
3561 .collect::<String>(),
3562 )
3563 } else {
3564 None
3565 }
3566 }
3567
3568 pub fn toggle_inlay_hints(
3569 &mut self,
3570 _: &ToggleInlayHints,
3571 _: &mut Window,
3572 cx: &mut Context<Self>,
3573 ) {
3574 self.refresh_inlay_hints(
3575 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3576 cx,
3577 );
3578 }
3579
3580 pub fn inlay_hints_enabled(&self) -> bool {
3581 self.inlay_hint_cache.enabled
3582 }
3583
3584 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3585 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3586 return;
3587 }
3588
3589 let reason_description = reason.description();
3590 let ignore_debounce = matches!(
3591 reason,
3592 InlayHintRefreshReason::SettingsChange(_)
3593 | InlayHintRefreshReason::Toggle(_)
3594 | InlayHintRefreshReason::ExcerptsRemoved(_)
3595 );
3596 let (invalidate_cache, required_languages) = match reason {
3597 InlayHintRefreshReason::Toggle(enabled) => {
3598 self.inlay_hint_cache.enabled = enabled;
3599 if enabled {
3600 (InvalidationStrategy::RefreshRequested, None)
3601 } else {
3602 self.inlay_hint_cache.clear();
3603 self.splice_inlays(
3604 &self
3605 .visible_inlay_hints(cx)
3606 .iter()
3607 .map(|inlay| inlay.id)
3608 .collect::<Vec<InlayId>>(),
3609 Vec::new(),
3610 cx,
3611 );
3612 return;
3613 }
3614 }
3615 InlayHintRefreshReason::SettingsChange(new_settings) => {
3616 match self.inlay_hint_cache.update_settings(
3617 &self.buffer,
3618 new_settings,
3619 self.visible_inlay_hints(cx),
3620 cx,
3621 ) {
3622 ControlFlow::Break(Some(InlaySplice {
3623 to_remove,
3624 to_insert,
3625 })) => {
3626 self.splice_inlays(&to_remove, to_insert, cx);
3627 return;
3628 }
3629 ControlFlow::Break(None) => return,
3630 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3631 }
3632 }
3633 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3634 if let Some(InlaySplice {
3635 to_remove,
3636 to_insert,
3637 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3638 {
3639 self.splice_inlays(&to_remove, to_insert, cx);
3640 }
3641 return;
3642 }
3643 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3644 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3645 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3646 }
3647 InlayHintRefreshReason::RefreshRequested => {
3648 (InvalidationStrategy::RefreshRequested, None)
3649 }
3650 };
3651
3652 if let Some(InlaySplice {
3653 to_remove,
3654 to_insert,
3655 }) = self.inlay_hint_cache.spawn_hint_refresh(
3656 reason_description,
3657 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3658 invalidate_cache,
3659 ignore_debounce,
3660 cx,
3661 ) {
3662 self.splice_inlays(&to_remove, to_insert, cx);
3663 }
3664 }
3665
3666 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3667 self.display_map
3668 .read(cx)
3669 .current_inlays()
3670 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3671 .cloned()
3672 .collect()
3673 }
3674
3675 pub fn excerpts_for_inlay_hints_query(
3676 &self,
3677 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3678 cx: &mut Context<Editor>,
3679 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3680 let Some(project) = self.project.as_ref() else {
3681 return HashMap::default();
3682 };
3683 let project = project.read(cx);
3684 let multi_buffer = self.buffer().read(cx);
3685 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3686 let multi_buffer_visible_start = self
3687 .scroll_manager
3688 .anchor()
3689 .anchor
3690 .to_point(&multi_buffer_snapshot);
3691 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3692 multi_buffer_visible_start
3693 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3694 Bias::Left,
3695 );
3696 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3697 multi_buffer_snapshot
3698 .range_to_buffer_ranges(multi_buffer_visible_range)
3699 .into_iter()
3700 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3701 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3702 let buffer_file = project::File::from_dyn(buffer.file())?;
3703 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3704 let worktree_entry = buffer_worktree
3705 .read(cx)
3706 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3707 if worktree_entry.is_ignored {
3708 return None;
3709 }
3710
3711 let language = buffer.language()?;
3712 if let Some(restrict_to_languages) = restrict_to_languages {
3713 if !restrict_to_languages.contains(language) {
3714 return None;
3715 }
3716 }
3717 Some((
3718 excerpt_id,
3719 (
3720 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3721 buffer.version().clone(),
3722 excerpt_visible_range,
3723 ),
3724 ))
3725 })
3726 .collect()
3727 }
3728
3729 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3730 TextLayoutDetails {
3731 text_system: window.text_system().clone(),
3732 editor_style: self.style.clone().unwrap(),
3733 rem_size: window.rem_size(),
3734 scroll_anchor: self.scroll_manager.anchor(),
3735 visible_rows: self.visible_line_count(),
3736 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3737 }
3738 }
3739
3740 pub fn splice_inlays(
3741 &self,
3742 to_remove: &[InlayId],
3743 to_insert: Vec<Inlay>,
3744 cx: &mut Context<Self>,
3745 ) {
3746 self.display_map.update(cx, |display_map, cx| {
3747 display_map.splice_inlays(to_remove, to_insert, cx)
3748 });
3749 cx.notify();
3750 }
3751
3752 fn trigger_on_type_formatting(
3753 &self,
3754 input: String,
3755 window: &mut Window,
3756 cx: &mut Context<Self>,
3757 ) -> Option<Task<Result<()>>> {
3758 if input.len() != 1 {
3759 return None;
3760 }
3761
3762 let project = self.project.as_ref()?;
3763 let position = self.selections.newest_anchor().head();
3764 let (buffer, buffer_position) = self
3765 .buffer
3766 .read(cx)
3767 .text_anchor_for_position(position, cx)?;
3768
3769 let settings = language_settings::language_settings(
3770 buffer
3771 .read(cx)
3772 .language_at(buffer_position)
3773 .map(|l| l.name()),
3774 buffer.read(cx).file(),
3775 cx,
3776 );
3777 if !settings.use_on_type_format {
3778 return None;
3779 }
3780
3781 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3782 // hence we do LSP request & edit on host side only — add formats to host's history.
3783 let push_to_lsp_host_history = true;
3784 // If this is not the host, append its history with new edits.
3785 let push_to_client_history = project.read(cx).is_via_collab();
3786
3787 let on_type_formatting = project.update(cx, |project, cx| {
3788 project.on_type_format(
3789 buffer.clone(),
3790 buffer_position,
3791 input,
3792 push_to_lsp_host_history,
3793 cx,
3794 )
3795 });
3796 Some(cx.spawn_in(window, |editor, mut cx| async move {
3797 if let Some(transaction) = on_type_formatting.await? {
3798 if push_to_client_history {
3799 buffer
3800 .update(&mut cx, |buffer, _| {
3801 buffer.push_transaction(transaction, Instant::now());
3802 })
3803 .ok();
3804 }
3805 editor.update(&mut cx, |editor, cx| {
3806 editor.refresh_document_highlights(cx);
3807 })?;
3808 }
3809 Ok(())
3810 }))
3811 }
3812
3813 pub fn show_completions(
3814 &mut self,
3815 options: &ShowCompletions,
3816 window: &mut Window,
3817 cx: &mut Context<Self>,
3818 ) {
3819 if self.pending_rename.is_some() {
3820 return;
3821 }
3822
3823 let Some(provider) = self.completion_provider.as_ref() else {
3824 return;
3825 };
3826
3827 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3828 return;
3829 }
3830
3831 let position = self.selections.newest_anchor().head();
3832 if position.diff_base_anchor.is_some() {
3833 return;
3834 }
3835 let (buffer, buffer_position) =
3836 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3837 output
3838 } else {
3839 return;
3840 };
3841 let show_completion_documentation = buffer
3842 .read(cx)
3843 .snapshot()
3844 .settings_at(buffer_position, cx)
3845 .show_completion_documentation;
3846
3847 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3848
3849 let trigger_kind = match &options.trigger {
3850 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3851 CompletionTriggerKind::TRIGGER_CHARACTER
3852 }
3853 _ => CompletionTriggerKind::INVOKED,
3854 };
3855 let completion_context = CompletionContext {
3856 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3857 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3858 Some(String::from(trigger))
3859 } else {
3860 None
3861 }
3862 }),
3863 trigger_kind,
3864 };
3865 let completions =
3866 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3867 let sort_completions = provider.sort_completions();
3868
3869 let id = post_inc(&mut self.next_completion_id);
3870 let task = cx.spawn_in(window, |editor, mut cx| {
3871 async move {
3872 editor.update(&mut cx, |this, _| {
3873 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3874 })?;
3875 let completions = completions.await.log_err();
3876 let menu = if let Some(completions) = completions {
3877 let mut menu = CompletionsMenu::new(
3878 id,
3879 sort_completions,
3880 show_completion_documentation,
3881 position,
3882 buffer.clone(),
3883 completions.into(),
3884 );
3885
3886 menu.filter(query.as_deref(), cx.background_executor().clone())
3887 .await;
3888
3889 menu.visible().then_some(menu)
3890 } else {
3891 None
3892 };
3893
3894 editor.update_in(&mut cx, |editor, window, cx| {
3895 match editor.context_menu.borrow().as_ref() {
3896 None => {}
3897 Some(CodeContextMenu::Completions(prev_menu)) => {
3898 if prev_menu.id > id {
3899 return;
3900 }
3901 }
3902 _ => return,
3903 }
3904
3905 if editor.focus_handle.is_focused(window) && menu.is_some() {
3906 let mut menu = menu.unwrap();
3907 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3908
3909 *editor.context_menu.borrow_mut() =
3910 Some(CodeContextMenu::Completions(menu));
3911
3912 if editor.show_edit_predictions_in_menu(cx) {
3913 editor.update_visible_inline_completion(window, cx);
3914 } else {
3915 editor.discard_inline_completion(false, cx);
3916 }
3917
3918 cx.notify();
3919 } else if editor.completion_tasks.len() <= 1 {
3920 // If there are no more completion tasks and the last menu was
3921 // empty, we should hide it.
3922 let was_hidden = editor.hide_context_menu(window, cx).is_none();
3923 // If it was already hidden and we don't show inline
3924 // completions in the menu, we should also show the
3925 // inline-completion when available.
3926 if was_hidden && editor.show_edit_predictions_in_menu(cx) {
3927 editor.update_visible_inline_completion(window, cx);
3928 }
3929 }
3930 })?;
3931
3932 Ok::<_, anyhow::Error>(())
3933 }
3934 .log_err()
3935 });
3936
3937 self.completion_tasks.push((id, task));
3938 }
3939
3940 pub fn confirm_completion(
3941 &mut self,
3942 action: &ConfirmCompletion,
3943 window: &mut Window,
3944 cx: &mut Context<Self>,
3945 ) -> Option<Task<Result<()>>> {
3946 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
3947 }
3948
3949 pub fn compose_completion(
3950 &mut self,
3951 action: &ComposeCompletion,
3952 window: &mut Window,
3953 cx: &mut Context<Self>,
3954 ) -> Option<Task<Result<()>>> {
3955 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
3956 }
3957
3958 fn do_completion(
3959 &mut self,
3960 item_ix: Option<usize>,
3961 intent: CompletionIntent,
3962 window: &mut Window,
3963 cx: &mut Context<Editor>,
3964 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3965 use language::ToOffset as _;
3966
3967 let completions_menu =
3968 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
3969 menu
3970 } else {
3971 return None;
3972 };
3973
3974 let entries = completions_menu.entries.borrow();
3975 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
3976 if self.show_edit_predictions_in_menu(cx) {
3977 self.discard_inline_completion(true, cx);
3978 }
3979 let candidate_id = mat.candidate_id;
3980 drop(entries);
3981
3982 let buffer_handle = completions_menu.buffer;
3983 let completion = completions_menu
3984 .completions
3985 .borrow()
3986 .get(candidate_id)?
3987 .clone();
3988 cx.stop_propagation();
3989
3990 let snippet;
3991 let text;
3992
3993 if completion.is_snippet() {
3994 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3995 text = snippet.as_ref().unwrap().text.clone();
3996 } else {
3997 snippet = None;
3998 text = completion.new_text.clone();
3999 };
4000 let selections = self.selections.all::<usize>(cx);
4001 let buffer = buffer_handle.read(cx);
4002 let old_range = completion.old_range.to_offset(buffer);
4003 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4004
4005 let newest_selection = self.selections.newest_anchor();
4006 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4007 return None;
4008 }
4009
4010 let lookbehind = newest_selection
4011 .start
4012 .text_anchor
4013 .to_offset(buffer)
4014 .saturating_sub(old_range.start);
4015 let lookahead = old_range
4016 .end
4017 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4018 let mut common_prefix_len = old_text
4019 .bytes()
4020 .zip(text.bytes())
4021 .take_while(|(a, b)| a == b)
4022 .count();
4023
4024 let snapshot = self.buffer.read(cx).snapshot(cx);
4025 let mut range_to_replace: Option<Range<isize>> = None;
4026 let mut ranges = Vec::new();
4027 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4028 for selection in &selections {
4029 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4030 let start = selection.start.saturating_sub(lookbehind);
4031 let end = selection.end + lookahead;
4032 if selection.id == newest_selection.id {
4033 range_to_replace = Some(
4034 ((start + common_prefix_len) as isize - selection.start as isize)
4035 ..(end as isize - selection.start as isize),
4036 );
4037 }
4038 ranges.push(start + common_prefix_len..end);
4039 } else {
4040 common_prefix_len = 0;
4041 ranges.clear();
4042 ranges.extend(selections.iter().map(|s| {
4043 if s.id == newest_selection.id {
4044 range_to_replace = Some(
4045 old_range.start.to_offset_utf16(&snapshot).0 as isize
4046 - selection.start as isize
4047 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4048 - selection.start as isize,
4049 );
4050 old_range.clone()
4051 } else {
4052 s.start..s.end
4053 }
4054 }));
4055 break;
4056 }
4057 if !self.linked_edit_ranges.is_empty() {
4058 let start_anchor = snapshot.anchor_before(selection.head());
4059 let end_anchor = snapshot.anchor_after(selection.tail());
4060 if let Some(ranges) = self
4061 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4062 {
4063 for (buffer, edits) in ranges {
4064 linked_edits.entry(buffer.clone()).or_default().extend(
4065 edits
4066 .into_iter()
4067 .map(|range| (range, text[common_prefix_len..].to_owned())),
4068 );
4069 }
4070 }
4071 }
4072 }
4073 let text = &text[common_prefix_len..];
4074
4075 cx.emit(EditorEvent::InputHandled {
4076 utf16_range_to_replace: range_to_replace,
4077 text: text.into(),
4078 });
4079
4080 self.transact(window, cx, |this, window, cx| {
4081 if let Some(mut snippet) = snippet {
4082 snippet.text = text.to_string();
4083 for tabstop in snippet
4084 .tabstops
4085 .iter_mut()
4086 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4087 {
4088 tabstop.start -= common_prefix_len as isize;
4089 tabstop.end -= common_prefix_len as isize;
4090 }
4091
4092 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4093 } else {
4094 this.buffer.update(cx, |buffer, cx| {
4095 buffer.edit(
4096 ranges.iter().map(|range| (range.clone(), text)),
4097 this.autoindent_mode.clone(),
4098 cx,
4099 );
4100 });
4101 }
4102 for (buffer, edits) in linked_edits {
4103 buffer.update(cx, |buffer, cx| {
4104 let snapshot = buffer.snapshot();
4105 let edits = edits
4106 .into_iter()
4107 .map(|(range, text)| {
4108 use text::ToPoint as TP;
4109 let end_point = TP::to_point(&range.end, &snapshot);
4110 let start_point = TP::to_point(&range.start, &snapshot);
4111 (start_point..end_point, text)
4112 })
4113 .sorted_by_key(|(range, _)| range.start)
4114 .collect::<Vec<_>>();
4115 buffer.edit(edits, None, cx);
4116 })
4117 }
4118
4119 this.refresh_inline_completion(true, false, window, cx);
4120 });
4121
4122 let show_new_completions_on_confirm = completion
4123 .confirm
4124 .as_ref()
4125 .map_or(false, |confirm| confirm(intent, window, cx));
4126 if show_new_completions_on_confirm {
4127 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4128 }
4129
4130 let provider = self.completion_provider.as_ref()?;
4131 drop(completion);
4132 let apply_edits = provider.apply_additional_edits_for_completion(
4133 buffer_handle,
4134 completions_menu.completions.clone(),
4135 candidate_id,
4136 true,
4137 cx,
4138 );
4139
4140 let editor_settings = EditorSettings::get_global(cx);
4141 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4142 // After the code completion is finished, users often want to know what signatures are needed.
4143 // so we should automatically call signature_help
4144 self.show_signature_help(&ShowSignatureHelp, window, cx);
4145 }
4146
4147 Some(cx.foreground_executor().spawn(async move {
4148 apply_edits.await?;
4149 Ok(())
4150 }))
4151 }
4152
4153 pub fn toggle_code_actions(
4154 &mut self,
4155 action: &ToggleCodeActions,
4156 window: &mut Window,
4157 cx: &mut Context<Self>,
4158 ) {
4159 let mut context_menu = self.context_menu.borrow_mut();
4160 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4161 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4162 // Toggle if we're selecting the same one
4163 *context_menu = None;
4164 cx.notify();
4165 return;
4166 } else {
4167 // Otherwise, clear it and start a new one
4168 *context_menu = None;
4169 cx.notify();
4170 }
4171 }
4172 drop(context_menu);
4173 let snapshot = self.snapshot(window, cx);
4174 let deployed_from_indicator = action.deployed_from_indicator;
4175 let mut task = self.code_actions_task.take();
4176 let action = action.clone();
4177 cx.spawn_in(window, |editor, mut cx| async move {
4178 while let Some(prev_task) = task {
4179 prev_task.await.log_err();
4180 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4181 }
4182
4183 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4184 if editor.focus_handle.is_focused(window) {
4185 let multibuffer_point = action
4186 .deployed_from_indicator
4187 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4188 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4189 let (buffer, buffer_row) = snapshot
4190 .buffer_snapshot
4191 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4192 .and_then(|(buffer_snapshot, range)| {
4193 editor
4194 .buffer
4195 .read(cx)
4196 .buffer(buffer_snapshot.remote_id())
4197 .map(|buffer| (buffer, range.start.row))
4198 })?;
4199 let (_, code_actions) = editor
4200 .available_code_actions
4201 .clone()
4202 .and_then(|(location, code_actions)| {
4203 let snapshot = location.buffer.read(cx).snapshot();
4204 let point_range = location.range.to_point(&snapshot);
4205 let point_range = point_range.start.row..=point_range.end.row;
4206 if point_range.contains(&buffer_row) {
4207 Some((location, code_actions))
4208 } else {
4209 None
4210 }
4211 })
4212 .unzip();
4213 let buffer_id = buffer.read(cx).remote_id();
4214 let tasks = editor
4215 .tasks
4216 .get(&(buffer_id, buffer_row))
4217 .map(|t| Arc::new(t.to_owned()));
4218 if tasks.is_none() && code_actions.is_none() {
4219 return None;
4220 }
4221
4222 editor.completion_tasks.clear();
4223 editor.discard_inline_completion(false, cx);
4224 let task_context =
4225 tasks
4226 .as_ref()
4227 .zip(editor.project.clone())
4228 .map(|(tasks, project)| {
4229 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4230 });
4231
4232 Some(cx.spawn_in(window, |editor, mut cx| async move {
4233 let task_context = match task_context {
4234 Some(task_context) => task_context.await,
4235 None => None,
4236 };
4237 let resolved_tasks =
4238 tasks.zip(task_context).map(|(tasks, task_context)| {
4239 Rc::new(ResolvedTasks {
4240 templates: tasks.resolve(&task_context).collect(),
4241 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4242 multibuffer_point.row,
4243 tasks.column,
4244 )),
4245 })
4246 });
4247 let spawn_straight_away = resolved_tasks
4248 .as_ref()
4249 .map_or(false, |tasks| tasks.templates.len() == 1)
4250 && code_actions
4251 .as_ref()
4252 .map_or(true, |actions| actions.is_empty());
4253 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4254 *editor.context_menu.borrow_mut() =
4255 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4256 buffer,
4257 actions: CodeActionContents {
4258 tasks: resolved_tasks,
4259 actions: code_actions,
4260 },
4261 selected_item: Default::default(),
4262 scroll_handle: UniformListScrollHandle::default(),
4263 deployed_from_indicator,
4264 }));
4265 if spawn_straight_away {
4266 if let Some(task) = editor.confirm_code_action(
4267 &ConfirmCodeAction { item_ix: Some(0) },
4268 window,
4269 cx,
4270 ) {
4271 cx.notify();
4272 return task;
4273 }
4274 }
4275 cx.notify();
4276 Task::ready(Ok(()))
4277 }) {
4278 task.await
4279 } else {
4280 Ok(())
4281 }
4282 }))
4283 } else {
4284 Some(Task::ready(Ok(())))
4285 }
4286 })?;
4287 if let Some(task) = spawned_test_task {
4288 task.await?;
4289 }
4290
4291 Ok::<_, anyhow::Error>(())
4292 })
4293 .detach_and_log_err(cx);
4294 }
4295
4296 pub fn confirm_code_action(
4297 &mut self,
4298 action: &ConfirmCodeAction,
4299 window: &mut Window,
4300 cx: &mut Context<Self>,
4301 ) -> Option<Task<Result<()>>> {
4302 let actions_menu =
4303 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4304 menu
4305 } else {
4306 return None;
4307 };
4308 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4309 let action = actions_menu.actions.get(action_ix)?;
4310 let title = action.label();
4311 let buffer = actions_menu.buffer;
4312 let workspace = self.workspace()?;
4313
4314 match action {
4315 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4316 workspace.update(cx, |workspace, cx| {
4317 workspace::tasks::schedule_resolved_task(
4318 workspace,
4319 task_source_kind,
4320 resolved_task,
4321 false,
4322 cx,
4323 );
4324
4325 Some(Task::ready(Ok(())))
4326 })
4327 }
4328 CodeActionsItem::CodeAction {
4329 excerpt_id,
4330 action,
4331 provider,
4332 } => {
4333 let apply_code_action =
4334 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4335 let workspace = workspace.downgrade();
4336 Some(cx.spawn_in(window, |editor, cx| async move {
4337 let project_transaction = apply_code_action.await?;
4338 Self::open_project_transaction(
4339 &editor,
4340 workspace,
4341 project_transaction,
4342 title,
4343 cx,
4344 )
4345 .await
4346 }))
4347 }
4348 }
4349 }
4350
4351 pub async fn open_project_transaction(
4352 this: &WeakEntity<Editor>,
4353 workspace: WeakEntity<Workspace>,
4354 transaction: ProjectTransaction,
4355 title: String,
4356 mut cx: AsyncWindowContext,
4357 ) -> Result<()> {
4358 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4359 cx.update(|_, cx| {
4360 entries.sort_unstable_by_key(|(buffer, _)| {
4361 buffer.read(cx).file().map(|f| f.path().clone())
4362 });
4363 })?;
4364
4365 // If the project transaction's edits are all contained within this editor, then
4366 // avoid opening a new editor to display them.
4367
4368 if let Some((buffer, transaction)) = entries.first() {
4369 if entries.len() == 1 {
4370 let excerpt = this.update(&mut cx, |editor, cx| {
4371 editor
4372 .buffer()
4373 .read(cx)
4374 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4375 })?;
4376 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4377 if excerpted_buffer == *buffer {
4378 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4379 let excerpt_range = excerpt_range.to_offset(buffer);
4380 buffer
4381 .edited_ranges_for_transaction::<usize>(transaction)
4382 .all(|range| {
4383 excerpt_range.start <= range.start
4384 && excerpt_range.end >= range.end
4385 })
4386 })?;
4387
4388 if all_edits_within_excerpt {
4389 return Ok(());
4390 }
4391 }
4392 }
4393 }
4394 } else {
4395 return Ok(());
4396 }
4397
4398 let mut ranges_to_highlight = Vec::new();
4399 let excerpt_buffer = cx.new(|cx| {
4400 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4401 for (buffer_handle, transaction) in &entries {
4402 let buffer = buffer_handle.read(cx);
4403 ranges_to_highlight.extend(
4404 multibuffer.push_excerpts_with_context_lines(
4405 buffer_handle.clone(),
4406 buffer
4407 .edited_ranges_for_transaction::<usize>(transaction)
4408 .collect(),
4409 DEFAULT_MULTIBUFFER_CONTEXT,
4410 cx,
4411 ),
4412 );
4413 }
4414 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4415 multibuffer
4416 })?;
4417
4418 workspace.update_in(&mut cx, |workspace, window, cx| {
4419 let project = workspace.project().clone();
4420 let editor = cx
4421 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4422 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4423 editor.update(cx, |editor, cx| {
4424 editor.highlight_background::<Self>(
4425 &ranges_to_highlight,
4426 |theme| theme.editor_highlighted_line_background,
4427 cx,
4428 );
4429 });
4430 })?;
4431
4432 Ok(())
4433 }
4434
4435 pub fn clear_code_action_providers(&mut self) {
4436 self.code_action_providers.clear();
4437 self.available_code_actions.take();
4438 }
4439
4440 pub fn add_code_action_provider(
4441 &mut self,
4442 provider: Rc<dyn CodeActionProvider>,
4443 window: &mut Window,
4444 cx: &mut Context<Self>,
4445 ) {
4446 if self
4447 .code_action_providers
4448 .iter()
4449 .any(|existing_provider| existing_provider.id() == provider.id())
4450 {
4451 return;
4452 }
4453
4454 self.code_action_providers.push(provider);
4455 self.refresh_code_actions(window, cx);
4456 }
4457
4458 pub fn remove_code_action_provider(
4459 &mut self,
4460 id: Arc<str>,
4461 window: &mut Window,
4462 cx: &mut Context<Self>,
4463 ) {
4464 self.code_action_providers
4465 .retain(|provider| provider.id() != id);
4466 self.refresh_code_actions(window, cx);
4467 }
4468
4469 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4470 let buffer = self.buffer.read(cx);
4471 let newest_selection = self.selections.newest_anchor().clone();
4472 if newest_selection.head().diff_base_anchor.is_some() {
4473 return None;
4474 }
4475 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4476 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4477 if start_buffer != end_buffer {
4478 return None;
4479 }
4480
4481 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4482 cx.background_executor()
4483 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4484 .await;
4485
4486 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4487 let providers = this.code_action_providers.clone();
4488 let tasks = this
4489 .code_action_providers
4490 .iter()
4491 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4492 .collect::<Vec<_>>();
4493 (providers, tasks)
4494 })?;
4495
4496 let mut actions = Vec::new();
4497 for (provider, provider_actions) in
4498 providers.into_iter().zip(future::join_all(tasks).await)
4499 {
4500 if let Some(provider_actions) = provider_actions.log_err() {
4501 actions.extend(provider_actions.into_iter().map(|action| {
4502 AvailableCodeAction {
4503 excerpt_id: newest_selection.start.excerpt_id,
4504 action,
4505 provider: provider.clone(),
4506 }
4507 }));
4508 }
4509 }
4510
4511 this.update(&mut cx, |this, cx| {
4512 this.available_code_actions = if actions.is_empty() {
4513 None
4514 } else {
4515 Some((
4516 Location {
4517 buffer: start_buffer,
4518 range: start..end,
4519 },
4520 actions.into(),
4521 ))
4522 };
4523 cx.notify();
4524 })
4525 }));
4526 None
4527 }
4528
4529 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4530 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4531 self.show_git_blame_inline = false;
4532
4533 self.show_git_blame_inline_delay_task =
4534 Some(cx.spawn_in(window, |this, mut cx| async move {
4535 cx.background_executor().timer(delay).await;
4536
4537 this.update(&mut cx, |this, cx| {
4538 this.show_git_blame_inline = true;
4539 cx.notify();
4540 })
4541 .log_err();
4542 }));
4543 }
4544 }
4545
4546 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4547 if self.pending_rename.is_some() {
4548 return None;
4549 }
4550
4551 let provider = self.semantics_provider.clone()?;
4552 let buffer = self.buffer.read(cx);
4553 let newest_selection = self.selections.newest_anchor().clone();
4554 let cursor_position = newest_selection.head();
4555 let (cursor_buffer, cursor_buffer_position) =
4556 buffer.text_anchor_for_position(cursor_position, cx)?;
4557 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4558 if cursor_buffer != tail_buffer {
4559 return None;
4560 }
4561 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4562 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4563 cx.background_executor()
4564 .timer(Duration::from_millis(debounce))
4565 .await;
4566
4567 let highlights = if let Some(highlights) = cx
4568 .update(|cx| {
4569 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4570 })
4571 .ok()
4572 .flatten()
4573 {
4574 highlights.await.log_err()
4575 } else {
4576 None
4577 };
4578
4579 if let Some(highlights) = highlights {
4580 this.update(&mut cx, |this, cx| {
4581 if this.pending_rename.is_some() {
4582 return;
4583 }
4584
4585 let buffer_id = cursor_position.buffer_id;
4586 let buffer = this.buffer.read(cx);
4587 if !buffer
4588 .text_anchor_for_position(cursor_position, cx)
4589 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4590 {
4591 return;
4592 }
4593
4594 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4595 let mut write_ranges = Vec::new();
4596 let mut read_ranges = Vec::new();
4597 for highlight in highlights {
4598 for (excerpt_id, excerpt_range) in
4599 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4600 {
4601 let start = highlight
4602 .range
4603 .start
4604 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4605 let end = highlight
4606 .range
4607 .end
4608 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4609 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4610 continue;
4611 }
4612
4613 let range = Anchor {
4614 buffer_id,
4615 excerpt_id,
4616 text_anchor: start,
4617 diff_base_anchor: None,
4618 }..Anchor {
4619 buffer_id,
4620 excerpt_id,
4621 text_anchor: end,
4622 diff_base_anchor: None,
4623 };
4624 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4625 write_ranges.push(range);
4626 } else {
4627 read_ranges.push(range);
4628 }
4629 }
4630 }
4631
4632 this.highlight_background::<DocumentHighlightRead>(
4633 &read_ranges,
4634 |theme| theme.editor_document_highlight_read_background,
4635 cx,
4636 );
4637 this.highlight_background::<DocumentHighlightWrite>(
4638 &write_ranges,
4639 |theme| theme.editor_document_highlight_write_background,
4640 cx,
4641 );
4642 cx.notify();
4643 })
4644 .log_err();
4645 }
4646 }));
4647 None
4648 }
4649
4650 pub fn refresh_inline_completion(
4651 &mut self,
4652 debounce: bool,
4653 user_requested: bool,
4654 window: &mut Window,
4655 cx: &mut Context<Self>,
4656 ) -> Option<()> {
4657 let provider = self.edit_prediction_provider()?;
4658 let cursor = self.selections.newest_anchor().head();
4659 let (buffer, cursor_buffer_position) =
4660 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4661
4662 if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4663 self.discard_inline_completion(false, cx);
4664 return None;
4665 }
4666
4667 if !user_requested
4668 && (!self.should_show_inline_completions_in_buffer(&buffer, cursor_buffer_position, cx)
4669 || !self.is_focused(window)
4670 || buffer.read(cx).is_empty())
4671 {
4672 self.discard_inline_completion(false, cx);
4673 return None;
4674 }
4675
4676 self.update_visible_inline_completion(window, cx);
4677 provider.refresh(
4678 self.project.clone(),
4679 buffer,
4680 cursor_buffer_position,
4681 debounce,
4682 cx,
4683 );
4684 Some(())
4685 }
4686
4687 pub fn should_show_inline_completions(&self, cx: &App) -> bool {
4688 let cursor = self.selections.newest_anchor().head();
4689 if let Some((buffer, cursor_position)) =
4690 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4691 {
4692 self.should_show_inline_completions_in_buffer(&buffer, cursor_position, cx)
4693 } else {
4694 false
4695 }
4696 }
4697
4698 fn edit_prediction_requires_modifier(&self, cx: &App) -> bool {
4699 let cursor = self.selections.newest_anchor().head();
4700
4701 self.buffer
4702 .read(cx)
4703 .text_anchor_for_position(cursor, cx)
4704 .map(|(buffer, _)| {
4705 all_language_settings(buffer.read(cx).file(), cx).inline_completions_preview_mode()
4706 == InlineCompletionPreviewMode::WhenHoldingModifier
4707 })
4708 .unwrap_or(false)
4709 }
4710
4711 fn should_show_inline_completions_in_buffer(
4712 &self,
4713 buffer: &Entity<Buffer>,
4714 buffer_position: language::Anchor,
4715 cx: &App,
4716 ) -> bool {
4717 if !self.snippet_stack.is_empty() {
4718 return false;
4719 }
4720
4721 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
4722 return false;
4723 }
4724
4725 if let Some(show_inline_completions) = self.show_inline_completions_override {
4726 show_inline_completions
4727 } else {
4728 let buffer = buffer.read(cx);
4729 self.mode == EditorMode::Full
4730 && language_settings(
4731 buffer.language_at(buffer_position).map(|l| l.name()),
4732 buffer.file(),
4733 cx,
4734 )
4735 .show_edit_predictions
4736 }
4737 }
4738
4739 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
4740 let cursor = self.selections.newest_anchor().head();
4741 if let Some((buffer, cursor_position)) =
4742 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4743 {
4744 self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
4745 } else {
4746 false
4747 }
4748 }
4749
4750 fn inline_completions_enabled_in_buffer(
4751 &self,
4752 buffer: &Entity<Buffer>,
4753 buffer_position: language::Anchor,
4754 cx: &App,
4755 ) -> bool {
4756 maybe!({
4757 let provider = self.edit_prediction_provider()?;
4758 if !provider.is_enabled(&buffer, buffer_position, cx) {
4759 return Some(false);
4760 }
4761 let buffer = buffer.read(cx);
4762 let Some(file) = buffer.file() else {
4763 return Some(true);
4764 };
4765 let settings = all_language_settings(Some(file), cx);
4766 Some(settings.inline_completions_enabled_for_path(file.path()))
4767 })
4768 .unwrap_or(false)
4769 }
4770
4771 fn cycle_inline_completion(
4772 &mut self,
4773 direction: Direction,
4774 window: &mut Window,
4775 cx: &mut Context<Self>,
4776 ) -> Option<()> {
4777 let provider = self.edit_prediction_provider()?;
4778 let cursor = self.selections.newest_anchor().head();
4779 let (buffer, cursor_buffer_position) =
4780 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4781 if self.inline_completions_hidden_for_vim_mode
4782 || !self.should_show_inline_completions_in_buffer(&buffer, cursor_buffer_position, cx)
4783 {
4784 return None;
4785 }
4786
4787 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4788 self.update_visible_inline_completion(window, cx);
4789
4790 Some(())
4791 }
4792
4793 pub fn show_inline_completion(
4794 &mut self,
4795 _: &ShowEditPrediction,
4796 window: &mut Window,
4797 cx: &mut Context<Self>,
4798 ) {
4799 if !self.has_active_inline_completion() {
4800 self.refresh_inline_completion(false, true, window, cx);
4801 return;
4802 }
4803
4804 self.update_visible_inline_completion(window, cx);
4805 }
4806
4807 pub fn display_cursor_names(
4808 &mut self,
4809 _: &DisplayCursorNames,
4810 window: &mut Window,
4811 cx: &mut Context<Self>,
4812 ) {
4813 self.show_cursor_names(window, cx);
4814 }
4815
4816 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4817 self.show_cursor_names = true;
4818 cx.notify();
4819 cx.spawn_in(window, |this, mut cx| async move {
4820 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4821 this.update(&mut cx, |this, cx| {
4822 this.show_cursor_names = false;
4823 cx.notify()
4824 })
4825 .ok()
4826 })
4827 .detach();
4828 }
4829
4830 pub fn next_edit_prediction(
4831 &mut self,
4832 _: &NextEditPrediction,
4833 window: &mut Window,
4834 cx: &mut Context<Self>,
4835 ) {
4836 if self.has_active_inline_completion() {
4837 self.cycle_inline_completion(Direction::Next, window, cx);
4838 } else {
4839 let is_copilot_disabled = self
4840 .refresh_inline_completion(false, true, window, cx)
4841 .is_none();
4842 if is_copilot_disabled {
4843 cx.propagate();
4844 }
4845 }
4846 }
4847
4848 pub fn previous_edit_prediction(
4849 &mut self,
4850 _: &PreviousEditPrediction,
4851 window: &mut Window,
4852 cx: &mut Context<Self>,
4853 ) {
4854 if self.has_active_inline_completion() {
4855 self.cycle_inline_completion(Direction::Prev, window, cx);
4856 } else {
4857 let is_copilot_disabled = self
4858 .refresh_inline_completion(false, true, window, cx)
4859 .is_none();
4860 if is_copilot_disabled {
4861 cx.propagate();
4862 }
4863 }
4864 }
4865
4866 pub fn accept_edit_prediction(
4867 &mut self,
4868 _: &AcceptEditPrediction,
4869 window: &mut Window,
4870 cx: &mut Context<Self>,
4871 ) {
4872 let buffer = self.buffer.read(cx);
4873 let snapshot = buffer.snapshot(cx);
4874 let selection = self.selections.newest_adjusted(cx);
4875 let cursor = selection.head();
4876 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
4877 let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
4878 if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
4879 {
4880 if cursor.column < suggested_indent.len
4881 && cursor.column <= current_indent.len
4882 && current_indent.len <= suggested_indent.len
4883 {
4884 self.tab(&Default::default(), window, cx);
4885 return;
4886 }
4887 }
4888
4889 if self.show_edit_predictions_in_menu(cx) {
4890 self.hide_context_menu(window, cx);
4891 }
4892
4893 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4894 return;
4895 };
4896
4897 self.report_inline_completion_event(
4898 active_inline_completion.completion_id.clone(),
4899 true,
4900 cx,
4901 );
4902
4903 match &active_inline_completion.completion {
4904 InlineCompletion::Move { target, .. } => {
4905 let target = *target;
4906 // Note that this is also done in vim's handler of the Tab action.
4907 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
4908 selections.select_anchor_ranges([target..target]);
4909 });
4910 }
4911 InlineCompletion::Edit { edits, .. } => {
4912 if let Some(provider) = self.edit_prediction_provider() {
4913 provider.accept(cx);
4914 }
4915
4916 let snapshot = self.buffer.read(cx).snapshot(cx);
4917 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4918
4919 self.buffer.update(cx, |buffer, cx| {
4920 buffer.edit(edits.iter().cloned(), None, cx)
4921 });
4922
4923 self.change_selections(None, window, cx, |s| {
4924 s.select_anchor_ranges([last_edit_end..last_edit_end])
4925 });
4926
4927 self.update_visible_inline_completion(window, cx);
4928 if self.active_inline_completion.is_none() {
4929 self.refresh_inline_completion(true, true, window, cx);
4930 }
4931
4932 cx.notify();
4933 }
4934 }
4935 }
4936
4937 pub fn accept_partial_inline_completion(
4938 &mut self,
4939 _: &AcceptPartialEditPrediction,
4940 window: &mut Window,
4941 cx: &mut Context<Self>,
4942 ) {
4943 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4944 return;
4945 };
4946 if self.selections.count() != 1 {
4947 return;
4948 }
4949
4950 self.report_inline_completion_event(
4951 active_inline_completion.completion_id.clone(),
4952 true,
4953 cx,
4954 );
4955
4956 match &active_inline_completion.completion {
4957 InlineCompletion::Move { target, .. } => {
4958 let target = *target;
4959 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
4960 selections.select_anchor_ranges([target..target]);
4961 });
4962 }
4963 InlineCompletion::Edit { edits, .. } => {
4964 // Find an insertion that starts at the cursor position.
4965 let snapshot = self.buffer.read(cx).snapshot(cx);
4966 let cursor_offset = self.selections.newest::<usize>(cx).head();
4967 let insertion = edits.iter().find_map(|(range, text)| {
4968 let range = range.to_offset(&snapshot);
4969 if range.is_empty() && range.start == cursor_offset {
4970 Some(text)
4971 } else {
4972 None
4973 }
4974 });
4975
4976 if let Some(text) = insertion {
4977 let mut partial_completion = text
4978 .chars()
4979 .by_ref()
4980 .take_while(|c| c.is_alphabetic())
4981 .collect::<String>();
4982 if partial_completion.is_empty() {
4983 partial_completion = text
4984 .chars()
4985 .by_ref()
4986 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4987 .collect::<String>();
4988 }
4989
4990 cx.emit(EditorEvent::InputHandled {
4991 utf16_range_to_replace: None,
4992 text: partial_completion.clone().into(),
4993 });
4994
4995 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
4996
4997 self.refresh_inline_completion(true, true, window, cx);
4998 cx.notify();
4999 } else {
5000 self.accept_edit_prediction(&Default::default(), window, cx);
5001 }
5002 }
5003 }
5004 }
5005
5006 fn discard_inline_completion(
5007 &mut self,
5008 should_report_inline_completion_event: bool,
5009 cx: &mut Context<Self>,
5010 ) -> bool {
5011 if should_report_inline_completion_event {
5012 let completion_id = self
5013 .active_inline_completion
5014 .as_ref()
5015 .and_then(|active_completion| active_completion.completion_id.clone());
5016
5017 self.report_inline_completion_event(completion_id, false, cx);
5018 }
5019
5020 if let Some(provider) = self.edit_prediction_provider() {
5021 provider.discard(cx);
5022 }
5023
5024 self.take_active_inline_completion(cx)
5025 }
5026
5027 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5028 let Some(provider) = self.edit_prediction_provider() else {
5029 return;
5030 };
5031
5032 let Some((_, buffer, _)) = self
5033 .buffer
5034 .read(cx)
5035 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5036 else {
5037 return;
5038 };
5039
5040 let extension = buffer
5041 .read(cx)
5042 .file()
5043 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5044
5045 let event_type = match accepted {
5046 true => "Edit Prediction Accepted",
5047 false => "Edit Prediction Discarded",
5048 };
5049 telemetry::event!(
5050 event_type,
5051 provider = provider.name(),
5052 prediction_id = id,
5053 suggestion_accepted = accepted,
5054 file_extension = extension,
5055 );
5056 }
5057
5058 pub fn has_active_inline_completion(&self) -> bool {
5059 self.active_inline_completion.is_some()
5060 }
5061
5062 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5063 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5064 return false;
5065 };
5066
5067 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5068 self.clear_highlights::<InlineCompletionHighlight>(cx);
5069 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5070 true
5071 }
5072
5073 /// Returns true when we're displaying the inline completion popover below the cursor
5074 /// like we are not previewing and the LSP autocomplete menu is visible
5075 /// or we are in `when_holding_modifier` mode.
5076 pub fn inline_completion_visible_in_cursor_popover(
5077 &self,
5078 has_completion: bool,
5079 cx: &App,
5080 ) -> bool {
5081 if self.previewing_inline_completion
5082 || !self.show_edit_predictions_in_menu(cx)
5083 || !self.should_show_inline_completions(cx)
5084 {
5085 return false;
5086 }
5087
5088 if self.has_visible_completions_menu() {
5089 return true;
5090 }
5091
5092 has_completion && self.edit_prediction_requires_modifier(cx)
5093 }
5094
5095 fn update_inline_completion_preview(
5096 &mut self,
5097 modifiers: &Modifiers,
5098 window: &mut Window,
5099 cx: &mut Context<Self>,
5100 ) {
5101 if !self.show_edit_predictions_in_menu(cx) {
5102 return;
5103 }
5104
5105 self.previewing_inline_completion = modifiers.alt;
5106 self.update_visible_inline_completion(window, cx);
5107 cx.notify();
5108 }
5109
5110 fn update_visible_inline_completion(
5111 &mut self,
5112 _window: &mut Window,
5113 cx: &mut Context<Self>,
5114 ) -> Option<()> {
5115 let selection = self.selections.newest_anchor();
5116 let cursor = selection.head();
5117 let multibuffer = self.buffer.read(cx).snapshot(cx);
5118 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5119 let excerpt_id = cursor.excerpt_id;
5120
5121 let show_in_menu = self.show_edit_predictions_in_menu(cx);
5122 let completions_menu_has_precedence = !show_in_menu
5123 && (self.context_menu.borrow().is_some()
5124 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5125 if completions_menu_has_precedence
5126 || !offset_selection.is_empty()
5127 || self
5128 .active_inline_completion
5129 .as_ref()
5130 .map_or(false, |completion| {
5131 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5132 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5133 !invalidation_range.contains(&offset_selection.head())
5134 })
5135 {
5136 self.discard_inline_completion(false, cx);
5137 return None;
5138 }
5139
5140 self.take_active_inline_completion(cx);
5141 let provider = self.edit_prediction_provider()?;
5142
5143 let (buffer, cursor_buffer_position) =
5144 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5145
5146 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5147 let edits = inline_completion
5148 .edits
5149 .into_iter()
5150 .flat_map(|(range, new_text)| {
5151 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5152 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5153 Some((start..end, new_text))
5154 })
5155 .collect::<Vec<_>>();
5156 if edits.is_empty() {
5157 return None;
5158 }
5159
5160 let first_edit_start = edits.first().unwrap().0.start;
5161 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5162 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5163
5164 let last_edit_end = edits.last().unwrap().0.end;
5165 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5166 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5167
5168 let cursor_row = cursor.to_point(&multibuffer).row;
5169
5170 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5171
5172 let mut inlay_ids = Vec::new();
5173 let invalidation_row_range;
5174 let move_invalidation_row_range = if cursor_row < edit_start_row {
5175 Some(cursor_row..edit_end_row)
5176 } else if cursor_row > edit_end_row {
5177 Some(edit_start_row..cursor_row)
5178 } else {
5179 None
5180 };
5181 let is_move =
5182 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5183 let completion = if is_move {
5184 invalidation_row_range =
5185 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5186 let target = first_edit_start;
5187 let target_point = text::ToPoint::to_point(&target.text_anchor, &snapshot);
5188 // TODO: Base this off of TreeSitter or word boundaries?
5189 let target_excerpt_begin = snapshot.anchor_before(snapshot.clip_point(
5190 Point::new(target_point.row, target_point.column.saturating_sub(20)),
5191 Bias::Left,
5192 ));
5193 let target_excerpt_end = snapshot.anchor_after(snapshot.clip_point(
5194 Point::new(target_point.row, target_point.column + 20),
5195 Bias::Right,
5196 ));
5197 let range_around_target = target_excerpt_begin..target_excerpt_end;
5198 InlineCompletion::Move {
5199 target,
5200 range_around_target,
5201 snapshot,
5202 }
5203 } else {
5204 let show_completions_in_buffer = !self
5205 .inline_completion_visible_in_cursor_popover(true, cx)
5206 && !self.inline_completions_hidden_for_vim_mode;
5207 if show_completions_in_buffer {
5208 if edits
5209 .iter()
5210 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5211 {
5212 let mut inlays = Vec::new();
5213 for (range, new_text) in &edits {
5214 let inlay = Inlay::inline_completion(
5215 post_inc(&mut self.next_inlay_id),
5216 range.start,
5217 new_text.as_str(),
5218 );
5219 inlay_ids.push(inlay.id);
5220 inlays.push(inlay);
5221 }
5222
5223 self.splice_inlays(&[], inlays, cx);
5224 } else {
5225 let background_color = cx.theme().status().deleted_background;
5226 self.highlight_text::<InlineCompletionHighlight>(
5227 edits.iter().map(|(range, _)| range.clone()).collect(),
5228 HighlightStyle {
5229 background_color: Some(background_color),
5230 ..Default::default()
5231 },
5232 cx,
5233 );
5234 }
5235 }
5236
5237 invalidation_row_range = edit_start_row..edit_end_row;
5238
5239 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5240 if provider.show_tab_accept_marker() {
5241 EditDisplayMode::TabAccept
5242 } else {
5243 EditDisplayMode::Inline
5244 }
5245 } else {
5246 EditDisplayMode::DiffPopover
5247 };
5248
5249 InlineCompletion::Edit {
5250 edits,
5251 edit_preview: inline_completion.edit_preview,
5252 display_mode,
5253 snapshot,
5254 }
5255 };
5256
5257 let invalidation_range = multibuffer
5258 .anchor_before(Point::new(invalidation_row_range.start, 0))
5259 ..multibuffer.anchor_after(Point::new(
5260 invalidation_row_range.end,
5261 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5262 ));
5263
5264 self.stale_inline_completion_in_menu = None;
5265 self.active_inline_completion = Some(InlineCompletionState {
5266 inlay_ids,
5267 completion,
5268 completion_id: inline_completion.id,
5269 invalidation_range,
5270 });
5271
5272 cx.notify();
5273
5274 Some(())
5275 }
5276
5277 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5278 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5279 }
5280
5281 fn show_edit_predictions_in_menu(&self, cx: &App) -> bool {
5282 let by_provider = matches!(
5283 self.menu_inline_completions_policy,
5284 MenuInlineCompletionsPolicy::ByProvider
5285 );
5286
5287 by_provider
5288 && EditorSettings::get_global(cx).show_edit_predictions_in_menu
5289 && self
5290 .edit_prediction_provider()
5291 .map_or(false, |provider| provider.show_completions_in_menu())
5292 }
5293
5294 fn render_code_actions_indicator(
5295 &self,
5296 _style: &EditorStyle,
5297 row: DisplayRow,
5298 is_active: bool,
5299 cx: &mut Context<Self>,
5300 ) -> Option<IconButton> {
5301 if self.available_code_actions.is_some() {
5302 Some(
5303 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5304 .shape(ui::IconButtonShape::Square)
5305 .icon_size(IconSize::XSmall)
5306 .icon_color(Color::Muted)
5307 .toggle_state(is_active)
5308 .tooltip({
5309 let focus_handle = self.focus_handle.clone();
5310 move |window, cx| {
5311 Tooltip::for_action_in(
5312 "Toggle Code Actions",
5313 &ToggleCodeActions {
5314 deployed_from_indicator: None,
5315 },
5316 &focus_handle,
5317 window,
5318 cx,
5319 )
5320 }
5321 })
5322 .on_click(cx.listener(move |editor, _e, window, cx| {
5323 window.focus(&editor.focus_handle(cx));
5324 editor.toggle_code_actions(
5325 &ToggleCodeActions {
5326 deployed_from_indicator: Some(row),
5327 },
5328 window,
5329 cx,
5330 );
5331 })),
5332 )
5333 } else {
5334 None
5335 }
5336 }
5337
5338 fn clear_tasks(&mut self) {
5339 self.tasks.clear()
5340 }
5341
5342 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5343 if self.tasks.insert(key, value).is_some() {
5344 // This case should hopefully be rare, but just in case...
5345 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5346 }
5347 }
5348
5349 fn build_tasks_context(
5350 project: &Entity<Project>,
5351 buffer: &Entity<Buffer>,
5352 buffer_row: u32,
5353 tasks: &Arc<RunnableTasks>,
5354 cx: &mut Context<Self>,
5355 ) -> Task<Option<task::TaskContext>> {
5356 let position = Point::new(buffer_row, tasks.column);
5357 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5358 let location = Location {
5359 buffer: buffer.clone(),
5360 range: range_start..range_start,
5361 };
5362 // Fill in the environmental variables from the tree-sitter captures
5363 let mut captured_task_variables = TaskVariables::default();
5364 for (capture_name, value) in tasks.extra_variables.clone() {
5365 captured_task_variables.insert(
5366 task::VariableName::Custom(capture_name.into()),
5367 value.clone(),
5368 );
5369 }
5370 project.update(cx, |project, cx| {
5371 project.task_store().update(cx, |task_store, cx| {
5372 task_store.task_context_for_location(captured_task_variables, location, cx)
5373 })
5374 })
5375 }
5376
5377 pub fn spawn_nearest_task(
5378 &mut self,
5379 action: &SpawnNearestTask,
5380 window: &mut Window,
5381 cx: &mut Context<Self>,
5382 ) {
5383 let Some((workspace, _)) = self.workspace.clone() else {
5384 return;
5385 };
5386 let Some(project) = self.project.clone() else {
5387 return;
5388 };
5389
5390 // Try to find a closest, enclosing node using tree-sitter that has a
5391 // task
5392 let Some((buffer, buffer_row, tasks)) = self
5393 .find_enclosing_node_task(cx)
5394 // Or find the task that's closest in row-distance.
5395 .or_else(|| self.find_closest_task(cx))
5396 else {
5397 return;
5398 };
5399
5400 let reveal_strategy = action.reveal;
5401 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5402 cx.spawn_in(window, |_, mut cx| async move {
5403 let context = task_context.await?;
5404 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5405
5406 let resolved = resolved_task.resolved.as_mut()?;
5407 resolved.reveal = reveal_strategy;
5408
5409 workspace
5410 .update(&mut cx, |workspace, cx| {
5411 workspace::tasks::schedule_resolved_task(
5412 workspace,
5413 task_source_kind,
5414 resolved_task,
5415 false,
5416 cx,
5417 );
5418 })
5419 .ok()
5420 })
5421 .detach();
5422 }
5423
5424 fn find_closest_task(
5425 &mut self,
5426 cx: &mut Context<Self>,
5427 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5428 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5429
5430 let ((buffer_id, row), tasks) = self
5431 .tasks
5432 .iter()
5433 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5434
5435 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5436 let tasks = Arc::new(tasks.to_owned());
5437 Some((buffer, *row, tasks))
5438 }
5439
5440 fn find_enclosing_node_task(
5441 &mut self,
5442 cx: &mut Context<Self>,
5443 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5444 let snapshot = self.buffer.read(cx).snapshot(cx);
5445 let offset = self.selections.newest::<usize>(cx).head();
5446 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5447 let buffer_id = excerpt.buffer().remote_id();
5448
5449 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5450 let mut cursor = layer.node().walk();
5451
5452 while cursor.goto_first_child_for_byte(offset).is_some() {
5453 if cursor.node().end_byte() == offset {
5454 cursor.goto_next_sibling();
5455 }
5456 }
5457
5458 // Ascend to the smallest ancestor that contains the range and has a task.
5459 loop {
5460 let node = cursor.node();
5461 let node_range = node.byte_range();
5462 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5463
5464 // Check if this node contains our offset
5465 if node_range.start <= offset && node_range.end >= offset {
5466 // If it contains offset, check for task
5467 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5468 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5469 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5470 }
5471 }
5472
5473 if !cursor.goto_parent() {
5474 break;
5475 }
5476 }
5477 None
5478 }
5479
5480 fn render_run_indicator(
5481 &self,
5482 _style: &EditorStyle,
5483 is_active: bool,
5484 row: DisplayRow,
5485 cx: &mut Context<Self>,
5486 ) -> IconButton {
5487 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5488 .shape(ui::IconButtonShape::Square)
5489 .icon_size(IconSize::XSmall)
5490 .icon_color(Color::Muted)
5491 .toggle_state(is_active)
5492 .on_click(cx.listener(move |editor, _e, window, cx| {
5493 window.focus(&editor.focus_handle(cx));
5494 editor.toggle_code_actions(
5495 &ToggleCodeActions {
5496 deployed_from_indicator: Some(row),
5497 },
5498 window,
5499 cx,
5500 );
5501 }))
5502 }
5503
5504 pub fn context_menu_visible(&self) -> bool {
5505 !self.previewing_inline_completion
5506 && self
5507 .context_menu
5508 .borrow()
5509 .as_ref()
5510 .map_or(false, |menu| menu.visible())
5511 }
5512
5513 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5514 self.context_menu
5515 .borrow()
5516 .as_ref()
5517 .map(|menu| menu.origin())
5518 }
5519
5520 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5521 px(30.)
5522 }
5523
5524 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5525 if self.read_only(cx) {
5526 cx.theme().players().read_only()
5527 } else {
5528 self.style.as_ref().unwrap().local_player
5529 }
5530 }
5531
5532 #[allow(clippy::too_many_arguments)]
5533 fn render_edit_prediction_cursor_popover(
5534 &self,
5535 min_width: Pixels,
5536 max_width: Pixels,
5537 cursor_point: Point,
5538 style: &EditorStyle,
5539 accept_keystroke: &gpui::Keystroke,
5540 window: &Window,
5541 cx: &mut Context<Editor>,
5542 ) -> Option<AnyElement> {
5543 let provider = self.edit_prediction_provider.as_ref()?;
5544
5545 if provider.provider.needs_terms_acceptance(cx) {
5546 return Some(
5547 h_flex()
5548 .h(self.edit_prediction_cursor_popover_height())
5549 .min_w(min_width)
5550 .flex_1()
5551 .px_2()
5552 .gap_3()
5553 .elevation_2(cx)
5554 .hover(|style| style.bg(cx.theme().colors().element_hover))
5555 .id("accept-terms")
5556 .cursor_pointer()
5557 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5558 .on_click(cx.listener(|this, _event, window, cx| {
5559 cx.stop_propagation();
5560 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
5561 window.dispatch_action(
5562 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
5563 cx,
5564 );
5565 }))
5566 .child(
5567 h_flex()
5568 .flex_1()
5569 .gap_2()
5570 .child(Icon::new(IconName::ZedPredict))
5571 .child(Label::new("Accept Terms of Service"))
5572 .child(div().w_full())
5573 .child(
5574 Icon::new(IconName::ArrowUpRight)
5575 .color(Color::Muted)
5576 .size(IconSize::Small),
5577 )
5578 .into_any_element(),
5579 )
5580 .into_any(),
5581 );
5582 }
5583
5584 let is_refreshing = provider.provider.is_refreshing(cx);
5585
5586 fn pending_completion_container() -> Div {
5587 h_flex()
5588 .h_full()
5589 .flex_1()
5590 .gap_2()
5591 .child(Icon::new(IconName::ZedPredict))
5592 }
5593
5594 let completion = match &self.active_inline_completion {
5595 Some(completion) => self.render_edit_prediction_cursor_popover_preview(
5596 completion,
5597 cursor_point,
5598 style,
5599 window,
5600 cx,
5601 )?,
5602
5603 None if is_refreshing => match &self.stale_inline_completion_in_menu {
5604 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
5605 stale_completion,
5606 cursor_point,
5607 style,
5608 window,
5609 cx,
5610 )?,
5611
5612 None => {
5613 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
5614 }
5615 },
5616
5617 None => pending_completion_container().child(Label::new("No Prediction")),
5618 };
5619
5620 let buffer_font = theme::ThemeSettings::get_global(cx).buffer_font.clone();
5621 let completion = completion.font(buffer_font.clone());
5622
5623 let completion = if is_refreshing {
5624 completion
5625 .with_animation(
5626 "loading-completion",
5627 Animation::new(Duration::from_secs(2))
5628 .repeat()
5629 .with_easing(pulsating_between(0.4, 0.8)),
5630 |label, delta| label.opacity(delta),
5631 )
5632 .into_any_element()
5633 } else {
5634 completion.into_any_element()
5635 };
5636
5637 let has_completion = self.active_inline_completion.is_some();
5638
5639 Some(
5640 h_flex()
5641 .h(self.edit_prediction_cursor_popover_height())
5642 .min_w(min_width)
5643 .max_w(max_width)
5644 .flex_1()
5645 .px_2()
5646 .elevation_2(cx)
5647 .child(completion)
5648 .child(ui::Divider::vertical())
5649 .child(
5650 h_flex()
5651 .h_full()
5652 .gap_1()
5653 .pl_2()
5654 .child(h_flex().font(buffer_font.clone()).gap_1().children(
5655 ui::render_modifiers(
5656 &accept_keystroke.modifiers,
5657 PlatformStyle::platform(),
5658 Some(if !has_completion {
5659 Color::Muted
5660 } else {
5661 Color::Default
5662 }),
5663 None,
5664 true,
5665 ),
5666 ))
5667 .child(Label::new("Preview").into_any_element())
5668 .opacity(if has_completion { 1.0 } else { 0.4 }),
5669 )
5670 .into_any(),
5671 )
5672 }
5673
5674 fn render_edit_prediction_cursor_popover_preview(
5675 &self,
5676 completion: &InlineCompletionState,
5677 cursor_point: Point,
5678 style: &EditorStyle,
5679 window: &Window,
5680 cx: &mut Context<Editor>,
5681 ) -> Option<Div> {
5682 use text::ToPoint as _;
5683
5684 fn render_relative_row_jump(
5685 prefix: impl Into<String>,
5686 current_row: u32,
5687 target_row: u32,
5688 ) -> Div {
5689 let (row_diff, arrow) = if target_row < current_row {
5690 (current_row - target_row, IconName::ArrowUp)
5691 } else {
5692 (target_row - current_row, IconName::ArrowDown)
5693 };
5694
5695 h_flex()
5696 .child(
5697 Label::new(format!("{}{}", prefix.into(), row_diff))
5698 .color(Color::Muted)
5699 .size(LabelSize::Small),
5700 )
5701 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
5702 }
5703
5704 match &completion.completion {
5705 InlineCompletion::Edit {
5706 edits,
5707 edit_preview,
5708 snapshot,
5709 display_mode: _,
5710 } => {
5711 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
5712
5713 let highlighted_edits = crate::inline_completion_edit_text(
5714 &snapshot,
5715 &edits,
5716 edit_preview.as_ref()?,
5717 true,
5718 cx,
5719 );
5720
5721 let len_total = highlighted_edits.text.len();
5722 let first_line = &highlighted_edits.text
5723 [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
5724 let first_line_len = first_line.len();
5725
5726 let first_highlight_start = highlighted_edits
5727 .highlights
5728 .first()
5729 .map_or(0, |(range, _)| range.start);
5730 let drop_prefix_len = first_line
5731 .char_indices()
5732 .find(|(_, c)| !c.is_whitespace())
5733 .map_or(first_highlight_start, |(ix, _)| {
5734 ix.min(first_highlight_start)
5735 });
5736
5737 let preview_text = &first_line[drop_prefix_len..];
5738 let preview_len = preview_text.len();
5739 let highlights = highlighted_edits
5740 .highlights
5741 .into_iter()
5742 .take_until(|(range, _)| range.start > first_line_len)
5743 .map(|(range, style)| {
5744 (
5745 range.start - drop_prefix_len
5746 ..(range.end - drop_prefix_len).min(preview_len),
5747 style,
5748 )
5749 });
5750
5751 let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
5752 .with_highlights(&style.text, highlights);
5753
5754 let preview = h_flex()
5755 .gap_1()
5756 .min_w_16()
5757 .child(styled_text)
5758 .when(len_total > first_line_len, |parent| parent.child("…"));
5759
5760 let left = if first_edit_row != cursor_point.row {
5761 render_relative_row_jump("", cursor_point.row, first_edit_row)
5762 .into_any_element()
5763 } else {
5764 Icon::new(IconName::ZedPredict).into_any_element()
5765 };
5766
5767 Some(
5768 h_flex()
5769 .h_full()
5770 .flex_1()
5771 .gap_2()
5772 .pr_1()
5773 .overflow_x_hidden()
5774 .child(left)
5775 .child(preview),
5776 )
5777 }
5778
5779 InlineCompletion::Move {
5780 target,
5781 range_around_target,
5782 snapshot,
5783 } => {
5784 let highlighted_text = snapshot.highlighted_text_for_range(
5785 range_around_target.clone(),
5786 None,
5787 &style.syntax,
5788 );
5789 let base = h_flex().gap_3().flex_1().child(render_relative_row_jump(
5790 "Jump ",
5791 cursor_point.row,
5792 target.text_anchor.to_point(&snapshot).row,
5793 ));
5794
5795 if highlighted_text.text.is_empty() {
5796 return Some(base);
5797 }
5798
5799 let cursor_color = self.current_user_player_color(cx).cursor;
5800
5801 let start_point = range_around_target.start.to_point(&snapshot);
5802 let end_point = range_around_target.end.to_point(&snapshot);
5803 let target_point = target.text_anchor.to_point(&snapshot);
5804
5805 let styled_text = highlighted_text.to_styled_text(&style.text);
5806 let text_len = highlighted_text.text.len();
5807
5808 let cursor_relative_position = window
5809 .text_system()
5810 .layout_line(
5811 highlighted_text.text,
5812 style.text.font_size.to_pixels(window.rem_size()),
5813 // We don't need to include highlights
5814 // because we are only using this for the cursor position
5815 &[TextRun {
5816 len: text_len,
5817 font: style.text.font(),
5818 color: style.text.color,
5819 background_color: None,
5820 underline: None,
5821 strikethrough: None,
5822 }],
5823 )
5824 .log_err()
5825 .map(|line| {
5826 line.x_for_index(
5827 target_point.column.saturating_sub(start_point.column) as usize
5828 )
5829 });
5830
5831 let fade_before = start_point.column > 0;
5832 let fade_after = end_point.column < snapshot.line_len(end_point.row);
5833
5834 let background = cx.theme().colors().elevated_surface_background;
5835
5836 let preview = h_flex()
5837 .relative()
5838 .child(styled_text)
5839 .when(fade_before, |parent| {
5840 parent.child(div().absolute().top_0().left_0().w_4().h_full().bg(
5841 linear_gradient(
5842 90.,
5843 linear_color_stop(background, 0.),
5844 linear_color_stop(background.opacity(0.), 1.),
5845 ),
5846 ))
5847 })
5848 .when(fade_after, |parent| {
5849 parent.child(div().absolute().top_0().right_0().w_4().h_full().bg(
5850 linear_gradient(
5851 -90.,
5852 linear_color_stop(background, 0.),
5853 linear_color_stop(background.opacity(0.), 1.),
5854 ),
5855 ))
5856 })
5857 .when_some(cursor_relative_position, |parent, position| {
5858 parent.child(
5859 div()
5860 .w(px(2.))
5861 .h_full()
5862 .bg(cursor_color)
5863 .absolute()
5864 .top_0()
5865 .left(position),
5866 )
5867 });
5868
5869 Some(base.child(preview))
5870 }
5871 }
5872 }
5873
5874 fn render_context_menu(
5875 &self,
5876 style: &EditorStyle,
5877 max_height_in_lines: u32,
5878 y_flipped: bool,
5879 window: &mut Window,
5880 cx: &mut Context<Editor>,
5881 ) -> Option<AnyElement> {
5882 let menu = self.context_menu.borrow();
5883 let menu = menu.as_ref()?;
5884 if !menu.visible() {
5885 return None;
5886 };
5887 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
5888 }
5889
5890 fn render_context_menu_aside(
5891 &self,
5892 style: &EditorStyle,
5893 max_size: Size<Pixels>,
5894 cx: &mut Context<Editor>,
5895 ) -> Option<AnyElement> {
5896 self.context_menu.borrow().as_ref().and_then(|menu| {
5897 if menu.visible() {
5898 menu.render_aside(
5899 style,
5900 max_size,
5901 self.workspace.as_ref().map(|(w, _)| w.clone()),
5902 cx,
5903 )
5904 } else {
5905 None
5906 }
5907 })
5908 }
5909
5910 fn hide_context_menu(
5911 &mut self,
5912 window: &mut Window,
5913 cx: &mut Context<Self>,
5914 ) -> Option<CodeContextMenu> {
5915 cx.notify();
5916 self.completion_tasks.clear();
5917 let context_menu = self.context_menu.borrow_mut().take();
5918 self.stale_inline_completion_in_menu.take();
5919 self.update_visible_inline_completion(window, cx);
5920 context_menu
5921 }
5922
5923 fn show_snippet_choices(
5924 &mut self,
5925 choices: &Vec<String>,
5926 selection: Range<Anchor>,
5927 cx: &mut Context<Self>,
5928 ) {
5929 if selection.start.buffer_id.is_none() {
5930 return;
5931 }
5932 let buffer_id = selection.start.buffer_id.unwrap();
5933 let buffer = self.buffer().read(cx).buffer(buffer_id);
5934 let id = post_inc(&mut self.next_completion_id);
5935
5936 if let Some(buffer) = buffer {
5937 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5938 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5939 ));
5940 }
5941 }
5942
5943 pub fn insert_snippet(
5944 &mut self,
5945 insertion_ranges: &[Range<usize>],
5946 snippet: Snippet,
5947 window: &mut Window,
5948 cx: &mut Context<Self>,
5949 ) -> Result<()> {
5950 struct Tabstop<T> {
5951 is_end_tabstop: bool,
5952 ranges: Vec<Range<T>>,
5953 choices: Option<Vec<String>>,
5954 }
5955
5956 let tabstops = self.buffer.update(cx, |buffer, cx| {
5957 let snippet_text: Arc<str> = snippet.text.clone().into();
5958 buffer.edit(
5959 insertion_ranges
5960 .iter()
5961 .cloned()
5962 .map(|range| (range, snippet_text.clone())),
5963 Some(AutoindentMode::EachLine),
5964 cx,
5965 );
5966
5967 let snapshot = &*buffer.read(cx);
5968 let snippet = &snippet;
5969 snippet
5970 .tabstops
5971 .iter()
5972 .map(|tabstop| {
5973 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5974 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5975 });
5976 let mut tabstop_ranges = tabstop
5977 .ranges
5978 .iter()
5979 .flat_map(|tabstop_range| {
5980 let mut delta = 0_isize;
5981 insertion_ranges.iter().map(move |insertion_range| {
5982 let insertion_start = insertion_range.start as isize + delta;
5983 delta +=
5984 snippet.text.len() as isize - insertion_range.len() as isize;
5985
5986 let start = ((insertion_start + tabstop_range.start) as usize)
5987 .min(snapshot.len());
5988 let end = ((insertion_start + tabstop_range.end) as usize)
5989 .min(snapshot.len());
5990 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5991 })
5992 })
5993 .collect::<Vec<_>>();
5994 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5995
5996 Tabstop {
5997 is_end_tabstop,
5998 ranges: tabstop_ranges,
5999 choices: tabstop.choices.clone(),
6000 }
6001 })
6002 .collect::<Vec<_>>()
6003 });
6004 if let Some(tabstop) = tabstops.first() {
6005 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6006 s.select_ranges(tabstop.ranges.iter().cloned());
6007 });
6008
6009 if let Some(choices) = &tabstop.choices {
6010 if let Some(selection) = tabstop.ranges.first() {
6011 self.show_snippet_choices(choices, selection.clone(), cx)
6012 }
6013 }
6014
6015 // If we're already at the last tabstop and it's at the end of the snippet,
6016 // we're done, we don't need to keep the state around.
6017 if !tabstop.is_end_tabstop {
6018 let choices = tabstops
6019 .iter()
6020 .map(|tabstop| tabstop.choices.clone())
6021 .collect();
6022
6023 let ranges = tabstops
6024 .into_iter()
6025 .map(|tabstop| tabstop.ranges)
6026 .collect::<Vec<_>>();
6027
6028 self.snippet_stack.push(SnippetState {
6029 active_index: 0,
6030 ranges,
6031 choices,
6032 });
6033 }
6034
6035 // Check whether the just-entered snippet ends with an auto-closable bracket.
6036 if self.autoclose_regions.is_empty() {
6037 let snapshot = self.buffer.read(cx).snapshot(cx);
6038 for selection in &mut self.selections.all::<Point>(cx) {
6039 let selection_head = selection.head();
6040 let Some(scope) = snapshot.language_scope_at(selection_head) else {
6041 continue;
6042 };
6043
6044 let mut bracket_pair = None;
6045 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
6046 let prev_chars = snapshot
6047 .reversed_chars_at(selection_head)
6048 .collect::<String>();
6049 for (pair, enabled) in scope.brackets() {
6050 if enabled
6051 && pair.close
6052 && prev_chars.starts_with(pair.start.as_str())
6053 && next_chars.starts_with(pair.end.as_str())
6054 {
6055 bracket_pair = Some(pair.clone());
6056 break;
6057 }
6058 }
6059 if let Some(pair) = bracket_pair {
6060 let start = snapshot.anchor_after(selection_head);
6061 let end = snapshot.anchor_after(selection_head);
6062 self.autoclose_regions.push(AutocloseRegion {
6063 selection_id: selection.id,
6064 range: start..end,
6065 pair,
6066 });
6067 }
6068 }
6069 }
6070 }
6071 Ok(())
6072 }
6073
6074 pub fn move_to_next_snippet_tabstop(
6075 &mut self,
6076 window: &mut Window,
6077 cx: &mut Context<Self>,
6078 ) -> bool {
6079 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6080 }
6081
6082 pub fn move_to_prev_snippet_tabstop(
6083 &mut self,
6084 window: &mut Window,
6085 cx: &mut Context<Self>,
6086 ) -> bool {
6087 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6088 }
6089
6090 pub fn move_to_snippet_tabstop(
6091 &mut self,
6092 bias: Bias,
6093 window: &mut Window,
6094 cx: &mut Context<Self>,
6095 ) -> bool {
6096 if let Some(mut snippet) = self.snippet_stack.pop() {
6097 match bias {
6098 Bias::Left => {
6099 if snippet.active_index > 0 {
6100 snippet.active_index -= 1;
6101 } else {
6102 self.snippet_stack.push(snippet);
6103 return false;
6104 }
6105 }
6106 Bias::Right => {
6107 if snippet.active_index + 1 < snippet.ranges.len() {
6108 snippet.active_index += 1;
6109 } else {
6110 self.snippet_stack.push(snippet);
6111 return false;
6112 }
6113 }
6114 }
6115 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6116 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6117 s.select_anchor_ranges(current_ranges.iter().cloned())
6118 });
6119
6120 if let Some(choices) = &snippet.choices[snippet.active_index] {
6121 if let Some(selection) = current_ranges.first() {
6122 self.show_snippet_choices(&choices, selection.clone(), cx);
6123 }
6124 }
6125
6126 // If snippet state is not at the last tabstop, push it back on the stack
6127 if snippet.active_index + 1 < snippet.ranges.len() {
6128 self.snippet_stack.push(snippet);
6129 }
6130 return true;
6131 }
6132 }
6133
6134 false
6135 }
6136
6137 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6138 self.transact(window, cx, |this, window, cx| {
6139 this.select_all(&SelectAll, window, cx);
6140 this.insert("", window, cx);
6141 });
6142 }
6143
6144 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6145 self.transact(window, cx, |this, window, cx| {
6146 this.select_autoclose_pair(window, cx);
6147 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6148 if !this.linked_edit_ranges.is_empty() {
6149 let selections = this.selections.all::<MultiBufferPoint>(cx);
6150 let snapshot = this.buffer.read(cx).snapshot(cx);
6151
6152 for selection in selections.iter() {
6153 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6154 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6155 if selection_start.buffer_id != selection_end.buffer_id {
6156 continue;
6157 }
6158 if let Some(ranges) =
6159 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6160 {
6161 for (buffer, entries) in ranges {
6162 linked_ranges.entry(buffer).or_default().extend(entries);
6163 }
6164 }
6165 }
6166 }
6167
6168 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6169 if !this.selections.line_mode {
6170 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6171 for selection in &mut selections {
6172 if selection.is_empty() {
6173 let old_head = selection.head();
6174 let mut new_head =
6175 movement::left(&display_map, old_head.to_display_point(&display_map))
6176 .to_point(&display_map);
6177 if let Some((buffer, line_buffer_range)) = display_map
6178 .buffer_snapshot
6179 .buffer_line_for_row(MultiBufferRow(old_head.row))
6180 {
6181 let indent_size =
6182 buffer.indent_size_for_line(line_buffer_range.start.row);
6183 let indent_len = match indent_size.kind {
6184 IndentKind::Space => {
6185 buffer.settings_at(line_buffer_range.start, cx).tab_size
6186 }
6187 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6188 };
6189 if old_head.column <= indent_size.len && old_head.column > 0 {
6190 let indent_len = indent_len.get();
6191 new_head = cmp::min(
6192 new_head,
6193 MultiBufferPoint::new(
6194 old_head.row,
6195 ((old_head.column - 1) / indent_len) * indent_len,
6196 ),
6197 );
6198 }
6199 }
6200
6201 selection.set_head(new_head, SelectionGoal::None);
6202 }
6203 }
6204 }
6205
6206 this.signature_help_state.set_backspace_pressed(true);
6207 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6208 s.select(selections)
6209 });
6210 this.insert("", window, cx);
6211 let empty_str: Arc<str> = Arc::from("");
6212 for (buffer, edits) in linked_ranges {
6213 let snapshot = buffer.read(cx).snapshot();
6214 use text::ToPoint as TP;
6215
6216 let edits = edits
6217 .into_iter()
6218 .map(|range| {
6219 let end_point = TP::to_point(&range.end, &snapshot);
6220 let mut start_point = TP::to_point(&range.start, &snapshot);
6221
6222 if end_point == start_point {
6223 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6224 .saturating_sub(1);
6225 start_point =
6226 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6227 };
6228
6229 (start_point..end_point, empty_str.clone())
6230 })
6231 .sorted_by_key(|(range, _)| range.start)
6232 .collect::<Vec<_>>();
6233 buffer.update(cx, |this, cx| {
6234 this.edit(edits, None, cx);
6235 })
6236 }
6237 this.refresh_inline_completion(true, false, window, cx);
6238 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6239 });
6240 }
6241
6242 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6243 self.transact(window, cx, |this, window, cx| {
6244 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6245 let line_mode = s.line_mode;
6246 s.move_with(|map, selection| {
6247 if selection.is_empty() && !line_mode {
6248 let cursor = movement::right(map, selection.head());
6249 selection.end = cursor;
6250 selection.reversed = true;
6251 selection.goal = SelectionGoal::None;
6252 }
6253 })
6254 });
6255 this.insert("", window, cx);
6256 this.refresh_inline_completion(true, false, window, cx);
6257 });
6258 }
6259
6260 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6261 if self.move_to_prev_snippet_tabstop(window, cx) {
6262 return;
6263 }
6264
6265 self.outdent(&Outdent, window, cx);
6266 }
6267
6268 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6269 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6270 return;
6271 }
6272
6273 let mut selections = self.selections.all_adjusted(cx);
6274 let buffer = self.buffer.read(cx);
6275 let snapshot = buffer.snapshot(cx);
6276 let rows_iter = selections.iter().map(|s| s.head().row);
6277 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6278
6279 let mut edits = Vec::new();
6280 let mut prev_edited_row = 0;
6281 let mut row_delta = 0;
6282 for selection in &mut selections {
6283 if selection.start.row != prev_edited_row {
6284 row_delta = 0;
6285 }
6286 prev_edited_row = selection.end.row;
6287
6288 // If the selection is non-empty, then increase the indentation of the selected lines.
6289 if !selection.is_empty() {
6290 row_delta =
6291 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6292 continue;
6293 }
6294
6295 // If the selection is empty and the cursor is in the leading whitespace before the
6296 // suggested indentation, then auto-indent the line.
6297 let cursor = selection.head();
6298 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6299 if let Some(suggested_indent) =
6300 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6301 {
6302 if cursor.column < suggested_indent.len
6303 && cursor.column <= current_indent.len
6304 && current_indent.len <= suggested_indent.len
6305 {
6306 selection.start = Point::new(cursor.row, suggested_indent.len);
6307 selection.end = selection.start;
6308 if row_delta == 0 {
6309 edits.extend(Buffer::edit_for_indent_size_adjustment(
6310 cursor.row,
6311 current_indent,
6312 suggested_indent,
6313 ));
6314 row_delta = suggested_indent.len - current_indent.len;
6315 }
6316 continue;
6317 }
6318 }
6319
6320 // Otherwise, insert a hard or soft tab.
6321 let settings = buffer.settings_at(cursor, cx);
6322 let tab_size = if settings.hard_tabs {
6323 IndentSize::tab()
6324 } else {
6325 let tab_size = settings.tab_size.get();
6326 let char_column = snapshot
6327 .text_for_range(Point::new(cursor.row, 0)..cursor)
6328 .flat_map(str::chars)
6329 .count()
6330 + row_delta as usize;
6331 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6332 IndentSize::spaces(chars_to_next_tab_stop)
6333 };
6334 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6335 selection.end = selection.start;
6336 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6337 row_delta += tab_size.len;
6338 }
6339
6340 self.transact(window, cx, |this, window, cx| {
6341 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6342 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6343 s.select(selections)
6344 });
6345 this.refresh_inline_completion(true, false, window, cx);
6346 });
6347 }
6348
6349 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6350 if self.read_only(cx) {
6351 return;
6352 }
6353 let mut selections = self.selections.all::<Point>(cx);
6354 let mut prev_edited_row = 0;
6355 let mut row_delta = 0;
6356 let mut edits = Vec::new();
6357 let buffer = self.buffer.read(cx);
6358 let snapshot = buffer.snapshot(cx);
6359 for selection in &mut selections {
6360 if selection.start.row != prev_edited_row {
6361 row_delta = 0;
6362 }
6363 prev_edited_row = selection.end.row;
6364
6365 row_delta =
6366 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6367 }
6368
6369 self.transact(window, cx, |this, window, cx| {
6370 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6371 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6372 s.select(selections)
6373 });
6374 });
6375 }
6376
6377 fn indent_selection(
6378 buffer: &MultiBuffer,
6379 snapshot: &MultiBufferSnapshot,
6380 selection: &mut Selection<Point>,
6381 edits: &mut Vec<(Range<Point>, String)>,
6382 delta_for_start_row: u32,
6383 cx: &App,
6384 ) -> u32 {
6385 let settings = buffer.settings_at(selection.start, cx);
6386 let tab_size = settings.tab_size.get();
6387 let indent_kind = if settings.hard_tabs {
6388 IndentKind::Tab
6389 } else {
6390 IndentKind::Space
6391 };
6392 let mut start_row = selection.start.row;
6393 let mut end_row = selection.end.row + 1;
6394
6395 // If a selection ends at the beginning of a line, don't indent
6396 // that last line.
6397 if selection.end.column == 0 && selection.end.row > selection.start.row {
6398 end_row -= 1;
6399 }
6400
6401 // Avoid re-indenting a row that has already been indented by a
6402 // previous selection, but still update this selection's column
6403 // to reflect that indentation.
6404 if delta_for_start_row > 0 {
6405 start_row += 1;
6406 selection.start.column += delta_for_start_row;
6407 if selection.end.row == selection.start.row {
6408 selection.end.column += delta_for_start_row;
6409 }
6410 }
6411
6412 let mut delta_for_end_row = 0;
6413 let has_multiple_rows = start_row + 1 != end_row;
6414 for row in start_row..end_row {
6415 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6416 let indent_delta = match (current_indent.kind, indent_kind) {
6417 (IndentKind::Space, IndentKind::Space) => {
6418 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6419 IndentSize::spaces(columns_to_next_tab_stop)
6420 }
6421 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6422 (_, IndentKind::Tab) => IndentSize::tab(),
6423 };
6424
6425 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6426 0
6427 } else {
6428 selection.start.column
6429 };
6430 let row_start = Point::new(row, start);
6431 edits.push((
6432 row_start..row_start,
6433 indent_delta.chars().collect::<String>(),
6434 ));
6435
6436 // Update this selection's endpoints to reflect the indentation.
6437 if row == selection.start.row {
6438 selection.start.column += indent_delta.len;
6439 }
6440 if row == selection.end.row {
6441 selection.end.column += indent_delta.len;
6442 delta_for_end_row = indent_delta.len;
6443 }
6444 }
6445
6446 if selection.start.row == selection.end.row {
6447 delta_for_start_row + delta_for_end_row
6448 } else {
6449 delta_for_end_row
6450 }
6451 }
6452
6453 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6454 if self.read_only(cx) {
6455 return;
6456 }
6457 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6458 let selections = self.selections.all::<Point>(cx);
6459 let mut deletion_ranges = Vec::new();
6460 let mut last_outdent = None;
6461 {
6462 let buffer = self.buffer.read(cx);
6463 let snapshot = buffer.snapshot(cx);
6464 for selection in &selections {
6465 let settings = buffer.settings_at(selection.start, cx);
6466 let tab_size = settings.tab_size.get();
6467 let mut rows = selection.spanned_rows(false, &display_map);
6468
6469 // Avoid re-outdenting a row that has already been outdented by a
6470 // previous selection.
6471 if let Some(last_row) = last_outdent {
6472 if last_row == rows.start {
6473 rows.start = rows.start.next_row();
6474 }
6475 }
6476 let has_multiple_rows = rows.len() > 1;
6477 for row in rows.iter_rows() {
6478 let indent_size = snapshot.indent_size_for_line(row);
6479 if indent_size.len > 0 {
6480 let deletion_len = match indent_size.kind {
6481 IndentKind::Space => {
6482 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6483 if columns_to_prev_tab_stop == 0 {
6484 tab_size
6485 } else {
6486 columns_to_prev_tab_stop
6487 }
6488 }
6489 IndentKind::Tab => 1,
6490 };
6491 let start = if has_multiple_rows
6492 || deletion_len > selection.start.column
6493 || indent_size.len < selection.start.column
6494 {
6495 0
6496 } else {
6497 selection.start.column - deletion_len
6498 };
6499 deletion_ranges.push(
6500 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6501 );
6502 last_outdent = Some(row);
6503 }
6504 }
6505 }
6506 }
6507
6508 self.transact(window, cx, |this, window, cx| {
6509 this.buffer.update(cx, |buffer, cx| {
6510 let empty_str: Arc<str> = Arc::default();
6511 buffer.edit(
6512 deletion_ranges
6513 .into_iter()
6514 .map(|range| (range, empty_str.clone())),
6515 None,
6516 cx,
6517 );
6518 });
6519 let selections = this.selections.all::<usize>(cx);
6520 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6521 s.select(selections)
6522 });
6523 });
6524 }
6525
6526 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6527 if self.read_only(cx) {
6528 return;
6529 }
6530 let selections = self
6531 .selections
6532 .all::<usize>(cx)
6533 .into_iter()
6534 .map(|s| s.range());
6535
6536 self.transact(window, cx, |this, window, cx| {
6537 this.buffer.update(cx, |buffer, cx| {
6538 buffer.autoindent_ranges(selections, cx);
6539 });
6540 let selections = this.selections.all::<usize>(cx);
6541 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6542 s.select(selections)
6543 });
6544 });
6545 }
6546
6547 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6548 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6549 let selections = self.selections.all::<Point>(cx);
6550
6551 let mut new_cursors = Vec::new();
6552 let mut edit_ranges = Vec::new();
6553 let mut selections = selections.iter().peekable();
6554 while let Some(selection) = selections.next() {
6555 let mut rows = selection.spanned_rows(false, &display_map);
6556 let goal_display_column = selection.head().to_display_point(&display_map).column();
6557
6558 // Accumulate contiguous regions of rows that we want to delete.
6559 while let Some(next_selection) = selections.peek() {
6560 let next_rows = next_selection.spanned_rows(false, &display_map);
6561 if next_rows.start <= rows.end {
6562 rows.end = next_rows.end;
6563 selections.next().unwrap();
6564 } else {
6565 break;
6566 }
6567 }
6568
6569 let buffer = &display_map.buffer_snapshot;
6570 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6571 let edit_end;
6572 let cursor_buffer_row;
6573 if buffer.max_point().row >= rows.end.0 {
6574 // If there's a line after the range, delete the \n from the end of the row range
6575 // and position the cursor on the next line.
6576 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6577 cursor_buffer_row = rows.end;
6578 } else {
6579 // If there isn't a line after the range, delete the \n from the line before the
6580 // start of the row range and position the cursor there.
6581 edit_start = edit_start.saturating_sub(1);
6582 edit_end = buffer.len();
6583 cursor_buffer_row = rows.start.previous_row();
6584 }
6585
6586 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6587 *cursor.column_mut() =
6588 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6589
6590 new_cursors.push((
6591 selection.id,
6592 buffer.anchor_after(cursor.to_point(&display_map)),
6593 ));
6594 edit_ranges.push(edit_start..edit_end);
6595 }
6596
6597 self.transact(window, cx, |this, window, cx| {
6598 let buffer = this.buffer.update(cx, |buffer, cx| {
6599 let empty_str: Arc<str> = Arc::default();
6600 buffer.edit(
6601 edit_ranges
6602 .into_iter()
6603 .map(|range| (range, empty_str.clone())),
6604 None,
6605 cx,
6606 );
6607 buffer.snapshot(cx)
6608 });
6609 let new_selections = new_cursors
6610 .into_iter()
6611 .map(|(id, cursor)| {
6612 let cursor = cursor.to_point(&buffer);
6613 Selection {
6614 id,
6615 start: cursor,
6616 end: cursor,
6617 reversed: false,
6618 goal: SelectionGoal::None,
6619 }
6620 })
6621 .collect();
6622
6623 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6624 s.select(new_selections);
6625 });
6626 });
6627 }
6628
6629 pub fn join_lines_impl(
6630 &mut self,
6631 insert_whitespace: bool,
6632 window: &mut Window,
6633 cx: &mut Context<Self>,
6634 ) {
6635 if self.read_only(cx) {
6636 return;
6637 }
6638 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6639 for selection in self.selections.all::<Point>(cx) {
6640 let start = MultiBufferRow(selection.start.row);
6641 // Treat single line selections as if they include the next line. Otherwise this action
6642 // would do nothing for single line selections individual cursors.
6643 let end = if selection.start.row == selection.end.row {
6644 MultiBufferRow(selection.start.row + 1)
6645 } else {
6646 MultiBufferRow(selection.end.row)
6647 };
6648
6649 if let Some(last_row_range) = row_ranges.last_mut() {
6650 if start <= last_row_range.end {
6651 last_row_range.end = end;
6652 continue;
6653 }
6654 }
6655 row_ranges.push(start..end);
6656 }
6657
6658 let snapshot = self.buffer.read(cx).snapshot(cx);
6659 let mut cursor_positions = Vec::new();
6660 for row_range in &row_ranges {
6661 let anchor = snapshot.anchor_before(Point::new(
6662 row_range.end.previous_row().0,
6663 snapshot.line_len(row_range.end.previous_row()),
6664 ));
6665 cursor_positions.push(anchor..anchor);
6666 }
6667
6668 self.transact(window, cx, |this, window, cx| {
6669 for row_range in row_ranges.into_iter().rev() {
6670 for row in row_range.iter_rows().rev() {
6671 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6672 let next_line_row = row.next_row();
6673 let indent = snapshot.indent_size_for_line(next_line_row);
6674 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6675
6676 let replace =
6677 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6678 " "
6679 } else {
6680 ""
6681 };
6682
6683 this.buffer.update(cx, |buffer, cx| {
6684 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6685 });
6686 }
6687 }
6688
6689 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6690 s.select_anchor_ranges(cursor_positions)
6691 });
6692 });
6693 }
6694
6695 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6696 self.join_lines_impl(true, window, cx);
6697 }
6698
6699 pub fn sort_lines_case_sensitive(
6700 &mut self,
6701 _: &SortLinesCaseSensitive,
6702 window: &mut Window,
6703 cx: &mut Context<Self>,
6704 ) {
6705 self.manipulate_lines(window, cx, |lines| lines.sort())
6706 }
6707
6708 pub fn sort_lines_case_insensitive(
6709 &mut self,
6710 _: &SortLinesCaseInsensitive,
6711 window: &mut Window,
6712 cx: &mut Context<Self>,
6713 ) {
6714 self.manipulate_lines(window, cx, |lines| {
6715 lines.sort_by_key(|line| line.to_lowercase())
6716 })
6717 }
6718
6719 pub fn unique_lines_case_insensitive(
6720 &mut self,
6721 _: &UniqueLinesCaseInsensitive,
6722 window: &mut Window,
6723 cx: &mut Context<Self>,
6724 ) {
6725 self.manipulate_lines(window, cx, |lines| {
6726 let mut seen = HashSet::default();
6727 lines.retain(|line| seen.insert(line.to_lowercase()));
6728 })
6729 }
6730
6731 pub fn unique_lines_case_sensitive(
6732 &mut self,
6733 _: &UniqueLinesCaseSensitive,
6734 window: &mut Window,
6735 cx: &mut Context<Self>,
6736 ) {
6737 self.manipulate_lines(window, cx, |lines| {
6738 let mut seen = HashSet::default();
6739 lines.retain(|line| seen.insert(*line));
6740 })
6741 }
6742
6743 pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
6744 let mut revert_changes = HashMap::default();
6745 let snapshot = self.snapshot(window, cx);
6746 for hunk in snapshot
6747 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
6748 {
6749 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6750 }
6751 if !revert_changes.is_empty() {
6752 self.transact(window, cx, |editor, window, cx| {
6753 editor.revert(revert_changes, window, cx);
6754 });
6755 }
6756 }
6757
6758 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
6759 let Some(project) = self.project.clone() else {
6760 return;
6761 };
6762 self.reload(project, window, cx)
6763 .detach_and_notify_err(window, cx);
6764 }
6765
6766 pub fn revert_selected_hunks(
6767 &mut self,
6768 _: &RevertSelectedHunks,
6769 window: &mut Window,
6770 cx: &mut Context<Self>,
6771 ) {
6772 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
6773 self.revert_hunks_in_ranges(selections, window, cx);
6774 }
6775
6776 fn revert_hunks_in_ranges(
6777 &mut self,
6778 ranges: impl Iterator<Item = Range<Point>>,
6779 window: &mut Window,
6780 cx: &mut Context<Editor>,
6781 ) {
6782 let mut revert_changes = HashMap::default();
6783 let snapshot = self.snapshot(window, cx);
6784 for hunk in &snapshot.hunks_for_ranges(ranges) {
6785 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6786 }
6787 if !revert_changes.is_empty() {
6788 self.transact(window, cx, |editor, window, cx| {
6789 editor.revert(revert_changes, window, cx);
6790 });
6791 }
6792 }
6793
6794 pub fn open_active_item_in_terminal(
6795 &mut self,
6796 _: &OpenInTerminal,
6797 window: &mut Window,
6798 cx: &mut Context<Self>,
6799 ) {
6800 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6801 let project_path = buffer.read(cx).project_path(cx)?;
6802 let project = self.project.as_ref()?.read(cx);
6803 let entry = project.entry_for_path(&project_path, cx)?;
6804 let parent = match &entry.canonical_path {
6805 Some(canonical_path) => canonical_path.to_path_buf(),
6806 None => project.absolute_path(&project_path, cx)?,
6807 }
6808 .parent()?
6809 .to_path_buf();
6810 Some(parent)
6811 }) {
6812 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
6813 }
6814 }
6815
6816 pub fn prepare_revert_change(
6817 &self,
6818 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6819 hunk: &MultiBufferDiffHunk,
6820 cx: &mut App,
6821 ) -> Option<()> {
6822 let buffer = self.buffer.read(cx);
6823 let diff = buffer.diff_for(hunk.buffer_id)?;
6824 let buffer = buffer.buffer(hunk.buffer_id)?;
6825 let buffer = buffer.read(cx);
6826 let original_text = diff
6827 .read(cx)
6828 .snapshot
6829 .base_text
6830 .as_ref()?
6831 .as_rope()
6832 .slice(hunk.diff_base_byte_range.clone());
6833 let buffer_snapshot = buffer.snapshot();
6834 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6835 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6836 probe
6837 .0
6838 .start
6839 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6840 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6841 }) {
6842 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6843 Some(())
6844 } else {
6845 None
6846 }
6847 }
6848
6849 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
6850 self.manipulate_lines(window, cx, |lines| lines.reverse())
6851 }
6852
6853 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
6854 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
6855 }
6856
6857 fn manipulate_lines<Fn>(
6858 &mut self,
6859 window: &mut Window,
6860 cx: &mut Context<Self>,
6861 mut callback: Fn,
6862 ) where
6863 Fn: FnMut(&mut Vec<&str>),
6864 {
6865 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6866 let buffer = self.buffer.read(cx).snapshot(cx);
6867
6868 let mut edits = Vec::new();
6869
6870 let selections = self.selections.all::<Point>(cx);
6871 let mut selections = selections.iter().peekable();
6872 let mut contiguous_row_selections = Vec::new();
6873 let mut new_selections = Vec::new();
6874 let mut added_lines = 0;
6875 let mut removed_lines = 0;
6876
6877 while let Some(selection) = selections.next() {
6878 let (start_row, end_row) = consume_contiguous_rows(
6879 &mut contiguous_row_selections,
6880 selection,
6881 &display_map,
6882 &mut selections,
6883 );
6884
6885 let start_point = Point::new(start_row.0, 0);
6886 let end_point = Point::new(
6887 end_row.previous_row().0,
6888 buffer.line_len(end_row.previous_row()),
6889 );
6890 let text = buffer
6891 .text_for_range(start_point..end_point)
6892 .collect::<String>();
6893
6894 let mut lines = text.split('\n').collect_vec();
6895
6896 let lines_before = lines.len();
6897 callback(&mut lines);
6898 let lines_after = lines.len();
6899
6900 edits.push((start_point..end_point, lines.join("\n")));
6901
6902 // Selections must change based on added and removed line count
6903 let start_row =
6904 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6905 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6906 new_selections.push(Selection {
6907 id: selection.id,
6908 start: start_row,
6909 end: end_row,
6910 goal: SelectionGoal::None,
6911 reversed: selection.reversed,
6912 });
6913
6914 if lines_after > lines_before {
6915 added_lines += lines_after - lines_before;
6916 } else if lines_before > lines_after {
6917 removed_lines += lines_before - lines_after;
6918 }
6919 }
6920
6921 self.transact(window, cx, |this, window, cx| {
6922 let buffer = this.buffer.update(cx, |buffer, cx| {
6923 buffer.edit(edits, None, cx);
6924 buffer.snapshot(cx)
6925 });
6926
6927 // Recalculate offsets on newly edited buffer
6928 let new_selections = new_selections
6929 .iter()
6930 .map(|s| {
6931 let start_point = Point::new(s.start.0, 0);
6932 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6933 Selection {
6934 id: s.id,
6935 start: buffer.point_to_offset(start_point),
6936 end: buffer.point_to_offset(end_point),
6937 goal: s.goal,
6938 reversed: s.reversed,
6939 }
6940 })
6941 .collect();
6942
6943 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6944 s.select(new_selections);
6945 });
6946
6947 this.request_autoscroll(Autoscroll::fit(), cx);
6948 });
6949 }
6950
6951 pub fn convert_to_upper_case(
6952 &mut self,
6953 _: &ConvertToUpperCase,
6954 window: &mut Window,
6955 cx: &mut Context<Self>,
6956 ) {
6957 self.manipulate_text(window, cx, |text| text.to_uppercase())
6958 }
6959
6960 pub fn convert_to_lower_case(
6961 &mut self,
6962 _: &ConvertToLowerCase,
6963 window: &mut Window,
6964 cx: &mut Context<Self>,
6965 ) {
6966 self.manipulate_text(window, cx, |text| text.to_lowercase())
6967 }
6968
6969 pub fn convert_to_title_case(
6970 &mut self,
6971 _: &ConvertToTitleCase,
6972 window: &mut Window,
6973 cx: &mut Context<Self>,
6974 ) {
6975 self.manipulate_text(window, cx, |text| {
6976 text.split('\n')
6977 .map(|line| line.to_case(Case::Title))
6978 .join("\n")
6979 })
6980 }
6981
6982 pub fn convert_to_snake_case(
6983 &mut self,
6984 _: &ConvertToSnakeCase,
6985 window: &mut Window,
6986 cx: &mut Context<Self>,
6987 ) {
6988 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
6989 }
6990
6991 pub fn convert_to_kebab_case(
6992 &mut self,
6993 _: &ConvertToKebabCase,
6994 window: &mut Window,
6995 cx: &mut Context<Self>,
6996 ) {
6997 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
6998 }
6999
7000 pub fn convert_to_upper_camel_case(
7001 &mut self,
7002 _: &ConvertToUpperCamelCase,
7003 window: &mut Window,
7004 cx: &mut Context<Self>,
7005 ) {
7006 self.manipulate_text(window, cx, |text| {
7007 text.split('\n')
7008 .map(|line| line.to_case(Case::UpperCamel))
7009 .join("\n")
7010 })
7011 }
7012
7013 pub fn convert_to_lower_camel_case(
7014 &mut self,
7015 _: &ConvertToLowerCamelCase,
7016 window: &mut Window,
7017 cx: &mut Context<Self>,
7018 ) {
7019 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
7020 }
7021
7022 pub fn convert_to_opposite_case(
7023 &mut self,
7024 _: &ConvertToOppositeCase,
7025 window: &mut Window,
7026 cx: &mut Context<Self>,
7027 ) {
7028 self.manipulate_text(window, cx, |text| {
7029 text.chars()
7030 .fold(String::with_capacity(text.len()), |mut t, c| {
7031 if c.is_uppercase() {
7032 t.extend(c.to_lowercase());
7033 } else {
7034 t.extend(c.to_uppercase());
7035 }
7036 t
7037 })
7038 })
7039 }
7040
7041 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
7042 where
7043 Fn: FnMut(&str) -> String,
7044 {
7045 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7046 let buffer = self.buffer.read(cx).snapshot(cx);
7047
7048 let mut new_selections = Vec::new();
7049 let mut edits = Vec::new();
7050 let mut selection_adjustment = 0i32;
7051
7052 for selection in self.selections.all::<usize>(cx) {
7053 let selection_is_empty = selection.is_empty();
7054
7055 let (start, end) = if selection_is_empty {
7056 let word_range = movement::surrounding_word(
7057 &display_map,
7058 selection.start.to_display_point(&display_map),
7059 );
7060 let start = word_range.start.to_offset(&display_map, Bias::Left);
7061 let end = word_range.end.to_offset(&display_map, Bias::Left);
7062 (start, end)
7063 } else {
7064 (selection.start, selection.end)
7065 };
7066
7067 let text = buffer.text_for_range(start..end).collect::<String>();
7068 let old_length = text.len() as i32;
7069 let text = callback(&text);
7070
7071 new_selections.push(Selection {
7072 start: (start as i32 - selection_adjustment) as usize,
7073 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
7074 goal: SelectionGoal::None,
7075 ..selection
7076 });
7077
7078 selection_adjustment += old_length - text.len() as i32;
7079
7080 edits.push((start..end, text));
7081 }
7082
7083 self.transact(window, cx, |this, window, cx| {
7084 this.buffer.update(cx, |buffer, cx| {
7085 buffer.edit(edits, None, cx);
7086 });
7087
7088 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7089 s.select(new_selections);
7090 });
7091
7092 this.request_autoscroll(Autoscroll::fit(), cx);
7093 });
7094 }
7095
7096 pub fn duplicate(
7097 &mut self,
7098 upwards: bool,
7099 whole_lines: bool,
7100 window: &mut Window,
7101 cx: &mut Context<Self>,
7102 ) {
7103 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7104 let buffer = &display_map.buffer_snapshot;
7105 let selections = self.selections.all::<Point>(cx);
7106
7107 let mut edits = Vec::new();
7108 let mut selections_iter = selections.iter().peekable();
7109 while let Some(selection) = selections_iter.next() {
7110 let mut rows = selection.spanned_rows(false, &display_map);
7111 // duplicate line-wise
7112 if whole_lines || selection.start == selection.end {
7113 // Avoid duplicating the same lines twice.
7114 while let Some(next_selection) = selections_iter.peek() {
7115 let next_rows = next_selection.spanned_rows(false, &display_map);
7116 if next_rows.start < rows.end {
7117 rows.end = next_rows.end;
7118 selections_iter.next().unwrap();
7119 } else {
7120 break;
7121 }
7122 }
7123
7124 // Copy the text from the selected row region and splice it either at the start
7125 // or end of the region.
7126 let start = Point::new(rows.start.0, 0);
7127 let end = Point::new(
7128 rows.end.previous_row().0,
7129 buffer.line_len(rows.end.previous_row()),
7130 );
7131 let text = buffer
7132 .text_for_range(start..end)
7133 .chain(Some("\n"))
7134 .collect::<String>();
7135 let insert_location = if upwards {
7136 Point::new(rows.end.0, 0)
7137 } else {
7138 start
7139 };
7140 edits.push((insert_location..insert_location, text));
7141 } else {
7142 // duplicate character-wise
7143 let start = selection.start;
7144 let end = selection.end;
7145 let text = buffer.text_for_range(start..end).collect::<String>();
7146 edits.push((selection.end..selection.end, text));
7147 }
7148 }
7149
7150 self.transact(window, cx, |this, _, cx| {
7151 this.buffer.update(cx, |buffer, cx| {
7152 buffer.edit(edits, None, cx);
7153 });
7154
7155 this.request_autoscroll(Autoscroll::fit(), cx);
7156 });
7157 }
7158
7159 pub fn duplicate_line_up(
7160 &mut self,
7161 _: &DuplicateLineUp,
7162 window: &mut Window,
7163 cx: &mut Context<Self>,
7164 ) {
7165 self.duplicate(true, true, window, cx);
7166 }
7167
7168 pub fn duplicate_line_down(
7169 &mut self,
7170 _: &DuplicateLineDown,
7171 window: &mut Window,
7172 cx: &mut Context<Self>,
7173 ) {
7174 self.duplicate(false, true, window, cx);
7175 }
7176
7177 pub fn duplicate_selection(
7178 &mut self,
7179 _: &DuplicateSelection,
7180 window: &mut Window,
7181 cx: &mut Context<Self>,
7182 ) {
7183 self.duplicate(false, false, window, cx);
7184 }
7185
7186 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7187 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7188 let buffer = self.buffer.read(cx).snapshot(cx);
7189
7190 let mut edits = Vec::new();
7191 let mut unfold_ranges = Vec::new();
7192 let mut refold_creases = Vec::new();
7193
7194 let selections = self.selections.all::<Point>(cx);
7195 let mut selections = selections.iter().peekable();
7196 let mut contiguous_row_selections = Vec::new();
7197 let mut new_selections = Vec::new();
7198
7199 while let Some(selection) = selections.next() {
7200 // Find all the selections that span a contiguous row range
7201 let (start_row, end_row) = consume_contiguous_rows(
7202 &mut contiguous_row_selections,
7203 selection,
7204 &display_map,
7205 &mut selections,
7206 );
7207
7208 // Move the text spanned by the row range to be before the line preceding the row range
7209 if start_row.0 > 0 {
7210 let range_to_move = Point::new(
7211 start_row.previous_row().0,
7212 buffer.line_len(start_row.previous_row()),
7213 )
7214 ..Point::new(
7215 end_row.previous_row().0,
7216 buffer.line_len(end_row.previous_row()),
7217 );
7218 let insertion_point = display_map
7219 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7220 .0;
7221
7222 // Don't move lines across excerpts
7223 if buffer
7224 .excerpt_containing(insertion_point..range_to_move.end)
7225 .is_some()
7226 {
7227 let text = buffer
7228 .text_for_range(range_to_move.clone())
7229 .flat_map(|s| s.chars())
7230 .skip(1)
7231 .chain(['\n'])
7232 .collect::<String>();
7233
7234 edits.push((
7235 buffer.anchor_after(range_to_move.start)
7236 ..buffer.anchor_before(range_to_move.end),
7237 String::new(),
7238 ));
7239 let insertion_anchor = buffer.anchor_after(insertion_point);
7240 edits.push((insertion_anchor..insertion_anchor, text));
7241
7242 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7243
7244 // Move selections up
7245 new_selections.extend(contiguous_row_selections.drain(..).map(
7246 |mut selection| {
7247 selection.start.row -= row_delta;
7248 selection.end.row -= row_delta;
7249 selection
7250 },
7251 ));
7252
7253 // Move folds up
7254 unfold_ranges.push(range_to_move.clone());
7255 for fold in display_map.folds_in_range(
7256 buffer.anchor_before(range_to_move.start)
7257 ..buffer.anchor_after(range_to_move.end),
7258 ) {
7259 let mut start = fold.range.start.to_point(&buffer);
7260 let mut end = fold.range.end.to_point(&buffer);
7261 start.row -= row_delta;
7262 end.row -= row_delta;
7263 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7264 }
7265 }
7266 }
7267
7268 // If we didn't move line(s), preserve the existing selections
7269 new_selections.append(&mut contiguous_row_selections);
7270 }
7271
7272 self.transact(window, cx, |this, window, cx| {
7273 this.unfold_ranges(&unfold_ranges, true, true, cx);
7274 this.buffer.update(cx, |buffer, cx| {
7275 for (range, text) in edits {
7276 buffer.edit([(range, text)], None, cx);
7277 }
7278 });
7279 this.fold_creases(refold_creases, true, window, cx);
7280 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7281 s.select(new_selections);
7282 })
7283 });
7284 }
7285
7286 pub fn move_line_down(
7287 &mut self,
7288 _: &MoveLineDown,
7289 window: &mut Window,
7290 cx: &mut Context<Self>,
7291 ) {
7292 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7293 let buffer = self.buffer.read(cx).snapshot(cx);
7294
7295 let mut edits = Vec::new();
7296 let mut unfold_ranges = Vec::new();
7297 let mut refold_creases = Vec::new();
7298
7299 let selections = self.selections.all::<Point>(cx);
7300 let mut selections = selections.iter().peekable();
7301 let mut contiguous_row_selections = Vec::new();
7302 let mut new_selections = Vec::new();
7303
7304 while let Some(selection) = selections.next() {
7305 // Find all the selections that span a contiguous row range
7306 let (start_row, end_row) = consume_contiguous_rows(
7307 &mut contiguous_row_selections,
7308 selection,
7309 &display_map,
7310 &mut selections,
7311 );
7312
7313 // Move the text spanned by the row range to be after the last line of the row range
7314 if end_row.0 <= buffer.max_point().row {
7315 let range_to_move =
7316 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7317 let insertion_point = display_map
7318 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7319 .0;
7320
7321 // Don't move lines across excerpt boundaries
7322 if buffer
7323 .excerpt_containing(range_to_move.start..insertion_point)
7324 .is_some()
7325 {
7326 let mut text = String::from("\n");
7327 text.extend(buffer.text_for_range(range_to_move.clone()));
7328 text.pop(); // Drop trailing newline
7329 edits.push((
7330 buffer.anchor_after(range_to_move.start)
7331 ..buffer.anchor_before(range_to_move.end),
7332 String::new(),
7333 ));
7334 let insertion_anchor = buffer.anchor_after(insertion_point);
7335 edits.push((insertion_anchor..insertion_anchor, text));
7336
7337 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7338
7339 // Move selections down
7340 new_selections.extend(contiguous_row_selections.drain(..).map(
7341 |mut selection| {
7342 selection.start.row += row_delta;
7343 selection.end.row += row_delta;
7344 selection
7345 },
7346 ));
7347
7348 // Move folds down
7349 unfold_ranges.push(range_to_move.clone());
7350 for fold in display_map.folds_in_range(
7351 buffer.anchor_before(range_to_move.start)
7352 ..buffer.anchor_after(range_to_move.end),
7353 ) {
7354 let mut start = fold.range.start.to_point(&buffer);
7355 let mut end = fold.range.end.to_point(&buffer);
7356 start.row += row_delta;
7357 end.row += row_delta;
7358 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7359 }
7360 }
7361 }
7362
7363 // If we didn't move line(s), preserve the existing selections
7364 new_selections.append(&mut contiguous_row_selections);
7365 }
7366
7367 self.transact(window, cx, |this, window, cx| {
7368 this.unfold_ranges(&unfold_ranges, true, true, cx);
7369 this.buffer.update(cx, |buffer, cx| {
7370 for (range, text) in edits {
7371 buffer.edit([(range, text)], None, cx);
7372 }
7373 });
7374 this.fold_creases(refold_creases, true, window, cx);
7375 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7376 s.select(new_selections)
7377 });
7378 });
7379 }
7380
7381 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7382 let text_layout_details = &self.text_layout_details(window);
7383 self.transact(window, cx, |this, window, cx| {
7384 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7385 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7386 let line_mode = s.line_mode;
7387 s.move_with(|display_map, selection| {
7388 if !selection.is_empty() || line_mode {
7389 return;
7390 }
7391
7392 let mut head = selection.head();
7393 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7394 if head.column() == display_map.line_len(head.row()) {
7395 transpose_offset = display_map
7396 .buffer_snapshot
7397 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7398 }
7399
7400 if transpose_offset == 0 {
7401 return;
7402 }
7403
7404 *head.column_mut() += 1;
7405 head = display_map.clip_point(head, Bias::Right);
7406 let goal = SelectionGoal::HorizontalPosition(
7407 display_map
7408 .x_for_display_point(head, text_layout_details)
7409 .into(),
7410 );
7411 selection.collapse_to(head, goal);
7412
7413 let transpose_start = display_map
7414 .buffer_snapshot
7415 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7416 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7417 let transpose_end = display_map
7418 .buffer_snapshot
7419 .clip_offset(transpose_offset + 1, Bias::Right);
7420 if let Some(ch) =
7421 display_map.buffer_snapshot.chars_at(transpose_start).next()
7422 {
7423 edits.push((transpose_start..transpose_offset, String::new()));
7424 edits.push((transpose_end..transpose_end, ch.to_string()));
7425 }
7426 }
7427 });
7428 edits
7429 });
7430 this.buffer
7431 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7432 let selections = this.selections.all::<usize>(cx);
7433 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7434 s.select(selections);
7435 });
7436 });
7437 }
7438
7439 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7440 self.rewrap_impl(IsVimMode::No, cx)
7441 }
7442
7443 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7444 let buffer = self.buffer.read(cx).snapshot(cx);
7445 let selections = self.selections.all::<Point>(cx);
7446 let mut selections = selections.iter().peekable();
7447
7448 let mut edits = Vec::new();
7449 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7450
7451 while let Some(selection) = selections.next() {
7452 let mut start_row = selection.start.row;
7453 let mut end_row = selection.end.row;
7454
7455 // Skip selections that overlap with a range that has already been rewrapped.
7456 let selection_range = start_row..end_row;
7457 if rewrapped_row_ranges
7458 .iter()
7459 .any(|range| range.overlaps(&selection_range))
7460 {
7461 continue;
7462 }
7463
7464 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7465
7466 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7467 match language_scope.language_name().as_ref() {
7468 "Markdown" | "Plain Text" => {
7469 should_rewrap = true;
7470 }
7471 _ => {}
7472 }
7473 }
7474
7475 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7476
7477 // Since not all lines in the selection may be at the same indent
7478 // level, choose the indent size that is the most common between all
7479 // of the lines.
7480 //
7481 // If there is a tie, we use the deepest indent.
7482 let (indent_size, indent_end) = {
7483 let mut indent_size_occurrences = HashMap::default();
7484 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7485
7486 for row in start_row..=end_row {
7487 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7488 rows_by_indent_size.entry(indent).or_default().push(row);
7489 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7490 }
7491
7492 let indent_size = indent_size_occurrences
7493 .into_iter()
7494 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7495 .map(|(indent, _)| indent)
7496 .unwrap_or_default();
7497 let row = rows_by_indent_size[&indent_size][0];
7498 let indent_end = Point::new(row, indent_size.len);
7499
7500 (indent_size, indent_end)
7501 };
7502
7503 let mut line_prefix = indent_size.chars().collect::<String>();
7504
7505 if let Some(comment_prefix) =
7506 buffer
7507 .language_scope_at(selection.head())
7508 .and_then(|language| {
7509 language
7510 .line_comment_prefixes()
7511 .iter()
7512 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7513 .cloned()
7514 })
7515 {
7516 line_prefix.push_str(&comment_prefix);
7517 should_rewrap = true;
7518 }
7519
7520 if !should_rewrap {
7521 continue;
7522 }
7523
7524 if selection.is_empty() {
7525 'expand_upwards: while start_row > 0 {
7526 let prev_row = start_row - 1;
7527 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7528 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7529 {
7530 start_row = prev_row;
7531 } else {
7532 break 'expand_upwards;
7533 }
7534 }
7535
7536 'expand_downwards: while end_row < buffer.max_point().row {
7537 let next_row = end_row + 1;
7538 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7539 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7540 {
7541 end_row = next_row;
7542 } else {
7543 break 'expand_downwards;
7544 }
7545 }
7546 }
7547
7548 let start = Point::new(start_row, 0);
7549 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7550 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7551 let Some(lines_without_prefixes) = selection_text
7552 .lines()
7553 .map(|line| {
7554 line.strip_prefix(&line_prefix)
7555 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7556 .ok_or_else(|| {
7557 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7558 })
7559 })
7560 .collect::<Result<Vec<_>, _>>()
7561 .log_err()
7562 else {
7563 continue;
7564 };
7565
7566 let wrap_column = buffer
7567 .settings_at(Point::new(start_row, 0), cx)
7568 .preferred_line_length as usize;
7569 let wrapped_text = wrap_with_prefix(
7570 line_prefix,
7571 lines_without_prefixes.join(" "),
7572 wrap_column,
7573 tab_size,
7574 );
7575
7576 // TODO: should always use char-based diff while still supporting cursor behavior that
7577 // matches vim.
7578 let diff = match is_vim_mode {
7579 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7580 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7581 };
7582 let mut offset = start.to_offset(&buffer);
7583 let mut moved_since_edit = true;
7584
7585 for change in diff.iter_all_changes() {
7586 let value = change.value();
7587 match change.tag() {
7588 ChangeTag::Equal => {
7589 offset += value.len();
7590 moved_since_edit = true;
7591 }
7592 ChangeTag::Delete => {
7593 let start = buffer.anchor_after(offset);
7594 let end = buffer.anchor_before(offset + value.len());
7595
7596 if moved_since_edit {
7597 edits.push((start..end, String::new()));
7598 } else {
7599 edits.last_mut().unwrap().0.end = end;
7600 }
7601
7602 offset += value.len();
7603 moved_since_edit = false;
7604 }
7605 ChangeTag::Insert => {
7606 if moved_since_edit {
7607 let anchor = buffer.anchor_after(offset);
7608 edits.push((anchor..anchor, value.to_string()));
7609 } else {
7610 edits.last_mut().unwrap().1.push_str(value);
7611 }
7612
7613 moved_since_edit = false;
7614 }
7615 }
7616 }
7617
7618 rewrapped_row_ranges.push(start_row..=end_row);
7619 }
7620
7621 self.buffer
7622 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7623 }
7624
7625 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7626 let mut text = String::new();
7627 let buffer = self.buffer.read(cx).snapshot(cx);
7628 let mut selections = self.selections.all::<Point>(cx);
7629 let mut clipboard_selections = Vec::with_capacity(selections.len());
7630 {
7631 let max_point = buffer.max_point();
7632 let mut is_first = true;
7633 for selection in &mut selections {
7634 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7635 if is_entire_line {
7636 selection.start = Point::new(selection.start.row, 0);
7637 if !selection.is_empty() && selection.end.column == 0 {
7638 selection.end = cmp::min(max_point, selection.end);
7639 } else {
7640 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7641 }
7642 selection.goal = SelectionGoal::None;
7643 }
7644 if is_first {
7645 is_first = false;
7646 } else {
7647 text += "\n";
7648 }
7649 let mut len = 0;
7650 for chunk in buffer.text_for_range(selection.start..selection.end) {
7651 text.push_str(chunk);
7652 len += chunk.len();
7653 }
7654 clipboard_selections.push(ClipboardSelection {
7655 len,
7656 is_entire_line,
7657 first_line_indent: buffer
7658 .indent_size_for_line(MultiBufferRow(selection.start.row))
7659 .len,
7660 });
7661 }
7662 }
7663
7664 self.transact(window, cx, |this, window, cx| {
7665 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7666 s.select(selections);
7667 });
7668 this.insert("", window, cx);
7669 });
7670 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7671 }
7672
7673 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
7674 let item = self.cut_common(window, cx);
7675 cx.write_to_clipboard(item);
7676 }
7677
7678 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
7679 self.change_selections(None, window, cx, |s| {
7680 s.move_with(|snapshot, sel| {
7681 if sel.is_empty() {
7682 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7683 }
7684 });
7685 });
7686 let item = self.cut_common(window, cx);
7687 cx.set_global(KillRing(item))
7688 }
7689
7690 pub fn kill_ring_yank(
7691 &mut self,
7692 _: &KillRingYank,
7693 window: &mut Window,
7694 cx: &mut Context<Self>,
7695 ) {
7696 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7697 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7698 (kill_ring.text().to_string(), kill_ring.metadata_json())
7699 } else {
7700 return;
7701 }
7702 } else {
7703 return;
7704 };
7705 self.do_paste(&text, metadata, false, window, cx);
7706 }
7707
7708 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
7709 let selections = self.selections.all::<Point>(cx);
7710 let buffer = self.buffer.read(cx).read(cx);
7711 let mut text = String::new();
7712
7713 let mut clipboard_selections = Vec::with_capacity(selections.len());
7714 {
7715 let max_point = buffer.max_point();
7716 let mut is_first = true;
7717 for selection in selections.iter() {
7718 let mut start = selection.start;
7719 let mut end = selection.end;
7720 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7721 if is_entire_line {
7722 start = Point::new(start.row, 0);
7723 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7724 }
7725 if is_first {
7726 is_first = false;
7727 } else {
7728 text += "\n";
7729 }
7730 let mut len = 0;
7731 for chunk in buffer.text_for_range(start..end) {
7732 text.push_str(chunk);
7733 len += chunk.len();
7734 }
7735 clipboard_selections.push(ClipboardSelection {
7736 len,
7737 is_entire_line,
7738 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7739 });
7740 }
7741 }
7742
7743 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7744 text,
7745 clipboard_selections,
7746 ));
7747 }
7748
7749 pub fn do_paste(
7750 &mut self,
7751 text: &String,
7752 clipboard_selections: Option<Vec<ClipboardSelection>>,
7753 handle_entire_lines: bool,
7754 window: &mut Window,
7755 cx: &mut Context<Self>,
7756 ) {
7757 if self.read_only(cx) {
7758 return;
7759 }
7760
7761 let clipboard_text = Cow::Borrowed(text);
7762
7763 self.transact(window, cx, |this, window, cx| {
7764 if let Some(mut clipboard_selections) = clipboard_selections {
7765 let old_selections = this.selections.all::<usize>(cx);
7766 let all_selections_were_entire_line =
7767 clipboard_selections.iter().all(|s| s.is_entire_line);
7768 let first_selection_indent_column =
7769 clipboard_selections.first().map(|s| s.first_line_indent);
7770 if clipboard_selections.len() != old_selections.len() {
7771 clipboard_selections.drain(..);
7772 }
7773 let cursor_offset = this.selections.last::<usize>(cx).head();
7774 let mut auto_indent_on_paste = true;
7775
7776 this.buffer.update(cx, |buffer, cx| {
7777 let snapshot = buffer.read(cx);
7778 auto_indent_on_paste =
7779 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7780
7781 let mut start_offset = 0;
7782 let mut edits = Vec::new();
7783 let mut original_indent_columns = Vec::new();
7784 for (ix, selection) in old_selections.iter().enumerate() {
7785 let to_insert;
7786 let entire_line;
7787 let original_indent_column;
7788 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7789 let end_offset = start_offset + clipboard_selection.len;
7790 to_insert = &clipboard_text[start_offset..end_offset];
7791 entire_line = clipboard_selection.is_entire_line;
7792 start_offset = end_offset + 1;
7793 original_indent_column = Some(clipboard_selection.first_line_indent);
7794 } else {
7795 to_insert = clipboard_text.as_str();
7796 entire_line = all_selections_were_entire_line;
7797 original_indent_column = first_selection_indent_column
7798 }
7799
7800 // If the corresponding selection was empty when this slice of the
7801 // clipboard text was written, then the entire line containing the
7802 // selection was copied. If this selection is also currently empty,
7803 // then paste the line before the current line of the buffer.
7804 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7805 let column = selection.start.to_point(&snapshot).column as usize;
7806 let line_start = selection.start - column;
7807 line_start..line_start
7808 } else {
7809 selection.range()
7810 };
7811
7812 edits.push((range, to_insert));
7813 original_indent_columns.extend(original_indent_column);
7814 }
7815 drop(snapshot);
7816
7817 buffer.edit(
7818 edits,
7819 if auto_indent_on_paste {
7820 Some(AutoindentMode::Block {
7821 original_indent_columns,
7822 })
7823 } else {
7824 None
7825 },
7826 cx,
7827 );
7828 });
7829
7830 let selections = this.selections.all::<usize>(cx);
7831 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7832 s.select(selections)
7833 });
7834 } else {
7835 this.insert(&clipboard_text, window, cx);
7836 }
7837 });
7838 }
7839
7840 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
7841 if let Some(item) = cx.read_from_clipboard() {
7842 let entries = item.entries();
7843
7844 match entries.first() {
7845 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7846 // of all the pasted entries.
7847 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7848 .do_paste(
7849 clipboard_string.text(),
7850 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7851 true,
7852 window,
7853 cx,
7854 ),
7855 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
7856 }
7857 }
7858 }
7859
7860 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
7861 if self.read_only(cx) {
7862 return;
7863 }
7864
7865 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7866 if let Some((selections, _)) =
7867 self.selection_history.transaction(transaction_id).cloned()
7868 {
7869 self.change_selections(None, window, cx, |s| {
7870 s.select_anchors(selections.to_vec());
7871 });
7872 }
7873 self.request_autoscroll(Autoscroll::fit(), cx);
7874 self.unmark_text(window, cx);
7875 self.refresh_inline_completion(true, false, window, cx);
7876 cx.emit(EditorEvent::Edited { transaction_id });
7877 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7878 }
7879 }
7880
7881 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
7882 if self.read_only(cx) {
7883 return;
7884 }
7885
7886 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7887 if let Some((_, Some(selections))) =
7888 self.selection_history.transaction(transaction_id).cloned()
7889 {
7890 self.change_selections(None, window, cx, |s| {
7891 s.select_anchors(selections.to_vec());
7892 });
7893 }
7894 self.request_autoscroll(Autoscroll::fit(), cx);
7895 self.unmark_text(window, cx);
7896 self.refresh_inline_completion(true, false, window, cx);
7897 cx.emit(EditorEvent::Edited { transaction_id });
7898 }
7899 }
7900
7901 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
7902 self.buffer
7903 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7904 }
7905
7906 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
7907 self.buffer
7908 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7909 }
7910
7911 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
7912 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7913 let line_mode = s.line_mode;
7914 s.move_with(|map, selection| {
7915 let cursor = if selection.is_empty() && !line_mode {
7916 movement::left(map, selection.start)
7917 } else {
7918 selection.start
7919 };
7920 selection.collapse_to(cursor, SelectionGoal::None);
7921 });
7922 })
7923 }
7924
7925 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
7926 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7927 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7928 })
7929 }
7930
7931 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
7932 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7933 let line_mode = s.line_mode;
7934 s.move_with(|map, selection| {
7935 let cursor = if selection.is_empty() && !line_mode {
7936 movement::right(map, selection.end)
7937 } else {
7938 selection.end
7939 };
7940 selection.collapse_to(cursor, SelectionGoal::None)
7941 });
7942 })
7943 }
7944
7945 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
7946 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7947 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7948 })
7949 }
7950
7951 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
7952 if self.take_rename(true, window, cx).is_some() {
7953 return;
7954 }
7955
7956 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7957 cx.propagate();
7958 return;
7959 }
7960
7961 let text_layout_details = &self.text_layout_details(window);
7962 let selection_count = self.selections.count();
7963 let first_selection = self.selections.first_anchor();
7964
7965 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7966 let line_mode = s.line_mode;
7967 s.move_with(|map, selection| {
7968 if !selection.is_empty() && !line_mode {
7969 selection.goal = SelectionGoal::None;
7970 }
7971 let (cursor, goal) = movement::up(
7972 map,
7973 selection.start,
7974 selection.goal,
7975 false,
7976 text_layout_details,
7977 );
7978 selection.collapse_to(cursor, goal);
7979 });
7980 });
7981
7982 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7983 {
7984 cx.propagate();
7985 }
7986 }
7987
7988 pub fn move_up_by_lines(
7989 &mut self,
7990 action: &MoveUpByLines,
7991 window: &mut Window,
7992 cx: &mut Context<Self>,
7993 ) {
7994 if self.take_rename(true, window, cx).is_some() {
7995 return;
7996 }
7997
7998 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7999 cx.propagate();
8000 return;
8001 }
8002
8003 let text_layout_details = &self.text_layout_details(window);
8004
8005 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8006 let line_mode = s.line_mode;
8007 s.move_with(|map, selection| {
8008 if !selection.is_empty() && !line_mode {
8009 selection.goal = SelectionGoal::None;
8010 }
8011 let (cursor, goal) = movement::up_by_rows(
8012 map,
8013 selection.start,
8014 action.lines,
8015 selection.goal,
8016 false,
8017 text_layout_details,
8018 );
8019 selection.collapse_to(cursor, goal);
8020 });
8021 })
8022 }
8023
8024 pub fn move_down_by_lines(
8025 &mut self,
8026 action: &MoveDownByLines,
8027 window: &mut Window,
8028 cx: &mut Context<Self>,
8029 ) {
8030 if self.take_rename(true, window, cx).is_some() {
8031 return;
8032 }
8033
8034 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8035 cx.propagate();
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 let line_mode = s.line_mode;
8043 s.move_with(|map, selection| {
8044 if !selection.is_empty() && !line_mode {
8045 selection.goal = SelectionGoal::None;
8046 }
8047 let (cursor, goal) = movement::down_by_rows(
8048 map,
8049 selection.start,
8050 action.lines,
8051 selection.goal,
8052 false,
8053 text_layout_details,
8054 );
8055 selection.collapse_to(cursor, goal);
8056 });
8057 })
8058 }
8059
8060 pub fn select_down_by_lines(
8061 &mut self,
8062 action: &SelectDownByLines,
8063 window: &mut Window,
8064 cx: &mut Context<Self>,
8065 ) {
8066 let text_layout_details = &self.text_layout_details(window);
8067 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8068 s.move_heads_with(|map, head, goal| {
8069 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
8070 })
8071 })
8072 }
8073
8074 pub fn select_up_by_lines(
8075 &mut self,
8076 action: &SelectUpByLines,
8077 window: &mut Window,
8078 cx: &mut Context<Self>,
8079 ) {
8080 let text_layout_details = &self.text_layout_details(window);
8081 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8082 s.move_heads_with(|map, head, goal| {
8083 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8084 })
8085 })
8086 }
8087
8088 pub fn select_page_up(
8089 &mut self,
8090 _: &SelectPageUp,
8091 window: &mut Window,
8092 cx: &mut Context<Self>,
8093 ) {
8094 let Some(row_count) = self.visible_row_count() else {
8095 return;
8096 };
8097
8098 let text_layout_details = &self.text_layout_details(window);
8099
8100 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8101 s.move_heads_with(|map, head, goal| {
8102 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8103 })
8104 })
8105 }
8106
8107 pub fn move_page_up(
8108 &mut self,
8109 action: &MovePageUp,
8110 window: &mut Window,
8111 cx: &mut Context<Self>,
8112 ) {
8113 if self.take_rename(true, window, cx).is_some() {
8114 return;
8115 }
8116
8117 if self
8118 .context_menu
8119 .borrow_mut()
8120 .as_mut()
8121 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8122 .unwrap_or(false)
8123 {
8124 return;
8125 }
8126
8127 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8128 cx.propagate();
8129 return;
8130 }
8131
8132 let Some(row_count) = self.visible_row_count() else {
8133 return;
8134 };
8135
8136 let autoscroll = if action.center_cursor {
8137 Autoscroll::center()
8138 } else {
8139 Autoscroll::fit()
8140 };
8141
8142 let text_layout_details = &self.text_layout_details(window);
8143
8144 self.change_selections(Some(autoscroll), window, cx, |s| {
8145 let line_mode = s.line_mode;
8146 s.move_with(|map, selection| {
8147 if !selection.is_empty() && !line_mode {
8148 selection.goal = SelectionGoal::None;
8149 }
8150 let (cursor, goal) = movement::up_by_rows(
8151 map,
8152 selection.end,
8153 row_count,
8154 selection.goal,
8155 false,
8156 text_layout_details,
8157 );
8158 selection.collapse_to(cursor, goal);
8159 });
8160 });
8161 }
8162
8163 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8164 let text_layout_details = &self.text_layout_details(window);
8165 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8166 s.move_heads_with(|map, head, goal| {
8167 movement::up(map, head, goal, false, text_layout_details)
8168 })
8169 })
8170 }
8171
8172 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8173 self.take_rename(true, window, cx);
8174
8175 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8176 cx.propagate();
8177 return;
8178 }
8179
8180 let text_layout_details = &self.text_layout_details(window);
8181 let selection_count = self.selections.count();
8182 let first_selection = self.selections.first_anchor();
8183
8184 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8185 let line_mode = s.line_mode;
8186 s.move_with(|map, selection| {
8187 if !selection.is_empty() && !line_mode {
8188 selection.goal = SelectionGoal::None;
8189 }
8190 let (cursor, goal) = movement::down(
8191 map,
8192 selection.end,
8193 selection.goal,
8194 false,
8195 text_layout_details,
8196 );
8197 selection.collapse_to(cursor, goal);
8198 });
8199 });
8200
8201 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8202 {
8203 cx.propagate();
8204 }
8205 }
8206
8207 pub fn select_page_down(
8208 &mut self,
8209 _: &SelectPageDown,
8210 window: &mut Window,
8211 cx: &mut Context<Self>,
8212 ) {
8213 let Some(row_count) = self.visible_row_count() else {
8214 return;
8215 };
8216
8217 let text_layout_details = &self.text_layout_details(window);
8218
8219 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8220 s.move_heads_with(|map, head, goal| {
8221 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8222 })
8223 })
8224 }
8225
8226 pub fn move_page_down(
8227 &mut self,
8228 action: &MovePageDown,
8229 window: &mut Window,
8230 cx: &mut Context<Self>,
8231 ) {
8232 if self.take_rename(true, window, cx).is_some() {
8233 return;
8234 }
8235
8236 if self
8237 .context_menu
8238 .borrow_mut()
8239 .as_mut()
8240 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8241 .unwrap_or(false)
8242 {
8243 return;
8244 }
8245
8246 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8247 cx.propagate();
8248 return;
8249 }
8250
8251 let Some(row_count) = self.visible_row_count() else {
8252 return;
8253 };
8254
8255 let autoscroll = if action.center_cursor {
8256 Autoscroll::center()
8257 } else {
8258 Autoscroll::fit()
8259 };
8260
8261 let text_layout_details = &self.text_layout_details(window);
8262 self.change_selections(Some(autoscroll), window, cx, |s| {
8263 let line_mode = s.line_mode;
8264 s.move_with(|map, selection| {
8265 if !selection.is_empty() && !line_mode {
8266 selection.goal = SelectionGoal::None;
8267 }
8268 let (cursor, goal) = movement::down_by_rows(
8269 map,
8270 selection.end,
8271 row_count,
8272 selection.goal,
8273 false,
8274 text_layout_details,
8275 );
8276 selection.collapse_to(cursor, goal);
8277 });
8278 });
8279 }
8280
8281 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8282 let text_layout_details = &self.text_layout_details(window);
8283 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8284 s.move_heads_with(|map, head, goal| {
8285 movement::down(map, head, goal, false, text_layout_details)
8286 })
8287 });
8288 }
8289
8290 pub fn context_menu_first(
8291 &mut self,
8292 _: &ContextMenuFirst,
8293 _window: &mut Window,
8294 cx: &mut Context<Self>,
8295 ) {
8296 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8297 context_menu.select_first(self.completion_provider.as_deref(), cx);
8298 }
8299 }
8300
8301 pub fn context_menu_prev(
8302 &mut self,
8303 _: &ContextMenuPrev,
8304 _window: &mut Window,
8305 cx: &mut Context<Self>,
8306 ) {
8307 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8308 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8309 }
8310 }
8311
8312 pub fn context_menu_next(
8313 &mut self,
8314 _: &ContextMenuNext,
8315 _window: &mut Window,
8316 cx: &mut Context<Self>,
8317 ) {
8318 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8319 context_menu.select_next(self.completion_provider.as_deref(), cx);
8320 }
8321 }
8322
8323 pub fn context_menu_last(
8324 &mut self,
8325 _: &ContextMenuLast,
8326 _window: &mut Window,
8327 cx: &mut Context<Self>,
8328 ) {
8329 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8330 context_menu.select_last(self.completion_provider.as_deref(), cx);
8331 }
8332 }
8333
8334 pub fn move_to_previous_word_start(
8335 &mut self,
8336 _: &MoveToPreviousWordStart,
8337 window: &mut Window,
8338 cx: &mut Context<Self>,
8339 ) {
8340 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8341 s.move_cursors_with(|map, head, _| {
8342 (
8343 movement::previous_word_start(map, head),
8344 SelectionGoal::None,
8345 )
8346 });
8347 })
8348 }
8349
8350 pub fn move_to_previous_subword_start(
8351 &mut self,
8352 _: &MoveToPreviousSubwordStart,
8353 window: &mut Window,
8354 cx: &mut Context<Self>,
8355 ) {
8356 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8357 s.move_cursors_with(|map, head, _| {
8358 (
8359 movement::previous_subword_start(map, head),
8360 SelectionGoal::None,
8361 )
8362 });
8363 })
8364 }
8365
8366 pub fn select_to_previous_word_start(
8367 &mut self,
8368 _: &SelectToPreviousWordStart,
8369 window: &mut Window,
8370 cx: &mut Context<Self>,
8371 ) {
8372 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8373 s.move_heads_with(|map, head, _| {
8374 (
8375 movement::previous_word_start(map, head),
8376 SelectionGoal::None,
8377 )
8378 });
8379 })
8380 }
8381
8382 pub fn select_to_previous_subword_start(
8383 &mut self,
8384 _: &SelectToPreviousSubwordStart,
8385 window: &mut Window,
8386 cx: &mut Context<Self>,
8387 ) {
8388 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8389 s.move_heads_with(|map, head, _| {
8390 (
8391 movement::previous_subword_start(map, head),
8392 SelectionGoal::None,
8393 )
8394 });
8395 })
8396 }
8397
8398 pub fn delete_to_previous_word_start(
8399 &mut self,
8400 action: &DeleteToPreviousWordStart,
8401 window: &mut Window,
8402 cx: &mut Context<Self>,
8403 ) {
8404 self.transact(window, cx, |this, window, cx| {
8405 this.select_autoclose_pair(window, cx);
8406 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8407 let line_mode = s.line_mode;
8408 s.move_with(|map, selection| {
8409 if selection.is_empty() && !line_mode {
8410 let cursor = if action.ignore_newlines {
8411 movement::previous_word_start(map, selection.head())
8412 } else {
8413 movement::previous_word_start_or_newline(map, selection.head())
8414 };
8415 selection.set_head(cursor, SelectionGoal::None);
8416 }
8417 });
8418 });
8419 this.insert("", window, cx);
8420 });
8421 }
8422
8423 pub fn delete_to_previous_subword_start(
8424 &mut self,
8425 _: &DeleteToPreviousSubwordStart,
8426 window: &mut Window,
8427 cx: &mut Context<Self>,
8428 ) {
8429 self.transact(window, cx, |this, window, cx| {
8430 this.select_autoclose_pair(window, cx);
8431 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8432 let line_mode = s.line_mode;
8433 s.move_with(|map, selection| {
8434 if selection.is_empty() && !line_mode {
8435 let cursor = movement::previous_subword_start(map, selection.head());
8436 selection.set_head(cursor, SelectionGoal::None);
8437 }
8438 });
8439 });
8440 this.insert("", window, cx);
8441 });
8442 }
8443
8444 pub fn move_to_next_word_end(
8445 &mut self,
8446 _: &MoveToNextWordEnd,
8447 window: &mut Window,
8448 cx: &mut Context<Self>,
8449 ) {
8450 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8451 s.move_cursors_with(|map, head, _| {
8452 (movement::next_word_end(map, head), SelectionGoal::None)
8453 });
8454 })
8455 }
8456
8457 pub fn move_to_next_subword_end(
8458 &mut self,
8459 _: &MoveToNextSubwordEnd,
8460 window: &mut Window,
8461 cx: &mut Context<Self>,
8462 ) {
8463 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8464 s.move_cursors_with(|map, head, _| {
8465 (movement::next_subword_end(map, head), SelectionGoal::None)
8466 });
8467 })
8468 }
8469
8470 pub fn select_to_next_word_end(
8471 &mut self,
8472 _: &SelectToNextWordEnd,
8473 window: &mut Window,
8474 cx: &mut Context<Self>,
8475 ) {
8476 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8477 s.move_heads_with(|map, head, _| {
8478 (movement::next_word_end(map, head), SelectionGoal::None)
8479 });
8480 })
8481 }
8482
8483 pub fn select_to_next_subword_end(
8484 &mut self,
8485 _: &SelectToNextSubwordEnd,
8486 window: &mut Window,
8487 cx: &mut Context<Self>,
8488 ) {
8489 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8490 s.move_heads_with(|map, head, _| {
8491 (movement::next_subword_end(map, head), SelectionGoal::None)
8492 });
8493 })
8494 }
8495
8496 pub fn delete_to_next_word_end(
8497 &mut self,
8498 action: &DeleteToNextWordEnd,
8499 window: &mut Window,
8500 cx: &mut Context<Self>,
8501 ) {
8502 self.transact(window, cx, |this, window, cx| {
8503 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8504 let line_mode = s.line_mode;
8505 s.move_with(|map, selection| {
8506 if selection.is_empty() && !line_mode {
8507 let cursor = if action.ignore_newlines {
8508 movement::next_word_end(map, selection.head())
8509 } else {
8510 movement::next_word_end_or_newline(map, selection.head())
8511 };
8512 selection.set_head(cursor, SelectionGoal::None);
8513 }
8514 });
8515 });
8516 this.insert("", window, cx);
8517 });
8518 }
8519
8520 pub fn delete_to_next_subword_end(
8521 &mut self,
8522 _: &DeleteToNextSubwordEnd,
8523 window: &mut Window,
8524 cx: &mut Context<Self>,
8525 ) {
8526 self.transact(window, cx, |this, window, cx| {
8527 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8528 s.move_with(|map, selection| {
8529 if selection.is_empty() {
8530 let cursor = movement::next_subword_end(map, selection.head());
8531 selection.set_head(cursor, SelectionGoal::None);
8532 }
8533 });
8534 });
8535 this.insert("", window, cx);
8536 });
8537 }
8538
8539 pub fn move_to_beginning_of_line(
8540 &mut self,
8541 action: &MoveToBeginningOfLine,
8542 window: &mut Window,
8543 cx: &mut Context<Self>,
8544 ) {
8545 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8546 s.move_cursors_with(|map, head, _| {
8547 (
8548 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8549 SelectionGoal::None,
8550 )
8551 });
8552 })
8553 }
8554
8555 pub fn select_to_beginning_of_line(
8556 &mut self,
8557 action: &SelectToBeginningOfLine,
8558 window: &mut Window,
8559 cx: &mut Context<Self>,
8560 ) {
8561 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8562 s.move_heads_with(|map, head, _| {
8563 (
8564 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8565 SelectionGoal::None,
8566 )
8567 });
8568 });
8569 }
8570
8571 pub fn delete_to_beginning_of_line(
8572 &mut self,
8573 _: &DeleteToBeginningOfLine,
8574 window: &mut Window,
8575 cx: &mut Context<Self>,
8576 ) {
8577 self.transact(window, cx, |this, window, cx| {
8578 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8579 s.move_with(|_, selection| {
8580 selection.reversed = true;
8581 });
8582 });
8583
8584 this.select_to_beginning_of_line(
8585 &SelectToBeginningOfLine {
8586 stop_at_soft_wraps: false,
8587 },
8588 window,
8589 cx,
8590 );
8591 this.backspace(&Backspace, window, cx);
8592 });
8593 }
8594
8595 pub fn move_to_end_of_line(
8596 &mut self,
8597 action: &MoveToEndOfLine,
8598 window: &mut Window,
8599 cx: &mut Context<Self>,
8600 ) {
8601 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8602 s.move_cursors_with(|map, head, _| {
8603 (
8604 movement::line_end(map, head, action.stop_at_soft_wraps),
8605 SelectionGoal::None,
8606 )
8607 });
8608 })
8609 }
8610
8611 pub fn select_to_end_of_line(
8612 &mut self,
8613 action: &SelectToEndOfLine,
8614 window: &mut Window,
8615 cx: &mut Context<Self>,
8616 ) {
8617 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8618 s.move_heads_with(|map, head, _| {
8619 (
8620 movement::line_end(map, head, action.stop_at_soft_wraps),
8621 SelectionGoal::None,
8622 )
8623 });
8624 })
8625 }
8626
8627 pub fn delete_to_end_of_line(
8628 &mut self,
8629 _: &DeleteToEndOfLine,
8630 window: &mut Window,
8631 cx: &mut Context<Self>,
8632 ) {
8633 self.transact(window, cx, |this, window, cx| {
8634 this.select_to_end_of_line(
8635 &SelectToEndOfLine {
8636 stop_at_soft_wraps: false,
8637 },
8638 window,
8639 cx,
8640 );
8641 this.delete(&Delete, window, cx);
8642 });
8643 }
8644
8645 pub fn cut_to_end_of_line(
8646 &mut self,
8647 _: &CutToEndOfLine,
8648 window: &mut Window,
8649 cx: &mut Context<Self>,
8650 ) {
8651 self.transact(window, cx, |this, window, cx| {
8652 this.select_to_end_of_line(
8653 &SelectToEndOfLine {
8654 stop_at_soft_wraps: false,
8655 },
8656 window,
8657 cx,
8658 );
8659 this.cut(&Cut, window, cx);
8660 });
8661 }
8662
8663 pub fn move_to_start_of_paragraph(
8664 &mut self,
8665 _: &MoveToStartOfParagraph,
8666 window: &mut Window,
8667 cx: &mut Context<Self>,
8668 ) {
8669 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8670 cx.propagate();
8671 return;
8672 }
8673
8674 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8675 s.move_with(|map, selection| {
8676 selection.collapse_to(
8677 movement::start_of_paragraph(map, selection.head(), 1),
8678 SelectionGoal::None,
8679 )
8680 });
8681 })
8682 }
8683
8684 pub fn move_to_end_of_paragraph(
8685 &mut self,
8686 _: &MoveToEndOfParagraph,
8687 window: &mut Window,
8688 cx: &mut Context<Self>,
8689 ) {
8690 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8691 cx.propagate();
8692 return;
8693 }
8694
8695 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8696 s.move_with(|map, selection| {
8697 selection.collapse_to(
8698 movement::end_of_paragraph(map, selection.head(), 1),
8699 SelectionGoal::None,
8700 )
8701 });
8702 })
8703 }
8704
8705 pub fn select_to_start_of_paragraph(
8706 &mut self,
8707 _: &SelectToStartOfParagraph,
8708 window: &mut Window,
8709 cx: &mut Context<Self>,
8710 ) {
8711 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8712 cx.propagate();
8713 return;
8714 }
8715
8716 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8717 s.move_heads_with(|map, head, _| {
8718 (
8719 movement::start_of_paragraph(map, head, 1),
8720 SelectionGoal::None,
8721 )
8722 });
8723 })
8724 }
8725
8726 pub fn select_to_end_of_paragraph(
8727 &mut self,
8728 _: &SelectToEndOfParagraph,
8729 window: &mut Window,
8730 cx: &mut Context<Self>,
8731 ) {
8732 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8733 cx.propagate();
8734 return;
8735 }
8736
8737 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8738 s.move_heads_with(|map, head, _| {
8739 (
8740 movement::end_of_paragraph(map, head, 1),
8741 SelectionGoal::None,
8742 )
8743 });
8744 })
8745 }
8746
8747 pub fn move_to_beginning(
8748 &mut self,
8749 _: &MoveToBeginning,
8750 window: &mut Window,
8751 cx: &mut Context<Self>,
8752 ) {
8753 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8754 cx.propagate();
8755 return;
8756 }
8757
8758 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8759 s.select_ranges(vec![0..0]);
8760 });
8761 }
8762
8763 pub fn select_to_beginning(
8764 &mut self,
8765 _: &SelectToBeginning,
8766 window: &mut Window,
8767 cx: &mut Context<Self>,
8768 ) {
8769 let mut selection = self.selections.last::<Point>(cx);
8770 selection.set_head(Point::zero(), SelectionGoal::None);
8771
8772 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8773 s.select(vec![selection]);
8774 });
8775 }
8776
8777 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
8778 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8779 cx.propagate();
8780 return;
8781 }
8782
8783 let cursor = self.buffer.read(cx).read(cx).len();
8784 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8785 s.select_ranges(vec![cursor..cursor])
8786 });
8787 }
8788
8789 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8790 self.nav_history = nav_history;
8791 }
8792
8793 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8794 self.nav_history.as_ref()
8795 }
8796
8797 fn push_to_nav_history(
8798 &mut self,
8799 cursor_anchor: Anchor,
8800 new_position: Option<Point>,
8801 cx: &mut Context<Self>,
8802 ) {
8803 if let Some(nav_history) = self.nav_history.as_mut() {
8804 let buffer = self.buffer.read(cx).read(cx);
8805 let cursor_position = cursor_anchor.to_point(&buffer);
8806 let scroll_state = self.scroll_manager.anchor();
8807 let scroll_top_row = scroll_state.top_row(&buffer);
8808 drop(buffer);
8809
8810 if let Some(new_position) = new_position {
8811 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8812 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8813 return;
8814 }
8815 }
8816
8817 nav_history.push(
8818 Some(NavigationData {
8819 cursor_anchor,
8820 cursor_position,
8821 scroll_anchor: scroll_state,
8822 scroll_top_row,
8823 }),
8824 cx,
8825 );
8826 }
8827 }
8828
8829 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
8830 let buffer = self.buffer.read(cx).snapshot(cx);
8831 let mut selection = self.selections.first::<usize>(cx);
8832 selection.set_head(buffer.len(), SelectionGoal::None);
8833 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8834 s.select(vec![selection]);
8835 });
8836 }
8837
8838 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
8839 let end = self.buffer.read(cx).read(cx).len();
8840 self.change_selections(None, window, cx, |s| {
8841 s.select_ranges(vec![0..end]);
8842 });
8843 }
8844
8845 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
8846 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8847 let mut selections = self.selections.all::<Point>(cx);
8848 let max_point = display_map.buffer_snapshot.max_point();
8849 for selection in &mut selections {
8850 let rows = selection.spanned_rows(true, &display_map);
8851 selection.start = Point::new(rows.start.0, 0);
8852 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8853 selection.reversed = false;
8854 }
8855 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8856 s.select(selections);
8857 });
8858 }
8859
8860 pub fn split_selection_into_lines(
8861 &mut self,
8862 _: &SplitSelectionIntoLines,
8863 window: &mut Window,
8864 cx: &mut Context<Self>,
8865 ) {
8866 let mut to_unfold = Vec::new();
8867 let mut new_selection_ranges = Vec::new();
8868 {
8869 let selections = self.selections.all::<Point>(cx);
8870 let buffer = self.buffer.read(cx).read(cx);
8871 for selection in selections {
8872 for row in selection.start.row..selection.end.row {
8873 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8874 new_selection_ranges.push(cursor..cursor);
8875 }
8876 new_selection_ranges.push(selection.end..selection.end);
8877 to_unfold.push(selection.start..selection.end);
8878 }
8879 }
8880 self.unfold_ranges(&to_unfold, true, true, cx);
8881 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8882 s.select_ranges(new_selection_ranges);
8883 });
8884 }
8885
8886 pub fn add_selection_above(
8887 &mut self,
8888 _: &AddSelectionAbove,
8889 window: &mut Window,
8890 cx: &mut Context<Self>,
8891 ) {
8892 self.add_selection(true, window, cx);
8893 }
8894
8895 pub fn add_selection_below(
8896 &mut self,
8897 _: &AddSelectionBelow,
8898 window: &mut Window,
8899 cx: &mut Context<Self>,
8900 ) {
8901 self.add_selection(false, window, cx);
8902 }
8903
8904 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
8905 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8906 let mut selections = self.selections.all::<Point>(cx);
8907 let text_layout_details = self.text_layout_details(window);
8908 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8909 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8910 let range = oldest_selection.display_range(&display_map).sorted();
8911
8912 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8913 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8914 let positions = start_x.min(end_x)..start_x.max(end_x);
8915
8916 selections.clear();
8917 let mut stack = Vec::new();
8918 for row in range.start.row().0..=range.end.row().0 {
8919 if let Some(selection) = self.selections.build_columnar_selection(
8920 &display_map,
8921 DisplayRow(row),
8922 &positions,
8923 oldest_selection.reversed,
8924 &text_layout_details,
8925 ) {
8926 stack.push(selection.id);
8927 selections.push(selection);
8928 }
8929 }
8930
8931 if above {
8932 stack.reverse();
8933 }
8934
8935 AddSelectionsState { above, stack }
8936 });
8937
8938 let last_added_selection = *state.stack.last().unwrap();
8939 let mut new_selections = Vec::new();
8940 if above == state.above {
8941 let end_row = if above {
8942 DisplayRow(0)
8943 } else {
8944 display_map.max_point().row()
8945 };
8946
8947 'outer: for selection in selections {
8948 if selection.id == last_added_selection {
8949 let range = selection.display_range(&display_map).sorted();
8950 debug_assert_eq!(range.start.row(), range.end.row());
8951 let mut row = range.start.row();
8952 let positions =
8953 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8954 px(start)..px(end)
8955 } else {
8956 let start_x =
8957 display_map.x_for_display_point(range.start, &text_layout_details);
8958 let end_x =
8959 display_map.x_for_display_point(range.end, &text_layout_details);
8960 start_x.min(end_x)..start_x.max(end_x)
8961 };
8962
8963 while row != end_row {
8964 if above {
8965 row.0 -= 1;
8966 } else {
8967 row.0 += 1;
8968 }
8969
8970 if let Some(new_selection) = self.selections.build_columnar_selection(
8971 &display_map,
8972 row,
8973 &positions,
8974 selection.reversed,
8975 &text_layout_details,
8976 ) {
8977 state.stack.push(new_selection.id);
8978 if above {
8979 new_selections.push(new_selection);
8980 new_selections.push(selection);
8981 } else {
8982 new_selections.push(selection);
8983 new_selections.push(new_selection);
8984 }
8985
8986 continue 'outer;
8987 }
8988 }
8989 }
8990
8991 new_selections.push(selection);
8992 }
8993 } else {
8994 new_selections = selections;
8995 new_selections.retain(|s| s.id != last_added_selection);
8996 state.stack.pop();
8997 }
8998
8999 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9000 s.select(new_selections);
9001 });
9002 if state.stack.len() > 1 {
9003 self.add_selections_state = Some(state);
9004 }
9005 }
9006
9007 pub fn select_next_match_internal(
9008 &mut self,
9009 display_map: &DisplaySnapshot,
9010 replace_newest: bool,
9011 autoscroll: Option<Autoscroll>,
9012 window: &mut Window,
9013 cx: &mut Context<Self>,
9014 ) -> Result<()> {
9015 fn select_next_match_ranges(
9016 this: &mut Editor,
9017 range: Range<usize>,
9018 replace_newest: bool,
9019 auto_scroll: Option<Autoscroll>,
9020 window: &mut Window,
9021 cx: &mut Context<Editor>,
9022 ) {
9023 this.unfold_ranges(&[range.clone()], false, true, cx);
9024 this.change_selections(auto_scroll, window, cx, |s| {
9025 if replace_newest {
9026 s.delete(s.newest_anchor().id);
9027 }
9028 s.insert_range(range.clone());
9029 });
9030 }
9031
9032 let buffer = &display_map.buffer_snapshot;
9033 let mut selections = self.selections.all::<usize>(cx);
9034 if let Some(mut select_next_state) = self.select_next_state.take() {
9035 let query = &select_next_state.query;
9036 if !select_next_state.done {
9037 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9038 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9039 let mut next_selected_range = None;
9040
9041 let bytes_after_last_selection =
9042 buffer.bytes_in_range(last_selection.end..buffer.len());
9043 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
9044 let query_matches = query
9045 .stream_find_iter(bytes_after_last_selection)
9046 .map(|result| (last_selection.end, result))
9047 .chain(
9048 query
9049 .stream_find_iter(bytes_before_first_selection)
9050 .map(|result| (0, result)),
9051 );
9052
9053 for (start_offset, query_match) in query_matches {
9054 let query_match = query_match.unwrap(); // can only fail due to I/O
9055 let offset_range =
9056 start_offset + query_match.start()..start_offset + query_match.end();
9057 let display_range = offset_range.start.to_display_point(display_map)
9058 ..offset_range.end.to_display_point(display_map);
9059
9060 if !select_next_state.wordwise
9061 || (!movement::is_inside_word(display_map, display_range.start)
9062 && !movement::is_inside_word(display_map, display_range.end))
9063 {
9064 // TODO: This is n^2, because we might check all the selections
9065 if !selections
9066 .iter()
9067 .any(|selection| selection.range().overlaps(&offset_range))
9068 {
9069 next_selected_range = Some(offset_range);
9070 break;
9071 }
9072 }
9073 }
9074
9075 if let Some(next_selected_range) = next_selected_range {
9076 select_next_match_ranges(
9077 self,
9078 next_selected_range,
9079 replace_newest,
9080 autoscroll,
9081 window,
9082 cx,
9083 );
9084 } else {
9085 select_next_state.done = true;
9086 }
9087 }
9088
9089 self.select_next_state = Some(select_next_state);
9090 } else {
9091 let mut only_carets = true;
9092 let mut same_text_selected = true;
9093 let mut selected_text = None;
9094
9095 let mut selections_iter = selections.iter().peekable();
9096 while let Some(selection) = selections_iter.next() {
9097 if selection.start != selection.end {
9098 only_carets = false;
9099 }
9100
9101 if same_text_selected {
9102 if selected_text.is_none() {
9103 selected_text =
9104 Some(buffer.text_for_range(selection.range()).collect::<String>());
9105 }
9106
9107 if let Some(next_selection) = selections_iter.peek() {
9108 if next_selection.range().len() == selection.range().len() {
9109 let next_selected_text = buffer
9110 .text_for_range(next_selection.range())
9111 .collect::<String>();
9112 if Some(next_selected_text) != selected_text {
9113 same_text_selected = false;
9114 selected_text = None;
9115 }
9116 } else {
9117 same_text_selected = false;
9118 selected_text = None;
9119 }
9120 }
9121 }
9122 }
9123
9124 if only_carets {
9125 for selection in &mut selections {
9126 let word_range = movement::surrounding_word(
9127 display_map,
9128 selection.start.to_display_point(display_map),
9129 );
9130 selection.start = word_range.start.to_offset(display_map, Bias::Left);
9131 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9132 selection.goal = SelectionGoal::None;
9133 selection.reversed = false;
9134 select_next_match_ranges(
9135 self,
9136 selection.start..selection.end,
9137 replace_newest,
9138 autoscroll,
9139 window,
9140 cx,
9141 );
9142 }
9143
9144 if selections.len() == 1 {
9145 let selection = selections
9146 .last()
9147 .expect("ensured that there's only one selection");
9148 let query = buffer
9149 .text_for_range(selection.start..selection.end)
9150 .collect::<String>();
9151 let is_empty = query.is_empty();
9152 let select_state = SelectNextState {
9153 query: AhoCorasick::new(&[query])?,
9154 wordwise: true,
9155 done: is_empty,
9156 };
9157 self.select_next_state = Some(select_state);
9158 } else {
9159 self.select_next_state = None;
9160 }
9161 } else if let Some(selected_text) = selected_text {
9162 self.select_next_state = Some(SelectNextState {
9163 query: AhoCorasick::new(&[selected_text])?,
9164 wordwise: false,
9165 done: false,
9166 });
9167 self.select_next_match_internal(
9168 display_map,
9169 replace_newest,
9170 autoscroll,
9171 window,
9172 cx,
9173 )?;
9174 }
9175 }
9176 Ok(())
9177 }
9178
9179 pub fn select_all_matches(
9180 &mut self,
9181 _action: &SelectAllMatches,
9182 window: &mut Window,
9183 cx: &mut Context<Self>,
9184 ) -> Result<()> {
9185 self.push_to_selection_history();
9186 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9187
9188 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9189 let Some(select_next_state) = self.select_next_state.as_mut() else {
9190 return Ok(());
9191 };
9192 if select_next_state.done {
9193 return Ok(());
9194 }
9195
9196 let mut new_selections = self.selections.all::<usize>(cx);
9197
9198 let buffer = &display_map.buffer_snapshot;
9199 let query_matches = select_next_state
9200 .query
9201 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9202
9203 for query_match in query_matches {
9204 let query_match = query_match.unwrap(); // can only fail due to I/O
9205 let offset_range = query_match.start()..query_match.end();
9206 let display_range = offset_range.start.to_display_point(&display_map)
9207 ..offset_range.end.to_display_point(&display_map);
9208
9209 if !select_next_state.wordwise
9210 || (!movement::is_inside_word(&display_map, display_range.start)
9211 && !movement::is_inside_word(&display_map, display_range.end))
9212 {
9213 self.selections.change_with(cx, |selections| {
9214 new_selections.push(Selection {
9215 id: selections.new_selection_id(),
9216 start: offset_range.start,
9217 end: offset_range.end,
9218 reversed: false,
9219 goal: SelectionGoal::None,
9220 });
9221 });
9222 }
9223 }
9224
9225 new_selections.sort_by_key(|selection| selection.start);
9226 let mut ix = 0;
9227 while ix + 1 < new_selections.len() {
9228 let current_selection = &new_selections[ix];
9229 let next_selection = &new_selections[ix + 1];
9230 if current_selection.range().overlaps(&next_selection.range()) {
9231 if current_selection.id < next_selection.id {
9232 new_selections.remove(ix + 1);
9233 } else {
9234 new_selections.remove(ix);
9235 }
9236 } else {
9237 ix += 1;
9238 }
9239 }
9240
9241 let reversed = self.selections.oldest::<usize>(cx).reversed;
9242
9243 for selection in new_selections.iter_mut() {
9244 selection.reversed = reversed;
9245 }
9246
9247 select_next_state.done = true;
9248 self.unfold_ranges(
9249 &new_selections
9250 .iter()
9251 .map(|selection| selection.range())
9252 .collect::<Vec<_>>(),
9253 false,
9254 false,
9255 cx,
9256 );
9257 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9258 selections.select(new_selections)
9259 });
9260
9261 Ok(())
9262 }
9263
9264 pub fn select_next(
9265 &mut self,
9266 action: &SelectNext,
9267 window: &mut Window,
9268 cx: &mut Context<Self>,
9269 ) -> Result<()> {
9270 self.push_to_selection_history();
9271 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9272 self.select_next_match_internal(
9273 &display_map,
9274 action.replace_newest,
9275 Some(Autoscroll::newest()),
9276 window,
9277 cx,
9278 )?;
9279 Ok(())
9280 }
9281
9282 pub fn select_previous(
9283 &mut self,
9284 action: &SelectPrevious,
9285 window: &mut Window,
9286 cx: &mut Context<Self>,
9287 ) -> Result<()> {
9288 self.push_to_selection_history();
9289 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9290 let buffer = &display_map.buffer_snapshot;
9291 let mut selections = self.selections.all::<usize>(cx);
9292 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9293 let query = &select_prev_state.query;
9294 if !select_prev_state.done {
9295 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9296 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9297 let mut next_selected_range = None;
9298 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9299 let bytes_before_last_selection =
9300 buffer.reversed_bytes_in_range(0..last_selection.start);
9301 let bytes_after_first_selection =
9302 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9303 let query_matches = query
9304 .stream_find_iter(bytes_before_last_selection)
9305 .map(|result| (last_selection.start, result))
9306 .chain(
9307 query
9308 .stream_find_iter(bytes_after_first_selection)
9309 .map(|result| (buffer.len(), result)),
9310 );
9311 for (end_offset, query_match) in query_matches {
9312 let query_match = query_match.unwrap(); // can only fail due to I/O
9313 let offset_range =
9314 end_offset - query_match.end()..end_offset - query_match.start();
9315 let display_range = offset_range.start.to_display_point(&display_map)
9316 ..offset_range.end.to_display_point(&display_map);
9317
9318 if !select_prev_state.wordwise
9319 || (!movement::is_inside_word(&display_map, display_range.start)
9320 && !movement::is_inside_word(&display_map, display_range.end))
9321 {
9322 next_selected_range = Some(offset_range);
9323 break;
9324 }
9325 }
9326
9327 if let Some(next_selected_range) = next_selected_range {
9328 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9329 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9330 if action.replace_newest {
9331 s.delete(s.newest_anchor().id);
9332 }
9333 s.insert_range(next_selected_range);
9334 });
9335 } else {
9336 select_prev_state.done = true;
9337 }
9338 }
9339
9340 self.select_prev_state = Some(select_prev_state);
9341 } else {
9342 let mut only_carets = true;
9343 let mut same_text_selected = true;
9344 let mut selected_text = None;
9345
9346 let mut selections_iter = selections.iter().peekable();
9347 while let Some(selection) = selections_iter.next() {
9348 if selection.start != selection.end {
9349 only_carets = false;
9350 }
9351
9352 if same_text_selected {
9353 if selected_text.is_none() {
9354 selected_text =
9355 Some(buffer.text_for_range(selection.range()).collect::<String>());
9356 }
9357
9358 if let Some(next_selection) = selections_iter.peek() {
9359 if next_selection.range().len() == selection.range().len() {
9360 let next_selected_text = buffer
9361 .text_for_range(next_selection.range())
9362 .collect::<String>();
9363 if Some(next_selected_text) != selected_text {
9364 same_text_selected = false;
9365 selected_text = None;
9366 }
9367 } else {
9368 same_text_selected = false;
9369 selected_text = None;
9370 }
9371 }
9372 }
9373 }
9374
9375 if only_carets {
9376 for selection in &mut selections {
9377 let word_range = movement::surrounding_word(
9378 &display_map,
9379 selection.start.to_display_point(&display_map),
9380 );
9381 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9382 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9383 selection.goal = SelectionGoal::None;
9384 selection.reversed = false;
9385 }
9386 if selections.len() == 1 {
9387 let selection = selections
9388 .last()
9389 .expect("ensured that there's only one selection");
9390 let query = buffer
9391 .text_for_range(selection.start..selection.end)
9392 .collect::<String>();
9393 let is_empty = query.is_empty();
9394 let select_state = SelectNextState {
9395 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9396 wordwise: true,
9397 done: is_empty,
9398 };
9399 self.select_prev_state = Some(select_state);
9400 } else {
9401 self.select_prev_state = None;
9402 }
9403
9404 self.unfold_ranges(
9405 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9406 false,
9407 true,
9408 cx,
9409 );
9410 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9411 s.select(selections);
9412 });
9413 } else if let Some(selected_text) = selected_text {
9414 self.select_prev_state = Some(SelectNextState {
9415 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9416 wordwise: false,
9417 done: false,
9418 });
9419 self.select_previous(action, window, cx)?;
9420 }
9421 }
9422 Ok(())
9423 }
9424
9425 pub fn toggle_comments(
9426 &mut self,
9427 action: &ToggleComments,
9428 window: &mut Window,
9429 cx: &mut Context<Self>,
9430 ) {
9431 if self.read_only(cx) {
9432 return;
9433 }
9434 let text_layout_details = &self.text_layout_details(window);
9435 self.transact(window, cx, |this, window, cx| {
9436 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9437 let mut edits = Vec::new();
9438 let mut selection_edit_ranges = Vec::new();
9439 let mut last_toggled_row = None;
9440 let snapshot = this.buffer.read(cx).read(cx);
9441 let empty_str: Arc<str> = Arc::default();
9442 let mut suffixes_inserted = Vec::new();
9443 let ignore_indent = action.ignore_indent;
9444
9445 fn comment_prefix_range(
9446 snapshot: &MultiBufferSnapshot,
9447 row: MultiBufferRow,
9448 comment_prefix: &str,
9449 comment_prefix_whitespace: &str,
9450 ignore_indent: bool,
9451 ) -> Range<Point> {
9452 let indent_size = if ignore_indent {
9453 0
9454 } else {
9455 snapshot.indent_size_for_line(row).len
9456 };
9457
9458 let start = Point::new(row.0, indent_size);
9459
9460 let mut line_bytes = snapshot
9461 .bytes_in_range(start..snapshot.max_point())
9462 .flatten()
9463 .copied();
9464
9465 // If this line currently begins with the line comment prefix, then record
9466 // the range containing the prefix.
9467 if line_bytes
9468 .by_ref()
9469 .take(comment_prefix.len())
9470 .eq(comment_prefix.bytes())
9471 {
9472 // Include any whitespace that matches the comment prefix.
9473 let matching_whitespace_len = line_bytes
9474 .zip(comment_prefix_whitespace.bytes())
9475 .take_while(|(a, b)| a == b)
9476 .count() as u32;
9477 let end = Point::new(
9478 start.row,
9479 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9480 );
9481 start..end
9482 } else {
9483 start..start
9484 }
9485 }
9486
9487 fn comment_suffix_range(
9488 snapshot: &MultiBufferSnapshot,
9489 row: MultiBufferRow,
9490 comment_suffix: &str,
9491 comment_suffix_has_leading_space: bool,
9492 ) -> Range<Point> {
9493 let end = Point::new(row.0, snapshot.line_len(row));
9494 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9495
9496 let mut line_end_bytes = snapshot
9497 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9498 .flatten()
9499 .copied();
9500
9501 let leading_space_len = if suffix_start_column > 0
9502 && line_end_bytes.next() == Some(b' ')
9503 && comment_suffix_has_leading_space
9504 {
9505 1
9506 } else {
9507 0
9508 };
9509
9510 // If this line currently begins with the line comment prefix, then record
9511 // the range containing the prefix.
9512 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9513 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9514 start..end
9515 } else {
9516 end..end
9517 }
9518 }
9519
9520 // TODO: Handle selections that cross excerpts
9521 for selection in &mut selections {
9522 let start_column = snapshot
9523 .indent_size_for_line(MultiBufferRow(selection.start.row))
9524 .len;
9525 let language = if let Some(language) =
9526 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9527 {
9528 language
9529 } else {
9530 continue;
9531 };
9532
9533 selection_edit_ranges.clear();
9534
9535 // If multiple selections contain a given row, avoid processing that
9536 // row more than once.
9537 let mut start_row = MultiBufferRow(selection.start.row);
9538 if last_toggled_row == Some(start_row) {
9539 start_row = start_row.next_row();
9540 }
9541 let end_row =
9542 if selection.end.row > selection.start.row && selection.end.column == 0 {
9543 MultiBufferRow(selection.end.row - 1)
9544 } else {
9545 MultiBufferRow(selection.end.row)
9546 };
9547 last_toggled_row = Some(end_row);
9548
9549 if start_row > end_row {
9550 continue;
9551 }
9552
9553 // If the language has line comments, toggle those.
9554 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9555
9556 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9557 if ignore_indent {
9558 full_comment_prefixes = full_comment_prefixes
9559 .into_iter()
9560 .map(|s| Arc::from(s.trim_end()))
9561 .collect();
9562 }
9563
9564 if !full_comment_prefixes.is_empty() {
9565 let first_prefix = full_comment_prefixes
9566 .first()
9567 .expect("prefixes is non-empty");
9568 let prefix_trimmed_lengths = full_comment_prefixes
9569 .iter()
9570 .map(|p| p.trim_end_matches(' ').len())
9571 .collect::<SmallVec<[usize; 4]>>();
9572
9573 let mut all_selection_lines_are_comments = true;
9574
9575 for row in start_row.0..=end_row.0 {
9576 let row = MultiBufferRow(row);
9577 if start_row < end_row && snapshot.is_line_blank(row) {
9578 continue;
9579 }
9580
9581 let prefix_range = full_comment_prefixes
9582 .iter()
9583 .zip(prefix_trimmed_lengths.iter().copied())
9584 .map(|(prefix, trimmed_prefix_len)| {
9585 comment_prefix_range(
9586 snapshot.deref(),
9587 row,
9588 &prefix[..trimmed_prefix_len],
9589 &prefix[trimmed_prefix_len..],
9590 ignore_indent,
9591 )
9592 })
9593 .max_by_key(|range| range.end.column - range.start.column)
9594 .expect("prefixes is non-empty");
9595
9596 if prefix_range.is_empty() {
9597 all_selection_lines_are_comments = false;
9598 }
9599
9600 selection_edit_ranges.push(prefix_range);
9601 }
9602
9603 if all_selection_lines_are_comments {
9604 edits.extend(
9605 selection_edit_ranges
9606 .iter()
9607 .cloned()
9608 .map(|range| (range, empty_str.clone())),
9609 );
9610 } else {
9611 let min_column = selection_edit_ranges
9612 .iter()
9613 .map(|range| range.start.column)
9614 .min()
9615 .unwrap_or(0);
9616 edits.extend(selection_edit_ranges.iter().map(|range| {
9617 let position = Point::new(range.start.row, min_column);
9618 (position..position, first_prefix.clone())
9619 }));
9620 }
9621 } else if let Some((full_comment_prefix, comment_suffix)) =
9622 language.block_comment_delimiters()
9623 {
9624 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9625 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9626 let prefix_range = comment_prefix_range(
9627 snapshot.deref(),
9628 start_row,
9629 comment_prefix,
9630 comment_prefix_whitespace,
9631 ignore_indent,
9632 );
9633 let suffix_range = comment_suffix_range(
9634 snapshot.deref(),
9635 end_row,
9636 comment_suffix.trim_start_matches(' '),
9637 comment_suffix.starts_with(' '),
9638 );
9639
9640 if prefix_range.is_empty() || suffix_range.is_empty() {
9641 edits.push((
9642 prefix_range.start..prefix_range.start,
9643 full_comment_prefix.clone(),
9644 ));
9645 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9646 suffixes_inserted.push((end_row, comment_suffix.len()));
9647 } else {
9648 edits.push((prefix_range, empty_str.clone()));
9649 edits.push((suffix_range, empty_str.clone()));
9650 }
9651 } else {
9652 continue;
9653 }
9654 }
9655
9656 drop(snapshot);
9657 this.buffer.update(cx, |buffer, cx| {
9658 buffer.edit(edits, None, cx);
9659 });
9660
9661 // Adjust selections so that they end before any comment suffixes that
9662 // were inserted.
9663 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9664 let mut selections = this.selections.all::<Point>(cx);
9665 let snapshot = this.buffer.read(cx).read(cx);
9666 for selection in &mut selections {
9667 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9668 match row.cmp(&MultiBufferRow(selection.end.row)) {
9669 Ordering::Less => {
9670 suffixes_inserted.next();
9671 continue;
9672 }
9673 Ordering::Greater => break,
9674 Ordering::Equal => {
9675 if selection.end.column == snapshot.line_len(row) {
9676 if selection.is_empty() {
9677 selection.start.column -= suffix_len as u32;
9678 }
9679 selection.end.column -= suffix_len as u32;
9680 }
9681 break;
9682 }
9683 }
9684 }
9685 }
9686
9687 drop(snapshot);
9688 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9689 s.select(selections)
9690 });
9691
9692 let selections = this.selections.all::<Point>(cx);
9693 let selections_on_single_row = selections.windows(2).all(|selections| {
9694 selections[0].start.row == selections[1].start.row
9695 && selections[0].end.row == selections[1].end.row
9696 && selections[0].start.row == selections[0].end.row
9697 });
9698 let selections_selecting = selections
9699 .iter()
9700 .any(|selection| selection.start != selection.end);
9701 let advance_downwards = action.advance_downwards
9702 && selections_on_single_row
9703 && !selections_selecting
9704 && !matches!(this.mode, EditorMode::SingleLine { .. });
9705
9706 if advance_downwards {
9707 let snapshot = this.buffer.read(cx).snapshot(cx);
9708
9709 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9710 s.move_cursors_with(|display_snapshot, display_point, _| {
9711 let mut point = display_point.to_point(display_snapshot);
9712 point.row += 1;
9713 point = snapshot.clip_point(point, Bias::Left);
9714 let display_point = point.to_display_point(display_snapshot);
9715 let goal = SelectionGoal::HorizontalPosition(
9716 display_snapshot
9717 .x_for_display_point(display_point, text_layout_details)
9718 .into(),
9719 );
9720 (display_point, goal)
9721 })
9722 });
9723 }
9724 });
9725 }
9726
9727 pub fn select_enclosing_symbol(
9728 &mut self,
9729 _: &SelectEnclosingSymbol,
9730 window: &mut Window,
9731 cx: &mut Context<Self>,
9732 ) {
9733 let buffer = self.buffer.read(cx).snapshot(cx);
9734 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9735
9736 fn update_selection(
9737 selection: &Selection<usize>,
9738 buffer_snap: &MultiBufferSnapshot,
9739 ) -> Option<Selection<usize>> {
9740 let cursor = selection.head();
9741 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9742 for symbol in symbols.iter().rev() {
9743 let start = symbol.range.start.to_offset(buffer_snap);
9744 let end = symbol.range.end.to_offset(buffer_snap);
9745 let new_range = start..end;
9746 if start < selection.start || end > selection.end {
9747 return Some(Selection {
9748 id: selection.id,
9749 start: new_range.start,
9750 end: new_range.end,
9751 goal: SelectionGoal::None,
9752 reversed: selection.reversed,
9753 });
9754 }
9755 }
9756 None
9757 }
9758
9759 let mut selected_larger_symbol = false;
9760 let new_selections = old_selections
9761 .iter()
9762 .map(|selection| match update_selection(selection, &buffer) {
9763 Some(new_selection) => {
9764 if new_selection.range() != selection.range() {
9765 selected_larger_symbol = true;
9766 }
9767 new_selection
9768 }
9769 None => selection.clone(),
9770 })
9771 .collect::<Vec<_>>();
9772
9773 if selected_larger_symbol {
9774 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9775 s.select(new_selections);
9776 });
9777 }
9778 }
9779
9780 pub fn select_larger_syntax_node(
9781 &mut self,
9782 _: &SelectLargerSyntaxNode,
9783 window: &mut Window,
9784 cx: &mut Context<Self>,
9785 ) {
9786 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9787 let buffer = self.buffer.read(cx).snapshot(cx);
9788 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9789
9790 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9791 let mut selected_larger_node = false;
9792 let new_selections = old_selections
9793 .iter()
9794 .map(|selection| {
9795 let old_range = selection.start..selection.end;
9796 let mut new_range = old_range.clone();
9797 let mut new_node = None;
9798 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
9799 {
9800 new_node = Some(node);
9801 new_range = containing_range;
9802 if !display_map.intersects_fold(new_range.start)
9803 && !display_map.intersects_fold(new_range.end)
9804 {
9805 break;
9806 }
9807 }
9808
9809 if let Some(node) = new_node {
9810 // Log the ancestor, to support using this action as a way to explore TreeSitter
9811 // nodes. Parent and grandparent are also logged because this operation will not
9812 // visit nodes that have the same range as their parent.
9813 log::info!("Node: {node:?}");
9814 let parent = node.parent();
9815 log::info!("Parent: {parent:?}");
9816 let grandparent = parent.and_then(|x| x.parent());
9817 log::info!("Grandparent: {grandparent:?}");
9818 }
9819
9820 selected_larger_node |= new_range != old_range;
9821 Selection {
9822 id: selection.id,
9823 start: new_range.start,
9824 end: new_range.end,
9825 goal: SelectionGoal::None,
9826 reversed: selection.reversed,
9827 }
9828 })
9829 .collect::<Vec<_>>();
9830
9831 if selected_larger_node {
9832 stack.push(old_selections);
9833 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9834 s.select(new_selections);
9835 });
9836 }
9837 self.select_larger_syntax_node_stack = stack;
9838 }
9839
9840 pub fn select_smaller_syntax_node(
9841 &mut self,
9842 _: &SelectSmallerSyntaxNode,
9843 window: &mut Window,
9844 cx: &mut Context<Self>,
9845 ) {
9846 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9847 if let Some(selections) = stack.pop() {
9848 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9849 s.select(selections.to_vec());
9850 });
9851 }
9852 self.select_larger_syntax_node_stack = stack;
9853 }
9854
9855 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
9856 if !EditorSettings::get_global(cx).gutter.runnables {
9857 self.clear_tasks();
9858 return Task::ready(());
9859 }
9860 let project = self.project.as_ref().map(Entity::downgrade);
9861 cx.spawn_in(window, |this, mut cx| async move {
9862 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
9863 let Some(project) = project.and_then(|p| p.upgrade()) else {
9864 return;
9865 };
9866 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9867 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9868 }) else {
9869 return;
9870 };
9871
9872 let hide_runnables = project
9873 .update(&mut cx, |project, cx| {
9874 // Do not display any test indicators in non-dev server remote projects.
9875 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9876 })
9877 .unwrap_or(true);
9878 if hide_runnables {
9879 return;
9880 }
9881 let new_rows =
9882 cx.background_executor()
9883 .spawn({
9884 let snapshot = display_snapshot.clone();
9885 async move {
9886 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9887 }
9888 })
9889 .await;
9890
9891 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9892 this.update(&mut cx, |this, _| {
9893 this.clear_tasks();
9894 for (key, value) in rows {
9895 this.insert_tasks(key, value);
9896 }
9897 })
9898 .ok();
9899 })
9900 }
9901 fn fetch_runnable_ranges(
9902 snapshot: &DisplaySnapshot,
9903 range: Range<Anchor>,
9904 ) -> Vec<language::RunnableRange> {
9905 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9906 }
9907
9908 fn runnable_rows(
9909 project: Entity<Project>,
9910 snapshot: DisplaySnapshot,
9911 runnable_ranges: Vec<RunnableRange>,
9912 mut cx: AsyncWindowContext,
9913 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9914 runnable_ranges
9915 .into_iter()
9916 .filter_map(|mut runnable| {
9917 let tasks = cx
9918 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9919 .ok()?;
9920 if tasks.is_empty() {
9921 return None;
9922 }
9923
9924 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9925
9926 let row = snapshot
9927 .buffer_snapshot
9928 .buffer_line_for_row(MultiBufferRow(point.row))?
9929 .1
9930 .start
9931 .row;
9932
9933 let context_range =
9934 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9935 Some((
9936 (runnable.buffer_id, row),
9937 RunnableTasks {
9938 templates: tasks,
9939 offset: MultiBufferOffset(runnable.run_range.start),
9940 context_range,
9941 column: point.column,
9942 extra_variables: runnable.extra_captures,
9943 },
9944 ))
9945 })
9946 .collect()
9947 }
9948
9949 fn templates_with_tags(
9950 project: &Entity<Project>,
9951 runnable: &mut Runnable,
9952 cx: &mut App,
9953 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9954 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9955 let (worktree_id, file) = project
9956 .buffer_for_id(runnable.buffer, cx)
9957 .and_then(|buffer| buffer.read(cx).file())
9958 .map(|file| (file.worktree_id(cx), file.clone()))
9959 .unzip();
9960
9961 (
9962 project.task_store().read(cx).task_inventory().cloned(),
9963 worktree_id,
9964 file,
9965 )
9966 });
9967
9968 let tags = mem::take(&mut runnable.tags);
9969 let mut tags: Vec<_> = tags
9970 .into_iter()
9971 .flat_map(|tag| {
9972 let tag = tag.0.clone();
9973 inventory
9974 .as_ref()
9975 .into_iter()
9976 .flat_map(|inventory| {
9977 inventory.read(cx).list_tasks(
9978 file.clone(),
9979 Some(runnable.language.clone()),
9980 worktree_id,
9981 cx,
9982 )
9983 })
9984 .filter(move |(_, template)| {
9985 template.tags.iter().any(|source_tag| source_tag == &tag)
9986 })
9987 })
9988 .sorted_by_key(|(kind, _)| kind.to_owned())
9989 .collect();
9990 if let Some((leading_tag_source, _)) = tags.first() {
9991 // Strongest source wins; if we have worktree tag binding, prefer that to
9992 // global and language bindings;
9993 // if we have a global binding, prefer that to language binding.
9994 let first_mismatch = tags
9995 .iter()
9996 .position(|(tag_source, _)| tag_source != leading_tag_source);
9997 if let Some(index) = first_mismatch {
9998 tags.truncate(index);
9999 }
10000 }
10001
10002 tags
10003 }
10004
10005 pub fn move_to_enclosing_bracket(
10006 &mut self,
10007 _: &MoveToEnclosingBracket,
10008 window: &mut Window,
10009 cx: &mut Context<Self>,
10010 ) {
10011 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10012 s.move_offsets_with(|snapshot, selection| {
10013 let Some(enclosing_bracket_ranges) =
10014 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10015 else {
10016 return;
10017 };
10018
10019 let mut best_length = usize::MAX;
10020 let mut best_inside = false;
10021 let mut best_in_bracket_range = false;
10022 let mut best_destination = None;
10023 for (open, close) in enclosing_bracket_ranges {
10024 let close = close.to_inclusive();
10025 let length = close.end() - open.start;
10026 let inside = selection.start >= open.end && selection.end <= *close.start();
10027 let in_bracket_range = open.to_inclusive().contains(&selection.head())
10028 || close.contains(&selection.head());
10029
10030 // If best is next to a bracket and current isn't, skip
10031 if !in_bracket_range && best_in_bracket_range {
10032 continue;
10033 }
10034
10035 // Prefer smaller lengths unless best is inside and current isn't
10036 if length > best_length && (best_inside || !inside) {
10037 continue;
10038 }
10039
10040 best_length = length;
10041 best_inside = inside;
10042 best_in_bracket_range = in_bracket_range;
10043 best_destination = Some(
10044 if close.contains(&selection.start) && close.contains(&selection.end) {
10045 if inside {
10046 open.end
10047 } else {
10048 open.start
10049 }
10050 } else if inside {
10051 *close.start()
10052 } else {
10053 *close.end()
10054 },
10055 );
10056 }
10057
10058 if let Some(destination) = best_destination {
10059 selection.collapse_to(destination, SelectionGoal::None);
10060 }
10061 })
10062 });
10063 }
10064
10065 pub fn undo_selection(
10066 &mut self,
10067 _: &UndoSelection,
10068 window: &mut Window,
10069 cx: &mut Context<Self>,
10070 ) {
10071 self.end_selection(window, cx);
10072 self.selection_history.mode = SelectionHistoryMode::Undoing;
10073 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10074 self.change_selections(None, window, cx, |s| {
10075 s.select_anchors(entry.selections.to_vec())
10076 });
10077 self.select_next_state = entry.select_next_state;
10078 self.select_prev_state = entry.select_prev_state;
10079 self.add_selections_state = entry.add_selections_state;
10080 self.request_autoscroll(Autoscroll::newest(), cx);
10081 }
10082 self.selection_history.mode = SelectionHistoryMode::Normal;
10083 }
10084
10085 pub fn redo_selection(
10086 &mut self,
10087 _: &RedoSelection,
10088 window: &mut Window,
10089 cx: &mut Context<Self>,
10090 ) {
10091 self.end_selection(window, cx);
10092 self.selection_history.mode = SelectionHistoryMode::Redoing;
10093 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10094 self.change_selections(None, window, cx, |s| {
10095 s.select_anchors(entry.selections.to_vec())
10096 });
10097 self.select_next_state = entry.select_next_state;
10098 self.select_prev_state = entry.select_prev_state;
10099 self.add_selections_state = entry.add_selections_state;
10100 self.request_autoscroll(Autoscroll::newest(), cx);
10101 }
10102 self.selection_history.mode = SelectionHistoryMode::Normal;
10103 }
10104
10105 pub fn expand_excerpts(
10106 &mut self,
10107 action: &ExpandExcerpts,
10108 _: &mut Window,
10109 cx: &mut Context<Self>,
10110 ) {
10111 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10112 }
10113
10114 pub fn expand_excerpts_down(
10115 &mut self,
10116 action: &ExpandExcerptsDown,
10117 _: &mut Window,
10118 cx: &mut Context<Self>,
10119 ) {
10120 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10121 }
10122
10123 pub fn expand_excerpts_up(
10124 &mut self,
10125 action: &ExpandExcerptsUp,
10126 _: &mut Window,
10127 cx: &mut Context<Self>,
10128 ) {
10129 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10130 }
10131
10132 pub fn expand_excerpts_for_direction(
10133 &mut self,
10134 lines: u32,
10135 direction: ExpandExcerptDirection,
10136
10137 cx: &mut Context<Self>,
10138 ) {
10139 let selections = self.selections.disjoint_anchors();
10140
10141 let lines = if lines == 0 {
10142 EditorSettings::get_global(cx).expand_excerpt_lines
10143 } else {
10144 lines
10145 };
10146
10147 self.buffer.update(cx, |buffer, cx| {
10148 let snapshot = buffer.snapshot(cx);
10149 let mut excerpt_ids = selections
10150 .iter()
10151 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10152 .collect::<Vec<_>>();
10153 excerpt_ids.sort();
10154 excerpt_ids.dedup();
10155 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10156 })
10157 }
10158
10159 pub fn expand_excerpt(
10160 &mut self,
10161 excerpt: ExcerptId,
10162 direction: ExpandExcerptDirection,
10163 cx: &mut Context<Self>,
10164 ) {
10165 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10166 self.buffer.update(cx, |buffer, cx| {
10167 buffer.expand_excerpts([excerpt], lines, direction, cx)
10168 })
10169 }
10170
10171 pub fn go_to_singleton_buffer_point(
10172 &mut self,
10173 point: Point,
10174 window: &mut Window,
10175 cx: &mut Context<Self>,
10176 ) {
10177 self.go_to_singleton_buffer_range(point..point, window, cx);
10178 }
10179
10180 pub fn go_to_singleton_buffer_range(
10181 &mut self,
10182 range: Range<Point>,
10183 window: &mut Window,
10184 cx: &mut Context<Self>,
10185 ) {
10186 let multibuffer = self.buffer().read(cx);
10187 let Some(buffer) = multibuffer.as_singleton() else {
10188 return;
10189 };
10190 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10191 return;
10192 };
10193 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10194 return;
10195 };
10196 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10197 s.select_anchor_ranges([start..end])
10198 });
10199 }
10200
10201 fn go_to_diagnostic(
10202 &mut self,
10203 _: &GoToDiagnostic,
10204 window: &mut Window,
10205 cx: &mut Context<Self>,
10206 ) {
10207 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10208 }
10209
10210 fn go_to_prev_diagnostic(
10211 &mut self,
10212 _: &GoToPrevDiagnostic,
10213 window: &mut Window,
10214 cx: &mut Context<Self>,
10215 ) {
10216 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10217 }
10218
10219 pub fn go_to_diagnostic_impl(
10220 &mut self,
10221 direction: Direction,
10222 window: &mut Window,
10223 cx: &mut Context<Self>,
10224 ) {
10225 let buffer = self.buffer.read(cx).snapshot(cx);
10226 let selection = self.selections.newest::<usize>(cx);
10227
10228 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10229 if direction == Direction::Next {
10230 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10231 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10232 return;
10233 };
10234 self.activate_diagnostics(
10235 buffer_id,
10236 popover.local_diagnostic.diagnostic.group_id,
10237 window,
10238 cx,
10239 );
10240 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10241 let primary_range_start = active_diagnostics.primary_range.start;
10242 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10243 let mut new_selection = s.newest_anchor().clone();
10244 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10245 s.select_anchors(vec![new_selection.clone()]);
10246 });
10247 self.refresh_inline_completion(false, true, window, cx);
10248 }
10249 return;
10250 }
10251 }
10252
10253 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10254 active_diagnostics
10255 .primary_range
10256 .to_offset(&buffer)
10257 .to_inclusive()
10258 });
10259 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10260 if active_primary_range.contains(&selection.head()) {
10261 *active_primary_range.start()
10262 } else {
10263 selection.head()
10264 }
10265 } else {
10266 selection.head()
10267 };
10268 let snapshot = self.snapshot(window, cx);
10269 loop {
10270 let mut diagnostics;
10271 if direction == Direction::Prev {
10272 diagnostics = buffer
10273 .diagnostics_in_range::<usize>(0..search_start)
10274 .collect::<Vec<_>>();
10275 diagnostics.reverse();
10276 } else {
10277 diagnostics = buffer
10278 .diagnostics_in_range::<usize>(search_start..buffer.len())
10279 .collect::<Vec<_>>();
10280 };
10281 let group = diagnostics
10282 .into_iter()
10283 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10284 // relies on diagnostics_in_range to return diagnostics with the same starting range to
10285 // be sorted in a stable way
10286 // skip until we are at current active diagnostic, if it exists
10287 .skip_while(|entry| {
10288 let is_in_range = match direction {
10289 Direction::Prev => entry.range.end > search_start,
10290 Direction::Next => entry.range.start < search_start,
10291 };
10292 is_in_range
10293 && self
10294 .active_diagnostics
10295 .as_ref()
10296 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
10297 })
10298 .find_map(|entry| {
10299 if entry.diagnostic.is_primary
10300 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
10301 && entry.range.start != entry.range.end
10302 {
10303 let entry_group = entry.diagnostic.group_id;
10304 let in_next_group = self.active_diagnostics.as_ref().map_or(
10305 true,
10306 |active| match direction {
10307 Direction::Prev => {
10308 entry_group != active.group_id
10309 && (active.group_id == 0 || entry_group < active.group_id)
10310 }
10311 Direction::Next => {
10312 entry_group != active.group_id
10313 && (entry_group == 0 || entry_group > active.group_id)
10314 }
10315 },
10316 );
10317 if in_next_group {
10318 return Some((entry.range, entry.diagnostic.group_id));
10319 }
10320 }
10321 None
10322 });
10323
10324 if let Some((primary_range, group_id)) = group {
10325 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10326 return;
10327 };
10328 self.activate_diagnostics(buffer_id, group_id, window, cx);
10329 if self.active_diagnostics.is_some() {
10330 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10331 s.select(vec![Selection {
10332 id: selection.id,
10333 start: primary_range.start,
10334 end: primary_range.start,
10335 reversed: false,
10336 goal: SelectionGoal::None,
10337 }]);
10338 });
10339 self.refresh_inline_completion(false, true, window, cx);
10340 }
10341 break;
10342 } else {
10343 // Cycle around to the start of the buffer, potentially moving back to the start of
10344 // the currently active diagnostic.
10345 active_primary_range.take();
10346 if direction == Direction::Prev {
10347 if search_start == buffer.len() {
10348 break;
10349 } else {
10350 search_start = buffer.len();
10351 }
10352 } else if search_start == 0 {
10353 break;
10354 } else {
10355 search_start = 0;
10356 }
10357 }
10358 }
10359 }
10360
10361 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10362 let snapshot = self.snapshot(window, cx);
10363 let selection = self.selections.newest::<Point>(cx);
10364 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10365 }
10366
10367 fn go_to_hunk_after_position(
10368 &mut self,
10369 snapshot: &EditorSnapshot,
10370 position: Point,
10371 window: &mut Window,
10372 cx: &mut Context<Editor>,
10373 ) -> Option<MultiBufferDiffHunk> {
10374 let mut hunk = snapshot
10375 .buffer_snapshot
10376 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10377 .find(|hunk| hunk.row_range.start.0 > position.row);
10378 if hunk.is_none() {
10379 hunk = snapshot
10380 .buffer_snapshot
10381 .diff_hunks_in_range(Point::zero()..position)
10382 .find(|hunk| hunk.row_range.end.0 < position.row)
10383 }
10384 if let Some(hunk) = &hunk {
10385 let destination = Point::new(hunk.row_range.start.0, 0);
10386 self.unfold_ranges(&[destination..destination], false, false, cx);
10387 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10388 s.select_ranges(vec![destination..destination]);
10389 });
10390 }
10391
10392 hunk
10393 }
10394
10395 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10396 let snapshot = self.snapshot(window, cx);
10397 let selection = self.selections.newest::<Point>(cx);
10398 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10399 }
10400
10401 fn go_to_hunk_before_position(
10402 &mut self,
10403 snapshot: &EditorSnapshot,
10404 position: Point,
10405 window: &mut Window,
10406 cx: &mut Context<Editor>,
10407 ) -> Option<MultiBufferDiffHunk> {
10408 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10409 if hunk.is_none() {
10410 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10411 }
10412 if let Some(hunk) = &hunk {
10413 let destination = Point::new(hunk.row_range.start.0, 0);
10414 self.unfold_ranges(&[destination..destination], false, false, cx);
10415 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10416 s.select_ranges(vec![destination..destination]);
10417 });
10418 }
10419
10420 hunk
10421 }
10422
10423 pub fn go_to_definition(
10424 &mut self,
10425 _: &GoToDefinition,
10426 window: &mut Window,
10427 cx: &mut Context<Self>,
10428 ) -> Task<Result<Navigated>> {
10429 let definition =
10430 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10431 cx.spawn_in(window, |editor, mut cx| async move {
10432 if definition.await? == Navigated::Yes {
10433 return Ok(Navigated::Yes);
10434 }
10435 match editor.update_in(&mut cx, |editor, window, cx| {
10436 editor.find_all_references(&FindAllReferences, window, cx)
10437 })? {
10438 Some(references) => references.await,
10439 None => Ok(Navigated::No),
10440 }
10441 })
10442 }
10443
10444 pub fn go_to_declaration(
10445 &mut self,
10446 _: &GoToDeclaration,
10447 window: &mut Window,
10448 cx: &mut Context<Self>,
10449 ) -> Task<Result<Navigated>> {
10450 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10451 }
10452
10453 pub fn go_to_declaration_split(
10454 &mut self,
10455 _: &GoToDeclaration,
10456 window: &mut Window,
10457 cx: &mut Context<Self>,
10458 ) -> Task<Result<Navigated>> {
10459 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10460 }
10461
10462 pub fn go_to_implementation(
10463 &mut self,
10464 _: &GoToImplementation,
10465 window: &mut Window,
10466 cx: &mut Context<Self>,
10467 ) -> Task<Result<Navigated>> {
10468 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10469 }
10470
10471 pub fn go_to_implementation_split(
10472 &mut self,
10473 _: &GoToImplementationSplit,
10474 window: &mut Window,
10475 cx: &mut Context<Self>,
10476 ) -> Task<Result<Navigated>> {
10477 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10478 }
10479
10480 pub fn go_to_type_definition(
10481 &mut self,
10482 _: &GoToTypeDefinition,
10483 window: &mut Window,
10484 cx: &mut Context<Self>,
10485 ) -> Task<Result<Navigated>> {
10486 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10487 }
10488
10489 pub fn go_to_definition_split(
10490 &mut self,
10491 _: &GoToDefinitionSplit,
10492 window: &mut Window,
10493 cx: &mut Context<Self>,
10494 ) -> Task<Result<Navigated>> {
10495 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10496 }
10497
10498 pub fn go_to_type_definition_split(
10499 &mut self,
10500 _: &GoToTypeDefinitionSplit,
10501 window: &mut Window,
10502 cx: &mut Context<Self>,
10503 ) -> Task<Result<Navigated>> {
10504 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10505 }
10506
10507 fn go_to_definition_of_kind(
10508 &mut self,
10509 kind: GotoDefinitionKind,
10510 split: bool,
10511 window: &mut Window,
10512 cx: &mut Context<Self>,
10513 ) -> Task<Result<Navigated>> {
10514 let Some(provider) = self.semantics_provider.clone() else {
10515 return Task::ready(Ok(Navigated::No));
10516 };
10517 let head = self.selections.newest::<usize>(cx).head();
10518 let buffer = self.buffer.read(cx);
10519 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10520 text_anchor
10521 } else {
10522 return Task::ready(Ok(Navigated::No));
10523 };
10524
10525 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10526 return Task::ready(Ok(Navigated::No));
10527 };
10528
10529 cx.spawn_in(window, |editor, mut cx| async move {
10530 let definitions = definitions.await?;
10531 let navigated = editor
10532 .update_in(&mut cx, |editor, window, cx| {
10533 editor.navigate_to_hover_links(
10534 Some(kind),
10535 definitions
10536 .into_iter()
10537 .filter(|location| {
10538 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10539 })
10540 .map(HoverLink::Text)
10541 .collect::<Vec<_>>(),
10542 split,
10543 window,
10544 cx,
10545 )
10546 })?
10547 .await?;
10548 anyhow::Ok(navigated)
10549 })
10550 }
10551
10552 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10553 let selection = self.selections.newest_anchor();
10554 let head = selection.head();
10555 let tail = selection.tail();
10556
10557 let Some((buffer, start_position)) =
10558 self.buffer.read(cx).text_anchor_for_position(head, cx)
10559 else {
10560 return;
10561 };
10562
10563 let end_position = if head != tail {
10564 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10565 return;
10566 };
10567 Some(pos)
10568 } else {
10569 None
10570 };
10571
10572 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10573 let url = if let Some(end_pos) = end_position {
10574 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10575 } else {
10576 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10577 };
10578
10579 if let Some(url) = url {
10580 editor.update(&mut cx, |_, cx| {
10581 cx.open_url(&url);
10582 })
10583 } else {
10584 Ok(())
10585 }
10586 });
10587
10588 url_finder.detach();
10589 }
10590
10591 pub fn open_selected_filename(
10592 &mut self,
10593 _: &OpenSelectedFilename,
10594 window: &mut Window,
10595 cx: &mut Context<Self>,
10596 ) {
10597 let Some(workspace) = self.workspace() else {
10598 return;
10599 };
10600
10601 let position = self.selections.newest_anchor().head();
10602
10603 let Some((buffer, buffer_position)) =
10604 self.buffer.read(cx).text_anchor_for_position(position, cx)
10605 else {
10606 return;
10607 };
10608
10609 let project = self.project.clone();
10610
10611 cx.spawn_in(window, |_, mut cx| async move {
10612 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10613
10614 if let Some((_, path)) = result {
10615 workspace
10616 .update_in(&mut cx, |workspace, window, cx| {
10617 workspace.open_resolved_path(path, window, cx)
10618 })?
10619 .await?;
10620 }
10621 anyhow::Ok(())
10622 })
10623 .detach();
10624 }
10625
10626 pub(crate) fn navigate_to_hover_links(
10627 &mut self,
10628 kind: Option<GotoDefinitionKind>,
10629 mut definitions: Vec<HoverLink>,
10630 split: bool,
10631 window: &mut Window,
10632 cx: &mut Context<Editor>,
10633 ) -> Task<Result<Navigated>> {
10634 // If there is one definition, just open it directly
10635 if definitions.len() == 1 {
10636 let definition = definitions.pop().unwrap();
10637
10638 enum TargetTaskResult {
10639 Location(Option<Location>),
10640 AlreadyNavigated,
10641 }
10642
10643 let target_task = match definition {
10644 HoverLink::Text(link) => {
10645 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10646 }
10647 HoverLink::InlayHint(lsp_location, server_id) => {
10648 let computation =
10649 self.compute_target_location(lsp_location, server_id, window, cx);
10650 cx.background_executor().spawn(async move {
10651 let location = computation.await?;
10652 Ok(TargetTaskResult::Location(location))
10653 })
10654 }
10655 HoverLink::Url(url) => {
10656 cx.open_url(&url);
10657 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10658 }
10659 HoverLink::File(path) => {
10660 if let Some(workspace) = self.workspace() {
10661 cx.spawn_in(window, |_, mut cx| async move {
10662 workspace
10663 .update_in(&mut cx, |workspace, window, cx| {
10664 workspace.open_resolved_path(path, window, cx)
10665 })?
10666 .await
10667 .map(|_| TargetTaskResult::AlreadyNavigated)
10668 })
10669 } else {
10670 Task::ready(Ok(TargetTaskResult::Location(None)))
10671 }
10672 }
10673 };
10674 cx.spawn_in(window, |editor, mut cx| async move {
10675 let target = match target_task.await.context("target resolution task")? {
10676 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10677 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10678 TargetTaskResult::Location(Some(target)) => target,
10679 };
10680
10681 editor.update_in(&mut cx, |editor, window, cx| {
10682 let Some(workspace) = editor.workspace() else {
10683 return Navigated::No;
10684 };
10685 let pane = workspace.read(cx).active_pane().clone();
10686
10687 let range = target.range.to_point(target.buffer.read(cx));
10688 let range = editor.range_for_match(&range);
10689 let range = collapse_multiline_range(range);
10690
10691 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10692 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10693 } else {
10694 window.defer(cx, move |window, cx| {
10695 let target_editor: Entity<Self> =
10696 workspace.update(cx, |workspace, cx| {
10697 let pane = if split {
10698 workspace.adjacent_pane(window, cx)
10699 } else {
10700 workspace.active_pane().clone()
10701 };
10702
10703 workspace.open_project_item(
10704 pane,
10705 target.buffer.clone(),
10706 true,
10707 true,
10708 window,
10709 cx,
10710 )
10711 });
10712 target_editor.update(cx, |target_editor, cx| {
10713 // When selecting a definition in a different buffer, disable the nav history
10714 // to avoid creating a history entry at the previous cursor location.
10715 pane.update(cx, |pane, _| pane.disable_history());
10716 target_editor.go_to_singleton_buffer_range(range, window, cx);
10717 pane.update(cx, |pane, _| pane.enable_history());
10718 });
10719 });
10720 }
10721 Navigated::Yes
10722 })
10723 })
10724 } else if !definitions.is_empty() {
10725 cx.spawn_in(window, |editor, mut cx| async move {
10726 let (title, location_tasks, workspace) = editor
10727 .update_in(&mut cx, |editor, window, cx| {
10728 let tab_kind = match kind {
10729 Some(GotoDefinitionKind::Implementation) => "Implementations",
10730 _ => "Definitions",
10731 };
10732 let title = definitions
10733 .iter()
10734 .find_map(|definition| match definition {
10735 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10736 let buffer = origin.buffer.read(cx);
10737 format!(
10738 "{} for {}",
10739 tab_kind,
10740 buffer
10741 .text_for_range(origin.range.clone())
10742 .collect::<String>()
10743 )
10744 }),
10745 HoverLink::InlayHint(_, _) => None,
10746 HoverLink::Url(_) => None,
10747 HoverLink::File(_) => None,
10748 })
10749 .unwrap_or(tab_kind.to_string());
10750 let location_tasks = definitions
10751 .into_iter()
10752 .map(|definition| match definition {
10753 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10754 HoverLink::InlayHint(lsp_location, server_id) => editor
10755 .compute_target_location(lsp_location, server_id, window, cx),
10756 HoverLink::Url(_) => Task::ready(Ok(None)),
10757 HoverLink::File(_) => Task::ready(Ok(None)),
10758 })
10759 .collect::<Vec<_>>();
10760 (title, location_tasks, editor.workspace().clone())
10761 })
10762 .context("location tasks preparation")?;
10763
10764 let locations = future::join_all(location_tasks)
10765 .await
10766 .into_iter()
10767 .filter_map(|location| location.transpose())
10768 .collect::<Result<_>>()
10769 .context("location tasks")?;
10770
10771 let Some(workspace) = workspace else {
10772 return Ok(Navigated::No);
10773 };
10774 let opened = workspace
10775 .update_in(&mut cx, |workspace, window, cx| {
10776 Self::open_locations_in_multibuffer(
10777 workspace,
10778 locations,
10779 title,
10780 split,
10781 MultibufferSelectionMode::First,
10782 window,
10783 cx,
10784 )
10785 })
10786 .ok();
10787
10788 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10789 })
10790 } else {
10791 Task::ready(Ok(Navigated::No))
10792 }
10793 }
10794
10795 fn compute_target_location(
10796 &self,
10797 lsp_location: lsp::Location,
10798 server_id: LanguageServerId,
10799 window: &mut Window,
10800 cx: &mut Context<Self>,
10801 ) -> Task<anyhow::Result<Option<Location>>> {
10802 let Some(project) = self.project.clone() else {
10803 return Task::ready(Ok(None));
10804 };
10805
10806 cx.spawn_in(window, move |editor, mut cx| async move {
10807 let location_task = editor.update(&mut cx, |_, cx| {
10808 project.update(cx, |project, cx| {
10809 let language_server_name = project
10810 .language_server_statuses(cx)
10811 .find(|(id, _)| server_id == *id)
10812 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10813 language_server_name.map(|language_server_name| {
10814 project.open_local_buffer_via_lsp(
10815 lsp_location.uri.clone(),
10816 server_id,
10817 language_server_name,
10818 cx,
10819 )
10820 })
10821 })
10822 })?;
10823 let location = match location_task {
10824 Some(task) => Some({
10825 let target_buffer_handle = task.await.context("open local buffer")?;
10826 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10827 let target_start = target_buffer
10828 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10829 let target_end = target_buffer
10830 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10831 target_buffer.anchor_after(target_start)
10832 ..target_buffer.anchor_before(target_end)
10833 })?;
10834 Location {
10835 buffer: target_buffer_handle,
10836 range,
10837 }
10838 }),
10839 None => None,
10840 };
10841 Ok(location)
10842 })
10843 }
10844
10845 pub fn find_all_references(
10846 &mut self,
10847 _: &FindAllReferences,
10848 window: &mut Window,
10849 cx: &mut Context<Self>,
10850 ) -> Option<Task<Result<Navigated>>> {
10851 let selection = self.selections.newest::<usize>(cx);
10852 let multi_buffer = self.buffer.read(cx);
10853 let head = selection.head();
10854
10855 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10856 let head_anchor = multi_buffer_snapshot.anchor_at(
10857 head,
10858 if head < selection.tail() {
10859 Bias::Right
10860 } else {
10861 Bias::Left
10862 },
10863 );
10864
10865 match self
10866 .find_all_references_task_sources
10867 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10868 {
10869 Ok(_) => {
10870 log::info!(
10871 "Ignoring repeated FindAllReferences invocation with the position of already running task"
10872 );
10873 return None;
10874 }
10875 Err(i) => {
10876 self.find_all_references_task_sources.insert(i, head_anchor);
10877 }
10878 }
10879
10880 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10881 let workspace = self.workspace()?;
10882 let project = workspace.read(cx).project().clone();
10883 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10884 Some(cx.spawn_in(window, |editor, mut cx| async move {
10885 let _cleanup = defer({
10886 let mut cx = cx.clone();
10887 move || {
10888 let _ = editor.update(&mut cx, |editor, _| {
10889 if let Ok(i) =
10890 editor
10891 .find_all_references_task_sources
10892 .binary_search_by(|anchor| {
10893 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10894 })
10895 {
10896 editor.find_all_references_task_sources.remove(i);
10897 }
10898 });
10899 }
10900 });
10901
10902 let locations = references.await?;
10903 if locations.is_empty() {
10904 return anyhow::Ok(Navigated::No);
10905 }
10906
10907 workspace.update_in(&mut cx, |workspace, window, cx| {
10908 let title = locations
10909 .first()
10910 .as_ref()
10911 .map(|location| {
10912 let buffer = location.buffer.read(cx);
10913 format!(
10914 "References to `{}`",
10915 buffer
10916 .text_for_range(location.range.clone())
10917 .collect::<String>()
10918 )
10919 })
10920 .unwrap();
10921 Self::open_locations_in_multibuffer(
10922 workspace,
10923 locations,
10924 title,
10925 false,
10926 MultibufferSelectionMode::First,
10927 window,
10928 cx,
10929 );
10930 Navigated::Yes
10931 })
10932 }))
10933 }
10934
10935 /// Opens a multibuffer with the given project locations in it
10936 pub fn open_locations_in_multibuffer(
10937 workspace: &mut Workspace,
10938 mut locations: Vec<Location>,
10939 title: String,
10940 split: bool,
10941 multibuffer_selection_mode: MultibufferSelectionMode,
10942 window: &mut Window,
10943 cx: &mut Context<Workspace>,
10944 ) {
10945 // If there are multiple definitions, open them in a multibuffer
10946 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10947 let mut locations = locations.into_iter().peekable();
10948 let mut ranges = Vec::new();
10949 let capability = workspace.project().read(cx).capability();
10950
10951 let excerpt_buffer = cx.new(|cx| {
10952 let mut multibuffer = MultiBuffer::new(capability);
10953 while let Some(location) = locations.next() {
10954 let buffer = location.buffer.read(cx);
10955 let mut ranges_for_buffer = Vec::new();
10956 let range = location.range.to_offset(buffer);
10957 ranges_for_buffer.push(range.clone());
10958
10959 while let Some(next_location) = locations.peek() {
10960 if next_location.buffer == location.buffer {
10961 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10962 locations.next();
10963 } else {
10964 break;
10965 }
10966 }
10967
10968 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10969 ranges.extend(multibuffer.push_excerpts_with_context_lines(
10970 location.buffer.clone(),
10971 ranges_for_buffer,
10972 DEFAULT_MULTIBUFFER_CONTEXT,
10973 cx,
10974 ))
10975 }
10976
10977 multibuffer.with_title(title)
10978 });
10979
10980 let editor = cx.new(|cx| {
10981 Editor::for_multibuffer(
10982 excerpt_buffer,
10983 Some(workspace.project().clone()),
10984 true,
10985 window,
10986 cx,
10987 )
10988 });
10989 editor.update(cx, |editor, cx| {
10990 match multibuffer_selection_mode {
10991 MultibufferSelectionMode::First => {
10992 if let Some(first_range) = ranges.first() {
10993 editor.change_selections(None, window, cx, |selections| {
10994 selections.clear_disjoint();
10995 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10996 });
10997 }
10998 editor.highlight_background::<Self>(
10999 &ranges,
11000 |theme| theme.editor_highlighted_line_background,
11001 cx,
11002 );
11003 }
11004 MultibufferSelectionMode::All => {
11005 editor.change_selections(None, window, cx, |selections| {
11006 selections.clear_disjoint();
11007 selections.select_anchor_ranges(ranges);
11008 });
11009 }
11010 }
11011 editor.register_buffers_with_language_servers(cx);
11012 });
11013
11014 let item = Box::new(editor);
11015 let item_id = item.item_id();
11016
11017 if split {
11018 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11019 } else {
11020 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11021 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11022 pane.close_current_preview_item(window, cx)
11023 } else {
11024 None
11025 }
11026 });
11027 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11028 }
11029 workspace.active_pane().update(cx, |pane, cx| {
11030 pane.set_preview_item_id(Some(item_id), cx);
11031 });
11032 }
11033
11034 pub fn rename(
11035 &mut self,
11036 _: &Rename,
11037 window: &mut Window,
11038 cx: &mut Context<Self>,
11039 ) -> Option<Task<Result<()>>> {
11040 use language::ToOffset as _;
11041
11042 let provider = self.semantics_provider.clone()?;
11043 let selection = self.selections.newest_anchor().clone();
11044 let (cursor_buffer, cursor_buffer_position) = self
11045 .buffer
11046 .read(cx)
11047 .text_anchor_for_position(selection.head(), cx)?;
11048 let (tail_buffer, cursor_buffer_position_end) = self
11049 .buffer
11050 .read(cx)
11051 .text_anchor_for_position(selection.tail(), cx)?;
11052 if tail_buffer != cursor_buffer {
11053 return None;
11054 }
11055
11056 let snapshot = cursor_buffer.read(cx).snapshot();
11057 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11058 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11059 let prepare_rename = provider
11060 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11061 .unwrap_or_else(|| Task::ready(Ok(None)));
11062 drop(snapshot);
11063
11064 Some(cx.spawn_in(window, |this, mut cx| async move {
11065 let rename_range = if let Some(range) = prepare_rename.await? {
11066 Some(range)
11067 } else {
11068 this.update(&mut cx, |this, cx| {
11069 let buffer = this.buffer.read(cx).snapshot(cx);
11070 let mut buffer_highlights = this
11071 .document_highlights_for_position(selection.head(), &buffer)
11072 .filter(|highlight| {
11073 highlight.start.excerpt_id == selection.head().excerpt_id
11074 && highlight.end.excerpt_id == selection.head().excerpt_id
11075 });
11076 buffer_highlights
11077 .next()
11078 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11079 })?
11080 };
11081 if let Some(rename_range) = rename_range {
11082 this.update_in(&mut cx, |this, window, cx| {
11083 let snapshot = cursor_buffer.read(cx).snapshot();
11084 let rename_buffer_range = rename_range.to_offset(&snapshot);
11085 let cursor_offset_in_rename_range =
11086 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11087 let cursor_offset_in_rename_range_end =
11088 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11089
11090 this.take_rename(false, window, cx);
11091 let buffer = this.buffer.read(cx).read(cx);
11092 let cursor_offset = selection.head().to_offset(&buffer);
11093 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11094 let rename_end = rename_start + rename_buffer_range.len();
11095 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11096 let mut old_highlight_id = None;
11097 let old_name: Arc<str> = buffer
11098 .chunks(rename_start..rename_end, true)
11099 .map(|chunk| {
11100 if old_highlight_id.is_none() {
11101 old_highlight_id = chunk.syntax_highlight_id;
11102 }
11103 chunk.text
11104 })
11105 .collect::<String>()
11106 .into();
11107
11108 drop(buffer);
11109
11110 // Position the selection in the rename editor so that it matches the current selection.
11111 this.show_local_selections = false;
11112 let rename_editor = cx.new(|cx| {
11113 let mut editor = Editor::single_line(window, cx);
11114 editor.buffer.update(cx, |buffer, cx| {
11115 buffer.edit([(0..0, old_name.clone())], None, cx)
11116 });
11117 let rename_selection_range = match cursor_offset_in_rename_range
11118 .cmp(&cursor_offset_in_rename_range_end)
11119 {
11120 Ordering::Equal => {
11121 editor.select_all(&SelectAll, window, cx);
11122 return editor;
11123 }
11124 Ordering::Less => {
11125 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11126 }
11127 Ordering::Greater => {
11128 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11129 }
11130 };
11131 if rename_selection_range.end > old_name.len() {
11132 editor.select_all(&SelectAll, window, cx);
11133 } else {
11134 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11135 s.select_ranges([rename_selection_range]);
11136 });
11137 }
11138 editor
11139 });
11140 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11141 if e == &EditorEvent::Focused {
11142 cx.emit(EditorEvent::FocusedIn)
11143 }
11144 })
11145 .detach();
11146
11147 let write_highlights =
11148 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11149 let read_highlights =
11150 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11151 let ranges = write_highlights
11152 .iter()
11153 .flat_map(|(_, ranges)| ranges.iter())
11154 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11155 .cloned()
11156 .collect();
11157
11158 this.highlight_text::<Rename>(
11159 ranges,
11160 HighlightStyle {
11161 fade_out: Some(0.6),
11162 ..Default::default()
11163 },
11164 cx,
11165 );
11166 let rename_focus_handle = rename_editor.focus_handle(cx);
11167 window.focus(&rename_focus_handle);
11168 let block_id = this.insert_blocks(
11169 [BlockProperties {
11170 style: BlockStyle::Flex,
11171 placement: BlockPlacement::Below(range.start),
11172 height: 1,
11173 render: Arc::new({
11174 let rename_editor = rename_editor.clone();
11175 move |cx: &mut BlockContext| {
11176 let mut text_style = cx.editor_style.text.clone();
11177 if let Some(highlight_style) = old_highlight_id
11178 .and_then(|h| h.style(&cx.editor_style.syntax))
11179 {
11180 text_style = text_style.highlight(highlight_style);
11181 }
11182 div()
11183 .block_mouse_down()
11184 .pl(cx.anchor_x)
11185 .child(EditorElement::new(
11186 &rename_editor,
11187 EditorStyle {
11188 background: cx.theme().system().transparent,
11189 local_player: cx.editor_style.local_player,
11190 text: text_style,
11191 scrollbar_width: cx.editor_style.scrollbar_width,
11192 syntax: cx.editor_style.syntax.clone(),
11193 status: cx.editor_style.status.clone(),
11194 inlay_hints_style: HighlightStyle {
11195 font_weight: Some(FontWeight::BOLD),
11196 ..make_inlay_hints_style(cx.app)
11197 },
11198 inline_completion_styles: make_suggestion_styles(
11199 cx.app,
11200 ),
11201 ..EditorStyle::default()
11202 },
11203 ))
11204 .into_any_element()
11205 }
11206 }),
11207 priority: 0,
11208 }],
11209 Some(Autoscroll::fit()),
11210 cx,
11211 )[0];
11212 this.pending_rename = Some(RenameState {
11213 range,
11214 old_name,
11215 editor: rename_editor,
11216 block_id,
11217 });
11218 })?;
11219 }
11220
11221 Ok(())
11222 }))
11223 }
11224
11225 pub fn confirm_rename(
11226 &mut self,
11227 _: &ConfirmRename,
11228 window: &mut Window,
11229 cx: &mut Context<Self>,
11230 ) -> Option<Task<Result<()>>> {
11231 let rename = self.take_rename(false, window, cx)?;
11232 let workspace = self.workspace()?.downgrade();
11233 let (buffer, start) = self
11234 .buffer
11235 .read(cx)
11236 .text_anchor_for_position(rename.range.start, cx)?;
11237 let (end_buffer, _) = self
11238 .buffer
11239 .read(cx)
11240 .text_anchor_for_position(rename.range.end, cx)?;
11241 if buffer != end_buffer {
11242 return None;
11243 }
11244
11245 let old_name = rename.old_name;
11246 let new_name = rename.editor.read(cx).text(cx);
11247
11248 let rename = self.semantics_provider.as_ref()?.perform_rename(
11249 &buffer,
11250 start,
11251 new_name.clone(),
11252 cx,
11253 )?;
11254
11255 Some(cx.spawn_in(window, |editor, mut cx| async move {
11256 let project_transaction = rename.await?;
11257 Self::open_project_transaction(
11258 &editor,
11259 workspace,
11260 project_transaction,
11261 format!("Rename: {} → {}", old_name, new_name),
11262 cx.clone(),
11263 )
11264 .await?;
11265
11266 editor.update(&mut cx, |editor, cx| {
11267 editor.refresh_document_highlights(cx);
11268 })?;
11269 Ok(())
11270 }))
11271 }
11272
11273 fn take_rename(
11274 &mut self,
11275 moving_cursor: bool,
11276 window: &mut Window,
11277 cx: &mut Context<Self>,
11278 ) -> Option<RenameState> {
11279 let rename = self.pending_rename.take()?;
11280 if rename.editor.focus_handle(cx).is_focused(window) {
11281 window.focus(&self.focus_handle);
11282 }
11283
11284 self.remove_blocks(
11285 [rename.block_id].into_iter().collect(),
11286 Some(Autoscroll::fit()),
11287 cx,
11288 );
11289 self.clear_highlights::<Rename>(cx);
11290 self.show_local_selections = true;
11291
11292 if moving_cursor {
11293 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11294 editor.selections.newest::<usize>(cx).head()
11295 });
11296
11297 // Update the selection to match the position of the selection inside
11298 // the rename editor.
11299 let snapshot = self.buffer.read(cx).read(cx);
11300 let rename_range = rename.range.to_offset(&snapshot);
11301 let cursor_in_editor = snapshot
11302 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11303 .min(rename_range.end);
11304 drop(snapshot);
11305
11306 self.change_selections(None, window, cx, |s| {
11307 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11308 });
11309 } else {
11310 self.refresh_document_highlights(cx);
11311 }
11312
11313 Some(rename)
11314 }
11315
11316 pub fn pending_rename(&self) -> Option<&RenameState> {
11317 self.pending_rename.as_ref()
11318 }
11319
11320 fn format(
11321 &mut self,
11322 _: &Format,
11323 window: &mut Window,
11324 cx: &mut Context<Self>,
11325 ) -> Option<Task<Result<()>>> {
11326 let project = match &self.project {
11327 Some(project) => project.clone(),
11328 None => return None,
11329 };
11330
11331 Some(self.perform_format(
11332 project,
11333 FormatTrigger::Manual,
11334 FormatTarget::Buffers,
11335 window,
11336 cx,
11337 ))
11338 }
11339
11340 fn format_selections(
11341 &mut self,
11342 _: &FormatSelections,
11343 window: &mut Window,
11344 cx: &mut Context<Self>,
11345 ) -> Option<Task<Result<()>>> {
11346 let project = match &self.project {
11347 Some(project) => project.clone(),
11348 None => return None,
11349 };
11350
11351 let ranges = self
11352 .selections
11353 .all_adjusted(cx)
11354 .into_iter()
11355 .map(|selection| selection.range())
11356 .collect_vec();
11357
11358 Some(self.perform_format(
11359 project,
11360 FormatTrigger::Manual,
11361 FormatTarget::Ranges(ranges),
11362 window,
11363 cx,
11364 ))
11365 }
11366
11367 fn perform_format(
11368 &mut self,
11369 project: Entity<Project>,
11370 trigger: FormatTrigger,
11371 target: FormatTarget,
11372 window: &mut Window,
11373 cx: &mut Context<Self>,
11374 ) -> Task<Result<()>> {
11375 let buffer = self.buffer.clone();
11376 let (buffers, target) = match target {
11377 FormatTarget::Buffers => {
11378 let mut buffers = buffer.read(cx).all_buffers();
11379 if trigger == FormatTrigger::Save {
11380 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11381 }
11382 (buffers, LspFormatTarget::Buffers)
11383 }
11384 FormatTarget::Ranges(selection_ranges) => {
11385 let multi_buffer = buffer.read(cx);
11386 let snapshot = multi_buffer.read(cx);
11387 let mut buffers = HashSet::default();
11388 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11389 BTreeMap::new();
11390 for selection_range in selection_ranges {
11391 for (buffer, buffer_range, _) in
11392 snapshot.range_to_buffer_ranges(selection_range)
11393 {
11394 let buffer_id = buffer.remote_id();
11395 let start = buffer.anchor_before(buffer_range.start);
11396 let end = buffer.anchor_after(buffer_range.end);
11397 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11398 buffer_id_to_ranges
11399 .entry(buffer_id)
11400 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11401 .or_insert_with(|| vec![start..end]);
11402 }
11403 }
11404 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11405 }
11406 };
11407
11408 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11409 let format = project.update(cx, |project, cx| {
11410 project.format(buffers, target, true, trigger, cx)
11411 });
11412
11413 cx.spawn_in(window, |_, mut cx| async move {
11414 let transaction = futures::select_biased! {
11415 () = timeout => {
11416 log::warn!("timed out waiting for formatting");
11417 None
11418 }
11419 transaction = format.log_err().fuse() => transaction,
11420 };
11421
11422 buffer
11423 .update(&mut cx, |buffer, cx| {
11424 if let Some(transaction) = transaction {
11425 if !buffer.is_singleton() {
11426 buffer.push_transaction(&transaction.0, cx);
11427 }
11428 }
11429
11430 cx.notify();
11431 })
11432 .ok();
11433
11434 Ok(())
11435 })
11436 }
11437
11438 fn restart_language_server(
11439 &mut self,
11440 _: &RestartLanguageServer,
11441 _: &mut Window,
11442 cx: &mut Context<Self>,
11443 ) {
11444 if let Some(project) = self.project.clone() {
11445 self.buffer.update(cx, |multi_buffer, cx| {
11446 project.update(cx, |project, cx| {
11447 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11448 });
11449 })
11450 }
11451 }
11452
11453 fn cancel_language_server_work(
11454 workspace: &mut Workspace,
11455 _: &actions::CancelLanguageServerWork,
11456 _: &mut Window,
11457 cx: &mut Context<Workspace>,
11458 ) {
11459 let project = workspace.project();
11460 let buffers = workspace
11461 .active_item(cx)
11462 .and_then(|item| item.act_as::<Editor>(cx))
11463 .map_or(HashSet::default(), |editor| {
11464 editor.read(cx).buffer.read(cx).all_buffers()
11465 });
11466 project.update(cx, |project, cx| {
11467 project.cancel_language_server_work_for_buffers(buffers, cx);
11468 });
11469 }
11470
11471 fn show_character_palette(
11472 &mut self,
11473 _: &ShowCharacterPalette,
11474 window: &mut Window,
11475 _: &mut Context<Self>,
11476 ) {
11477 window.show_character_palette();
11478 }
11479
11480 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11481 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11482 let buffer = self.buffer.read(cx).snapshot(cx);
11483 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11484 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11485 let is_valid = buffer
11486 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11487 .any(|entry| {
11488 entry.diagnostic.is_primary
11489 && !entry.range.is_empty()
11490 && entry.range.start == primary_range_start
11491 && entry.diagnostic.message == active_diagnostics.primary_message
11492 });
11493
11494 if is_valid != active_diagnostics.is_valid {
11495 active_diagnostics.is_valid = is_valid;
11496 let mut new_styles = HashMap::default();
11497 for (block_id, diagnostic) in &active_diagnostics.blocks {
11498 new_styles.insert(
11499 *block_id,
11500 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11501 );
11502 }
11503 self.display_map.update(cx, |display_map, _cx| {
11504 display_map.replace_blocks(new_styles)
11505 });
11506 }
11507 }
11508 }
11509
11510 fn activate_diagnostics(
11511 &mut self,
11512 buffer_id: BufferId,
11513 group_id: usize,
11514 window: &mut Window,
11515 cx: &mut Context<Self>,
11516 ) {
11517 self.dismiss_diagnostics(cx);
11518 let snapshot = self.snapshot(window, cx);
11519 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11520 let buffer = self.buffer.read(cx).snapshot(cx);
11521
11522 let mut primary_range = None;
11523 let mut primary_message = None;
11524 let diagnostic_group = buffer
11525 .diagnostic_group(buffer_id, group_id)
11526 .filter_map(|entry| {
11527 let start = entry.range.start;
11528 let end = entry.range.end;
11529 if snapshot.is_line_folded(MultiBufferRow(start.row))
11530 && (start.row == end.row
11531 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11532 {
11533 return None;
11534 }
11535 if entry.diagnostic.is_primary {
11536 primary_range = Some(entry.range.clone());
11537 primary_message = Some(entry.diagnostic.message.clone());
11538 }
11539 Some(entry)
11540 })
11541 .collect::<Vec<_>>();
11542 let primary_range = primary_range?;
11543 let primary_message = primary_message?;
11544
11545 let blocks = display_map
11546 .insert_blocks(
11547 diagnostic_group.iter().map(|entry| {
11548 let diagnostic = entry.diagnostic.clone();
11549 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11550 BlockProperties {
11551 style: BlockStyle::Fixed,
11552 placement: BlockPlacement::Below(
11553 buffer.anchor_after(entry.range.start),
11554 ),
11555 height: message_height,
11556 render: diagnostic_block_renderer(diagnostic, None, true, true),
11557 priority: 0,
11558 }
11559 }),
11560 cx,
11561 )
11562 .into_iter()
11563 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11564 .collect();
11565
11566 Some(ActiveDiagnosticGroup {
11567 primary_range: buffer.anchor_before(primary_range.start)
11568 ..buffer.anchor_after(primary_range.end),
11569 primary_message,
11570 group_id,
11571 blocks,
11572 is_valid: true,
11573 })
11574 });
11575 }
11576
11577 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11578 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11579 self.display_map.update(cx, |display_map, cx| {
11580 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11581 });
11582 cx.notify();
11583 }
11584 }
11585
11586 pub fn set_selections_from_remote(
11587 &mut self,
11588 selections: Vec<Selection<Anchor>>,
11589 pending_selection: Option<Selection<Anchor>>,
11590 window: &mut Window,
11591 cx: &mut Context<Self>,
11592 ) {
11593 let old_cursor_position = self.selections.newest_anchor().head();
11594 self.selections.change_with(cx, |s| {
11595 s.select_anchors(selections);
11596 if let Some(pending_selection) = pending_selection {
11597 s.set_pending(pending_selection, SelectMode::Character);
11598 } else {
11599 s.clear_pending();
11600 }
11601 });
11602 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11603 }
11604
11605 fn push_to_selection_history(&mut self) {
11606 self.selection_history.push(SelectionHistoryEntry {
11607 selections: self.selections.disjoint_anchors(),
11608 select_next_state: self.select_next_state.clone(),
11609 select_prev_state: self.select_prev_state.clone(),
11610 add_selections_state: self.add_selections_state.clone(),
11611 });
11612 }
11613
11614 pub fn transact(
11615 &mut self,
11616 window: &mut Window,
11617 cx: &mut Context<Self>,
11618 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11619 ) -> Option<TransactionId> {
11620 self.start_transaction_at(Instant::now(), window, cx);
11621 update(self, window, cx);
11622 self.end_transaction_at(Instant::now(), cx)
11623 }
11624
11625 pub fn start_transaction_at(
11626 &mut self,
11627 now: Instant,
11628 window: &mut Window,
11629 cx: &mut Context<Self>,
11630 ) {
11631 self.end_selection(window, cx);
11632 if let Some(tx_id) = self
11633 .buffer
11634 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11635 {
11636 self.selection_history
11637 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11638 cx.emit(EditorEvent::TransactionBegun {
11639 transaction_id: tx_id,
11640 })
11641 }
11642 }
11643
11644 pub fn end_transaction_at(
11645 &mut self,
11646 now: Instant,
11647 cx: &mut Context<Self>,
11648 ) -> Option<TransactionId> {
11649 if let Some(transaction_id) = self
11650 .buffer
11651 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11652 {
11653 if let Some((_, end_selections)) =
11654 self.selection_history.transaction_mut(transaction_id)
11655 {
11656 *end_selections = Some(self.selections.disjoint_anchors());
11657 } else {
11658 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11659 }
11660
11661 cx.emit(EditorEvent::Edited { transaction_id });
11662 Some(transaction_id)
11663 } else {
11664 None
11665 }
11666 }
11667
11668 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11669 if self.selection_mark_mode {
11670 self.change_selections(None, window, cx, |s| {
11671 s.move_with(|_, sel| {
11672 sel.collapse_to(sel.head(), SelectionGoal::None);
11673 });
11674 })
11675 }
11676 self.selection_mark_mode = true;
11677 cx.notify();
11678 }
11679
11680 pub fn swap_selection_ends(
11681 &mut self,
11682 _: &actions::SwapSelectionEnds,
11683 window: &mut Window,
11684 cx: &mut Context<Self>,
11685 ) {
11686 self.change_selections(None, window, cx, |s| {
11687 s.move_with(|_, sel| {
11688 if sel.start != sel.end {
11689 sel.reversed = !sel.reversed
11690 }
11691 });
11692 });
11693 self.request_autoscroll(Autoscroll::newest(), cx);
11694 cx.notify();
11695 }
11696
11697 pub fn toggle_fold(
11698 &mut self,
11699 _: &actions::ToggleFold,
11700 window: &mut Window,
11701 cx: &mut Context<Self>,
11702 ) {
11703 if self.is_singleton(cx) {
11704 let selection = self.selections.newest::<Point>(cx);
11705
11706 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11707 let range = if selection.is_empty() {
11708 let point = selection.head().to_display_point(&display_map);
11709 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11710 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11711 .to_point(&display_map);
11712 start..end
11713 } else {
11714 selection.range()
11715 };
11716 if display_map.folds_in_range(range).next().is_some() {
11717 self.unfold_lines(&Default::default(), window, cx)
11718 } else {
11719 self.fold(&Default::default(), window, cx)
11720 }
11721 } else {
11722 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11723 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11724 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11725 .map(|(snapshot, _, _)| snapshot.remote_id())
11726 .collect();
11727
11728 for buffer_id in buffer_ids {
11729 if self.is_buffer_folded(buffer_id, cx) {
11730 self.unfold_buffer(buffer_id, cx);
11731 } else {
11732 self.fold_buffer(buffer_id, cx);
11733 }
11734 }
11735 }
11736 }
11737
11738 pub fn toggle_fold_recursive(
11739 &mut self,
11740 _: &actions::ToggleFoldRecursive,
11741 window: &mut Window,
11742 cx: &mut Context<Self>,
11743 ) {
11744 let selection = self.selections.newest::<Point>(cx);
11745
11746 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11747 let range = if selection.is_empty() {
11748 let point = selection.head().to_display_point(&display_map);
11749 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11750 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11751 .to_point(&display_map);
11752 start..end
11753 } else {
11754 selection.range()
11755 };
11756 if display_map.folds_in_range(range).next().is_some() {
11757 self.unfold_recursive(&Default::default(), window, cx)
11758 } else {
11759 self.fold_recursive(&Default::default(), window, cx)
11760 }
11761 }
11762
11763 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11764 if self.is_singleton(cx) {
11765 let mut to_fold = Vec::new();
11766 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11767 let selections = self.selections.all_adjusted(cx);
11768
11769 for selection in selections {
11770 let range = selection.range().sorted();
11771 let buffer_start_row = range.start.row;
11772
11773 if range.start.row != range.end.row {
11774 let mut found = false;
11775 let mut row = range.start.row;
11776 while row <= range.end.row {
11777 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11778 {
11779 found = true;
11780 row = crease.range().end.row + 1;
11781 to_fold.push(crease);
11782 } else {
11783 row += 1
11784 }
11785 }
11786 if found {
11787 continue;
11788 }
11789 }
11790
11791 for row in (0..=range.start.row).rev() {
11792 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11793 if crease.range().end.row >= buffer_start_row {
11794 to_fold.push(crease);
11795 if row <= range.start.row {
11796 break;
11797 }
11798 }
11799 }
11800 }
11801 }
11802
11803 self.fold_creases(to_fold, true, window, cx);
11804 } else {
11805 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11806
11807 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11808 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11809 .map(|(snapshot, _, _)| snapshot.remote_id())
11810 .collect();
11811 for buffer_id in buffer_ids {
11812 self.fold_buffer(buffer_id, cx);
11813 }
11814 }
11815 }
11816
11817 fn fold_at_level(
11818 &mut self,
11819 fold_at: &FoldAtLevel,
11820 window: &mut Window,
11821 cx: &mut Context<Self>,
11822 ) {
11823 if !self.buffer.read(cx).is_singleton() {
11824 return;
11825 }
11826
11827 let fold_at_level = fold_at.0;
11828 let snapshot = self.buffer.read(cx).snapshot(cx);
11829 let mut to_fold = Vec::new();
11830 let mut stack = vec![(0, snapshot.max_row().0, 1)];
11831
11832 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11833 while start_row < end_row {
11834 match self
11835 .snapshot(window, cx)
11836 .crease_for_buffer_row(MultiBufferRow(start_row))
11837 {
11838 Some(crease) => {
11839 let nested_start_row = crease.range().start.row + 1;
11840 let nested_end_row = crease.range().end.row;
11841
11842 if current_level < fold_at_level {
11843 stack.push((nested_start_row, nested_end_row, current_level + 1));
11844 } else if current_level == fold_at_level {
11845 to_fold.push(crease);
11846 }
11847
11848 start_row = nested_end_row + 1;
11849 }
11850 None => start_row += 1,
11851 }
11852 }
11853 }
11854
11855 self.fold_creases(to_fold, true, window, cx);
11856 }
11857
11858 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11859 if self.buffer.read(cx).is_singleton() {
11860 let mut fold_ranges = Vec::new();
11861 let snapshot = self.buffer.read(cx).snapshot(cx);
11862
11863 for row in 0..snapshot.max_row().0 {
11864 if let Some(foldable_range) = self
11865 .snapshot(window, cx)
11866 .crease_for_buffer_row(MultiBufferRow(row))
11867 {
11868 fold_ranges.push(foldable_range);
11869 }
11870 }
11871
11872 self.fold_creases(fold_ranges, true, window, cx);
11873 } else {
11874 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11875 editor
11876 .update_in(&mut cx, |editor, _, cx| {
11877 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11878 editor.fold_buffer(buffer_id, cx);
11879 }
11880 })
11881 .ok();
11882 });
11883 }
11884 }
11885
11886 pub fn fold_function_bodies(
11887 &mut self,
11888 _: &actions::FoldFunctionBodies,
11889 window: &mut Window,
11890 cx: &mut Context<Self>,
11891 ) {
11892 let snapshot = self.buffer.read(cx).snapshot(cx);
11893
11894 let ranges = snapshot
11895 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11896 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11897 .collect::<Vec<_>>();
11898
11899 let creases = ranges
11900 .into_iter()
11901 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11902 .collect();
11903
11904 self.fold_creases(creases, true, window, cx);
11905 }
11906
11907 pub fn fold_recursive(
11908 &mut self,
11909 _: &actions::FoldRecursive,
11910 window: &mut Window,
11911 cx: &mut Context<Self>,
11912 ) {
11913 let mut to_fold = Vec::new();
11914 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11915 let selections = self.selections.all_adjusted(cx);
11916
11917 for selection in selections {
11918 let range = selection.range().sorted();
11919 let buffer_start_row = range.start.row;
11920
11921 if range.start.row != range.end.row {
11922 let mut found = false;
11923 for row in range.start.row..=range.end.row {
11924 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11925 found = true;
11926 to_fold.push(crease);
11927 }
11928 }
11929 if found {
11930 continue;
11931 }
11932 }
11933
11934 for row in (0..=range.start.row).rev() {
11935 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11936 if crease.range().end.row >= buffer_start_row {
11937 to_fold.push(crease);
11938 } else {
11939 break;
11940 }
11941 }
11942 }
11943 }
11944
11945 self.fold_creases(to_fold, true, window, cx);
11946 }
11947
11948 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11949 let buffer_row = fold_at.buffer_row;
11950 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11951
11952 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11953 let autoscroll = self
11954 .selections
11955 .all::<Point>(cx)
11956 .iter()
11957 .any(|selection| crease.range().overlaps(&selection.range()));
11958
11959 self.fold_creases(vec![crease], autoscroll, window, cx);
11960 }
11961 }
11962
11963 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
11964 if self.is_singleton(cx) {
11965 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11966 let buffer = &display_map.buffer_snapshot;
11967 let selections = self.selections.all::<Point>(cx);
11968 let ranges = selections
11969 .iter()
11970 .map(|s| {
11971 let range = s.display_range(&display_map).sorted();
11972 let mut start = range.start.to_point(&display_map);
11973 let mut end = range.end.to_point(&display_map);
11974 start.column = 0;
11975 end.column = buffer.line_len(MultiBufferRow(end.row));
11976 start..end
11977 })
11978 .collect::<Vec<_>>();
11979
11980 self.unfold_ranges(&ranges, true, true, cx);
11981 } else {
11982 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11983 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11984 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11985 .map(|(snapshot, _, _)| snapshot.remote_id())
11986 .collect();
11987 for buffer_id in buffer_ids {
11988 self.unfold_buffer(buffer_id, cx);
11989 }
11990 }
11991 }
11992
11993 pub fn unfold_recursive(
11994 &mut self,
11995 _: &UnfoldRecursive,
11996 _window: &mut Window,
11997 cx: &mut Context<Self>,
11998 ) {
11999 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12000 let selections = self.selections.all::<Point>(cx);
12001 let ranges = selections
12002 .iter()
12003 .map(|s| {
12004 let mut range = s.display_range(&display_map).sorted();
12005 *range.start.column_mut() = 0;
12006 *range.end.column_mut() = display_map.line_len(range.end.row());
12007 let start = range.start.to_point(&display_map);
12008 let end = range.end.to_point(&display_map);
12009 start..end
12010 })
12011 .collect::<Vec<_>>();
12012
12013 self.unfold_ranges(&ranges, true, true, cx);
12014 }
12015
12016 pub fn unfold_at(
12017 &mut self,
12018 unfold_at: &UnfoldAt,
12019 _window: &mut Window,
12020 cx: &mut Context<Self>,
12021 ) {
12022 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12023
12024 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12025 ..Point::new(
12026 unfold_at.buffer_row.0,
12027 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12028 );
12029
12030 let autoscroll = self
12031 .selections
12032 .all::<Point>(cx)
12033 .iter()
12034 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12035
12036 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12037 }
12038
12039 pub fn unfold_all(
12040 &mut self,
12041 _: &actions::UnfoldAll,
12042 _window: &mut Window,
12043 cx: &mut Context<Self>,
12044 ) {
12045 if self.buffer.read(cx).is_singleton() {
12046 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12047 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12048 } else {
12049 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12050 editor
12051 .update(&mut cx, |editor, cx| {
12052 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12053 editor.unfold_buffer(buffer_id, cx);
12054 }
12055 })
12056 .ok();
12057 });
12058 }
12059 }
12060
12061 pub fn fold_selected_ranges(
12062 &mut self,
12063 _: &FoldSelectedRanges,
12064 window: &mut Window,
12065 cx: &mut Context<Self>,
12066 ) {
12067 let selections = self.selections.all::<Point>(cx);
12068 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12069 let line_mode = self.selections.line_mode;
12070 let ranges = selections
12071 .into_iter()
12072 .map(|s| {
12073 if line_mode {
12074 let start = Point::new(s.start.row, 0);
12075 let end = Point::new(
12076 s.end.row,
12077 display_map
12078 .buffer_snapshot
12079 .line_len(MultiBufferRow(s.end.row)),
12080 );
12081 Crease::simple(start..end, display_map.fold_placeholder.clone())
12082 } else {
12083 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12084 }
12085 })
12086 .collect::<Vec<_>>();
12087 self.fold_creases(ranges, true, window, cx);
12088 }
12089
12090 pub fn fold_ranges<T: ToOffset + Clone>(
12091 &mut self,
12092 ranges: Vec<Range<T>>,
12093 auto_scroll: bool,
12094 window: &mut Window,
12095 cx: &mut Context<Self>,
12096 ) {
12097 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12098 let ranges = ranges
12099 .into_iter()
12100 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12101 .collect::<Vec<_>>();
12102 self.fold_creases(ranges, auto_scroll, window, cx);
12103 }
12104
12105 pub fn fold_creases<T: ToOffset + Clone>(
12106 &mut self,
12107 creases: Vec<Crease<T>>,
12108 auto_scroll: bool,
12109 window: &mut Window,
12110 cx: &mut Context<Self>,
12111 ) {
12112 if creases.is_empty() {
12113 return;
12114 }
12115
12116 let mut buffers_affected = HashSet::default();
12117 let multi_buffer = self.buffer().read(cx);
12118 for crease in &creases {
12119 if let Some((_, buffer, _)) =
12120 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12121 {
12122 buffers_affected.insert(buffer.read(cx).remote_id());
12123 };
12124 }
12125
12126 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12127
12128 if auto_scroll {
12129 self.request_autoscroll(Autoscroll::fit(), cx);
12130 }
12131
12132 cx.notify();
12133
12134 if let Some(active_diagnostics) = self.active_diagnostics.take() {
12135 // Clear diagnostics block when folding a range that contains it.
12136 let snapshot = self.snapshot(window, cx);
12137 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12138 drop(snapshot);
12139 self.active_diagnostics = Some(active_diagnostics);
12140 self.dismiss_diagnostics(cx);
12141 } else {
12142 self.active_diagnostics = Some(active_diagnostics);
12143 }
12144 }
12145
12146 self.scrollbar_marker_state.dirty = true;
12147 }
12148
12149 /// Removes any folds whose ranges intersect any of the given ranges.
12150 pub fn unfold_ranges<T: ToOffset + Clone>(
12151 &mut self,
12152 ranges: &[Range<T>],
12153 inclusive: bool,
12154 auto_scroll: bool,
12155 cx: &mut Context<Self>,
12156 ) {
12157 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12158 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12159 });
12160 }
12161
12162 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12163 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12164 return;
12165 }
12166 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12167 self.display_map
12168 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12169 cx.emit(EditorEvent::BufferFoldToggled {
12170 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12171 folded: true,
12172 });
12173 cx.notify();
12174 }
12175
12176 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12177 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12178 return;
12179 }
12180 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12181 self.display_map.update(cx, |display_map, cx| {
12182 display_map.unfold_buffer(buffer_id, cx);
12183 });
12184 cx.emit(EditorEvent::BufferFoldToggled {
12185 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12186 folded: false,
12187 });
12188 cx.notify();
12189 }
12190
12191 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12192 self.display_map.read(cx).is_buffer_folded(buffer)
12193 }
12194
12195 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12196 self.display_map.read(cx).folded_buffers()
12197 }
12198
12199 /// Removes any folds with the given ranges.
12200 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12201 &mut self,
12202 ranges: &[Range<T>],
12203 type_id: TypeId,
12204 auto_scroll: bool,
12205 cx: &mut Context<Self>,
12206 ) {
12207 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12208 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12209 });
12210 }
12211
12212 fn remove_folds_with<T: ToOffset + Clone>(
12213 &mut self,
12214 ranges: &[Range<T>],
12215 auto_scroll: bool,
12216 cx: &mut Context<Self>,
12217 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12218 ) {
12219 if ranges.is_empty() {
12220 return;
12221 }
12222
12223 let mut buffers_affected = HashSet::default();
12224 let multi_buffer = self.buffer().read(cx);
12225 for range in ranges {
12226 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12227 buffers_affected.insert(buffer.read(cx).remote_id());
12228 };
12229 }
12230
12231 self.display_map.update(cx, update);
12232
12233 if auto_scroll {
12234 self.request_autoscroll(Autoscroll::fit(), cx);
12235 }
12236
12237 cx.notify();
12238 self.scrollbar_marker_state.dirty = true;
12239 self.active_indent_guides_state.dirty = true;
12240 }
12241
12242 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12243 self.display_map.read(cx).fold_placeholder.clone()
12244 }
12245
12246 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12247 self.buffer.update(cx, |buffer, cx| {
12248 buffer.set_all_diff_hunks_expanded(cx);
12249 });
12250 }
12251
12252 pub fn expand_all_diff_hunks(
12253 &mut self,
12254 _: &ExpandAllHunkDiffs,
12255 _window: &mut Window,
12256 cx: &mut Context<Self>,
12257 ) {
12258 self.buffer.update(cx, |buffer, cx| {
12259 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12260 });
12261 }
12262
12263 pub fn toggle_selected_diff_hunks(
12264 &mut self,
12265 _: &ToggleSelectedDiffHunks,
12266 _window: &mut Window,
12267 cx: &mut Context<Self>,
12268 ) {
12269 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12270 self.toggle_diff_hunks_in_ranges(ranges, cx);
12271 }
12272
12273 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12274 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12275 self.buffer
12276 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12277 }
12278
12279 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12280 self.buffer.update(cx, |buffer, cx| {
12281 let ranges = vec![Anchor::min()..Anchor::max()];
12282 if !buffer.all_diff_hunks_expanded()
12283 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12284 {
12285 buffer.collapse_diff_hunks(ranges, cx);
12286 true
12287 } else {
12288 false
12289 }
12290 })
12291 }
12292
12293 fn toggle_diff_hunks_in_ranges(
12294 &mut self,
12295 ranges: Vec<Range<Anchor>>,
12296 cx: &mut Context<'_, Editor>,
12297 ) {
12298 self.buffer.update(cx, |buffer, cx| {
12299 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12300 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12301 })
12302 }
12303
12304 fn toggle_diff_hunks_in_ranges_narrow(
12305 &mut self,
12306 ranges: Vec<Range<Anchor>>,
12307 cx: &mut Context<'_, Editor>,
12308 ) {
12309 self.buffer.update(cx, |buffer, cx| {
12310 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12311 buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12312 })
12313 }
12314
12315 pub(crate) fn apply_all_diff_hunks(
12316 &mut self,
12317 _: &ApplyAllDiffHunks,
12318 window: &mut Window,
12319 cx: &mut Context<Self>,
12320 ) {
12321 let buffers = self.buffer.read(cx).all_buffers();
12322 for branch_buffer in buffers {
12323 branch_buffer.update(cx, |branch_buffer, cx| {
12324 branch_buffer.merge_into_base(Vec::new(), cx);
12325 });
12326 }
12327
12328 if let Some(project) = self.project.clone() {
12329 self.save(true, project, window, cx).detach_and_log_err(cx);
12330 }
12331 }
12332
12333 pub(crate) fn apply_selected_diff_hunks(
12334 &mut self,
12335 _: &ApplyDiffHunk,
12336 window: &mut Window,
12337 cx: &mut Context<Self>,
12338 ) {
12339 let snapshot = self.snapshot(window, cx);
12340 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12341 let mut ranges_by_buffer = HashMap::default();
12342 self.transact(window, cx, |editor, _window, cx| {
12343 for hunk in hunks {
12344 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12345 ranges_by_buffer
12346 .entry(buffer.clone())
12347 .or_insert_with(Vec::new)
12348 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12349 }
12350 }
12351
12352 for (buffer, ranges) in ranges_by_buffer {
12353 buffer.update(cx, |buffer, cx| {
12354 buffer.merge_into_base(ranges, cx);
12355 });
12356 }
12357 });
12358
12359 if let Some(project) = self.project.clone() {
12360 self.save(true, project, window, cx).detach_and_log_err(cx);
12361 }
12362 }
12363
12364 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12365 if hovered != self.gutter_hovered {
12366 self.gutter_hovered = hovered;
12367 cx.notify();
12368 }
12369 }
12370
12371 pub fn insert_blocks(
12372 &mut self,
12373 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12374 autoscroll: Option<Autoscroll>,
12375 cx: &mut Context<Self>,
12376 ) -> Vec<CustomBlockId> {
12377 let blocks = self
12378 .display_map
12379 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12380 if let Some(autoscroll) = autoscroll {
12381 self.request_autoscroll(autoscroll, cx);
12382 }
12383 cx.notify();
12384 blocks
12385 }
12386
12387 pub fn resize_blocks(
12388 &mut self,
12389 heights: HashMap<CustomBlockId, u32>,
12390 autoscroll: Option<Autoscroll>,
12391 cx: &mut Context<Self>,
12392 ) {
12393 self.display_map
12394 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12395 if let Some(autoscroll) = autoscroll {
12396 self.request_autoscroll(autoscroll, cx);
12397 }
12398 cx.notify();
12399 }
12400
12401 pub fn replace_blocks(
12402 &mut self,
12403 renderers: HashMap<CustomBlockId, RenderBlock>,
12404 autoscroll: Option<Autoscroll>,
12405 cx: &mut Context<Self>,
12406 ) {
12407 self.display_map
12408 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12409 if let Some(autoscroll) = autoscroll {
12410 self.request_autoscroll(autoscroll, cx);
12411 }
12412 cx.notify();
12413 }
12414
12415 pub fn remove_blocks(
12416 &mut self,
12417 block_ids: HashSet<CustomBlockId>,
12418 autoscroll: Option<Autoscroll>,
12419 cx: &mut Context<Self>,
12420 ) {
12421 self.display_map.update(cx, |display_map, cx| {
12422 display_map.remove_blocks(block_ids, cx)
12423 });
12424 if let Some(autoscroll) = autoscroll {
12425 self.request_autoscroll(autoscroll, cx);
12426 }
12427 cx.notify();
12428 }
12429
12430 pub fn row_for_block(
12431 &self,
12432 block_id: CustomBlockId,
12433 cx: &mut Context<Self>,
12434 ) -> Option<DisplayRow> {
12435 self.display_map
12436 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12437 }
12438
12439 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12440 self.focused_block = Some(focused_block);
12441 }
12442
12443 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12444 self.focused_block.take()
12445 }
12446
12447 pub fn insert_creases(
12448 &mut self,
12449 creases: impl IntoIterator<Item = Crease<Anchor>>,
12450 cx: &mut Context<Self>,
12451 ) -> Vec<CreaseId> {
12452 self.display_map
12453 .update(cx, |map, cx| map.insert_creases(creases, cx))
12454 }
12455
12456 pub fn remove_creases(
12457 &mut self,
12458 ids: impl IntoIterator<Item = CreaseId>,
12459 cx: &mut Context<Self>,
12460 ) {
12461 self.display_map
12462 .update(cx, |map, cx| map.remove_creases(ids, cx));
12463 }
12464
12465 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12466 self.display_map
12467 .update(cx, |map, cx| map.snapshot(cx))
12468 .longest_row()
12469 }
12470
12471 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12472 self.display_map
12473 .update(cx, |map, cx| map.snapshot(cx))
12474 .max_point()
12475 }
12476
12477 pub fn text(&self, cx: &App) -> String {
12478 self.buffer.read(cx).read(cx).text()
12479 }
12480
12481 pub fn is_empty(&self, cx: &App) -> bool {
12482 self.buffer.read(cx).read(cx).is_empty()
12483 }
12484
12485 pub fn text_option(&self, cx: &App) -> Option<String> {
12486 let text = self.text(cx);
12487 let text = text.trim();
12488
12489 if text.is_empty() {
12490 return None;
12491 }
12492
12493 Some(text.to_string())
12494 }
12495
12496 pub fn set_text(
12497 &mut self,
12498 text: impl Into<Arc<str>>,
12499 window: &mut Window,
12500 cx: &mut Context<Self>,
12501 ) {
12502 self.transact(window, cx, |this, _, cx| {
12503 this.buffer
12504 .read(cx)
12505 .as_singleton()
12506 .expect("you can only call set_text on editors for singleton buffers")
12507 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12508 });
12509 }
12510
12511 pub fn display_text(&self, cx: &mut App) -> String {
12512 self.display_map
12513 .update(cx, |map, cx| map.snapshot(cx))
12514 .text()
12515 }
12516
12517 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12518 let mut wrap_guides = smallvec::smallvec![];
12519
12520 if self.show_wrap_guides == Some(false) {
12521 return wrap_guides;
12522 }
12523
12524 let settings = self.buffer.read(cx).settings_at(0, cx);
12525 if settings.show_wrap_guides {
12526 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12527 wrap_guides.push((soft_wrap as usize, true));
12528 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12529 wrap_guides.push((soft_wrap as usize, true));
12530 }
12531 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12532 }
12533
12534 wrap_guides
12535 }
12536
12537 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12538 let settings = self.buffer.read(cx).settings_at(0, cx);
12539 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12540 match mode {
12541 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12542 SoftWrap::None
12543 }
12544 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12545 language_settings::SoftWrap::PreferredLineLength => {
12546 SoftWrap::Column(settings.preferred_line_length)
12547 }
12548 language_settings::SoftWrap::Bounded => {
12549 SoftWrap::Bounded(settings.preferred_line_length)
12550 }
12551 }
12552 }
12553
12554 pub fn set_soft_wrap_mode(
12555 &mut self,
12556 mode: language_settings::SoftWrap,
12557
12558 cx: &mut Context<Self>,
12559 ) {
12560 self.soft_wrap_mode_override = Some(mode);
12561 cx.notify();
12562 }
12563
12564 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12565 self.text_style_refinement = Some(style);
12566 }
12567
12568 /// called by the Element so we know what style we were most recently rendered with.
12569 pub(crate) fn set_style(
12570 &mut self,
12571 style: EditorStyle,
12572 window: &mut Window,
12573 cx: &mut Context<Self>,
12574 ) {
12575 let rem_size = window.rem_size();
12576 self.display_map.update(cx, |map, cx| {
12577 map.set_font(
12578 style.text.font(),
12579 style.text.font_size.to_pixels(rem_size),
12580 cx,
12581 )
12582 });
12583 self.style = Some(style);
12584 }
12585
12586 pub fn style(&self) -> Option<&EditorStyle> {
12587 self.style.as_ref()
12588 }
12589
12590 // Called by the element. This method is not designed to be called outside of the editor
12591 // element's layout code because it does not notify when rewrapping is computed synchronously.
12592 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12593 self.display_map
12594 .update(cx, |map, cx| map.set_wrap_width(width, cx))
12595 }
12596
12597 pub fn set_soft_wrap(&mut self) {
12598 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12599 }
12600
12601 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12602 if self.soft_wrap_mode_override.is_some() {
12603 self.soft_wrap_mode_override.take();
12604 } else {
12605 let soft_wrap = match self.soft_wrap_mode(cx) {
12606 SoftWrap::GitDiff => return,
12607 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12608 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12609 language_settings::SoftWrap::None
12610 }
12611 };
12612 self.soft_wrap_mode_override = Some(soft_wrap);
12613 }
12614 cx.notify();
12615 }
12616
12617 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12618 let Some(workspace) = self.workspace() else {
12619 return;
12620 };
12621 let fs = workspace.read(cx).app_state().fs.clone();
12622 let current_show = TabBarSettings::get_global(cx).show;
12623 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12624 setting.show = Some(!current_show);
12625 });
12626 }
12627
12628 pub fn toggle_indent_guides(
12629 &mut self,
12630 _: &ToggleIndentGuides,
12631 _: &mut Window,
12632 cx: &mut Context<Self>,
12633 ) {
12634 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12635 self.buffer
12636 .read(cx)
12637 .settings_at(0, cx)
12638 .indent_guides
12639 .enabled
12640 });
12641 self.show_indent_guides = Some(!currently_enabled);
12642 cx.notify();
12643 }
12644
12645 fn should_show_indent_guides(&self) -> Option<bool> {
12646 self.show_indent_guides
12647 }
12648
12649 pub fn toggle_line_numbers(
12650 &mut self,
12651 _: &ToggleLineNumbers,
12652 _: &mut Window,
12653 cx: &mut Context<Self>,
12654 ) {
12655 let mut editor_settings = EditorSettings::get_global(cx).clone();
12656 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12657 EditorSettings::override_global(editor_settings, cx);
12658 }
12659
12660 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12661 self.use_relative_line_numbers
12662 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12663 }
12664
12665 pub fn toggle_relative_line_numbers(
12666 &mut self,
12667 _: &ToggleRelativeLineNumbers,
12668 _: &mut Window,
12669 cx: &mut Context<Self>,
12670 ) {
12671 let is_relative = self.should_use_relative_line_numbers(cx);
12672 self.set_relative_line_number(Some(!is_relative), cx)
12673 }
12674
12675 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12676 self.use_relative_line_numbers = is_relative;
12677 cx.notify();
12678 }
12679
12680 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12681 self.show_gutter = show_gutter;
12682 cx.notify();
12683 }
12684
12685 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12686 self.show_scrollbars = show_scrollbars;
12687 cx.notify();
12688 }
12689
12690 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12691 self.show_line_numbers = Some(show_line_numbers);
12692 cx.notify();
12693 }
12694
12695 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12696 self.show_git_diff_gutter = Some(show_git_diff_gutter);
12697 cx.notify();
12698 }
12699
12700 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12701 self.show_code_actions = Some(show_code_actions);
12702 cx.notify();
12703 }
12704
12705 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12706 self.show_runnables = Some(show_runnables);
12707 cx.notify();
12708 }
12709
12710 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12711 if self.display_map.read(cx).masked != masked {
12712 self.display_map.update(cx, |map, _| map.masked = masked);
12713 }
12714 cx.notify()
12715 }
12716
12717 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12718 self.show_wrap_guides = Some(show_wrap_guides);
12719 cx.notify();
12720 }
12721
12722 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12723 self.show_indent_guides = Some(show_indent_guides);
12724 cx.notify();
12725 }
12726
12727 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12728 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12729 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12730 if let Some(dir) = file.abs_path(cx).parent() {
12731 return Some(dir.to_owned());
12732 }
12733 }
12734
12735 if let Some(project_path) = buffer.read(cx).project_path(cx) {
12736 return Some(project_path.path.to_path_buf());
12737 }
12738 }
12739
12740 None
12741 }
12742
12743 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12744 self.active_excerpt(cx)?
12745 .1
12746 .read(cx)
12747 .file()
12748 .and_then(|f| f.as_local())
12749 }
12750
12751 fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12752 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12753 let project_path = buffer.read(cx).project_path(cx)?;
12754 let project = self.project.as_ref()?.read(cx);
12755 project.absolute_path(&project_path, cx)
12756 })
12757 }
12758
12759 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12760 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12761 let project_path = buffer.read(cx).project_path(cx)?;
12762 let project = self.project.as_ref()?.read(cx);
12763 let entry = project.entry_for_path(&project_path, cx)?;
12764 let path = entry.path.to_path_buf();
12765 Some(path)
12766 })
12767 }
12768
12769 pub fn reveal_in_finder(
12770 &mut self,
12771 _: &RevealInFileManager,
12772 _window: &mut Window,
12773 cx: &mut Context<Self>,
12774 ) {
12775 if let Some(target) = self.target_file(cx) {
12776 cx.reveal_path(&target.abs_path(cx));
12777 }
12778 }
12779
12780 pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12781 if let Some(path) = self.target_file_abs_path(cx) {
12782 if let Some(path) = path.to_str() {
12783 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12784 }
12785 }
12786 }
12787
12788 pub fn copy_relative_path(
12789 &mut self,
12790 _: &CopyRelativePath,
12791 _window: &mut Window,
12792 cx: &mut Context<Self>,
12793 ) {
12794 if let Some(path) = self.target_file_path(cx) {
12795 if let Some(path) = path.to_str() {
12796 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12797 }
12798 }
12799 }
12800
12801 pub fn toggle_git_blame(
12802 &mut self,
12803 _: &ToggleGitBlame,
12804 window: &mut Window,
12805 cx: &mut Context<Self>,
12806 ) {
12807 self.show_git_blame_gutter = !self.show_git_blame_gutter;
12808
12809 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12810 self.start_git_blame(true, window, cx);
12811 }
12812
12813 cx.notify();
12814 }
12815
12816 pub fn toggle_git_blame_inline(
12817 &mut self,
12818 _: &ToggleGitBlameInline,
12819 window: &mut Window,
12820 cx: &mut Context<Self>,
12821 ) {
12822 self.toggle_git_blame_inline_internal(true, window, cx);
12823 cx.notify();
12824 }
12825
12826 pub fn git_blame_inline_enabled(&self) -> bool {
12827 self.git_blame_inline_enabled
12828 }
12829
12830 pub fn toggle_selection_menu(
12831 &mut self,
12832 _: &ToggleSelectionMenu,
12833 _: &mut Window,
12834 cx: &mut Context<Self>,
12835 ) {
12836 self.show_selection_menu = self
12837 .show_selection_menu
12838 .map(|show_selections_menu| !show_selections_menu)
12839 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12840
12841 cx.notify();
12842 }
12843
12844 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12845 self.show_selection_menu
12846 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12847 }
12848
12849 fn start_git_blame(
12850 &mut self,
12851 user_triggered: bool,
12852 window: &mut Window,
12853 cx: &mut Context<Self>,
12854 ) {
12855 if let Some(project) = self.project.as_ref() {
12856 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12857 return;
12858 };
12859
12860 if buffer.read(cx).file().is_none() {
12861 return;
12862 }
12863
12864 let focused = self.focus_handle(cx).contains_focused(window, cx);
12865
12866 let project = project.clone();
12867 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12868 self.blame_subscription =
12869 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12870 self.blame = Some(blame);
12871 }
12872 }
12873
12874 fn toggle_git_blame_inline_internal(
12875 &mut self,
12876 user_triggered: bool,
12877 window: &mut Window,
12878 cx: &mut Context<Self>,
12879 ) {
12880 if self.git_blame_inline_enabled {
12881 self.git_blame_inline_enabled = false;
12882 self.show_git_blame_inline = false;
12883 self.show_git_blame_inline_delay_task.take();
12884 } else {
12885 self.git_blame_inline_enabled = true;
12886 self.start_git_blame_inline(user_triggered, window, cx);
12887 }
12888
12889 cx.notify();
12890 }
12891
12892 fn start_git_blame_inline(
12893 &mut self,
12894 user_triggered: bool,
12895 window: &mut Window,
12896 cx: &mut Context<Self>,
12897 ) {
12898 self.start_git_blame(user_triggered, window, cx);
12899
12900 if ProjectSettings::get_global(cx)
12901 .git
12902 .inline_blame_delay()
12903 .is_some()
12904 {
12905 self.start_inline_blame_timer(window, cx);
12906 } else {
12907 self.show_git_blame_inline = true
12908 }
12909 }
12910
12911 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12912 self.blame.as_ref()
12913 }
12914
12915 pub fn show_git_blame_gutter(&self) -> bool {
12916 self.show_git_blame_gutter
12917 }
12918
12919 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12920 self.show_git_blame_gutter && self.has_blame_entries(cx)
12921 }
12922
12923 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12924 self.show_git_blame_inline
12925 && self.focus_handle.is_focused(window)
12926 && !self.newest_selection_head_on_empty_line(cx)
12927 && self.has_blame_entries(cx)
12928 }
12929
12930 fn has_blame_entries(&self, cx: &App) -> bool {
12931 self.blame()
12932 .map_or(false, |blame| blame.read(cx).has_generated_entries())
12933 }
12934
12935 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12936 let cursor_anchor = self.selections.newest_anchor().head();
12937
12938 let snapshot = self.buffer.read(cx).snapshot(cx);
12939 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12940
12941 snapshot.line_len(buffer_row) == 0
12942 }
12943
12944 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12945 let buffer_and_selection = maybe!({
12946 let selection = self.selections.newest::<Point>(cx);
12947 let selection_range = selection.range();
12948
12949 let multi_buffer = self.buffer().read(cx);
12950 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12951 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12952
12953 let (buffer, range, _) = if selection.reversed {
12954 buffer_ranges.first()
12955 } else {
12956 buffer_ranges.last()
12957 }?;
12958
12959 let selection = text::ToPoint::to_point(&range.start, &buffer).row
12960 ..text::ToPoint::to_point(&range.end, &buffer).row;
12961 Some((
12962 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
12963 selection,
12964 ))
12965 });
12966
12967 let Some((buffer, selection)) = buffer_and_selection else {
12968 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12969 };
12970
12971 let Some(project) = self.project.as_ref() else {
12972 return Task::ready(Err(anyhow!("editor does not have project")));
12973 };
12974
12975 project.update(cx, |project, cx| {
12976 project.get_permalink_to_line(&buffer, selection, cx)
12977 })
12978 }
12979
12980 pub fn copy_permalink_to_line(
12981 &mut self,
12982 _: &CopyPermalinkToLine,
12983 window: &mut Window,
12984 cx: &mut Context<Self>,
12985 ) {
12986 let permalink_task = self.get_permalink_to_line(cx);
12987 let workspace = self.workspace();
12988
12989 cx.spawn_in(window, |_, mut cx| async move {
12990 match permalink_task.await {
12991 Ok(permalink) => {
12992 cx.update(|_, cx| {
12993 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12994 })
12995 .ok();
12996 }
12997 Err(err) => {
12998 let message = format!("Failed to copy permalink: {err}");
12999
13000 Err::<(), anyhow::Error>(err).log_err();
13001
13002 if let Some(workspace) = workspace {
13003 workspace
13004 .update_in(&mut cx, |workspace, _, cx| {
13005 struct CopyPermalinkToLine;
13006
13007 workspace.show_toast(
13008 Toast::new(
13009 NotificationId::unique::<CopyPermalinkToLine>(),
13010 message,
13011 ),
13012 cx,
13013 )
13014 })
13015 .ok();
13016 }
13017 }
13018 }
13019 })
13020 .detach();
13021 }
13022
13023 pub fn copy_file_location(
13024 &mut self,
13025 _: &CopyFileLocation,
13026 _: &mut Window,
13027 cx: &mut Context<Self>,
13028 ) {
13029 let selection = self.selections.newest::<Point>(cx).start.row + 1;
13030 if let Some(file) = self.target_file(cx) {
13031 if let Some(path) = file.path().to_str() {
13032 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13033 }
13034 }
13035 }
13036
13037 pub fn open_permalink_to_line(
13038 &mut self,
13039 _: &OpenPermalinkToLine,
13040 window: &mut Window,
13041 cx: &mut Context<Self>,
13042 ) {
13043 let permalink_task = self.get_permalink_to_line(cx);
13044 let workspace = self.workspace();
13045
13046 cx.spawn_in(window, |_, mut cx| async move {
13047 match permalink_task.await {
13048 Ok(permalink) => {
13049 cx.update(|_, cx| {
13050 cx.open_url(permalink.as_ref());
13051 })
13052 .ok();
13053 }
13054 Err(err) => {
13055 let message = format!("Failed to open permalink: {err}");
13056
13057 Err::<(), anyhow::Error>(err).log_err();
13058
13059 if let Some(workspace) = workspace {
13060 workspace
13061 .update(&mut cx, |workspace, cx| {
13062 struct OpenPermalinkToLine;
13063
13064 workspace.show_toast(
13065 Toast::new(
13066 NotificationId::unique::<OpenPermalinkToLine>(),
13067 message,
13068 ),
13069 cx,
13070 )
13071 })
13072 .ok();
13073 }
13074 }
13075 }
13076 })
13077 .detach();
13078 }
13079
13080 pub fn insert_uuid_v4(
13081 &mut self,
13082 _: &InsertUuidV4,
13083 window: &mut Window,
13084 cx: &mut Context<Self>,
13085 ) {
13086 self.insert_uuid(UuidVersion::V4, window, cx);
13087 }
13088
13089 pub fn insert_uuid_v7(
13090 &mut self,
13091 _: &InsertUuidV7,
13092 window: &mut Window,
13093 cx: &mut Context<Self>,
13094 ) {
13095 self.insert_uuid(UuidVersion::V7, window, cx);
13096 }
13097
13098 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13099 self.transact(window, cx, |this, window, cx| {
13100 let edits = this
13101 .selections
13102 .all::<Point>(cx)
13103 .into_iter()
13104 .map(|selection| {
13105 let uuid = match version {
13106 UuidVersion::V4 => uuid::Uuid::new_v4(),
13107 UuidVersion::V7 => uuid::Uuid::now_v7(),
13108 };
13109
13110 (selection.range(), uuid.to_string())
13111 });
13112 this.edit(edits, cx);
13113 this.refresh_inline_completion(true, false, window, cx);
13114 });
13115 }
13116
13117 pub fn open_selections_in_multibuffer(
13118 &mut self,
13119 _: &OpenSelectionsInMultibuffer,
13120 window: &mut Window,
13121 cx: &mut Context<Self>,
13122 ) {
13123 let multibuffer = self.buffer.read(cx);
13124
13125 let Some(buffer) = multibuffer.as_singleton() else {
13126 return;
13127 };
13128
13129 let Some(workspace) = self.workspace() else {
13130 return;
13131 };
13132
13133 let locations = self
13134 .selections
13135 .disjoint_anchors()
13136 .iter()
13137 .map(|range| Location {
13138 buffer: buffer.clone(),
13139 range: range.start.text_anchor..range.end.text_anchor,
13140 })
13141 .collect::<Vec<_>>();
13142
13143 let title = multibuffer.title(cx).to_string();
13144
13145 cx.spawn_in(window, |_, mut cx| async move {
13146 workspace.update_in(&mut cx, |workspace, window, cx| {
13147 Self::open_locations_in_multibuffer(
13148 workspace,
13149 locations,
13150 format!("Selections for '{title}'"),
13151 false,
13152 MultibufferSelectionMode::All,
13153 window,
13154 cx,
13155 );
13156 })
13157 })
13158 .detach();
13159 }
13160
13161 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13162 /// last highlight added will be used.
13163 ///
13164 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13165 pub fn highlight_rows<T: 'static>(
13166 &mut self,
13167 range: Range<Anchor>,
13168 color: Hsla,
13169 should_autoscroll: bool,
13170 cx: &mut Context<Self>,
13171 ) {
13172 let snapshot = self.buffer().read(cx).snapshot(cx);
13173 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13174 let ix = row_highlights.binary_search_by(|highlight| {
13175 Ordering::Equal
13176 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13177 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13178 });
13179
13180 if let Err(mut ix) = ix {
13181 let index = post_inc(&mut self.highlight_order);
13182
13183 // If this range intersects with the preceding highlight, then merge it with
13184 // the preceding highlight. Otherwise insert a new highlight.
13185 let mut merged = false;
13186 if ix > 0 {
13187 let prev_highlight = &mut row_highlights[ix - 1];
13188 if prev_highlight
13189 .range
13190 .end
13191 .cmp(&range.start, &snapshot)
13192 .is_ge()
13193 {
13194 ix -= 1;
13195 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13196 prev_highlight.range.end = range.end;
13197 }
13198 merged = true;
13199 prev_highlight.index = index;
13200 prev_highlight.color = color;
13201 prev_highlight.should_autoscroll = should_autoscroll;
13202 }
13203 }
13204
13205 if !merged {
13206 row_highlights.insert(
13207 ix,
13208 RowHighlight {
13209 range: range.clone(),
13210 index,
13211 color,
13212 should_autoscroll,
13213 },
13214 );
13215 }
13216
13217 // If any of the following highlights intersect with this one, merge them.
13218 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13219 let highlight = &row_highlights[ix];
13220 if next_highlight
13221 .range
13222 .start
13223 .cmp(&highlight.range.end, &snapshot)
13224 .is_le()
13225 {
13226 if next_highlight
13227 .range
13228 .end
13229 .cmp(&highlight.range.end, &snapshot)
13230 .is_gt()
13231 {
13232 row_highlights[ix].range.end = next_highlight.range.end;
13233 }
13234 row_highlights.remove(ix + 1);
13235 } else {
13236 break;
13237 }
13238 }
13239 }
13240 }
13241
13242 /// Remove any highlighted row ranges of the given type that intersect the
13243 /// given ranges.
13244 pub fn remove_highlighted_rows<T: 'static>(
13245 &mut self,
13246 ranges_to_remove: Vec<Range<Anchor>>,
13247 cx: &mut Context<Self>,
13248 ) {
13249 let snapshot = self.buffer().read(cx).snapshot(cx);
13250 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13251 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13252 row_highlights.retain(|highlight| {
13253 while let Some(range_to_remove) = ranges_to_remove.peek() {
13254 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13255 Ordering::Less | Ordering::Equal => {
13256 ranges_to_remove.next();
13257 }
13258 Ordering::Greater => {
13259 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13260 Ordering::Less | Ordering::Equal => {
13261 return false;
13262 }
13263 Ordering::Greater => break,
13264 }
13265 }
13266 }
13267 }
13268
13269 true
13270 })
13271 }
13272
13273 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13274 pub fn clear_row_highlights<T: 'static>(&mut self) {
13275 self.highlighted_rows.remove(&TypeId::of::<T>());
13276 }
13277
13278 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13279 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13280 self.highlighted_rows
13281 .get(&TypeId::of::<T>())
13282 .map_or(&[] as &[_], |vec| vec.as_slice())
13283 .iter()
13284 .map(|highlight| (highlight.range.clone(), highlight.color))
13285 }
13286
13287 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13288 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13289 /// Allows to ignore certain kinds of highlights.
13290 pub fn highlighted_display_rows(
13291 &self,
13292 window: &mut Window,
13293 cx: &mut App,
13294 ) -> BTreeMap<DisplayRow, Hsla> {
13295 let snapshot = self.snapshot(window, cx);
13296 let mut used_highlight_orders = HashMap::default();
13297 self.highlighted_rows
13298 .iter()
13299 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13300 .fold(
13301 BTreeMap::<DisplayRow, Hsla>::new(),
13302 |mut unique_rows, highlight| {
13303 let start = highlight.range.start.to_display_point(&snapshot);
13304 let end = highlight.range.end.to_display_point(&snapshot);
13305 let start_row = start.row().0;
13306 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13307 && end.column() == 0
13308 {
13309 end.row().0.saturating_sub(1)
13310 } else {
13311 end.row().0
13312 };
13313 for row in start_row..=end_row {
13314 let used_index =
13315 used_highlight_orders.entry(row).or_insert(highlight.index);
13316 if highlight.index >= *used_index {
13317 *used_index = highlight.index;
13318 unique_rows.insert(DisplayRow(row), highlight.color);
13319 }
13320 }
13321 unique_rows
13322 },
13323 )
13324 }
13325
13326 pub fn highlighted_display_row_for_autoscroll(
13327 &self,
13328 snapshot: &DisplaySnapshot,
13329 ) -> Option<DisplayRow> {
13330 self.highlighted_rows
13331 .values()
13332 .flat_map(|highlighted_rows| highlighted_rows.iter())
13333 .filter_map(|highlight| {
13334 if highlight.should_autoscroll {
13335 Some(highlight.range.start.to_display_point(snapshot).row())
13336 } else {
13337 None
13338 }
13339 })
13340 .min()
13341 }
13342
13343 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13344 self.highlight_background::<SearchWithinRange>(
13345 ranges,
13346 |colors| colors.editor_document_highlight_read_background,
13347 cx,
13348 )
13349 }
13350
13351 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13352 self.breadcrumb_header = Some(new_header);
13353 }
13354
13355 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13356 self.clear_background_highlights::<SearchWithinRange>(cx);
13357 }
13358
13359 pub fn highlight_background<T: 'static>(
13360 &mut self,
13361 ranges: &[Range<Anchor>],
13362 color_fetcher: fn(&ThemeColors) -> Hsla,
13363 cx: &mut Context<Self>,
13364 ) {
13365 self.background_highlights
13366 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13367 self.scrollbar_marker_state.dirty = true;
13368 cx.notify();
13369 }
13370
13371 pub fn clear_background_highlights<T: 'static>(
13372 &mut self,
13373 cx: &mut Context<Self>,
13374 ) -> Option<BackgroundHighlight> {
13375 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13376 if !text_highlights.1.is_empty() {
13377 self.scrollbar_marker_state.dirty = true;
13378 cx.notify();
13379 }
13380 Some(text_highlights)
13381 }
13382
13383 pub fn highlight_gutter<T: 'static>(
13384 &mut self,
13385 ranges: &[Range<Anchor>],
13386 color_fetcher: fn(&App) -> Hsla,
13387 cx: &mut Context<Self>,
13388 ) {
13389 self.gutter_highlights
13390 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13391 cx.notify();
13392 }
13393
13394 pub fn clear_gutter_highlights<T: 'static>(
13395 &mut self,
13396 cx: &mut Context<Self>,
13397 ) -> Option<GutterHighlight> {
13398 cx.notify();
13399 self.gutter_highlights.remove(&TypeId::of::<T>())
13400 }
13401
13402 #[cfg(feature = "test-support")]
13403 pub fn all_text_background_highlights(
13404 &self,
13405 window: &mut Window,
13406 cx: &mut Context<Self>,
13407 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13408 let snapshot = self.snapshot(window, cx);
13409 let buffer = &snapshot.buffer_snapshot;
13410 let start = buffer.anchor_before(0);
13411 let end = buffer.anchor_after(buffer.len());
13412 let theme = cx.theme().colors();
13413 self.background_highlights_in_range(start..end, &snapshot, theme)
13414 }
13415
13416 #[cfg(feature = "test-support")]
13417 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13418 let snapshot = self.buffer().read(cx).snapshot(cx);
13419
13420 let highlights = self
13421 .background_highlights
13422 .get(&TypeId::of::<items::BufferSearchHighlights>());
13423
13424 if let Some((_color, ranges)) = highlights {
13425 ranges
13426 .iter()
13427 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13428 .collect_vec()
13429 } else {
13430 vec![]
13431 }
13432 }
13433
13434 fn document_highlights_for_position<'a>(
13435 &'a self,
13436 position: Anchor,
13437 buffer: &'a MultiBufferSnapshot,
13438 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13439 let read_highlights = self
13440 .background_highlights
13441 .get(&TypeId::of::<DocumentHighlightRead>())
13442 .map(|h| &h.1);
13443 let write_highlights = self
13444 .background_highlights
13445 .get(&TypeId::of::<DocumentHighlightWrite>())
13446 .map(|h| &h.1);
13447 let left_position = position.bias_left(buffer);
13448 let right_position = position.bias_right(buffer);
13449 read_highlights
13450 .into_iter()
13451 .chain(write_highlights)
13452 .flat_map(move |ranges| {
13453 let start_ix = match ranges.binary_search_by(|probe| {
13454 let cmp = probe.end.cmp(&left_position, buffer);
13455 if cmp.is_ge() {
13456 Ordering::Greater
13457 } else {
13458 Ordering::Less
13459 }
13460 }) {
13461 Ok(i) | Err(i) => i,
13462 };
13463
13464 ranges[start_ix..]
13465 .iter()
13466 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13467 })
13468 }
13469
13470 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13471 self.background_highlights
13472 .get(&TypeId::of::<T>())
13473 .map_or(false, |(_, highlights)| !highlights.is_empty())
13474 }
13475
13476 pub fn background_highlights_in_range(
13477 &self,
13478 search_range: Range<Anchor>,
13479 display_snapshot: &DisplaySnapshot,
13480 theme: &ThemeColors,
13481 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13482 let mut results = Vec::new();
13483 for (color_fetcher, ranges) in self.background_highlights.values() {
13484 let color = color_fetcher(theme);
13485 let start_ix = match ranges.binary_search_by(|probe| {
13486 let cmp = probe
13487 .end
13488 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13489 if cmp.is_gt() {
13490 Ordering::Greater
13491 } else {
13492 Ordering::Less
13493 }
13494 }) {
13495 Ok(i) | Err(i) => i,
13496 };
13497 for range in &ranges[start_ix..] {
13498 if range
13499 .start
13500 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13501 .is_ge()
13502 {
13503 break;
13504 }
13505
13506 let start = range.start.to_display_point(display_snapshot);
13507 let end = range.end.to_display_point(display_snapshot);
13508 results.push((start..end, color))
13509 }
13510 }
13511 results
13512 }
13513
13514 pub fn background_highlight_row_ranges<T: 'static>(
13515 &self,
13516 search_range: Range<Anchor>,
13517 display_snapshot: &DisplaySnapshot,
13518 count: usize,
13519 ) -> Vec<RangeInclusive<DisplayPoint>> {
13520 let mut results = Vec::new();
13521 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13522 return vec![];
13523 };
13524
13525 let start_ix = match ranges.binary_search_by(|probe| {
13526 let cmp = probe
13527 .end
13528 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13529 if cmp.is_gt() {
13530 Ordering::Greater
13531 } else {
13532 Ordering::Less
13533 }
13534 }) {
13535 Ok(i) | Err(i) => i,
13536 };
13537 let mut push_region = |start: Option<Point>, end: Option<Point>| {
13538 if let (Some(start_display), Some(end_display)) = (start, end) {
13539 results.push(
13540 start_display.to_display_point(display_snapshot)
13541 ..=end_display.to_display_point(display_snapshot),
13542 );
13543 }
13544 };
13545 let mut start_row: Option<Point> = None;
13546 let mut end_row: Option<Point> = None;
13547 if ranges.len() > count {
13548 return Vec::new();
13549 }
13550 for range in &ranges[start_ix..] {
13551 if range
13552 .start
13553 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13554 .is_ge()
13555 {
13556 break;
13557 }
13558 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13559 if let Some(current_row) = &end_row {
13560 if end.row == current_row.row {
13561 continue;
13562 }
13563 }
13564 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13565 if start_row.is_none() {
13566 assert_eq!(end_row, None);
13567 start_row = Some(start);
13568 end_row = Some(end);
13569 continue;
13570 }
13571 if let Some(current_end) = end_row.as_mut() {
13572 if start.row > current_end.row + 1 {
13573 push_region(start_row, end_row);
13574 start_row = Some(start);
13575 end_row = Some(end);
13576 } else {
13577 // Merge two hunks.
13578 *current_end = end;
13579 }
13580 } else {
13581 unreachable!();
13582 }
13583 }
13584 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13585 push_region(start_row, end_row);
13586 results
13587 }
13588
13589 pub fn gutter_highlights_in_range(
13590 &self,
13591 search_range: Range<Anchor>,
13592 display_snapshot: &DisplaySnapshot,
13593 cx: &App,
13594 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13595 let mut results = Vec::new();
13596 for (color_fetcher, ranges) in self.gutter_highlights.values() {
13597 let color = color_fetcher(cx);
13598 let start_ix = match ranges.binary_search_by(|probe| {
13599 let cmp = probe
13600 .end
13601 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13602 if cmp.is_gt() {
13603 Ordering::Greater
13604 } else {
13605 Ordering::Less
13606 }
13607 }) {
13608 Ok(i) | Err(i) => i,
13609 };
13610 for range in &ranges[start_ix..] {
13611 if range
13612 .start
13613 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13614 .is_ge()
13615 {
13616 break;
13617 }
13618
13619 let start = range.start.to_display_point(display_snapshot);
13620 let end = range.end.to_display_point(display_snapshot);
13621 results.push((start..end, color))
13622 }
13623 }
13624 results
13625 }
13626
13627 /// Get the text ranges corresponding to the redaction query
13628 pub fn redacted_ranges(
13629 &self,
13630 search_range: Range<Anchor>,
13631 display_snapshot: &DisplaySnapshot,
13632 cx: &App,
13633 ) -> Vec<Range<DisplayPoint>> {
13634 display_snapshot
13635 .buffer_snapshot
13636 .redacted_ranges(search_range, |file| {
13637 if let Some(file) = file {
13638 file.is_private()
13639 && EditorSettings::get(
13640 Some(SettingsLocation {
13641 worktree_id: file.worktree_id(cx),
13642 path: file.path().as_ref(),
13643 }),
13644 cx,
13645 )
13646 .redact_private_values
13647 } else {
13648 false
13649 }
13650 })
13651 .map(|range| {
13652 range.start.to_display_point(display_snapshot)
13653 ..range.end.to_display_point(display_snapshot)
13654 })
13655 .collect()
13656 }
13657
13658 pub fn highlight_text<T: 'static>(
13659 &mut self,
13660 ranges: Vec<Range<Anchor>>,
13661 style: HighlightStyle,
13662 cx: &mut Context<Self>,
13663 ) {
13664 self.display_map.update(cx, |map, _| {
13665 map.highlight_text(TypeId::of::<T>(), ranges, style)
13666 });
13667 cx.notify();
13668 }
13669
13670 pub(crate) fn highlight_inlays<T: 'static>(
13671 &mut self,
13672 highlights: Vec<InlayHighlight>,
13673 style: HighlightStyle,
13674 cx: &mut Context<Self>,
13675 ) {
13676 self.display_map.update(cx, |map, _| {
13677 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13678 });
13679 cx.notify();
13680 }
13681
13682 pub fn text_highlights<'a, T: 'static>(
13683 &'a self,
13684 cx: &'a App,
13685 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13686 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13687 }
13688
13689 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13690 let cleared = self
13691 .display_map
13692 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13693 if cleared {
13694 cx.notify();
13695 }
13696 }
13697
13698 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13699 (self.read_only(cx) || self.blink_manager.read(cx).visible())
13700 && self.focus_handle.is_focused(window)
13701 }
13702
13703 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13704 self.show_cursor_when_unfocused = is_enabled;
13705 cx.notify();
13706 }
13707
13708 pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13709 self.project
13710 .as_ref()
13711 .map(|project| project.read(cx).lsp_store())
13712 }
13713
13714 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13715 cx.notify();
13716 }
13717
13718 fn on_buffer_event(
13719 &mut self,
13720 multibuffer: &Entity<MultiBuffer>,
13721 event: &multi_buffer::Event,
13722 window: &mut Window,
13723 cx: &mut Context<Self>,
13724 ) {
13725 match event {
13726 multi_buffer::Event::Edited {
13727 singleton_buffer_edited,
13728 edited_buffer: buffer_edited,
13729 } => {
13730 self.scrollbar_marker_state.dirty = true;
13731 self.active_indent_guides_state.dirty = true;
13732 self.refresh_active_diagnostics(cx);
13733 self.refresh_code_actions(window, cx);
13734 if self.has_active_inline_completion() {
13735 self.update_visible_inline_completion(window, cx);
13736 }
13737 if let Some(buffer) = buffer_edited {
13738 let buffer_id = buffer.read(cx).remote_id();
13739 if !self.registered_buffers.contains_key(&buffer_id) {
13740 if let Some(lsp_store) = self.lsp_store(cx) {
13741 lsp_store.update(cx, |lsp_store, cx| {
13742 self.registered_buffers.insert(
13743 buffer_id,
13744 lsp_store.register_buffer_with_language_servers(&buffer, cx),
13745 );
13746 })
13747 }
13748 }
13749 }
13750 cx.emit(EditorEvent::BufferEdited);
13751 cx.emit(SearchEvent::MatchesInvalidated);
13752 if *singleton_buffer_edited {
13753 if let Some(project) = &self.project {
13754 let project = project.read(cx);
13755 #[allow(clippy::mutable_key_type)]
13756 let languages_affected = multibuffer
13757 .read(cx)
13758 .all_buffers()
13759 .into_iter()
13760 .filter_map(|buffer| {
13761 let buffer = buffer.read(cx);
13762 let language = buffer.language()?;
13763 if project.is_local()
13764 && project
13765 .language_servers_for_local_buffer(buffer, cx)
13766 .count()
13767 == 0
13768 {
13769 None
13770 } else {
13771 Some(language)
13772 }
13773 })
13774 .cloned()
13775 .collect::<HashSet<_>>();
13776 if !languages_affected.is_empty() {
13777 self.refresh_inlay_hints(
13778 InlayHintRefreshReason::BufferEdited(languages_affected),
13779 cx,
13780 );
13781 }
13782 }
13783 }
13784
13785 let Some(project) = &self.project else { return };
13786 let (telemetry, is_via_ssh) = {
13787 let project = project.read(cx);
13788 let telemetry = project.client().telemetry().clone();
13789 let is_via_ssh = project.is_via_ssh();
13790 (telemetry, is_via_ssh)
13791 };
13792 refresh_linked_ranges(self, window, cx);
13793 telemetry.log_edit_event("editor", is_via_ssh);
13794 }
13795 multi_buffer::Event::ExcerptsAdded {
13796 buffer,
13797 predecessor,
13798 excerpts,
13799 } => {
13800 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13801 let buffer_id = buffer.read(cx).remote_id();
13802 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
13803 if let Some(project) = &self.project {
13804 get_uncommitted_diff_for_buffer(
13805 project,
13806 [buffer.clone()],
13807 self.buffer.clone(),
13808 cx,
13809 );
13810 }
13811 }
13812 cx.emit(EditorEvent::ExcerptsAdded {
13813 buffer: buffer.clone(),
13814 predecessor: *predecessor,
13815 excerpts: excerpts.clone(),
13816 });
13817 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13818 }
13819 multi_buffer::Event::ExcerptsRemoved { ids } => {
13820 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13821 let buffer = self.buffer.read(cx);
13822 self.registered_buffers
13823 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13824 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13825 }
13826 multi_buffer::Event::ExcerptsEdited { ids } => {
13827 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13828 }
13829 multi_buffer::Event::ExcerptsExpanded { ids } => {
13830 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13831 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13832 }
13833 multi_buffer::Event::Reparsed(buffer_id) => {
13834 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13835
13836 cx.emit(EditorEvent::Reparsed(*buffer_id));
13837 }
13838 multi_buffer::Event::DiffHunksToggled => {
13839 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13840 }
13841 multi_buffer::Event::LanguageChanged(buffer_id) => {
13842 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13843 cx.emit(EditorEvent::Reparsed(*buffer_id));
13844 cx.notify();
13845 }
13846 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13847 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13848 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13849 cx.emit(EditorEvent::TitleChanged)
13850 }
13851 // multi_buffer::Event::DiffBaseChanged => {
13852 // self.scrollbar_marker_state.dirty = true;
13853 // cx.emit(EditorEvent::DiffBaseChanged);
13854 // cx.notify();
13855 // }
13856 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13857 multi_buffer::Event::DiagnosticsUpdated => {
13858 self.refresh_active_diagnostics(cx);
13859 self.scrollbar_marker_state.dirty = true;
13860 cx.notify();
13861 }
13862 _ => {}
13863 };
13864 }
13865
13866 fn on_display_map_changed(
13867 &mut self,
13868 _: Entity<DisplayMap>,
13869 _: &mut Window,
13870 cx: &mut Context<Self>,
13871 ) {
13872 cx.notify();
13873 }
13874
13875 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13876 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13877 self.refresh_inline_completion(true, false, window, cx);
13878 self.refresh_inlay_hints(
13879 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13880 self.selections.newest_anchor().head(),
13881 &self.buffer.read(cx).snapshot(cx),
13882 cx,
13883 )),
13884 cx,
13885 );
13886
13887 let old_cursor_shape = self.cursor_shape;
13888
13889 {
13890 let editor_settings = EditorSettings::get_global(cx);
13891 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13892 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13893 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13894 }
13895
13896 if old_cursor_shape != self.cursor_shape {
13897 cx.emit(EditorEvent::CursorShapeChanged);
13898 }
13899
13900 let project_settings = ProjectSettings::get_global(cx);
13901 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13902
13903 if self.mode == EditorMode::Full {
13904 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13905 if self.git_blame_inline_enabled != inline_blame_enabled {
13906 self.toggle_git_blame_inline_internal(false, window, cx);
13907 }
13908 }
13909
13910 cx.notify();
13911 }
13912
13913 pub fn set_searchable(&mut self, searchable: bool) {
13914 self.searchable = searchable;
13915 }
13916
13917 pub fn searchable(&self) -> bool {
13918 self.searchable
13919 }
13920
13921 fn open_proposed_changes_editor(
13922 &mut self,
13923 _: &OpenProposedChangesEditor,
13924 window: &mut Window,
13925 cx: &mut Context<Self>,
13926 ) {
13927 let Some(workspace) = self.workspace() else {
13928 cx.propagate();
13929 return;
13930 };
13931
13932 let selections = self.selections.all::<usize>(cx);
13933 let multi_buffer = self.buffer.read(cx);
13934 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13935 let mut new_selections_by_buffer = HashMap::default();
13936 for selection in selections {
13937 for (buffer, range, _) in
13938 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13939 {
13940 let mut range = range.to_point(buffer);
13941 range.start.column = 0;
13942 range.end.column = buffer.line_len(range.end.row);
13943 new_selections_by_buffer
13944 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13945 .or_insert(Vec::new())
13946 .push(range)
13947 }
13948 }
13949
13950 let proposed_changes_buffers = new_selections_by_buffer
13951 .into_iter()
13952 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13953 .collect::<Vec<_>>();
13954 let proposed_changes_editor = cx.new(|cx| {
13955 ProposedChangesEditor::new(
13956 "Proposed changes",
13957 proposed_changes_buffers,
13958 self.project.clone(),
13959 window,
13960 cx,
13961 )
13962 });
13963
13964 window.defer(cx, move |window, cx| {
13965 workspace.update(cx, |workspace, cx| {
13966 workspace.active_pane().update(cx, |pane, cx| {
13967 pane.add_item(
13968 Box::new(proposed_changes_editor),
13969 true,
13970 true,
13971 None,
13972 window,
13973 cx,
13974 );
13975 });
13976 });
13977 });
13978 }
13979
13980 pub fn open_excerpts_in_split(
13981 &mut self,
13982 _: &OpenExcerptsSplit,
13983 window: &mut Window,
13984 cx: &mut Context<Self>,
13985 ) {
13986 self.open_excerpts_common(None, true, window, cx)
13987 }
13988
13989 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
13990 self.open_excerpts_common(None, false, window, cx)
13991 }
13992
13993 fn open_excerpts_common(
13994 &mut self,
13995 jump_data: Option<JumpData>,
13996 split: bool,
13997 window: &mut Window,
13998 cx: &mut Context<Self>,
13999 ) {
14000 let Some(workspace) = self.workspace() else {
14001 cx.propagate();
14002 return;
14003 };
14004
14005 if self.buffer.read(cx).is_singleton() {
14006 cx.propagate();
14007 return;
14008 }
14009
14010 let mut new_selections_by_buffer = HashMap::default();
14011 match &jump_data {
14012 Some(JumpData::MultiBufferPoint {
14013 excerpt_id,
14014 position,
14015 anchor,
14016 line_offset_from_top,
14017 }) => {
14018 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14019 if let Some(buffer) = multi_buffer_snapshot
14020 .buffer_id_for_excerpt(*excerpt_id)
14021 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14022 {
14023 let buffer_snapshot = buffer.read(cx).snapshot();
14024 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14025 language::ToPoint::to_point(anchor, &buffer_snapshot)
14026 } else {
14027 buffer_snapshot.clip_point(*position, Bias::Left)
14028 };
14029 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14030 new_selections_by_buffer.insert(
14031 buffer,
14032 (
14033 vec![jump_to_offset..jump_to_offset],
14034 Some(*line_offset_from_top),
14035 ),
14036 );
14037 }
14038 }
14039 Some(JumpData::MultiBufferRow {
14040 row,
14041 line_offset_from_top,
14042 }) => {
14043 let point = MultiBufferPoint::new(row.0, 0);
14044 if let Some((buffer, buffer_point, _)) =
14045 self.buffer.read(cx).point_to_buffer_point(point, cx)
14046 {
14047 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14048 new_selections_by_buffer
14049 .entry(buffer)
14050 .or_insert((Vec::new(), Some(*line_offset_from_top)))
14051 .0
14052 .push(buffer_offset..buffer_offset)
14053 }
14054 }
14055 None => {
14056 let selections = self.selections.all::<usize>(cx);
14057 let multi_buffer = self.buffer.read(cx);
14058 for selection in selections {
14059 for (buffer, mut range, _) in multi_buffer
14060 .snapshot(cx)
14061 .range_to_buffer_ranges(selection.range())
14062 {
14063 // When editing branch buffers, jump to the corresponding location
14064 // in their base buffer.
14065 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14066 let buffer = buffer_handle.read(cx);
14067 if let Some(base_buffer) = buffer.base_buffer() {
14068 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14069 buffer_handle = base_buffer;
14070 }
14071
14072 if selection.reversed {
14073 mem::swap(&mut range.start, &mut range.end);
14074 }
14075 new_selections_by_buffer
14076 .entry(buffer_handle)
14077 .or_insert((Vec::new(), None))
14078 .0
14079 .push(range)
14080 }
14081 }
14082 }
14083 }
14084
14085 if new_selections_by_buffer.is_empty() {
14086 return;
14087 }
14088
14089 // We defer the pane interaction because we ourselves are a workspace item
14090 // and activating a new item causes the pane to call a method on us reentrantly,
14091 // which panics if we're on the stack.
14092 window.defer(cx, move |window, cx| {
14093 workspace.update(cx, |workspace, cx| {
14094 let pane = if split {
14095 workspace.adjacent_pane(window, cx)
14096 } else {
14097 workspace.active_pane().clone()
14098 };
14099
14100 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14101 let editor = buffer
14102 .read(cx)
14103 .file()
14104 .is_none()
14105 .then(|| {
14106 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14107 // so `workspace.open_project_item` will never find them, always opening a new editor.
14108 // Instead, we try to activate the existing editor in the pane first.
14109 let (editor, pane_item_index) =
14110 pane.read(cx).items().enumerate().find_map(|(i, item)| {
14111 let editor = item.downcast::<Editor>()?;
14112 let singleton_buffer =
14113 editor.read(cx).buffer().read(cx).as_singleton()?;
14114 if singleton_buffer == buffer {
14115 Some((editor, i))
14116 } else {
14117 None
14118 }
14119 })?;
14120 pane.update(cx, |pane, cx| {
14121 pane.activate_item(pane_item_index, true, true, window, cx)
14122 });
14123 Some(editor)
14124 })
14125 .flatten()
14126 .unwrap_or_else(|| {
14127 workspace.open_project_item::<Self>(
14128 pane.clone(),
14129 buffer,
14130 true,
14131 true,
14132 window,
14133 cx,
14134 )
14135 });
14136
14137 editor.update(cx, |editor, cx| {
14138 let autoscroll = match scroll_offset {
14139 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14140 None => Autoscroll::newest(),
14141 };
14142 let nav_history = editor.nav_history.take();
14143 editor.change_selections(Some(autoscroll), window, cx, |s| {
14144 s.select_ranges(ranges);
14145 });
14146 editor.nav_history = nav_history;
14147 });
14148 }
14149 })
14150 });
14151 }
14152
14153 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14154 let snapshot = self.buffer.read(cx).read(cx);
14155 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14156 Some(
14157 ranges
14158 .iter()
14159 .map(move |range| {
14160 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14161 })
14162 .collect(),
14163 )
14164 }
14165
14166 fn selection_replacement_ranges(
14167 &self,
14168 range: Range<OffsetUtf16>,
14169 cx: &mut App,
14170 ) -> Vec<Range<OffsetUtf16>> {
14171 let selections = self.selections.all::<OffsetUtf16>(cx);
14172 let newest_selection = selections
14173 .iter()
14174 .max_by_key(|selection| selection.id)
14175 .unwrap();
14176 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14177 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14178 let snapshot = self.buffer.read(cx).read(cx);
14179 selections
14180 .into_iter()
14181 .map(|mut selection| {
14182 selection.start.0 =
14183 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14184 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14185 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14186 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14187 })
14188 .collect()
14189 }
14190
14191 fn report_editor_event(
14192 &self,
14193 event_type: &'static str,
14194 file_extension: Option<String>,
14195 cx: &App,
14196 ) {
14197 if cfg!(any(test, feature = "test-support")) {
14198 return;
14199 }
14200
14201 let Some(project) = &self.project else { return };
14202
14203 // If None, we are in a file without an extension
14204 let file = self
14205 .buffer
14206 .read(cx)
14207 .as_singleton()
14208 .and_then(|b| b.read(cx).file());
14209 let file_extension = file_extension.or(file
14210 .as_ref()
14211 .and_then(|file| Path::new(file.file_name(cx)).extension())
14212 .and_then(|e| e.to_str())
14213 .map(|a| a.to_string()));
14214
14215 let vim_mode = cx
14216 .global::<SettingsStore>()
14217 .raw_user_settings()
14218 .get("vim_mode")
14219 == Some(&serde_json::Value::Bool(true));
14220
14221 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14222 let copilot_enabled = edit_predictions_provider
14223 == language::language_settings::EditPredictionProvider::Copilot;
14224 let copilot_enabled_for_language = self
14225 .buffer
14226 .read(cx)
14227 .settings_at(0, cx)
14228 .show_edit_predictions;
14229
14230 let project = project.read(cx);
14231 telemetry::event!(
14232 event_type,
14233 file_extension,
14234 vim_mode,
14235 copilot_enabled,
14236 copilot_enabled_for_language,
14237 edit_predictions_provider,
14238 is_via_ssh = project.is_via_ssh(),
14239 );
14240 }
14241
14242 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14243 /// with each line being an array of {text, highlight} objects.
14244 fn copy_highlight_json(
14245 &mut self,
14246 _: &CopyHighlightJson,
14247 window: &mut Window,
14248 cx: &mut Context<Self>,
14249 ) {
14250 #[derive(Serialize)]
14251 struct Chunk<'a> {
14252 text: String,
14253 highlight: Option<&'a str>,
14254 }
14255
14256 let snapshot = self.buffer.read(cx).snapshot(cx);
14257 let range = self
14258 .selected_text_range(false, window, cx)
14259 .and_then(|selection| {
14260 if selection.range.is_empty() {
14261 None
14262 } else {
14263 Some(selection.range)
14264 }
14265 })
14266 .unwrap_or_else(|| 0..snapshot.len());
14267
14268 let chunks = snapshot.chunks(range, true);
14269 let mut lines = Vec::new();
14270 let mut line: VecDeque<Chunk> = VecDeque::new();
14271
14272 let Some(style) = self.style.as_ref() else {
14273 return;
14274 };
14275
14276 for chunk in chunks {
14277 let highlight = chunk
14278 .syntax_highlight_id
14279 .and_then(|id| id.name(&style.syntax));
14280 let mut chunk_lines = chunk.text.split('\n').peekable();
14281 while let Some(text) = chunk_lines.next() {
14282 let mut merged_with_last_token = false;
14283 if let Some(last_token) = line.back_mut() {
14284 if last_token.highlight == highlight {
14285 last_token.text.push_str(text);
14286 merged_with_last_token = true;
14287 }
14288 }
14289
14290 if !merged_with_last_token {
14291 line.push_back(Chunk {
14292 text: text.into(),
14293 highlight,
14294 });
14295 }
14296
14297 if chunk_lines.peek().is_some() {
14298 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14299 line.pop_front();
14300 }
14301 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14302 line.pop_back();
14303 }
14304
14305 lines.push(mem::take(&mut line));
14306 }
14307 }
14308 }
14309
14310 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14311 return;
14312 };
14313 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14314 }
14315
14316 pub fn open_context_menu(
14317 &mut self,
14318 _: &OpenContextMenu,
14319 window: &mut Window,
14320 cx: &mut Context<Self>,
14321 ) {
14322 self.request_autoscroll(Autoscroll::newest(), cx);
14323 let position = self.selections.newest_display(cx).start;
14324 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14325 }
14326
14327 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14328 &self.inlay_hint_cache
14329 }
14330
14331 pub fn replay_insert_event(
14332 &mut self,
14333 text: &str,
14334 relative_utf16_range: Option<Range<isize>>,
14335 window: &mut Window,
14336 cx: &mut Context<Self>,
14337 ) {
14338 if !self.input_enabled {
14339 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14340 return;
14341 }
14342 if let Some(relative_utf16_range) = relative_utf16_range {
14343 let selections = self.selections.all::<OffsetUtf16>(cx);
14344 self.change_selections(None, window, cx, |s| {
14345 let new_ranges = selections.into_iter().map(|range| {
14346 let start = OffsetUtf16(
14347 range
14348 .head()
14349 .0
14350 .saturating_add_signed(relative_utf16_range.start),
14351 );
14352 let end = OffsetUtf16(
14353 range
14354 .head()
14355 .0
14356 .saturating_add_signed(relative_utf16_range.end),
14357 );
14358 start..end
14359 });
14360 s.select_ranges(new_ranges);
14361 });
14362 }
14363
14364 self.handle_input(text, window, cx);
14365 }
14366
14367 pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14368 let Some(provider) = self.semantics_provider.as_ref() else {
14369 return false;
14370 };
14371
14372 let mut supports = false;
14373 self.buffer().read(cx).for_each_buffer(|buffer| {
14374 supports |= provider.supports_inlay_hints(buffer, cx);
14375 });
14376 supports
14377 }
14378 pub fn is_focused(&self, window: &mut Window) -> bool {
14379 self.focus_handle.is_focused(window)
14380 }
14381
14382 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14383 cx.emit(EditorEvent::Focused);
14384
14385 if let Some(descendant) = self
14386 .last_focused_descendant
14387 .take()
14388 .and_then(|descendant| descendant.upgrade())
14389 {
14390 window.focus(&descendant);
14391 } else {
14392 if let Some(blame) = self.blame.as_ref() {
14393 blame.update(cx, GitBlame::focus)
14394 }
14395
14396 self.blink_manager.update(cx, BlinkManager::enable);
14397 self.show_cursor_names(window, cx);
14398 self.buffer.update(cx, |buffer, cx| {
14399 buffer.finalize_last_transaction(cx);
14400 if self.leader_peer_id.is_none() {
14401 buffer.set_active_selections(
14402 &self.selections.disjoint_anchors(),
14403 self.selections.line_mode,
14404 self.cursor_shape,
14405 cx,
14406 );
14407 }
14408 });
14409 }
14410 }
14411
14412 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14413 cx.emit(EditorEvent::FocusedIn)
14414 }
14415
14416 fn handle_focus_out(
14417 &mut self,
14418 event: FocusOutEvent,
14419 _window: &mut Window,
14420 _cx: &mut Context<Self>,
14421 ) {
14422 if event.blurred != self.focus_handle {
14423 self.last_focused_descendant = Some(event.blurred);
14424 }
14425 }
14426
14427 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14428 self.blink_manager.update(cx, BlinkManager::disable);
14429 self.buffer
14430 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14431
14432 if let Some(blame) = self.blame.as_ref() {
14433 blame.update(cx, GitBlame::blur)
14434 }
14435 if !self.hover_state.focused(window, cx) {
14436 hide_hover(self, cx);
14437 }
14438
14439 self.hide_context_menu(window, cx);
14440 cx.emit(EditorEvent::Blurred);
14441 cx.notify();
14442 }
14443
14444 pub fn register_action<A: Action>(
14445 &mut self,
14446 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14447 ) -> Subscription {
14448 let id = self.next_editor_action_id.post_inc();
14449 let listener = Arc::new(listener);
14450 self.editor_actions.borrow_mut().insert(
14451 id,
14452 Box::new(move |window, _| {
14453 let listener = listener.clone();
14454 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14455 let action = action.downcast_ref().unwrap();
14456 if phase == DispatchPhase::Bubble {
14457 listener(action, window, cx)
14458 }
14459 })
14460 }),
14461 );
14462
14463 let editor_actions = self.editor_actions.clone();
14464 Subscription::new(move || {
14465 editor_actions.borrow_mut().remove(&id);
14466 })
14467 }
14468
14469 pub fn file_header_size(&self) -> u32 {
14470 FILE_HEADER_HEIGHT
14471 }
14472
14473 pub fn revert(
14474 &mut self,
14475 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14476 window: &mut Window,
14477 cx: &mut Context<Self>,
14478 ) {
14479 self.buffer().update(cx, |multi_buffer, cx| {
14480 for (buffer_id, changes) in revert_changes {
14481 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14482 buffer.update(cx, |buffer, cx| {
14483 buffer.edit(
14484 changes.into_iter().map(|(range, text)| {
14485 (range, text.to_string().map(Arc::<str>::from))
14486 }),
14487 None,
14488 cx,
14489 );
14490 });
14491 }
14492 }
14493 });
14494 self.change_selections(None, window, cx, |selections| selections.refresh());
14495 }
14496
14497 pub fn to_pixel_point(
14498 &self,
14499 source: multi_buffer::Anchor,
14500 editor_snapshot: &EditorSnapshot,
14501 window: &mut Window,
14502 ) -> Option<gpui::Point<Pixels>> {
14503 let source_point = source.to_display_point(editor_snapshot);
14504 self.display_to_pixel_point(source_point, editor_snapshot, window)
14505 }
14506
14507 pub fn display_to_pixel_point(
14508 &self,
14509 source: DisplayPoint,
14510 editor_snapshot: &EditorSnapshot,
14511 window: &mut Window,
14512 ) -> Option<gpui::Point<Pixels>> {
14513 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14514 let text_layout_details = self.text_layout_details(window);
14515 let scroll_top = text_layout_details
14516 .scroll_anchor
14517 .scroll_position(editor_snapshot)
14518 .y;
14519
14520 if source.row().as_f32() < scroll_top.floor() {
14521 return None;
14522 }
14523 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14524 let source_y = line_height * (source.row().as_f32() - scroll_top);
14525 Some(gpui::Point::new(source_x, source_y))
14526 }
14527
14528 pub fn has_visible_completions_menu(&self) -> bool {
14529 !self.previewing_inline_completion
14530 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14531 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14532 })
14533 }
14534
14535 pub fn register_addon<T: Addon>(&mut self, instance: T) {
14536 self.addons
14537 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14538 }
14539
14540 pub fn unregister_addon<T: Addon>(&mut self) {
14541 self.addons.remove(&std::any::TypeId::of::<T>());
14542 }
14543
14544 pub fn addon<T: Addon>(&self) -> Option<&T> {
14545 let type_id = std::any::TypeId::of::<T>();
14546 self.addons
14547 .get(&type_id)
14548 .and_then(|item| item.to_any().downcast_ref::<T>())
14549 }
14550
14551 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14552 let text_layout_details = self.text_layout_details(window);
14553 let style = &text_layout_details.editor_style;
14554 let font_id = window.text_system().resolve_font(&style.text.font());
14555 let font_size = style.text.font_size.to_pixels(window.rem_size());
14556 let line_height = style.text.line_height_in_pixels(window.rem_size());
14557 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14558
14559 gpui::Size::new(em_width, line_height)
14560 }
14561}
14562
14563fn get_uncommitted_diff_for_buffer(
14564 project: &Entity<Project>,
14565 buffers: impl IntoIterator<Item = Entity<Buffer>>,
14566 buffer: Entity<MultiBuffer>,
14567 cx: &mut App,
14568) {
14569 let mut tasks = Vec::new();
14570 project.update(cx, |project, cx| {
14571 for buffer in buffers {
14572 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14573 }
14574 });
14575 cx.spawn(|mut cx| async move {
14576 let diffs = futures::future::join_all(tasks).await;
14577 buffer
14578 .update(&mut cx, |buffer, cx| {
14579 for diff in diffs.into_iter().flatten() {
14580 buffer.add_diff(diff, cx);
14581 }
14582 })
14583 .ok();
14584 })
14585 .detach();
14586}
14587
14588fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14589 let tab_size = tab_size.get() as usize;
14590 let mut width = offset;
14591
14592 for ch in text.chars() {
14593 width += if ch == '\t' {
14594 tab_size - (width % tab_size)
14595 } else {
14596 1
14597 };
14598 }
14599
14600 width - offset
14601}
14602
14603#[cfg(test)]
14604mod tests {
14605 use super::*;
14606
14607 #[test]
14608 fn test_string_size_with_expanded_tabs() {
14609 let nz = |val| NonZeroU32::new(val).unwrap();
14610 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14611 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14612 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14613 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14614 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14615 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14616 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14617 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14618 }
14619}
14620
14621/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14622struct WordBreakingTokenizer<'a> {
14623 input: &'a str,
14624}
14625
14626impl<'a> WordBreakingTokenizer<'a> {
14627 fn new(input: &'a str) -> Self {
14628 Self { input }
14629 }
14630}
14631
14632fn is_char_ideographic(ch: char) -> bool {
14633 use unicode_script::Script::*;
14634 use unicode_script::UnicodeScript;
14635 matches!(ch.script(), Han | Tangut | Yi)
14636}
14637
14638fn is_grapheme_ideographic(text: &str) -> bool {
14639 text.chars().any(is_char_ideographic)
14640}
14641
14642fn is_grapheme_whitespace(text: &str) -> bool {
14643 text.chars().any(|x| x.is_whitespace())
14644}
14645
14646fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14647 text.chars().next().map_or(false, |ch| {
14648 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14649 })
14650}
14651
14652#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14653struct WordBreakToken<'a> {
14654 token: &'a str,
14655 grapheme_len: usize,
14656 is_whitespace: bool,
14657}
14658
14659impl<'a> Iterator for WordBreakingTokenizer<'a> {
14660 /// Yields a span, the count of graphemes in the token, and whether it was
14661 /// whitespace. Note that it also breaks at word boundaries.
14662 type Item = WordBreakToken<'a>;
14663
14664 fn next(&mut self) -> Option<Self::Item> {
14665 use unicode_segmentation::UnicodeSegmentation;
14666 if self.input.is_empty() {
14667 return None;
14668 }
14669
14670 let mut iter = self.input.graphemes(true).peekable();
14671 let mut offset = 0;
14672 let mut graphemes = 0;
14673 if let Some(first_grapheme) = iter.next() {
14674 let is_whitespace = is_grapheme_whitespace(first_grapheme);
14675 offset += first_grapheme.len();
14676 graphemes += 1;
14677 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14678 if let Some(grapheme) = iter.peek().copied() {
14679 if should_stay_with_preceding_ideograph(grapheme) {
14680 offset += grapheme.len();
14681 graphemes += 1;
14682 }
14683 }
14684 } else {
14685 let mut words = self.input[offset..].split_word_bound_indices().peekable();
14686 let mut next_word_bound = words.peek().copied();
14687 if next_word_bound.map_or(false, |(i, _)| i == 0) {
14688 next_word_bound = words.next();
14689 }
14690 while let Some(grapheme) = iter.peek().copied() {
14691 if next_word_bound.map_or(false, |(i, _)| i == offset) {
14692 break;
14693 };
14694 if is_grapheme_whitespace(grapheme) != is_whitespace {
14695 break;
14696 };
14697 offset += grapheme.len();
14698 graphemes += 1;
14699 iter.next();
14700 }
14701 }
14702 let token = &self.input[..offset];
14703 self.input = &self.input[offset..];
14704 if is_whitespace {
14705 Some(WordBreakToken {
14706 token: " ",
14707 grapheme_len: 1,
14708 is_whitespace: true,
14709 })
14710 } else {
14711 Some(WordBreakToken {
14712 token,
14713 grapheme_len: graphemes,
14714 is_whitespace: false,
14715 })
14716 }
14717 } else {
14718 None
14719 }
14720 }
14721}
14722
14723#[test]
14724fn test_word_breaking_tokenizer() {
14725 let tests: &[(&str, &[(&str, usize, bool)])] = &[
14726 ("", &[]),
14727 (" ", &[(" ", 1, true)]),
14728 ("Ʒ", &[("Ʒ", 1, false)]),
14729 ("Ǽ", &[("Ǽ", 1, false)]),
14730 ("⋑", &[("⋑", 1, false)]),
14731 ("⋑⋑", &[("⋑⋑", 2, false)]),
14732 (
14733 "原理,进而",
14734 &[
14735 ("原", 1, false),
14736 ("理,", 2, false),
14737 ("进", 1, false),
14738 ("而", 1, false),
14739 ],
14740 ),
14741 (
14742 "hello world",
14743 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14744 ),
14745 (
14746 "hello, world",
14747 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14748 ),
14749 (
14750 " hello world",
14751 &[
14752 (" ", 1, true),
14753 ("hello", 5, false),
14754 (" ", 1, true),
14755 ("world", 5, false),
14756 ],
14757 ),
14758 (
14759 "这是什么 \n 钢笔",
14760 &[
14761 ("这", 1, false),
14762 ("是", 1, false),
14763 ("什", 1, false),
14764 ("么", 1, false),
14765 (" ", 1, true),
14766 ("钢", 1, false),
14767 ("笔", 1, false),
14768 ],
14769 ),
14770 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14771 ];
14772
14773 for (input, result) in tests {
14774 assert_eq!(
14775 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14776 result
14777 .iter()
14778 .copied()
14779 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14780 token,
14781 grapheme_len,
14782 is_whitespace,
14783 })
14784 .collect::<Vec<_>>()
14785 );
14786 }
14787}
14788
14789fn wrap_with_prefix(
14790 line_prefix: String,
14791 unwrapped_text: String,
14792 wrap_column: usize,
14793 tab_size: NonZeroU32,
14794) -> String {
14795 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14796 let mut wrapped_text = String::new();
14797 let mut current_line = line_prefix.clone();
14798
14799 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14800 let mut current_line_len = line_prefix_len;
14801 for WordBreakToken {
14802 token,
14803 grapheme_len,
14804 is_whitespace,
14805 } in tokenizer
14806 {
14807 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14808 wrapped_text.push_str(current_line.trim_end());
14809 wrapped_text.push('\n');
14810 current_line.truncate(line_prefix.len());
14811 current_line_len = line_prefix_len;
14812 if !is_whitespace {
14813 current_line.push_str(token);
14814 current_line_len += grapheme_len;
14815 }
14816 } else if !is_whitespace {
14817 current_line.push_str(token);
14818 current_line_len += grapheme_len;
14819 } else if current_line_len != line_prefix_len {
14820 current_line.push(' ');
14821 current_line_len += 1;
14822 }
14823 }
14824
14825 if !current_line.is_empty() {
14826 wrapped_text.push_str(¤t_line);
14827 }
14828 wrapped_text
14829}
14830
14831#[test]
14832fn test_wrap_with_prefix() {
14833 assert_eq!(
14834 wrap_with_prefix(
14835 "# ".to_string(),
14836 "abcdefg".to_string(),
14837 4,
14838 NonZeroU32::new(4).unwrap()
14839 ),
14840 "# abcdefg"
14841 );
14842 assert_eq!(
14843 wrap_with_prefix(
14844 "".to_string(),
14845 "\thello world".to_string(),
14846 8,
14847 NonZeroU32::new(4).unwrap()
14848 ),
14849 "hello\nworld"
14850 );
14851 assert_eq!(
14852 wrap_with_prefix(
14853 "// ".to_string(),
14854 "xx \nyy zz aa bb cc".to_string(),
14855 12,
14856 NonZeroU32::new(4).unwrap()
14857 ),
14858 "// xx yy zz\n// aa bb cc"
14859 );
14860 assert_eq!(
14861 wrap_with_prefix(
14862 String::new(),
14863 "这是什么 \n 钢笔".to_string(),
14864 3,
14865 NonZeroU32::new(4).unwrap()
14866 ),
14867 "这是什\n么 钢\n笔"
14868 );
14869}
14870
14871pub trait CollaborationHub {
14872 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14873 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14874 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14875}
14876
14877impl CollaborationHub for Entity<Project> {
14878 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14879 self.read(cx).collaborators()
14880 }
14881
14882 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14883 self.read(cx).user_store().read(cx).participant_indices()
14884 }
14885
14886 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14887 let this = self.read(cx);
14888 let user_ids = this.collaborators().values().map(|c| c.user_id);
14889 this.user_store().read_with(cx, |user_store, cx| {
14890 user_store.participant_names(user_ids, cx)
14891 })
14892 }
14893}
14894
14895pub trait SemanticsProvider {
14896 fn hover(
14897 &self,
14898 buffer: &Entity<Buffer>,
14899 position: text::Anchor,
14900 cx: &mut App,
14901 ) -> Option<Task<Vec<project::Hover>>>;
14902
14903 fn inlay_hints(
14904 &self,
14905 buffer_handle: Entity<Buffer>,
14906 range: Range<text::Anchor>,
14907 cx: &mut App,
14908 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14909
14910 fn resolve_inlay_hint(
14911 &self,
14912 hint: InlayHint,
14913 buffer_handle: Entity<Buffer>,
14914 server_id: LanguageServerId,
14915 cx: &mut App,
14916 ) -> Option<Task<anyhow::Result<InlayHint>>>;
14917
14918 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
14919
14920 fn document_highlights(
14921 &self,
14922 buffer: &Entity<Buffer>,
14923 position: text::Anchor,
14924 cx: &mut App,
14925 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14926
14927 fn definitions(
14928 &self,
14929 buffer: &Entity<Buffer>,
14930 position: text::Anchor,
14931 kind: GotoDefinitionKind,
14932 cx: &mut App,
14933 ) -> Option<Task<Result<Vec<LocationLink>>>>;
14934
14935 fn range_for_rename(
14936 &self,
14937 buffer: &Entity<Buffer>,
14938 position: text::Anchor,
14939 cx: &mut App,
14940 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14941
14942 fn perform_rename(
14943 &self,
14944 buffer: &Entity<Buffer>,
14945 position: text::Anchor,
14946 new_name: String,
14947 cx: &mut App,
14948 ) -> Option<Task<Result<ProjectTransaction>>>;
14949}
14950
14951pub trait CompletionProvider {
14952 fn completions(
14953 &self,
14954 buffer: &Entity<Buffer>,
14955 buffer_position: text::Anchor,
14956 trigger: CompletionContext,
14957 window: &mut Window,
14958 cx: &mut Context<Editor>,
14959 ) -> Task<Result<Vec<Completion>>>;
14960
14961 fn resolve_completions(
14962 &self,
14963 buffer: Entity<Buffer>,
14964 completion_indices: Vec<usize>,
14965 completions: Rc<RefCell<Box<[Completion]>>>,
14966 cx: &mut Context<Editor>,
14967 ) -> Task<Result<bool>>;
14968
14969 fn apply_additional_edits_for_completion(
14970 &self,
14971 _buffer: Entity<Buffer>,
14972 _completions: Rc<RefCell<Box<[Completion]>>>,
14973 _completion_index: usize,
14974 _push_to_history: bool,
14975 _cx: &mut Context<Editor>,
14976 ) -> Task<Result<Option<language::Transaction>>> {
14977 Task::ready(Ok(None))
14978 }
14979
14980 fn is_completion_trigger(
14981 &self,
14982 buffer: &Entity<Buffer>,
14983 position: language::Anchor,
14984 text: &str,
14985 trigger_in_words: bool,
14986 cx: &mut Context<Editor>,
14987 ) -> bool;
14988
14989 fn sort_completions(&self) -> bool {
14990 true
14991 }
14992}
14993
14994pub trait CodeActionProvider {
14995 fn id(&self) -> Arc<str>;
14996
14997 fn code_actions(
14998 &self,
14999 buffer: &Entity<Buffer>,
15000 range: Range<text::Anchor>,
15001 window: &mut Window,
15002 cx: &mut App,
15003 ) -> Task<Result<Vec<CodeAction>>>;
15004
15005 fn apply_code_action(
15006 &self,
15007 buffer_handle: Entity<Buffer>,
15008 action: CodeAction,
15009 excerpt_id: ExcerptId,
15010 push_to_history: bool,
15011 window: &mut Window,
15012 cx: &mut App,
15013 ) -> Task<Result<ProjectTransaction>>;
15014}
15015
15016impl CodeActionProvider for Entity<Project> {
15017 fn id(&self) -> Arc<str> {
15018 "project".into()
15019 }
15020
15021 fn code_actions(
15022 &self,
15023 buffer: &Entity<Buffer>,
15024 range: Range<text::Anchor>,
15025 _window: &mut Window,
15026 cx: &mut App,
15027 ) -> Task<Result<Vec<CodeAction>>> {
15028 self.update(cx, |project, cx| {
15029 project.code_actions(buffer, range, None, cx)
15030 })
15031 }
15032
15033 fn apply_code_action(
15034 &self,
15035 buffer_handle: Entity<Buffer>,
15036 action: CodeAction,
15037 _excerpt_id: ExcerptId,
15038 push_to_history: bool,
15039 _window: &mut Window,
15040 cx: &mut App,
15041 ) -> Task<Result<ProjectTransaction>> {
15042 self.update(cx, |project, cx| {
15043 project.apply_code_action(buffer_handle, action, push_to_history, cx)
15044 })
15045 }
15046}
15047
15048fn snippet_completions(
15049 project: &Project,
15050 buffer: &Entity<Buffer>,
15051 buffer_position: text::Anchor,
15052 cx: &mut App,
15053) -> Task<Result<Vec<Completion>>> {
15054 let language = buffer.read(cx).language_at(buffer_position);
15055 let language_name = language.as_ref().map(|language| language.lsp_id());
15056 let snippet_store = project.snippets().read(cx);
15057 let snippets = snippet_store.snippets_for(language_name, cx);
15058
15059 if snippets.is_empty() {
15060 return Task::ready(Ok(vec![]));
15061 }
15062 let snapshot = buffer.read(cx).text_snapshot();
15063 let chars: String = snapshot
15064 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15065 .collect();
15066
15067 let scope = language.map(|language| language.default_scope());
15068 let executor = cx.background_executor().clone();
15069
15070 cx.background_executor().spawn(async move {
15071 let classifier = CharClassifier::new(scope).for_completion(true);
15072 let mut last_word = chars
15073 .chars()
15074 .take_while(|c| classifier.is_word(*c))
15075 .collect::<String>();
15076 last_word = last_word.chars().rev().collect();
15077
15078 if last_word.is_empty() {
15079 return Ok(vec![]);
15080 }
15081
15082 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15083 let to_lsp = |point: &text::Anchor| {
15084 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15085 point_to_lsp(end)
15086 };
15087 let lsp_end = to_lsp(&buffer_position);
15088
15089 let candidates = snippets
15090 .iter()
15091 .enumerate()
15092 .flat_map(|(ix, snippet)| {
15093 snippet
15094 .prefix
15095 .iter()
15096 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15097 })
15098 .collect::<Vec<StringMatchCandidate>>();
15099
15100 let mut matches = fuzzy::match_strings(
15101 &candidates,
15102 &last_word,
15103 last_word.chars().any(|c| c.is_uppercase()),
15104 100,
15105 &Default::default(),
15106 executor,
15107 )
15108 .await;
15109
15110 // Remove all candidates where the query's start does not match the start of any word in the candidate
15111 if let Some(query_start) = last_word.chars().next() {
15112 matches.retain(|string_match| {
15113 split_words(&string_match.string).any(|word| {
15114 // Check that the first codepoint of the word as lowercase matches the first
15115 // codepoint of the query as lowercase
15116 word.chars()
15117 .flat_map(|codepoint| codepoint.to_lowercase())
15118 .zip(query_start.to_lowercase())
15119 .all(|(word_cp, query_cp)| word_cp == query_cp)
15120 })
15121 });
15122 }
15123
15124 let matched_strings = matches
15125 .into_iter()
15126 .map(|m| m.string)
15127 .collect::<HashSet<_>>();
15128
15129 let result: Vec<Completion> = snippets
15130 .into_iter()
15131 .filter_map(|snippet| {
15132 let matching_prefix = snippet
15133 .prefix
15134 .iter()
15135 .find(|prefix| matched_strings.contains(*prefix))?;
15136 let start = as_offset - last_word.len();
15137 let start = snapshot.anchor_before(start);
15138 let range = start..buffer_position;
15139 let lsp_start = to_lsp(&start);
15140 let lsp_range = lsp::Range {
15141 start: lsp_start,
15142 end: lsp_end,
15143 };
15144 Some(Completion {
15145 old_range: range,
15146 new_text: snippet.body.clone(),
15147 resolved: false,
15148 label: CodeLabel {
15149 text: matching_prefix.clone(),
15150 runs: vec![],
15151 filter_range: 0..matching_prefix.len(),
15152 },
15153 server_id: LanguageServerId(usize::MAX),
15154 documentation: snippet
15155 .description
15156 .clone()
15157 .map(CompletionDocumentation::SingleLine),
15158 lsp_completion: lsp::CompletionItem {
15159 label: snippet.prefix.first().unwrap().clone(),
15160 kind: Some(CompletionItemKind::SNIPPET),
15161 label_details: snippet.description.as_ref().map(|description| {
15162 lsp::CompletionItemLabelDetails {
15163 detail: Some(description.clone()),
15164 description: None,
15165 }
15166 }),
15167 insert_text_format: Some(InsertTextFormat::SNIPPET),
15168 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15169 lsp::InsertReplaceEdit {
15170 new_text: snippet.body.clone(),
15171 insert: lsp_range,
15172 replace: lsp_range,
15173 },
15174 )),
15175 filter_text: Some(snippet.body.clone()),
15176 sort_text: Some(char::MAX.to_string()),
15177 ..Default::default()
15178 },
15179 confirm: None,
15180 })
15181 })
15182 .collect();
15183
15184 Ok(result)
15185 })
15186}
15187
15188impl CompletionProvider for Entity<Project> {
15189 fn completions(
15190 &self,
15191 buffer: &Entity<Buffer>,
15192 buffer_position: text::Anchor,
15193 options: CompletionContext,
15194 _window: &mut Window,
15195 cx: &mut Context<Editor>,
15196 ) -> Task<Result<Vec<Completion>>> {
15197 self.update(cx, |project, cx| {
15198 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15199 let project_completions = project.completions(buffer, buffer_position, options, cx);
15200 cx.background_executor().spawn(async move {
15201 let mut completions = project_completions.await?;
15202 let snippets_completions = snippets.await?;
15203 completions.extend(snippets_completions);
15204 Ok(completions)
15205 })
15206 })
15207 }
15208
15209 fn resolve_completions(
15210 &self,
15211 buffer: Entity<Buffer>,
15212 completion_indices: Vec<usize>,
15213 completions: Rc<RefCell<Box<[Completion]>>>,
15214 cx: &mut Context<Editor>,
15215 ) -> Task<Result<bool>> {
15216 self.update(cx, |project, cx| {
15217 project.lsp_store().update(cx, |lsp_store, cx| {
15218 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15219 })
15220 })
15221 }
15222
15223 fn apply_additional_edits_for_completion(
15224 &self,
15225 buffer: Entity<Buffer>,
15226 completions: Rc<RefCell<Box<[Completion]>>>,
15227 completion_index: usize,
15228 push_to_history: bool,
15229 cx: &mut Context<Editor>,
15230 ) -> Task<Result<Option<language::Transaction>>> {
15231 self.update(cx, |project, cx| {
15232 project.lsp_store().update(cx, |lsp_store, cx| {
15233 lsp_store.apply_additional_edits_for_completion(
15234 buffer,
15235 completions,
15236 completion_index,
15237 push_to_history,
15238 cx,
15239 )
15240 })
15241 })
15242 }
15243
15244 fn is_completion_trigger(
15245 &self,
15246 buffer: &Entity<Buffer>,
15247 position: language::Anchor,
15248 text: &str,
15249 trigger_in_words: bool,
15250 cx: &mut Context<Editor>,
15251 ) -> bool {
15252 let mut chars = text.chars();
15253 let char = if let Some(char) = chars.next() {
15254 char
15255 } else {
15256 return false;
15257 };
15258 if chars.next().is_some() {
15259 return false;
15260 }
15261
15262 let buffer = buffer.read(cx);
15263 let snapshot = buffer.snapshot();
15264 if !snapshot.settings_at(position, cx).show_completions_on_input {
15265 return false;
15266 }
15267 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15268 if trigger_in_words && classifier.is_word(char) {
15269 return true;
15270 }
15271
15272 buffer.completion_triggers().contains(text)
15273 }
15274}
15275
15276impl SemanticsProvider for Entity<Project> {
15277 fn hover(
15278 &self,
15279 buffer: &Entity<Buffer>,
15280 position: text::Anchor,
15281 cx: &mut App,
15282 ) -> Option<Task<Vec<project::Hover>>> {
15283 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15284 }
15285
15286 fn document_highlights(
15287 &self,
15288 buffer: &Entity<Buffer>,
15289 position: text::Anchor,
15290 cx: &mut App,
15291 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15292 Some(self.update(cx, |project, cx| {
15293 project.document_highlights(buffer, position, cx)
15294 }))
15295 }
15296
15297 fn definitions(
15298 &self,
15299 buffer: &Entity<Buffer>,
15300 position: text::Anchor,
15301 kind: GotoDefinitionKind,
15302 cx: &mut App,
15303 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15304 Some(self.update(cx, |project, cx| match kind {
15305 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15306 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15307 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15308 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15309 }))
15310 }
15311
15312 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15313 // TODO: make this work for remote projects
15314 self.read(cx)
15315 .language_servers_for_local_buffer(buffer.read(cx), cx)
15316 .any(
15317 |(_, server)| match server.capabilities().inlay_hint_provider {
15318 Some(lsp::OneOf::Left(enabled)) => enabled,
15319 Some(lsp::OneOf::Right(_)) => true,
15320 None => false,
15321 },
15322 )
15323 }
15324
15325 fn inlay_hints(
15326 &self,
15327 buffer_handle: Entity<Buffer>,
15328 range: Range<text::Anchor>,
15329 cx: &mut App,
15330 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15331 Some(self.update(cx, |project, cx| {
15332 project.inlay_hints(buffer_handle, range, cx)
15333 }))
15334 }
15335
15336 fn resolve_inlay_hint(
15337 &self,
15338 hint: InlayHint,
15339 buffer_handle: Entity<Buffer>,
15340 server_id: LanguageServerId,
15341 cx: &mut App,
15342 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15343 Some(self.update(cx, |project, cx| {
15344 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15345 }))
15346 }
15347
15348 fn range_for_rename(
15349 &self,
15350 buffer: &Entity<Buffer>,
15351 position: text::Anchor,
15352 cx: &mut App,
15353 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15354 Some(self.update(cx, |project, cx| {
15355 let buffer = buffer.clone();
15356 let task = project.prepare_rename(buffer.clone(), position, cx);
15357 cx.spawn(|_, mut cx| async move {
15358 Ok(match task.await? {
15359 PrepareRenameResponse::Success(range) => Some(range),
15360 PrepareRenameResponse::InvalidPosition => None,
15361 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15362 // Fallback on using TreeSitter info to determine identifier range
15363 buffer.update(&mut cx, |buffer, _| {
15364 let snapshot = buffer.snapshot();
15365 let (range, kind) = snapshot.surrounding_word(position);
15366 if kind != Some(CharKind::Word) {
15367 return None;
15368 }
15369 Some(
15370 snapshot.anchor_before(range.start)
15371 ..snapshot.anchor_after(range.end),
15372 )
15373 })?
15374 }
15375 })
15376 })
15377 }))
15378 }
15379
15380 fn perform_rename(
15381 &self,
15382 buffer: &Entity<Buffer>,
15383 position: text::Anchor,
15384 new_name: String,
15385 cx: &mut App,
15386 ) -> Option<Task<Result<ProjectTransaction>>> {
15387 Some(self.update(cx, |project, cx| {
15388 project.perform_rename(buffer.clone(), position, new_name, cx)
15389 }))
15390 }
15391}
15392
15393fn inlay_hint_settings(
15394 location: Anchor,
15395 snapshot: &MultiBufferSnapshot,
15396 cx: &mut Context<Editor>,
15397) -> InlayHintSettings {
15398 let file = snapshot.file_at(location);
15399 let language = snapshot.language_at(location).map(|l| l.name());
15400 language_settings(language, file, cx).inlay_hints
15401}
15402
15403fn consume_contiguous_rows(
15404 contiguous_row_selections: &mut Vec<Selection<Point>>,
15405 selection: &Selection<Point>,
15406 display_map: &DisplaySnapshot,
15407 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15408) -> (MultiBufferRow, MultiBufferRow) {
15409 contiguous_row_selections.push(selection.clone());
15410 let start_row = MultiBufferRow(selection.start.row);
15411 let mut end_row = ending_row(selection, display_map);
15412
15413 while let Some(next_selection) = selections.peek() {
15414 if next_selection.start.row <= end_row.0 {
15415 end_row = ending_row(next_selection, display_map);
15416 contiguous_row_selections.push(selections.next().unwrap().clone());
15417 } else {
15418 break;
15419 }
15420 }
15421 (start_row, end_row)
15422}
15423
15424fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15425 if next_selection.end.column > 0 || next_selection.is_empty() {
15426 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15427 } else {
15428 MultiBufferRow(next_selection.end.row)
15429 }
15430}
15431
15432impl EditorSnapshot {
15433 pub fn remote_selections_in_range<'a>(
15434 &'a self,
15435 range: &'a Range<Anchor>,
15436 collaboration_hub: &dyn CollaborationHub,
15437 cx: &'a App,
15438 ) -> impl 'a + Iterator<Item = RemoteSelection> {
15439 let participant_names = collaboration_hub.user_names(cx);
15440 let participant_indices = collaboration_hub.user_participant_indices(cx);
15441 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15442 let collaborators_by_replica_id = collaborators_by_peer_id
15443 .iter()
15444 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15445 .collect::<HashMap<_, _>>();
15446 self.buffer_snapshot
15447 .selections_in_range(range, false)
15448 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15449 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15450 let participant_index = participant_indices.get(&collaborator.user_id).copied();
15451 let user_name = participant_names.get(&collaborator.user_id).cloned();
15452 Some(RemoteSelection {
15453 replica_id,
15454 selection,
15455 cursor_shape,
15456 line_mode,
15457 participant_index,
15458 peer_id: collaborator.peer_id,
15459 user_name,
15460 })
15461 })
15462 }
15463
15464 pub fn hunks_for_ranges(
15465 &self,
15466 ranges: impl Iterator<Item = Range<Point>>,
15467 ) -> Vec<MultiBufferDiffHunk> {
15468 let mut hunks = Vec::new();
15469 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15470 HashMap::default();
15471 for query_range in ranges {
15472 let query_rows =
15473 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15474 for hunk in self.buffer_snapshot.diff_hunks_in_range(
15475 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15476 ) {
15477 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15478 // when the caret is just above or just below the deleted hunk.
15479 let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15480 let related_to_selection = if allow_adjacent {
15481 hunk.row_range.overlaps(&query_rows)
15482 || hunk.row_range.start == query_rows.end
15483 || hunk.row_range.end == query_rows.start
15484 } else {
15485 hunk.row_range.overlaps(&query_rows)
15486 };
15487 if related_to_selection {
15488 if !processed_buffer_rows
15489 .entry(hunk.buffer_id)
15490 .or_default()
15491 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15492 {
15493 continue;
15494 }
15495 hunks.push(hunk);
15496 }
15497 }
15498 }
15499
15500 hunks
15501 }
15502
15503 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15504 self.display_snapshot.buffer_snapshot.language_at(position)
15505 }
15506
15507 pub fn is_focused(&self) -> bool {
15508 self.is_focused
15509 }
15510
15511 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15512 self.placeholder_text.as_ref()
15513 }
15514
15515 pub fn scroll_position(&self) -> gpui::Point<f32> {
15516 self.scroll_anchor.scroll_position(&self.display_snapshot)
15517 }
15518
15519 fn gutter_dimensions(
15520 &self,
15521 font_id: FontId,
15522 font_size: Pixels,
15523 max_line_number_width: Pixels,
15524 cx: &App,
15525 ) -> Option<GutterDimensions> {
15526 if !self.show_gutter {
15527 return None;
15528 }
15529
15530 let descent = cx.text_system().descent(font_id, font_size);
15531 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15532 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15533
15534 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15535 matches!(
15536 ProjectSettings::get_global(cx).git.git_gutter,
15537 Some(GitGutterSetting::TrackedFiles)
15538 )
15539 });
15540 let gutter_settings = EditorSettings::get_global(cx).gutter;
15541 let show_line_numbers = self
15542 .show_line_numbers
15543 .unwrap_or(gutter_settings.line_numbers);
15544 let line_gutter_width = if show_line_numbers {
15545 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15546 let min_width_for_number_on_gutter = em_advance * 4.0;
15547 max_line_number_width.max(min_width_for_number_on_gutter)
15548 } else {
15549 0.0.into()
15550 };
15551
15552 let show_code_actions = self
15553 .show_code_actions
15554 .unwrap_or(gutter_settings.code_actions);
15555
15556 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15557
15558 let git_blame_entries_width =
15559 self.git_blame_gutter_max_author_length
15560 .map(|max_author_length| {
15561 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15562
15563 /// The number of characters to dedicate to gaps and margins.
15564 const SPACING_WIDTH: usize = 4;
15565
15566 let max_char_count = max_author_length
15567 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15568 + ::git::SHORT_SHA_LENGTH
15569 + MAX_RELATIVE_TIMESTAMP.len()
15570 + SPACING_WIDTH;
15571
15572 em_advance * max_char_count
15573 });
15574
15575 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15576 left_padding += if show_code_actions || show_runnables {
15577 em_width * 3.0
15578 } else if show_git_gutter && show_line_numbers {
15579 em_width * 2.0
15580 } else if show_git_gutter || show_line_numbers {
15581 em_width
15582 } else {
15583 px(0.)
15584 };
15585
15586 let right_padding = if gutter_settings.folds && show_line_numbers {
15587 em_width * 4.0
15588 } else if gutter_settings.folds {
15589 em_width * 3.0
15590 } else if show_line_numbers {
15591 em_width
15592 } else {
15593 px(0.)
15594 };
15595
15596 Some(GutterDimensions {
15597 left_padding,
15598 right_padding,
15599 width: line_gutter_width + left_padding + right_padding,
15600 margin: -descent,
15601 git_blame_entries_width,
15602 })
15603 }
15604
15605 pub fn render_crease_toggle(
15606 &self,
15607 buffer_row: MultiBufferRow,
15608 row_contains_cursor: bool,
15609 editor: Entity<Editor>,
15610 window: &mut Window,
15611 cx: &mut App,
15612 ) -> Option<AnyElement> {
15613 let folded = self.is_line_folded(buffer_row);
15614 let mut is_foldable = false;
15615
15616 if let Some(crease) = self
15617 .crease_snapshot
15618 .query_row(buffer_row, &self.buffer_snapshot)
15619 {
15620 is_foldable = true;
15621 match crease {
15622 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15623 if let Some(render_toggle) = render_toggle {
15624 let toggle_callback =
15625 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15626 if folded {
15627 editor.update(cx, |editor, cx| {
15628 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15629 });
15630 } else {
15631 editor.update(cx, |editor, cx| {
15632 editor.unfold_at(
15633 &crate::UnfoldAt { buffer_row },
15634 window,
15635 cx,
15636 )
15637 });
15638 }
15639 });
15640 return Some((render_toggle)(
15641 buffer_row,
15642 folded,
15643 toggle_callback,
15644 window,
15645 cx,
15646 ));
15647 }
15648 }
15649 }
15650 }
15651
15652 is_foldable |= self.starts_indent(buffer_row);
15653
15654 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15655 Some(
15656 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15657 .toggle_state(folded)
15658 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15659 if folded {
15660 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15661 } else {
15662 this.fold_at(&FoldAt { buffer_row }, window, cx);
15663 }
15664 }))
15665 .into_any_element(),
15666 )
15667 } else {
15668 None
15669 }
15670 }
15671
15672 pub fn render_crease_trailer(
15673 &self,
15674 buffer_row: MultiBufferRow,
15675 window: &mut Window,
15676 cx: &mut App,
15677 ) -> Option<AnyElement> {
15678 let folded = self.is_line_folded(buffer_row);
15679 if let Crease::Inline { render_trailer, .. } = self
15680 .crease_snapshot
15681 .query_row(buffer_row, &self.buffer_snapshot)?
15682 {
15683 let render_trailer = render_trailer.as_ref()?;
15684 Some(render_trailer(buffer_row, folded, window, cx))
15685 } else {
15686 None
15687 }
15688 }
15689}
15690
15691impl Deref for EditorSnapshot {
15692 type Target = DisplaySnapshot;
15693
15694 fn deref(&self) -> &Self::Target {
15695 &self.display_snapshot
15696 }
15697}
15698
15699#[derive(Clone, Debug, PartialEq, Eq)]
15700pub enum EditorEvent {
15701 InputIgnored {
15702 text: Arc<str>,
15703 },
15704 InputHandled {
15705 utf16_range_to_replace: Option<Range<isize>>,
15706 text: Arc<str>,
15707 },
15708 ExcerptsAdded {
15709 buffer: Entity<Buffer>,
15710 predecessor: ExcerptId,
15711 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15712 },
15713 ExcerptsRemoved {
15714 ids: Vec<ExcerptId>,
15715 },
15716 BufferFoldToggled {
15717 ids: Vec<ExcerptId>,
15718 folded: bool,
15719 },
15720 ExcerptsEdited {
15721 ids: Vec<ExcerptId>,
15722 },
15723 ExcerptsExpanded {
15724 ids: Vec<ExcerptId>,
15725 },
15726 BufferEdited,
15727 Edited {
15728 transaction_id: clock::Lamport,
15729 },
15730 Reparsed(BufferId),
15731 Focused,
15732 FocusedIn,
15733 Blurred,
15734 DirtyChanged,
15735 Saved,
15736 TitleChanged,
15737 DiffBaseChanged,
15738 SelectionsChanged {
15739 local: bool,
15740 },
15741 ScrollPositionChanged {
15742 local: bool,
15743 autoscroll: bool,
15744 },
15745 Closed,
15746 TransactionUndone {
15747 transaction_id: clock::Lamport,
15748 },
15749 TransactionBegun {
15750 transaction_id: clock::Lamport,
15751 },
15752 Reloaded,
15753 CursorShapeChanged,
15754}
15755
15756impl EventEmitter<EditorEvent> for Editor {}
15757
15758impl Focusable for Editor {
15759 fn focus_handle(&self, _cx: &App) -> FocusHandle {
15760 self.focus_handle.clone()
15761 }
15762}
15763
15764impl Render for Editor {
15765 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15766 let settings = ThemeSettings::get_global(cx);
15767
15768 let mut text_style = match self.mode {
15769 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15770 color: cx.theme().colors().editor_foreground,
15771 font_family: settings.ui_font.family.clone(),
15772 font_features: settings.ui_font.features.clone(),
15773 font_fallbacks: settings.ui_font.fallbacks.clone(),
15774 font_size: rems(0.875).into(),
15775 font_weight: settings.ui_font.weight,
15776 line_height: relative(settings.buffer_line_height.value()),
15777 ..Default::default()
15778 },
15779 EditorMode::Full => TextStyle {
15780 color: cx.theme().colors().editor_foreground,
15781 font_family: settings.buffer_font.family.clone(),
15782 font_features: settings.buffer_font.features.clone(),
15783 font_fallbacks: settings.buffer_font.fallbacks.clone(),
15784 font_size: settings.buffer_font_size().into(),
15785 font_weight: settings.buffer_font.weight,
15786 line_height: relative(settings.buffer_line_height.value()),
15787 ..Default::default()
15788 },
15789 };
15790 if let Some(text_style_refinement) = &self.text_style_refinement {
15791 text_style.refine(text_style_refinement)
15792 }
15793
15794 let background = match self.mode {
15795 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15796 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15797 EditorMode::Full => cx.theme().colors().editor_background,
15798 };
15799
15800 EditorElement::new(
15801 &cx.entity(),
15802 EditorStyle {
15803 background,
15804 local_player: cx.theme().players().local(),
15805 text: text_style,
15806 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15807 syntax: cx.theme().syntax().clone(),
15808 status: cx.theme().status().clone(),
15809 inlay_hints_style: make_inlay_hints_style(cx),
15810 inline_completion_styles: make_suggestion_styles(cx),
15811 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15812 },
15813 )
15814 }
15815}
15816
15817impl EntityInputHandler for Editor {
15818 fn text_for_range(
15819 &mut self,
15820 range_utf16: Range<usize>,
15821 adjusted_range: &mut Option<Range<usize>>,
15822 _: &mut Window,
15823 cx: &mut Context<Self>,
15824 ) -> Option<String> {
15825 let snapshot = self.buffer.read(cx).read(cx);
15826 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15827 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15828 if (start.0..end.0) != range_utf16 {
15829 adjusted_range.replace(start.0..end.0);
15830 }
15831 Some(snapshot.text_for_range(start..end).collect())
15832 }
15833
15834 fn selected_text_range(
15835 &mut self,
15836 ignore_disabled_input: bool,
15837 _: &mut Window,
15838 cx: &mut Context<Self>,
15839 ) -> Option<UTF16Selection> {
15840 // Prevent the IME menu from appearing when holding down an alphabetic key
15841 // while input is disabled.
15842 if !ignore_disabled_input && !self.input_enabled {
15843 return None;
15844 }
15845
15846 let selection = self.selections.newest::<OffsetUtf16>(cx);
15847 let range = selection.range();
15848
15849 Some(UTF16Selection {
15850 range: range.start.0..range.end.0,
15851 reversed: selection.reversed,
15852 })
15853 }
15854
15855 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15856 let snapshot = self.buffer.read(cx).read(cx);
15857 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15858 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15859 }
15860
15861 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15862 self.clear_highlights::<InputComposition>(cx);
15863 self.ime_transaction.take();
15864 }
15865
15866 fn replace_text_in_range(
15867 &mut self,
15868 range_utf16: Option<Range<usize>>,
15869 text: &str,
15870 window: &mut Window,
15871 cx: &mut Context<Self>,
15872 ) {
15873 if !self.input_enabled {
15874 cx.emit(EditorEvent::InputIgnored { text: text.into() });
15875 return;
15876 }
15877
15878 self.transact(window, cx, |this, window, cx| {
15879 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15880 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15881 Some(this.selection_replacement_ranges(range_utf16, cx))
15882 } else {
15883 this.marked_text_ranges(cx)
15884 };
15885
15886 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15887 let newest_selection_id = this.selections.newest_anchor().id;
15888 this.selections
15889 .all::<OffsetUtf16>(cx)
15890 .iter()
15891 .zip(ranges_to_replace.iter())
15892 .find_map(|(selection, range)| {
15893 if selection.id == newest_selection_id {
15894 Some(
15895 (range.start.0 as isize - selection.head().0 as isize)
15896 ..(range.end.0 as isize - selection.head().0 as isize),
15897 )
15898 } else {
15899 None
15900 }
15901 })
15902 });
15903
15904 cx.emit(EditorEvent::InputHandled {
15905 utf16_range_to_replace: range_to_replace,
15906 text: text.into(),
15907 });
15908
15909 if let Some(new_selected_ranges) = new_selected_ranges {
15910 this.change_selections(None, window, cx, |selections| {
15911 selections.select_ranges(new_selected_ranges)
15912 });
15913 this.backspace(&Default::default(), window, cx);
15914 }
15915
15916 this.handle_input(text, window, cx);
15917 });
15918
15919 if let Some(transaction) = self.ime_transaction {
15920 self.buffer.update(cx, |buffer, cx| {
15921 buffer.group_until_transaction(transaction, cx);
15922 });
15923 }
15924
15925 self.unmark_text(window, cx);
15926 }
15927
15928 fn replace_and_mark_text_in_range(
15929 &mut self,
15930 range_utf16: Option<Range<usize>>,
15931 text: &str,
15932 new_selected_range_utf16: Option<Range<usize>>,
15933 window: &mut Window,
15934 cx: &mut Context<Self>,
15935 ) {
15936 if !self.input_enabled {
15937 return;
15938 }
15939
15940 let transaction = self.transact(window, cx, |this, window, cx| {
15941 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15942 let snapshot = this.buffer.read(cx).read(cx);
15943 if let Some(relative_range_utf16) = range_utf16.as_ref() {
15944 for marked_range in &mut marked_ranges {
15945 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15946 marked_range.start.0 += relative_range_utf16.start;
15947 marked_range.start =
15948 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15949 marked_range.end =
15950 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15951 }
15952 }
15953 Some(marked_ranges)
15954 } else if let Some(range_utf16) = range_utf16 {
15955 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15956 Some(this.selection_replacement_ranges(range_utf16, cx))
15957 } else {
15958 None
15959 };
15960
15961 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
15962 let newest_selection_id = this.selections.newest_anchor().id;
15963 this.selections
15964 .all::<OffsetUtf16>(cx)
15965 .iter()
15966 .zip(ranges_to_replace.iter())
15967 .find_map(|(selection, range)| {
15968 if selection.id == newest_selection_id {
15969 Some(
15970 (range.start.0 as isize - selection.head().0 as isize)
15971 ..(range.end.0 as isize - selection.head().0 as isize),
15972 )
15973 } else {
15974 None
15975 }
15976 })
15977 });
15978
15979 cx.emit(EditorEvent::InputHandled {
15980 utf16_range_to_replace: range_to_replace,
15981 text: text.into(),
15982 });
15983
15984 if let Some(ranges) = ranges_to_replace {
15985 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
15986 }
15987
15988 let marked_ranges = {
15989 let snapshot = this.buffer.read(cx).read(cx);
15990 this.selections
15991 .disjoint_anchors()
15992 .iter()
15993 .map(|selection| {
15994 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
15995 })
15996 .collect::<Vec<_>>()
15997 };
15998
15999 if text.is_empty() {
16000 this.unmark_text(window, cx);
16001 } else {
16002 this.highlight_text::<InputComposition>(
16003 marked_ranges.clone(),
16004 HighlightStyle {
16005 underline: Some(UnderlineStyle {
16006 thickness: px(1.),
16007 color: None,
16008 wavy: false,
16009 }),
16010 ..Default::default()
16011 },
16012 cx,
16013 );
16014 }
16015
16016 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16017 let use_autoclose = this.use_autoclose;
16018 let use_auto_surround = this.use_auto_surround;
16019 this.set_use_autoclose(false);
16020 this.set_use_auto_surround(false);
16021 this.handle_input(text, window, cx);
16022 this.set_use_autoclose(use_autoclose);
16023 this.set_use_auto_surround(use_auto_surround);
16024
16025 if let Some(new_selected_range) = new_selected_range_utf16 {
16026 let snapshot = this.buffer.read(cx).read(cx);
16027 let new_selected_ranges = marked_ranges
16028 .into_iter()
16029 .map(|marked_range| {
16030 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16031 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16032 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16033 snapshot.clip_offset_utf16(new_start, Bias::Left)
16034 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16035 })
16036 .collect::<Vec<_>>();
16037
16038 drop(snapshot);
16039 this.change_selections(None, window, cx, |selections| {
16040 selections.select_ranges(new_selected_ranges)
16041 });
16042 }
16043 });
16044
16045 self.ime_transaction = self.ime_transaction.or(transaction);
16046 if let Some(transaction) = self.ime_transaction {
16047 self.buffer.update(cx, |buffer, cx| {
16048 buffer.group_until_transaction(transaction, cx);
16049 });
16050 }
16051
16052 if self.text_highlights::<InputComposition>(cx).is_none() {
16053 self.ime_transaction.take();
16054 }
16055 }
16056
16057 fn bounds_for_range(
16058 &mut self,
16059 range_utf16: Range<usize>,
16060 element_bounds: gpui::Bounds<Pixels>,
16061 window: &mut Window,
16062 cx: &mut Context<Self>,
16063 ) -> Option<gpui::Bounds<Pixels>> {
16064 let text_layout_details = self.text_layout_details(window);
16065 let gpui::Size {
16066 width: em_width,
16067 height: line_height,
16068 } = self.character_size(window);
16069
16070 let snapshot = self.snapshot(window, cx);
16071 let scroll_position = snapshot.scroll_position();
16072 let scroll_left = scroll_position.x * em_width;
16073
16074 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16075 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16076 + self.gutter_dimensions.width
16077 + self.gutter_dimensions.margin;
16078 let y = line_height * (start.row().as_f32() - scroll_position.y);
16079
16080 Some(Bounds {
16081 origin: element_bounds.origin + point(x, y),
16082 size: size(em_width, line_height),
16083 })
16084 }
16085
16086 fn character_index_for_point(
16087 &mut self,
16088 point: gpui::Point<Pixels>,
16089 _window: &mut Window,
16090 _cx: &mut Context<Self>,
16091 ) -> Option<usize> {
16092 let position_map = self.last_position_map.as_ref()?;
16093 if !position_map.text_hitbox.contains(&point) {
16094 return None;
16095 }
16096 let display_point = position_map.point_for_position(point).previous_valid;
16097 let anchor = position_map
16098 .snapshot
16099 .display_point_to_anchor(display_point, Bias::Left);
16100 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16101 Some(utf16_offset.0)
16102 }
16103}
16104
16105trait SelectionExt {
16106 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16107 fn spanned_rows(
16108 &self,
16109 include_end_if_at_line_start: bool,
16110 map: &DisplaySnapshot,
16111 ) -> Range<MultiBufferRow>;
16112}
16113
16114impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16115 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16116 let start = self
16117 .start
16118 .to_point(&map.buffer_snapshot)
16119 .to_display_point(map);
16120 let end = self
16121 .end
16122 .to_point(&map.buffer_snapshot)
16123 .to_display_point(map);
16124 if self.reversed {
16125 end..start
16126 } else {
16127 start..end
16128 }
16129 }
16130
16131 fn spanned_rows(
16132 &self,
16133 include_end_if_at_line_start: bool,
16134 map: &DisplaySnapshot,
16135 ) -> Range<MultiBufferRow> {
16136 let start = self.start.to_point(&map.buffer_snapshot);
16137 let mut end = self.end.to_point(&map.buffer_snapshot);
16138 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16139 end.row -= 1;
16140 }
16141
16142 let buffer_start = map.prev_line_boundary(start).0;
16143 let buffer_end = map.next_line_boundary(end).0;
16144 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16145 }
16146}
16147
16148impl<T: InvalidationRegion> InvalidationStack<T> {
16149 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16150 where
16151 S: Clone + ToOffset,
16152 {
16153 while let Some(region) = self.last() {
16154 let all_selections_inside_invalidation_ranges =
16155 if selections.len() == region.ranges().len() {
16156 selections
16157 .iter()
16158 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16159 .all(|(selection, invalidation_range)| {
16160 let head = selection.head().to_offset(buffer);
16161 invalidation_range.start <= head && invalidation_range.end >= head
16162 })
16163 } else {
16164 false
16165 };
16166
16167 if all_selections_inside_invalidation_ranges {
16168 break;
16169 } else {
16170 self.pop();
16171 }
16172 }
16173 }
16174}
16175
16176impl<T> Default for InvalidationStack<T> {
16177 fn default() -> Self {
16178 Self(Default::default())
16179 }
16180}
16181
16182impl<T> Deref for InvalidationStack<T> {
16183 type Target = Vec<T>;
16184
16185 fn deref(&self) -> &Self::Target {
16186 &self.0
16187 }
16188}
16189
16190impl<T> DerefMut for InvalidationStack<T> {
16191 fn deref_mut(&mut self) -> &mut Self::Target {
16192 &mut self.0
16193 }
16194}
16195
16196impl InvalidationRegion for SnippetState {
16197 fn ranges(&self) -> &[Range<Anchor>] {
16198 &self.ranges[self.active_index]
16199 }
16200}
16201
16202pub fn diagnostic_block_renderer(
16203 diagnostic: Diagnostic,
16204 max_message_rows: Option<u8>,
16205 allow_closing: bool,
16206 _is_valid: bool,
16207) -> RenderBlock {
16208 let (text_without_backticks, code_ranges) =
16209 highlight_diagnostic_message(&diagnostic, max_message_rows);
16210
16211 Arc::new(move |cx: &mut BlockContext| {
16212 let group_id: SharedString = cx.block_id.to_string().into();
16213
16214 let mut text_style = cx.window.text_style().clone();
16215 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16216 let theme_settings = ThemeSettings::get_global(cx);
16217 text_style.font_family = theme_settings.buffer_font.family.clone();
16218 text_style.font_style = theme_settings.buffer_font.style;
16219 text_style.font_features = theme_settings.buffer_font.features.clone();
16220 text_style.font_weight = theme_settings.buffer_font.weight;
16221
16222 let multi_line_diagnostic = diagnostic.message.contains('\n');
16223
16224 let buttons = |diagnostic: &Diagnostic| {
16225 if multi_line_diagnostic {
16226 v_flex()
16227 } else {
16228 h_flex()
16229 }
16230 .when(allow_closing, |div| {
16231 div.children(diagnostic.is_primary.then(|| {
16232 IconButton::new("close-block", IconName::XCircle)
16233 .icon_color(Color::Muted)
16234 .size(ButtonSize::Compact)
16235 .style(ButtonStyle::Transparent)
16236 .visible_on_hover(group_id.clone())
16237 .on_click(move |_click, window, cx| {
16238 window.dispatch_action(Box::new(Cancel), cx)
16239 })
16240 .tooltip(|window, cx| {
16241 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16242 })
16243 }))
16244 })
16245 .child(
16246 IconButton::new("copy-block", IconName::Copy)
16247 .icon_color(Color::Muted)
16248 .size(ButtonSize::Compact)
16249 .style(ButtonStyle::Transparent)
16250 .visible_on_hover(group_id.clone())
16251 .on_click({
16252 let message = diagnostic.message.clone();
16253 move |_click, _, cx| {
16254 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16255 }
16256 })
16257 .tooltip(Tooltip::text("Copy diagnostic message")),
16258 )
16259 };
16260
16261 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16262 AvailableSpace::min_size(),
16263 cx.window,
16264 cx.app,
16265 );
16266
16267 h_flex()
16268 .id(cx.block_id)
16269 .group(group_id.clone())
16270 .relative()
16271 .size_full()
16272 .block_mouse_down()
16273 .pl(cx.gutter_dimensions.width)
16274 .w(cx.max_width - cx.gutter_dimensions.full_width())
16275 .child(
16276 div()
16277 .flex()
16278 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16279 .flex_shrink(),
16280 )
16281 .child(buttons(&diagnostic))
16282 .child(div().flex().flex_shrink_0().child(
16283 StyledText::new(text_without_backticks.clone()).with_highlights(
16284 &text_style,
16285 code_ranges.iter().map(|range| {
16286 (
16287 range.clone(),
16288 HighlightStyle {
16289 font_weight: Some(FontWeight::BOLD),
16290 ..Default::default()
16291 },
16292 )
16293 }),
16294 ),
16295 ))
16296 .into_any_element()
16297 })
16298}
16299
16300fn inline_completion_edit_text(
16301 current_snapshot: &BufferSnapshot,
16302 edits: &[(Range<Anchor>, String)],
16303 edit_preview: &EditPreview,
16304 include_deletions: bool,
16305 cx: &App,
16306) -> HighlightedText {
16307 let edits = edits
16308 .iter()
16309 .map(|(anchor, text)| {
16310 (
16311 anchor.start.text_anchor..anchor.end.text_anchor,
16312 text.clone(),
16313 )
16314 })
16315 .collect::<Vec<_>>();
16316
16317 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16318}
16319
16320pub fn highlight_diagnostic_message(
16321 diagnostic: &Diagnostic,
16322 mut max_message_rows: Option<u8>,
16323) -> (SharedString, Vec<Range<usize>>) {
16324 let mut text_without_backticks = String::new();
16325 let mut code_ranges = Vec::new();
16326
16327 if let Some(source) = &diagnostic.source {
16328 text_without_backticks.push_str(source);
16329 code_ranges.push(0..source.len());
16330 text_without_backticks.push_str(": ");
16331 }
16332
16333 let mut prev_offset = 0;
16334 let mut in_code_block = false;
16335 let has_row_limit = max_message_rows.is_some();
16336 let mut newline_indices = diagnostic
16337 .message
16338 .match_indices('\n')
16339 .filter(|_| has_row_limit)
16340 .map(|(ix, _)| ix)
16341 .fuse()
16342 .peekable();
16343
16344 for (quote_ix, _) in diagnostic
16345 .message
16346 .match_indices('`')
16347 .chain([(diagnostic.message.len(), "")])
16348 {
16349 let mut first_newline_ix = None;
16350 let mut last_newline_ix = None;
16351 while let Some(newline_ix) = newline_indices.peek() {
16352 if *newline_ix < quote_ix {
16353 if first_newline_ix.is_none() {
16354 first_newline_ix = Some(*newline_ix);
16355 }
16356 last_newline_ix = Some(*newline_ix);
16357
16358 if let Some(rows_left) = &mut max_message_rows {
16359 if *rows_left == 0 {
16360 break;
16361 } else {
16362 *rows_left -= 1;
16363 }
16364 }
16365 let _ = newline_indices.next();
16366 } else {
16367 break;
16368 }
16369 }
16370 let prev_len = text_without_backticks.len();
16371 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16372 text_without_backticks.push_str(new_text);
16373 if in_code_block {
16374 code_ranges.push(prev_len..text_without_backticks.len());
16375 }
16376 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16377 in_code_block = !in_code_block;
16378 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16379 text_without_backticks.push_str("...");
16380 break;
16381 }
16382 }
16383
16384 (text_without_backticks.into(), code_ranges)
16385}
16386
16387fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16388 match severity {
16389 DiagnosticSeverity::ERROR => colors.error,
16390 DiagnosticSeverity::WARNING => colors.warning,
16391 DiagnosticSeverity::INFORMATION => colors.info,
16392 DiagnosticSeverity::HINT => colors.info,
16393 _ => colors.ignored,
16394 }
16395}
16396
16397pub fn styled_runs_for_code_label<'a>(
16398 label: &'a CodeLabel,
16399 syntax_theme: &'a theme::SyntaxTheme,
16400) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16401 let fade_out = HighlightStyle {
16402 fade_out: Some(0.35),
16403 ..Default::default()
16404 };
16405
16406 let mut prev_end = label.filter_range.end;
16407 label
16408 .runs
16409 .iter()
16410 .enumerate()
16411 .flat_map(move |(ix, (range, highlight_id))| {
16412 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16413 style
16414 } else {
16415 return Default::default();
16416 };
16417 let mut muted_style = style;
16418 muted_style.highlight(fade_out);
16419
16420 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16421 if range.start >= label.filter_range.end {
16422 if range.start > prev_end {
16423 runs.push((prev_end..range.start, fade_out));
16424 }
16425 runs.push((range.clone(), muted_style));
16426 } else if range.end <= label.filter_range.end {
16427 runs.push((range.clone(), style));
16428 } else {
16429 runs.push((range.start..label.filter_range.end, style));
16430 runs.push((label.filter_range.end..range.end, muted_style));
16431 }
16432 prev_end = cmp::max(prev_end, range.end);
16433
16434 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16435 runs.push((prev_end..label.text.len(), fade_out));
16436 }
16437
16438 runs
16439 })
16440}
16441
16442pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16443 let mut prev_index = 0;
16444 let mut prev_codepoint: Option<char> = None;
16445 text.char_indices()
16446 .chain([(text.len(), '\0')])
16447 .filter_map(move |(index, codepoint)| {
16448 let prev_codepoint = prev_codepoint.replace(codepoint)?;
16449 let is_boundary = index == text.len()
16450 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16451 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16452 if is_boundary {
16453 let chunk = &text[prev_index..index];
16454 prev_index = index;
16455 Some(chunk)
16456 } else {
16457 None
16458 }
16459 })
16460}
16461
16462pub trait RangeToAnchorExt: Sized {
16463 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16464
16465 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16466 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16467 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16468 }
16469}
16470
16471impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16472 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16473 let start_offset = self.start.to_offset(snapshot);
16474 let end_offset = self.end.to_offset(snapshot);
16475 if start_offset == end_offset {
16476 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16477 } else {
16478 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16479 }
16480 }
16481}
16482
16483pub trait RowExt {
16484 fn as_f32(&self) -> f32;
16485
16486 fn next_row(&self) -> Self;
16487
16488 fn previous_row(&self) -> Self;
16489
16490 fn minus(&self, other: Self) -> u32;
16491}
16492
16493impl RowExt for DisplayRow {
16494 fn as_f32(&self) -> f32 {
16495 self.0 as f32
16496 }
16497
16498 fn next_row(&self) -> Self {
16499 Self(self.0 + 1)
16500 }
16501
16502 fn previous_row(&self) -> Self {
16503 Self(self.0.saturating_sub(1))
16504 }
16505
16506 fn minus(&self, other: Self) -> u32 {
16507 self.0 - other.0
16508 }
16509}
16510
16511impl RowExt for MultiBufferRow {
16512 fn as_f32(&self) -> f32 {
16513 self.0 as f32
16514 }
16515
16516 fn next_row(&self) -> Self {
16517 Self(self.0 + 1)
16518 }
16519
16520 fn previous_row(&self) -> Self {
16521 Self(self.0.saturating_sub(1))
16522 }
16523
16524 fn minus(&self, other: Self) -> u32 {
16525 self.0 - other.0
16526 }
16527}
16528
16529trait RowRangeExt {
16530 type Row;
16531
16532 fn len(&self) -> usize;
16533
16534 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16535}
16536
16537impl RowRangeExt for Range<MultiBufferRow> {
16538 type Row = MultiBufferRow;
16539
16540 fn len(&self) -> usize {
16541 (self.end.0 - self.start.0) as usize
16542 }
16543
16544 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16545 (self.start.0..self.end.0).map(MultiBufferRow)
16546 }
16547}
16548
16549impl RowRangeExt for Range<DisplayRow> {
16550 type Row = DisplayRow;
16551
16552 fn len(&self) -> usize {
16553 (self.end.0 - self.start.0) as usize
16554 }
16555
16556 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16557 (self.start.0..self.end.0).map(DisplayRow)
16558 }
16559}
16560
16561/// If select range has more than one line, we
16562/// just point the cursor to range.start.
16563fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16564 if range.start.row == range.end.row {
16565 range
16566 } else {
16567 range.start..range.start
16568 }
16569}
16570pub struct KillRing(ClipboardItem);
16571impl Global for KillRing {}
16572
16573const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16574
16575fn all_edits_insertions_or_deletions(
16576 edits: &Vec<(Range<Anchor>, String)>,
16577 snapshot: &MultiBufferSnapshot,
16578) -> bool {
16579 let mut all_insertions = true;
16580 let mut all_deletions = true;
16581
16582 for (range, new_text) in edits.iter() {
16583 let range_is_empty = range.to_offset(&snapshot).is_empty();
16584 let text_is_empty = new_text.is_empty();
16585
16586 if range_is_empty != text_is_empty {
16587 if range_is_empty {
16588 all_deletions = false;
16589 } else {
16590 all_insertions = false;
16591 }
16592 } else {
16593 return false;
16594 }
16595
16596 if !all_insertions && !all_deletions {
16597 return false;
16598 }
16599 }
16600 all_insertions || all_deletions
16601}