1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod clangd_ext;
19mod code_context_menus;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod indent_guides;
29mod inlay_hint_cache;
30pub mod items;
31mod linked_editing_ranges;
32mod lsp_ext;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod proposed_changes_editor;
37mod rust_analyzer_ext;
38pub mod scroll;
39mod selections_collection;
40pub mod tasks;
41
42#[cfg(test)]
43mod editor_tests;
44#[cfg(test)]
45mod inline_completion_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50use ::git::diff::DiffHunkStatus;
51pub(crate) use actions::*;
52pub use actions::{OpenExcerpts, OpenExcerptsSplit};
53use aho_corasick::AhoCorasick;
54use anyhow::{anyhow, Context as _, Result};
55use blink_manager::BlinkManager;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{
63 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
64};
65pub use editor_settings_controls::*;
66pub use element::{
67 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
68};
69use element::{LineWithInvisibles, PositionMap};
70use futures::{future, FutureExt};
71use fuzzy::StringMatchCandidate;
72
73use code_context_menus::{
74 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
75 CompletionsMenu, ContextMenuOrigin,
76};
77use git::blame::GitBlame;
78use gpui::{
79 div, impl_actions, 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, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
86 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::{InlineCompletionProvider, InlineCompletionProviderHandle};
94pub use items::MAX_TAB_TITLE_LEN;
95use itertools::Itertools;
96use language::{
97 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
98 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
99 CompletionDocumentation, CursorShape, Diagnostic, EditPreview, HighlightedText, IndentKind,
100 IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
101 TransactionId, TreeSitterOptions,
102};
103use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
104use linked_editing_ranges::refresh_linked_ranges;
105use mouse_context_menu::MouseContextMenu;
106pub use proposed_changes_editor::{
107 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
108};
109use similar::{ChangeTag, TextDiff};
110use std::iter::Peekable;
111use task::{ResolvedTask, TaskTemplate, TaskVariables};
112
113use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
114pub use lsp::CompletionContext;
115use lsp::{
116 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
117 LanguageServerId, LanguageServerName,
118};
119
120use language::BufferSnapshot;
121use movement::TextLayoutDetails;
122pub use multi_buffer::{
123 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
124 ToOffset, ToPoint,
125};
126use multi_buffer::{
127 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
128};
129use project::{
130 lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
131 project_settings::{GitGutterSetting, ProjectSettings},
132 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
133 LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
134};
135use rand::prelude::*;
136use rpc::{proto::*, ErrorExt};
137use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
138use selections_collection::{
139 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
140};
141use serde::{Deserialize, Serialize};
142use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
143use smallvec::SmallVec;
144use snippet::Snippet;
145use std::{
146 any::TypeId,
147 borrow::Cow,
148 cell::RefCell,
149 cmp::{self, Ordering, Reverse},
150 mem,
151 num::NonZeroU32,
152 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
153 path::{Path, PathBuf},
154 rc::Rc,
155 sync::Arc,
156 time::{Duration, Instant},
157};
158pub use sum_tree::Bias;
159use sum_tree::TreeMap;
160use text::{BufferId, OffsetUtf16, Rope};
161use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
162use ui::{
163 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
164 Tooltip,
165};
166use util::{defer, maybe, post_inc, RangeExt, ResultExt, TakeUntilExt, TryFutureExt};
167use workspace::item::{ItemHandle, PreviewTabsSettings};
168use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
169use workspace::{
170 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
171};
172use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
173
174use crate::hover_links::{find_url, find_url_from_range};
175use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
176
177pub const FILE_HEADER_HEIGHT: u32 = 2;
178pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
179pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
180pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
181const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
182const MAX_LINE_LEN: usize = 1024;
183const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
184const MAX_SELECTION_HISTORY_LEN: usize = 1024;
185pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
186#[doc(hidden)]
187pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
188
189pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
190pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
191
192pub fn render_parsed_markdown(
193 element_id: impl Into<ElementId>,
194 parsed: &language::ParsedMarkdown,
195 editor_style: &EditorStyle,
196 workspace: Option<WeakEntity<Workspace>>,
197 cx: &mut App,
198) -> InteractiveText {
199 let code_span_background_color = cx
200 .theme()
201 .colors()
202 .editor_document_highlight_read_background;
203
204 let highlights = gpui::combine_highlights(
205 parsed.highlights.iter().filter_map(|(range, highlight)| {
206 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
207 Some((range.clone(), highlight))
208 }),
209 parsed
210 .regions
211 .iter()
212 .zip(&parsed.region_ranges)
213 .filter_map(|(region, range)| {
214 if region.code {
215 Some((
216 range.clone(),
217 HighlightStyle {
218 background_color: Some(code_span_background_color),
219 ..Default::default()
220 },
221 ))
222 } else {
223 None
224 }
225 }),
226 );
227
228 let mut links = Vec::new();
229 let mut link_ranges = Vec::new();
230 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
231 if let Some(link) = region.link.clone() {
232 links.push(link);
233 link_ranges.push(range.clone());
234 }
235 }
236
237 InteractiveText::new(
238 element_id,
239 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
240 )
241 .on_click(
242 link_ranges,
243 move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
244 markdown::Link::Web { url } => cx.open_url(url),
245 markdown::Link::Path { path } => {
246 if let Some(workspace) = &workspace {
247 _ = workspace.update(cx, |workspace, cx| {
248 workspace
249 .open_abs_path(path.clone(), false, window, cx)
250 .detach();
251 });
252 }
253 }
254 },
255 )
256}
257
258#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
259pub enum InlayId {
260 InlineCompletion(usize),
261 Hint(usize),
262}
263
264impl InlayId {
265 fn id(&self) -> usize {
266 match self {
267 Self::InlineCompletion(id) => *id,
268 Self::Hint(id) => *id,
269 }
270 }
271}
272
273enum DocumentHighlightRead {}
274enum DocumentHighlightWrite {}
275enum InputComposition {}
276
277#[derive(Debug, Copy, Clone, PartialEq, Eq)]
278pub enum Navigated {
279 Yes,
280 No,
281}
282
283impl Navigated {
284 pub fn from_bool(yes: bool) -> Navigated {
285 if yes {
286 Navigated::Yes
287 } else {
288 Navigated::No
289 }
290 }
291}
292
293pub fn init_settings(cx: &mut App) {
294 EditorSettings::register(cx);
295}
296
297pub fn init(cx: &mut App) {
298 init_settings(cx);
299
300 workspace::register_project_item::<Editor>(cx);
301 workspace::FollowableViewRegistry::register::<Editor>(cx);
302 workspace::register_serializable_item::<Editor>(cx);
303
304 cx.observe_new(
305 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
306 workspace.register_action(Editor::new_file);
307 workspace.register_action(Editor::new_file_vertical);
308 workspace.register_action(Editor::new_file_horizontal);
309 workspace.register_action(Editor::cancel_language_server_work);
310 },
311 )
312 .detach();
313
314 cx.on_action(move |_: &workspace::NewFile, cx| {
315 let app_state = workspace::AppState::global(cx);
316 if let Some(app_state) = app_state.upgrade() {
317 workspace::open_new(
318 Default::default(),
319 app_state,
320 cx,
321 |workspace, window, cx| {
322 Editor::new_file(workspace, &Default::default(), window, cx)
323 },
324 )
325 .detach();
326 }
327 });
328 cx.on_action(move |_: &workspace::NewWindow, cx| {
329 let app_state = workspace::AppState::global(cx);
330 if let Some(app_state) = app_state.upgrade() {
331 workspace::open_new(
332 Default::default(),
333 app_state,
334 cx,
335 |workspace, window, cx| {
336 cx.activate(true);
337 Editor::new_file(workspace, &Default::default(), window, cx)
338 },
339 )
340 .detach();
341 }
342 });
343}
344
345pub struct SearchWithinRange;
346
347trait InvalidationRegion {
348 fn ranges(&self) -> &[Range<Anchor>];
349}
350
351#[derive(Clone, Debug, PartialEq)]
352pub enum SelectPhase {
353 Begin {
354 position: DisplayPoint,
355 add: bool,
356 click_count: usize,
357 },
358 BeginColumnar {
359 position: DisplayPoint,
360 reset: bool,
361 goal_column: u32,
362 },
363 Extend {
364 position: DisplayPoint,
365 click_count: usize,
366 },
367 Update {
368 position: DisplayPoint,
369 goal_column: u32,
370 scroll_delta: gpui::Point<f32>,
371 },
372 End,
373}
374
375#[derive(Clone, Debug)]
376pub enum SelectMode {
377 Character,
378 Word(Range<Anchor>),
379 Line(Range<Anchor>),
380 All,
381}
382
383#[derive(Copy, Clone, PartialEq, Eq, Debug)]
384pub enum EditorMode {
385 SingleLine { auto_width: bool },
386 AutoHeight { max_lines: usize },
387 Full,
388}
389
390#[derive(Copy, Clone, Debug)]
391pub enum SoftWrap {
392 /// Prefer not to wrap at all.
393 ///
394 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
395 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
396 GitDiff,
397 /// Prefer a single line generally, unless an overly long line is encountered.
398 None,
399 /// Soft wrap lines that exceed the editor width.
400 EditorWidth,
401 /// Soft wrap lines at the preferred line length.
402 Column(u32),
403 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
404 Bounded(u32),
405}
406
407#[derive(Clone)]
408pub struct EditorStyle {
409 pub background: Hsla,
410 pub local_player: PlayerColor,
411 pub text: TextStyle,
412 pub scrollbar_width: Pixels,
413 pub syntax: Arc<SyntaxTheme>,
414 pub status: StatusColors,
415 pub inlay_hints_style: HighlightStyle,
416 pub inline_completion_styles: InlineCompletionStyles,
417 pub unnecessary_code_fade: f32,
418}
419
420impl Default for EditorStyle {
421 fn default() -> Self {
422 Self {
423 background: Hsla::default(),
424 local_player: PlayerColor::default(),
425 text: TextStyle::default(),
426 scrollbar_width: Pixels::default(),
427 syntax: Default::default(),
428 // HACK: Status colors don't have a real default.
429 // We should look into removing the status colors from the editor
430 // style and retrieve them directly from the theme.
431 status: StatusColors::dark(),
432 inlay_hints_style: HighlightStyle::default(),
433 inline_completion_styles: InlineCompletionStyles {
434 insertion: HighlightStyle::default(),
435 whitespace: HighlightStyle::default(),
436 },
437 unnecessary_code_fade: Default::default(),
438 }
439 }
440}
441
442pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
443 let show_background = language_settings::language_settings(None, None, cx)
444 .inlay_hints
445 .show_background;
446
447 HighlightStyle {
448 color: Some(cx.theme().status().hint),
449 background_color: show_background.then(|| cx.theme().status().hint_background),
450 ..HighlightStyle::default()
451 }
452}
453
454pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
455 InlineCompletionStyles {
456 insertion: HighlightStyle {
457 color: Some(cx.theme().status().predictive),
458 ..HighlightStyle::default()
459 },
460 whitespace: HighlightStyle {
461 background_color: Some(cx.theme().status().created_background),
462 ..HighlightStyle::default()
463 },
464 }
465}
466
467type CompletionId = usize;
468
469pub(crate) enum EditDisplayMode {
470 TabAccept(bool),
471 DiffPopover,
472 Inline,
473}
474
475enum InlineCompletion {
476 Edit {
477 edits: Vec<(Range<Anchor>, String)>,
478 edit_preview: Option<EditPreview>,
479 display_mode: EditDisplayMode,
480 snapshot: BufferSnapshot,
481 },
482 Move {
483 target: Anchor,
484 range_around_target: Range<text::Anchor>,
485 snapshot: BufferSnapshot,
486 },
487}
488
489struct InlineCompletionState {
490 inlay_ids: Vec<InlayId>,
491 completion: InlineCompletion,
492 invalidation_range: Range<Anchor>,
493}
494
495impl InlineCompletionState {
496 pub fn is_move(&self) -> bool {
497 match &self.completion {
498 InlineCompletion::Move { .. } => true,
499 _ => false,
500 }
501 }
502}
503
504enum InlineCompletionHighlight {}
505
506pub enum MenuInlineCompletionsPolicy {
507 Never,
508 ByProvider,
509}
510
511#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
512struct EditorActionId(usize);
513
514impl EditorActionId {
515 pub fn post_inc(&mut self) -> Self {
516 let answer = self.0;
517
518 *self = Self(answer + 1);
519
520 Self(answer)
521 }
522}
523
524// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
525// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
526
527type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
528type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
529
530#[derive(Default)]
531struct ScrollbarMarkerState {
532 scrollbar_size: Size<Pixels>,
533 dirty: bool,
534 markers: Arc<[PaintQuad]>,
535 pending_refresh: Option<Task<Result<()>>>,
536}
537
538impl ScrollbarMarkerState {
539 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
540 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
541 }
542}
543
544#[derive(Clone, Debug)]
545struct RunnableTasks {
546 templates: Vec<(TaskSourceKind, TaskTemplate)>,
547 offset: MultiBufferOffset,
548 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
549 column: u32,
550 // Values of all named captures, including those starting with '_'
551 extra_variables: HashMap<String, String>,
552 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
553 context_range: Range<BufferOffset>,
554}
555
556impl RunnableTasks {
557 fn resolve<'a>(
558 &'a self,
559 cx: &'a task::TaskContext,
560 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
561 self.templates.iter().filter_map(|(kind, template)| {
562 template
563 .resolve_task(&kind.to_id_base(), cx)
564 .map(|task| (kind.clone(), task))
565 })
566 }
567}
568
569#[derive(Clone)]
570struct ResolvedTasks {
571 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
572 position: Anchor,
573}
574#[derive(Copy, Clone, Debug)]
575struct MultiBufferOffset(usize);
576#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
577struct BufferOffset(usize);
578
579// Addons allow storing per-editor state in other crates (e.g. Vim)
580pub trait Addon: 'static {
581 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
582
583 fn to_any(&self) -> &dyn std::any::Any;
584}
585
586#[derive(Debug, Copy, Clone, PartialEq, Eq)]
587pub enum IsVimMode {
588 Yes,
589 No,
590}
591
592/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
593///
594/// See the [module level documentation](self) for more information.
595pub struct Editor {
596 focus_handle: FocusHandle,
597 last_focused_descendant: Option<WeakFocusHandle>,
598 /// The text buffer being edited
599 buffer: Entity<MultiBuffer>,
600 /// Map of how text in the buffer should be displayed.
601 /// Handles soft wraps, folds, fake inlay text insertions, etc.
602 pub display_map: Entity<DisplayMap>,
603 pub selections: SelectionsCollection,
604 pub scroll_manager: ScrollManager,
605 /// When inline assist editors are linked, they all render cursors because
606 /// typing enters text into each of them, even the ones that aren't focused.
607 pub(crate) show_cursor_when_unfocused: bool,
608 columnar_selection_tail: Option<Anchor>,
609 add_selections_state: Option<AddSelectionsState>,
610 select_next_state: Option<SelectNextState>,
611 select_prev_state: Option<SelectNextState>,
612 selection_history: SelectionHistory,
613 autoclose_regions: Vec<AutocloseRegion>,
614 snippet_stack: InvalidationStack<SnippetState>,
615 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
616 ime_transaction: Option<TransactionId>,
617 active_diagnostics: Option<ActiveDiagnosticGroup>,
618 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
619
620 // TODO: make this a access method
621 pub project: Option<Entity<Project>>,
622 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
623 completion_provider: Option<Box<dyn CompletionProvider>>,
624 collaboration_hub: Option<Box<dyn CollaborationHub>>,
625 blink_manager: Entity<BlinkManager>,
626 show_cursor_names: bool,
627 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
628 pub show_local_selections: bool,
629 mode: EditorMode,
630 show_breadcrumbs: bool,
631 show_gutter: bool,
632 show_scrollbars: bool,
633 show_line_numbers: Option<bool>,
634 use_relative_line_numbers: Option<bool>,
635 show_git_diff_gutter: Option<bool>,
636 show_code_actions: Option<bool>,
637 show_runnables: Option<bool>,
638 show_wrap_guides: Option<bool>,
639 show_indent_guides: Option<bool>,
640 placeholder_text: Option<Arc<str>>,
641 highlight_order: usize,
642 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
643 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
644 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
645 scrollbar_marker_state: ScrollbarMarkerState,
646 active_indent_guides_state: ActiveIndentGuidesState,
647 nav_history: Option<ItemNavHistory>,
648 context_menu: RefCell<Option<CodeContextMenu>>,
649 mouse_context_menu: Option<MouseContextMenu>,
650 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
651 signature_help_state: SignatureHelpState,
652 auto_signature_help: Option<bool>,
653 find_all_references_task_sources: Vec<Anchor>,
654 next_completion_id: CompletionId,
655 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
656 code_actions_task: Option<Task<Result<()>>>,
657 document_highlights_task: Option<Task<()>>,
658 linked_editing_range_task: Option<Task<Option<()>>>,
659 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
660 pending_rename: Option<RenameState>,
661 searchable: bool,
662 cursor_shape: CursorShape,
663 current_line_highlight: Option<CurrentLineHighlight>,
664 collapse_matches: bool,
665 autoindent_mode: Option<AutoindentMode>,
666 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
667 input_enabled: bool,
668 use_modal_editing: bool,
669 read_only: bool,
670 leader_peer_id: Option<PeerId>,
671 remote_id: Option<ViewId>,
672 hover_state: HoverState,
673 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
674 gutter_hovered: bool,
675 hovered_link_state: Option<HoveredLinkState>,
676 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
677 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
678 active_inline_completion: Option<InlineCompletionState>,
679 /// Used to prevent flickering as the user types while the menu is open
680 stale_inline_completion_in_menu: Option<InlineCompletionState>,
681 // enable_inline_completions is a switch that Vim can use to disable
682 // edit predictions based on its mode.
683 enable_inline_completions: bool,
684 show_inline_completions_override: Option<bool>,
685 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
686 inlay_hint_cache: InlayHintCache,
687 next_inlay_id: usize,
688 _subscriptions: Vec<Subscription>,
689 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
690 gutter_dimensions: GutterDimensions,
691 style: Option<EditorStyle>,
692 text_style_refinement: Option<TextStyleRefinement>,
693 next_editor_action_id: EditorActionId,
694 editor_actions:
695 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
696 use_autoclose: bool,
697 use_auto_surround: bool,
698 auto_replace_emoji_shortcode: bool,
699 show_git_blame_gutter: bool,
700 show_git_blame_inline: bool,
701 show_git_blame_inline_delay_task: Option<Task<()>>,
702 git_blame_inline_enabled: bool,
703 serialize_dirty_buffers: bool,
704 show_selection_menu: Option<bool>,
705 blame: Option<Entity<GitBlame>>,
706 blame_subscription: Option<Subscription>,
707 custom_context_menu: Option<
708 Box<
709 dyn 'static
710 + Fn(
711 &mut Self,
712 DisplayPoint,
713 &mut Window,
714 &mut Context<Self>,
715 ) -> Option<Entity<ui::ContextMenu>>,
716 >,
717 >,
718 last_bounds: Option<Bounds<Pixels>>,
719 last_position_map: Option<Rc<PositionMap>>,
720 expect_bounds_change: Option<Bounds<Pixels>>,
721 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
722 tasks_update_task: Option<Task<()>>,
723 in_project_search: bool,
724 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
725 breadcrumb_header: Option<String>,
726 focused_block: Option<FocusedBlock>,
727 next_scroll_position: NextScrollCursorCenterTopBottom,
728 addons: HashMap<TypeId, Box<dyn Addon>>,
729 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
730 selection_mark_mode: bool,
731 toggle_fold_multiple_buffers: Task<()>,
732 _scroll_cursor_center_top_bottom_task: Task<()>,
733}
734
735#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
736enum NextScrollCursorCenterTopBottom {
737 #[default]
738 Center,
739 Top,
740 Bottom,
741}
742
743impl NextScrollCursorCenterTopBottom {
744 fn next(&self) -> Self {
745 match self {
746 Self::Center => Self::Top,
747 Self::Top => Self::Bottom,
748 Self::Bottom => Self::Center,
749 }
750 }
751}
752
753#[derive(Clone)]
754pub struct EditorSnapshot {
755 pub mode: EditorMode,
756 show_gutter: bool,
757 show_line_numbers: Option<bool>,
758 show_git_diff_gutter: Option<bool>,
759 show_code_actions: Option<bool>,
760 show_runnables: Option<bool>,
761 git_blame_gutter_max_author_length: Option<usize>,
762 pub display_snapshot: DisplaySnapshot,
763 pub placeholder_text: Option<Arc<str>>,
764 is_focused: bool,
765 scroll_anchor: ScrollAnchor,
766 ongoing_scroll: OngoingScroll,
767 current_line_highlight: CurrentLineHighlight,
768 gutter_hovered: bool,
769}
770
771const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
772
773#[derive(Default, Debug, Clone, Copy)]
774pub struct GutterDimensions {
775 pub left_padding: Pixels,
776 pub right_padding: Pixels,
777 pub width: Pixels,
778 pub margin: Pixels,
779 pub git_blame_entries_width: Option<Pixels>,
780}
781
782impl GutterDimensions {
783 /// The full width of the space taken up by the gutter.
784 pub fn full_width(&self) -> Pixels {
785 self.margin + self.width
786 }
787
788 /// The width of the space reserved for the fold indicators,
789 /// use alongside 'justify_end' and `gutter_width` to
790 /// right align content with the line numbers
791 pub fn fold_area_width(&self) -> Pixels {
792 self.margin + self.right_padding
793 }
794}
795
796#[derive(Debug)]
797pub struct RemoteSelection {
798 pub replica_id: ReplicaId,
799 pub selection: Selection<Anchor>,
800 pub cursor_shape: CursorShape,
801 pub peer_id: PeerId,
802 pub line_mode: bool,
803 pub participant_index: Option<ParticipantIndex>,
804 pub user_name: Option<SharedString>,
805}
806
807#[derive(Clone, Debug)]
808struct SelectionHistoryEntry {
809 selections: Arc<[Selection<Anchor>]>,
810 select_next_state: Option<SelectNextState>,
811 select_prev_state: Option<SelectNextState>,
812 add_selections_state: Option<AddSelectionsState>,
813}
814
815enum SelectionHistoryMode {
816 Normal,
817 Undoing,
818 Redoing,
819}
820
821#[derive(Clone, PartialEq, Eq, Hash)]
822struct HoveredCursor {
823 replica_id: u16,
824 selection_id: usize,
825}
826
827impl Default for SelectionHistoryMode {
828 fn default() -> Self {
829 Self::Normal
830 }
831}
832
833#[derive(Default)]
834struct SelectionHistory {
835 #[allow(clippy::type_complexity)]
836 selections_by_transaction:
837 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
838 mode: SelectionHistoryMode,
839 undo_stack: VecDeque<SelectionHistoryEntry>,
840 redo_stack: VecDeque<SelectionHistoryEntry>,
841}
842
843impl SelectionHistory {
844 fn insert_transaction(
845 &mut self,
846 transaction_id: TransactionId,
847 selections: Arc<[Selection<Anchor>]>,
848 ) {
849 self.selections_by_transaction
850 .insert(transaction_id, (selections, None));
851 }
852
853 #[allow(clippy::type_complexity)]
854 fn transaction(
855 &self,
856 transaction_id: TransactionId,
857 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
858 self.selections_by_transaction.get(&transaction_id)
859 }
860
861 #[allow(clippy::type_complexity)]
862 fn transaction_mut(
863 &mut self,
864 transaction_id: TransactionId,
865 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
866 self.selections_by_transaction.get_mut(&transaction_id)
867 }
868
869 fn push(&mut self, entry: SelectionHistoryEntry) {
870 if !entry.selections.is_empty() {
871 match self.mode {
872 SelectionHistoryMode::Normal => {
873 self.push_undo(entry);
874 self.redo_stack.clear();
875 }
876 SelectionHistoryMode::Undoing => self.push_redo(entry),
877 SelectionHistoryMode::Redoing => self.push_undo(entry),
878 }
879 }
880 }
881
882 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
883 if self
884 .undo_stack
885 .back()
886 .map_or(true, |e| e.selections != entry.selections)
887 {
888 self.undo_stack.push_back(entry);
889 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
890 self.undo_stack.pop_front();
891 }
892 }
893 }
894
895 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
896 if self
897 .redo_stack
898 .back()
899 .map_or(true, |e| e.selections != entry.selections)
900 {
901 self.redo_stack.push_back(entry);
902 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
903 self.redo_stack.pop_front();
904 }
905 }
906 }
907}
908
909struct RowHighlight {
910 index: usize,
911 range: Range<Anchor>,
912 color: Hsla,
913 should_autoscroll: bool,
914}
915
916#[derive(Clone, Debug)]
917struct AddSelectionsState {
918 above: bool,
919 stack: Vec<usize>,
920}
921
922#[derive(Clone)]
923struct SelectNextState {
924 query: AhoCorasick,
925 wordwise: bool,
926 done: bool,
927}
928
929impl std::fmt::Debug for SelectNextState {
930 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
931 f.debug_struct(std::any::type_name::<Self>())
932 .field("wordwise", &self.wordwise)
933 .field("done", &self.done)
934 .finish()
935 }
936}
937
938#[derive(Debug)]
939struct AutocloseRegion {
940 selection_id: usize,
941 range: Range<Anchor>,
942 pair: BracketPair,
943}
944
945#[derive(Debug)]
946struct SnippetState {
947 ranges: Vec<Vec<Range<Anchor>>>,
948 active_index: usize,
949 choices: Vec<Option<Vec<String>>>,
950}
951
952#[doc(hidden)]
953pub struct RenameState {
954 pub range: Range<Anchor>,
955 pub old_name: Arc<str>,
956 pub editor: Entity<Editor>,
957 block_id: CustomBlockId,
958}
959
960struct InvalidationStack<T>(Vec<T>);
961
962struct RegisteredInlineCompletionProvider {
963 provider: Arc<dyn InlineCompletionProviderHandle>,
964 _subscription: Subscription,
965}
966
967#[derive(Debug)]
968struct ActiveDiagnosticGroup {
969 primary_range: Range<Anchor>,
970 primary_message: String,
971 group_id: usize,
972 blocks: HashMap<CustomBlockId, Diagnostic>,
973 is_valid: bool,
974}
975
976#[derive(Serialize, Deserialize, Clone, Debug)]
977pub struct ClipboardSelection {
978 pub len: usize,
979 pub is_entire_line: bool,
980 pub first_line_indent: u32,
981}
982
983#[derive(Debug)]
984pub(crate) struct NavigationData {
985 cursor_anchor: Anchor,
986 cursor_position: Point,
987 scroll_anchor: ScrollAnchor,
988 scroll_top_row: u32,
989}
990
991#[derive(Debug, Clone, Copy, PartialEq, Eq)]
992pub enum GotoDefinitionKind {
993 Symbol,
994 Declaration,
995 Type,
996 Implementation,
997}
998
999#[derive(Debug, Clone)]
1000enum InlayHintRefreshReason {
1001 Toggle(bool),
1002 SettingsChange(InlayHintSettings),
1003 NewLinesShown,
1004 BufferEdited(HashSet<Arc<Language>>),
1005 RefreshRequested,
1006 ExcerptsRemoved(Vec<ExcerptId>),
1007}
1008
1009impl InlayHintRefreshReason {
1010 fn description(&self) -> &'static str {
1011 match self {
1012 Self::Toggle(_) => "toggle",
1013 Self::SettingsChange(_) => "settings change",
1014 Self::NewLinesShown => "new lines shown",
1015 Self::BufferEdited(_) => "buffer edited",
1016 Self::RefreshRequested => "refresh requested",
1017 Self::ExcerptsRemoved(_) => "excerpts removed",
1018 }
1019 }
1020}
1021
1022pub enum FormatTarget {
1023 Buffers,
1024 Ranges(Vec<Range<MultiBufferPoint>>),
1025}
1026
1027pub(crate) struct FocusedBlock {
1028 id: BlockId,
1029 focus_handle: WeakFocusHandle,
1030}
1031
1032#[derive(Clone)]
1033enum JumpData {
1034 MultiBufferRow {
1035 row: MultiBufferRow,
1036 line_offset_from_top: u32,
1037 },
1038 MultiBufferPoint {
1039 excerpt_id: ExcerptId,
1040 position: Point,
1041 anchor: text::Anchor,
1042 line_offset_from_top: u32,
1043 },
1044}
1045
1046pub enum MultibufferSelectionMode {
1047 First,
1048 All,
1049}
1050
1051impl Editor {
1052 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1053 let buffer = cx.new(|cx| Buffer::local("", cx));
1054 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1055 Self::new(
1056 EditorMode::SingleLine { auto_width: false },
1057 buffer,
1058 None,
1059 false,
1060 window,
1061 cx,
1062 )
1063 }
1064
1065 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1066 let buffer = cx.new(|cx| Buffer::local("", cx));
1067 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1068 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1069 }
1070
1071 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1072 let buffer = cx.new(|cx| Buffer::local("", cx));
1073 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1074 Self::new(
1075 EditorMode::SingleLine { auto_width: true },
1076 buffer,
1077 None,
1078 false,
1079 window,
1080 cx,
1081 )
1082 }
1083
1084 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1085 let buffer = cx.new(|cx| Buffer::local("", cx));
1086 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1087 Self::new(
1088 EditorMode::AutoHeight { max_lines },
1089 buffer,
1090 None,
1091 false,
1092 window,
1093 cx,
1094 )
1095 }
1096
1097 pub fn for_buffer(
1098 buffer: Entity<Buffer>,
1099 project: Option<Entity<Project>>,
1100 window: &mut Window,
1101 cx: &mut Context<Self>,
1102 ) -> Self {
1103 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1104 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1105 }
1106
1107 pub fn for_multibuffer(
1108 buffer: Entity<MultiBuffer>,
1109 project: Option<Entity<Project>>,
1110 show_excerpt_controls: bool,
1111 window: &mut Window,
1112 cx: &mut Context<Self>,
1113 ) -> Self {
1114 Self::new(
1115 EditorMode::Full,
1116 buffer,
1117 project,
1118 show_excerpt_controls,
1119 window,
1120 cx,
1121 )
1122 }
1123
1124 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1125 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1126 let mut clone = Self::new(
1127 self.mode,
1128 self.buffer.clone(),
1129 self.project.clone(),
1130 show_excerpt_controls,
1131 window,
1132 cx,
1133 );
1134 self.display_map.update(cx, |display_map, cx| {
1135 let snapshot = display_map.snapshot(cx);
1136 clone.display_map.update(cx, |display_map, cx| {
1137 display_map.set_state(&snapshot, cx);
1138 });
1139 });
1140 clone.selections.clone_state(&self.selections);
1141 clone.scroll_manager.clone_state(&self.scroll_manager);
1142 clone.searchable = self.searchable;
1143 clone
1144 }
1145
1146 pub fn new(
1147 mode: EditorMode,
1148 buffer: Entity<MultiBuffer>,
1149 project: Option<Entity<Project>>,
1150 show_excerpt_controls: bool,
1151 window: &mut Window,
1152 cx: &mut Context<Self>,
1153 ) -> Self {
1154 let style = window.text_style();
1155 let font_size = style.font_size.to_pixels(window.rem_size());
1156 let editor = cx.entity().downgrade();
1157 let fold_placeholder = FoldPlaceholder {
1158 constrain_width: true,
1159 render: Arc::new(move |fold_id, fold_range, _, cx| {
1160 let editor = editor.clone();
1161 div()
1162 .id(fold_id)
1163 .bg(cx.theme().colors().ghost_element_background)
1164 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1165 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1166 .rounded_sm()
1167 .size_full()
1168 .cursor_pointer()
1169 .child("⋯")
1170 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1171 .on_click(move |_, _window, cx| {
1172 editor
1173 .update(cx, |editor, cx| {
1174 editor.unfold_ranges(
1175 &[fold_range.start..fold_range.end],
1176 true,
1177 false,
1178 cx,
1179 );
1180 cx.stop_propagation();
1181 })
1182 .ok();
1183 })
1184 .into_any()
1185 }),
1186 merge_adjacent: true,
1187 ..Default::default()
1188 };
1189 let display_map = cx.new(|cx| {
1190 DisplayMap::new(
1191 buffer.clone(),
1192 style.font(),
1193 font_size,
1194 None,
1195 show_excerpt_controls,
1196 FILE_HEADER_HEIGHT,
1197 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1198 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1199 fold_placeholder,
1200 cx,
1201 )
1202 });
1203
1204 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1205
1206 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1207
1208 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1209 .then(|| language_settings::SoftWrap::None);
1210
1211 let mut project_subscriptions = Vec::new();
1212 if mode == EditorMode::Full {
1213 if let Some(project) = project.as_ref() {
1214 if buffer.read(cx).is_singleton() {
1215 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1216 cx.emit(EditorEvent::TitleChanged);
1217 }));
1218 }
1219 project_subscriptions.push(cx.subscribe_in(
1220 project,
1221 window,
1222 |editor, _, event, window, cx| {
1223 if let project::Event::RefreshInlayHints = event {
1224 editor
1225 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1226 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1227 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1228 let focus_handle = editor.focus_handle(cx);
1229 if focus_handle.is_focused(window) {
1230 let snapshot = buffer.read(cx).snapshot();
1231 for (range, snippet) in snippet_edits {
1232 let editor_range =
1233 language::range_from_lsp(*range).to_offset(&snapshot);
1234 editor
1235 .insert_snippet(
1236 &[editor_range],
1237 snippet.clone(),
1238 window,
1239 cx,
1240 )
1241 .ok();
1242 }
1243 }
1244 }
1245 }
1246 },
1247 ));
1248 if let Some(task_inventory) = project
1249 .read(cx)
1250 .task_store()
1251 .read(cx)
1252 .task_inventory()
1253 .cloned()
1254 {
1255 project_subscriptions.push(cx.observe_in(
1256 &task_inventory,
1257 window,
1258 |editor, _, window, cx| {
1259 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1260 },
1261 ));
1262 }
1263 }
1264 }
1265
1266 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1267
1268 let inlay_hint_settings =
1269 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1270 let focus_handle = cx.focus_handle();
1271 cx.on_focus(&focus_handle, window, Self::handle_focus)
1272 .detach();
1273 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1274 .detach();
1275 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1276 .detach();
1277 cx.on_blur(&focus_handle, window, Self::handle_blur)
1278 .detach();
1279
1280 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1281 Some(false)
1282 } else {
1283 None
1284 };
1285
1286 let mut code_action_providers = Vec::new();
1287 if let Some(project) = project.clone() {
1288 get_unstaged_changes_for_buffers(
1289 &project,
1290 buffer.read(cx).all_buffers(),
1291 buffer.clone(),
1292 cx,
1293 );
1294 code_action_providers.push(Rc::new(project) as Rc<_>);
1295 }
1296
1297 let mut this = Self {
1298 focus_handle,
1299 show_cursor_when_unfocused: false,
1300 last_focused_descendant: None,
1301 buffer: buffer.clone(),
1302 display_map: display_map.clone(),
1303 selections,
1304 scroll_manager: ScrollManager::new(cx),
1305 columnar_selection_tail: None,
1306 add_selections_state: None,
1307 select_next_state: None,
1308 select_prev_state: None,
1309 selection_history: Default::default(),
1310 autoclose_regions: Default::default(),
1311 snippet_stack: Default::default(),
1312 select_larger_syntax_node_stack: Vec::new(),
1313 ime_transaction: Default::default(),
1314 active_diagnostics: None,
1315 soft_wrap_mode_override,
1316 completion_provider: project.clone().map(|project| Box::new(project) as _),
1317 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1318 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1319 project,
1320 blink_manager: blink_manager.clone(),
1321 show_local_selections: true,
1322 show_scrollbars: true,
1323 mode,
1324 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1325 show_gutter: mode == EditorMode::Full,
1326 show_line_numbers: None,
1327 use_relative_line_numbers: None,
1328 show_git_diff_gutter: None,
1329 show_code_actions: None,
1330 show_runnables: None,
1331 show_wrap_guides: None,
1332 show_indent_guides,
1333 placeholder_text: None,
1334 highlight_order: 0,
1335 highlighted_rows: HashMap::default(),
1336 background_highlights: Default::default(),
1337 gutter_highlights: TreeMap::default(),
1338 scrollbar_marker_state: ScrollbarMarkerState::default(),
1339 active_indent_guides_state: ActiveIndentGuidesState::default(),
1340 nav_history: None,
1341 context_menu: RefCell::new(None),
1342 mouse_context_menu: None,
1343 completion_tasks: Default::default(),
1344 signature_help_state: SignatureHelpState::default(),
1345 auto_signature_help: None,
1346 find_all_references_task_sources: Vec::new(),
1347 next_completion_id: 0,
1348 next_inlay_id: 0,
1349 code_action_providers,
1350 available_code_actions: Default::default(),
1351 code_actions_task: Default::default(),
1352 document_highlights_task: Default::default(),
1353 linked_editing_range_task: Default::default(),
1354 pending_rename: Default::default(),
1355 searchable: true,
1356 cursor_shape: EditorSettings::get_global(cx)
1357 .cursor_shape
1358 .unwrap_or_default(),
1359 current_line_highlight: None,
1360 autoindent_mode: Some(AutoindentMode::EachLine),
1361 collapse_matches: false,
1362 workspace: None,
1363 input_enabled: true,
1364 use_modal_editing: mode == EditorMode::Full,
1365 read_only: false,
1366 use_autoclose: true,
1367 use_auto_surround: true,
1368 auto_replace_emoji_shortcode: false,
1369 leader_peer_id: None,
1370 remote_id: None,
1371 hover_state: Default::default(),
1372 pending_mouse_down: None,
1373 hovered_link_state: Default::default(),
1374 inline_completion_provider: None,
1375 active_inline_completion: None,
1376 stale_inline_completion_in_menu: None,
1377 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1378
1379 gutter_hovered: false,
1380 pixel_position_of_newest_cursor: None,
1381 last_bounds: None,
1382 last_position_map: None,
1383 expect_bounds_change: None,
1384 gutter_dimensions: GutterDimensions::default(),
1385 style: None,
1386 show_cursor_names: false,
1387 hovered_cursors: Default::default(),
1388 next_editor_action_id: EditorActionId::default(),
1389 editor_actions: Rc::default(),
1390 show_inline_completions_override: None,
1391 enable_inline_completions: true,
1392 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1393 custom_context_menu: None,
1394 show_git_blame_gutter: false,
1395 show_git_blame_inline: false,
1396 show_selection_menu: None,
1397 show_git_blame_inline_delay_task: None,
1398 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1399 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1400 .session
1401 .restore_unsaved_buffers,
1402 blame: None,
1403 blame_subscription: None,
1404 tasks: Default::default(),
1405 _subscriptions: vec![
1406 cx.observe(&buffer, Self::on_buffer_changed),
1407 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1408 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1409 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1410 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1411 cx.observe_window_activation(window, |editor, window, cx| {
1412 let active = window.is_window_active();
1413 editor.blink_manager.update(cx, |blink_manager, cx| {
1414 if active {
1415 blink_manager.enable(cx);
1416 } else {
1417 blink_manager.disable(cx);
1418 }
1419 });
1420 }),
1421 ],
1422 tasks_update_task: None,
1423 linked_edit_ranges: Default::default(),
1424 in_project_search: false,
1425 previous_search_ranges: None,
1426 breadcrumb_header: None,
1427 focused_block: None,
1428 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1429 addons: HashMap::default(),
1430 registered_buffers: HashMap::default(),
1431 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1432 selection_mark_mode: false,
1433 toggle_fold_multiple_buffers: Task::ready(()),
1434 text_style_refinement: None,
1435 };
1436 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1437 this._subscriptions.extend(project_subscriptions);
1438
1439 this.end_selection(window, cx);
1440 this.scroll_manager.show_scrollbar(window, cx);
1441
1442 if mode == EditorMode::Full {
1443 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1444 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1445
1446 if this.git_blame_inline_enabled {
1447 this.git_blame_inline_enabled = true;
1448 this.start_git_blame_inline(false, window, cx);
1449 }
1450
1451 if let Some(buffer) = buffer.read(cx).as_singleton() {
1452 if let Some(project) = this.project.as_ref() {
1453 let lsp_store = project.read(cx).lsp_store();
1454 let handle = lsp_store.update(cx, |lsp_store, cx| {
1455 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1456 });
1457 this.registered_buffers
1458 .insert(buffer.read(cx).remote_id(), handle);
1459 }
1460 }
1461 }
1462
1463 this.report_editor_event("Editor Opened", None, cx);
1464 this
1465 }
1466
1467 pub fn mouse_menu_is_focused(&self, window: &mut Window, cx: &mut App) -> bool {
1468 self.mouse_context_menu
1469 .as_ref()
1470 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1471 }
1472
1473 fn key_context(&self, window: &mut Window, cx: &mut Context<Self>) -> KeyContext {
1474 let mut key_context = KeyContext::new_with_defaults();
1475 key_context.add("Editor");
1476 let mode = match self.mode {
1477 EditorMode::SingleLine { .. } => "single_line",
1478 EditorMode::AutoHeight { .. } => "auto_height",
1479 EditorMode::Full => "full",
1480 };
1481
1482 if EditorSettings::jupyter_enabled(cx) {
1483 key_context.add("jupyter");
1484 }
1485
1486 key_context.set("mode", mode);
1487 if self.pending_rename.is_some() {
1488 key_context.add("renaming");
1489 }
1490 match self.context_menu.borrow().as_ref() {
1491 Some(CodeContextMenu::Completions(_)) => {
1492 key_context.add("menu");
1493 key_context.add("showing_completions");
1494 }
1495 Some(CodeContextMenu::CodeActions(_)) => {
1496 key_context.add("menu");
1497 key_context.add("showing_code_actions")
1498 }
1499 None => {}
1500 }
1501
1502 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1503 if !self.focus_handle(cx).contains_focused(window, cx)
1504 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1505 {
1506 for addon in self.addons.values() {
1507 addon.extend_key_context(&mut key_context, cx)
1508 }
1509 }
1510
1511 if let Some(extension) = self
1512 .buffer
1513 .read(cx)
1514 .as_singleton()
1515 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1516 {
1517 key_context.set("extension", extension.to_string());
1518 }
1519
1520 if self.has_active_inline_completion() {
1521 key_context.add("copilot_suggestion");
1522 key_context.add("inline_completion");
1523 }
1524
1525 if self.selection_mark_mode {
1526 key_context.add("selection_mode");
1527 }
1528
1529 key_context
1530 }
1531
1532 pub fn new_file(
1533 workspace: &mut Workspace,
1534 _: &workspace::NewFile,
1535 window: &mut Window,
1536 cx: &mut Context<Workspace>,
1537 ) {
1538 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1539 "Failed to create buffer",
1540 window,
1541 cx,
1542 |e, _, _| match e.error_code() {
1543 ErrorCode::RemoteUpgradeRequired => Some(format!(
1544 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1545 e.error_tag("required").unwrap_or("the latest version")
1546 )),
1547 _ => None,
1548 },
1549 );
1550 }
1551
1552 pub fn new_in_workspace(
1553 workspace: &mut Workspace,
1554 window: &mut Window,
1555 cx: &mut Context<Workspace>,
1556 ) -> Task<Result<Entity<Editor>>> {
1557 let project = workspace.project().clone();
1558 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1559
1560 cx.spawn_in(window, |workspace, mut cx| async move {
1561 let buffer = create.await?;
1562 workspace.update_in(&mut cx, |workspace, window, cx| {
1563 let editor =
1564 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1565 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1566 editor
1567 })
1568 })
1569 }
1570
1571 fn new_file_vertical(
1572 workspace: &mut Workspace,
1573 _: &workspace::NewFileSplitVertical,
1574 window: &mut Window,
1575 cx: &mut Context<Workspace>,
1576 ) {
1577 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1578 }
1579
1580 fn new_file_horizontal(
1581 workspace: &mut Workspace,
1582 _: &workspace::NewFileSplitHorizontal,
1583 window: &mut Window,
1584 cx: &mut Context<Workspace>,
1585 ) {
1586 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1587 }
1588
1589 fn new_file_in_direction(
1590 workspace: &mut Workspace,
1591 direction: SplitDirection,
1592 window: &mut Window,
1593 cx: &mut Context<Workspace>,
1594 ) {
1595 let project = workspace.project().clone();
1596 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1597
1598 cx.spawn_in(window, |workspace, mut cx| async move {
1599 let buffer = create.await?;
1600 workspace.update_in(&mut cx, move |workspace, window, cx| {
1601 workspace.split_item(
1602 direction,
1603 Box::new(
1604 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1605 ),
1606 window,
1607 cx,
1608 )
1609 })?;
1610 anyhow::Ok(())
1611 })
1612 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1613 match e.error_code() {
1614 ErrorCode::RemoteUpgradeRequired => Some(format!(
1615 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1616 e.error_tag("required").unwrap_or("the latest version")
1617 )),
1618 _ => None,
1619 }
1620 });
1621 }
1622
1623 pub fn leader_peer_id(&self) -> Option<PeerId> {
1624 self.leader_peer_id
1625 }
1626
1627 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1628 &self.buffer
1629 }
1630
1631 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1632 self.workspace.as_ref()?.0.upgrade()
1633 }
1634
1635 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1636 self.buffer().read(cx).title(cx)
1637 }
1638
1639 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1640 let git_blame_gutter_max_author_length = self
1641 .render_git_blame_gutter(cx)
1642 .then(|| {
1643 if let Some(blame) = self.blame.as_ref() {
1644 let max_author_length =
1645 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1646 Some(max_author_length)
1647 } else {
1648 None
1649 }
1650 })
1651 .flatten();
1652
1653 EditorSnapshot {
1654 mode: self.mode,
1655 show_gutter: self.show_gutter,
1656 show_line_numbers: self.show_line_numbers,
1657 show_git_diff_gutter: self.show_git_diff_gutter,
1658 show_code_actions: self.show_code_actions,
1659 show_runnables: self.show_runnables,
1660 git_blame_gutter_max_author_length,
1661 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1662 scroll_anchor: self.scroll_manager.anchor(),
1663 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1664 placeholder_text: self.placeholder_text.clone(),
1665 is_focused: self.focus_handle.is_focused(window),
1666 current_line_highlight: self
1667 .current_line_highlight
1668 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1669 gutter_hovered: self.gutter_hovered,
1670 }
1671 }
1672
1673 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1674 self.buffer.read(cx).language_at(point, cx)
1675 }
1676
1677 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1678 self.buffer.read(cx).read(cx).file_at(point).cloned()
1679 }
1680
1681 pub fn active_excerpt(
1682 &self,
1683 cx: &App,
1684 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1685 self.buffer
1686 .read(cx)
1687 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1688 }
1689
1690 pub fn mode(&self) -> EditorMode {
1691 self.mode
1692 }
1693
1694 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1695 self.collaboration_hub.as_deref()
1696 }
1697
1698 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1699 self.collaboration_hub = Some(hub);
1700 }
1701
1702 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1703 self.in_project_search = in_project_search;
1704 }
1705
1706 pub fn set_custom_context_menu(
1707 &mut self,
1708 f: impl 'static
1709 + Fn(
1710 &mut Self,
1711 DisplayPoint,
1712 &mut Window,
1713 &mut Context<Self>,
1714 ) -> Option<Entity<ui::ContextMenu>>,
1715 ) {
1716 self.custom_context_menu = Some(Box::new(f))
1717 }
1718
1719 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1720 self.completion_provider = provider;
1721 }
1722
1723 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1724 self.semantics_provider.clone()
1725 }
1726
1727 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1728 self.semantics_provider = provider;
1729 }
1730
1731 pub fn set_inline_completion_provider<T>(
1732 &mut self,
1733 provider: Option<Entity<T>>,
1734 window: &mut Window,
1735 cx: &mut Context<Self>,
1736 ) where
1737 T: InlineCompletionProvider,
1738 {
1739 self.inline_completion_provider =
1740 provider.map(|provider| RegisteredInlineCompletionProvider {
1741 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1742 if this.focus_handle.is_focused(window) {
1743 this.update_visible_inline_completion(window, cx);
1744 }
1745 }),
1746 provider: Arc::new(provider),
1747 });
1748 self.refresh_inline_completion(false, false, window, cx);
1749 }
1750
1751 pub fn placeholder_text(&self) -> Option<&str> {
1752 self.placeholder_text.as_deref()
1753 }
1754
1755 pub fn set_placeholder_text(
1756 &mut self,
1757 placeholder_text: impl Into<Arc<str>>,
1758 cx: &mut Context<Self>,
1759 ) {
1760 let placeholder_text = Some(placeholder_text.into());
1761 if self.placeholder_text != placeholder_text {
1762 self.placeholder_text = placeholder_text;
1763 cx.notify();
1764 }
1765 }
1766
1767 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1768 self.cursor_shape = cursor_shape;
1769
1770 // Disrupt blink for immediate user feedback that the cursor shape has changed
1771 self.blink_manager.update(cx, BlinkManager::show_cursor);
1772
1773 cx.notify();
1774 }
1775
1776 pub fn set_current_line_highlight(
1777 &mut self,
1778 current_line_highlight: Option<CurrentLineHighlight>,
1779 ) {
1780 self.current_line_highlight = current_line_highlight;
1781 }
1782
1783 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1784 self.collapse_matches = collapse_matches;
1785 }
1786
1787 pub fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1788 let buffers = self.buffer.read(cx).all_buffers();
1789 let Some(lsp_store) = self.lsp_store(cx) else {
1790 return;
1791 };
1792 lsp_store.update(cx, |lsp_store, cx| {
1793 for buffer in buffers {
1794 self.registered_buffers
1795 .entry(buffer.read(cx).remote_id())
1796 .or_insert_with(|| {
1797 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1798 });
1799 }
1800 })
1801 }
1802
1803 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1804 if self.collapse_matches {
1805 return range.start..range.start;
1806 }
1807 range.clone()
1808 }
1809
1810 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1811 if self.display_map.read(cx).clip_at_line_ends != clip {
1812 self.display_map
1813 .update(cx, |map, _| map.clip_at_line_ends = clip);
1814 }
1815 }
1816
1817 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1818 self.input_enabled = input_enabled;
1819 }
1820
1821 pub fn set_inline_completions_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
1822 self.enable_inline_completions = enabled;
1823 if !self.enable_inline_completions {
1824 self.take_active_inline_completion(cx);
1825 cx.notify();
1826 }
1827 }
1828
1829 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1830 self.menu_inline_completions_policy = value;
1831 }
1832
1833 pub fn set_autoindent(&mut self, autoindent: bool) {
1834 if autoindent {
1835 self.autoindent_mode = Some(AutoindentMode::EachLine);
1836 } else {
1837 self.autoindent_mode = None;
1838 }
1839 }
1840
1841 pub fn read_only(&self, cx: &App) -> bool {
1842 self.read_only || self.buffer.read(cx).read_only()
1843 }
1844
1845 pub fn set_read_only(&mut self, read_only: bool) {
1846 self.read_only = read_only;
1847 }
1848
1849 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1850 self.use_autoclose = autoclose;
1851 }
1852
1853 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1854 self.use_auto_surround = auto_surround;
1855 }
1856
1857 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1858 self.auto_replace_emoji_shortcode = auto_replace;
1859 }
1860
1861 pub fn toggle_inline_completions(
1862 &mut self,
1863 _: &ToggleInlineCompletions,
1864 window: &mut Window,
1865 cx: &mut Context<Self>,
1866 ) {
1867 if self.show_inline_completions_override.is_some() {
1868 self.set_show_inline_completions(None, window, cx);
1869 } else {
1870 let cursor = self.selections.newest_anchor().head();
1871 if let Some((buffer, cursor_buffer_position)) =
1872 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1873 {
1874 let show_inline_completions =
1875 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
1876 self.set_show_inline_completions(Some(show_inline_completions), window, cx);
1877 }
1878 }
1879 }
1880
1881 pub fn set_show_inline_completions(
1882 &mut self,
1883 show_inline_completions: Option<bool>,
1884 window: &mut Window,
1885 cx: &mut Context<Self>,
1886 ) {
1887 self.show_inline_completions_override = show_inline_completions;
1888 self.refresh_inline_completion(false, true, window, cx);
1889 }
1890
1891 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
1892 let cursor = self.selections.newest_anchor().head();
1893 if let Some((buffer, buffer_position)) =
1894 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1895 {
1896 self.should_show_inline_completions(&buffer, buffer_position, cx)
1897 } else {
1898 false
1899 }
1900 }
1901
1902 fn should_show_inline_completions(
1903 &self,
1904 buffer: &Entity<Buffer>,
1905 buffer_position: language::Anchor,
1906 cx: &App,
1907 ) -> bool {
1908 if !self.snippet_stack.is_empty() {
1909 return false;
1910 }
1911
1912 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
1913 return false;
1914 }
1915
1916 if let Some(provider) = self.inline_completion_provider() {
1917 if let Some(show_inline_completions) = self.show_inline_completions_override {
1918 show_inline_completions
1919 } else {
1920 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
1921 }
1922 } else {
1923 false
1924 }
1925 }
1926
1927 fn inline_completions_disabled_in_scope(
1928 &self,
1929 buffer: &Entity<Buffer>,
1930 buffer_position: language::Anchor,
1931 cx: &App,
1932 ) -> bool {
1933 let snapshot = buffer.read(cx).snapshot();
1934 let settings = snapshot.settings_at(buffer_position, cx);
1935
1936 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1937 return false;
1938 };
1939
1940 scope.override_name().map_or(false, |scope_name| {
1941 settings
1942 .inline_completions_disabled_in
1943 .iter()
1944 .any(|s| s == scope_name)
1945 })
1946 }
1947
1948 pub fn set_use_modal_editing(&mut self, to: bool) {
1949 self.use_modal_editing = to;
1950 }
1951
1952 pub fn use_modal_editing(&self) -> bool {
1953 self.use_modal_editing
1954 }
1955
1956 fn selections_did_change(
1957 &mut self,
1958 local: bool,
1959 old_cursor_position: &Anchor,
1960 show_completions: bool,
1961 window: &mut Window,
1962 cx: &mut Context<Self>,
1963 ) {
1964 window.invalidate_character_coordinates();
1965
1966 // Copy selections to primary selection buffer
1967 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1968 if local {
1969 let selections = self.selections.all::<usize>(cx);
1970 let buffer_handle = self.buffer.read(cx).read(cx);
1971
1972 let mut text = String::new();
1973 for (index, selection) in selections.iter().enumerate() {
1974 let text_for_selection = buffer_handle
1975 .text_for_range(selection.start..selection.end)
1976 .collect::<String>();
1977
1978 text.push_str(&text_for_selection);
1979 if index != selections.len() - 1 {
1980 text.push('\n');
1981 }
1982 }
1983
1984 if !text.is_empty() {
1985 cx.write_to_primary(ClipboardItem::new_string(text));
1986 }
1987 }
1988
1989 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
1990 self.buffer.update(cx, |buffer, cx| {
1991 buffer.set_active_selections(
1992 &self.selections.disjoint_anchors(),
1993 self.selections.line_mode,
1994 self.cursor_shape,
1995 cx,
1996 )
1997 });
1998 }
1999 let display_map = self
2000 .display_map
2001 .update(cx, |display_map, cx| display_map.snapshot(cx));
2002 let buffer = &display_map.buffer_snapshot;
2003 self.add_selections_state = None;
2004 self.select_next_state = None;
2005 self.select_prev_state = None;
2006 self.select_larger_syntax_node_stack.clear();
2007 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2008 self.snippet_stack
2009 .invalidate(&self.selections.disjoint_anchors(), buffer);
2010 self.take_rename(false, window, cx);
2011
2012 let new_cursor_position = self.selections.newest_anchor().head();
2013
2014 self.push_to_nav_history(
2015 *old_cursor_position,
2016 Some(new_cursor_position.to_point(buffer)),
2017 cx,
2018 );
2019
2020 if local {
2021 let new_cursor_position = self.selections.newest_anchor().head();
2022 let mut context_menu = self.context_menu.borrow_mut();
2023 let completion_menu = match context_menu.as_ref() {
2024 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2025 _ => {
2026 *context_menu = None;
2027 None
2028 }
2029 };
2030
2031 if let Some(completion_menu) = completion_menu {
2032 let cursor_position = new_cursor_position.to_offset(buffer);
2033 let (word_range, kind) =
2034 buffer.surrounding_word(completion_menu.initial_position, true);
2035 if kind == Some(CharKind::Word)
2036 && word_range.to_inclusive().contains(&cursor_position)
2037 {
2038 let mut completion_menu = completion_menu.clone();
2039 drop(context_menu);
2040
2041 let query = Self::completion_query(buffer, cursor_position);
2042 cx.spawn(move |this, mut cx| async move {
2043 completion_menu
2044 .filter(query.as_deref(), cx.background_executor().clone())
2045 .await;
2046
2047 this.update(&mut cx, |this, cx| {
2048 let mut context_menu = this.context_menu.borrow_mut();
2049 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2050 else {
2051 return;
2052 };
2053
2054 if menu.id > completion_menu.id {
2055 return;
2056 }
2057
2058 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2059 drop(context_menu);
2060 cx.notify();
2061 })
2062 })
2063 .detach();
2064
2065 if show_completions {
2066 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2067 }
2068 } else {
2069 drop(context_menu);
2070 self.hide_context_menu(window, cx);
2071 }
2072 } else {
2073 drop(context_menu);
2074 }
2075
2076 hide_hover(self, cx);
2077
2078 if old_cursor_position.to_display_point(&display_map).row()
2079 != new_cursor_position.to_display_point(&display_map).row()
2080 {
2081 self.available_code_actions.take();
2082 }
2083 self.refresh_code_actions(window, cx);
2084 self.refresh_document_highlights(cx);
2085 refresh_matching_bracket_highlights(self, window, cx);
2086 self.update_visible_inline_completion(window, cx);
2087 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2088 if self.git_blame_inline_enabled {
2089 self.start_inline_blame_timer(window, cx);
2090 }
2091 }
2092
2093 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2094 cx.emit(EditorEvent::SelectionsChanged { local });
2095
2096 if self.selections.disjoint_anchors().len() == 1 {
2097 cx.emit(SearchEvent::ActiveMatchChanged)
2098 }
2099 cx.notify();
2100 }
2101
2102 pub fn change_selections<R>(
2103 &mut self,
2104 autoscroll: Option<Autoscroll>,
2105 window: &mut Window,
2106 cx: &mut Context<Self>,
2107 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2108 ) -> R {
2109 self.change_selections_inner(autoscroll, true, window, cx, change)
2110 }
2111
2112 pub fn change_selections_inner<R>(
2113 &mut self,
2114 autoscroll: Option<Autoscroll>,
2115 request_completions: bool,
2116 window: &mut Window,
2117 cx: &mut Context<Self>,
2118 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2119 ) -> R {
2120 let old_cursor_position = self.selections.newest_anchor().head();
2121 self.push_to_selection_history();
2122
2123 let (changed, result) = self.selections.change_with(cx, change);
2124
2125 if changed {
2126 if let Some(autoscroll) = autoscroll {
2127 self.request_autoscroll(autoscroll, cx);
2128 }
2129 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2130
2131 if self.should_open_signature_help_automatically(
2132 &old_cursor_position,
2133 self.signature_help_state.backspace_pressed(),
2134 cx,
2135 ) {
2136 self.show_signature_help(&ShowSignatureHelp, window, cx);
2137 }
2138 self.signature_help_state.set_backspace_pressed(false);
2139 }
2140
2141 result
2142 }
2143
2144 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2145 where
2146 I: IntoIterator<Item = (Range<S>, T)>,
2147 S: ToOffset,
2148 T: Into<Arc<str>>,
2149 {
2150 if self.read_only(cx) {
2151 return;
2152 }
2153
2154 self.buffer
2155 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2156 }
2157
2158 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2159 where
2160 I: IntoIterator<Item = (Range<S>, T)>,
2161 S: ToOffset,
2162 T: Into<Arc<str>>,
2163 {
2164 if self.read_only(cx) {
2165 return;
2166 }
2167
2168 self.buffer.update(cx, |buffer, cx| {
2169 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2170 });
2171 }
2172
2173 pub fn edit_with_block_indent<I, S, T>(
2174 &mut self,
2175 edits: I,
2176 original_indent_columns: Vec<u32>,
2177 cx: &mut Context<Self>,
2178 ) where
2179 I: IntoIterator<Item = (Range<S>, T)>,
2180 S: ToOffset,
2181 T: Into<Arc<str>>,
2182 {
2183 if self.read_only(cx) {
2184 return;
2185 }
2186
2187 self.buffer.update(cx, |buffer, cx| {
2188 buffer.edit(
2189 edits,
2190 Some(AutoindentMode::Block {
2191 original_indent_columns,
2192 }),
2193 cx,
2194 )
2195 });
2196 }
2197
2198 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2199 self.hide_context_menu(window, cx);
2200
2201 match phase {
2202 SelectPhase::Begin {
2203 position,
2204 add,
2205 click_count,
2206 } => self.begin_selection(position, add, click_count, window, cx),
2207 SelectPhase::BeginColumnar {
2208 position,
2209 goal_column,
2210 reset,
2211 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2212 SelectPhase::Extend {
2213 position,
2214 click_count,
2215 } => self.extend_selection(position, click_count, window, cx),
2216 SelectPhase::Update {
2217 position,
2218 goal_column,
2219 scroll_delta,
2220 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2221 SelectPhase::End => self.end_selection(window, cx),
2222 }
2223 }
2224
2225 fn extend_selection(
2226 &mut self,
2227 position: DisplayPoint,
2228 click_count: usize,
2229 window: &mut Window,
2230 cx: &mut Context<Self>,
2231 ) {
2232 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2233 let tail = self.selections.newest::<usize>(cx).tail();
2234 self.begin_selection(position, false, click_count, window, cx);
2235
2236 let position = position.to_offset(&display_map, Bias::Left);
2237 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2238
2239 let mut pending_selection = self
2240 .selections
2241 .pending_anchor()
2242 .expect("extend_selection not called with pending selection");
2243 if position >= tail {
2244 pending_selection.start = tail_anchor;
2245 } else {
2246 pending_selection.end = tail_anchor;
2247 pending_selection.reversed = true;
2248 }
2249
2250 let mut pending_mode = self.selections.pending_mode().unwrap();
2251 match &mut pending_mode {
2252 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2253 _ => {}
2254 }
2255
2256 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2257 s.set_pending(pending_selection, pending_mode)
2258 });
2259 }
2260
2261 fn begin_selection(
2262 &mut self,
2263 position: DisplayPoint,
2264 add: bool,
2265 click_count: usize,
2266 window: &mut Window,
2267 cx: &mut Context<Self>,
2268 ) {
2269 if !self.focus_handle.is_focused(window) {
2270 self.last_focused_descendant = None;
2271 window.focus(&self.focus_handle);
2272 }
2273
2274 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2275 let buffer = &display_map.buffer_snapshot;
2276 let newest_selection = self.selections.newest_anchor().clone();
2277 let position = display_map.clip_point(position, Bias::Left);
2278
2279 let start;
2280 let end;
2281 let mode;
2282 let mut auto_scroll;
2283 match click_count {
2284 1 => {
2285 start = buffer.anchor_before(position.to_point(&display_map));
2286 end = start;
2287 mode = SelectMode::Character;
2288 auto_scroll = true;
2289 }
2290 2 => {
2291 let range = movement::surrounding_word(&display_map, position);
2292 start = buffer.anchor_before(range.start.to_point(&display_map));
2293 end = buffer.anchor_before(range.end.to_point(&display_map));
2294 mode = SelectMode::Word(start..end);
2295 auto_scroll = true;
2296 }
2297 3 => {
2298 let position = display_map
2299 .clip_point(position, Bias::Left)
2300 .to_point(&display_map);
2301 let line_start = display_map.prev_line_boundary(position).0;
2302 let next_line_start = buffer.clip_point(
2303 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2304 Bias::Left,
2305 );
2306 start = buffer.anchor_before(line_start);
2307 end = buffer.anchor_before(next_line_start);
2308 mode = SelectMode::Line(start..end);
2309 auto_scroll = true;
2310 }
2311 _ => {
2312 start = buffer.anchor_before(0);
2313 end = buffer.anchor_before(buffer.len());
2314 mode = SelectMode::All;
2315 auto_scroll = false;
2316 }
2317 }
2318 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2319
2320 let point_to_delete: Option<usize> = {
2321 let selected_points: Vec<Selection<Point>> =
2322 self.selections.disjoint_in_range(start..end, cx);
2323
2324 if !add || click_count > 1 {
2325 None
2326 } else if !selected_points.is_empty() {
2327 Some(selected_points[0].id)
2328 } else {
2329 let clicked_point_already_selected =
2330 self.selections.disjoint.iter().find(|selection| {
2331 selection.start.to_point(buffer) == start.to_point(buffer)
2332 || selection.end.to_point(buffer) == end.to_point(buffer)
2333 });
2334
2335 clicked_point_already_selected.map(|selection| selection.id)
2336 }
2337 };
2338
2339 let selections_count = self.selections.count();
2340
2341 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2342 if let Some(point_to_delete) = point_to_delete {
2343 s.delete(point_to_delete);
2344
2345 if selections_count == 1 {
2346 s.set_pending_anchor_range(start..end, mode);
2347 }
2348 } else {
2349 if !add {
2350 s.clear_disjoint();
2351 } else if click_count > 1 {
2352 s.delete(newest_selection.id)
2353 }
2354
2355 s.set_pending_anchor_range(start..end, mode);
2356 }
2357 });
2358 }
2359
2360 fn begin_columnar_selection(
2361 &mut self,
2362 position: DisplayPoint,
2363 goal_column: u32,
2364 reset: bool,
2365 window: &mut Window,
2366 cx: &mut Context<Self>,
2367 ) {
2368 if !self.focus_handle.is_focused(window) {
2369 self.last_focused_descendant = None;
2370 window.focus(&self.focus_handle);
2371 }
2372
2373 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2374
2375 if reset {
2376 let pointer_position = display_map
2377 .buffer_snapshot
2378 .anchor_before(position.to_point(&display_map));
2379
2380 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2381 s.clear_disjoint();
2382 s.set_pending_anchor_range(
2383 pointer_position..pointer_position,
2384 SelectMode::Character,
2385 );
2386 });
2387 }
2388
2389 let tail = self.selections.newest::<Point>(cx).tail();
2390 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2391
2392 if !reset {
2393 self.select_columns(
2394 tail.to_display_point(&display_map),
2395 position,
2396 goal_column,
2397 &display_map,
2398 window,
2399 cx,
2400 );
2401 }
2402 }
2403
2404 fn update_selection(
2405 &mut self,
2406 position: DisplayPoint,
2407 goal_column: u32,
2408 scroll_delta: gpui::Point<f32>,
2409 window: &mut Window,
2410 cx: &mut Context<Self>,
2411 ) {
2412 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2413
2414 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2415 let tail = tail.to_display_point(&display_map);
2416 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2417 } else if let Some(mut pending) = self.selections.pending_anchor() {
2418 let buffer = self.buffer.read(cx).snapshot(cx);
2419 let head;
2420 let tail;
2421 let mode = self.selections.pending_mode().unwrap();
2422 match &mode {
2423 SelectMode::Character => {
2424 head = position.to_point(&display_map);
2425 tail = pending.tail().to_point(&buffer);
2426 }
2427 SelectMode::Word(original_range) => {
2428 let original_display_range = original_range.start.to_display_point(&display_map)
2429 ..original_range.end.to_display_point(&display_map);
2430 let original_buffer_range = original_display_range.start.to_point(&display_map)
2431 ..original_display_range.end.to_point(&display_map);
2432 if movement::is_inside_word(&display_map, position)
2433 || original_display_range.contains(&position)
2434 {
2435 let word_range = movement::surrounding_word(&display_map, position);
2436 if word_range.start < original_display_range.start {
2437 head = word_range.start.to_point(&display_map);
2438 } else {
2439 head = word_range.end.to_point(&display_map);
2440 }
2441 } else {
2442 head = position.to_point(&display_map);
2443 }
2444
2445 if head <= original_buffer_range.start {
2446 tail = original_buffer_range.end;
2447 } else {
2448 tail = original_buffer_range.start;
2449 }
2450 }
2451 SelectMode::Line(original_range) => {
2452 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2453
2454 let position = display_map
2455 .clip_point(position, Bias::Left)
2456 .to_point(&display_map);
2457 let line_start = display_map.prev_line_boundary(position).0;
2458 let next_line_start = buffer.clip_point(
2459 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2460 Bias::Left,
2461 );
2462
2463 if line_start < original_range.start {
2464 head = line_start
2465 } else {
2466 head = next_line_start
2467 }
2468
2469 if head <= original_range.start {
2470 tail = original_range.end;
2471 } else {
2472 tail = original_range.start;
2473 }
2474 }
2475 SelectMode::All => {
2476 return;
2477 }
2478 };
2479
2480 if head < tail {
2481 pending.start = buffer.anchor_before(head);
2482 pending.end = buffer.anchor_before(tail);
2483 pending.reversed = true;
2484 } else {
2485 pending.start = buffer.anchor_before(tail);
2486 pending.end = buffer.anchor_before(head);
2487 pending.reversed = false;
2488 }
2489
2490 self.change_selections(None, window, cx, |s| {
2491 s.set_pending(pending, mode);
2492 });
2493 } else {
2494 log::error!("update_selection dispatched with no pending selection");
2495 return;
2496 }
2497
2498 self.apply_scroll_delta(scroll_delta, window, cx);
2499 cx.notify();
2500 }
2501
2502 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2503 self.columnar_selection_tail.take();
2504 if self.selections.pending_anchor().is_some() {
2505 let selections = self.selections.all::<usize>(cx);
2506 self.change_selections(None, window, cx, |s| {
2507 s.select(selections);
2508 s.clear_pending();
2509 });
2510 }
2511 }
2512
2513 fn select_columns(
2514 &mut self,
2515 tail: DisplayPoint,
2516 head: DisplayPoint,
2517 goal_column: u32,
2518 display_map: &DisplaySnapshot,
2519 window: &mut Window,
2520 cx: &mut Context<Self>,
2521 ) {
2522 let start_row = cmp::min(tail.row(), head.row());
2523 let end_row = cmp::max(tail.row(), head.row());
2524 let start_column = cmp::min(tail.column(), goal_column);
2525 let end_column = cmp::max(tail.column(), goal_column);
2526 let reversed = start_column < tail.column();
2527
2528 let selection_ranges = (start_row.0..=end_row.0)
2529 .map(DisplayRow)
2530 .filter_map(|row| {
2531 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2532 let start = display_map
2533 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2534 .to_point(display_map);
2535 let end = display_map
2536 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2537 .to_point(display_map);
2538 if reversed {
2539 Some(end..start)
2540 } else {
2541 Some(start..end)
2542 }
2543 } else {
2544 None
2545 }
2546 })
2547 .collect::<Vec<_>>();
2548
2549 self.change_selections(None, window, cx, |s| {
2550 s.select_ranges(selection_ranges);
2551 });
2552 cx.notify();
2553 }
2554
2555 pub fn has_pending_nonempty_selection(&self) -> bool {
2556 let pending_nonempty_selection = match self.selections.pending_anchor() {
2557 Some(Selection { start, end, .. }) => start != end,
2558 None => false,
2559 };
2560
2561 pending_nonempty_selection
2562 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2563 }
2564
2565 pub fn has_pending_selection(&self) -> bool {
2566 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2567 }
2568
2569 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2570 self.selection_mark_mode = false;
2571
2572 if self.clear_expanded_diff_hunks(cx) {
2573 cx.notify();
2574 return;
2575 }
2576 if self.dismiss_menus_and_popups(true, window, cx) {
2577 return;
2578 }
2579
2580 if self.mode == EditorMode::Full
2581 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2582 {
2583 return;
2584 }
2585
2586 cx.propagate();
2587 }
2588
2589 pub fn dismiss_menus_and_popups(
2590 &mut self,
2591 should_report_inline_completion_event: bool,
2592 window: &mut Window,
2593 cx: &mut Context<Self>,
2594 ) -> bool {
2595 if self.take_rename(false, window, cx).is_some() {
2596 return true;
2597 }
2598
2599 if hide_hover(self, cx) {
2600 return true;
2601 }
2602
2603 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2604 return true;
2605 }
2606
2607 if self.hide_context_menu(window, cx).is_some() {
2608 return true;
2609 }
2610
2611 if self.mouse_context_menu.take().is_some() {
2612 return true;
2613 }
2614
2615 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2616 return true;
2617 }
2618
2619 if self.snippet_stack.pop().is_some() {
2620 return true;
2621 }
2622
2623 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2624 self.dismiss_diagnostics(cx);
2625 return true;
2626 }
2627
2628 false
2629 }
2630
2631 fn linked_editing_ranges_for(
2632 &self,
2633 selection: Range<text::Anchor>,
2634 cx: &App,
2635 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2636 if self.linked_edit_ranges.is_empty() {
2637 return None;
2638 }
2639 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2640 selection.end.buffer_id.and_then(|end_buffer_id| {
2641 if selection.start.buffer_id != Some(end_buffer_id) {
2642 return None;
2643 }
2644 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2645 let snapshot = buffer.read(cx).snapshot();
2646 self.linked_edit_ranges
2647 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2648 .map(|ranges| (ranges, snapshot, buffer))
2649 })?;
2650 use text::ToOffset as TO;
2651 // find offset from the start of current range to current cursor position
2652 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2653
2654 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2655 let start_difference = start_offset - start_byte_offset;
2656 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2657 let end_difference = end_offset - start_byte_offset;
2658 // Current range has associated linked ranges.
2659 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2660 for range in linked_ranges.iter() {
2661 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2662 let end_offset = start_offset + end_difference;
2663 let start_offset = start_offset + start_difference;
2664 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2665 continue;
2666 }
2667 if self.selections.disjoint_anchor_ranges().any(|s| {
2668 if s.start.buffer_id != selection.start.buffer_id
2669 || s.end.buffer_id != selection.end.buffer_id
2670 {
2671 return false;
2672 }
2673 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2674 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2675 }) {
2676 continue;
2677 }
2678 let start = buffer_snapshot.anchor_after(start_offset);
2679 let end = buffer_snapshot.anchor_after(end_offset);
2680 linked_edits
2681 .entry(buffer.clone())
2682 .or_default()
2683 .push(start..end);
2684 }
2685 Some(linked_edits)
2686 }
2687
2688 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2689 let text: Arc<str> = text.into();
2690
2691 if self.read_only(cx) {
2692 return;
2693 }
2694
2695 let selections = self.selections.all_adjusted(cx);
2696 let mut bracket_inserted = false;
2697 let mut edits = Vec::new();
2698 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2699 let mut new_selections = Vec::with_capacity(selections.len());
2700 let mut new_autoclose_regions = Vec::new();
2701 let snapshot = self.buffer.read(cx).read(cx);
2702
2703 for (selection, autoclose_region) in
2704 self.selections_with_autoclose_regions(selections, &snapshot)
2705 {
2706 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2707 // Determine if the inserted text matches the opening or closing
2708 // bracket of any of this language's bracket pairs.
2709 let mut bracket_pair = None;
2710 let mut is_bracket_pair_start = false;
2711 let mut is_bracket_pair_end = false;
2712 if !text.is_empty() {
2713 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2714 // and they are removing the character that triggered IME popup.
2715 for (pair, enabled) in scope.brackets() {
2716 if !pair.close && !pair.surround {
2717 continue;
2718 }
2719
2720 if enabled && pair.start.ends_with(text.as_ref()) {
2721 let prefix_len = pair.start.len() - text.len();
2722 let preceding_text_matches_prefix = prefix_len == 0
2723 || (selection.start.column >= (prefix_len as u32)
2724 && snapshot.contains_str_at(
2725 Point::new(
2726 selection.start.row,
2727 selection.start.column - (prefix_len as u32),
2728 ),
2729 &pair.start[..prefix_len],
2730 ));
2731 if preceding_text_matches_prefix {
2732 bracket_pair = Some(pair.clone());
2733 is_bracket_pair_start = true;
2734 break;
2735 }
2736 }
2737 if pair.end.as_str() == text.as_ref() {
2738 bracket_pair = Some(pair.clone());
2739 is_bracket_pair_end = true;
2740 break;
2741 }
2742 }
2743 }
2744
2745 if let Some(bracket_pair) = bracket_pair {
2746 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2747 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2748 let auto_surround =
2749 self.use_auto_surround && snapshot_settings.use_auto_surround;
2750 if selection.is_empty() {
2751 if is_bracket_pair_start {
2752 // If the inserted text is a suffix of an opening bracket and the
2753 // selection is preceded by the rest of the opening bracket, then
2754 // insert the closing bracket.
2755 let following_text_allows_autoclose = snapshot
2756 .chars_at(selection.start)
2757 .next()
2758 .map_or(true, |c| scope.should_autoclose_before(c));
2759
2760 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2761 && bracket_pair.start.len() == 1
2762 {
2763 let target = bracket_pair.start.chars().next().unwrap();
2764 let current_line_count = snapshot
2765 .reversed_chars_at(selection.start)
2766 .take_while(|&c| c != '\n')
2767 .filter(|&c| c == target)
2768 .count();
2769 current_line_count % 2 == 1
2770 } else {
2771 false
2772 };
2773
2774 if autoclose
2775 && bracket_pair.close
2776 && following_text_allows_autoclose
2777 && !is_closing_quote
2778 {
2779 let anchor = snapshot.anchor_before(selection.end);
2780 new_selections.push((selection.map(|_| anchor), text.len()));
2781 new_autoclose_regions.push((
2782 anchor,
2783 text.len(),
2784 selection.id,
2785 bracket_pair.clone(),
2786 ));
2787 edits.push((
2788 selection.range(),
2789 format!("{}{}", text, bracket_pair.end).into(),
2790 ));
2791 bracket_inserted = true;
2792 continue;
2793 }
2794 }
2795
2796 if let Some(region) = autoclose_region {
2797 // If the selection is followed by an auto-inserted closing bracket,
2798 // then don't insert that closing bracket again; just move the selection
2799 // past the closing bracket.
2800 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2801 && text.as_ref() == region.pair.end.as_str();
2802 if should_skip {
2803 let anchor = snapshot.anchor_after(selection.end);
2804 new_selections
2805 .push((selection.map(|_| anchor), region.pair.end.len()));
2806 continue;
2807 }
2808 }
2809
2810 let always_treat_brackets_as_autoclosed = snapshot
2811 .settings_at(selection.start, cx)
2812 .always_treat_brackets_as_autoclosed;
2813 if always_treat_brackets_as_autoclosed
2814 && is_bracket_pair_end
2815 && snapshot.contains_str_at(selection.end, text.as_ref())
2816 {
2817 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2818 // and the inserted text is a closing bracket and the selection is followed
2819 // by the closing bracket then move the selection past the closing bracket.
2820 let anchor = snapshot.anchor_after(selection.end);
2821 new_selections.push((selection.map(|_| anchor), text.len()));
2822 continue;
2823 }
2824 }
2825 // If an opening bracket is 1 character long and is typed while
2826 // text is selected, then surround that text with the bracket pair.
2827 else if auto_surround
2828 && bracket_pair.surround
2829 && is_bracket_pair_start
2830 && bracket_pair.start.chars().count() == 1
2831 {
2832 edits.push((selection.start..selection.start, text.clone()));
2833 edits.push((
2834 selection.end..selection.end,
2835 bracket_pair.end.as_str().into(),
2836 ));
2837 bracket_inserted = true;
2838 new_selections.push((
2839 Selection {
2840 id: selection.id,
2841 start: snapshot.anchor_after(selection.start),
2842 end: snapshot.anchor_before(selection.end),
2843 reversed: selection.reversed,
2844 goal: selection.goal,
2845 },
2846 0,
2847 ));
2848 continue;
2849 }
2850 }
2851 }
2852
2853 if self.auto_replace_emoji_shortcode
2854 && selection.is_empty()
2855 && text.as_ref().ends_with(':')
2856 {
2857 if let Some(possible_emoji_short_code) =
2858 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2859 {
2860 if !possible_emoji_short_code.is_empty() {
2861 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2862 let emoji_shortcode_start = Point::new(
2863 selection.start.row,
2864 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2865 );
2866
2867 // Remove shortcode from buffer
2868 edits.push((
2869 emoji_shortcode_start..selection.start,
2870 "".to_string().into(),
2871 ));
2872 new_selections.push((
2873 Selection {
2874 id: selection.id,
2875 start: snapshot.anchor_after(emoji_shortcode_start),
2876 end: snapshot.anchor_before(selection.start),
2877 reversed: selection.reversed,
2878 goal: selection.goal,
2879 },
2880 0,
2881 ));
2882
2883 // Insert emoji
2884 let selection_start_anchor = snapshot.anchor_after(selection.start);
2885 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2886 edits.push((selection.start..selection.end, emoji.to_string().into()));
2887
2888 continue;
2889 }
2890 }
2891 }
2892 }
2893
2894 // If not handling any auto-close operation, then just replace the selected
2895 // text with the given input and move the selection to the end of the
2896 // newly inserted text.
2897 let anchor = snapshot.anchor_after(selection.end);
2898 if !self.linked_edit_ranges.is_empty() {
2899 let start_anchor = snapshot.anchor_before(selection.start);
2900
2901 let is_word_char = text.chars().next().map_or(true, |char| {
2902 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2903 classifier.is_word(char)
2904 });
2905
2906 if is_word_char {
2907 if let Some(ranges) = self
2908 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2909 {
2910 for (buffer, edits) in ranges {
2911 linked_edits
2912 .entry(buffer.clone())
2913 .or_default()
2914 .extend(edits.into_iter().map(|range| (range, text.clone())));
2915 }
2916 }
2917 }
2918 }
2919
2920 new_selections.push((selection.map(|_| anchor), 0));
2921 edits.push((selection.start..selection.end, text.clone()));
2922 }
2923
2924 drop(snapshot);
2925
2926 self.transact(window, cx, |this, window, cx| {
2927 this.buffer.update(cx, |buffer, cx| {
2928 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2929 });
2930 for (buffer, edits) in linked_edits {
2931 buffer.update(cx, |buffer, cx| {
2932 let snapshot = buffer.snapshot();
2933 let edits = edits
2934 .into_iter()
2935 .map(|(range, text)| {
2936 use text::ToPoint as TP;
2937 let end_point = TP::to_point(&range.end, &snapshot);
2938 let start_point = TP::to_point(&range.start, &snapshot);
2939 (start_point..end_point, text)
2940 })
2941 .sorted_by_key(|(range, _)| range.start)
2942 .collect::<Vec<_>>();
2943 buffer.edit(edits, None, cx);
2944 })
2945 }
2946 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2947 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2948 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2949 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2950 .zip(new_selection_deltas)
2951 .map(|(selection, delta)| Selection {
2952 id: selection.id,
2953 start: selection.start + delta,
2954 end: selection.end + delta,
2955 reversed: selection.reversed,
2956 goal: SelectionGoal::None,
2957 })
2958 .collect::<Vec<_>>();
2959
2960 let mut i = 0;
2961 for (position, delta, selection_id, pair) in new_autoclose_regions {
2962 let position = position.to_offset(&map.buffer_snapshot) + delta;
2963 let start = map.buffer_snapshot.anchor_before(position);
2964 let end = map.buffer_snapshot.anchor_after(position);
2965 while let Some(existing_state) = this.autoclose_regions.get(i) {
2966 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2967 Ordering::Less => i += 1,
2968 Ordering::Greater => break,
2969 Ordering::Equal => {
2970 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2971 Ordering::Less => i += 1,
2972 Ordering::Equal => break,
2973 Ordering::Greater => break,
2974 }
2975 }
2976 }
2977 }
2978 this.autoclose_regions.insert(
2979 i,
2980 AutocloseRegion {
2981 selection_id,
2982 range: start..end,
2983 pair,
2984 },
2985 );
2986 }
2987
2988 let had_active_inline_completion = this.has_active_inline_completion();
2989 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
2990 s.select(new_selections)
2991 });
2992
2993 if !bracket_inserted {
2994 if let Some(on_type_format_task) =
2995 this.trigger_on_type_formatting(text.to_string(), window, cx)
2996 {
2997 on_type_format_task.detach_and_log_err(cx);
2998 }
2999 }
3000
3001 let editor_settings = EditorSettings::get_global(cx);
3002 if bracket_inserted
3003 && (editor_settings.auto_signature_help
3004 || editor_settings.show_signature_help_after_edits)
3005 {
3006 this.show_signature_help(&ShowSignatureHelp, window, cx);
3007 }
3008
3009 let trigger_in_words =
3010 this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
3011 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3012 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3013 this.refresh_inline_completion(true, false, window, cx);
3014 });
3015 }
3016
3017 fn find_possible_emoji_shortcode_at_position(
3018 snapshot: &MultiBufferSnapshot,
3019 position: Point,
3020 ) -> Option<String> {
3021 let mut chars = Vec::new();
3022 let mut found_colon = false;
3023 for char in snapshot.reversed_chars_at(position).take(100) {
3024 // Found a possible emoji shortcode in the middle of the buffer
3025 if found_colon {
3026 if char.is_whitespace() {
3027 chars.reverse();
3028 return Some(chars.iter().collect());
3029 }
3030 // If the previous character is not a whitespace, we are in the middle of a word
3031 // and we only want to complete the shortcode if the word is made up of other emojis
3032 let mut containing_word = String::new();
3033 for ch in snapshot
3034 .reversed_chars_at(position)
3035 .skip(chars.len() + 1)
3036 .take(100)
3037 {
3038 if ch.is_whitespace() {
3039 break;
3040 }
3041 containing_word.push(ch);
3042 }
3043 let containing_word = containing_word.chars().rev().collect::<String>();
3044 if util::word_consists_of_emojis(containing_word.as_str()) {
3045 chars.reverse();
3046 return Some(chars.iter().collect());
3047 }
3048 }
3049
3050 if char.is_whitespace() || !char.is_ascii() {
3051 return None;
3052 }
3053 if char == ':' {
3054 found_colon = true;
3055 } else {
3056 chars.push(char);
3057 }
3058 }
3059 // Found a possible emoji shortcode at the beginning of the buffer
3060 chars.reverse();
3061 Some(chars.iter().collect())
3062 }
3063
3064 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3065 self.transact(window, cx, |this, window, cx| {
3066 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3067 let selections = this.selections.all::<usize>(cx);
3068 let multi_buffer = this.buffer.read(cx);
3069 let buffer = multi_buffer.snapshot(cx);
3070 selections
3071 .iter()
3072 .map(|selection| {
3073 let start_point = selection.start.to_point(&buffer);
3074 let mut indent =
3075 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3076 indent.len = cmp::min(indent.len, start_point.column);
3077 let start = selection.start;
3078 let end = selection.end;
3079 let selection_is_empty = start == end;
3080 let language_scope = buffer.language_scope_at(start);
3081 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3082 &language_scope
3083 {
3084 let leading_whitespace_len = buffer
3085 .reversed_chars_at(start)
3086 .take_while(|c| c.is_whitespace() && *c != '\n')
3087 .map(|c| c.len_utf8())
3088 .sum::<usize>();
3089
3090 let trailing_whitespace_len = buffer
3091 .chars_at(end)
3092 .take_while(|c| c.is_whitespace() && *c != '\n')
3093 .map(|c| c.len_utf8())
3094 .sum::<usize>();
3095
3096 let insert_extra_newline =
3097 language.brackets().any(|(pair, enabled)| {
3098 let pair_start = pair.start.trim_end();
3099 let pair_end = pair.end.trim_start();
3100
3101 enabled
3102 && pair.newline
3103 && buffer.contains_str_at(
3104 end + trailing_whitespace_len,
3105 pair_end,
3106 )
3107 && buffer.contains_str_at(
3108 (start - leading_whitespace_len)
3109 .saturating_sub(pair_start.len()),
3110 pair_start,
3111 )
3112 });
3113
3114 // Comment extension on newline is allowed only for cursor selections
3115 let comment_delimiter = maybe!({
3116 if !selection_is_empty {
3117 return None;
3118 }
3119
3120 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3121 return None;
3122 }
3123
3124 let delimiters = language.line_comment_prefixes();
3125 let max_len_of_delimiter =
3126 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3127 let (snapshot, range) =
3128 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3129
3130 let mut index_of_first_non_whitespace = 0;
3131 let comment_candidate = snapshot
3132 .chars_for_range(range)
3133 .skip_while(|c| {
3134 let should_skip = c.is_whitespace();
3135 if should_skip {
3136 index_of_first_non_whitespace += 1;
3137 }
3138 should_skip
3139 })
3140 .take(max_len_of_delimiter)
3141 .collect::<String>();
3142 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3143 comment_candidate.starts_with(comment_prefix.as_ref())
3144 })?;
3145 let cursor_is_placed_after_comment_marker =
3146 index_of_first_non_whitespace + comment_prefix.len()
3147 <= start_point.column as usize;
3148 if cursor_is_placed_after_comment_marker {
3149 Some(comment_prefix.clone())
3150 } else {
3151 None
3152 }
3153 });
3154 (comment_delimiter, insert_extra_newline)
3155 } else {
3156 (None, false)
3157 };
3158
3159 let capacity_for_delimiter = comment_delimiter
3160 .as_deref()
3161 .map(str::len)
3162 .unwrap_or_default();
3163 let mut new_text =
3164 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3165 new_text.push('\n');
3166 new_text.extend(indent.chars());
3167 if let Some(delimiter) = &comment_delimiter {
3168 new_text.push_str(delimiter);
3169 }
3170 if insert_extra_newline {
3171 new_text = new_text.repeat(2);
3172 }
3173
3174 let anchor = buffer.anchor_after(end);
3175 let new_selection = selection.map(|_| anchor);
3176 (
3177 (start..end, new_text),
3178 (insert_extra_newline, new_selection),
3179 )
3180 })
3181 .unzip()
3182 };
3183
3184 this.edit_with_autoindent(edits, cx);
3185 let buffer = this.buffer.read(cx).snapshot(cx);
3186 let new_selections = selection_fixup_info
3187 .into_iter()
3188 .map(|(extra_newline_inserted, new_selection)| {
3189 let mut cursor = new_selection.end.to_point(&buffer);
3190 if extra_newline_inserted {
3191 cursor.row -= 1;
3192 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3193 }
3194 new_selection.map(|_| cursor)
3195 })
3196 .collect();
3197
3198 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3199 s.select(new_selections)
3200 });
3201 this.refresh_inline_completion(true, false, window, cx);
3202 });
3203 }
3204
3205 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3206 let buffer = self.buffer.read(cx);
3207 let snapshot = buffer.snapshot(cx);
3208
3209 let mut edits = Vec::new();
3210 let mut rows = Vec::new();
3211
3212 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3213 let cursor = selection.head();
3214 let row = cursor.row;
3215
3216 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3217
3218 let newline = "\n".to_string();
3219 edits.push((start_of_line..start_of_line, newline));
3220
3221 rows.push(row + rows_inserted as u32);
3222 }
3223
3224 self.transact(window, cx, |editor, window, cx| {
3225 editor.edit(edits, cx);
3226
3227 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3228 let mut index = 0;
3229 s.move_cursors_with(|map, _, _| {
3230 let row = rows[index];
3231 index += 1;
3232
3233 let point = Point::new(row, 0);
3234 let boundary = map.next_line_boundary(point).1;
3235 let clipped = map.clip_point(boundary, Bias::Left);
3236
3237 (clipped, SelectionGoal::None)
3238 });
3239 });
3240
3241 let mut indent_edits = Vec::new();
3242 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3243 for row in rows {
3244 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3245 for (row, indent) in indents {
3246 if indent.len == 0 {
3247 continue;
3248 }
3249
3250 let text = match indent.kind {
3251 IndentKind::Space => " ".repeat(indent.len as usize),
3252 IndentKind::Tab => "\t".repeat(indent.len as usize),
3253 };
3254 let point = Point::new(row.0, 0);
3255 indent_edits.push((point..point, text));
3256 }
3257 }
3258 editor.edit(indent_edits, cx);
3259 });
3260 }
3261
3262 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3263 let buffer = self.buffer.read(cx);
3264 let snapshot = buffer.snapshot(cx);
3265
3266 let mut edits = Vec::new();
3267 let mut rows = Vec::new();
3268 let mut rows_inserted = 0;
3269
3270 for selection in self.selections.all_adjusted(cx) {
3271 let cursor = selection.head();
3272 let row = cursor.row;
3273
3274 let point = Point::new(row + 1, 0);
3275 let start_of_line = snapshot.clip_point(point, Bias::Left);
3276
3277 let newline = "\n".to_string();
3278 edits.push((start_of_line..start_of_line, newline));
3279
3280 rows_inserted += 1;
3281 rows.push(row + rows_inserted);
3282 }
3283
3284 self.transact(window, cx, |editor, window, cx| {
3285 editor.edit(edits, cx);
3286
3287 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3288 let mut index = 0;
3289 s.move_cursors_with(|map, _, _| {
3290 let row = rows[index];
3291 index += 1;
3292
3293 let point = Point::new(row, 0);
3294 let boundary = map.next_line_boundary(point).1;
3295 let clipped = map.clip_point(boundary, Bias::Left);
3296
3297 (clipped, SelectionGoal::None)
3298 });
3299 });
3300
3301 let mut indent_edits = Vec::new();
3302 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3303 for row in rows {
3304 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3305 for (row, indent) in indents {
3306 if indent.len == 0 {
3307 continue;
3308 }
3309
3310 let text = match indent.kind {
3311 IndentKind::Space => " ".repeat(indent.len as usize),
3312 IndentKind::Tab => "\t".repeat(indent.len as usize),
3313 };
3314 let point = Point::new(row.0, 0);
3315 indent_edits.push((point..point, text));
3316 }
3317 }
3318 editor.edit(indent_edits, cx);
3319 });
3320 }
3321
3322 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3323 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3324 original_indent_columns: Vec::new(),
3325 });
3326 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3327 }
3328
3329 fn insert_with_autoindent_mode(
3330 &mut self,
3331 text: &str,
3332 autoindent_mode: Option<AutoindentMode>,
3333 window: &mut Window,
3334 cx: &mut Context<Self>,
3335 ) {
3336 if self.read_only(cx) {
3337 return;
3338 }
3339
3340 let text: Arc<str> = text.into();
3341 self.transact(window, cx, |this, window, cx| {
3342 let old_selections = this.selections.all_adjusted(cx);
3343 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3344 let anchors = {
3345 let snapshot = buffer.read(cx);
3346 old_selections
3347 .iter()
3348 .map(|s| {
3349 let anchor = snapshot.anchor_after(s.head());
3350 s.map(|_| anchor)
3351 })
3352 .collect::<Vec<_>>()
3353 };
3354 buffer.edit(
3355 old_selections
3356 .iter()
3357 .map(|s| (s.start..s.end, text.clone())),
3358 autoindent_mode,
3359 cx,
3360 );
3361 anchors
3362 });
3363
3364 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3365 s.select_anchors(selection_anchors);
3366 });
3367
3368 cx.notify();
3369 });
3370 }
3371
3372 fn trigger_completion_on_input(
3373 &mut self,
3374 text: &str,
3375 trigger_in_words: bool,
3376 window: &mut Window,
3377 cx: &mut Context<Self>,
3378 ) {
3379 if self.is_completion_trigger(text, trigger_in_words, cx) {
3380 self.show_completions(
3381 &ShowCompletions {
3382 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3383 },
3384 window,
3385 cx,
3386 );
3387 } else {
3388 self.hide_context_menu(window, cx);
3389 }
3390 }
3391
3392 fn is_completion_trigger(
3393 &self,
3394 text: &str,
3395 trigger_in_words: bool,
3396 cx: &mut Context<Self>,
3397 ) -> bool {
3398 let position = self.selections.newest_anchor().head();
3399 let multibuffer = self.buffer.read(cx);
3400 let Some(buffer) = position
3401 .buffer_id
3402 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3403 else {
3404 return false;
3405 };
3406
3407 if let Some(completion_provider) = &self.completion_provider {
3408 completion_provider.is_completion_trigger(
3409 &buffer,
3410 position.text_anchor,
3411 text,
3412 trigger_in_words,
3413 cx,
3414 )
3415 } else {
3416 false
3417 }
3418 }
3419
3420 /// If any empty selections is touching the start of its innermost containing autoclose
3421 /// region, expand it to select the brackets.
3422 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3423 let selections = self.selections.all::<usize>(cx);
3424 let buffer = self.buffer.read(cx).read(cx);
3425 let new_selections = self
3426 .selections_with_autoclose_regions(selections, &buffer)
3427 .map(|(mut selection, region)| {
3428 if !selection.is_empty() {
3429 return selection;
3430 }
3431
3432 if let Some(region) = region {
3433 let mut range = region.range.to_offset(&buffer);
3434 if selection.start == range.start && range.start >= region.pair.start.len() {
3435 range.start -= region.pair.start.len();
3436 if buffer.contains_str_at(range.start, ®ion.pair.start)
3437 && buffer.contains_str_at(range.end, ®ion.pair.end)
3438 {
3439 range.end += region.pair.end.len();
3440 selection.start = range.start;
3441 selection.end = range.end;
3442
3443 return selection;
3444 }
3445 }
3446 }
3447
3448 let always_treat_brackets_as_autoclosed = buffer
3449 .settings_at(selection.start, cx)
3450 .always_treat_brackets_as_autoclosed;
3451
3452 if !always_treat_brackets_as_autoclosed {
3453 return selection;
3454 }
3455
3456 if let Some(scope) = buffer.language_scope_at(selection.start) {
3457 for (pair, enabled) in scope.brackets() {
3458 if !enabled || !pair.close {
3459 continue;
3460 }
3461
3462 if buffer.contains_str_at(selection.start, &pair.end) {
3463 let pair_start_len = pair.start.len();
3464 if buffer.contains_str_at(
3465 selection.start.saturating_sub(pair_start_len),
3466 &pair.start,
3467 ) {
3468 selection.start -= pair_start_len;
3469 selection.end += pair.end.len();
3470
3471 return selection;
3472 }
3473 }
3474 }
3475 }
3476
3477 selection
3478 })
3479 .collect();
3480
3481 drop(buffer);
3482 self.change_selections(None, window, cx, |selections| {
3483 selections.select(new_selections)
3484 });
3485 }
3486
3487 /// Iterate the given selections, and for each one, find the smallest surrounding
3488 /// autoclose region. This uses the ordering of the selections and the autoclose
3489 /// regions to avoid repeated comparisons.
3490 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3491 &'a self,
3492 selections: impl IntoIterator<Item = Selection<D>>,
3493 buffer: &'a MultiBufferSnapshot,
3494 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3495 let mut i = 0;
3496 let mut regions = self.autoclose_regions.as_slice();
3497 selections.into_iter().map(move |selection| {
3498 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3499
3500 let mut enclosing = None;
3501 while let Some(pair_state) = regions.get(i) {
3502 if pair_state.range.end.to_offset(buffer) < range.start {
3503 regions = ®ions[i + 1..];
3504 i = 0;
3505 } else if pair_state.range.start.to_offset(buffer) > range.end {
3506 break;
3507 } else {
3508 if pair_state.selection_id == selection.id {
3509 enclosing = Some(pair_state);
3510 }
3511 i += 1;
3512 }
3513 }
3514
3515 (selection, enclosing)
3516 })
3517 }
3518
3519 /// Remove any autoclose regions that no longer contain their selection.
3520 fn invalidate_autoclose_regions(
3521 &mut self,
3522 mut selections: &[Selection<Anchor>],
3523 buffer: &MultiBufferSnapshot,
3524 ) {
3525 self.autoclose_regions.retain(|state| {
3526 let mut i = 0;
3527 while let Some(selection) = selections.get(i) {
3528 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3529 selections = &selections[1..];
3530 continue;
3531 }
3532 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3533 break;
3534 }
3535 if selection.id == state.selection_id {
3536 return true;
3537 } else {
3538 i += 1;
3539 }
3540 }
3541 false
3542 });
3543 }
3544
3545 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3546 let offset = position.to_offset(buffer);
3547 let (word_range, kind) = buffer.surrounding_word(offset, true);
3548 if offset > word_range.start && kind == Some(CharKind::Word) {
3549 Some(
3550 buffer
3551 .text_for_range(word_range.start..offset)
3552 .collect::<String>(),
3553 )
3554 } else {
3555 None
3556 }
3557 }
3558
3559 pub fn toggle_inlay_hints(
3560 &mut self,
3561 _: &ToggleInlayHints,
3562 _: &mut Window,
3563 cx: &mut Context<Self>,
3564 ) {
3565 self.refresh_inlay_hints(
3566 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3567 cx,
3568 );
3569 }
3570
3571 pub fn inlay_hints_enabled(&self) -> bool {
3572 self.inlay_hint_cache.enabled
3573 }
3574
3575 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3576 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3577 return;
3578 }
3579
3580 let reason_description = reason.description();
3581 let ignore_debounce = matches!(
3582 reason,
3583 InlayHintRefreshReason::SettingsChange(_)
3584 | InlayHintRefreshReason::Toggle(_)
3585 | InlayHintRefreshReason::ExcerptsRemoved(_)
3586 );
3587 let (invalidate_cache, required_languages) = match reason {
3588 InlayHintRefreshReason::Toggle(enabled) => {
3589 self.inlay_hint_cache.enabled = enabled;
3590 if enabled {
3591 (InvalidationStrategy::RefreshRequested, None)
3592 } else {
3593 self.inlay_hint_cache.clear();
3594 self.splice_inlays(
3595 &self
3596 .visible_inlay_hints(cx)
3597 .iter()
3598 .map(|inlay| inlay.id)
3599 .collect::<Vec<InlayId>>(),
3600 Vec::new(),
3601 cx,
3602 );
3603 return;
3604 }
3605 }
3606 InlayHintRefreshReason::SettingsChange(new_settings) => {
3607 match self.inlay_hint_cache.update_settings(
3608 &self.buffer,
3609 new_settings,
3610 self.visible_inlay_hints(cx),
3611 cx,
3612 ) {
3613 ControlFlow::Break(Some(InlaySplice {
3614 to_remove,
3615 to_insert,
3616 })) => {
3617 self.splice_inlays(&to_remove, to_insert, cx);
3618 return;
3619 }
3620 ControlFlow::Break(None) => return,
3621 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3622 }
3623 }
3624 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3625 if let Some(InlaySplice {
3626 to_remove,
3627 to_insert,
3628 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3629 {
3630 self.splice_inlays(&to_remove, to_insert, cx);
3631 }
3632 return;
3633 }
3634 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3635 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3636 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3637 }
3638 InlayHintRefreshReason::RefreshRequested => {
3639 (InvalidationStrategy::RefreshRequested, None)
3640 }
3641 };
3642
3643 if let Some(InlaySplice {
3644 to_remove,
3645 to_insert,
3646 }) = self.inlay_hint_cache.spawn_hint_refresh(
3647 reason_description,
3648 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3649 invalidate_cache,
3650 ignore_debounce,
3651 cx,
3652 ) {
3653 self.splice_inlays(&to_remove, to_insert, cx);
3654 }
3655 }
3656
3657 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3658 self.display_map
3659 .read(cx)
3660 .current_inlays()
3661 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3662 .cloned()
3663 .collect()
3664 }
3665
3666 pub fn excerpts_for_inlay_hints_query(
3667 &self,
3668 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3669 cx: &mut Context<Editor>,
3670 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3671 let Some(project) = self.project.as_ref() else {
3672 return HashMap::default();
3673 };
3674 let project = project.read(cx);
3675 let multi_buffer = self.buffer().read(cx);
3676 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3677 let multi_buffer_visible_start = self
3678 .scroll_manager
3679 .anchor()
3680 .anchor
3681 .to_point(&multi_buffer_snapshot);
3682 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3683 multi_buffer_visible_start
3684 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3685 Bias::Left,
3686 );
3687 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3688 multi_buffer_snapshot
3689 .range_to_buffer_ranges(multi_buffer_visible_range)
3690 .into_iter()
3691 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3692 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3693 let buffer_file = project::File::from_dyn(buffer.file())?;
3694 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3695 let worktree_entry = buffer_worktree
3696 .read(cx)
3697 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3698 if worktree_entry.is_ignored {
3699 return None;
3700 }
3701
3702 let language = buffer.language()?;
3703 if let Some(restrict_to_languages) = restrict_to_languages {
3704 if !restrict_to_languages.contains(language) {
3705 return None;
3706 }
3707 }
3708 Some((
3709 excerpt_id,
3710 (
3711 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3712 buffer.version().clone(),
3713 excerpt_visible_range,
3714 ),
3715 ))
3716 })
3717 .collect()
3718 }
3719
3720 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3721 TextLayoutDetails {
3722 text_system: window.text_system().clone(),
3723 editor_style: self.style.clone().unwrap(),
3724 rem_size: window.rem_size(),
3725 scroll_anchor: self.scroll_manager.anchor(),
3726 visible_rows: self.visible_line_count(),
3727 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3728 }
3729 }
3730
3731 pub fn splice_inlays(
3732 &self,
3733 to_remove: &[InlayId],
3734 to_insert: Vec<Inlay>,
3735 cx: &mut Context<Self>,
3736 ) {
3737 self.display_map.update(cx, |display_map, cx| {
3738 display_map.splice_inlays(to_remove, to_insert, cx)
3739 });
3740 cx.notify();
3741 }
3742
3743 fn trigger_on_type_formatting(
3744 &self,
3745 input: String,
3746 window: &mut Window,
3747 cx: &mut Context<Self>,
3748 ) -> Option<Task<Result<()>>> {
3749 if input.len() != 1 {
3750 return None;
3751 }
3752
3753 let project = self.project.as_ref()?;
3754 let position = self.selections.newest_anchor().head();
3755 let (buffer, buffer_position) = self
3756 .buffer
3757 .read(cx)
3758 .text_anchor_for_position(position, cx)?;
3759
3760 let settings = language_settings::language_settings(
3761 buffer
3762 .read(cx)
3763 .language_at(buffer_position)
3764 .map(|l| l.name()),
3765 buffer.read(cx).file(),
3766 cx,
3767 );
3768 if !settings.use_on_type_format {
3769 return None;
3770 }
3771
3772 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3773 // hence we do LSP request & edit on host side only — add formats to host's history.
3774 let push_to_lsp_host_history = true;
3775 // If this is not the host, append its history with new edits.
3776 let push_to_client_history = project.read(cx).is_via_collab();
3777
3778 let on_type_formatting = project.update(cx, |project, cx| {
3779 project.on_type_format(
3780 buffer.clone(),
3781 buffer_position,
3782 input,
3783 push_to_lsp_host_history,
3784 cx,
3785 )
3786 });
3787 Some(cx.spawn_in(window, |editor, mut cx| async move {
3788 if let Some(transaction) = on_type_formatting.await? {
3789 if push_to_client_history {
3790 buffer
3791 .update(&mut cx, |buffer, _| {
3792 buffer.push_transaction(transaction, Instant::now());
3793 })
3794 .ok();
3795 }
3796 editor.update(&mut cx, |editor, cx| {
3797 editor.refresh_document_highlights(cx);
3798 })?;
3799 }
3800 Ok(())
3801 }))
3802 }
3803
3804 pub fn show_completions(
3805 &mut self,
3806 options: &ShowCompletions,
3807 window: &mut Window,
3808 cx: &mut Context<Self>,
3809 ) {
3810 if self.pending_rename.is_some() {
3811 return;
3812 }
3813
3814 let Some(provider) = self.completion_provider.as_ref() else {
3815 return;
3816 };
3817
3818 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3819 return;
3820 }
3821
3822 let position = self.selections.newest_anchor().head();
3823 if position.diff_base_anchor.is_some() {
3824 return;
3825 }
3826 let (buffer, buffer_position) =
3827 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3828 output
3829 } else {
3830 return;
3831 };
3832 let show_completion_documentation = buffer
3833 .read(cx)
3834 .snapshot()
3835 .settings_at(buffer_position, cx)
3836 .show_completion_documentation;
3837
3838 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3839
3840 let trigger_kind = match &options.trigger {
3841 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3842 CompletionTriggerKind::TRIGGER_CHARACTER
3843 }
3844 _ => CompletionTriggerKind::INVOKED,
3845 };
3846 let completion_context = CompletionContext {
3847 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3848 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3849 Some(String::from(trigger))
3850 } else {
3851 None
3852 }
3853 }),
3854 trigger_kind,
3855 };
3856 let completions =
3857 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3858 let sort_completions = provider.sort_completions();
3859
3860 let id = post_inc(&mut self.next_completion_id);
3861 let task = cx.spawn_in(window, |editor, mut cx| {
3862 async move {
3863 editor.update(&mut cx, |this, _| {
3864 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3865 })?;
3866 let completions = completions.await.log_err();
3867 let menu = if let Some(completions) = completions {
3868 let mut menu = CompletionsMenu::new(
3869 id,
3870 sort_completions,
3871 show_completion_documentation,
3872 position,
3873 buffer.clone(),
3874 completions.into(),
3875 );
3876
3877 menu.filter(query.as_deref(), cx.background_executor().clone())
3878 .await;
3879
3880 menu.visible().then_some(menu)
3881 } else {
3882 None
3883 };
3884
3885 editor.update_in(&mut cx, |editor, window, cx| {
3886 match editor.context_menu.borrow().as_ref() {
3887 None => {}
3888 Some(CodeContextMenu::Completions(prev_menu)) => {
3889 if prev_menu.id > id {
3890 return;
3891 }
3892 }
3893 _ => return,
3894 }
3895
3896 if editor.focus_handle.is_focused(window) && menu.is_some() {
3897 let mut menu = menu.unwrap();
3898 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3899
3900 *editor.context_menu.borrow_mut() =
3901 Some(CodeContextMenu::Completions(menu));
3902
3903 if editor.show_inline_completions_in_menu(cx) {
3904 editor.update_visible_inline_completion(window, cx);
3905 } else {
3906 editor.discard_inline_completion(false, cx);
3907 }
3908
3909 cx.notify();
3910 } else if editor.completion_tasks.len() <= 1 {
3911 // If there are no more completion tasks and the last menu was
3912 // empty, we should hide it.
3913 let was_hidden = editor.hide_context_menu(window, cx).is_none();
3914 // If it was already hidden and we don't show inline
3915 // completions in the menu, we should also show the
3916 // inline-completion when available.
3917 if was_hidden && editor.show_inline_completions_in_menu(cx) {
3918 editor.update_visible_inline_completion(window, cx);
3919 }
3920 }
3921 })?;
3922
3923 Ok::<_, anyhow::Error>(())
3924 }
3925 .log_err()
3926 });
3927
3928 self.completion_tasks.push((id, task));
3929 }
3930
3931 pub fn confirm_completion(
3932 &mut self,
3933 action: &ConfirmCompletion,
3934 window: &mut Window,
3935 cx: &mut Context<Self>,
3936 ) -> Option<Task<Result<()>>> {
3937 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
3938 }
3939
3940 pub fn compose_completion(
3941 &mut self,
3942 action: &ComposeCompletion,
3943 window: &mut Window,
3944 cx: &mut Context<Self>,
3945 ) -> Option<Task<Result<()>>> {
3946 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
3947 }
3948
3949 fn toggle_zed_predict_onboarding(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3950 window.dispatch_action(zed_actions::OpenZedPredictOnboarding.boxed_clone(), cx);
3951 }
3952
3953 fn do_completion(
3954 &mut self,
3955 item_ix: Option<usize>,
3956 intent: CompletionIntent,
3957 window: &mut Window,
3958 cx: &mut Context<Editor>,
3959 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3960 use language::ToOffset as _;
3961
3962 let completions_menu =
3963 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
3964 menu
3965 } else {
3966 return None;
3967 };
3968
3969 let entries = completions_menu.entries.borrow();
3970 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
3971 if self.show_inline_completions_in_menu(cx) {
3972 self.discard_inline_completion(true, cx);
3973 }
3974 let candidate_id = mat.candidate_id;
3975 drop(entries);
3976
3977 let buffer_handle = completions_menu.buffer;
3978 let completion = completions_menu
3979 .completions
3980 .borrow()
3981 .get(candidate_id)?
3982 .clone();
3983 cx.stop_propagation();
3984
3985 let snippet;
3986 let text;
3987
3988 if completion.is_snippet() {
3989 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3990 text = snippet.as_ref().unwrap().text.clone();
3991 } else {
3992 snippet = None;
3993 text = completion.new_text.clone();
3994 };
3995 let selections = self.selections.all::<usize>(cx);
3996 let buffer = buffer_handle.read(cx);
3997 let old_range = completion.old_range.to_offset(buffer);
3998 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3999
4000 let newest_selection = self.selections.newest_anchor();
4001 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4002 return None;
4003 }
4004
4005 let lookbehind = newest_selection
4006 .start
4007 .text_anchor
4008 .to_offset(buffer)
4009 .saturating_sub(old_range.start);
4010 let lookahead = old_range
4011 .end
4012 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4013 let mut common_prefix_len = old_text
4014 .bytes()
4015 .zip(text.bytes())
4016 .take_while(|(a, b)| a == b)
4017 .count();
4018
4019 let snapshot = self.buffer.read(cx).snapshot(cx);
4020 let mut range_to_replace: Option<Range<isize>> = None;
4021 let mut ranges = Vec::new();
4022 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4023 for selection in &selections {
4024 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4025 let start = selection.start.saturating_sub(lookbehind);
4026 let end = selection.end + lookahead;
4027 if selection.id == newest_selection.id {
4028 range_to_replace = Some(
4029 ((start + common_prefix_len) as isize - selection.start as isize)
4030 ..(end as isize - selection.start as isize),
4031 );
4032 }
4033 ranges.push(start + common_prefix_len..end);
4034 } else {
4035 common_prefix_len = 0;
4036 ranges.clear();
4037 ranges.extend(selections.iter().map(|s| {
4038 if s.id == newest_selection.id {
4039 range_to_replace = Some(
4040 old_range.start.to_offset_utf16(&snapshot).0 as isize
4041 - selection.start as isize
4042 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4043 - selection.start as isize,
4044 );
4045 old_range.clone()
4046 } else {
4047 s.start..s.end
4048 }
4049 }));
4050 break;
4051 }
4052 if !self.linked_edit_ranges.is_empty() {
4053 let start_anchor = snapshot.anchor_before(selection.head());
4054 let end_anchor = snapshot.anchor_after(selection.tail());
4055 if let Some(ranges) = self
4056 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4057 {
4058 for (buffer, edits) in ranges {
4059 linked_edits.entry(buffer.clone()).or_default().extend(
4060 edits
4061 .into_iter()
4062 .map(|range| (range, text[common_prefix_len..].to_owned())),
4063 );
4064 }
4065 }
4066 }
4067 }
4068 let text = &text[common_prefix_len..];
4069
4070 cx.emit(EditorEvent::InputHandled {
4071 utf16_range_to_replace: range_to_replace,
4072 text: text.into(),
4073 });
4074
4075 self.transact(window, cx, |this, window, cx| {
4076 if let Some(mut snippet) = snippet {
4077 snippet.text = text.to_string();
4078 for tabstop in snippet
4079 .tabstops
4080 .iter_mut()
4081 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4082 {
4083 tabstop.start -= common_prefix_len as isize;
4084 tabstop.end -= common_prefix_len as isize;
4085 }
4086
4087 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4088 } else {
4089 this.buffer.update(cx, |buffer, cx| {
4090 buffer.edit(
4091 ranges.iter().map(|range| (range.clone(), text)),
4092 this.autoindent_mode.clone(),
4093 cx,
4094 );
4095 });
4096 }
4097 for (buffer, edits) in linked_edits {
4098 buffer.update(cx, |buffer, cx| {
4099 let snapshot = buffer.snapshot();
4100 let edits = edits
4101 .into_iter()
4102 .map(|(range, text)| {
4103 use text::ToPoint as TP;
4104 let end_point = TP::to_point(&range.end, &snapshot);
4105 let start_point = TP::to_point(&range.start, &snapshot);
4106 (start_point..end_point, text)
4107 })
4108 .sorted_by_key(|(range, _)| range.start)
4109 .collect::<Vec<_>>();
4110 buffer.edit(edits, None, cx);
4111 })
4112 }
4113
4114 this.refresh_inline_completion(true, false, window, cx);
4115 });
4116
4117 let show_new_completions_on_confirm = completion
4118 .confirm
4119 .as_ref()
4120 .map_or(false, |confirm| confirm(intent, window, cx));
4121 if show_new_completions_on_confirm {
4122 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4123 }
4124
4125 let provider = self.completion_provider.as_ref()?;
4126 drop(completion);
4127 let apply_edits = provider.apply_additional_edits_for_completion(
4128 buffer_handle,
4129 completions_menu.completions.clone(),
4130 candidate_id,
4131 true,
4132 cx,
4133 );
4134
4135 let editor_settings = EditorSettings::get_global(cx);
4136 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4137 // After the code completion is finished, users often want to know what signatures are needed.
4138 // so we should automatically call signature_help
4139 self.show_signature_help(&ShowSignatureHelp, window, cx);
4140 }
4141
4142 Some(cx.foreground_executor().spawn(async move {
4143 apply_edits.await?;
4144 Ok(())
4145 }))
4146 }
4147
4148 pub fn toggle_code_actions(
4149 &mut self,
4150 action: &ToggleCodeActions,
4151 window: &mut Window,
4152 cx: &mut Context<Self>,
4153 ) {
4154 let mut context_menu = self.context_menu.borrow_mut();
4155 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4156 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4157 // Toggle if we're selecting the same one
4158 *context_menu = None;
4159 cx.notify();
4160 return;
4161 } else {
4162 // Otherwise, clear it and start a new one
4163 *context_menu = None;
4164 cx.notify();
4165 }
4166 }
4167 drop(context_menu);
4168 let snapshot = self.snapshot(window, cx);
4169 let deployed_from_indicator = action.deployed_from_indicator;
4170 let mut task = self.code_actions_task.take();
4171 let action = action.clone();
4172 cx.spawn_in(window, |editor, mut cx| async move {
4173 while let Some(prev_task) = task {
4174 prev_task.await.log_err();
4175 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4176 }
4177
4178 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4179 if editor.focus_handle.is_focused(window) {
4180 let multibuffer_point = action
4181 .deployed_from_indicator
4182 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4183 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4184 let (buffer, buffer_row) = snapshot
4185 .buffer_snapshot
4186 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4187 .and_then(|(buffer_snapshot, range)| {
4188 editor
4189 .buffer
4190 .read(cx)
4191 .buffer(buffer_snapshot.remote_id())
4192 .map(|buffer| (buffer, range.start.row))
4193 })?;
4194 let (_, code_actions) = editor
4195 .available_code_actions
4196 .clone()
4197 .and_then(|(location, code_actions)| {
4198 let snapshot = location.buffer.read(cx).snapshot();
4199 let point_range = location.range.to_point(&snapshot);
4200 let point_range = point_range.start.row..=point_range.end.row;
4201 if point_range.contains(&buffer_row) {
4202 Some((location, code_actions))
4203 } else {
4204 None
4205 }
4206 })
4207 .unzip();
4208 let buffer_id = buffer.read(cx).remote_id();
4209 let tasks = editor
4210 .tasks
4211 .get(&(buffer_id, buffer_row))
4212 .map(|t| Arc::new(t.to_owned()));
4213 if tasks.is_none() && code_actions.is_none() {
4214 return None;
4215 }
4216
4217 editor.completion_tasks.clear();
4218 editor.discard_inline_completion(false, cx);
4219 let task_context =
4220 tasks
4221 .as_ref()
4222 .zip(editor.project.clone())
4223 .map(|(tasks, project)| {
4224 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4225 });
4226
4227 Some(cx.spawn_in(window, |editor, mut cx| async move {
4228 let task_context = match task_context {
4229 Some(task_context) => task_context.await,
4230 None => None,
4231 };
4232 let resolved_tasks =
4233 tasks.zip(task_context).map(|(tasks, task_context)| {
4234 Rc::new(ResolvedTasks {
4235 templates: tasks.resolve(&task_context).collect(),
4236 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4237 multibuffer_point.row,
4238 tasks.column,
4239 )),
4240 })
4241 });
4242 let spawn_straight_away = resolved_tasks
4243 .as_ref()
4244 .map_or(false, |tasks| tasks.templates.len() == 1)
4245 && code_actions
4246 .as_ref()
4247 .map_or(true, |actions| actions.is_empty());
4248 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4249 *editor.context_menu.borrow_mut() =
4250 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4251 buffer,
4252 actions: CodeActionContents {
4253 tasks: resolved_tasks,
4254 actions: code_actions,
4255 },
4256 selected_item: Default::default(),
4257 scroll_handle: UniformListScrollHandle::default(),
4258 deployed_from_indicator,
4259 }));
4260 if spawn_straight_away {
4261 if let Some(task) = editor.confirm_code_action(
4262 &ConfirmCodeAction { item_ix: Some(0) },
4263 window,
4264 cx,
4265 ) {
4266 cx.notify();
4267 return task;
4268 }
4269 }
4270 cx.notify();
4271 Task::ready(Ok(()))
4272 }) {
4273 task.await
4274 } else {
4275 Ok(())
4276 }
4277 }))
4278 } else {
4279 Some(Task::ready(Ok(())))
4280 }
4281 })?;
4282 if let Some(task) = spawned_test_task {
4283 task.await?;
4284 }
4285
4286 Ok::<_, anyhow::Error>(())
4287 })
4288 .detach_and_log_err(cx);
4289 }
4290
4291 pub fn confirm_code_action(
4292 &mut self,
4293 action: &ConfirmCodeAction,
4294 window: &mut Window,
4295 cx: &mut Context<Self>,
4296 ) -> Option<Task<Result<()>>> {
4297 let actions_menu =
4298 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4299 menu
4300 } else {
4301 return None;
4302 };
4303 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4304 let action = actions_menu.actions.get(action_ix)?;
4305 let title = action.label();
4306 let buffer = actions_menu.buffer;
4307 let workspace = self.workspace()?;
4308
4309 match action {
4310 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4311 workspace.update(cx, |workspace, cx| {
4312 workspace::tasks::schedule_resolved_task(
4313 workspace,
4314 task_source_kind,
4315 resolved_task,
4316 false,
4317 cx,
4318 );
4319
4320 Some(Task::ready(Ok(())))
4321 })
4322 }
4323 CodeActionsItem::CodeAction {
4324 excerpt_id,
4325 action,
4326 provider,
4327 } => {
4328 let apply_code_action =
4329 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4330 let workspace = workspace.downgrade();
4331 Some(cx.spawn_in(window, |editor, cx| async move {
4332 let project_transaction = apply_code_action.await?;
4333 Self::open_project_transaction(
4334 &editor,
4335 workspace,
4336 project_transaction,
4337 title,
4338 cx,
4339 )
4340 .await
4341 }))
4342 }
4343 }
4344 }
4345
4346 pub async fn open_project_transaction(
4347 this: &WeakEntity<Editor>,
4348 workspace: WeakEntity<Workspace>,
4349 transaction: ProjectTransaction,
4350 title: String,
4351 mut cx: AsyncWindowContext,
4352 ) -> Result<()> {
4353 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4354 cx.update(|_, cx| {
4355 entries.sort_unstable_by_key(|(buffer, _)| {
4356 buffer.read(cx).file().map(|f| f.path().clone())
4357 });
4358 })?;
4359
4360 // If the project transaction's edits are all contained within this editor, then
4361 // avoid opening a new editor to display them.
4362
4363 if let Some((buffer, transaction)) = entries.first() {
4364 if entries.len() == 1 {
4365 let excerpt = this.update(&mut cx, |editor, cx| {
4366 editor
4367 .buffer()
4368 .read(cx)
4369 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4370 })?;
4371 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4372 if excerpted_buffer == *buffer {
4373 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4374 let excerpt_range = excerpt_range.to_offset(buffer);
4375 buffer
4376 .edited_ranges_for_transaction::<usize>(transaction)
4377 .all(|range| {
4378 excerpt_range.start <= range.start
4379 && excerpt_range.end >= range.end
4380 })
4381 })?;
4382
4383 if all_edits_within_excerpt {
4384 return Ok(());
4385 }
4386 }
4387 }
4388 }
4389 } else {
4390 return Ok(());
4391 }
4392
4393 let mut ranges_to_highlight = Vec::new();
4394 let excerpt_buffer = cx.new(|cx| {
4395 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4396 for (buffer_handle, transaction) in &entries {
4397 let buffer = buffer_handle.read(cx);
4398 ranges_to_highlight.extend(
4399 multibuffer.push_excerpts_with_context_lines(
4400 buffer_handle.clone(),
4401 buffer
4402 .edited_ranges_for_transaction::<usize>(transaction)
4403 .collect(),
4404 DEFAULT_MULTIBUFFER_CONTEXT,
4405 cx,
4406 ),
4407 );
4408 }
4409 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4410 multibuffer
4411 })?;
4412
4413 workspace.update_in(&mut cx, |workspace, window, cx| {
4414 let project = workspace.project().clone();
4415 let editor = cx
4416 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4417 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4418 editor.update(cx, |editor, cx| {
4419 editor.highlight_background::<Self>(
4420 &ranges_to_highlight,
4421 |theme| theme.editor_highlighted_line_background,
4422 cx,
4423 );
4424 });
4425 })?;
4426
4427 Ok(())
4428 }
4429
4430 pub fn clear_code_action_providers(&mut self) {
4431 self.code_action_providers.clear();
4432 self.available_code_actions.take();
4433 }
4434
4435 pub fn add_code_action_provider(
4436 &mut self,
4437 provider: Rc<dyn CodeActionProvider>,
4438 window: &mut Window,
4439 cx: &mut Context<Self>,
4440 ) {
4441 if self
4442 .code_action_providers
4443 .iter()
4444 .any(|existing_provider| existing_provider.id() == provider.id())
4445 {
4446 return;
4447 }
4448
4449 self.code_action_providers.push(provider);
4450 self.refresh_code_actions(window, cx);
4451 }
4452
4453 pub fn remove_code_action_provider(
4454 &mut self,
4455 id: Arc<str>,
4456 window: &mut Window,
4457 cx: &mut Context<Self>,
4458 ) {
4459 self.code_action_providers
4460 .retain(|provider| provider.id() != id);
4461 self.refresh_code_actions(window, cx);
4462 }
4463
4464 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4465 let buffer = self.buffer.read(cx);
4466 let newest_selection = self.selections.newest_anchor().clone();
4467 if newest_selection.head().diff_base_anchor.is_some() {
4468 return None;
4469 }
4470 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4471 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4472 if start_buffer != end_buffer {
4473 return None;
4474 }
4475
4476 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4477 cx.background_executor()
4478 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4479 .await;
4480
4481 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4482 let providers = this.code_action_providers.clone();
4483 let tasks = this
4484 .code_action_providers
4485 .iter()
4486 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4487 .collect::<Vec<_>>();
4488 (providers, tasks)
4489 })?;
4490
4491 let mut actions = Vec::new();
4492 for (provider, provider_actions) in
4493 providers.into_iter().zip(future::join_all(tasks).await)
4494 {
4495 if let Some(provider_actions) = provider_actions.log_err() {
4496 actions.extend(provider_actions.into_iter().map(|action| {
4497 AvailableCodeAction {
4498 excerpt_id: newest_selection.start.excerpt_id,
4499 action,
4500 provider: provider.clone(),
4501 }
4502 }));
4503 }
4504 }
4505
4506 this.update(&mut cx, |this, cx| {
4507 this.available_code_actions = if actions.is_empty() {
4508 None
4509 } else {
4510 Some((
4511 Location {
4512 buffer: start_buffer,
4513 range: start..end,
4514 },
4515 actions.into(),
4516 ))
4517 };
4518 cx.notify();
4519 })
4520 }));
4521 None
4522 }
4523
4524 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4525 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4526 self.show_git_blame_inline = false;
4527
4528 self.show_git_blame_inline_delay_task =
4529 Some(cx.spawn_in(window, |this, mut cx| async move {
4530 cx.background_executor().timer(delay).await;
4531
4532 this.update(&mut cx, |this, cx| {
4533 this.show_git_blame_inline = true;
4534 cx.notify();
4535 })
4536 .log_err();
4537 }));
4538 }
4539 }
4540
4541 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4542 if self.pending_rename.is_some() {
4543 return None;
4544 }
4545
4546 let provider = self.semantics_provider.clone()?;
4547 let buffer = self.buffer.read(cx);
4548 let newest_selection = self.selections.newest_anchor().clone();
4549 let cursor_position = newest_selection.head();
4550 let (cursor_buffer, cursor_buffer_position) =
4551 buffer.text_anchor_for_position(cursor_position, cx)?;
4552 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4553 if cursor_buffer != tail_buffer {
4554 return None;
4555 }
4556 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4557 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4558 cx.background_executor()
4559 .timer(Duration::from_millis(debounce))
4560 .await;
4561
4562 let highlights = if let Some(highlights) = cx
4563 .update(|cx| {
4564 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4565 })
4566 .ok()
4567 .flatten()
4568 {
4569 highlights.await.log_err()
4570 } else {
4571 None
4572 };
4573
4574 if let Some(highlights) = highlights {
4575 this.update(&mut cx, |this, cx| {
4576 if this.pending_rename.is_some() {
4577 return;
4578 }
4579
4580 let buffer_id = cursor_position.buffer_id;
4581 let buffer = this.buffer.read(cx);
4582 if !buffer
4583 .text_anchor_for_position(cursor_position, cx)
4584 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4585 {
4586 return;
4587 }
4588
4589 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4590 let mut write_ranges = Vec::new();
4591 let mut read_ranges = Vec::new();
4592 for highlight in highlights {
4593 for (excerpt_id, excerpt_range) in
4594 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4595 {
4596 let start = highlight
4597 .range
4598 .start
4599 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4600 let end = highlight
4601 .range
4602 .end
4603 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4604 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4605 continue;
4606 }
4607
4608 let range = Anchor {
4609 buffer_id,
4610 excerpt_id,
4611 text_anchor: start,
4612 diff_base_anchor: None,
4613 }..Anchor {
4614 buffer_id,
4615 excerpt_id,
4616 text_anchor: end,
4617 diff_base_anchor: None,
4618 };
4619 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4620 write_ranges.push(range);
4621 } else {
4622 read_ranges.push(range);
4623 }
4624 }
4625 }
4626
4627 this.highlight_background::<DocumentHighlightRead>(
4628 &read_ranges,
4629 |theme| theme.editor_document_highlight_read_background,
4630 cx,
4631 );
4632 this.highlight_background::<DocumentHighlightWrite>(
4633 &write_ranges,
4634 |theme| theme.editor_document_highlight_write_background,
4635 cx,
4636 );
4637 cx.notify();
4638 })
4639 .log_err();
4640 }
4641 }));
4642 None
4643 }
4644
4645 pub fn refresh_inline_completion(
4646 &mut self,
4647 debounce: bool,
4648 user_requested: bool,
4649 window: &mut Window,
4650 cx: &mut Context<Self>,
4651 ) -> Option<()> {
4652 let provider = self.inline_completion_provider()?;
4653 let cursor = self.selections.newest_anchor().head();
4654 let (buffer, cursor_buffer_position) =
4655 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4656
4657 if !user_requested
4658 && (!self.enable_inline_completions
4659 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4660 || !self.is_focused(window)
4661 || buffer.read(cx).is_empty())
4662 {
4663 self.discard_inline_completion(false, cx);
4664 return None;
4665 }
4666
4667 self.update_visible_inline_completion(window, cx);
4668 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4669 Some(())
4670 }
4671
4672 fn cycle_inline_completion(
4673 &mut self,
4674 direction: Direction,
4675 window: &mut Window,
4676 cx: &mut Context<Self>,
4677 ) -> Option<()> {
4678 let provider = self.inline_completion_provider()?;
4679 let cursor = self.selections.newest_anchor().head();
4680 let (buffer, cursor_buffer_position) =
4681 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4682 if !self.enable_inline_completions
4683 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4684 {
4685 return None;
4686 }
4687
4688 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4689 self.update_visible_inline_completion(window, cx);
4690
4691 Some(())
4692 }
4693
4694 pub fn show_inline_completion(
4695 &mut self,
4696 _: &ShowInlineCompletion,
4697 window: &mut Window,
4698 cx: &mut Context<Self>,
4699 ) {
4700 if !self.has_active_inline_completion() {
4701 self.refresh_inline_completion(false, true, window, cx);
4702 return;
4703 }
4704
4705 self.update_visible_inline_completion(window, cx);
4706 }
4707
4708 pub fn display_cursor_names(
4709 &mut self,
4710 _: &DisplayCursorNames,
4711 window: &mut Window,
4712 cx: &mut Context<Self>,
4713 ) {
4714 self.show_cursor_names(window, cx);
4715 }
4716
4717 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4718 self.show_cursor_names = true;
4719 cx.notify();
4720 cx.spawn_in(window, |this, mut cx| async move {
4721 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4722 this.update(&mut cx, |this, cx| {
4723 this.show_cursor_names = false;
4724 cx.notify()
4725 })
4726 .ok()
4727 })
4728 .detach();
4729 }
4730
4731 pub fn next_inline_completion(
4732 &mut self,
4733 _: &NextInlineCompletion,
4734 window: &mut Window,
4735 cx: &mut Context<Self>,
4736 ) {
4737 if self.has_active_inline_completion() {
4738 self.cycle_inline_completion(Direction::Next, window, cx);
4739 } else {
4740 let is_copilot_disabled = self
4741 .refresh_inline_completion(false, true, window, cx)
4742 .is_none();
4743 if is_copilot_disabled {
4744 cx.propagate();
4745 }
4746 }
4747 }
4748
4749 pub fn previous_inline_completion(
4750 &mut self,
4751 _: &PreviousInlineCompletion,
4752 window: &mut Window,
4753 cx: &mut Context<Self>,
4754 ) {
4755 if self.has_active_inline_completion() {
4756 self.cycle_inline_completion(Direction::Prev, window, cx);
4757 } else {
4758 let is_copilot_disabled = self
4759 .refresh_inline_completion(false, true, window, cx)
4760 .is_none();
4761 if is_copilot_disabled {
4762 cx.propagate();
4763 }
4764 }
4765 }
4766
4767 pub fn accept_inline_completion(
4768 &mut self,
4769 _: &AcceptInlineCompletion,
4770 window: &mut Window,
4771 cx: &mut Context<Self>,
4772 ) {
4773 let buffer = self.buffer.read(cx);
4774 let snapshot = buffer.snapshot(cx);
4775 let selection = self.selections.newest_adjusted(cx);
4776 let cursor = selection.head();
4777 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
4778 let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
4779 if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
4780 {
4781 if cursor.column < suggested_indent.len
4782 && cursor.column <= current_indent.len
4783 && current_indent.len <= suggested_indent.len
4784 {
4785 self.tab(&Default::default(), window, cx);
4786 return;
4787 }
4788 }
4789
4790 if self.show_inline_completions_in_menu(cx) {
4791 self.hide_context_menu(window, cx);
4792 }
4793
4794 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4795 return;
4796 };
4797
4798 self.report_inline_completion_event(true, cx);
4799
4800 match &active_inline_completion.completion {
4801 InlineCompletion::Move { target, .. } => {
4802 let target = *target;
4803 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
4804 selections.select_anchor_ranges([target..target]);
4805 });
4806 }
4807 InlineCompletion::Edit { edits, .. } => {
4808 if let Some(provider) = self.inline_completion_provider() {
4809 provider.accept(cx);
4810 }
4811
4812 let snapshot = self.buffer.read(cx).snapshot(cx);
4813 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4814
4815 self.buffer.update(cx, |buffer, cx| {
4816 buffer.edit(edits.iter().cloned(), None, cx)
4817 });
4818
4819 self.change_selections(None, window, cx, |s| {
4820 s.select_anchor_ranges([last_edit_end..last_edit_end])
4821 });
4822
4823 self.update_visible_inline_completion(window, cx);
4824 if self.active_inline_completion.is_none() {
4825 self.refresh_inline_completion(true, true, window, cx);
4826 }
4827
4828 cx.notify();
4829 }
4830 }
4831 }
4832
4833 pub fn accept_partial_inline_completion(
4834 &mut self,
4835 _: &AcceptPartialInlineCompletion,
4836 window: &mut Window,
4837 cx: &mut Context<Self>,
4838 ) {
4839 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4840 return;
4841 };
4842 if self.selections.count() != 1 {
4843 return;
4844 }
4845
4846 self.report_inline_completion_event(true, cx);
4847
4848 match &active_inline_completion.completion {
4849 InlineCompletion::Move { target, .. } => {
4850 let target = *target;
4851 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
4852 selections.select_anchor_ranges([target..target]);
4853 });
4854 }
4855 InlineCompletion::Edit { edits, .. } => {
4856 // Find an insertion that starts at the cursor position.
4857 let snapshot = self.buffer.read(cx).snapshot(cx);
4858 let cursor_offset = self.selections.newest::<usize>(cx).head();
4859 let insertion = edits.iter().find_map(|(range, text)| {
4860 let range = range.to_offset(&snapshot);
4861 if range.is_empty() && range.start == cursor_offset {
4862 Some(text)
4863 } else {
4864 None
4865 }
4866 });
4867
4868 if let Some(text) = insertion {
4869 let mut partial_completion = text
4870 .chars()
4871 .by_ref()
4872 .take_while(|c| c.is_alphabetic())
4873 .collect::<String>();
4874 if partial_completion.is_empty() {
4875 partial_completion = text
4876 .chars()
4877 .by_ref()
4878 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4879 .collect::<String>();
4880 }
4881
4882 cx.emit(EditorEvent::InputHandled {
4883 utf16_range_to_replace: None,
4884 text: partial_completion.clone().into(),
4885 });
4886
4887 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
4888
4889 self.refresh_inline_completion(true, true, window, cx);
4890 cx.notify();
4891 } else {
4892 self.accept_inline_completion(&Default::default(), window, cx);
4893 }
4894 }
4895 }
4896 }
4897
4898 fn discard_inline_completion(
4899 &mut self,
4900 should_report_inline_completion_event: bool,
4901 cx: &mut Context<Self>,
4902 ) -> bool {
4903 if should_report_inline_completion_event {
4904 self.report_inline_completion_event(false, cx);
4905 }
4906
4907 if let Some(provider) = self.inline_completion_provider() {
4908 provider.discard(cx);
4909 }
4910
4911 self.take_active_inline_completion(cx)
4912 }
4913
4914 fn report_inline_completion_event(&self, accepted: bool, cx: &App) {
4915 let Some(provider) = self.inline_completion_provider() else {
4916 return;
4917 };
4918
4919 let Some((_, buffer, _)) = self
4920 .buffer
4921 .read(cx)
4922 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4923 else {
4924 return;
4925 };
4926
4927 let extension = buffer
4928 .read(cx)
4929 .file()
4930 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4931
4932 let event_type = match accepted {
4933 true => "Edit Prediction Accepted",
4934 false => "Edit Prediction Discarded",
4935 };
4936 telemetry::event!(
4937 event_type,
4938 provider = provider.name(),
4939 suggestion_accepted = accepted,
4940 file_extension = extension,
4941 );
4942 }
4943
4944 pub fn has_active_inline_completion(&self) -> bool {
4945 self.active_inline_completion.is_some()
4946 }
4947
4948 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
4949 let Some(active_inline_completion) = self.active_inline_completion.take() else {
4950 return false;
4951 };
4952
4953 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
4954 self.clear_highlights::<InlineCompletionHighlight>(cx);
4955 self.stale_inline_completion_in_menu = Some(active_inline_completion);
4956 true
4957 }
4958
4959 pub fn is_previewing_inline_completion(&self) -> bool {
4960 matches!(
4961 self.context_menu.borrow().as_ref(),
4962 Some(CodeContextMenu::Completions(menu)) if !menu.is_empty() && menu.previewing_inline_completion
4963 )
4964 }
4965
4966 fn update_inline_completion_preview(
4967 &mut self,
4968 modifiers: &Modifiers,
4969 window: &mut Window,
4970 cx: &mut Context<Self>,
4971 ) {
4972 // Moves jump directly with a preview step
4973
4974 if self
4975 .active_inline_completion
4976 .as_ref()
4977 .map_or(true, |c| c.is_move())
4978 {
4979 cx.notify();
4980 return;
4981 }
4982
4983 if !self.show_inline_completions_in_menu(cx) {
4984 return;
4985 }
4986
4987 let mut menu_borrow = self.context_menu.borrow_mut();
4988
4989 let Some(CodeContextMenu::Completions(completions_menu)) = menu_borrow.as_mut() else {
4990 return;
4991 };
4992
4993 if completions_menu.is_empty()
4994 || completions_menu.previewing_inline_completion == modifiers.alt
4995 {
4996 return;
4997 }
4998
4999 completions_menu.set_previewing_inline_completion(modifiers.alt);
5000 drop(menu_borrow);
5001 self.update_visible_inline_completion(window, cx);
5002 }
5003
5004 fn update_visible_inline_completion(
5005 &mut self,
5006 _window: &mut Window,
5007 cx: &mut Context<Self>,
5008 ) -> Option<()> {
5009 let selection = self.selections.newest_anchor();
5010 let cursor = selection.head();
5011 let multibuffer = self.buffer.read(cx).snapshot(cx);
5012 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5013 let excerpt_id = cursor.excerpt_id;
5014
5015 let show_in_menu = self.show_inline_completions_in_menu(cx);
5016 let completions_menu_has_precedence = !show_in_menu
5017 && (self.context_menu.borrow().is_some()
5018 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5019 if completions_menu_has_precedence
5020 || !offset_selection.is_empty()
5021 || !self.enable_inline_completions
5022 || self
5023 .active_inline_completion
5024 .as_ref()
5025 .map_or(false, |completion| {
5026 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5027 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5028 !invalidation_range.contains(&offset_selection.head())
5029 })
5030 {
5031 self.discard_inline_completion(false, cx);
5032 return None;
5033 }
5034
5035 self.take_active_inline_completion(cx);
5036 let provider = self.inline_completion_provider()?;
5037
5038 let (buffer, cursor_buffer_position) =
5039 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5040
5041 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5042 let edits = inline_completion
5043 .edits
5044 .into_iter()
5045 .flat_map(|(range, new_text)| {
5046 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5047 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5048 Some((start..end, new_text))
5049 })
5050 .collect::<Vec<_>>();
5051 if edits.is_empty() {
5052 return None;
5053 }
5054
5055 let first_edit_start = edits.first().unwrap().0.start;
5056 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5057 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5058
5059 let last_edit_end = edits.last().unwrap().0.end;
5060 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5061 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5062
5063 let cursor_row = cursor.to_point(&multibuffer).row;
5064
5065 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5066
5067 let mut inlay_ids = Vec::new();
5068 let invalidation_row_range;
5069 let move_invalidation_row_range = if cursor_row < edit_start_row {
5070 Some(cursor_row..edit_end_row)
5071 } else if cursor_row > edit_end_row {
5072 Some(edit_start_row..cursor_row)
5073 } else {
5074 None
5075 };
5076 let completion = if let Some(move_invalidation_row_range) = move_invalidation_row_range {
5077 invalidation_row_range = move_invalidation_row_range;
5078 let target = first_edit_start;
5079 let target_point = text::ToPoint::to_point(&target.text_anchor, &snapshot);
5080 // TODO: Base this off of TreeSitter or word boundaries?
5081 let target_excerpt_begin = snapshot.anchor_before(snapshot.clip_point(
5082 Point::new(target_point.row, target_point.column.saturating_sub(20)),
5083 Bias::Left,
5084 ));
5085 let target_excerpt_end = snapshot.anchor_after(snapshot.clip_point(
5086 Point::new(target_point.row, target_point.column + 20),
5087 Bias::Right,
5088 ));
5089 let range_around_target = target_excerpt_begin..target_excerpt_end;
5090 InlineCompletion::Move {
5091 target,
5092 range_around_target,
5093 snapshot,
5094 }
5095 } else {
5096 if !show_in_menu || !self.has_active_completions_menu() {
5097 if edits
5098 .iter()
5099 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5100 {
5101 let mut inlays = Vec::new();
5102 for (range, new_text) in &edits {
5103 let inlay = Inlay::inline_completion(
5104 post_inc(&mut self.next_inlay_id),
5105 range.start,
5106 new_text.as_str(),
5107 );
5108 inlay_ids.push(inlay.id);
5109 inlays.push(inlay);
5110 }
5111
5112 self.splice_inlays(&[], inlays, cx);
5113 } else {
5114 let background_color = cx.theme().status().deleted_background;
5115 self.highlight_text::<InlineCompletionHighlight>(
5116 edits.iter().map(|(range, _)| range.clone()).collect(),
5117 HighlightStyle {
5118 background_color: Some(background_color),
5119 ..Default::default()
5120 },
5121 cx,
5122 );
5123 }
5124 }
5125
5126 invalidation_row_range = edit_start_row..edit_end_row;
5127
5128 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5129 if provider.show_tab_accept_marker() {
5130 EditDisplayMode::TabAccept(self.is_previewing_inline_completion())
5131 } else {
5132 EditDisplayMode::Inline
5133 }
5134 } else {
5135 EditDisplayMode::DiffPopover
5136 };
5137
5138 InlineCompletion::Edit {
5139 edits,
5140 edit_preview: inline_completion.edit_preview,
5141 display_mode,
5142 snapshot,
5143 }
5144 };
5145
5146 let invalidation_range = multibuffer
5147 .anchor_before(Point::new(invalidation_row_range.start, 0))
5148 ..multibuffer.anchor_after(Point::new(
5149 invalidation_row_range.end,
5150 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5151 ));
5152
5153 self.stale_inline_completion_in_menu = None;
5154 self.active_inline_completion = Some(InlineCompletionState {
5155 inlay_ids,
5156 completion,
5157 invalidation_range,
5158 });
5159
5160 cx.notify();
5161
5162 Some(())
5163 }
5164
5165 pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5166 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5167 }
5168
5169 fn show_inline_completions_in_menu(&self, cx: &App) -> bool {
5170 let by_provider = matches!(
5171 self.menu_inline_completions_policy,
5172 MenuInlineCompletionsPolicy::ByProvider
5173 );
5174
5175 by_provider
5176 && EditorSettings::get_global(cx).show_inline_completions_in_menu
5177 && self
5178 .inline_completion_provider()
5179 .map_or(false, |provider| provider.show_completions_in_menu())
5180 }
5181
5182 fn render_code_actions_indicator(
5183 &self,
5184 _style: &EditorStyle,
5185 row: DisplayRow,
5186 is_active: bool,
5187 cx: &mut Context<Self>,
5188 ) -> Option<IconButton> {
5189 if self.available_code_actions.is_some() {
5190 Some(
5191 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5192 .shape(ui::IconButtonShape::Square)
5193 .icon_size(IconSize::XSmall)
5194 .icon_color(Color::Muted)
5195 .toggle_state(is_active)
5196 .tooltip({
5197 let focus_handle = self.focus_handle.clone();
5198 move |window, cx| {
5199 Tooltip::for_action_in(
5200 "Toggle Code Actions",
5201 &ToggleCodeActions {
5202 deployed_from_indicator: None,
5203 },
5204 &focus_handle,
5205 window,
5206 cx,
5207 )
5208 }
5209 })
5210 .on_click(cx.listener(move |editor, _e, window, cx| {
5211 window.focus(&editor.focus_handle(cx));
5212 editor.toggle_code_actions(
5213 &ToggleCodeActions {
5214 deployed_from_indicator: Some(row),
5215 },
5216 window,
5217 cx,
5218 );
5219 })),
5220 )
5221 } else {
5222 None
5223 }
5224 }
5225
5226 fn clear_tasks(&mut self) {
5227 self.tasks.clear()
5228 }
5229
5230 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5231 if self.tasks.insert(key, value).is_some() {
5232 // This case should hopefully be rare, but just in case...
5233 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5234 }
5235 }
5236
5237 fn build_tasks_context(
5238 project: &Entity<Project>,
5239 buffer: &Entity<Buffer>,
5240 buffer_row: u32,
5241 tasks: &Arc<RunnableTasks>,
5242 cx: &mut Context<Self>,
5243 ) -> Task<Option<task::TaskContext>> {
5244 let position = Point::new(buffer_row, tasks.column);
5245 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5246 let location = Location {
5247 buffer: buffer.clone(),
5248 range: range_start..range_start,
5249 };
5250 // Fill in the environmental variables from the tree-sitter captures
5251 let mut captured_task_variables = TaskVariables::default();
5252 for (capture_name, value) in tasks.extra_variables.clone() {
5253 captured_task_variables.insert(
5254 task::VariableName::Custom(capture_name.into()),
5255 value.clone(),
5256 );
5257 }
5258 project.update(cx, |project, cx| {
5259 project.task_store().update(cx, |task_store, cx| {
5260 task_store.task_context_for_location(captured_task_variables, location, cx)
5261 })
5262 })
5263 }
5264
5265 pub fn spawn_nearest_task(
5266 &mut self,
5267 action: &SpawnNearestTask,
5268 window: &mut Window,
5269 cx: &mut Context<Self>,
5270 ) {
5271 let Some((workspace, _)) = self.workspace.clone() else {
5272 return;
5273 };
5274 let Some(project) = self.project.clone() else {
5275 return;
5276 };
5277
5278 // Try to find a closest, enclosing node using tree-sitter that has a
5279 // task
5280 let Some((buffer, buffer_row, tasks)) = self
5281 .find_enclosing_node_task(cx)
5282 // Or find the task that's closest in row-distance.
5283 .or_else(|| self.find_closest_task(cx))
5284 else {
5285 return;
5286 };
5287
5288 let reveal_strategy = action.reveal;
5289 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5290 cx.spawn_in(window, |_, mut cx| async move {
5291 let context = task_context.await?;
5292 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5293
5294 let resolved = resolved_task.resolved.as_mut()?;
5295 resolved.reveal = reveal_strategy;
5296
5297 workspace
5298 .update(&mut cx, |workspace, cx| {
5299 workspace::tasks::schedule_resolved_task(
5300 workspace,
5301 task_source_kind,
5302 resolved_task,
5303 false,
5304 cx,
5305 );
5306 })
5307 .ok()
5308 })
5309 .detach();
5310 }
5311
5312 fn find_closest_task(
5313 &mut self,
5314 cx: &mut Context<Self>,
5315 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5316 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5317
5318 let ((buffer_id, row), tasks) = self
5319 .tasks
5320 .iter()
5321 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5322
5323 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5324 let tasks = Arc::new(tasks.to_owned());
5325 Some((buffer, *row, tasks))
5326 }
5327
5328 fn find_enclosing_node_task(
5329 &mut self,
5330 cx: &mut Context<Self>,
5331 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5332 let snapshot = self.buffer.read(cx).snapshot(cx);
5333 let offset = self.selections.newest::<usize>(cx).head();
5334 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5335 let buffer_id = excerpt.buffer().remote_id();
5336
5337 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5338 let mut cursor = layer.node().walk();
5339
5340 while cursor.goto_first_child_for_byte(offset).is_some() {
5341 if cursor.node().end_byte() == offset {
5342 cursor.goto_next_sibling();
5343 }
5344 }
5345
5346 // Ascend to the smallest ancestor that contains the range and has a task.
5347 loop {
5348 let node = cursor.node();
5349 let node_range = node.byte_range();
5350 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5351
5352 // Check if this node contains our offset
5353 if node_range.start <= offset && node_range.end >= offset {
5354 // If it contains offset, check for task
5355 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5356 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5357 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5358 }
5359 }
5360
5361 if !cursor.goto_parent() {
5362 break;
5363 }
5364 }
5365 None
5366 }
5367
5368 fn render_run_indicator(
5369 &self,
5370 _style: &EditorStyle,
5371 is_active: bool,
5372 row: DisplayRow,
5373 cx: &mut Context<Self>,
5374 ) -> IconButton {
5375 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5376 .shape(ui::IconButtonShape::Square)
5377 .icon_size(IconSize::XSmall)
5378 .icon_color(Color::Muted)
5379 .toggle_state(is_active)
5380 .on_click(cx.listener(move |editor, _e, window, cx| {
5381 window.focus(&editor.focus_handle(cx));
5382 editor.toggle_code_actions(
5383 &ToggleCodeActions {
5384 deployed_from_indicator: Some(row),
5385 },
5386 window,
5387 cx,
5388 );
5389 }))
5390 }
5391
5392 pub fn context_menu_visible(&self) -> bool {
5393 self.context_menu
5394 .borrow()
5395 .as_ref()
5396 .map_or(false, |menu| menu.visible())
5397 }
5398
5399 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5400 self.context_menu
5401 .borrow()
5402 .as_ref()
5403 .map(|menu| menu.origin())
5404 }
5405
5406 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5407 px(32.)
5408 }
5409
5410 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5411 if self.read_only(cx) {
5412 cx.theme().players().read_only()
5413 } else {
5414 self.style.as_ref().unwrap().local_player
5415 }
5416 }
5417
5418 #[allow(clippy::too_many_arguments)]
5419 fn render_edit_prediction_cursor_popover(
5420 &self,
5421 min_width: Pixels,
5422 max_width: Pixels,
5423 cursor_point: Point,
5424 line_layouts: &[LineWithInvisibles],
5425 style: &EditorStyle,
5426 accept_keystroke: &gpui::Keystroke,
5427 window: &Window,
5428 cx: &mut Context<Editor>,
5429 ) -> Option<AnyElement> {
5430 let provider = self.inline_completion_provider.as_ref()?;
5431
5432 if provider.provider.needs_terms_acceptance(cx) {
5433 return Some(
5434 h_flex()
5435 .h(self.edit_prediction_cursor_popover_height())
5436 .min_w(min_width)
5437 .flex_1()
5438 .px_2()
5439 .gap_3()
5440 .elevation_2(cx)
5441 .hover(|style| style.bg(cx.theme().colors().element_hover))
5442 .id("accept-terms")
5443 .cursor_pointer()
5444 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5445 .on_click(cx.listener(|this, _event, window, cx| {
5446 cx.stop_propagation();
5447 this.toggle_zed_predict_onboarding(window, cx)
5448 }))
5449 .child(
5450 h_flex()
5451 .w_full()
5452 .gap_2()
5453 .child(Icon::new(IconName::ZedPredict))
5454 .child(Label::new("Accept Terms of Service"))
5455 .child(div().w_full())
5456 .child(Icon::new(IconName::ArrowUpRight))
5457 .into_any_element(),
5458 )
5459 .into_any(),
5460 );
5461 }
5462
5463 let is_refreshing = provider.provider.is_refreshing(cx);
5464
5465 fn pending_completion_container() -> Div {
5466 h_flex()
5467 .flex_1()
5468 .gap_3()
5469 .child(Icon::new(IconName::ZedPredict))
5470 }
5471
5472 let completion = match &self.active_inline_completion {
5473 Some(completion) => self.render_edit_prediction_cursor_popover_preview(
5474 completion,
5475 cursor_point,
5476 line_layouts,
5477 style,
5478 cx,
5479 )?,
5480
5481 None if is_refreshing => match &self.stale_inline_completion_in_menu {
5482 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
5483 stale_completion,
5484 cursor_point,
5485 line_layouts,
5486 style,
5487 cx,
5488 )?,
5489
5490 None => {
5491 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
5492 }
5493 },
5494
5495 None => pending_completion_container().child(Label::new("No Prediction")),
5496 };
5497
5498 let buffer_font = theme::ThemeSettings::get_global(cx).buffer_font.clone();
5499 let completion = completion.font(buffer_font.clone());
5500
5501 let completion = if is_refreshing {
5502 completion
5503 .with_animation(
5504 "loading-completion",
5505 Animation::new(Duration::from_secs(2))
5506 .repeat()
5507 .with_easing(pulsating_between(0.4, 0.8)),
5508 |label, delta| label.opacity(delta),
5509 )
5510 .into_any_element()
5511 } else {
5512 completion.into_any_element()
5513 };
5514
5515 let has_completion = self.active_inline_completion.is_some();
5516
5517 let is_move = self
5518 .active_inline_completion
5519 .as_ref()
5520 .map_or(false, |c| c.is_move());
5521
5522 Some(
5523 h_flex()
5524 .h(self.edit_prediction_cursor_popover_height())
5525 .min_w(min_width)
5526 .max_w(max_width)
5527 .flex_1()
5528 .px_2()
5529 .gap_3()
5530 .elevation_2(cx)
5531 .child(completion)
5532 .child(
5533 h_flex()
5534 .border_l_1()
5535 .border_color(cx.theme().colors().border_variant)
5536 .pl_2()
5537 .child(
5538 h_flex()
5539 .font(buffer_font.clone())
5540 .p_1()
5541 .rounded_sm()
5542 .children(ui::render_modifiers(
5543 &accept_keystroke.modifiers,
5544 PlatformStyle::platform(),
5545 if window.modifiers() == accept_keystroke.modifiers {
5546 Some(Color::Accent)
5547 } else {
5548 None
5549 },
5550 !is_move,
5551 )),
5552 )
5553 .opacity(if has_completion { 1.0 } else { 0.1 })
5554 .child(if is_move {
5555 div()
5556 .child(ui::Key::new(&accept_keystroke.key, None))
5557 .font(buffer_font.clone())
5558 .into_any()
5559 } else {
5560 Label::new("Preview").color(Color::Muted).into_any_element()
5561 }),
5562 )
5563 .into_any(),
5564 )
5565 }
5566
5567 fn render_edit_prediction_cursor_popover_preview(
5568 &self,
5569 completion: &InlineCompletionState,
5570 cursor_point: Point,
5571 line_layouts: &[LineWithInvisibles],
5572 style: &EditorStyle,
5573 cx: &mut Context<Editor>,
5574 ) -> Option<Div> {
5575 use text::ToPoint as _;
5576
5577 fn render_relative_row_jump(
5578 prefix: impl Into<String>,
5579 current_row: u32,
5580 target_row: u32,
5581 ) -> Div {
5582 let (row_diff, arrow) = if target_row < current_row {
5583 (current_row - target_row, IconName::ArrowUp)
5584 } else {
5585 (target_row - current_row, IconName::ArrowDown)
5586 };
5587
5588 h_flex()
5589 .child(
5590 Label::new(format!("{}{}", prefix.into(), row_diff))
5591 .color(Color::Muted)
5592 .size(LabelSize::Small),
5593 )
5594 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
5595 }
5596
5597 match &completion.completion {
5598 InlineCompletion::Edit {
5599 edits,
5600 edit_preview,
5601 snapshot,
5602 display_mode: _,
5603 } => {
5604 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
5605
5606 let highlighted_edits = crate::inline_completion_edit_text(
5607 &snapshot,
5608 &edits,
5609 edit_preview.as_ref()?,
5610 true,
5611 cx,
5612 );
5613
5614 let len_total = highlighted_edits.text.len();
5615 let first_line = &highlighted_edits.text
5616 [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
5617 let first_line_len = first_line.len();
5618
5619 let first_highlight_start = highlighted_edits
5620 .highlights
5621 .first()
5622 .map_or(0, |(range, _)| range.start);
5623 let drop_prefix_len = first_line
5624 .char_indices()
5625 .find(|(_, c)| !c.is_whitespace())
5626 .map_or(first_highlight_start, |(ix, _)| {
5627 ix.min(first_highlight_start)
5628 });
5629
5630 let preview_text = &first_line[drop_prefix_len..];
5631 let preview_len = preview_text.len();
5632 let highlights = highlighted_edits
5633 .highlights
5634 .into_iter()
5635 .take_until(|(range, _)| range.start > first_line_len)
5636 .map(|(range, style)| {
5637 (
5638 range.start - drop_prefix_len
5639 ..(range.end - drop_prefix_len).min(preview_len),
5640 style,
5641 )
5642 });
5643
5644 let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
5645 .with_highlights(&style.text, highlights);
5646
5647 let preview = h_flex()
5648 .gap_1()
5649 .child(styled_text)
5650 .when(len_total > first_line_len, |parent| parent.child("…"));
5651
5652 let left = if first_edit_row != cursor_point.row {
5653 render_relative_row_jump("", cursor_point.row, first_edit_row)
5654 .into_any_element()
5655 } else {
5656 Icon::new(IconName::ZedPredict).into_any_element()
5657 };
5658
5659 Some(h_flex().flex_1().gap_3().child(left).child(preview))
5660 }
5661
5662 InlineCompletion::Move {
5663 target,
5664 range_around_target,
5665 snapshot,
5666 } => {
5667 let highlighted_text = snapshot.highlighted_text_for_range(
5668 range_around_target.clone(),
5669 None,
5670 &style.syntax,
5671 );
5672 let cursor_color = self.current_user_player_color(cx).cursor;
5673
5674 let start_point = range_around_target.start.to_point(&snapshot);
5675 let end_point = range_around_target.end.to_point(&snapshot);
5676 let target_point = target.text_anchor.to_point(&snapshot);
5677
5678 let cursor_relative_position =
5679 line_layouts.get(start_point.row as usize).map(|line| {
5680 let start_column_x = line.x_for_index(start_point.column as usize);
5681 let target_column_x = line.x_for_index(target_point.column as usize);
5682 target_column_x - start_column_x
5683 });
5684
5685 let fade_before = start_point.column > 0;
5686 let fade_after = end_point.column < snapshot.line_len(end_point.row);
5687
5688 let background = cx.theme().colors().elevated_surface_background;
5689
5690 Some(
5691 h_flex()
5692 .gap_3()
5693 .flex_1()
5694 .child(render_relative_row_jump(
5695 "Jump ",
5696 cursor_point.row,
5697 target.text_anchor.to_point(&snapshot).row,
5698 ))
5699 .when(!highlighted_text.text.is_empty(), |parent| {
5700 parent.child(
5701 h_flex()
5702 .relative()
5703 .child(highlighted_text.to_styled_text(&style.text))
5704 .when(fade_before, |parent| {
5705 parent.child(
5706 div().absolute().top_0().left_0().w_4().h_full().bg(
5707 linear_gradient(
5708 90.,
5709 linear_color_stop(background, 0.),
5710 linear_color_stop(background.opacity(0.), 1.),
5711 ),
5712 ),
5713 )
5714 })
5715 .when(fade_after, |parent| {
5716 parent.child(
5717 div().absolute().top_0().right_0().w_4().h_full().bg(
5718 linear_gradient(
5719 -90.,
5720 linear_color_stop(background, 0.),
5721 linear_color_stop(background.opacity(0.), 1.),
5722 ),
5723 ),
5724 )
5725 })
5726 .when_some(cursor_relative_position, |parent, position| {
5727 parent.child(
5728 div()
5729 .w(px(2.))
5730 .h_full()
5731 .bg(cursor_color)
5732 .absolute()
5733 .top_0()
5734 .left(position),
5735 )
5736 }),
5737 )
5738 }),
5739 )
5740 }
5741 }
5742 }
5743
5744 fn render_context_menu(
5745 &self,
5746 style: &EditorStyle,
5747 max_height_in_lines: u32,
5748 y_flipped: bool,
5749 window: &mut Window,
5750 cx: &mut Context<Editor>,
5751 ) -> Option<AnyElement> {
5752 let menu = self.context_menu.borrow();
5753 let menu = menu.as_ref()?;
5754 if !menu.visible() {
5755 return None;
5756 };
5757 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
5758 }
5759
5760 fn render_context_menu_aside(
5761 &self,
5762 style: &EditorStyle,
5763 max_size: Size<Pixels>,
5764 cx: &mut Context<Editor>,
5765 ) -> Option<AnyElement> {
5766 self.context_menu.borrow().as_ref().and_then(|menu| {
5767 if menu.visible() {
5768 menu.render_aside(
5769 style,
5770 max_size,
5771 self.workspace.as_ref().map(|(w, _)| w.clone()),
5772 cx,
5773 )
5774 } else {
5775 None
5776 }
5777 })
5778 }
5779
5780 fn hide_context_menu(
5781 &mut self,
5782 window: &mut Window,
5783 cx: &mut Context<Self>,
5784 ) -> Option<CodeContextMenu> {
5785 cx.notify();
5786 self.completion_tasks.clear();
5787 let context_menu = self.context_menu.borrow_mut().take();
5788 self.stale_inline_completion_in_menu.take();
5789 if context_menu.is_some() {
5790 self.update_visible_inline_completion(window, cx);
5791 }
5792 context_menu
5793 }
5794
5795 fn show_snippet_choices(
5796 &mut self,
5797 choices: &Vec<String>,
5798 selection: Range<Anchor>,
5799 cx: &mut Context<Self>,
5800 ) {
5801 if selection.start.buffer_id.is_none() {
5802 return;
5803 }
5804 let buffer_id = selection.start.buffer_id.unwrap();
5805 let buffer = self.buffer().read(cx).buffer(buffer_id);
5806 let id = post_inc(&mut self.next_completion_id);
5807
5808 if let Some(buffer) = buffer {
5809 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5810 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5811 ));
5812 }
5813 }
5814
5815 pub fn insert_snippet(
5816 &mut self,
5817 insertion_ranges: &[Range<usize>],
5818 snippet: Snippet,
5819 window: &mut Window,
5820 cx: &mut Context<Self>,
5821 ) -> Result<()> {
5822 struct Tabstop<T> {
5823 is_end_tabstop: bool,
5824 ranges: Vec<Range<T>>,
5825 choices: Option<Vec<String>>,
5826 }
5827
5828 let tabstops = self.buffer.update(cx, |buffer, cx| {
5829 let snippet_text: Arc<str> = snippet.text.clone().into();
5830 buffer.edit(
5831 insertion_ranges
5832 .iter()
5833 .cloned()
5834 .map(|range| (range, snippet_text.clone())),
5835 Some(AutoindentMode::EachLine),
5836 cx,
5837 );
5838
5839 let snapshot = &*buffer.read(cx);
5840 let snippet = &snippet;
5841 snippet
5842 .tabstops
5843 .iter()
5844 .map(|tabstop| {
5845 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5846 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5847 });
5848 let mut tabstop_ranges = tabstop
5849 .ranges
5850 .iter()
5851 .flat_map(|tabstop_range| {
5852 let mut delta = 0_isize;
5853 insertion_ranges.iter().map(move |insertion_range| {
5854 let insertion_start = insertion_range.start as isize + delta;
5855 delta +=
5856 snippet.text.len() as isize - insertion_range.len() as isize;
5857
5858 let start = ((insertion_start + tabstop_range.start) as usize)
5859 .min(snapshot.len());
5860 let end = ((insertion_start + tabstop_range.end) as usize)
5861 .min(snapshot.len());
5862 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5863 })
5864 })
5865 .collect::<Vec<_>>();
5866 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5867
5868 Tabstop {
5869 is_end_tabstop,
5870 ranges: tabstop_ranges,
5871 choices: tabstop.choices.clone(),
5872 }
5873 })
5874 .collect::<Vec<_>>()
5875 });
5876 if let Some(tabstop) = tabstops.first() {
5877 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
5878 s.select_ranges(tabstop.ranges.iter().cloned());
5879 });
5880
5881 if let Some(choices) = &tabstop.choices {
5882 if let Some(selection) = tabstop.ranges.first() {
5883 self.show_snippet_choices(choices, selection.clone(), cx)
5884 }
5885 }
5886
5887 // If we're already at the last tabstop and it's at the end of the snippet,
5888 // we're done, we don't need to keep the state around.
5889 if !tabstop.is_end_tabstop {
5890 let choices = tabstops
5891 .iter()
5892 .map(|tabstop| tabstop.choices.clone())
5893 .collect();
5894
5895 let ranges = tabstops
5896 .into_iter()
5897 .map(|tabstop| tabstop.ranges)
5898 .collect::<Vec<_>>();
5899
5900 self.snippet_stack.push(SnippetState {
5901 active_index: 0,
5902 ranges,
5903 choices,
5904 });
5905 }
5906
5907 // Check whether the just-entered snippet ends with an auto-closable bracket.
5908 if self.autoclose_regions.is_empty() {
5909 let snapshot = self.buffer.read(cx).snapshot(cx);
5910 for selection in &mut self.selections.all::<Point>(cx) {
5911 let selection_head = selection.head();
5912 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5913 continue;
5914 };
5915
5916 let mut bracket_pair = None;
5917 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5918 let prev_chars = snapshot
5919 .reversed_chars_at(selection_head)
5920 .collect::<String>();
5921 for (pair, enabled) in scope.brackets() {
5922 if enabled
5923 && pair.close
5924 && prev_chars.starts_with(pair.start.as_str())
5925 && next_chars.starts_with(pair.end.as_str())
5926 {
5927 bracket_pair = Some(pair.clone());
5928 break;
5929 }
5930 }
5931 if let Some(pair) = bracket_pair {
5932 let start = snapshot.anchor_after(selection_head);
5933 let end = snapshot.anchor_after(selection_head);
5934 self.autoclose_regions.push(AutocloseRegion {
5935 selection_id: selection.id,
5936 range: start..end,
5937 pair,
5938 });
5939 }
5940 }
5941 }
5942 }
5943 Ok(())
5944 }
5945
5946 pub fn move_to_next_snippet_tabstop(
5947 &mut self,
5948 window: &mut Window,
5949 cx: &mut Context<Self>,
5950 ) -> bool {
5951 self.move_to_snippet_tabstop(Bias::Right, window, cx)
5952 }
5953
5954 pub fn move_to_prev_snippet_tabstop(
5955 &mut self,
5956 window: &mut Window,
5957 cx: &mut Context<Self>,
5958 ) -> bool {
5959 self.move_to_snippet_tabstop(Bias::Left, window, cx)
5960 }
5961
5962 pub fn move_to_snippet_tabstop(
5963 &mut self,
5964 bias: Bias,
5965 window: &mut Window,
5966 cx: &mut Context<Self>,
5967 ) -> bool {
5968 if let Some(mut snippet) = self.snippet_stack.pop() {
5969 match bias {
5970 Bias::Left => {
5971 if snippet.active_index > 0 {
5972 snippet.active_index -= 1;
5973 } else {
5974 self.snippet_stack.push(snippet);
5975 return false;
5976 }
5977 }
5978 Bias::Right => {
5979 if snippet.active_index + 1 < snippet.ranges.len() {
5980 snippet.active_index += 1;
5981 } else {
5982 self.snippet_stack.push(snippet);
5983 return false;
5984 }
5985 }
5986 }
5987 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5988 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
5989 s.select_anchor_ranges(current_ranges.iter().cloned())
5990 });
5991
5992 if let Some(choices) = &snippet.choices[snippet.active_index] {
5993 if let Some(selection) = current_ranges.first() {
5994 self.show_snippet_choices(&choices, selection.clone(), cx);
5995 }
5996 }
5997
5998 // If snippet state is not at the last tabstop, push it back on the stack
5999 if snippet.active_index + 1 < snippet.ranges.len() {
6000 self.snippet_stack.push(snippet);
6001 }
6002 return true;
6003 }
6004 }
6005
6006 false
6007 }
6008
6009 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6010 self.transact(window, cx, |this, window, cx| {
6011 this.select_all(&SelectAll, window, cx);
6012 this.insert("", window, cx);
6013 });
6014 }
6015
6016 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6017 self.transact(window, cx, |this, window, cx| {
6018 this.select_autoclose_pair(window, cx);
6019 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6020 if !this.linked_edit_ranges.is_empty() {
6021 let selections = this.selections.all::<MultiBufferPoint>(cx);
6022 let snapshot = this.buffer.read(cx).snapshot(cx);
6023
6024 for selection in selections.iter() {
6025 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6026 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6027 if selection_start.buffer_id != selection_end.buffer_id {
6028 continue;
6029 }
6030 if let Some(ranges) =
6031 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6032 {
6033 for (buffer, entries) in ranges {
6034 linked_ranges.entry(buffer).or_default().extend(entries);
6035 }
6036 }
6037 }
6038 }
6039
6040 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6041 if !this.selections.line_mode {
6042 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6043 for selection in &mut selections {
6044 if selection.is_empty() {
6045 let old_head = selection.head();
6046 let mut new_head =
6047 movement::left(&display_map, old_head.to_display_point(&display_map))
6048 .to_point(&display_map);
6049 if let Some((buffer, line_buffer_range)) = display_map
6050 .buffer_snapshot
6051 .buffer_line_for_row(MultiBufferRow(old_head.row))
6052 {
6053 let indent_size =
6054 buffer.indent_size_for_line(line_buffer_range.start.row);
6055 let indent_len = match indent_size.kind {
6056 IndentKind::Space => {
6057 buffer.settings_at(line_buffer_range.start, cx).tab_size
6058 }
6059 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6060 };
6061 if old_head.column <= indent_size.len && old_head.column > 0 {
6062 let indent_len = indent_len.get();
6063 new_head = cmp::min(
6064 new_head,
6065 MultiBufferPoint::new(
6066 old_head.row,
6067 ((old_head.column - 1) / indent_len) * indent_len,
6068 ),
6069 );
6070 }
6071 }
6072
6073 selection.set_head(new_head, SelectionGoal::None);
6074 }
6075 }
6076 }
6077
6078 this.signature_help_state.set_backspace_pressed(true);
6079 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6080 s.select(selections)
6081 });
6082 this.insert("", window, cx);
6083 let empty_str: Arc<str> = Arc::from("");
6084 for (buffer, edits) in linked_ranges {
6085 let snapshot = buffer.read(cx).snapshot();
6086 use text::ToPoint as TP;
6087
6088 let edits = edits
6089 .into_iter()
6090 .map(|range| {
6091 let end_point = TP::to_point(&range.end, &snapshot);
6092 let mut start_point = TP::to_point(&range.start, &snapshot);
6093
6094 if end_point == start_point {
6095 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6096 .saturating_sub(1);
6097 start_point =
6098 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6099 };
6100
6101 (start_point..end_point, empty_str.clone())
6102 })
6103 .sorted_by_key(|(range, _)| range.start)
6104 .collect::<Vec<_>>();
6105 buffer.update(cx, |this, cx| {
6106 this.edit(edits, None, cx);
6107 })
6108 }
6109 this.refresh_inline_completion(true, false, window, cx);
6110 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6111 });
6112 }
6113
6114 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6115 self.transact(window, cx, |this, window, cx| {
6116 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6117 let line_mode = s.line_mode;
6118 s.move_with(|map, selection| {
6119 if selection.is_empty() && !line_mode {
6120 let cursor = movement::right(map, selection.head());
6121 selection.end = cursor;
6122 selection.reversed = true;
6123 selection.goal = SelectionGoal::None;
6124 }
6125 })
6126 });
6127 this.insert("", window, cx);
6128 this.refresh_inline_completion(true, false, window, cx);
6129 });
6130 }
6131
6132 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6133 if self.move_to_prev_snippet_tabstop(window, cx) {
6134 return;
6135 }
6136
6137 self.outdent(&Outdent, window, cx);
6138 }
6139
6140 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6141 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6142 return;
6143 }
6144
6145 let mut selections = self.selections.all_adjusted(cx);
6146 let buffer = self.buffer.read(cx);
6147 let snapshot = buffer.snapshot(cx);
6148 let rows_iter = selections.iter().map(|s| s.head().row);
6149 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6150
6151 let mut edits = Vec::new();
6152 let mut prev_edited_row = 0;
6153 let mut row_delta = 0;
6154 for selection in &mut selections {
6155 if selection.start.row != prev_edited_row {
6156 row_delta = 0;
6157 }
6158 prev_edited_row = selection.end.row;
6159
6160 // If the selection is non-empty, then increase the indentation of the selected lines.
6161 if !selection.is_empty() {
6162 row_delta =
6163 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6164 continue;
6165 }
6166
6167 // If the selection is empty and the cursor is in the leading whitespace before the
6168 // suggested indentation, then auto-indent the line.
6169 let cursor = selection.head();
6170 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6171 if let Some(suggested_indent) =
6172 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6173 {
6174 if cursor.column < suggested_indent.len
6175 && cursor.column <= current_indent.len
6176 && current_indent.len <= suggested_indent.len
6177 {
6178 selection.start = Point::new(cursor.row, suggested_indent.len);
6179 selection.end = selection.start;
6180 if row_delta == 0 {
6181 edits.extend(Buffer::edit_for_indent_size_adjustment(
6182 cursor.row,
6183 current_indent,
6184 suggested_indent,
6185 ));
6186 row_delta = suggested_indent.len - current_indent.len;
6187 }
6188 continue;
6189 }
6190 }
6191
6192 // Otherwise, insert a hard or soft tab.
6193 let settings = buffer.settings_at(cursor, cx);
6194 let tab_size = if settings.hard_tabs {
6195 IndentSize::tab()
6196 } else {
6197 let tab_size = settings.tab_size.get();
6198 let char_column = snapshot
6199 .text_for_range(Point::new(cursor.row, 0)..cursor)
6200 .flat_map(str::chars)
6201 .count()
6202 + row_delta as usize;
6203 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6204 IndentSize::spaces(chars_to_next_tab_stop)
6205 };
6206 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6207 selection.end = selection.start;
6208 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6209 row_delta += tab_size.len;
6210 }
6211
6212 self.transact(window, cx, |this, window, cx| {
6213 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6214 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6215 s.select(selections)
6216 });
6217 this.refresh_inline_completion(true, false, window, cx);
6218 });
6219 }
6220
6221 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6222 if self.read_only(cx) {
6223 return;
6224 }
6225 let mut selections = self.selections.all::<Point>(cx);
6226 let mut prev_edited_row = 0;
6227 let mut row_delta = 0;
6228 let mut edits = Vec::new();
6229 let buffer = self.buffer.read(cx);
6230 let snapshot = buffer.snapshot(cx);
6231 for selection in &mut selections {
6232 if selection.start.row != prev_edited_row {
6233 row_delta = 0;
6234 }
6235 prev_edited_row = selection.end.row;
6236
6237 row_delta =
6238 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6239 }
6240
6241 self.transact(window, cx, |this, window, cx| {
6242 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6243 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6244 s.select(selections)
6245 });
6246 });
6247 }
6248
6249 fn indent_selection(
6250 buffer: &MultiBuffer,
6251 snapshot: &MultiBufferSnapshot,
6252 selection: &mut Selection<Point>,
6253 edits: &mut Vec<(Range<Point>, String)>,
6254 delta_for_start_row: u32,
6255 cx: &App,
6256 ) -> u32 {
6257 let settings = buffer.settings_at(selection.start, cx);
6258 let tab_size = settings.tab_size.get();
6259 let indent_kind = if settings.hard_tabs {
6260 IndentKind::Tab
6261 } else {
6262 IndentKind::Space
6263 };
6264 let mut start_row = selection.start.row;
6265 let mut end_row = selection.end.row + 1;
6266
6267 // If a selection ends at the beginning of a line, don't indent
6268 // that last line.
6269 if selection.end.column == 0 && selection.end.row > selection.start.row {
6270 end_row -= 1;
6271 }
6272
6273 // Avoid re-indenting a row that has already been indented by a
6274 // previous selection, but still update this selection's column
6275 // to reflect that indentation.
6276 if delta_for_start_row > 0 {
6277 start_row += 1;
6278 selection.start.column += delta_for_start_row;
6279 if selection.end.row == selection.start.row {
6280 selection.end.column += delta_for_start_row;
6281 }
6282 }
6283
6284 let mut delta_for_end_row = 0;
6285 let has_multiple_rows = start_row + 1 != end_row;
6286 for row in start_row..end_row {
6287 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6288 let indent_delta = match (current_indent.kind, indent_kind) {
6289 (IndentKind::Space, IndentKind::Space) => {
6290 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6291 IndentSize::spaces(columns_to_next_tab_stop)
6292 }
6293 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6294 (_, IndentKind::Tab) => IndentSize::tab(),
6295 };
6296
6297 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6298 0
6299 } else {
6300 selection.start.column
6301 };
6302 let row_start = Point::new(row, start);
6303 edits.push((
6304 row_start..row_start,
6305 indent_delta.chars().collect::<String>(),
6306 ));
6307
6308 // Update this selection's endpoints to reflect the indentation.
6309 if row == selection.start.row {
6310 selection.start.column += indent_delta.len;
6311 }
6312 if row == selection.end.row {
6313 selection.end.column += indent_delta.len;
6314 delta_for_end_row = indent_delta.len;
6315 }
6316 }
6317
6318 if selection.start.row == selection.end.row {
6319 delta_for_start_row + delta_for_end_row
6320 } else {
6321 delta_for_end_row
6322 }
6323 }
6324
6325 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6326 if self.read_only(cx) {
6327 return;
6328 }
6329 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6330 let selections = self.selections.all::<Point>(cx);
6331 let mut deletion_ranges = Vec::new();
6332 let mut last_outdent = None;
6333 {
6334 let buffer = self.buffer.read(cx);
6335 let snapshot = buffer.snapshot(cx);
6336 for selection in &selections {
6337 let settings = buffer.settings_at(selection.start, cx);
6338 let tab_size = settings.tab_size.get();
6339 let mut rows = selection.spanned_rows(false, &display_map);
6340
6341 // Avoid re-outdenting a row that has already been outdented by a
6342 // previous selection.
6343 if let Some(last_row) = last_outdent {
6344 if last_row == rows.start {
6345 rows.start = rows.start.next_row();
6346 }
6347 }
6348 let has_multiple_rows = rows.len() > 1;
6349 for row in rows.iter_rows() {
6350 let indent_size = snapshot.indent_size_for_line(row);
6351 if indent_size.len > 0 {
6352 let deletion_len = match indent_size.kind {
6353 IndentKind::Space => {
6354 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6355 if columns_to_prev_tab_stop == 0 {
6356 tab_size
6357 } else {
6358 columns_to_prev_tab_stop
6359 }
6360 }
6361 IndentKind::Tab => 1,
6362 };
6363 let start = if has_multiple_rows
6364 || deletion_len > selection.start.column
6365 || indent_size.len < selection.start.column
6366 {
6367 0
6368 } else {
6369 selection.start.column - deletion_len
6370 };
6371 deletion_ranges.push(
6372 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6373 );
6374 last_outdent = Some(row);
6375 }
6376 }
6377 }
6378 }
6379
6380 self.transact(window, cx, |this, window, cx| {
6381 this.buffer.update(cx, |buffer, cx| {
6382 let empty_str: Arc<str> = Arc::default();
6383 buffer.edit(
6384 deletion_ranges
6385 .into_iter()
6386 .map(|range| (range, empty_str.clone())),
6387 None,
6388 cx,
6389 );
6390 });
6391 let selections = this.selections.all::<usize>(cx);
6392 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6393 s.select(selections)
6394 });
6395 });
6396 }
6397
6398 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6399 if self.read_only(cx) {
6400 return;
6401 }
6402 let selections = self
6403 .selections
6404 .all::<usize>(cx)
6405 .into_iter()
6406 .map(|s| s.range());
6407
6408 self.transact(window, cx, |this, window, cx| {
6409 this.buffer.update(cx, |buffer, cx| {
6410 buffer.autoindent_ranges(selections, cx);
6411 });
6412 let selections = this.selections.all::<usize>(cx);
6413 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6414 s.select(selections)
6415 });
6416 });
6417 }
6418
6419 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6420 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6421 let selections = self.selections.all::<Point>(cx);
6422
6423 let mut new_cursors = Vec::new();
6424 let mut edit_ranges = Vec::new();
6425 let mut selections = selections.iter().peekable();
6426 while let Some(selection) = selections.next() {
6427 let mut rows = selection.spanned_rows(false, &display_map);
6428 let goal_display_column = selection.head().to_display_point(&display_map).column();
6429
6430 // Accumulate contiguous regions of rows that we want to delete.
6431 while let Some(next_selection) = selections.peek() {
6432 let next_rows = next_selection.spanned_rows(false, &display_map);
6433 if next_rows.start <= rows.end {
6434 rows.end = next_rows.end;
6435 selections.next().unwrap();
6436 } else {
6437 break;
6438 }
6439 }
6440
6441 let buffer = &display_map.buffer_snapshot;
6442 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6443 let edit_end;
6444 let cursor_buffer_row;
6445 if buffer.max_point().row >= rows.end.0 {
6446 // If there's a line after the range, delete the \n from the end of the row range
6447 // and position the cursor on the next line.
6448 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6449 cursor_buffer_row = rows.end;
6450 } else {
6451 // If there isn't a line after the range, delete the \n from the line before the
6452 // start of the row range and position the cursor there.
6453 edit_start = edit_start.saturating_sub(1);
6454 edit_end = buffer.len();
6455 cursor_buffer_row = rows.start.previous_row();
6456 }
6457
6458 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6459 *cursor.column_mut() =
6460 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6461
6462 new_cursors.push((
6463 selection.id,
6464 buffer.anchor_after(cursor.to_point(&display_map)),
6465 ));
6466 edit_ranges.push(edit_start..edit_end);
6467 }
6468
6469 self.transact(window, cx, |this, window, cx| {
6470 let buffer = this.buffer.update(cx, |buffer, cx| {
6471 let empty_str: Arc<str> = Arc::default();
6472 buffer.edit(
6473 edit_ranges
6474 .into_iter()
6475 .map(|range| (range, empty_str.clone())),
6476 None,
6477 cx,
6478 );
6479 buffer.snapshot(cx)
6480 });
6481 let new_selections = new_cursors
6482 .into_iter()
6483 .map(|(id, cursor)| {
6484 let cursor = cursor.to_point(&buffer);
6485 Selection {
6486 id,
6487 start: cursor,
6488 end: cursor,
6489 reversed: false,
6490 goal: SelectionGoal::None,
6491 }
6492 })
6493 .collect();
6494
6495 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6496 s.select(new_selections);
6497 });
6498 });
6499 }
6500
6501 pub fn join_lines_impl(
6502 &mut self,
6503 insert_whitespace: bool,
6504 window: &mut Window,
6505 cx: &mut Context<Self>,
6506 ) {
6507 if self.read_only(cx) {
6508 return;
6509 }
6510 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6511 for selection in self.selections.all::<Point>(cx) {
6512 let start = MultiBufferRow(selection.start.row);
6513 // Treat single line selections as if they include the next line. Otherwise this action
6514 // would do nothing for single line selections individual cursors.
6515 let end = if selection.start.row == selection.end.row {
6516 MultiBufferRow(selection.start.row + 1)
6517 } else {
6518 MultiBufferRow(selection.end.row)
6519 };
6520
6521 if let Some(last_row_range) = row_ranges.last_mut() {
6522 if start <= last_row_range.end {
6523 last_row_range.end = end;
6524 continue;
6525 }
6526 }
6527 row_ranges.push(start..end);
6528 }
6529
6530 let snapshot = self.buffer.read(cx).snapshot(cx);
6531 let mut cursor_positions = Vec::new();
6532 for row_range in &row_ranges {
6533 let anchor = snapshot.anchor_before(Point::new(
6534 row_range.end.previous_row().0,
6535 snapshot.line_len(row_range.end.previous_row()),
6536 ));
6537 cursor_positions.push(anchor..anchor);
6538 }
6539
6540 self.transact(window, cx, |this, window, cx| {
6541 for row_range in row_ranges.into_iter().rev() {
6542 for row in row_range.iter_rows().rev() {
6543 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6544 let next_line_row = row.next_row();
6545 let indent = snapshot.indent_size_for_line(next_line_row);
6546 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6547
6548 let replace =
6549 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6550 " "
6551 } else {
6552 ""
6553 };
6554
6555 this.buffer.update(cx, |buffer, cx| {
6556 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6557 });
6558 }
6559 }
6560
6561 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6562 s.select_anchor_ranges(cursor_positions)
6563 });
6564 });
6565 }
6566
6567 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6568 self.join_lines_impl(true, window, cx);
6569 }
6570
6571 pub fn sort_lines_case_sensitive(
6572 &mut self,
6573 _: &SortLinesCaseSensitive,
6574 window: &mut Window,
6575 cx: &mut Context<Self>,
6576 ) {
6577 self.manipulate_lines(window, cx, |lines| lines.sort())
6578 }
6579
6580 pub fn sort_lines_case_insensitive(
6581 &mut self,
6582 _: &SortLinesCaseInsensitive,
6583 window: &mut Window,
6584 cx: &mut Context<Self>,
6585 ) {
6586 self.manipulate_lines(window, cx, |lines| {
6587 lines.sort_by_key(|line| line.to_lowercase())
6588 })
6589 }
6590
6591 pub fn unique_lines_case_insensitive(
6592 &mut self,
6593 _: &UniqueLinesCaseInsensitive,
6594 window: &mut Window,
6595 cx: &mut Context<Self>,
6596 ) {
6597 self.manipulate_lines(window, cx, |lines| {
6598 let mut seen = HashSet::default();
6599 lines.retain(|line| seen.insert(line.to_lowercase()));
6600 })
6601 }
6602
6603 pub fn unique_lines_case_sensitive(
6604 &mut self,
6605 _: &UniqueLinesCaseSensitive,
6606 window: &mut Window,
6607 cx: &mut Context<Self>,
6608 ) {
6609 self.manipulate_lines(window, cx, |lines| {
6610 let mut seen = HashSet::default();
6611 lines.retain(|line| seen.insert(*line));
6612 })
6613 }
6614
6615 pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
6616 let mut revert_changes = HashMap::default();
6617 let snapshot = self.snapshot(window, cx);
6618 for hunk in snapshot
6619 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
6620 {
6621 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6622 }
6623 if !revert_changes.is_empty() {
6624 self.transact(window, cx, |editor, window, cx| {
6625 editor.revert(revert_changes, window, cx);
6626 });
6627 }
6628 }
6629
6630 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
6631 let Some(project) = self.project.clone() else {
6632 return;
6633 };
6634 self.reload(project, window, cx)
6635 .detach_and_notify_err(window, cx);
6636 }
6637
6638 pub fn revert_selected_hunks(
6639 &mut self,
6640 _: &RevertSelectedHunks,
6641 window: &mut Window,
6642 cx: &mut Context<Self>,
6643 ) {
6644 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
6645 self.revert_hunks_in_ranges(selections, window, cx);
6646 }
6647
6648 fn revert_hunks_in_ranges(
6649 &mut self,
6650 ranges: impl Iterator<Item = Range<Point>>,
6651 window: &mut Window,
6652 cx: &mut Context<Editor>,
6653 ) {
6654 let mut revert_changes = HashMap::default();
6655 let snapshot = self.snapshot(window, cx);
6656 for hunk in &snapshot.hunks_for_ranges(ranges) {
6657 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6658 }
6659 if !revert_changes.is_empty() {
6660 self.transact(window, cx, |editor, window, cx| {
6661 editor.revert(revert_changes, window, cx);
6662 });
6663 }
6664 }
6665
6666 pub fn open_active_item_in_terminal(
6667 &mut self,
6668 _: &OpenInTerminal,
6669 window: &mut Window,
6670 cx: &mut Context<Self>,
6671 ) {
6672 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6673 let project_path = buffer.read(cx).project_path(cx)?;
6674 let project = self.project.as_ref()?.read(cx);
6675 let entry = project.entry_for_path(&project_path, cx)?;
6676 let parent = match &entry.canonical_path {
6677 Some(canonical_path) => canonical_path.to_path_buf(),
6678 None => project.absolute_path(&project_path, cx)?,
6679 }
6680 .parent()?
6681 .to_path_buf();
6682 Some(parent)
6683 }) {
6684 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
6685 }
6686 }
6687
6688 pub fn prepare_revert_change(
6689 &self,
6690 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6691 hunk: &MultiBufferDiffHunk,
6692 cx: &mut App,
6693 ) -> Option<()> {
6694 let buffer = self.buffer.read(cx);
6695 let change_set = buffer.change_set_for(hunk.buffer_id)?;
6696 let buffer = buffer.buffer(hunk.buffer_id)?;
6697 let buffer = buffer.read(cx);
6698 let original_text = change_set
6699 .read(cx)
6700 .base_text
6701 .as_ref()?
6702 .as_rope()
6703 .slice(hunk.diff_base_byte_range.clone());
6704 let buffer_snapshot = buffer.snapshot();
6705 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6706 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6707 probe
6708 .0
6709 .start
6710 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6711 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6712 }) {
6713 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6714 Some(())
6715 } else {
6716 None
6717 }
6718 }
6719
6720 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
6721 self.manipulate_lines(window, cx, |lines| lines.reverse())
6722 }
6723
6724 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
6725 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
6726 }
6727
6728 fn manipulate_lines<Fn>(
6729 &mut self,
6730 window: &mut Window,
6731 cx: &mut Context<Self>,
6732 mut callback: Fn,
6733 ) where
6734 Fn: FnMut(&mut Vec<&str>),
6735 {
6736 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6737 let buffer = self.buffer.read(cx).snapshot(cx);
6738
6739 let mut edits = Vec::new();
6740
6741 let selections = self.selections.all::<Point>(cx);
6742 let mut selections = selections.iter().peekable();
6743 let mut contiguous_row_selections = Vec::new();
6744 let mut new_selections = Vec::new();
6745 let mut added_lines = 0;
6746 let mut removed_lines = 0;
6747
6748 while let Some(selection) = selections.next() {
6749 let (start_row, end_row) = consume_contiguous_rows(
6750 &mut contiguous_row_selections,
6751 selection,
6752 &display_map,
6753 &mut selections,
6754 );
6755
6756 let start_point = Point::new(start_row.0, 0);
6757 let end_point = Point::new(
6758 end_row.previous_row().0,
6759 buffer.line_len(end_row.previous_row()),
6760 );
6761 let text = buffer
6762 .text_for_range(start_point..end_point)
6763 .collect::<String>();
6764
6765 let mut lines = text.split('\n').collect_vec();
6766
6767 let lines_before = lines.len();
6768 callback(&mut lines);
6769 let lines_after = lines.len();
6770
6771 edits.push((start_point..end_point, lines.join("\n")));
6772
6773 // Selections must change based on added and removed line count
6774 let start_row =
6775 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6776 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6777 new_selections.push(Selection {
6778 id: selection.id,
6779 start: start_row,
6780 end: end_row,
6781 goal: SelectionGoal::None,
6782 reversed: selection.reversed,
6783 });
6784
6785 if lines_after > lines_before {
6786 added_lines += lines_after - lines_before;
6787 } else if lines_before > lines_after {
6788 removed_lines += lines_before - lines_after;
6789 }
6790 }
6791
6792 self.transact(window, cx, |this, window, cx| {
6793 let buffer = this.buffer.update(cx, |buffer, cx| {
6794 buffer.edit(edits, None, cx);
6795 buffer.snapshot(cx)
6796 });
6797
6798 // Recalculate offsets on newly edited buffer
6799 let new_selections = new_selections
6800 .iter()
6801 .map(|s| {
6802 let start_point = Point::new(s.start.0, 0);
6803 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6804 Selection {
6805 id: s.id,
6806 start: buffer.point_to_offset(start_point),
6807 end: buffer.point_to_offset(end_point),
6808 goal: s.goal,
6809 reversed: s.reversed,
6810 }
6811 })
6812 .collect();
6813
6814 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6815 s.select(new_selections);
6816 });
6817
6818 this.request_autoscroll(Autoscroll::fit(), cx);
6819 });
6820 }
6821
6822 pub fn convert_to_upper_case(
6823 &mut self,
6824 _: &ConvertToUpperCase,
6825 window: &mut Window,
6826 cx: &mut Context<Self>,
6827 ) {
6828 self.manipulate_text(window, cx, |text| text.to_uppercase())
6829 }
6830
6831 pub fn convert_to_lower_case(
6832 &mut self,
6833 _: &ConvertToLowerCase,
6834 window: &mut Window,
6835 cx: &mut Context<Self>,
6836 ) {
6837 self.manipulate_text(window, cx, |text| text.to_lowercase())
6838 }
6839
6840 pub fn convert_to_title_case(
6841 &mut self,
6842 _: &ConvertToTitleCase,
6843 window: &mut Window,
6844 cx: &mut Context<Self>,
6845 ) {
6846 self.manipulate_text(window, cx, |text| {
6847 text.split('\n')
6848 .map(|line| line.to_case(Case::Title))
6849 .join("\n")
6850 })
6851 }
6852
6853 pub fn convert_to_snake_case(
6854 &mut self,
6855 _: &ConvertToSnakeCase,
6856 window: &mut Window,
6857 cx: &mut Context<Self>,
6858 ) {
6859 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
6860 }
6861
6862 pub fn convert_to_kebab_case(
6863 &mut self,
6864 _: &ConvertToKebabCase,
6865 window: &mut Window,
6866 cx: &mut Context<Self>,
6867 ) {
6868 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
6869 }
6870
6871 pub fn convert_to_upper_camel_case(
6872 &mut self,
6873 _: &ConvertToUpperCamelCase,
6874 window: &mut Window,
6875 cx: &mut Context<Self>,
6876 ) {
6877 self.manipulate_text(window, cx, |text| {
6878 text.split('\n')
6879 .map(|line| line.to_case(Case::UpperCamel))
6880 .join("\n")
6881 })
6882 }
6883
6884 pub fn convert_to_lower_camel_case(
6885 &mut self,
6886 _: &ConvertToLowerCamelCase,
6887 window: &mut Window,
6888 cx: &mut Context<Self>,
6889 ) {
6890 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
6891 }
6892
6893 pub fn convert_to_opposite_case(
6894 &mut self,
6895 _: &ConvertToOppositeCase,
6896 window: &mut Window,
6897 cx: &mut Context<Self>,
6898 ) {
6899 self.manipulate_text(window, cx, |text| {
6900 text.chars()
6901 .fold(String::with_capacity(text.len()), |mut t, c| {
6902 if c.is_uppercase() {
6903 t.extend(c.to_lowercase());
6904 } else {
6905 t.extend(c.to_uppercase());
6906 }
6907 t
6908 })
6909 })
6910 }
6911
6912 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
6913 where
6914 Fn: FnMut(&str) -> String,
6915 {
6916 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6917 let buffer = self.buffer.read(cx).snapshot(cx);
6918
6919 let mut new_selections = Vec::new();
6920 let mut edits = Vec::new();
6921 let mut selection_adjustment = 0i32;
6922
6923 for selection in self.selections.all::<usize>(cx) {
6924 let selection_is_empty = selection.is_empty();
6925
6926 let (start, end) = if selection_is_empty {
6927 let word_range = movement::surrounding_word(
6928 &display_map,
6929 selection.start.to_display_point(&display_map),
6930 );
6931 let start = word_range.start.to_offset(&display_map, Bias::Left);
6932 let end = word_range.end.to_offset(&display_map, Bias::Left);
6933 (start, end)
6934 } else {
6935 (selection.start, selection.end)
6936 };
6937
6938 let text = buffer.text_for_range(start..end).collect::<String>();
6939 let old_length = text.len() as i32;
6940 let text = callback(&text);
6941
6942 new_selections.push(Selection {
6943 start: (start as i32 - selection_adjustment) as usize,
6944 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6945 goal: SelectionGoal::None,
6946 ..selection
6947 });
6948
6949 selection_adjustment += old_length - text.len() as i32;
6950
6951 edits.push((start..end, text));
6952 }
6953
6954 self.transact(window, cx, |this, window, cx| {
6955 this.buffer.update(cx, |buffer, cx| {
6956 buffer.edit(edits, None, cx);
6957 });
6958
6959 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6960 s.select(new_selections);
6961 });
6962
6963 this.request_autoscroll(Autoscroll::fit(), cx);
6964 });
6965 }
6966
6967 pub fn duplicate(
6968 &mut self,
6969 upwards: bool,
6970 whole_lines: bool,
6971 window: &mut Window,
6972 cx: &mut Context<Self>,
6973 ) {
6974 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6975 let buffer = &display_map.buffer_snapshot;
6976 let selections = self.selections.all::<Point>(cx);
6977
6978 let mut edits = Vec::new();
6979 let mut selections_iter = selections.iter().peekable();
6980 while let Some(selection) = selections_iter.next() {
6981 let mut rows = selection.spanned_rows(false, &display_map);
6982 // duplicate line-wise
6983 if whole_lines || selection.start == selection.end {
6984 // Avoid duplicating the same lines twice.
6985 while let Some(next_selection) = selections_iter.peek() {
6986 let next_rows = next_selection.spanned_rows(false, &display_map);
6987 if next_rows.start < rows.end {
6988 rows.end = next_rows.end;
6989 selections_iter.next().unwrap();
6990 } else {
6991 break;
6992 }
6993 }
6994
6995 // Copy the text from the selected row region and splice it either at the start
6996 // or end of the region.
6997 let start = Point::new(rows.start.0, 0);
6998 let end = Point::new(
6999 rows.end.previous_row().0,
7000 buffer.line_len(rows.end.previous_row()),
7001 );
7002 let text = buffer
7003 .text_for_range(start..end)
7004 .chain(Some("\n"))
7005 .collect::<String>();
7006 let insert_location = if upwards {
7007 Point::new(rows.end.0, 0)
7008 } else {
7009 start
7010 };
7011 edits.push((insert_location..insert_location, text));
7012 } else {
7013 // duplicate character-wise
7014 let start = selection.start;
7015 let end = selection.end;
7016 let text = buffer.text_for_range(start..end).collect::<String>();
7017 edits.push((selection.end..selection.end, text));
7018 }
7019 }
7020
7021 self.transact(window, cx, |this, _, cx| {
7022 this.buffer.update(cx, |buffer, cx| {
7023 buffer.edit(edits, None, cx);
7024 });
7025
7026 this.request_autoscroll(Autoscroll::fit(), cx);
7027 });
7028 }
7029
7030 pub fn duplicate_line_up(
7031 &mut self,
7032 _: &DuplicateLineUp,
7033 window: &mut Window,
7034 cx: &mut Context<Self>,
7035 ) {
7036 self.duplicate(true, true, window, cx);
7037 }
7038
7039 pub fn duplicate_line_down(
7040 &mut self,
7041 _: &DuplicateLineDown,
7042 window: &mut Window,
7043 cx: &mut Context<Self>,
7044 ) {
7045 self.duplicate(false, true, window, cx);
7046 }
7047
7048 pub fn duplicate_selection(
7049 &mut self,
7050 _: &DuplicateSelection,
7051 window: &mut Window,
7052 cx: &mut Context<Self>,
7053 ) {
7054 self.duplicate(false, false, window, cx);
7055 }
7056
7057 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7058 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7059 let buffer = self.buffer.read(cx).snapshot(cx);
7060
7061 let mut edits = Vec::new();
7062 let mut unfold_ranges = Vec::new();
7063 let mut refold_creases = Vec::new();
7064
7065 let selections = self.selections.all::<Point>(cx);
7066 let mut selections = selections.iter().peekable();
7067 let mut contiguous_row_selections = Vec::new();
7068 let mut new_selections = Vec::new();
7069
7070 while let Some(selection) = selections.next() {
7071 // Find all the selections that span a contiguous row range
7072 let (start_row, end_row) = consume_contiguous_rows(
7073 &mut contiguous_row_selections,
7074 selection,
7075 &display_map,
7076 &mut selections,
7077 );
7078
7079 // Move the text spanned by the row range to be before the line preceding the row range
7080 if start_row.0 > 0 {
7081 let range_to_move = Point::new(
7082 start_row.previous_row().0,
7083 buffer.line_len(start_row.previous_row()),
7084 )
7085 ..Point::new(
7086 end_row.previous_row().0,
7087 buffer.line_len(end_row.previous_row()),
7088 );
7089 let insertion_point = display_map
7090 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7091 .0;
7092
7093 // Don't move lines across excerpts
7094 if buffer
7095 .excerpt_containing(insertion_point..range_to_move.end)
7096 .is_some()
7097 {
7098 let text = buffer
7099 .text_for_range(range_to_move.clone())
7100 .flat_map(|s| s.chars())
7101 .skip(1)
7102 .chain(['\n'])
7103 .collect::<String>();
7104
7105 edits.push((
7106 buffer.anchor_after(range_to_move.start)
7107 ..buffer.anchor_before(range_to_move.end),
7108 String::new(),
7109 ));
7110 let insertion_anchor = buffer.anchor_after(insertion_point);
7111 edits.push((insertion_anchor..insertion_anchor, text));
7112
7113 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7114
7115 // Move selections up
7116 new_selections.extend(contiguous_row_selections.drain(..).map(
7117 |mut selection| {
7118 selection.start.row -= row_delta;
7119 selection.end.row -= row_delta;
7120 selection
7121 },
7122 ));
7123
7124 // Move folds up
7125 unfold_ranges.push(range_to_move.clone());
7126 for fold in display_map.folds_in_range(
7127 buffer.anchor_before(range_to_move.start)
7128 ..buffer.anchor_after(range_to_move.end),
7129 ) {
7130 let mut start = fold.range.start.to_point(&buffer);
7131 let mut end = fold.range.end.to_point(&buffer);
7132 start.row -= row_delta;
7133 end.row -= row_delta;
7134 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7135 }
7136 }
7137 }
7138
7139 // If we didn't move line(s), preserve the existing selections
7140 new_selections.append(&mut contiguous_row_selections);
7141 }
7142
7143 self.transact(window, cx, |this, window, cx| {
7144 this.unfold_ranges(&unfold_ranges, true, true, cx);
7145 this.buffer.update(cx, |buffer, cx| {
7146 for (range, text) in edits {
7147 buffer.edit([(range, text)], None, cx);
7148 }
7149 });
7150 this.fold_creases(refold_creases, true, window, cx);
7151 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7152 s.select(new_selections);
7153 })
7154 });
7155 }
7156
7157 pub fn move_line_down(
7158 &mut self,
7159 _: &MoveLineDown,
7160 window: &mut Window,
7161 cx: &mut Context<Self>,
7162 ) {
7163 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7164 let buffer = self.buffer.read(cx).snapshot(cx);
7165
7166 let mut edits = Vec::new();
7167 let mut unfold_ranges = Vec::new();
7168 let mut refold_creases = Vec::new();
7169
7170 let selections = self.selections.all::<Point>(cx);
7171 let mut selections = selections.iter().peekable();
7172 let mut contiguous_row_selections = Vec::new();
7173 let mut new_selections = Vec::new();
7174
7175 while let Some(selection) = selections.next() {
7176 // Find all the selections that span a contiguous row range
7177 let (start_row, end_row) = consume_contiguous_rows(
7178 &mut contiguous_row_selections,
7179 selection,
7180 &display_map,
7181 &mut selections,
7182 );
7183
7184 // Move the text spanned by the row range to be after the last line of the row range
7185 if end_row.0 <= buffer.max_point().row {
7186 let range_to_move =
7187 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7188 let insertion_point = display_map
7189 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7190 .0;
7191
7192 // Don't move lines across excerpt boundaries
7193 if buffer
7194 .excerpt_containing(range_to_move.start..insertion_point)
7195 .is_some()
7196 {
7197 let mut text = String::from("\n");
7198 text.extend(buffer.text_for_range(range_to_move.clone()));
7199 text.pop(); // Drop trailing newline
7200 edits.push((
7201 buffer.anchor_after(range_to_move.start)
7202 ..buffer.anchor_before(range_to_move.end),
7203 String::new(),
7204 ));
7205 let insertion_anchor = buffer.anchor_after(insertion_point);
7206 edits.push((insertion_anchor..insertion_anchor, text));
7207
7208 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7209
7210 // Move selections down
7211 new_selections.extend(contiguous_row_selections.drain(..).map(
7212 |mut selection| {
7213 selection.start.row += row_delta;
7214 selection.end.row += row_delta;
7215 selection
7216 },
7217 ));
7218
7219 // Move folds down
7220 unfold_ranges.push(range_to_move.clone());
7221 for fold in display_map.folds_in_range(
7222 buffer.anchor_before(range_to_move.start)
7223 ..buffer.anchor_after(range_to_move.end),
7224 ) {
7225 let mut start = fold.range.start.to_point(&buffer);
7226 let mut end = fold.range.end.to_point(&buffer);
7227 start.row += row_delta;
7228 end.row += row_delta;
7229 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7230 }
7231 }
7232 }
7233
7234 // If we didn't move line(s), preserve the existing selections
7235 new_selections.append(&mut contiguous_row_selections);
7236 }
7237
7238 self.transact(window, cx, |this, window, cx| {
7239 this.unfold_ranges(&unfold_ranges, true, true, cx);
7240 this.buffer.update(cx, |buffer, cx| {
7241 for (range, text) in edits {
7242 buffer.edit([(range, text)], None, cx);
7243 }
7244 });
7245 this.fold_creases(refold_creases, true, window, cx);
7246 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7247 s.select(new_selections)
7248 });
7249 });
7250 }
7251
7252 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7253 let text_layout_details = &self.text_layout_details(window);
7254 self.transact(window, cx, |this, window, cx| {
7255 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7256 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7257 let line_mode = s.line_mode;
7258 s.move_with(|display_map, selection| {
7259 if !selection.is_empty() || line_mode {
7260 return;
7261 }
7262
7263 let mut head = selection.head();
7264 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7265 if head.column() == display_map.line_len(head.row()) {
7266 transpose_offset = display_map
7267 .buffer_snapshot
7268 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7269 }
7270
7271 if transpose_offset == 0 {
7272 return;
7273 }
7274
7275 *head.column_mut() += 1;
7276 head = display_map.clip_point(head, Bias::Right);
7277 let goal = SelectionGoal::HorizontalPosition(
7278 display_map
7279 .x_for_display_point(head, text_layout_details)
7280 .into(),
7281 );
7282 selection.collapse_to(head, goal);
7283
7284 let transpose_start = display_map
7285 .buffer_snapshot
7286 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7287 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7288 let transpose_end = display_map
7289 .buffer_snapshot
7290 .clip_offset(transpose_offset + 1, Bias::Right);
7291 if let Some(ch) =
7292 display_map.buffer_snapshot.chars_at(transpose_start).next()
7293 {
7294 edits.push((transpose_start..transpose_offset, String::new()));
7295 edits.push((transpose_end..transpose_end, ch.to_string()));
7296 }
7297 }
7298 });
7299 edits
7300 });
7301 this.buffer
7302 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7303 let selections = this.selections.all::<usize>(cx);
7304 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7305 s.select(selections);
7306 });
7307 });
7308 }
7309
7310 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7311 self.rewrap_impl(IsVimMode::No, cx)
7312 }
7313
7314 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7315 let buffer = self.buffer.read(cx).snapshot(cx);
7316 let selections = self.selections.all::<Point>(cx);
7317 let mut selections = selections.iter().peekable();
7318
7319 let mut edits = Vec::new();
7320 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7321
7322 while let Some(selection) = selections.next() {
7323 let mut start_row = selection.start.row;
7324 let mut end_row = selection.end.row;
7325
7326 // Skip selections that overlap with a range that has already been rewrapped.
7327 let selection_range = start_row..end_row;
7328 if rewrapped_row_ranges
7329 .iter()
7330 .any(|range| range.overlaps(&selection_range))
7331 {
7332 continue;
7333 }
7334
7335 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7336
7337 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7338 match language_scope.language_name().as_ref() {
7339 "Markdown" | "Plain Text" => {
7340 should_rewrap = true;
7341 }
7342 _ => {}
7343 }
7344 }
7345
7346 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7347
7348 // Since not all lines in the selection may be at the same indent
7349 // level, choose the indent size that is the most common between all
7350 // of the lines.
7351 //
7352 // If there is a tie, we use the deepest indent.
7353 let (indent_size, indent_end) = {
7354 let mut indent_size_occurrences = HashMap::default();
7355 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7356
7357 for row in start_row..=end_row {
7358 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7359 rows_by_indent_size.entry(indent).or_default().push(row);
7360 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7361 }
7362
7363 let indent_size = indent_size_occurrences
7364 .into_iter()
7365 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7366 .map(|(indent, _)| indent)
7367 .unwrap_or_default();
7368 let row = rows_by_indent_size[&indent_size][0];
7369 let indent_end = Point::new(row, indent_size.len);
7370
7371 (indent_size, indent_end)
7372 };
7373
7374 let mut line_prefix = indent_size.chars().collect::<String>();
7375
7376 if let Some(comment_prefix) =
7377 buffer
7378 .language_scope_at(selection.head())
7379 .and_then(|language| {
7380 language
7381 .line_comment_prefixes()
7382 .iter()
7383 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7384 .cloned()
7385 })
7386 {
7387 line_prefix.push_str(&comment_prefix);
7388 should_rewrap = true;
7389 }
7390
7391 if !should_rewrap {
7392 continue;
7393 }
7394
7395 if selection.is_empty() {
7396 'expand_upwards: while start_row > 0 {
7397 let prev_row = start_row - 1;
7398 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7399 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7400 {
7401 start_row = prev_row;
7402 } else {
7403 break 'expand_upwards;
7404 }
7405 }
7406
7407 'expand_downwards: while end_row < buffer.max_point().row {
7408 let next_row = end_row + 1;
7409 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7410 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7411 {
7412 end_row = next_row;
7413 } else {
7414 break 'expand_downwards;
7415 }
7416 }
7417 }
7418
7419 let start = Point::new(start_row, 0);
7420 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7421 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7422 let Some(lines_without_prefixes) = selection_text
7423 .lines()
7424 .map(|line| {
7425 line.strip_prefix(&line_prefix)
7426 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7427 .ok_or_else(|| {
7428 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7429 })
7430 })
7431 .collect::<Result<Vec<_>, _>>()
7432 .log_err()
7433 else {
7434 continue;
7435 };
7436
7437 let wrap_column = buffer
7438 .settings_at(Point::new(start_row, 0), cx)
7439 .preferred_line_length as usize;
7440 let wrapped_text = wrap_with_prefix(
7441 line_prefix,
7442 lines_without_prefixes.join(" "),
7443 wrap_column,
7444 tab_size,
7445 );
7446
7447 // TODO: should always use char-based diff while still supporting cursor behavior that
7448 // matches vim.
7449 let diff = match is_vim_mode {
7450 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7451 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7452 };
7453 let mut offset = start.to_offset(&buffer);
7454 let mut moved_since_edit = true;
7455
7456 for change in diff.iter_all_changes() {
7457 let value = change.value();
7458 match change.tag() {
7459 ChangeTag::Equal => {
7460 offset += value.len();
7461 moved_since_edit = true;
7462 }
7463 ChangeTag::Delete => {
7464 let start = buffer.anchor_after(offset);
7465 let end = buffer.anchor_before(offset + value.len());
7466
7467 if moved_since_edit {
7468 edits.push((start..end, String::new()));
7469 } else {
7470 edits.last_mut().unwrap().0.end = end;
7471 }
7472
7473 offset += value.len();
7474 moved_since_edit = false;
7475 }
7476 ChangeTag::Insert => {
7477 if moved_since_edit {
7478 let anchor = buffer.anchor_after(offset);
7479 edits.push((anchor..anchor, value.to_string()));
7480 } else {
7481 edits.last_mut().unwrap().1.push_str(value);
7482 }
7483
7484 moved_since_edit = false;
7485 }
7486 }
7487 }
7488
7489 rewrapped_row_ranges.push(start_row..=end_row);
7490 }
7491
7492 self.buffer
7493 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7494 }
7495
7496 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7497 let mut text = String::new();
7498 let buffer = self.buffer.read(cx).snapshot(cx);
7499 let mut selections = self.selections.all::<Point>(cx);
7500 let mut clipboard_selections = Vec::with_capacity(selections.len());
7501 {
7502 let max_point = buffer.max_point();
7503 let mut is_first = true;
7504 for selection in &mut selections {
7505 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7506 if is_entire_line {
7507 selection.start = Point::new(selection.start.row, 0);
7508 if !selection.is_empty() && selection.end.column == 0 {
7509 selection.end = cmp::min(max_point, selection.end);
7510 } else {
7511 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7512 }
7513 selection.goal = SelectionGoal::None;
7514 }
7515 if is_first {
7516 is_first = false;
7517 } else {
7518 text += "\n";
7519 }
7520 let mut len = 0;
7521 for chunk in buffer.text_for_range(selection.start..selection.end) {
7522 text.push_str(chunk);
7523 len += chunk.len();
7524 }
7525 clipboard_selections.push(ClipboardSelection {
7526 len,
7527 is_entire_line,
7528 first_line_indent: buffer
7529 .indent_size_for_line(MultiBufferRow(selection.start.row))
7530 .len,
7531 });
7532 }
7533 }
7534
7535 self.transact(window, cx, |this, window, cx| {
7536 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7537 s.select(selections);
7538 });
7539 this.insert("", window, cx);
7540 });
7541 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7542 }
7543
7544 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
7545 let item = self.cut_common(window, cx);
7546 cx.write_to_clipboard(item);
7547 }
7548
7549 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
7550 self.change_selections(None, window, cx, |s| {
7551 s.move_with(|snapshot, sel| {
7552 if sel.is_empty() {
7553 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7554 }
7555 });
7556 });
7557 let item = self.cut_common(window, cx);
7558 cx.set_global(KillRing(item))
7559 }
7560
7561 pub fn kill_ring_yank(
7562 &mut self,
7563 _: &KillRingYank,
7564 window: &mut Window,
7565 cx: &mut Context<Self>,
7566 ) {
7567 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7568 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7569 (kill_ring.text().to_string(), kill_ring.metadata_json())
7570 } else {
7571 return;
7572 }
7573 } else {
7574 return;
7575 };
7576 self.do_paste(&text, metadata, false, window, cx);
7577 }
7578
7579 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
7580 let selections = self.selections.all::<Point>(cx);
7581 let buffer = self.buffer.read(cx).read(cx);
7582 let mut text = String::new();
7583
7584 let mut clipboard_selections = Vec::with_capacity(selections.len());
7585 {
7586 let max_point = buffer.max_point();
7587 let mut is_first = true;
7588 for selection in selections.iter() {
7589 let mut start = selection.start;
7590 let mut end = selection.end;
7591 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7592 if is_entire_line {
7593 start = Point::new(start.row, 0);
7594 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7595 }
7596 if is_first {
7597 is_first = false;
7598 } else {
7599 text += "\n";
7600 }
7601 let mut len = 0;
7602 for chunk in buffer.text_for_range(start..end) {
7603 text.push_str(chunk);
7604 len += chunk.len();
7605 }
7606 clipboard_selections.push(ClipboardSelection {
7607 len,
7608 is_entire_line,
7609 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7610 });
7611 }
7612 }
7613
7614 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7615 text,
7616 clipboard_selections,
7617 ));
7618 }
7619
7620 pub fn do_paste(
7621 &mut self,
7622 text: &String,
7623 clipboard_selections: Option<Vec<ClipboardSelection>>,
7624 handle_entire_lines: bool,
7625 window: &mut Window,
7626 cx: &mut Context<Self>,
7627 ) {
7628 if self.read_only(cx) {
7629 return;
7630 }
7631
7632 let clipboard_text = Cow::Borrowed(text);
7633
7634 self.transact(window, cx, |this, window, cx| {
7635 if let Some(mut clipboard_selections) = clipboard_selections {
7636 let old_selections = this.selections.all::<usize>(cx);
7637 let all_selections_were_entire_line =
7638 clipboard_selections.iter().all(|s| s.is_entire_line);
7639 let first_selection_indent_column =
7640 clipboard_selections.first().map(|s| s.first_line_indent);
7641 if clipboard_selections.len() != old_selections.len() {
7642 clipboard_selections.drain(..);
7643 }
7644 let cursor_offset = this.selections.last::<usize>(cx).head();
7645 let mut auto_indent_on_paste = true;
7646
7647 this.buffer.update(cx, |buffer, cx| {
7648 let snapshot = buffer.read(cx);
7649 auto_indent_on_paste =
7650 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7651
7652 let mut start_offset = 0;
7653 let mut edits = Vec::new();
7654 let mut original_indent_columns = Vec::new();
7655 for (ix, selection) in old_selections.iter().enumerate() {
7656 let to_insert;
7657 let entire_line;
7658 let original_indent_column;
7659 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7660 let end_offset = start_offset + clipboard_selection.len;
7661 to_insert = &clipboard_text[start_offset..end_offset];
7662 entire_line = clipboard_selection.is_entire_line;
7663 start_offset = end_offset + 1;
7664 original_indent_column = Some(clipboard_selection.first_line_indent);
7665 } else {
7666 to_insert = clipboard_text.as_str();
7667 entire_line = all_selections_were_entire_line;
7668 original_indent_column = first_selection_indent_column
7669 }
7670
7671 // If the corresponding selection was empty when this slice of the
7672 // clipboard text was written, then the entire line containing the
7673 // selection was copied. If this selection is also currently empty,
7674 // then paste the line before the current line of the buffer.
7675 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7676 let column = selection.start.to_point(&snapshot).column as usize;
7677 let line_start = selection.start - column;
7678 line_start..line_start
7679 } else {
7680 selection.range()
7681 };
7682
7683 edits.push((range, to_insert));
7684 original_indent_columns.extend(original_indent_column);
7685 }
7686 drop(snapshot);
7687
7688 buffer.edit(
7689 edits,
7690 if auto_indent_on_paste {
7691 Some(AutoindentMode::Block {
7692 original_indent_columns,
7693 })
7694 } else {
7695 None
7696 },
7697 cx,
7698 );
7699 });
7700
7701 let selections = this.selections.all::<usize>(cx);
7702 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7703 s.select(selections)
7704 });
7705 } else {
7706 this.insert(&clipboard_text, window, cx);
7707 }
7708 });
7709 }
7710
7711 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
7712 if let Some(item) = cx.read_from_clipboard() {
7713 let entries = item.entries();
7714
7715 match entries.first() {
7716 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7717 // of all the pasted entries.
7718 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7719 .do_paste(
7720 clipboard_string.text(),
7721 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7722 true,
7723 window,
7724 cx,
7725 ),
7726 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
7727 }
7728 }
7729 }
7730
7731 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
7732 if self.read_only(cx) {
7733 return;
7734 }
7735
7736 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7737 if let Some((selections, _)) =
7738 self.selection_history.transaction(transaction_id).cloned()
7739 {
7740 self.change_selections(None, window, cx, |s| {
7741 s.select_anchors(selections.to_vec());
7742 });
7743 }
7744 self.request_autoscroll(Autoscroll::fit(), cx);
7745 self.unmark_text(window, cx);
7746 self.refresh_inline_completion(true, false, window, cx);
7747 cx.emit(EditorEvent::Edited { transaction_id });
7748 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7749 }
7750 }
7751
7752 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
7753 if self.read_only(cx) {
7754 return;
7755 }
7756
7757 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7758 if let Some((_, Some(selections))) =
7759 self.selection_history.transaction(transaction_id).cloned()
7760 {
7761 self.change_selections(None, window, cx, |s| {
7762 s.select_anchors(selections.to_vec());
7763 });
7764 }
7765 self.request_autoscroll(Autoscroll::fit(), cx);
7766 self.unmark_text(window, cx);
7767 self.refresh_inline_completion(true, false, window, cx);
7768 cx.emit(EditorEvent::Edited { transaction_id });
7769 }
7770 }
7771
7772 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
7773 self.buffer
7774 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7775 }
7776
7777 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
7778 self.buffer
7779 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7780 }
7781
7782 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
7783 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7784 let line_mode = s.line_mode;
7785 s.move_with(|map, selection| {
7786 let cursor = if selection.is_empty() && !line_mode {
7787 movement::left(map, selection.start)
7788 } else {
7789 selection.start
7790 };
7791 selection.collapse_to(cursor, SelectionGoal::None);
7792 });
7793 })
7794 }
7795
7796 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
7797 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7798 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7799 })
7800 }
7801
7802 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
7803 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7804 let line_mode = s.line_mode;
7805 s.move_with(|map, selection| {
7806 let cursor = if selection.is_empty() && !line_mode {
7807 movement::right(map, selection.end)
7808 } else {
7809 selection.end
7810 };
7811 selection.collapse_to(cursor, SelectionGoal::None)
7812 });
7813 })
7814 }
7815
7816 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
7817 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7818 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7819 })
7820 }
7821
7822 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
7823 if self.take_rename(true, window, cx).is_some() {
7824 return;
7825 }
7826
7827 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7828 cx.propagate();
7829 return;
7830 }
7831
7832 let text_layout_details = &self.text_layout_details(window);
7833 let selection_count = self.selections.count();
7834 let first_selection = self.selections.first_anchor();
7835
7836 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7837 let line_mode = s.line_mode;
7838 s.move_with(|map, selection| {
7839 if !selection.is_empty() && !line_mode {
7840 selection.goal = SelectionGoal::None;
7841 }
7842 let (cursor, goal) = movement::up(
7843 map,
7844 selection.start,
7845 selection.goal,
7846 false,
7847 text_layout_details,
7848 );
7849 selection.collapse_to(cursor, goal);
7850 });
7851 });
7852
7853 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7854 {
7855 cx.propagate();
7856 }
7857 }
7858
7859 pub fn move_up_by_lines(
7860 &mut self,
7861 action: &MoveUpByLines,
7862 window: &mut Window,
7863 cx: &mut Context<Self>,
7864 ) {
7865 if self.take_rename(true, window, cx).is_some() {
7866 return;
7867 }
7868
7869 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7870 cx.propagate();
7871 return;
7872 }
7873
7874 let text_layout_details = &self.text_layout_details(window);
7875
7876 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7877 let line_mode = s.line_mode;
7878 s.move_with(|map, selection| {
7879 if !selection.is_empty() && !line_mode {
7880 selection.goal = SelectionGoal::None;
7881 }
7882 let (cursor, goal) = movement::up_by_rows(
7883 map,
7884 selection.start,
7885 action.lines,
7886 selection.goal,
7887 false,
7888 text_layout_details,
7889 );
7890 selection.collapse_to(cursor, goal);
7891 });
7892 })
7893 }
7894
7895 pub fn move_down_by_lines(
7896 &mut self,
7897 action: &MoveDownByLines,
7898 window: &mut Window,
7899 cx: &mut Context<Self>,
7900 ) {
7901 if self.take_rename(true, window, cx).is_some() {
7902 return;
7903 }
7904
7905 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7906 cx.propagate();
7907 return;
7908 }
7909
7910 let text_layout_details = &self.text_layout_details(window);
7911
7912 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7913 let line_mode = s.line_mode;
7914 s.move_with(|map, selection| {
7915 if !selection.is_empty() && !line_mode {
7916 selection.goal = SelectionGoal::None;
7917 }
7918 let (cursor, goal) = movement::down_by_rows(
7919 map,
7920 selection.start,
7921 action.lines,
7922 selection.goal,
7923 false,
7924 text_layout_details,
7925 );
7926 selection.collapse_to(cursor, goal);
7927 });
7928 })
7929 }
7930
7931 pub fn select_down_by_lines(
7932 &mut self,
7933 action: &SelectDownByLines,
7934 window: &mut Window,
7935 cx: &mut Context<Self>,
7936 ) {
7937 let text_layout_details = &self.text_layout_details(window);
7938 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7939 s.move_heads_with(|map, head, goal| {
7940 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7941 })
7942 })
7943 }
7944
7945 pub fn select_up_by_lines(
7946 &mut self,
7947 action: &SelectUpByLines,
7948 window: &mut Window,
7949 cx: &mut Context<Self>,
7950 ) {
7951 let text_layout_details = &self.text_layout_details(window);
7952 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7953 s.move_heads_with(|map, head, goal| {
7954 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7955 })
7956 })
7957 }
7958
7959 pub fn select_page_up(
7960 &mut self,
7961 _: &SelectPageUp,
7962 window: &mut Window,
7963 cx: &mut Context<Self>,
7964 ) {
7965 let Some(row_count) = self.visible_row_count() else {
7966 return;
7967 };
7968
7969 let text_layout_details = &self.text_layout_details(window);
7970
7971 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7972 s.move_heads_with(|map, head, goal| {
7973 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7974 })
7975 })
7976 }
7977
7978 pub fn move_page_up(
7979 &mut self,
7980 action: &MovePageUp,
7981 window: &mut Window,
7982 cx: &mut Context<Self>,
7983 ) {
7984 if self.take_rename(true, window, cx).is_some() {
7985 return;
7986 }
7987
7988 if self
7989 .context_menu
7990 .borrow_mut()
7991 .as_mut()
7992 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7993 .unwrap_or(false)
7994 {
7995 return;
7996 }
7997
7998 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7999 cx.propagate();
8000 return;
8001 }
8002
8003 let Some(row_count) = self.visible_row_count() else {
8004 return;
8005 };
8006
8007 let autoscroll = if action.center_cursor {
8008 Autoscroll::center()
8009 } else {
8010 Autoscroll::fit()
8011 };
8012
8013 let text_layout_details = &self.text_layout_details(window);
8014
8015 self.change_selections(Some(autoscroll), window, cx, |s| {
8016 let line_mode = s.line_mode;
8017 s.move_with(|map, selection| {
8018 if !selection.is_empty() && !line_mode {
8019 selection.goal = SelectionGoal::None;
8020 }
8021 let (cursor, goal) = movement::up_by_rows(
8022 map,
8023 selection.end,
8024 row_count,
8025 selection.goal,
8026 false,
8027 text_layout_details,
8028 );
8029 selection.collapse_to(cursor, goal);
8030 });
8031 });
8032 }
8033
8034 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8035 let text_layout_details = &self.text_layout_details(window);
8036 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8037 s.move_heads_with(|map, head, goal| {
8038 movement::up(map, head, goal, false, text_layout_details)
8039 })
8040 })
8041 }
8042
8043 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8044 self.take_rename(true, window, cx);
8045
8046 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8047 cx.propagate();
8048 return;
8049 }
8050
8051 let text_layout_details = &self.text_layout_details(window);
8052 let selection_count = self.selections.count();
8053 let first_selection = self.selections.first_anchor();
8054
8055 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8056 let line_mode = s.line_mode;
8057 s.move_with(|map, selection| {
8058 if !selection.is_empty() && !line_mode {
8059 selection.goal = SelectionGoal::None;
8060 }
8061 let (cursor, goal) = movement::down(
8062 map,
8063 selection.end,
8064 selection.goal,
8065 false,
8066 text_layout_details,
8067 );
8068 selection.collapse_to(cursor, goal);
8069 });
8070 });
8071
8072 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8073 {
8074 cx.propagate();
8075 }
8076 }
8077
8078 pub fn select_page_down(
8079 &mut self,
8080 _: &SelectPageDown,
8081 window: &mut Window,
8082 cx: &mut Context<Self>,
8083 ) {
8084 let Some(row_count) = self.visible_row_count() else {
8085 return;
8086 };
8087
8088 let text_layout_details = &self.text_layout_details(window);
8089
8090 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8091 s.move_heads_with(|map, head, goal| {
8092 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8093 })
8094 })
8095 }
8096
8097 pub fn move_page_down(
8098 &mut self,
8099 action: &MovePageDown,
8100 window: &mut Window,
8101 cx: &mut Context<Self>,
8102 ) {
8103 if self.take_rename(true, window, cx).is_some() {
8104 return;
8105 }
8106
8107 if self
8108 .context_menu
8109 .borrow_mut()
8110 .as_mut()
8111 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8112 .unwrap_or(false)
8113 {
8114 return;
8115 }
8116
8117 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8118 cx.propagate();
8119 return;
8120 }
8121
8122 let Some(row_count) = self.visible_row_count() else {
8123 return;
8124 };
8125
8126 let autoscroll = if action.center_cursor {
8127 Autoscroll::center()
8128 } else {
8129 Autoscroll::fit()
8130 };
8131
8132 let text_layout_details = &self.text_layout_details(window);
8133 self.change_selections(Some(autoscroll), window, cx, |s| {
8134 let line_mode = s.line_mode;
8135 s.move_with(|map, selection| {
8136 if !selection.is_empty() && !line_mode {
8137 selection.goal = SelectionGoal::None;
8138 }
8139 let (cursor, goal) = movement::down_by_rows(
8140 map,
8141 selection.end,
8142 row_count,
8143 selection.goal,
8144 false,
8145 text_layout_details,
8146 );
8147 selection.collapse_to(cursor, goal);
8148 });
8149 });
8150 }
8151
8152 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8153 let text_layout_details = &self.text_layout_details(window);
8154 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8155 s.move_heads_with(|map, head, goal| {
8156 movement::down(map, head, goal, false, text_layout_details)
8157 })
8158 });
8159 }
8160
8161 pub fn context_menu_first(
8162 &mut self,
8163 _: &ContextMenuFirst,
8164 _window: &mut Window,
8165 cx: &mut Context<Self>,
8166 ) {
8167 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8168 context_menu.select_first(self.completion_provider.as_deref(), cx);
8169 }
8170 }
8171
8172 pub fn context_menu_prev(
8173 &mut self,
8174 _: &ContextMenuPrev,
8175 _window: &mut Window,
8176 cx: &mut Context<Self>,
8177 ) {
8178 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8179 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8180 }
8181 }
8182
8183 pub fn context_menu_next(
8184 &mut self,
8185 _: &ContextMenuNext,
8186 _window: &mut Window,
8187 cx: &mut Context<Self>,
8188 ) {
8189 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8190 context_menu.select_next(self.completion_provider.as_deref(), cx);
8191 }
8192 }
8193
8194 pub fn context_menu_last(
8195 &mut self,
8196 _: &ContextMenuLast,
8197 _window: &mut Window,
8198 cx: &mut Context<Self>,
8199 ) {
8200 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8201 context_menu.select_last(self.completion_provider.as_deref(), cx);
8202 }
8203 }
8204
8205 pub fn move_to_previous_word_start(
8206 &mut self,
8207 _: &MoveToPreviousWordStart,
8208 window: &mut Window,
8209 cx: &mut Context<Self>,
8210 ) {
8211 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8212 s.move_cursors_with(|map, head, _| {
8213 (
8214 movement::previous_word_start(map, head),
8215 SelectionGoal::None,
8216 )
8217 });
8218 })
8219 }
8220
8221 pub fn move_to_previous_subword_start(
8222 &mut self,
8223 _: &MoveToPreviousSubwordStart,
8224 window: &mut Window,
8225 cx: &mut Context<Self>,
8226 ) {
8227 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8228 s.move_cursors_with(|map, head, _| {
8229 (
8230 movement::previous_subword_start(map, head),
8231 SelectionGoal::None,
8232 )
8233 });
8234 })
8235 }
8236
8237 pub fn select_to_previous_word_start(
8238 &mut self,
8239 _: &SelectToPreviousWordStart,
8240 window: &mut Window,
8241 cx: &mut Context<Self>,
8242 ) {
8243 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8244 s.move_heads_with(|map, head, _| {
8245 (
8246 movement::previous_word_start(map, head),
8247 SelectionGoal::None,
8248 )
8249 });
8250 })
8251 }
8252
8253 pub fn select_to_previous_subword_start(
8254 &mut self,
8255 _: &SelectToPreviousSubwordStart,
8256 window: &mut Window,
8257 cx: &mut Context<Self>,
8258 ) {
8259 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8260 s.move_heads_with(|map, head, _| {
8261 (
8262 movement::previous_subword_start(map, head),
8263 SelectionGoal::None,
8264 )
8265 });
8266 })
8267 }
8268
8269 pub fn delete_to_previous_word_start(
8270 &mut self,
8271 action: &DeleteToPreviousWordStart,
8272 window: &mut Window,
8273 cx: &mut Context<Self>,
8274 ) {
8275 self.transact(window, cx, |this, window, cx| {
8276 this.select_autoclose_pair(window, cx);
8277 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8278 let line_mode = s.line_mode;
8279 s.move_with(|map, selection| {
8280 if selection.is_empty() && !line_mode {
8281 let cursor = if action.ignore_newlines {
8282 movement::previous_word_start(map, selection.head())
8283 } else {
8284 movement::previous_word_start_or_newline(map, selection.head())
8285 };
8286 selection.set_head(cursor, SelectionGoal::None);
8287 }
8288 });
8289 });
8290 this.insert("", window, cx);
8291 });
8292 }
8293
8294 pub fn delete_to_previous_subword_start(
8295 &mut self,
8296 _: &DeleteToPreviousSubwordStart,
8297 window: &mut Window,
8298 cx: &mut Context<Self>,
8299 ) {
8300 self.transact(window, cx, |this, window, cx| {
8301 this.select_autoclose_pair(window, cx);
8302 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8303 let line_mode = s.line_mode;
8304 s.move_with(|map, selection| {
8305 if selection.is_empty() && !line_mode {
8306 let cursor = movement::previous_subword_start(map, selection.head());
8307 selection.set_head(cursor, SelectionGoal::None);
8308 }
8309 });
8310 });
8311 this.insert("", window, cx);
8312 });
8313 }
8314
8315 pub fn move_to_next_word_end(
8316 &mut self,
8317 _: &MoveToNextWordEnd,
8318 window: &mut Window,
8319 cx: &mut Context<Self>,
8320 ) {
8321 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8322 s.move_cursors_with(|map, head, _| {
8323 (movement::next_word_end(map, head), SelectionGoal::None)
8324 });
8325 })
8326 }
8327
8328 pub fn move_to_next_subword_end(
8329 &mut self,
8330 _: &MoveToNextSubwordEnd,
8331 window: &mut Window,
8332 cx: &mut Context<Self>,
8333 ) {
8334 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8335 s.move_cursors_with(|map, head, _| {
8336 (movement::next_subword_end(map, head), SelectionGoal::None)
8337 });
8338 })
8339 }
8340
8341 pub fn select_to_next_word_end(
8342 &mut self,
8343 _: &SelectToNextWordEnd,
8344 window: &mut Window,
8345 cx: &mut Context<Self>,
8346 ) {
8347 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8348 s.move_heads_with(|map, head, _| {
8349 (movement::next_word_end(map, head), SelectionGoal::None)
8350 });
8351 })
8352 }
8353
8354 pub fn select_to_next_subword_end(
8355 &mut self,
8356 _: &SelectToNextSubwordEnd,
8357 window: &mut Window,
8358 cx: &mut Context<Self>,
8359 ) {
8360 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8361 s.move_heads_with(|map, head, _| {
8362 (movement::next_subword_end(map, head), SelectionGoal::None)
8363 });
8364 })
8365 }
8366
8367 pub fn delete_to_next_word_end(
8368 &mut self,
8369 action: &DeleteToNextWordEnd,
8370 window: &mut Window,
8371 cx: &mut Context<Self>,
8372 ) {
8373 self.transact(window, cx, |this, window, cx| {
8374 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8375 let line_mode = s.line_mode;
8376 s.move_with(|map, selection| {
8377 if selection.is_empty() && !line_mode {
8378 let cursor = if action.ignore_newlines {
8379 movement::next_word_end(map, selection.head())
8380 } else {
8381 movement::next_word_end_or_newline(map, selection.head())
8382 };
8383 selection.set_head(cursor, SelectionGoal::None);
8384 }
8385 });
8386 });
8387 this.insert("", window, cx);
8388 });
8389 }
8390
8391 pub fn delete_to_next_subword_end(
8392 &mut self,
8393 _: &DeleteToNextSubwordEnd,
8394 window: &mut Window,
8395 cx: &mut Context<Self>,
8396 ) {
8397 self.transact(window, cx, |this, window, cx| {
8398 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8399 s.move_with(|map, selection| {
8400 if selection.is_empty() {
8401 let cursor = movement::next_subword_end(map, selection.head());
8402 selection.set_head(cursor, SelectionGoal::None);
8403 }
8404 });
8405 });
8406 this.insert("", window, cx);
8407 });
8408 }
8409
8410 pub fn move_to_beginning_of_line(
8411 &mut self,
8412 action: &MoveToBeginningOfLine,
8413 window: &mut Window,
8414 cx: &mut Context<Self>,
8415 ) {
8416 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8417 s.move_cursors_with(|map, head, _| {
8418 (
8419 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8420 SelectionGoal::None,
8421 )
8422 });
8423 })
8424 }
8425
8426 pub fn select_to_beginning_of_line(
8427 &mut self,
8428 action: &SelectToBeginningOfLine,
8429 window: &mut Window,
8430 cx: &mut Context<Self>,
8431 ) {
8432 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8433 s.move_heads_with(|map, head, _| {
8434 (
8435 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8436 SelectionGoal::None,
8437 )
8438 });
8439 });
8440 }
8441
8442 pub fn delete_to_beginning_of_line(
8443 &mut self,
8444 _: &DeleteToBeginningOfLine,
8445 window: &mut Window,
8446 cx: &mut Context<Self>,
8447 ) {
8448 self.transact(window, cx, |this, window, cx| {
8449 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8450 s.move_with(|_, selection| {
8451 selection.reversed = true;
8452 });
8453 });
8454
8455 this.select_to_beginning_of_line(
8456 &SelectToBeginningOfLine {
8457 stop_at_soft_wraps: false,
8458 },
8459 window,
8460 cx,
8461 );
8462 this.backspace(&Backspace, window, cx);
8463 });
8464 }
8465
8466 pub fn move_to_end_of_line(
8467 &mut self,
8468 action: &MoveToEndOfLine,
8469 window: &mut Window,
8470 cx: &mut Context<Self>,
8471 ) {
8472 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8473 s.move_cursors_with(|map, head, _| {
8474 (
8475 movement::line_end(map, head, action.stop_at_soft_wraps),
8476 SelectionGoal::None,
8477 )
8478 });
8479 })
8480 }
8481
8482 pub fn select_to_end_of_line(
8483 &mut self,
8484 action: &SelectToEndOfLine,
8485 window: &mut Window,
8486 cx: &mut Context<Self>,
8487 ) {
8488 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8489 s.move_heads_with(|map, head, _| {
8490 (
8491 movement::line_end(map, head, action.stop_at_soft_wraps),
8492 SelectionGoal::None,
8493 )
8494 });
8495 })
8496 }
8497
8498 pub fn delete_to_end_of_line(
8499 &mut self,
8500 _: &DeleteToEndOfLine,
8501 window: &mut Window,
8502 cx: &mut Context<Self>,
8503 ) {
8504 self.transact(window, cx, |this, window, cx| {
8505 this.select_to_end_of_line(
8506 &SelectToEndOfLine {
8507 stop_at_soft_wraps: false,
8508 },
8509 window,
8510 cx,
8511 );
8512 this.delete(&Delete, window, cx);
8513 });
8514 }
8515
8516 pub fn cut_to_end_of_line(
8517 &mut self,
8518 _: &CutToEndOfLine,
8519 window: &mut Window,
8520 cx: &mut Context<Self>,
8521 ) {
8522 self.transact(window, cx, |this, window, cx| {
8523 this.select_to_end_of_line(
8524 &SelectToEndOfLine {
8525 stop_at_soft_wraps: false,
8526 },
8527 window,
8528 cx,
8529 );
8530 this.cut(&Cut, window, cx);
8531 });
8532 }
8533
8534 pub fn move_to_start_of_paragraph(
8535 &mut self,
8536 _: &MoveToStartOfParagraph,
8537 window: &mut Window,
8538 cx: &mut Context<Self>,
8539 ) {
8540 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8541 cx.propagate();
8542 return;
8543 }
8544
8545 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8546 s.move_with(|map, selection| {
8547 selection.collapse_to(
8548 movement::start_of_paragraph(map, selection.head(), 1),
8549 SelectionGoal::None,
8550 )
8551 });
8552 })
8553 }
8554
8555 pub fn move_to_end_of_paragraph(
8556 &mut self,
8557 _: &MoveToEndOfParagraph,
8558 window: &mut Window,
8559 cx: &mut Context<Self>,
8560 ) {
8561 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8562 cx.propagate();
8563 return;
8564 }
8565
8566 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8567 s.move_with(|map, selection| {
8568 selection.collapse_to(
8569 movement::end_of_paragraph(map, selection.head(), 1),
8570 SelectionGoal::None,
8571 )
8572 });
8573 })
8574 }
8575
8576 pub fn select_to_start_of_paragraph(
8577 &mut self,
8578 _: &SelectToStartOfParagraph,
8579 window: &mut Window,
8580 cx: &mut Context<Self>,
8581 ) {
8582 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8583 cx.propagate();
8584 return;
8585 }
8586
8587 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8588 s.move_heads_with(|map, head, _| {
8589 (
8590 movement::start_of_paragraph(map, head, 1),
8591 SelectionGoal::None,
8592 )
8593 });
8594 })
8595 }
8596
8597 pub fn select_to_end_of_paragraph(
8598 &mut self,
8599 _: &SelectToEndOfParagraph,
8600 window: &mut Window,
8601 cx: &mut Context<Self>,
8602 ) {
8603 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8604 cx.propagate();
8605 return;
8606 }
8607
8608 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8609 s.move_heads_with(|map, head, _| {
8610 (
8611 movement::end_of_paragraph(map, head, 1),
8612 SelectionGoal::None,
8613 )
8614 });
8615 })
8616 }
8617
8618 pub fn move_to_beginning(
8619 &mut self,
8620 _: &MoveToBeginning,
8621 window: &mut Window,
8622 cx: &mut Context<Self>,
8623 ) {
8624 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8625 cx.propagate();
8626 return;
8627 }
8628
8629 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8630 s.select_ranges(vec![0..0]);
8631 });
8632 }
8633
8634 pub fn select_to_beginning(
8635 &mut self,
8636 _: &SelectToBeginning,
8637 window: &mut Window,
8638 cx: &mut Context<Self>,
8639 ) {
8640 let mut selection = self.selections.last::<Point>(cx);
8641 selection.set_head(Point::zero(), SelectionGoal::None);
8642
8643 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8644 s.select(vec![selection]);
8645 });
8646 }
8647
8648 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
8649 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8650 cx.propagate();
8651 return;
8652 }
8653
8654 let cursor = self.buffer.read(cx).read(cx).len();
8655 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8656 s.select_ranges(vec![cursor..cursor])
8657 });
8658 }
8659
8660 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8661 self.nav_history = nav_history;
8662 }
8663
8664 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8665 self.nav_history.as_ref()
8666 }
8667
8668 fn push_to_nav_history(
8669 &mut self,
8670 cursor_anchor: Anchor,
8671 new_position: Option<Point>,
8672 cx: &mut Context<Self>,
8673 ) {
8674 if let Some(nav_history) = self.nav_history.as_mut() {
8675 let buffer = self.buffer.read(cx).read(cx);
8676 let cursor_position = cursor_anchor.to_point(&buffer);
8677 let scroll_state = self.scroll_manager.anchor();
8678 let scroll_top_row = scroll_state.top_row(&buffer);
8679 drop(buffer);
8680
8681 if let Some(new_position) = new_position {
8682 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8683 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8684 return;
8685 }
8686 }
8687
8688 nav_history.push(
8689 Some(NavigationData {
8690 cursor_anchor,
8691 cursor_position,
8692 scroll_anchor: scroll_state,
8693 scroll_top_row,
8694 }),
8695 cx,
8696 );
8697 }
8698 }
8699
8700 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
8701 let buffer = self.buffer.read(cx).snapshot(cx);
8702 let mut selection = self.selections.first::<usize>(cx);
8703 selection.set_head(buffer.len(), SelectionGoal::None);
8704 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8705 s.select(vec![selection]);
8706 });
8707 }
8708
8709 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
8710 let end = self.buffer.read(cx).read(cx).len();
8711 self.change_selections(None, window, cx, |s| {
8712 s.select_ranges(vec![0..end]);
8713 });
8714 }
8715
8716 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
8717 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8718 let mut selections = self.selections.all::<Point>(cx);
8719 let max_point = display_map.buffer_snapshot.max_point();
8720 for selection in &mut selections {
8721 let rows = selection.spanned_rows(true, &display_map);
8722 selection.start = Point::new(rows.start.0, 0);
8723 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8724 selection.reversed = false;
8725 }
8726 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8727 s.select(selections);
8728 });
8729 }
8730
8731 pub fn split_selection_into_lines(
8732 &mut self,
8733 _: &SplitSelectionIntoLines,
8734 window: &mut Window,
8735 cx: &mut Context<Self>,
8736 ) {
8737 let mut to_unfold = Vec::new();
8738 let mut new_selection_ranges = Vec::new();
8739 {
8740 let selections = self.selections.all::<Point>(cx);
8741 let buffer = self.buffer.read(cx).read(cx);
8742 for selection in selections {
8743 for row in selection.start.row..selection.end.row {
8744 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8745 new_selection_ranges.push(cursor..cursor);
8746 }
8747 new_selection_ranges.push(selection.end..selection.end);
8748 to_unfold.push(selection.start..selection.end);
8749 }
8750 }
8751 self.unfold_ranges(&to_unfold, true, true, cx);
8752 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8753 s.select_ranges(new_selection_ranges);
8754 });
8755 }
8756
8757 pub fn add_selection_above(
8758 &mut self,
8759 _: &AddSelectionAbove,
8760 window: &mut Window,
8761 cx: &mut Context<Self>,
8762 ) {
8763 self.add_selection(true, window, cx);
8764 }
8765
8766 pub fn add_selection_below(
8767 &mut self,
8768 _: &AddSelectionBelow,
8769 window: &mut Window,
8770 cx: &mut Context<Self>,
8771 ) {
8772 self.add_selection(false, window, cx);
8773 }
8774
8775 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
8776 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8777 let mut selections = self.selections.all::<Point>(cx);
8778 let text_layout_details = self.text_layout_details(window);
8779 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8780 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8781 let range = oldest_selection.display_range(&display_map).sorted();
8782
8783 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8784 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8785 let positions = start_x.min(end_x)..start_x.max(end_x);
8786
8787 selections.clear();
8788 let mut stack = Vec::new();
8789 for row in range.start.row().0..=range.end.row().0 {
8790 if let Some(selection) = self.selections.build_columnar_selection(
8791 &display_map,
8792 DisplayRow(row),
8793 &positions,
8794 oldest_selection.reversed,
8795 &text_layout_details,
8796 ) {
8797 stack.push(selection.id);
8798 selections.push(selection);
8799 }
8800 }
8801
8802 if above {
8803 stack.reverse();
8804 }
8805
8806 AddSelectionsState { above, stack }
8807 });
8808
8809 let last_added_selection = *state.stack.last().unwrap();
8810 let mut new_selections = Vec::new();
8811 if above == state.above {
8812 let end_row = if above {
8813 DisplayRow(0)
8814 } else {
8815 display_map.max_point().row()
8816 };
8817
8818 'outer: for selection in selections {
8819 if selection.id == last_added_selection {
8820 let range = selection.display_range(&display_map).sorted();
8821 debug_assert_eq!(range.start.row(), range.end.row());
8822 let mut row = range.start.row();
8823 let positions =
8824 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8825 px(start)..px(end)
8826 } else {
8827 let start_x =
8828 display_map.x_for_display_point(range.start, &text_layout_details);
8829 let end_x =
8830 display_map.x_for_display_point(range.end, &text_layout_details);
8831 start_x.min(end_x)..start_x.max(end_x)
8832 };
8833
8834 while row != end_row {
8835 if above {
8836 row.0 -= 1;
8837 } else {
8838 row.0 += 1;
8839 }
8840
8841 if let Some(new_selection) = self.selections.build_columnar_selection(
8842 &display_map,
8843 row,
8844 &positions,
8845 selection.reversed,
8846 &text_layout_details,
8847 ) {
8848 state.stack.push(new_selection.id);
8849 if above {
8850 new_selections.push(new_selection);
8851 new_selections.push(selection);
8852 } else {
8853 new_selections.push(selection);
8854 new_selections.push(new_selection);
8855 }
8856
8857 continue 'outer;
8858 }
8859 }
8860 }
8861
8862 new_selections.push(selection);
8863 }
8864 } else {
8865 new_selections = selections;
8866 new_selections.retain(|s| s.id != last_added_selection);
8867 state.stack.pop();
8868 }
8869
8870 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8871 s.select(new_selections);
8872 });
8873 if state.stack.len() > 1 {
8874 self.add_selections_state = Some(state);
8875 }
8876 }
8877
8878 pub fn select_next_match_internal(
8879 &mut self,
8880 display_map: &DisplaySnapshot,
8881 replace_newest: bool,
8882 autoscroll: Option<Autoscroll>,
8883 window: &mut Window,
8884 cx: &mut Context<Self>,
8885 ) -> Result<()> {
8886 fn select_next_match_ranges(
8887 this: &mut Editor,
8888 range: Range<usize>,
8889 replace_newest: bool,
8890 auto_scroll: Option<Autoscroll>,
8891 window: &mut Window,
8892 cx: &mut Context<Editor>,
8893 ) {
8894 this.unfold_ranges(&[range.clone()], false, true, cx);
8895 this.change_selections(auto_scroll, window, cx, |s| {
8896 if replace_newest {
8897 s.delete(s.newest_anchor().id);
8898 }
8899 s.insert_range(range.clone());
8900 });
8901 }
8902
8903 let buffer = &display_map.buffer_snapshot;
8904 let mut selections = self.selections.all::<usize>(cx);
8905 if let Some(mut select_next_state) = self.select_next_state.take() {
8906 let query = &select_next_state.query;
8907 if !select_next_state.done {
8908 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8909 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8910 let mut next_selected_range = None;
8911
8912 let bytes_after_last_selection =
8913 buffer.bytes_in_range(last_selection.end..buffer.len());
8914 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8915 let query_matches = query
8916 .stream_find_iter(bytes_after_last_selection)
8917 .map(|result| (last_selection.end, result))
8918 .chain(
8919 query
8920 .stream_find_iter(bytes_before_first_selection)
8921 .map(|result| (0, result)),
8922 );
8923
8924 for (start_offset, query_match) in query_matches {
8925 let query_match = query_match.unwrap(); // can only fail due to I/O
8926 let offset_range =
8927 start_offset + query_match.start()..start_offset + query_match.end();
8928 let display_range = offset_range.start.to_display_point(display_map)
8929 ..offset_range.end.to_display_point(display_map);
8930
8931 if !select_next_state.wordwise
8932 || (!movement::is_inside_word(display_map, display_range.start)
8933 && !movement::is_inside_word(display_map, display_range.end))
8934 {
8935 // TODO: This is n^2, because we might check all the selections
8936 if !selections
8937 .iter()
8938 .any(|selection| selection.range().overlaps(&offset_range))
8939 {
8940 next_selected_range = Some(offset_range);
8941 break;
8942 }
8943 }
8944 }
8945
8946 if let Some(next_selected_range) = next_selected_range {
8947 select_next_match_ranges(
8948 self,
8949 next_selected_range,
8950 replace_newest,
8951 autoscroll,
8952 window,
8953 cx,
8954 );
8955 } else {
8956 select_next_state.done = true;
8957 }
8958 }
8959
8960 self.select_next_state = Some(select_next_state);
8961 } else {
8962 let mut only_carets = true;
8963 let mut same_text_selected = true;
8964 let mut selected_text = None;
8965
8966 let mut selections_iter = selections.iter().peekable();
8967 while let Some(selection) = selections_iter.next() {
8968 if selection.start != selection.end {
8969 only_carets = false;
8970 }
8971
8972 if same_text_selected {
8973 if selected_text.is_none() {
8974 selected_text =
8975 Some(buffer.text_for_range(selection.range()).collect::<String>());
8976 }
8977
8978 if let Some(next_selection) = selections_iter.peek() {
8979 if next_selection.range().len() == selection.range().len() {
8980 let next_selected_text = buffer
8981 .text_for_range(next_selection.range())
8982 .collect::<String>();
8983 if Some(next_selected_text) != selected_text {
8984 same_text_selected = false;
8985 selected_text = None;
8986 }
8987 } else {
8988 same_text_selected = false;
8989 selected_text = None;
8990 }
8991 }
8992 }
8993 }
8994
8995 if only_carets {
8996 for selection in &mut selections {
8997 let word_range = movement::surrounding_word(
8998 display_map,
8999 selection.start.to_display_point(display_map),
9000 );
9001 selection.start = word_range.start.to_offset(display_map, Bias::Left);
9002 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9003 selection.goal = SelectionGoal::None;
9004 selection.reversed = false;
9005 select_next_match_ranges(
9006 self,
9007 selection.start..selection.end,
9008 replace_newest,
9009 autoscroll,
9010 window,
9011 cx,
9012 );
9013 }
9014
9015 if selections.len() == 1 {
9016 let selection = selections
9017 .last()
9018 .expect("ensured that there's only one selection");
9019 let query = buffer
9020 .text_for_range(selection.start..selection.end)
9021 .collect::<String>();
9022 let is_empty = query.is_empty();
9023 let select_state = SelectNextState {
9024 query: AhoCorasick::new(&[query])?,
9025 wordwise: true,
9026 done: is_empty,
9027 };
9028 self.select_next_state = Some(select_state);
9029 } else {
9030 self.select_next_state = None;
9031 }
9032 } else if let Some(selected_text) = selected_text {
9033 self.select_next_state = Some(SelectNextState {
9034 query: AhoCorasick::new(&[selected_text])?,
9035 wordwise: false,
9036 done: false,
9037 });
9038 self.select_next_match_internal(
9039 display_map,
9040 replace_newest,
9041 autoscroll,
9042 window,
9043 cx,
9044 )?;
9045 }
9046 }
9047 Ok(())
9048 }
9049
9050 pub fn select_all_matches(
9051 &mut self,
9052 _action: &SelectAllMatches,
9053 window: &mut Window,
9054 cx: &mut Context<Self>,
9055 ) -> Result<()> {
9056 self.push_to_selection_history();
9057 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9058
9059 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9060 let Some(select_next_state) = self.select_next_state.as_mut() else {
9061 return Ok(());
9062 };
9063 if select_next_state.done {
9064 return Ok(());
9065 }
9066
9067 let mut new_selections = self.selections.all::<usize>(cx);
9068
9069 let buffer = &display_map.buffer_snapshot;
9070 let query_matches = select_next_state
9071 .query
9072 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9073
9074 for query_match in query_matches {
9075 let query_match = query_match.unwrap(); // can only fail due to I/O
9076 let offset_range = query_match.start()..query_match.end();
9077 let display_range = offset_range.start.to_display_point(&display_map)
9078 ..offset_range.end.to_display_point(&display_map);
9079
9080 if !select_next_state.wordwise
9081 || (!movement::is_inside_word(&display_map, display_range.start)
9082 && !movement::is_inside_word(&display_map, display_range.end))
9083 {
9084 self.selections.change_with(cx, |selections| {
9085 new_selections.push(Selection {
9086 id: selections.new_selection_id(),
9087 start: offset_range.start,
9088 end: offset_range.end,
9089 reversed: false,
9090 goal: SelectionGoal::None,
9091 });
9092 });
9093 }
9094 }
9095
9096 new_selections.sort_by_key(|selection| selection.start);
9097 let mut ix = 0;
9098 while ix + 1 < new_selections.len() {
9099 let current_selection = &new_selections[ix];
9100 let next_selection = &new_selections[ix + 1];
9101 if current_selection.range().overlaps(&next_selection.range()) {
9102 if current_selection.id < next_selection.id {
9103 new_selections.remove(ix + 1);
9104 } else {
9105 new_selections.remove(ix);
9106 }
9107 } else {
9108 ix += 1;
9109 }
9110 }
9111
9112 let reversed = self.selections.oldest::<usize>(cx).reversed;
9113
9114 for selection in new_selections.iter_mut() {
9115 selection.reversed = reversed;
9116 }
9117
9118 select_next_state.done = true;
9119 self.unfold_ranges(
9120 &new_selections
9121 .iter()
9122 .map(|selection| selection.range())
9123 .collect::<Vec<_>>(),
9124 false,
9125 false,
9126 cx,
9127 );
9128 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9129 selections.select(new_selections)
9130 });
9131
9132 Ok(())
9133 }
9134
9135 pub fn select_next(
9136 &mut self,
9137 action: &SelectNext,
9138 window: &mut Window,
9139 cx: &mut Context<Self>,
9140 ) -> Result<()> {
9141 self.push_to_selection_history();
9142 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9143 self.select_next_match_internal(
9144 &display_map,
9145 action.replace_newest,
9146 Some(Autoscroll::newest()),
9147 window,
9148 cx,
9149 )?;
9150 Ok(())
9151 }
9152
9153 pub fn select_previous(
9154 &mut self,
9155 action: &SelectPrevious,
9156 window: &mut Window,
9157 cx: &mut Context<Self>,
9158 ) -> Result<()> {
9159 self.push_to_selection_history();
9160 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9161 let buffer = &display_map.buffer_snapshot;
9162 let mut selections = self.selections.all::<usize>(cx);
9163 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9164 let query = &select_prev_state.query;
9165 if !select_prev_state.done {
9166 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9167 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9168 let mut next_selected_range = None;
9169 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9170 let bytes_before_last_selection =
9171 buffer.reversed_bytes_in_range(0..last_selection.start);
9172 let bytes_after_first_selection =
9173 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9174 let query_matches = query
9175 .stream_find_iter(bytes_before_last_selection)
9176 .map(|result| (last_selection.start, result))
9177 .chain(
9178 query
9179 .stream_find_iter(bytes_after_first_selection)
9180 .map(|result| (buffer.len(), result)),
9181 );
9182 for (end_offset, query_match) in query_matches {
9183 let query_match = query_match.unwrap(); // can only fail due to I/O
9184 let offset_range =
9185 end_offset - query_match.end()..end_offset - query_match.start();
9186 let display_range = offset_range.start.to_display_point(&display_map)
9187 ..offset_range.end.to_display_point(&display_map);
9188
9189 if !select_prev_state.wordwise
9190 || (!movement::is_inside_word(&display_map, display_range.start)
9191 && !movement::is_inside_word(&display_map, display_range.end))
9192 {
9193 next_selected_range = Some(offset_range);
9194 break;
9195 }
9196 }
9197
9198 if let Some(next_selected_range) = next_selected_range {
9199 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9200 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9201 if action.replace_newest {
9202 s.delete(s.newest_anchor().id);
9203 }
9204 s.insert_range(next_selected_range);
9205 });
9206 } else {
9207 select_prev_state.done = true;
9208 }
9209 }
9210
9211 self.select_prev_state = Some(select_prev_state);
9212 } else {
9213 let mut only_carets = true;
9214 let mut same_text_selected = true;
9215 let mut selected_text = None;
9216
9217 let mut selections_iter = selections.iter().peekable();
9218 while let Some(selection) = selections_iter.next() {
9219 if selection.start != selection.end {
9220 only_carets = false;
9221 }
9222
9223 if same_text_selected {
9224 if selected_text.is_none() {
9225 selected_text =
9226 Some(buffer.text_for_range(selection.range()).collect::<String>());
9227 }
9228
9229 if let Some(next_selection) = selections_iter.peek() {
9230 if next_selection.range().len() == selection.range().len() {
9231 let next_selected_text = buffer
9232 .text_for_range(next_selection.range())
9233 .collect::<String>();
9234 if Some(next_selected_text) != selected_text {
9235 same_text_selected = false;
9236 selected_text = None;
9237 }
9238 } else {
9239 same_text_selected = false;
9240 selected_text = None;
9241 }
9242 }
9243 }
9244 }
9245
9246 if only_carets {
9247 for selection in &mut selections {
9248 let word_range = movement::surrounding_word(
9249 &display_map,
9250 selection.start.to_display_point(&display_map),
9251 );
9252 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9253 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9254 selection.goal = SelectionGoal::None;
9255 selection.reversed = false;
9256 }
9257 if selections.len() == 1 {
9258 let selection = selections
9259 .last()
9260 .expect("ensured that there's only one selection");
9261 let query = buffer
9262 .text_for_range(selection.start..selection.end)
9263 .collect::<String>();
9264 let is_empty = query.is_empty();
9265 let select_state = SelectNextState {
9266 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9267 wordwise: true,
9268 done: is_empty,
9269 };
9270 self.select_prev_state = Some(select_state);
9271 } else {
9272 self.select_prev_state = None;
9273 }
9274
9275 self.unfold_ranges(
9276 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9277 false,
9278 true,
9279 cx,
9280 );
9281 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9282 s.select(selections);
9283 });
9284 } else if let Some(selected_text) = selected_text {
9285 self.select_prev_state = Some(SelectNextState {
9286 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9287 wordwise: false,
9288 done: false,
9289 });
9290 self.select_previous(action, window, cx)?;
9291 }
9292 }
9293 Ok(())
9294 }
9295
9296 pub fn toggle_comments(
9297 &mut self,
9298 action: &ToggleComments,
9299 window: &mut Window,
9300 cx: &mut Context<Self>,
9301 ) {
9302 if self.read_only(cx) {
9303 return;
9304 }
9305 let text_layout_details = &self.text_layout_details(window);
9306 self.transact(window, cx, |this, window, cx| {
9307 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9308 let mut edits = Vec::new();
9309 let mut selection_edit_ranges = Vec::new();
9310 let mut last_toggled_row = None;
9311 let snapshot = this.buffer.read(cx).read(cx);
9312 let empty_str: Arc<str> = Arc::default();
9313 let mut suffixes_inserted = Vec::new();
9314 let ignore_indent = action.ignore_indent;
9315
9316 fn comment_prefix_range(
9317 snapshot: &MultiBufferSnapshot,
9318 row: MultiBufferRow,
9319 comment_prefix: &str,
9320 comment_prefix_whitespace: &str,
9321 ignore_indent: bool,
9322 ) -> Range<Point> {
9323 let indent_size = if ignore_indent {
9324 0
9325 } else {
9326 snapshot.indent_size_for_line(row).len
9327 };
9328
9329 let start = Point::new(row.0, indent_size);
9330
9331 let mut line_bytes = snapshot
9332 .bytes_in_range(start..snapshot.max_point())
9333 .flatten()
9334 .copied();
9335
9336 // If this line currently begins with the line comment prefix, then record
9337 // the range containing the prefix.
9338 if line_bytes
9339 .by_ref()
9340 .take(comment_prefix.len())
9341 .eq(comment_prefix.bytes())
9342 {
9343 // Include any whitespace that matches the comment prefix.
9344 let matching_whitespace_len = line_bytes
9345 .zip(comment_prefix_whitespace.bytes())
9346 .take_while(|(a, b)| a == b)
9347 .count() as u32;
9348 let end = Point::new(
9349 start.row,
9350 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9351 );
9352 start..end
9353 } else {
9354 start..start
9355 }
9356 }
9357
9358 fn comment_suffix_range(
9359 snapshot: &MultiBufferSnapshot,
9360 row: MultiBufferRow,
9361 comment_suffix: &str,
9362 comment_suffix_has_leading_space: bool,
9363 ) -> Range<Point> {
9364 let end = Point::new(row.0, snapshot.line_len(row));
9365 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9366
9367 let mut line_end_bytes = snapshot
9368 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9369 .flatten()
9370 .copied();
9371
9372 let leading_space_len = if suffix_start_column > 0
9373 && line_end_bytes.next() == Some(b' ')
9374 && comment_suffix_has_leading_space
9375 {
9376 1
9377 } else {
9378 0
9379 };
9380
9381 // If this line currently begins with the line comment prefix, then record
9382 // the range containing the prefix.
9383 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9384 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9385 start..end
9386 } else {
9387 end..end
9388 }
9389 }
9390
9391 // TODO: Handle selections that cross excerpts
9392 for selection in &mut selections {
9393 let start_column = snapshot
9394 .indent_size_for_line(MultiBufferRow(selection.start.row))
9395 .len;
9396 let language = if let Some(language) =
9397 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9398 {
9399 language
9400 } else {
9401 continue;
9402 };
9403
9404 selection_edit_ranges.clear();
9405
9406 // If multiple selections contain a given row, avoid processing that
9407 // row more than once.
9408 let mut start_row = MultiBufferRow(selection.start.row);
9409 if last_toggled_row == Some(start_row) {
9410 start_row = start_row.next_row();
9411 }
9412 let end_row =
9413 if selection.end.row > selection.start.row && selection.end.column == 0 {
9414 MultiBufferRow(selection.end.row - 1)
9415 } else {
9416 MultiBufferRow(selection.end.row)
9417 };
9418 last_toggled_row = Some(end_row);
9419
9420 if start_row > end_row {
9421 continue;
9422 }
9423
9424 // If the language has line comments, toggle those.
9425 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9426
9427 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9428 if ignore_indent {
9429 full_comment_prefixes = full_comment_prefixes
9430 .into_iter()
9431 .map(|s| Arc::from(s.trim_end()))
9432 .collect();
9433 }
9434
9435 if !full_comment_prefixes.is_empty() {
9436 let first_prefix = full_comment_prefixes
9437 .first()
9438 .expect("prefixes is non-empty");
9439 let prefix_trimmed_lengths = full_comment_prefixes
9440 .iter()
9441 .map(|p| p.trim_end_matches(' ').len())
9442 .collect::<SmallVec<[usize; 4]>>();
9443
9444 let mut all_selection_lines_are_comments = true;
9445
9446 for row in start_row.0..=end_row.0 {
9447 let row = MultiBufferRow(row);
9448 if start_row < end_row && snapshot.is_line_blank(row) {
9449 continue;
9450 }
9451
9452 let prefix_range = full_comment_prefixes
9453 .iter()
9454 .zip(prefix_trimmed_lengths.iter().copied())
9455 .map(|(prefix, trimmed_prefix_len)| {
9456 comment_prefix_range(
9457 snapshot.deref(),
9458 row,
9459 &prefix[..trimmed_prefix_len],
9460 &prefix[trimmed_prefix_len..],
9461 ignore_indent,
9462 )
9463 })
9464 .max_by_key(|range| range.end.column - range.start.column)
9465 .expect("prefixes is non-empty");
9466
9467 if prefix_range.is_empty() {
9468 all_selection_lines_are_comments = false;
9469 }
9470
9471 selection_edit_ranges.push(prefix_range);
9472 }
9473
9474 if all_selection_lines_are_comments {
9475 edits.extend(
9476 selection_edit_ranges
9477 .iter()
9478 .cloned()
9479 .map(|range| (range, empty_str.clone())),
9480 );
9481 } else {
9482 let min_column = selection_edit_ranges
9483 .iter()
9484 .map(|range| range.start.column)
9485 .min()
9486 .unwrap_or(0);
9487 edits.extend(selection_edit_ranges.iter().map(|range| {
9488 let position = Point::new(range.start.row, min_column);
9489 (position..position, first_prefix.clone())
9490 }));
9491 }
9492 } else if let Some((full_comment_prefix, comment_suffix)) =
9493 language.block_comment_delimiters()
9494 {
9495 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9496 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9497 let prefix_range = comment_prefix_range(
9498 snapshot.deref(),
9499 start_row,
9500 comment_prefix,
9501 comment_prefix_whitespace,
9502 ignore_indent,
9503 );
9504 let suffix_range = comment_suffix_range(
9505 snapshot.deref(),
9506 end_row,
9507 comment_suffix.trim_start_matches(' '),
9508 comment_suffix.starts_with(' '),
9509 );
9510
9511 if prefix_range.is_empty() || suffix_range.is_empty() {
9512 edits.push((
9513 prefix_range.start..prefix_range.start,
9514 full_comment_prefix.clone(),
9515 ));
9516 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9517 suffixes_inserted.push((end_row, comment_suffix.len()));
9518 } else {
9519 edits.push((prefix_range, empty_str.clone()));
9520 edits.push((suffix_range, empty_str.clone()));
9521 }
9522 } else {
9523 continue;
9524 }
9525 }
9526
9527 drop(snapshot);
9528 this.buffer.update(cx, |buffer, cx| {
9529 buffer.edit(edits, None, cx);
9530 });
9531
9532 // Adjust selections so that they end before any comment suffixes that
9533 // were inserted.
9534 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9535 let mut selections = this.selections.all::<Point>(cx);
9536 let snapshot = this.buffer.read(cx).read(cx);
9537 for selection in &mut selections {
9538 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9539 match row.cmp(&MultiBufferRow(selection.end.row)) {
9540 Ordering::Less => {
9541 suffixes_inserted.next();
9542 continue;
9543 }
9544 Ordering::Greater => break,
9545 Ordering::Equal => {
9546 if selection.end.column == snapshot.line_len(row) {
9547 if selection.is_empty() {
9548 selection.start.column -= suffix_len as u32;
9549 }
9550 selection.end.column -= suffix_len as u32;
9551 }
9552 break;
9553 }
9554 }
9555 }
9556 }
9557
9558 drop(snapshot);
9559 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9560 s.select(selections)
9561 });
9562
9563 let selections = this.selections.all::<Point>(cx);
9564 let selections_on_single_row = selections.windows(2).all(|selections| {
9565 selections[0].start.row == selections[1].start.row
9566 && selections[0].end.row == selections[1].end.row
9567 && selections[0].start.row == selections[0].end.row
9568 });
9569 let selections_selecting = selections
9570 .iter()
9571 .any(|selection| selection.start != selection.end);
9572 let advance_downwards = action.advance_downwards
9573 && selections_on_single_row
9574 && !selections_selecting
9575 && !matches!(this.mode, EditorMode::SingleLine { .. });
9576
9577 if advance_downwards {
9578 let snapshot = this.buffer.read(cx).snapshot(cx);
9579
9580 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9581 s.move_cursors_with(|display_snapshot, display_point, _| {
9582 let mut point = display_point.to_point(display_snapshot);
9583 point.row += 1;
9584 point = snapshot.clip_point(point, Bias::Left);
9585 let display_point = point.to_display_point(display_snapshot);
9586 let goal = SelectionGoal::HorizontalPosition(
9587 display_snapshot
9588 .x_for_display_point(display_point, text_layout_details)
9589 .into(),
9590 );
9591 (display_point, goal)
9592 })
9593 });
9594 }
9595 });
9596 }
9597
9598 pub fn select_enclosing_symbol(
9599 &mut self,
9600 _: &SelectEnclosingSymbol,
9601 window: &mut Window,
9602 cx: &mut Context<Self>,
9603 ) {
9604 let buffer = self.buffer.read(cx).snapshot(cx);
9605 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9606
9607 fn update_selection(
9608 selection: &Selection<usize>,
9609 buffer_snap: &MultiBufferSnapshot,
9610 ) -> Option<Selection<usize>> {
9611 let cursor = selection.head();
9612 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9613 for symbol in symbols.iter().rev() {
9614 let start = symbol.range.start.to_offset(buffer_snap);
9615 let end = symbol.range.end.to_offset(buffer_snap);
9616 let new_range = start..end;
9617 if start < selection.start || end > selection.end {
9618 return Some(Selection {
9619 id: selection.id,
9620 start: new_range.start,
9621 end: new_range.end,
9622 goal: SelectionGoal::None,
9623 reversed: selection.reversed,
9624 });
9625 }
9626 }
9627 None
9628 }
9629
9630 let mut selected_larger_symbol = false;
9631 let new_selections = old_selections
9632 .iter()
9633 .map(|selection| match update_selection(selection, &buffer) {
9634 Some(new_selection) => {
9635 if new_selection.range() != selection.range() {
9636 selected_larger_symbol = true;
9637 }
9638 new_selection
9639 }
9640 None => selection.clone(),
9641 })
9642 .collect::<Vec<_>>();
9643
9644 if selected_larger_symbol {
9645 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9646 s.select(new_selections);
9647 });
9648 }
9649 }
9650
9651 pub fn select_larger_syntax_node(
9652 &mut self,
9653 _: &SelectLargerSyntaxNode,
9654 window: &mut Window,
9655 cx: &mut Context<Self>,
9656 ) {
9657 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9658 let buffer = self.buffer.read(cx).snapshot(cx);
9659 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9660
9661 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9662 let mut selected_larger_node = false;
9663 let new_selections = old_selections
9664 .iter()
9665 .map(|selection| {
9666 let old_range = selection.start..selection.end;
9667 let mut new_range = old_range.clone();
9668 let mut new_node = None;
9669 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
9670 {
9671 new_node = Some(node);
9672 new_range = containing_range;
9673 if !display_map.intersects_fold(new_range.start)
9674 && !display_map.intersects_fold(new_range.end)
9675 {
9676 break;
9677 }
9678 }
9679
9680 if let Some(node) = new_node {
9681 // Log the ancestor, to support using this action as a way to explore TreeSitter
9682 // nodes. Parent and grandparent are also logged because this operation will not
9683 // visit nodes that have the same range as their parent.
9684 log::info!("Node: {node:?}");
9685 let parent = node.parent();
9686 log::info!("Parent: {parent:?}");
9687 let grandparent = parent.and_then(|x| x.parent());
9688 log::info!("Grandparent: {grandparent:?}");
9689 }
9690
9691 selected_larger_node |= new_range != old_range;
9692 Selection {
9693 id: selection.id,
9694 start: new_range.start,
9695 end: new_range.end,
9696 goal: SelectionGoal::None,
9697 reversed: selection.reversed,
9698 }
9699 })
9700 .collect::<Vec<_>>();
9701
9702 if selected_larger_node {
9703 stack.push(old_selections);
9704 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9705 s.select(new_selections);
9706 });
9707 }
9708 self.select_larger_syntax_node_stack = stack;
9709 }
9710
9711 pub fn select_smaller_syntax_node(
9712 &mut self,
9713 _: &SelectSmallerSyntaxNode,
9714 window: &mut Window,
9715 cx: &mut Context<Self>,
9716 ) {
9717 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9718 if let Some(selections) = stack.pop() {
9719 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9720 s.select(selections.to_vec());
9721 });
9722 }
9723 self.select_larger_syntax_node_stack = stack;
9724 }
9725
9726 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
9727 if !EditorSettings::get_global(cx).gutter.runnables {
9728 self.clear_tasks();
9729 return Task::ready(());
9730 }
9731 let project = self.project.as_ref().map(Entity::downgrade);
9732 cx.spawn_in(window, |this, mut cx| async move {
9733 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
9734 let Some(project) = project.and_then(|p| p.upgrade()) else {
9735 return;
9736 };
9737 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9738 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9739 }) else {
9740 return;
9741 };
9742
9743 let hide_runnables = project
9744 .update(&mut cx, |project, cx| {
9745 // Do not display any test indicators in non-dev server remote projects.
9746 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9747 })
9748 .unwrap_or(true);
9749 if hide_runnables {
9750 return;
9751 }
9752 let new_rows =
9753 cx.background_executor()
9754 .spawn({
9755 let snapshot = display_snapshot.clone();
9756 async move {
9757 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9758 }
9759 })
9760 .await;
9761
9762 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9763 this.update(&mut cx, |this, _| {
9764 this.clear_tasks();
9765 for (key, value) in rows {
9766 this.insert_tasks(key, value);
9767 }
9768 })
9769 .ok();
9770 })
9771 }
9772 fn fetch_runnable_ranges(
9773 snapshot: &DisplaySnapshot,
9774 range: Range<Anchor>,
9775 ) -> Vec<language::RunnableRange> {
9776 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9777 }
9778
9779 fn runnable_rows(
9780 project: Entity<Project>,
9781 snapshot: DisplaySnapshot,
9782 runnable_ranges: Vec<RunnableRange>,
9783 mut cx: AsyncWindowContext,
9784 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9785 runnable_ranges
9786 .into_iter()
9787 .filter_map(|mut runnable| {
9788 let tasks = cx
9789 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9790 .ok()?;
9791 if tasks.is_empty() {
9792 return None;
9793 }
9794
9795 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9796
9797 let row = snapshot
9798 .buffer_snapshot
9799 .buffer_line_for_row(MultiBufferRow(point.row))?
9800 .1
9801 .start
9802 .row;
9803
9804 let context_range =
9805 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9806 Some((
9807 (runnable.buffer_id, row),
9808 RunnableTasks {
9809 templates: tasks,
9810 offset: MultiBufferOffset(runnable.run_range.start),
9811 context_range,
9812 column: point.column,
9813 extra_variables: runnable.extra_captures,
9814 },
9815 ))
9816 })
9817 .collect()
9818 }
9819
9820 fn templates_with_tags(
9821 project: &Entity<Project>,
9822 runnable: &mut Runnable,
9823 cx: &mut App,
9824 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9825 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9826 let (worktree_id, file) = project
9827 .buffer_for_id(runnable.buffer, cx)
9828 .and_then(|buffer| buffer.read(cx).file())
9829 .map(|file| (file.worktree_id(cx), file.clone()))
9830 .unzip();
9831
9832 (
9833 project.task_store().read(cx).task_inventory().cloned(),
9834 worktree_id,
9835 file,
9836 )
9837 });
9838
9839 let tags = mem::take(&mut runnable.tags);
9840 let mut tags: Vec<_> = tags
9841 .into_iter()
9842 .flat_map(|tag| {
9843 let tag = tag.0.clone();
9844 inventory
9845 .as_ref()
9846 .into_iter()
9847 .flat_map(|inventory| {
9848 inventory.read(cx).list_tasks(
9849 file.clone(),
9850 Some(runnable.language.clone()),
9851 worktree_id,
9852 cx,
9853 )
9854 })
9855 .filter(move |(_, template)| {
9856 template.tags.iter().any(|source_tag| source_tag == &tag)
9857 })
9858 })
9859 .sorted_by_key(|(kind, _)| kind.to_owned())
9860 .collect();
9861 if let Some((leading_tag_source, _)) = tags.first() {
9862 // Strongest source wins; if we have worktree tag binding, prefer that to
9863 // global and language bindings;
9864 // if we have a global binding, prefer that to language binding.
9865 let first_mismatch = tags
9866 .iter()
9867 .position(|(tag_source, _)| tag_source != leading_tag_source);
9868 if let Some(index) = first_mismatch {
9869 tags.truncate(index);
9870 }
9871 }
9872
9873 tags
9874 }
9875
9876 pub fn move_to_enclosing_bracket(
9877 &mut self,
9878 _: &MoveToEnclosingBracket,
9879 window: &mut Window,
9880 cx: &mut Context<Self>,
9881 ) {
9882 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9883 s.move_offsets_with(|snapshot, selection| {
9884 let Some(enclosing_bracket_ranges) =
9885 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9886 else {
9887 return;
9888 };
9889
9890 let mut best_length = usize::MAX;
9891 let mut best_inside = false;
9892 let mut best_in_bracket_range = false;
9893 let mut best_destination = None;
9894 for (open, close) in enclosing_bracket_ranges {
9895 let close = close.to_inclusive();
9896 let length = close.end() - open.start;
9897 let inside = selection.start >= open.end && selection.end <= *close.start();
9898 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9899 || close.contains(&selection.head());
9900
9901 // If best is next to a bracket and current isn't, skip
9902 if !in_bracket_range && best_in_bracket_range {
9903 continue;
9904 }
9905
9906 // Prefer smaller lengths unless best is inside and current isn't
9907 if length > best_length && (best_inside || !inside) {
9908 continue;
9909 }
9910
9911 best_length = length;
9912 best_inside = inside;
9913 best_in_bracket_range = in_bracket_range;
9914 best_destination = Some(
9915 if close.contains(&selection.start) && close.contains(&selection.end) {
9916 if inside {
9917 open.end
9918 } else {
9919 open.start
9920 }
9921 } else if inside {
9922 *close.start()
9923 } else {
9924 *close.end()
9925 },
9926 );
9927 }
9928
9929 if let Some(destination) = best_destination {
9930 selection.collapse_to(destination, SelectionGoal::None);
9931 }
9932 })
9933 });
9934 }
9935
9936 pub fn undo_selection(
9937 &mut self,
9938 _: &UndoSelection,
9939 window: &mut Window,
9940 cx: &mut Context<Self>,
9941 ) {
9942 self.end_selection(window, cx);
9943 self.selection_history.mode = SelectionHistoryMode::Undoing;
9944 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9945 self.change_selections(None, window, cx, |s| {
9946 s.select_anchors(entry.selections.to_vec())
9947 });
9948 self.select_next_state = entry.select_next_state;
9949 self.select_prev_state = entry.select_prev_state;
9950 self.add_selections_state = entry.add_selections_state;
9951 self.request_autoscroll(Autoscroll::newest(), cx);
9952 }
9953 self.selection_history.mode = SelectionHistoryMode::Normal;
9954 }
9955
9956 pub fn redo_selection(
9957 &mut self,
9958 _: &RedoSelection,
9959 window: &mut Window,
9960 cx: &mut Context<Self>,
9961 ) {
9962 self.end_selection(window, cx);
9963 self.selection_history.mode = SelectionHistoryMode::Redoing;
9964 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9965 self.change_selections(None, window, cx, |s| {
9966 s.select_anchors(entry.selections.to_vec())
9967 });
9968 self.select_next_state = entry.select_next_state;
9969 self.select_prev_state = entry.select_prev_state;
9970 self.add_selections_state = entry.add_selections_state;
9971 self.request_autoscroll(Autoscroll::newest(), cx);
9972 }
9973 self.selection_history.mode = SelectionHistoryMode::Normal;
9974 }
9975
9976 pub fn expand_excerpts(
9977 &mut self,
9978 action: &ExpandExcerpts,
9979 _: &mut Window,
9980 cx: &mut Context<Self>,
9981 ) {
9982 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9983 }
9984
9985 pub fn expand_excerpts_down(
9986 &mut self,
9987 action: &ExpandExcerptsDown,
9988 _: &mut Window,
9989 cx: &mut Context<Self>,
9990 ) {
9991 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9992 }
9993
9994 pub fn expand_excerpts_up(
9995 &mut self,
9996 action: &ExpandExcerptsUp,
9997 _: &mut Window,
9998 cx: &mut Context<Self>,
9999 ) {
10000 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10001 }
10002
10003 pub fn expand_excerpts_for_direction(
10004 &mut self,
10005 lines: u32,
10006 direction: ExpandExcerptDirection,
10007
10008 cx: &mut Context<Self>,
10009 ) {
10010 let selections = self.selections.disjoint_anchors();
10011
10012 let lines = if lines == 0 {
10013 EditorSettings::get_global(cx).expand_excerpt_lines
10014 } else {
10015 lines
10016 };
10017
10018 self.buffer.update(cx, |buffer, cx| {
10019 let snapshot = buffer.snapshot(cx);
10020 let mut excerpt_ids = selections
10021 .iter()
10022 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10023 .collect::<Vec<_>>();
10024 excerpt_ids.sort();
10025 excerpt_ids.dedup();
10026 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10027 })
10028 }
10029
10030 pub fn expand_excerpt(
10031 &mut self,
10032 excerpt: ExcerptId,
10033 direction: ExpandExcerptDirection,
10034 cx: &mut Context<Self>,
10035 ) {
10036 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10037 self.buffer.update(cx, |buffer, cx| {
10038 buffer.expand_excerpts([excerpt], lines, direction, cx)
10039 })
10040 }
10041
10042 pub fn go_to_singleton_buffer_point(
10043 &mut self,
10044 point: Point,
10045 window: &mut Window,
10046 cx: &mut Context<Self>,
10047 ) {
10048 self.go_to_singleton_buffer_range(point..point, window, cx);
10049 }
10050
10051 pub fn go_to_singleton_buffer_range(
10052 &mut self,
10053 range: Range<Point>,
10054 window: &mut Window,
10055 cx: &mut Context<Self>,
10056 ) {
10057 let multibuffer = self.buffer().read(cx);
10058 let Some(buffer) = multibuffer.as_singleton() else {
10059 return;
10060 };
10061 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10062 return;
10063 };
10064 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10065 return;
10066 };
10067 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10068 s.select_anchor_ranges([start..end])
10069 });
10070 }
10071
10072 fn go_to_diagnostic(
10073 &mut self,
10074 _: &GoToDiagnostic,
10075 window: &mut Window,
10076 cx: &mut Context<Self>,
10077 ) {
10078 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10079 }
10080
10081 fn go_to_prev_diagnostic(
10082 &mut self,
10083 _: &GoToPrevDiagnostic,
10084 window: &mut Window,
10085 cx: &mut Context<Self>,
10086 ) {
10087 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10088 }
10089
10090 pub fn go_to_diagnostic_impl(
10091 &mut self,
10092 direction: Direction,
10093 window: &mut Window,
10094 cx: &mut Context<Self>,
10095 ) {
10096 let buffer = self.buffer.read(cx).snapshot(cx);
10097 let selection = self.selections.newest::<usize>(cx);
10098
10099 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10100 if direction == Direction::Next {
10101 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10102 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10103 return;
10104 };
10105 self.activate_diagnostics(
10106 buffer_id,
10107 popover.local_diagnostic.diagnostic.group_id,
10108 window,
10109 cx,
10110 );
10111 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10112 let primary_range_start = active_diagnostics.primary_range.start;
10113 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10114 let mut new_selection = s.newest_anchor().clone();
10115 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10116 s.select_anchors(vec![new_selection.clone()]);
10117 });
10118 self.refresh_inline_completion(false, true, window, cx);
10119 }
10120 return;
10121 }
10122 }
10123
10124 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10125 active_diagnostics
10126 .primary_range
10127 .to_offset(&buffer)
10128 .to_inclusive()
10129 });
10130 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10131 if active_primary_range.contains(&selection.head()) {
10132 *active_primary_range.start()
10133 } else {
10134 selection.head()
10135 }
10136 } else {
10137 selection.head()
10138 };
10139 let snapshot = self.snapshot(window, cx);
10140 loop {
10141 let mut diagnostics;
10142 if direction == Direction::Prev {
10143 diagnostics = buffer
10144 .diagnostics_in_range::<usize>(0..search_start)
10145 .collect::<Vec<_>>();
10146 diagnostics.reverse();
10147 } else {
10148 diagnostics = buffer
10149 .diagnostics_in_range::<usize>(search_start..buffer.len())
10150 .collect::<Vec<_>>();
10151 };
10152 let group = diagnostics
10153 .into_iter()
10154 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10155 // relies on diagnostics_in_range to return diagnostics with the same starting range to
10156 // be sorted in a stable way
10157 // skip until we are at current active diagnostic, if it exists
10158 .skip_while(|entry| {
10159 let is_in_range = match direction {
10160 Direction::Prev => entry.range.end > search_start,
10161 Direction::Next => entry.range.start < search_start,
10162 };
10163 is_in_range
10164 && self
10165 .active_diagnostics
10166 .as_ref()
10167 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
10168 })
10169 .find_map(|entry| {
10170 if entry.diagnostic.is_primary
10171 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
10172 && entry.range.start != entry.range.end
10173 // if we match with the active diagnostic, skip it
10174 && Some(entry.diagnostic.group_id)
10175 != self.active_diagnostics.as_ref().map(|d| d.group_id)
10176 {
10177 Some((entry.range, entry.diagnostic.group_id))
10178 } else {
10179 None
10180 }
10181 });
10182
10183 if let Some((primary_range, group_id)) = group {
10184 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10185 return;
10186 };
10187 self.activate_diagnostics(buffer_id, group_id, window, cx);
10188 if self.active_diagnostics.is_some() {
10189 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10190 s.select(vec![Selection {
10191 id: selection.id,
10192 start: primary_range.start,
10193 end: primary_range.start,
10194 reversed: false,
10195 goal: SelectionGoal::None,
10196 }]);
10197 });
10198 self.refresh_inline_completion(false, true, window, cx);
10199 }
10200 break;
10201 } else {
10202 // Cycle around to the start of the buffer, potentially moving back to the start of
10203 // the currently active diagnostic.
10204 active_primary_range.take();
10205 if direction == Direction::Prev {
10206 if search_start == buffer.len() {
10207 break;
10208 } else {
10209 search_start = buffer.len();
10210 }
10211 } else if search_start == 0 {
10212 break;
10213 } else {
10214 search_start = 0;
10215 }
10216 }
10217 }
10218 }
10219
10220 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10221 let snapshot = self.snapshot(window, cx);
10222 let selection = self.selections.newest::<Point>(cx);
10223 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10224 }
10225
10226 fn go_to_hunk_after_position(
10227 &mut self,
10228 snapshot: &EditorSnapshot,
10229 position: Point,
10230 window: &mut Window,
10231 cx: &mut Context<Editor>,
10232 ) -> Option<MultiBufferDiffHunk> {
10233 let mut hunk = snapshot
10234 .buffer_snapshot
10235 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10236 .find(|hunk| hunk.row_range.start.0 > position.row);
10237 if hunk.is_none() {
10238 hunk = snapshot
10239 .buffer_snapshot
10240 .diff_hunks_in_range(Point::zero()..position)
10241 .find(|hunk| hunk.row_range.end.0 < position.row)
10242 }
10243 if let Some(hunk) = &hunk {
10244 let destination = Point::new(hunk.row_range.start.0, 0);
10245 self.unfold_ranges(&[destination..destination], false, false, cx);
10246 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10247 s.select_ranges(vec![destination..destination]);
10248 });
10249 }
10250
10251 hunk
10252 }
10253
10254 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10255 let snapshot = self.snapshot(window, cx);
10256 let selection = self.selections.newest::<Point>(cx);
10257 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10258 }
10259
10260 fn go_to_hunk_before_position(
10261 &mut self,
10262 snapshot: &EditorSnapshot,
10263 position: Point,
10264 window: &mut Window,
10265 cx: &mut Context<Editor>,
10266 ) -> Option<MultiBufferDiffHunk> {
10267 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10268 if hunk.is_none() {
10269 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10270 }
10271 if let Some(hunk) = &hunk {
10272 let destination = Point::new(hunk.row_range.start.0, 0);
10273 self.unfold_ranges(&[destination..destination], false, false, cx);
10274 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10275 s.select_ranges(vec![destination..destination]);
10276 });
10277 }
10278
10279 hunk
10280 }
10281
10282 pub fn go_to_definition(
10283 &mut self,
10284 _: &GoToDefinition,
10285 window: &mut Window,
10286 cx: &mut Context<Self>,
10287 ) -> Task<Result<Navigated>> {
10288 let definition =
10289 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10290 cx.spawn_in(window, |editor, mut cx| async move {
10291 if definition.await? == Navigated::Yes {
10292 return Ok(Navigated::Yes);
10293 }
10294 match editor.update_in(&mut cx, |editor, window, cx| {
10295 editor.find_all_references(&FindAllReferences, window, cx)
10296 })? {
10297 Some(references) => references.await,
10298 None => Ok(Navigated::No),
10299 }
10300 })
10301 }
10302
10303 pub fn go_to_declaration(
10304 &mut self,
10305 _: &GoToDeclaration,
10306 window: &mut Window,
10307 cx: &mut Context<Self>,
10308 ) -> Task<Result<Navigated>> {
10309 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10310 }
10311
10312 pub fn go_to_declaration_split(
10313 &mut self,
10314 _: &GoToDeclaration,
10315 window: &mut Window,
10316 cx: &mut Context<Self>,
10317 ) -> Task<Result<Navigated>> {
10318 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10319 }
10320
10321 pub fn go_to_implementation(
10322 &mut self,
10323 _: &GoToImplementation,
10324 window: &mut Window,
10325 cx: &mut Context<Self>,
10326 ) -> Task<Result<Navigated>> {
10327 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10328 }
10329
10330 pub fn go_to_implementation_split(
10331 &mut self,
10332 _: &GoToImplementationSplit,
10333 window: &mut Window,
10334 cx: &mut Context<Self>,
10335 ) -> Task<Result<Navigated>> {
10336 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10337 }
10338
10339 pub fn go_to_type_definition(
10340 &mut self,
10341 _: &GoToTypeDefinition,
10342 window: &mut Window,
10343 cx: &mut Context<Self>,
10344 ) -> Task<Result<Navigated>> {
10345 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10346 }
10347
10348 pub fn go_to_definition_split(
10349 &mut self,
10350 _: &GoToDefinitionSplit,
10351 window: &mut Window,
10352 cx: &mut Context<Self>,
10353 ) -> Task<Result<Navigated>> {
10354 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10355 }
10356
10357 pub fn go_to_type_definition_split(
10358 &mut self,
10359 _: &GoToTypeDefinitionSplit,
10360 window: &mut Window,
10361 cx: &mut Context<Self>,
10362 ) -> Task<Result<Navigated>> {
10363 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10364 }
10365
10366 fn go_to_definition_of_kind(
10367 &mut self,
10368 kind: GotoDefinitionKind,
10369 split: bool,
10370 window: &mut Window,
10371 cx: &mut Context<Self>,
10372 ) -> Task<Result<Navigated>> {
10373 let Some(provider) = self.semantics_provider.clone() else {
10374 return Task::ready(Ok(Navigated::No));
10375 };
10376 let head = self.selections.newest::<usize>(cx).head();
10377 let buffer = self.buffer.read(cx);
10378 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10379 text_anchor
10380 } else {
10381 return Task::ready(Ok(Navigated::No));
10382 };
10383
10384 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10385 return Task::ready(Ok(Navigated::No));
10386 };
10387
10388 cx.spawn_in(window, |editor, mut cx| async move {
10389 let definitions = definitions.await?;
10390 let navigated = editor
10391 .update_in(&mut cx, |editor, window, cx| {
10392 editor.navigate_to_hover_links(
10393 Some(kind),
10394 definitions
10395 .into_iter()
10396 .filter(|location| {
10397 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10398 })
10399 .map(HoverLink::Text)
10400 .collect::<Vec<_>>(),
10401 split,
10402 window,
10403 cx,
10404 )
10405 })?
10406 .await?;
10407 anyhow::Ok(navigated)
10408 })
10409 }
10410
10411 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10412 let selection = self.selections.newest_anchor();
10413 let head = selection.head();
10414 let tail = selection.tail();
10415
10416 let Some((buffer, start_position)) =
10417 self.buffer.read(cx).text_anchor_for_position(head, cx)
10418 else {
10419 return;
10420 };
10421
10422 let end_position = if head != tail {
10423 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10424 return;
10425 };
10426 Some(pos)
10427 } else {
10428 None
10429 };
10430
10431 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10432 let url = if let Some(end_pos) = end_position {
10433 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10434 } else {
10435 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10436 };
10437
10438 if let Some(url) = url {
10439 editor.update(&mut cx, |_, cx| {
10440 cx.open_url(&url);
10441 })
10442 } else {
10443 Ok(())
10444 }
10445 });
10446
10447 url_finder.detach();
10448 }
10449
10450 pub fn open_selected_filename(
10451 &mut self,
10452 _: &OpenSelectedFilename,
10453 window: &mut Window,
10454 cx: &mut Context<Self>,
10455 ) {
10456 let Some(workspace) = self.workspace() else {
10457 return;
10458 };
10459
10460 let position = self.selections.newest_anchor().head();
10461
10462 let Some((buffer, buffer_position)) =
10463 self.buffer.read(cx).text_anchor_for_position(position, cx)
10464 else {
10465 return;
10466 };
10467
10468 let project = self.project.clone();
10469
10470 cx.spawn_in(window, |_, mut cx| async move {
10471 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10472
10473 if let Some((_, path)) = result {
10474 workspace
10475 .update_in(&mut cx, |workspace, window, cx| {
10476 workspace.open_resolved_path(path, window, cx)
10477 })?
10478 .await?;
10479 }
10480 anyhow::Ok(())
10481 })
10482 .detach();
10483 }
10484
10485 pub(crate) fn navigate_to_hover_links(
10486 &mut self,
10487 kind: Option<GotoDefinitionKind>,
10488 mut definitions: Vec<HoverLink>,
10489 split: bool,
10490 window: &mut Window,
10491 cx: &mut Context<Editor>,
10492 ) -> Task<Result<Navigated>> {
10493 // If there is one definition, just open it directly
10494 if definitions.len() == 1 {
10495 let definition = definitions.pop().unwrap();
10496
10497 enum TargetTaskResult {
10498 Location(Option<Location>),
10499 AlreadyNavigated,
10500 }
10501
10502 let target_task = match definition {
10503 HoverLink::Text(link) => {
10504 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10505 }
10506 HoverLink::InlayHint(lsp_location, server_id) => {
10507 let computation =
10508 self.compute_target_location(lsp_location, server_id, window, cx);
10509 cx.background_executor().spawn(async move {
10510 let location = computation.await?;
10511 Ok(TargetTaskResult::Location(location))
10512 })
10513 }
10514 HoverLink::Url(url) => {
10515 cx.open_url(&url);
10516 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10517 }
10518 HoverLink::File(path) => {
10519 if let Some(workspace) = self.workspace() {
10520 cx.spawn_in(window, |_, mut cx| async move {
10521 workspace
10522 .update_in(&mut cx, |workspace, window, cx| {
10523 workspace.open_resolved_path(path, window, cx)
10524 })?
10525 .await
10526 .map(|_| TargetTaskResult::AlreadyNavigated)
10527 })
10528 } else {
10529 Task::ready(Ok(TargetTaskResult::Location(None)))
10530 }
10531 }
10532 };
10533 cx.spawn_in(window, |editor, mut cx| async move {
10534 let target = match target_task.await.context("target resolution task")? {
10535 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10536 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10537 TargetTaskResult::Location(Some(target)) => target,
10538 };
10539
10540 editor.update_in(&mut cx, |editor, window, cx| {
10541 let Some(workspace) = editor.workspace() else {
10542 return Navigated::No;
10543 };
10544 let pane = workspace.read(cx).active_pane().clone();
10545
10546 let range = target.range.to_point(target.buffer.read(cx));
10547 let range = editor.range_for_match(&range);
10548 let range = collapse_multiline_range(range);
10549
10550 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10551 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10552 } else {
10553 window.defer(cx, move |window, cx| {
10554 let target_editor: Entity<Self> =
10555 workspace.update(cx, |workspace, cx| {
10556 let pane = if split {
10557 workspace.adjacent_pane(window, cx)
10558 } else {
10559 workspace.active_pane().clone()
10560 };
10561
10562 workspace.open_project_item(
10563 pane,
10564 target.buffer.clone(),
10565 true,
10566 true,
10567 window,
10568 cx,
10569 )
10570 });
10571 target_editor.update(cx, |target_editor, cx| {
10572 // When selecting a definition in a different buffer, disable the nav history
10573 // to avoid creating a history entry at the previous cursor location.
10574 pane.update(cx, |pane, _| pane.disable_history());
10575 target_editor.go_to_singleton_buffer_range(range, window, cx);
10576 pane.update(cx, |pane, _| pane.enable_history());
10577 });
10578 });
10579 }
10580 Navigated::Yes
10581 })
10582 })
10583 } else if !definitions.is_empty() {
10584 cx.spawn_in(window, |editor, mut cx| async move {
10585 let (title, location_tasks, workspace) = editor
10586 .update_in(&mut cx, |editor, window, cx| {
10587 let tab_kind = match kind {
10588 Some(GotoDefinitionKind::Implementation) => "Implementations",
10589 _ => "Definitions",
10590 };
10591 let title = definitions
10592 .iter()
10593 .find_map(|definition| match definition {
10594 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10595 let buffer = origin.buffer.read(cx);
10596 format!(
10597 "{} for {}",
10598 tab_kind,
10599 buffer
10600 .text_for_range(origin.range.clone())
10601 .collect::<String>()
10602 )
10603 }),
10604 HoverLink::InlayHint(_, _) => None,
10605 HoverLink::Url(_) => None,
10606 HoverLink::File(_) => None,
10607 })
10608 .unwrap_or(tab_kind.to_string());
10609 let location_tasks = definitions
10610 .into_iter()
10611 .map(|definition| match definition {
10612 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10613 HoverLink::InlayHint(lsp_location, server_id) => editor
10614 .compute_target_location(lsp_location, server_id, window, cx),
10615 HoverLink::Url(_) => Task::ready(Ok(None)),
10616 HoverLink::File(_) => Task::ready(Ok(None)),
10617 })
10618 .collect::<Vec<_>>();
10619 (title, location_tasks, editor.workspace().clone())
10620 })
10621 .context("location tasks preparation")?;
10622
10623 let locations = future::join_all(location_tasks)
10624 .await
10625 .into_iter()
10626 .filter_map(|location| location.transpose())
10627 .collect::<Result<_>>()
10628 .context("location tasks")?;
10629
10630 let Some(workspace) = workspace else {
10631 return Ok(Navigated::No);
10632 };
10633 let opened = workspace
10634 .update_in(&mut cx, |workspace, window, cx| {
10635 Self::open_locations_in_multibuffer(
10636 workspace,
10637 locations,
10638 title,
10639 split,
10640 MultibufferSelectionMode::First,
10641 window,
10642 cx,
10643 )
10644 })
10645 .ok();
10646
10647 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10648 })
10649 } else {
10650 Task::ready(Ok(Navigated::No))
10651 }
10652 }
10653
10654 fn compute_target_location(
10655 &self,
10656 lsp_location: lsp::Location,
10657 server_id: LanguageServerId,
10658 window: &mut Window,
10659 cx: &mut Context<Self>,
10660 ) -> Task<anyhow::Result<Option<Location>>> {
10661 let Some(project) = self.project.clone() else {
10662 return Task::ready(Ok(None));
10663 };
10664
10665 cx.spawn_in(window, move |editor, mut cx| async move {
10666 let location_task = editor.update(&mut cx, |_, cx| {
10667 project.update(cx, |project, cx| {
10668 let language_server_name = project
10669 .language_server_statuses(cx)
10670 .find(|(id, _)| server_id == *id)
10671 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10672 language_server_name.map(|language_server_name| {
10673 project.open_local_buffer_via_lsp(
10674 lsp_location.uri.clone(),
10675 server_id,
10676 language_server_name,
10677 cx,
10678 )
10679 })
10680 })
10681 })?;
10682 let location = match location_task {
10683 Some(task) => Some({
10684 let target_buffer_handle = task.await.context("open local buffer")?;
10685 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10686 let target_start = target_buffer
10687 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10688 let target_end = target_buffer
10689 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10690 target_buffer.anchor_after(target_start)
10691 ..target_buffer.anchor_before(target_end)
10692 })?;
10693 Location {
10694 buffer: target_buffer_handle,
10695 range,
10696 }
10697 }),
10698 None => None,
10699 };
10700 Ok(location)
10701 })
10702 }
10703
10704 pub fn find_all_references(
10705 &mut self,
10706 _: &FindAllReferences,
10707 window: &mut Window,
10708 cx: &mut Context<Self>,
10709 ) -> Option<Task<Result<Navigated>>> {
10710 let selection = self.selections.newest::<usize>(cx);
10711 let multi_buffer = self.buffer.read(cx);
10712 let head = selection.head();
10713
10714 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10715 let head_anchor = multi_buffer_snapshot.anchor_at(
10716 head,
10717 if head < selection.tail() {
10718 Bias::Right
10719 } else {
10720 Bias::Left
10721 },
10722 );
10723
10724 match self
10725 .find_all_references_task_sources
10726 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10727 {
10728 Ok(_) => {
10729 log::info!(
10730 "Ignoring repeated FindAllReferences invocation with the position of already running task"
10731 );
10732 return None;
10733 }
10734 Err(i) => {
10735 self.find_all_references_task_sources.insert(i, head_anchor);
10736 }
10737 }
10738
10739 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10740 let workspace = self.workspace()?;
10741 let project = workspace.read(cx).project().clone();
10742 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10743 Some(cx.spawn_in(window, |editor, mut cx| async move {
10744 let _cleanup = defer({
10745 let mut cx = cx.clone();
10746 move || {
10747 let _ = editor.update(&mut cx, |editor, _| {
10748 if let Ok(i) =
10749 editor
10750 .find_all_references_task_sources
10751 .binary_search_by(|anchor| {
10752 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10753 })
10754 {
10755 editor.find_all_references_task_sources.remove(i);
10756 }
10757 });
10758 }
10759 });
10760
10761 let locations = references.await?;
10762 if locations.is_empty() {
10763 return anyhow::Ok(Navigated::No);
10764 }
10765
10766 workspace.update_in(&mut cx, |workspace, window, cx| {
10767 let title = locations
10768 .first()
10769 .as_ref()
10770 .map(|location| {
10771 let buffer = location.buffer.read(cx);
10772 format!(
10773 "References to `{}`",
10774 buffer
10775 .text_for_range(location.range.clone())
10776 .collect::<String>()
10777 )
10778 })
10779 .unwrap();
10780 Self::open_locations_in_multibuffer(
10781 workspace,
10782 locations,
10783 title,
10784 false,
10785 MultibufferSelectionMode::First,
10786 window,
10787 cx,
10788 );
10789 Navigated::Yes
10790 })
10791 }))
10792 }
10793
10794 /// Opens a multibuffer with the given project locations in it
10795 pub fn open_locations_in_multibuffer(
10796 workspace: &mut Workspace,
10797 mut locations: Vec<Location>,
10798 title: String,
10799 split: bool,
10800 multibuffer_selection_mode: MultibufferSelectionMode,
10801 window: &mut Window,
10802 cx: &mut Context<Workspace>,
10803 ) {
10804 // If there are multiple definitions, open them in a multibuffer
10805 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10806 let mut locations = locations.into_iter().peekable();
10807 let mut ranges = Vec::new();
10808 let capability = workspace.project().read(cx).capability();
10809
10810 let excerpt_buffer = cx.new(|cx| {
10811 let mut multibuffer = MultiBuffer::new(capability);
10812 while let Some(location) = locations.next() {
10813 let buffer = location.buffer.read(cx);
10814 let mut ranges_for_buffer = Vec::new();
10815 let range = location.range.to_offset(buffer);
10816 ranges_for_buffer.push(range.clone());
10817
10818 while let Some(next_location) = locations.peek() {
10819 if next_location.buffer == location.buffer {
10820 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10821 locations.next();
10822 } else {
10823 break;
10824 }
10825 }
10826
10827 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10828 ranges.extend(multibuffer.push_excerpts_with_context_lines(
10829 location.buffer.clone(),
10830 ranges_for_buffer,
10831 DEFAULT_MULTIBUFFER_CONTEXT,
10832 cx,
10833 ))
10834 }
10835
10836 multibuffer.with_title(title)
10837 });
10838
10839 let editor = cx.new(|cx| {
10840 Editor::for_multibuffer(
10841 excerpt_buffer,
10842 Some(workspace.project().clone()),
10843 true,
10844 window,
10845 cx,
10846 )
10847 });
10848 editor.update(cx, |editor, cx| {
10849 match multibuffer_selection_mode {
10850 MultibufferSelectionMode::First => {
10851 if let Some(first_range) = ranges.first() {
10852 editor.change_selections(None, window, cx, |selections| {
10853 selections.clear_disjoint();
10854 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10855 });
10856 }
10857 editor.highlight_background::<Self>(
10858 &ranges,
10859 |theme| theme.editor_highlighted_line_background,
10860 cx,
10861 );
10862 }
10863 MultibufferSelectionMode::All => {
10864 editor.change_selections(None, window, cx, |selections| {
10865 selections.clear_disjoint();
10866 selections.select_anchor_ranges(ranges);
10867 });
10868 }
10869 }
10870 editor.register_buffers_with_language_servers(cx);
10871 });
10872
10873 let item = Box::new(editor);
10874 let item_id = item.item_id();
10875
10876 if split {
10877 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
10878 } else {
10879 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10880 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10881 pane.close_current_preview_item(window, cx)
10882 } else {
10883 None
10884 }
10885 });
10886 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
10887 }
10888 workspace.active_pane().update(cx, |pane, cx| {
10889 pane.set_preview_item_id(Some(item_id), cx);
10890 });
10891 }
10892
10893 pub fn rename(
10894 &mut self,
10895 _: &Rename,
10896 window: &mut Window,
10897 cx: &mut Context<Self>,
10898 ) -> Option<Task<Result<()>>> {
10899 use language::ToOffset as _;
10900
10901 let provider = self.semantics_provider.clone()?;
10902 let selection = self.selections.newest_anchor().clone();
10903 let (cursor_buffer, cursor_buffer_position) = self
10904 .buffer
10905 .read(cx)
10906 .text_anchor_for_position(selection.head(), cx)?;
10907 let (tail_buffer, cursor_buffer_position_end) = self
10908 .buffer
10909 .read(cx)
10910 .text_anchor_for_position(selection.tail(), cx)?;
10911 if tail_buffer != cursor_buffer {
10912 return None;
10913 }
10914
10915 let snapshot = cursor_buffer.read(cx).snapshot();
10916 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10917 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10918 let prepare_rename = provider
10919 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10920 .unwrap_or_else(|| Task::ready(Ok(None)));
10921 drop(snapshot);
10922
10923 Some(cx.spawn_in(window, |this, mut cx| async move {
10924 let rename_range = if let Some(range) = prepare_rename.await? {
10925 Some(range)
10926 } else {
10927 this.update(&mut cx, |this, cx| {
10928 let buffer = this.buffer.read(cx).snapshot(cx);
10929 let mut buffer_highlights = this
10930 .document_highlights_for_position(selection.head(), &buffer)
10931 .filter(|highlight| {
10932 highlight.start.excerpt_id == selection.head().excerpt_id
10933 && highlight.end.excerpt_id == selection.head().excerpt_id
10934 });
10935 buffer_highlights
10936 .next()
10937 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10938 })?
10939 };
10940 if let Some(rename_range) = rename_range {
10941 this.update_in(&mut cx, |this, window, cx| {
10942 let snapshot = cursor_buffer.read(cx).snapshot();
10943 let rename_buffer_range = rename_range.to_offset(&snapshot);
10944 let cursor_offset_in_rename_range =
10945 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10946 let cursor_offset_in_rename_range_end =
10947 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10948
10949 this.take_rename(false, window, cx);
10950 let buffer = this.buffer.read(cx).read(cx);
10951 let cursor_offset = selection.head().to_offset(&buffer);
10952 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10953 let rename_end = rename_start + rename_buffer_range.len();
10954 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10955 let mut old_highlight_id = None;
10956 let old_name: Arc<str> = buffer
10957 .chunks(rename_start..rename_end, true)
10958 .map(|chunk| {
10959 if old_highlight_id.is_none() {
10960 old_highlight_id = chunk.syntax_highlight_id;
10961 }
10962 chunk.text
10963 })
10964 .collect::<String>()
10965 .into();
10966
10967 drop(buffer);
10968
10969 // Position the selection in the rename editor so that it matches the current selection.
10970 this.show_local_selections = false;
10971 let rename_editor = cx.new(|cx| {
10972 let mut editor = Editor::single_line(window, cx);
10973 editor.buffer.update(cx, |buffer, cx| {
10974 buffer.edit([(0..0, old_name.clone())], None, cx)
10975 });
10976 let rename_selection_range = match cursor_offset_in_rename_range
10977 .cmp(&cursor_offset_in_rename_range_end)
10978 {
10979 Ordering::Equal => {
10980 editor.select_all(&SelectAll, window, cx);
10981 return editor;
10982 }
10983 Ordering::Less => {
10984 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10985 }
10986 Ordering::Greater => {
10987 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10988 }
10989 };
10990 if rename_selection_range.end > old_name.len() {
10991 editor.select_all(&SelectAll, window, cx);
10992 } else {
10993 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10994 s.select_ranges([rename_selection_range]);
10995 });
10996 }
10997 editor
10998 });
10999 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11000 if e == &EditorEvent::Focused {
11001 cx.emit(EditorEvent::FocusedIn)
11002 }
11003 })
11004 .detach();
11005
11006 let write_highlights =
11007 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11008 let read_highlights =
11009 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11010 let ranges = write_highlights
11011 .iter()
11012 .flat_map(|(_, ranges)| ranges.iter())
11013 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11014 .cloned()
11015 .collect();
11016
11017 this.highlight_text::<Rename>(
11018 ranges,
11019 HighlightStyle {
11020 fade_out: Some(0.6),
11021 ..Default::default()
11022 },
11023 cx,
11024 );
11025 let rename_focus_handle = rename_editor.focus_handle(cx);
11026 window.focus(&rename_focus_handle);
11027 let block_id = this.insert_blocks(
11028 [BlockProperties {
11029 style: BlockStyle::Flex,
11030 placement: BlockPlacement::Below(range.start),
11031 height: 1,
11032 render: Arc::new({
11033 let rename_editor = rename_editor.clone();
11034 move |cx: &mut BlockContext| {
11035 let mut text_style = cx.editor_style.text.clone();
11036 if let Some(highlight_style) = old_highlight_id
11037 .and_then(|h| h.style(&cx.editor_style.syntax))
11038 {
11039 text_style = text_style.highlight(highlight_style);
11040 }
11041 div()
11042 .block_mouse_down()
11043 .pl(cx.anchor_x)
11044 .child(EditorElement::new(
11045 &rename_editor,
11046 EditorStyle {
11047 background: cx.theme().system().transparent,
11048 local_player: cx.editor_style.local_player,
11049 text: text_style,
11050 scrollbar_width: cx.editor_style.scrollbar_width,
11051 syntax: cx.editor_style.syntax.clone(),
11052 status: cx.editor_style.status.clone(),
11053 inlay_hints_style: HighlightStyle {
11054 font_weight: Some(FontWeight::BOLD),
11055 ..make_inlay_hints_style(cx.app)
11056 },
11057 inline_completion_styles: make_suggestion_styles(
11058 cx.app,
11059 ),
11060 ..EditorStyle::default()
11061 },
11062 ))
11063 .into_any_element()
11064 }
11065 }),
11066 priority: 0,
11067 }],
11068 Some(Autoscroll::fit()),
11069 cx,
11070 )[0];
11071 this.pending_rename = Some(RenameState {
11072 range,
11073 old_name,
11074 editor: rename_editor,
11075 block_id,
11076 });
11077 })?;
11078 }
11079
11080 Ok(())
11081 }))
11082 }
11083
11084 pub fn confirm_rename(
11085 &mut self,
11086 _: &ConfirmRename,
11087 window: &mut Window,
11088 cx: &mut Context<Self>,
11089 ) -> Option<Task<Result<()>>> {
11090 let rename = self.take_rename(false, window, cx)?;
11091 let workspace = self.workspace()?.downgrade();
11092 let (buffer, start) = self
11093 .buffer
11094 .read(cx)
11095 .text_anchor_for_position(rename.range.start, cx)?;
11096 let (end_buffer, _) = self
11097 .buffer
11098 .read(cx)
11099 .text_anchor_for_position(rename.range.end, cx)?;
11100 if buffer != end_buffer {
11101 return None;
11102 }
11103
11104 let old_name = rename.old_name;
11105 let new_name = rename.editor.read(cx).text(cx);
11106
11107 let rename = self.semantics_provider.as_ref()?.perform_rename(
11108 &buffer,
11109 start,
11110 new_name.clone(),
11111 cx,
11112 )?;
11113
11114 Some(cx.spawn_in(window, |editor, mut cx| async move {
11115 let project_transaction = rename.await?;
11116 Self::open_project_transaction(
11117 &editor,
11118 workspace,
11119 project_transaction,
11120 format!("Rename: {} → {}", old_name, new_name),
11121 cx.clone(),
11122 )
11123 .await?;
11124
11125 editor.update(&mut cx, |editor, cx| {
11126 editor.refresh_document_highlights(cx);
11127 })?;
11128 Ok(())
11129 }))
11130 }
11131
11132 fn take_rename(
11133 &mut self,
11134 moving_cursor: bool,
11135 window: &mut Window,
11136 cx: &mut Context<Self>,
11137 ) -> Option<RenameState> {
11138 let rename = self.pending_rename.take()?;
11139 if rename.editor.focus_handle(cx).is_focused(window) {
11140 window.focus(&self.focus_handle);
11141 }
11142
11143 self.remove_blocks(
11144 [rename.block_id].into_iter().collect(),
11145 Some(Autoscroll::fit()),
11146 cx,
11147 );
11148 self.clear_highlights::<Rename>(cx);
11149 self.show_local_selections = true;
11150
11151 if moving_cursor {
11152 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11153 editor.selections.newest::<usize>(cx).head()
11154 });
11155
11156 // Update the selection to match the position of the selection inside
11157 // the rename editor.
11158 let snapshot = self.buffer.read(cx).read(cx);
11159 let rename_range = rename.range.to_offset(&snapshot);
11160 let cursor_in_editor = snapshot
11161 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11162 .min(rename_range.end);
11163 drop(snapshot);
11164
11165 self.change_selections(None, window, cx, |s| {
11166 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11167 });
11168 } else {
11169 self.refresh_document_highlights(cx);
11170 }
11171
11172 Some(rename)
11173 }
11174
11175 pub fn pending_rename(&self) -> Option<&RenameState> {
11176 self.pending_rename.as_ref()
11177 }
11178
11179 fn format(
11180 &mut self,
11181 _: &Format,
11182 window: &mut Window,
11183 cx: &mut Context<Self>,
11184 ) -> Option<Task<Result<()>>> {
11185 let project = match &self.project {
11186 Some(project) => project.clone(),
11187 None => return None,
11188 };
11189
11190 Some(self.perform_format(
11191 project,
11192 FormatTrigger::Manual,
11193 FormatTarget::Buffers,
11194 window,
11195 cx,
11196 ))
11197 }
11198
11199 fn format_selections(
11200 &mut self,
11201 _: &FormatSelections,
11202 window: &mut Window,
11203 cx: &mut Context<Self>,
11204 ) -> Option<Task<Result<()>>> {
11205 let project = match &self.project {
11206 Some(project) => project.clone(),
11207 None => return None,
11208 };
11209
11210 let ranges = self
11211 .selections
11212 .all_adjusted(cx)
11213 .into_iter()
11214 .map(|selection| selection.range())
11215 .collect_vec();
11216
11217 Some(self.perform_format(
11218 project,
11219 FormatTrigger::Manual,
11220 FormatTarget::Ranges(ranges),
11221 window,
11222 cx,
11223 ))
11224 }
11225
11226 fn perform_format(
11227 &mut self,
11228 project: Entity<Project>,
11229 trigger: FormatTrigger,
11230 target: FormatTarget,
11231 window: &mut Window,
11232 cx: &mut Context<Self>,
11233 ) -> Task<Result<()>> {
11234 let buffer = self.buffer.clone();
11235 let (buffers, target) = match target {
11236 FormatTarget::Buffers => {
11237 let mut buffers = buffer.read(cx).all_buffers();
11238 if trigger == FormatTrigger::Save {
11239 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11240 }
11241 (buffers, LspFormatTarget::Buffers)
11242 }
11243 FormatTarget::Ranges(selection_ranges) => {
11244 let multi_buffer = buffer.read(cx);
11245 let snapshot = multi_buffer.read(cx);
11246 let mut buffers = HashSet::default();
11247 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11248 BTreeMap::new();
11249 for selection_range in selection_ranges {
11250 for (buffer, buffer_range, _) in
11251 snapshot.range_to_buffer_ranges(selection_range)
11252 {
11253 let buffer_id = buffer.remote_id();
11254 let start = buffer.anchor_before(buffer_range.start);
11255 let end = buffer.anchor_after(buffer_range.end);
11256 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11257 buffer_id_to_ranges
11258 .entry(buffer_id)
11259 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11260 .or_insert_with(|| vec![start..end]);
11261 }
11262 }
11263 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11264 }
11265 };
11266
11267 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11268 let format = project.update(cx, |project, cx| {
11269 project.format(buffers, target, true, trigger, cx)
11270 });
11271
11272 cx.spawn_in(window, |_, mut cx| async move {
11273 let transaction = futures::select_biased! {
11274 () = timeout => {
11275 log::warn!("timed out waiting for formatting");
11276 None
11277 }
11278 transaction = format.log_err().fuse() => transaction,
11279 };
11280
11281 buffer
11282 .update(&mut cx, |buffer, cx| {
11283 if let Some(transaction) = transaction {
11284 if !buffer.is_singleton() {
11285 buffer.push_transaction(&transaction.0, cx);
11286 }
11287 }
11288
11289 cx.notify();
11290 })
11291 .ok();
11292
11293 Ok(())
11294 })
11295 }
11296
11297 fn restart_language_server(
11298 &mut self,
11299 _: &RestartLanguageServer,
11300 _: &mut Window,
11301 cx: &mut Context<Self>,
11302 ) {
11303 if let Some(project) = self.project.clone() {
11304 self.buffer.update(cx, |multi_buffer, cx| {
11305 project.update(cx, |project, cx| {
11306 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11307 });
11308 })
11309 }
11310 }
11311
11312 fn cancel_language_server_work(
11313 workspace: &mut Workspace,
11314 _: &actions::CancelLanguageServerWork,
11315 _: &mut Window,
11316 cx: &mut Context<Workspace>,
11317 ) {
11318 let project = workspace.project();
11319 let buffers = workspace
11320 .active_item(cx)
11321 .and_then(|item| item.act_as::<Editor>(cx))
11322 .map_or(HashSet::default(), |editor| {
11323 editor.read(cx).buffer.read(cx).all_buffers()
11324 });
11325 project.update(cx, |project, cx| {
11326 project.cancel_language_server_work_for_buffers(buffers, cx);
11327 });
11328 }
11329
11330 fn show_character_palette(
11331 &mut self,
11332 _: &ShowCharacterPalette,
11333 window: &mut Window,
11334 _: &mut Context<Self>,
11335 ) {
11336 window.show_character_palette();
11337 }
11338
11339 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11340 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11341 let buffer = self.buffer.read(cx).snapshot(cx);
11342 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11343 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11344 let is_valid = buffer
11345 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11346 .any(|entry| {
11347 entry.diagnostic.is_primary
11348 && !entry.range.is_empty()
11349 && entry.range.start == primary_range_start
11350 && entry.diagnostic.message == active_diagnostics.primary_message
11351 });
11352
11353 if is_valid != active_diagnostics.is_valid {
11354 active_diagnostics.is_valid = is_valid;
11355 let mut new_styles = HashMap::default();
11356 for (block_id, diagnostic) in &active_diagnostics.blocks {
11357 new_styles.insert(
11358 *block_id,
11359 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11360 );
11361 }
11362 self.display_map.update(cx, |display_map, _cx| {
11363 display_map.replace_blocks(new_styles)
11364 });
11365 }
11366 }
11367 }
11368
11369 fn activate_diagnostics(
11370 &mut self,
11371 buffer_id: BufferId,
11372 group_id: usize,
11373 window: &mut Window,
11374 cx: &mut Context<Self>,
11375 ) {
11376 self.dismiss_diagnostics(cx);
11377 let snapshot = self.snapshot(window, cx);
11378 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11379 let buffer = self.buffer.read(cx).snapshot(cx);
11380
11381 let mut primary_range = None;
11382 let mut primary_message = None;
11383 let diagnostic_group = buffer
11384 .diagnostic_group(buffer_id, group_id)
11385 .filter_map(|entry| {
11386 let start = entry.range.start;
11387 let end = entry.range.end;
11388 if snapshot.is_line_folded(MultiBufferRow(start.row))
11389 && (start.row == end.row
11390 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11391 {
11392 return None;
11393 }
11394 if entry.diagnostic.is_primary {
11395 primary_range = Some(entry.range.clone());
11396 primary_message = Some(entry.diagnostic.message.clone());
11397 }
11398 Some(entry)
11399 })
11400 .collect::<Vec<_>>();
11401 let primary_range = primary_range?;
11402 let primary_message = primary_message?;
11403
11404 let blocks = display_map
11405 .insert_blocks(
11406 diagnostic_group.iter().map(|entry| {
11407 let diagnostic = entry.diagnostic.clone();
11408 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11409 BlockProperties {
11410 style: BlockStyle::Fixed,
11411 placement: BlockPlacement::Below(
11412 buffer.anchor_after(entry.range.start),
11413 ),
11414 height: message_height,
11415 render: diagnostic_block_renderer(diagnostic, None, true, true),
11416 priority: 0,
11417 }
11418 }),
11419 cx,
11420 )
11421 .into_iter()
11422 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11423 .collect();
11424
11425 Some(ActiveDiagnosticGroup {
11426 primary_range: buffer.anchor_before(primary_range.start)
11427 ..buffer.anchor_after(primary_range.end),
11428 primary_message,
11429 group_id,
11430 blocks,
11431 is_valid: true,
11432 })
11433 });
11434 }
11435
11436 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11437 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11438 self.display_map.update(cx, |display_map, cx| {
11439 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11440 });
11441 cx.notify();
11442 }
11443 }
11444
11445 pub fn set_selections_from_remote(
11446 &mut self,
11447 selections: Vec<Selection<Anchor>>,
11448 pending_selection: Option<Selection<Anchor>>,
11449 window: &mut Window,
11450 cx: &mut Context<Self>,
11451 ) {
11452 let old_cursor_position = self.selections.newest_anchor().head();
11453 self.selections.change_with(cx, |s| {
11454 s.select_anchors(selections);
11455 if let Some(pending_selection) = pending_selection {
11456 s.set_pending(pending_selection, SelectMode::Character);
11457 } else {
11458 s.clear_pending();
11459 }
11460 });
11461 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11462 }
11463
11464 fn push_to_selection_history(&mut self) {
11465 self.selection_history.push(SelectionHistoryEntry {
11466 selections: self.selections.disjoint_anchors(),
11467 select_next_state: self.select_next_state.clone(),
11468 select_prev_state: self.select_prev_state.clone(),
11469 add_selections_state: self.add_selections_state.clone(),
11470 });
11471 }
11472
11473 pub fn transact(
11474 &mut self,
11475 window: &mut Window,
11476 cx: &mut Context<Self>,
11477 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11478 ) -> Option<TransactionId> {
11479 self.start_transaction_at(Instant::now(), window, cx);
11480 update(self, window, cx);
11481 self.end_transaction_at(Instant::now(), cx)
11482 }
11483
11484 pub fn start_transaction_at(
11485 &mut self,
11486 now: Instant,
11487 window: &mut Window,
11488 cx: &mut Context<Self>,
11489 ) {
11490 self.end_selection(window, cx);
11491 if let Some(tx_id) = self
11492 .buffer
11493 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11494 {
11495 self.selection_history
11496 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11497 cx.emit(EditorEvent::TransactionBegun {
11498 transaction_id: tx_id,
11499 })
11500 }
11501 }
11502
11503 pub fn end_transaction_at(
11504 &mut self,
11505 now: Instant,
11506 cx: &mut Context<Self>,
11507 ) -> Option<TransactionId> {
11508 if let Some(transaction_id) = self
11509 .buffer
11510 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11511 {
11512 if let Some((_, end_selections)) =
11513 self.selection_history.transaction_mut(transaction_id)
11514 {
11515 *end_selections = Some(self.selections.disjoint_anchors());
11516 } else {
11517 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11518 }
11519
11520 cx.emit(EditorEvent::Edited { transaction_id });
11521 Some(transaction_id)
11522 } else {
11523 None
11524 }
11525 }
11526
11527 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11528 if self.selection_mark_mode {
11529 self.change_selections(None, window, cx, |s| {
11530 s.move_with(|_, sel| {
11531 sel.collapse_to(sel.head(), SelectionGoal::None);
11532 });
11533 })
11534 }
11535 self.selection_mark_mode = true;
11536 cx.notify();
11537 }
11538
11539 pub fn swap_selection_ends(
11540 &mut self,
11541 _: &actions::SwapSelectionEnds,
11542 window: &mut Window,
11543 cx: &mut Context<Self>,
11544 ) {
11545 self.change_selections(None, window, cx, |s| {
11546 s.move_with(|_, sel| {
11547 if sel.start != sel.end {
11548 sel.reversed = !sel.reversed
11549 }
11550 });
11551 });
11552 self.request_autoscroll(Autoscroll::newest(), cx);
11553 cx.notify();
11554 }
11555
11556 pub fn toggle_fold(
11557 &mut self,
11558 _: &actions::ToggleFold,
11559 window: &mut Window,
11560 cx: &mut Context<Self>,
11561 ) {
11562 if self.is_singleton(cx) {
11563 let selection = self.selections.newest::<Point>(cx);
11564
11565 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11566 let range = if selection.is_empty() {
11567 let point = selection.head().to_display_point(&display_map);
11568 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11569 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11570 .to_point(&display_map);
11571 start..end
11572 } else {
11573 selection.range()
11574 };
11575 if display_map.folds_in_range(range).next().is_some() {
11576 self.unfold_lines(&Default::default(), window, cx)
11577 } else {
11578 self.fold(&Default::default(), window, cx)
11579 }
11580 } else {
11581 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11582 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11583 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11584 .map(|(snapshot, _, _)| snapshot.remote_id())
11585 .collect();
11586
11587 for buffer_id in buffer_ids {
11588 if self.is_buffer_folded(buffer_id, cx) {
11589 self.unfold_buffer(buffer_id, cx);
11590 } else {
11591 self.fold_buffer(buffer_id, cx);
11592 }
11593 }
11594 }
11595 }
11596
11597 pub fn toggle_fold_recursive(
11598 &mut self,
11599 _: &actions::ToggleFoldRecursive,
11600 window: &mut Window,
11601 cx: &mut Context<Self>,
11602 ) {
11603 let selection = self.selections.newest::<Point>(cx);
11604
11605 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11606 let range = if selection.is_empty() {
11607 let point = selection.head().to_display_point(&display_map);
11608 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11609 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11610 .to_point(&display_map);
11611 start..end
11612 } else {
11613 selection.range()
11614 };
11615 if display_map.folds_in_range(range).next().is_some() {
11616 self.unfold_recursive(&Default::default(), window, cx)
11617 } else {
11618 self.fold_recursive(&Default::default(), window, cx)
11619 }
11620 }
11621
11622 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11623 if self.is_singleton(cx) {
11624 let mut to_fold = Vec::new();
11625 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11626 let selections = self.selections.all_adjusted(cx);
11627
11628 for selection in selections {
11629 let range = selection.range().sorted();
11630 let buffer_start_row = range.start.row;
11631
11632 if range.start.row != range.end.row {
11633 let mut found = false;
11634 let mut row = range.start.row;
11635 while row <= range.end.row {
11636 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11637 {
11638 found = true;
11639 row = crease.range().end.row + 1;
11640 to_fold.push(crease);
11641 } else {
11642 row += 1
11643 }
11644 }
11645 if found {
11646 continue;
11647 }
11648 }
11649
11650 for row in (0..=range.start.row).rev() {
11651 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11652 if crease.range().end.row >= buffer_start_row {
11653 to_fold.push(crease);
11654 if row <= range.start.row {
11655 break;
11656 }
11657 }
11658 }
11659 }
11660 }
11661
11662 self.fold_creases(to_fold, true, window, cx);
11663 } else {
11664 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11665
11666 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11667 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11668 .map(|(snapshot, _, _)| snapshot.remote_id())
11669 .collect();
11670 for buffer_id in buffer_ids {
11671 self.fold_buffer(buffer_id, cx);
11672 }
11673 }
11674 }
11675
11676 fn fold_at_level(
11677 &mut self,
11678 fold_at: &FoldAtLevel,
11679 window: &mut Window,
11680 cx: &mut Context<Self>,
11681 ) {
11682 if !self.buffer.read(cx).is_singleton() {
11683 return;
11684 }
11685
11686 let fold_at_level = fold_at.level;
11687 let snapshot = self.buffer.read(cx).snapshot(cx);
11688 let mut to_fold = Vec::new();
11689 let mut stack = vec![(0, snapshot.max_row().0, 1)];
11690
11691 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11692 while start_row < end_row {
11693 match self
11694 .snapshot(window, cx)
11695 .crease_for_buffer_row(MultiBufferRow(start_row))
11696 {
11697 Some(crease) => {
11698 let nested_start_row = crease.range().start.row + 1;
11699 let nested_end_row = crease.range().end.row;
11700
11701 if current_level < fold_at_level {
11702 stack.push((nested_start_row, nested_end_row, current_level + 1));
11703 } else if current_level == fold_at_level {
11704 to_fold.push(crease);
11705 }
11706
11707 start_row = nested_end_row + 1;
11708 }
11709 None => start_row += 1,
11710 }
11711 }
11712 }
11713
11714 self.fold_creases(to_fold, true, window, cx);
11715 }
11716
11717 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11718 if self.buffer.read(cx).is_singleton() {
11719 let mut fold_ranges = Vec::new();
11720 let snapshot = self.buffer.read(cx).snapshot(cx);
11721
11722 for row in 0..snapshot.max_row().0 {
11723 if let Some(foldable_range) = self
11724 .snapshot(window, cx)
11725 .crease_for_buffer_row(MultiBufferRow(row))
11726 {
11727 fold_ranges.push(foldable_range);
11728 }
11729 }
11730
11731 self.fold_creases(fold_ranges, true, window, cx);
11732 } else {
11733 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11734 editor
11735 .update_in(&mut cx, |editor, _, cx| {
11736 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11737 editor.fold_buffer(buffer_id, cx);
11738 }
11739 })
11740 .ok();
11741 });
11742 }
11743 }
11744
11745 pub fn fold_function_bodies(
11746 &mut self,
11747 _: &actions::FoldFunctionBodies,
11748 window: &mut Window,
11749 cx: &mut Context<Self>,
11750 ) {
11751 let snapshot = self.buffer.read(cx).snapshot(cx);
11752
11753 let ranges = snapshot
11754 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11755 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11756 .collect::<Vec<_>>();
11757
11758 let creases = ranges
11759 .into_iter()
11760 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11761 .collect();
11762
11763 self.fold_creases(creases, true, window, cx);
11764 }
11765
11766 pub fn fold_recursive(
11767 &mut self,
11768 _: &actions::FoldRecursive,
11769 window: &mut Window,
11770 cx: &mut Context<Self>,
11771 ) {
11772 let mut to_fold = Vec::new();
11773 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11774 let selections = self.selections.all_adjusted(cx);
11775
11776 for selection in selections {
11777 let range = selection.range().sorted();
11778 let buffer_start_row = range.start.row;
11779
11780 if range.start.row != range.end.row {
11781 let mut found = false;
11782 for row in range.start.row..=range.end.row {
11783 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11784 found = true;
11785 to_fold.push(crease);
11786 }
11787 }
11788 if found {
11789 continue;
11790 }
11791 }
11792
11793 for row in (0..=range.start.row).rev() {
11794 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11795 if crease.range().end.row >= buffer_start_row {
11796 to_fold.push(crease);
11797 } else {
11798 break;
11799 }
11800 }
11801 }
11802 }
11803
11804 self.fold_creases(to_fold, true, window, cx);
11805 }
11806
11807 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11808 let buffer_row = fold_at.buffer_row;
11809 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11810
11811 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11812 let autoscroll = self
11813 .selections
11814 .all::<Point>(cx)
11815 .iter()
11816 .any(|selection| crease.range().overlaps(&selection.range()));
11817
11818 self.fold_creases(vec![crease], autoscroll, window, cx);
11819 }
11820 }
11821
11822 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
11823 if self.is_singleton(cx) {
11824 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11825 let buffer = &display_map.buffer_snapshot;
11826 let selections = self.selections.all::<Point>(cx);
11827 let ranges = selections
11828 .iter()
11829 .map(|s| {
11830 let range = s.display_range(&display_map).sorted();
11831 let mut start = range.start.to_point(&display_map);
11832 let mut end = range.end.to_point(&display_map);
11833 start.column = 0;
11834 end.column = buffer.line_len(MultiBufferRow(end.row));
11835 start..end
11836 })
11837 .collect::<Vec<_>>();
11838
11839 self.unfold_ranges(&ranges, true, true, cx);
11840 } else {
11841 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11842 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11843 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11844 .map(|(snapshot, _, _)| snapshot.remote_id())
11845 .collect();
11846 for buffer_id in buffer_ids {
11847 self.unfold_buffer(buffer_id, cx);
11848 }
11849 }
11850 }
11851
11852 pub fn unfold_recursive(
11853 &mut self,
11854 _: &UnfoldRecursive,
11855 _window: &mut Window,
11856 cx: &mut Context<Self>,
11857 ) {
11858 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11859 let selections = self.selections.all::<Point>(cx);
11860 let ranges = selections
11861 .iter()
11862 .map(|s| {
11863 let mut range = s.display_range(&display_map).sorted();
11864 *range.start.column_mut() = 0;
11865 *range.end.column_mut() = display_map.line_len(range.end.row());
11866 let start = range.start.to_point(&display_map);
11867 let end = range.end.to_point(&display_map);
11868 start..end
11869 })
11870 .collect::<Vec<_>>();
11871
11872 self.unfold_ranges(&ranges, true, true, cx);
11873 }
11874
11875 pub fn unfold_at(
11876 &mut self,
11877 unfold_at: &UnfoldAt,
11878 _window: &mut Window,
11879 cx: &mut Context<Self>,
11880 ) {
11881 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11882
11883 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11884 ..Point::new(
11885 unfold_at.buffer_row.0,
11886 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11887 );
11888
11889 let autoscroll = self
11890 .selections
11891 .all::<Point>(cx)
11892 .iter()
11893 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11894
11895 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
11896 }
11897
11898 pub fn unfold_all(
11899 &mut self,
11900 _: &actions::UnfoldAll,
11901 _window: &mut Window,
11902 cx: &mut Context<Self>,
11903 ) {
11904 if self.buffer.read(cx).is_singleton() {
11905 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11906 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11907 } else {
11908 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
11909 editor
11910 .update(&mut cx, |editor, cx| {
11911 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11912 editor.unfold_buffer(buffer_id, cx);
11913 }
11914 })
11915 .ok();
11916 });
11917 }
11918 }
11919
11920 pub fn fold_selected_ranges(
11921 &mut self,
11922 _: &FoldSelectedRanges,
11923 window: &mut Window,
11924 cx: &mut Context<Self>,
11925 ) {
11926 let selections = self.selections.all::<Point>(cx);
11927 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11928 let line_mode = self.selections.line_mode;
11929 let ranges = selections
11930 .into_iter()
11931 .map(|s| {
11932 if line_mode {
11933 let start = Point::new(s.start.row, 0);
11934 let end = Point::new(
11935 s.end.row,
11936 display_map
11937 .buffer_snapshot
11938 .line_len(MultiBufferRow(s.end.row)),
11939 );
11940 Crease::simple(start..end, display_map.fold_placeholder.clone())
11941 } else {
11942 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11943 }
11944 })
11945 .collect::<Vec<_>>();
11946 self.fold_creases(ranges, true, window, cx);
11947 }
11948
11949 pub fn fold_ranges<T: ToOffset + Clone>(
11950 &mut self,
11951 ranges: Vec<Range<T>>,
11952 auto_scroll: bool,
11953 window: &mut Window,
11954 cx: &mut Context<Self>,
11955 ) {
11956 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11957 let ranges = ranges
11958 .into_iter()
11959 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
11960 .collect::<Vec<_>>();
11961 self.fold_creases(ranges, auto_scroll, window, cx);
11962 }
11963
11964 pub fn fold_creases<T: ToOffset + Clone>(
11965 &mut self,
11966 creases: Vec<Crease<T>>,
11967 auto_scroll: bool,
11968 window: &mut Window,
11969 cx: &mut Context<Self>,
11970 ) {
11971 if creases.is_empty() {
11972 return;
11973 }
11974
11975 let mut buffers_affected = HashSet::default();
11976 let multi_buffer = self.buffer().read(cx);
11977 for crease in &creases {
11978 if let Some((_, buffer, _)) =
11979 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11980 {
11981 buffers_affected.insert(buffer.read(cx).remote_id());
11982 };
11983 }
11984
11985 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11986
11987 if auto_scroll {
11988 self.request_autoscroll(Autoscroll::fit(), cx);
11989 }
11990
11991 cx.notify();
11992
11993 if let Some(active_diagnostics) = self.active_diagnostics.take() {
11994 // Clear diagnostics block when folding a range that contains it.
11995 let snapshot = self.snapshot(window, cx);
11996 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11997 drop(snapshot);
11998 self.active_diagnostics = Some(active_diagnostics);
11999 self.dismiss_diagnostics(cx);
12000 } else {
12001 self.active_diagnostics = Some(active_diagnostics);
12002 }
12003 }
12004
12005 self.scrollbar_marker_state.dirty = true;
12006 }
12007
12008 /// Removes any folds whose ranges intersect any of the given ranges.
12009 pub fn unfold_ranges<T: ToOffset + Clone>(
12010 &mut self,
12011 ranges: &[Range<T>],
12012 inclusive: bool,
12013 auto_scroll: bool,
12014 cx: &mut Context<Self>,
12015 ) {
12016 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12017 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12018 });
12019 }
12020
12021 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12022 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12023 return;
12024 }
12025 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12026 self.display_map
12027 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12028 cx.emit(EditorEvent::BufferFoldToggled {
12029 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12030 folded: true,
12031 });
12032 cx.notify();
12033 }
12034
12035 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12036 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12037 return;
12038 }
12039 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12040 self.display_map.update(cx, |display_map, cx| {
12041 display_map.unfold_buffer(buffer_id, cx);
12042 });
12043 cx.emit(EditorEvent::BufferFoldToggled {
12044 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12045 folded: false,
12046 });
12047 cx.notify();
12048 }
12049
12050 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12051 self.display_map.read(cx).is_buffer_folded(buffer)
12052 }
12053
12054 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12055 self.display_map.read(cx).folded_buffers()
12056 }
12057
12058 /// Removes any folds with the given ranges.
12059 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12060 &mut self,
12061 ranges: &[Range<T>],
12062 type_id: TypeId,
12063 auto_scroll: bool,
12064 cx: &mut Context<Self>,
12065 ) {
12066 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12067 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12068 });
12069 }
12070
12071 fn remove_folds_with<T: ToOffset + Clone>(
12072 &mut self,
12073 ranges: &[Range<T>],
12074 auto_scroll: bool,
12075 cx: &mut Context<Self>,
12076 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12077 ) {
12078 if ranges.is_empty() {
12079 return;
12080 }
12081
12082 let mut buffers_affected = HashSet::default();
12083 let multi_buffer = self.buffer().read(cx);
12084 for range in ranges {
12085 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12086 buffers_affected.insert(buffer.read(cx).remote_id());
12087 };
12088 }
12089
12090 self.display_map.update(cx, update);
12091
12092 if auto_scroll {
12093 self.request_autoscroll(Autoscroll::fit(), cx);
12094 }
12095
12096 cx.notify();
12097 self.scrollbar_marker_state.dirty = true;
12098 self.active_indent_guides_state.dirty = true;
12099 }
12100
12101 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12102 self.display_map.read(cx).fold_placeholder.clone()
12103 }
12104
12105 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12106 self.buffer.update(cx, |buffer, cx| {
12107 buffer.set_all_diff_hunks_expanded(cx);
12108 });
12109 }
12110
12111 pub fn expand_all_diff_hunks(
12112 &mut self,
12113 _: &ExpandAllHunkDiffs,
12114 _window: &mut Window,
12115 cx: &mut Context<Self>,
12116 ) {
12117 self.buffer.update(cx, |buffer, cx| {
12118 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12119 });
12120 }
12121
12122 pub fn toggle_selected_diff_hunks(
12123 &mut self,
12124 _: &ToggleSelectedDiffHunks,
12125 _window: &mut Window,
12126 cx: &mut Context<Self>,
12127 ) {
12128 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12129 self.toggle_diff_hunks_in_ranges(ranges, cx);
12130 }
12131
12132 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12133 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12134 self.buffer
12135 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12136 }
12137
12138 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12139 self.buffer.update(cx, |buffer, cx| {
12140 let ranges = vec![Anchor::min()..Anchor::max()];
12141 if !buffer.all_diff_hunks_expanded()
12142 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12143 {
12144 buffer.collapse_diff_hunks(ranges, cx);
12145 true
12146 } else {
12147 false
12148 }
12149 })
12150 }
12151
12152 fn toggle_diff_hunks_in_ranges(
12153 &mut self,
12154 ranges: Vec<Range<Anchor>>,
12155 cx: &mut Context<'_, Editor>,
12156 ) {
12157 self.buffer.update(cx, |buffer, cx| {
12158 if buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx) {
12159 buffer.collapse_diff_hunks(ranges, cx)
12160 } else {
12161 buffer.expand_diff_hunks(ranges, cx)
12162 }
12163 })
12164 }
12165
12166 pub(crate) fn apply_all_diff_hunks(
12167 &mut self,
12168 _: &ApplyAllDiffHunks,
12169 window: &mut Window,
12170 cx: &mut Context<Self>,
12171 ) {
12172 let buffers = self.buffer.read(cx).all_buffers();
12173 for branch_buffer in buffers {
12174 branch_buffer.update(cx, |branch_buffer, cx| {
12175 branch_buffer.merge_into_base(Vec::new(), cx);
12176 });
12177 }
12178
12179 if let Some(project) = self.project.clone() {
12180 self.save(true, project, window, cx).detach_and_log_err(cx);
12181 }
12182 }
12183
12184 pub(crate) fn apply_selected_diff_hunks(
12185 &mut self,
12186 _: &ApplyDiffHunk,
12187 window: &mut Window,
12188 cx: &mut Context<Self>,
12189 ) {
12190 let snapshot = self.snapshot(window, cx);
12191 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12192 let mut ranges_by_buffer = HashMap::default();
12193 self.transact(window, cx, |editor, _window, cx| {
12194 for hunk in hunks {
12195 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12196 ranges_by_buffer
12197 .entry(buffer.clone())
12198 .or_insert_with(Vec::new)
12199 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12200 }
12201 }
12202
12203 for (buffer, ranges) in ranges_by_buffer {
12204 buffer.update(cx, |buffer, cx| {
12205 buffer.merge_into_base(ranges, cx);
12206 });
12207 }
12208 });
12209
12210 if let Some(project) = self.project.clone() {
12211 self.save(true, project, window, cx).detach_and_log_err(cx);
12212 }
12213 }
12214
12215 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12216 if hovered != self.gutter_hovered {
12217 self.gutter_hovered = hovered;
12218 cx.notify();
12219 }
12220 }
12221
12222 pub fn insert_blocks(
12223 &mut self,
12224 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12225 autoscroll: Option<Autoscroll>,
12226 cx: &mut Context<Self>,
12227 ) -> Vec<CustomBlockId> {
12228 let blocks = self
12229 .display_map
12230 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12231 if let Some(autoscroll) = autoscroll {
12232 self.request_autoscroll(autoscroll, cx);
12233 }
12234 cx.notify();
12235 blocks
12236 }
12237
12238 pub fn resize_blocks(
12239 &mut self,
12240 heights: HashMap<CustomBlockId, u32>,
12241 autoscroll: Option<Autoscroll>,
12242 cx: &mut Context<Self>,
12243 ) {
12244 self.display_map
12245 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12246 if let Some(autoscroll) = autoscroll {
12247 self.request_autoscroll(autoscroll, cx);
12248 }
12249 cx.notify();
12250 }
12251
12252 pub fn replace_blocks(
12253 &mut self,
12254 renderers: HashMap<CustomBlockId, RenderBlock>,
12255 autoscroll: Option<Autoscroll>,
12256 cx: &mut Context<Self>,
12257 ) {
12258 self.display_map
12259 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12260 if let Some(autoscroll) = autoscroll {
12261 self.request_autoscroll(autoscroll, cx);
12262 }
12263 cx.notify();
12264 }
12265
12266 pub fn remove_blocks(
12267 &mut self,
12268 block_ids: HashSet<CustomBlockId>,
12269 autoscroll: Option<Autoscroll>,
12270 cx: &mut Context<Self>,
12271 ) {
12272 self.display_map.update(cx, |display_map, cx| {
12273 display_map.remove_blocks(block_ids, cx)
12274 });
12275 if let Some(autoscroll) = autoscroll {
12276 self.request_autoscroll(autoscroll, cx);
12277 }
12278 cx.notify();
12279 }
12280
12281 pub fn row_for_block(
12282 &self,
12283 block_id: CustomBlockId,
12284 cx: &mut Context<Self>,
12285 ) -> Option<DisplayRow> {
12286 self.display_map
12287 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12288 }
12289
12290 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12291 self.focused_block = Some(focused_block);
12292 }
12293
12294 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12295 self.focused_block.take()
12296 }
12297
12298 pub fn insert_creases(
12299 &mut self,
12300 creases: impl IntoIterator<Item = Crease<Anchor>>,
12301 cx: &mut Context<Self>,
12302 ) -> Vec<CreaseId> {
12303 self.display_map
12304 .update(cx, |map, cx| map.insert_creases(creases, cx))
12305 }
12306
12307 pub fn remove_creases(
12308 &mut self,
12309 ids: impl IntoIterator<Item = CreaseId>,
12310 cx: &mut Context<Self>,
12311 ) {
12312 self.display_map
12313 .update(cx, |map, cx| map.remove_creases(ids, cx));
12314 }
12315
12316 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12317 self.display_map
12318 .update(cx, |map, cx| map.snapshot(cx))
12319 .longest_row()
12320 }
12321
12322 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12323 self.display_map
12324 .update(cx, |map, cx| map.snapshot(cx))
12325 .max_point()
12326 }
12327
12328 pub fn text(&self, cx: &App) -> String {
12329 self.buffer.read(cx).read(cx).text()
12330 }
12331
12332 pub fn is_empty(&self, cx: &App) -> bool {
12333 self.buffer.read(cx).read(cx).is_empty()
12334 }
12335
12336 pub fn text_option(&self, cx: &App) -> Option<String> {
12337 let text = self.text(cx);
12338 let text = text.trim();
12339
12340 if text.is_empty() {
12341 return None;
12342 }
12343
12344 Some(text.to_string())
12345 }
12346
12347 pub fn set_text(
12348 &mut self,
12349 text: impl Into<Arc<str>>,
12350 window: &mut Window,
12351 cx: &mut Context<Self>,
12352 ) {
12353 self.transact(window, cx, |this, _, cx| {
12354 this.buffer
12355 .read(cx)
12356 .as_singleton()
12357 .expect("you can only call set_text on editors for singleton buffers")
12358 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12359 });
12360 }
12361
12362 pub fn display_text(&self, cx: &mut App) -> String {
12363 self.display_map
12364 .update(cx, |map, cx| map.snapshot(cx))
12365 .text()
12366 }
12367
12368 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12369 let mut wrap_guides = smallvec::smallvec![];
12370
12371 if self.show_wrap_guides == Some(false) {
12372 return wrap_guides;
12373 }
12374
12375 let settings = self.buffer.read(cx).settings_at(0, cx);
12376 if settings.show_wrap_guides {
12377 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12378 wrap_guides.push((soft_wrap as usize, true));
12379 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12380 wrap_guides.push((soft_wrap as usize, true));
12381 }
12382 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12383 }
12384
12385 wrap_guides
12386 }
12387
12388 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12389 let settings = self.buffer.read(cx).settings_at(0, cx);
12390 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12391 match mode {
12392 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12393 SoftWrap::None
12394 }
12395 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12396 language_settings::SoftWrap::PreferredLineLength => {
12397 SoftWrap::Column(settings.preferred_line_length)
12398 }
12399 language_settings::SoftWrap::Bounded => {
12400 SoftWrap::Bounded(settings.preferred_line_length)
12401 }
12402 }
12403 }
12404
12405 pub fn set_soft_wrap_mode(
12406 &mut self,
12407 mode: language_settings::SoftWrap,
12408
12409 cx: &mut Context<Self>,
12410 ) {
12411 self.soft_wrap_mode_override = Some(mode);
12412 cx.notify();
12413 }
12414
12415 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12416 self.text_style_refinement = Some(style);
12417 }
12418
12419 /// called by the Element so we know what style we were most recently rendered with.
12420 pub(crate) fn set_style(
12421 &mut self,
12422 style: EditorStyle,
12423 window: &mut Window,
12424 cx: &mut Context<Self>,
12425 ) {
12426 let rem_size = window.rem_size();
12427 self.display_map.update(cx, |map, cx| {
12428 map.set_font(
12429 style.text.font(),
12430 style.text.font_size.to_pixels(rem_size),
12431 cx,
12432 )
12433 });
12434 self.style = Some(style);
12435 }
12436
12437 pub fn style(&self) -> Option<&EditorStyle> {
12438 self.style.as_ref()
12439 }
12440
12441 // Called by the element. This method is not designed to be called outside of the editor
12442 // element's layout code because it does not notify when rewrapping is computed synchronously.
12443 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12444 self.display_map
12445 .update(cx, |map, cx| map.set_wrap_width(width, cx))
12446 }
12447
12448 pub fn set_soft_wrap(&mut self) {
12449 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12450 }
12451
12452 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12453 if self.soft_wrap_mode_override.is_some() {
12454 self.soft_wrap_mode_override.take();
12455 } else {
12456 let soft_wrap = match self.soft_wrap_mode(cx) {
12457 SoftWrap::GitDiff => return,
12458 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12459 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12460 language_settings::SoftWrap::None
12461 }
12462 };
12463 self.soft_wrap_mode_override = Some(soft_wrap);
12464 }
12465 cx.notify();
12466 }
12467
12468 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12469 let Some(workspace) = self.workspace() else {
12470 return;
12471 };
12472 let fs = workspace.read(cx).app_state().fs.clone();
12473 let current_show = TabBarSettings::get_global(cx).show;
12474 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12475 setting.show = Some(!current_show);
12476 });
12477 }
12478
12479 pub fn toggle_indent_guides(
12480 &mut self,
12481 _: &ToggleIndentGuides,
12482 _: &mut Window,
12483 cx: &mut Context<Self>,
12484 ) {
12485 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12486 self.buffer
12487 .read(cx)
12488 .settings_at(0, cx)
12489 .indent_guides
12490 .enabled
12491 });
12492 self.show_indent_guides = Some(!currently_enabled);
12493 cx.notify();
12494 }
12495
12496 fn should_show_indent_guides(&self) -> Option<bool> {
12497 self.show_indent_guides
12498 }
12499
12500 pub fn toggle_line_numbers(
12501 &mut self,
12502 _: &ToggleLineNumbers,
12503 _: &mut Window,
12504 cx: &mut Context<Self>,
12505 ) {
12506 let mut editor_settings = EditorSettings::get_global(cx).clone();
12507 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12508 EditorSettings::override_global(editor_settings, cx);
12509 }
12510
12511 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12512 self.use_relative_line_numbers
12513 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12514 }
12515
12516 pub fn toggle_relative_line_numbers(
12517 &mut self,
12518 _: &ToggleRelativeLineNumbers,
12519 _: &mut Window,
12520 cx: &mut Context<Self>,
12521 ) {
12522 let is_relative = self.should_use_relative_line_numbers(cx);
12523 self.set_relative_line_number(Some(!is_relative), cx)
12524 }
12525
12526 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12527 self.use_relative_line_numbers = is_relative;
12528 cx.notify();
12529 }
12530
12531 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12532 self.show_gutter = show_gutter;
12533 cx.notify();
12534 }
12535
12536 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12537 self.show_scrollbars = show_scrollbars;
12538 cx.notify();
12539 }
12540
12541 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12542 self.show_line_numbers = Some(show_line_numbers);
12543 cx.notify();
12544 }
12545
12546 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12547 self.show_git_diff_gutter = Some(show_git_diff_gutter);
12548 cx.notify();
12549 }
12550
12551 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12552 self.show_code_actions = Some(show_code_actions);
12553 cx.notify();
12554 }
12555
12556 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12557 self.show_runnables = Some(show_runnables);
12558 cx.notify();
12559 }
12560
12561 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12562 if self.display_map.read(cx).masked != masked {
12563 self.display_map.update(cx, |map, _| map.masked = masked);
12564 }
12565 cx.notify()
12566 }
12567
12568 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12569 self.show_wrap_guides = Some(show_wrap_guides);
12570 cx.notify();
12571 }
12572
12573 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12574 self.show_indent_guides = Some(show_indent_guides);
12575 cx.notify();
12576 }
12577
12578 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12579 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12580 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12581 if let Some(dir) = file.abs_path(cx).parent() {
12582 return Some(dir.to_owned());
12583 }
12584 }
12585
12586 if let Some(project_path) = buffer.read(cx).project_path(cx) {
12587 return Some(project_path.path.to_path_buf());
12588 }
12589 }
12590
12591 None
12592 }
12593
12594 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12595 self.active_excerpt(cx)?
12596 .1
12597 .read(cx)
12598 .file()
12599 .and_then(|f| f.as_local())
12600 }
12601
12602 fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12603 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12604 let project_path = buffer.read(cx).project_path(cx)?;
12605 let project = self.project.as_ref()?.read(cx);
12606 project.absolute_path(&project_path, cx)
12607 })
12608 }
12609
12610 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12611 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12612 let project_path = buffer.read(cx).project_path(cx)?;
12613 let project = self.project.as_ref()?.read(cx);
12614 let entry = project.entry_for_path(&project_path, cx)?;
12615 let path = entry.path.to_path_buf();
12616 Some(path)
12617 })
12618 }
12619
12620 pub fn reveal_in_finder(
12621 &mut self,
12622 _: &RevealInFileManager,
12623 _window: &mut Window,
12624 cx: &mut Context<Self>,
12625 ) {
12626 if let Some(target) = self.target_file(cx) {
12627 cx.reveal_path(&target.abs_path(cx));
12628 }
12629 }
12630
12631 pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12632 if let Some(path) = self.target_file_abs_path(cx) {
12633 if let Some(path) = path.to_str() {
12634 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12635 }
12636 }
12637 }
12638
12639 pub fn copy_relative_path(
12640 &mut self,
12641 _: &CopyRelativePath,
12642 _window: &mut Window,
12643 cx: &mut Context<Self>,
12644 ) {
12645 if let Some(path) = self.target_file_path(cx) {
12646 if let Some(path) = path.to_str() {
12647 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12648 }
12649 }
12650 }
12651
12652 pub fn toggle_git_blame(
12653 &mut self,
12654 _: &ToggleGitBlame,
12655 window: &mut Window,
12656 cx: &mut Context<Self>,
12657 ) {
12658 self.show_git_blame_gutter = !self.show_git_blame_gutter;
12659
12660 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12661 self.start_git_blame(true, window, cx);
12662 }
12663
12664 cx.notify();
12665 }
12666
12667 pub fn toggle_git_blame_inline(
12668 &mut self,
12669 _: &ToggleGitBlameInline,
12670 window: &mut Window,
12671 cx: &mut Context<Self>,
12672 ) {
12673 self.toggle_git_blame_inline_internal(true, window, cx);
12674 cx.notify();
12675 }
12676
12677 pub fn git_blame_inline_enabled(&self) -> bool {
12678 self.git_blame_inline_enabled
12679 }
12680
12681 pub fn toggle_selection_menu(
12682 &mut self,
12683 _: &ToggleSelectionMenu,
12684 _: &mut Window,
12685 cx: &mut Context<Self>,
12686 ) {
12687 self.show_selection_menu = self
12688 .show_selection_menu
12689 .map(|show_selections_menu| !show_selections_menu)
12690 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12691
12692 cx.notify();
12693 }
12694
12695 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12696 self.show_selection_menu
12697 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12698 }
12699
12700 fn start_git_blame(
12701 &mut self,
12702 user_triggered: bool,
12703 window: &mut Window,
12704 cx: &mut Context<Self>,
12705 ) {
12706 if let Some(project) = self.project.as_ref() {
12707 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12708 return;
12709 };
12710
12711 if buffer.read(cx).file().is_none() {
12712 return;
12713 }
12714
12715 let focused = self.focus_handle(cx).contains_focused(window, cx);
12716
12717 let project = project.clone();
12718 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12719 self.blame_subscription =
12720 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12721 self.blame = Some(blame);
12722 }
12723 }
12724
12725 fn toggle_git_blame_inline_internal(
12726 &mut self,
12727 user_triggered: bool,
12728 window: &mut Window,
12729 cx: &mut Context<Self>,
12730 ) {
12731 if self.git_blame_inline_enabled {
12732 self.git_blame_inline_enabled = false;
12733 self.show_git_blame_inline = false;
12734 self.show_git_blame_inline_delay_task.take();
12735 } else {
12736 self.git_blame_inline_enabled = true;
12737 self.start_git_blame_inline(user_triggered, window, cx);
12738 }
12739
12740 cx.notify();
12741 }
12742
12743 fn start_git_blame_inline(
12744 &mut self,
12745 user_triggered: bool,
12746 window: &mut Window,
12747 cx: &mut Context<Self>,
12748 ) {
12749 self.start_git_blame(user_triggered, window, cx);
12750
12751 if ProjectSettings::get_global(cx)
12752 .git
12753 .inline_blame_delay()
12754 .is_some()
12755 {
12756 self.start_inline_blame_timer(window, cx);
12757 } else {
12758 self.show_git_blame_inline = true
12759 }
12760 }
12761
12762 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12763 self.blame.as_ref()
12764 }
12765
12766 pub fn show_git_blame_gutter(&self) -> bool {
12767 self.show_git_blame_gutter
12768 }
12769
12770 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12771 self.show_git_blame_gutter && self.has_blame_entries(cx)
12772 }
12773
12774 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12775 self.show_git_blame_inline
12776 && self.focus_handle.is_focused(window)
12777 && !self.newest_selection_head_on_empty_line(cx)
12778 && self.has_blame_entries(cx)
12779 }
12780
12781 fn has_blame_entries(&self, cx: &App) -> bool {
12782 self.blame()
12783 .map_or(false, |blame| blame.read(cx).has_generated_entries())
12784 }
12785
12786 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12787 let cursor_anchor = self.selections.newest_anchor().head();
12788
12789 let snapshot = self.buffer.read(cx).snapshot(cx);
12790 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12791
12792 snapshot.line_len(buffer_row) == 0
12793 }
12794
12795 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12796 let buffer_and_selection = maybe!({
12797 let selection = self.selections.newest::<Point>(cx);
12798 let selection_range = selection.range();
12799
12800 let multi_buffer = self.buffer().read(cx);
12801 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12802 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12803
12804 let (buffer, range, _) = if selection.reversed {
12805 buffer_ranges.first()
12806 } else {
12807 buffer_ranges.last()
12808 }?;
12809
12810 let selection = text::ToPoint::to_point(&range.start, &buffer).row
12811 ..text::ToPoint::to_point(&range.end, &buffer).row;
12812 Some((
12813 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
12814 selection,
12815 ))
12816 });
12817
12818 let Some((buffer, selection)) = buffer_and_selection else {
12819 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12820 };
12821
12822 let Some(project) = self.project.as_ref() else {
12823 return Task::ready(Err(anyhow!("editor does not have project")));
12824 };
12825
12826 project.update(cx, |project, cx| {
12827 project.get_permalink_to_line(&buffer, selection, cx)
12828 })
12829 }
12830
12831 pub fn copy_permalink_to_line(
12832 &mut self,
12833 _: &CopyPermalinkToLine,
12834 window: &mut Window,
12835 cx: &mut Context<Self>,
12836 ) {
12837 let permalink_task = self.get_permalink_to_line(cx);
12838 let workspace = self.workspace();
12839
12840 cx.spawn_in(window, |_, mut cx| async move {
12841 match permalink_task.await {
12842 Ok(permalink) => {
12843 cx.update(|_, cx| {
12844 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12845 })
12846 .ok();
12847 }
12848 Err(err) => {
12849 let message = format!("Failed to copy permalink: {err}");
12850
12851 Err::<(), anyhow::Error>(err).log_err();
12852
12853 if let Some(workspace) = workspace {
12854 workspace
12855 .update_in(&mut cx, |workspace, _, cx| {
12856 struct CopyPermalinkToLine;
12857
12858 workspace.show_toast(
12859 Toast::new(
12860 NotificationId::unique::<CopyPermalinkToLine>(),
12861 message,
12862 ),
12863 cx,
12864 )
12865 })
12866 .ok();
12867 }
12868 }
12869 }
12870 })
12871 .detach();
12872 }
12873
12874 pub fn copy_file_location(
12875 &mut self,
12876 _: &CopyFileLocation,
12877 _: &mut Window,
12878 cx: &mut Context<Self>,
12879 ) {
12880 let selection = self.selections.newest::<Point>(cx).start.row + 1;
12881 if let Some(file) = self.target_file(cx) {
12882 if let Some(path) = file.path().to_str() {
12883 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
12884 }
12885 }
12886 }
12887
12888 pub fn open_permalink_to_line(
12889 &mut self,
12890 _: &OpenPermalinkToLine,
12891 window: &mut Window,
12892 cx: &mut Context<Self>,
12893 ) {
12894 let permalink_task = self.get_permalink_to_line(cx);
12895 let workspace = self.workspace();
12896
12897 cx.spawn_in(window, |_, mut cx| async move {
12898 match permalink_task.await {
12899 Ok(permalink) => {
12900 cx.update(|_, cx| {
12901 cx.open_url(permalink.as_ref());
12902 })
12903 .ok();
12904 }
12905 Err(err) => {
12906 let message = format!("Failed to open permalink: {err}");
12907
12908 Err::<(), anyhow::Error>(err).log_err();
12909
12910 if let Some(workspace) = workspace {
12911 workspace
12912 .update(&mut cx, |workspace, cx| {
12913 struct OpenPermalinkToLine;
12914
12915 workspace.show_toast(
12916 Toast::new(
12917 NotificationId::unique::<OpenPermalinkToLine>(),
12918 message,
12919 ),
12920 cx,
12921 )
12922 })
12923 .ok();
12924 }
12925 }
12926 }
12927 })
12928 .detach();
12929 }
12930
12931 pub fn insert_uuid_v4(
12932 &mut self,
12933 _: &InsertUuidV4,
12934 window: &mut Window,
12935 cx: &mut Context<Self>,
12936 ) {
12937 self.insert_uuid(UuidVersion::V4, window, cx);
12938 }
12939
12940 pub fn insert_uuid_v7(
12941 &mut self,
12942 _: &InsertUuidV7,
12943 window: &mut Window,
12944 cx: &mut Context<Self>,
12945 ) {
12946 self.insert_uuid(UuidVersion::V7, window, cx);
12947 }
12948
12949 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
12950 self.transact(window, cx, |this, window, cx| {
12951 let edits = this
12952 .selections
12953 .all::<Point>(cx)
12954 .into_iter()
12955 .map(|selection| {
12956 let uuid = match version {
12957 UuidVersion::V4 => uuid::Uuid::new_v4(),
12958 UuidVersion::V7 => uuid::Uuid::now_v7(),
12959 };
12960
12961 (selection.range(), uuid.to_string())
12962 });
12963 this.edit(edits, cx);
12964 this.refresh_inline_completion(true, false, window, cx);
12965 });
12966 }
12967
12968 pub fn open_selections_in_multibuffer(
12969 &mut self,
12970 _: &OpenSelectionsInMultibuffer,
12971 window: &mut Window,
12972 cx: &mut Context<Self>,
12973 ) {
12974 let multibuffer = self.buffer.read(cx);
12975
12976 let Some(buffer) = multibuffer.as_singleton() else {
12977 return;
12978 };
12979
12980 let Some(workspace) = self.workspace() else {
12981 return;
12982 };
12983
12984 let locations = self
12985 .selections
12986 .disjoint_anchors()
12987 .iter()
12988 .map(|range| Location {
12989 buffer: buffer.clone(),
12990 range: range.start.text_anchor..range.end.text_anchor,
12991 })
12992 .collect::<Vec<_>>();
12993
12994 let title = multibuffer.title(cx).to_string();
12995
12996 cx.spawn_in(window, |_, mut cx| async move {
12997 workspace.update_in(&mut cx, |workspace, window, cx| {
12998 Self::open_locations_in_multibuffer(
12999 workspace,
13000 locations,
13001 format!("Selections for '{title}'"),
13002 false,
13003 MultibufferSelectionMode::All,
13004 window,
13005 cx,
13006 );
13007 })
13008 })
13009 .detach();
13010 }
13011
13012 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13013 /// last highlight added will be used.
13014 ///
13015 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13016 pub fn highlight_rows<T: 'static>(
13017 &mut self,
13018 range: Range<Anchor>,
13019 color: Hsla,
13020 should_autoscroll: bool,
13021 cx: &mut Context<Self>,
13022 ) {
13023 let snapshot = self.buffer().read(cx).snapshot(cx);
13024 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13025 let ix = row_highlights.binary_search_by(|highlight| {
13026 Ordering::Equal
13027 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13028 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13029 });
13030
13031 if let Err(mut ix) = ix {
13032 let index = post_inc(&mut self.highlight_order);
13033
13034 // If this range intersects with the preceding highlight, then merge it with
13035 // the preceding highlight. Otherwise insert a new highlight.
13036 let mut merged = false;
13037 if ix > 0 {
13038 let prev_highlight = &mut row_highlights[ix - 1];
13039 if prev_highlight
13040 .range
13041 .end
13042 .cmp(&range.start, &snapshot)
13043 .is_ge()
13044 {
13045 ix -= 1;
13046 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13047 prev_highlight.range.end = range.end;
13048 }
13049 merged = true;
13050 prev_highlight.index = index;
13051 prev_highlight.color = color;
13052 prev_highlight.should_autoscroll = should_autoscroll;
13053 }
13054 }
13055
13056 if !merged {
13057 row_highlights.insert(
13058 ix,
13059 RowHighlight {
13060 range: range.clone(),
13061 index,
13062 color,
13063 should_autoscroll,
13064 },
13065 );
13066 }
13067
13068 // If any of the following highlights intersect with this one, merge them.
13069 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13070 let highlight = &row_highlights[ix];
13071 if next_highlight
13072 .range
13073 .start
13074 .cmp(&highlight.range.end, &snapshot)
13075 .is_le()
13076 {
13077 if next_highlight
13078 .range
13079 .end
13080 .cmp(&highlight.range.end, &snapshot)
13081 .is_gt()
13082 {
13083 row_highlights[ix].range.end = next_highlight.range.end;
13084 }
13085 row_highlights.remove(ix + 1);
13086 } else {
13087 break;
13088 }
13089 }
13090 }
13091 }
13092
13093 /// Remove any highlighted row ranges of the given type that intersect the
13094 /// given ranges.
13095 pub fn remove_highlighted_rows<T: 'static>(
13096 &mut self,
13097 ranges_to_remove: Vec<Range<Anchor>>,
13098 cx: &mut Context<Self>,
13099 ) {
13100 let snapshot = self.buffer().read(cx).snapshot(cx);
13101 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13102 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13103 row_highlights.retain(|highlight| {
13104 while let Some(range_to_remove) = ranges_to_remove.peek() {
13105 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13106 Ordering::Less | Ordering::Equal => {
13107 ranges_to_remove.next();
13108 }
13109 Ordering::Greater => {
13110 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13111 Ordering::Less | Ordering::Equal => {
13112 return false;
13113 }
13114 Ordering::Greater => break,
13115 }
13116 }
13117 }
13118 }
13119
13120 true
13121 })
13122 }
13123
13124 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13125 pub fn clear_row_highlights<T: 'static>(&mut self) {
13126 self.highlighted_rows.remove(&TypeId::of::<T>());
13127 }
13128
13129 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13130 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13131 self.highlighted_rows
13132 .get(&TypeId::of::<T>())
13133 .map_or(&[] as &[_], |vec| vec.as_slice())
13134 .iter()
13135 .map(|highlight| (highlight.range.clone(), highlight.color))
13136 }
13137
13138 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13139 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13140 /// Allows to ignore certain kinds of highlights.
13141 pub fn highlighted_display_rows(
13142 &self,
13143 window: &mut Window,
13144 cx: &mut App,
13145 ) -> BTreeMap<DisplayRow, Hsla> {
13146 let snapshot = self.snapshot(window, cx);
13147 let mut used_highlight_orders = HashMap::default();
13148 self.highlighted_rows
13149 .iter()
13150 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13151 .fold(
13152 BTreeMap::<DisplayRow, Hsla>::new(),
13153 |mut unique_rows, highlight| {
13154 let start = highlight.range.start.to_display_point(&snapshot);
13155 let end = highlight.range.end.to_display_point(&snapshot);
13156 let start_row = start.row().0;
13157 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13158 && end.column() == 0
13159 {
13160 end.row().0.saturating_sub(1)
13161 } else {
13162 end.row().0
13163 };
13164 for row in start_row..=end_row {
13165 let used_index =
13166 used_highlight_orders.entry(row).or_insert(highlight.index);
13167 if highlight.index >= *used_index {
13168 *used_index = highlight.index;
13169 unique_rows.insert(DisplayRow(row), highlight.color);
13170 }
13171 }
13172 unique_rows
13173 },
13174 )
13175 }
13176
13177 pub fn highlighted_display_row_for_autoscroll(
13178 &self,
13179 snapshot: &DisplaySnapshot,
13180 ) -> Option<DisplayRow> {
13181 self.highlighted_rows
13182 .values()
13183 .flat_map(|highlighted_rows| highlighted_rows.iter())
13184 .filter_map(|highlight| {
13185 if highlight.should_autoscroll {
13186 Some(highlight.range.start.to_display_point(snapshot).row())
13187 } else {
13188 None
13189 }
13190 })
13191 .min()
13192 }
13193
13194 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13195 self.highlight_background::<SearchWithinRange>(
13196 ranges,
13197 |colors| colors.editor_document_highlight_read_background,
13198 cx,
13199 )
13200 }
13201
13202 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13203 self.breadcrumb_header = Some(new_header);
13204 }
13205
13206 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13207 self.clear_background_highlights::<SearchWithinRange>(cx);
13208 }
13209
13210 pub fn highlight_background<T: 'static>(
13211 &mut self,
13212 ranges: &[Range<Anchor>],
13213 color_fetcher: fn(&ThemeColors) -> Hsla,
13214 cx: &mut Context<Self>,
13215 ) {
13216 self.background_highlights
13217 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13218 self.scrollbar_marker_state.dirty = true;
13219 cx.notify();
13220 }
13221
13222 pub fn clear_background_highlights<T: 'static>(
13223 &mut self,
13224 cx: &mut Context<Self>,
13225 ) -> Option<BackgroundHighlight> {
13226 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13227 if !text_highlights.1.is_empty() {
13228 self.scrollbar_marker_state.dirty = true;
13229 cx.notify();
13230 }
13231 Some(text_highlights)
13232 }
13233
13234 pub fn highlight_gutter<T: 'static>(
13235 &mut self,
13236 ranges: &[Range<Anchor>],
13237 color_fetcher: fn(&App) -> Hsla,
13238 cx: &mut Context<Self>,
13239 ) {
13240 self.gutter_highlights
13241 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13242 cx.notify();
13243 }
13244
13245 pub fn clear_gutter_highlights<T: 'static>(
13246 &mut self,
13247 cx: &mut Context<Self>,
13248 ) -> Option<GutterHighlight> {
13249 cx.notify();
13250 self.gutter_highlights.remove(&TypeId::of::<T>())
13251 }
13252
13253 #[cfg(feature = "test-support")]
13254 pub fn all_text_background_highlights(
13255 &self,
13256 window: &mut Window,
13257 cx: &mut Context<Self>,
13258 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13259 let snapshot = self.snapshot(window, cx);
13260 let buffer = &snapshot.buffer_snapshot;
13261 let start = buffer.anchor_before(0);
13262 let end = buffer.anchor_after(buffer.len());
13263 let theme = cx.theme().colors();
13264 self.background_highlights_in_range(start..end, &snapshot, theme)
13265 }
13266
13267 #[cfg(feature = "test-support")]
13268 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13269 let snapshot = self.buffer().read(cx).snapshot(cx);
13270
13271 let highlights = self
13272 .background_highlights
13273 .get(&TypeId::of::<items::BufferSearchHighlights>());
13274
13275 if let Some((_color, ranges)) = highlights {
13276 ranges
13277 .iter()
13278 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13279 .collect_vec()
13280 } else {
13281 vec![]
13282 }
13283 }
13284
13285 fn document_highlights_for_position<'a>(
13286 &'a self,
13287 position: Anchor,
13288 buffer: &'a MultiBufferSnapshot,
13289 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13290 let read_highlights = self
13291 .background_highlights
13292 .get(&TypeId::of::<DocumentHighlightRead>())
13293 .map(|h| &h.1);
13294 let write_highlights = self
13295 .background_highlights
13296 .get(&TypeId::of::<DocumentHighlightWrite>())
13297 .map(|h| &h.1);
13298 let left_position = position.bias_left(buffer);
13299 let right_position = position.bias_right(buffer);
13300 read_highlights
13301 .into_iter()
13302 .chain(write_highlights)
13303 .flat_map(move |ranges| {
13304 let start_ix = match ranges.binary_search_by(|probe| {
13305 let cmp = probe.end.cmp(&left_position, buffer);
13306 if cmp.is_ge() {
13307 Ordering::Greater
13308 } else {
13309 Ordering::Less
13310 }
13311 }) {
13312 Ok(i) | Err(i) => i,
13313 };
13314
13315 ranges[start_ix..]
13316 .iter()
13317 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13318 })
13319 }
13320
13321 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13322 self.background_highlights
13323 .get(&TypeId::of::<T>())
13324 .map_or(false, |(_, highlights)| !highlights.is_empty())
13325 }
13326
13327 pub fn background_highlights_in_range(
13328 &self,
13329 search_range: Range<Anchor>,
13330 display_snapshot: &DisplaySnapshot,
13331 theme: &ThemeColors,
13332 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13333 let mut results = Vec::new();
13334 for (color_fetcher, ranges) in self.background_highlights.values() {
13335 let color = color_fetcher(theme);
13336 let start_ix = match ranges.binary_search_by(|probe| {
13337 let cmp = probe
13338 .end
13339 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13340 if cmp.is_gt() {
13341 Ordering::Greater
13342 } else {
13343 Ordering::Less
13344 }
13345 }) {
13346 Ok(i) | Err(i) => i,
13347 };
13348 for range in &ranges[start_ix..] {
13349 if range
13350 .start
13351 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13352 .is_ge()
13353 {
13354 break;
13355 }
13356
13357 let start = range.start.to_display_point(display_snapshot);
13358 let end = range.end.to_display_point(display_snapshot);
13359 results.push((start..end, color))
13360 }
13361 }
13362 results
13363 }
13364
13365 pub fn background_highlight_row_ranges<T: 'static>(
13366 &self,
13367 search_range: Range<Anchor>,
13368 display_snapshot: &DisplaySnapshot,
13369 count: usize,
13370 ) -> Vec<RangeInclusive<DisplayPoint>> {
13371 let mut results = Vec::new();
13372 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13373 return vec![];
13374 };
13375
13376 let start_ix = match ranges.binary_search_by(|probe| {
13377 let cmp = probe
13378 .end
13379 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13380 if cmp.is_gt() {
13381 Ordering::Greater
13382 } else {
13383 Ordering::Less
13384 }
13385 }) {
13386 Ok(i) | Err(i) => i,
13387 };
13388 let mut push_region = |start: Option<Point>, end: Option<Point>| {
13389 if let (Some(start_display), Some(end_display)) = (start, end) {
13390 results.push(
13391 start_display.to_display_point(display_snapshot)
13392 ..=end_display.to_display_point(display_snapshot),
13393 );
13394 }
13395 };
13396 let mut start_row: Option<Point> = None;
13397 let mut end_row: Option<Point> = None;
13398 if ranges.len() > count {
13399 return Vec::new();
13400 }
13401 for range in &ranges[start_ix..] {
13402 if range
13403 .start
13404 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13405 .is_ge()
13406 {
13407 break;
13408 }
13409 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13410 if let Some(current_row) = &end_row {
13411 if end.row == current_row.row {
13412 continue;
13413 }
13414 }
13415 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13416 if start_row.is_none() {
13417 assert_eq!(end_row, None);
13418 start_row = Some(start);
13419 end_row = Some(end);
13420 continue;
13421 }
13422 if let Some(current_end) = end_row.as_mut() {
13423 if start.row > current_end.row + 1 {
13424 push_region(start_row, end_row);
13425 start_row = Some(start);
13426 end_row = Some(end);
13427 } else {
13428 // Merge two hunks.
13429 *current_end = end;
13430 }
13431 } else {
13432 unreachable!();
13433 }
13434 }
13435 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13436 push_region(start_row, end_row);
13437 results
13438 }
13439
13440 pub fn gutter_highlights_in_range(
13441 &self,
13442 search_range: Range<Anchor>,
13443 display_snapshot: &DisplaySnapshot,
13444 cx: &App,
13445 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13446 let mut results = Vec::new();
13447 for (color_fetcher, ranges) in self.gutter_highlights.values() {
13448 let color = color_fetcher(cx);
13449 let start_ix = match ranges.binary_search_by(|probe| {
13450 let cmp = probe
13451 .end
13452 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13453 if cmp.is_gt() {
13454 Ordering::Greater
13455 } else {
13456 Ordering::Less
13457 }
13458 }) {
13459 Ok(i) | Err(i) => i,
13460 };
13461 for range in &ranges[start_ix..] {
13462 if range
13463 .start
13464 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13465 .is_ge()
13466 {
13467 break;
13468 }
13469
13470 let start = range.start.to_display_point(display_snapshot);
13471 let end = range.end.to_display_point(display_snapshot);
13472 results.push((start..end, color))
13473 }
13474 }
13475 results
13476 }
13477
13478 /// Get the text ranges corresponding to the redaction query
13479 pub fn redacted_ranges(
13480 &self,
13481 search_range: Range<Anchor>,
13482 display_snapshot: &DisplaySnapshot,
13483 cx: &App,
13484 ) -> Vec<Range<DisplayPoint>> {
13485 display_snapshot
13486 .buffer_snapshot
13487 .redacted_ranges(search_range, |file| {
13488 if let Some(file) = file {
13489 file.is_private()
13490 && EditorSettings::get(
13491 Some(SettingsLocation {
13492 worktree_id: file.worktree_id(cx),
13493 path: file.path().as_ref(),
13494 }),
13495 cx,
13496 )
13497 .redact_private_values
13498 } else {
13499 false
13500 }
13501 })
13502 .map(|range| {
13503 range.start.to_display_point(display_snapshot)
13504 ..range.end.to_display_point(display_snapshot)
13505 })
13506 .collect()
13507 }
13508
13509 pub fn highlight_text<T: 'static>(
13510 &mut self,
13511 ranges: Vec<Range<Anchor>>,
13512 style: HighlightStyle,
13513 cx: &mut Context<Self>,
13514 ) {
13515 self.display_map.update(cx, |map, _| {
13516 map.highlight_text(TypeId::of::<T>(), ranges, style)
13517 });
13518 cx.notify();
13519 }
13520
13521 pub(crate) fn highlight_inlays<T: 'static>(
13522 &mut self,
13523 highlights: Vec<InlayHighlight>,
13524 style: HighlightStyle,
13525 cx: &mut Context<Self>,
13526 ) {
13527 self.display_map.update(cx, |map, _| {
13528 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13529 });
13530 cx.notify();
13531 }
13532
13533 pub fn text_highlights<'a, T: 'static>(
13534 &'a self,
13535 cx: &'a App,
13536 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13537 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13538 }
13539
13540 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13541 let cleared = self
13542 .display_map
13543 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13544 if cleared {
13545 cx.notify();
13546 }
13547 }
13548
13549 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13550 (self.read_only(cx) || self.blink_manager.read(cx).visible())
13551 && self.focus_handle.is_focused(window)
13552 }
13553
13554 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13555 self.show_cursor_when_unfocused = is_enabled;
13556 cx.notify();
13557 }
13558
13559 pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13560 self.project
13561 .as_ref()
13562 .map(|project| project.read(cx).lsp_store())
13563 }
13564
13565 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13566 cx.notify();
13567 }
13568
13569 fn on_buffer_event(
13570 &mut self,
13571 multibuffer: &Entity<MultiBuffer>,
13572 event: &multi_buffer::Event,
13573 window: &mut Window,
13574 cx: &mut Context<Self>,
13575 ) {
13576 match event {
13577 multi_buffer::Event::Edited {
13578 singleton_buffer_edited,
13579 edited_buffer: buffer_edited,
13580 } => {
13581 self.scrollbar_marker_state.dirty = true;
13582 self.active_indent_guides_state.dirty = true;
13583 self.refresh_active_diagnostics(cx);
13584 self.refresh_code_actions(window, cx);
13585 if self.has_active_inline_completion() {
13586 self.update_visible_inline_completion(window, cx);
13587 }
13588 if let Some(buffer) = buffer_edited {
13589 let buffer_id = buffer.read(cx).remote_id();
13590 if !self.registered_buffers.contains_key(&buffer_id) {
13591 if let Some(lsp_store) = self.lsp_store(cx) {
13592 lsp_store.update(cx, |lsp_store, cx| {
13593 self.registered_buffers.insert(
13594 buffer_id,
13595 lsp_store.register_buffer_with_language_servers(&buffer, cx),
13596 );
13597 })
13598 }
13599 }
13600 }
13601 cx.emit(EditorEvent::BufferEdited);
13602 cx.emit(SearchEvent::MatchesInvalidated);
13603 if *singleton_buffer_edited {
13604 if let Some(project) = &self.project {
13605 let project = project.read(cx);
13606 #[allow(clippy::mutable_key_type)]
13607 let languages_affected = multibuffer
13608 .read(cx)
13609 .all_buffers()
13610 .into_iter()
13611 .filter_map(|buffer| {
13612 let buffer = buffer.read(cx);
13613 let language = buffer.language()?;
13614 if project.is_local()
13615 && project
13616 .language_servers_for_local_buffer(buffer, cx)
13617 .count()
13618 == 0
13619 {
13620 None
13621 } else {
13622 Some(language)
13623 }
13624 })
13625 .cloned()
13626 .collect::<HashSet<_>>();
13627 if !languages_affected.is_empty() {
13628 self.refresh_inlay_hints(
13629 InlayHintRefreshReason::BufferEdited(languages_affected),
13630 cx,
13631 );
13632 }
13633 }
13634 }
13635
13636 let Some(project) = &self.project else { return };
13637 let (telemetry, is_via_ssh) = {
13638 let project = project.read(cx);
13639 let telemetry = project.client().telemetry().clone();
13640 let is_via_ssh = project.is_via_ssh();
13641 (telemetry, is_via_ssh)
13642 };
13643 refresh_linked_ranges(self, window, cx);
13644 telemetry.log_edit_event("editor", is_via_ssh);
13645 }
13646 multi_buffer::Event::ExcerptsAdded {
13647 buffer,
13648 predecessor,
13649 excerpts,
13650 } => {
13651 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13652 let buffer_id = buffer.read(cx).remote_id();
13653 if self.buffer.read(cx).change_set_for(buffer_id).is_none() {
13654 if let Some(project) = &self.project {
13655 get_unstaged_changes_for_buffers(
13656 project,
13657 [buffer.clone()],
13658 self.buffer.clone(),
13659 cx,
13660 );
13661 }
13662 }
13663 cx.emit(EditorEvent::ExcerptsAdded {
13664 buffer: buffer.clone(),
13665 predecessor: *predecessor,
13666 excerpts: excerpts.clone(),
13667 });
13668 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13669 }
13670 multi_buffer::Event::ExcerptsRemoved { ids } => {
13671 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13672 let buffer = self.buffer.read(cx);
13673 self.registered_buffers
13674 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13675 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13676 }
13677 multi_buffer::Event::ExcerptsEdited { ids } => {
13678 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13679 }
13680 multi_buffer::Event::ExcerptsExpanded { ids } => {
13681 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13682 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13683 }
13684 multi_buffer::Event::Reparsed(buffer_id) => {
13685 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13686
13687 cx.emit(EditorEvent::Reparsed(*buffer_id));
13688 }
13689 multi_buffer::Event::DiffHunksToggled => {
13690 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13691 }
13692 multi_buffer::Event::LanguageChanged(buffer_id) => {
13693 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13694 cx.emit(EditorEvent::Reparsed(*buffer_id));
13695 cx.notify();
13696 }
13697 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13698 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13699 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13700 cx.emit(EditorEvent::TitleChanged)
13701 }
13702 // multi_buffer::Event::DiffBaseChanged => {
13703 // self.scrollbar_marker_state.dirty = true;
13704 // cx.emit(EditorEvent::DiffBaseChanged);
13705 // cx.notify();
13706 // }
13707 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13708 multi_buffer::Event::DiagnosticsUpdated => {
13709 self.refresh_active_diagnostics(cx);
13710 self.scrollbar_marker_state.dirty = true;
13711 cx.notify();
13712 }
13713 _ => {}
13714 };
13715 }
13716
13717 fn on_display_map_changed(
13718 &mut self,
13719 _: Entity<DisplayMap>,
13720 _: &mut Window,
13721 cx: &mut Context<Self>,
13722 ) {
13723 cx.notify();
13724 }
13725
13726 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13727 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13728 self.refresh_inline_completion(true, false, window, cx);
13729 self.refresh_inlay_hints(
13730 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13731 self.selections.newest_anchor().head(),
13732 &self.buffer.read(cx).snapshot(cx),
13733 cx,
13734 )),
13735 cx,
13736 );
13737
13738 let old_cursor_shape = self.cursor_shape;
13739
13740 {
13741 let editor_settings = EditorSettings::get_global(cx);
13742 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13743 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13744 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13745 }
13746
13747 if old_cursor_shape != self.cursor_shape {
13748 cx.emit(EditorEvent::CursorShapeChanged);
13749 }
13750
13751 let project_settings = ProjectSettings::get_global(cx);
13752 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13753
13754 if self.mode == EditorMode::Full {
13755 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13756 if self.git_blame_inline_enabled != inline_blame_enabled {
13757 self.toggle_git_blame_inline_internal(false, window, cx);
13758 }
13759 }
13760
13761 cx.notify();
13762 }
13763
13764 pub fn set_searchable(&mut self, searchable: bool) {
13765 self.searchable = searchable;
13766 }
13767
13768 pub fn searchable(&self) -> bool {
13769 self.searchable
13770 }
13771
13772 fn open_proposed_changes_editor(
13773 &mut self,
13774 _: &OpenProposedChangesEditor,
13775 window: &mut Window,
13776 cx: &mut Context<Self>,
13777 ) {
13778 let Some(workspace) = self.workspace() else {
13779 cx.propagate();
13780 return;
13781 };
13782
13783 let selections = self.selections.all::<usize>(cx);
13784 let multi_buffer = self.buffer.read(cx);
13785 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13786 let mut new_selections_by_buffer = HashMap::default();
13787 for selection in selections {
13788 for (buffer, range, _) in
13789 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13790 {
13791 let mut range = range.to_point(buffer);
13792 range.start.column = 0;
13793 range.end.column = buffer.line_len(range.end.row);
13794 new_selections_by_buffer
13795 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13796 .or_insert(Vec::new())
13797 .push(range)
13798 }
13799 }
13800
13801 let proposed_changes_buffers = new_selections_by_buffer
13802 .into_iter()
13803 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13804 .collect::<Vec<_>>();
13805 let proposed_changes_editor = cx.new(|cx| {
13806 ProposedChangesEditor::new(
13807 "Proposed changes",
13808 proposed_changes_buffers,
13809 self.project.clone(),
13810 window,
13811 cx,
13812 )
13813 });
13814
13815 window.defer(cx, move |window, cx| {
13816 workspace.update(cx, |workspace, cx| {
13817 workspace.active_pane().update(cx, |pane, cx| {
13818 pane.add_item(
13819 Box::new(proposed_changes_editor),
13820 true,
13821 true,
13822 None,
13823 window,
13824 cx,
13825 );
13826 });
13827 });
13828 });
13829 }
13830
13831 pub fn open_excerpts_in_split(
13832 &mut self,
13833 _: &OpenExcerptsSplit,
13834 window: &mut Window,
13835 cx: &mut Context<Self>,
13836 ) {
13837 self.open_excerpts_common(None, true, window, cx)
13838 }
13839
13840 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
13841 self.open_excerpts_common(None, false, window, cx)
13842 }
13843
13844 fn open_excerpts_common(
13845 &mut self,
13846 jump_data: Option<JumpData>,
13847 split: bool,
13848 window: &mut Window,
13849 cx: &mut Context<Self>,
13850 ) {
13851 let Some(workspace) = self.workspace() else {
13852 cx.propagate();
13853 return;
13854 };
13855
13856 if self.buffer.read(cx).is_singleton() {
13857 cx.propagate();
13858 return;
13859 }
13860
13861 let mut new_selections_by_buffer = HashMap::default();
13862 match &jump_data {
13863 Some(JumpData::MultiBufferPoint {
13864 excerpt_id,
13865 position,
13866 anchor,
13867 line_offset_from_top,
13868 }) => {
13869 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13870 if let Some(buffer) = multi_buffer_snapshot
13871 .buffer_id_for_excerpt(*excerpt_id)
13872 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
13873 {
13874 let buffer_snapshot = buffer.read(cx).snapshot();
13875 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
13876 language::ToPoint::to_point(anchor, &buffer_snapshot)
13877 } else {
13878 buffer_snapshot.clip_point(*position, Bias::Left)
13879 };
13880 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
13881 new_selections_by_buffer.insert(
13882 buffer,
13883 (
13884 vec![jump_to_offset..jump_to_offset],
13885 Some(*line_offset_from_top),
13886 ),
13887 );
13888 }
13889 }
13890 Some(JumpData::MultiBufferRow {
13891 row,
13892 line_offset_from_top,
13893 }) => {
13894 let point = MultiBufferPoint::new(row.0, 0);
13895 if let Some((buffer, buffer_point, _)) =
13896 self.buffer.read(cx).point_to_buffer_point(point, cx)
13897 {
13898 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
13899 new_selections_by_buffer
13900 .entry(buffer)
13901 .or_insert((Vec::new(), Some(*line_offset_from_top)))
13902 .0
13903 .push(buffer_offset..buffer_offset)
13904 }
13905 }
13906 None => {
13907 let selections = self.selections.all::<usize>(cx);
13908 let multi_buffer = self.buffer.read(cx);
13909 for selection in selections {
13910 for (buffer, mut range, _) in multi_buffer
13911 .snapshot(cx)
13912 .range_to_buffer_ranges(selection.range())
13913 {
13914 // When editing branch buffers, jump to the corresponding location
13915 // in their base buffer.
13916 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
13917 let buffer = buffer_handle.read(cx);
13918 if let Some(base_buffer) = buffer.base_buffer() {
13919 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
13920 buffer_handle = base_buffer;
13921 }
13922
13923 if selection.reversed {
13924 mem::swap(&mut range.start, &mut range.end);
13925 }
13926 new_selections_by_buffer
13927 .entry(buffer_handle)
13928 .or_insert((Vec::new(), None))
13929 .0
13930 .push(range)
13931 }
13932 }
13933 }
13934 }
13935
13936 if new_selections_by_buffer.is_empty() {
13937 return;
13938 }
13939
13940 // We defer the pane interaction because we ourselves are a workspace item
13941 // and activating a new item causes the pane to call a method on us reentrantly,
13942 // which panics if we're on the stack.
13943 window.defer(cx, move |window, cx| {
13944 workspace.update(cx, |workspace, cx| {
13945 let pane = if split {
13946 workspace.adjacent_pane(window, cx)
13947 } else {
13948 workspace.active_pane().clone()
13949 };
13950
13951 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
13952 let editor = buffer
13953 .read(cx)
13954 .file()
13955 .is_none()
13956 .then(|| {
13957 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
13958 // so `workspace.open_project_item` will never find them, always opening a new editor.
13959 // Instead, we try to activate the existing editor in the pane first.
13960 let (editor, pane_item_index) =
13961 pane.read(cx).items().enumerate().find_map(|(i, item)| {
13962 let editor = item.downcast::<Editor>()?;
13963 let singleton_buffer =
13964 editor.read(cx).buffer().read(cx).as_singleton()?;
13965 if singleton_buffer == buffer {
13966 Some((editor, i))
13967 } else {
13968 None
13969 }
13970 })?;
13971 pane.update(cx, |pane, cx| {
13972 pane.activate_item(pane_item_index, true, true, window, cx)
13973 });
13974 Some(editor)
13975 })
13976 .flatten()
13977 .unwrap_or_else(|| {
13978 workspace.open_project_item::<Self>(
13979 pane.clone(),
13980 buffer,
13981 true,
13982 true,
13983 window,
13984 cx,
13985 )
13986 });
13987
13988 editor.update(cx, |editor, cx| {
13989 let autoscroll = match scroll_offset {
13990 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
13991 None => Autoscroll::newest(),
13992 };
13993 let nav_history = editor.nav_history.take();
13994 editor.change_selections(Some(autoscroll), window, cx, |s| {
13995 s.select_ranges(ranges);
13996 });
13997 editor.nav_history = nav_history;
13998 });
13999 }
14000 })
14001 });
14002 }
14003
14004 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14005 let snapshot = self.buffer.read(cx).read(cx);
14006 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14007 Some(
14008 ranges
14009 .iter()
14010 .map(move |range| {
14011 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14012 })
14013 .collect(),
14014 )
14015 }
14016
14017 fn selection_replacement_ranges(
14018 &self,
14019 range: Range<OffsetUtf16>,
14020 cx: &mut App,
14021 ) -> Vec<Range<OffsetUtf16>> {
14022 let selections = self.selections.all::<OffsetUtf16>(cx);
14023 let newest_selection = selections
14024 .iter()
14025 .max_by_key(|selection| selection.id)
14026 .unwrap();
14027 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14028 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14029 let snapshot = self.buffer.read(cx).read(cx);
14030 selections
14031 .into_iter()
14032 .map(|mut selection| {
14033 selection.start.0 =
14034 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14035 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14036 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14037 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14038 })
14039 .collect()
14040 }
14041
14042 fn report_editor_event(
14043 &self,
14044 event_type: &'static str,
14045 file_extension: Option<String>,
14046 cx: &App,
14047 ) {
14048 if cfg!(any(test, feature = "test-support")) {
14049 return;
14050 }
14051
14052 let Some(project) = &self.project else { return };
14053
14054 // If None, we are in a file without an extension
14055 let file = self
14056 .buffer
14057 .read(cx)
14058 .as_singleton()
14059 .and_then(|b| b.read(cx).file());
14060 let file_extension = file_extension.or(file
14061 .as_ref()
14062 .and_then(|file| Path::new(file.file_name(cx)).extension())
14063 .and_then(|e| e.to_str())
14064 .map(|a| a.to_string()));
14065
14066 let vim_mode = cx
14067 .global::<SettingsStore>()
14068 .raw_user_settings()
14069 .get("vim_mode")
14070 == Some(&serde_json::Value::Bool(true));
14071
14072 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
14073 == language::language_settings::InlineCompletionProvider::Copilot;
14074 let copilot_enabled_for_language = self
14075 .buffer
14076 .read(cx)
14077 .settings_at(0, cx)
14078 .show_inline_completions;
14079
14080 let project = project.read(cx);
14081 telemetry::event!(
14082 event_type,
14083 file_extension,
14084 vim_mode,
14085 copilot_enabled,
14086 copilot_enabled_for_language,
14087 is_via_ssh = project.is_via_ssh(),
14088 );
14089 }
14090
14091 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14092 /// with each line being an array of {text, highlight} objects.
14093 fn copy_highlight_json(
14094 &mut self,
14095 _: &CopyHighlightJson,
14096 window: &mut Window,
14097 cx: &mut Context<Self>,
14098 ) {
14099 #[derive(Serialize)]
14100 struct Chunk<'a> {
14101 text: String,
14102 highlight: Option<&'a str>,
14103 }
14104
14105 let snapshot = self.buffer.read(cx).snapshot(cx);
14106 let range = self
14107 .selected_text_range(false, window, cx)
14108 .and_then(|selection| {
14109 if selection.range.is_empty() {
14110 None
14111 } else {
14112 Some(selection.range)
14113 }
14114 })
14115 .unwrap_or_else(|| 0..snapshot.len());
14116
14117 let chunks = snapshot.chunks(range, true);
14118 let mut lines = Vec::new();
14119 let mut line: VecDeque<Chunk> = VecDeque::new();
14120
14121 let Some(style) = self.style.as_ref() else {
14122 return;
14123 };
14124
14125 for chunk in chunks {
14126 let highlight = chunk
14127 .syntax_highlight_id
14128 .and_then(|id| id.name(&style.syntax));
14129 let mut chunk_lines = chunk.text.split('\n').peekable();
14130 while let Some(text) = chunk_lines.next() {
14131 let mut merged_with_last_token = false;
14132 if let Some(last_token) = line.back_mut() {
14133 if last_token.highlight == highlight {
14134 last_token.text.push_str(text);
14135 merged_with_last_token = true;
14136 }
14137 }
14138
14139 if !merged_with_last_token {
14140 line.push_back(Chunk {
14141 text: text.into(),
14142 highlight,
14143 });
14144 }
14145
14146 if chunk_lines.peek().is_some() {
14147 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14148 line.pop_front();
14149 }
14150 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14151 line.pop_back();
14152 }
14153
14154 lines.push(mem::take(&mut line));
14155 }
14156 }
14157 }
14158
14159 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14160 return;
14161 };
14162 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14163 }
14164
14165 pub fn open_context_menu(
14166 &mut self,
14167 _: &OpenContextMenu,
14168 window: &mut Window,
14169 cx: &mut Context<Self>,
14170 ) {
14171 self.request_autoscroll(Autoscroll::newest(), cx);
14172 let position = self.selections.newest_display(cx).start;
14173 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14174 }
14175
14176 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14177 &self.inlay_hint_cache
14178 }
14179
14180 pub fn replay_insert_event(
14181 &mut self,
14182 text: &str,
14183 relative_utf16_range: Option<Range<isize>>,
14184 window: &mut Window,
14185 cx: &mut Context<Self>,
14186 ) {
14187 if !self.input_enabled {
14188 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14189 return;
14190 }
14191 if let Some(relative_utf16_range) = relative_utf16_range {
14192 let selections = self.selections.all::<OffsetUtf16>(cx);
14193 self.change_selections(None, window, cx, |s| {
14194 let new_ranges = selections.into_iter().map(|range| {
14195 let start = OffsetUtf16(
14196 range
14197 .head()
14198 .0
14199 .saturating_add_signed(relative_utf16_range.start),
14200 );
14201 let end = OffsetUtf16(
14202 range
14203 .head()
14204 .0
14205 .saturating_add_signed(relative_utf16_range.end),
14206 );
14207 start..end
14208 });
14209 s.select_ranges(new_ranges);
14210 });
14211 }
14212
14213 self.handle_input(text, window, cx);
14214 }
14215
14216 pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14217 let Some(provider) = self.semantics_provider.as_ref() else {
14218 return false;
14219 };
14220
14221 let mut supports = false;
14222 self.buffer().read(cx).for_each_buffer(|buffer| {
14223 supports |= provider.supports_inlay_hints(buffer, cx);
14224 });
14225 supports
14226 }
14227 pub fn is_focused(&self, window: &mut Window) -> bool {
14228 self.focus_handle.is_focused(window)
14229 }
14230
14231 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14232 cx.emit(EditorEvent::Focused);
14233
14234 if let Some(descendant) = self
14235 .last_focused_descendant
14236 .take()
14237 .and_then(|descendant| descendant.upgrade())
14238 {
14239 window.focus(&descendant);
14240 } else {
14241 if let Some(blame) = self.blame.as_ref() {
14242 blame.update(cx, GitBlame::focus)
14243 }
14244
14245 self.blink_manager.update(cx, BlinkManager::enable);
14246 self.show_cursor_names(window, cx);
14247 self.buffer.update(cx, |buffer, cx| {
14248 buffer.finalize_last_transaction(cx);
14249 if self.leader_peer_id.is_none() {
14250 buffer.set_active_selections(
14251 &self.selections.disjoint_anchors(),
14252 self.selections.line_mode,
14253 self.cursor_shape,
14254 cx,
14255 );
14256 }
14257 });
14258 }
14259 }
14260
14261 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14262 cx.emit(EditorEvent::FocusedIn)
14263 }
14264
14265 fn handle_focus_out(
14266 &mut self,
14267 event: FocusOutEvent,
14268 _window: &mut Window,
14269 _cx: &mut Context<Self>,
14270 ) {
14271 if event.blurred != self.focus_handle {
14272 self.last_focused_descendant = Some(event.blurred);
14273 }
14274 }
14275
14276 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14277 self.blink_manager.update(cx, BlinkManager::disable);
14278 self.buffer
14279 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14280
14281 if let Some(blame) = self.blame.as_ref() {
14282 blame.update(cx, GitBlame::blur)
14283 }
14284 if !self.hover_state.focused(window, cx) {
14285 hide_hover(self, cx);
14286 }
14287
14288 self.hide_context_menu(window, cx);
14289 cx.emit(EditorEvent::Blurred);
14290 cx.notify();
14291 }
14292
14293 pub fn register_action<A: Action>(
14294 &mut self,
14295 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14296 ) -> Subscription {
14297 let id = self.next_editor_action_id.post_inc();
14298 let listener = Arc::new(listener);
14299 self.editor_actions.borrow_mut().insert(
14300 id,
14301 Box::new(move |window, _| {
14302 let listener = listener.clone();
14303 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14304 let action = action.downcast_ref().unwrap();
14305 if phase == DispatchPhase::Bubble {
14306 listener(action, window, cx)
14307 }
14308 })
14309 }),
14310 );
14311
14312 let editor_actions = self.editor_actions.clone();
14313 Subscription::new(move || {
14314 editor_actions.borrow_mut().remove(&id);
14315 })
14316 }
14317
14318 pub fn file_header_size(&self) -> u32 {
14319 FILE_HEADER_HEIGHT
14320 }
14321
14322 pub fn revert(
14323 &mut self,
14324 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14325 window: &mut Window,
14326 cx: &mut Context<Self>,
14327 ) {
14328 self.buffer().update(cx, |multi_buffer, cx| {
14329 for (buffer_id, changes) in revert_changes {
14330 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14331 buffer.update(cx, |buffer, cx| {
14332 buffer.edit(
14333 changes.into_iter().map(|(range, text)| {
14334 (range, text.to_string().map(Arc::<str>::from))
14335 }),
14336 None,
14337 cx,
14338 );
14339 });
14340 }
14341 }
14342 });
14343 self.change_selections(None, window, cx, |selections| selections.refresh());
14344 }
14345
14346 pub fn to_pixel_point(
14347 &self,
14348 source: multi_buffer::Anchor,
14349 editor_snapshot: &EditorSnapshot,
14350 window: &mut Window,
14351 ) -> Option<gpui::Point<Pixels>> {
14352 let source_point = source.to_display_point(editor_snapshot);
14353 self.display_to_pixel_point(source_point, editor_snapshot, window)
14354 }
14355
14356 pub fn display_to_pixel_point(
14357 &self,
14358 source: DisplayPoint,
14359 editor_snapshot: &EditorSnapshot,
14360 window: &mut Window,
14361 ) -> Option<gpui::Point<Pixels>> {
14362 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14363 let text_layout_details = self.text_layout_details(window);
14364 let scroll_top = text_layout_details
14365 .scroll_anchor
14366 .scroll_position(editor_snapshot)
14367 .y;
14368
14369 if source.row().as_f32() < scroll_top.floor() {
14370 return None;
14371 }
14372 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14373 let source_y = line_height * (source.row().as_f32() - scroll_top);
14374 Some(gpui::Point::new(source_x, source_y))
14375 }
14376
14377 pub fn has_active_completions_menu(&self) -> bool {
14378 self.context_menu.borrow().as_ref().map_or(false, |menu| {
14379 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14380 })
14381 }
14382
14383 pub fn register_addon<T: Addon>(&mut self, instance: T) {
14384 self.addons
14385 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14386 }
14387
14388 pub fn unregister_addon<T: Addon>(&mut self) {
14389 self.addons.remove(&std::any::TypeId::of::<T>());
14390 }
14391
14392 pub fn addon<T: Addon>(&self) -> Option<&T> {
14393 let type_id = std::any::TypeId::of::<T>();
14394 self.addons
14395 .get(&type_id)
14396 .and_then(|item| item.to_any().downcast_ref::<T>())
14397 }
14398
14399 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14400 let text_layout_details = self.text_layout_details(window);
14401 let style = &text_layout_details.editor_style;
14402 let font_id = window.text_system().resolve_font(&style.text.font());
14403 let font_size = style.text.font_size.to_pixels(window.rem_size());
14404 let line_height = style.text.line_height_in_pixels(window.rem_size());
14405 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14406
14407 gpui::Size::new(em_width, line_height)
14408 }
14409}
14410
14411fn get_unstaged_changes_for_buffers(
14412 project: &Entity<Project>,
14413 buffers: impl IntoIterator<Item = Entity<Buffer>>,
14414 buffer: Entity<MultiBuffer>,
14415 cx: &mut App,
14416) {
14417 let mut tasks = Vec::new();
14418 project.update(cx, |project, cx| {
14419 for buffer in buffers {
14420 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
14421 }
14422 });
14423 cx.spawn(|mut cx| async move {
14424 let change_sets = futures::future::join_all(tasks).await;
14425 buffer
14426 .update(&mut cx, |buffer, cx| {
14427 for change_set in change_sets {
14428 if let Some(change_set) = change_set.log_err() {
14429 buffer.add_change_set(change_set, cx);
14430 }
14431 }
14432 })
14433 .ok();
14434 })
14435 .detach();
14436}
14437
14438fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14439 let tab_size = tab_size.get() as usize;
14440 let mut width = offset;
14441
14442 for ch in text.chars() {
14443 width += if ch == '\t' {
14444 tab_size - (width % tab_size)
14445 } else {
14446 1
14447 };
14448 }
14449
14450 width - offset
14451}
14452
14453#[cfg(test)]
14454mod tests {
14455 use super::*;
14456
14457 #[test]
14458 fn test_string_size_with_expanded_tabs() {
14459 let nz = |val| NonZeroU32::new(val).unwrap();
14460 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14461 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14462 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14463 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14464 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14465 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14466 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14467 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14468 }
14469}
14470
14471/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14472struct WordBreakingTokenizer<'a> {
14473 input: &'a str,
14474}
14475
14476impl<'a> WordBreakingTokenizer<'a> {
14477 fn new(input: &'a str) -> Self {
14478 Self { input }
14479 }
14480}
14481
14482fn is_char_ideographic(ch: char) -> bool {
14483 use unicode_script::Script::*;
14484 use unicode_script::UnicodeScript;
14485 matches!(ch.script(), Han | Tangut | Yi)
14486}
14487
14488fn is_grapheme_ideographic(text: &str) -> bool {
14489 text.chars().any(is_char_ideographic)
14490}
14491
14492fn is_grapheme_whitespace(text: &str) -> bool {
14493 text.chars().any(|x| x.is_whitespace())
14494}
14495
14496fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14497 text.chars().next().map_or(false, |ch| {
14498 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14499 })
14500}
14501
14502#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14503struct WordBreakToken<'a> {
14504 token: &'a str,
14505 grapheme_len: usize,
14506 is_whitespace: bool,
14507}
14508
14509impl<'a> Iterator for WordBreakingTokenizer<'a> {
14510 /// Yields a span, the count of graphemes in the token, and whether it was
14511 /// whitespace. Note that it also breaks at word boundaries.
14512 type Item = WordBreakToken<'a>;
14513
14514 fn next(&mut self) -> Option<Self::Item> {
14515 use unicode_segmentation::UnicodeSegmentation;
14516 if self.input.is_empty() {
14517 return None;
14518 }
14519
14520 let mut iter = self.input.graphemes(true).peekable();
14521 let mut offset = 0;
14522 let mut graphemes = 0;
14523 if let Some(first_grapheme) = iter.next() {
14524 let is_whitespace = is_grapheme_whitespace(first_grapheme);
14525 offset += first_grapheme.len();
14526 graphemes += 1;
14527 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14528 if let Some(grapheme) = iter.peek().copied() {
14529 if should_stay_with_preceding_ideograph(grapheme) {
14530 offset += grapheme.len();
14531 graphemes += 1;
14532 }
14533 }
14534 } else {
14535 let mut words = self.input[offset..].split_word_bound_indices().peekable();
14536 let mut next_word_bound = words.peek().copied();
14537 if next_word_bound.map_or(false, |(i, _)| i == 0) {
14538 next_word_bound = words.next();
14539 }
14540 while let Some(grapheme) = iter.peek().copied() {
14541 if next_word_bound.map_or(false, |(i, _)| i == offset) {
14542 break;
14543 };
14544 if is_grapheme_whitespace(grapheme) != is_whitespace {
14545 break;
14546 };
14547 offset += grapheme.len();
14548 graphemes += 1;
14549 iter.next();
14550 }
14551 }
14552 let token = &self.input[..offset];
14553 self.input = &self.input[offset..];
14554 if is_whitespace {
14555 Some(WordBreakToken {
14556 token: " ",
14557 grapheme_len: 1,
14558 is_whitespace: true,
14559 })
14560 } else {
14561 Some(WordBreakToken {
14562 token,
14563 grapheme_len: graphemes,
14564 is_whitespace: false,
14565 })
14566 }
14567 } else {
14568 None
14569 }
14570 }
14571}
14572
14573#[test]
14574fn test_word_breaking_tokenizer() {
14575 let tests: &[(&str, &[(&str, usize, bool)])] = &[
14576 ("", &[]),
14577 (" ", &[(" ", 1, true)]),
14578 ("Ʒ", &[("Ʒ", 1, false)]),
14579 ("Ǽ", &[("Ǽ", 1, false)]),
14580 ("⋑", &[("⋑", 1, false)]),
14581 ("⋑⋑", &[("⋑⋑", 2, false)]),
14582 (
14583 "原理,进而",
14584 &[
14585 ("原", 1, false),
14586 ("理,", 2, false),
14587 ("进", 1, false),
14588 ("而", 1, false),
14589 ],
14590 ),
14591 (
14592 "hello world",
14593 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14594 ),
14595 (
14596 "hello, world",
14597 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14598 ),
14599 (
14600 " hello world",
14601 &[
14602 (" ", 1, true),
14603 ("hello", 5, false),
14604 (" ", 1, true),
14605 ("world", 5, false),
14606 ],
14607 ),
14608 (
14609 "这是什么 \n 钢笔",
14610 &[
14611 ("这", 1, false),
14612 ("是", 1, false),
14613 ("什", 1, false),
14614 ("么", 1, false),
14615 (" ", 1, true),
14616 ("钢", 1, false),
14617 ("笔", 1, false),
14618 ],
14619 ),
14620 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14621 ];
14622
14623 for (input, result) in tests {
14624 assert_eq!(
14625 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14626 result
14627 .iter()
14628 .copied()
14629 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14630 token,
14631 grapheme_len,
14632 is_whitespace,
14633 })
14634 .collect::<Vec<_>>()
14635 );
14636 }
14637}
14638
14639fn wrap_with_prefix(
14640 line_prefix: String,
14641 unwrapped_text: String,
14642 wrap_column: usize,
14643 tab_size: NonZeroU32,
14644) -> String {
14645 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14646 let mut wrapped_text = String::new();
14647 let mut current_line = line_prefix.clone();
14648
14649 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14650 let mut current_line_len = line_prefix_len;
14651 for WordBreakToken {
14652 token,
14653 grapheme_len,
14654 is_whitespace,
14655 } in tokenizer
14656 {
14657 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14658 wrapped_text.push_str(current_line.trim_end());
14659 wrapped_text.push('\n');
14660 current_line.truncate(line_prefix.len());
14661 current_line_len = line_prefix_len;
14662 if !is_whitespace {
14663 current_line.push_str(token);
14664 current_line_len += grapheme_len;
14665 }
14666 } else if !is_whitespace {
14667 current_line.push_str(token);
14668 current_line_len += grapheme_len;
14669 } else if current_line_len != line_prefix_len {
14670 current_line.push(' ');
14671 current_line_len += 1;
14672 }
14673 }
14674
14675 if !current_line.is_empty() {
14676 wrapped_text.push_str(¤t_line);
14677 }
14678 wrapped_text
14679}
14680
14681#[test]
14682fn test_wrap_with_prefix() {
14683 assert_eq!(
14684 wrap_with_prefix(
14685 "# ".to_string(),
14686 "abcdefg".to_string(),
14687 4,
14688 NonZeroU32::new(4).unwrap()
14689 ),
14690 "# abcdefg"
14691 );
14692 assert_eq!(
14693 wrap_with_prefix(
14694 "".to_string(),
14695 "\thello world".to_string(),
14696 8,
14697 NonZeroU32::new(4).unwrap()
14698 ),
14699 "hello\nworld"
14700 );
14701 assert_eq!(
14702 wrap_with_prefix(
14703 "// ".to_string(),
14704 "xx \nyy zz aa bb cc".to_string(),
14705 12,
14706 NonZeroU32::new(4).unwrap()
14707 ),
14708 "// xx yy zz\n// aa bb cc"
14709 );
14710 assert_eq!(
14711 wrap_with_prefix(
14712 String::new(),
14713 "这是什么 \n 钢笔".to_string(),
14714 3,
14715 NonZeroU32::new(4).unwrap()
14716 ),
14717 "这是什\n么 钢\n笔"
14718 );
14719}
14720
14721pub trait CollaborationHub {
14722 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14723 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14724 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14725}
14726
14727impl CollaborationHub for Entity<Project> {
14728 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14729 self.read(cx).collaborators()
14730 }
14731
14732 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14733 self.read(cx).user_store().read(cx).participant_indices()
14734 }
14735
14736 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14737 let this = self.read(cx);
14738 let user_ids = this.collaborators().values().map(|c| c.user_id);
14739 this.user_store().read_with(cx, |user_store, cx| {
14740 user_store.participant_names(user_ids, cx)
14741 })
14742 }
14743}
14744
14745pub trait SemanticsProvider {
14746 fn hover(
14747 &self,
14748 buffer: &Entity<Buffer>,
14749 position: text::Anchor,
14750 cx: &mut App,
14751 ) -> Option<Task<Vec<project::Hover>>>;
14752
14753 fn inlay_hints(
14754 &self,
14755 buffer_handle: Entity<Buffer>,
14756 range: Range<text::Anchor>,
14757 cx: &mut App,
14758 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14759
14760 fn resolve_inlay_hint(
14761 &self,
14762 hint: InlayHint,
14763 buffer_handle: Entity<Buffer>,
14764 server_id: LanguageServerId,
14765 cx: &mut App,
14766 ) -> Option<Task<anyhow::Result<InlayHint>>>;
14767
14768 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
14769
14770 fn document_highlights(
14771 &self,
14772 buffer: &Entity<Buffer>,
14773 position: text::Anchor,
14774 cx: &mut App,
14775 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14776
14777 fn definitions(
14778 &self,
14779 buffer: &Entity<Buffer>,
14780 position: text::Anchor,
14781 kind: GotoDefinitionKind,
14782 cx: &mut App,
14783 ) -> Option<Task<Result<Vec<LocationLink>>>>;
14784
14785 fn range_for_rename(
14786 &self,
14787 buffer: &Entity<Buffer>,
14788 position: text::Anchor,
14789 cx: &mut App,
14790 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14791
14792 fn perform_rename(
14793 &self,
14794 buffer: &Entity<Buffer>,
14795 position: text::Anchor,
14796 new_name: String,
14797 cx: &mut App,
14798 ) -> Option<Task<Result<ProjectTransaction>>>;
14799}
14800
14801pub trait CompletionProvider {
14802 fn completions(
14803 &self,
14804 buffer: &Entity<Buffer>,
14805 buffer_position: text::Anchor,
14806 trigger: CompletionContext,
14807 window: &mut Window,
14808 cx: &mut Context<Editor>,
14809 ) -> Task<Result<Vec<Completion>>>;
14810
14811 fn resolve_completions(
14812 &self,
14813 buffer: Entity<Buffer>,
14814 completion_indices: Vec<usize>,
14815 completions: Rc<RefCell<Box<[Completion]>>>,
14816 cx: &mut Context<Editor>,
14817 ) -> Task<Result<bool>>;
14818
14819 fn apply_additional_edits_for_completion(
14820 &self,
14821 _buffer: Entity<Buffer>,
14822 _completions: Rc<RefCell<Box<[Completion]>>>,
14823 _completion_index: usize,
14824 _push_to_history: bool,
14825 _cx: &mut Context<Editor>,
14826 ) -> Task<Result<Option<language::Transaction>>> {
14827 Task::ready(Ok(None))
14828 }
14829
14830 fn is_completion_trigger(
14831 &self,
14832 buffer: &Entity<Buffer>,
14833 position: language::Anchor,
14834 text: &str,
14835 trigger_in_words: bool,
14836 cx: &mut Context<Editor>,
14837 ) -> bool;
14838
14839 fn sort_completions(&self) -> bool {
14840 true
14841 }
14842}
14843
14844pub trait CodeActionProvider {
14845 fn id(&self) -> Arc<str>;
14846
14847 fn code_actions(
14848 &self,
14849 buffer: &Entity<Buffer>,
14850 range: Range<text::Anchor>,
14851 window: &mut Window,
14852 cx: &mut App,
14853 ) -> Task<Result<Vec<CodeAction>>>;
14854
14855 fn apply_code_action(
14856 &self,
14857 buffer_handle: Entity<Buffer>,
14858 action: CodeAction,
14859 excerpt_id: ExcerptId,
14860 push_to_history: bool,
14861 window: &mut Window,
14862 cx: &mut App,
14863 ) -> Task<Result<ProjectTransaction>>;
14864}
14865
14866impl CodeActionProvider for Entity<Project> {
14867 fn id(&self) -> Arc<str> {
14868 "project".into()
14869 }
14870
14871 fn code_actions(
14872 &self,
14873 buffer: &Entity<Buffer>,
14874 range: Range<text::Anchor>,
14875 _window: &mut Window,
14876 cx: &mut App,
14877 ) -> Task<Result<Vec<CodeAction>>> {
14878 self.update(cx, |project, cx| {
14879 project.code_actions(buffer, range, None, cx)
14880 })
14881 }
14882
14883 fn apply_code_action(
14884 &self,
14885 buffer_handle: Entity<Buffer>,
14886 action: CodeAction,
14887 _excerpt_id: ExcerptId,
14888 push_to_history: bool,
14889 _window: &mut Window,
14890 cx: &mut App,
14891 ) -> Task<Result<ProjectTransaction>> {
14892 self.update(cx, |project, cx| {
14893 project.apply_code_action(buffer_handle, action, push_to_history, cx)
14894 })
14895 }
14896}
14897
14898fn snippet_completions(
14899 project: &Project,
14900 buffer: &Entity<Buffer>,
14901 buffer_position: text::Anchor,
14902 cx: &mut App,
14903) -> Task<Result<Vec<Completion>>> {
14904 let language = buffer.read(cx).language_at(buffer_position);
14905 let language_name = language.as_ref().map(|language| language.lsp_id());
14906 let snippet_store = project.snippets().read(cx);
14907 let snippets = snippet_store.snippets_for(language_name, cx);
14908
14909 if snippets.is_empty() {
14910 return Task::ready(Ok(vec![]));
14911 }
14912 let snapshot = buffer.read(cx).text_snapshot();
14913 let chars: String = snapshot
14914 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
14915 .collect();
14916
14917 let scope = language.map(|language| language.default_scope());
14918 let executor = cx.background_executor().clone();
14919
14920 cx.background_executor().spawn(async move {
14921 let classifier = CharClassifier::new(scope).for_completion(true);
14922 let mut last_word = chars
14923 .chars()
14924 .take_while(|c| classifier.is_word(*c))
14925 .collect::<String>();
14926 last_word = last_word.chars().rev().collect();
14927
14928 if last_word.is_empty() {
14929 return Ok(vec![]);
14930 }
14931
14932 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
14933 let to_lsp = |point: &text::Anchor| {
14934 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
14935 point_to_lsp(end)
14936 };
14937 let lsp_end = to_lsp(&buffer_position);
14938
14939 let candidates = snippets
14940 .iter()
14941 .enumerate()
14942 .flat_map(|(ix, snippet)| {
14943 snippet
14944 .prefix
14945 .iter()
14946 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
14947 })
14948 .collect::<Vec<StringMatchCandidate>>();
14949
14950 let mut matches = fuzzy::match_strings(
14951 &candidates,
14952 &last_word,
14953 last_word.chars().any(|c| c.is_uppercase()),
14954 100,
14955 &Default::default(),
14956 executor,
14957 )
14958 .await;
14959
14960 // Remove all candidates where the query's start does not match the start of any word in the candidate
14961 if let Some(query_start) = last_word.chars().next() {
14962 matches.retain(|string_match| {
14963 split_words(&string_match.string).any(|word| {
14964 // Check that the first codepoint of the word as lowercase matches the first
14965 // codepoint of the query as lowercase
14966 word.chars()
14967 .flat_map(|codepoint| codepoint.to_lowercase())
14968 .zip(query_start.to_lowercase())
14969 .all(|(word_cp, query_cp)| word_cp == query_cp)
14970 })
14971 });
14972 }
14973
14974 let matched_strings = matches
14975 .into_iter()
14976 .map(|m| m.string)
14977 .collect::<HashSet<_>>();
14978
14979 let result: Vec<Completion> = snippets
14980 .into_iter()
14981 .filter_map(|snippet| {
14982 let matching_prefix = snippet
14983 .prefix
14984 .iter()
14985 .find(|prefix| matched_strings.contains(*prefix))?;
14986 let start = as_offset - last_word.len();
14987 let start = snapshot.anchor_before(start);
14988 let range = start..buffer_position;
14989 let lsp_start = to_lsp(&start);
14990 let lsp_range = lsp::Range {
14991 start: lsp_start,
14992 end: lsp_end,
14993 };
14994 Some(Completion {
14995 old_range: range,
14996 new_text: snippet.body.clone(),
14997 resolved: false,
14998 label: CodeLabel {
14999 text: matching_prefix.clone(),
15000 runs: vec![],
15001 filter_range: 0..matching_prefix.len(),
15002 },
15003 server_id: LanguageServerId(usize::MAX),
15004 documentation: snippet
15005 .description
15006 .clone()
15007 .map(CompletionDocumentation::SingleLine),
15008 lsp_completion: lsp::CompletionItem {
15009 label: snippet.prefix.first().unwrap().clone(),
15010 kind: Some(CompletionItemKind::SNIPPET),
15011 label_details: snippet.description.as_ref().map(|description| {
15012 lsp::CompletionItemLabelDetails {
15013 detail: Some(description.clone()),
15014 description: None,
15015 }
15016 }),
15017 insert_text_format: Some(InsertTextFormat::SNIPPET),
15018 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15019 lsp::InsertReplaceEdit {
15020 new_text: snippet.body.clone(),
15021 insert: lsp_range,
15022 replace: lsp_range,
15023 },
15024 )),
15025 filter_text: Some(snippet.body.clone()),
15026 sort_text: Some(char::MAX.to_string()),
15027 ..Default::default()
15028 },
15029 confirm: None,
15030 })
15031 })
15032 .collect();
15033
15034 Ok(result)
15035 })
15036}
15037
15038impl CompletionProvider for Entity<Project> {
15039 fn completions(
15040 &self,
15041 buffer: &Entity<Buffer>,
15042 buffer_position: text::Anchor,
15043 options: CompletionContext,
15044 _window: &mut Window,
15045 cx: &mut Context<Editor>,
15046 ) -> Task<Result<Vec<Completion>>> {
15047 self.update(cx, |project, cx| {
15048 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15049 let project_completions = project.completions(buffer, buffer_position, options, cx);
15050 cx.background_executor().spawn(async move {
15051 let mut completions = project_completions.await?;
15052 let snippets_completions = snippets.await?;
15053 completions.extend(snippets_completions);
15054 Ok(completions)
15055 })
15056 })
15057 }
15058
15059 fn resolve_completions(
15060 &self,
15061 buffer: Entity<Buffer>,
15062 completion_indices: Vec<usize>,
15063 completions: Rc<RefCell<Box<[Completion]>>>,
15064 cx: &mut Context<Editor>,
15065 ) -> Task<Result<bool>> {
15066 self.update(cx, |project, cx| {
15067 project.lsp_store().update(cx, |lsp_store, cx| {
15068 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15069 })
15070 })
15071 }
15072
15073 fn apply_additional_edits_for_completion(
15074 &self,
15075 buffer: Entity<Buffer>,
15076 completions: Rc<RefCell<Box<[Completion]>>>,
15077 completion_index: usize,
15078 push_to_history: bool,
15079 cx: &mut Context<Editor>,
15080 ) -> Task<Result<Option<language::Transaction>>> {
15081 self.update(cx, |project, cx| {
15082 project.lsp_store().update(cx, |lsp_store, cx| {
15083 lsp_store.apply_additional_edits_for_completion(
15084 buffer,
15085 completions,
15086 completion_index,
15087 push_to_history,
15088 cx,
15089 )
15090 })
15091 })
15092 }
15093
15094 fn is_completion_trigger(
15095 &self,
15096 buffer: &Entity<Buffer>,
15097 position: language::Anchor,
15098 text: &str,
15099 trigger_in_words: bool,
15100 cx: &mut Context<Editor>,
15101 ) -> bool {
15102 let mut chars = text.chars();
15103 let char = if let Some(char) = chars.next() {
15104 char
15105 } else {
15106 return false;
15107 };
15108 if chars.next().is_some() {
15109 return false;
15110 }
15111
15112 let buffer = buffer.read(cx);
15113 let snapshot = buffer.snapshot();
15114 if !snapshot.settings_at(position, cx).show_completions_on_input {
15115 return false;
15116 }
15117 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15118 if trigger_in_words && classifier.is_word(char) {
15119 return true;
15120 }
15121
15122 buffer.completion_triggers().contains(text)
15123 }
15124}
15125
15126impl SemanticsProvider for Entity<Project> {
15127 fn hover(
15128 &self,
15129 buffer: &Entity<Buffer>,
15130 position: text::Anchor,
15131 cx: &mut App,
15132 ) -> Option<Task<Vec<project::Hover>>> {
15133 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15134 }
15135
15136 fn document_highlights(
15137 &self,
15138 buffer: &Entity<Buffer>,
15139 position: text::Anchor,
15140 cx: &mut App,
15141 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15142 Some(self.update(cx, |project, cx| {
15143 project.document_highlights(buffer, position, cx)
15144 }))
15145 }
15146
15147 fn definitions(
15148 &self,
15149 buffer: &Entity<Buffer>,
15150 position: text::Anchor,
15151 kind: GotoDefinitionKind,
15152 cx: &mut App,
15153 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15154 Some(self.update(cx, |project, cx| match kind {
15155 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15156 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15157 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15158 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15159 }))
15160 }
15161
15162 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15163 // TODO: make this work for remote projects
15164 self.read(cx)
15165 .language_servers_for_local_buffer(buffer.read(cx), cx)
15166 .any(
15167 |(_, server)| match server.capabilities().inlay_hint_provider {
15168 Some(lsp::OneOf::Left(enabled)) => enabled,
15169 Some(lsp::OneOf::Right(_)) => true,
15170 None => false,
15171 },
15172 )
15173 }
15174
15175 fn inlay_hints(
15176 &self,
15177 buffer_handle: Entity<Buffer>,
15178 range: Range<text::Anchor>,
15179 cx: &mut App,
15180 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15181 Some(self.update(cx, |project, cx| {
15182 project.inlay_hints(buffer_handle, range, cx)
15183 }))
15184 }
15185
15186 fn resolve_inlay_hint(
15187 &self,
15188 hint: InlayHint,
15189 buffer_handle: Entity<Buffer>,
15190 server_id: LanguageServerId,
15191 cx: &mut App,
15192 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15193 Some(self.update(cx, |project, cx| {
15194 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15195 }))
15196 }
15197
15198 fn range_for_rename(
15199 &self,
15200 buffer: &Entity<Buffer>,
15201 position: text::Anchor,
15202 cx: &mut App,
15203 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15204 Some(self.update(cx, |project, cx| {
15205 let buffer = buffer.clone();
15206 let task = project.prepare_rename(buffer.clone(), position, cx);
15207 cx.spawn(|_, mut cx| async move {
15208 Ok(match task.await? {
15209 PrepareRenameResponse::Success(range) => Some(range),
15210 PrepareRenameResponse::InvalidPosition => None,
15211 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15212 // Fallback on using TreeSitter info to determine identifier range
15213 buffer.update(&mut cx, |buffer, _| {
15214 let snapshot = buffer.snapshot();
15215 let (range, kind) = snapshot.surrounding_word(position);
15216 if kind != Some(CharKind::Word) {
15217 return None;
15218 }
15219 Some(
15220 snapshot.anchor_before(range.start)
15221 ..snapshot.anchor_after(range.end),
15222 )
15223 })?
15224 }
15225 })
15226 })
15227 }))
15228 }
15229
15230 fn perform_rename(
15231 &self,
15232 buffer: &Entity<Buffer>,
15233 position: text::Anchor,
15234 new_name: String,
15235 cx: &mut App,
15236 ) -> Option<Task<Result<ProjectTransaction>>> {
15237 Some(self.update(cx, |project, cx| {
15238 project.perform_rename(buffer.clone(), position, new_name, cx)
15239 }))
15240 }
15241}
15242
15243fn inlay_hint_settings(
15244 location: Anchor,
15245 snapshot: &MultiBufferSnapshot,
15246 cx: &mut Context<Editor>,
15247) -> InlayHintSettings {
15248 let file = snapshot.file_at(location);
15249 let language = snapshot.language_at(location).map(|l| l.name());
15250 language_settings(language, file, cx).inlay_hints
15251}
15252
15253fn consume_contiguous_rows(
15254 contiguous_row_selections: &mut Vec<Selection<Point>>,
15255 selection: &Selection<Point>,
15256 display_map: &DisplaySnapshot,
15257 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15258) -> (MultiBufferRow, MultiBufferRow) {
15259 contiguous_row_selections.push(selection.clone());
15260 let start_row = MultiBufferRow(selection.start.row);
15261 let mut end_row = ending_row(selection, display_map);
15262
15263 while let Some(next_selection) = selections.peek() {
15264 if next_selection.start.row <= end_row.0 {
15265 end_row = ending_row(next_selection, display_map);
15266 contiguous_row_selections.push(selections.next().unwrap().clone());
15267 } else {
15268 break;
15269 }
15270 }
15271 (start_row, end_row)
15272}
15273
15274fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15275 if next_selection.end.column > 0 || next_selection.is_empty() {
15276 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15277 } else {
15278 MultiBufferRow(next_selection.end.row)
15279 }
15280}
15281
15282impl EditorSnapshot {
15283 pub fn remote_selections_in_range<'a>(
15284 &'a self,
15285 range: &'a Range<Anchor>,
15286 collaboration_hub: &dyn CollaborationHub,
15287 cx: &'a App,
15288 ) -> impl 'a + Iterator<Item = RemoteSelection> {
15289 let participant_names = collaboration_hub.user_names(cx);
15290 let participant_indices = collaboration_hub.user_participant_indices(cx);
15291 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15292 let collaborators_by_replica_id = collaborators_by_peer_id
15293 .iter()
15294 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15295 .collect::<HashMap<_, _>>();
15296 self.buffer_snapshot
15297 .selections_in_range(range, false)
15298 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15299 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15300 let participant_index = participant_indices.get(&collaborator.user_id).copied();
15301 let user_name = participant_names.get(&collaborator.user_id).cloned();
15302 Some(RemoteSelection {
15303 replica_id,
15304 selection,
15305 cursor_shape,
15306 line_mode,
15307 participant_index,
15308 peer_id: collaborator.peer_id,
15309 user_name,
15310 })
15311 })
15312 }
15313
15314 pub fn hunks_for_ranges(
15315 &self,
15316 ranges: impl Iterator<Item = Range<Point>>,
15317 ) -> Vec<MultiBufferDiffHunk> {
15318 let mut hunks = Vec::new();
15319 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15320 HashMap::default();
15321 for query_range in ranges {
15322 let query_rows =
15323 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15324 for hunk in self.buffer_snapshot.diff_hunks_in_range(
15325 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15326 ) {
15327 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15328 // when the caret is just above or just below the deleted hunk.
15329 let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15330 let related_to_selection = if allow_adjacent {
15331 hunk.row_range.overlaps(&query_rows)
15332 || hunk.row_range.start == query_rows.end
15333 || hunk.row_range.end == query_rows.start
15334 } else {
15335 hunk.row_range.overlaps(&query_rows)
15336 };
15337 if related_to_selection {
15338 if !processed_buffer_rows
15339 .entry(hunk.buffer_id)
15340 .or_default()
15341 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15342 {
15343 continue;
15344 }
15345 hunks.push(hunk);
15346 }
15347 }
15348 }
15349
15350 hunks
15351 }
15352
15353 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15354 self.display_snapshot.buffer_snapshot.language_at(position)
15355 }
15356
15357 pub fn is_focused(&self) -> bool {
15358 self.is_focused
15359 }
15360
15361 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15362 self.placeholder_text.as_ref()
15363 }
15364
15365 pub fn scroll_position(&self) -> gpui::Point<f32> {
15366 self.scroll_anchor.scroll_position(&self.display_snapshot)
15367 }
15368
15369 fn gutter_dimensions(
15370 &self,
15371 font_id: FontId,
15372 font_size: Pixels,
15373 max_line_number_width: Pixels,
15374 cx: &App,
15375 ) -> Option<GutterDimensions> {
15376 if !self.show_gutter {
15377 return None;
15378 }
15379
15380 let descent = cx.text_system().descent(font_id, font_size);
15381 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15382 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15383
15384 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15385 matches!(
15386 ProjectSettings::get_global(cx).git.git_gutter,
15387 Some(GitGutterSetting::TrackedFiles)
15388 )
15389 });
15390 let gutter_settings = EditorSettings::get_global(cx).gutter;
15391 let show_line_numbers = self
15392 .show_line_numbers
15393 .unwrap_or(gutter_settings.line_numbers);
15394 let line_gutter_width = if show_line_numbers {
15395 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15396 let min_width_for_number_on_gutter = em_advance * 4.0;
15397 max_line_number_width.max(min_width_for_number_on_gutter)
15398 } else {
15399 0.0.into()
15400 };
15401
15402 let show_code_actions = self
15403 .show_code_actions
15404 .unwrap_or(gutter_settings.code_actions);
15405
15406 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15407
15408 let git_blame_entries_width =
15409 self.git_blame_gutter_max_author_length
15410 .map(|max_author_length| {
15411 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15412
15413 /// The number of characters to dedicate to gaps and margins.
15414 const SPACING_WIDTH: usize = 4;
15415
15416 let max_char_count = max_author_length
15417 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15418 + ::git::SHORT_SHA_LENGTH
15419 + MAX_RELATIVE_TIMESTAMP.len()
15420 + SPACING_WIDTH;
15421
15422 em_advance * max_char_count
15423 });
15424
15425 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15426 left_padding += if show_code_actions || show_runnables {
15427 em_width * 3.0
15428 } else if show_git_gutter && show_line_numbers {
15429 em_width * 2.0
15430 } else if show_git_gutter || show_line_numbers {
15431 em_width
15432 } else {
15433 px(0.)
15434 };
15435
15436 let right_padding = if gutter_settings.folds && show_line_numbers {
15437 em_width * 4.0
15438 } else if gutter_settings.folds {
15439 em_width * 3.0
15440 } else if show_line_numbers {
15441 em_width
15442 } else {
15443 px(0.)
15444 };
15445
15446 Some(GutterDimensions {
15447 left_padding,
15448 right_padding,
15449 width: line_gutter_width + left_padding + right_padding,
15450 margin: -descent,
15451 git_blame_entries_width,
15452 })
15453 }
15454
15455 pub fn render_crease_toggle(
15456 &self,
15457 buffer_row: MultiBufferRow,
15458 row_contains_cursor: bool,
15459 editor: Entity<Editor>,
15460 window: &mut Window,
15461 cx: &mut App,
15462 ) -> Option<AnyElement> {
15463 let folded = self.is_line_folded(buffer_row);
15464 let mut is_foldable = false;
15465
15466 if let Some(crease) = self
15467 .crease_snapshot
15468 .query_row(buffer_row, &self.buffer_snapshot)
15469 {
15470 is_foldable = true;
15471 match crease {
15472 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15473 if let Some(render_toggle) = render_toggle {
15474 let toggle_callback =
15475 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15476 if folded {
15477 editor.update(cx, |editor, cx| {
15478 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15479 });
15480 } else {
15481 editor.update(cx, |editor, cx| {
15482 editor.unfold_at(
15483 &crate::UnfoldAt { buffer_row },
15484 window,
15485 cx,
15486 )
15487 });
15488 }
15489 });
15490 return Some((render_toggle)(
15491 buffer_row,
15492 folded,
15493 toggle_callback,
15494 window,
15495 cx,
15496 ));
15497 }
15498 }
15499 }
15500 }
15501
15502 is_foldable |= self.starts_indent(buffer_row);
15503
15504 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15505 Some(
15506 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15507 .toggle_state(folded)
15508 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15509 if folded {
15510 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15511 } else {
15512 this.fold_at(&FoldAt { buffer_row }, window, cx);
15513 }
15514 }))
15515 .into_any_element(),
15516 )
15517 } else {
15518 None
15519 }
15520 }
15521
15522 pub fn render_crease_trailer(
15523 &self,
15524 buffer_row: MultiBufferRow,
15525 window: &mut Window,
15526 cx: &mut App,
15527 ) -> Option<AnyElement> {
15528 let folded = self.is_line_folded(buffer_row);
15529 if let Crease::Inline { render_trailer, .. } = self
15530 .crease_snapshot
15531 .query_row(buffer_row, &self.buffer_snapshot)?
15532 {
15533 let render_trailer = render_trailer.as_ref()?;
15534 Some(render_trailer(buffer_row, folded, window, cx))
15535 } else {
15536 None
15537 }
15538 }
15539}
15540
15541impl Deref for EditorSnapshot {
15542 type Target = DisplaySnapshot;
15543
15544 fn deref(&self) -> &Self::Target {
15545 &self.display_snapshot
15546 }
15547}
15548
15549#[derive(Clone, Debug, PartialEq, Eq)]
15550pub enum EditorEvent {
15551 InputIgnored {
15552 text: Arc<str>,
15553 },
15554 InputHandled {
15555 utf16_range_to_replace: Option<Range<isize>>,
15556 text: Arc<str>,
15557 },
15558 ExcerptsAdded {
15559 buffer: Entity<Buffer>,
15560 predecessor: ExcerptId,
15561 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15562 },
15563 ExcerptsRemoved {
15564 ids: Vec<ExcerptId>,
15565 },
15566 BufferFoldToggled {
15567 ids: Vec<ExcerptId>,
15568 folded: bool,
15569 },
15570 ExcerptsEdited {
15571 ids: Vec<ExcerptId>,
15572 },
15573 ExcerptsExpanded {
15574 ids: Vec<ExcerptId>,
15575 },
15576 BufferEdited,
15577 Edited {
15578 transaction_id: clock::Lamport,
15579 },
15580 Reparsed(BufferId),
15581 Focused,
15582 FocusedIn,
15583 Blurred,
15584 DirtyChanged,
15585 Saved,
15586 TitleChanged,
15587 DiffBaseChanged,
15588 SelectionsChanged {
15589 local: bool,
15590 },
15591 ScrollPositionChanged {
15592 local: bool,
15593 autoscroll: bool,
15594 },
15595 Closed,
15596 TransactionUndone {
15597 transaction_id: clock::Lamport,
15598 },
15599 TransactionBegun {
15600 transaction_id: clock::Lamport,
15601 },
15602 Reloaded,
15603 CursorShapeChanged,
15604}
15605
15606impl EventEmitter<EditorEvent> for Editor {}
15607
15608impl Focusable for Editor {
15609 fn focus_handle(&self, _cx: &App) -> FocusHandle {
15610 self.focus_handle.clone()
15611 }
15612}
15613
15614impl Render for Editor {
15615 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15616 let settings = ThemeSettings::get_global(cx);
15617
15618 let mut text_style = match self.mode {
15619 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15620 color: cx.theme().colors().editor_foreground,
15621 font_family: settings.ui_font.family.clone(),
15622 font_features: settings.ui_font.features.clone(),
15623 font_fallbacks: settings.ui_font.fallbacks.clone(),
15624 font_size: rems(0.875).into(),
15625 font_weight: settings.ui_font.weight,
15626 line_height: relative(settings.buffer_line_height.value()),
15627 ..Default::default()
15628 },
15629 EditorMode::Full => TextStyle {
15630 color: cx.theme().colors().editor_foreground,
15631 font_family: settings.buffer_font.family.clone(),
15632 font_features: settings.buffer_font.features.clone(),
15633 font_fallbacks: settings.buffer_font.fallbacks.clone(),
15634 font_size: settings.buffer_font_size().into(),
15635 font_weight: settings.buffer_font.weight,
15636 line_height: relative(settings.buffer_line_height.value()),
15637 ..Default::default()
15638 },
15639 };
15640 if let Some(text_style_refinement) = &self.text_style_refinement {
15641 text_style.refine(text_style_refinement)
15642 }
15643
15644 let background = match self.mode {
15645 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15646 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15647 EditorMode::Full => cx.theme().colors().editor_background,
15648 };
15649
15650 EditorElement::new(
15651 &cx.entity(),
15652 EditorStyle {
15653 background,
15654 local_player: cx.theme().players().local(),
15655 text: text_style,
15656 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15657 syntax: cx.theme().syntax().clone(),
15658 status: cx.theme().status().clone(),
15659 inlay_hints_style: make_inlay_hints_style(cx),
15660 inline_completion_styles: make_suggestion_styles(cx),
15661 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15662 },
15663 )
15664 }
15665}
15666
15667impl EntityInputHandler for Editor {
15668 fn text_for_range(
15669 &mut self,
15670 range_utf16: Range<usize>,
15671 adjusted_range: &mut Option<Range<usize>>,
15672 _: &mut Window,
15673 cx: &mut Context<Self>,
15674 ) -> Option<String> {
15675 let snapshot = self.buffer.read(cx).read(cx);
15676 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15677 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15678 if (start.0..end.0) != range_utf16 {
15679 adjusted_range.replace(start.0..end.0);
15680 }
15681 Some(snapshot.text_for_range(start..end).collect())
15682 }
15683
15684 fn selected_text_range(
15685 &mut self,
15686 ignore_disabled_input: bool,
15687 _: &mut Window,
15688 cx: &mut Context<Self>,
15689 ) -> Option<UTF16Selection> {
15690 // Prevent the IME menu from appearing when holding down an alphabetic key
15691 // while input is disabled.
15692 if !ignore_disabled_input && !self.input_enabled {
15693 return None;
15694 }
15695
15696 let selection = self.selections.newest::<OffsetUtf16>(cx);
15697 let range = selection.range();
15698
15699 Some(UTF16Selection {
15700 range: range.start.0..range.end.0,
15701 reversed: selection.reversed,
15702 })
15703 }
15704
15705 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15706 let snapshot = self.buffer.read(cx).read(cx);
15707 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15708 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15709 }
15710
15711 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15712 self.clear_highlights::<InputComposition>(cx);
15713 self.ime_transaction.take();
15714 }
15715
15716 fn replace_text_in_range(
15717 &mut self,
15718 range_utf16: Option<Range<usize>>,
15719 text: &str,
15720 window: &mut Window,
15721 cx: &mut Context<Self>,
15722 ) {
15723 if !self.input_enabled {
15724 cx.emit(EditorEvent::InputIgnored { text: text.into() });
15725 return;
15726 }
15727
15728 self.transact(window, cx, |this, window, cx| {
15729 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15730 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15731 Some(this.selection_replacement_ranges(range_utf16, cx))
15732 } else {
15733 this.marked_text_ranges(cx)
15734 };
15735
15736 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15737 let newest_selection_id = this.selections.newest_anchor().id;
15738 this.selections
15739 .all::<OffsetUtf16>(cx)
15740 .iter()
15741 .zip(ranges_to_replace.iter())
15742 .find_map(|(selection, range)| {
15743 if selection.id == newest_selection_id {
15744 Some(
15745 (range.start.0 as isize - selection.head().0 as isize)
15746 ..(range.end.0 as isize - selection.head().0 as isize),
15747 )
15748 } else {
15749 None
15750 }
15751 })
15752 });
15753
15754 cx.emit(EditorEvent::InputHandled {
15755 utf16_range_to_replace: range_to_replace,
15756 text: text.into(),
15757 });
15758
15759 if let Some(new_selected_ranges) = new_selected_ranges {
15760 this.change_selections(None, window, cx, |selections| {
15761 selections.select_ranges(new_selected_ranges)
15762 });
15763 this.backspace(&Default::default(), window, cx);
15764 }
15765
15766 this.handle_input(text, window, cx);
15767 });
15768
15769 if let Some(transaction) = self.ime_transaction {
15770 self.buffer.update(cx, |buffer, cx| {
15771 buffer.group_until_transaction(transaction, cx);
15772 });
15773 }
15774
15775 self.unmark_text(window, cx);
15776 }
15777
15778 fn replace_and_mark_text_in_range(
15779 &mut self,
15780 range_utf16: Option<Range<usize>>,
15781 text: &str,
15782 new_selected_range_utf16: Option<Range<usize>>,
15783 window: &mut Window,
15784 cx: &mut Context<Self>,
15785 ) {
15786 if !self.input_enabled {
15787 return;
15788 }
15789
15790 let transaction = self.transact(window, cx, |this, window, cx| {
15791 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15792 let snapshot = this.buffer.read(cx).read(cx);
15793 if let Some(relative_range_utf16) = range_utf16.as_ref() {
15794 for marked_range in &mut marked_ranges {
15795 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15796 marked_range.start.0 += relative_range_utf16.start;
15797 marked_range.start =
15798 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15799 marked_range.end =
15800 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15801 }
15802 }
15803 Some(marked_ranges)
15804 } else if let Some(range_utf16) = range_utf16 {
15805 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15806 Some(this.selection_replacement_ranges(range_utf16, cx))
15807 } else {
15808 None
15809 };
15810
15811 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
15812 let newest_selection_id = this.selections.newest_anchor().id;
15813 this.selections
15814 .all::<OffsetUtf16>(cx)
15815 .iter()
15816 .zip(ranges_to_replace.iter())
15817 .find_map(|(selection, range)| {
15818 if selection.id == newest_selection_id {
15819 Some(
15820 (range.start.0 as isize - selection.head().0 as isize)
15821 ..(range.end.0 as isize - selection.head().0 as isize),
15822 )
15823 } else {
15824 None
15825 }
15826 })
15827 });
15828
15829 cx.emit(EditorEvent::InputHandled {
15830 utf16_range_to_replace: range_to_replace,
15831 text: text.into(),
15832 });
15833
15834 if let Some(ranges) = ranges_to_replace {
15835 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
15836 }
15837
15838 let marked_ranges = {
15839 let snapshot = this.buffer.read(cx).read(cx);
15840 this.selections
15841 .disjoint_anchors()
15842 .iter()
15843 .map(|selection| {
15844 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
15845 })
15846 .collect::<Vec<_>>()
15847 };
15848
15849 if text.is_empty() {
15850 this.unmark_text(window, cx);
15851 } else {
15852 this.highlight_text::<InputComposition>(
15853 marked_ranges.clone(),
15854 HighlightStyle {
15855 underline: Some(UnderlineStyle {
15856 thickness: px(1.),
15857 color: None,
15858 wavy: false,
15859 }),
15860 ..Default::default()
15861 },
15862 cx,
15863 );
15864 }
15865
15866 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
15867 let use_autoclose = this.use_autoclose;
15868 let use_auto_surround = this.use_auto_surround;
15869 this.set_use_autoclose(false);
15870 this.set_use_auto_surround(false);
15871 this.handle_input(text, window, cx);
15872 this.set_use_autoclose(use_autoclose);
15873 this.set_use_auto_surround(use_auto_surround);
15874
15875 if let Some(new_selected_range) = new_selected_range_utf16 {
15876 let snapshot = this.buffer.read(cx).read(cx);
15877 let new_selected_ranges = marked_ranges
15878 .into_iter()
15879 .map(|marked_range| {
15880 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
15881 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
15882 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
15883 snapshot.clip_offset_utf16(new_start, Bias::Left)
15884 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
15885 })
15886 .collect::<Vec<_>>();
15887
15888 drop(snapshot);
15889 this.change_selections(None, window, cx, |selections| {
15890 selections.select_ranges(new_selected_ranges)
15891 });
15892 }
15893 });
15894
15895 self.ime_transaction = self.ime_transaction.or(transaction);
15896 if let Some(transaction) = self.ime_transaction {
15897 self.buffer.update(cx, |buffer, cx| {
15898 buffer.group_until_transaction(transaction, cx);
15899 });
15900 }
15901
15902 if self.text_highlights::<InputComposition>(cx).is_none() {
15903 self.ime_transaction.take();
15904 }
15905 }
15906
15907 fn bounds_for_range(
15908 &mut self,
15909 range_utf16: Range<usize>,
15910 element_bounds: gpui::Bounds<Pixels>,
15911 window: &mut Window,
15912 cx: &mut Context<Self>,
15913 ) -> Option<gpui::Bounds<Pixels>> {
15914 let text_layout_details = self.text_layout_details(window);
15915 let gpui::Size {
15916 width: em_width,
15917 height: line_height,
15918 } = self.character_size(window);
15919
15920 let snapshot = self.snapshot(window, cx);
15921 let scroll_position = snapshot.scroll_position();
15922 let scroll_left = scroll_position.x * em_width;
15923
15924 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
15925 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
15926 + self.gutter_dimensions.width
15927 + self.gutter_dimensions.margin;
15928 let y = line_height * (start.row().as_f32() - scroll_position.y);
15929
15930 Some(Bounds {
15931 origin: element_bounds.origin + point(x, y),
15932 size: size(em_width, line_height),
15933 })
15934 }
15935
15936 fn character_index_for_point(
15937 &mut self,
15938 point: gpui::Point<Pixels>,
15939 _window: &mut Window,
15940 _cx: &mut Context<Self>,
15941 ) -> Option<usize> {
15942 let position_map = self.last_position_map.as_ref()?;
15943 if !position_map.text_hitbox.contains(&point) {
15944 return None;
15945 }
15946 let display_point = position_map.point_for_position(point).previous_valid;
15947 let anchor = position_map
15948 .snapshot
15949 .display_point_to_anchor(display_point, Bias::Left);
15950 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
15951 Some(utf16_offset.0)
15952 }
15953}
15954
15955trait SelectionExt {
15956 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
15957 fn spanned_rows(
15958 &self,
15959 include_end_if_at_line_start: bool,
15960 map: &DisplaySnapshot,
15961 ) -> Range<MultiBufferRow>;
15962}
15963
15964impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
15965 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
15966 let start = self
15967 .start
15968 .to_point(&map.buffer_snapshot)
15969 .to_display_point(map);
15970 let end = self
15971 .end
15972 .to_point(&map.buffer_snapshot)
15973 .to_display_point(map);
15974 if self.reversed {
15975 end..start
15976 } else {
15977 start..end
15978 }
15979 }
15980
15981 fn spanned_rows(
15982 &self,
15983 include_end_if_at_line_start: bool,
15984 map: &DisplaySnapshot,
15985 ) -> Range<MultiBufferRow> {
15986 let start = self.start.to_point(&map.buffer_snapshot);
15987 let mut end = self.end.to_point(&map.buffer_snapshot);
15988 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
15989 end.row -= 1;
15990 }
15991
15992 let buffer_start = map.prev_line_boundary(start).0;
15993 let buffer_end = map.next_line_boundary(end).0;
15994 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
15995 }
15996}
15997
15998impl<T: InvalidationRegion> InvalidationStack<T> {
15999 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16000 where
16001 S: Clone + ToOffset,
16002 {
16003 while let Some(region) = self.last() {
16004 let all_selections_inside_invalidation_ranges =
16005 if selections.len() == region.ranges().len() {
16006 selections
16007 .iter()
16008 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16009 .all(|(selection, invalidation_range)| {
16010 let head = selection.head().to_offset(buffer);
16011 invalidation_range.start <= head && invalidation_range.end >= head
16012 })
16013 } else {
16014 false
16015 };
16016
16017 if all_selections_inside_invalidation_ranges {
16018 break;
16019 } else {
16020 self.pop();
16021 }
16022 }
16023 }
16024}
16025
16026impl<T> Default for InvalidationStack<T> {
16027 fn default() -> Self {
16028 Self(Default::default())
16029 }
16030}
16031
16032impl<T> Deref for InvalidationStack<T> {
16033 type Target = Vec<T>;
16034
16035 fn deref(&self) -> &Self::Target {
16036 &self.0
16037 }
16038}
16039
16040impl<T> DerefMut for InvalidationStack<T> {
16041 fn deref_mut(&mut self) -> &mut Self::Target {
16042 &mut self.0
16043 }
16044}
16045
16046impl InvalidationRegion for SnippetState {
16047 fn ranges(&self) -> &[Range<Anchor>] {
16048 &self.ranges[self.active_index]
16049 }
16050}
16051
16052pub fn diagnostic_block_renderer(
16053 diagnostic: Diagnostic,
16054 max_message_rows: Option<u8>,
16055 allow_closing: bool,
16056 _is_valid: bool,
16057) -> RenderBlock {
16058 let (text_without_backticks, code_ranges) =
16059 highlight_diagnostic_message(&diagnostic, max_message_rows);
16060
16061 Arc::new(move |cx: &mut BlockContext| {
16062 let group_id: SharedString = cx.block_id.to_string().into();
16063
16064 let mut text_style = cx.window.text_style().clone();
16065 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16066 let theme_settings = ThemeSettings::get_global(cx);
16067 text_style.font_family = theme_settings.buffer_font.family.clone();
16068 text_style.font_style = theme_settings.buffer_font.style;
16069 text_style.font_features = theme_settings.buffer_font.features.clone();
16070 text_style.font_weight = theme_settings.buffer_font.weight;
16071
16072 let multi_line_diagnostic = diagnostic.message.contains('\n');
16073
16074 let buttons = |diagnostic: &Diagnostic| {
16075 if multi_line_diagnostic {
16076 v_flex()
16077 } else {
16078 h_flex()
16079 }
16080 .when(allow_closing, |div| {
16081 div.children(diagnostic.is_primary.then(|| {
16082 IconButton::new("close-block", IconName::XCircle)
16083 .icon_color(Color::Muted)
16084 .size(ButtonSize::Compact)
16085 .style(ButtonStyle::Transparent)
16086 .visible_on_hover(group_id.clone())
16087 .on_click(move |_click, window, cx| {
16088 window.dispatch_action(Box::new(Cancel), cx)
16089 })
16090 .tooltip(|window, cx| {
16091 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16092 })
16093 }))
16094 })
16095 .child(
16096 IconButton::new("copy-block", IconName::Copy)
16097 .icon_color(Color::Muted)
16098 .size(ButtonSize::Compact)
16099 .style(ButtonStyle::Transparent)
16100 .visible_on_hover(group_id.clone())
16101 .on_click({
16102 let message = diagnostic.message.clone();
16103 move |_click, _, cx| {
16104 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16105 }
16106 })
16107 .tooltip(Tooltip::text("Copy diagnostic message")),
16108 )
16109 };
16110
16111 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16112 AvailableSpace::min_size(),
16113 cx.window,
16114 cx.app,
16115 );
16116
16117 h_flex()
16118 .id(cx.block_id)
16119 .group(group_id.clone())
16120 .relative()
16121 .size_full()
16122 .block_mouse_down()
16123 .pl(cx.gutter_dimensions.width)
16124 .w(cx.max_width - cx.gutter_dimensions.full_width())
16125 .child(
16126 div()
16127 .flex()
16128 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16129 .flex_shrink(),
16130 )
16131 .child(buttons(&diagnostic))
16132 .child(div().flex().flex_shrink_0().child(
16133 StyledText::new(text_without_backticks.clone()).with_highlights(
16134 &text_style,
16135 code_ranges.iter().map(|range| {
16136 (
16137 range.clone(),
16138 HighlightStyle {
16139 font_weight: Some(FontWeight::BOLD),
16140 ..Default::default()
16141 },
16142 )
16143 }),
16144 ),
16145 ))
16146 .into_any_element()
16147 })
16148}
16149
16150fn inline_completion_edit_text(
16151 current_snapshot: &BufferSnapshot,
16152 edits: &[(Range<Anchor>, String)],
16153 edit_preview: &EditPreview,
16154 include_deletions: bool,
16155 cx: &App,
16156) -> HighlightedText {
16157 let edits = edits
16158 .iter()
16159 .map(|(anchor, text)| {
16160 (
16161 anchor.start.text_anchor..anchor.end.text_anchor,
16162 text.clone(),
16163 )
16164 })
16165 .collect::<Vec<_>>();
16166
16167 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16168}
16169
16170pub fn highlight_diagnostic_message(
16171 diagnostic: &Diagnostic,
16172 mut max_message_rows: Option<u8>,
16173) -> (SharedString, Vec<Range<usize>>) {
16174 let mut text_without_backticks = String::new();
16175 let mut code_ranges = Vec::new();
16176
16177 if let Some(source) = &diagnostic.source {
16178 text_without_backticks.push_str(source);
16179 code_ranges.push(0..source.len());
16180 text_without_backticks.push_str(": ");
16181 }
16182
16183 let mut prev_offset = 0;
16184 let mut in_code_block = false;
16185 let has_row_limit = max_message_rows.is_some();
16186 let mut newline_indices = diagnostic
16187 .message
16188 .match_indices('\n')
16189 .filter(|_| has_row_limit)
16190 .map(|(ix, _)| ix)
16191 .fuse()
16192 .peekable();
16193
16194 for (quote_ix, _) in diagnostic
16195 .message
16196 .match_indices('`')
16197 .chain([(diagnostic.message.len(), "")])
16198 {
16199 let mut first_newline_ix = None;
16200 let mut last_newline_ix = None;
16201 while let Some(newline_ix) = newline_indices.peek() {
16202 if *newline_ix < quote_ix {
16203 if first_newline_ix.is_none() {
16204 first_newline_ix = Some(*newline_ix);
16205 }
16206 last_newline_ix = Some(*newline_ix);
16207
16208 if let Some(rows_left) = &mut max_message_rows {
16209 if *rows_left == 0 {
16210 break;
16211 } else {
16212 *rows_left -= 1;
16213 }
16214 }
16215 let _ = newline_indices.next();
16216 } else {
16217 break;
16218 }
16219 }
16220 let prev_len = text_without_backticks.len();
16221 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16222 text_without_backticks.push_str(new_text);
16223 if in_code_block {
16224 code_ranges.push(prev_len..text_without_backticks.len());
16225 }
16226 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16227 in_code_block = !in_code_block;
16228 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16229 text_without_backticks.push_str("...");
16230 break;
16231 }
16232 }
16233
16234 (text_without_backticks.into(), code_ranges)
16235}
16236
16237fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16238 match severity {
16239 DiagnosticSeverity::ERROR => colors.error,
16240 DiagnosticSeverity::WARNING => colors.warning,
16241 DiagnosticSeverity::INFORMATION => colors.info,
16242 DiagnosticSeverity::HINT => colors.info,
16243 _ => colors.ignored,
16244 }
16245}
16246
16247pub fn styled_runs_for_code_label<'a>(
16248 label: &'a CodeLabel,
16249 syntax_theme: &'a theme::SyntaxTheme,
16250) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16251 let fade_out = HighlightStyle {
16252 fade_out: Some(0.35),
16253 ..Default::default()
16254 };
16255
16256 let mut prev_end = label.filter_range.end;
16257 label
16258 .runs
16259 .iter()
16260 .enumerate()
16261 .flat_map(move |(ix, (range, highlight_id))| {
16262 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16263 style
16264 } else {
16265 return Default::default();
16266 };
16267 let mut muted_style = style;
16268 muted_style.highlight(fade_out);
16269
16270 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16271 if range.start >= label.filter_range.end {
16272 if range.start > prev_end {
16273 runs.push((prev_end..range.start, fade_out));
16274 }
16275 runs.push((range.clone(), muted_style));
16276 } else if range.end <= label.filter_range.end {
16277 runs.push((range.clone(), style));
16278 } else {
16279 runs.push((range.start..label.filter_range.end, style));
16280 runs.push((label.filter_range.end..range.end, muted_style));
16281 }
16282 prev_end = cmp::max(prev_end, range.end);
16283
16284 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16285 runs.push((prev_end..label.text.len(), fade_out));
16286 }
16287
16288 runs
16289 })
16290}
16291
16292pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16293 let mut prev_index = 0;
16294 let mut prev_codepoint: Option<char> = None;
16295 text.char_indices()
16296 .chain([(text.len(), '\0')])
16297 .filter_map(move |(index, codepoint)| {
16298 let prev_codepoint = prev_codepoint.replace(codepoint)?;
16299 let is_boundary = index == text.len()
16300 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16301 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16302 if is_boundary {
16303 let chunk = &text[prev_index..index];
16304 prev_index = index;
16305 Some(chunk)
16306 } else {
16307 None
16308 }
16309 })
16310}
16311
16312pub trait RangeToAnchorExt: Sized {
16313 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16314
16315 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16316 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16317 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16318 }
16319}
16320
16321impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16322 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16323 let start_offset = self.start.to_offset(snapshot);
16324 let end_offset = self.end.to_offset(snapshot);
16325 if start_offset == end_offset {
16326 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16327 } else {
16328 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16329 }
16330 }
16331}
16332
16333pub trait RowExt {
16334 fn as_f32(&self) -> f32;
16335
16336 fn next_row(&self) -> Self;
16337
16338 fn previous_row(&self) -> Self;
16339
16340 fn minus(&self, other: Self) -> u32;
16341}
16342
16343impl RowExt for DisplayRow {
16344 fn as_f32(&self) -> f32 {
16345 self.0 as f32
16346 }
16347
16348 fn next_row(&self) -> Self {
16349 Self(self.0 + 1)
16350 }
16351
16352 fn previous_row(&self) -> Self {
16353 Self(self.0.saturating_sub(1))
16354 }
16355
16356 fn minus(&self, other: Self) -> u32 {
16357 self.0 - other.0
16358 }
16359}
16360
16361impl RowExt for MultiBufferRow {
16362 fn as_f32(&self) -> f32 {
16363 self.0 as f32
16364 }
16365
16366 fn next_row(&self) -> Self {
16367 Self(self.0 + 1)
16368 }
16369
16370 fn previous_row(&self) -> Self {
16371 Self(self.0.saturating_sub(1))
16372 }
16373
16374 fn minus(&self, other: Self) -> u32 {
16375 self.0 - other.0
16376 }
16377}
16378
16379trait RowRangeExt {
16380 type Row;
16381
16382 fn len(&self) -> usize;
16383
16384 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16385}
16386
16387impl RowRangeExt for Range<MultiBufferRow> {
16388 type Row = MultiBufferRow;
16389
16390 fn len(&self) -> usize {
16391 (self.end.0 - self.start.0) as usize
16392 }
16393
16394 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16395 (self.start.0..self.end.0).map(MultiBufferRow)
16396 }
16397}
16398
16399impl RowRangeExt for Range<DisplayRow> {
16400 type Row = DisplayRow;
16401
16402 fn len(&self) -> usize {
16403 (self.end.0 - self.start.0) as usize
16404 }
16405
16406 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16407 (self.start.0..self.end.0).map(DisplayRow)
16408 }
16409}
16410
16411/// If select range has more than one line, we
16412/// just point the cursor to range.start.
16413fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16414 if range.start.row == range.end.row {
16415 range
16416 } else {
16417 range.start..range.start
16418 }
16419}
16420pub struct KillRing(ClipboardItem);
16421impl Global for KillRing {}
16422
16423const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16424
16425fn all_edits_insertions_or_deletions(
16426 edits: &Vec<(Range<Anchor>, String)>,
16427 snapshot: &MultiBufferSnapshot,
16428) -> bool {
16429 let mut all_insertions = true;
16430 let mut all_deletions = true;
16431
16432 for (range, new_text) in edits.iter() {
16433 let range_is_empty = range.to_offset(&snapshot).is_empty();
16434 let text_is_empty = new_text.is_empty();
16435
16436 if range_is_empty != text_is_empty {
16437 if range_is_empty {
16438 all_deletions = false;
16439 } else {
16440 all_insertions = false;
16441 }
16442 } else {
16443 return false;
16444 }
16445
16446 if !all_insertions && !all_deletions {
16447 return false;
16448 }
16449 }
16450 all_insertions || all_deletions
16451}